speech: make the Supertonic engine shutdown-safe and retry a lost device
- Commit
fb3f3c82e6a901666a0156a2dc8c8f934df9ea1b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 22:38 UTC (3 months ago)
- Parents
e90678f
Diff
library/ml/src/main/rust/src/post/supertonic.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic.rs b/library/ml/src/main/rust/src/post/supertonic.rsindex c0a1599a24..cc0be1fa1f 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -212,7 +212,7 @@ pub const STEPS: u32 = 16; /// The GPU stages, as a trait, so the sequencing below is host-testable against stubs. ///-/// The same shape `post::ocr` and `post::speech` use, and for the same reason: the order of the+/// The same shape `post::ocr` uses, and for the same reason: the order of the /// four nets, the length arithmetic between them and the sampler loop are where the mistakes are, /// and none of them needs a device to check. pub trait Stages {
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex 568edbb13a..cba2b2b7b2 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -500,9 +500,9 @@ def layer_norm_scale(node, consumers, held, array): """Whether `node` is the `Mul(x, gamma)` of a decomposed layer norm. Recognised by structure rather than by name: a `Mul` against a rank-1 constant whose one- consumer is an `Add` against a rank-1 constant of the same length. In Piper's encoder that- matches exactly the twelve norms and nothing else — the mask multiplies and the embedding- scale are against scalars or computed tensors.+ consumer is an `Add` against a rank-1 constant of the same length. In the exports this reads+ that matches the layer norms and nothing else - mask multiplies and embedding scales are+ against scalars or computed tensors. """ scales = [n for n in node.input if held(n) and array(n).ndim == 1] if len(scales) != 1:
scripts/speech/fetch_whisper_onnx.sh
diff --git a/scripts/speech/fetch_whisper_onnx.sh b/scripts/speech/fetch_whisper_onnx.shindex 16853dac33..df56cf79f0 100644--- a/scripts/speech/fetch_whisper_onnx.sh+++ b/scripts/speech/fetch_whisper_onnx.sh@@ -2,9 +2,9 @@ # # Refresh the bundled Whisper-base int8 ONNX assets in speech/src/main/assets/whisper-base/. #-# Unlike the Piper voices, these are NOT downloaded at runtime — they ship inside the APK and-# are read straight out of the asset manager by WhisperOnnxEngine, so this script is a-# build-host tool for updating a vendored dependency, not a mirror-staging step.+# These are NOT downloaded at runtime - they ship inside the APK and are read straight out of+# the asset manager by WhisperOnnxEngine, so this script is a build-host tool for updating a+# vendored dependency, not a mirror-staging step. # # Upstream is HuggingFace onnx-community/whisper-base, which is an ONNX Runtime *dynamic* # int8 quantization of openai/whisper-base. We consume it as-is: onnx2ncnn cannot read@@ -26,8 +26,8 @@ set -euo pipefail REPO="onnx-community/whisper-base"-# Pinned, as the PP-OCR and Piper fetchers are: `main` moving under us would change the-# weights without changing this script.+# Pinned, as `scripts/ml/fetch_and_convert.sh` pins its models: `main` moving under us would+# change the weights without changing this script. REVISION="1846881b6b3a3024392c1eea3ad983695bc23925" BASE="https://huggingface.co/${REPO}/resolve/${REVISION}" DEST="speech/src/main/assets/whisper-base"
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 2bb2fb5092..406234ae4a 100644--- a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt@@ -17,13 +17,11 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.DropdownMenuItem@@ -40,7 +38,6 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight@@ -459,12 +456,7 @@ private fun TtsTestSection( context, { st -> if (st == TextToSpeech.SUCCESS) {- val locale = try {- Locale.forLanguageTag(bcp47)- } catch (_: Throwable) {- Locale(chosen.code)- }- tts?.language = locale+ tts?.language = Locale.forLanguageTag(bcp47) tts?.speak( sample, TextToSpeech.QUEUE_FLUSH, null, "sample",
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.ktindex 4e60b3c909..0c37dbcc80 100644--- a/speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.kt+++ b/speech/src/main/java/com/vayunmathur/speech/domain/SupertonicVoices.kt@@ -126,6 +126,9 @@ object SupertonicVoices { fun voiceName(language: SupertonicLanguage, voice: String): String = "${language.bcp47}$VOICE_MARK$voice" + /** Whether `voiceName` carries a `-x-` style at all, whether or not it is one we have. */+ fun namesAStyle(voiceName: String?): Boolean = voiceName?.contains(VOICE_MARK) == true+ /** * The voice style named in `voiceName`, or null if it names none or names one we do not have. *
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.ktindex d7212469f4..8612d6a85d 100644--- a/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt@@ -25,8 +25,9 @@ import java.io.File 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+ private var attempts = 0+ private var closed = false /** Supertonic's output rate, fixed by the vocoder rather than by the voice. */ val sampleRate: Int get() = SupertonicSynthesizer.SAMPLE_RATE@@ -49,8 +50,8 @@ class SupertonicEngine(private val context: Context) { */ 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 (style == voice) return true if (!engine.voice(style)) return false voice = style true@@ -65,6 +66,10 @@ class SupertonicEngine(private val context: Context) { * 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. *+ * The lock covers the synthesis and **not** the delivery. `onChunk` writes into the framework's+ * audio track and blocks while it plays, so holding the handle across it would make [close] —+ * which arrives on the main thread from `onDestroy` — wait out a whole utterance.+ * * 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@@ -72,13 +77,15 @@ class SupertonicEngine(private val context: Context) { * 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+ fun synthesize(text: String, onChunk: (FloatArray) -> Boolean): Boolean {+ val samples = synchronized(lock) {+ val engine = ensure() ?: return false+ try {+ engine.synthesize(text)+ } catch (e: Throwable) {+ Log.e(TAG, "synthesis failed", e)+ return false+ } } if (samples.isEmpty()) return false var offset = 0@@ -87,40 +94,58 @@ class SupertonicEngine(private val context: Context) { if (!onChunk(samples.copyOfRange(offset, offset + n))) return false offset += n }- true+ return true } - /** Free the four networks. Idempotent. */+ /**+ * Free the four networks. Idempotent, and **terminal**.+ *+ * Terminal because `onCreate` warms the engine on a detached thread while `onDestroy` calls+ * this on the main one: without the flag, a `preload` that lost the race to the lock would+ * rebuild ~105 MB of GPU state immediately after it was freed, with nothing left to free it+ * again.+ */ fun close() = synchronized(lock) {+ closed = true 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.+ * # Why the attempt is counted+ *+ * `SupertonicSynthesizer`'s constructor never throws; it comes up unavailable instead. Most of+ * the reasons are properties of the install and will never change — no `libmodelrunner.so` for+ * this ABI, no Vulkan device with fp16 compute, a missing asset — and retrying those re-reads+ * the bundle to fail identically. But not all of them are: a lost device or a failed allocation+ * under memory pressure is transient, and latching on the first one would leave the engine+ * advertising 31 languages and erroring on every utterance until the process died.+ *+ * So it retries, and a small bound is what stops a permanently broken device paying for a+ * ~105 MB load attempt on every sentence. */ private fun ensure(): SupertonicSynthesizer? {- loaded?.let { return it }- if (synthesizer != null) return null+ synthesizer?.let { return it }+ if (closed || attempts >= MAX_ATTEMPTS) return null+ attempts++ 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")+ Log.e(TAG, "the Supertonic bundle is not usable on this device (attempt $attempts)")+ built.close() return null }- loaded = built+ synthesizer = built return built } private companion object { const val TAG = "SupertonicEngine" + /** Loads to try before giving up for the life of the process. See [ensure]. */+ const val MAX_ATTEMPTS = 2+ /** * Samples per chunk handed to the callback. *@@ -153,13 +178,16 @@ object SupertonicBundle { 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 }+ val entries = try {+ context.assets.list(SupertonicSynthesizer.ASSET_PATH)?.toSet().orEmpty() } catch (e: Throwable) {+ // Deliberately not cached. A throw here is a failure to *read* the assets rather than+ // an answer about them, and pinning `false` on it would unadvertise the engine for the+ // life of the process over something that may not recur. Log.e(TAG, "cannot list the Supertonic assets", e)- false+ return false }+ val found = REQUIRED.all { it in entries } present = found return found }
speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.ktindex 2df0065729..bb62446cbe 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt@@ -107,14 +107,24 @@ class SupertonicTtsService : TextToSpeechService() { return SupertonicVoices.voiceName(found, SupertonicVoices.DEFAULT_VOICE) } + /**+ * Whether `voiceName` is one this engine published.+ *+ * The style half is checked as well as the language, because [onGetVoices] publishes an explicit+ * name per style: accepting `en-US-x-BOGUS` here would be a success for a voice the caller will+ * never hear, since [onLoadVoice] would then leave whatever style was already selected.+ */ 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+ if (SupertonicVoices.resolve(voiceName = voiceName) == null) return TextToSpeech.ERROR+ if (SupertonicVoices.namesAStyle(voiceName) && SupertonicVoices.styleIn(voiceName) == null) {+ return TextToSpeech.ERROR+ }+ return TextToSpeech.SUCCESS } override fun onLoadVoice(voiceName: String?): Int {- if (voiceName == null || !usable()) return TextToSpeech.ERROR+ if (onIsValidVoiceName(voiceName) != TextToSpeech.SUCCESS) return TextToSpeech.ERROR val found = SupertonicVoices.resolve(voiceName = voiceName) ?: return TextToSpeech.ERROR language = found SupertonicVoices.styleIn(voiceName)?.let { voice = it }@@ -206,11 +216,14 @@ class SupertonicTtsService : TextToSpeechService() { emptySet(), ) - private fun localeFor(found: SupertonicLanguage): Locale = try {+ /**+ * The locale for a language, from its tag.+ *+ * `forLanguageTag` never throws — a tag it cannot parse gives `Locale.ROOT` — and all 31 tags in+ * [SupertonicVoices.ALL] are well-formed, so there is nothing to fall back to.+ */+ private fun localeFor(found: SupertonicLanguage): Locale = 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 {
speech/src/main/res/xml/data_extraction_rules.xml
diff --git a/speech/src/main/res/xml/data_extraction_rules.xml b/speech/src/main/res/xml/data_extraction_rules.xmlindex f32d9aa014..93001dd365 100644--- a/speech/src/main/res/xml/data_extraction_rules.xml+++ b/speech/src/main/res/xml/data_extraction_rules.xml@@ -2,18 +2,20 @@ <!-- Overrides the permissive default in the shared :library module. Storage audited:- external/piper/voices/** Piper TTS voice archives and unpacked ncnn models- (PiperVoiceRegistry). Hundreds of MB, re-downloadable.- external/<whisper dir> Whisper recognition model files (WhisperModel). Same.- file/datastore_default.preferences_pb download bookkeeping keyed per model- (progress_*, dlid_*, speed_*), plus any app settings.- (no Room database, and no learned or adaptation data was found - neither the+ external/piper/** dead. Piper's voice archives and unpacked models used to live+ here; the TTS service deletes the tree on first run now (see+ SupertonicBundle.deleteOrphanedPiperVoices). An upgraded install+ can still hold up to 1.8 GB of it until that runs, and none of it+ is worth backing up.+ (no models of any kind under external/ on a fresh install: both the Whisper recogniser+ and the Supertonic voices ship inside the APK, so there is nothing downloaded to+ preserve and nothing to re-download after a restore.)+ (no DataStore, no Room database, and no learned or adaptation data - neither the recognition service nor the TTS service persists user speech or per-user models.) - Everything large here is a re-downloadable model, so nothing goes to cloud backup.- The DataStore is excluded from cloud backup too: it is download state with no restore- value, and its full key set could not be enumerated with certainty, so it defaults to- private. Device transfer carries it so any settings survive the move. -->+ So there is nothing here worth carrying anywhere: everything the app needs is in the APK+ and everything under external/ is a leftover. Both backup and device transfer are empty+ rather than selective, which is a statement rather than an omission. --> <data-extraction-rules> <cloud-backup> <exclude domain="root" path="." />@@ -23,6 +25,10 @@ <exclude domain="external" path="." /> </cloud-backup> <device-transfer>- <include domain="file" path="datastore_default.preferences_pb" />+ <exclude domain="root" path="." />+ <exclude domain="file" path="." />+ <exclude domain="database" path="." />+ <exclude domain="sharedpref" path="." />+ <exclude domain="external" path="." /> </device-transfer> </data-extraction-rules>