263 lines · 10.2 KB · KotlinRaw
package com.cottondb.android.platformimport android.Manifestimport android.content.Contextimport android.content.Intentimport android.content.pm.PackageManagerimport android.os.Buildimport android.os.Bundleimport android.os.Looperimport android.speech.RecognitionListenerimport android.speech.RecognizerIntentimport android.speech.SpeechRecognizerimport com.cottondb.android.capture.CaptureSpeechEventimport com.cottondb.android.capture.CaptureVoice/** * Android's [SpeechRecognizer] at Cotton's small capture boundary. * * Recognition services may send audio to a remote service. API 31+ uses the * on-device recognizer when Android says it is present; an unavailable local * engine deliberately falls back to the system recognizer, which may use its * configured network service. This adapter never creates an [android.media.AudioRecord]: * SpeechRecognizer owns the microphone and its RMS callback is the only level * signal it exposes. * * Every SpeechRecognizer call is made on the main thread, as Android requires. * [close] belongs to the hosting lifecycle; [cancel] is the capture-model path. */class AndroidDictation private constructor( private val microphoneGranted: () -> Boolean, private val recognizers: AndroidSpeechRecognizerFactory,) : CaptureVoice { constructor(context: Context) : this( microphoneGranted = { context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED }, recognizers = SystemSpeechRecognizerFactory(context.applicationContext), ) private var generation = 0L private var active: ActiveSession? = null /** Capture's established no-bias entry point. Its intent stays byte-for-byte unchanged. */ override fun start(listener: (CaptureSpeechEvent) -> Unit) = startWithBiasTerms(null, listener) /** * Take's explicit recognition hint path. Terms come from native `read.take` * and are forwarded unchanged: this boundary neither ranks nor caps them. */ fun start(biasTerms: List<String>, listener: (CaptureSpeechEvent) -> Unit) = startWithBiasTerms(biasTerms, listener) private fun startWithBiasTerms(biasTerms: List<String>?, listener: (CaptureSpeechEvent) -> Unit) { requireMainThread() endActiveSession() val thisGeneration = ++generation if (!microphoneGranted()) { beforeSession(listener, CaptureSpeechEvent.Failed(DENIED_MESSAGE)) return } val session = try { recognizers.create(listenerFor(listener, thisGeneration)) } catch (_: RuntimeException) { beforeSession(listener, CaptureSpeechEvent.Failed(UNAVAILABLE_MESSAGE)) return } active = ActiveSession(thisGeneration, session, listener) try { session.startListening(recognizerIntent(session.onDevice, biasTerms)) } catch (_: RuntimeException) { terminal(listener, thisGeneration, CaptureSpeechEvent.Failed(UNAVAILABLE_MESSAGE)) } } override fun cancel() { requireMainThread() active?.session?.cancel() endActiveSession() } /** Ask the recognizer to settle its final transcript; callbacks own teardown. */ override fun finish() { requireMainThread() active?.session?.stopListening() } /** Release Android's service and ignore callbacks belonging to its old session. */ fun close() { requireMainThread() endActiveSession() } private fun listenerFor( sink: (CaptureSpeechEvent) -> Unit, thisGeneration: Long, ): RecognitionListener = object : RecognitionListener { override fun onReadyForSpeech(params: Bundle?) = Unit override fun onBeginningOfSpeech() = Unit // This is supplied by SpeechRecognizer itself. We deliberately do not // open a second AudioRecord merely to duplicate a level meter. override fun onRmsChanged(rmsdB: Float) = Unit override fun onBufferReceived(buffer: ByteArray?) = Unit // End of input is not terminal: Android normally calls onResults after // it. Treating it as Ended would discard that final transcript. override fun onEndOfSpeech() = Unit override fun onError(error: Int) { terminal(sink, thisGeneration, CaptureSpeechEvent.Failed(messageFor(error))) } override fun onResults(results: Bundle?) { if (!isCurrent(thisGeneration)) return sink(CaptureSpeechEvent.Final(transcript(results))) terminal(sink, thisGeneration, CaptureSpeechEvent.Ended) } override fun onPartialResults(partialResults: Bundle?) { if (isCurrent(thisGeneration)) sink(CaptureSpeechEvent.Partial(transcript(partialResults))) } override fun onEvent(eventType: Int, params: Bundle?) = Unit override fun onSegmentResults(segmentResults: Bundle) { if (isCurrent(thisGeneration)) sink(CaptureSpeechEvent.Segment(transcript(segmentResults))) } override fun onEndOfSegmentedSession() { terminal(sink, thisGeneration, CaptureSpeechEvent.Ended) } } private fun terminal( sink: (CaptureSpeechEvent) -> Unit, thisGeneration: Long, event: CaptureSpeechEvent, ) { if (!isCurrent(thisGeneration)) return sink(event) if (event !is CaptureSpeechEvent.Ended) sink(CaptureSpeechEvent.Ended) if (active?.generation == thisGeneration) endActiveSession() } /** Permission and factory failures happen before there is a session to guard. */ private fun beforeSession(sink: (CaptureSpeechEvent) -> Unit, event: CaptureSpeechEvent.Failed) { sink(event) sink(CaptureSpeechEvent.Ended) } private fun isCurrent(candidate: Long): Boolean = active?.generation == candidate private fun endActiveSession() { val ending = active ?: return active = null ending.session.destroy() } private fun recognizerIntent(onDevice: Boolean, biasTerms: List<String>?): Intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) .apply { if (onDevice) putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true) // Android documents this optional ArrayList extra from API 33. // Older recognizers receive the original capture intent. if (biasTerms != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { putStringArrayListExtra( RecognizerIntent.EXTRA_BIASING_STRINGS, ArrayList(biasTerms), ) } } private fun transcript(bundle: Bundle?): String = bundle ?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) ?.firstOrNull() .orEmpty() private fun messageFor(error: Int): String = when (error) { SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> DENIED_MESSAGE SpeechRecognizer.ERROR_NO_MATCH, SpeechRecognizer.ERROR_SPEECH_TIMEOUT, -> EMPTY_MESSAGE SpeechRecognizer.ERROR_NETWORK, SpeechRecognizer.ERROR_NETWORK_TIMEOUT, SpeechRecognizer.ERROR_SERVER, -> UNAVAILABLE_MESSAGE else -> UNAVAILABLE_MESSAGE } private fun requireMainThread() { check(Looper.getMainLooper().thread === Thread.currentThread()) { "Android dictation must be called from the main thread." } } private data class ActiveSession( val generation: Long, val session: AndroidSpeechRecognizerSession, val sink: (CaptureSpeechEvent) -> Unit, ) companion object { private const val DENIED_MESSAGE = "Dictation needs microphone access — you can turn it on in Settings." private const val EMPTY_MESSAGE = "Nothing came through the microphone, so there was nothing to keep." private const val UNAVAILABLE_MESSAGE = "Dictation isn't available on this device right now." internal fun withBoundary( microphoneGranted: () -> Boolean, recognizers: AndroidSpeechRecognizerFactory, ): AndroidDictation = AndroidDictation(microphoneGranted, recognizers) }}/** Android platform boundary kept injectable so tests never need a recognizer service. */internal interface AndroidSpeechRecognizerFactory { fun create(listener: RecognitionListener): AndroidSpeechRecognizerSession}internal interface AndroidSpeechRecognizerSession { val onDevice: Boolean fun startListening(intent: Intent) fun stopListening() fun cancel() fun destroy()}private class SystemSpeechRecognizerFactory( private val context: Context,) : AndroidSpeechRecognizerFactory { override fun create(listener: RecognitionListener): AndroidSpeechRecognizerSession { if (!SpeechRecognizer.isRecognitionAvailable(context)) { throw IllegalStateException("No Android recognition service is available.") } val onDeviceAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && SpeechRecognizer.isOnDeviceRecognitionAvailable(context) val (recognizer, onDevice) = if (onDeviceAvailable) { try { SpeechRecognizer.createOnDeviceSpeechRecognizer(context) to true } catch (_: UnsupportedOperationException) { SpeechRecognizer.createSpeechRecognizer(context) to false } } else { SpeechRecognizer.createSpeechRecognizer(context) to false } recognizer.setRecognitionListener(listener) return AndroidSpeechRecognizerSessionImpl(recognizer, onDevice) }}private class AndroidSpeechRecognizerSessionImpl( private val recognizer: SpeechRecognizer, override val onDevice: Boolean,) : AndroidSpeechRecognizerSession { override fun startListening(intent: Intent) = recognizer.startListening(intent) override fun stopListening() = recognizer.stopListening() override fun cancel() = recognizer.cancel() override fun destroy() = recognizer.destroy()}