package com.cottondb.voice import android.app.Service import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Binder import android.os.IBinder import android.util.Log import com.cottondb.shell.core.CottonSigners import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put /** The phone's network as the store asks it: usable at all, and unmetered unless mobile data is allowed. */ class AndroidNetwork(context: Context) : Network { private val cm = context.getSystemService(ConnectivityManager::class.java) override fun usable(mobileData: Boolean): Boolean { val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && (mobileData || caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) } } /** * Cotton Voice's runtime, shared by its binder (VoiceService), the system's voice input (VoiceRecognition) and its own * screen: the store, the loaded engines, one thread per open dictation and one for every second pass. */ object Runtime { @Volatile private var made: Pair? = null fun of(context: Context): Pair = made ?: synchronized(this) { made ?: run { val store = ModelStore(context.applicationContext.filesDir.resolve("voice-models"), network = AndroidNetwork(context.applicationContext)) (store to Engines(store)).also { made = it } } } val store: ModelStore get() = made!!.first /** Second passes, one at a time, after the live words they correct. */ val seconds: ExecutorService = Executors.newSingleThreadExecutor { r -> Thread(r, "voice-second").apply { priority = Thread.NORM_PRIORITY - 1 } } /** The voice catalogue this build carries (assets/kits/shell/voice/models.json). */ @Volatile private var catalogue: Map? = null fun catalogue(context: Context): Map = catalogue ?: runCatching { context.assets.open("kits/shell/voice/models.json").bufferedReader().use { Plan.catalogue(it.readText()) } }.getOrDefault(emptyMap()).also { catalogue = it } /** Downloads, one model at a time. */ val fetches: ExecutorService = Executors.newSingleThreadExecutor { r -> Thread(r, "voice-fetch") } /** The models this phone knows of: the stand-ins and every model a plan or a fetch has named (kept beside its files). */ fun known(store: ModelStore): List { val seen = store.root.listFiles()?.mapNotNull { dir -> dir.resolve("entry.json").takeIf { it.isFile }?.let { f -> runCatching { ModelEntry.of(dir.name, Json.parseToJsonElement(f.readText()) as kotlinx.serialization.json.JsonObject) }.getOrNull() } } ?: emptyList() return (StandIns.all + seen).distinctBy { it.id } } fun remember(store: ModelStore, model: ModelEntry) { store.folder(model.id).apply { mkdirs() }.resolve("entry.json").writeText(model.json().toString()) } } /** * The binder every other Cotton app dictates through (ICottonVoice). Each Play app has a signing key of its own, so * no signature permission could let a sibling in: each call checks instead that the caller is a Cotton app * ([CottonSigners]: its certificate is the one the registry lists for it; a dev build, signed as this one is). */ class VoiceService : Service() { private class Open(val dictation: Dictation, val thread: ExecutorService, val listener: ICottonVoiceListener) private val sessions = ConcurrentHashMap() override fun onDestroy() { sessions.values.forEach { o -> o.thread.execute { o.dictation.close() }; o.thread.shutdown() } sessions.clear() super.onDestroy() } override fun onBind(intent: Intent): IBinder = object : ICottonVoice.Stub() { private val runtime = Runtime.of(this@VoiceService) private val store = runtime.first private val engines = runtime.second private val signers = CottonSigners.of(this@VoiceService) private fun caller() { val uid = Binder.getCallingUid() if (!signers.trustsUid(this@VoiceService, uid)) throw SecurityException("$uid") } override fun contract(): Int = 1 override fun store(): String { caller() return buildJsonObject { put("models", buildJsonArray { Runtime.known(store).forEach { add(store.state(it).json()) } }) }.toString() } override fun fetch(downloadsJson: String, mobileData: Boolean, listener: ICottonVoiceListener) { caller() val known = Runtime.catalogue(this@VoiceService) + Runtime.known(store).associateBy { it.id } val models = runCatching { ModelEntry.fromDownloads(Json.parseToJsonElement(downloadsJson) as JsonArray, known) }.getOrElse { Log.w(TAG, "fetch: unreadable downloads", it); return } // The caller hears each change while it stays bound; the download itself outlives it (ModelFetch). val hear: (ModelState) -> Unit = { s -> runCatching { listener.model(s.json().toString()) } } ModelFetch.listeners += hear runCatching { listener.asBinder().linkToDeath({ ModelFetch.listeners.remove(hear) }, 0) }.onFailure { ModelFetch.listeners.remove(hear) } models.forEach { m -> ModelFetch.enqueue(this@VoiceService, m, mobileData) } } override fun remove(model: String) { caller() androidx.work.WorkManager.getInstance(this@VoiceService).cancelUniqueWork("voice-model-$model") Runtime.fetches.execute { store.remove(model) } } override fun open(session: String, planJson: String, listener: ICottonVoiceListener) { caller() fun failed(code: String, message: String) = runCatching { listener.failed(session, code, message) } if (sessions.containsKey(session)) return failed("busy", session).let {} val plan = runCatching { Plan.parse(session, planJson, Runtime.catalogue(this@VoiceService)) }.getOrElse { return failed("bad_plan", it.message ?: "unreadable").let {} } val thread = Executors.newSingleThreadExecutor { r -> Thread(r, "voice-$session") } // Known before the engines load, so audio fed meanwhile queues behind the load on the session's thread. opening[session] = thread thread.execute { try { val resolved = plan.resolve(store::ready) listOfNotNull(resolved.live, resolved.second, resolved.vad).forEach { Runtime.remember(store, it) } if (!resolved.runnable) { failed("missing_model", buildJsonObject { put("downloads", resolved.downloads()) }.toString()) thread.shutdown(); opening.remove(session); return@execute } val live = engines.live(resolved.live, resolved.vad, resolved.language) val second = resolved.second?.takeIf { it !in resolved.missing }?.let { engines.second(it, resolved.language) } val opened = System.nanoTime() val dictation = Dictation(live, second, resolved.language, later = { job -> Runtime.seconds.execute(job) }, level = resolved.level) { h -> // A debug build says when each result left, from the session's open (the walk's timings). if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) Log.i(TAG, "${(System.nanoTime() - opened) / 1_000_000} ${h.json()}") runCatching { listener.heard(session, h.json().toString()) } } sessions[session] = Open(dictation, thread, listener) runCatching { listener.ready(session, buildJsonObject { put("language", resolved.language) put("live", buildJsonObject { put("engine", "sherpa:${resolved.live.id}"); put("model", resolved.live.id); if (resolved.live.standIn) put("stand_in", true) }) if (second != null) put("second", buildJsonObject { put("engine", "sherpa:${resolved.second!!.id}"); put("model", resolved.second.id); if (resolved.second.standIn) put("stand_in", true) }) if (resolved.missing.isNotEmpty()) put("downloads", resolved.downloads()) }.toString()) } listener.asBinder().linkToDeath({ cancel(session) }, 0) } catch (e: NoEngine) { failed("no_engine", "${e.code} ${e.what}") opening.remove(session); thread.shutdown() } catch (e: Throwable) { Log.e(TAG, "open $session", e) failed("failed", e.message ?: e.javaClass.simpleName) opening.remove(session); thread.shutdown() } } } override fun feed(session: String, pcm: ByteArray) { caller() val thread = sessions[session]?.thread ?: opening[session] ?: return thread.execute { sessions[session]?.dictation?.feed(pcm) } } override fun finish(session: String) { caller() val thread = sessions[session]?.thread ?: opening[session] ?: return thread.execute { val open = sessions[session] ?: return@execute open.dictation.finish { sessions.remove(session); opening.remove(session) runCatching { open.listener.ended(session) } thread.execute { open.dictation.close() } thread.shutdown() } } } override fun cancel(session: String) { caller() val open = sessions.remove(session) val thread = open?.thread ?: opening[session] ?: return opening.remove(session) thread.execute { open?.dictation?.close(); runCatching { open?.listener?.ended(session) } } thread.shutdown() } } private val opening = ConcurrentHashMap() companion object { const val TAG = "CottonVoice" } }