Modern Apps git

← Modern-Apps.git

speech: abort recognition on persistent microphone read errors

Commit
5cb14e3cedf419c6bb50758792151ac0ec5546ba
Author
Vayun Mathur <[email protected]>
When
2026-11-08 02:41 UTC (28 days ago)
Parents
b93817c
WhisperRecognitionService's recording loop never terminated when
AudioRecord.read kept failing. A failed read (n <= 0) returned to the
top of the loop without advancing the VAD's audio clock, so none of
the terminal conditions (no-speech timeout, 29 s cap, end silence)
could ever fire: the session spun at full speed forever, holding the
microphone open while the client waited for a callback that never
came. This is reachable in production whenever the mic dies or is
preempted mid-session (read then returns ERROR_INVALID_OPERATION /
ERROR_DEAD_OBJECT persistently).

Count consecutive failed reads in the session state and, after 50 in
a row, finish the session with ERROR_AUDIO instead of NO_MATCH so
clients learn the microphone failed rather than that the user said
nothing. A successful chunk resets the count, so transient glitches
are still tolerated. The loop's exit path gains a matching
errorReported guard so the audio-error report is not followed by a
spurious final transcription.

Extend FakeAudioRecordShadow so a queued negative value (other than
the BLOCK sentinel) is returned as-is as a read error, and add two
session tests: persistent errors report ERROR_AUDIO, and two
transient errors followed by speech still deliver the transcript.

User-visible effect: a dead mid-session microphone now ends
recognition promptly with an audio error instead of hanging the
requesting app indefinitely.

Verified with :speech:testDevUnitTest from the worktree root (11/11
WhisperRecognitionSessionTest, 4/4 MainActivityTest, whole module
green).

Diff

speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt b/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.ktindex 5add3c6380..e184b97a83 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt@@ -143,7 +143,7 @@ open class WhisperRecognitionService : RecognitionService() {             while (running && pumpOnce(chunk, state)) {                 // All work happens in pumpOnce; an empty body keeps the loop to one jump.             }-            if (cancelled || state.noMatchReported) return+            if (cancelled || state.noMatchReported || state.errorReported) return             finishAndTranscribe(state.speechStarted)         } @@ -153,7 +153,19 @@ open class WhisperRecognitionService : RecognitionService() {          */         private fun pumpOnce(chunk: ShortArray, state: VadState): Boolean {             val n = readChunk(chunk) ?: return false-            if (n <= 0) return true // a failed read that is not a cancel: keep draining+            if (n <= 0) {+                // A failed read advances no audio clock, so none of the VAD+                // timeouts can fire. Tolerate transient glitches but abort a+                // dead microphone instead of spinning forever holding it.+                state.consecutiveReadErrors+++                if (state.consecutiveReadErrors >= MAX_CONSECUTIVE_READ_ERRORS) {+                    finishError(SpeechRecognizer.ERROR_AUDIO)+                    state.errorReported = true+                    return false+                }+                return true // a failed read that is not a cancel: keep draining+            }+            state.consecutiveReadErrors = 0             appendAudio(chunk, n, state)             updateVad(state)             maybeEmitPartial(state)@@ -250,6 +262,10 @@ open class WhisperRecognitionService : RecognitionService() {             var partialArmed = false             /** Set when the no-speech timeout already reported no-match for this session. */             var noMatchReported = false+            /** Consecutive AudioRecord read failures; reset by every good chunk. */+            var consecutiveReadErrors = 0+            /** Set when a dead microphone already reported ERROR_AUDIO for this session. */+            var errorReported = false         }          private fun finishAndTranscribe(speechStarted: Boolean) {@@ -324,6 +340,12 @@ open class WhisperRecognitionService : RecognitionService() {         private const val END_SILENCE_MS = 1000    // trailing silence that ends the utterance         private const val NO_SPEECH_MS = 8000      // give up if nothing is said         private const val MAX_MS = 29000           // Whisper handles <= 30 s+        /**+         * Consecutive failed AudioRecord reads before the session gives up+         * with ERROR_AUDIO. Failed reads advance no audio clock, so without+         * this bound a dead microphone spins the recording loop forever.+         */+        private const val MAX_CONSECUTIVE_READ_ERRORS = 50         /** dB scale factor for the UI meter. */         private const val DB_SCALE = 10.0         /** Floor keeping silence at 0 dB rather than -infinity. */
speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt b/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.ktindex bc070afb30..4f72b1a10e 100644--- a/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt+++ b/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt@@ -4,6 +4,7 @@ import android.Manifest import android.app.Application import android.content.Context import android.content.Intent+import android.media.AudioRecord import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import androidx.test.core.app.ApplicationProvider@@ -233,4 +234,33 @@ class WhisperRecognitionSessionTest {         assertTrue(cb.awaitTerminal())         assertEquals(listOf("hello world"), cb.resultsTexts.toList())     }++    @Test+    fun persistentReadErrorsReportAudioErrorInsteadOfSpinning() {+        grantMic()+        val (service, _) = fakeService()+        // A dead microphone: every read fails. Failed reads advance no audio+        // clock, so without an error bound the loop would never terminate.+        FakeAudioRecordShadow.reset(List(200) { AudioRecord.ERROR_INVALID_OPERATION })+        val cb = RecordingRecognitionCallback(service)+        service.start(intentWithLang("en"), cb)+        assertTrue(cb.awaitTerminal(), "no terminal callback; errors=${cb.errors}")+        assertEquals(listOf(SpeechRecognizer.ERROR_AUDIO), cb.errors.toList())+        assertTrue(cb.resultsTexts.isEmpty())+    }++    @Test+    fun transientReadErrorsDoNotAbortTheSession() {+        grantMic()+        val (service, _) = fakeService()+        FakeAudioRecordShadow.reset(+            listOf(AudioRecord.ERROR_INVALID_OPERATION, AudioRecord.ERROR_INVALID_OPERATION) ++                listOf(10000, 10000, 10000) + List(15) { 0 },+        )+        val cb = RecordingRecognitionCallback(service)+        service.start(intentWithLang("en"), cb)+        assertTrue(cb.awaitTerminal(), "no terminal callback; errors=${cb.errors} results=${cb.resultsTexts}")+        assertEquals(listOf("hello world"), cb.resultsTexts.toList())+        assertTrue(cb.errors.isEmpty(), "errors=${cb.errors}")+    } }
speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt b/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.ktindex 7e779eebbb..3dad2320c7 100644--- a/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt+++ b/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt@@ -9,7 +9,8 @@ import org.robolectric.annotation.Implements  * Scripts the microphone: each read fills the buffer with the next queued  * amplitude (100 ms of constant samples) and returns a full chunk. When the  * script runs out, reads return silence, which drives the VAD to its- * end-of-utterance / no-speech exits.+ * end-of-utterance / no-speech exits. A queued negative value (other than+ * [BLOCK]) is returned as-is to simulate an AudioRecord read error.  */ @Implements(AudioRecord::class) class FakeAudioRecordShadow {@@ -30,6 +31,9 @@ class FakeAudioRecordShadow {             blockEntered?.countDown()             blockRelease?.await(10, java.util.concurrent.TimeUnit.SECONDS)             for (i in 0 until sizeInShorts) audioData[offsetInShorts + i] = 0+        } else if (amplitude < 0) {+            reads+++            return amplitude         } else {             for (i in 0 until sizeInShorts) audioData[offsetInShorts + i] = amplitude.toShort()         }