Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
perf(wakeword): keep the ONNX sessions loaded across pause and resume
Durganshu Mishraaa27494d6c50
diff --git a/app/src/androidTest/java/com/gotcha/service/WakeWordDetectorLifecycleTest.kt b/app/src/androidTest/java/com/gotcha/service/WakeWordDetectorLifecycleTest.ktnew file mode 100644index 0000000..6aba1d0--- /dev/null+++ b/app/src/androidTest/java/com/gotcha/service/WakeWordDetectorLifecycleTest.kt@@ -0,0 +1,136 @@+package com.gotcha.service++import android.Manifest+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.rule.GrantPermissionRule+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference++/**+ * Guards the pause/release split from issue #37.+ *+ * `AssistiveBallService` pauses the listener on every call transition *and*+ * every TTS utterance, which before this split meant re-reading ~2.6 MB of+ * model bytes and rebuilding three ORT sessions each time the app spoke a+ * single sentence. The fix only holds if [WakeWordDetector.pause] genuinely+ * keeps the sessions, so that is asserted directly rather than inferred from+ * how long a resume takes.+ */+@RunWith(AndroidJUnit4::class)+class WakeWordDetectorLifecycleTest {++ @get:Rule+ val micPermission: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.RECORD_AUDIO)++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ private val error = AtomicReference<String?>(null)+ private var started = CountDownLatch(1)+ private var detector: WakeWordDetector? = null++ @After+ fun tearDown() {+ detector?.release()+ scope.cancel()+ }++ @Test+ fun pauseKeepsTheModelsLoaded_releaseGivesThemBack() {+ val detector = newDetector()++ awaitStart(detector)+ assertEquals("cold start should load the models once", 1, detector.sessionLoadCount)++ // Three rounds of the churn a talkative session produces.+ repeat(3) { round ->+ detector.pause()+ assertTrue("detector still running after pause in round $round", !detector.isRunning())+ awaitStart(detector)+ assertEquals(+ "resume in round $round reloaded the models",+ 1,+ detector.sessionLoadCount+ )+ }++ // release() is the other half of the contract: it must actually let go,+ // so switching the wake word off does not leave 2.6 MB of models resident.+ detector.release()+ awaitStart(detector)+ assertEquals("release should force a fresh load", 2, detector.sessionLoadCount)+ assertNull(error.get())+ }++ @Test+ fun pauseReleasesTheMicrophone() {+ val detector = newDetector()+ awaitStart(detector)+ detector.pause()++ // The privacy guarantee in privacy-data-retention.md §10.3 is that the+ // mic is handed back while the app's own TTS speaks — keeping the ONNX+ // sessions must not have quietly weakened that. If pause() still held+ // the recorder, this second AudioRecord could not start.+ val probe = android.media.AudioRecord(+ android.media.MediaRecorder.AudioSource.VOICE_RECOGNITION,+ OnnxWakeWordPipeline.SAMPLE_RATE,+ android.media.AudioFormat.CHANNEL_IN_MONO,+ android.media.AudioFormat.ENCODING_PCM_16BIT,+ OnnxWakeWordPipeline.FRAME_SIZE * 2 * 4+ )+ try {+ assertEquals(+ android.media.AudioRecord.STATE_INITIALIZED,+ probe.state+ )+ probe.startRecording()+ val buffer = ShortArray(OnnxWakeWordPipeline.FRAME_SIZE)+ assertTrue("could not read audio after pause", probe.read(buffer, 0, buffer.size) > 0)+ } finally {+ try {+ probe.stop()+ } catch (_: IllegalStateException) {+ // Never started.+ }+ probe.release()+ }+ }++ private fun newDetector(): WakeWordDetector {+ val context = ApplicationProvider.getApplicationContext<Context>()+ return WakeWordDetector(+ context = context,+ scope = scope,+ sensitivityProvider = { WakeWordMatcher.DEFAULT_SENSITIVITY },+ onStarted = { started.countDown() },+ onDetected = {},+ onError = { message ->+ error.set(message)+ started.countDown()+ }+ ).also { detector = it }+ }++ private fun awaitStart(detector: WakeWordDetector) {+ started = CountDownLatch(1)+ assertTrue("start() reported a precondition failure", detector.start())+ assertTrue(+ "listener never started (error=${error.get()})",+ started.await(10, TimeUnit.SECONDS)+ )+ assertNull("listener reported an error", error.get())+ }+}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 3feec3b..ece3c6f 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -79,7 +79,7 @@ class AssistiveBallService : Service() {private val wakeWordSettingsWatcher = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->val s = settingsRepository.load()if (!s.wakeWordEnabled || !s.assistiveBallEnabled) {- wakeWordDetector.stop()+ wakeWordDetector.release()return@OnSharedPreferenceChangeListener}// The key arrives encrypted; compare the value read back instead (see@@ -227,7 +227,9 @@ class AssistiveBallService : Service() {callController.state.collect { state ->val active = state != CallState.IDLE && state != CallState.ENDINGif (active) {- wakeWordDetector.stop()+ // Pause, not release: a call ends and we re-arm within+ // seconds, so keep the models loaded across it.+ wakeWordDetector.pause()} else if (state == CallState.IDLE) {maybeStartWakeWord()}@@ -247,10 +249,14 @@ class AssistiveBallService : Service() {// post-detection isSpeaking guard in onWakeWordDetected is a second// line of defence against self-triggering, but stopping the listener// here closes the race at the source — see privacy-data-retention.md §10.3.+ // pause() still hands the microphone back in full; it keeps only the+ // loaded ONNX models, which hold no audio. The privacy guarantee is+ // unchanged — what goes away is reloading 2.6 MB of models every time+ // the app speaks a sentence.scope.launch {ttsEngine.isSpeaking.collect { speaking ->if (speaking) {- wakeWordDetector.stop()+ wakeWordDetector.pause()} else if (callController.state.value == CallState.IDLE) {maybeStartWakeWord()}@@ -864,7 +870,7 @@ class AssistiveBallService : Service() {) == android.content.pm.PackageManager.PERMISSION_GRANTEDprivate fun onWakeWordDetected() {- wakeWordDetector.stop()+ wakeWordDetector.pause()if (ttsEngine.isSpeaking.value) {// The app was reading something aloud (e.g. a screen read-aloud that// happened to contain "gotcha") — never start a call from our own@@ -894,12 +900,13 @@ class AssistiveBallService : Service() {if (appliedWakeWordSensitivity != settings.wakeWordSensitivity &&wakeWordDetector.isRunning()) {- wakeWordDetector.stop()+ wakeWordDetector.pause()}appliedWakeWordSensitivity = settings.wakeWordSensitivitywakeWordDetector.start()} else {- wakeWordDetector.stop()+ // Switched off, or no mic grant: give the models back.+ wakeWordDetector.release()}}@@ -924,7 +931,7 @@ class AssistiveBallService : Service() {override fun onDestroy() {if (instance === this) instance = null_isRunning.value = false- wakeWordDetector.stop()+ wakeWordDetector.release()if (::settingsPrefs.isInitialized) {settingsPrefs.unregisterOnSharedPreferenceChangeListener(wakeWordSettingsWatcher)}@@ -1007,7 +1014,7 @@ class AssistiveBallService : Service() {// ---- Lifecycle helpers ----private fun stopBall() {- wakeWordDetector.stop()+ wakeWordDetector.release()if (::settingsPrefs.isInitialized) {settingsPrefs.unregisterOnSharedPreferenceChangeListener(wakeWordSettingsWatcher)}diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.ktindex 7760cfb..98fe36b 100644--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt@@ -25,6 +25,11 @@ import java.util.concurrent.atomic.AtomicBoolean* The three ONNX models are read from assets and loaded on an IO coroutine —* model load takes tens of milliseconds, so doing it on the service's main* thread would show up as a ball-service freeze right after start.+ *+ * There are two ways to stop it, and the difference is the point:+ * [pause] gives up the microphone but keeps the loaded models, for the+ * constant interruptions of ordinary use; [release] gives up everything, for+ * when the feature is switched off or the service is going away.*/class WakeWordDetector(context: Context,@@ -41,12 +46,27 @@ class WakeWordDetector(private val running = AtomicBoolean(false)private var job: Job? = nullprivate var recorder: AudioRecord? = null- private var melSession: OrtSession? = null- private var embeddingSession: OrtSession? = null- private var classifierSession: OrtSession? = null++ /**+ * The three ORT sessions, cached across [pause]/[start] cycles. Only+ * [release] closes them — see [pause] for why.+ */+ private var sessions: Sessions? = nullprivate var matcher = WakeWordMatcher(WakeWordMatcher.DEFAULT_SENSITIVITY)private var generation = 0+ private class Sessions(+ val mel: OrtSession,+ val embedding: OrtSession,+ val classifier: OrtSession+ ) {+ fun close() {+ mel.close()+ embedding.close()+ classifier.close()+ }+ }+@Volatilevar lastError: String? = nullprivate set@@ -71,26 +91,49 @@ class WakeWordDetector(return true}- fun stop() {+ /**+ * Stops listening and **fully releases the microphone**, but keeps the ONNX+ * sessions loaded for the next [start].+ *+ * This is the right call for every transient interruption — a call starting+ * or ending, the app's own TTS speaking. Those happen constantly: the+ * service pauses the listener on every single TTS utterance, and before+ * this split that meant re-reading ~2.6 MB of model bytes out of assets and+ * rebuilding three ORT sessions each time the app said one sentence.+ *+ * The mic is still released here, not merely stopped. That matters beyond+ * battery: pausing while TTS speaks is a privacy guarantee, not an+ * optimisation (privacy-data-retention.md §10.3), and "we kept the mic open+ * but promise we ignored it" is not the same guarantee. Keeping sessions is+ * safe because a loaded model holds no audio.+ */+ fun pause() {+ teardown(closeSessions = false)+ }++ /**+ * Stops listening and frees everything, sessions included. For when the+ * wake word is switched off or the service is going away — not for the+ * pause/resume churn of ordinary use.+ */+ fun release() {+ teardown(closeSessions = true)+ }++ private fun teardown(closeSessions: Boolean) {val oldRecorder: AudioRecord?- val oldMel: OrtSession?- val oldEmbedding: OrtSession?- val oldClassifier: OrtSession?+ val oldSessions: Sessions?val oldJob: Job?synchronized(stateLock) {running.set(false)generation++matcher.reset()oldRecorder = recorder- oldMel = melSession- oldEmbedding = embeddingSession- oldClassifier = classifierSessionoldJob = job+ oldSessions = if (closeSessions) sessions else nullrecorder = null- melSession = null- embeddingSession = null- classifierSession = nulljob = null+ if (closeSessions) sessions = null}oldRecorder?.let {try {@@ -100,7 +143,7 @@ class WakeWordDetector(}it.release()}- closeSessions(oldMel, oldEmbedding, oldClassifier)+ oldSessions?.close()oldJob?.cancel()}@@ -109,14 +152,13 @@ class WakeWordDetector(@SuppressLint("MissingPermission")private suspend fun initializeAndListen(generation: Int) {val env = OrtEnvironment.getEnvironment()- var createdMel: OrtSession? = null- var createdEmbedding: OrtSession? = null- var createdClassifier: OrtSession? = null+ var loadedSessions: Sessions? = nullvar createdRecorder: AudioRecord? = nulltry {- createdMel = loadSession(env, "$modelAssetDir/melspectrogram.onnx")- createdEmbedding = loadSession(env, "$modelAssetDir/embedding_model.onnx")- createdClassifier = loadSession(env, "$modelAssetDir/$classifierModel")+ // Reuse the sessions from a previous run when this is a resume+ // after pause(); only a cold start pays the ~2.6 MB model load.+ val cached = synchronized(stateLock) { sessions }+ val active = cached ?: loadSessions(env).also { loadedSessions = it }// Bytes, not samples: 16-bit mono. A minimum-size buffer forces a// wakeup every 80 ms and leaves no room to absorb the burst of work// that re-arming the gate can cost, so ask for ~1.3 s instead. The@@ -139,13 +181,13 @@ class WakeWordDetector(synchronized(stateLock) {if (!running.get() || generation != this.generation) {- closeSessions(createdMel, createdEmbedding, createdClassifier)+ // Stopped while loading. Only discard sessions this run+ // created — a cached set belongs to whoever comes next.+ loadedSessions?.close()createdRecorder.release()return}- melSession = createdMel- embeddingSession = createdEmbedding- classifierSession = createdClassifier+ sessions = activerecorder = createdRecorder}scope.launch(Dispatchers.Main) { onStarted() }@@ -153,17 +195,42 @@ class WakeWordDetector(generation = generation,env = env,localRecorder = createdRecorder,- localMel = createdMel,- localEmbedding = createdEmbedding,- localClassifier = createdClassifier+ localSessions = active)} catch (e: Exception) {- closeSessions(createdMel, createdEmbedding, createdClassifier)+ loadedSessions?.close()createdRecorder?.release()fail(startupError(e), e, generation)}}+ /**+ * How many times all three models have been read out of assets and turned+ * into ORT sessions. The whole point of [pause] is that this does not climb+ * with ordinary use, and a count is the only way to assert that from a test+ * — the alternative is timing a resume, which is inherently flaky.+ */+ @Volatile+ internal var sessionLoadCount = 0+ private set++ /** Loads all three models, closing any that succeeded if a later one fails. */+ private fun loadSessions(env: OrtEnvironment): Sessions {+ var mel: OrtSession? = null+ var embedding: OrtSession? = null+ try {+ mel = loadSession(env, "$modelAssetDir/melspectrogram.onnx")+ embedding = loadSession(env, "$modelAssetDir/embedding_model.onnx")+ val loaded = Sessions(mel, embedding, loadSession(env, "$modelAssetDir/$classifierModel"))+ sessionLoadCount+++ return loaded+ } catch (e: Exception) {+ mel?.close()+ embedding?.close()+ throw e+ }+ }+/*** Loads one model with a thread configuration suited to a 12.5 Hz duty* cycle (issue #37). ONNX Runtime's defaults are tuned for throughput on a@@ -205,9 +272,7 @@ class WakeWordDetector(generation: Int,env: OrtEnvironment,localRecorder: AudioRecord,- localMel: OrtSession,- localEmbedding: OrtSession,- localClassifier: OrtSession+ localSessions: Sessions) {// Read several 80 ms frames per wakeup rather than one. The pipeline// splits whatever it is handed back into frames, so this changes only@@ -215,9 +280,9 @@ class WakeWordDetector(val block = ShortArray(OnnxWakeWordPipeline.FRAME_SIZE * READ_FRAMES)val pipeline = OnnxWakeWordPipeline(env = env,- melSession = localMel,- embeddingSession = localEmbedding,- classifierSession = localClassifier,+ melSession = localSessions.mel,+ embeddingSession = localSessions.embedding,+ classifierSession = localSessions.classifier,matcher = matcher)try {@@ -262,7 +327,9 @@ class WakeWordDetector(}lastError = messageif (cause != null) Log.w(TAG, message, cause)- stop()+ // Full release, not pause: a failure here can mean a session that never+ // loaded or one that broke mid-run, so nothing cached is worth keeping.+ release()scope.launch(Dispatchers.Main) { onError(message) }}@@ -272,12 +339,6 @@ class WakeWordDetector(else -> "Wake word could not start."}- private fun closeSessions(mel: OrtSession?, embedding: OrtSession?, classifier: OrtSession?) {- mel?.close()- embedding?.close()- classifier?.close()- }-companion object {const val WAKE_PHRASE = "hey gotcha"const val MODEL_ASSET_DIR = "openwakeword"