package eu.friedcutlet.yokan.services.tts import eu.friedcutlet.yokan.AndroidAppContext import android.os.Build import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import java.util.Locale import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlin.coroutines.resume actual fun createPlatformTextToSpeechService(): TextToSpeechService = AndroidTextToSpeechService() /** * Holds one engine bound to the application context until its owner closes; * init is single-flight so concurrent callers never bind (and leak) extra engines. */ private class AndroidTextToSpeechService : TextToSpeechService { private val engineLock = Mutex() @Volatile private var tts: TextToSpeech? = null private suspend fun engine(): TextToSpeech? = engineLock.withLock { tts?.let { return@withLock it } val context = AndroidAppContext.appContext ?: return@withLock null val ready = CompletableDeferred() val instance = TextToSpeech(context) { status -> ready.complete(status == TextToSpeech.SUCCESS) } val ok = try { ready.await() } catch (cancelled: CancellationException) { instance.shutdown() throw cancelled } if (ok) { instance.also { tts = it } } else { instance.shutdown() null } } override suspend fun voices(language: String?): List { val engine = engine() ?: return emptyList() val all = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { engine.voices.orEmpty() } else { emptyList() } return all.filter { language.isNullOrBlank() || it.locale.language.equals(language, ignoreCase = true) } .map { it.name } .distinct() } override suspend fun speak( text: String, request: TextToSpeechRequest, onProgress: (startOffset: Int, endOffset: Int) -> Unit, ) { val engine = engine() ?: return if (!request.language.isNullOrBlank()) { engine.language = Locale.forLanguageTag(request.language) } if (!request.voice.isNullOrBlank() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { engine.voices?.firstOrNull { it.name == request.voice }?.let { engine.voice = it } } engine.setSpeechRate(request.speechRate.toFloat()) engine.setPitch(request.pitch.toFloat()) suspendCancellableCoroutine { continuation -> val utteranceId = "${text.hashCode()}:${System.nanoTime()}" engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() { override fun onStart(id: String?) = Unit override fun onDone(id: String?) { if (id == utteranceId && continuation.isActive) continuation.resume(Unit) } @Deprecated("Required override") override fun onError(id: String?) { if (id == utteranceId && continuation.isActive) continuation.resume(Unit) } override fun onRangeStart(id: String?, start: Int, end: Int, frame: Int) { if (id == utteranceId) onProgress(start, end) } }) engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId) continuation.invokeOnCancellation { engine.stop() } } } override suspend fun stop() { tts?.stop() } override suspend fun closeAndJoin() = engineLock.withLock { val engine = tts ?: return@withLock engine.stop() engine.shutdown() tts = null } }