package eu.friedcutlet.yokan.ui.screens.novel import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest import eu.friedcutlet.yokan.services.tts.TextToSpeechService import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.updateAndGet import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext internal enum class NovelTtsPlaybackState { Stopped, Playing, Paused } internal data class NovelTtsUiState( val playback: NovelTtsPlaybackState = NovelTtsPlaybackState.Stopped, val paragraphIndex: Int = 0, val paragraphCount: Int = 0, val wordStart: Int = -1, val wordEnd: Int = -1, ) { val progress: Float get() = if (paragraphCount == 0) 0f else (paragraphIndex + 1f) / paragraphCount } internal fun novelTtsParagraphs(content: NovelRichContent): List = content.blocks .mapNotNull { (it as? NovelContentBlock.Text)?.text?.text?.trim()?.takeIf(String::isNotEmpty) } internal class NovelTtsController( private val service: TextToSpeechService, ownerScope: CoroutineScope, private val isOwnerOpen: () -> Boolean = { true }, ) { private val parentJob = requireNotNull(ownerScope.coroutineContext[Job]) private val job = SupervisorJob(parentJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) private val operations = Mutex() private val mutableState = MutableStateFlow(NovelTtsUiState()) val state: StateFlow = mutableState.asStateFlow() private var paragraphs: List = emptyList() private var request = TextToSpeechRequest() private var resumeOffset = 0 private var playbackJob: Job? = null private val generation = MutableStateFlow(0L) private fun ensureCurrent(call: Job) { call.ensureActive() parentJob.ensureActive() job.ensureActive() if (!isOwnerOpen()) throw CancellationException("Reader speech owner is retired.") } private suspend fun command(action: suspend () -> Unit) { val caller = requireNotNull(currentCoroutineContext()[Job]) ensureCurrent(caller) val work = scope.async { operations.withLock { caller.ensureActive() ensureCurrent(requireNotNull(currentCoroutineContext()[Job])) action() ensureCurrent(requireNotNull(currentCoroutineContext()[Job])) } } try { work.await() } finally { withContext(NonCancellable) { work.cancelAndJoin() } ensureCurrent(caller) } } suspend fun start(paragraphs: List, request: TextToSpeechRequest, startIndex: Int = 0) = command { haltCurrent() this.paragraphs = paragraphs.filter(String::isNotBlank) this.request = request resumeOffset = 0 mutableState.update { if (this.paragraphs.isEmpty()) NovelTtsUiState() else NovelTtsUiState( playback = NovelTtsPlaybackState.Playing, paragraphIndex = startIndex.coerceIn(this.paragraphs.indices), paragraphCount = this.paragraphs.size, ) } if (this.paragraphs.isNotEmpty()) launchPlayback() } suspend fun pause() = command { val current = mutableState.value if (current.playback == NovelTtsPlaybackState.Playing) { resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset haltCurrent() mutableState.update { current.copy(playback = NovelTtsPlaybackState.Paused) } } } suspend fun resume() = command { if (mutableState.value.playback == NovelTtsPlaybackState.Paused && paragraphs.isNotEmpty()) { mutableState.update { it.copy(playback = NovelTtsPlaybackState.Playing) } launchPlayback() } } suspend fun skipNext() = command { jumpTo((mutableState.value.paragraphIndex + 1).coerceAtMost(paragraphs.lastIndex)) } suspend fun skipPrevious() = command { jumpTo((mutableState.value.paragraphIndex - 1).coerceAtLeast(0)) } private suspend fun jumpTo(index: Int) { if (index !in paragraphs.indices) return val wasPlaying = mutableState.value.playback == NovelTtsPlaybackState.Playing haltCurrent() resumeOffset = 0 mutableState.update { it.copy( playback = if (wasPlaying) NovelTtsPlaybackState.Playing else NovelTtsPlaybackState.Paused, paragraphIndex = index, wordStart = -1, wordEnd = -1, ) } if (wasPlaying) launchPlayback() } suspend fun updateRequest(request: TextToSpeechRequest) = command { this.request = request val current = mutableState.value if (current.playback == NovelTtsPlaybackState.Playing) { resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset haltCurrent() mutableState.update { current.copy(playback = NovelTtsPlaybackState.Playing) } launchPlayback() } } suspend fun stop() = command { haltCurrent() paragraphs = emptyList() resumeOffset = 0 mutableState.update { NovelTtsUiState() } } internal fun retire() { generation.update { it + 1 } job.cancel() mutableState.update { NovelTtsUiState() } } internal suspend fun closeAndJoin() { retire() withContext(NonCancellable) { job.join() } } private fun launchPlayback() { val token = generation.updateAndGet { it + 1 } playbackJob = scope.launch { val call = requireNotNull(currentCoroutineContext()[Job]) fun admitted() = call.isActive && job.isActive && parentJob.isActive && isOwnerOpen() && token == generation.value try { while (admitted() && mutableState.value.playback == NovelTtsPlaybackState.Playing) { val paragraphIndex = mutableState.value.paragraphIndex val paragraph = paragraphs.getOrNull(paragraphIndex) ?: break val offset = resumeOffset.coerceIn(0, paragraph.length) if (offset < paragraph.length) { service.speak(paragraph.substring(offset), request) { start, end -> if (admitted()) mutableState.update { current -> if (admitted() && current.playback == NovelTtsPlaybackState.Playing) current.copy( wordStart = (offset + start).coerceIn(0, paragraph.length), wordEnd = (offset + end).coerceIn(0, paragraph.length), ) else current } } } ensureCurrent(call) if (!admitted() || mutableState.value.playback != NovelTtsPlaybackState.Playing) break if (paragraphIndex >= paragraphs.lastIndex) { mutableState.update { it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1) } break } resumeOffset = 0 mutableState.update { it.copy(paragraphIndex = paragraphIndex + 1, wordStart = -1, wordEnd = -1) } } } catch (cancelled: CancellationException) { throw cancelled } catch (_: Throwable) { if (admitted()) mutableState.update { it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1) } } } } private suspend fun haltCurrent() { generation.update { it + 1 } val previous = playbackJob previous?.cancel() withContext(NonCancellable) { previous?.join() service.stop() } playbackJob = null ensureCurrent(requireNotNull(currentCoroutineContext()[Job])) } }