package eu.friedcutlet.yokan.services.tts import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** Captures one native service; reader handles cannot stop another reader's utterance. */ class ProfileSpeechService internal constructor( private val delegate: TextToSpeechService, ownerScope: CoroutineScope, private val isOwnerOpen: () -> Boolean = { true }, ) : TextToSpeechService { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) private val job = SupervisorJob(ownerJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) private val callsLock = PlatformLock() private val calls = mutableMapOf() private val nativeLock = Mutex() private val closeLock = Mutex() private var needsStop = false // guarded by nativeLock; failed cleanup retries before reuse private var released = false private val direct = Reader() internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen() private fun ensureOpen() { ownerJob.ensureActive() job.ensureActive() if (!isOwnerOpen()) throw CancellationException("Speech owner is retiring.") } internal fun reader(): Reader { ensureOpen() return Reader().also { if (!isAvailable) { it.retire(); ensureOpen() } } } override suspend fun voices(language: String?): List = direct.voices(language) override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) = direct.speak(text, request, onProgress) override suspend fun stop() = stopCalls(null) private suspend fun stopCalls(reader: Reader?) { val caller = requireNotNull(currentCoroutineContext()[Job]) caller.ensureActive() ensureOpen() reader?.ensureOpen() val stopping = callsLock.withLock { calls.filterValues { reader == null || it === reader }.keys.toList() } stopping.forEach { it.cancel() } withContext(NonCancellable) { stopping.forEach { it.join() } } caller.ensureActive() ensureOpen() reader?.ensureOpen() } private suspend fun releaseUtterance() { if (needsStop) { delegate.stop() needsStop = false } } internal fun retire() { job.cancel() } override suspend fun closeAndJoin() = withContext(NonCancellable) { closeLock.withLock { retire() job.join() if (!released) nativeLock.withLock { releaseUtterance() delegate.closeAndJoin() released = true } } } internal inner class Reader : TextToSpeechService { private val readerJob = SupervisorJob(job) private val readerScope = CoroutineScope(scope.coroutineContext + readerJob) val isAvailable: Boolean get() = readerJob.isActive && this@ProfileSpeechService.isAvailable fun ensureOpen() { readerJob.ensureActive(); this@ProfileSpeechService.ensureOpen() } fun retire() { readerJob.cancel() } override suspend fun closeAndJoin() { retire() withContext(NonCancellable) { readerJob.join() } } private suspend fun runOwned(action: suspend (Job, Job) -> T): T { val caller = requireNotNull(currentCoroutineContext()[Job]) caller.ensureActive() ensureOpen() val work: Deferred = readerScope.async(start = CoroutineStart.LAZY) { val call = requireNotNull(currentCoroutineContext()[Job]) call.ensureActive(); caller.ensureActive(); ensureOpen() nativeLock.withLock { call.ensureActive(); caller.ensureActive(); ensureOpen() withContext(NonCancellable) { releaseUtterance() } call.ensureActive(); caller.ensureActive(); ensureOpen() action(call, caller).also { call.ensureActive(); caller.ensureActive(); ensureOpen() } } } callsLock.withLock { calls[work] = this } work.invokeOnCompletion { callsLock.withLock { calls.remove(work) } } work.start() return try { work.await() } finally { withContext(NonCancellable) { work.cancelAndJoin() } caller.ensureActive(); ensureOpen() } } override suspend fun voices(language: String?): List = runOwned { _, _ -> delegate.voices(language) } override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) = runOwned { call, caller -> needsStop = true try { delegate.speak(text, request) { start, end -> if (call.isActive && caller.isActive && isAvailable) onProgress(start, end) } } finally { withContext(NonCancellable) { releaseUtterance() } } } override suspend fun stop() = stopCalls(this) } }