Modern Apps git

← Modern-Apps.git

speech: text-to-speech is Supertonic, bundled, 31 languages

Commit
abfbd31ed1a735f5a4439f54917030021d21197d
Author
vayun-mathur <[email protected]>
When
2026-08-28 22:02 UTC (3 months ago)
Parents
a95c288

Diff

speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex 6789bbb293..3a1e68f892 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -20,29 +20,26 @@ android {         // a 40 MB heap buffer first. Storing them uncompressed costs nothing on download size         // either - int8 weights are already incompressible.         noCompress += "onnx"-        // Voices are downloaded rather than bundled, so no .maml sits in this APK. The entry-        // is here for the same reason as `onnx`: if a voice is ever bundled, fp16 weights-        // should not be deflated only to be inflated straight back.+        // Load-bearing, not an optimisation. `AssetManager.openFd` throws for a deflated entry,+        // and the fd is how Supertonic's ~105 MB of weights reach the GPU without being copied+        // through the Java heap three times - see SupertonicSynthesizer.inAssets.         noCompress += "maml"     } } dependencies {-    // Text-to-speech is Piper (VITS) on :library:ml, our own Vulkan compute runtime. Four-    // networks per voice: the text encoder, the flow and the HiFi-GAN vocoder are compiled-    // plans on the GPU, and the stochastic duration predictor runs on the CPU because it is a-    // bin search and a quadratic solve per phoneme. Voices are extracted to disk before use.+    // Text-to-speech is Supertonic 3 on :library:ml, our own Vulkan compute runtime. Four networks+    // for all 31 languages, every one of them on the GPU: the duration predictor, the text encoder,+    // a flow-matching sampler and a ConvNeXt vocoder. The bundle ships in `assets/supertonic/` and+    // is streamed from a file descriptor, which is what `noCompress += "maml"` above is for.     implementation(project(":library:ml"))-     // Speech-to-text is whisper-base int8 ONNX (bundled in assets, see WhisperOnnxEngine).     // It is not ncnn: onnx2ncnn has no DynamicQuantizeLinear/MatMulInteger/ConvInteger     // support, and the AAR's Whisper expects a six-net decomposition HF does not export.     //     // Reduced ORT build (10 MB native, vs 28 MB for the full one). Its operator set is     // generated from the two bundled .onnx files, so if they are ever re-exported with-    // different ops the session will fail to create — regenerate the AAR, don't work around it.+    // different ops the session will fail to create - regenerate the AAR, don't work around it.     implementation(libs.onnxruntime.reduced)--    // Runtime model download (mirror-hosted, SHA-256 pinned) — non-English TTS voices only.-    implementation(project(":library:downloadservice"))-    implementation(libs.androidx.datastore.preferences)+    // No `:library:downloadservice` and no DataStore: both models ship in the APK, so this app+    // downloads nothing and stores no preferences. They went when Piper's 1,834 MB of voices did. }
speech/src/main/AndroidManifest.xml
diff --git a/speech/src/main/AndroidManifest.xml b/speech/src/main/AndroidManifest.xmlindex 9631494c52..78ce03e5e1 100644--- a/speech/src/main/AndroidManifest.xml+++ b/speech/src/main/AndroidManifest.xml@@ -37,7 +37,7 @@         </service>          <service-            android:name=".service.PiperTtsService"+            android:name=".service.SupertonicTtsService"             android:label="@string/tts_engine_label"             android:exported="true">             <intent-filter>
speech/src/main/assets/supertonic/README.md
diff --git a/speech/src/main/assets/supertonic/README.md b/speech/src/main/assets/supertonic/README.mdnew file mode 100644index 0000000000..4ee9c87779--- /dev/null+++ b/speech/src/main/assets/supertonic/README.md@@ -0,0 +1,35 @@+# Supertonic 3, bundled++`SupertonicSynthesizer.inAssets` reads these six files, and `SupertonicBundle.isPresent` refuses to+advertise the TTS engine unless they are all here. They are **not in version control** — the four+`.maml` come to ~105 MB — so a fresh checkout has to build them:++```+./scripts/ml/supertonic_fold.py duration_predictor.onnx --graph supertonic_dp  -o supertonic_dp.maml+./scripts/ml/supertonic_fold.py text_encoder.onnx       --graph supertonic_ttl -o supertonic_ttl.maml+./scripts/ml/supertonic_fold.py vector_estimator.onnx   --graph supertonic_ve  -o supertonic_ve.maml+./scripts/ml/supertonic_fold.py vocoder.onnx            --graph supertonic_voc -o supertonic_voc.maml+./scripts/ml/supertonic_bundle.py --indexer <ttl.json> --styles voice_styles/ -o .+```++| File | What it is |+| :--- | :--- |+| `supertonic_dp.maml` | duration predictor — one number, the utterance's length in seconds |+| `supertonic_ttl.maml` | text encoder — characters to a `[256, chars]` conditioning |+| `supertonic_ve.maml` | flow-matching sampler — the expensive one, 32 passes per sentence |+| `supertonic_voc.maml` | ConvNeXt vocoder — latent to 44,100 Hz samples |+| `unicode_indexer.bin` | 65,536 `int16`, one per BMP codepoint; the whole front end |+| `style_F1.bin` … `style_M5.bin` | ten voices, ~25 KB each; two style tensors, not a model |++## Uncompressed, and it has to stay that way++`noCompress += "maml"` in `speech/build.gradle.kts` is load-bearing rather than an optimisation:+`AssetManager.openFd` throws for a deflated entry, and the fd is how the weights reach the GPU+without being copied through the Java heap three times. Adding a `.bin` entry would be worth it too+if the codepoint table ever grew, but at 128 KB it is read whole anyway.++## Licence++Supertonic 3 is **OpenRAIL**, which is use-restricted — the first such licence in this tree, and the+reason `SUPPLY_CHAIN_RISKS.md` calls it out separately. It ships in the APK rather than being+downloaded, so the restriction travels with every release.
speech/src/main/java/com/vayunmathur/speech/MainActivity.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt b/speech/src/main/java/com/vayunmathur/speech/MainActivity.ktindex 488907a139..2bb2fb5092 100644--- a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt@@ -7,7 +7,6 @@ import android.content.ComponentName import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle-import android.os.StatFs import android.provider.Settings import android.speech.RecognitionListener import android.speech.RecognizerIntent@@ -32,13 +31,10 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults-import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf@@ -58,18 +54,13 @@ import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.rememberPermissionRequest-import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.speech.domain.SupertonicVoices+import com.vayunmathur.speech.platform.SupertonicBundle import com.vayunmathur.speech.service.WhisperRecognitionService-import com.vayunmathur.speech.util.PiperModel-import com.vayunmathur.speech.util.PiperVoiceRegistry import com.vayunmathur.speech.util.SpeechSetupActions import com.vayunmathur.speech.util.SpeechSetupUiState import com.vayunmathur.speech.util.TtsVoiceUiState import com.vayunmathur.speech.util.WhisperModel-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.delay-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext import java.util.Locale  class MainActivity : ComponentActivity() {@@ -101,52 +92,22 @@ private fun SetupScreen() {         ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==             PackageManager.PERMISSION_GRANTED     }-    val ds = remember { DataStoreUtils.getInstance(context) }-     // Whisper     val modelReady = remember(refresh) { WhisperModel.isReady(context) } -    // Voices — migrate legacy if needed then compute installed list and per-voice states-    val installedCodes = remember(refresh) {-        try {-            PiperVoiceRegistry.migrateLegacyIfNeeded(context)-            PiperVoiceRegistry.installedCodes(context).let { codes ->-                if (codes.isEmpty() && PiperModel.isReady(context)) listOf("en") else codes-            }-        } catch (_: Throwable) {-            if (PiperModel.isReady(context)) listOf("en") else emptyList()-        }-    }-    val ttsVoices = remember(refresh, installedCodes) {-        try {-            PiperVoiceRegistry.ALL.map { def ->-                TtsVoiceUiState(-                    code = def.code,-                    bcp47 = def.bcp47,-                    iso3 = def.iso3,-                    nativeName = def.nativeName,-                    englishName = def.englishName,-                    isInstalled = def.code in installedCodes,-                    progress = 0f, // real progress from DataStore in the card itself-                    sizeEstimateMb = def.sizeEstimateMb,-                    quality = def.quality,-                    sampleRate = def.sampleRate,-                )-            }-        } catch (_: Throwable) {-            emptyList()-        }-    }-    val installedBytes = remember(refresh) {-        try {-            PiperVoiceRegistry.installedBytes(context)-        } catch (_: Throwable) {-            0L+    // Every language the bundle covers. Not a per-install fact any more: the four networks and the+    // ten voices ship in the APK, so this list is the same on every device that has the asset.+    val ttsVoices = remember {+        SupertonicVoices.ALL.map { language ->+            TtsVoiceUiState(+                code = language.code,+                bcp47 = language.bcp47,+                nativeName = language.nativeName,+                englishName = language.englishName,+            )         }     }-    val ttsModelReady = remember(refresh, installedCodes) {-        installedCodes.isNotEmpty() || PiperModel.isReady(context)-    }+    val ttsModelReady = remember(refresh) { SupertonicBundle.isPresent(context) }     val isTtsDefault = remember(refresh) {         Settings.Secure.getString(context.contentResolver, "tts_default_synth") == context.packageName     }@@ -163,8 +124,7 @@ private fun SetupScreen() {             ttsModelReady = ttsModelReady,             isTtsDefault = isTtsDefault,             ttsVoices = ttsVoices,-            installedBytes = installedBytes,-            currentTestLang = if (installedCodes.isNotEmpty()) installedCodes.first() else "en",+            currentTestLang = SupertonicVoices.DEFAULT.code,         ),         actions = object : SpeechSetupActions {             override fun requestMicPermission() = launchMicRequest()@@ -201,46 +161,6 @@ private fun SetupScreen() {             }              override fun refresh() { refresh++ }--            // Legacy single-voice-            override fun voiceProgress() = PiperVoiceRegistry.overallProgress(ds)-            override suspend fun downloadVoice() {-                PiperVoiceRegistry.download(context, ds, listOf("en"))-                withContext(Dispatchers.IO) {-                    PiperVoiceRegistry.installIfNeeded(context, PiperVoiceRegistry.DEFAULT)-                }-            }--            // Per-voice-            override fun voiceProgress(code: String): Float {-                val def = PiperVoiceRegistry.byCode(code) ?: return 0f-                return PiperVoiceRegistry.progress(ds, def)-            }--            override suspend fun downloadVoice(code: String) {-                val def = PiperVoiceRegistry.byCode(code) ?: return-                PiperVoiceRegistry.download(context, ds, listOf(code))-                withContext(Dispatchers.IO) {-                    PiperVoiceRegistry.installIfNeeded(context, def)-                }-            }--            override fun deleteVoice(code: String) {-                val def = PiperVoiceRegistry.byCode(code) ?: return-                // Immediate file deletion + async DataStore cleanup-                PiperVoiceRegistry.deleteFiles(context, def)-                // Fire-and-forget DataStore reset (suspend) in IO scope-                kotlinx.coroutines.CoroutineScope(Dispatchers.IO).launch {-                    try {-                        ds.setDouble("progress_${PiperVoiceRegistry.VOICES_ROOT}/${def.remoteArchive}", 0.0)-                        ds.setLong("dlid_${PiperVoiceRegistry.VOICES_ROOT}/${def.remoteArchive}", 0L)-                        ds.setDouble("speed_${PiperVoiceRegistry.VOICES_ROOT}/${def.remoteArchive}", 0.0)-                    } catch (_: Throwable) {}-                }-                refresh++-            }--            override fun installedCodes(): List<String> = installedCodes         },     ) }@@ -308,41 +228,29 @@ fun SpeechSetupScreen(state: SpeechSetupUiState, actions: SpeechSetupActions) {          StepCard(             index = 4,-            title = "Text-to-speech voices (${state.ttsVoices.count { it.isInstalled }}/${state.ttsVoices.size})",+            title = "Text-to-speech voices",             done = state.ttsModelReady,         ) {-            // Storage summary-            if (state.installedBytes > 0) {-                val mb = state.installedBytes / (1024 * 1024)+            if (state.ttsModelReady) {                 Text(-                    text = "Installed: ${mb} MB • ${state.ttsVoices.count { it.isInstalled }} voices",+                    text = "${state.ttsVoices.size} languages and " ++                        "${SupertonicVoices.VOICES.size} voices, bundled with the app. " ++                        "Nothing to download.",                     style = MaterialTheme.typography.bodySmall,                     color = MaterialTheme.colorScheme.onSurfaceVariant,                 )                 Spacer(Modifier.height(4.dp))-            }--            // WiFi warning — high quality 22kHz ~80-90 MB each-            if (state.ttsVoices.any { !it.isInstalled }) {                 Text(-                    text = "High-quality voices (22kHz) download ~80-90 MB each on Wi-Fi. Total ~1.6 GB if all 20 installed.",-                    style = MaterialTheme.typography.bodySmall,+                    text = state.ttsVoices.joinToString(" · ") { it.nativeName },+                    style = MaterialTheme.typography.labelSmall,                     color = MaterialTheme.colorScheme.onSurfaceVariant,                 )-                Spacer(Modifier.height(8.dp))-            }--            // Per-voice rows-            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {-                for (voice in state.ttsVoices) {-                    VoiceRow(-                        voice = voice,-                        progressOf = { actions.voiceProgress(voice.code) },-                        onDownload = { actions.downloadVoice(voice.code) },-                        onDelete = { actions.deleteVoice(voice.code) },-                        onDone = actions::refresh,-                    )-                }+            } else {+                Text(+                    text = "The bundled voices could not be read. Reinstalling the app should fix it.",+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.error,+                )             }         } @@ -358,7 +266,7 @@ fun SpeechSetupScreen(state: SpeechSetupUiState, actions: SpeechSetupActions) {          TtsTestSection(             enabled = state.ttsModelReady,-            installedVoices = state.ttsVoices.filter { it.isInstalled },+            languages = state.ttsVoices,             currentLang = state.currentTestLang,         )         }@@ -384,120 +292,6 @@ private fun StepCard(     } } -/**- * A per-voice download row with progress bar, size badge, quality/sample-rate note, and delete.- */-@Composable-private fun VoiceRow(-    voice: TtsVoiceUiState,-    progressOf: () -> Float,-    onDownload: suspend () -> Unit,-    onDelete: () -> Unit,-    onDone: () -> Unit,-) {-    val scope = rememberCoroutineScope()-    var busy by remember { mutableStateOf(false) }-    var pct by remember { mutableIntStateOf(0) }--    LaunchedEffect(busy) {-        while (busy) {-            pct = (progressOf() * 100f).toInt().coerceIn(0, 100)-            delay(500)-        }-    }--    // Poll progress even when not busy so the bar shows download manager progress-    LaunchedEffect(voice.code, voice.isInstalled) {-        if (!voice.isInstalled) {-            // Light polling while download may be in progress in background-            while (!voice.isInstalled) {-                pct = (progressOf() * 100f).toInt().coerceIn(0, 100)-                delay(1000)-            }-        }-    }--    Card(modifier = Modifier.fillMaxWidth()) {-        Column(-            Modifier-                .fillMaxWidth()-                .padding(12.dp),-            verticalArrangement = Arrangement.spacedBy(6.dp),-        ) {-            Row(-                Modifier.fillMaxWidth(),-                horizontalArrangement = Arrangement.SpaceBetween,-                verticalAlignment = Alignment.CenterVertically,-            ) {-                Column(Modifier.weight(1f)) {-                    Row(verticalAlignment = Alignment.CenterVertically) {-                        Text(-                            text = "${voice.nativeName} (${voice.englishName})",-                            fontWeight = FontWeight.SemiBold,-                            style = MaterialTheme.typography.bodyMedium,-                        )-                        if (voice.isInstalled) {-                            Spacer(Modifier.width(6.dp))-                            Text(-                                text = "✓",-                                color = MaterialTheme.colorScheme.primary,-                                style = MaterialTheme.typography.bodySmall,-                            )-                        }-                    }-                    Spacer(Modifier.height(2.dp))-                    Text(-                        text = "${voice.code.uppercase()} • ${voice.bcp47} • ${voice.quality} • ${voice.sampleRate} Hz • ~${voice.sizeEstimateMb} MB",-                        style = MaterialTheme.typography.labelSmall,-                        color = MaterialTheme.colorScheme.onSurfaceVariant,-                    )-                }-            }--            if (!voice.isInstalled) {-                if (pct in 1..99 || busy) {-                    LinearProgressIndicator(-                        progress = { pct / 100f },-                        modifier = Modifier.fillMaxWidth(),-                    )-                    Text(-                        text = "Downloading… $pct%",-                        style = MaterialTheme.typography.labelSmall,-                        color = MaterialTheme.colorScheme.primary,-                    )-                }-                Button(-                    enabled = !busy,-                    onClick = {-                        busy = true-                        scope.launch {-                            runCatching { onDownload() }-                            busy = false-                            onDone()-                        }-                    },-                ) {-                    Text(if (busy) "Downloading… $pct%" else "Download ${voice.nativeName} (~${voice.sizeEstimateMb} MB)")-                }-            } else {-                Row(-                    verticalAlignment = Alignment.CenterVertically,-                    horizontalArrangement = Arrangement.spacedBy(8.dp),-                ) {-                    Text(-                        text = "Installed",-                        style = MaterialTheme.typography.labelSmall,-                        color = MaterialTheme.colorScheme.primary,-                    )-                    OutlinedButton(onClick = { onDelete() }) {-                        Text("Delete")-                    }-                }-            }-        }-    }-}- @Composable private fun TestSection(enabled: Boolean) {     val context = LocalContext.current@@ -549,15 +343,15 @@ private fun TestSection(enabled: Boolean) { @Composable private fun TtsTestSection(     enabled: Boolean,-    installedVoices: List<TtsVoiceUiState>,+    languages: List<TtsVoiceUiState>,     currentLang: String, ) {     val context = LocalContext.current     var status by remember { mutableStateOf("") }-    var selectedCode by remember(currentLang, installedVoices) {+    var selectedCode by remember(currentLang, languages) {         mutableStateOf(-            if (installedVoices.any { it.code == currentLang }) currentLang-            else installedVoices.firstOrNull()?.code ?: "en"+            if (languages.any { it.code == currentLang }) currentLang+            else languages.firstOrNull()?.code ?: "en"         )     }     var dropdownExpanded by remember { mutableStateOf(false) }@@ -568,29 +362,42 @@ private fun TtsTestSection(         onDispose { engine.value?.shutdown(); engine.value = null }     } -    // Sample utterances per language (keep short, same length rough).+    // One sample sentence per language the bundle covers, and the reason each is written out rather+    // than translated at runtime is that the model reads *characters*: a sentence has to exercise+    // the script, not just the language, or a missing codepoint in the table goes unnoticed.     val samples = remember {         mapOf(-            "en" to "Hello, this is the offline Piper voice.",-            "es" to "Hola, esta es la voz sin conexión de Piper.",-            "fr" to "Bonjour, ceci est la voix hors ligne Piper.",-            "de" to "Hallo, das ist die Offline-Piper-Stimme.",-            "it" to "Ciao, questa è la voce offline di Piper.",-            "pt" to "Olá, esta é a voz offline do Piper.",-            "nl" to "Hallo, dit is de offline Piper-stem.",-            "ru" to "Привет, это автономный голос Пайпер.",-            "pl" to "Cześć, to jest głos offline Piper.",-            "tr" to "Merhaba, bu çevrimdışı Piper sesi.",-            "ar" to "مرحبا، هذا هو صوت بايبر دون اتصال.",-            "hi" to "नमस्ते, यह ऑफ़लाइन पाइपर आवाज़ है।",-            "zh" to "你好,这是离线 Piper 语音。",-            "ja" to "こんにちは、これはオフラインのPiper音声です。",-            "ko" to "안녕하세요, 오프라인 Piper 음성입니다.",-            "vi" to "Xin chào, đây là giọng nói ngoại tuyến của Piper.",-            "th" to "สวัสดี นี่คือเสียงออฟไลน์ของ Piper",-            "id" to "Halo, ini adalah suara Piper offline.",-            "uk" to "Привіт, це автономний голос Пайпер.",-            "sv" to "Hej, det här är Pipers offlineröst.",+            "en" to "Hello, this voice runs entirely on this device.",+            "ar" to "مرحبا، هذا الصوت يعمل بالكامل على هذا الجهاز.",+            "bg" to "Здравейте, този глас работи изцяло на това устройство.",+            "cs" to "Dobrý den, tento hlas běží celý na tomto zařízení.",+            "da" to "Hej, denne stemme kører helt på denne enhed.",+            "de" to "Hallo, diese Stimme läuft vollständig auf diesem Gerät.",+            "el" to "Γεια σας, αυτή η φωνή λειτουργεί εξ ολοκλήρου σε αυτή τη συσκευή.",+            "es" to "Hola, esta voz funciona por completo en este dispositivo.",+            "et" to "Tere, see hääl töötab täielikult selles seadmes.",+            "fi" to "Hei, tämä ääni toimii kokonaan tässä laitteessa.",+            "fr" to "Bonjour, cette voix fonctionne entièrement sur cet appareil.",+            "hi" to "नमस्ते, यह आवाज़ पूरी तरह इस उपकरण पर चलती है।",+            "hr" to "Zdravo, ovaj glas radi u cijelosti na ovom uređaju.",+            "hu" to "Üdvözlöm, ez a hang teljesen ezen a készüléken fut.",+            "id" to "Halo, suara ini berjalan sepenuhnya di perangkat ini.",+            "it" to "Ciao, questa voce funziona interamente su questo dispositivo.",+            "ja" to "こんにちは。この音声はすべてこの端末で動いています。",+            "ko" to "안녕하세요. 이 음성은 전부 이 기기에서 동작합니다.",+            "lt" to "Sveiki, šis balsas veikia visiškai šiame įrenginyje.",+            "lv" to "Sveiki, šī balss darbojas pilnībā šajā ierīcē.",+            "nl" to "Hallo, deze stem werkt volledig op dit apparaat.",+            "pl" to "Cześć, ten głos działa całkowicie na tym urządzeniu.",+            "pt" to "Olá, esta voz funciona inteiramente neste dispositivo.",+            "ro" to "Bună, această voce rulează complet pe acest dispozitiv.",+            "ru" to "Здравствуйте, этот голос работает полностью на этом устройстве.",+            "sk" to "Dobrý deň, tento hlas beží celý na tomto zariadení.",+            "sl" to "Zdravo, ta glas deluje popolnoma na tej napravi.",+            "sv" to "Hej, den här rösten körs helt på den här enheten.",+            "tr" to "Merhaba, bu ses tamamen bu cihazda çalışıyor.",+            "uk" to "Вітаю, цей голос працює повністю на цьому пристрої.",+            "vi" to "Xin chào, giọng nói này chạy hoàn toàn trên thiết bị này.",         )     } @@ -598,14 +405,14 @@ private fun TtsTestSection(         Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {             Text(stringResource(R.string.try_the_voice), fontWeight = FontWeight.Bold) -            if (installedVoices.isNotEmpty()) {+            if (languages.isNotEmpty()) {                 // Language picker for TTS test — using simple ExposedDropdown                 ExposedDropdownMenuBox(                     expanded = dropdownExpanded,                     onExpandedChange = { dropdownExpanded = !dropdownExpanded },                 ) {                     OutlinedTextField(-                        value = installedVoices.firstOrNull { it.code == selectedCode }+                        value = languages.firstOrNull { it.code == selectedCode }                             ?.let { "${it.nativeName} (${it.englishName})" } ?: selectedCode,                         onValueChange = {},                         readOnly = true,@@ -620,7 +427,7 @@ private fun TtsTestSection(                         expanded = dropdownExpanded,                         onDismissRequest = { dropdownExpanded = false },                     ) {-                        installedVoices.forEach { voice ->+                        languages.forEach { voice ->                             DropdownMenuItem(                                 text = { Text("${voice.nativeName} · ${voice.englishName} (${voice.code})") },                                 onClick = {@@ -636,12 +443,12 @@ private fun TtsTestSection(             Button(                 enabled = enabled,                 onClick = {-                    if (installedVoices.isEmpty()) {-                        status = "No voice installed yet."+                    if (languages.isEmpty()) {+                        status = "The bundled voices could not be read."                         return@Button                     }-                    val chosen = installedVoices.firstOrNull { it.code == selectedCode }-                        ?: installedVoices.first()+                    val chosen = languages.firstOrNull { it.code == selectedCode }+                        ?: languages.first()                     val bcp47 = chosen.bcp47                     val sample = samples[chosen.code] ?: samples["en"]!! 
speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.kt b/speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.ktnew file mode 100644index 0000000000..4e60b3c909--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.kt@@ -0,0 +1,191 @@+package com.vayunmathur.speech.domain++/**+ * The languages and voices Supertonic 3 can speak, and the name forms the TTS framework asks for.+ *+ * This replaced a 1,118-line registry. Almost all of that was **delivery**: a mirror URL, a+ * SHA-256, a size estimate and an espeak-ng dictionary name per language, plus the code to+ * download, unzip, migrate and garbage-collect 1,834 MB of voices across 42 archives. One bundle+ * ships in the APK now, so none of it is needed and what is left is identity: given whatever+ * spelling of a language the framework hands us, which language is it.+ *+ * # The 16 languages that went, and the 5 that arrived+ *+ * Supertonic covers 31 languages against Piper's 42, and the difference is deliberate rather than+ * accidental. Gone: Chinese, Hebrew, Thai, Bengali, Telugu, Malayalam, Marathi, Urdu, Serbian,+ * Norwegian, Catalan, Georgian, Kurdish, Luxembourgish, Nepali and Swahili. Arrived: Estonian,+ * Croatian, Lithuanian, Latvian and Slovenian.+ *+ * A language that is not here does not appear in [ALL], so it is never advertised and never shown+ * in the setup screen — a user does not get offered a language and then find it silent.+ *+ * # A voice is not a model+ *+ * Piper's voices were separate networks, one download each. Supertonic's are two small style+ * tensors read against the same four networks, so all ten cost ~250 KB together and switching+ * between them re-uploads nothing. Every language can be spoken by every voice, which is why+ * [VOICES] is a flat list rather than a property of a language.+ *+ * # Why the identity layer is still needed+ *+ * `TextToSpeech` asks for a language in at least four spellings — a BCP-47 tag, an ISO-639-1 code,+ * an ISO-639-2 code with an ISO-3166-3 country, and a voice name that may carry a `-x-` extension —+ * and the `CHECK_TTS_DATA` probe insists on the ISO-3 form specifically. Getting any of them wrong+ * makes the Play button in the system settings silently do nothing, which is a failure mode with no+ * error message anywhere, so all four are kept and [resolve] accepts any of them.+ */+data class SupertonicLanguage(+    /** ISO-639-1, the key everything else is looked up by. */+    val code: String,+    /** The BCP-47 tag, which is what [android.speech.tts.Voice] names are built from. */+    val bcp47: String,+    /** ISO-639-2/T, which `CHECK_TTS_DATA` reports in. */+    val iso3: String,+    /** ISO-3166-3, the country half of the `CHECK_TTS_DATA` pair. */+    val iso3Country: String,+    val englishName: String,+    val nativeName: String,+)++object SupertonicVoices {+    /**+     * All 31 languages, English first because it is the default and the rest alphabetically by+     * code so the setup screen and the system voice list are in a stable, reviewable order.+     */+    val ALL: List<SupertonicLanguage> = listOf(+        SupertonicLanguage("en", "en-US", "eng", "USA", "English", "English"),+        SupertonicLanguage("ar", "ar-SA", "ara", "SAU", "Arabic", "العربية"),+        SupertonicLanguage("bg", "bg-BG", "bul", "BGR", "Bulgarian", "Български"),+        SupertonicLanguage("cs", "cs-CZ", "ces", "CZE", "Czech", "Čeština"),+        SupertonicLanguage("da", "da-DK", "dan", "DNK", "Danish", "Dansk"),+        SupertonicLanguage("de", "de-DE", "deu", "DEU", "German", "Deutsch"),+        SupertonicLanguage("el", "el-GR", "ell", "GRC", "Greek", "Ελληνικά"),+        SupertonicLanguage("es", "es-ES", "spa", "ESP", "Spanish", "Español"),+        SupertonicLanguage("et", "et-EE", "est", "EST", "Estonian", "Eesti"),+        SupertonicLanguage("fi", "fi-FI", "fin", "FIN", "Finnish", "Suomi"),+        SupertonicLanguage("fr", "fr-FR", "fra", "FRA", "French", "Français"),+        SupertonicLanguage("hi", "hi-IN", "hin", "IND", "Hindi", "हिन्दी"),+        SupertonicLanguage("hr", "hr-HR", "hrv", "HRV", "Croatian", "Hrvatski"),+        SupertonicLanguage("hu", "hu-HU", "hun", "HUN", "Hungarian", "Magyar"),+        SupertonicLanguage("id", "id-ID", "ind", "IDN", "Indonesian", "Bahasa Indonesia"),+        SupertonicLanguage("it", "it-IT", "ita", "ITA", "Italian", "Italiano"),+        SupertonicLanguage("ja", "ja-JP", "jpn", "JPN", "Japanese", "日本語"),+        SupertonicLanguage("ko", "ko-KR", "kor", "KOR", "Korean", "한국어"),+        SupertonicLanguage("lt", "lt-LT", "lit", "LTU", "Lithuanian", "Lietuvių"),+        SupertonicLanguage("lv", "lv-LV", "lav", "LVA", "Latvian", "Latviešu"),+        SupertonicLanguage("nl", "nl-NL", "nld", "NLD", "Dutch", "Nederlands"),+        SupertonicLanguage("pl", "pl-PL", "pol", "POL", "Polish", "Polski"),+        SupertonicLanguage("pt", "pt-BR", "por", "BRA", "Portuguese", "Português"),+        SupertonicLanguage("ro", "ro-RO", "ron", "ROU", "Romanian", "Română"),+        SupertonicLanguage("ru", "ru-RU", "rus", "RUS", "Russian", "Русский"),+        SupertonicLanguage("sk", "sk-SK", "slk", "SVK", "Slovak", "Slovenčina"),+        SupertonicLanguage("sl", "sl-SI", "slv", "SVN", "Slovenian", "Slovenščina"),+        SupertonicLanguage("sv", "sv-SE", "swe", "SWE", "Swedish", "Svenska"),+        SupertonicLanguage("tr", "tr-TR", "tur", "TUR", "Turkish", "Türkçe"),+        SupertonicLanguage("uk", "uk-UA", "ukr", "UKR", "Ukrainian", "Українська"),+        SupertonicLanguage("vi", "vi-VN", "vie", "VNM", "Vietnamese", "Tiếng Việt"),+    )++    /** English, used whenever a request names no language we recognise. */+    val DEFAULT: SupertonicLanguage = ALL.first()++    /**+     * The ten voice styles in the bundle, five female and five male.+     *+     * These are `style_<name>.bin` filenames, so the list has to match what+     * `scripts/ml/supertonic_bundle.py` wrote into `assets/supertonic/`. A name that is not there+     * fails at load with the asset's own error rather than silently falling back, which is what+     * makes a typo here visible.+     */+    val VOICES: List<String> = listOf("F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5")++    /** The voice used when a request names none. */+    const val DEFAULT_VOICE = "F1"++    /**+     * The `-x-` marker separating a BCP-47 tag from a voice style in a+     * [android.speech.tts.Voice] name, as in `en-US-x-F1`.+     *+     * BCP-47's private-use subtag is the only place a name may carry something the standard does+     * not define, and the framework passes voice names through verbatim, so this is how a caller+     * asks for a specific voice rather than just a language.+     */+    private const val VOICE_MARK = "-x-"++    private val byCodeMap = ALL.associateBy { it.code }+    private val byBcp47Map = ALL.associateBy { it.bcp47.lowercase() }+    private val byIso3Map = ALL.associateBy { it.iso3 }++    fun byCode(code: String): SupertonicLanguage? = byCodeMap[code.lowercase()]++    fun byBcp47(tag: String): SupertonicLanguage? = byBcp47Map[tag.lowercase().replace('_', '-')]++    fun byIso3(iso3: String): SupertonicLanguage? = byIso3Map[iso3.lowercase()]++    /** The voice name this engine advertises for `language` spoken by `voice`. */+    fun voiceName(language: SupertonicLanguage, voice: String): String =+        "${language.bcp47}$VOICE_MARK$voice"++    /**+     * The voice style named in `voiceName`, or null if it names none or names one we do not have.+     *+     * Case-insensitive, because the framework round-trips voice names through settings storage and+     * has been observed to lower-case them.+     */+    fun styleIn(voiceName: String?): String? {+        val at = voiceName?.indexOf(VOICE_MARK) ?: return null+        if (at < 0) return null+        val named = voiceName.substring(at + VOICE_MARK.length)+        return VOICES.firstOrNull { it.equals(named, ignoreCase = true) }+    }++    /**+     * The language a request is asking for, from whichever of the four spellings it used.+     *+     * `voiceName` wins over `lang`, because a caller that named a voice was more specific than one+     * that named a language. Within each, the order is most specific first: a full tag, then a+     * three-letter code, then a two-letter one, then the language half of a tag we do not have the+     * region of — `pt-PT` resolves to the `pt-BR` voice rather than to nothing, which is the right+     * answer given there is one Portuguese voice.+     *+     * Null only when nothing in the request names a language we have. Callers treat that as+     * "unsupported" rather than falling back to [DEFAULT], so a request for Thai is answered+     * honestly instead of being read aloud in English.+     */+    fun resolve(+        lang: String? = null,+        country: String? = null,+        variant: String? = null,+        voiceName: String? = null,+    ): SupertonicLanguage? {+        voiceName?.let { name ->+            // Strip a voice style first: `en-US-x-F1` is a request for English, and the style is+            // read separately by `styleIn`.+            val tag = name.substringBefore(VOICE_MARK)+            byBcp47(tag)?.let { return it }+            fromParts(tag)?.let { return it }+        }+        if (lang.isNullOrEmpty()) return null+        // The framework passes language, country and variant separately, and a tag is the three+        // joined — so try the joined form before the parts, or `en` + `US` would resolve by the+        // two-letter code and lose the region.+        val joined = listOfNotNull(+            lang,+            country?.takeIf { it.isNotEmpty() },+            variant?.takeIf { it.isNotEmpty() },+        ).joinToString("-")+        byBcp47(joined)?.let { return it }+        return fromParts(lang)+    }++    /** A tag or code in any of the accepted spellings, ignoring any region it carries. */+    private fun fromParts(tag: String): SupertonicLanguage? {+        byBcp47(tag)?.let { return it }+        val head = tag.replace('_', '-').substringBefore('-')+        return when (head.length) {+            2 -> byCode(head)+            3 -> byIso3(head)+            else -> null+        }+    }+}
speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt b/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.ktnew file mode 100644index 0000000000..17888e6068--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt@@ -0,0 +1,183 @@+package com.vayunmathur.speech.platform++import android.content.Context+import android.util.Log+import com.vayunmathur.library.ml.SupertonicSynthesizer+import com.vayunmathur.speech.domain.SupertonicVoices++/**+ * The one Supertonic handle the TTS service speaks through.+ *+ * Replaced `PiperEngine`, which kept an access-ordered LRU of two `PiperSynthesizer`s because a+ * Piper voice *was* a set of networks — changing language meant closing one 80 MB model and+ * opening another. Supertonic has one set of networks for all 31 languages, and a voice is two+ * small style tensors, so there is one handle for the life of the service and switching voices+ * uploads nothing. That is what deleted the cache, the eviction, the per-voice sample rates and+ * the directory resolution along with it.+ *+ * # Threading+ *+ * [SupertonicSynthesizer] is not thread-safe, so every call here is synchronised on this object.+ * `TextToSpeechService` serialises `onSynthesizeText` itself, but [preload] runs on a background+ * thread from `onCreate` and [close] arrives from `onDestroy`, so the three can overlap.+ */+class SupertonicEngine(private val context: Context) {+    private val lock = Any()+    private var synthesizer: SupertonicSynthesizer? = null+    private var loaded: SupertonicSynthesizer? = null+    private var voice: String = SupertonicVoices.DEFAULT_VOICE++    /** Supertonic's output rate, fixed by the vocoder rather than by the voice. */+    val sampleRate: Int get() = SupertonicSynthesizer.SAMPLE_RATE++    /**+     * Bring the four networks up, returning whether they came up. Idempotent and cheap after the+     * first call, so the service can call it on every utterance as well as warming it at startup.+     *+     * Slow the first time: ~105 MB of weights are streamed out of the APK into GPU memory, and four+     * command buffers are recorded. That is why `onCreate` warms it off the main thread.+     */+    fun preload(): Boolean = synchronized(lock) { ensure() != null }++    /**+     * Switch to `style`, returning whether it took.+     *+     * A 25 KB read and an input swap, not a reload, so this is safe to call per utterance. An+     * unknown style is refused rather than ignored: silently reading every voice in `F1` would be+     * indistinguishable from the voice picker not working.+     */+    fun voice(style: String): Boolean = synchronized(lock) {+        if (style !in SupertonicVoices.VOICES) return false+        if (style == voice) return ensure() != null+        val engine = ensure() ?: return false+        if (!engine.voice(style)) return false+        voice = style+        true+    }++    /**+     * Synthesise `text` and hand the samples to `onChunk` in pieces, stopping early if it returns+     * false.+     *+     * Chunked rather than returned whole because the framework wants audio as it is produced and a+     * paragraph of 44.1 kHz mono is megabytes. The whole utterance is synthesised before the first+     * chunk is delivered — Supertonic's sampler is one pass over the entire sequence, so there is no+     * streaming to be had inside it — so this splits the finished waveform rather than pipelining.+     *+     * There is no `speed`: [SupertonicSynthesizer.synthesize] takes none, and the only ways to fake+     * one on the host are to resample the PCM, which shifts the pitch, or to time-stretch it, which+     * is a signal-processing feature rather than part of a port. Rate control therefore does not+     * work in this engine; changing it in the system settings has no effect. Doing it properly means+     * scaling the duration predictor's frame count natively, which is where Piper's `length_scale`+     * did it too.+     */+    fun synthesize(text: String, onChunk: (FloatArray) -> Boolean): Boolean = synchronized(lock) {+        val engine = ensure() ?: return false+        val samples = try {+            engine.synthesize(text)+        } catch (e: Throwable) {+            Log.e(TAG, "synthesis failed", e)+            return false+        }+        if (samples.isEmpty()) return false+        var offset = 0+        while (offset < samples.size) {+            val n = minOf(CHUNK_SAMPLES, samples.size - offset)+            if (!onChunk(samples.copyOfRange(offset, offset + n))) return false+            offset += n+        }+        true+    }++    /** Free the four networks. Idempotent. */+    fun close() = synchronized(lock) {+        synthesizer?.close()+        synthesizer = null+        loaded = null+    }++    /**+     * The handle, built on first use.+     *+     * A failure is not retried: `SupertonicSynthesizer`'s constructor never throws, and the reasons+     * it can come up unavailable — no `libmodelrunner.so` for this ABI, no Vulkan device with fp16+     * compute, a missing asset — are all properties of the install rather than transient. Retrying+     * would re-read the bundle on every utterance to fail the same way.+     */+    private fun ensure(): SupertonicSynthesizer? {+        loaded?.let { return it }+        if (synthesizer != null) return null+        val built = SupertonicSynthesizer.inAssets(context.assets, voice = voice)+        synthesizer = built+        if (!built.isAvailable) {+            Log.e(TAG, "the Supertonic bundle is not usable on this device")+            return null+        }+        loaded = built+        return built+    }++    private companion object {+        const val TAG = "SupertonicEngine"++        /**+         * Samples per chunk handed to the callback.+         *+         * The service splits these again against `SynthesisCallback.maxBufferSize`, which is what+         * actually bounds a write, so this only decides how much PCM is converted at a time. 4,096+         * floats is 8 KB of PCM16 and 93 ms of audio at 44.1 kHz.+         */+        const val CHUNK_SAMPLES = 4096+    }+}++/**+ * Whether the Supertonic bundle is in the APK, without bringing up a GPU or reading a weight.+ *+ * This is what became of `PiperVoiceRegistry.isExtracted`. That answered a *per-language* question+ * — is this voice's 80 MB on disk — and six of the eleven `TextToSpeechService` overrides consulted+ * it, which is most of what made that service as long as it was. One bundle serves all 31 languages+ * now, so the question has one answer for the whole install, and it collapses to this.+ *+ * It is still worth asking rather than assuming true. The bundle is ~105 MB of assets, and an+ * install that somehow lacks it should advertise no languages at all rather than advertise 31 and+ * fail on the first utterance — a TTS engine that is selectable but silent has no error surface+ * anywhere the user can see.+ *+ * Cheap: `AssetManager.list` on one directory, no asset opened. Cached, because the answer cannot+ * change while the process lives.+ */+object SupertonicBundle {+    @Volatile private var present: Boolean? = null++    fun isPresent(context: Context): Boolean {+        present?.let { return it }+        val found = try {+            val entries = context.assets.list(SupertonicSynthesizer.ASSET_PATH)?.toSet().orEmpty()+            REQUIRED.all { it in entries }+        } catch (e: Throwable) {+            Log.e(TAG, "cannot list the Supertonic assets", e)+            false+        }+        present = found+        return found+    }++    private const val TAG = "SupertonicBundle"++    /**+     * The four plans, the codepoint table and the default voice.+     *+     * The other nine voices are not required: a bundle missing one of those loses a voice, while a+     * bundle missing a plan cannot speak at all, and only the second should stop the engine being+     * advertised.+     */+    private val REQUIRED = listOf(+        "supertonic_dp.maml",+        "supertonic_ttl.maml",+        "supertonic_ve.maml",+        "supertonic_voc.maml",+        "unicode_indexer.bin",+        SupertonicSynthesizer.styleName(SupertonicVoices.DEFAULT_VOICE),+    )+}
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.ktdeleted file mode 100644index afec2c9922..0000000000--- a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt+++ /dev/null@@ -1,371 +0,0 @@-package com.vayunmathur.speech.service--import android.media.AudioFormat-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 com.vayunmathur.speech.util.PiperVoiceDef-import com.vayunmathur.speech.util.PiperVoiceRegistry-import java.util.Locale-import kotlin.math.roundToInt--/**- * System text-to-speech engine backed by offline **Piper (VITS)** running on the Vulkan- * compute runtime in `:library:ml`. Once selected as the device's TTS engine, any app- * that uses [android.speech.tts.TextToSpeech] (Translate's read-aloud, TalkBack,- * ebook readers, ...) synthesizes fully on-device.- *- * Originally English-only (`en-US` Amy medium, 22050 Hz). After the multilingual- * expansion we advertise only the voices that are actually extracted on disk under- * `getExternalFilesDir()/piper/voices/<bcp47>/<id>/`, e.g. `de-DE`, `fr-FR`, etc.- * Each voice's sample rate comes from its `config.json` — all high quality 22.05 kHz- * now (previously 16 kHz low) — so [onSynthesizeText] starts the callback at the correct hz.- *- * The Settings Play button is enabled only if:- *   isLanguageAvailable >= LANG_AVAILABLE AND getDefaultVoiceNameFor returns a- *   non-empty name that exists in getVoices().- */-class PiperTtsService : TextToSpeechService() {--    private val engine by lazy { PiperEngine(applicationContext) }--    @Volatile private var stopped = false-    @Volatile private var currentVoiceId: String = PiperVoiceRegistry.DEFAULT.id--    override fun onCreate() {-        super.onCreate()-        // Warm default voice off main thread so first utterance doesn't stall.-        Thread {-            try {-                PiperVoiceRegistry.migrateLegacyIfNeeded(applicationContext)-            } catch (_: Throwable) {}-            engine.preload()-        }.start()-    }--    override fun onDestroy() {-        engine.closeAll()-        super.onDestroy()-    }--    // --- Language availability: dynamic over installed voices -----    private fun resolveDef(-        lang: String?,-        country: String? = null,-        variant: String? = null,-        voiceName: String? = null,-    ): PiperVoiceDef? {-        return PiperVoiceRegistry.resolve(lang, country, variant, voiceName)-    }--    private fun isInstalled(def: PiperVoiceDef): Boolean {-        return try {-            PiperVoiceRegistry.isExtracted(applicationContext, def) ||-                (def.code == "en" && PiperModel.isExtracted(applicationContext))-        } catch (_: Throwable) {-            false-        }-    }--    override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int {-        val def = resolveDef(lang, country, variant) ?: return TextToSpeech.LANG_NOT_SUPPORTED-        // Only advertise installed voices — uninstalled langs would show a disabled-        // Play button in Settings. Returning LANG_NOT_SUPPORTED hides them.-        if (!isInstalled(def)) return TextToSpeech.LANG_NOT_SUPPORTED--        val hasCountry = !country.isNullOrEmpty()-        val hasVariant = !variant.isNullOrEmpty()-        return when {-            hasCountry && hasVariant -> TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE-            hasCountry -> TextToSpeech.LANG_COUNTRY_AVAILABLE-            else -> TextToSpeech.LANG_AVAILABLE-        }-    }--    override fun onLoadLanguage(lang: String?, country: String?, variant: String?): Int {-        val code = onIsLanguageAvailable(lang, country, variant)-        if (code != TextToSpeech.LANG_NOT_SUPPORTED) {-            resolveDef(lang, country, variant)?.let { def ->-                currentVoiceId = def.id-            }-        }-        return code-    }--    override fun onGetLanguage(): Array<String> {-        // Return current voice's ISO3 triple, fallback eng-USA for legacy callers.-        return try {-            val def = PiperVoiceRegistry.byId(currentVoiceId) ?: PiperVoiceRegistry.DEFAULT-            if (isInstalled(def)) {-                arrayOf(def.iso3, def.iso3Country, "")-            } else {-                // Try first installed-                val installed = PiperVoiceRegistry.installedDefs(applicationContext)-                if (installed.isNotEmpty()) {-                    arrayOf(installed[0].iso3, installed[0].iso3Country, "")-                } else {-                    arrayOf("eng", "USA", "")-                }-            }-        } catch (_: Throwable) {-            arrayOf("eng", "USA", "")-        }-    }--    override fun onGetDefaultVoiceNameFor(lang: String?, country: String?, variant: String?): String? {-        if (lang == null && country == null && variant == null) {-            // Framework probe without args — return first installed as BCP47.-            val installed = try {-                PiperVoiceRegistry.installedDefs(applicationContext)-            } catch (_: Throwable) {-                emptyList()-            }-            if (installed.isNotEmpty()) return installed[0].bcp47-            if (PiperModel.isExtracted(applicationContext)) return "en-US"-            return null-        }-        val avail = onIsLanguageAvailable(lang, country, variant)-        if (avail == TextToSpeech.LANG_NOT_SUPPORTED) return null-        val def = resolveDef(lang, country, variant) ?: return null-        if (!isInstalled(def)) return null-        // Must match a Voice name from onGetVoices() — return BCP47 tag.-        return def.bcp47-    }--    override fun onIsValidVoiceName(voiceName: String?): Int {-        if (voiceName == null) return TextToSpeech.ERROR-        // Accept if any installed def matches via smart resolver.-        val def = resolveDef(voiceName = voiceName, lang = voiceName)-        if (def != null && isInstalled(def)) return TextToSpeech.SUCCESS--        // Legacy accept: eng-USA, en-US, any installed BCP47 case-insensitive, en-us-x-*-        val installed = try {-            PiperVoiceRegistry.installedDefs(applicationContext)-        } catch (_: Throwable) {-            emptyList()-        }-        for (d in installed) {-            if (voiceName.equals(d.bcp47, ignoreCase = true)) return TextToSpeech.SUCCESS-            if (voiceName.equals("${d.iso3}-${d.iso3Country}", ignoreCase = true)) return TextToSpeech.SUCCESS-            if (voiceName.equals(d.id, ignoreCase = true)) return TextToSpeech.SUCCESS-            if (voiceName.lowercase().startsWith(d.code.lowercase() + "-") ||-                voiceName.lowercase().startsWith(d.code.lowercase() + "_")-            ) return TextToSpeech.SUCCESS-        }-        // Also accept legacy English tags even if only legacy dir present-        if (voiceName.equals("en-US", ignoreCase = true) ||-            voiceName.equals("eng-USA", ignoreCase = true) ||-            voiceName.lowercase().startsWith("en-") ||-            voiceName.lowercase().startsWith("en_") ||-            voiceName.equals("en", ignoreCase = true)-        ) {-            if (PiperModel.isExtracted(applicationContext) ||-                PiperVoiceRegistry.isExtracted(applicationContext, PiperVoiceRegistry.DEFAULT)-            ) {-                return TextToSpeech.SUCCESS-            }-        }--        return try {-            super.onIsValidVoiceName(voiceName)-        } catch (_: Throwable) {-            TextToSpeech.ERROR-        }-    }--    override fun onLoadVoice(voiceName: String?): Int {-        if (voiceName == null) return TextToSpeech.ERROR-        val def = resolveDef(voiceName = voiceName, lang = voiceName)-        if (def != null && isInstalled(def)) {-            currentVoiceId = def.id-            return TextToSpeech.SUCCESS-        }-        // Check legacy english-        if (voiceName.equals("en-US", ignoreCase = true) ||-            voiceName.equals("eng-USA", ignoreCase = true) ||-            voiceName.lowercase().startsWith("en")-        ) {-            if (PiperModel.isExtracted(applicationContext) ||-                PiperVoiceRegistry.isExtracted(applicationContext, PiperVoiceRegistry.DEFAULT)-            ) {-                currentVoiceId = PiperVoiceRegistry.DEFAULT.id-                return TextToSpeech.SUCCESS-            }-        }-        return onIsValidVoiceName(voiceName)-    }--    override fun onGetVoices(): MutableList<Voice> {-        val ctx = applicationContext-        val installed = try {-            PiperVoiceRegistry.installedDefs(ctx).let { defs ->-                if (defs.isEmpty() && PiperModel.isExtracted(ctx)) {-                    listOf(PiperVoiceRegistry.DEFAULT)-                } else {-                    defs-                }-            }-        } catch (_: Throwable) {-            emptyList()-        }-        if (installed.isEmpty()) return mutableListOf()--        val voices = mutableListOf<Voice>()--        for (def in installed) {-            val locale = try {-                Locale.forLanguageTag(def.bcp47)-            } catch (_: Throwable) {-                Locale(def.code, def.iso3Country.take(2))-            }--            // Primary: BCP-47 tag with extension carrying voice id so clients can-            // distinguish multiple voices for same language if ever needed.-            // Name format "<bcp47>-x-<id>" e.g. "en-US-x-en_US-amy-medium"-            val primaryName = "${def.bcp47}-x-${def.id}"-            voices += Voice(-                primaryName,-                locale,-                Voice.QUALITY_VERY_HIGH,-                Voice.LATENCY_NORMAL,-                false,-                emptySet(),-            )-            // Also publish plain BCP-47 for easy selection ("de-DE")-            if (def.bcp47 != primaryName) {-                voices += Voice(-                    def.bcp47,-                    locale,-                    Voice.QUALITY_VERY_HIGH,-                    Voice.LATENCY_NORMAL,-                    false,-                    emptySet(),-                )-            }-            // ISO3 variant for CHECK_TTS_DATA compat ("deu-DEU")-            val iso3Name = "${def.iso3}-${def.iso3Country}"-            voices += Voice(-                iso3Name,-                Locale(def.code, def.iso3Country.take(2)),-                Voice.QUALITY_VERY_HIGH,-                Voice.LATENCY_NORMAL,-                false,-                emptySet(),-            )-        }--        // Backward compat: for EN also publish "en-US" and "eng-USA" without x- extension-        // so older framework probes that expect exactly those names still enable Play.-        if (installed.any { it.code == "en" }) {-            val enLocale = Locale.US-            val enLegacy = Locale.US-            if (voices.none { it.name == "en-US" }) {-                voices += Voice(-                    "en-US",-                    enLocale,-                    Voice.QUALITY_VERY_HIGH,-                    Voice.LATENCY_NORMAL,-                    false,-                    emptySet(),-                )-            }-            if (voices.none { it.name == "eng-USA" }) {-                voices += Voice(-                    "eng-USA",-                    enLegacy,-                    Voice.QUALITY_VERY_HIGH,-                    Voice.LATENCY_NORMAL,-                    false,-                    emptySet(),-                )-            }-        }--        return voices-    }--    override fun onStop() {-        stopped = true-    }--    override fun onSynthesizeText(request: SynthesisRequest, callback: SynthesisCallback) {-        stopped = false-        val text = request.charSequenceText?.toString().orEmpty()--        // Resolve voice from request params: voiceName has priority, then language.-        val voiceName = request.voiceName--        val resolvedDef = resolveDef(-            lang = request.language,-            country = request.country,-            variant = request.variant,-            voiceName = voiceName,-        ) ?: run {-            // Fallback to current voice id-            PiperVoiceRegistry.byId(currentVoiceId) ?: PiperVoiceRegistry.DEFAULT-        }--        // Update current voice id so subsequent calls without explicit voice keep using it.-        if (isInstalled(resolvedDef)) {-            currentVoiceId = resolvedDef.id-        }--        if (!engine.preload(currentVoiceId)) {-            callback.error()-            return-        }-        val sampleRate = engine.sampleRate(currentVoiceId).let { sr ->-            if (sr <= 0) resolvedDef.sampleRate else sr-        }-        if (sampleRate <= 0) {-            callback.error()-            return-        }-        if (text.isBlank()) {-            callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1)-            callback.done()-            return-        }--        val speed = (request.speechRate / 100f).coerceIn(0.3f, 3.0f)--        if (callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1) != TextToSpeech.SUCCESS) {-            return-        }--        val maxBytes = callback.maxBufferSize-        val ok = engine.synthesize(text, currentVoiceId, speed) { samples ->-            if (stopped) return@synthesize false-            val pcm = floatsToPcm16(samples)-            var offset = 0-            while (offset < pcm.size) {-                if (stopped) return@synthesize false-                val n = minOf(maxBytes, pcm.size - offset)-                if (callback.audioAvailable(pcm, offset, n) != TextToSpeech.SUCCESS) {-                    return@synthesize false-                }-                offset += n-            }-            true-        }--        if (ok || stopped) callback.done() else callback.error()-    }--    /** Convert Piper's float samples ([-1, 1]) to little-endian 16-bit PCM bytes. */-    private fun floatsToPcm16(samples: FloatArray): ByteArray {-        val out = ByteArray(samples.size * 2)-        var i = 0-        for (s in samples) {-            val v = (s.coerceIn(-1f, 1f) * 32767f).roundToInt()-            out[i++] = (v and 0xFF).toByte()-            out[i++] = ((v shr 8) and 0xFF).toByte()-        }-        return out-    }-}
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.ktnew file mode 100644index 0000000000..8ffee3ba47--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt@@ -0,0 +1,222 @@+package com.vayunmathur.speech.service++import android.media.AudioFormat+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.domain.SupertonicLanguage+import com.vayunmathur.speech.domain.SupertonicVoices+import com.vayunmathur.speech.platform.SupertonicBundle+import com.vayunmathur.speech.platform.SupertonicEngine+import java.util.Locale+import kotlin.math.roundToInt++/**+ * System text-to-speech engine backed by offline **Supertonic 3** running on the Vulkan compute+ * runtime in `:library:ml`. Once selected as the device's TTS engine, any app that uses+ * [android.speech.tts.TextToSpeech] — Translate's read-aloud, TalkBack, ebook readers — synthesises+ * fully on-device.+ *+ * # What bundling removed from this service+ *+ * The Piper version of this file asked "is this language installed?" in six of its eleven overrides,+ * because a Piper voice was an 80 MB download that might or might not be on disk. The answer varied+ * per language, per install and over time, so every override had to cope: `onGetVoices` published+ * only extracted voices, `onIsLanguageAvailable` hid the rest, and a legacy English path was+ * threaded through all of them for installs predating the multilingual registry.+ *+ * One bundle in the APK serves all 31 languages, so that question has one answer for the whole+ * install — [SupertonicBundle.isPresent] — and everything downstream of it became unconditional.+ *+ * # Two things a caller will notice+ *+ * * **44,100 Hz, always.** Piper's rate was per-voice, read from each `config.json`; Supertonic's is+ *   fixed by the vocoder. That doubles the PCM byte volume against Piper's 22,050, which is why+ *   [onSynthesizeText] splits every chunk against [SynthesisCallback.maxBufferSize] rather than+ *   trusting one to fit.+ * * **The speech rate is ignored.** See [SupertonicEngine.synthesize] for why.+ */+class SupertonicTtsService : TextToSpeechService() {++    private val engine by lazy { SupertonicEngine(applicationContext) }++    @Volatile private var stopped = false+    @Volatile private var language: SupertonicLanguage = SupertonicVoices.DEFAULT+    @Volatile private var voice: String = SupertonicVoices.DEFAULT_VOICE++    override fun onCreate() {+        super.onCreate()+        // ~105 MB of weights to stream into GPU memory and four command buffers to record, so the+        // first utterance would otherwise stall for seconds.+        Thread { engine.preload() }.start()+    }++    override fun onDestroy() {+        engine.close()+        super.onDestroy()+    }++    /** Whether this install can speak at all. Constant for the life of the process. */+    private fun usable(): Boolean = SupertonicBundle.isPresent(applicationContext)++    override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int {+        if (!usable()) return TextToSpeech.LANG_NOT_SUPPORTED+        SupertonicVoices.resolve(lang, country, variant) ?: return TextToSpeech.LANG_NOT_SUPPORTED+        // The framework distinguishes how much of the request was honoured, and it decides whether+        // Settings offers a region picker. There is one voice per language here, so a request that+        // named a country got its country in the sense that matters.+        return when {+            !country.isNullOrEmpty() && !variant.isNullOrEmpty() ->+                TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE+            !country.isNullOrEmpty() -> TextToSpeech.LANG_COUNTRY_AVAILABLE+            else -> TextToSpeech.LANG_AVAILABLE+        }+    }++    override fun onLoadLanguage(lang: String?, country: String?, variant: String?): Int {+        val availability = onIsLanguageAvailable(lang, country, variant)+        if (availability != TextToSpeech.LANG_NOT_SUPPORTED) {+            SupertonicVoices.resolve(lang, country, variant)?.let { language = it }+        }+        return availability+    }++    override fun onGetLanguage(): Array<String> =+        arrayOf(language.iso3, language.iso3Country, "")++    override fun onGetDefaultVoiceNameFor(+        lang: String?,+        country: String?,+        variant: String?,+    ): String? {+        if (!usable()) return null+        // The framework probes with all three null to ask "what would you speak by default". It+        // then looks the answer up in `onGetVoices`, and a name that is not there leaves the Play+        // button in Settings doing nothing with no error anywhere, so both sides build the name+        // through `SupertonicVoices.voiceName`.+        if (lang == null && country == null && variant == null) {+            return SupertonicVoices.voiceName(SupertonicVoices.DEFAULT, SupertonicVoices.DEFAULT_VOICE)+        }+        val found = SupertonicVoices.resolve(lang, country, variant) ?: return null+        return SupertonicVoices.voiceName(found, SupertonicVoices.DEFAULT_VOICE)+    }++    override fun onIsValidVoiceName(voiceName: String?): Int {+        if (voiceName == null || !usable()) return TextToSpeech.ERROR+        val known = SupertonicVoices.resolve(voiceName = voiceName) != null+        return if (known) TextToSpeech.SUCCESS else TextToSpeech.ERROR+    }++    override fun onLoadVoice(voiceName: String?): Int {+        if (voiceName == null || !usable()) return TextToSpeech.ERROR+        val found = SupertonicVoices.resolve(voiceName = voiceName) ?: return TextToSpeech.ERROR+        language = found+        SupertonicVoices.styleIn(voiceName)?.let { voice = it }+        return TextToSpeech.SUCCESS+    }++    /**+     * Every language in all three name forms, plus one per voice style.+     *+     * Three forms because callers ask in three: the plain BCP-47 tag, the `iso3-ISO3COUNTRY` pair+     * that `CHECK_TTS_DATA` deals in, and the `-x-` form that names a specific voice. Publishing+     * fewer is what breaks Settings' Play button, since it enables it only when+     * [onGetDefaultVoiceNameFor]'s answer appears in this list.+     */+    override fun onGetVoices(): MutableList<Voice> {+        if (!usable()) return mutableListOf()+        val voices = mutableListOf<Voice>()+        for (found in SupertonicVoices.ALL) {+            val locale = localeFor(found)+            voices += voiceEntry(found.bcp47, locale)+            voices += voiceEntry("${found.iso3}-${found.iso3Country}", locale)+            for (style in SupertonicVoices.VOICES) {+                voices += voiceEntry(SupertonicVoices.voiceName(found, style), locale)+            }+        }+        return voices+    }++    override fun onStop() {+        stopped = true+    }++    override fun onSynthesizeText(request: SynthesisRequest, callback: SynthesisCallback) {+        stopped = false+        if (!usable()) {+            callback.error()+            return+        }+        SupertonicVoices.resolve(+            lang = request.language,+            country = request.country,+            variant = request.variant,+            voiceName = request.voiceName,+        )?.let { language = it }+        SupertonicVoices.styleIn(request.voiceName)?.let { voice = it }++        val rate = engine.sampleRate+        val text = request.charSequenceText?.toString().orEmpty()+        if (text.isBlank()) {+            // Still start and finish: a caller that queued an empty utterance is waiting for its+            // completion callback, and erroring would surface as a failure it did not cause.+            callback.start(rate, AudioFormat.ENCODING_PCM_16BIT, 1)+            callback.done()+            return+        }+        if (!engine.preload() || !engine.voice(voice)) {+            callback.error()+            return+        }+        if (callback.start(rate, AudioFormat.ENCODING_PCM_16BIT, 1) != TextToSpeech.SUCCESS) {+            return+        }++        val maxBytes = callback.maxBufferSize+        val ok = engine.synthesize(text) { samples ->+            if (stopped) return@synthesize false+            val pcm = floatsToPcm16(samples)+            var offset = 0+            while (offset < pcm.size) {+                if (stopped) return@synthesize false+                val n = minOf(maxBytes, pcm.size - offset)+                if (callback.audioAvailable(pcm, offset, n) != TextToSpeech.SUCCESS) {+                    return@synthesize false+                }+                offset += n+            }+            true+        }++        if (ok || stopped) callback.done() else callback.error()+    }++    private fun voiceEntry(name: String, locale: Locale): Voice = Voice(+        name,+        locale,+        Voice.QUALITY_VERY_HIGH,+        Voice.LATENCY_NORMAL,+        false,+        emptySet(),+    )++    private fun localeFor(found: SupertonicLanguage): Locale = try {+        Locale.forLanguageTag(found.bcp47)+    } catch (_: Throwable) {+        Locale(found.code)+    }++    /** Supertonic's float samples in `-1..1` as little-endian 16-bit PCM. */+    private fun floatsToPcm16(samples: FloatArray): ByteArray {+        val out = ByteArray(samples.size * 2)+        var i = 0+        for (sample in samples) {+            val value = (sample.coerceIn(-1f, 1f) * 32767f).roundToInt()+            out[i++] = (value and 0xFF).toByte()+            out[i++] = ((value shr 8) and 0xFF).toByte()+        }+        return out+    }+}
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 3fa61cb174..026572de65 100644--- a/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt@@ -4,85 +4,46 @@ import android.app.Activity import android.content.Intent import android.os.Bundle import android.speech.tts.TextToSpeech-import com.vayunmathur.speech.util.PiperModel-import com.vayunmathur.speech.util.PiperVoiceRegistry+import com.vayunmathur.speech.domain.SupertonicVoices+import com.vayunmathur.speech.platform.SupertonicBundle  /**- * 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.+ * 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.  *- * Must keep ISO3 format (e.g. `eng-USA`, `deu-DEU`) in EXTRA_AVAILABLE_VOICES.- * The Play button in Settings is enabled only if CHECK returns PASS and- * PiperTtsService.onGetVoices() contains voices matching BCP-47 and ISO3 variants,- * and onGetDefaultVoiceNameFor(null,null,null) returns a non-empty installed voice- * name. If any of those disagree, Play silently does nothing — this was the bug- * after registry renamed to generic IDs (en_US-high) while old dirs still existed- * as en_US-lessac-low.+ * The answer must be in the ISO-3 form — `eng-USA`, `deu-DEU` — and it must agree with+ * `SupertonicTtsService.onGetVoices`, which publishes the same pairs. If the two disagree, Settings'+ * Play button silently does nothing, with no error visible anywhere. That is why both sides build+ * the strings from [SupertonicVoices] rather than each spelling them out.+ *+ * # Why this is now a fixed answer+ *+ * With Piper this activity had real work to do: it migrated legacy voice directories, listed which+ * of 42 languages were extracted, and reported the rest as unavailable so Settings could offer them+ * as downloads. All 31 languages ship in the APK now, so either the bundle is there and every+ * language is available, or it is not and none is.  */ class CheckVoiceDataActivity : Activity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState) -        val available = ArrayList<String>()-        val unavailable = ArrayList<String>()--        try {-            // Ensure old low/medium -> high migration + removal of dup archives-            PiperVoiceRegistry.migrateLegacyIfNeeded(this)-            // Also allow old speaker-specific dirs to count as installed (via fallback-            // findAnyValidDirForBcp47) so Settings Play works on upgraded installs.-            val installed = PiperVoiceRegistry.installedDefs(this)-            if (installed.isNotEmpty()) {-                for (def in installed) {-                    val iso = "${def.iso3}-${def.iso3Country}"-                    if (!available.contains(iso)) {-                        available.add(iso)-                    }-                }-                // Report everything else as unavailable, de-duped.-                for (def in PiperVoiceRegistry.ALL) {-                    val iso = "${def.iso3}-${def.iso3Country}"-                    if (iso !in available && iso !in unavailable) {-                        // Only report as unavailable if not extracted-                        if (!PiperVoiceRegistry.isExtracted(this, def)) {-                            unavailable.add(iso)-                        }-                    }-                }-            } else {-                if (PiperModel.isExtracted(this)) {-                    available.add(VOICE)-                } else {-                    unavailable.add(VOICE)-                    for (def in PiperVoiceRegistry.ALL) {-                        val iso = "${def.iso3}-${def.iso3Country}"-                        if (def.code != "en" && iso !in unavailable && iso !in available) {-                            unavailable.add(iso)-                        }-                    }-                }-            }-        } catch (_: Throwable) {-            if (PiperModel.isExtracted(this)) {-                available.add(VOICE)-            } else {-                unavailable.add(VOICE)-            }-        }-+        val all = ArrayList(SupertonicVoices.ALL.map { "${it.iso3}-${it.iso3Country}" })+        val present = SupertonicBundle.isPresent(this)         val data = Intent().apply {-            putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available)-            putStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES, unavailable)+            putStringArrayListExtra(+                TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES,+                if (present) all else ArrayList(),+            )+            putStringArrayListExtra(+                TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES,+                if (present) ArrayList() else all,+            )         }         setResult(-            if (available.isNotEmpty()) TextToSpeech.Engine.CHECK_VOICE_DATA_PASS+            if (present) TextToSpeech.Engine.CHECK_VOICE_DATA_PASS             else TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL,             data,         )         finish()     }--    private companion object {-        const val VOICE = "eng-USA"-    } }
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.ktdeleted file mode 100644index dff4603b4d..0000000000--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt+++ /dev/null@@ -1,287 +0,0 @@-package com.vayunmathur.speech.util--import android.content.Context-import android.util.Log-import com.vayunmathur.library.ml.PiperConfig-import com.vayunmathur.library.ml.PiperSynthesizer-import org.json.JSONObject-import java.io.File--/**- * Wrapper around [PiperSynthesizer], which runs offline **Piper (VITS)** voices on the Vulkan- *- * compute runtime in `:library:ml`. The original implementation held a single ncnn `Vits`- * 22050 Hz) with a `loadFailed` latch. After the multilingual expansion we keep a- * bounded LRU cache (max 2 voices, ~50-100 MB per instance on arm64-v8a) keyed by- * [PiperVoiceDef.id] so switching languages doesn't pay a cold-load each time and- * RAM stays bounded.- *- * Multi-quality migration: old installs have dirs like `en_US-lessac-low` or- * `de_DE-thorsten-medium` while new registry uses generic `en_US-high`. [isExtracted]- * tolerates old ids via [PiperVoiceRegistry.findAnyValidDirForBcp47], so this wrapper- * must also be tolerant when resolving the actual dir for Vits loading – otherwise- * in-app play works but Settings play (which goes through- * [com.vayunmathur.speech.service.PiperTtsService]) fails.- *- * Not thread-safe beyond the `@Synchronized` methods; the TTS framework calls- * [com.vayunmathur.speech.service.PiperTtsService.onSynthesizeText] serially, so- * single-thread contract holds.- */-class PiperEngine(private val context: Context) {--    /** LRU cache: voice id -> loaded synthesiser, access-order for eviction. */-    private val cache = LinkedHashMap<String, PiperSynthesizer>(2, 0.75f, true)-    private val failed = mutableMapOf<String, Boolean>()--    fun preload(): Boolean = ensure()--    /** Load a specific language/code/id, e.g. "de" or "de-DE" or "en_US-high". */-    fun preload(code: String): Boolean = ensure(code)--    fun preloadAllInstalled(): Boolean = ensure(PiperVoiceRegistry.DEFAULT.id)--    /** Native sample rate of the default loaded voice (Hz); 0 if not loaded. */-    fun sampleRate(): Int {-        val defId = PiperVoiceRegistry.DEFAULT.id-        return cache[defId]?.sampleRate ?: cache.values.firstOrNull()?.sampleRate ?: 0-    }--    /** Sample rate of a specific loaded voice, 0 if not in cache. */-    fun sampleRate(voiceIdOrCode: String): Int {-        val def = resolveDef(voiceIdOrCode) ?: return 0-        return cache[def.id]?.sampleRate ?: 0-    }--    @Synchronized-    fun synthesize(text: String, speed: Float, onChunk: (FloatArray) -> Boolean): Boolean =-        synthesize(text, PiperVoiceRegistry.DEFAULT.id, speed, onChunk)--    @Synchronized-    fun synthesize(text: String, voiceIdOrCode: String, speed: Float, onChunk: (FloatArray) -> Boolean): Boolean {-        if (!ensure(voiceIdOrCode)) return false-        val def = resolveDef(voiceIdOrCode) ?: return false-        val engine = cache[def.id] ?: return false-        return try {-            val samples = engine.synthesize(text, speed)-            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) {-            Log.e(TAG, "synthesize failed for ${def.id}", t)-            false-        }-    }--    @Synchronized-    fun close() {-        closeAll()-    }--    @Synchronized-    fun close(voiceIdOrCode: String) {-        val def = resolveDef(voiceIdOrCode) ?: run {-            cache[voiceIdOrCode]?.let { v ->-                try { v.close() } catch (_: Throwable) {}-                cache.remove(voiceIdOrCode)-            }-            return-        }-        try {-            cache[def.id]?.close()-        } catch (_: Throwable) {-        }-        cache.remove(def.id)-    }--    @Synchronized-    fun closeAll() {-        for ((_, v) in cache) {-            try { v.close() } catch (_: Throwable) {}-        }-        cache.clear()-    }--    @Synchronized-    private fun ensure(): Boolean = ensure(PiperVoiceRegistry.DEFAULT.id)--    @Synchronized-    private fun ensure(voiceIdOrCode: String): Boolean {-        val def = resolveDef(voiceIdOrCode) ?: run {-            Log.d(TAG, "resolve failed for $voiceIdOrCode")-            return false-        }-        val id = def.id-        // Don't hard-fail on previously-failed cache entry – retry once after migration,-        // because registry IDs changed (en_US-lessac-low -> en_US-high) and old failed latch-        // would block Settings Play forever.-        if (failed[id] == true) {-            failed.remove(id)-        }--        if (cache.containsKey(id)) {-            cache[id]?.let { v -> cache[id] = v }-            return true-        }--        val extracted = PiperVoiceRegistry.isExtracted(context, def) ||-            (def.code == "en" && PiperModel.isExtracted(context))-        if (!extracted) return false--        return try {-            PiperVoiceRegistry.migrateLegacyIfNeeded(context)-            val dir = voiceDirForDef(def)-            if (!dir.isDirectory) {-                Log.e(TAG, "voice dir missing for $id resolved to $dir, code=$voiceIdOrCode")-                failed[id] = true-                return false-            }-            val engine = open(dir) ?: run {-                failed[id] = true-                return false-            }-            if (!engine.isAvailable) {-                Log.e(TAG, "the runtime could not load the voice in $dir for $id")-                try { engine.close() } catch (_: Throwable) {}-                failed[id] = true-                return false-            }-            if (cache.size >= MAX_CACHED) {-                val eldestKey = cache.keys.firstOrNull()-                eldestKey?.let { key ->-                    try { cache[key]?.close() } catch (_: Throwable) {}-                    cache.remove(key)-                    Log.d(TAG, "evicted $key (LRU)")-                }-            }-            cache[id] = engine-            true-        } catch (t: Throwable) {-            Log.e(TAG, "Piper load failed for $id (code=$voiceIdOrCode)", t)-            failed[id] = true-            false-        }-    }--    /**-     * Build a synthesiser from a voice directory.-     *-     * The bundle names its four networks `<voice>_{enc_p,dp,flow,dec}.maml`, so the prefix is-     * recovered from whichever encoder is present rather than reconstructed from the registry-     * id - the two have diverged before, which is what the `voiceDirForDef` fallbacks below-     * exist to survive.-     *-     * Returns null, having logged, when the directory is not a voice.-     */-    private fun open(dir: File): PiperSynthesizer? {-        val encoder = dir.listFiles()?.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) }-        if (encoder == null) {-            Log.e(TAG, "no *$ENCODER_SUFFIX in $dir")-            return null-        }-        val voice = encoder.name.removeSuffix(ENCODER_SUFFIX)-        val config = readConfig(dir) ?: return null-        if (config.second > 1) {-            // A multi-speaker voice also ships an `emb_g` network, which is not converted:-            // every voice in the registry is single-speaker. Loading one anyway would speak-            // in whichever voice the embedding defaulted to.-            Log.e(TAG, "$voice has ${config.second} speakers; only single-speaker voices run")-            return null-        }-        return PiperSynthesizer(dir, voice, config.first)-    }--    /**-     * The voice's sample rate, scales and speaker count from its `config.json`.-     *-     * The rate is not defaulted: a voice played at the wrong rate is intelligible but-     * wrongly pitched, which is worse than refusing to load it.-     */-    private fun readConfig(dir: File): Pair<PiperConfig, Int>? = try {-        val json = JSONObject(File(dir, "config.json").readText())-        val audio = json.optJSONObject("audio")-        val rate = audio?.optInt("sample_rate", 0) ?: 0-        if (rate <= 0) {-            Log.e(TAG, "config.json in $dir has no audio.sample_rate")-            return null-        }-        val inference = json.optJSONObject("inference")-        val config = PiperConfig(-            sampleRate = rate,-            noise = inference?.optDouble("noise_scale", 0.667)?.toFloat() ?: 0.667f,-            length = inference?.optDouble("length_scale", 1.0)?.toFloat() ?: 1.0f,-            durationNoise = inference?.optDouble("noise_w", 0.8)?.toFloat() ?: 0.8f,-        )-        config to json.optInt("num_speakers", 1)-    } catch (t: Throwable) {-        Log.e(TAG, "cannot read config.json in $dir", t)-        null-    }--    private fun resolveDef(voiceIdOrCode: String): PiperVoiceDef? {-        if (voiceIdOrCode.isBlank()) return PiperVoiceRegistry.DEFAULT-        PiperVoiceRegistry.resolve(-            lang = voiceIdOrCode,-            voiceName = voiceIdOrCode,-        )?.let { return it }-        PiperVoiceRegistry.byId(voiceIdOrCode)?.let { return it }-        PiperVoiceRegistry.byCode(voiceIdOrCode)?.let { return it }-        PiperVoiceRegistry.byBcp47(voiceIdOrCode)?.let { return it }-        PiperVoiceRegistry.byBcp47(voiceIdOrCode.replace('_', '-'))?.let { return it }-        PiperVoiceRegistry.byIso3(voiceIdOrCode)?.let { return it }-        if (voiceIdOrCode.length >= 2) {-            PiperVoiceRegistry.byCode(voiceIdOrCode.take(2))?.let { return it }-        }-        return null-    }--    private fun voiceDirForDef(def: PiperVoiceDef): File {-        val direct = PiperVoiceRegistry.voiceDir(context, def)-        if (direct.isDirectory) return direct-        // Tolerate old speaker-specific ids after rename to generic (e.g. en_US-lessac-low-        // dir present but registry now expects en_US-high). This makes Settings Play work-        // on upgraded installs.-        PiperVoiceRegistry.findAnyValidDirForBcp47(context, def.bcp47)?.let { return it }-        try {-            val vRoot = PiperVoiceRegistry.voicesDir(context)-            if (vRoot.isDirectory) {-                // Search same BCP-47 folder for any dir with encoder – last resort-                val bcpRoot = File(vRoot, def.bcp47)-                if (bcpRoot.isDirectory) {-                    bcpRoot.listFiles()?.firstOrNull { child ->-                        child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.maml") } == true-                    }?.let { return it }-                }-                // Broader search: any BCP-47 starting with code-                vRoot.listFiles()?.forEach { bcpDir ->-                    if (!bcpDir.isDirectory) return@forEach-                    if (!bcpDir.name.equals(def.bcp47, ignoreCase = true) &&-                        !bcpDir.name.lowercase().startsWith(def.code.lowercase())) return@forEach-                    bcpDir.listFiles()?.firstOrNull { child ->-                        child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.maml") } == true-                    }?.let { return it }-                }-            }-        } catch (_: Throwable) {}-        if (def.code == "en") {-            val legacy = PiperVoiceRegistry.legacyVoiceDir(context)-            if (legacy.isDirectory) return legacy-            val shim = PiperModel.voiceDir(context)-            if (shim.isDirectory) return shim-        }-        return direct-    }--    companion object {-        private const val TAG = "PiperEngine"-        private const val MAX_CACHED = 2--        /** How the bundle names the text encoder, and so how the voice prefix is found. */-        private const val ENCODER_SUFFIX = "_enc_p.maml"-    }-}
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.ktdeleted file mode 100644index 0057d77944..0000000000--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt+++ /dev/null@@ -1,137 +0,0 @@-package com.vayunmathur.speech.util--import android.content.Context-import android.util.Log-import com.vayunmathur.library.downloadservice.ModelDownloadItem-import com.vayunmathur.library.util.DataStoreUtils-import java.io.File--/**- * Backward-compat shim over [PiperVoiceRegistry]. The app previously had a single- * hard-coded voice `piper/voice` (Amy medium, voice3.zip, 22050 Hz, 125k dict).- *- * After multilingual expansion the canonical location is- * `piper/voices/<bcp47>/<id>/` (e.g. `piper/voices/en-US/en_US-amy-medium`).- * This object now delegates to the default English entry in the registry and runs- * legacy migration (rename `piper/voice` -> new path) so existing installs keep- * working without re-download.- *- * New code should use [PiperVoiceRegistry] directly. This shim remains for- * [com.vayunmathur.speech.service.PiperTtsService] and- * [com.vayunmathur.speech.tts.CheckVoiceDataActivity] during the transition and for- * any external callers that still reference `PiperModel`.- */-object PiperModel {-    const val DIR = PiperVoiceRegistry.DIR-    const val DICT = "en-word_id.bin"-    const val CONFIG = "config.json"--    private const val ENCODER_SUFFIX = "_enc_p.maml"-    private val REQUIRED_NETS = listOf("_enc_p", "_dp", "_flow", "_dec")-    private const val BASE = PiperVoiceRegistry.BASE-    const val REMOTE_ARCHIVE = PiperVoiceRegistry.LEGACY_REMOTE_ARCHIVE-    private const val ARCHIVE = PiperVoiceRegistry.LEGACY_ARCHIVE--    /** Single downloadable archive (deprecated alias) — use [PiperVoiceRegistry] for new voices. */-    val FILES: List<ModelDownloadItem> = listOf(-        ModelDownloadItem(-            "${BASE}${REMOTE_ARCHIVE}",-            ARCHIVE,-            "Piper voice (TTS)",-            "49a18080c2e97b066854d2a5360443275ef3041c7524fcc023b7efdcb063952c",-        ),-    )--    private fun rootDir(context: Context): File? =-        context.getExternalFilesDir(null) ?: context.filesDir--    private fun archive(context: Context): File {-        val root = rootDir(context) ?: return File(ARCHIVE)-        return File(root, ARCHIVE)-    }--    /** Extracted voice dir — now delegates to registry default en (+ legacy fallback). */-    fun voiceDir(context: Context): File {-        // Prefer new location if migrated; otherwise legacy.-        val newDir = PiperVoiceRegistry.voiceDir(context, PiperVoiceRegistry.DEFAULT)-        return if (newDir.isDirectory && PiperVoiceRegistry.isExtracted(context, PiperVoiceRegistry.DEFAULT)) {-            newDir-        } else {-            val legacy = PiperVoiceRegistry.legacyVoiceDir(context)-            if (legacy.isDirectory) legacy else newDir-        }-    }--    fun voicePrefix(context: Context): String? {-        val def = PiperVoiceRegistry.DEFAULT-        val prefix = PiperVoiceRegistry.voicePrefix(context, def)-        if (prefix != null) return prefix-        // Legacy fallback-        val files = PiperVoiceRegistry.legacyVoiceDir(context).listFiles() ?: return null-        val encoder = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return null-        return encoder.name.removeSuffix(ENCODER_SUFFIX)-    }--    /** True if default en voice is extracted (new or legacy location). */-    fun isExtracted(context: Context): Boolean {-        if (PiperVoiceRegistry.isExtracted(context, PiperVoiceRegistry.DEFAULT)) return true-        // Legacy dir check (forces migration eligibility)-        return PiperVoiceRegistry.let { registry ->-            try {-                val legacyDir = registry.legacyVoiceDir(context)-                if (!legacyDir.isDirectory) return@let false-                val files = legacyDir.listFiles() ?: return@let false-                if (files.any { it.name.endsWith(".onnx") }) return@let false-                val dictFile = File(legacyDir, DICT)-                if (dictFile.exists() && dictFile.length() < 1_000_000L) return@let false-                val enc = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return@let false-                val pref = enc.name.removeSuffix(ENCODER_SUFFIX)-                REQUIRED_NETS.all { net ->-                    File(legacyDir, "$pref$net.maml").exists()-                } && dictFile.exists() && File(legacyDir, CONFIG).exists()-            } catch (_: Throwable) {-                false-            }-        }-    }--    fun isReady(context: Context): Boolean {-        val dir = PiperVoiceRegistry.legacyVoiceDir(context)-        if (dir.isDirectory) {-            val legacy = dir.listFiles()?.any { it.name.endsWith(".onnx") } == true ||-                File(dir, "tokens.txt").exists() ||-                File(dir, "espeak-ng-data").isDirectory ||-                File(dir, DICT).let { it.exists() && it.length() < 1_000_000L }-            if (legacy) {-                Log.d(TAG, "deleting legacy/broken voice at $dir for migration to ncnn full dict")-                dir.deleteRecursively()-            }-        }-        // Migrate if needed so new path becomes truth.-        PiperVoiceRegistry.migrateLegacyIfNeeded(context)-        return PiperVoiceRegistry.isExtracted(context, PiperVoiceRegistry.DEFAULT) ||-            isExtracted(context)-    }--    suspend fun download(context: Context, ds: DataStoreUtils) {-        PiperVoiceRegistry.migrateLegacyIfNeeded(context)-        PiperVoiceRegistry.download(context, ds, listOf("en"))-    }--    fun progress(ds: DataStoreUtils): Float =-        PiperVoiceRegistry.progress(ds, PiperVoiceRegistry.DEFAULT)--    @Synchronized-    fun installIfNeeded(context: Context): Boolean {-        PiperVoiceRegistry.migrateLegacyIfNeeded(context)-        if (PiperVoiceRegistry.isExtracted(context, PiperVoiceRegistry.DEFAULT)) return true-        if (isExtracted(context) && PiperVoiceRegistry.legacyVoiceDir(context).isDirectory) {-            // Migrate legacy to new location-            PiperVoiceRegistry.migrateLegacyIfNeeded(context)-            if (PiperVoiceRegistry.isExtracted(context, PiperVoiceRegistry.DEFAULT)) return true-        }-        return PiperVoiceRegistry.installIfNeeded(context, PiperVoiceRegistry.DEFAULT)-    }--    private const val TAG = "PiperModel"-}
speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.ktdeleted file mode 100644index e69de29bb2..0000000000
speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.ktdeleted file mode 100644index f18786629a..0000000000--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt+++ /dev/null@@ -1,1117 +0,0 @@-package com.vayunmathur.speech.util--import android.content.Context-import android.util.Log-import com.vayunmathur.library.downloadservice.ModelDownloadItem-import com.vayunmathur.library.downloadservice.downloadModels-import com.vayunmathur.library.util.DataStoreUtils-import java.io.File-import java.util.zip.ZipInputStream--/**- * Multi-voice registry for offline **Piper (VITS)** TTS. Each voice is a directory tree- * fetched as a single `.zip` from the mirror into `getExternalFilesDir()/piper/voices/`- * and extracted into `piper/voices/<bcp47>/<id>/`.- *- * Per latest request: one voice per language, highest quality available (high 22 kHz > medium- * 22 kHz > low). Dist folder `dist/speech-mirror/piper/` is deduped to one zip per lang using- * same rule. All sample rates are 22050 Hz (previously 16 kHz low for en/ar/cs). Registry SHAs- * match `dist/speech-mirror/piper/sha256.json` after cleanup.- *- * If a high checkpoint exists upstream for a language missing high in dist (e.g. after- * `fetch_piper_model.sh <dir> ... high <lang>-high.zip`), rebuild that language to high and- * re-run dedup + hash step — registry will then be upgraded to high automatically.- *- * The original single-voice layout `piper/voice` (voice3.zip, Amy medium, 22050 Hz) is kept- * as legacy and migrated. On upgrade, old `-low.zip` / `-low` / `-medium` installs are cleaned- * via [cleanOldLowVariants] so storage doesn't double-count.- *- * Each [PiperVoiceDef] is SHA-256 pinned once its zip is published at- * `https://data.vayunmathur.com/models/piper/`.- */-data class PiperVoiceDef(-    /** HF-style id "<locale>-<speaker>-<quality>", e.g. "en_US-high". */-    val id: String,-    /** ISO-639-1 or broader code, e.g. "en", "zh". */-    val code: String,-    /** BCP-47 tag used for `Voice(name)` and `Locale.forLanguageTag`. */-    val bcp47: String,-    /** ISO-639-3, e.g. "eng", "deu". */-    val iso3: String,-    /** ISO-3166-1 alpha-3 country, e.g. "USA", "DEU". */-    val iso3Country: String,-    /** Native name, e.g. "Deutsch". */-    val nativeName: String,-    /** English name, e.g. "German". */-    val englishName: String,-    /** Remote archive name at BASE, e.g. "de-high.zip". */-    val remoteArchive: String,-    /** Dictionary file inside voice dir, e.g. "de-word_id.bin". */-    val dictFile: String,-    /** SHA-256 of remote archive, null until published. */-    val sha256: String?,-    /** Quality — highest available per language: high > medium > low. */-    val quality: String,-    /** Sample rate from config.json. */-    val sampleRate: Int,-    /** Estimated size badge in MB. */-    val sizeEstimateMb: Int,-    val speakerId: Int = 0,-    val isMultiSpeaker: Boolean = false,-)--object PiperVoiceRegistry {--    const val DIR = "piper"-    const val VOICES_ROOT = "piper/voices"-    const val LEGACY_VOICE_DIR = "piper/voice"-    const val LEGACY_ARCHIVE = "piper/voice.zip"-    const val LEGACY_REMOTE_ARCHIVE = "voice3.zip"-    const val BASE = "https://data.vayunmathur.com/models/piper/"--    private const val ENCODER_SUFFIX = "_enc_p.maml"-    private const val CONFIG = "config.json"-    private val REQUIRED_NETS = listOf("_enc_p", "_dp", "_flow", "_dec")--    /**-     * Full catalog: one voice per language, highest quality available (from local dist mirror).-     * Currently 2 high, 15 medium, 12 low = 29 langs (after dist dedup). SHA256 pinned from-     * `dist/speech-mirror/piper/sha256.json`. All 22050 Hz.-     */-    val ALL: List<PiperVoiceDef> = listOf(-        // --- high quality 22 kHz where built ----        PiperVoiceDef(-            id = "en_US-high",-            code = "en",-            bcp47 = "en-US",-            iso3 = "eng",-            iso3Country = "USA",-            nativeName = "English",-            englishName = "English",-            remoteArchive = "en-high.zip",-            dictFile = "en-word_id.bin",-            sha256 = "ec61d6fccf0d2920abd65bcf4edfd6a96d767eb38faa8f2de344b18dc222839d",-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 51,-        ),-        PiperVoiceDef(-            id = "de_DE-high",-            code = "de",-            bcp47 = "de-DE",-            iso3 = "deu",-            iso3Country = "DEU",-            nativeName = "Deutsch",-            englishName = "German",-            remoteArchive = "de-high.zip",-            dictFile = "de-word_id.bin",-            sha256 = "7cb8622a9f2668d6d33d94eaf4fcdda5278d4ba835a0b4e4c2bc0d0bdb535970",-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 51,-        ),-        // --- medium is highest available for these 15 langs (dup low deleted from dist) ----        PiperVoiceDef(-            id = "ar_JO-medium",-            code = "ar",-            bcp47 = "ar-SA",-            iso3 = "ara",-            iso3Country = "SAU",-            nativeName = "العربية",-            englishName = "Arabic",-            remoteArchive = "ar-medium.zip",-            dictFile = "ar-word_id.bin",-            sha256 = "e8a82c9940f41498cc08434194a871a33ca49df70470a1869f4898832d51a63c",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "bg_BG-medium",-            code = "bg",-            bcp47 = "bg-BG",-            iso3 = "bul",-            iso3Country = "BGR",-            nativeName = "Български",-            englishName = "Bulgarian",-            remoteArchive = "bg-medium.zip",-            dictFile = "bg-word_id.bin",-            sha256 = "324b06ad0c7c46d4adf175c1231c9494da1ef51dad7c9e542b0fed2477cbf525",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "ca_ES-medium",-            code = "ca",-            bcp47 = "ca-ES",-            iso3 = "cat",-            iso3Country = "ESP",-            nativeName = "Català",-            englishName = "Catalan",-            remoteArchive = "ca-medium.zip",-            dictFile = "ca-word_id.bin",-            sha256 = "3fc392eb49afa57a52cbcb9ac46470e4754d365e8bd4e4bef2919eb49b67d778",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "cs_CZ-medium",-            code = "cs",-            bcp47 = "cs-CZ",-            iso3 = "ces",-            iso3Country = "CZE",-            nativeName = "Čeština",-            englishName = "Czech",-            remoteArchive = "cs-medium.zip",-            dictFile = "cs-word_id.bin",-            sha256 = "9ed2977919c51d61f9fc87c7505952f9a33aa611637431dceab42f42945b8759",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "da_DK-medium",-            code = "da",-            bcp47 = "da-DK",-            iso3 = "dan",-            iso3Country = "DNK",-            nativeName = "Dansk",-            englishName = "Danish",-            remoteArchive = "da-medium.zip",-            dictFile = "da-word_id.bin",-            sha256 = "9c2f7e76b4d63733381046b5adb55ffb2625e12fb5ebddccfa306d0a7890d601",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "el_GR-medium",-            code = "el",-            bcp47 = "el-GR",-            iso3 = "ell",-            iso3Country = "GRC",-            nativeName = "Ελληνικά",-            englishName = "Greek",-            remoteArchive = "el-medium.zip",-            dictFile = "el-word_id.bin",-            sha256 = "246752cd4bd240f885e6768c1a37514913caa8dfaaf460e2b5bcdd86345d0696",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "fi_FI-medium",-            code = "fi",-            bcp47 = "fi-FI",-            iso3 = "fin",-            iso3Country = "FIN",-            nativeName = "Suomi",-            englishName = "Finnish",-            remoteArchive = "fi-medium.zip",-            dictFile = "fi-word_id.bin",-            sha256 = "911877ca09b3fb7ee234320ef29ca3837167bbf9be150606e238ffd070d772a6",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "hu_HU-medium",-            code = "hu",-            bcp47 = "hu-HU",-            iso3 = "hun",-            iso3Country = "HUN",-            nativeName = "Magyar",-            englishName = "Hungarian",-            remoteArchive = "hu-medium.zip",-            dictFile = "hu-word_id.bin",-            sha256 = "a2ae82ab596d9d186f319dcd8568d80afa9a9cd848c448cf646b2e8852f6910d",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "ka_GE-medium",-            code = "ka",-            bcp47 = "ka-GE",-            iso3 = "kat",-            iso3Country = "GEO",-            nativeName = "ქართული",-            englishName = "Georgian",-            remoteArchive = "ka-medium.zip",-            dictFile = "ka-word_id.bin",-            sha256 = "a578d418cb1021475453fc80386e851ef6f1dc7f59e687114ba992ee24957c74",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "lb_LU-medium",-            code = "lb",-            bcp47 = "lb-LU",-            iso3 = "ltz",-            iso3Country = "LUX",-            nativeName = "Lëtzebuergesch",-            englishName = "Luxembourgish",-            remoteArchive = "lb-medium.zip",-            dictFile = "lb-word_id.bin",-            sha256 = "9fab5c3999d445297104dc4ca33708124c7a4d5bd09496ebaa379ccc6ebd4cc3",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "ml_IN-medium",-            code = "ml",-            bcp47 = "ml-IN",-            iso3 = "mal",-            iso3Country = "IND",-            nativeName = "മലയാളം",-            englishName = "Malayalam",-            remoteArchive = "ml-medium.zip",-            dictFile = "ml-word_id.bin",-            sha256 = "a6f08fc134fe8efe78eca6da2508cc7b5b408768e9b917e4e4b82913f4f593a7",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "nb_NO-medium",-            code = "nb",-            bcp47 = "nb-NO",-            iso3 = "nob",-            iso3Country = "NOR",-            nativeName = "Norsk Bokmål",-            englishName = "Norwegian",-            remoteArchive = "nb-medium.zip",-            dictFile = "nb-word_id.bin",-            sha256 = "8eae59d616f14a9f4c2b2672f6389da6c8d543594253b6feefd6d76820bcec22",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "ne_NP-medium",-            code = "ne",-            bcp47 = "ne-NP",-            iso3 = "nep",-            iso3Country = "NPL",-            nativeName = "नेपाली",-            englishName = "Nepali",-            remoteArchive = "ne-medium.zip",-            dictFile = "ne-word_id.bin",-            sha256 = "7ae1acb07aba57b2d160f14780f14860e5c0dade28f9e3958bbd38002d4a75ce",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 35,-        ),-        PiperVoiceDef(-            id = "ro_RO-medium",-            code = "ro",-            bcp47 = "ro-RO",-            iso3 = "ron",-            iso3Country = "ROU",-            nativeName = "Română",-            englishName = "Romanian",-            remoteArchive = "ro-medium.zip",-            dictFile = "ro-word_id.bin",-            sha256 = "cbb257a1fb1c3a124048c03e67af0e467c4a5568d81a72fe886a7af569d42e35",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "sk_SK-medium",-            code = "sk",-            bcp47 = "sk-SK",-            iso3 = "slk",-            iso3Country = "SVK",-            nativeName = "Slovenčina",-            englishName = "Slovak",-            remoteArchive = "sk-medium.zip",-            dictFile = "sk-word_id.bin",-            sha256 = "82a1942fdb302e44f5246977e0f29ede00ae8c38ccca747f1f4c0361a231c3e3",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        // --- low is highest available for these 12 langs (only low built locally) ----        PiperVoiceDef(-            id = "es_ES-low",-            code = "es",-            bcp47 = "es-ES",-            iso3 = "spa",-            iso3Country = "ESP",-            nativeName = "Español",-            englishName = "Spanish",-            remoteArchive = "es-low.zip",-            dictFile = "es-word_id.bin",-            sha256 = "3a5d14ad7687e4ed71e93eec4e5373dad75cec6a97ed1e88e5247e15afb3aab5",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 34,-        ),-        PiperVoiceDef(-            id = "fr_FR-low",-            code = "fr",-            bcp47 = "fr-FR",-            iso3 = "fra",-            iso3Country = "FRA",-            nativeName = "Français",-            englishName = "French",-            remoteArchive = "fr-low.zip",-            dictFile = "fr-word_id.bin",-            sha256 = "ae372af01d6efd92c4ac0adb45f11db0f9ac24c571b46ace0aca050c34a9a7e5",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "pt_BR-low",-            code = "pt",-            bcp47 = "pt-BR",-            iso3 = "por",-            iso3Country = "BRA",-            nativeName = "Português",-            englishName = "Portuguese",-            remoteArchive = "pt-low.zip",-            dictFile = "pt-word_id.bin",-            sha256 = "07a93715c0ed4e6ea1351d4a98abdbf6a1c7bb97e45034ffee8ae9fad1e7d25c",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "nl_BE-low",-            code = "nl",-            bcp47 = "nl-NL",-            iso3 = "nld",-            iso3Country = "NLD",-            nativeName = "Nederlands",-            englishName = "Dutch",-            remoteArchive = "nl-low.zip",-            dictFile = "nl-word_id.bin",-            sha256 = "f7cfff1040cd325fadb1ec49476b77090877907a0eedffe5c5cde870737e5cba",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "ru_RU-low",-            code = "ru",-            bcp47 = "ru-RU",-            iso3 = "rus",-            iso3Country = "RUS",-            nativeName = "Русский",-            englishName = "Russian",-            remoteArchive = "ru-low.zip",-            dictFile = "ru-word_id.bin",-            sha256 = "7995a39b9a8e02c9840bd29d3d3e6ab1991bb26f5b85f674e47dadf4eca87b6e",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "pl_PL-low",-            code = "pl",-            bcp47 = "pl-PL",-            iso3 = "pol",-            iso3Country = "POL",-            nativeName = "Polski",-            englishName = "Polish",-            remoteArchive = "pl-low.zip",-            dictFile = "pl-word_id.bin",-            sha256 = "1d2f12113f76368f4c5e50c5c67c09c216d50077261dbafae3c6fdbb4b04714d",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "tr_TR-low",-            code = "tr",-            bcp47 = "tr-TR",-            iso3 = "tur",-            iso3Country = "TUR",-            nativeName = "Türkçe",-            englishName = "Turkish",-            remoteArchive = "tr-low.zip",-            dictFile = "tr-word_id.bin",-            sha256 = "3f7e36d044b37a4fe82579b991ae36c05dd7d2f9683bf7eb177d58d4de468f52",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "hi_IN-low",-            code = "hi",-            bcp47 = "hi-IN",-            iso3 = "hin",-            iso3Country = "IND",-            nativeName = "हिन्दी",-            englishName = "Hindi",-            remoteArchive = "hi-low.zip",-            dictFile = "hi-word_id.bin",-            sha256 = "92f1469eaee834e51ae6b6176c50a301ccf8322cd42c24b39842fb32a50442e9",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "zh_CN-low",-            code = "zh",-            bcp47 = "zh-CN",-            iso3 = "zho",-            iso3Country = "CHN",-            nativeName = "中文",-            englishName = "Chinese",-            remoteArchive = "zh-low.zip",-            dictFile = "zh-word_id.bin",-            sha256 = "64dfea77bd960093d122cb8e2cceac450e5ced0f34f074fb4fcf4d48a43df81e",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "vi_VN-low",-            code = "vi",-            bcp47 = "vi-VN",-            iso3 = "vie",-            iso3Country = "VNM",-            nativeName = "Tiếng Việt",-            englishName = "Vietnamese",-            remoteArchive = "vi-low.zip",-            dictFile = "vi-word_id.bin",-            sha256 = "4dc346df5e71b6f268456d4dc30e22f9928bb2e8d5a73aa80cee5a9f1b703938",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "id_ID-low",-            code = "id",-            bcp47 = "id-ID",-            iso3 = "ind",-            iso3Country = "IDN",-            nativeName = "Bahasa Indonesia",-            englishName = "Indonesian",-            remoteArchive = "id-low.zip",-            dictFile = "id-word_id.bin",-            sha256 = "39ea9531b7039c71c3e300e9ecbe14ecf2ba49ac67ec84988de4267c6b2a9fef",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 28,-        ),-        PiperVoiceDef(-            id = "uk_UA-low",-            code = "uk",-            bcp47 = "uk-UA",-            iso3 = "ukr",-            iso3Country = "UKR",-            nativeName = "Українська",-            englishName = "Ukrainian",-            remoteArchive = "uk-low.zip",-            dictFile = "uk-word_id.bin",-            sha256 = "efb9f61d6a32160c06c9a79fbba52561c85ad5590e823c07ada033592f0f2447",-            quality = "low",-            sampleRate = 22050,-            sizeEstimateMb = 34,-        ),-        // --- remaining high placeholders not yet built in dist (optional, keep for future) ----        PiperVoiceDef(-            id = "it_IT-high",-            code = "it",-            bcp47 = "it-IT",-            iso3 = "ita",-            iso3Country = "ITA",-            nativeName = "Italiano",-            englishName = "Italian",-            remoteArchive = "it-high.zip",-            dictFile = "it-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "ja_JP-high",-            code = "ja",-            bcp47 = "ja-JP",-            iso3 = "jpn",-            iso3Country = "JPN",-            nativeName = "日本語",-            englishName = "Japanese",-            remoteArchive = "ja-high.zip",-            dictFile = "ja-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "ko_KR-high",-            code = "ko",-            bcp47 = "ko-KR",-            iso3 = "kor",-            iso3Country = "KOR",-            nativeName = "한국어",-            englishName = "Korean",-            remoteArchive = "ko-high.zip",-            dictFile = "ko-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "th_TH-high",-            code = "th",-            bcp47 = "th-TH",-            iso3 = "tha",-            iso3Country = "THA",-            nativeName = "ไทย",-            englishName = "Thai",-            remoteArchive = "th-high.zip",-            dictFile = "th-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "sv_SE-high",-            code = "sv",-            bcp47 = "sv-SE",-            iso3 = "swe",-            iso3Country = "SWE",-            nativeName = "Svenska",-            englishName = "Swedish",-            remoteArchive = "sv-high.zip",-            dictFile = "sv-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "bn_BD-high",-            code = "bn",-            bcp47 = "bn-BD",-            iso3 = "ben",-            iso3Country = "BGD",-            nativeName = "বাংলা",-            englishName = "Bengali",-            remoteArchive = "bn-high.zip",-            dictFile = "bn-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "he_IL-high",-            code = "he",-            bcp47 = "he-IL",-            iso3 = "heb",-            iso3Country = "ISR",-            nativeName = "עברית",-            englishName = "Hebrew",-            remoteArchive = "he-high.zip",-            dictFile = "he-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "ku_TR-high",-            code = "ku",-            bcp47 = "ku-TR",-            iso3 = "kur",-            iso3Country = "TUR",-            nativeName = "Kurdî",-            englishName = "Kurdish",-            remoteArchive = "ku-high.zip",-            dictFile = "ku-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "mr_IN-high",-            code = "mr",-            bcp47 = "mr-IN",-            iso3 = "mar",-            iso3Country = "IND",-            nativeName = "मराठी",-            englishName = "Marathi",-            remoteArchive = "mr-high.zip",-            dictFile = "mr-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "sr_RS-medium",-            code = "sr",-            bcp47 = "sr-RS",-            iso3 = "srp",-            iso3Country = "SRB",-            nativeName = "Српски",-            englishName = "Serbian",-            remoteArchive = "sr-medium.zip",-            dictFile = "sr-word_id.bin",-            sha256 = "e70070b6ba3e037dbc97ff9f099f26c0dc268cf4a193604f20fcc0b637972e6d",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 34,-        ),-        PiperVoiceDef(-            id = "sw_CD-medium",-            code = "sw",-            bcp47 = "sw-CD",-            iso3 = "swa",-            iso3Country = "COD",-            nativeName = "Kiswahili",-            englishName = "Swahili",-            remoteArchive = "sw-medium.zip",-            dictFile = "sw-word_id.bin",-            sha256 = "85490ef10c9c8b16c49025d5fecd64c89b74971a97644be068dad9161c016d37",-            quality = "medium",-            sampleRate = 22050,-            sizeEstimateMb = 29,-        ),-        PiperVoiceDef(-            id = "te_IN-high",-            code = "te",-            bcp47 = "te-IN",-            iso3 = "tel",-            iso3Country = "IND",-            nativeName = "తెలుగు",-            englishName = "Telugu",-            remoteArchive = "te-high.zip",-            dictFile = "te-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-        PiperVoiceDef(-            id = "ur_PK-high",-            code = "ur",-            bcp47 = "ur-PK",-            iso3 = "urd",-            iso3Country = "PAK",-            nativeName = "اردو",-            englishName = "Urdu",-            remoteArchive = "ur-high.zip",-            dictFile = "ur-word_id.bin",-            sha256 = null,-            quality = "high",-            sampleRate = 22050,-            sizeEstimateMb = 80,-        ),-    )--    /** Default English voice — en-high.zip (high, 22 kHz). */-    val DEFAULT: PiperVoiceDef = ALL.first { it.code == "en" }--    private val byCodeMap: Map<String, PiperVoiceDef> = ALL.associateBy { it.code.lowercase() }-    private val byBcp47Map: Map<String, PiperVoiceDef> = ALL.associateBy { it.bcp47.lowercase() }-    private val byIso3Map: Map<String, PiperVoiceDef> = ALL.associateBy { it.iso3.lowercase() }-    private val byIdMap: Map<String, PiperVoiceDef> = ALL.associateBy { it.id }-    private val byRemoteMap: Map<String, PiperVoiceDef> = ALL.associateBy { it.remoteArchive }--    fun byCode(code: String): PiperVoiceDef? = byCodeMap[code.lowercase()]-    fun byBcp47(tag: String): PiperVoiceDef? = byBcp47Map[tag.lowercase()]-    fun byIso3(iso3: String): PiperVoiceDef? = byIso3Map[iso3.lowercase()]-    fun byId(id: String): PiperVoiceDef? = byIdMap[id]-    fun byRemoteArchive(name: String): PiperVoiceDef? = byRemoteMap[name]--    fun resolve(-        lang: String? = null,-        country: String? = null,-        variant: String? = null,-        voiceName: String? = null,-    ): PiperVoiceDef? {-        voiceName?.let { name ->-            val lower = name.lowercase()-            val xIdx = lower.indexOf("-x-")-            if (xIdx >= 0) {-                val bcpPart = name.substring(0, xIdx)-                byBcp47(bcpPart)?.let { return it }-                val idPart = name.substring(xIdx + 3)-                byId(idPart)?.let { return it }-            }-            byBcp47(name)?.let { return it }-            byId(name)?.let { return it }-            val parts = name.split("-", "_")-            if (parts.isNotEmpty()) {-                byCode(parts[0])?.let { return it }-                byIso3(parts[0])?.let { return it }-            }-            if (parts.size >= 2) {-                byIso3(parts[0])?.let { return it }-            }-        }--        lang?.let { l ->-            val ll = l.lowercase()-            byCode(ll)?.let { return it }-            byIso3(ll)?.let { return it }-            byBcp47(ll)?.let { return it }-            val normalized = ll.replace('_', '-')-            byBcp47(normalized)?.let { return it }-            if (ll.length >= 2) {-                val prefix = ll.substring(0, 2)-                byCode(prefix)?.let { return it }-            }-        }--        return null-    }--    fun rootDir(context: Context): File? =-        context.getExternalFilesDir(null) ?: context.filesDir--    fun voicesDir(context: Context): File {-        val root = rootDir(context) ?: return File(VOICES_ROOT)-        return File(root, VOICES_ROOT)-    }--    fun voiceDir(context: Context, def: PiperVoiceDef): File {-        val root = rootDir(context) ?: return File("$VOICES_ROOT/${def.bcp47}/${def.id}")-        return File(root, "$VOICES_ROOT/${def.bcp47}/${def.id}")-    }--    fun archiveFile(context: Context, def: PiperVoiceDef): File {-        val root = rootDir(context) ?: return File("$VOICES_ROOT/${def.remoteArchive}")-        return File(root, "$VOICES_ROOT/${def.remoteArchive}")-    }--    fun legacyArchive(context: Context): File {-        val root = rootDir(context) ?: return File(LEGACY_ARCHIVE)-        return File(root, LEGACY_ARCHIVE)-    }--    fun legacyVoiceDir(context: Context): File {-        val root = rootDir(context) ?: return File(LEGACY_VOICE_DIR)-        return File(root, LEGACY_VOICE_DIR)-    }--    fun voicePrefix(context: Context, def: PiperVoiceDef): String? {-        val files = voiceDir(context, def).listFiles() ?: return null-        val encoder = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return null-        return encoder.name.removeSuffix(ENCODER_SUFFIX)-    }--    private fun isValidVoiceDir(dir: File, minDictBytes: Long = 100_000L): Boolean {-        if (!dir.isDirectory) return false-        if (dir.listFiles()?.any { it.name.endsWith(".onnx") } == true) return false-        val dict = dir.listFiles()?.firstOrNull { it.name.endsWith("-word_id.bin") } ?: return false-        if (dict.length() < minDictBytes) return false-        val enc = dir.listFiles()?.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return false-        val prefix = enc.name.removeSuffix(ENCODER_SUFFIX)-        val netsOk = REQUIRED_NETS.all { net ->-            File(dir, "${prefix}${net}.maml").exists()-        }-        if (!netsOk) return false-        if (!File(dir, CONFIG).exists()) return false-        return true-    }--    /**-     * Find any valid voice dir under `piper/voices/<bcp47>/` – tolerates old speaker-specific-     * ids like `en_US-lessac-low` after we renamed to generic `en_US-high`. Used to make-     * CHECK_TTS_DATA and onGetVoices work on upgraded installs.-     */-    fun findAnyValidDirForBcp47(context: Context, bcp47: String): File? {-        return try {-            val bcpRoot = File(voicesDir(context), bcp47)-            if (!bcpRoot.isDirectory) return null-            bcpRoot.listFiles()?.firstOrNull { child ->-                child.isDirectory && isValidVoiceDir(child, if (bcp47.startsWith("en")) 1_000_000L else 100_000L)-            }-        } catch (_: Throwable) {-            null-        }-    }--    fun isExtracted(context: Context, def: PiperVoiceDef): Boolean {-        val dir = voiceDir(context, def)-        if (dir.isDirectory && isValidVoiceDir(dir, if (def.code == "en") 1_000_000L else 100_000L)) {-            return true-        }-        // Fallback: any valid dir under same BCP-47 (old speaker-specific ids)-        if (findAnyValidDirForBcp47(context, def.bcp47) != null) {-            return true-        }-        if (def.code == "en") {-            val legacyDir = legacyVoiceDir(context)-            if (legacyDir.isDirectory && isLegacyExtracted(context)) {-                return true-            }-        }-        return false-    }--    private fun isLegacyExtracted(context: Context): Boolean {-        val dir = legacyVoiceDir(context)-        val files = dir.listFiles() ?: return false-        if (files.any { it.name.endsWith(".onnx") }) return false-        val dict = File(dir, "en-word_id.bin")-        if (!dict.exists() || dict.length() < 1_000_000L) return false-        val enc = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return false-        val prefix = enc.name.removeSuffix(ENCODER_SUFFIX)-        val netsOk = REQUIRED_NETS.all { net ->-            File(dir, "${prefix}${net}.maml").exists()-        }-        return netsOk && File(dir, CONFIG).exists()-    }--    fun isAnyExtracted(context: Context): Boolean =-        ALL.any { isExtracted(context, it) } || isLegacyExtracted(context)--    fun installedDefs(context: Context): List<PiperVoiceDef> =-        ALL.filter { isExtracted(context, it) }.let { list ->-            if (list.isEmpty() && isLegacyExtracted(context)) listOf(DEFAULT) else list-        }--    fun installedCodes(context: Context): List<String> =-        installedDefs(context).map { it.code }.distinct

Diff truncated.