Modern Apps git

← Modern-Apps.git

speech: survive cancel races and NaN TTS samples

Commit
2fbc67f4475303331e76eb772e6a0267a00be7be
Author
Vayun Mathur <[email protected]>
When
2026-11-19 01:53 UTC (17 days ago)
Parents
fe1e46e
Two runtime throw paths in the system speech services:

- WhisperRecognitionService: cancel() calls releaseRecord() and
  transcribeExec.shutdownNow() while the recording thread may be
  blocked in AudioRecord.read() or about to submit a partial/final
  transcription. The submit threw RejectedExecutionException and a
  racing read can throw IllegalStateException, both uncaught on an
  unsupervised thread, killing the process. Route submits through
  a helper that swallows RejectedExecutionException, and guard the
  recording loop so an unexpected failure reports ERROR_AUDIO
  instead of crashing.
- SupertonicTtsService.floatsToPcm16: coerceIn preserves NaN and
  Float.roundToInt throws IllegalArgumentException on NaN, so one
  NaN sample from the native vocoder crashed synthesis for any
  calling app. Map NaN to silence before rounding.

Verification: ./gradlew :speech:testDevUnitTest and
./check speech (run after this commit).

Diff

speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.ktindex 7431d78c7e..ad59f920e9 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt@@ -233,7 +233,10 @@ open class SupertonicTtsService : TextToSpeechService() {         val out = ByteArray(samples.size * BYTES_PER_SAMPLE)         var i = 0         for (sample in samples) {-            val value = (sample.coerceIn(-1f, 1f) * PCM_PEAK).roundToInt()+            // coerceIn preserves NaN and roundToInt throws on it; a NaN sample from+            // the native vocoder is silence, not a reason to kill the TTS service.+            val clamped = if (sample.isNaN()) 0f else sample.coerceIn(-1f, 1f)+            val value = (clamped * PCM_PEAK).roundToInt()             out[i++] = (value and BYTE_MASK).toByte()             out[i++] = ((value shr BYTE_BITS) and BYTE_MASK).toByte()         }
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 4a22b57d61..17cbdf4a46 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt@@ -13,6 +13,7 @@ import android.speech.SpeechRecognizer import com.vayunmathur.library.log.Log import com.vayunmathur.speech.platform.WhisperEngine import java.util.concurrent.Executors+import java.util.concurrent.RejectedExecutionException import kotlin.math.log10 import kotlin.math.sqrt @@ -137,16 +138,41 @@ open class WhisperRecognitionService : RecognitionService() {             transcribeExec.shutdownNow()         } +        // The recording thread is unsupervised and the platform audio layer throws+        // undocumented RuntimeExceptions; any failure here is a dead microphone,+        // so the catch stays broad by design.+        @Suppress("TooGenericExceptionCaught")         private fun loop() {             val chunk = ShortArray(SAMPLE_RATE / 10) // 100 ms             val state = VadState()-            while (running && pumpOnce(chunk, state)) {-                // All work happens in pumpOnce; an empty body keeps the loop to one jump.+            // This thread is not supervised: a throw here (a read racing cancel's+            // release(), a transcription submit racing shutdownNow()) would kill+            // the process. Treat an unexpected failure as a dead microphone.+            try {+                while (running && pumpOnce(chunk, state)) {+                    // All work happens in pumpOnce; an empty body keeps the loop to one jump.+                }+            } catch (e: Exception) {+                if (!cancelled && !state.errorReported) {+                    Log.error(TAG, "recording loop failed", e)+                    state.errorReported = true+                    finishError(SpeechRecognizer.ERROR_AUDIO)+                }+                return             }             if (cancelled || state.noMatchReported || state.errorReported) return             finishAndTranscribe(state.speechStarted)         } +        /** Submit transcription work; a submit racing cancel's shutdown is a no-op. */+        private fun submitTranscription(block: () -> Unit) {+            try {+                transcribeExec.execute(block)+            } catch (_: RejectedExecutionException) {+                // cancel() shut the executor down first; the session is over anyway.+            }+        }+         /**          * One loop iteration: drain a chunk, fold it into the VAD and maybe emit a partial.          * True keeps recording; false exits to the final transcription.@@ -213,7 +239,7 @@ open class WhisperRecognitionService : RecognitionService() {             state.partialArmed = false             partialPending = true             val snapshot = flatten()-            transcribeExec.execute {+            submitTranscription {                 val t = engine.transcribe(snapshot, lang)?.trim()                 partialPending = false                 if (!cancelled && !t.isNullOrBlank()) {@@ -275,10 +301,10 @@ open class WhisperRecognitionService : RecognitionService() {             val audio = flatten()             // Queue the final pass behind any in-flight partial so the engine is only ever             // touched by one thread; this is the last task submitted.-            transcribeExec.execute {+            submitTranscription {                 val text = engine.transcribe(audio, lang)?.trim()-                if (cancelled) return@execute-                if (text.isNullOrBlank()) { finishNoMatch(); return@execute }+                if (cancelled) return@submitTranscription+                if (text.isNullOrBlank()) { finishNoMatch(); return@submitTranscription }                 val b = Bundle().apply {                     putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, arrayListOf(text))                     putFloatArray(SpeechRecognizer.CONFIDENCE_SCORES, floatArrayOf(1f))