Skip to content

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): gate the embedding backbone behind an energy check

Durganshu Mishra5b18aa46233c
diff --git a/app/src/androidTest/java/com/gotcha/service/OnnxWakeWordPipelineGateTest.kt b/app/src/androidTest/java/com/gotcha/service/OnnxWakeWordPipelineGateTest.kt
new file mode 100644
index 0000000..c2ffd2e
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/service/OnnxWakeWordPipelineGateTest.kt
@@ -0,0 +1,200 @@
+package com.gotcha.service
+
+import ai.onnxruntime.OrtEnvironment
+import ai.onnxruntime.OrtSession
+import android.content.Context
+import android.util.Log
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import kotlin.math.PI
+import kotlin.math.sin
+import kotlin.random.Random
+
+/**
+ * The regression guard for the energy gate added in issue #37.
+ *
+ * The acceptance criterion for that work is "no drop in detection rate", which
+ * is normally only checkable by saying "Hey Gotcha" at a phone and trusting the
+ * result. The gate is built so it can be checked properly instead: because the
+ * mel front-end keeps running while the gate is shut, every embedding the gate
+ * skipped can be rebuilt from the mel rows that are still in the buffer. So a
+ * gated pipeline and an ungated one must emit **identical** classifier scores
+ * for every frame the gate let through — not similar, identical.
+ *
+ * If that holds, gating provably cannot change what the matcher sees, and so
+ * cannot change the detection rate. If someone later breaks the replay path,
+ * these tests fail rather than the wake word quietly getting worse in rooms
+ * that happen to be quiet.
+ *
+ * ```
+ * ./gradlew :app:connectedDebugAndroidTest \
+ * -Pandroid.testInstrumentationRunnerArguments.class=com.gotcha.service.OnnxWakeWordPipelineGateTest
+ * ```
+ */
+@RunWith(AndroidJUnit4::class)
+class OnnxWakeWordPipelineGateTest {
+
+ private val context: Context get() = ApplicationProvider.getApplicationContext()
+
+ @Test
+ fun gatedAndUngatedPipelines_produceIdenticalScores() {
+ val clip = buildClip()
+ val gated = run(clip, WakeWordGate())
+ val ungated = run(clip, WakeWordGate.alwaysOpen())
+
+ Log.i(
+ TAG,
+ "frames=${clip.size} scored: gated=${gated.scores.size} " +
+ "ungated=${ungated.scores.size} gatedOut=${gated.gatedFrames}"
+ )
+
+ assertTrue(
+ "the gate never closed, so this proved nothing — check the clip's silence level",
+ gated.gatedFrames > 0
+ )
+ assertTrue("the gate never opened", gated.scores.isNotEmpty())
+ assertEquals(
+ "the ungated baseline should score every frame it can",
+ ungated.scores.size,
+ gated.scores.size + gated.gatedFrames
+ )
+
+ for ((frame, score) in gated.scores) {
+ val baseline = ungated.scores[frame]
+ ?: error("ungated run produced no score for frame $frame")
+ assertEquals(
+ "frame $frame diverged after the gate re-armed",
+ baseline,
+ score,
+ 0f
+ )
+ }
+ }
+
+ /**
+ * The case the replay exists for: the gate shuts during a long silence and
+ * has to re-arm on the first frame of the phrase. Every score from the
+ * re-arm onwards has to match the ungated baseline, because those are the
+ * frames a detection would actually come from.
+ */
+ @Test
+ fun scoresImmediatelyAfterReArming_matchTheUngatedBaseline() {
+ val clip = buildClip()
+ val gated = run(clip, WakeWordGate())
+ val ungated = run(clip, WakeWordGate.alwaysOpen())
+
+ // The first scored frame after a gap in the scored-frame sequence is a
+ // re-arm. Those are the frames the replay path is responsible for.
+ val scoredFrames = gated.scores.keys.sorted()
+ val reArms = scoredFrames.filterIndexed { index, frame ->
+ index > 0 && frame != scoredFrames[index - 1] + 1
+ }
+ Log.i(TAG, "re-arm frames: $reArms")
+ assertTrue("no re-arm happened in this clip", reArms.isNotEmpty())
+
+ for (frame in reArms) {
+ // The re-arm frame plus the rest of the classifier window after it.
+ for (offset in 0 until OnnxWakeWordPipeline.CLASSIFIER_FRAMES) {
+ val score = gated.scores[frame + offset] ?: continue
+ assertEquals(
+ "frame ${frame + offset} (re-arm at $frame + $offset) diverged",
+ ungated.scores.getValue(frame + offset),
+ score,
+ 0f
+ )
+ }
+ }
+ }
+
+ private fun run(clip: List<ShortArray>, gate: WakeWordGate): Recorder {
+ val env = OrtEnvironment.getEnvironment()
+ val recorder = Recorder()
+ val mel = loadSession(env, "melspectrogram.onnx")
+ val embedding = loadSession(env, "embedding_model.onnx")
+ val classifier = loadSession(env, WakeWordDetector.CLASSIFIER_MODEL)
+ try {
+ val pipeline = OnnxWakeWordPipeline(
+ env = env,
+ melSession = mel,
+ embeddingSession = embedding,
+ classifierSession = classifier,
+ matcher = WakeWordMatcher(WakeWordMatcher.DEFAULT_SENSITIVITY),
+ gate = gate,
+ probe = recorder
+ )
+ clip.forEach { frame -> pipeline.feed(frame, frame.size) }
+ } finally {
+ classifier.close()
+ embedding.close()
+ mel.close()
+ }
+ return recorder
+ }
+
+ private fun loadSession(env: OrtEnvironment, name: String): OrtSession {
+ val bytes = context.assets
+ .open("${WakeWordDetector.MODEL_ASSET_DIR}/$name")
+ .use { it.readBytes() }
+ return OrtSession.SessionOptions().use { env.createSession(bytes, it) }
+ }
+
+ /**
+ * Room tone, then two bursts of sound separated by silences long enough to
+ * outlast the gate's hangover. Parity is a property of the plumbing, not of
+ * the audio, so this does not need to be a real "Hey Gotcha" recording — it
+ * needs to make the gate open, close, and re-arm, which it does.
+ */
+ private fun buildClip(): List<ShortArray> = buildList {
+ // The first stretch has to outlast both the 50-frame floor priming and
+ // the 38-frame hangover before the gate can close at all.
+ addAll(frames(count = 100, amplitude = QUIET))
+ addAll(frames(count = 20, amplitude = LOUD))
+ addAll(frames(count = 70, amplitude = QUIET))
+ addAll(frames(count = 25, amplitude = LOUD))
+ addAll(frames(count = 60, amplitude = QUIET))
+ }
+
+ private fun frames(count: Int, amplitude: Int): List<ShortArray> =
+ List(count) { index ->
+ val random = Random(index * 31 + amplitude)
+ ShortArray(OnnxWakeWordPipeline.FRAME_SIZE) { i ->
+ val tone = sin(2.0 * PI * 220.0 * i / OnnxWakeWordPipeline.SAMPLE_RATE)
+ ((tone * 0.6 + random.nextDouble(-0.4, 0.4)) * amplitude).toInt().toShort()
+ }
+ }
+
+ private class Recorder : OnnxWakeWordPipeline.PipelineProbe {
+ /** Frame index → classifier score. */
+ val scores = mutableMapOf<Int, Float>()
+ var gatedFrames = 0
+ private set
+
+ // computeMel() runs on every frame, gated or not, and emits rows every
+ // time — so this fires exactly once per frame and doubles as the clock.
+ private var frames = -1
+
+ override fun onMelRows(rows: Int) {
+ frames++
+ }
+
+ override fun onGated() {
+ gatedFrames++
+ }
+
+ override fun onScore(score: Float) {
+ scores[frames] = score
+ }
+ }
+
+ private companion object {
+ const val TAG = "WakeWordGateParity"
+
+ /** Below the gate's −60 dBFS floor once the noise floor has been learned. */
+ const val QUIET = 12
+ const val LOUD = 6000
+ }
+}
diff --git a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt
index eb76a42..2fe0586 100644
--- a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt
+++ b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt
@@ -22,6 +22,25 @@ import java.nio.FloatBuffer
* The first [WARMUP_FRAMES] scored frames are ignored so the feature buffers
* fill up before anything can be detected.
*
+ * ## Energy gating (issue #37)
+ *
+ * Steps 1 and 2 above are ~8% of a frame's cost; step 3 is the rest. So the
+ * mel front-end runs on every frame and [WakeWordGate] decides whether to pay
+ * for the embedding backbone. When the room is quiet the pipeline is doing
+ * mel + an RMS, and nothing else.
+ *
+ * Re-arming is **exact**, not approximate. Because `melBuffer` kept filling
+ * while the gate was shut, [replayGatedEmbeddings] can rebuild the skipped
+ * embeddings from the real audio that produced them, so the classifier sees
+ * bit-for-bit the window an ungated run would have handed it. That is what
+ * `OnnxWakeWordPipelineGateTest` asserts, and it is why gating cannot cost a
+ * detection — including when the gate closes mid-phrase.
+ *
+ * The one thing gating trades away is CPU in a *choppy* room: each re-arm
+ * replays up to 15 embeddings, which only pays for itself if the quiet gap was
+ * longer than ~1.3 s. `WakeWordGate`'s hangover is what keeps gaps that short
+ * from re-arming at all.
+ *
* The hot path avoids per-frame GC pressure: the raw PCM ring buffer, the
* combined feed buffer, the frame buffer, and the mel window are all
* pre-allocated once and reused. The per-row mel arrays, `toList()` snapshots,
@@ -36,6 +55,7 @@ internal class OnnxWakeWordPipeline(
private val embeddingSession: OrtSession,
private val classifierSession: OrtSession,
private val matcher: WakeWordMatcher,
+ private val gate: WakeWordGate = WakeWordGate(),
private val probe: PipelineProbe? = null
) {
/**
@@ -49,6 +69,12 @@ internal class OnnxWakeWordPipeline(
/** Number of mel rows one `melspectrogram.onnx` run emitted. */
fun onMelRows(rows: Int) {}
+ /** A frame whose embedding stage was skipped by [WakeWordGate]. */
+ fun onGated() {}
+
+ /** The classifier's output for a frame that made it past the gate. */
+ fun onScore(score: Float) {}
+
enum class Stage { MEL, EMBEDDING, CLASSIFY }
}
@@ -59,11 +85,13 @@ internal class OnnxWakeWordPipeline(
/**
* Scratch buffer that holds the current feed's samples plus whatever was
- * carried over from the previous feed. Bounded by
- * [MEL_WINDOW] + [FRAME_SIZE], which is the worst case when [feed] is
- * called with a full [FRAME_SIZE] shortly after a remainder was kept.
+ * carried over from the previous feed. [feed] takes whatever the caller's
+ * `AudioRecord.read` returned — several frames at a time, since the reads
+ * were batched to cut wakeups — so this grows to fit the largest feed seen
+ * and is then reused. The carried-over remainder is always shorter than
+ * [FRAME_SIZE].
*/
- private val combined = ShortArray(MEL_WINDOW + FRAME_SIZE)
+ private var combined = ShortArray(MEL_WINDOW + FRAME_SIZE)
private var combinedLength = 0
/** Reused destination for each extracted 80 ms frame. */
@@ -75,6 +103,20 @@ internal class OnnxWakeWordPipeline(
private val melBuffer = ArrayDeque<FloatArray>()
private val featureBuffer = ArrayDeque<FloatArray>()
+ /**
+ * Rows appended to [melBuffer] by each of the last [CLASSIFIER_FRAMES]
+ * frames. Re-arming after the gate closes has to rebuild the embeddings for
+ * a run of earlier frames, and that means knowing where each of those
+ * frames ended in [melBuffer]. Measured to be a flat 8 rows per frame, but
+ * recording it beats hardcoding a number the bundled graph could change.
+ */
+ private val rowCounts = IntArray(CLASSIFIER_FRAMES)
+ private var rowCountHead = 0
+ private var rowCountFilled = 0
+
+ /** Consecutive frames whose embedding was skipped because the gate was shut. */
+ private var gatedFrames = 0
+
private var remainder = ShortArray(0)
private var scoredFrames = 0
@@ -105,9 +147,13 @@ internal class OnnxWakeWordPipeline(
combinedLength = 0
remainder = ShortArray(0)
scoredFrames = 0
+ rowCountHead = 0
+ rowCountFilled = 0
+ gatedFrames = 0
melBuffer.clear()
featureBuffer.clear()
matcher.reset()
+ gate.reset()
prefillFeatures()
}
@@ -116,6 +162,8 @@ internal class OnnxWakeWordPipeline(
var detected = false
// Concatenate remainder + new samples into the reusable combined buffer.
+ val needed = remainder.size + count
+ if (combined.size < needed) combined = ShortArray(needed)
combinedLength = 0
if (remainder.isNotEmpty()) {
System.arraycopy(remainder, 0, combined, 0, remainder.size)
@@ -151,9 +199,28 @@ internal class OnnxWakeWordPipeline(
if (rawCount < MEL_WINDOW) rawCount++
}
+ val open = gate.onFrame(frame, FRAME_SIZE)
+
+ // The mel front-end runs unconditionally even while the gate is shut.
+ // It is ~8% of the chain's cost, and keeping it warm is what makes
+ // re-arming exact: every mel row the embedding stage skipped is still
+ // in melBuffer, so the classifier window can be rebuilt from real audio
+ // instead of from whatever silence-shaped stand-in was available.
if (!timed(PipelineProbe.Stage.MEL) { computeMel() }) return false
+
+ if (!open) {
+ if (gatedFrames < CLASSIFIER_FRAMES) gatedFrames++
+ probe?.onGated()
+ return false
+ }
+ if (gatedFrames > 0) {
+ replayGatedEmbeddings(gatedFrames)
+ gatedFrames = 0
+ }
+
if (!timed(PipelineProbe.Stage.EMBEDDING) { computeEmbedding() }) return false
val score = timed(PipelineProbe.Stage.CLASSIFY) { classify() } ?: return false
+ probe?.onScore(score)
scoredFrames++
if (scoredFrames <= WARMUP_FRAMES) return false
@@ -194,16 +261,38 @@ internal class OnnxWakeWordPipeline(
melBuffer.addLast(FloatArray(MEL_BINS) { row[it] / 10f + 2f })
}
while (melBuffer.size > MEL_BUFFER_MAX) melBuffer.removeFirst()
+ recordRowCount(rows.size)
return true
}
- private fun computeEmbedding(): Boolean {
- if (melBuffer.size < MEL_EMBEDDING_WINDOW) return false
- val mels = melBuffer.toList()
+ /**
+ * Rebuilds the embeddings for the [missedFrames] frames the gate skipped,
+ * oldest first, so the classifier sees the same 16-embedding window it
+ * would have seen had the gate never closed.
+ *
+ * Only the last [CLASSIFIER_FRAMES] − 1 matter: anything older has already
+ * fallen out of the classifier's window, and the entries still sitting in
+ * [featureBuffer] from before the gate closed are exactly the ones an
+ * ungated run would have there.
+ */
+ private fun replayGatedEmbeddings(missedFrames: Int) {
+ val replay = minOf(missedFrames, CLASSIFIER_FRAMES - 1, rowCountFilled - 1)
+ for (framesBack in replay downTo 1) {
+ timed(PipelineProbe.Stage.EMBEDDING) { computeEmbedding(rowsInLast(framesBack)) }
+ }
+ }
+
+ /**
+ * Runs the embedding model over the 76 mel rows ending [rowsBack] rows
+ * before the end of [melBuffer]. [rowsBack] of 0 is the current frame.
+ */
+ private fun computeEmbedding(rowsBack: Int = 0): Boolean {
+ val end = melBuffer.size - rowsBack
+ val base = end - MEL_EMBEDDING_WINDOW
+ if (base < 0) return false
val x = Array(1) { Array(MEL_EMBEDDING_WINDOW) { Array(MEL_BINS) { FloatArray(1) } } }
- val base = mels.size - MEL_EMBEDDING_WINDOW
for (k in 0 until MEL_EMBEDDING_WINDOW) {
- val row = mels[base + k]
+ val row = melBuffer[base + k]
for (w in 0 until MEL_BINS) x[0][k][w][0] = row[w]
}
@@ -222,10 +311,9 @@ internal class OnnxWakeWordPipeline(
private fun classify(): Float? {
if (featureBuffer.size < CLASSIFIER_FRAMES) return null
- val features = featureBuffer.toList()
val x = Array(1) { Array(CLASSIFIER_FRAMES) { FloatArray(FEATURE_DIM) } }
- val base = features.size - CLASSIFIER_FRAMES
- for (k in 0 until CLASSIFIER_FRAMES) x[0][k] = features[base + k]
+ val base = featureBuffer.size - CLASSIFIER_FRAMES
+ for (k in 0 until CLASSIFIER_FRAMES) x[0][k] = featureBuffer[base + k]
val tensor = OnnxTensor.createTensor(env, x)
return try {
@@ -237,6 +325,21 @@ internal class OnnxWakeWordPipeline(
}
}
+ private fun recordRowCount(rows: Int) {
+ rowCounts[rowCountHead] = rows
+ rowCountHead = (rowCountHead + 1) % CLASSIFIER_FRAMES
+ if (rowCountFilled < CLASSIFIER_FRAMES) rowCountFilled++
+ }
+
+ /** Rows appended by the most recent [frames] frames, current frame included. */
+ private fun rowsInLast(frames: Int): Int {
+ var total = 0
+ for (k in 1..frames) {
+ total += rowCounts[(rowCountHead - k + CLASSIFIER_FRAMES) % CLASSIFIER_FRAMES]
+ }
+ return total
+ }
+
/** Times [body] only when a [probe] is attached, so production stays free of the clock reads. */
private inline fun <T> timed(stage: PipelineProbe.Stage, body: () -> T): T {
val active = probe ?: return body()
@@ -261,7 +364,15 @@ internal class OnnxWakeWordPipeline(
const val FEATURE_DIM = 96
const val CLASSIFIER_FRAMES = 16
private const val WARMUP_FRAMES = 5
- private const val MEL_BUFFER_MAX = 120
+
+ /**
+ * Mel rows kept around. Re-arming after the gate closes has to rebuild
+ * the embeddings for up to [CLASSIFIER_FRAMES] − 1 earlier frames, and
+ * the oldest of those still needs a full [MEL_EMBEDDING_WINDOW] of rows
+ * behind it: 76 + 15 × 8 = 196 at the measured 8 rows per frame. 240
+ * leaves headroom without mattering (240 × 32 floats ≈ 30 KB).
+ */
+ private const val MEL_BUFFER_MAX = 240
private const val FEATURE_BUFFER_MAX = 32
}
}
diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
index a6e84c3..812a388 100644
--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
@@ -117,11 +117,15 @@ class WakeWordDetector(
createdMel = loadSession(env, "$modelAssetDir/melspectrogram.onnx")
createdEmbedding = loadSession(env, "$modelAssetDir/embedding_model.onnx")
createdClassifier = loadSession(env, "$modelAssetDir/$classifierModel")
+ // 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
+ // memory is irrelevant (~40 KB); the wakeup rate is not.
val bufferSize = AudioRecord.getMinBufferSize(
OnnxWakeWordPipeline.SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
- ).coerceAtLeast(OnnxWakeWordPipeline.FRAME_SIZE * 2)
+ ).coerceAtLeast(OnnxWakeWordPipeline.FRAME_SIZE * 2 * BUFFER_FRAMES)
createdRecorder = AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
OnnxWakeWordPipeline.SAMPLE_RATE,
@@ -173,7 +177,10 @@ class WakeWordDetector(
localEmbedding: OrtSession,
localClassifier: OrtSession
) {
- val frame = ShortArray(OnnxWakeWordPipeline.FRAME_SIZE)
+ // Read several 80 ms frames per wakeup rather than one. The pipeline
+ // splits whatever it is handed back into frames, so this changes only
+ // how often the CPU is woken: 3.1 times a second instead of 12.5.
+ val block = ShortArray(OnnxWakeWordPipeline.FRAME_SIZE * READ_FRAMES)
val pipeline = OnnxWakeWordPipeline(
env = env,
melSession = localMel,
@@ -184,19 +191,25 @@ class WakeWordDetector(
try {
localRecorder.startRecording()
while (running.get()) {
- val count = localRecorder.read(frame, 0, frame.size)
+ val count = localRecorder.read(block, 0, block.size)
if (count < 0) {
if (running.get()) throw IOException("AudioRecord read failed: $count")
return
}
- if (count == 0) continue
+ // A blocking read should never come back empty, but returning
+ // to the top on 0 would spin the loop at full tilt if one ever
+ // did. Wait out a frame instead.
+ if (count == 0) {
+ Thread.sleep(FRAME_DURATION_MS)
+ continue
+ }
var detected = false
synchronized(stateLock) {
if (!running.get() || recorder !== localRecorder || generation != this.generation) {
return
}
- if (pipeline.feed(frame, count)) {
+ if (pipeline.feed(block, count)) {
detected = true
running.set(false)
}
@@ -238,5 +251,17 @@ class WakeWordDetector(
const val MODEL_ASSET_DIR = "openwakeword"
const val CLASSIFIER_MODEL = "hey_gotcha.onnx"
private const val TAG = "WakeWordDetector"
+
+ /**
+ * 80 ms frames drained per `AudioRecord.read`. Four cuts the wakeup
+ * rate by 4× and costs up to 320 ms of extra trigger latency, on top of
+ * the matcher's existing 160 ms patience.
+ */
+ private const val READ_FRAMES = 4
+
+ /** ~1.3 s of audio: enough headroom that a slow frame cannot overrun the buffer. */
+ private const val BUFFER_FRAMES = 16
+
+ private const val FRAME_DURATION_MS = 80L
}
}
diff --git a/app/src/main/java/com/gotcha/service/WakeWordGate.kt b/app/src/main/java/com/gotcha/service/WakeWordGate.kt
new file mode 100644
index 0000000..723627f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/WakeWordGate.kt
@@ -0,0 +1,149 @@
+package com.gotcha.service
+
+import kotlin.math.log10
+import kotlin.math.sqrt
+
+/**
+ * Cheap energy gate in front of the wake-word embedding stage (issue #37).
+ *
+ * The listener runs 12.5 frames a second forever, and a measured ~85% of each
+ * frame's cost is the embedding backbone. Almost every real-world frame is
+ * silence, so the fix is to only pay for that backbone when there is something
+ * to hear. This class answers exactly one question per 80 ms frame — "is there
+ * energy above the room's noise floor?" — for a few microseconds of RMS.
+ *
+ * It deliberately does **not** reuse [com.gotcha.audio.SilenceDetector]:
+ *
+ * - That is a conversational state machine (accept-streak, "user stopped
+ * talking", "user never spoke") built for the STT turn. Its `Decision` values
+ * have no meaning per frame.
+ * - Its `rmsDb` clamps its return at −50 dBFS, so a gate built on it has no
+ * resolution below −50 and cannot be tuned for a quiet room. [rmsDb] here is
+ * unclamped.
+ *
+ * Behaviour:
+ *
+ * - The noise floor is a low percentile over the last [FLOOR_WINDOW] frames, so
+ * a loud room raises the bar instead of holding the gate permanently open.
+ * Unlike `SilenceDetector` the floor keeps updating while the gate is open:
+ * re-arming is exact (see [OnnxWakeWordPipeline]), so a gate that closes
+ * mid-phrase costs a little CPU but never costs a detection, and that makes
+ * "never let the floor go stale" the safer trade.
+ * - A **single** frame above the threshold opens the gate — no accept-streak.
+ * A spurious open costs milliseconds; a missed onset costs a detection.
+ * - Once open it stays open for [hangoverFrames] after energy drops. This is
+ * what keeps an intermittently noisy room from flapping the gate: each
+ * re-arm replays the classifier window, and that replay only pays for itself
+ * if the quiet gap was longer than ~1.3 s.
+ * - It starts open and stays open until the floor window is primed, so the
+ * first seconds after start can never be gated against an unlearned floor.
+ */
+internal class WakeWordGate(
+ private val marginDb: Float = SPEECH_MARGIN_DB,
+ private val minThresholdDb: Float = MIN_THRESHOLD_DB,
+ private val hangoverFrames: Int = HANGOVER_FRAMES,
+ private val alwaysOpen: Boolean = false
+) {
+ private val recentRms = FloatArray(FLOOR_WINDOW)
+ private var recentCount = 0
+ private var recentStart = 0
+ private var framesSinceEnergy = 0
+
+ /** The level a frame must exceed to open the gate, in dBFS. */
+ val thresholdDb: Float
+ get() = maxOf(minThresholdDb, noiseFloorEstimate + marginDb)
+
+ /** True while the floor window is still filling; the gate is forced open. */
+ val priming: Boolean
+ get() = recentCount < FLOOR_WINDOW
+
+ /** Returns true when [frame] should be run through the embedding stage. */
+ fun onFrame(frame: ShortArray, count: Int): Boolean = onLevel(rmsDb(frame, count))
+
+ /** [onFrame] split out from the PCM, so tests can drive levels directly. */
+ fun onLevel(frameRmsDb: Float): Boolean {
+ if (alwaysOpen) return true
+ val open = priming || frameRmsDb > thresholdDb
+
+ recentRms[recentStart] = frameRmsDb
+ recentStart = (recentStart + 1) % FLOOR_WINDOW
+ if (recentCount < FLOOR_WINDOW) recentCount++
+
+ if (open) {
+ framesSinceEnergy = 0
+ return true
+ }
+ // Saturate rather than overflow: this counter runs for as long as the
+ // room is quiet, which on a 24/7 listener is a very long time.
+ if (framesSinceEnergy <= hangoverFrames) framesSinceEnergy++
+ return framesSinceEnergy <= hangoverFrames
+ }
+
+ fun reset() {
+ recentCount = 0
+ recentStart = 0
+ framesSinceEnergy = 0
+ }
+
+ 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]
+ }
+
+ companion object {
+ /**
+ * A gate that never closes — i.e. the pre-#37 behaviour, where every
+ * frame paid for the embedding backbone. The parity tests run one
+ * pipeline behind this and one behind a real gate, and require the two
+ * to produce identical classifier scores.
+ */
+ fun alwaysOpen(): WakeWordGate = WakeWordGate(alwaysOpen = true)
+
+ /** How far above the noise floor a frame has to be to count as sound. */
+ private const val SPEECH_MARGIN_DB = 6f
+
+ /**
+ * Absolute lower bound on the threshold. Well below
+ * `SilenceDetector.ABSOLUTE_FLOOR_DB` (−50) on purpose: a quiet bedroom
+ * at night sits below −50 dBFS, and a gate that cannot be set quieter
+ * than the room never closes.
+ */
+ private const val MIN_THRESHOLD_DB = -60f
+
+ private const val INITIAL_NOISE_FLOOR_DB = -70f
+
+ /**
+ * ~3 s. Long enough that a pause inside a sentence does not re-arm the
+ * pipeline, which matters because each re-arm costs a replay of the
+ * 16-frame classifier window.
+ */
+ private const val HANGOVER_FRAMES = 38
+
+ /** ~4 s of frames. Long enough that continuous speech cannot lift the floor to its own level. */
+ private const val FLOOR_WINDOW = 50
+
+ private const val FLOOR_QUANTILE = 0.2f
+
+ /** Level reported for digital silence, where the log is undefined. */
+ const val SILENT_DB = -120f
+
+ /**
+ * RMS of [count] 16-bit PCM samples in dBFS. Unlike
+ * `SilenceDetector.rmsDb` this is **not** clamped at −50 dBFS.
+ */
+ fun rmsDb(samples: ShortArray, count: Int): Float {
+ if (count <= 0) return SILENT_DB
+ var sum = 0L
+ for (i in 0 until count) {
+ val sample = samples[i].toInt()
+ sum += sample.toLong() * sample
+ }
+ val rms = sqrt(sum.toDouble() / count)
+ if (rms <= 0.0) return SILENT_DB
+ return maxOf(20.0 * log10(rms / 32768.0), SILENT_DB.toDouble()).toFloat()
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt b/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt
new file mode 100644
index 0000000..5e2d883
--- /dev/null
+++ b/app/src/test/java/com/gotcha/service/WakeWordGateTest.kt
@@ -0,0 +1,156 @@
+package com.gotcha.service
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * The gate is the one piece of the battery work that can be tested off-device:
+ * it is pure arithmetic over frame levels, with no ONNX and no Android.
+ */
+class WakeWordGateTest {
+
+ /** Enough frames to prime the floor window; the gate is forced open until then. */
+ private fun WakeWordGate.prime(levelDb: Float = QUIET_ROOM_DB) {
+ repeat(PRIMING_FRAMES) { onLevel(levelDb) }
+ }
+
+ @Test
+ fun beforeTheFloorIsLearned_theGateStaysOpen() {
+ val gate = WakeWordGate()
+ // Digital silence, the most gate-able input there is — but with no
+ // learned floor, closing would be a guess, and a wrong guess drops the
+ // first seconds of listening.
+ repeat(PRIMING_FRAMES) { assertTrue(gate.onLevel(WakeWordGate.SILENT_DB)) }
+ assertFalse(gate.priming)
+ }
+
+ @Test
+ fun quietRoom_closesTheGateOnceTheHangoverExpires() {
+ val gate = WakeWordGate()
+ gate.prime()
+
+ // The hangover has to run out first — it is armed by the priming phase.
+ repeat(HANGOVER_FRAMES) { assertTrue(gate.onLevel(QUIET_ROOM_DB)) }
+ assertFalse(gate.onLevel(QUIET_ROOM_DB))
+ assertFalse(gate.onLevel(QUIET_ROOM_DB))
+ }
+
+ @Test
+ fun quietRoomFloor_sitsWellBelowSilenceDetectorsClamp() {
+ val gate = WakeWordGate()
+ gate.prime(levelDb = -72f)
+
+ // SilenceDetector.rmsDb bottoms out at -50 dBFS, so a gate built on it
+ // could never close in a room this quiet. This one can.
+ assertTrue(
+ "threshold ${gate.thresholdDb} should be below -50 dBFS in a quiet room",
+ gate.thresholdDb < -50f
+ )
+ repeat(HANGOVER_FRAMES + 1) { gate.onLevel(-72f) }
+ assertFalse(gate.onLevel(-72f))
+ assertTrue(gate.onLevel(-40f))
+ }
+
+ @Test
+ fun aSingleLoudFrame_opensTheGateImmediately() {
+ val gate = WakeWordGate()
+ gate.prime()
+ repeat(HANGOVER_FRAMES + 1) { gate.onLevel(QUIET_ROOM_DB) }
+ assertFalse(gate.onLevel(QUIET_ROOM_DB))
+
+ // No accept-streak, deliberately: a spurious open costs milliseconds of
+ // CPU, a missed onset costs the user their wake word.
+ assertTrue(gate.onLevel(SPEECH_DB))
+ }
+
+ @Test
+ fun afterSpeechStops_theGateHoldsOpenForTheHangover() {
+ val gate = WakeWordGate()
+ gate.prime()
+ assertTrue(gate.onLevel(SPEECH_DB))
+
+ // A pause inside a sentence must not re-arm the pipeline: each re-arm
+ // replays the classifier window.
+ repeat(HANGOVER_FRAMES) { index ->
+ assertTrue("closed $index frames into the hangover", gate.onLevel(QUIET_ROOM_DB))
+ }
+ assertFalse(gate.onLevel(QUIET_ROOM_DB))
+ }
+
+ @Test
+ fun aLoudRoom_raisesTheThresholdWithIt() {
+ val quiet = WakeWordGate().apply { prime(levelDb = -70f) }
+ val loud = WakeWordGate().apply { prime(levelDb = -30f) }
+
+ assertTrue(
+ "a loud room should demand a louder frame (${quiet.thresholdDb} vs ${loud.thresholdDb})",
+ loud.thresholdDb > quiet.thresholdDb
+ )
+ // Ambient chatter at the room's own level is not an onset.
+ repeat(HANGOVER_FRAMES + 1) { loud.onLevel(-30f) }
+ assertFalse(loud.onLevel(-30f))
+ }
+
+ @Test
+ fun sustainedSpeech_cannotDragTheFloorUpToItsOwnLevel() {
+ val gate = WakeWordGate()
+ gate.prime(levelDb = -70f)
+
+ // Ten seconds of talking. Real speech is not a flat level — syllables,
+ // word gaps and breaths put a good fraction of frames far below the
+ // peaks, and the floor is a low percentile precisely so it tracks those
+ // dips rather than the speech itself.
+ val syllable = listOf(SPEECH_DB, -30f, -58f, SPEECH_DB, -34f, -62f, -40f, SPEECH_DB)
+ repeat(125) { index -> gate.onLevel(syllable[index % syllable.size]) }
+
+ assertTrue(
+ "threshold ${gate.thresholdDb} climbed to speech level",
+ gate.thresholdDb < SPEECH_DB
+ )
+ assertTrue(gate.onLevel(SPEECH_DB))
+ }
+
+ @Test
+ fun anUnbrokenConstantTone_becomesTheFloorAndIsGatedOut() {
+ val gate = WakeWordGate()
+ gate.prime(levelDb = -70f)
+
+ // A fan, a hum, a held note: once it has filled the whole floor window
+ // it *is* the room's ambient level, and gating it out is the point.
+ // Safe to do because re-arming replays the classifier window from
+ // retained mel rows, so even if this were speech, closing the gate
+ // costs CPU on the next onset and never costs a detection.
+ repeat(PRIMING_FRAMES + HANGOVER_FRAMES + 1) { gate.onLevel(-25f) }
+ assertFalse(gate.onLevel(-25f))
+
+ // Anything that rises above the new ambient still gets through.
+ assertTrue(gate.onLevel(-15f))
+ }
+
+ @Test
+ fun rmsDb_isUnclampedAndTracksLevel() {
+ val fullScale = ShortArray(160) { Short.MAX_VALUE }
+ assertEquals(0f, WakeWordGate.rmsDb(fullScale, fullScale.size), 0.1f)
+
+ assertEquals(WakeWordGate.SILENT_DB, WakeWordGate.rmsDb(ShortArray(160), 160), 0.001f)
+ assertEquals(WakeWordGate.SILENT_DB, WakeWordGate.rmsDb(fullScale, 0), 0.001f)
+
+ // The point of not reusing SilenceDetector.rmsDb: this keeps resolving
+ // below -50 dBFS instead of flattening out there.
+ val veryQuiet = ShortArray(160) { 20 }
+ val quieter = ShortArray(160) { 5 }
+ assertTrue(WakeWordGate.rmsDb(veryQuiet, 160) < -50f)
+ assertTrue(WakeWordGate.rmsDb(quieter, 160) < WakeWordGate.rmsDb(veryQuiet, 160))
+ }
+
+ private companion object {
+ /** Mirrors WakeWordGate.FLOOR_WINDOW / HANGOVER_FRAMES (both private). */
+ const val PRIMING_FRAMES = 50
+ const val HANGOVER_FRAMES = 38
+
+ const val QUIET_ROOM_DB = -70f
+ const val SPEECH_DB = -25f
+ }
+}