Opt-in wake word: on-device keyword spotting in a microphone foreground service
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- Engine: sherpa-onnx 2.0.1 keyword spotter (Apache-2.0) with the English zipformer-gigaspeech-3.3M KWS model (Apache-2.0, int8), fetched hash-pinned by scripts/fetch-wakeword.py into app/libs and src/full/assets (gitignored); CI and release run it. `full` flavour only (abiFilters arm64-v8a, armeabi-v7a, x86_64); `fdroid` has a stub engine and Settings says why. ProGuard keeps com.k2fsa.sherpa.onnx (JNI reads fields by name). - WakeWordService (foregroundServiceType microphone): persistent notification with Stop; audio only to the engine in memory; pauses while the sheet is up (AssistPresence), in battery saver, and with the screen off unless Settings says otherwise. On the word: the sheet opens listening through LembasAssistService.showSession when LLeMbas is the assistant, else the activity, else a "tap to ask" notification. - No microphone service at boot: WakeBootReceiver posts "tap to listen again"; MainActivity restarts a service the phone stopped. - Settings › Assistant › Wake word: switch (off), four built-in English phrases (BPE-tokenized with the model's bpe.model), screen-on only, battery-optimisation page; privacy and cost text. - The sheet's "no wake word" line now points at the setting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
31 files changed
+1181
-22
No files matched your search
@@ -54,6 +54,9 @@ import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.wake.WakeBootReceiver
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -75,6 +78,10 @@ class MainActivity : ComponentActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
take(intent)
|
||||
followLanguage()
|
||||
// A wake word that is on, but whose service the phone stopped: it listens again.
|
||||
lifecycleScope.launch {
|
||||
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) runCatching { WakeWordService.start(this@MainActivity) }
|
||||
}
|
||||
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
|
||||
lifecycleScope.launch { runCatching { ReleaseCheck(this@MainActivity).daily() } }
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
@@ -115,6 +122,11 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun take(intent: Intent?) {
|
||||
// "Tap to listen again" after a restart: the app is on screen now, so the microphone
|
||||
// service may start.
|
||||
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
|
||||
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
|
||||
}
|
||||
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
|
||||
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
|
||||
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
|
||||
|
||||
@@ -17,6 +17,7 @@ import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
enum class Opening {
|
||||
@@ -72,6 +73,7 @@ class AssistActivity : ComponentActivity() {
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
AssistPresence.shown()
|
||||
take(intent)
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
@@ -146,6 +148,7 @@ class AssistActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistPresence.hidden()
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
@@ -41,7 +42,28 @@ import kotlinx.coroutines.runBlocking
|
||||
* there is no hotword here -- Android keeps always-on hotword detection for the system's own
|
||||
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
|
||||
*/
|
||||
class LembasAssistService : VoiceInteractionService()
|
||||
class LembasAssistService : VoiceInteractionService() {
|
||||
override fun onReady() {
|
||||
super.onReady()
|
||||
current = this
|
||||
}
|
||||
|
||||
override fun onShutdown() {
|
||||
if (current === this) current = null
|
||||
super.onShutdown()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
|
||||
* wake word opens the sheet through it ([showSession]), which Android allows from the
|
||||
* background, as it does for the power button.
|
||||
*/
|
||||
@Volatile
|
||||
var current: LembasAssistService? = null
|
||||
private set
|
||||
}
|
||||
}
|
||||
|
||||
class LembasAssistSessionService : VoiceInteractionSessionService() {
|
||||
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
|
||||
@@ -109,7 +131,9 @@ class LembasAssistSession(context: Context) :
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
controller.opened(locked())
|
||||
AssistPresence.shown()
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening.
|
||||
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,6 +143,7 @@ class LembasAssistSession(context: Context) :
|
||||
*/
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
AssistPresence.hidden()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
@@ -445,7 +445,7 @@ private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boole
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_no_wake_word), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_wake_word_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +87,12 @@ data class Prefs(
|
||||
val assistantListens: Boolean = true,
|
||||
/** After a spoken answer is read aloud, listen again: a spoken conversation. */
|
||||
val assistantConversation: Boolean = true,
|
||||
/** Listen for a wake word on the phone (WakeWordService). Off until the person turns it on. */
|
||||
val wakeWord: Boolean = false,
|
||||
/** Which of WakePhrases.all. */
|
||||
val wakePhrase: String = "hey_lembas",
|
||||
/** Listen only while the screen is on. */
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
|
||||
@@ -2,9 +2,13 @@
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -26,10 +30,12 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Logout
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Assistant
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
@@ -38,6 +44,7 @@ import androidx.compose.material.icons.filled.Palette
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.RecordVoiceOver
|
||||
import androidx.compose.material.icons.filled.Science
|
||||
import androidx.compose.material.icons.filled.ScreenLockPortrait
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material.icons.filled.Timer
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
@@ -72,6 +79,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
@@ -88,6 +96,9 @@ import eu.llembas.android.update.UpdateResult
|
||||
import eu.llembas.android.update.Updater
|
||||
import eu.llembas.android.update.checksUpdates
|
||||
import eu.llembas.android.update.offersBetas
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakePhrases
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** What the settings page does; every action has a do-nothing default for the screenshots. */
|
||||
@@ -104,6 +115,10 @@ interface SettingsActions {
|
||||
fun voiceInput(value: String) {}
|
||||
fun assistantListens(on: Boolean) {}
|
||||
fun assistantConversation(on: Boolean) {}
|
||||
fun wakeWord(on: Boolean) {}
|
||||
fun wakePhrase(id: String) {}
|
||||
fun wakeScreenOnly(on: Boolean) {}
|
||||
fun batterySettings() {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
@@ -128,6 +143,8 @@ data class SettingsState(
|
||||
val beta: Boolean = false,
|
||||
/** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */
|
||||
val phoneRecognizer: Boolean = false,
|
||||
/** Whether this build has a wake-word engine (the F-Droid build has none). */
|
||||
val wakeAvailable: Boolean = false,
|
||||
)
|
||||
|
||||
@Composable
|
||||
@@ -143,6 +160,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
|
||||
val beta = remember { AppVersion.parse(BuildConfig.VERSION_NAME)?.isBeta ?: false }
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
// The wake word needs the microphone before it can be turned on.
|
||||
val micForWake = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = true) }
|
||||
WakeWordService.start(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
val actions = remember {
|
||||
object : SettingsActions {
|
||||
override fun use(instance: Instance) {
|
||||
@@ -202,6 +228,36 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantConversation = on) } }
|
||||
}
|
||||
|
||||
override fun wakeWord(on: Boolean) {
|
||||
val mic = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
when {
|
||||
on && !mic -> micForWake.launch(Manifest.permission.RECORD_AUDIO)
|
||||
|
||||
on -> scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = true) }
|
||||
WakeWordService.start(context)
|
||||
}
|
||||
|
||||
else -> scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = false) }
|
||||
WakeWordService.stop(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun wakePhrase(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(wakePhrase = id) } }
|
||||
}
|
||||
|
||||
override fun wakeScreenOnly(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(wakeScreenOnly = on) } }
|
||||
}
|
||||
|
||||
// The list of apps the phone's battery optimisation leaves alone; no permission needed to open it.
|
||||
override fun batterySettings() {
|
||||
runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
@@ -256,6 +312,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
selfUpdate = BuildConfig.SELF_UPDATE,
|
||||
beta = beta,
|
||||
phoneRecognizer = remember { PhoneRecognizer.available(context) },
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
@@ -431,12 +488,13 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
|
||||
stringResource(R.string.assistant_samsung),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
item { WakeWordGroup(state, actions) }
|
||||
item {
|
||||
// Which recogniser turns speech into words: the instance's or the phone's -- what
|
||||
// each one is, and where the recording goes, said in the row itself.
|
||||
@@ -518,6 +576,59 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wake word: off until turned on; the phrase (the engine's own, English); only while the
|
||||
* screen is on; and what it costs and why a phone may stop it, said before it is turned on.
|
||||
*/
|
||||
@Composable
|
||||
private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val on = state.prefs.wakeWord && state.wakeAvailable
|
||||
Group(stringResource(R.string.wake_word)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Hearing,
|
||||
stringResource(R.string.wake_word_listen),
|
||||
subtitle = stringResource(if (state.wakeAvailable) R.string.wake_word_line else R.string.wake_word_unavailable),
|
||||
enabled = state.wakeAvailable,
|
||||
onClick = { actions.wakeWord(!on) },
|
||||
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
|
||||
)
|
||||
if (state.wakeAvailable) {
|
||||
WakePhrases.all.forEach { phrase ->
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.RecordVoiceOver,
|
||||
"“${phrase.words}”",
|
||||
showIcon = false,
|
||||
onClick = { actions.wakePhrase(phrase.id) },
|
||||
trailing = { RadioButton(selected = state.prefs.wakePhrase == phrase.id, onClick = { actions.wakePhrase(phrase.id) }) },
|
||||
)
|
||||
}
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.ScreenLockPortrait,
|
||||
stringResource(R.string.wake_screen_only),
|
||||
subtitle = stringResource(R.string.wake_screen_only_line),
|
||||
onClick = { actions.wakeScreenOnly(!state.prefs.wakeScreenOnly) },
|
||||
trailing = { Switch(checked = state.prefs.wakeScreenOnly, onCheckedChange = actions::wakeScreenOnly) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.BatteryAlert,
|
||||
stringResource(R.string.wake_battery),
|
||||
subtitle = stringResource(R.string.wake_battery_line),
|
||||
onClick = actions::batterySettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.wake_word_privacy) + "\n\n" + stringResource(R.string.wake_word_cost),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Group(title: String, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* A wake word the engine ships: what the person says ([words]), the engine's spelling of it
|
||||
* ([tokens], the model's BPE pieces, worked out once with its `bpe.model` -- the phone has no
|
||||
* tokenizer), and the id Settings keeps.
|
||||
*
|
||||
* Only phrases from this list can be chosen: an open-vocabulary spotter hears any phrase it can
|
||||
* spell, but how well each one works was not measured, and a free text box would invite one that
|
||||
* fires on every other sentence. English only: the model is trained on English speech.
|
||||
*/
|
||||
data class WakePhrase(val id: String, val words: String, val tokens: String)
|
||||
|
||||
object WakePhrases {
|
||||
val all = listOf(
|
||||
WakePhrase("hey_lembas", "Hey Lembas", "▁HE Y ▁LE M B AS"),
|
||||
WakePhrase("ok_lembas", "OK Lembas", "▁O K ▁LE M B AS"),
|
||||
WakePhrase("hello_lembas", "Hello Lembas", "▁HE LL O ▁LE M B AS"),
|
||||
WakePhrase("hey_assistant", "Hey Assistant", "▁HE Y ▁AS S IST ANT"),
|
||||
)
|
||||
|
||||
val default: WakePhrase get() = all.first()
|
||||
|
||||
fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine, as the service sees it: 16 kHz mono samples in, the phrase out when it was heard.
|
||||
* Everything happens on the phone; [accept] neither records nor sends anything.
|
||||
*/
|
||||
interface WakeDetector {
|
||||
/** Feed [samples] (-1..1); true when the wake word ended in them. */
|
||||
fun accept(samples: FloatArray): Boolean
|
||||
|
||||
fun release()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
|
||||
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
|
||||
* can overlap for a moment when one hands over to the other.
|
||||
*/
|
||||
object AssistPresence {
|
||||
private val _open = MutableStateFlow(0)
|
||||
val open: StateFlow<Int> = _open.asStateFlow()
|
||||
|
||||
fun shown() = _open.update { it + 1 }
|
||||
|
||||
fun hidden() = _open.update { (it - 1).coerceAtLeast(0) }
|
||||
}
|
||||
|
||||
/** Why listening for the wake word is paused, or [None]: what the notification and Settings say. */
|
||||
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone }
|
||||
|
||||
/**
|
||||
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
|
||||
* microphone), never in battery saver (the person asked the phone to spare power), and -- when
|
||||
* Settings says so, the default -- only while the screen is on.
|
||||
*/
|
||||
fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, sheetOpen: Boolean, micAllowed: Boolean): WakePause = when {
|
||||
!micAllowed -> WakePause.NoMicrophone
|
||||
sheetOpen -> WakePause.Assistant
|
||||
batterySaver -> WakePause.BatterySaver
|
||||
screenOnly && !screenOn -> WakePause.ScreenOff
|
||||
else -> WakePause.None
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaRecorder
|
||||
import android.os.Bundle
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
|
||||
*
|
||||
* A `microphone` foreground service with its notification up the whole time it runs -- Android
|
||||
* lets an app hear the microphone in the background only that way, and only once the person has
|
||||
* started it from the app. The audio goes to the on-device engine ([WakeEngine]) in memory and
|
||||
* nowhere else; it is not kept, and nothing is sent anywhere until the word is heard. Then the
|
||||
* microphone is let go and the assistant opens, listening, as the power button would open it.
|
||||
*
|
||||
* It pauses itself (the notification says why) while the assistant's sheet is up, in battery
|
||||
* saver, and -- unless Settings says otherwise -- while the screen is off; it goes on once the
|
||||
* reason is gone. It cannot start itself at boot (Android forbids a microphone service there):
|
||||
* [WakeBootReceiver] posts "tap to listen again" instead.
|
||||
*/
|
||||
class WakeWordService : LifecycleService() {
|
||||
private val screenOn = MutableStateFlow(true)
|
||||
private val batterySaver = MutableStateFlow(false)
|
||||
private var listening: Job? = null
|
||||
private var detector: WakeDetector? = null
|
||||
private var phraseId: String? = null
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_SCREEN_ON -> screenOn.value = true
|
||||
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
|
||||
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
channel(this)
|
||||
screenOn.value = power().isInteractive
|
||||
batterySaver.value = power().isPowerSaveMode
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
receiver,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
lifecycleScope.launch {
|
||||
lembas.instances.savePrefs { it.copy(wakeWord = false) }
|
||||
stopSelf()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
// The notification first: Android stops a foreground service that is slow to show one.
|
||||
ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(null, WakePause.None), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
||||
if (listening == null) follow()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
|
||||
private fun follow() {
|
||||
listening = lifecycleScope.launch {
|
||||
combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open) { prefs, on, saver, open ->
|
||||
if (!prefs.wakeWord) {
|
||||
null
|
||||
} else {
|
||||
prefs.wakePhrase to wakePause(on, prefs.wakeScreenOnly, saver, open > 0, micAllowed())
|
||||
}
|
||||
}.distinctUntilChanged().collect { now ->
|
||||
if (now == null) {
|
||||
stopSelf()
|
||||
return@collect
|
||||
}
|
||||
val (id, pause) = now
|
||||
val phrase = WakePhrases.byId(id)
|
||||
notify(phrase, pause)
|
||||
hearing?.cancel()
|
||||
hearing = if (pause == WakePause.None) launch { hear(phrase) } else null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var hearing: Job? = null
|
||||
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
private suspend fun hear(phrase: WakePhrase) {
|
||||
val engine = withContext(Dispatchers.Default) {
|
||||
if (phraseId != phrase.id) {
|
||||
detector?.release()
|
||||
detector = WakeEngine.create(this@WakeWordService, phrase)
|
||||
phraseId = phrase.id
|
||||
}
|
||||
detector
|
||||
} ?: return notify(phrase, WakePause.NoMicrophone)
|
||||
val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
|
||||
val audio = runCatching {
|
||||
AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, RATE))
|
||||
}.getOrNull() ?: return
|
||||
var heard = false
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
audio.startRecording()
|
||||
val chunk = ShortArray(RATE / 10)
|
||||
val samples = FloatArray(chunk.size)
|
||||
while (isActive && !heard) {
|
||||
val read = audio.read(chunk, 0, chunk.size)
|
||||
if (read <= 0) continue
|
||||
for (i in 0 until read) samples[i] = chunk[i] / 32768f
|
||||
heard = engine.accept(if (read == chunk.size) samples else samples.copyOf(read))
|
||||
}
|
||||
} finally {
|
||||
runCatching { audio.stop() }
|
||||
audio.release()
|
||||
}
|
||||
}
|
||||
if (heard) wake()
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening. Through the voice-interaction service
|
||||
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background),
|
||||
* else as an activity; and if Android refuses that too, a notification to tap.
|
||||
*/
|
||||
private fun wake() {
|
||||
AssistPresence.shown() // the microphone is the sheet's from here, until it says it is gone
|
||||
val shownBySystem = LembasAssistService.current?.let { service ->
|
||||
runCatching { service.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
|
||||
} ?: false
|
||||
val opened = shownBySystem || runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
|
||||
if (!opened) {
|
||||
getSystemService(NotificationManager::class.java).notify(
|
||||
HEARD_ID,
|
||||
NotificationCompat.Builder(this, CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(getString(R.string.wake_heard))
|
||||
.setContentIntent(PendingIntent.getActivity(this, 1, AssistActivity.listening(this), PendingIntent.FLAG_IMMUTABLE))
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
// Released by the sheet as it shows and hides; if nothing opened, at once.
|
||||
lifecycleScope.launch {
|
||||
delay(SHEET_GRACE_MS)
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
}
|
||||
|
||||
private fun notify(phrase: WakePhrase, pause: WakePause) {
|
||||
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(phrase, pause))
|
||||
}
|
||||
|
||||
/** What the persistent notification says: the phrase it listens for, or why it is paused. Nothing from the account. */
|
||||
private fun notification(phrase: WakePhrase?, pause: WakePause): Notification {
|
||||
val title = when (pause) {
|
||||
WakePause.None -> getString(R.string.wake_listening_for, (phrase ?: WakePhrases.default).words)
|
||||
WakePause.ScreenOff -> getString(R.string.wake_paused_screen)
|
||||
WakePause.BatterySaver -> getString(R.string.wake_paused_battery)
|
||||
WakePause.Assistant -> getString(R.string.wake_paused_assistant)
|
||||
WakePause.NoMicrophone -> getString(R.string.wake_paused_microphone)
|
||||
}
|
||||
val stop = PendingIntent.getService(this, 2, Intent(this, WakeWordService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
|
||||
val open = PendingIntent.getActivity(this, 3, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
|
||||
return NotificationCompat.Builder(this, CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(getString(R.string.wake_notification_line))
|
||||
.setOngoing(true)
|
||||
.setSilent(true)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(open)
|
||||
.addAction(0, getString(R.string.wake_stop), stop)
|
||||
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun micAllowed() = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun power() = getSystemService(PowerManager::class.java)
|
||||
|
||||
override fun onDestroy() {
|
||||
hearing?.cancel()
|
||||
listening?.cancel()
|
||||
runCatching { unregisterReceiver(receiver) }
|
||||
detector?.release()
|
||||
detector = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL = "wake_word"
|
||||
private const val NOTIFICATION_ID = 7001
|
||||
private const val HEARD_ID = 7002
|
||||
private const val RATE = 16_000
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
|
||||
/** Start listening. Only from the app on screen: Android allows a microphone service from there. */
|
||||
fun start(context: Context) {
|
||||
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, WakeWordService::class.java))
|
||||
}
|
||||
|
||||
fun channel(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
|
||||
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After a restart: Android does not let a microphone service start at boot, so a wake word that
|
||||
* was on says "tap to listen again" -- the tap opens the app, which starts it.
|
||||
*/
|
||||
class WakeBootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
val pending = goAsync()
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
try {
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
if (!prefs.wakeWord || !WakeEngine.AVAILABLE) return@launch
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return@launch
|
||||
WakeWordService.channel(context)
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
4,
|
||||
Intent(context, MainActivity::class.java).putExtra(EXTRA_RESUME, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
context.getSystemService(NotificationManager::class.java).notify(
|
||||
RESUME_ID,
|
||||
NotificationCompat.Builder(context, WakeWordService.CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_resume))
|
||||
.setContentText(context.getString(R.string.wake_resume_line))
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.build(),
|
||||
)
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** On MainActivity's intent: start listening for the wake word again. */
|
||||
const val EXTRA_RESUME = "eu.llembas.android.WAKE_RESUME"
|
||||
const val RESUME_ID = 7003
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user