Modern Apps git

← Modern-Apps.git

speech: several fixes

Commit
2f6e2cffce9c1d61aba12424337f11715f68680c
Author
Vayun Mathur <[email protected]>
When
2026-07-31 03:35 UTC (4 months ago)
Parents
65d974f

Diff

speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.ktindex 22c3bd7cf2..de6642c0bd 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt@@ -1,11 +1,15 @@ package com.vayunmathur.speech.service  import android.media.AudioFormat+import android.os.Build import android.speech.tts.SynthesisCallback import android.speech.tts.SynthesisRequest import android.speech.tts.TextToSpeech import android.speech.tts.TextToSpeechService+import android.speech.tts.Voice import com.vayunmathur.speech.util.PiperEngine+import com.vayunmathur.speech.util.PiperModel+import java.util.Locale import kotlin.math.roundToInt  /**@@ -38,18 +42,46 @@ class PiperTtsService : TextToSpeechService() {      // --- Language support: English (en-US) only. --- -    override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int =-        when {-            !lang.equals("eng", ignoreCase = true) -> TextToSpeech.LANG_NOT_SUPPORTED-            country.equals("USA", ignoreCase = true) -> TextToSpeech.LANG_COUNTRY_AVAILABLE+    override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int {+        // Guard against nulls — old implementations crashed calling equals() on null country.+        val l = lang?.lowercase() ?: return TextToSpeech.LANG_NOT_SUPPORTED+        if (l != "eng" && l != "en") return TextToSpeech.LANG_NOT_SUPPORTED+        // If voice isn't installed yet, still report as available so the framework doesn't+        // hide us; CheckVoiceDataActivity will report FAIL and the Settings will show+        // the download prompt. Once extracted we report country-level availability.+        val c = country?.lowercase()+        return when {+            c == null || c.isEmpty() || c == "usa" || c == "us" -> TextToSpeech.LANG_COUNTRY_AVAILABLE             else -> TextToSpeech.LANG_AVAILABLE         }+    }      override fun onLoadLanguage(lang: String?, country: String?, variant: String?): Int =         onIsLanguageAvailable(lang, country, variant)      override fun onGetLanguage(): Array<String> = arrayOf("eng", "USA", "") +    // Provide a Voice list so modern Settings (API 21+) shows a voice and enables the Play+    // button. Without this, some OEM / AOSP builds disable Play when getVoices() is empty.+    // Do NOT extract here — that would ANR the TTS binder thread. Extraction happens+    // right after download in MainActivity (PiperModel.download + installIfNeeded on IO).+    override fun onGetVoices(): MutableList<Voice> {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return super.onGetVoices()+        val ctx = applicationContext+        if (!PiperModel.isExtracted(ctx)) return mutableListOf()+        val locale = Locale("en", "US")+        // Name must be stable, quality high, local (no network) so Settings enables preview.+        val voice = Voice(+            "en-us-x-ma-speech-local",+            locale,+            Voice.QUALITY_HIGH,+            Voice.LATENCY_NORMAL,+            false,+            emptySet()+        )+        return mutableListOf(voice)+    }+     override fun onStop() {         stopped = true     }
speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt b/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.ktindex 351eb9cb64..f8471e04f8 100644--- a/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt@@ -9,7 +9,7 @@ import com.vayunmathur.speech.util.PiperModel /**  * Answers the framework's `CHECK_TTS_DATA` probe: the system TTS settings run this before  * letting the user pick our engine, to learn which voices are installed. We report en-US as- * available when the bundled Piper voice is present, otherwise as unavailable.+ * available when the Piper voice has been extracted (extraction happens right after download).  */ class CheckVoiceDataActivity : Activity() {     override fun onCreate(savedInstanceState: Bundle?) {@@ -17,7 +17,7 @@ class CheckVoiceDataActivity : Activity() {          val available = ArrayList<String>()         val unavailable = ArrayList<String>()-        if (PiperModel.isReady(this)) available.add(VOICE) else unavailable.add(VOICE)+        if (PiperModel.isExtracted(this)) available.add(VOICE) else unavailable.add(VOICE)          val data = Intent().apply {             putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available)
speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.ktindex 6f105b61bc..110d703cf9 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt@@ -14,6 +14,11 @@ import java.io.File  * phonemization needs real file paths); this loads it once and reuses it across syntheses.  * Not thread-safe; drive it from one worker thread (the TTS framework calls  * [com.vayunmathur.speech.service.PiperTtsService.onSynthesizeText] serially).+ *+ * IMPORTANT: sherpa 1.13.4's generateWithCallback JNI expects a Function1<FloatArray, Int>+ * as a *sam* interface, but R8/minify + Kotlin synthetic lambdas cause+ * NoSuchMethodError for ExternalSyntheticLambda (see tombstone_00). We use the blocking+ * generate() API and chunk the PCM ourselves to avoid the callback JNI path.  */ class PiperEngine(private val context: Context) { @@ -27,19 +32,25 @@ class PiperEngine(private val context: Context) {     fun sampleRate(): Int = tts?.sampleRate() ?: 0      /**-     * Stream synthesis of [text]. [onChunk] receives PCM float samples ([-1, 1]) as they-     * are produced and returns false to abort (e.g. the caller was stopped). Returns true-     * if synthesis ran, false if the engine couldn't load.+     * Synthesize [text] into PCM float chunks. [onChunk] receives each chunk and returns+     * false to abort. Uses blocking generate() to avoid the crashy callback JNI.      */     @Synchronized     fun synthesize(text: String, speed: Float, onChunk: (FloatArray) -> Boolean): Boolean {         if (!ensure()) return false         val engine = tts ?: return false         return try {-            // sherpa returns 1 to keep going, 0 to stop; it also returns the full audio,-            // which we ignore since we've already streamed it out chunk by chunk.-            engine.generateWithCallback(text, /* sid = */ 0, speed) { samples ->-                if (onChunk(samples)) 1 else 0+            // Blocking synthesis — returns full audio. We then stream it out in 4k-sample+            // chunks so the caller's audioAvailable loop still gets progressive output.+            val audio = engine.generate(text, /* sid = */ 0, speed)+            val samples = audio.samples ?: return false+            if (samples.isEmpty()) return true+            var offset = 0+            while (offset < samples.size) {+                val end = minOf(offset + 4096, samples.size)+                val chunk = samples.copyOfRange(offset, end)+                if (!onChunk(chunk)) return false+                offset = end             }             true         } catch (t: Throwable) {@@ -61,9 +72,11 @@ class PiperEngine(private val context: Context) {     private fun ensure(): Boolean {         tts?.let { return true }         if (loadFailed) return false-        // Extract the downloaded voice on first use. Don't latch loadFailed if it simply-        // isn't downloaded yet — a later call can succeed once the model arrives.-        if (!PiperModel.installIfNeeded(context)) return false+        // Voice should already be extracted right after download (MainActivity does it).+        // Don't try to extract here on the TTS binder/SynthThread — that would ANR the+        // system TTS service. If not extracted yet, just return false so the caller can+        // prompt the user to finish download in the app.+        if (!PiperModel.isExtracted(context)) return false         return try {             val dir = PiperModel.voiceDir(context)             val onnx = PiperModel.onnxFile(context)
speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.ktindex f9d2552bea..86c7855e02 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt@@ -52,8 +52,8 @@ object PiperModel {             File(dir, ESPEAK_DATA).isDirectory     } -    /** True if TTS can run now or after extracting an already-downloaded archive. */-    fun isReady(context: Context): Boolean = isExtracted(context) || archive(context).exists()+    /** True if TTS can run now (extracted). Extraction happens immediately after download. */+    fun isReady(context: Context): Boolean = isExtracted(context)      /** Download the voice archive if missing; suspends until complete. */     suspend fun download(context: Context, ds: DataStoreUtils) = downloadModels(context, ds, FILES)