Wake word: the engine loads, and its state is one truth that is shown
CI / check (push) Canceled after 0s

The model was read from the APK with AssetManager.openFd, which throws for a
compressed asset; the assets were compressed, runCatching swallowed it, and
the engine never loaded on any phone.

- The model is copied out by stream, keyed by a version file the fetch
  script writes (a hash of the pinned model); onnx assets are stored.
- WakeState (Off, Starting, Listening, Paused, Failed) in one StateFlow that
  the service, its notification and Settings read. onStartCommand no longer
  posts the default phrase; the notification is written from the state only.
- WakeListener holds the loop apart from Android: an engine that does not
  load and a microphone that does not start or stops are Failed states with
  a reason, logged, retried with back-off; a new phrase cancels and joins the
  old loop before the engine is released.
- A keywords line is checked against tokens.txt before the engine sees it
  (the engine exits the process on an unknown piece).
- The service is not started without the microphone permission, and the app
  looks again each time it comes to the screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 09:44:49 +00:00
1 parent 2d38ccd321
commit 374574b9ce
24 files changed
+1154 -151

No files matched your search

@@ -78,10 +78,6 @@ 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 &&
@@ -97,6 +93,18 @@ class MainActivity : ComponentActivity() {
}
}
/**
* A wake word that is on, but whose service the phone stopped, listens again -- each time the
* app comes to the screen, which is also when a microphone permission given or taken in the
* system's settings is noticed ([WakeWordService.start] says which it is).
*/
override fun onStart() {
super.onStart()
lifecycleScope.launch {
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity)
}
}
/**
* Keep the app in the language Settings › Language says: the account's by default. A
* language chosen for the app in the system's own settings (Android 13+) since the app last
@@ -34,7 +34,9 @@ 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.ErrorOutline
import androidx.compose.material.icons.filled.Forum
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.Hearing
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Mic
@@ -102,8 +104,13 @@ 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.WakeFailure
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeStatus
import eu.llembas.android.wake.WakeWordService
import eu.llembas.android.wake.wakeTitle
import kotlinx.coroutines.launch
/** What the settings page does; every action has a do-nothing default for the screenshots. */
@@ -154,6 +161,8 @@ data class SettingsState(
val phoneRecognizer: Boolean = false,
/** Whether this build has a wake-word engine (the F-Droid build has none). */
val wakeAvailable: Boolean = false,
/** What the wake word is doing right now (WakeStatus), said under its switch while it is on. */
val wakeState: WakeState = WakeState.Off,
/** Whether Android's notification access is given to LLeMbas. */
val notificationAccess: Boolean = false,
/** The navigation apps installed: NavApp ids. */
@@ -168,6 +177,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
val instances by store.instances.collectAsState(initial = emptyList())
val active by store.active.collectAsState(initial = null)
val prefs by store.prefs.collectAsState(initial = Prefs())
val wakeState by WakeStatus.state.collectAsState()
var pushNote by remember { mutableStateOf<String?>(null) }
var updateNote by remember { mutableStateOf<String?>(null) }
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
@@ -344,6 +354,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
beta = beta,
phoneRecognizer = remember { PhoneRecognizer.available(context) },
wakeAvailable = WakeEngine.AVAILABLE,
wakeState = wakeState,
// Read again each time Settings is composed: the person comes back from the system's page.
notificationAccess = NotificationReader.granted(context),
navApps = remember { NavApp.installedApps(context).map { it.id } },
@@ -629,6 +640,27 @@ private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) {
onClick = { actions.wakeWord(!on) },
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
)
if (on) {
// The truth, not the setting: listening, paused and why, or failed and why. A tap
// tries again (and asks for the microphone when that is what is missing).
val wake = state.wakeState
val trouble = wake is WakeState.Failed || wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone)
Rule()
SettingRow(
if (trouble) Icons.Filled.ErrorOutline else Icons.Filled.GraphicEq,
wakeTitle(LocalContext.current, wake),
subtitle = when {
wake is WakeState.Failed && wake.why != WakeFailure.NoEngine ->
listOf(stringResource(R.string.wake_failed_line), wake.detail).filter { it.isNotBlank() }.joinToString("\n")
wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone) -> stringResource(R.string.wake_tap_to_start)
else -> null
},
tint = if (trouble) palette.warning else null,
onClick = { actions.wakeWord(true) },
)
}
if (state.wakeAvailable) {
WakePhrases.all.forEach { phrase ->
Rule()
@@ -1,9 +1,14 @@
package eu.llembas.android.wake
import android.content.Context
import eu.llembas.android.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* A wake word the engine ships: what the person says ([words]), the engine's spelling of it
@@ -40,6 +45,14 @@ interface WakeDetector {
fun release()
}
/** The microphone, as the listener sees it: 16 kHz mono samples, already recording when it is made. */
interface WakeMicrophone {
/** Fill [into]; how many samples were read, or a negative number when the microphone failed. */
fun read(into: ShortArray): Int
fun close()
}
/**
* 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
@@ -54,8 +67,13 @@ object AssistPresence {
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 }
/**
* Why listening for the wake word is paused, or [None]: what the notification and Settings say.
* [Silent] is the one the listener finds out itself: the microphone is open but gives no sound at
* all, which is what Android hands a background app while a call or another recorder has it, or
* while the phone's microphone switch is off.
*/
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone, Silent }
/**
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
@@ -69,3 +87,129 @@ fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, she
screenOnly && !screenOn -> WakePause.ScreenOff
else -> WakePause.None
}
/** What went wrong: this build has no engine, the model's files, the engine itself, or the microphone. */
enum class WakeFailure { NoEngine, Model, Engine, Microphone }
/** A failure with its kind, so the notification and Settings can say it in plain words. */
class WakeError(val why: WakeFailure, cause: Throwable? = null, message: String? = cause?.message) : Exception(message, cause) {
/** The technical half, for Settings and the log: the exception's name and what it said. */
val detail: String
get() = listOfNotNull(cause?.javaClass?.simpleName, message?.takeIf { it.isNotBlank() }).joinToString(": ").take(DETAIL_MAX)
private companion object {
const val DETAIL_MAX = 200
}
}
/**
* What the wake word is doing, the one truth the service, its notification and Settings all read
* ([WakeStatus.state]). [Failed] carries the plain reason and the technical [Failed.detail];
* nothing here is ever a guess from the settings alone.
*/
sealed interface WakeState {
/** Not running: turned off, or the phone stopped the service. */
data object Off : WakeState
/** Running, loading the engine. */
data object Starting : WakeState
/** The microphone is open and the engine hears it, for these words. */
data class Listening(val phrase: String) : WakeState
data class Paused(val why: WakePause) : WakeState
data class Failed(val why: WakeFailure, val detail: String = "") : WakeState
}
/** The wake word's state for the whole process: written by the service, read by everything else. */
object WakeStatus {
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
val state: StateFlow<WakeState> = _state.asStateFlow()
fun set(now: WakeState) {
_state.value = now
}
}
/**
* [state] in plain words: the notification's title and Settings' line. A failure names what
* failed and that it is tried again; it never claims to listen while it does not.
*/
fun wakeTitle(context: Context, state: WakeState): String = when (state) {
WakeState.Off -> context.getString(R.string.wake_off)
WakeState.Starting -> context.getString(R.string.wake_starting)
is WakeState.Listening -> context.getString(R.string.wake_listening_for, state.phrase)
is WakeState.Paused -> context.getString(
when (state.why) {
WakePause.None -> R.string.wake_starting
WakePause.ScreenOff -> R.string.wake_paused_screen
WakePause.BatterySaver -> R.string.wake_paused_battery
WakePause.Assistant -> R.string.wake_paused_assistant
WakePause.NoMicrophone -> R.string.wake_paused_microphone
WakePause.Silent -> R.string.wake_paused_silent
},
)
is WakeState.Failed -> context.getString(
when (state.why) {
WakeFailure.NoEngine -> R.string.wake_failed_no_engine
WakeFailure.Model -> R.string.wake_failed_model
WakeFailure.Engine -> R.string.wake_failed_engine
WakeFailure.Microphone -> R.string.wake_failed_microphone
},
)
}
/** The notification's second line: the promise while it listens, else nothing more to say. */
fun wakeLine(context: Context, state: WakeState): String? = when (state) {
is WakeState.Listening -> context.getString(R.string.wake_notification_line)
is WakeState.Failed -> if (state.why == WakeFailure.NoEngine) null else context.getString(R.string.wake_failed_line)
else -> null
}
/** The engine's keywords file for [phrase]: its pieces, then `@` and the id the engine answers with. */
fun wakeKeywords(phrase: WakePhrase): String = "${phrase.tokens} @${phrase.id}\n"
/**
* Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece
* and its number per line): the engine ends the whole app on a piece it does not know, so it is
* never handed one.
*/
fun checkKeywords(keywords: String, tokens: String) {
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
for (line in keywords.lineSequence().filter { it.isNotBlank() }) {
val unknown = line.split(' ').filter { it.isNotEmpty() && it[0] !in ":#@" }.firstOrNull { it !in known }
if (unknown != null) throw WakeError(WakeFailure.Engine, message = "the model has no piece \"$unknown\"")
}
}
/**
* The model's files, out of the APK's assets into [dir], where the engine reads them as files.
* Copied by stream ([open] is `AssetManager.open`), so it works however the APK stores them, and
* keyed by the assets' `version` (a hash of the pinned model, written by
* `scripts/fetch-wakeword.py`): a new model replaces the old one, and a copy that was cut short
* has no marker and is made again.
*/
fun unpackWakeModel(open: (String) -> InputStream, dir: File, files: List<String>) {
val version = open("version").use { it.readBytes().decodeToString().trim() }
val marker = File(dir, "version")
if (marker.isFile && marker.readText() == version && files.all { File(dir, it).length() > 0 }) return
if (!dir.isDirectory && !dir.mkdirs()) throw IOException("cannot make ${dir.name}")
marker.delete()
for (name in files) {
val part = File(dir, "$name.part")
open(name).use { input -> part.outputStream().use { input.copyTo(it) } }
if (part.length() == 0L) throw IOException("$name is empty")
val target = File(dir, name)
target.delete()
if (!part.renameTo(target)) throw IOException("cannot write $name")
}
marker.writeText(version)
}
/** How long to wait before the next try after the [attempt]-th failure in a row: 2 s, 5 s, 15 s, 1 min, then every 5 min. */
fun wakeBackoff(attempt: Int): Long = listOf(2_000L, 5_000L, 15_000L, 60_000L).getOrElse(attempt) { 300_000L }
@@ -0,0 +1,181 @@
package eu.llembas.android.wake
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
/**
* The listening itself, apart from Android so it can be tested: follows the plans, keeps one
* engine and one microphone, and says every change of state through [say].
*
* Nothing fails silently. An engine that does not load, a microphone that does not start or
* stops giving samples: each is a [WakeState.Failed] with its reason, logged, and tried again
* after [backoff]. And the engine is never released while a loop may still be feeding it: a new
* plan first cancels the old loop and waits for it to end ([cancelAndJoin]), then the engine is
* swapped, on the one coroutine that owns it.
*/
class WakeListener(
private val say: (WakeState) -> Unit,
private val engine: (keywords: String) -> WakeDetector,
private val microphone: () -> WakeMicrophone,
private val heard: suspend (WakePhrase) -> Unit,
private val work: CoroutineDispatcher = Dispatchers.IO,
private val backoff: (attempt: Int) -> Long = ::wakeBackoff,
private val log: (String, Throwable) -> Unit = { _, _ -> },
) {
@Volatile private var detector: WakeDetector? = null
@Volatile private var detectorFor: String? = null
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
var hearing: Job? = null
try {
plans.distinctUntilChanged().collect { plan ->
hearing?.cancelAndJoin()
hearing = null
if (plan.pause != WakePause.None) {
say(WakeState.Paused(plan.pause))
} else {
hearing = launch { hear(plan) }
}
}
} finally {
withContext(NonCancellable) {
hearing?.cancelAndJoin()
release()
}
}
}
private fun release() {
runCatching { detector?.release() }
detector = null
detectorFor = null
}
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
private suspend fun hear(plan: WakePlan) {
var failures = 0
while (true) {
try {
listen(plan)
failures = 0
heard(plan.phrase)
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
delay(HEARD_REST_MS)
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
log("wake word: ${e.why}: ${e.detail}", e)
say(WakeState.Failed(e.why, e.detail))
// A build without an engine does not grow one: nothing to try again.
if (e.why == WakeFailure.NoEngine) return
delay(backoff(failures++))
}
}
}
/** One stretch of listening: returns when the word was heard, throws a [WakeError] when something failed. */
private suspend fun listen(plan: WakePlan) {
val spotter = engineFor(plan)
try {
withContext(work) {
// Opened and closed on this one thread, so a cancellation cannot leave it open.
val mic = try {
microphone()
} catch (e: Exception) {
throw WakeError(WakeFailure.Microphone, e)
}
try {
say(WakeState.Listening(plan.phrase.words))
val chunk = ShortArray(CHUNK)
var empty = 0
var silent = 0
while (true) {
ensureActive()
val read = mic.read(chunk)
if (read < 0) throw WakeError(WakeFailure.Microphone, message = "the microphone stopped (error $read)")
if (read == 0) {
if (++empty > EMPTY_READS) throw WakeError(WakeFailure.Microphone, message = "the microphone gives no samples")
continue
}
empty = 0
val samples = FloatArray(read)
var sound = false
for (i in 0 until read) {
if (chunk[i] != 0.toShort()) sound = true
samples[i] = chunk[i] / 32768f
}
// Exact silence for seconds is not a quiet room: Android gives a background
// app zeros while another app has the microphone or its switch is off.
if (sound) {
if (silent >= SILENT_SAMPLES) say(WakeState.Listening(plan.phrase.words))
silent = 0
} else if (silent < SILENT_SAMPLES) {
silent += read
if (silent >= SILENT_SAMPLES) say(WakeState.Paused(WakePause.Silent))
}
if (spotter.accept(samples)) break
}
} finally {
runCatching { mic.close() }
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// The engine threw while hearing: it is not trusted again, a new one is made.
release()
throw WakeError(WakeFailure.Engine, e)
}
}
/** The engine for [plan]'s keywords: the one there is, or a new one once the old is released. */
private suspend fun engineFor(plan: WakePlan): WakeDetector {
detector?.takeIf { detectorFor == plan.keywords }?.let { return it }
release()
say(WakeState.Starting)
return try {
// Kept the moment it exists, so a cancellation while it loads cannot lose it unreleased.
withContext(work) {
engine(plan.keywords).also {
detector = it
detectorFor = plan.keywords
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// A missing native library is an Error, not an Exception: it is a failure to show all the same.
throw WakeError(WakeFailure.Engine, e)
}
}
companion object {
const val RATE = 16_000
/** A tenth of a second at a time. */
private const val CHUNK = RATE / 10
private const val EMPTY_READS = 50
private const val SILENT_SAMPLES = RATE * 5
private const val HEARD_REST_MS = 1_500L
}
}
@@ -16,6 +16,7 @@ import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
@@ -32,11 +33,10 @@ 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.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
@@ -55,15 +55,22 @@ import kotlinx.coroutines.withContext
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 mayRecord = MutableStateFlow(true)
private var following: Job? = null
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
private var keepState = false
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_ON -> {
screenOn.value = true
mayRecord.value = micAllowed(this@WakeWordService)
}
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
}
}
@@ -95,69 +102,66 @@ class WakeWordService : LifecycleService() {
}
return START_NOT_STICKY
}
mayRecord.value = micAllowed(this)
// 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()
// It says what is true now -- "starting" for a service that just began, and on every
// later start (the app opens) whatever the state already is; never a phrase by default.
val now = WakeStatus.state.value.takeUnless { following == null || it == WakeState.Off } ?: WakeState.Starting
try {
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
} catch (e: Exception) {
// Android refuses a microphone service without the permission, or from the background.
Log.w(TAG, "wake word: the service could not start", e)
keepState = true
WakeStatus.set(
if (mayRecord.value) {
WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail)
} else {
WakeState.Paused(WakePause.NoMicrophone)
},
)
stopSelf()
return START_NOT_STICKY
}
if (following == null) {
keepState = false
WakeStatus.set(now)
following = lifecycleScope.launch { follow() }
// The one place the notification is written: from the state, whenever it changes.
val manager = getSystemService(NotificationManager::class.java)
lifecycleScope.launch {
WakeStatus.state.collect { state ->
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
}
}
}
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 suspend fun follow() {
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
if (!prefs.wakeWord) {
null
} else {
val phrase = WakePhrases.byId(prefs.wakePhrase)
WakePlan(phrase, wakeKeywords(phrase), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
}
}
}
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()
}
val listener = WakeListener(
say = WakeStatus::set,
engine = { keywords -> WakeEngine.create(this, keywords) },
microphone = { PhoneMicrophone() },
heard = { wake() },
log = { message, cause -> Log.w(TAG, message, cause) },
)
try {
listener.follow(plans.takeWhile { it != null }.filterNotNull())
} finally {
// After the loop has ended, so nothing it said on its way out is left standing.
if (!keepState) WakeStatus.set(WakeState.Off)
}
if (heard) wake()
stopSelf()
}
/**
@@ -190,44 +194,13 @@ class WakeWordService : LifecycleService() {
}
}
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
// The scope ends with the service: the listener's loop is joined and its engine released
// on the way out (WakeListener.follow), not here under a loop that may still run.
if (!keepState) WakeStatus.set(WakeState.Off)
super.onDestroy()
}
@@ -235,19 +208,33 @@ class WakeWordService : LifecycleService() {
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
private const val TAG = "LLeMbasWake"
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. */
/**
* Start listening, or say why not. Only from the app on screen: Android allows a
* microphone service from there, and only with the microphone permission -- without it
* the service is not started at all, and the state says so.
*/
fun start(context: Context) {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
if (!WakeEngine.AVAILABLE) return WakeStatus.set(WakeState.Failed(WakeFailure.NoEngine))
if (!micAllowed(context)) return WakeStatus.set(WakeState.Paused(WakePause.NoMicrophone))
try {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
} catch (e: Exception) {
Log.w(TAG, "wake word: the service could not be started", e)
WakeStatus.set(WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail))
}
}
fun stop(context: Context) {
context.stopService(Intent(context, WakeWordService::class.java))
WakeStatus.set(WakeState.Off)
}
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
fun channel(context: Context) {
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
@@ -256,6 +243,63 @@ class WakeWordService : LifecycleService() {
}
}
/**
* The persistent notification, from [state] alone: what the wake word is doing in plain words
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
*/
fun wakeNotification(context: Context, state: WakeState): Notification {
val stop = PendingIntent.getService(
context,
2,
Intent(context, WakeWordService::class.java).setAction(WakeWordService.ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val open = PendingIntent.getActivity(context, 3, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(context, WakeWordService.CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(wakeTitle(context, state))
.setContentText(wakeLine(context, state))
.setOngoing(true)
.setSilent(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(open)
.addAction(0, context.getString(R.string.wake_stop), stop)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
/**
* The phone's microphone at 16 kHz, recording from the moment it is made -- or an exception that
* says what did not work. Android reports none of this by throwing: a recorder that could not be
* opened is merely "uninitialized", and one that did not start merely "stopped".
*/
@android.annotation.SuppressLint("MissingPermission")
private class PhoneMicrophone : WakeMicrophone {
private val audio: AudioRecord
init {
val rate = WakeListener.RATE
val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
check(min > 0) { "the phone cannot record at 16 kHz" }
audio = AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate))
try {
check(audio.state == AudioRecord.STATE_INITIALIZED) { "the microphone could not be opened" }
audio.startRecording()
check(audio.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "recording did not start; another app may have the microphone" }
} catch (e: Exception) {
audio.release()
throw e
}
}
override fun read(into: ShortArray): Int = audio.read(into, 0, into.size)
override fun close() {
runCatching { audio.stop() }
audio.release()
}
}
/**
* 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.