ProfileSpeechService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tts/ProfileSpeechService.kt
1package eu.friedcutlet.yokan.services.tts23import eu.friedcutlet.yokan.util.PlatformLock4import kotlinx.coroutines.CancellationException5import kotlinx.coroutines.CoroutineScope6import kotlinx.coroutines.CoroutineStart7import kotlinx.coroutines.Deferred8import kotlinx.coroutines.Job9import kotlinx.coroutines.NonCancellable10import kotlinx.coroutines.SupervisorJob11import kotlinx.coroutines.async12import kotlinx.coroutines.cancelAndJoin13import kotlinx.coroutines.currentCoroutineContext14import kotlinx.coroutines.ensureActive15import kotlinx.coroutines.sync.Mutex16import kotlinx.coroutines.sync.withLock17import kotlinx.coroutines.withContext1819/** Captures one native service; reader handles cannot stop another reader's utterance. */20class ProfileSpeechService internal constructor(21 private val delegate: TextToSpeechService,22 ownerScope: CoroutineScope,23 private val isOwnerOpen: () -> Boolean = { true },24) : TextToSpeechService {25 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])26 private val job = SupervisorJob(ownerJob)27 private val scope = CoroutineScope(ownerScope.coroutineContext + job)28 private val callsLock = PlatformLock()29 private val calls = mutableMapOf<Job, Reader>()30 private val nativeLock = Mutex()31 private val closeLock = Mutex()32 private var needsStop = false // guarded by nativeLock; failed cleanup retries before reuse33 private var released = false34 private val direct = Reader()3536 internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen()3738 private fun ensureOpen() {39 ownerJob.ensureActive()40 job.ensureActive()41 if (!isOwnerOpen()) throw CancellationException("Speech owner is retiring.")42 }4344 internal fun reader(): Reader {45 ensureOpen()46 return Reader().also {47 if (!isAvailable) { it.retire(); ensureOpen() }48 }49 }5051 override suspend fun voices(language: String?): List<String> = direct.voices(language)52 override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =53 direct.speak(text, request, onProgress)5455 override suspend fun stop() = stopCalls(null)5657 private suspend fun stopCalls(reader: Reader?) {58 val caller = requireNotNull(currentCoroutineContext()[Job])59 caller.ensureActive()60 ensureOpen()61 reader?.ensureOpen()62 val stopping = callsLock.withLock { calls.filterValues { reader == null || it === reader }.keys.toList() }63 stopping.forEach { it.cancel() }64 withContext(NonCancellable) { stopping.forEach { it.join() } }65 caller.ensureActive()66 ensureOpen()67 reader?.ensureOpen()68 }6970 private suspend fun releaseUtterance() {71 if (needsStop) {72 delegate.stop()73 needsStop = false74 }75 }7677 internal fun retire() { job.cancel() }7879 override suspend fun closeAndJoin() = withContext(NonCancellable) {80 closeLock.withLock {81 retire()82 job.join()83 if (!released) nativeLock.withLock {84 releaseUtterance()85 delegate.closeAndJoin()86 released = true87 }88 }89 }9091 internal inner class Reader : TextToSpeechService {92 private val readerJob = SupervisorJob(job)93 private val readerScope = CoroutineScope(scope.coroutineContext + readerJob)94 val isAvailable: Boolean get() = readerJob.isActive && this@ProfileSpeechService.isAvailable9596 fun ensureOpen() { readerJob.ensureActive(); this@ProfileSpeechService.ensureOpen() }97 fun retire() { readerJob.cancel() }98 override suspend fun closeAndJoin() {99 retire()100 withContext(NonCancellable) { readerJob.join() }101 }102103 private suspend fun <T> runOwned(action: suspend (Job, Job) -> T): T {104 val caller = requireNotNull(currentCoroutineContext()[Job])105 caller.ensureActive()106 ensureOpen()107 val work: Deferred<T> = readerScope.async(start = CoroutineStart.LAZY) {108 val call = requireNotNull(currentCoroutineContext()[Job])109 call.ensureActive(); caller.ensureActive(); ensureOpen()110 nativeLock.withLock {111 call.ensureActive(); caller.ensureActive(); ensureOpen()112 withContext(NonCancellable) { releaseUtterance() }113 call.ensureActive(); caller.ensureActive(); ensureOpen()114 action(call, caller).also { call.ensureActive(); caller.ensureActive(); ensureOpen() }115 }116 }117 callsLock.withLock { calls[work] = this }118 work.invokeOnCompletion { callsLock.withLock { calls.remove(work) } }119 work.start()120 return try { work.await() }121 finally {122 withContext(NonCancellable) { work.cancelAndJoin() }123 caller.ensureActive(); ensureOpen()124 }125 }126127 override suspend fun voices(language: String?): List<String> = runOwned { _, _ -> delegate.voices(language) }128129 override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =130 runOwned { call, caller ->131 needsStop = true132 try {133 delegate.speak(text, request) { start, end ->134 if (call.isActive && caller.isActive && isAvailable) onProgress(start, end)135 }136 } finally { withContext(NonCancellable) { releaseUtterance() } }137 }138139 override suspend fun stop() = stopCalls(this)140 }141}142