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): stop recomputing the gate's noise floor every frame
Durganshu Mishra57acd6ee265a
diff --git a/app/src/androidTest/java/com/gotcha/service/WakeWordDetectionDiagnosticTest.kt b/app/src/androidTest/java/com/gotcha/service/WakeWordDetectionDiagnosticTest.ktindex 1229c99..c72b247 100644--- a/app/src/androidTest/java/com/gotcha/service/WakeWordDetectionDiagnosticTest.kt+++ b/app/src/androidTest/java/com/gotcha/service/WakeWordDetectionDiagnosticTest.kt@@ -170,10 +170,15 @@ class WakeWordDetectionDiagnosticTest {override fun onError(utteranceId: String?) = done.countDown()})tts.synthesizeToFile(text, null, out, "wake-probe")- assertTrue("TTS never produced a file", done.await(30, TimeUnit.SECONDS))- tts.shutdown()-- return resampleTo16k(readWav(out))+ try {+ assertTrue("TTS never produced a file", done.await(30, TimeUnit.SECONDS))+ tts.shutdown()+ return resampleTo16k(readWav(out))+ } finally {+ // A rendering of the wake phrase is not something to leave sitting+ // in the app's cache after the test.+ out.delete()+ }}/** Minimal PCM-16 WAV reader: walks the chunk list for `fmt ` and `data`. */diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex a1a57ce..d27b52f 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -874,8 +874,13 @@ class AssistiveBallService : Service() {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- // voice. Resume listening instead.- maybeStartWakeWord()+ // voice.+ //+ // Deliberately does not re-arm here. Doing so put the listener back+ // on the mic *while the app was still talking*, so the rest of the+ // utterance could trigger this path again and again. The isSpeaking+ // collector re-arms as soon as the app goes quiet, which is the+ // moment listening should resume.return}val s = settingsRepository.load()diff --git a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.ktindex 7f2e64a..68b851b 100644--- a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt+++ b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt@@ -50,6 +50,9 @@ import java.nio.FloatBuffer* and the classifier input. The mel rows and embeddings are recycled through* [melRowPool] and [featurePool] as they fall out of their bounded buffers.*+ * [WakeWordGate] holds the same line: its noise floor is a sorted percentile,+ * but over reused scratch and refreshed on a schedule rather than per frame.+ ** What still allocates per frame: the `OnnxTensor` wrappers and whatever ORT* hands back from `run()`. Both are ORT's to own. This is not "zero* allocation" — keep the claim honest, a profiler is the arbiter.@@ -251,7 +254,9 @@ internal class OnnxWakeWordPipeline(if (!timed(PipelineProbe.Stage.MEL) { computeMel() }) return falseif (!open) {- if (gatedFrames < CLASSIFIER_FRAMES) gatedFrames+++ // Capped at what a replay can actually use; anything older has+ // already fallen out of the classifier's window.+ if (gatedFrames < CLASSIFIER_FRAMES - 1) gatedFrames++probe?.onGated()return false}diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.ktindex a40edcc..59da53b 100644--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt@@ -424,12 +424,15 @@ class WakeWordDetector(if (rmsDb > peakRms) peakRms = rmsDbif (rmsDb < quietestRms) quietestRms = rmsDbif (reads % REPORT_EVERY_READS != 0) return+ // Locale.ROOT, not the default: on a decimal-comma device these+ // become "-70,5" and stop being greppable, which is the whole point+ // of the line.Log.d(TAG,- "heard: rms ${"%.1f".format(quietestRms)}..${"%.1f".format(peakRms)} dBFS, " +- "frames=$frames scored=$scored gated=$gated peakScore=${"%.3f".format(peakScore)} " +- "mel[${"%.2f".format(melMin)}..${"%.2f".format(melMax)} avg ${"%.2f".format(melMean)}] " +- "emb[${"%.2f".format(embMin)}..${"%.2f".format(embMax)} avg ${"%.2f".format(embMean)}]"+ "heard: rms ${fmt(quietestRms, 1)}..${fmt(peakRms, 1)} dBFS, " ++ "frames=$frames scored=$scored gated=$gated peakScore=${fmt(peakScore, 3)} " ++ "mel[${fmt(melMin, 2)}..${fmt(melMax, 2)} avg ${fmt(melMean, 2)}] " ++ "emb[${fmt(embMin, 2)}..${fmt(embMax, 2)} avg ${fmt(embMean, 2)}]")melMin = Float.MAX_VALUEmelMax = -Float.MAX_VALUE@@ -456,6 +459,9 @@ class WakeWordDetector(if (score > peakScore) peakScore = score}+ private fun fmt(value: Float, decimals: Int): String =+ String.format(java.util.Locale.ROOT, "%.${decimals}f", value)+private companion object {/** ~3 s at 4 frames per read. */const val REPORT_EVERY_READS = 10diff --git a/app/src/main/java/com/gotcha/service/WakeWordGate.kt b/app/src/main/java/com/gotcha/service/WakeWordGate.ktindex 723627f..16694b3 100644--- a/app/src/main/java/com/gotcha/service/WakeWordGate.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordGate.kt@@ -45,13 +45,26 @@ internal class WakeWordGate(private val alwaysOpen: Boolean = false) {private val recentRms = FloatArray(FLOOR_WINDOW)++ /** Reused scratch for the percentile sort, so the floor costs no allocation. */+ private val floorScratch = FloatArray(FLOOR_WINDOW)private var recentCount = 0private var recentStart = 0private var framesSinceEnergy = 0-- /** The level a frame must exceed to open the gate, in dBFS. */- val thresholdDb: Float- get() = maxOf(minThresholdDb, noiseFloorEstimate + marginDb)+ private var framesSinceFloorRefresh = 0++ /**+ * The level a frame must exceed to open the gate, in dBFS.+ *+ * Cached rather than recomputed per frame. The floor is a percentile over+ * four seconds of history — it moves slowly by construction, so refreshing+ * it every [FLOOR_REFRESH_FRAMES] tracks it just as well while keeping the+ * sort off a path that runs 12.5 times a second for as long as the phone is+ * on. Recomputing it per frame made the gate the only remaining per-frame+ * allocation in the listener.+ */+ var thresholdDb: Float = maxOf(minThresholdDb, INITIAL_NOISE_FLOOR_DB + marginDb)+ private set/** True while the floor window is still filling; the gate is forced open. */val priming: Boolean@@ -67,7 +80,17 @@ internal class WakeWordGate(recentRms[recentStart] = frameRmsDbrecentStart = (recentStart + 1) % FLOOR_WINDOW- if (recentCount < FLOOR_WINDOW) recentCount+++ val wasPriming = recentCount < FLOOR_WINDOW+ if (wasPriming) recentCount++++ // Refresh on the frame that completes priming — the first real floor is+ // worth having immediately — and periodically after that.+ framesSinceFloorRefresh+++ if ((wasPriming && recentCount == FLOOR_WINDOW) ||+ framesSinceFloorRefresh >= FLOOR_REFRESH_FRAMES+ ) {+ refreshThreshold()+ }if (open) {framesSinceEnergy = 0@@ -83,15 +106,24 @@ internal class WakeWordGate(recentCount = 0recentStart = 0framesSinceEnergy = 0+ framesSinceFloorRefresh = 0+ recentRms.fill(0f)+ thresholdDb = maxOf(minThresholdDb, INITIAL_NOISE_FLOOR_DB + marginDb)}- private val noiseFloorEstimate: Float- get() {- if (recentCount < FLOOR_WINDOW) return INITIAL_NOISE_FLOOR_DB- val sorted = recentRms.copyOf(FLOOR_WINDOW).apply { sort() }- val index = (sorted.size * FLOOR_QUANTILE).toInt().coerceIn(0, sorted.lastIndex)- return sorted[index]- }+ private fun refreshThreshold() {+ framesSinceFloorRefresh = 0+ thresholdDb = maxOf(minThresholdDb, noiseFloorEstimate() + marginDb)+ }++ private fun noiseFloorEstimate(): Float {+ if (recentCount < FLOOR_WINDOW) return INITIAL_NOISE_FLOOR_DB+ recentRms.copyInto(floorScratch)+ floorScratch.sort()+ val index = (floorScratch.size * FLOOR_QUANTILE).toInt()+ .coerceIn(0, floorScratch.lastIndex)+ return floorScratch[index]+ }companion object {/**@@ -127,6 +159,9 @@ internal class WakeWordGate(private const val FLOOR_QUANTILE = 0.2f+ /** ~1 s. The floor spans 4 s of history, so this loses nothing. */+ private const val FLOOR_REFRESH_FRAMES = 12+/** Level reported for digital silence, where the log is undefined. */const val SILENT_DB = -120fdiff --git a/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt b/app/src/test/java/com/gotcha/service/WakeWordGateTest.ktindex 5e2d883..027517b 100644--- a/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt+++ b/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt@@ -129,6 +129,30 @@ class WakeWordGateTest {assertTrue(gate.onLevel(-15f))}+ @Test+ fun theThresholdKeepsTrackingTheRoomAfterPriming() {+ val gate = WakeWordGate()+ gate.prime(levelDb = -70f)+ val quietThreshold = gate.thresholdDb++ // The floor is cached and refreshed periodically rather than recomputed+ // per frame. A cache that never refreshed would leave the gate judging+ // a loud room against a silent one's threshold forever, so pin that it+ // still moves — one refresh window is well inside 60 frames.+ repeat(60) { gate.onLevel(-30f) }+ assertTrue(+ "threshold froze at $quietThreshold after the room got louder (now ${gate.thresholdDb})",+ gate.thresholdDb > quietThreshold+ )++ // And back down again when the room goes quiet.+ repeat(60) { gate.onLevel(-70f) }+ assertTrue(+ "threshold stayed high (${gate.thresholdDb}) after the room went quiet",+ gate.thresholdDb < -50f+ )+ }+@Testfun rmsDb_isUnclampedAndTracksLevel() {val fullScale = ShortArray(160) { Short.MAX_VALUE }