NovelTtsController.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsController.kt
1package eu.friedcutlet.yokan.ui.screens.novel23import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest4import eu.friedcutlet.yokan.services.tts.TextToSpeechService5import kotlinx.coroutines.CancellationException6import kotlinx.coroutines.CoroutineScope7import kotlinx.coroutines.Job8import kotlinx.coroutines.cancelAndJoin9import kotlinx.coroutines.flow.MutableStateFlow10import kotlinx.coroutines.flow.StateFlow11import kotlinx.coroutines.flow.asStateFlow12import kotlinx.coroutines.launch13import kotlinx.coroutines.NonCancellable14import kotlinx.coroutines.SupervisorJob15import kotlinx.coroutines.async16import kotlinx.coroutines.currentCoroutineContext17import kotlinx.coroutines.ensureActive18import kotlinx.coroutines.flow.update19import kotlinx.coroutines.flow.updateAndGet20import kotlinx.coroutines.sync.Mutex21import kotlinx.coroutines.sync.withLock22import kotlinx.coroutines.withContext2324internal enum class NovelTtsPlaybackState { Stopped, Playing, Paused }2526internal data class NovelTtsUiState(27 val playback: NovelTtsPlaybackState = NovelTtsPlaybackState.Stopped,28 val paragraphIndex: Int = 0,29 val paragraphCount: Int = 0,30 val wordStart: Int = -1,31 val wordEnd: Int = -1,32) {33 val progress: Float34 get() = if (paragraphCount == 0) 0f else (paragraphIndex + 1f) / paragraphCount35}3637internal fun novelTtsParagraphs(content: NovelRichContent): List<String> = content.blocks38 .mapNotNull { (it as? NovelContentBlock.Text)?.text?.text?.trim()?.takeIf(String::isNotEmpty) }3940internal class NovelTtsController(41 private val service: TextToSpeechService,42 ownerScope: CoroutineScope,43 private val isOwnerOpen: () -> Boolean = { true },44) {45 private val parentJob = requireNotNull(ownerScope.coroutineContext[Job])46 private val job = SupervisorJob(parentJob)47 private val scope = CoroutineScope(ownerScope.coroutineContext + job)48 private val operations = Mutex()49 private val mutableState = MutableStateFlow(NovelTtsUiState())50 val state: StateFlow<NovelTtsUiState> = mutableState.asStateFlow()5152 private var paragraphs: List<String> = emptyList()53 private var request = TextToSpeechRequest()54 private var resumeOffset = 055 private var playbackJob: Job? = null56 private val generation = MutableStateFlow(0L)5758 private fun ensureCurrent(call: Job) {59 call.ensureActive()60 parentJob.ensureActive()61 job.ensureActive()62 if (!isOwnerOpen()) throw CancellationException("Reader speech owner is retired.")63 }6465 private suspend fun command(action: suspend () -> Unit) {66 val caller = requireNotNull(currentCoroutineContext()[Job])67 ensureCurrent(caller)68 val work = scope.async {69 operations.withLock {70 caller.ensureActive()71 ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))72 action()73 ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))74 }75 }76 try { work.await() }77 finally {78 withContext(NonCancellable) { work.cancelAndJoin() }79 ensureCurrent(caller)80 }81 }8283 suspend fun start(paragraphs: List<String>, request: TextToSpeechRequest, startIndex: Int = 0) = command {84 haltCurrent()85 this.paragraphs = paragraphs.filter(String::isNotBlank)86 this.request = request87 resumeOffset = 088 mutableState.update {89 if (this.paragraphs.isEmpty()) NovelTtsUiState() else NovelTtsUiState(90 playback = NovelTtsPlaybackState.Playing,91 paragraphIndex = startIndex.coerceIn(this.paragraphs.indices),92 paragraphCount = this.paragraphs.size,93 )94 }95 if (this.paragraphs.isNotEmpty()) launchPlayback()96 }9798 suspend fun pause() = command {99 val current = mutableState.value100 if (current.playback == NovelTtsPlaybackState.Playing) {101 resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset102 haltCurrent()103 mutableState.update { current.copy(playback = NovelTtsPlaybackState.Paused) }104 }105 }106107 suspend fun resume() = command {108 if (mutableState.value.playback == NovelTtsPlaybackState.Paused && paragraphs.isNotEmpty()) {109 mutableState.update { it.copy(playback = NovelTtsPlaybackState.Playing) }110 launchPlayback()111 }112 }113114 suspend fun skipNext() = command { jumpTo((mutableState.value.paragraphIndex + 1).coerceAtMost(paragraphs.lastIndex)) }115 suspend fun skipPrevious() = command { jumpTo((mutableState.value.paragraphIndex - 1).coerceAtLeast(0)) }116117 private suspend fun jumpTo(index: Int) {118 if (index !in paragraphs.indices) return119 val wasPlaying = mutableState.value.playback == NovelTtsPlaybackState.Playing120 haltCurrent()121 resumeOffset = 0122 mutableState.update { it.copy(123 playback = if (wasPlaying) NovelTtsPlaybackState.Playing else NovelTtsPlaybackState.Paused,124 paragraphIndex = index, wordStart = -1, wordEnd = -1,125 ) }126 if (wasPlaying) launchPlayback()127 }128129 suspend fun updateRequest(request: TextToSpeechRequest) = command {130 this.request = request131 val current = mutableState.value132 if (current.playback == NovelTtsPlaybackState.Playing) {133 resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset134 haltCurrent()135 mutableState.update { current.copy(playback = NovelTtsPlaybackState.Playing) }136 launchPlayback()137 }138 }139140 suspend fun stop() = command {141 haltCurrent()142 paragraphs = emptyList()143 resumeOffset = 0144 mutableState.update { NovelTtsUiState() }145 }146147 internal fun retire() {148 generation.update { it + 1 }149 job.cancel()150 mutableState.update { NovelTtsUiState() }151 }152153 internal suspend fun closeAndJoin() {154 retire()155 withContext(NonCancellable) { job.join() }156 }157158 private fun launchPlayback() {159 val token = generation.updateAndGet { it + 1 }160 playbackJob = scope.launch {161 val call = requireNotNull(currentCoroutineContext()[Job])162 fun admitted() = call.isActive && job.isActive && parentJob.isActive && isOwnerOpen() && token == generation.value163 try {164 while (admitted() && mutableState.value.playback == NovelTtsPlaybackState.Playing) {165 val paragraphIndex = mutableState.value.paragraphIndex166 val paragraph = paragraphs.getOrNull(paragraphIndex) ?: break167 val offset = resumeOffset.coerceIn(0, paragraph.length)168 if (offset < paragraph.length) {169 service.speak(paragraph.substring(offset), request) { start, end ->170 if (admitted()) mutableState.update { current ->171 if (admitted() && current.playback == NovelTtsPlaybackState.Playing) current.copy(172 wordStart = (offset + start).coerceIn(0, paragraph.length),173 wordEnd = (offset + end).coerceIn(0, paragraph.length),174 ) else current175 }176 }177 }178 ensureCurrent(call)179 if (!admitted() || mutableState.value.playback != NovelTtsPlaybackState.Playing) break180 if (paragraphIndex >= paragraphs.lastIndex) {181 mutableState.update { it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1) }182 break183 }184 resumeOffset = 0185 mutableState.update { it.copy(paragraphIndex = paragraphIndex + 1, wordStart = -1, wordEnd = -1) }186 }187 } catch (cancelled: CancellationException) {188 throw cancelled189 } catch (_: Throwable) {190 if (admitted()) mutableState.update {191 it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1)192 }193 }194 }195 }196197 private suspend fun haltCurrent() {198 generation.update { it + 1 }199 val previous = playbackJob200 previous?.cancel()201 withContext(NonCancellable) {202 previous?.join()203 service.stop()204 }205 playbackJob = null206 ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))207 }208}209