From 8c4c8a36551113f382d4b5ee42c1e748b1988e8d Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:42:15 +0530 Subject: [PATCH 01/16] Add files via upload --- Ttscontroller.kt | 1165 ++++++++++++++++++++++++++++ Ttscontrollertest.kt | 1718 ++++++++++++++++++++++++++++++++++++++++++ Ttsengine.kt | 344 +++++++++ 3 files changed, 3227 insertions(+) create mode 100644 Ttscontroller.kt create mode 100644 Ttscontrollertest.kt create mode 100644 Ttsengine.kt diff --git a/Ttscontroller.kt b/Ttscontroller.kt new file mode 100644 index 0000000..2387322 --- /dev/null +++ b/Ttscontroller.kt @@ -0,0 +1,1165 @@ +package dev.mirutime.feature.tts + +import android.os.SystemClock +import dev.mirutime.app.features.reader.document.BlockId +import dev.mirutime.app.features.reader.document.ReaderDocument +import dev.mirutime.core.log.MiruLog +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +enum class TtsStatus { Idle, Loading, Playing, Paused, Failed } + +/** Chapter hand-off the reader must resolve; the controller has no chapter list. */ +enum class TtsChapterDirection { Next, Previous } + +/** + * Text the rich TTS player renders. The reader parses the chapter, so it + * publishes the spoken sentence, its paragraph and the counterpart translation + * here; the in-app player and the system overlay then show the same plate. + */ +data class TtsPlayerText( + val sentence: String? = null, + val paragraph: String? = null, + val counterpart: String? = null, + val sentenceHighlightStart: Int = 0, + val sentenceHighlightEnd: Int = 0, + val chapterPercent: Int = 0, + val glowColorArgb: Long = 0L, +) + +data class TtsState( + val status: TtsStatus = TtsStatus.Idle, + val currentChunk: Int = 0, + val chunkCount: Int = 0, + val blockId: BlockId? = null, + val sentenceIndex: Int = 0, + val rangeStart: Int = 0, + val rangeEnd: Int = 0, + val translated: Boolean = false, + val atEnd: Boolean = false, + /** NoveLA-style estimate; zero until the chunk text is loaded. */ + val estimatedTotalSeconds: Int = 0, + val estimatedRemainingSeconds: Int = 0, + val message: String? = null, +) + +/** + * Small in-app TTS player. It uses the platform engine, speaks stable + * TtsChunker units, and exposes the current chunk/range for highlight. + * The cursor is persisted so a process death restores a paused position. + * Foreground playback/MediaSession/floating overlay are a later layer. + */ +class TtsController( + private val engine: TtsEngine, + private val scope: CoroutineScope, + private val sessions: TtsSessionStore = InMemoryTtsSessionStore(), + private val settingsStore: TtsSettingsStore = InMemoryTtsSettingsStore(), + /** Monotonic clock; tests inject the virtual scheduler time. */ + private val now: () -> Long = { SystemClock.elapsedRealtime() }, + private val voicePreviewer: TtsVoicePreviewer = NoopTtsVoicePreviewer, +) : TtsHandoffSource { + private val _state = MutableStateFlow(TtsState()) + override val state: StateFlow = _state.asStateFlow() + + private val _settings = MutableStateFlow(settingsStore.load().sanitized()) + val settings: StateFlow = _settings.asStateFlow() + + private val _capabilities = MutableStateFlow(TtsCapabilities()) + val capabilities: StateFlow = _capabilities.asStateFlow() + + // Conflated: a second arrow tap must not be dropped while the collector is + // still starting the first hand-off. The latest direction is what the user + // asked for, so dropping the older one is correct. + private val _chapterRequests = MutableSharedFlow( + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** + * Emitted when playback needs the reader to open another chapter (manual + * skip or auto-next). The reader owns the chapter list, loads the document + * and calls [play] so the controller never guesses what comes next. + */ + override val chapterRequests: SharedFlow = _chapterRequests.asSharedFlow() + + private val _sleepTimer = MutableStateFlow(null) + /** Running sleep timer, or null. A tick updates only [TtsSleepTimerState.remainingSeconds]. */ + val sleepTimer: StateFlow = _sleepTimer.asStateFlow() + + private val _playerText = MutableStateFlow(TtsPlayerText()) + + /** + * Text the rich player shows. The reader owns the document, so it publishes + * the current sentence/paragraph here instead of passing text through a + * service intent; the overlay renders the same plate as the in-app player. + */ + val playerText: StateFlow = _playerText.asStateFlow() + + fun updatePlayerText(value: TtsPlayerText) { + _playerText.value = value + } + + /** Stops playback after [minutes]. Setting a new timer replaces the old one. */ + fun setSleepTimer(minutes: Int) { + if (!sleepTimerAvailable()) return + clearSleepTimer() + val seconds = clampSleepTimerMinutes(minutes) * 60 + sleepDeadline = now() + seconds * 1000L + _sleepTimer.value = TtsSleepTimerState( + mode = TtsSleepTimerMode.Minutes, + remainingSeconds = seconds, + totalSeconds = seconds, + endsAtEpochMillis = System.currentTimeMillis() + seconds * 1000L, + ) + startSleepTicker() + } + + /** Stops at the end of the [chapters]th chapter counted from now. */ + fun setSleepTimerChapters(chapters: Int) { + if (!sleepTimerAvailable()) return + clearSleepTimer() + val count = clampSleepTimerChapters(chapters) + _sleepTimer.value = TtsSleepTimerState( + mode = TtsSleepTimerMode.Chapters, + chaptersRemaining = count, + chaptersTotal = count, + ) + } + + fun cancelSleepTimer() { + clearSleepTimer() + } + + /** A timer makes sense only while a TTS session exists and can still stop. */ + private fun sleepTimerAvailable(): Boolean = + chunks.isNotEmpty() && + _state.value.status != TtsStatus.Idle && + _state.value.status != TtsStatus.Failed + + private fun clearSleepTimer() { + sleepTimerJob?.cancel() + sleepTimerJob = null + sleepDeadline = 0L + _sleepTimer.value = null + } + + private fun startSleepTicker() { + sleepTimerJob = scope.launch { + while (true) { + val left = ((sleepDeadline - now()) / 1000L).coerceAtLeast(0L).toInt() + val current = _sleepTimer.value ?: return@launch + if (current.mode == TtsSleepTimerMode.Minutes && + current.remainingSeconds != left + ) { + _sleepTimer.value = current.copy(remainingSeconds = left) + } + if (left <= 0) { + // resetPlayback drops a hand-off that was requested just + // before the deadline, so waiting for Loading is unnecessary. + _sleepTimer.value = null + resetPlayback(clearSession = false) + return@launch + } + delay(250) + } + } + } + + /** + * True only while the pending chapter request came from the queue finishing + * the chapter (auto-next). A manual skip clears it first, so the reader + * never marks a chapter read the user skipped through (FR-082/FR-083). + */ + @Volatile + override var chapterEndedNaturally: Boolean = false + private set + + private var ready = false + private var pending: (() -> Unit)? = null + private var chunks: List = emptyList() + // Language of the current session. Translation is a page-level decision: + // parallel ORIGINAL_FIRST passes an empty translation map. A partially + // translated page keeps this flag for the whole session by design. + private var sessionTranslated = false + // Suffix sums of chunk text lengths: suffix[i] is "characters from chunk i + // to the end". Rebuilt only when chunks change, so the timer estimate is + // O(1) on every chunk/range update. + private var chunkCharSuffix: IntArray = IntArray(0) + private var current = 0 + private var active = false + // Platform utterance ids are unique per queue (not chunk indexes), so a + // late callback from a stopped queue cannot be mistaken for the current + // one. Cleared whenever the queue is paused/skipped/replaced. + private val utteranceChunks = java.util.concurrent.ConcurrentHashMap() + private var nextUtteranceId = 0 + private var queuedUpTo = -1 + private var bookUrl = "" + private var chapterIndex = 0 + private var voiceId: String? = _settings.value.voiceId + private var speed = _settings.value.speed + private var pitch = _settings.value.pitch + // Language slot the engine was last configured for, null until the first + // apply. Settings edits come through updateSettings(), so a seek inside the + // same slot must not reload prefs or re-hit the TTS binders. + private var appliedVoiceSlot: Boolean? = null + private var sleepTimerJob: Job? = null + private var sleepDeadline = 0L + // Set when a chapter hand-off is requested and not yet applied. Stop, pause, + // timer, close and explicit starts clear it, so a stale request can never + // resurrect playback. + @Volatile + private var handoffPending = false + private var handoffTimeout: Job? = null + + /** True while a chapter hand-off is between the request and its document. */ + val isHandoffPending: Boolean + get() = handoffPending + + // Snapshot for the reader's revert: stop() clears the persisted session, so + // the last spoken cursor would otherwise be lost. + private var _lastStoppedSession: TtsSession? = null + + /** Last session captured by a user Stop; null after a new start/resume. */ + override val lastStoppedSession: TtsSession? + get() = _lastStoppedSession + + /** + * Language the live session speaks; null when there is no session. The + * reader compares the language the page wants with this one, so a settings + * switch restarts the speech instead of waiting for the next session. + */ + override val sessionLanguage: TtsLanguage? + get() = when (_state.value.status) { + TtsStatus.Idle, TtsStatus.Failed -> null + else -> if (sessionTranslated) TtsLanguage.Translation else TtsLanguage.Original + } + + fun play( + document: ReaderDocument, + translations: Map = emptyMap(), + language: TtsLanguage = TtsLanguage.from(translations), + ) { + playFrom(document, translations, blockIndex = null, language = language) + } + + /** + * Starts at the first spoken chunk at or after [blockIndex]. The reader + * passes its visible anchor, so "Start here" never jumps back to the + * chapter top. A null blockIndex keeps the ordinary chapter start. + */ + fun playFrom( + document: ReaderDocument, + translations: Map = emptyMap(), + blockIndex: Int?, + charOffset: Int = 0, + language: TtsLanguage = TtsLanguage.from(translations), + ) { + voicePreviewer.stop() + handoffPending = false + _lastStoppedSession = null + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + if (next.isEmpty()) { + setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) + return + } + // A session speaks one language: the caller decides from the page mode, + // not from whichever block happens to be first. + sessionTranslated = language == TtsLanguage.Translation + applySavedSettings(sessionTranslated) + stopInternal(keepStatus = true) + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl + chapterIndex = document.chapterIndex + current = if (blockIndex == null) 0 else ttsStartIndex(next, blockIndex, charOffset) + active = true + MiruLog.event( + "tts", + "play", + "chunks" to next.size, + "chapter" to document.chapterIndex, + "block" to blockIndex, + "startChunk" to current, + "translated" to sessionTranslated, + "voice" to voiceId, + ) + persist(wasPlaying = true, immediate = true, background = true) + if (!ready) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } else { + speakFrom(current) + } + } + + /** + * Moves the cursor to [blockIndex] while keeping the transport state: a + * paused session only moves its cursor/highlight and stays paused, while a + * playing one re-queues from the new block. The mini player's paragraph + * arrows use this so a pause is never silently undone (FR-051). + */ + fun seekToBlock( + document: ReaderDocument, + translations: Map = emptyMap(), + blockIndex: Int, + charOffset: Int = 0, + language: TtsLanguage = TtsLanguage.from(translations), + ) { + if (_state.value.status != TtsStatus.Paused) { + playFrom(document, translations, blockIndex, charOffset, language) + return + } + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + if (next.isEmpty()) { + setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) + return + } + sessionTranslated = language == TtsLanguage.Translation + // Same slot = same voice/engine/speed, already applied: a paused chapter + // crossing must not reload settings or hit the engine binders again. + if (appliedVoiceSlot != sessionTranslated) applySavedSettings(sessionTranslated) + stopInternal(keepStatus = true) + pending = null + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl + chapterIndex = document.chapterIndex + current = ttsStartIndex(next, blockIndex, charOffset) + active = false + MiruLog.event( + "tts", + "seek", + "chunks" to next.size, + "chapter" to document.chapterIndex, + "block" to blockIndex, + "startChunk" to current, + ) + // Never starts speech: resume() is what moves a paused session. + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + + /** + * Rebuilds chunks from the current document/translation state and restores + * a paused cursor. Never starts speech, even if the session was playing. + */ + fun restore( + document: ReaderDocument, + translations: Map = emptyMap(), + session: TtsSession, + language: TtsLanguage = TtsLanguage.from(translations), + ): Boolean { + if (document.chapterUrl != session.chapterUrl) return false + if (document.chapterIndex != session.chapterIndex) return false + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + val cursor = resolveTtsCursor(next, session) ?: return false + stopInternal(keepStatus = true) + pending = null + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl.ifBlank { session.bookUrl } + chapterIndex = document.chapterIndex + current = cursor + active = false + sessionTranslated = language == TtsLanguage.Translation + val restoredSelection = sessionVoiceSelection(_settings.value, sessionTranslated) + // The engine belongs to the session's slot, not to the original one: + // a translated session must speak with the translated engine. + applyEngine(restoredSelection.engineId) + // A saved session keeps its voice only while it speaks the same + // language. Switching parallel order must pick the new language's slot. + val sameLanguage = session.translated == sessionTranslated + voiceId = if (sameLanguage) { + session.voiceId ?: restoredSelection.voiceId + } else { + restoredSelection.voiceId + } + speed = clampTtsSpeed(session.speed) + pitch = clampTtsPitch(session.pitch) + applyPlaybackSettings() + MiruLog.event( + "tts", + "restore", + "translated" to sessionTranslated, + "voice" to voiceId, + ) + setState(chunkState(cursor, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + return true + } + + /** + * True only while the pause came from audio-focus loss (call, navigation + * prompt). Every explicit pause path — notification, headset media button, + * becoming-noisy, user — clears it, so a later focus gain can never undo a + * user pause (FR-045/FR-046). + */ + @Volatile + var pausedByFocusLoss: Boolean = false + private set + + fun pause() { + MiruLog.event("tts", "pause-request", "source" to "user") + pausedByFocusLoss = false + pauseInternal(cancelSleepTimer = true) + } + + /** Pause caused by a transient audio-focus loss; a focus gain may resume it. */ + fun pauseForFocusLoss() { + if (!active && _state.value.status != TtsStatus.Loading) return + MiruLog.event("tts", "pause-request", "source" to "focus") + pausedByFocusLoss = true + pauseInternal(cancelSleepTimer = false) + } + + /** + * Pause not initiated by the user (headphone unplugged, service teardown). + * The sleep timer keeps running: the user did not ask to cancel it. + */ + fun pauseFromSystem() { + MiruLog.event("tts", "pause-request", "source" to "system") + pauseInternal(cancelSleepTimer = false) + } + + private fun pauseInternal(cancelSleepTimer: Boolean) { + handoffPending = false + if (cancelSleepTimer) clearSleepTimer() + if (!active && _state.value.status != TtsStatus.Loading) return + pending = null + invalidateUtterances() + engine.stop() + active = false + setState(_state.value.copy(status = TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + + override fun resume() { + voicePreviewer.stop() + handoffPending = false + _lastStoppedSession = null + pausedByFocusLoss = false + if (chunks.isEmpty()) return + active = true + applyPlaybackSettings() + persist(wasPlaying = true, immediate = true, background = true) + if (!ready) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + return + } + speakFrom(current) + } + + /** + * Stops the platform queue and resumes at the neighbouring chunk. While + * paused the cursor still moves (and persists) without speaking; at an + * edge the current chunk is restarted only when speech is already active. + */ + fun skipNextChunk() = skipChunkBy(1) + + fun skipPreviousChunk() = skipChunkBy(-1) + + /** + * Stops the current utterance immediately and asks the reader to load the + * next/previous chapter. The reader calls [play] on the new document, so a + * failed navigation can never leave the old chapter speaking in parallel. + */ + fun skipNextChapter() = requestChapter(TtsChapterDirection.Next) + + fun skipPreviousChapter() = requestChapter(TtsChapterDirection.Previous) + + private fun skipChunkBy(delta: Int) { + if (chunks.isEmpty()) return + invalidateUtterances() + val target = (current + delta).coerceIn(0, chunks.lastIndex) + if (target == current) { + if (active && ready) speakFrom(current) + return + } + current = target + if (active) { + if (ready) { + speakFrom(target) + } else { + setState(chunkState(target, TtsStatus.Loading)) + pending = { speakFrom(target) } + } + } else { + setState(chunkState(target, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + } + + private fun requestChapter(direction: TtsChapterDirection) { + if (chunks.isEmpty()) return + // Manual skip: never a natural end, even when the cursor sits on the + // last chunk (atEnd would be true there anyway). + chapterEndedNaturally = false + active = false + pending = null + // Mark the hand-off before the Paused state reaches the service: the + // service keeps its wake lock while a hand-off is pending. + handoffPending = true + invalidateUtterances() + engine.stop() + // Keep the old cursor paused so a rejected request can resume it. + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + requestHandoff(direction) + } + + private fun requestHandoff(direction: TtsChapterDirection) { + handoffPending = true + _chapterRequests.tryEmit(direction) + handoffTimeout?.cancel() + handoffTimeout = scope.launch { + delay(HandoffTimeoutMs) + if (!handoffPending) return@launch + // No chapter arrived: drop the pending hand-off instead of holding + // Loading (and the service wake lock) forever. + handoffPending = false + if (_state.value.status == TtsStatus.Paused || _state.value.status == TtsStatus.Loading) { + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + MiruLog.w("tts", "event=tts-handoff-timeout") + } + } + + fun toggle( + document: ReaderDocument, + translations: Map = emptyMap(), + language: TtsLanguage = TtsLanguage.from(translations), + ) { + when (_state.value.status) { + TtsStatus.Playing, TtsStatus.Loading -> pause() + // A paused session resumes only while it speaks the same language: + // a settings switch must not resume the old text in the old voice. + TtsStatus.Paused -> if (language != sessionLanguage) { + playFrom( + document = document, + translations = translations, + blockIndex = chunks.getOrNull(current)?.blockId?.index, + language = language, + ) + } else { + resume() + } + else -> play(document, translations, language) + } + } + + /** + * Starts speech on a chapter the reader loaded for a [chapterRequests] + * hand-off. A request is consumed only once: Stop, Pause, a new start or + * the sleep timer clears it, so a stale hand-off cannot resurrect playback. + */ + override fun playHandoff( + document: ReaderDocument, + translations: Map, + language: TtsLanguage, + ): Boolean { + if (!handoffPending) return false + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + play(document, translations, language) + return true + } + + override fun stop() { + _lastStoppedSession = sessions.load() + clearSleepTimer() + resetPlayback(clearSession = true) + } + + private fun resetPlayback(clearSession: Boolean) { + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + pausedByFocusLoss = false + active = false + pending = null + invalidateUtterances() + engine.stop() + // Persist before chunks/bookUrl are cleared, or the cursor is lost. + if (!clearSession) persist(wasPlaying = false, immediate = true) + chunks = emptyList() + chunkCharSuffix = IntArray(0) + current = 0 + sessionTranslated = false + bookUrl = "" + chapterIndex = 0 + if (clearSession) sessions.clear(immediate = true) + setState(TtsState(status = TtsStatus.Idle)) + } + + fun close() { + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + clearSleepTimer() + active = false + pending = null + invalidateUtterances() + engine.stop() + engine.shutdown() + voicePreviewer.shutdown() + ready = false + publishCapabilities() + } + + /** + * Persists and applies immediately; a restored session still wins later. + * The UI calls this on release, so voice/rate/pitch changes stop and + * re-queue the current chunk while appearance-only fields never interrupt + * speech. An engine switch re-initializes and resumes the same chunk. + */ + fun updateSettings(settings: TtsSettings) { + val previous = _settings.value + val sanitized = settings.sanitized() + // The session speaks one language: edits apply to that slot. + val previousSelection = previous.sanitized().voiceForSession(sessionTranslated) + val nextSelection = sanitized.voiceForSession(sessionTranslated) + // Only the slot this session speaks can affect playback: editing the + // other language's voice must not restart the current chunk. + val playbackChanged = ttsPlaybackChanged(previous, sanitized, sessionTranslated) + val engineChanged = previousSelection.engineId != nextSelection.engineId + _settings.value = sanitized + settingsStore.save(sanitized) + voiceId = nextSelection.voiceId + speed = sanitized.speed + pitch = sanitized.pitch + + if (engineChanged) { + val wasActive = active + invalidateUtterances() + engine.stop() + if (wasActive) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } + val reinitializing = applyEngine(nextSelection.engineId) + if (!reinitializing) { + // Already on the requested engine (e.g. explicit default id); + // no readiness callback will arrive, so resume now. + pending = null + applyPlaybackSettings() + if (wasActive) speakFrom(current) + } + } else if (playbackChanged) { + applyPlaybackSettings() + if (active && ready && _state.value.status == TtsStatus.Playing) { + speakFrom(current) + } + } + refreshTimeEstimate() + publishCapabilities() + } + + override fun switchLanguage( + document: ReaderDocument, + translations: Map, + blockIndex: Int, + language: TtsLanguage, + ) { + seekToBlock(document, translations, blockIndex, charOffset = 0, language = language) + } + + fun resetSettings() { + updateSettings(TtsSettings()) + } + + /** + * Re-discovers installed engines (including ones installed while the app + * is running). The voice picker calls this on open, so the catalog never + * needs an app restart or a hardcoded engine list. + */ + fun refreshEngines() { + engine.refreshEngines() + publishCapabilities() + } + + /** Short sample with the current voice/rate/pitch; pauses a live reading. */ + fun testUtterance(text: String) { + if (!ready) { + setState( + _state.value.copy( + status = TtsStatus.Failed, + message = "TTS unavailable", + ), + ) + return + } + if (active) pauseFromSystem() + applyPlaybackSettings() + engine.preview(text) + } + + /** Retries after a failure; re-creates the engine when it never came up. */ + fun retry() { + if (chunks.isEmpty()) { + setState(TtsState()) + return + } + applySavedSettings(sessionTranslated) + invalidateUtterances() + setState(chunkState(current, TtsStatus.Loading)) + if (ready) { + speakFrom(current) + } else { + pending = { speakFrom(current) } + engine.restart() + } + } + + private fun speakFrom(index: Int) { + if (!ready || chunks.isEmpty()) return + invalidateUtterances() + current = index.coerceIn(0, chunks.lastIndex) + active = true + setState(chunkState(current, TtsStatus.Playing)) + // Persist before the platform callback so skipping cannot lose the + // cursor if speech never starts (engine race, process death). + persist(wasPlaying = true, immediate = true, background = true) + engine.stop() + val end = minOf(current + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + enqueueRange(current, end, flushFirst = true) + } + + private fun enqueueRange(startIndex: Int, endIndex: Int, flushFirst: Boolean): Boolean { + for (i in startIndex..endIndex) { + val utteranceId = ++nextUtteranceId + utteranceChunks[utteranceId] = i + val flush = flushFirst && i == startIndex + if (!engine.speak(chunks[i].text, utteranceId, flush)) { + utteranceChunks.remove(utteranceId) + if (i == current) { + // Only abort playback if the active chunk itself failed to queue. + engine.stop() + setState( + _state.value.copy( + status = TtsStatus.Failed, + message = "TTS speak failed", + ), + ) + active = false + return false + } + return true + } + queuedUpTo = i + } + return true + } + + private fun topUpQueue(fromIndex: Int) { + if (!active || !ready || chunks.isEmpty()) return + val targetEnd = minOf(fromIndex + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + if (queuedUpTo < targetEnd) { + val start = maxOf(fromIndex, queuedUpTo + 1) + if (start <= targetEnd) { + enqueueRange(start, targetEnd, flushFirst = false) + } + } + } + + // Status/chunk transitions only; never the spoken text. + private fun setState(next: TtsState) { + val previous = _state.value + _state.value = next + if (previous.status != next.status || previous.currentChunk != next.currentChunk) { + MiruLog.event("tts", "state", "status" to next.status, "chunk" to next.currentChunk) + } + } + + private fun chunkState(index: Int, status: TtsStatus): TtsState { + val chunk = chunks.getOrNull(index) ?: return TtsState(status = status) + val totalSeconds = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) + val remainingSeconds = ttsEstimatedSeconds( + chunkCharSuffix.getOrElse(index) { 0 }, + speed, + ) + return TtsState( + status = status, + currentChunk = index, + chunkCount = chunks.size, + blockId = chunk.blockId, + sentenceIndex = chunk.sentenceIndex, + // Do not paint the whole sentence before the platform reports its + // first word range; that looked like a full-sentence flash. + rangeStart = chunk.startOffset, + rangeEnd = if (status == TtsStatus.Playing || status == TtsStatus.Loading) { + chunk.startOffset + } else { + chunk.endOffset + }, + translated = chunk.translated, + atEnd = index >= chunks.lastIndex, + estimatedTotalSeconds = totalSeconds, + estimatedRemainingSeconds = remainingSeconds, + ) + } + + private fun rebuildChunkCharStats() { + chunkCharSuffix = IntArray(chunks.size + 1) + for (index in chunks.indices.reversed()) { + chunkCharSuffix[index] = chunkCharSuffix[index + 1] + chunks[index].text.length + } + } + + /** Speed is live; a changed rate must not leave the old estimate behind. */ + private fun refreshTimeEstimate() { + if (chunks.isEmpty()) return + val total = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) + val remaining = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(current) { 0 }, speed) + val state = _state.value + if (state.estimatedTotalSeconds == total && + state.estimatedRemainingSeconds == remaining + ) { + return + } + setState( + state.copy( + estimatedTotalSeconds = total, + estimatedRemainingSeconds = remaining, + ), + ) + } + + private fun stopInternal(keepStatus: Boolean) { + pausedByFocusLoss = false + active = false + invalidateUtterances() + engine.stop() + if (!keepStatus) setState(TtsState()) + } + + private fun invalidateUtterances() { + utteranceChunks.clear() + queuedUpTo = -1 + } + + private fun onEngineReady() { + ready = true + applyPlaybackSettings() + publishCapabilities() + pending?.invoke() + pending = null + } + + private fun applySavedSettings(translated: Boolean = false) { + appliedVoiceSlot = translated + val saved = settingsStore.load().sanitized() + _settings.value = saved + val selection = sessionVoiceSelection(saved, translated) + voiceId = selection.voiceId + speed = saved.speed + pitch = saved.pitch + applyEngine(selection.engineId) + applyPlaybackSettings() + publishCapabilities() + } + + /** + * The text a session speaks. An Original session never reads the + * translation; a Translation session reads it and falls back to the + * original text while the translation has not arrived yet. + */ + private fun sessionTranslations( + language: TtsLanguage, + translations: Map, + ): Map { + if (language == TtsLanguage.Original) return emptyMap() + if (translations.isEmpty()) { + MiruLog.event("tts", "text-fallback", "reason" to "translation-missing") + } + return translations + } + + /** + * The voice slot a session speaks with. A translated session without a + * translated voice falls back to the original one; the fallback is logged + * so a wrong language is visible in the diagnostics. + */ + private fun sessionVoiceSelection( + settings: TtsSettings, + translated: Boolean, + ): TtsVoiceSelection { + val sanitized = settings.sanitized() + val selection = sanitized.voiceForSession(translated) + if (translated && sanitized.translatedVoiceId == null) { + MiruLog.event("tts", "voice-fallback", "reason" to "translated-voice-unset") + } + return selection + } + + /** Re-reads the durable TTS prefs after a backup restore. */ + fun reloadSettings() { + // Restore runs on an IO thread; the controller and engine are main-confined. + scope.launch { + // The session prefs were written directly by the backup store. + sessions.invalidate() + val saved = settingsStore.load().sanitized() + val selection = saved.voiceForSession(sessionTranslated) + val targetEngine = selection.engineId ?: engine.defaultEngineId + if (active && targetEngine != null && targetEngine != engine.currentEngineId) { + // The engine restarts and its queue dies with it: the session + // must re-queue the current chunk instead of staying "Playing" + // without sound. + invalidateUtterances() + engine.stop() + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } + applySavedSettings(translated = sessionTranslated) + } + } + + /** Auditions a voice without changing the selected voice/engine. */ + fun previewVoice( + voiceId: String?, + engineId: String?, + speed: Float, + pitch: Float, + text: String, + onUnavailable: () -> Unit = {}, + ) { + if (active) pauseFromSystem() + voicePreviewer.preview(voiceId, engineId, speed, pitch, text, onUnavailable) + } + + fun stopVoicePreview() = voicePreviewer.stop() + + /** Returns true when the platform engine is being re-initialized. */ + private fun applyEngine(id: String?): Boolean { + val target = id ?: engine.defaultEngineId + if (target != null && target != engine.currentEngineId) { + ready = false + engine.selectEngine(target) + return true + } + return false + } + + private fun applyPlaybackSettings() { + if (!ready) return + speed = clampTtsSpeed(speed) + pitch = clampTtsPitch(pitch) + engine.setRate(speed) + engine.setPitch(pitch) + if (!engine.setVoice(voiceId)) { + // A saved engine voice may be gone after an engine switch. + MiruLog.event("tts", "voice-fallback", "reason" to "voice-unavailable") + voiceId = null + engine.setVoice(null) + } + } + + private fun publishCapabilities() { + _capabilities.value = TtsCapabilities( + ready = ready, + // Auxiliary engine scans can still provide a usable catalog while + // the selected engine is down; the picker must offer another + // engine instead of a dead "unavailable" wall. + voices = engine.voices, + engines = engine.engines, + currentEngineId = engine.currentEngineId, + defaultEngineId = engine.defaultEngineId, + ) + } + + private fun persist( + wasPlaying: Boolean, + immediate: Boolean = false, + background: Boolean = false, + ) { + val chunk = chunks.getOrNull(current) ?: return + if (bookUrl.isBlank()) return + sessions.save( + TtsSession( + bookUrl = bookUrl, + chapterIndex = chapterIndex, + chapterUrl = chunk.blockId.chapterUrl, + blockIndex = chunk.blockId.index, + sentenceIndex = chunk.sentenceIndex, + charOffset = chunk.startOffset, + voiceId = voiceId, + speed = speed, + pitch = pitch, + wasPlaying = wasPlaying, + translated = sessionTranslated, + textHash = "${chunk.text.length}:${chunk.text.hashCode()}", + updatedAt = System.currentTimeMillis(), + ), + immediate, + background, + ) + } + + private val listener = object : TtsEngineListener { + override fun onReady(ok: Boolean) { + if (ok) { + onEngineReady() + } else { + active = false + setState(TtsState(status = TtsStatus.Failed, message = "TTS unavailable")) + pending = null + } + } + + override fun onVoicesChanged() { + publishCapabilities() + } + + override fun onStart(utteranceId: Int) { + // Only utterances queued by the current speakFrom call are known; + // a stopped/replaced queue no longer has any valid ids. + val index = utteranceChunks[utteranceId] ?: return + if (!active || index < current) return + current = index + setState(chunkState(index, TtsStatus.Playing)) + persist(wasPlaying = true, immediate = true, background = true) + topUpQueue(index) + } + + override fun onDone(utteranceId: Int) { + val index = utteranceChunks[utteranceId] ?: return + if (index < chunks.lastIndex || !active) return + active = false + persist(wasPlaying = false, immediate = true) + val timer = _sleepTimer.value + if (timer?.mode == TtsSleepTimerMode.Chapters) { + val left = timer.chaptersRemaining - 1 + if (left <= 0) { + clearSleepTimer() + invalidateUtterances() + setState( + _state.value.copy( + status = TtsStatus.Idle, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + return + } + // The chapter timer continues chapters on its own, even when + // auto-next is off: that is what "stop after N chapters" means. + _sleepTimer.value = timer.copy(chaptersRemaining = left) + chapterEndedNaturally = true + setState( + _state.value.copy( + status = TtsStatus.Loading, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + requestHandoff(TtsChapterDirection.Next) + return + } + if (_settings.value.autoNextChapter) { + // Keep the status active across the chapter load so the + // foreground service is not torn down between chapters. + chapterEndedNaturally = true + setState( + _state.value.copy( + status = TtsStatus.Loading, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + requestHandoff(TtsChapterDirection.Next) + } else { + // Playback ends here; a running minutes timer has nothing left + // to stop and would only fire into an idle session. + clearSleepTimer() + setState( + _state.value.copy( + status = TtsStatus.Idle, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + } + } + + override fun onError(utteranceId: Int?) { + // Late errors from a stopped/skipped queue must not fail this one. + if (utteranceId != null && utteranceChunks[utteranceId] == null) return + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + clearSleepTimer() + setState(_state.value.copy(status = TtsStatus.Failed, message = "TTS error")) + active = false + persist(wasPlaying = false, immediate = true) + } + + override fun onRangeStart(utteranceId: Int, start: Int, end: Int) { + val index = utteranceChunks[utteranceId] ?: return + val state = _state.value + // Late callbacks from a paused/skipped/replaced queue are not in + // the map (or no longer match the live chunk); never move the + // highlight for them. + if (!active || index != current || state.currentChunk != index) return + val chunk = chunks.getOrNull(index) ?: return + if (state.blockId != chunk.blockId) return + val base = chunk.startOffset + val consumed = start.coerceIn(0, chunk.text.length) + val remainingChars = (chunkCharSuffix.getOrElse(index) { 0 } - consumed) + .coerceAtLeast(0) + setState( + state.copy( + rangeStart = base + start, + rangeEnd = base + end, + estimatedRemainingSeconds = ttsEstimatedSeconds(remainingChars, speed), + ), + ) + } + } + + init { + engine.listener = listener + publishCapabilities() + if (engine.isReady) onEngineReady() + } +} + +/** + * First chunk at or after the reader's visible block. Chunks are ordered by + * block, so a heading/image without speech is skipped rather than failing. + * [charOffset] only matters when the anchor points inside a spoken block. + */ +internal fun ttsStartIndex( + chunks: List, + blockIndex: Int, + charOffset: Int, +): Int { + if (chunks.isEmpty()) return 0 + if (charOffset > 0) { + chunks.indexOfFirst { chunk -> + chunk.blockId.index == blockIndex && + charOffset >= chunk.startOffset && + charOffset < chunk.endOffset + }.takeIf { it >= 0 }?.let { return it } + } + return chunks.indexOfFirst { it.blockId.index >= blockIndex } + .takeIf { it >= 0 } + ?: chunks.lastIndex +} + +/** A chapter hand-off that never arrives must not hold Loading forever. */ +private const val HandoffTimeoutMs = 30_000L +private const val LOOKAHEAD_CHUNKS = 4 diff --git a/Ttscontrollertest.kt b/Ttscontrollertest.kt new file mode 100644 index 0000000..da167f8 --- /dev/null +++ b/Ttscontrollertest.kt @@ -0,0 +1,1718 @@ +package dev.mirutime.feature.tts + +import dev.mirutime.app.features.reader.document.BlockId +import dev.mirutime.app.features.reader.document.BlockKind +import dev.mirutime.app.features.reader.document.ReaderBlock +import dev.mirutime.app.features.reader.document.ReaderDocument +import dev.mirutime.app.features.reader.document.SentenceSpan +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TtsControllerTest { + private val chapterUrl = "local://book#chapter=1" + private val document = ReaderDocument( + bookUrl = "local://book", + chapterUrl = chapterUrl, + chapterIndex = 1, + title = "Chapter", + blocks = listOf( + ReaderBlock( + id = BlockId(chapterUrl, 0), + kind = BlockKind.Paragraph, + original = "First sentence. Second sentence.", + sentences = listOf(SentenceSpan(0, 15), SentenceSpan(16, 31)), + ), + ), + ) + + private fun session( + sentence: Int = 1, + offset: Int = 16, + playing: Boolean = true, + chapter: String = chapterUrl, + ) = TtsSession( + bookUrl = "local://book", + chapterIndex = 1, + chapterUrl = chapter, + blockIndex = 0, + sentenceIndex = sentence, + charOffset = offset, + wasPlaying = playing, + ) + + private class FakeEngine( + private var ready: Boolean = true, + ) : TtsEngine { + override var listener: TtsEngineListener? = null + override val isReady: Boolean + get() = ready + + val spoken = mutableListOf() + val spokenTexts = mutableListOf() + val flushFlags = mutableListOf() + val previews = mutableListOf() + var stops = 0 + var failSpeak = false + val availableVoices = setOf("voice-a", "voice-b") + var voice: String? = null + var appliedRate = 1f + var appliedPitch = 1f + // Engine binder traffic a paused chapter crossing must not repeat. + var voiceCatalogReads = 0 + var voiceSets = 0 + var rateSets = 0 + var pitchSets = 0 + var deferEngineReady = false + var pendingEngineId: String? = null + var refreshCount = 0 + var installedEngines = listOf( + TtsEngineInfo("default", "Default", true), + TtsEngineInfo("engine-b", "Second", false), + ) + override var currentEngineId: String? = "default" + override val defaultEngineId: String? = "default" + + override val voices: List + get() { + voiceCatalogReads += 1 + return availableVoices.map { name -> + TtsVoice(name, name, java.util.Locale.US, 400, currentEngineId) + } + } + + override val engines: List + get() = installedEngines + + override fun refreshEngines() { + refreshCount += 1 + listener?.onVoicesChanged() + } + + override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { + spoken += utteranceId + spokenTexts += text + flushFlags += flush + return !failSpeak + } + + override fun preview(text: String): Boolean { + previews += text + return true + } + + override fun stop() { + stops += 1 + } + + override fun setVoice(name: String?): Boolean { + voiceSets += 1 + if (name != null && name !in availableVoices) return false + voice = name + return true + } + + override fun setRate(rate: Float) { + rateSets += 1 + appliedRate = rate + } + + override fun setPitch(pitch: Float) { + pitchSets += 1 + appliedPitch = pitch + } + + override fun selectEngine(engineId: String): Boolean { + currentEngineId = engineId + if (deferEngineReady) { + pendingEngineId = engineId + ready = false + return true + } + ready = true + listener?.onReady(true) + return true + } + + fun completeEngineInit() { + pendingEngineId = null + ready = true + listener?.onReady(true) + } + + override fun restart() { + ready = true + listener?.onReady(true) + } + + override fun shutdown() = Unit + } + + @Test + fun `restore is paused and never speaks`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store) + + assertTrue(controller.restore(document, emptyMap(), session())) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + assertTrue(engine.spoken.isEmpty()) + } + + @Test + fun `persisted playing rehydrates as paused`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + + assertTrue(controller.restore(document, emptyMap(), session(playing = true))) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + @Test + fun `restore rejects a mismatched chapter`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + + assertTrue( + !controller.restore(document, emptyMap(), session(chapter = "local://book#chapter=2")), + ) + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `resume continues from the restored cursor`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.restore(document, emptyMap(), session()) + + controller.resume() + + assertEquals(1, engine.spoken.size) + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + } + + @Test + fun `a stale utterance error does not fail the live session`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + val live = engine.spoken.last() + + engine.listener?.onError(live + 100_000) + assertEquals(TtsStatus.Playing, controller.state.value.status) + + engine.listener?.onError(live) + assertEquals(TtsStatus.Failed, controller.state.value.status) + } + + @Test + fun `a handoff that never arrives leaves the session paused`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + + controller.skipNextChapter() + assertEquals(TtsStatus.Paused, controller.state.value.status) + + advanceTimeBy(30_001) + runCurrent() + + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + @Test + fun `a speak failure stops the already queued chunks`() = runTest { + val engine = FakeEngine().apply { failSpeak = true } + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + + controller.play(document, emptyMap()) + + assertEquals(TtsStatus.Failed, controller.state.value.status) + // One stop before queueing, one stop on the failure. + assertTrue(engine.stops >= 2) + } + + @Test + fun `state carries a remaining-time estimate from spoken characters`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + + controller.play(document, emptyMap()) + + val state = controller.state.value + assertTrue(state.estimatedTotalSeconds > 0) + assertTrue(state.estimatedRemainingSeconds in 1..state.estimatedTotalSeconds) + } + + @Test + fun `play persists the cursor immediately in the background`() = runTest { + val store = RecordingSessionStore() + val controller = TtsController(FakeEngine(), this, store) + + controller.play(document, emptyMap()) + + assertNotNull(store.saved) + assertTrue(store.savedImmediate) + assertTrue(store.savedBackground) + assertEquals(true, store.saved?.wasPlaying) + } + + @Test + fun `speed changes update the live time estimate`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + val normal = controller.state.value.estimatedRemainingSeconds + + controller.updateSettings(TtsSettings(speed = 2f)) + + assertTrue(controller.state.value.estimatedRemainingSeconds < normal) + } + + @Test + fun `only a focus-loss pause can auto-resume`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertFalse(controller.pausedByFocusLoss) + + controller.pauseForFocusLoss() + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertTrue(controller.pausedByFocusLoss) + + controller.resume() + assertFalse(controller.pausedByFocusLoss) + assertEquals(TtsStatus.Playing, controller.state.value.status) + + // A headset/notification pause after a focus-loss pause cancels the + // auto-resume, so the call ending cannot start speech the user stopped. + controller.pauseForFocusLoss() + assertTrue(controller.pausedByFocusLoss) + controller.pause() + assertFalse(controller.pausedByFocusLoss) + + controller.resume() + controller.stop() + assertFalse(controller.pausedByFocusLoss) + } + + @Test + fun `only a finished queue reports a natural chapter end`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.updateSettings(TtsSettings(autoNextChapter = true)) + controller.play(document, emptyMap()) + + // A manual skip from the last chunk is not a natural end, even though + // the state reports atEnd = true there. + controller.skipNextChunk() + assertTrue(controller.state.value.atEnd) + controller.skipNextChapter() + assertFalse(controller.chapterEndedNaturally) + + // The queue finishing the last chunk is the only natural end. + controller.play(document, emptyMap()) + engine.listener?.onDone(engine.spoken.last()) + assertTrue(controller.chapterEndedNaturally) + + // A manual skip after that must clear it again. + controller.skipNextChapter() + assertFalse(controller.chapterEndedNaturally) + } + + @Test + fun `paragraph seek keeps a paused session paused`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + controller.skipNextChunk() + controller.pause() + assertEquals(1, controller.state.value.currentChunk) + val spoken = engine.spoken.size + + controller.seekToBlock(document, emptyMap(), blockIndex = 0) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(0, controller.state.value.currentChunk) + assertEquals(spoken, engine.spoken.size) + } + + @Test + fun `paused seek to another chapter persists the cursor and never speaks`() = runTest { + val engine = FakeEngine() + val sessions = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, sessions) + controller.play(document, emptyMap()) + controller.pause() + val spoken = engine.spokenTexts.size + val otherChapter = "local://book#chapter=2" + val other = ReaderDocument( + bookUrl = "local://book", + chapterUrl = otherChapter, + chapterIndex = 2, + title = "Chapter 2", + blocks = listOf( + ReaderBlock( + id = BlockId(otherChapter, 0), + kind = BlockKind.Paragraph, + original = "Chapter two.", + sentences = listOf(SentenceSpan(0, 11)), + ), + ReaderBlock( + id = BlockId(otherChapter, 1), + kind = BlockKind.Paragraph, + original = "Second paragraph.", + sentences = listOf(SentenceSpan(0, 17)), + ), + ), + ) + + controller.seekToBlock(other, emptyMap(), blockIndex = 1) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(spoken, engine.spokenTexts.size) + val saved = sessions.load() + assertEquals(2, saved?.chapterIndex) + assertEquals(otherChapter, saved?.chapterUrl) + assertEquals(1, saved?.blockIndex) + assertEquals(false, saved?.wasPlaying) + } + + @Test + fun `paragraph seek keeps a playing session playing`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + controller.skipNextChunk() + assertEquals(1, controller.state.value.currentChunk) + + controller.seekToBlock(document, emptyMap(), blockIndex = 0) + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(0, controller.state.value.currentChunk) + } + + /** + * A paused chapter crossing used to reload settings and re-apply the engine + * voice: the voice catalog twice plus rate/pitch/voice binders on the + * scroll path, although the spoken language slot did not change. + */ + @Test + fun `seek in the same language leaves the engine alone`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + val translations = mapOf(0 to "Первый. Второй.") + controller.play(document, translations) + controller.pause() + engine.voiceCatalogReads = 0 + engine.voiceSets = 0 + engine.rateSets = 0 + engine.pitchSets = 0 + + controller.seekToBlock(document, translations, blockIndex = 0) + + assertEquals(0, engine.voiceCatalogReads) + assertEquals(0, engine.voiceSets) + assertEquals(0, engine.rateSets) + assertEquals(0, engine.pitchSets) + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + /** The other slot has its own voice/engine, so a switch must re-apply them. */ + @Test + fun `language switch re-applies the voice slot`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document, mapOf(0 to "Первый. Второй.")) + controller.pause() + engine.voiceSets = 0 + + controller.switchLanguage(document, emptyMap(), blockIndex = 0, language = TtsLanguage.Original) + + assertTrue(engine.voiceSets > 0) + } + + @Test + fun `stop clears the persisted session`() = runTest { + val store = InMemoryTtsSessionStore() + val controller = TtsController(FakeEngine(), this, store) + controller.restore(document, emptyMap(), session()) + assertTrue(store.load() != null) + + controller.stop() + + assertNull(store.load()) + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `playFrom starts at the visible block instead of the chapter top`() = runTest { + val multiBlock = ReaderDocument( + bookUrl = "local://book", + chapterUrl = chapterUrl, + chapterIndex = 1, + title = "Chapter", + blocks = (0..4).map { index -> + ReaderBlock( + id = BlockId(chapterUrl, index), + kind = BlockKind.Paragraph, + original = "Block $index sentence.", + sentences = listOf(SentenceSpan(0, 19)), + ) + }, + ) + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + + controller.playFrom(multiBlock, emptyMap(), blockIndex = 3) + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(3, controller.state.value.currentChunk) + assertEquals(3, controller.state.value.blockId?.index) + assertEquals(5, controller.state.value.chunkCount) + assertEquals(2, engine.spoken.size) + } + + @Test + fun `playFrom skips a block without speech and lands on the next one`() { + val chunks = listOf( + TtsChunk(BlockId(chapterUrl, 0), 0, "one", 0, 3, false), + TtsChunk(BlockId(chapterUrl, 2), 0, "two", 0, 3, false), + ) + + assertEquals(1, ttsStartIndex(chunks, blockIndex = 1, charOffset = 0)) + assertEquals(1, ttsStartIndex(chunks, blockIndex = 2, charOffset = 0)) + assertEquals(0, ttsStartIndex(chunks, blockIndex = 0, charOffset = 0)) + assertEquals(1, ttsStartIndex(chunks, blockIndex = 9, charOffset = 0)) + } + + @Test + fun `playFrom uses the char offset inside a long block`() { + val chunks = listOf( + TtsChunk(BlockId(chapterUrl, 0), 0, "one", 0, 10, false), + TtsChunk(BlockId(chapterUrl, 0), 1, "two", 10, 20, false), + ) + + assertEquals(1, ttsStartIndex(chunks, blockIndex = 0, charOffset = 12)) + } + + @Test + fun `play applies persisted settings and engine`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings( + voiceId = "voice-a", + engineId = "engine-b", + speed = 1.5f, + pitch = 0.8f, + ), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + controller.play(document) + + assertEquals("engine-b", engine.currentEngineId) + assertEquals("voice-a", engine.voice) + assertEquals(1.5f, engine.appliedRate, 0.001f) + assertEquals(0.8f, engine.appliedPitch, 0.001f) + assertEquals(TtsStatus.Playing, controller.state.value.status) + } + + @Test + fun `translated page uses the translated voice and original page uses the original voice`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + controller.play(document, mapOf(0 to "First sentence. Second sentence.")) + assertEquals("voice-b", engine.voice) + + controller.stop() + controller.play(document, emptyMap()) + assertEquals("voice-a", engine.voice) + } + + @Test + fun `missing saved voice falls back to the engine default`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-gone")) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + controller.play(document) + + assertEquals(null, engine.voice) + assertEquals(TtsStatus.Playing, controller.state.value.status) + } + + @Test + fun `restore keeps session values and falls back to saved settings`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", speed = 1.6f, pitch = 1.7f), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + assertTrue( + controller.restore( + document, + emptyMap(), + session().copy(voiceId = null, speed = 0.7f, pitch = 1.2f), + ), + ) + + assertEquals("voice-a", engine.voice) + assertEquals(0.7f, engine.appliedRate, 0.001f) + assertEquals(1.2f, engine.appliedPitch, 0.001f) + } + + @Test + fun `session voice wins over saved settings`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-a")) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + assertTrue( + controller.restore(document, emptyMap(), session().copy(voiceId = "voice-b")), + ) + + assertEquals("voice-b", engine.voice) + } + + @Test + fun `restore after a parallel language switch picks the new voice`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + assertTrue( + controller.restore( + document, + mapOf(0 to "First sentence. Second sentence."), + session().copy(translated = false, voiceId = "voice-a"), + ), + ) + + assertEquals("voice-b", engine.voice) + } + + @Test + fun `restore of a translated session uses the translated engine`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings( + voiceId = "voice-a", + engineId = "default", + translatedVoiceId = "voice-b", + translatedEngineId = "engine-b", + ), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + assertTrue( + controller.restore( + document, + emptyMap(), + session(), + language = TtsLanguage.Translation, + ), + ) + + assertEquals("engine-b", engine.currentEngineId) + assertEquals("voice-b", engine.voice) + } + + @Test + fun `translation language keeps the translated voice without a translation map`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + controller.playFrom( + document, + translations = emptyMap(), + blockIndex = null, + language = TtsLanguage.Translation, + ) + + // An explicit Translation language (the reader only asks for it when the + // chapter has translated text) keeps the translated voice even for an + // empty map; the text falls back to the original. + assertEquals("voice-b", engine.voice) + assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) + } + + @Test + fun `session language follows the played session and clears on stop`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + + assertNull(controller.sessionLanguage) + + controller.play(document, mapOf(0 to "Переведённое предложение.")) + assertEquals(TtsLanguage.Translation, controller.sessionLanguage) + + controller.stop() + assertNull(controller.sessionLanguage) + + controller.play(document, emptyMap()) + assertEquals(TtsLanguage.Original, controller.sessionLanguage) + } + + @Test + fun `toggle with a different language restarts the spoken block in the new voice`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store, settings) + controller.play(document, mapOf(0 to "Переведённое предложение.")) + controller.skipNextChunk() + controller.pause() + assertEquals("voice-b", engine.voice) + engine.spokenTexts.clear() + + controller.toggle(document, emptyMap(), TtsLanguage.Original) + + // The new language re-chunks the text and picks the original voice; the + // cursor stays in the spoken block instead of the chapter top. + assertEquals("voice-a", engine.voice) + assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) + assertEquals(TtsLanguage.Original, controller.sessionLanguage) + assertFalse(engine.spokenTexts.any { it.contains("Переведённое") }) + assertEquals(false, store.load()?.translated) + } + + @Test + fun `toggle with the same language resumes instead of re-chunking`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document, emptyMap()) + controller.skipNextChunk() + controller.pause() + assertEquals(1, controller.state.value.currentChunk) + engine.spokenTexts.clear() + + controller.toggle(document, emptyMap(), TtsLanguage.Original) + + // Resuming continues at the current chunk; a re-chunk would speak the + // chapter's first sentence again. + assertEquals(listOf("Second sentence"), engine.spokenTexts) + } + + @Test + fun `seek to block with a new language stays paused and switches the voice`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + controller.play(document, mapOf(0 to "Переведённое предложение.")) + controller.pause() + assertEquals("voice-b", engine.voice) + val spoken = engine.spokenTexts.size + + controller.seekToBlock(document, emptyMap(), blockIndex = 0, language = TtsLanguage.Original) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals("voice-a", engine.voice) + assertEquals(spoken, engine.spokenTexts.size) + } + + @Test + fun `original language never reads the translation`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + + controller.playFrom( + document, + translations = mapOf(0 to "Translated sentence."), + blockIndex = null, + language = TtsLanguage.Original, + ) + + assertEquals("voice-a", engine.voice) + assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) + } + + @Test + fun `failed engine is surfaced and retry restarts playback`() = runTest { + val engine = FakeEngine(ready = false) + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + + controller.play(document) + engine.listener?.onReady(false) + + assertEquals(TtsStatus.Failed, controller.state.value.status) + assertEquals("TTS unavailable", controller.state.value.message) + + controller.retry() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(2, engine.spoken.size) + } + + @Test + fun `failed engine still exposes other engine voices for recovery`() = runTest { + val engine = FakeEngine(ready = false) + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + + engine.listener?.onReady(false) + + assertFalse(controller.capabilities.value.ready) + assertEquals( + setOf("voice-a", "voice-b"), + controller.capabilities.value.voices.map { it.id }.toSet(), + ) + assertEquals(2, controller.capabilities.value.engines.size) + } + + @Test + fun `test utterance pauses reading and speaks the sample`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + + controller.testUtterance("sample") + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(listOf("sample"), engine.previews) + } + + @Test + fun `settings are clamped before they reach the engine`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSettingsStore() + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), store) + + controller.updateSettings(TtsSettings(speed = 9f, pitch = 0.1f)) + + assertEquals(5f, controller.settings.value.speed) + assertEquals(0.5f, controller.settings.value.pitch) + assertEquals(5f, engine.appliedRate) + assertEquals(0.5f, engine.appliedPitch) + assertEquals(TtsSettings(speed = 5f, pitch = 0.5f), store.load()) + } + + @Test + fun `skip next chunk stops the queue and continues at the next chunk`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store) + controller.play(document) + engine.listener?.onStart(engine.spoken[0]) + engine.spoken.clear() + engine.stops = 0 + + controller.skipNextChunk() + + assertEquals(1, engine.stops) + assertEquals(1, engine.spoken.size) + assertEquals(1, controller.state.value.currentChunk) + assertTrue(controller.state.value.atEnd) + assertEquals(1, store.load()?.sentenceIndex) + } + + @Test + fun `skip previous chunk re-speaks from the previous chunk`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + engine.listener?.onStart(engine.spoken[1]) + engine.spoken.clear() + + controller.skipPreviousChunk() + + assertEquals(2, engine.spoken.size) + assertEquals(0, controller.state.value.currentChunk) + assertFalse(controller.state.value.atEnd) + } + + @Test + fun `paused skip moves the cursor without speaking`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store) + controller.restore(document, emptyMap(), session()) + + controller.skipPreviousChunk() + + assertTrue(engine.spoken.isEmpty()) + assertEquals(0, controller.state.value.currentChunk) + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertFalse(controller.state.value.atEnd) + assertEquals(0, store.load()?.sentenceIndex) + } + + @Test + fun `chapter skip stops speech and requests the next chapter`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store) + val requests = mutableListOf() + val job = launch { controller.chapterRequests.collect { requests += it } } + runCurrent() + controller.play(document) + engine.listener?.onStart(engine.spoken[0]) + engine.spoken.clear() + engine.stops = 0 + + controller.skipNextChapter() + runCurrent() + + assertEquals(listOf(TtsChapterDirection.Next), requests) + assertEquals(1, engine.stops) + assertTrue(engine.spoken.isEmpty()) + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertFalse(store.load()?.wasPlaying ?: true) + job.cancel() + } + + @Test + fun `previous chapter skip requests the previous direction`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + val requests = mutableListOf() + val job = launch { controller.chapterRequests.collect { requests += it } } + runCurrent() + controller.play(document) + + controller.skipPreviousChapter() + runCurrent() + + assertEquals(listOf(TtsChapterDirection.Previous), requests) + job.cancel() + } + + @Test + fun `late range from a previous utterance cannot move the highlight`() = runTest { + val twoBlocks = document.copy( + blocks = listOf( + ReaderBlock( + id = BlockId(chapterUrl, 0), + kind = BlockKind.Paragraph, + original = "First block.", + sentences = listOf(SentenceSpan(0, 12)), + ), + ReaderBlock( + id = BlockId(chapterUrl, 1), + kind = BlockKind.Paragraph, + original = "Second block.", + sentences = listOf(SentenceSpan(0, 13)), + ), + ), + ) + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(twoBlocks) + val first = engine.spoken[0] + val second = engine.spoken[1] + engine.listener?.onStart(first) + engine.listener?.onStart(second) + + val before = controller.state.value + engine.listener?.onRangeStart(first, 2, 7) + + assertEquals(before.rangeStart, controller.state.value.rangeStart) + assertEquals(before.rangeEnd, controller.state.value.rangeEnd) + assertEquals(1, controller.state.value.currentChunk) + assertEquals(1, controller.state.value.blockId?.index) + + engine.listener?.onRangeStart(second, 0, 6) + + assertEquals(0, controller.state.value.rangeStart) + assertEquals(6, controller.state.value.rangeEnd) + assertEquals(TtsStatus.Playing, controller.state.value.status) + } + + @Test + fun `late range after pause cannot move the highlight`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + val last = engine.spoken[1] + engine.listener?.onStart(last) + val before = controller.state.value + + controller.pause() + engine.listener?.onRangeStart(last, 2, 7) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(before.rangeStart, controller.state.value.rangeStart) + assertEquals(before.rangeEnd, controller.state.value.rangeEnd) + assertEquals(1, controller.state.value.currentChunk) + } + + @Test + fun `late range after a chapter request cannot move the highlight`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + val last = engine.spoken[1] + engine.listener?.onStart(last) + + controller.skipNextChapter() + val paused = controller.state.value + engine.listener?.onRangeStart(last, 2, 7) + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals(paused.rangeStart, controller.state.value.rangeStart) + assertEquals(paused.rangeEnd, controller.state.value.rangeEnd) + assertEquals(1, controller.state.value.currentChunk) + } + + @Test + fun `late onStart cannot move the cursor back`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + val first = engine.spoken[0] + val second = engine.spoken[1] + engine.listener?.onStart(first) + engine.listener?.onStart(second) + + engine.listener?.onStart(first) + + assertEquals(1, controller.state.value.currentChunk) + assertEquals(TtsStatus.Playing, controller.state.value.status) + } + + @Test + fun `atEnd follows the last chunk only`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + + engine.listener?.onStart(engine.spoken[0]) + assertFalse(controller.state.value.atEnd) + + engine.listener?.onStart(engine.spoken[1]) + assertTrue(controller.state.value.atEnd) + } + + @Test + fun `auto-next finishes the last chunk with a next chapter request`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine, + this, + InMemoryTtsSessionStore(), + InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = true)), + ) + val requests = mutableListOf() + val job = launch { controller.chapterRequests.collect { requests += it } } + runCurrent() + controller.play(document) + val last = engine.spoken[1] + engine.listener?.onStart(last) + + engine.listener?.onDone(last) + runCurrent() + + assertEquals(listOf(TtsChapterDirection.Next), requests) + assertEquals(TtsStatus.Loading, controller.state.value.status) + assertTrue(controller.state.value.atEnd) + job.cancel() + } + + @Test + fun `auto-next off ends the chapter without a request`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine, + this, + InMemoryTtsSessionStore(), + InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = false)), + ) + val requests = mutableListOf() + val job = launch { controller.chapterRequests.collect { requests += it } } + runCurrent() + controller.play(document) + val last = engine.spoken[1] + engine.listener?.onStart(last) + + engine.listener?.onDone(last) + runCurrent() + + assertTrue(requests.isEmpty()) + assertEquals(TtsStatus.Idle, controller.state.value.status) + assertTrue(controller.state.value.atEnd) + job.cancel() + } + + @Test + fun `restore applies voice and clamps rate and pitch`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + + assertTrue( + controller.restore( + document, + emptyMap(), + session().copy(voiceId = "voice-a", speed = 9f, pitch = 0.1f), + ), + ) + + assertEquals("voice-a", engine.voice) + assertEquals(5f, engine.appliedRate) + assertEquals(0.5f, engine.appliedPitch) + } + @Test + fun `playing rate change stops and requeues the current chunk`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController(engine, this, store) + controller.play(document) + engine.listener?.onStart(engine.spoken[1]) + engine.spoken.clear() + engine.stops = 0 + + controller.updateSettings( + controller.settings.value.copy(speed = 2.5f, voiceId = "voice-b"), + ) + + assertEquals(1, engine.stops) + assertEquals(1, engine.spoken.size) + assertEquals(1, controller.state.value.currentChunk) + assertEquals(2.5f, engine.appliedRate, 0.001f) + assertEquals("voice-b", engine.voice) + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(2.5f, store.load()?.speed) + assertEquals(1, store.load()?.sentenceIndex) + } + + @Test + fun `paused settings change applies without speaking`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.restore(document, emptyMap(), session()) + engine.spoken.clear() + engine.stops = 0 + + controller.updateSettings(controller.settings.value.copy(speed = 2.5f)) + + assertTrue(engine.spoken.isEmpty()) + assertEquals(0, engine.stops) + assertEquals(2.5f, engine.appliedRate, 0.001f) + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + @Test + fun `appearance only settings do not interrupt playback`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + engine.listener?.onStart(engine.spoken[1]) + engine.spoken.clear() + engine.stops = 0 + + controller.updateSettings( + controller.settings.value.copy( + floatingPlayer = true, + floatingOpacity = 0.5f, + autoNextChapter = true, + ), + ) + + assertTrue(engine.spoken.isEmpty()) + assertEquals(0, engine.stops) + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + } + + @Test + fun `engine switch during playback resumes the same chunk after init`() = runTest { + val engine = FakeEngine().apply { deferEngineReady = true } + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + engine.listener?.onStart(engine.spoken[1]) + engine.spoken.clear() + engine.stops = 0 + + controller.updateSettings(controller.settings.value.copy(engineId = "engine-b")) + + assertEquals(TtsStatus.Loading, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + assertTrue(engine.spoken.isEmpty()) + + engine.completeEngineInit() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + assertEquals(1, engine.spoken.size) + assertEquals("engine-b", engine.currentEngineId) + } + + @Test + fun `refresh discovers engines installed or removed while running`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + assertEquals( + listOf("default", "engine-b"), + controller.capabilities.value.engines.map { it.id }, + ) + + engine.installedEngines = listOf( + TtsEngineInfo("com.google.android.tts", "Speech Services by Google", true), + TtsEngineInfo("com.github.olga_yakovleva.rhvoice.android", "RHVoice", false), + ) + controller.refreshEngines() + + assertEquals(1, engine.refreshCount) + assertEquals( + listOf("Speech Services by Google", "RHVoice"), + controller.capabilities.value.engines.map { it.label }, + ) + + engine.installedEngines = listOf( + TtsEngineInfo("com.google.android.tts", "Speech Services by Google", true), + ) + controller.refreshEngines() + + assertEquals( + listOf("com.google.android.tts"), + controller.capabilities.value.engines.map { it.id }, + ) + } + + private fun finishChapter(engine: FakeEngine) { + val last = engine.spoken.last() + engine.listener?.onStart(last) + engine.listener?.onDone(last) + } + + @Test + fun `sleep timer stops playback and keeps the session`() = runTest { + val engine = FakeEngine() + val store = InMemoryTtsSessionStore() + val controller = TtsController( + engine, + this, + store, + InMemoryTtsSettingsStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + + advanceTimeBy(60_000) + runCurrent() + + assertEquals(TtsStatus.Idle, controller.state.value.status) + assertTrue(engine.stops > 0) + assertNotNull(store.load()) + assertFalse(controller.state.value.atEnd) + assertNull(controller.sleepTimer.value) + } + + @Test + fun `sleep timer ticks down every second`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + + advanceTimeBy(2_000) + runCurrent() + + assertEquals(58, controller.sleepTimer.value?.remainingSeconds) + controller.cancelSleepTimer() + } + + @Test + fun `user pause cancels the sleep timer`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + + controller.pause() + assertNull(controller.sleepTimer.value) + + advanceTimeBy(60_000) + runCurrent() + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + @Test + fun `system pause keeps the sleep timer running`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + + controller.pauseFromSystem() + assertNotNull(controller.sleepTimer.value) + + advanceTimeBy(60_000) + runCurrent() + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `test utterance keeps the sleep timer`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(5) + + controller.testUtterance("sample") + + assertNotNull(controller.sleepTimer.value) + controller.cancelSleepTimer() + } + + @Test + fun `chapter timer continues chapters without auto-next and stops at zero`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine, + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + val requests = mutableListOf() + val job = launch { controller.chapterRequests.collect { requests += it } } + runCurrent() + controller.play(document) + controller.setSleepTimerChapters(2) + + finishChapter(engine) + runCurrent() + assertEquals(listOf(TtsChapterDirection.Next), requests) + assertEquals(TtsStatus.Loading, controller.state.value.status) + assertEquals(1, controller.sleepTimer.value?.chaptersRemaining) + + controller.play(document) + finishChapter(engine) + runCurrent() + + assertEquals(1, requests.size) + assertEquals(TtsStatus.Idle, controller.state.value.status) + assertTrue(controller.state.value.atEnd) + assertNull(controller.sleepTimer.value) + job.cancel() + } + + @Test + fun `manual chapter skip does not spend the chapter timer`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimerChapters(2) + + controller.skipNextChapter() + runCurrent() + + assertEquals(2, controller.sleepTimer.value?.chaptersRemaining) + controller.cancelSleepTimer() + } + + @Test + fun `stop and close clear the sleep timer`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimerChapters(2) + controller.stop() + assertNull(controller.sleepTimer.value) + + controller.play(document) + controller.setSleepTimer(5) + controller.close() + assertNull(controller.sleepTimer.value) + } + + @Test + fun `natural chapter end without auto-next clears the minutes timer`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine = engine, + scope = this, + sessions = InMemoryTtsSessionStore(), + settingsStore = InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = false)), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(5) + + finishChapter(engine) + runCurrent() + + assertEquals(TtsStatus.Idle, controller.state.value.status) + assertNull(controller.sleepTimer.value) + } + + @Test + fun `sleep timer is ignored while playback is idle`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + + controller.setSleepTimer(5) + controller.setSleepTimerChapters(2) + + assertNull(controller.sleepTimer.value) + } + + @Test + fun `expired timer blocks a chapter hand-off`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine, + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + advanceTimeBy(60_000) + runCurrent() + + val spoken = engine.spoken.size + assertFalse(controller.playHandoff(document, emptyMap())) + assertEquals(spoken, engine.spoken.size) + assertEquals(TtsStatus.Idle, controller.state.value.status) + + controller.play(document) + assertEquals(TtsStatus.Playing, controller.state.value.status) + } + + @Test + fun `manual skip at the timer boundary cannot resurrect the chapter`() = runTest { + val controller = TtsController( + FakeEngine(), + this, + InMemoryTtsSessionStore(), + now = { testScheduler.currentTime }, + ) + controller.play(document) + controller.setSleepTimer(1) + controller.skipNextChapter() + advanceTimeBy(60_000) + runCurrent() + + assertFalse(controller.playHandoff(document, emptyMap())) + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `stop during a chapter handoff drops it`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + finishChapter(engine) + runCurrent() + assertEquals(TtsStatus.Loading, controller.state.value.status) + + controller.stop() + val spoken = engine.spoken.size + + assertFalse(controller.playHandoff(document, emptyMap())) + assertEquals(spoken, engine.spoken.size) + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `pause during a chapter handoff drops it`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + controller.play(document) + finishChapter(engine) + runCurrent() + + controller.pause() + + assertFalse(controller.playHandoff(document, emptyMap())) + assertEquals(TtsStatus.Paused, controller.state.value.status) + } + + @Test + fun `handoff without a request is ignored`() = runTest { + val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) + + assertFalse(controller.playHandoff(document, emptyMap())) + assertEquals(TtsStatus.Idle, controller.state.value.status) + } + + @Test + fun `reload settings applies a restored store snapshot`() = runTest { + val engine = FakeEngine() + val settings = InMemoryTtsSettingsStore( + TtsSettings(voiceId = "voice-a", engineId = "default", speed = 1f, pitch = 1f), + ) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + engine.listener?.onReady(true) + + settings.save( + TtsSettings(voiceId = "voice-b", engineId = "default", speed = 1.8f, pitch = 0.6f), + ) + controller.reloadSettings() + runCurrent() + + assertEquals("voice-b", controller.settings.value.voiceId) + assertEquals("voice-b", engine.voice) + assertEquals(1.8f, engine.appliedRate, 0.001f) + assertEquals(0.6f, engine.appliedPitch, 0.001f) + } + + @Test + fun `reload settings with a new engine resumes the current chunk`() = runTest { + val engine = FakeEngine().apply { deferEngineReady = true } + val settings = InMemoryTtsSettingsStore(TtsSettings(engineId = "default")) + val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) + controller.play(document) + engine.listener?.onStart(engine.spoken[1]) + engine.spoken.clear() + engine.stops = 0 + + settings.save(TtsSettings(engineId = "engine-b")) + controller.reloadSettings() + runCurrent() + + // The engine restarts: the session must not stay "Playing" without sound. + assertEquals(TtsStatus.Loading, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + assertTrue(engine.spoken.isEmpty()) + + engine.completeEngineInit() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(1, controller.state.value.currentChunk) + assertEquals(1, engine.spoken.size) + assertEquals("engine-b", engine.currentEngineId) + } + + @Test + fun `sleep timer presets set the expected duration`() = runTest { + val engine = FakeEngine() + val controller = TtsController( + engine = engine, + scope = this, + sessions = InMemoryTtsSessionStore(), + now = { 1_000L }, + ) + controller.play(document) + + TtsSleepTimerPresetMinutes.forEach { minutes -> + controller.setSleepTimer(minutes) + val timer = controller.sleepTimer.value + assertEquals(minutes * 60, timer?.totalSeconds) + assertTrue(isSleepTimerPresetActive(timer, minutes)) + } + controller.setSleepTimer(20) + assertFalse(isSleepTimerPresetActive(controller.sleepTimer.value, 15)) + controller.setSleepTimerChapters(2) + assertFalse(isSleepTimerPresetActive(controller.sleepTimer.value, 15)) + } + + @Test + fun `preview voice delegates without changing the selected voice`() = runTest { + val engine = FakeEngine() + val previewer = FakeVoicePreviewer() + val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-a")) + val controller = TtsController( + engine = engine, + scope = this, + sessions = InMemoryTtsSessionStore(), + settingsStore = settings, + voicePreviewer = previewer, + ) + val before = controller.settings.value + + controller.previewVoice("voice-b", "engine-b", 1.4f, 0.9f, "sample") + + assertEquals("voice-b", previewer.voiceId) + assertEquals("engine-b", previewer.engineId) + assertEquals(1.4f, previewer.speed) + assertEquals(0.9f, previewer.pitch) + assertEquals("sample", previewer.text) + assertEquals(before, controller.settings.value) + assertEquals("voice-a", controller.settings.value.voiceId) + + controller.stopVoicePreview() + assertEquals(1, previewer.stops) + } + + @Test + fun `preview voice pauses active reading`() = runTest { + val engine = FakeEngine() + val previewer = FakeVoicePreviewer() + val controller = TtsController( + engine = engine, + scope = this, + sessions = InMemoryTtsSessionStore(), + voicePreviewer = previewer, + ) + controller.play(document) + assertEquals(TtsStatus.Playing, controller.state.value.status) + + controller.previewVoice("voice-b", null, 1f, 1f, "sample") + + assertEquals(TtsStatus.Paused, controller.state.value.status) + assertEquals("voice-b", previewer.voiceId) + } + + @Test + fun `stop remembers the last session`() = runTest { + val sessions = InMemoryTtsSessionStore() + val controller = TtsController(FakeEngine(), this, sessions) + controller.play(document) + + controller.stop() + + val stopped = controller.lastStoppedSession + assertNotNull(stopped) + assertEquals(document.bookUrl, stopped?.bookUrl) + assertEquals(document.chapterIndex, stopped?.chapterIndex) + } + +} + +private class FakeVoicePreviewer : TtsVoicePreviewer { + var voiceId: String? = null + var engineId: String? = null + var speed: Float = 0f + var pitch: Float = 0f + var text: String = "" + var stops = 0 + + override fun preview( + voiceId: String?, + engineId: String?, + speed: Float, + pitch: Float, + text: String, + onUnavailable: () -> Unit, + ) { + this.voiceId = voiceId + this.engineId = engineId + this.speed = speed + this.pitch = pitch + this.text = text + } + + override fun stop() { + stops++ + } + + override fun shutdown() = Unit +} + +private class RecordingSessionStore : TtsSessionStore { + var saved: TtsSession? = null + private set + var savedImmediate = false + private set + var savedBackground = false + private set + + override fun load(): TtsSession? = saved + + override fun save(session: TtsSession, immediate: Boolean, background: Boolean) { + saved = session + savedImmediate = immediate + savedBackground = background + } + + override fun clear(immediate: Boolean, background: Boolean) { + saved = null + } + + @Test + fun `play queues only a bounded lookahead window and tops up on onStart`() = runTest { + val engine = FakeEngine() + val controller = createController(engine) + val doc = ReaderDocument( + bookUrl = "book://1", + chapterUrl = "ch://1", + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId("ch://1", 0), + original = "One. Two. Three. Four. Five. Six.", + ), + ), + ) + + controller.play(doc) + assertEquals(4, engine.spoken.size) + assertEquals(listOf(true, false, false, false), engine.flushFlags) + + engine.listener?.onStart(engine.spoken[1]) + assertEquals(5, engine.spoken.size) + assertEquals("Five.", engine.spokenTexts.last()) + } + + @Test + fun `rapid skipNextChunk fast-forward uses flush on first chunk and stays Playing`() = runTest { + val engine = FakeEngine() + val controller = createController(engine) + val doc = ReaderDocument( + bookUrl = "book://1", + chapterUrl = "ch://1", + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId("ch://1", 0), + original = "Line 1. Line 2. Line 3. Line 4. Line 5. Line 6.", + ), + ), + ) + + controller.play(doc) + engine.spoken.clear() + engine.spokenTexts.clear() + engine.flushFlags.clear() + + controller.skipNextChunk() + controller.skipNextChunk() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(2, controller.state.value.currentChunk) + assertTrue(engine.flushFlags.first()) + assertEquals("Line 3.", engine.spokenTexts.first()) + } +} \ No newline at end of file diff --git a/Ttsengine.kt b/Ttsengine.kt new file mode 100644 index 0000000..a2c9aeb --- /dev/null +++ b/Ttsengine.kt @@ -0,0 +1,344 @@ +package dev.mirutime.feature.tts + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.Bundle +import android.provider.Settings +import android.speech.tts.TextToSpeech +import android.speech.tts.UtteranceProgressListener +import dev.mirutime.core.log.MiruLog +import java.util.Locale + +interface TtsEngineListener { + fun onReady(ok: Boolean) + fun onStart(utteranceId: Int) + fun onDone(utteranceId: Int) + fun onError(utteranceId: Int?) + fun onRangeStart(utteranceId: Int, start: Int, end: Int) + + /** Auxiliary engines finished scanning their voices. */ + fun onVoicesChanged() = Unit +} + +/** Thin seam over the platform engine so controller state is unit-testable. */ +interface TtsEngine { + var listener: TtsEngineListener? + val isReady: Boolean + val voices: List + val engines: List + val currentEngineId: String? + val defaultEngineId: String? + + /** Re-reads the installed engines from the platform (no app restart). */ + fun refreshEngines() + + fun speak(text: String, utteranceId: Int, flush: Boolean = false): Boolean + fun preview(text: String): Boolean + fun stop() + fun setVoice(name: String?): Boolean + fun setRate(rate: Float) + fun setPitch(pitch: Float) + + /** Recreates the platform engine; the listener reports readiness again. */ + fun selectEngine(engineId: String): Boolean + fun restart() + fun shutdown() +} + +class AndroidTtsEngine(context: Context) : TtsEngine { + private val appContext = context.applicationContext + @Volatile + private var tts: TextToSpeech? = null + @Volatile + private var ready = false + private var engineId: String? = null + + // Voices of the installed engines that are not current. TextToSpeech only + // lists the voices of its own engine, so each auxiliary engine is queried + // once and shut down again; the catalog keeps the metadata afterwards. + private val auxiliaryLock = Any() + private val auxiliaryVoices = HashMap>() + private val auxiliaryRequested = HashSet() + private val auxiliaryEngines = HashMap() + + override var listener: TtsEngineListener? = null + + override val isReady: Boolean + get() = ready + + override val defaultEngineId: String? + get() = Settings.Secure.getString( + appContext.contentResolver, + Settings.Secure.TTS_DEFAULT_SYNTH, + )?.takeIf { it.isNotBlank() } + + override val currentEngineId: String? + get() { + val selected = engineId ?: defaultEngineId + val installed = tts?.engines.orEmpty().map { it.name } + return selected?.takeIf { installed.isEmpty() || it in installed } + ?: installed.firstOrNull() + } + + override val voices: List + get() { + val id = currentEngineId + val current = tts?.voices.orEmpty() + .filter { it.locale != null } + .map { voice -> + TtsVoice( + id = voice.name, + name = voice.name, + locale = voice.locale, + quality = voice.quality, + engineId = id, + needsInternet = voice.isNetworkConnectionRequired, + ) + } + val auxiliary = synchronized(auxiliaryLock) { + auxiliaryVoices.mapValues { it.value } + } + return ttsVoiceCatalog(id, current, auxiliary) + } + + override val engines: List + get() { + val default = defaultEngineId + return tts?.engines.orEmpty() + .map { TtsEngineInfo(id = it.name, label = it.label, isDefault = it.name == default) } + .sortedWith(compareBy({ !it.isDefault }, { it.label })) + } + + override fun refreshEngines() { + val platform = tts ?: return + val installed = platform.engines.orEmpty().map { it.name } + // Debug-only evidence: which engines the platform actually exposes to + // this app (package visibility matters on Android 11+). + MiruLog.d( + "tts", + "event=tts_engines count=${installed.size} ids=${installed.joinToString(",")}", + ) + // The selected engine may have been uninstalled while the app was + // running; fall back to the system engine instead of keeping a dead + // package id in settings. + val selected = engineId + if (selected != null && installed.isNotEmpty() && selected !in installed) { + initEngine(null) + return + } + refreshAuxiliaryVoices() + mainHandler.post { listener?.onVoicesChanged() } + } + + private fun refreshAuxiliaryVoices() { + val installed = tts?.engines.orEmpty().map { it.name } + if (installed.isEmpty()) return + val current = currentEngineId + val missing = synchronized(auxiliaryLock) { + installed.filter { it != current && it !in auxiliaryRequested } + } + missing.forEach(::loadAuxiliaryVoices) + var removed = false + synchronized(auxiliaryLock) { + val keep = installed.toSet() + auxiliaryRequested.retainAll(keep) + if (auxiliaryVoices.keys.any { it !in keep }) { + auxiliaryVoices.keys.retainAll(keep) + removed = true + } + val stale = auxiliaryEngines.keys.filter { it !in keep } + stale.forEach { id -> auxiliaryEngines.remove(id)?.shutdown() } + } + if (removed) mainHandler.post { listener?.onVoicesChanged() } + } + + private fun loadAuxiliaryVoices(engine: String) { + synchronized(auxiliaryLock) { + if (!auxiliaryRequested.add(engine)) return + } + // TextToSpeech reports readiness asynchronously, so the callback needs + // a holder instead of a self-reference in the constructor expression. + val holder = arrayOfNulls(1) + val instance = TextToSpeech( + appContext, + { status -> + val auxiliary = holder[0] + val voices = if (status == TextToSpeech.SUCCESS) { + auxiliary?.voices.orEmpty() + .filter { it.locale != null } + .map { voice -> + TtsVoice( + id = voice.name, + name = voice.name, + locale = voice.locale, + quality = voice.quality, + engineId = engine, + needsInternet = voice.isNetworkConnectionRequired, + ) + } + } else { + emptyList() + } + synchronized(auxiliaryLock) { + auxiliaryEngines.remove(engine) + if (voices.isNotEmpty()) { + auxiliaryVoices[engine] = voices + } else { + // Allow a later refresh to retry a failed scan. + auxiliaryRequested.remove(engine) + } + } + MiruLog.d( + "tts", + "event=tts_engine_voices engine=$engine status=$status " + + "count=${voices.size} ids=${voices.joinToString(",") { it.id }}", + ) + auxiliary?.shutdown() + mainHandler.post { listener?.onVoicesChanged() } + }, + engine, + ) + holder[0] = instance + synchronized(auxiliaryLock) { + auxiliaryEngines[engine] = instance + } + } + + // Engine callbacks arrive on binder threads; the controller is main-confined. + private val mainHandler = Handler(Looper.getMainLooper()) + + // Diagnostic: the platform may deliver these on a binder thread, not Main. + private fun logProgressThread(role: String, utteranceId: String?) { + MiruLog.d( + "tts", + "event=tts-thread role=$role thread=${Thread.currentThread().name} " + + "utterance=${utteranceId ?: "-"}", + ) + } + + // Incremented on every init/shutdown: a late onInit from an old engine + // must never mark the current (or a shut-down) engine ready. + @Volatile + private var engineGeneration = 0 + + private val progress = object : UtteranceProgressListener() { + override fun onStart(utteranceId: String?) { + logProgressThread("onStart", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onStart(value) } + } + + override fun onDone(utteranceId: String?) { + logProgressThread("onDone", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onDone(value) } + } + + @Deprecated("Deprecated in Java") + override fun onError(utteranceId: String?) { + logProgressThread("onError", utteranceId) + // Preview ("tts-preview") and foreign ids must not fail the book. + if (!shouldReportPlaybackError(utteranceId)) return + val value = utteranceId?.toIntOrNull() + mainHandler.post { listener?.onError(value) } + } + + override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) { + logProgressThread("onRangeStart", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onRangeStart(value, start, end) } + } + } + + init { + initEngine(null) + } + + private fun initEngine(enginePackage: String?) { + val generation = ++engineGeneration + ready = false + tts?.stop() + tts?.shutdown() + engineId = enginePackage + tts = TextToSpeech( + appContext, + { status -> + if (generation == engineGeneration) { + ready = status == TextToSpeech.SUCCESS + if (ready) { + tts?.language = Locale.getDefault() + tts?.setOnUtteranceProgressListener(progress) + refreshAuxiliaryVoices() + } + mainHandler.post { listener?.onReady(ready) } + } + }, + enginePackage, + ) + } + + override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { + val queueMode = if (flush) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD + return tts?.speak(text, queueMode, Bundle(), utteranceId.toString()) == + TextToSpeech.SUCCESS + } + + // QUEUE_FLUSH: a test utterance must be heard now, not after the book queue. + override fun preview(text: String): Boolean = + tts?.speak(text, TextToSpeech.QUEUE_FLUSH, Bundle(), PREVIEW_UTTERANCE) == + TextToSpeech.SUCCESS + + override fun stop() { + tts?.stop() + } + + override fun setVoice(name: String?): Boolean { + val engine = tts ?: return false + val voice = if (name == null) { + engine.defaultVoice ?: engine.voices?.firstOrNull() + } else { + engine.voices?.firstOrNull { it.name == name } + } ?: return false + return engine.setVoice(voice) == TextToSpeech.SUCCESS + } + + override fun setRate(rate: Float) { + tts?.setSpeechRate(rate) + } + + override fun setPitch(pitch: Float) { + tts?.setPitch(pitch) + } + + override fun selectEngine(engineId: String): Boolean { + if (engineId.isBlank()) return false + if (engineId == currentEngineId && ready) return true + initEngine(engineId) + return true + } + + override fun restart() { + initEngine(engineId) + } + + override fun shutdown() { + engineGeneration += 1 + tts?.stop() + tts?.shutdown() + tts = null + ready = false + synchronized(auxiliaryLock) { + auxiliaryEngines.values.forEach { it.shutdown() } + auxiliaryEngines.clear() + } + } + + private companion object { + const val PREVIEW_UTTERANCE = "tts-preview" + } +} + +/** Only a real playback utterance id may fail the active session. */ +internal fun shouldReportPlaybackError(utteranceId: String?): Boolean = + utteranceId?.toIntOrNull() != null From 8fb804107cb4ab590682f8a9df59ddab9e5d3bf2 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:43:51 +0530 Subject: [PATCH 02/16] Delete Ttscontroller.kt --- Ttscontroller.kt | 1165 ---------------------------------------------- 1 file changed, 1165 deletions(-) delete mode 100644 Ttscontroller.kt diff --git a/Ttscontroller.kt b/Ttscontroller.kt deleted file mode 100644 index 2387322..0000000 --- a/Ttscontroller.kt +++ /dev/null @@ -1,1165 +0,0 @@ -package dev.mirutime.feature.tts - -import android.os.SystemClock -import dev.mirutime.app.features.reader.document.BlockId -import dev.mirutime.app.features.reader.document.ReaderDocument -import dev.mirutime.core.log.MiruLog -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.channels.BufferOverflow -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharedFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asSharedFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -enum class TtsStatus { Idle, Loading, Playing, Paused, Failed } - -/** Chapter hand-off the reader must resolve; the controller has no chapter list. */ -enum class TtsChapterDirection { Next, Previous } - -/** - * Text the rich TTS player renders. The reader parses the chapter, so it - * publishes the spoken sentence, its paragraph and the counterpart translation - * here; the in-app player and the system overlay then show the same plate. - */ -data class TtsPlayerText( - val sentence: String? = null, - val paragraph: String? = null, - val counterpart: String? = null, - val sentenceHighlightStart: Int = 0, - val sentenceHighlightEnd: Int = 0, - val chapterPercent: Int = 0, - val glowColorArgb: Long = 0L, -) - -data class TtsState( - val status: TtsStatus = TtsStatus.Idle, - val currentChunk: Int = 0, - val chunkCount: Int = 0, - val blockId: BlockId? = null, - val sentenceIndex: Int = 0, - val rangeStart: Int = 0, - val rangeEnd: Int = 0, - val translated: Boolean = false, - val atEnd: Boolean = false, - /** NoveLA-style estimate; zero until the chunk text is loaded. */ - val estimatedTotalSeconds: Int = 0, - val estimatedRemainingSeconds: Int = 0, - val message: String? = null, -) - -/** - * Small in-app TTS player. It uses the platform engine, speaks stable - * TtsChunker units, and exposes the current chunk/range for highlight. - * The cursor is persisted so a process death restores a paused position. - * Foreground playback/MediaSession/floating overlay are a later layer. - */ -class TtsController( - private val engine: TtsEngine, - private val scope: CoroutineScope, - private val sessions: TtsSessionStore = InMemoryTtsSessionStore(), - private val settingsStore: TtsSettingsStore = InMemoryTtsSettingsStore(), - /** Monotonic clock; tests inject the virtual scheduler time. */ - private val now: () -> Long = { SystemClock.elapsedRealtime() }, - private val voicePreviewer: TtsVoicePreviewer = NoopTtsVoicePreviewer, -) : TtsHandoffSource { - private val _state = MutableStateFlow(TtsState()) - override val state: StateFlow = _state.asStateFlow() - - private val _settings = MutableStateFlow(settingsStore.load().sanitized()) - val settings: StateFlow = _settings.asStateFlow() - - private val _capabilities = MutableStateFlow(TtsCapabilities()) - val capabilities: StateFlow = _capabilities.asStateFlow() - - // Conflated: a second arrow tap must not be dropped while the collector is - // still starting the first hand-off. The latest direction is what the user - // asked for, so dropping the older one is correct. - private val _chapterRequests = MutableSharedFlow( - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - - /** - * Emitted when playback needs the reader to open another chapter (manual - * skip or auto-next). The reader owns the chapter list, loads the document - * and calls [play] so the controller never guesses what comes next. - */ - override val chapterRequests: SharedFlow = _chapterRequests.asSharedFlow() - - private val _sleepTimer = MutableStateFlow(null) - /** Running sleep timer, or null. A tick updates only [TtsSleepTimerState.remainingSeconds]. */ - val sleepTimer: StateFlow = _sleepTimer.asStateFlow() - - private val _playerText = MutableStateFlow(TtsPlayerText()) - - /** - * Text the rich player shows. The reader owns the document, so it publishes - * the current sentence/paragraph here instead of passing text through a - * service intent; the overlay renders the same plate as the in-app player. - */ - val playerText: StateFlow = _playerText.asStateFlow() - - fun updatePlayerText(value: TtsPlayerText) { - _playerText.value = value - } - - /** Stops playback after [minutes]. Setting a new timer replaces the old one. */ - fun setSleepTimer(minutes: Int) { - if (!sleepTimerAvailable()) return - clearSleepTimer() - val seconds = clampSleepTimerMinutes(minutes) * 60 - sleepDeadline = now() + seconds * 1000L - _sleepTimer.value = TtsSleepTimerState( - mode = TtsSleepTimerMode.Minutes, - remainingSeconds = seconds, - totalSeconds = seconds, - endsAtEpochMillis = System.currentTimeMillis() + seconds * 1000L, - ) - startSleepTicker() - } - - /** Stops at the end of the [chapters]th chapter counted from now. */ - fun setSleepTimerChapters(chapters: Int) { - if (!sleepTimerAvailable()) return - clearSleepTimer() - val count = clampSleepTimerChapters(chapters) - _sleepTimer.value = TtsSleepTimerState( - mode = TtsSleepTimerMode.Chapters, - chaptersRemaining = count, - chaptersTotal = count, - ) - } - - fun cancelSleepTimer() { - clearSleepTimer() - } - - /** A timer makes sense only while a TTS session exists and can still stop. */ - private fun sleepTimerAvailable(): Boolean = - chunks.isNotEmpty() && - _state.value.status != TtsStatus.Idle && - _state.value.status != TtsStatus.Failed - - private fun clearSleepTimer() { - sleepTimerJob?.cancel() - sleepTimerJob = null - sleepDeadline = 0L - _sleepTimer.value = null - } - - private fun startSleepTicker() { - sleepTimerJob = scope.launch { - while (true) { - val left = ((sleepDeadline - now()) / 1000L).coerceAtLeast(0L).toInt() - val current = _sleepTimer.value ?: return@launch - if (current.mode == TtsSleepTimerMode.Minutes && - current.remainingSeconds != left - ) { - _sleepTimer.value = current.copy(remainingSeconds = left) - } - if (left <= 0) { - // resetPlayback drops a hand-off that was requested just - // before the deadline, so waiting for Loading is unnecessary. - _sleepTimer.value = null - resetPlayback(clearSession = false) - return@launch - } - delay(250) - } - } - } - - /** - * True only while the pending chapter request came from the queue finishing - * the chapter (auto-next). A manual skip clears it first, so the reader - * never marks a chapter read the user skipped through (FR-082/FR-083). - */ - @Volatile - override var chapterEndedNaturally: Boolean = false - private set - - private var ready = false - private var pending: (() -> Unit)? = null - private var chunks: List = emptyList() - // Language of the current session. Translation is a page-level decision: - // parallel ORIGINAL_FIRST passes an empty translation map. A partially - // translated page keeps this flag for the whole session by design. - private var sessionTranslated = false - // Suffix sums of chunk text lengths: suffix[i] is "characters from chunk i - // to the end". Rebuilt only when chunks change, so the timer estimate is - // O(1) on every chunk/range update. - private var chunkCharSuffix: IntArray = IntArray(0) - private var current = 0 - private var active = false - // Platform utterance ids are unique per queue (not chunk indexes), so a - // late callback from a stopped queue cannot be mistaken for the current - // one. Cleared whenever the queue is paused/skipped/replaced. - private val utteranceChunks = java.util.concurrent.ConcurrentHashMap() - private var nextUtteranceId = 0 - private var queuedUpTo = -1 - private var bookUrl = "" - private var chapterIndex = 0 - private var voiceId: String? = _settings.value.voiceId - private var speed = _settings.value.speed - private var pitch = _settings.value.pitch - // Language slot the engine was last configured for, null until the first - // apply. Settings edits come through updateSettings(), so a seek inside the - // same slot must not reload prefs or re-hit the TTS binders. - private var appliedVoiceSlot: Boolean? = null - private var sleepTimerJob: Job? = null - private var sleepDeadline = 0L - // Set when a chapter hand-off is requested and not yet applied. Stop, pause, - // timer, close and explicit starts clear it, so a stale request can never - // resurrect playback. - @Volatile - private var handoffPending = false - private var handoffTimeout: Job? = null - - /** True while a chapter hand-off is between the request and its document. */ - val isHandoffPending: Boolean - get() = handoffPending - - // Snapshot for the reader's revert: stop() clears the persisted session, so - // the last spoken cursor would otherwise be lost. - private var _lastStoppedSession: TtsSession? = null - - /** Last session captured by a user Stop; null after a new start/resume. */ - override val lastStoppedSession: TtsSession? - get() = _lastStoppedSession - - /** - * Language the live session speaks; null when there is no session. The - * reader compares the language the page wants with this one, so a settings - * switch restarts the speech instead of waiting for the next session. - */ - override val sessionLanguage: TtsLanguage? - get() = when (_state.value.status) { - TtsStatus.Idle, TtsStatus.Failed -> null - else -> if (sessionTranslated) TtsLanguage.Translation else TtsLanguage.Original - } - - fun play( - document: ReaderDocument, - translations: Map = emptyMap(), - language: TtsLanguage = TtsLanguage.from(translations), - ) { - playFrom(document, translations, blockIndex = null, language = language) - } - - /** - * Starts at the first spoken chunk at or after [blockIndex]. The reader - * passes its visible anchor, so "Start here" never jumps back to the - * chapter top. A null blockIndex keeps the ordinary chapter start. - */ - fun playFrom( - document: ReaderDocument, - translations: Map = emptyMap(), - blockIndex: Int?, - charOffset: Int = 0, - language: TtsLanguage = TtsLanguage.from(translations), - ) { - voicePreviewer.stop() - handoffPending = false - _lastStoppedSession = null - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - if (next.isEmpty()) { - setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) - return - } - // A session speaks one language: the caller decides from the page mode, - // not from whichever block happens to be first. - sessionTranslated = language == TtsLanguage.Translation - applySavedSettings(sessionTranslated) - stopInternal(keepStatus = true) - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl - chapterIndex = document.chapterIndex - current = if (blockIndex == null) 0 else ttsStartIndex(next, blockIndex, charOffset) - active = true - MiruLog.event( - "tts", - "play", - "chunks" to next.size, - "chapter" to document.chapterIndex, - "block" to blockIndex, - "startChunk" to current, - "translated" to sessionTranslated, - "voice" to voiceId, - ) - persist(wasPlaying = true, immediate = true, background = true) - if (!ready) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } else { - speakFrom(current) - } - } - - /** - * Moves the cursor to [blockIndex] while keeping the transport state: a - * paused session only moves its cursor/highlight and stays paused, while a - * playing one re-queues from the new block. The mini player's paragraph - * arrows use this so a pause is never silently undone (FR-051). - */ - fun seekToBlock( - document: ReaderDocument, - translations: Map = emptyMap(), - blockIndex: Int, - charOffset: Int = 0, - language: TtsLanguage = TtsLanguage.from(translations), - ) { - if (_state.value.status != TtsStatus.Paused) { - playFrom(document, translations, blockIndex, charOffset, language) - return - } - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - if (next.isEmpty()) { - setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) - return - } - sessionTranslated = language == TtsLanguage.Translation - // Same slot = same voice/engine/speed, already applied: a paused chapter - // crossing must not reload settings or hit the engine binders again. - if (appliedVoiceSlot != sessionTranslated) applySavedSettings(sessionTranslated) - stopInternal(keepStatus = true) - pending = null - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl - chapterIndex = document.chapterIndex - current = ttsStartIndex(next, blockIndex, charOffset) - active = false - MiruLog.event( - "tts", - "seek", - "chunks" to next.size, - "chapter" to document.chapterIndex, - "block" to blockIndex, - "startChunk" to current, - ) - // Never starts speech: resume() is what moves a paused session. - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - - /** - * Rebuilds chunks from the current document/translation state and restores - * a paused cursor. Never starts speech, even if the session was playing. - */ - fun restore( - document: ReaderDocument, - translations: Map = emptyMap(), - session: TtsSession, - language: TtsLanguage = TtsLanguage.from(translations), - ): Boolean { - if (document.chapterUrl != session.chapterUrl) return false - if (document.chapterIndex != session.chapterIndex) return false - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - val cursor = resolveTtsCursor(next, session) ?: return false - stopInternal(keepStatus = true) - pending = null - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl.ifBlank { session.bookUrl } - chapterIndex = document.chapterIndex - current = cursor - active = false - sessionTranslated = language == TtsLanguage.Translation - val restoredSelection = sessionVoiceSelection(_settings.value, sessionTranslated) - // The engine belongs to the session's slot, not to the original one: - // a translated session must speak with the translated engine. - applyEngine(restoredSelection.engineId) - // A saved session keeps its voice only while it speaks the same - // language. Switching parallel order must pick the new language's slot. - val sameLanguage = session.translated == sessionTranslated - voiceId = if (sameLanguage) { - session.voiceId ?: restoredSelection.voiceId - } else { - restoredSelection.voiceId - } - speed = clampTtsSpeed(session.speed) - pitch = clampTtsPitch(session.pitch) - applyPlaybackSettings() - MiruLog.event( - "tts", - "restore", - "translated" to sessionTranslated, - "voice" to voiceId, - ) - setState(chunkState(cursor, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - return true - } - - /** - * True only while the pause came from audio-focus loss (call, navigation - * prompt). Every explicit pause path — notification, headset media button, - * becoming-noisy, user — clears it, so a later focus gain can never undo a - * user pause (FR-045/FR-046). - */ - @Volatile - var pausedByFocusLoss: Boolean = false - private set - - fun pause() { - MiruLog.event("tts", "pause-request", "source" to "user") - pausedByFocusLoss = false - pauseInternal(cancelSleepTimer = true) - } - - /** Pause caused by a transient audio-focus loss; a focus gain may resume it. */ - fun pauseForFocusLoss() { - if (!active && _state.value.status != TtsStatus.Loading) return - MiruLog.event("tts", "pause-request", "source" to "focus") - pausedByFocusLoss = true - pauseInternal(cancelSleepTimer = false) - } - - /** - * Pause not initiated by the user (headphone unplugged, service teardown). - * The sleep timer keeps running: the user did not ask to cancel it. - */ - fun pauseFromSystem() { - MiruLog.event("tts", "pause-request", "source" to "system") - pauseInternal(cancelSleepTimer = false) - } - - private fun pauseInternal(cancelSleepTimer: Boolean) { - handoffPending = false - if (cancelSleepTimer) clearSleepTimer() - if (!active && _state.value.status != TtsStatus.Loading) return - pending = null - invalidateUtterances() - engine.stop() - active = false - setState(_state.value.copy(status = TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - - override fun resume() { - voicePreviewer.stop() - handoffPending = false - _lastStoppedSession = null - pausedByFocusLoss = false - if (chunks.isEmpty()) return - active = true - applyPlaybackSettings() - persist(wasPlaying = true, immediate = true, background = true) - if (!ready) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - return - } - speakFrom(current) - } - - /** - * Stops the platform queue and resumes at the neighbouring chunk. While - * paused the cursor still moves (and persists) without speaking; at an - * edge the current chunk is restarted only when speech is already active. - */ - fun skipNextChunk() = skipChunkBy(1) - - fun skipPreviousChunk() = skipChunkBy(-1) - - /** - * Stops the current utterance immediately and asks the reader to load the - * next/previous chapter. The reader calls [play] on the new document, so a - * failed navigation can never leave the old chapter speaking in parallel. - */ - fun skipNextChapter() = requestChapter(TtsChapterDirection.Next) - - fun skipPreviousChapter() = requestChapter(TtsChapterDirection.Previous) - - private fun skipChunkBy(delta: Int) { - if (chunks.isEmpty()) return - invalidateUtterances() - val target = (current + delta).coerceIn(0, chunks.lastIndex) - if (target == current) { - if (active && ready) speakFrom(current) - return - } - current = target - if (active) { - if (ready) { - speakFrom(target) - } else { - setState(chunkState(target, TtsStatus.Loading)) - pending = { speakFrom(target) } - } - } else { - setState(chunkState(target, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - } - - private fun requestChapter(direction: TtsChapterDirection) { - if (chunks.isEmpty()) return - // Manual skip: never a natural end, even when the cursor sits on the - // last chunk (atEnd would be true there anyway). - chapterEndedNaturally = false - active = false - pending = null - // Mark the hand-off before the Paused state reaches the service: the - // service keeps its wake lock while a hand-off is pending. - handoffPending = true - invalidateUtterances() - engine.stop() - // Keep the old cursor paused so a rejected request can resume it. - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - requestHandoff(direction) - } - - private fun requestHandoff(direction: TtsChapterDirection) { - handoffPending = true - _chapterRequests.tryEmit(direction) - handoffTimeout?.cancel() - handoffTimeout = scope.launch { - delay(HandoffTimeoutMs) - if (!handoffPending) return@launch - // No chapter arrived: drop the pending hand-off instead of holding - // Loading (and the service wake lock) forever. - handoffPending = false - if (_state.value.status == TtsStatus.Paused || _state.value.status == TtsStatus.Loading) { - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - MiruLog.w("tts", "event=tts-handoff-timeout") - } - } - - fun toggle( - document: ReaderDocument, - translations: Map = emptyMap(), - language: TtsLanguage = TtsLanguage.from(translations), - ) { - when (_state.value.status) { - TtsStatus.Playing, TtsStatus.Loading -> pause() - // A paused session resumes only while it speaks the same language: - // a settings switch must not resume the old text in the old voice. - TtsStatus.Paused -> if (language != sessionLanguage) { - playFrom( - document = document, - translations = translations, - blockIndex = chunks.getOrNull(current)?.blockId?.index, - language = language, - ) - } else { - resume() - } - else -> play(document, translations, language) - } - } - - /** - * Starts speech on a chapter the reader loaded for a [chapterRequests] - * hand-off. A request is consumed only once: Stop, Pause, a new start or - * the sleep timer clears it, so a stale hand-off cannot resurrect playback. - */ - override fun playHandoff( - document: ReaderDocument, - translations: Map, - language: TtsLanguage, - ): Boolean { - if (!handoffPending) return false - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - play(document, translations, language) - return true - } - - override fun stop() { - _lastStoppedSession = sessions.load() - clearSleepTimer() - resetPlayback(clearSession = true) - } - - private fun resetPlayback(clearSession: Boolean) { - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - pausedByFocusLoss = false - active = false - pending = null - invalidateUtterances() - engine.stop() - // Persist before chunks/bookUrl are cleared, or the cursor is lost. - if (!clearSession) persist(wasPlaying = false, immediate = true) - chunks = emptyList() - chunkCharSuffix = IntArray(0) - current = 0 - sessionTranslated = false - bookUrl = "" - chapterIndex = 0 - if (clearSession) sessions.clear(immediate = true) - setState(TtsState(status = TtsStatus.Idle)) - } - - fun close() { - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - clearSleepTimer() - active = false - pending = null - invalidateUtterances() - engine.stop() - engine.shutdown() - voicePreviewer.shutdown() - ready = false - publishCapabilities() - } - - /** - * Persists and applies immediately; a restored session still wins later. - * The UI calls this on release, so voice/rate/pitch changes stop and - * re-queue the current chunk while appearance-only fields never interrupt - * speech. An engine switch re-initializes and resumes the same chunk. - */ - fun updateSettings(settings: TtsSettings) { - val previous = _settings.value - val sanitized = settings.sanitized() - // The session speaks one language: edits apply to that slot. - val previousSelection = previous.sanitized().voiceForSession(sessionTranslated) - val nextSelection = sanitized.voiceForSession(sessionTranslated) - // Only the slot this session speaks can affect playback: editing the - // other language's voice must not restart the current chunk. - val playbackChanged = ttsPlaybackChanged(previous, sanitized, sessionTranslated) - val engineChanged = previousSelection.engineId != nextSelection.engineId - _settings.value = sanitized - settingsStore.save(sanitized) - voiceId = nextSelection.voiceId - speed = sanitized.speed - pitch = sanitized.pitch - - if (engineChanged) { - val wasActive = active - invalidateUtterances() - engine.stop() - if (wasActive) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } - val reinitializing = applyEngine(nextSelection.engineId) - if (!reinitializing) { - // Already on the requested engine (e.g. explicit default id); - // no readiness callback will arrive, so resume now. - pending = null - applyPlaybackSettings() - if (wasActive) speakFrom(current) - } - } else if (playbackChanged) { - applyPlaybackSettings() - if (active && ready && _state.value.status == TtsStatus.Playing) { - speakFrom(current) - } - } - refreshTimeEstimate() - publishCapabilities() - } - - override fun switchLanguage( - document: ReaderDocument, - translations: Map, - blockIndex: Int, - language: TtsLanguage, - ) { - seekToBlock(document, translations, blockIndex, charOffset = 0, language = language) - } - - fun resetSettings() { - updateSettings(TtsSettings()) - } - - /** - * Re-discovers installed engines (including ones installed while the app - * is running). The voice picker calls this on open, so the catalog never - * needs an app restart or a hardcoded engine list. - */ - fun refreshEngines() { - engine.refreshEngines() - publishCapabilities() - } - - /** Short sample with the current voice/rate/pitch; pauses a live reading. */ - fun testUtterance(text: String) { - if (!ready) { - setState( - _state.value.copy( - status = TtsStatus.Failed, - message = "TTS unavailable", - ), - ) - return - } - if (active) pauseFromSystem() - applyPlaybackSettings() - engine.preview(text) - } - - /** Retries after a failure; re-creates the engine when it never came up. */ - fun retry() { - if (chunks.isEmpty()) { - setState(TtsState()) - return - } - applySavedSettings(sessionTranslated) - invalidateUtterances() - setState(chunkState(current, TtsStatus.Loading)) - if (ready) { - speakFrom(current) - } else { - pending = { speakFrom(current) } - engine.restart() - } - } - - private fun speakFrom(index: Int) { - if (!ready || chunks.isEmpty()) return - invalidateUtterances() - current = index.coerceIn(0, chunks.lastIndex) - active = true - setState(chunkState(current, TtsStatus.Playing)) - // Persist before the platform callback so skipping cannot lose the - // cursor if speech never starts (engine race, process death). - persist(wasPlaying = true, immediate = true, background = true) - engine.stop() - val end = minOf(current + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) - enqueueRange(current, end, flushFirst = true) - } - - private fun enqueueRange(startIndex: Int, endIndex: Int, flushFirst: Boolean): Boolean { - for (i in startIndex..endIndex) { - val utteranceId = ++nextUtteranceId - utteranceChunks[utteranceId] = i - val flush = flushFirst && i == startIndex - if (!engine.speak(chunks[i].text, utteranceId, flush)) { - utteranceChunks.remove(utteranceId) - if (i == current) { - // Only abort playback if the active chunk itself failed to queue. - engine.stop() - setState( - _state.value.copy( - status = TtsStatus.Failed, - message = "TTS speak failed", - ), - ) - active = false - return false - } - return true - } - queuedUpTo = i - } - return true - } - - private fun topUpQueue(fromIndex: Int) { - if (!active || !ready || chunks.isEmpty()) return - val targetEnd = minOf(fromIndex + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) - if (queuedUpTo < targetEnd) { - val start = maxOf(fromIndex, queuedUpTo + 1) - if (start <= targetEnd) { - enqueueRange(start, targetEnd, flushFirst = false) - } - } - } - - // Status/chunk transitions only; never the spoken text. - private fun setState(next: TtsState) { - val previous = _state.value - _state.value = next - if (previous.status != next.status || previous.currentChunk != next.currentChunk) { - MiruLog.event("tts", "state", "status" to next.status, "chunk" to next.currentChunk) - } - } - - private fun chunkState(index: Int, status: TtsStatus): TtsState { - val chunk = chunks.getOrNull(index) ?: return TtsState(status = status) - val totalSeconds = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) - val remainingSeconds = ttsEstimatedSeconds( - chunkCharSuffix.getOrElse(index) { 0 }, - speed, - ) - return TtsState( - status = status, - currentChunk = index, - chunkCount = chunks.size, - blockId = chunk.blockId, - sentenceIndex = chunk.sentenceIndex, - // Do not paint the whole sentence before the platform reports its - // first word range; that looked like a full-sentence flash. - rangeStart = chunk.startOffset, - rangeEnd = if (status == TtsStatus.Playing || status == TtsStatus.Loading) { - chunk.startOffset - } else { - chunk.endOffset - }, - translated = chunk.translated, - atEnd = index >= chunks.lastIndex, - estimatedTotalSeconds = totalSeconds, - estimatedRemainingSeconds = remainingSeconds, - ) - } - - private fun rebuildChunkCharStats() { - chunkCharSuffix = IntArray(chunks.size + 1) - for (index in chunks.indices.reversed()) { - chunkCharSuffix[index] = chunkCharSuffix[index + 1] + chunks[index].text.length - } - } - - /** Speed is live; a changed rate must not leave the old estimate behind. */ - private fun refreshTimeEstimate() { - if (chunks.isEmpty()) return - val total = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) - val remaining = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(current) { 0 }, speed) - val state = _state.value - if (state.estimatedTotalSeconds == total && - state.estimatedRemainingSeconds == remaining - ) { - return - } - setState( - state.copy( - estimatedTotalSeconds = total, - estimatedRemainingSeconds = remaining, - ), - ) - } - - private fun stopInternal(keepStatus: Boolean) { - pausedByFocusLoss = false - active = false - invalidateUtterances() - engine.stop() - if (!keepStatus) setState(TtsState()) - } - - private fun invalidateUtterances() { - utteranceChunks.clear() - queuedUpTo = -1 - } - - private fun onEngineReady() { - ready = true - applyPlaybackSettings() - publishCapabilities() - pending?.invoke() - pending = null - } - - private fun applySavedSettings(translated: Boolean = false) { - appliedVoiceSlot = translated - val saved = settingsStore.load().sanitized() - _settings.value = saved - val selection = sessionVoiceSelection(saved, translated) - voiceId = selection.voiceId - speed = saved.speed - pitch = saved.pitch - applyEngine(selection.engineId) - applyPlaybackSettings() - publishCapabilities() - } - - /** - * The text a session speaks. An Original session never reads the - * translation; a Translation session reads it and falls back to the - * original text while the translation has not arrived yet. - */ - private fun sessionTranslations( - language: TtsLanguage, - translations: Map, - ): Map { - if (language == TtsLanguage.Original) return emptyMap() - if (translations.isEmpty()) { - MiruLog.event("tts", "text-fallback", "reason" to "translation-missing") - } - return translations - } - - /** - * The voice slot a session speaks with. A translated session without a - * translated voice falls back to the original one; the fallback is logged - * so a wrong language is visible in the diagnostics. - */ - private fun sessionVoiceSelection( - settings: TtsSettings, - translated: Boolean, - ): TtsVoiceSelection { - val sanitized = settings.sanitized() - val selection = sanitized.voiceForSession(translated) - if (translated && sanitized.translatedVoiceId == null) { - MiruLog.event("tts", "voice-fallback", "reason" to "translated-voice-unset") - } - return selection - } - - /** Re-reads the durable TTS prefs after a backup restore. */ - fun reloadSettings() { - // Restore runs on an IO thread; the controller and engine are main-confined. - scope.launch { - // The session prefs were written directly by the backup store. - sessions.invalidate() - val saved = settingsStore.load().sanitized() - val selection = saved.voiceForSession(sessionTranslated) - val targetEngine = selection.engineId ?: engine.defaultEngineId - if (active && targetEngine != null && targetEngine != engine.currentEngineId) { - // The engine restarts and its queue dies with it: the session - // must re-queue the current chunk instead of staying "Playing" - // without sound. - invalidateUtterances() - engine.stop() - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } - applySavedSettings(translated = sessionTranslated) - } - } - - /** Auditions a voice without changing the selected voice/engine. */ - fun previewVoice( - voiceId: String?, - engineId: String?, - speed: Float, - pitch: Float, - text: String, - onUnavailable: () -> Unit = {}, - ) { - if (active) pauseFromSystem() - voicePreviewer.preview(voiceId, engineId, speed, pitch, text, onUnavailable) - } - - fun stopVoicePreview() = voicePreviewer.stop() - - /** Returns true when the platform engine is being re-initialized. */ - private fun applyEngine(id: String?): Boolean { - val target = id ?: engine.defaultEngineId - if (target != null && target != engine.currentEngineId) { - ready = false - engine.selectEngine(target) - return true - } - return false - } - - private fun applyPlaybackSettings() { - if (!ready) return - speed = clampTtsSpeed(speed) - pitch = clampTtsPitch(pitch) - engine.setRate(speed) - engine.setPitch(pitch) - if (!engine.setVoice(voiceId)) { - // A saved engine voice may be gone after an engine switch. - MiruLog.event("tts", "voice-fallback", "reason" to "voice-unavailable") - voiceId = null - engine.setVoice(null) - } - } - - private fun publishCapabilities() { - _capabilities.value = TtsCapabilities( - ready = ready, - // Auxiliary engine scans can still provide a usable catalog while - // the selected engine is down; the picker must offer another - // engine instead of a dead "unavailable" wall. - voices = engine.voices, - engines = engine.engines, - currentEngineId = engine.currentEngineId, - defaultEngineId = engine.defaultEngineId, - ) - } - - private fun persist( - wasPlaying: Boolean, - immediate: Boolean = false, - background: Boolean = false, - ) { - val chunk = chunks.getOrNull(current) ?: return - if (bookUrl.isBlank()) return - sessions.save( - TtsSession( - bookUrl = bookUrl, - chapterIndex = chapterIndex, - chapterUrl = chunk.blockId.chapterUrl, - blockIndex = chunk.blockId.index, - sentenceIndex = chunk.sentenceIndex, - charOffset = chunk.startOffset, - voiceId = voiceId, - speed = speed, - pitch = pitch, - wasPlaying = wasPlaying, - translated = sessionTranslated, - textHash = "${chunk.text.length}:${chunk.text.hashCode()}", - updatedAt = System.currentTimeMillis(), - ), - immediate, - background, - ) - } - - private val listener = object : TtsEngineListener { - override fun onReady(ok: Boolean) { - if (ok) { - onEngineReady() - } else { - active = false - setState(TtsState(status = TtsStatus.Failed, message = "TTS unavailable")) - pending = null - } - } - - override fun onVoicesChanged() { - publishCapabilities() - } - - override fun onStart(utteranceId: Int) { - // Only utterances queued by the current speakFrom call are known; - // a stopped/replaced queue no longer has any valid ids. - val index = utteranceChunks[utteranceId] ?: return - if (!active || index < current) return - current = index - setState(chunkState(index, TtsStatus.Playing)) - persist(wasPlaying = true, immediate = true, background = true) - topUpQueue(index) - } - - override fun onDone(utteranceId: Int) { - val index = utteranceChunks[utteranceId] ?: return - if (index < chunks.lastIndex || !active) return - active = false - persist(wasPlaying = false, immediate = true) - val timer = _sleepTimer.value - if (timer?.mode == TtsSleepTimerMode.Chapters) { - val left = timer.chaptersRemaining - 1 - if (left <= 0) { - clearSleepTimer() - invalidateUtterances() - setState( - _state.value.copy( - status = TtsStatus.Idle, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - return - } - // The chapter timer continues chapters on its own, even when - // auto-next is off: that is what "stop after N chapters" means. - _sleepTimer.value = timer.copy(chaptersRemaining = left) - chapterEndedNaturally = true - setState( - _state.value.copy( - status = TtsStatus.Loading, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - requestHandoff(TtsChapterDirection.Next) - return - } - if (_settings.value.autoNextChapter) { - // Keep the status active across the chapter load so the - // foreground service is not torn down between chapters. - chapterEndedNaturally = true - setState( - _state.value.copy( - status = TtsStatus.Loading, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - requestHandoff(TtsChapterDirection.Next) - } else { - // Playback ends here; a running minutes timer has nothing left - // to stop and would only fire into an idle session. - clearSleepTimer() - setState( - _state.value.copy( - status = TtsStatus.Idle, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - } - } - - override fun onError(utteranceId: Int?) { - // Late errors from a stopped/skipped queue must not fail this one. - if (utteranceId != null && utteranceChunks[utteranceId] == null) return - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - clearSleepTimer() - setState(_state.value.copy(status = TtsStatus.Failed, message = "TTS error")) - active = false - persist(wasPlaying = false, immediate = true) - } - - override fun onRangeStart(utteranceId: Int, start: Int, end: Int) { - val index = utteranceChunks[utteranceId] ?: return - val state = _state.value - // Late callbacks from a paused/skipped/replaced queue are not in - // the map (or no longer match the live chunk); never move the - // highlight for them. - if (!active || index != current || state.currentChunk != index) return - val chunk = chunks.getOrNull(index) ?: return - if (state.blockId != chunk.blockId) return - val base = chunk.startOffset - val consumed = start.coerceIn(0, chunk.text.length) - val remainingChars = (chunkCharSuffix.getOrElse(index) { 0 } - consumed) - .coerceAtLeast(0) - setState( - state.copy( - rangeStart = base + start, - rangeEnd = base + end, - estimatedRemainingSeconds = ttsEstimatedSeconds(remainingChars, speed), - ), - ) - } - } - - init { - engine.listener = listener - publishCapabilities() - if (engine.isReady) onEngineReady() - } -} - -/** - * First chunk at or after the reader's visible block. Chunks are ordered by - * block, so a heading/image without speech is skipped rather than failing. - * [charOffset] only matters when the anchor points inside a spoken block. - */ -internal fun ttsStartIndex( - chunks: List, - blockIndex: Int, - charOffset: Int, -): Int { - if (chunks.isEmpty()) return 0 - if (charOffset > 0) { - chunks.indexOfFirst { chunk -> - chunk.blockId.index == blockIndex && - charOffset >= chunk.startOffset && - charOffset < chunk.endOffset - }.takeIf { it >= 0 }?.let { return it } - } - return chunks.indexOfFirst { it.blockId.index >= blockIndex } - .takeIf { it >= 0 } - ?: chunks.lastIndex -} - -/** A chapter hand-off that never arrives must not hold Loading forever. */ -private const val HandoffTimeoutMs = 30_000L -private const val LOOKAHEAD_CHUNKS = 4 From ca70d0f1aaf89f254864379c06d9a3e861157e5d Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:44:37 +0530 Subject: [PATCH 03/16] Delete Ttscontrollertest.kt --- Ttscontrollertest.kt | 1718 ------------------------------------------ 1 file changed, 1718 deletions(-) delete mode 100644 Ttscontrollertest.kt diff --git a/Ttscontrollertest.kt b/Ttscontrollertest.kt deleted file mode 100644 index da167f8..0000000 --- a/Ttscontrollertest.kt +++ /dev/null @@ -1,1718 +0,0 @@ -package dev.mirutime.feature.tts - -import dev.mirutime.app.features.reader.document.BlockId -import dev.mirutime.app.features.reader.document.BlockKind -import dev.mirutime.app.features.reader.document.ReaderBlock -import dev.mirutime.app.features.reader.document.ReaderDocument -import dev.mirutime.app.features.reader.document.SentenceSpan -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.advanceTimeBy -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test - -class TtsControllerTest { - private val chapterUrl = "local://book#chapter=1" - private val document = ReaderDocument( - bookUrl = "local://book", - chapterUrl = chapterUrl, - chapterIndex = 1, - title = "Chapter", - blocks = listOf( - ReaderBlock( - id = BlockId(chapterUrl, 0), - kind = BlockKind.Paragraph, - original = "First sentence. Second sentence.", - sentences = listOf(SentenceSpan(0, 15), SentenceSpan(16, 31)), - ), - ), - ) - - private fun session( - sentence: Int = 1, - offset: Int = 16, - playing: Boolean = true, - chapter: String = chapterUrl, - ) = TtsSession( - bookUrl = "local://book", - chapterIndex = 1, - chapterUrl = chapter, - blockIndex = 0, - sentenceIndex = sentence, - charOffset = offset, - wasPlaying = playing, - ) - - private class FakeEngine( - private var ready: Boolean = true, - ) : TtsEngine { - override var listener: TtsEngineListener? = null - override val isReady: Boolean - get() = ready - - val spoken = mutableListOf() - val spokenTexts = mutableListOf() - val flushFlags = mutableListOf() - val previews = mutableListOf() - var stops = 0 - var failSpeak = false - val availableVoices = setOf("voice-a", "voice-b") - var voice: String? = null - var appliedRate = 1f - var appliedPitch = 1f - // Engine binder traffic a paused chapter crossing must not repeat. - var voiceCatalogReads = 0 - var voiceSets = 0 - var rateSets = 0 - var pitchSets = 0 - var deferEngineReady = false - var pendingEngineId: String? = null - var refreshCount = 0 - var installedEngines = listOf( - TtsEngineInfo("default", "Default", true), - TtsEngineInfo("engine-b", "Second", false), - ) - override var currentEngineId: String? = "default" - override val defaultEngineId: String? = "default" - - override val voices: List - get() { - voiceCatalogReads += 1 - return availableVoices.map { name -> - TtsVoice(name, name, java.util.Locale.US, 400, currentEngineId) - } - } - - override val engines: List - get() = installedEngines - - override fun refreshEngines() { - refreshCount += 1 - listener?.onVoicesChanged() - } - - override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { - spoken += utteranceId - spokenTexts += text - flushFlags += flush - return !failSpeak - } - - override fun preview(text: String): Boolean { - previews += text - return true - } - - override fun stop() { - stops += 1 - } - - override fun setVoice(name: String?): Boolean { - voiceSets += 1 - if (name != null && name !in availableVoices) return false - voice = name - return true - } - - override fun setRate(rate: Float) { - rateSets += 1 - appliedRate = rate - } - - override fun setPitch(pitch: Float) { - pitchSets += 1 - appliedPitch = pitch - } - - override fun selectEngine(engineId: String): Boolean { - currentEngineId = engineId - if (deferEngineReady) { - pendingEngineId = engineId - ready = false - return true - } - ready = true - listener?.onReady(true) - return true - } - - fun completeEngineInit() { - pendingEngineId = null - ready = true - listener?.onReady(true) - } - - override fun restart() { - ready = true - listener?.onReady(true) - } - - override fun shutdown() = Unit - } - - @Test - fun `restore is paused and never speaks`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store) - - assertTrue(controller.restore(document, emptyMap(), session())) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - assertTrue(engine.spoken.isEmpty()) - } - - @Test - fun `persisted playing rehydrates as paused`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - - assertTrue(controller.restore(document, emptyMap(), session(playing = true))) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - @Test - fun `restore rejects a mismatched chapter`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - - assertTrue( - !controller.restore(document, emptyMap(), session(chapter = "local://book#chapter=2")), - ) - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `resume continues from the restored cursor`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.restore(document, emptyMap(), session()) - - controller.resume() - - assertEquals(1, engine.spoken.size) - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - } - - @Test - fun `a stale utterance error does not fail the live session`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - val live = engine.spoken.last() - - engine.listener?.onError(live + 100_000) - assertEquals(TtsStatus.Playing, controller.state.value.status) - - engine.listener?.onError(live) - assertEquals(TtsStatus.Failed, controller.state.value.status) - } - - @Test - fun `a handoff that never arrives leaves the session paused`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - - controller.skipNextChapter() - assertEquals(TtsStatus.Paused, controller.state.value.status) - - advanceTimeBy(30_001) - runCurrent() - - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - @Test - fun `a speak failure stops the already queued chunks`() = runTest { - val engine = FakeEngine().apply { failSpeak = true } - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - - controller.play(document, emptyMap()) - - assertEquals(TtsStatus.Failed, controller.state.value.status) - // One stop before queueing, one stop on the failure. - assertTrue(engine.stops >= 2) - } - - @Test - fun `state carries a remaining-time estimate from spoken characters`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - - controller.play(document, emptyMap()) - - val state = controller.state.value - assertTrue(state.estimatedTotalSeconds > 0) - assertTrue(state.estimatedRemainingSeconds in 1..state.estimatedTotalSeconds) - } - - @Test - fun `play persists the cursor immediately in the background`() = runTest { - val store = RecordingSessionStore() - val controller = TtsController(FakeEngine(), this, store) - - controller.play(document, emptyMap()) - - assertNotNull(store.saved) - assertTrue(store.savedImmediate) - assertTrue(store.savedBackground) - assertEquals(true, store.saved?.wasPlaying) - } - - @Test - fun `speed changes update the live time estimate`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - val normal = controller.state.value.estimatedRemainingSeconds - - controller.updateSettings(TtsSettings(speed = 2f)) - - assertTrue(controller.state.value.estimatedRemainingSeconds < normal) - } - - @Test - fun `only a focus-loss pause can auto-resume`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertFalse(controller.pausedByFocusLoss) - - controller.pauseForFocusLoss() - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertTrue(controller.pausedByFocusLoss) - - controller.resume() - assertFalse(controller.pausedByFocusLoss) - assertEquals(TtsStatus.Playing, controller.state.value.status) - - // A headset/notification pause after a focus-loss pause cancels the - // auto-resume, so the call ending cannot start speech the user stopped. - controller.pauseForFocusLoss() - assertTrue(controller.pausedByFocusLoss) - controller.pause() - assertFalse(controller.pausedByFocusLoss) - - controller.resume() - controller.stop() - assertFalse(controller.pausedByFocusLoss) - } - - @Test - fun `only a finished queue reports a natural chapter end`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.updateSettings(TtsSettings(autoNextChapter = true)) - controller.play(document, emptyMap()) - - // A manual skip from the last chunk is not a natural end, even though - // the state reports atEnd = true there. - controller.skipNextChunk() - assertTrue(controller.state.value.atEnd) - controller.skipNextChapter() - assertFalse(controller.chapterEndedNaturally) - - // The queue finishing the last chunk is the only natural end. - controller.play(document, emptyMap()) - engine.listener?.onDone(engine.spoken.last()) - assertTrue(controller.chapterEndedNaturally) - - // A manual skip after that must clear it again. - controller.skipNextChapter() - assertFalse(controller.chapterEndedNaturally) - } - - @Test - fun `paragraph seek keeps a paused session paused`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - controller.skipNextChunk() - controller.pause() - assertEquals(1, controller.state.value.currentChunk) - val spoken = engine.spoken.size - - controller.seekToBlock(document, emptyMap(), blockIndex = 0) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(0, controller.state.value.currentChunk) - assertEquals(spoken, engine.spoken.size) - } - - @Test - fun `paused seek to another chapter persists the cursor and never speaks`() = runTest { - val engine = FakeEngine() - val sessions = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, sessions) - controller.play(document, emptyMap()) - controller.pause() - val spoken = engine.spokenTexts.size - val otherChapter = "local://book#chapter=2" - val other = ReaderDocument( - bookUrl = "local://book", - chapterUrl = otherChapter, - chapterIndex = 2, - title = "Chapter 2", - blocks = listOf( - ReaderBlock( - id = BlockId(otherChapter, 0), - kind = BlockKind.Paragraph, - original = "Chapter two.", - sentences = listOf(SentenceSpan(0, 11)), - ), - ReaderBlock( - id = BlockId(otherChapter, 1), - kind = BlockKind.Paragraph, - original = "Second paragraph.", - sentences = listOf(SentenceSpan(0, 17)), - ), - ), - ) - - controller.seekToBlock(other, emptyMap(), blockIndex = 1) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(spoken, engine.spokenTexts.size) - val saved = sessions.load() - assertEquals(2, saved?.chapterIndex) - assertEquals(otherChapter, saved?.chapterUrl) - assertEquals(1, saved?.blockIndex) - assertEquals(false, saved?.wasPlaying) - } - - @Test - fun `paragraph seek keeps a playing session playing`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - controller.skipNextChunk() - assertEquals(1, controller.state.value.currentChunk) - - controller.seekToBlock(document, emptyMap(), blockIndex = 0) - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(0, controller.state.value.currentChunk) - } - - /** - * A paused chapter crossing used to reload settings and re-apply the engine - * voice: the voice catalog twice plus rate/pitch/voice binders on the - * scroll path, although the spoken language slot did not change. - */ - @Test - fun `seek in the same language leaves the engine alone`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - val translations = mapOf(0 to "Первый. Второй.") - controller.play(document, translations) - controller.pause() - engine.voiceCatalogReads = 0 - engine.voiceSets = 0 - engine.rateSets = 0 - engine.pitchSets = 0 - - controller.seekToBlock(document, translations, blockIndex = 0) - - assertEquals(0, engine.voiceCatalogReads) - assertEquals(0, engine.voiceSets) - assertEquals(0, engine.rateSets) - assertEquals(0, engine.pitchSets) - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - /** The other slot has its own voice/engine, so a switch must re-apply them. */ - @Test - fun `language switch re-applies the voice slot`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document, mapOf(0 to "Первый. Второй.")) - controller.pause() - engine.voiceSets = 0 - - controller.switchLanguage(document, emptyMap(), blockIndex = 0, language = TtsLanguage.Original) - - assertTrue(engine.voiceSets > 0) - } - - @Test - fun `stop clears the persisted session`() = runTest { - val store = InMemoryTtsSessionStore() - val controller = TtsController(FakeEngine(), this, store) - controller.restore(document, emptyMap(), session()) - assertTrue(store.load() != null) - - controller.stop() - - assertNull(store.load()) - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `playFrom starts at the visible block instead of the chapter top`() = runTest { - val multiBlock = ReaderDocument( - bookUrl = "local://book", - chapterUrl = chapterUrl, - chapterIndex = 1, - title = "Chapter", - blocks = (0..4).map { index -> - ReaderBlock( - id = BlockId(chapterUrl, index), - kind = BlockKind.Paragraph, - original = "Block $index sentence.", - sentences = listOf(SentenceSpan(0, 19)), - ) - }, - ) - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - - controller.playFrom(multiBlock, emptyMap(), blockIndex = 3) - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(3, controller.state.value.currentChunk) - assertEquals(3, controller.state.value.blockId?.index) - assertEquals(5, controller.state.value.chunkCount) - assertEquals(2, engine.spoken.size) - } - - @Test - fun `playFrom skips a block without speech and lands on the next one`() { - val chunks = listOf( - TtsChunk(BlockId(chapterUrl, 0), 0, "one", 0, 3, false), - TtsChunk(BlockId(chapterUrl, 2), 0, "two", 0, 3, false), - ) - - assertEquals(1, ttsStartIndex(chunks, blockIndex = 1, charOffset = 0)) - assertEquals(1, ttsStartIndex(chunks, blockIndex = 2, charOffset = 0)) - assertEquals(0, ttsStartIndex(chunks, blockIndex = 0, charOffset = 0)) - assertEquals(1, ttsStartIndex(chunks, blockIndex = 9, charOffset = 0)) - } - - @Test - fun `playFrom uses the char offset inside a long block`() { - val chunks = listOf( - TtsChunk(BlockId(chapterUrl, 0), 0, "one", 0, 10, false), - TtsChunk(BlockId(chapterUrl, 0), 1, "two", 10, 20, false), - ) - - assertEquals(1, ttsStartIndex(chunks, blockIndex = 0, charOffset = 12)) - } - - @Test - fun `play applies persisted settings and engine`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings( - voiceId = "voice-a", - engineId = "engine-b", - speed = 1.5f, - pitch = 0.8f, - ), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - controller.play(document) - - assertEquals("engine-b", engine.currentEngineId) - assertEquals("voice-a", engine.voice) - assertEquals(1.5f, engine.appliedRate, 0.001f) - assertEquals(0.8f, engine.appliedPitch, 0.001f) - assertEquals(TtsStatus.Playing, controller.state.value.status) - } - - @Test - fun `translated page uses the translated voice and original page uses the original voice`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - controller.play(document, mapOf(0 to "First sentence. Second sentence.")) - assertEquals("voice-b", engine.voice) - - controller.stop() - controller.play(document, emptyMap()) - assertEquals("voice-a", engine.voice) - } - - @Test - fun `missing saved voice falls back to the engine default`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-gone")) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - controller.play(document) - - assertEquals(null, engine.voice) - assertEquals(TtsStatus.Playing, controller.state.value.status) - } - - @Test - fun `restore keeps session values and falls back to saved settings`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", speed = 1.6f, pitch = 1.7f), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - assertTrue( - controller.restore( - document, - emptyMap(), - session().copy(voiceId = null, speed = 0.7f, pitch = 1.2f), - ), - ) - - assertEquals("voice-a", engine.voice) - assertEquals(0.7f, engine.appliedRate, 0.001f) - assertEquals(1.2f, engine.appliedPitch, 0.001f) - } - - @Test - fun `session voice wins over saved settings`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-a")) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - assertTrue( - controller.restore(document, emptyMap(), session().copy(voiceId = "voice-b")), - ) - - assertEquals("voice-b", engine.voice) - } - - @Test - fun `restore after a parallel language switch picks the new voice`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - assertTrue( - controller.restore( - document, - mapOf(0 to "First sentence. Second sentence."), - session().copy(translated = false, voiceId = "voice-a"), - ), - ) - - assertEquals("voice-b", engine.voice) - } - - @Test - fun `restore of a translated session uses the translated engine`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings( - voiceId = "voice-a", - engineId = "default", - translatedVoiceId = "voice-b", - translatedEngineId = "engine-b", - ), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - assertTrue( - controller.restore( - document, - emptyMap(), - session(), - language = TtsLanguage.Translation, - ), - ) - - assertEquals("engine-b", engine.currentEngineId) - assertEquals("voice-b", engine.voice) - } - - @Test - fun `translation language keeps the translated voice without a translation map`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - controller.playFrom( - document, - translations = emptyMap(), - blockIndex = null, - language = TtsLanguage.Translation, - ) - - // An explicit Translation language (the reader only asks for it when the - // chapter has translated text) keeps the translated voice even for an - // empty map; the text falls back to the original. - assertEquals("voice-b", engine.voice) - assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) - } - - @Test - fun `session language follows the played session and clears on stop`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - - assertNull(controller.sessionLanguage) - - controller.play(document, mapOf(0 to "Переведённое предложение.")) - assertEquals(TtsLanguage.Translation, controller.sessionLanguage) - - controller.stop() - assertNull(controller.sessionLanguage) - - controller.play(document, emptyMap()) - assertEquals(TtsLanguage.Original, controller.sessionLanguage) - } - - @Test - fun `toggle with a different language restarts the spoken block in the new voice`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store, settings) - controller.play(document, mapOf(0 to "Переведённое предложение.")) - controller.skipNextChunk() - controller.pause() - assertEquals("voice-b", engine.voice) - engine.spokenTexts.clear() - - controller.toggle(document, emptyMap(), TtsLanguage.Original) - - // The new language re-chunks the text and picks the original voice; the - // cursor stays in the spoken block instead of the chapter top. - assertEquals("voice-a", engine.voice) - assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) - assertEquals(TtsLanguage.Original, controller.sessionLanguage) - assertFalse(engine.spokenTexts.any { it.contains("Переведённое") }) - assertEquals(false, store.load()?.translated) - } - - @Test - fun `toggle with the same language resumes instead of re-chunking`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document, emptyMap()) - controller.skipNextChunk() - controller.pause() - assertEquals(1, controller.state.value.currentChunk) - engine.spokenTexts.clear() - - controller.toggle(document, emptyMap(), TtsLanguage.Original) - - // Resuming continues at the current chunk; a re-chunk would speak the - // chapter's first sentence again. - assertEquals(listOf("Second sentence"), engine.spokenTexts) - } - - @Test - fun `seek to block with a new language stays paused and switches the voice`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - controller.play(document, mapOf(0 to "Переведённое предложение.")) - controller.pause() - assertEquals("voice-b", engine.voice) - val spoken = engine.spokenTexts.size - - controller.seekToBlock(document, emptyMap(), blockIndex = 0, language = TtsLanguage.Original) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals("voice-a", engine.voice) - assertEquals(spoken, engine.spokenTexts.size) - } - - @Test - fun `original language never reads the translation`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", translatedVoiceId = "voice-b"), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - - controller.playFrom( - document, - translations = mapOf(0 to "Translated sentence."), - blockIndex = null, - language = TtsLanguage.Original, - ) - - assertEquals("voice-a", engine.voice) - assertEquals(listOf("First sentence.", "Second sentence"), engine.spokenTexts) - } - - @Test - fun `failed engine is surfaced and retry restarts playback`() = runTest { - val engine = FakeEngine(ready = false) - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - - controller.play(document) - engine.listener?.onReady(false) - - assertEquals(TtsStatus.Failed, controller.state.value.status) - assertEquals("TTS unavailable", controller.state.value.message) - - controller.retry() - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(2, engine.spoken.size) - } - - @Test - fun `failed engine still exposes other engine voices for recovery`() = runTest { - val engine = FakeEngine(ready = false) - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - - engine.listener?.onReady(false) - - assertFalse(controller.capabilities.value.ready) - assertEquals( - setOf("voice-a", "voice-b"), - controller.capabilities.value.voices.map { it.id }.toSet(), - ) - assertEquals(2, controller.capabilities.value.engines.size) - } - - @Test - fun `test utterance pauses reading and speaks the sample`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - - controller.testUtterance("sample") - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(listOf("sample"), engine.previews) - } - - @Test - fun `settings are clamped before they reach the engine`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSettingsStore() - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), store) - - controller.updateSettings(TtsSettings(speed = 9f, pitch = 0.1f)) - - assertEquals(5f, controller.settings.value.speed) - assertEquals(0.5f, controller.settings.value.pitch) - assertEquals(5f, engine.appliedRate) - assertEquals(0.5f, engine.appliedPitch) - assertEquals(TtsSettings(speed = 5f, pitch = 0.5f), store.load()) - } - - @Test - fun `skip next chunk stops the queue and continues at the next chunk`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store) - controller.play(document) - engine.listener?.onStart(engine.spoken[0]) - engine.spoken.clear() - engine.stops = 0 - - controller.skipNextChunk() - - assertEquals(1, engine.stops) - assertEquals(1, engine.spoken.size) - assertEquals(1, controller.state.value.currentChunk) - assertTrue(controller.state.value.atEnd) - assertEquals(1, store.load()?.sentenceIndex) - } - - @Test - fun `skip previous chunk re-speaks from the previous chunk`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - engine.listener?.onStart(engine.spoken[1]) - engine.spoken.clear() - - controller.skipPreviousChunk() - - assertEquals(2, engine.spoken.size) - assertEquals(0, controller.state.value.currentChunk) - assertFalse(controller.state.value.atEnd) - } - - @Test - fun `paused skip moves the cursor without speaking`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store) - controller.restore(document, emptyMap(), session()) - - controller.skipPreviousChunk() - - assertTrue(engine.spoken.isEmpty()) - assertEquals(0, controller.state.value.currentChunk) - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertFalse(controller.state.value.atEnd) - assertEquals(0, store.load()?.sentenceIndex) - } - - @Test - fun `chapter skip stops speech and requests the next chapter`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store) - val requests = mutableListOf() - val job = launch { controller.chapterRequests.collect { requests += it } } - runCurrent() - controller.play(document) - engine.listener?.onStart(engine.spoken[0]) - engine.spoken.clear() - engine.stops = 0 - - controller.skipNextChapter() - runCurrent() - - assertEquals(listOf(TtsChapterDirection.Next), requests) - assertEquals(1, engine.stops) - assertTrue(engine.spoken.isEmpty()) - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertFalse(store.load()?.wasPlaying ?: true) - job.cancel() - } - - @Test - fun `previous chapter skip requests the previous direction`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - val requests = mutableListOf() - val job = launch { controller.chapterRequests.collect { requests += it } } - runCurrent() - controller.play(document) - - controller.skipPreviousChapter() - runCurrent() - - assertEquals(listOf(TtsChapterDirection.Previous), requests) - job.cancel() - } - - @Test - fun `late range from a previous utterance cannot move the highlight`() = runTest { - val twoBlocks = document.copy( - blocks = listOf( - ReaderBlock( - id = BlockId(chapterUrl, 0), - kind = BlockKind.Paragraph, - original = "First block.", - sentences = listOf(SentenceSpan(0, 12)), - ), - ReaderBlock( - id = BlockId(chapterUrl, 1), - kind = BlockKind.Paragraph, - original = "Second block.", - sentences = listOf(SentenceSpan(0, 13)), - ), - ), - ) - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(twoBlocks) - val first = engine.spoken[0] - val second = engine.spoken[1] - engine.listener?.onStart(first) - engine.listener?.onStart(second) - - val before = controller.state.value - engine.listener?.onRangeStart(first, 2, 7) - - assertEquals(before.rangeStart, controller.state.value.rangeStart) - assertEquals(before.rangeEnd, controller.state.value.rangeEnd) - assertEquals(1, controller.state.value.currentChunk) - assertEquals(1, controller.state.value.blockId?.index) - - engine.listener?.onRangeStart(second, 0, 6) - - assertEquals(0, controller.state.value.rangeStart) - assertEquals(6, controller.state.value.rangeEnd) - assertEquals(TtsStatus.Playing, controller.state.value.status) - } - - @Test - fun `late range after pause cannot move the highlight`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - val last = engine.spoken[1] - engine.listener?.onStart(last) - val before = controller.state.value - - controller.pause() - engine.listener?.onRangeStart(last, 2, 7) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(before.rangeStart, controller.state.value.rangeStart) - assertEquals(before.rangeEnd, controller.state.value.rangeEnd) - assertEquals(1, controller.state.value.currentChunk) - } - - @Test - fun `late range after a chapter request cannot move the highlight`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - val last = engine.spoken[1] - engine.listener?.onStart(last) - - controller.skipNextChapter() - val paused = controller.state.value - engine.listener?.onRangeStart(last, 2, 7) - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals(paused.rangeStart, controller.state.value.rangeStart) - assertEquals(paused.rangeEnd, controller.state.value.rangeEnd) - assertEquals(1, controller.state.value.currentChunk) - } - - @Test - fun `late onStart cannot move the cursor back`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - val first = engine.spoken[0] - val second = engine.spoken[1] - engine.listener?.onStart(first) - engine.listener?.onStart(second) - - engine.listener?.onStart(first) - - assertEquals(1, controller.state.value.currentChunk) - assertEquals(TtsStatus.Playing, controller.state.value.status) - } - - @Test - fun `atEnd follows the last chunk only`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - - engine.listener?.onStart(engine.spoken[0]) - assertFalse(controller.state.value.atEnd) - - engine.listener?.onStart(engine.spoken[1]) - assertTrue(controller.state.value.atEnd) - } - - @Test - fun `auto-next finishes the last chunk with a next chapter request`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine, - this, - InMemoryTtsSessionStore(), - InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = true)), - ) - val requests = mutableListOf() - val job = launch { controller.chapterRequests.collect { requests += it } } - runCurrent() - controller.play(document) - val last = engine.spoken[1] - engine.listener?.onStart(last) - - engine.listener?.onDone(last) - runCurrent() - - assertEquals(listOf(TtsChapterDirection.Next), requests) - assertEquals(TtsStatus.Loading, controller.state.value.status) - assertTrue(controller.state.value.atEnd) - job.cancel() - } - - @Test - fun `auto-next off ends the chapter without a request`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine, - this, - InMemoryTtsSessionStore(), - InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = false)), - ) - val requests = mutableListOf() - val job = launch { controller.chapterRequests.collect { requests += it } } - runCurrent() - controller.play(document) - val last = engine.spoken[1] - engine.listener?.onStart(last) - - engine.listener?.onDone(last) - runCurrent() - - assertTrue(requests.isEmpty()) - assertEquals(TtsStatus.Idle, controller.state.value.status) - assertTrue(controller.state.value.atEnd) - job.cancel() - } - - @Test - fun `restore applies voice and clamps rate and pitch`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - - assertTrue( - controller.restore( - document, - emptyMap(), - session().copy(voiceId = "voice-a", speed = 9f, pitch = 0.1f), - ), - ) - - assertEquals("voice-a", engine.voice) - assertEquals(5f, engine.appliedRate) - assertEquals(0.5f, engine.appliedPitch) - } - @Test - fun `playing rate change stops and requeues the current chunk`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController(engine, this, store) - controller.play(document) - engine.listener?.onStart(engine.spoken[1]) - engine.spoken.clear() - engine.stops = 0 - - controller.updateSettings( - controller.settings.value.copy(speed = 2.5f, voiceId = "voice-b"), - ) - - assertEquals(1, engine.stops) - assertEquals(1, engine.spoken.size) - assertEquals(1, controller.state.value.currentChunk) - assertEquals(2.5f, engine.appliedRate, 0.001f) - assertEquals("voice-b", engine.voice) - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(2.5f, store.load()?.speed) - assertEquals(1, store.load()?.sentenceIndex) - } - - @Test - fun `paused settings change applies without speaking`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.restore(document, emptyMap(), session()) - engine.spoken.clear() - engine.stops = 0 - - controller.updateSettings(controller.settings.value.copy(speed = 2.5f)) - - assertTrue(engine.spoken.isEmpty()) - assertEquals(0, engine.stops) - assertEquals(2.5f, engine.appliedRate, 0.001f) - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - @Test - fun `appearance only settings do not interrupt playback`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - engine.listener?.onStart(engine.spoken[1]) - engine.spoken.clear() - engine.stops = 0 - - controller.updateSettings( - controller.settings.value.copy( - floatingPlayer = true, - floatingOpacity = 0.5f, - autoNextChapter = true, - ), - ) - - assertTrue(engine.spoken.isEmpty()) - assertEquals(0, engine.stops) - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - } - - @Test - fun `engine switch during playback resumes the same chunk after init`() = runTest { - val engine = FakeEngine().apply { deferEngineReady = true } - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - engine.listener?.onStart(engine.spoken[1]) - engine.spoken.clear() - engine.stops = 0 - - controller.updateSettings(controller.settings.value.copy(engineId = "engine-b")) - - assertEquals(TtsStatus.Loading, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - assertTrue(engine.spoken.isEmpty()) - - engine.completeEngineInit() - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - assertEquals(1, engine.spoken.size) - assertEquals("engine-b", engine.currentEngineId) - } - - @Test - fun `refresh discovers engines installed or removed while running`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - assertEquals( - listOf("default", "engine-b"), - controller.capabilities.value.engines.map { it.id }, - ) - - engine.installedEngines = listOf( - TtsEngineInfo("com.google.android.tts", "Speech Services by Google", true), - TtsEngineInfo("com.github.olga_yakovleva.rhvoice.android", "RHVoice", false), - ) - controller.refreshEngines() - - assertEquals(1, engine.refreshCount) - assertEquals( - listOf("Speech Services by Google", "RHVoice"), - controller.capabilities.value.engines.map { it.label }, - ) - - engine.installedEngines = listOf( - TtsEngineInfo("com.google.android.tts", "Speech Services by Google", true), - ) - controller.refreshEngines() - - assertEquals( - listOf("com.google.android.tts"), - controller.capabilities.value.engines.map { it.id }, - ) - } - - private fun finishChapter(engine: FakeEngine) { - val last = engine.spoken.last() - engine.listener?.onStart(last) - engine.listener?.onDone(last) - } - - @Test - fun `sleep timer stops playback and keeps the session`() = runTest { - val engine = FakeEngine() - val store = InMemoryTtsSessionStore() - val controller = TtsController( - engine, - this, - store, - InMemoryTtsSettingsStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - - advanceTimeBy(60_000) - runCurrent() - - assertEquals(TtsStatus.Idle, controller.state.value.status) - assertTrue(engine.stops > 0) - assertNotNull(store.load()) - assertFalse(controller.state.value.atEnd) - assertNull(controller.sleepTimer.value) - } - - @Test - fun `sleep timer ticks down every second`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - - advanceTimeBy(2_000) - runCurrent() - - assertEquals(58, controller.sleepTimer.value?.remainingSeconds) - controller.cancelSleepTimer() - } - - @Test - fun `user pause cancels the sleep timer`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - - controller.pause() - assertNull(controller.sleepTimer.value) - - advanceTimeBy(60_000) - runCurrent() - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - @Test - fun `system pause keeps the sleep timer running`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - - controller.pauseFromSystem() - assertNotNull(controller.sleepTimer.value) - - advanceTimeBy(60_000) - runCurrent() - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `test utterance keeps the sleep timer`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(5) - - controller.testUtterance("sample") - - assertNotNull(controller.sleepTimer.value) - controller.cancelSleepTimer() - } - - @Test - fun `chapter timer continues chapters without auto-next and stops at zero`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine, - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - val requests = mutableListOf() - val job = launch { controller.chapterRequests.collect { requests += it } } - runCurrent() - controller.play(document) - controller.setSleepTimerChapters(2) - - finishChapter(engine) - runCurrent() - assertEquals(listOf(TtsChapterDirection.Next), requests) - assertEquals(TtsStatus.Loading, controller.state.value.status) - assertEquals(1, controller.sleepTimer.value?.chaptersRemaining) - - controller.play(document) - finishChapter(engine) - runCurrent() - - assertEquals(1, requests.size) - assertEquals(TtsStatus.Idle, controller.state.value.status) - assertTrue(controller.state.value.atEnd) - assertNull(controller.sleepTimer.value) - job.cancel() - } - - @Test - fun `manual chapter skip does not spend the chapter timer`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimerChapters(2) - - controller.skipNextChapter() - runCurrent() - - assertEquals(2, controller.sleepTimer.value?.chaptersRemaining) - controller.cancelSleepTimer() - } - - @Test - fun `stop and close clear the sleep timer`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimerChapters(2) - controller.stop() - assertNull(controller.sleepTimer.value) - - controller.play(document) - controller.setSleepTimer(5) - controller.close() - assertNull(controller.sleepTimer.value) - } - - @Test - fun `natural chapter end without auto-next clears the minutes timer`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine = engine, - scope = this, - sessions = InMemoryTtsSessionStore(), - settingsStore = InMemoryTtsSettingsStore(TtsSettings(autoNextChapter = false)), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(5) - - finishChapter(engine) - runCurrent() - - assertEquals(TtsStatus.Idle, controller.state.value.status) - assertNull(controller.sleepTimer.value) - } - - @Test - fun `sleep timer is ignored while playback is idle`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - - controller.setSleepTimer(5) - controller.setSleepTimerChapters(2) - - assertNull(controller.sleepTimer.value) - } - - @Test - fun `expired timer blocks a chapter hand-off`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine, - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - advanceTimeBy(60_000) - runCurrent() - - val spoken = engine.spoken.size - assertFalse(controller.playHandoff(document, emptyMap())) - assertEquals(spoken, engine.spoken.size) - assertEquals(TtsStatus.Idle, controller.state.value.status) - - controller.play(document) - assertEquals(TtsStatus.Playing, controller.state.value.status) - } - - @Test - fun `manual skip at the timer boundary cannot resurrect the chapter`() = runTest { - val controller = TtsController( - FakeEngine(), - this, - InMemoryTtsSessionStore(), - now = { testScheduler.currentTime }, - ) - controller.play(document) - controller.setSleepTimer(1) - controller.skipNextChapter() - advanceTimeBy(60_000) - runCurrent() - - assertFalse(controller.playHandoff(document, emptyMap())) - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `stop during a chapter handoff drops it`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - finishChapter(engine) - runCurrent() - assertEquals(TtsStatus.Loading, controller.state.value.status) - - controller.stop() - val spoken = engine.spoken.size - - assertFalse(controller.playHandoff(document, emptyMap())) - assertEquals(spoken, engine.spoken.size) - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `pause during a chapter handoff drops it`() = runTest { - val engine = FakeEngine() - val controller = TtsController(engine, this, InMemoryTtsSessionStore()) - controller.play(document) - finishChapter(engine) - runCurrent() - - controller.pause() - - assertFalse(controller.playHandoff(document, emptyMap())) - assertEquals(TtsStatus.Paused, controller.state.value.status) - } - - @Test - fun `handoff without a request is ignored`() = runTest { - val controller = TtsController(FakeEngine(), this, InMemoryTtsSessionStore()) - - assertFalse(controller.playHandoff(document, emptyMap())) - assertEquals(TtsStatus.Idle, controller.state.value.status) - } - - @Test - fun `reload settings applies a restored store snapshot`() = runTest { - val engine = FakeEngine() - val settings = InMemoryTtsSettingsStore( - TtsSettings(voiceId = "voice-a", engineId = "default", speed = 1f, pitch = 1f), - ) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - engine.listener?.onReady(true) - - settings.save( - TtsSettings(voiceId = "voice-b", engineId = "default", speed = 1.8f, pitch = 0.6f), - ) - controller.reloadSettings() - runCurrent() - - assertEquals("voice-b", controller.settings.value.voiceId) - assertEquals("voice-b", engine.voice) - assertEquals(1.8f, engine.appliedRate, 0.001f) - assertEquals(0.6f, engine.appliedPitch, 0.001f) - } - - @Test - fun `reload settings with a new engine resumes the current chunk`() = runTest { - val engine = FakeEngine().apply { deferEngineReady = true } - val settings = InMemoryTtsSettingsStore(TtsSettings(engineId = "default")) - val controller = TtsController(engine, this, InMemoryTtsSessionStore(), settings) - controller.play(document) - engine.listener?.onStart(engine.spoken[1]) - engine.spoken.clear() - engine.stops = 0 - - settings.save(TtsSettings(engineId = "engine-b")) - controller.reloadSettings() - runCurrent() - - // The engine restarts: the session must not stay "Playing" without sound. - assertEquals(TtsStatus.Loading, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - assertTrue(engine.spoken.isEmpty()) - - engine.completeEngineInit() - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(1, controller.state.value.currentChunk) - assertEquals(1, engine.spoken.size) - assertEquals("engine-b", engine.currentEngineId) - } - - @Test - fun `sleep timer presets set the expected duration`() = runTest { - val engine = FakeEngine() - val controller = TtsController( - engine = engine, - scope = this, - sessions = InMemoryTtsSessionStore(), - now = { 1_000L }, - ) - controller.play(document) - - TtsSleepTimerPresetMinutes.forEach { minutes -> - controller.setSleepTimer(minutes) - val timer = controller.sleepTimer.value - assertEquals(minutes * 60, timer?.totalSeconds) - assertTrue(isSleepTimerPresetActive(timer, minutes)) - } - controller.setSleepTimer(20) - assertFalse(isSleepTimerPresetActive(controller.sleepTimer.value, 15)) - controller.setSleepTimerChapters(2) - assertFalse(isSleepTimerPresetActive(controller.sleepTimer.value, 15)) - } - - @Test - fun `preview voice delegates without changing the selected voice`() = runTest { - val engine = FakeEngine() - val previewer = FakeVoicePreviewer() - val settings = InMemoryTtsSettingsStore(TtsSettings(voiceId = "voice-a")) - val controller = TtsController( - engine = engine, - scope = this, - sessions = InMemoryTtsSessionStore(), - settingsStore = settings, - voicePreviewer = previewer, - ) - val before = controller.settings.value - - controller.previewVoice("voice-b", "engine-b", 1.4f, 0.9f, "sample") - - assertEquals("voice-b", previewer.voiceId) - assertEquals("engine-b", previewer.engineId) - assertEquals(1.4f, previewer.speed) - assertEquals(0.9f, previewer.pitch) - assertEquals("sample", previewer.text) - assertEquals(before, controller.settings.value) - assertEquals("voice-a", controller.settings.value.voiceId) - - controller.stopVoicePreview() - assertEquals(1, previewer.stops) - } - - @Test - fun `preview voice pauses active reading`() = runTest { - val engine = FakeEngine() - val previewer = FakeVoicePreviewer() - val controller = TtsController( - engine = engine, - scope = this, - sessions = InMemoryTtsSessionStore(), - voicePreviewer = previewer, - ) - controller.play(document) - assertEquals(TtsStatus.Playing, controller.state.value.status) - - controller.previewVoice("voice-b", null, 1f, 1f, "sample") - - assertEquals(TtsStatus.Paused, controller.state.value.status) - assertEquals("voice-b", previewer.voiceId) - } - - @Test - fun `stop remembers the last session`() = runTest { - val sessions = InMemoryTtsSessionStore() - val controller = TtsController(FakeEngine(), this, sessions) - controller.play(document) - - controller.stop() - - val stopped = controller.lastStoppedSession - assertNotNull(stopped) - assertEquals(document.bookUrl, stopped?.bookUrl) - assertEquals(document.chapterIndex, stopped?.chapterIndex) - } - -} - -private class FakeVoicePreviewer : TtsVoicePreviewer { - var voiceId: String? = null - var engineId: String? = null - var speed: Float = 0f - var pitch: Float = 0f - var text: String = "" - var stops = 0 - - override fun preview( - voiceId: String?, - engineId: String?, - speed: Float, - pitch: Float, - text: String, - onUnavailable: () -> Unit, - ) { - this.voiceId = voiceId - this.engineId = engineId - this.speed = speed - this.pitch = pitch - this.text = text - } - - override fun stop() { - stops++ - } - - override fun shutdown() = Unit -} - -private class RecordingSessionStore : TtsSessionStore { - var saved: TtsSession? = null - private set - var savedImmediate = false - private set - var savedBackground = false - private set - - override fun load(): TtsSession? = saved - - override fun save(session: TtsSession, immediate: Boolean, background: Boolean) { - saved = session - savedImmediate = immediate - savedBackground = background - } - - override fun clear(immediate: Boolean, background: Boolean) { - saved = null - } - - @Test - fun `play queues only a bounded lookahead window and tops up on onStart`() = runTest { - val engine = FakeEngine() - val controller = createController(engine) - val doc = ReaderDocument( - bookUrl = "book://1", - chapterUrl = "ch://1", - chapterIndex = 0, - title = "Ch 1", - blocks = listOf( - ReaderBlock( - id = BlockId("ch://1", 0), - original = "One. Two. Three. Four. Five. Six.", - ), - ), - ) - - controller.play(doc) - assertEquals(4, engine.spoken.size) - assertEquals(listOf(true, false, false, false), engine.flushFlags) - - engine.listener?.onStart(engine.spoken[1]) - assertEquals(5, engine.spoken.size) - assertEquals("Five.", engine.spokenTexts.last()) - } - - @Test - fun `rapid skipNextChunk fast-forward uses flush on first chunk and stays Playing`() = runTest { - val engine = FakeEngine() - val controller = createController(engine) - val doc = ReaderDocument( - bookUrl = "book://1", - chapterUrl = "ch://1", - chapterIndex = 0, - title = "Ch 1", - blocks = listOf( - ReaderBlock( - id = BlockId("ch://1", 0), - original = "Line 1. Line 2. Line 3. Line 4. Line 5. Line 6.", - ), - ), - ) - - controller.play(doc) - engine.spoken.clear() - engine.spokenTexts.clear() - engine.flushFlags.clear() - - controller.skipNextChunk() - controller.skipNextChunk() - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(2, controller.state.value.currentChunk) - assertTrue(engine.flushFlags.first()) - assertEquals("Line 3.", engine.spokenTexts.first()) - } -} \ No newline at end of file From f67f3689dafd2693d3e85f93919e7b535174aa35 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:44:53 +0530 Subject: [PATCH 04/16] Delete Ttsengine.kt --- Ttsengine.kt | 344 --------------------------------------------------- 1 file changed, 344 deletions(-) delete mode 100644 Ttsengine.kt diff --git a/Ttsengine.kt b/Ttsengine.kt deleted file mode 100644 index a2c9aeb..0000000 --- a/Ttsengine.kt +++ /dev/null @@ -1,344 +0,0 @@ -package dev.mirutime.feature.tts - -import android.content.Context -import android.os.Handler -import android.os.Looper -import android.os.Bundle -import android.provider.Settings -import android.speech.tts.TextToSpeech -import android.speech.tts.UtteranceProgressListener -import dev.mirutime.core.log.MiruLog -import java.util.Locale - -interface TtsEngineListener { - fun onReady(ok: Boolean) - fun onStart(utteranceId: Int) - fun onDone(utteranceId: Int) - fun onError(utteranceId: Int?) - fun onRangeStart(utteranceId: Int, start: Int, end: Int) - - /** Auxiliary engines finished scanning their voices. */ - fun onVoicesChanged() = Unit -} - -/** Thin seam over the platform engine so controller state is unit-testable. */ -interface TtsEngine { - var listener: TtsEngineListener? - val isReady: Boolean - val voices: List - val engines: List - val currentEngineId: String? - val defaultEngineId: String? - - /** Re-reads the installed engines from the platform (no app restart). */ - fun refreshEngines() - - fun speak(text: String, utteranceId: Int, flush: Boolean = false): Boolean - fun preview(text: String): Boolean - fun stop() - fun setVoice(name: String?): Boolean - fun setRate(rate: Float) - fun setPitch(pitch: Float) - - /** Recreates the platform engine; the listener reports readiness again. */ - fun selectEngine(engineId: String): Boolean - fun restart() - fun shutdown() -} - -class AndroidTtsEngine(context: Context) : TtsEngine { - private val appContext = context.applicationContext - @Volatile - private var tts: TextToSpeech? = null - @Volatile - private var ready = false - private var engineId: String? = null - - // Voices of the installed engines that are not current. TextToSpeech only - // lists the voices of its own engine, so each auxiliary engine is queried - // once and shut down again; the catalog keeps the metadata afterwards. - private val auxiliaryLock = Any() - private val auxiliaryVoices = HashMap>() - private val auxiliaryRequested = HashSet() - private val auxiliaryEngines = HashMap() - - override var listener: TtsEngineListener? = null - - override val isReady: Boolean - get() = ready - - override val defaultEngineId: String? - get() = Settings.Secure.getString( - appContext.contentResolver, - Settings.Secure.TTS_DEFAULT_SYNTH, - )?.takeIf { it.isNotBlank() } - - override val currentEngineId: String? - get() { - val selected = engineId ?: defaultEngineId - val installed = tts?.engines.orEmpty().map { it.name } - return selected?.takeIf { installed.isEmpty() || it in installed } - ?: installed.firstOrNull() - } - - override val voices: List - get() { - val id = currentEngineId - val current = tts?.voices.orEmpty() - .filter { it.locale != null } - .map { voice -> - TtsVoice( - id = voice.name, - name = voice.name, - locale = voice.locale, - quality = voice.quality, - engineId = id, - needsInternet = voice.isNetworkConnectionRequired, - ) - } - val auxiliary = synchronized(auxiliaryLock) { - auxiliaryVoices.mapValues { it.value } - } - return ttsVoiceCatalog(id, current, auxiliary) - } - - override val engines: List - get() { - val default = defaultEngineId - return tts?.engines.orEmpty() - .map { TtsEngineInfo(id = it.name, label = it.label, isDefault = it.name == default) } - .sortedWith(compareBy({ !it.isDefault }, { it.label })) - } - - override fun refreshEngines() { - val platform = tts ?: return - val installed = platform.engines.orEmpty().map { it.name } - // Debug-only evidence: which engines the platform actually exposes to - // this app (package visibility matters on Android 11+). - MiruLog.d( - "tts", - "event=tts_engines count=${installed.size} ids=${installed.joinToString(",")}", - ) - // The selected engine may have been uninstalled while the app was - // running; fall back to the system engine instead of keeping a dead - // package id in settings. - val selected = engineId - if (selected != null && installed.isNotEmpty() && selected !in installed) { - initEngine(null) - return - } - refreshAuxiliaryVoices() - mainHandler.post { listener?.onVoicesChanged() } - } - - private fun refreshAuxiliaryVoices() { - val installed = tts?.engines.orEmpty().map { it.name } - if (installed.isEmpty()) return - val current = currentEngineId - val missing = synchronized(auxiliaryLock) { - installed.filter { it != current && it !in auxiliaryRequested } - } - missing.forEach(::loadAuxiliaryVoices) - var removed = false - synchronized(auxiliaryLock) { - val keep = installed.toSet() - auxiliaryRequested.retainAll(keep) - if (auxiliaryVoices.keys.any { it !in keep }) { - auxiliaryVoices.keys.retainAll(keep) - removed = true - } - val stale = auxiliaryEngines.keys.filter { it !in keep } - stale.forEach { id -> auxiliaryEngines.remove(id)?.shutdown() } - } - if (removed) mainHandler.post { listener?.onVoicesChanged() } - } - - private fun loadAuxiliaryVoices(engine: String) { - synchronized(auxiliaryLock) { - if (!auxiliaryRequested.add(engine)) return - } - // TextToSpeech reports readiness asynchronously, so the callback needs - // a holder instead of a self-reference in the constructor expression. - val holder = arrayOfNulls(1) - val instance = TextToSpeech( - appContext, - { status -> - val auxiliary = holder[0] - val voices = if (status == TextToSpeech.SUCCESS) { - auxiliary?.voices.orEmpty() - .filter { it.locale != null } - .map { voice -> - TtsVoice( - id = voice.name, - name = voice.name, - locale = voice.locale, - quality = voice.quality, - engineId = engine, - needsInternet = voice.isNetworkConnectionRequired, - ) - } - } else { - emptyList() - } - synchronized(auxiliaryLock) { - auxiliaryEngines.remove(engine) - if (voices.isNotEmpty()) { - auxiliaryVoices[engine] = voices - } else { - // Allow a later refresh to retry a failed scan. - auxiliaryRequested.remove(engine) - } - } - MiruLog.d( - "tts", - "event=tts_engine_voices engine=$engine status=$status " + - "count=${voices.size} ids=${voices.joinToString(",") { it.id }}", - ) - auxiliary?.shutdown() - mainHandler.post { listener?.onVoicesChanged() } - }, - engine, - ) - holder[0] = instance - synchronized(auxiliaryLock) { - auxiliaryEngines[engine] = instance - } - } - - // Engine callbacks arrive on binder threads; the controller is main-confined. - private val mainHandler = Handler(Looper.getMainLooper()) - - // Diagnostic: the platform may deliver these on a binder thread, not Main. - private fun logProgressThread(role: String, utteranceId: String?) { - MiruLog.d( - "tts", - "event=tts-thread role=$role thread=${Thread.currentThread().name} " + - "utterance=${utteranceId ?: "-"}", - ) - } - - // Incremented on every init/shutdown: a late onInit from an old engine - // must never mark the current (or a shut-down) engine ready. - @Volatile - private var engineGeneration = 0 - - private val progress = object : UtteranceProgressListener() { - override fun onStart(utteranceId: String?) { - logProgressThread("onStart", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onStart(value) } - } - - override fun onDone(utteranceId: String?) { - logProgressThread("onDone", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onDone(value) } - } - - @Deprecated("Deprecated in Java") - override fun onError(utteranceId: String?) { - logProgressThread("onError", utteranceId) - // Preview ("tts-preview") and foreign ids must not fail the book. - if (!shouldReportPlaybackError(utteranceId)) return - val value = utteranceId?.toIntOrNull() - mainHandler.post { listener?.onError(value) } - } - - override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) { - logProgressThread("onRangeStart", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onRangeStart(value, start, end) } - } - } - - init { - initEngine(null) - } - - private fun initEngine(enginePackage: String?) { - val generation = ++engineGeneration - ready = false - tts?.stop() - tts?.shutdown() - engineId = enginePackage - tts = TextToSpeech( - appContext, - { status -> - if (generation == engineGeneration) { - ready = status == TextToSpeech.SUCCESS - if (ready) { - tts?.language = Locale.getDefault() - tts?.setOnUtteranceProgressListener(progress) - refreshAuxiliaryVoices() - } - mainHandler.post { listener?.onReady(ready) } - } - }, - enginePackage, - ) - } - - override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { - val queueMode = if (flush) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD - return tts?.speak(text, queueMode, Bundle(), utteranceId.toString()) == - TextToSpeech.SUCCESS - } - - // QUEUE_FLUSH: a test utterance must be heard now, not after the book queue. - override fun preview(text: String): Boolean = - tts?.speak(text, TextToSpeech.QUEUE_FLUSH, Bundle(), PREVIEW_UTTERANCE) == - TextToSpeech.SUCCESS - - override fun stop() { - tts?.stop() - } - - override fun setVoice(name: String?): Boolean { - val engine = tts ?: return false - val voice = if (name == null) { - engine.defaultVoice ?: engine.voices?.firstOrNull() - } else { - engine.voices?.firstOrNull { it.name == name } - } ?: return false - return engine.setVoice(voice) == TextToSpeech.SUCCESS - } - - override fun setRate(rate: Float) { - tts?.setSpeechRate(rate) - } - - override fun setPitch(pitch: Float) { - tts?.setPitch(pitch) - } - - override fun selectEngine(engineId: String): Boolean { - if (engineId.isBlank()) return false - if (engineId == currentEngineId && ready) return true - initEngine(engineId) - return true - } - - override fun restart() { - initEngine(engineId) - } - - override fun shutdown() { - engineGeneration += 1 - tts?.stop() - tts?.shutdown() - tts = null - ready = false - synchronized(auxiliaryLock) { - auxiliaryEngines.values.forEach { it.shutdown() } - auxiliaryEngines.clear() - } - } - - private companion object { - const val PREVIEW_UTTERANCE = "tts-preview" - } -} - -/** Only a real playback utterance id may fail the active session. */ -internal fun shouldReportPlaybackError(utteranceId: String?): Boolean = - utteranceId?.toIntOrNull() != null From c8369a976784db0b94dfc95cce4e993bd3f3fda8 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:53:10 +0530 Subject: [PATCH 05/16] Add files via upload --- .../dev/mirutime/feature/tts/Ttscontroller.kt | 1165 +++++++++++++++++ .../dev/mirutime/feature/tts/Ttsengine.kt | 344 +++++ 2 files changed, 1509 insertions(+) create mode 100644 feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt create mode 100644 feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt new file mode 100644 index 0000000..2387322 --- /dev/null +++ b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt @@ -0,0 +1,1165 @@ +package dev.mirutime.feature.tts + +import android.os.SystemClock +import dev.mirutime.app.features.reader.document.BlockId +import dev.mirutime.app.features.reader.document.ReaderDocument +import dev.mirutime.core.log.MiruLog +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +enum class TtsStatus { Idle, Loading, Playing, Paused, Failed } + +/** Chapter hand-off the reader must resolve; the controller has no chapter list. */ +enum class TtsChapterDirection { Next, Previous } + +/** + * Text the rich TTS player renders. The reader parses the chapter, so it + * publishes the spoken sentence, its paragraph and the counterpart translation + * here; the in-app player and the system overlay then show the same plate. + */ +data class TtsPlayerText( + val sentence: String? = null, + val paragraph: String? = null, + val counterpart: String? = null, + val sentenceHighlightStart: Int = 0, + val sentenceHighlightEnd: Int = 0, + val chapterPercent: Int = 0, + val glowColorArgb: Long = 0L, +) + +data class TtsState( + val status: TtsStatus = TtsStatus.Idle, + val currentChunk: Int = 0, + val chunkCount: Int = 0, + val blockId: BlockId? = null, + val sentenceIndex: Int = 0, + val rangeStart: Int = 0, + val rangeEnd: Int = 0, + val translated: Boolean = false, + val atEnd: Boolean = false, + /** NoveLA-style estimate; zero until the chunk text is loaded. */ + val estimatedTotalSeconds: Int = 0, + val estimatedRemainingSeconds: Int = 0, + val message: String? = null, +) + +/** + * Small in-app TTS player. It uses the platform engine, speaks stable + * TtsChunker units, and exposes the current chunk/range for highlight. + * The cursor is persisted so a process death restores a paused position. + * Foreground playback/MediaSession/floating overlay are a later layer. + */ +class TtsController( + private val engine: TtsEngine, + private val scope: CoroutineScope, + private val sessions: TtsSessionStore = InMemoryTtsSessionStore(), + private val settingsStore: TtsSettingsStore = InMemoryTtsSettingsStore(), + /** Monotonic clock; tests inject the virtual scheduler time. */ + private val now: () -> Long = { SystemClock.elapsedRealtime() }, + private val voicePreviewer: TtsVoicePreviewer = NoopTtsVoicePreviewer, +) : TtsHandoffSource { + private val _state = MutableStateFlow(TtsState()) + override val state: StateFlow = _state.asStateFlow() + + private val _settings = MutableStateFlow(settingsStore.load().sanitized()) + val settings: StateFlow = _settings.asStateFlow() + + private val _capabilities = MutableStateFlow(TtsCapabilities()) + val capabilities: StateFlow = _capabilities.asStateFlow() + + // Conflated: a second arrow tap must not be dropped while the collector is + // still starting the first hand-off. The latest direction is what the user + // asked for, so dropping the older one is correct. + private val _chapterRequests = MutableSharedFlow( + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** + * Emitted when playback needs the reader to open another chapter (manual + * skip or auto-next). The reader owns the chapter list, loads the document + * and calls [play] so the controller never guesses what comes next. + */ + override val chapterRequests: SharedFlow = _chapterRequests.asSharedFlow() + + private val _sleepTimer = MutableStateFlow(null) + /** Running sleep timer, or null. A tick updates only [TtsSleepTimerState.remainingSeconds]. */ + val sleepTimer: StateFlow = _sleepTimer.asStateFlow() + + private val _playerText = MutableStateFlow(TtsPlayerText()) + + /** + * Text the rich player shows. The reader owns the document, so it publishes + * the current sentence/paragraph here instead of passing text through a + * service intent; the overlay renders the same plate as the in-app player. + */ + val playerText: StateFlow = _playerText.asStateFlow() + + fun updatePlayerText(value: TtsPlayerText) { + _playerText.value = value + } + + /** Stops playback after [minutes]. Setting a new timer replaces the old one. */ + fun setSleepTimer(minutes: Int) { + if (!sleepTimerAvailable()) return + clearSleepTimer() + val seconds = clampSleepTimerMinutes(minutes) * 60 + sleepDeadline = now() + seconds * 1000L + _sleepTimer.value = TtsSleepTimerState( + mode = TtsSleepTimerMode.Minutes, + remainingSeconds = seconds, + totalSeconds = seconds, + endsAtEpochMillis = System.currentTimeMillis() + seconds * 1000L, + ) + startSleepTicker() + } + + /** Stops at the end of the [chapters]th chapter counted from now. */ + fun setSleepTimerChapters(chapters: Int) { + if (!sleepTimerAvailable()) return + clearSleepTimer() + val count = clampSleepTimerChapters(chapters) + _sleepTimer.value = TtsSleepTimerState( + mode = TtsSleepTimerMode.Chapters, + chaptersRemaining = count, + chaptersTotal = count, + ) + } + + fun cancelSleepTimer() { + clearSleepTimer() + } + + /** A timer makes sense only while a TTS session exists and can still stop. */ + private fun sleepTimerAvailable(): Boolean = + chunks.isNotEmpty() && + _state.value.status != TtsStatus.Idle && + _state.value.status != TtsStatus.Failed + + private fun clearSleepTimer() { + sleepTimerJob?.cancel() + sleepTimerJob = null + sleepDeadline = 0L + _sleepTimer.value = null + } + + private fun startSleepTicker() { + sleepTimerJob = scope.launch { + while (true) { + val left = ((sleepDeadline - now()) / 1000L).coerceAtLeast(0L).toInt() + val current = _sleepTimer.value ?: return@launch + if (current.mode == TtsSleepTimerMode.Minutes && + current.remainingSeconds != left + ) { + _sleepTimer.value = current.copy(remainingSeconds = left) + } + if (left <= 0) { + // resetPlayback drops a hand-off that was requested just + // before the deadline, so waiting for Loading is unnecessary. + _sleepTimer.value = null + resetPlayback(clearSession = false) + return@launch + } + delay(250) + } + } + } + + /** + * True only while the pending chapter request came from the queue finishing + * the chapter (auto-next). A manual skip clears it first, so the reader + * never marks a chapter read the user skipped through (FR-082/FR-083). + */ + @Volatile + override var chapterEndedNaturally: Boolean = false + private set + + private var ready = false + private var pending: (() -> Unit)? = null + private var chunks: List = emptyList() + // Language of the current session. Translation is a page-level decision: + // parallel ORIGINAL_FIRST passes an empty translation map. A partially + // translated page keeps this flag for the whole session by design. + private var sessionTranslated = false + // Suffix sums of chunk text lengths: suffix[i] is "characters from chunk i + // to the end". Rebuilt only when chunks change, so the timer estimate is + // O(1) on every chunk/range update. + private var chunkCharSuffix: IntArray = IntArray(0) + private var current = 0 + private var active = false + // Platform utterance ids are unique per queue (not chunk indexes), so a + // late callback from a stopped queue cannot be mistaken for the current + // one. Cleared whenever the queue is paused/skipped/replaced. + private val utteranceChunks = java.util.concurrent.ConcurrentHashMap() + private var nextUtteranceId = 0 + private var queuedUpTo = -1 + private var bookUrl = "" + private var chapterIndex = 0 + private var voiceId: String? = _settings.value.voiceId + private var speed = _settings.value.speed + private var pitch = _settings.value.pitch + // Language slot the engine was last configured for, null until the first + // apply. Settings edits come through updateSettings(), so a seek inside the + // same slot must not reload prefs or re-hit the TTS binders. + private var appliedVoiceSlot: Boolean? = null + private var sleepTimerJob: Job? = null + private var sleepDeadline = 0L + // Set when a chapter hand-off is requested and not yet applied. Stop, pause, + // timer, close and explicit starts clear it, so a stale request can never + // resurrect playback. + @Volatile + private var handoffPending = false + private var handoffTimeout: Job? = null + + /** True while a chapter hand-off is between the request and its document. */ + val isHandoffPending: Boolean + get() = handoffPending + + // Snapshot for the reader's revert: stop() clears the persisted session, so + // the last spoken cursor would otherwise be lost. + private var _lastStoppedSession: TtsSession? = null + + /** Last session captured by a user Stop; null after a new start/resume. */ + override val lastStoppedSession: TtsSession? + get() = _lastStoppedSession + + /** + * Language the live session speaks; null when there is no session. The + * reader compares the language the page wants with this one, so a settings + * switch restarts the speech instead of waiting for the next session. + */ + override val sessionLanguage: TtsLanguage? + get() = when (_state.value.status) { + TtsStatus.Idle, TtsStatus.Failed -> null + else -> if (sessionTranslated) TtsLanguage.Translation else TtsLanguage.Original + } + + fun play( + document: ReaderDocument, + translations: Map = emptyMap(), + language: TtsLanguage = TtsLanguage.from(translations), + ) { + playFrom(document, translations, blockIndex = null, language = language) + } + + /** + * Starts at the first spoken chunk at or after [blockIndex]. The reader + * passes its visible anchor, so "Start here" never jumps back to the + * chapter top. A null blockIndex keeps the ordinary chapter start. + */ + fun playFrom( + document: ReaderDocument, + translations: Map = emptyMap(), + blockIndex: Int?, + charOffset: Int = 0, + language: TtsLanguage = TtsLanguage.from(translations), + ) { + voicePreviewer.stop() + handoffPending = false + _lastStoppedSession = null + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + if (next.isEmpty()) { + setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) + return + } + // A session speaks one language: the caller decides from the page mode, + // not from whichever block happens to be first. + sessionTranslated = language == TtsLanguage.Translation + applySavedSettings(sessionTranslated) + stopInternal(keepStatus = true) + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl + chapterIndex = document.chapterIndex + current = if (blockIndex == null) 0 else ttsStartIndex(next, blockIndex, charOffset) + active = true + MiruLog.event( + "tts", + "play", + "chunks" to next.size, + "chapter" to document.chapterIndex, + "block" to blockIndex, + "startChunk" to current, + "translated" to sessionTranslated, + "voice" to voiceId, + ) + persist(wasPlaying = true, immediate = true, background = true) + if (!ready) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } else { + speakFrom(current) + } + } + + /** + * Moves the cursor to [blockIndex] while keeping the transport state: a + * paused session only moves its cursor/highlight and stays paused, while a + * playing one re-queues from the new block. The mini player's paragraph + * arrows use this so a pause is never silently undone (FR-051). + */ + fun seekToBlock( + document: ReaderDocument, + translations: Map = emptyMap(), + blockIndex: Int, + charOffset: Int = 0, + language: TtsLanguage = TtsLanguage.from(translations), + ) { + if (_state.value.status != TtsStatus.Paused) { + playFrom(document, translations, blockIndex, charOffset, language) + return + } + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + if (next.isEmpty()) { + setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) + return + } + sessionTranslated = language == TtsLanguage.Translation + // Same slot = same voice/engine/speed, already applied: a paused chapter + // crossing must not reload settings or hit the engine binders again. + if (appliedVoiceSlot != sessionTranslated) applySavedSettings(sessionTranslated) + stopInternal(keepStatus = true) + pending = null + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl + chapterIndex = document.chapterIndex + current = ttsStartIndex(next, blockIndex, charOffset) + active = false + MiruLog.event( + "tts", + "seek", + "chunks" to next.size, + "chapter" to document.chapterIndex, + "block" to blockIndex, + "startChunk" to current, + ) + // Never starts speech: resume() is what moves a paused session. + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + + /** + * Rebuilds chunks from the current document/translation state and restores + * a paused cursor. Never starts speech, even if the session was playing. + */ + fun restore( + document: ReaderDocument, + translations: Map = emptyMap(), + session: TtsSession, + language: TtsLanguage = TtsLanguage.from(translations), + ): Boolean { + if (document.chapterUrl != session.chapterUrl) return false + if (document.chapterIndex != session.chapterIndex) return false + val spoken = sessionTranslations(language, translations) + val next = TtsChunker.chunks(document, spoken) + val cursor = resolveTtsCursor(next, session) ?: return false + stopInternal(keepStatus = true) + pending = null + chunks = next + rebuildChunkCharStats() + bookUrl = document.bookUrl.ifBlank { session.bookUrl } + chapterIndex = document.chapterIndex + current = cursor + active = false + sessionTranslated = language == TtsLanguage.Translation + val restoredSelection = sessionVoiceSelection(_settings.value, sessionTranslated) + // The engine belongs to the session's slot, not to the original one: + // a translated session must speak with the translated engine. + applyEngine(restoredSelection.engineId) + // A saved session keeps its voice only while it speaks the same + // language. Switching parallel order must pick the new language's slot. + val sameLanguage = session.translated == sessionTranslated + voiceId = if (sameLanguage) { + session.voiceId ?: restoredSelection.voiceId + } else { + restoredSelection.voiceId + } + speed = clampTtsSpeed(session.speed) + pitch = clampTtsPitch(session.pitch) + applyPlaybackSettings() + MiruLog.event( + "tts", + "restore", + "translated" to sessionTranslated, + "voice" to voiceId, + ) + setState(chunkState(cursor, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + return true + } + + /** + * True only while the pause came from audio-focus loss (call, navigation + * prompt). Every explicit pause path — notification, headset media button, + * becoming-noisy, user — clears it, so a later focus gain can never undo a + * user pause (FR-045/FR-046). + */ + @Volatile + var pausedByFocusLoss: Boolean = false + private set + + fun pause() { + MiruLog.event("tts", "pause-request", "source" to "user") + pausedByFocusLoss = false + pauseInternal(cancelSleepTimer = true) + } + + /** Pause caused by a transient audio-focus loss; a focus gain may resume it. */ + fun pauseForFocusLoss() { + if (!active && _state.value.status != TtsStatus.Loading) return + MiruLog.event("tts", "pause-request", "source" to "focus") + pausedByFocusLoss = true + pauseInternal(cancelSleepTimer = false) + } + + /** + * Pause not initiated by the user (headphone unplugged, service teardown). + * The sleep timer keeps running: the user did not ask to cancel it. + */ + fun pauseFromSystem() { + MiruLog.event("tts", "pause-request", "source" to "system") + pauseInternal(cancelSleepTimer = false) + } + + private fun pauseInternal(cancelSleepTimer: Boolean) { + handoffPending = false + if (cancelSleepTimer) clearSleepTimer() + if (!active && _state.value.status != TtsStatus.Loading) return + pending = null + invalidateUtterances() + engine.stop() + active = false + setState(_state.value.copy(status = TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + + override fun resume() { + voicePreviewer.stop() + handoffPending = false + _lastStoppedSession = null + pausedByFocusLoss = false + if (chunks.isEmpty()) return + active = true + applyPlaybackSettings() + persist(wasPlaying = true, immediate = true, background = true) + if (!ready) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + return + } + speakFrom(current) + } + + /** + * Stops the platform queue and resumes at the neighbouring chunk. While + * paused the cursor still moves (and persists) without speaking; at an + * edge the current chunk is restarted only when speech is already active. + */ + fun skipNextChunk() = skipChunkBy(1) + + fun skipPreviousChunk() = skipChunkBy(-1) + + /** + * Stops the current utterance immediately and asks the reader to load the + * next/previous chapter. The reader calls [play] on the new document, so a + * failed navigation can never leave the old chapter speaking in parallel. + */ + fun skipNextChapter() = requestChapter(TtsChapterDirection.Next) + + fun skipPreviousChapter() = requestChapter(TtsChapterDirection.Previous) + + private fun skipChunkBy(delta: Int) { + if (chunks.isEmpty()) return + invalidateUtterances() + val target = (current + delta).coerceIn(0, chunks.lastIndex) + if (target == current) { + if (active && ready) speakFrom(current) + return + } + current = target + if (active) { + if (ready) { + speakFrom(target) + } else { + setState(chunkState(target, TtsStatus.Loading)) + pending = { speakFrom(target) } + } + } else { + setState(chunkState(target, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + } + + private fun requestChapter(direction: TtsChapterDirection) { + if (chunks.isEmpty()) return + // Manual skip: never a natural end, even when the cursor sits on the + // last chunk (atEnd would be true there anyway). + chapterEndedNaturally = false + active = false + pending = null + // Mark the hand-off before the Paused state reaches the service: the + // service keeps its wake lock while a hand-off is pending. + handoffPending = true + invalidateUtterances() + engine.stop() + // Keep the old cursor paused so a rejected request can resume it. + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + requestHandoff(direction) + } + + private fun requestHandoff(direction: TtsChapterDirection) { + handoffPending = true + _chapterRequests.tryEmit(direction) + handoffTimeout?.cancel() + handoffTimeout = scope.launch { + delay(HandoffTimeoutMs) + if (!handoffPending) return@launch + // No chapter arrived: drop the pending hand-off instead of holding + // Loading (and the service wake lock) forever. + handoffPending = false + if (_state.value.status == TtsStatus.Paused || _state.value.status == TtsStatus.Loading) { + setState(chunkState(current, TtsStatus.Paused)) + persist(wasPlaying = false, immediate = true) + } + MiruLog.w("tts", "event=tts-handoff-timeout") + } + } + + fun toggle( + document: ReaderDocument, + translations: Map = emptyMap(), + language: TtsLanguage = TtsLanguage.from(translations), + ) { + when (_state.value.status) { + TtsStatus.Playing, TtsStatus.Loading -> pause() + // A paused session resumes only while it speaks the same language: + // a settings switch must not resume the old text in the old voice. + TtsStatus.Paused -> if (language != sessionLanguage) { + playFrom( + document = document, + translations = translations, + blockIndex = chunks.getOrNull(current)?.blockId?.index, + language = language, + ) + } else { + resume() + } + else -> play(document, translations, language) + } + } + + /** + * Starts speech on a chapter the reader loaded for a [chapterRequests] + * hand-off. A request is consumed only once: Stop, Pause, a new start or + * the sleep timer clears it, so a stale hand-off cannot resurrect playback. + */ + override fun playHandoff( + document: ReaderDocument, + translations: Map, + language: TtsLanguage, + ): Boolean { + if (!handoffPending) return false + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + play(document, translations, language) + return true + } + + override fun stop() { + _lastStoppedSession = sessions.load() + clearSleepTimer() + resetPlayback(clearSession = true) + } + + private fun resetPlayback(clearSession: Boolean) { + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + pausedByFocusLoss = false + active = false + pending = null + invalidateUtterances() + engine.stop() + // Persist before chunks/bookUrl are cleared, or the cursor is lost. + if (!clearSession) persist(wasPlaying = false, immediate = true) + chunks = emptyList() + chunkCharSuffix = IntArray(0) + current = 0 + sessionTranslated = false + bookUrl = "" + chapterIndex = 0 + if (clearSession) sessions.clear(immediate = true) + setState(TtsState(status = TtsStatus.Idle)) + } + + fun close() { + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + clearSleepTimer() + active = false + pending = null + invalidateUtterances() + engine.stop() + engine.shutdown() + voicePreviewer.shutdown() + ready = false + publishCapabilities() + } + + /** + * Persists and applies immediately; a restored session still wins later. + * The UI calls this on release, so voice/rate/pitch changes stop and + * re-queue the current chunk while appearance-only fields never interrupt + * speech. An engine switch re-initializes and resumes the same chunk. + */ + fun updateSettings(settings: TtsSettings) { + val previous = _settings.value + val sanitized = settings.sanitized() + // The session speaks one language: edits apply to that slot. + val previousSelection = previous.sanitized().voiceForSession(sessionTranslated) + val nextSelection = sanitized.voiceForSession(sessionTranslated) + // Only the slot this session speaks can affect playback: editing the + // other language's voice must not restart the current chunk. + val playbackChanged = ttsPlaybackChanged(previous, sanitized, sessionTranslated) + val engineChanged = previousSelection.engineId != nextSelection.engineId + _settings.value = sanitized + settingsStore.save(sanitized) + voiceId = nextSelection.voiceId + speed = sanitized.speed + pitch = sanitized.pitch + + if (engineChanged) { + val wasActive = active + invalidateUtterances() + engine.stop() + if (wasActive) { + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } + val reinitializing = applyEngine(nextSelection.engineId) + if (!reinitializing) { + // Already on the requested engine (e.g. explicit default id); + // no readiness callback will arrive, so resume now. + pending = null + applyPlaybackSettings() + if (wasActive) speakFrom(current) + } + } else if (playbackChanged) { + applyPlaybackSettings() + if (active && ready && _state.value.status == TtsStatus.Playing) { + speakFrom(current) + } + } + refreshTimeEstimate() + publishCapabilities() + } + + override fun switchLanguage( + document: ReaderDocument, + translations: Map, + blockIndex: Int, + language: TtsLanguage, + ) { + seekToBlock(document, translations, blockIndex, charOffset = 0, language = language) + } + + fun resetSettings() { + updateSettings(TtsSettings()) + } + + /** + * Re-discovers installed engines (including ones installed while the app + * is running). The voice picker calls this on open, so the catalog never + * needs an app restart or a hardcoded engine list. + */ + fun refreshEngines() { + engine.refreshEngines() + publishCapabilities() + } + + /** Short sample with the current voice/rate/pitch; pauses a live reading. */ + fun testUtterance(text: String) { + if (!ready) { + setState( + _state.value.copy( + status = TtsStatus.Failed, + message = "TTS unavailable", + ), + ) + return + } + if (active) pauseFromSystem() + applyPlaybackSettings() + engine.preview(text) + } + + /** Retries after a failure; re-creates the engine when it never came up. */ + fun retry() { + if (chunks.isEmpty()) { + setState(TtsState()) + return + } + applySavedSettings(sessionTranslated) + invalidateUtterances() + setState(chunkState(current, TtsStatus.Loading)) + if (ready) { + speakFrom(current) + } else { + pending = { speakFrom(current) } + engine.restart() + } + } + + private fun speakFrom(index: Int) { + if (!ready || chunks.isEmpty()) return + invalidateUtterances() + current = index.coerceIn(0, chunks.lastIndex) + active = true + setState(chunkState(current, TtsStatus.Playing)) + // Persist before the platform callback so skipping cannot lose the + // cursor if speech never starts (engine race, process death). + persist(wasPlaying = true, immediate = true, background = true) + engine.stop() + val end = minOf(current + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + enqueueRange(current, end, flushFirst = true) + } + + private fun enqueueRange(startIndex: Int, endIndex: Int, flushFirst: Boolean): Boolean { + for (i in startIndex..endIndex) { + val utteranceId = ++nextUtteranceId + utteranceChunks[utteranceId] = i + val flush = flushFirst && i == startIndex + if (!engine.speak(chunks[i].text, utteranceId, flush)) { + utteranceChunks.remove(utteranceId) + if (i == current) { + // Only abort playback if the active chunk itself failed to queue. + engine.stop() + setState( + _state.value.copy( + status = TtsStatus.Failed, + message = "TTS speak failed", + ), + ) + active = false + return false + } + return true + } + queuedUpTo = i + } + return true + } + + private fun topUpQueue(fromIndex: Int) { + if (!active || !ready || chunks.isEmpty()) return + val targetEnd = minOf(fromIndex + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + if (queuedUpTo < targetEnd) { + val start = maxOf(fromIndex, queuedUpTo + 1) + if (start <= targetEnd) { + enqueueRange(start, targetEnd, flushFirst = false) + } + } + } + + // Status/chunk transitions only; never the spoken text. + private fun setState(next: TtsState) { + val previous = _state.value + _state.value = next + if (previous.status != next.status || previous.currentChunk != next.currentChunk) { + MiruLog.event("tts", "state", "status" to next.status, "chunk" to next.currentChunk) + } + } + + private fun chunkState(index: Int, status: TtsStatus): TtsState { + val chunk = chunks.getOrNull(index) ?: return TtsState(status = status) + val totalSeconds = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) + val remainingSeconds = ttsEstimatedSeconds( + chunkCharSuffix.getOrElse(index) { 0 }, + speed, + ) + return TtsState( + status = status, + currentChunk = index, + chunkCount = chunks.size, + blockId = chunk.blockId, + sentenceIndex = chunk.sentenceIndex, + // Do not paint the whole sentence before the platform reports its + // first word range; that looked like a full-sentence flash. + rangeStart = chunk.startOffset, + rangeEnd = if (status == TtsStatus.Playing || status == TtsStatus.Loading) { + chunk.startOffset + } else { + chunk.endOffset + }, + translated = chunk.translated, + atEnd = index >= chunks.lastIndex, + estimatedTotalSeconds = totalSeconds, + estimatedRemainingSeconds = remainingSeconds, + ) + } + + private fun rebuildChunkCharStats() { + chunkCharSuffix = IntArray(chunks.size + 1) + for (index in chunks.indices.reversed()) { + chunkCharSuffix[index] = chunkCharSuffix[index + 1] + chunks[index].text.length + } + } + + /** Speed is live; a changed rate must not leave the old estimate behind. */ + private fun refreshTimeEstimate() { + if (chunks.isEmpty()) return + val total = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) + val remaining = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(current) { 0 }, speed) + val state = _state.value + if (state.estimatedTotalSeconds == total && + state.estimatedRemainingSeconds == remaining + ) { + return + } + setState( + state.copy( + estimatedTotalSeconds = total, + estimatedRemainingSeconds = remaining, + ), + ) + } + + private fun stopInternal(keepStatus: Boolean) { + pausedByFocusLoss = false + active = false + invalidateUtterances() + engine.stop() + if (!keepStatus) setState(TtsState()) + } + + private fun invalidateUtterances() { + utteranceChunks.clear() + queuedUpTo = -1 + } + + private fun onEngineReady() { + ready = true + applyPlaybackSettings() + publishCapabilities() + pending?.invoke() + pending = null + } + + private fun applySavedSettings(translated: Boolean = false) { + appliedVoiceSlot = translated + val saved = settingsStore.load().sanitized() + _settings.value = saved + val selection = sessionVoiceSelection(saved, translated) + voiceId = selection.voiceId + speed = saved.speed + pitch = saved.pitch + applyEngine(selection.engineId) + applyPlaybackSettings() + publishCapabilities() + } + + /** + * The text a session speaks. An Original session never reads the + * translation; a Translation session reads it and falls back to the + * original text while the translation has not arrived yet. + */ + private fun sessionTranslations( + language: TtsLanguage, + translations: Map, + ): Map { + if (language == TtsLanguage.Original) return emptyMap() + if (translations.isEmpty()) { + MiruLog.event("tts", "text-fallback", "reason" to "translation-missing") + } + return translations + } + + /** + * The voice slot a session speaks with. A translated session without a + * translated voice falls back to the original one; the fallback is logged + * so a wrong language is visible in the diagnostics. + */ + private fun sessionVoiceSelection( + settings: TtsSettings, + translated: Boolean, + ): TtsVoiceSelection { + val sanitized = settings.sanitized() + val selection = sanitized.voiceForSession(translated) + if (translated && sanitized.translatedVoiceId == null) { + MiruLog.event("tts", "voice-fallback", "reason" to "translated-voice-unset") + } + return selection + } + + /** Re-reads the durable TTS prefs after a backup restore. */ + fun reloadSettings() { + // Restore runs on an IO thread; the controller and engine are main-confined. + scope.launch { + // The session prefs were written directly by the backup store. + sessions.invalidate() + val saved = settingsStore.load().sanitized() + val selection = saved.voiceForSession(sessionTranslated) + val targetEngine = selection.engineId ?: engine.defaultEngineId + if (active && targetEngine != null && targetEngine != engine.currentEngineId) { + // The engine restarts and its queue dies with it: the session + // must re-queue the current chunk instead of staying "Playing" + // without sound. + invalidateUtterances() + engine.stop() + setState(chunkState(current, TtsStatus.Loading)) + pending = { speakFrom(current) } + } + applySavedSettings(translated = sessionTranslated) + } + } + + /** Auditions a voice without changing the selected voice/engine. */ + fun previewVoice( + voiceId: String?, + engineId: String?, + speed: Float, + pitch: Float, + text: String, + onUnavailable: () -> Unit = {}, + ) { + if (active) pauseFromSystem() + voicePreviewer.preview(voiceId, engineId, speed, pitch, text, onUnavailable) + } + + fun stopVoicePreview() = voicePreviewer.stop() + + /** Returns true when the platform engine is being re-initialized. */ + private fun applyEngine(id: String?): Boolean { + val target = id ?: engine.defaultEngineId + if (target != null && target != engine.currentEngineId) { + ready = false + engine.selectEngine(target) + return true + } + return false + } + + private fun applyPlaybackSettings() { + if (!ready) return + speed = clampTtsSpeed(speed) + pitch = clampTtsPitch(pitch) + engine.setRate(speed) + engine.setPitch(pitch) + if (!engine.setVoice(voiceId)) { + // A saved engine voice may be gone after an engine switch. + MiruLog.event("tts", "voice-fallback", "reason" to "voice-unavailable") + voiceId = null + engine.setVoice(null) + } + } + + private fun publishCapabilities() { + _capabilities.value = TtsCapabilities( + ready = ready, + // Auxiliary engine scans can still provide a usable catalog while + // the selected engine is down; the picker must offer another + // engine instead of a dead "unavailable" wall. + voices = engine.voices, + engines = engine.engines, + currentEngineId = engine.currentEngineId, + defaultEngineId = engine.defaultEngineId, + ) + } + + private fun persist( + wasPlaying: Boolean, + immediate: Boolean = false, + background: Boolean = false, + ) { + val chunk = chunks.getOrNull(current) ?: return + if (bookUrl.isBlank()) return + sessions.save( + TtsSession( + bookUrl = bookUrl, + chapterIndex = chapterIndex, + chapterUrl = chunk.blockId.chapterUrl, + blockIndex = chunk.blockId.index, + sentenceIndex = chunk.sentenceIndex, + charOffset = chunk.startOffset, + voiceId = voiceId, + speed = speed, + pitch = pitch, + wasPlaying = wasPlaying, + translated = sessionTranslated, + textHash = "${chunk.text.length}:${chunk.text.hashCode()}", + updatedAt = System.currentTimeMillis(), + ), + immediate, + background, + ) + } + + private val listener = object : TtsEngineListener { + override fun onReady(ok: Boolean) { + if (ok) { + onEngineReady() + } else { + active = false + setState(TtsState(status = TtsStatus.Failed, message = "TTS unavailable")) + pending = null + } + } + + override fun onVoicesChanged() { + publishCapabilities() + } + + override fun onStart(utteranceId: Int) { + // Only utterances queued by the current speakFrom call are known; + // a stopped/replaced queue no longer has any valid ids. + val index = utteranceChunks[utteranceId] ?: return + if (!active || index < current) return + current = index + setState(chunkState(index, TtsStatus.Playing)) + persist(wasPlaying = true, immediate = true, background = true) + topUpQueue(index) + } + + override fun onDone(utteranceId: Int) { + val index = utteranceChunks[utteranceId] ?: return + if (index < chunks.lastIndex || !active) return + active = false + persist(wasPlaying = false, immediate = true) + val timer = _sleepTimer.value + if (timer?.mode == TtsSleepTimerMode.Chapters) { + val left = timer.chaptersRemaining - 1 + if (left <= 0) { + clearSleepTimer() + invalidateUtterances() + setState( + _state.value.copy( + status = TtsStatus.Idle, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + return + } + // The chapter timer continues chapters on its own, even when + // auto-next is off: that is what "stop after N chapters" means. + _sleepTimer.value = timer.copy(chaptersRemaining = left) + chapterEndedNaturally = true + setState( + _state.value.copy( + status = TtsStatus.Loading, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + requestHandoff(TtsChapterDirection.Next) + return + } + if (_settings.value.autoNextChapter) { + // Keep the status active across the chapter load so the + // foreground service is not torn down between chapters. + chapterEndedNaturally = true + setState( + _state.value.copy( + status = TtsStatus.Loading, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + requestHandoff(TtsChapterDirection.Next) + } else { + // Playback ends here; a running minutes timer has nothing left + // to stop and would only fire into an idle session. + clearSleepTimer() + setState( + _state.value.copy( + status = TtsStatus.Idle, + atEnd = true, + estimatedRemainingSeconds = 0, + ), + ) + } + } + + override fun onError(utteranceId: Int?) { + // Late errors from a stopped/skipped queue must not fail this one. + if (utteranceId != null && utteranceChunks[utteranceId] == null) return + handoffPending = false + handoffTimeout?.cancel() + handoffTimeout = null + clearSleepTimer() + setState(_state.value.copy(status = TtsStatus.Failed, message = "TTS error")) + active = false + persist(wasPlaying = false, immediate = true) + } + + override fun onRangeStart(utteranceId: Int, start: Int, end: Int) { + val index = utteranceChunks[utteranceId] ?: return + val state = _state.value + // Late callbacks from a paused/skipped/replaced queue are not in + // the map (or no longer match the live chunk); never move the + // highlight for them. + if (!active || index != current || state.currentChunk != index) return + val chunk = chunks.getOrNull(index) ?: return + if (state.blockId != chunk.blockId) return + val base = chunk.startOffset + val consumed = start.coerceIn(0, chunk.text.length) + val remainingChars = (chunkCharSuffix.getOrElse(index) { 0 } - consumed) + .coerceAtLeast(0) + setState( + state.copy( + rangeStart = base + start, + rangeEnd = base + end, + estimatedRemainingSeconds = ttsEstimatedSeconds(remainingChars, speed), + ), + ) + } + } + + init { + engine.listener = listener + publishCapabilities() + if (engine.isReady) onEngineReady() + } +} + +/** + * First chunk at or after the reader's visible block. Chunks are ordered by + * block, so a heading/image without speech is skipped rather than failing. + * [charOffset] only matters when the anchor points inside a spoken block. + */ +internal fun ttsStartIndex( + chunks: List, + blockIndex: Int, + charOffset: Int, +): Int { + if (chunks.isEmpty()) return 0 + if (charOffset > 0) { + chunks.indexOfFirst { chunk -> + chunk.blockId.index == blockIndex && + charOffset >= chunk.startOffset && + charOffset < chunk.endOffset + }.takeIf { it >= 0 }?.let { return it } + } + return chunks.indexOfFirst { it.blockId.index >= blockIndex } + .takeIf { it >= 0 } + ?: chunks.lastIndex +} + +/** A chapter hand-off that never arrives must not hold Loading forever. */ +private const val HandoffTimeoutMs = 30_000L +private const val LOOKAHEAD_CHUNKS = 4 diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt new file mode 100644 index 0000000..a2c9aeb --- /dev/null +++ b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt @@ -0,0 +1,344 @@ +package dev.mirutime.feature.tts + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.Bundle +import android.provider.Settings +import android.speech.tts.TextToSpeech +import android.speech.tts.UtteranceProgressListener +import dev.mirutime.core.log.MiruLog +import java.util.Locale + +interface TtsEngineListener { + fun onReady(ok: Boolean) + fun onStart(utteranceId: Int) + fun onDone(utteranceId: Int) + fun onError(utteranceId: Int?) + fun onRangeStart(utteranceId: Int, start: Int, end: Int) + + /** Auxiliary engines finished scanning their voices. */ + fun onVoicesChanged() = Unit +} + +/** Thin seam over the platform engine so controller state is unit-testable. */ +interface TtsEngine { + var listener: TtsEngineListener? + val isReady: Boolean + val voices: List + val engines: List + val currentEngineId: String? + val defaultEngineId: String? + + /** Re-reads the installed engines from the platform (no app restart). */ + fun refreshEngines() + + fun speak(text: String, utteranceId: Int, flush: Boolean = false): Boolean + fun preview(text: String): Boolean + fun stop() + fun setVoice(name: String?): Boolean + fun setRate(rate: Float) + fun setPitch(pitch: Float) + + /** Recreates the platform engine; the listener reports readiness again. */ + fun selectEngine(engineId: String): Boolean + fun restart() + fun shutdown() +} + +class AndroidTtsEngine(context: Context) : TtsEngine { + private val appContext = context.applicationContext + @Volatile + private var tts: TextToSpeech? = null + @Volatile + private var ready = false + private var engineId: String? = null + + // Voices of the installed engines that are not current. TextToSpeech only + // lists the voices of its own engine, so each auxiliary engine is queried + // once and shut down again; the catalog keeps the metadata afterwards. + private val auxiliaryLock = Any() + private val auxiliaryVoices = HashMap>() + private val auxiliaryRequested = HashSet() + private val auxiliaryEngines = HashMap() + + override var listener: TtsEngineListener? = null + + override val isReady: Boolean + get() = ready + + override val defaultEngineId: String? + get() = Settings.Secure.getString( + appContext.contentResolver, + Settings.Secure.TTS_DEFAULT_SYNTH, + )?.takeIf { it.isNotBlank() } + + override val currentEngineId: String? + get() { + val selected = engineId ?: defaultEngineId + val installed = tts?.engines.orEmpty().map { it.name } + return selected?.takeIf { installed.isEmpty() || it in installed } + ?: installed.firstOrNull() + } + + override val voices: List + get() { + val id = currentEngineId + val current = tts?.voices.orEmpty() + .filter { it.locale != null } + .map { voice -> + TtsVoice( + id = voice.name, + name = voice.name, + locale = voice.locale, + quality = voice.quality, + engineId = id, + needsInternet = voice.isNetworkConnectionRequired, + ) + } + val auxiliary = synchronized(auxiliaryLock) { + auxiliaryVoices.mapValues { it.value } + } + return ttsVoiceCatalog(id, current, auxiliary) + } + + override val engines: List + get() { + val default = defaultEngineId + return tts?.engines.orEmpty() + .map { TtsEngineInfo(id = it.name, label = it.label, isDefault = it.name == default) } + .sortedWith(compareBy({ !it.isDefault }, { it.label })) + } + + override fun refreshEngines() { + val platform = tts ?: return + val installed = platform.engines.orEmpty().map { it.name } + // Debug-only evidence: which engines the platform actually exposes to + // this app (package visibility matters on Android 11+). + MiruLog.d( + "tts", + "event=tts_engines count=${installed.size} ids=${installed.joinToString(",")}", + ) + // The selected engine may have been uninstalled while the app was + // running; fall back to the system engine instead of keeping a dead + // package id in settings. + val selected = engineId + if (selected != null && installed.isNotEmpty() && selected !in installed) { + initEngine(null) + return + } + refreshAuxiliaryVoices() + mainHandler.post { listener?.onVoicesChanged() } + } + + private fun refreshAuxiliaryVoices() { + val installed = tts?.engines.orEmpty().map { it.name } + if (installed.isEmpty()) return + val current = currentEngineId + val missing = synchronized(auxiliaryLock) { + installed.filter { it != current && it !in auxiliaryRequested } + } + missing.forEach(::loadAuxiliaryVoices) + var removed = false + synchronized(auxiliaryLock) { + val keep = installed.toSet() + auxiliaryRequested.retainAll(keep) + if (auxiliaryVoices.keys.any { it !in keep }) { + auxiliaryVoices.keys.retainAll(keep) + removed = true + } + val stale = auxiliaryEngines.keys.filter { it !in keep } + stale.forEach { id -> auxiliaryEngines.remove(id)?.shutdown() } + } + if (removed) mainHandler.post { listener?.onVoicesChanged() } + } + + private fun loadAuxiliaryVoices(engine: String) { + synchronized(auxiliaryLock) { + if (!auxiliaryRequested.add(engine)) return + } + // TextToSpeech reports readiness asynchronously, so the callback needs + // a holder instead of a self-reference in the constructor expression. + val holder = arrayOfNulls(1) + val instance = TextToSpeech( + appContext, + { status -> + val auxiliary = holder[0] + val voices = if (status == TextToSpeech.SUCCESS) { + auxiliary?.voices.orEmpty() + .filter { it.locale != null } + .map { voice -> + TtsVoice( + id = voice.name, + name = voice.name, + locale = voice.locale, + quality = voice.quality, + engineId = engine, + needsInternet = voice.isNetworkConnectionRequired, + ) + } + } else { + emptyList() + } + synchronized(auxiliaryLock) { + auxiliaryEngines.remove(engine) + if (voices.isNotEmpty()) { + auxiliaryVoices[engine] = voices + } else { + // Allow a later refresh to retry a failed scan. + auxiliaryRequested.remove(engine) + } + } + MiruLog.d( + "tts", + "event=tts_engine_voices engine=$engine status=$status " + + "count=${voices.size} ids=${voices.joinToString(",") { it.id }}", + ) + auxiliary?.shutdown() + mainHandler.post { listener?.onVoicesChanged() } + }, + engine, + ) + holder[0] = instance + synchronized(auxiliaryLock) { + auxiliaryEngines[engine] = instance + } + } + + // Engine callbacks arrive on binder threads; the controller is main-confined. + private val mainHandler = Handler(Looper.getMainLooper()) + + // Diagnostic: the platform may deliver these on a binder thread, not Main. + private fun logProgressThread(role: String, utteranceId: String?) { + MiruLog.d( + "tts", + "event=tts-thread role=$role thread=${Thread.currentThread().name} " + + "utterance=${utteranceId ?: "-"}", + ) + } + + // Incremented on every init/shutdown: a late onInit from an old engine + // must never mark the current (or a shut-down) engine ready. + @Volatile + private var engineGeneration = 0 + + private val progress = object : UtteranceProgressListener() { + override fun onStart(utteranceId: String?) { + logProgressThread("onStart", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onStart(value) } + } + + override fun onDone(utteranceId: String?) { + logProgressThread("onDone", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onDone(value) } + } + + @Deprecated("Deprecated in Java") + override fun onError(utteranceId: String?) { + logProgressThread("onError", utteranceId) + // Preview ("tts-preview") and foreign ids must not fail the book. + if (!shouldReportPlaybackError(utteranceId)) return + val value = utteranceId?.toIntOrNull() + mainHandler.post { listener?.onError(value) } + } + + override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) { + logProgressThread("onRangeStart", utteranceId) + val value = utteranceId?.toIntOrNull() ?: return + mainHandler.post { listener?.onRangeStart(value, start, end) } + } + } + + init { + initEngine(null) + } + + private fun initEngine(enginePackage: String?) { + val generation = ++engineGeneration + ready = false + tts?.stop() + tts?.shutdown() + engineId = enginePackage + tts = TextToSpeech( + appContext, + { status -> + if (generation == engineGeneration) { + ready = status == TextToSpeech.SUCCESS + if (ready) { + tts?.language = Locale.getDefault() + tts?.setOnUtteranceProgressListener(progress) + refreshAuxiliaryVoices() + } + mainHandler.post { listener?.onReady(ready) } + } + }, + enginePackage, + ) + } + + override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { + val queueMode = if (flush) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD + return tts?.speak(text, queueMode, Bundle(), utteranceId.toString()) == + TextToSpeech.SUCCESS + } + + // QUEUE_FLUSH: a test utterance must be heard now, not after the book queue. + override fun preview(text: String): Boolean = + tts?.speak(text, TextToSpeech.QUEUE_FLUSH, Bundle(), PREVIEW_UTTERANCE) == + TextToSpeech.SUCCESS + + override fun stop() { + tts?.stop() + } + + override fun setVoice(name: String?): Boolean { + val engine = tts ?: return false + val voice = if (name == null) { + engine.defaultVoice ?: engine.voices?.firstOrNull() + } else { + engine.voices?.firstOrNull { it.name == name } + } ?: return false + return engine.setVoice(voice) == TextToSpeech.SUCCESS + } + + override fun setRate(rate: Float) { + tts?.setSpeechRate(rate) + } + + override fun setPitch(pitch: Float) { + tts?.setPitch(pitch) + } + + override fun selectEngine(engineId: String): Boolean { + if (engineId.isBlank()) return false + if (engineId == currentEngineId && ready) return true + initEngine(engineId) + return true + } + + override fun restart() { + initEngine(engineId) + } + + override fun shutdown() { + engineGeneration += 1 + tts?.stop() + tts?.shutdown() + tts = null + ready = false + synchronized(auxiliaryLock) { + auxiliaryEngines.values.forEach { it.shutdown() } + auxiliaryEngines.clear() + } + } + + private companion object { + const val PREVIEW_UTTERANCE = "tts-preview" + } +} + +/** Only a real playback utterance id may fail the active session. */ +internal fun shouldReportPlaybackError(utteranceId: String?): Boolean = + utteranceId?.toIntOrNull() != null From 3a52ecbff84f38b103bd5a2e0008cbf64913c6f1 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:54:34 +0530 Subject: [PATCH 06/16] Delete feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt --- .../dev/mirutime/feature/tts/Ttscontroller.kt | 1165 ----------------- 1 file changed, 1165 deletions(-) delete mode 100644 feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt deleted file mode 100644 index 2387322..0000000 --- a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttscontroller.kt +++ /dev/null @@ -1,1165 +0,0 @@ -package dev.mirutime.feature.tts - -import android.os.SystemClock -import dev.mirutime.app.features.reader.document.BlockId -import dev.mirutime.app.features.reader.document.ReaderDocument -import dev.mirutime.core.log.MiruLog -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.channels.BufferOverflow -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharedFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asSharedFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -enum class TtsStatus { Idle, Loading, Playing, Paused, Failed } - -/** Chapter hand-off the reader must resolve; the controller has no chapter list. */ -enum class TtsChapterDirection { Next, Previous } - -/** - * Text the rich TTS player renders. The reader parses the chapter, so it - * publishes the spoken sentence, its paragraph and the counterpart translation - * here; the in-app player and the system overlay then show the same plate. - */ -data class TtsPlayerText( - val sentence: String? = null, - val paragraph: String? = null, - val counterpart: String? = null, - val sentenceHighlightStart: Int = 0, - val sentenceHighlightEnd: Int = 0, - val chapterPercent: Int = 0, - val glowColorArgb: Long = 0L, -) - -data class TtsState( - val status: TtsStatus = TtsStatus.Idle, - val currentChunk: Int = 0, - val chunkCount: Int = 0, - val blockId: BlockId? = null, - val sentenceIndex: Int = 0, - val rangeStart: Int = 0, - val rangeEnd: Int = 0, - val translated: Boolean = false, - val atEnd: Boolean = false, - /** NoveLA-style estimate; zero until the chunk text is loaded. */ - val estimatedTotalSeconds: Int = 0, - val estimatedRemainingSeconds: Int = 0, - val message: String? = null, -) - -/** - * Small in-app TTS player. It uses the platform engine, speaks stable - * TtsChunker units, and exposes the current chunk/range for highlight. - * The cursor is persisted so a process death restores a paused position. - * Foreground playback/MediaSession/floating overlay are a later layer. - */ -class TtsController( - private val engine: TtsEngine, - private val scope: CoroutineScope, - private val sessions: TtsSessionStore = InMemoryTtsSessionStore(), - private val settingsStore: TtsSettingsStore = InMemoryTtsSettingsStore(), - /** Monotonic clock; tests inject the virtual scheduler time. */ - private val now: () -> Long = { SystemClock.elapsedRealtime() }, - private val voicePreviewer: TtsVoicePreviewer = NoopTtsVoicePreviewer, -) : TtsHandoffSource { - private val _state = MutableStateFlow(TtsState()) - override val state: StateFlow = _state.asStateFlow() - - private val _settings = MutableStateFlow(settingsStore.load().sanitized()) - val settings: StateFlow = _settings.asStateFlow() - - private val _capabilities = MutableStateFlow(TtsCapabilities()) - val capabilities: StateFlow = _capabilities.asStateFlow() - - // Conflated: a second arrow tap must not be dropped while the collector is - // still starting the first hand-off. The latest direction is what the user - // asked for, so dropping the older one is correct. - private val _chapterRequests = MutableSharedFlow( - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - - /** - * Emitted when playback needs the reader to open another chapter (manual - * skip or auto-next). The reader owns the chapter list, loads the document - * and calls [play] so the controller never guesses what comes next. - */ - override val chapterRequests: SharedFlow = _chapterRequests.asSharedFlow() - - private val _sleepTimer = MutableStateFlow(null) - /** Running sleep timer, or null. A tick updates only [TtsSleepTimerState.remainingSeconds]. */ - val sleepTimer: StateFlow = _sleepTimer.asStateFlow() - - private val _playerText = MutableStateFlow(TtsPlayerText()) - - /** - * Text the rich player shows. The reader owns the document, so it publishes - * the current sentence/paragraph here instead of passing text through a - * service intent; the overlay renders the same plate as the in-app player. - */ - val playerText: StateFlow = _playerText.asStateFlow() - - fun updatePlayerText(value: TtsPlayerText) { - _playerText.value = value - } - - /** Stops playback after [minutes]. Setting a new timer replaces the old one. */ - fun setSleepTimer(minutes: Int) { - if (!sleepTimerAvailable()) return - clearSleepTimer() - val seconds = clampSleepTimerMinutes(minutes) * 60 - sleepDeadline = now() + seconds * 1000L - _sleepTimer.value = TtsSleepTimerState( - mode = TtsSleepTimerMode.Minutes, - remainingSeconds = seconds, - totalSeconds = seconds, - endsAtEpochMillis = System.currentTimeMillis() + seconds * 1000L, - ) - startSleepTicker() - } - - /** Stops at the end of the [chapters]th chapter counted from now. */ - fun setSleepTimerChapters(chapters: Int) { - if (!sleepTimerAvailable()) return - clearSleepTimer() - val count = clampSleepTimerChapters(chapters) - _sleepTimer.value = TtsSleepTimerState( - mode = TtsSleepTimerMode.Chapters, - chaptersRemaining = count, - chaptersTotal = count, - ) - } - - fun cancelSleepTimer() { - clearSleepTimer() - } - - /** A timer makes sense only while a TTS session exists and can still stop. */ - private fun sleepTimerAvailable(): Boolean = - chunks.isNotEmpty() && - _state.value.status != TtsStatus.Idle && - _state.value.status != TtsStatus.Failed - - private fun clearSleepTimer() { - sleepTimerJob?.cancel() - sleepTimerJob = null - sleepDeadline = 0L - _sleepTimer.value = null - } - - private fun startSleepTicker() { - sleepTimerJob = scope.launch { - while (true) { - val left = ((sleepDeadline - now()) / 1000L).coerceAtLeast(0L).toInt() - val current = _sleepTimer.value ?: return@launch - if (current.mode == TtsSleepTimerMode.Minutes && - current.remainingSeconds != left - ) { - _sleepTimer.value = current.copy(remainingSeconds = left) - } - if (left <= 0) { - // resetPlayback drops a hand-off that was requested just - // before the deadline, so waiting for Loading is unnecessary. - _sleepTimer.value = null - resetPlayback(clearSession = false) - return@launch - } - delay(250) - } - } - } - - /** - * True only while the pending chapter request came from the queue finishing - * the chapter (auto-next). A manual skip clears it first, so the reader - * never marks a chapter read the user skipped through (FR-082/FR-083). - */ - @Volatile - override var chapterEndedNaturally: Boolean = false - private set - - private var ready = false - private var pending: (() -> Unit)? = null - private var chunks: List = emptyList() - // Language of the current session. Translation is a page-level decision: - // parallel ORIGINAL_FIRST passes an empty translation map. A partially - // translated page keeps this flag for the whole session by design. - private var sessionTranslated = false - // Suffix sums of chunk text lengths: suffix[i] is "characters from chunk i - // to the end". Rebuilt only when chunks change, so the timer estimate is - // O(1) on every chunk/range update. - private var chunkCharSuffix: IntArray = IntArray(0) - private var current = 0 - private var active = false - // Platform utterance ids are unique per queue (not chunk indexes), so a - // late callback from a stopped queue cannot be mistaken for the current - // one. Cleared whenever the queue is paused/skipped/replaced. - private val utteranceChunks = java.util.concurrent.ConcurrentHashMap() - private var nextUtteranceId = 0 - private var queuedUpTo = -1 - private var bookUrl = "" - private var chapterIndex = 0 - private var voiceId: String? = _settings.value.voiceId - private var speed = _settings.value.speed - private var pitch = _settings.value.pitch - // Language slot the engine was last configured for, null until the first - // apply. Settings edits come through updateSettings(), so a seek inside the - // same slot must not reload prefs or re-hit the TTS binders. - private var appliedVoiceSlot: Boolean? = null - private var sleepTimerJob: Job? = null - private var sleepDeadline = 0L - // Set when a chapter hand-off is requested and not yet applied. Stop, pause, - // timer, close and explicit starts clear it, so a stale request can never - // resurrect playback. - @Volatile - private var handoffPending = false - private var handoffTimeout: Job? = null - - /** True while a chapter hand-off is between the request and its document. */ - val isHandoffPending: Boolean - get() = handoffPending - - // Snapshot for the reader's revert: stop() clears the persisted session, so - // the last spoken cursor would otherwise be lost. - private var _lastStoppedSession: TtsSession? = null - - /** Last session captured by a user Stop; null after a new start/resume. */ - override val lastStoppedSession: TtsSession? - get() = _lastStoppedSession - - /** - * Language the live session speaks; null when there is no session. The - * reader compares the language the page wants with this one, so a settings - * switch restarts the speech instead of waiting for the next session. - */ - override val sessionLanguage: TtsLanguage? - get() = when (_state.value.status) { - TtsStatus.Idle, TtsStatus.Failed -> null - else -> if (sessionTranslated) TtsLanguage.Translation else TtsLanguage.Original - } - - fun play( - document: ReaderDocument, - translations: Map = emptyMap(), - language: TtsLanguage = TtsLanguage.from(translations), - ) { - playFrom(document, translations, blockIndex = null, language = language) - } - - /** - * Starts at the first spoken chunk at or after [blockIndex]. The reader - * passes its visible anchor, so "Start here" never jumps back to the - * chapter top. A null blockIndex keeps the ordinary chapter start. - */ - fun playFrom( - document: ReaderDocument, - translations: Map = emptyMap(), - blockIndex: Int?, - charOffset: Int = 0, - language: TtsLanguage = TtsLanguage.from(translations), - ) { - voicePreviewer.stop() - handoffPending = false - _lastStoppedSession = null - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - if (next.isEmpty()) { - setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) - return - } - // A session speaks one language: the caller decides from the page mode, - // not from whichever block happens to be first. - sessionTranslated = language == TtsLanguage.Translation - applySavedSettings(sessionTranslated) - stopInternal(keepStatus = true) - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl - chapterIndex = document.chapterIndex - current = if (blockIndex == null) 0 else ttsStartIndex(next, blockIndex, charOffset) - active = true - MiruLog.event( - "tts", - "play", - "chunks" to next.size, - "chapter" to document.chapterIndex, - "block" to blockIndex, - "startChunk" to current, - "translated" to sessionTranslated, - "voice" to voiceId, - ) - persist(wasPlaying = true, immediate = true, background = true) - if (!ready) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } else { - speakFrom(current) - } - } - - /** - * Moves the cursor to [blockIndex] while keeping the transport state: a - * paused session only moves its cursor/highlight and stays paused, while a - * playing one re-queues from the new block. The mini player's paragraph - * arrows use this so a pause is never silently undone (FR-051). - */ - fun seekToBlock( - document: ReaderDocument, - translations: Map = emptyMap(), - blockIndex: Int, - charOffset: Int = 0, - language: TtsLanguage = TtsLanguage.from(translations), - ) { - if (_state.value.status != TtsStatus.Paused) { - playFrom(document, translations, blockIndex, charOffset, language) - return - } - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - if (next.isEmpty()) { - setState(TtsState(status = TtsStatus.Failed, message = "Nothing to read")) - return - } - sessionTranslated = language == TtsLanguage.Translation - // Same slot = same voice/engine/speed, already applied: a paused chapter - // crossing must not reload settings or hit the engine binders again. - if (appliedVoiceSlot != sessionTranslated) applySavedSettings(sessionTranslated) - stopInternal(keepStatus = true) - pending = null - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl - chapterIndex = document.chapterIndex - current = ttsStartIndex(next, blockIndex, charOffset) - active = false - MiruLog.event( - "tts", - "seek", - "chunks" to next.size, - "chapter" to document.chapterIndex, - "block" to blockIndex, - "startChunk" to current, - ) - // Never starts speech: resume() is what moves a paused session. - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - - /** - * Rebuilds chunks from the current document/translation state and restores - * a paused cursor. Never starts speech, even if the session was playing. - */ - fun restore( - document: ReaderDocument, - translations: Map = emptyMap(), - session: TtsSession, - language: TtsLanguage = TtsLanguage.from(translations), - ): Boolean { - if (document.chapterUrl != session.chapterUrl) return false - if (document.chapterIndex != session.chapterIndex) return false - val spoken = sessionTranslations(language, translations) - val next = TtsChunker.chunks(document, spoken) - val cursor = resolveTtsCursor(next, session) ?: return false - stopInternal(keepStatus = true) - pending = null - chunks = next - rebuildChunkCharStats() - bookUrl = document.bookUrl.ifBlank { session.bookUrl } - chapterIndex = document.chapterIndex - current = cursor - active = false - sessionTranslated = language == TtsLanguage.Translation - val restoredSelection = sessionVoiceSelection(_settings.value, sessionTranslated) - // The engine belongs to the session's slot, not to the original one: - // a translated session must speak with the translated engine. - applyEngine(restoredSelection.engineId) - // A saved session keeps its voice only while it speaks the same - // language. Switching parallel order must pick the new language's slot. - val sameLanguage = session.translated == sessionTranslated - voiceId = if (sameLanguage) { - session.voiceId ?: restoredSelection.voiceId - } else { - restoredSelection.voiceId - } - speed = clampTtsSpeed(session.speed) - pitch = clampTtsPitch(session.pitch) - applyPlaybackSettings() - MiruLog.event( - "tts", - "restore", - "translated" to sessionTranslated, - "voice" to voiceId, - ) - setState(chunkState(cursor, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - return true - } - - /** - * True only while the pause came from audio-focus loss (call, navigation - * prompt). Every explicit pause path — notification, headset media button, - * becoming-noisy, user — clears it, so a later focus gain can never undo a - * user pause (FR-045/FR-046). - */ - @Volatile - var pausedByFocusLoss: Boolean = false - private set - - fun pause() { - MiruLog.event("tts", "pause-request", "source" to "user") - pausedByFocusLoss = false - pauseInternal(cancelSleepTimer = true) - } - - /** Pause caused by a transient audio-focus loss; a focus gain may resume it. */ - fun pauseForFocusLoss() { - if (!active && _state.value.status != TtsStatus.Loading) return - MiruLog.event("tts", "pause-request", "source" to "focus") - pausedByFocusLoss = true - pauseInternal(cancelSleepTimer = false) - } - - /** - * Pause not initiated by the user (headphone unplugged, service teardown). - * The sleep timer keeps running: the user did not ask to cancel it. - */ - fun pauseFromSystem() { - MiruLog.event("tts", "pause-request", "source" to "system") - pauseInternal(cancelSleepTimer = false) - } - - private fun pauseInternal(cancelSleepTimer: Boolean) { - handoffPending = false - if (cancelSleepTimer) clearSleepTimer() - if (!active && _state.value.status != TtsStatus.Loading) return - pending = null - invalidateUtterances() - engine.stop() - active = false - setState(_state.value.copy(status = TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - - override fun resume() { - voicePreviewer.stop() - handoffPending = false - _lastStoppedSession = null - pausedByFocusLoss = false - if (chunks.isEmpty()) return - active = true - applyPlaybackSettings() - persist(wasPlaying = true, immediate = true, background = true) - if (!ready) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - return - } - speakFrom(current) - } - - /** - * Stops the platform queue and resumes at the neighbouring chunk. While - * paused the cursor still moves (and persists) without speaking; at an - * edge the current chunk is restarted only when speech is already active. - */ - fun skipNextChunk() = skipChunkBy(1) - - fun skipPreviousChunk() = skipChunkBy(-1) - - /** - * Stops the current utterance immediately and asks the reader to load the - * next/previous chapter. The reader calls [play] on the new document, so a - * failed navigation can never leave the old chapter speaking in parallel. - */ - fun skipNextChapter() = requestChapter(TtsChapterDirection.Next) - - fun skipPreviousChapter() = requestChapter(TtsChapterDirection.Previous) - - private fun skipChunkBy(delta: Int) { - if (chunks.isEmpty()) return - invalidateUtterances() - val target = (current + delta).coerceIn(0, chunks.lastIndex) - if (target == current) { - if (active && ready) speakFrom(current) - return - } - current = target - if (active) { - if (ready) { - speakFrom(target) - } else { - setState(chunkState(target, TtsStatus.Loading)) - pending = { speakFrom(target) } - } - } else { - setState(chunkState(target, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - } - - private fun requestChapter(direction: TtsChapterDirection) { - if (chunks.isEmpty()) return - // Manual skip: never a natural end, even when the cursor sits on the - // last chunk (atEnd would be true there anyway). - chapterEndedNaturally = false - active = false - pending = null - // Mark the hand-off before the Paused state reaches the service: the - // service keeps its wake lock while a hand-off is pending. - handoffPending = true - invalidateUtterances() - engine.stop() - // Keep the old cursor paused so a rejected request can resume it. - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - requestHandoff(direction) - } - - private fun requestHandoff(direction: TtsChapterDirection) { - handoffPending = true - _chapterRequests.tryEmit(direction) - handoffTimeout?.cancel() - handoffTimeout = scope.launch { - delay(HandoffTimeoutMs) - if (!handoffPending) return@launch - // No chapter arrived: drop the pending hand-off instead of holding - // Loading (and the service wake lock) forever. - handoffPending = false - if (_state.value.status == TtsStatus.Paused || _state.value.status == TtsStatus.Loading) { - setState(chunkState(current, TtsStatus.Paused)) - persist(wasPlaying = false, immediate = true) - } - MiruLog.w("tts", "event=tts-handoff-timeout") - } - } - - fun toggle( - document: ReaderDocument, - translations: Map = emptyMap(), - language: TtsLanguage = TtsLanguage.from(translations), - ) { - when (_state.value.status) { - TtsStatus.Playing, TtsStatus.Loading -> pause() - // A paused session resumes only while it speaks the same language: - // a settings switch must not resume the old text in the old voice. - TtsStatus.Paused -> if (language != sessionLanguage) { - playFrom( - document = document, - translations = translations, - blockIndex = chunks.getOrNull(current)?.blockId?.index, - language = language, - ) - } else { - resume() - } - else -> play(document, translations, language) - } - } - - /** - * Starts speech on a chapter the reader loaded for a [chapterRequests] - * hand-off. A request is consumed only once: Stop, Pause, a new start or - * the sleep timer clears it, so a stale hand-off cannot resurrect playback. - */ - override fun playHandoff( - document: ReaderDocument, - translations: Map, - language: TtsLanguage, - ): Boolean { - if (!handoffPending) return false - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - play(document, translations, language) - return true - } - - override fun stop() { - _lastStoppedSession = sessions.load() - clearSleepTimer() - resetPlayback(clearSession = true) - } - - private fun resetPlayback(clearSession: Boolean) { - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - pausedByFocusLoss = false - active = false - pending = null - invalidateUtterances() - engine.stop() - // Persist before chunks/bookUrl are cleared, or the cursor is lost. - if (!clearSession) persist(wasPlaying = false, immediate = true) - chunks = emptyList() - chunkCharSuffix = IntArray(0) - current = 0 - sessionTranslated = false - bookUrl = "" - chapterIndex = 0 - if (clearSession) sessions.clear(immediate = true) - setState(TtsState(status = TtsStatus.Idle)) - } - - fun close() { - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - clearSleepTimer() - active = false - pending = null - invalidateUtterances() - engine.stop() - engine.shutdown() - voicePreviewer.shutdown() - ready = false - publishCapabilities() - } - - /** - * Persists and applies immediately; a restored session still wins later. - * The UI calls this on release, so voice/rate/pitch changes stop and - * re-queue the current chunk while appearance-only fields never interrupt - * speech. An engine switch re-initializes and resumes the same chunk. - */ - fun updateSettings(settings: TtsSettings) { - val previous = _settings.value - val sanitized = settings.sanitized() - // The session speaks one language: edits apply to that slot. - val previousSelection = previous.sanitized().voiceForSession(sessionTranslated) - val nextSelection = sanitized.voiceForSession(sessionTranslated) - // Only the slot this session speaks can affect playback: editing the - // other language's voice must not restart the current chunk. - val playbackChanged = ttsPlaybackChanged(previous, sanitized, sessionTranslated) - val engineChanged = previousSelection.engineId != nextSelection.engineId - _settings.value = sanitized - settingsStore.save(sanitized) - voiceId = nextSelection.voiceId - speed = sanitized.speed - pitch = sanitized.pitch - - if (engineChanged) { - val wasActive = active - invalidateUtterances() - engine.stop() - if (wasActive) { - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } - val reinitializing = applyEngine(nextSelection.engineId) - if (!reinitializing) { - // Already on the requested engine (e.g. explicit default id); - // no readiness callback will arrive, so resume now. - pending = null - applyPlaybackSettings() - if (wasActive) speakFrom(current) - } - } else if (playbackChanged) { - applyPlaybackSettings() - if (active && ready && _state.value.status == TtsStatus.Playing) { - speakFrom(current) - } - } - refreshTimeEstimate() - publishCapabilities() - } - - override fun switchLanguage( - document: ReaderDocument, - translations: Map, - blockIndex: Int, - language: TtsLanguage, - ) { - seekToBlock(document, translations, blockIndex, charOffset = 0, language = language) - } - - fun resetSettings() { - updateSettings(TtsSettings()) - } - - /** - * Re-discovers installed engines (including ones installed while the app - * is running). The voice picker calls this on open, so the catalog never - * needs an app restart or a hardcoded engine list. - */ - fun refreshEngines() { - engine.refreshEngines() - publishCapabilities() - } - - /** Short sample with the current voice/rate/pitch; pauses a live reading. */ - fun testUtterance(text: String) { - if (!ready) { - setState( - _state.value.copy( - status = TtsStatus.Failed, - message = "TTS unavailable", - ), - ) - return - } - if (active) pauseFromSystem() - applyPlaybackSettings() - engine.preview(text) - } - - /** Retries after a failure; re-creates the engine when it never came up. */ - fun retry() { - if (chunks.isEmpty()) { - setState(TtsState()) - return - } - applySavedSettings(sessionTranslated) - invalidateUtterances() - setState(chunkState(current, TtsStatus.Loading)) - if (ready) { - speakFrom(current) - } else { - pending = { speakFrom(current) } - engine.restart() - } - } - - private fun speakFrom(index: Int) { - if (!ready || chunks.isEmpty()) return - invalidateUtterances() - current = index.coerceIn(0, chunks.lastIndex) - active = true - setState(chunkState(current, TtsStatus.Playing)) - // Persist before the platform callback so skipping cannot lose the - // cursor if speech never starts (engine race, process death). - persist(wasPlaying = true, immediate = true, background = true) - engine.stop() - val end = minOf(current + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) - enqueueRange(current, end, flushFirst = true) - } - - private fun enqueueRange(startIndex: Int, endIndex: Int, flushFirst: Boolean): Boolean { - for (i in startIndex..endIndex) { - val utteranceId = ++nextUtteranceId - utteranceChunks[utteranceId] = i - val flush = flushFirst && i == startIndex - if (!engine.speak(chunks[i].text, utteranceId, flush)) { - utteranceChunks.remove(utteranceId) - if (i == current) { - // Only abort playback if the active chunk itself failed to queue. - engine.stop() - setState( - _state.value.copy( - status = TtsStatus.Failed, - message = "TTS speak failed", - ), - ) - active = false - return false - } - return true - } - queuedUpTo = i - } - return true - } - - private fun topUpQueue(fromIndex: Int) { - if (!active || !ready || chunks.isEmpty()) return - val targetEnd = minOf(fromIndex + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) - if (queuedUpTo < targetEnd) { - val start = maxOf(fromIndex, queuedUpTo + 1) - if (start <= targetEnd) { - enqueueRange(start, targetEnd, flushFirst = false) - } - } - } - - // Status/chunk transitions only; never the spoken text. - private fun setState(next: TtsState) { - val previous = _state.value - _state.value = next - if (previous.status != next.status || previous.currentChunk != next.currentChunk) { - MiruLog.event("tts", "state", "status" to next.status, "chunk" to next.currentChunk) - } - } - - private fun chunkState(index: Int, status: TtsStatus): TtsState { - val chunk = chunks.getOrNull(index) ?: return TtsState(status = status) - val totalSeconds = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) - val remainingSeconds = ttsEstimatedSeconds( - chunkCharSuffix.getOrElse(index) { 0 }, - speed, - ) - return TtsState( - status = status, - currentChunk = index, - chunkCount = chunks.size, - blockId = chunk.blockId, - sentenceIndex = chunk.sentenceIndex, - // Do not paint the whole sentence before the platform reports its - // first word range; that looked like a full-sentence flash. - rangeStart = chunk.startOffset, - rangeEnd = if (status == TtsStatus.Playing || status == TtsStatus.Loading) { - chunk.startOffset - } else { - chunk.endOffset - }, - translated = chunk.translated, - atEnd = index >= chunks.lastIndex, - estimatedTotalSeconds = totalSeconds, - estimatedRemainingSeconds = remainingSeconds, - ) - } - - private fun rebuildChunkCharStats() { - chunkCharSuffix = IntArray(chunks.size + 1) - for (index in chunks.indices.reversed()) { - chunkCharSuffix[index] = chunkCharSuffix[index + 1] + chunks[index].text.length - } - } - - /** Speed is live; a changed rate must not leave the old estimate behind. */ - private fun refreshTimeEstimate() { - if (chunks.isEmpty()) return - val total = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(0) { 0 }, speed) - val remaining = ttsEstimatedSeconds(chunkCharSuffix.getOrElse(current) { 0 }, speed) - val state = _state.value - if (state.estimatedTotalSeconds == total && - state.estimatedRemainingSeconds == remaining - ) { - return - } - setState( - state.copy( - estimatedTotalSeconds = total, - estimatedRemainingSeconds = remaining, - ), - ) - } - - private fun stopInternal(keepStatus: Boolean) { - pausedByFocusLoss = false - active = false - invalidateUtterances() - engine.stop() - if (!keepStatus) setState(TtsState()) - } - - private fun invalidateUtterances() { - utteranceChunks.clear() - queuedUpTo = -1 - } - - private fun onEngineReady() { - ready = true - applyPlaybackSettings() - publishCapabilities() - pending?.invoke() - pending = null - } - - private fun applySavedSettings(translated: Boolean = false) { - appliedVoiceSlot = translated - val saved = settingsStore.load().sanitized() - _settings.value = saved - val selection = sessionVoiceSelection(saved, translated) - voiceId = selection.voiceId - speed = saved.speed - pitch = saved.pitch - applyEngine(selection.engineId) - applyPlaybackSettings() - publishCapabilities() - } - - /** - * The text a session speaks. An Original session never reads the - * translation; a Translation session reads it and falls back to the - * original text while the translation has not arrived yet. - */ - private fun sessionTranslations( - language: TtsLanguage, - translations: Map, - ): Map { - if (language == TtsLanguage.Original) return emptyMap() - if (translations.isEmpty()) { - MiruLog.event("tts", "text-fallback", "reason" to "translation-missing") - } - return translations - } - - /** - * The voice slot a session speaks with. A translated session without a - * translated voice falls back to the original one; the fallback is logged - * so a wrong language is visible in the diagnostics. - */ - private fun sessionVoiceSelection( - settings: TtsSettings, - translated: Boolean, - ): TtsVoiceSelection { - val sanitized = settings.sanitized() - val selection = sanitized.voiceForSession(translated) - if (translated && sanitized.translatedVoiceId == null) { - MiruLog.event("tts", "voice-fallback", "reason" to "translated-voice-unset") - } - return selection - } - - /** Re-reads the durable TTS prefs after a backup restore. */ - fun reloadSettings() { - // Restore runs on an IO thread; the controller and engine are main-confined. - scope.launch { - // The session prefs were written directly by the backup store. - sessions.invalidate() - val saved = settingsStore.load().sanitized() - val selection = saved.voiceForSession(sessionTranslated) - val targetEngine = selection.engineId ?: engine.defaultEngineId - if (active && targetEngine != null && targetEngine != engine.currentEngineId) { - // The engine restarts and its queue dies with it: the session - // must re-queue the current chunk instead of staying "Playing" - // without sound. - invalidateUtterances() - engine.stop() - setState(chunkState(current, TtsStatus.Loading)) - pending = { speakFrom(current) } - } - applySavedSettings(translated = sessionTranslated) - } - } - - /** Auditions a voice without changing the selected voice/engine. */ - fun previewVoice( - voiceId: String?, - engineId: String?, - speed: Float, - pitch: Float, - text: String, - onUnavailable: () -> Unit = {}, - ) { - if (active) pauseFromSystem() - voicePreviewer.preview(voiceId, engineId, speed, pitch, text, onUnavailable) - } - - fun stopVoicePreview() = voicePreviewer.stop() - - /** Returns true when the platform engine is being re-initialized. */ - private fun applyEngine(id: String?): Boolean { - val target = id ?: engine.defaultEngineId - if (target != null && target != engine.currentEngineId) { - ready = false - engine.selectEngine(target) - return true - } - return false - } - - private fun applyPlaybackSettings() { - if (!ready) return - speed = clampTtsSpeed(speed) - pitch = clampTtsPitch(pitch) - engine.setRate(speed) - engine.setPitch(pitch) - if (!engine.setVoice(voiceId)) { - // A saved engine voice may be gone after an engine switch. - MiruLog.event("tts", "voice-fallback", "reason" to "voice-unavailable") - voiceId = null - engine.setVoice(null) - } - } - - private fun publishCapabilities() { - _capabilities.value = TtsCapabilities( - ready = ready, - // Auxiliary engine scans can still provide a usable catalog while - // the selected engine is down; the picker must offer another - // engine instead of a dead "unavailable" wall. - voices = engine.voices, - engines = engine.engines, - currentEngineId = engine.currentEngineId, - defaultEngineId = engine.defaultEngineId, - ) - } - - private fun persist( - wasPlaying: Boolean, - immediate: Boolean = false, - background: Boolean = false, - ) { - val chunk = chunks.getOrNull(current) ?: return - if (bookUrl.isBlank()) return - sessions.save( - TtsSession( - bookUrl = bookUrl, - chapterIndex = chapterIndex, - chapterUrl = chunk.blockId.chapterUrl, - blockIndex = chunk.blockId.index, - sentenceIndex = chunk.sentenceIndex, - charOffset = chunk.startOffset, - voiceId = voiceId, - speed = speed, - pitch = pitch, - wasPlaying = wasPlaying, - translated = sessionTranslated, - textHash = "${chunk.text.length}:${chunk.text.hashCode()}", - updatedAt = System.currentTimeMillis(), - ), - immediate, - background, - ) - } - - private val listener = object : TtsEngineListener { - override fun onReady(ok: Boolean) { - if (ok) { - onEngineReady() - } else { - active = false - setState(TtsState(status = TtsStatus.Failed, message = "TTS unavailable")) - pending = null - } - } - - override fun onVoicesChanged() { - publishCapabilities() - } - - override fun onStart(utteranceId: Int) { - // Only utterances queued by the current speakFrom call are known; - // a stopped/replaced queue no longer has any valid ids. - val index = utteranceChunks[utteranceId] ?: return - if (!active || index < current) return - current = index - setState(chunkState(index, TtsStatus.Playing)) - persist(wasPlaying = true, immediate = true, background = true) - topUpQueue(index) - } - - override fun onDone(utteranceId: Int) { - val index = utteranceChunks[utteranceId] ?: return - if (index < chunks.lastIndex || !active) return - active = false - persist(wasPlaying = false, immediate = true) - val timer = _sleepTimer.value - if (timer?.mode == TtsSleepTimerMode.Chapters) { - val left = timer.chaptersRemaining - 1 - if (left <= 0) { - clearSleepTimer() - invalidateUtterances() - setState( - _state.value.copy( - status = TtsStatus.Idle, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - return - } - // The chapter timer continues chapters on its own, even when - // auto-next is off: that is what "stop after N chapters" means. - _sleepTimer.value = timer.copy(chaptersRemaining = left) - chapterEndedNaturally = true - setState( - _state.value.copy( - status = TtsStatus.Loading, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - requestHandoff(TtsChapterDirection.Next) - return - } - if (_settings.value.autoNextChapter) { - // Keep the status active across the chapter load so the - // foreground service is not torn down between chapters. - chapterEndedNaturally = true - setState( - _state.value.copy( - status = TtsStatus.Loading, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - requestHandoff(TtsChapterDirection.Next) - } else { - // Playback ends here; a running minutes timer has nothing left - // to stop and would only fire into an idle session. - clearSleepTimer() - setState( - _state.value.copy( - status = TtsStatus.Idle, - atEnd = true, - estimatedRemainingSeconds = 0, - ), - ) - } - } - - override fun onError(utteranceId: Int?) { - // Late errors from a stopped/skipped queue must not fail this one. - if (utteranceId != null && utteranceChunks[utteranceId] == null) return - handoffPending = false - handoffTimeout?.cancel() - handoffTimeout = null - clearSleepTimer() - setState(_state.value.copy(status = TtsStatus.Failed, message = "TTS error")) - active = false - persist(wasPlaying = false, immediate = true) - } - - override fun onRangeStart(utteranceId: Int, start: Int, end: Int) { - val index = utteranceChunks[utteranceId] ?: return - val state = _state.value - // Late callbacks from a paused/skipped/replaced queue are not in - // the map (or no longer match the live chunk); never move the - // highlight for them. - if (!active || index != current || state.currentChunk != index) return - val chunk = chunks.getOrNull(index) ?: return - if (state.blockId != chunk.blockId) return - val base = chunk.startOffset - val consumed = start.coerceIn(0, chunk.text.length) - val remainingChars = (chunkCharSuffix.getOrElse(index) { 0 } - consumed) - .coerceAtLeast(0) - setState( - state.copy( - rangeStart = base + start, - rangeEnd = base + end, - estimatedRemainingSeconds = ttsEstimatedSeconds(remainingChars, speed), - ), - ) - } - } - - init { - engine.listener = listener - publishCapabilities() - if (engine.isReady) onEngineReady() - } -} - -/** - * First chunk at or after the reader's visible block. Chunks are ordered by - * block, so a heading/image without speech is skipped rather than failing. - * [charOffset] only matters when the anchor points inside a spoken block. - */ -internal fun ttsStartIndex( - chunks: List, - blockIndex: Int, - charOffset: Int, -): Int { - if (chunks.isEmpty()) return 0 - if (charOffset > 0) { - chunks.indexOfFirst { chunk -> - chunk.blockId.index == blockIndex && - charOffset >= chunk.startOffset && - charOffset < chunk.endOffset - }.takeIf { it >= 0 }?.let { return it } - } - return chunks.indexOfFirst { it.blockId.index >= blockIndex } - .takeIf { it >= 0 } - ?: chunks.lastIndex -} - -/** A chapter hand-off that never arrives must not hold Loading forever. */ -private const val HandoffTimeoutMs = 30_000L -private const val LOOKAHEAD_CHUNKS = 4 From 70ca42fed644e4369542e0875435820e3cf549e0 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:55:32 +0530 Subject: [PATCH 07/16] Delete feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt --- .../dev/mirutime/feature/tts/Ttsengine.kt | 344 ------------------ 1 file changed, 344 deletions(-) delete mode 100644 feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt deleted file mode 100644 index a2c9aeb..0000000 --- a/feature-tts/src/main/java/dev/mirutime/feature/tts/Ttsengine.kt +++ /dev/null @@ -1,344 +0,0 @@ -package dev.mirutime.feature.tts - -import android.content.Context -import android.os.Handler -import android.os.Looper -import android.os.Bundle -import android.provider.Settings -import android.speech.tts.TextToSpeech -import android.speech.tts.UtteranceProgressListener -import dev.mirutime.core.log.MiruLog -import java.util.Locale - -interface TtsEngineListener { - fun onReady(ok: Boolean) - fun onStart(utteranceId: Int) - fun onDone(utteranceId: Int) - fun onError(utteranceId: Int?) - fun onRangeStart(utteranceId: Int, start: Int, end: Int) - - /** Auxiliary engines finished scanning their voices. */ - fun onVoicesChanged() = Unit -} - -/** Thin seam over the platform engine so controller state is unit-testable. */ -interface TtsEngine { - var listener: TtsEngineListener? - val isReady: Boolean - val voices: List - val engines: List - val currentEngineId: String? - val defaultEngineId: String? - - /** Re-reads the installed engines from the platform (no app restart). */ - fun refreshEngines() - - fun speak(text: String, utteranceId: Int, flush: Boolean = false): Boolean - fun preview(text: String): Boolean - fun stop() - fun setVoice(name: String?): Boolean - fun setRate(rate: Float) - fun setPitch(pitch: Float) - - /** Recreates the platform engine; the listener reports readiness again. */ - fun selectEngine(engineId: String): Boolean - fun restart() - fun shutdown() -} - -class AndroidTtsEngine(context: Context) : TtsEngine { - private val appContext = context.applicationContext - @Volatile - private var tts: TextToSpeech? = null - @Volatile - private var ready = false - private var engineId: String? = null - - // Voices of the installed engines that are not current. TextToSpeech only - // lists the voices of its own engine, so each auxiliary engine is queried - // once and shut down again; the catalog keeps the metadata afterwards. - private val auxiliaryLock = Any() - private val auxiliaryVoices = HashMap>() - private val auxiliaryRequested = HashSet() - private val auxiliaryEngines = HashMap() - - override var listener: TtsEngineListener? = null - - override val isReady: Boolean - get() = ready - - override val defaultEngineId: String? - get() = Settings.Secure.getString( - appContext.contentResolver, - Settings.Secure.TTS_DEFAULT_SYNTH, - )?.takeIf { it.isNotBlank() } - - override val currentEngineId: String? - get() { - val selected = engineId ?: defaultEngineId - val installed = tts?.engines.orEmpty().map { it.name } - return selected?.takeIf { installed.isEmpty() || it in installed } - ?: installed.firstOrNull() - } - - override val voices: List - get() { - val id = currentEngineId - val current = tts?.voices.orEmpty() - .filter { it.locale != null } - .map { voice -> - TtsVoice( - id = voice.name, - name = voice.name, - locale = voice.locale, - quality = voice.quality, - engineId = id, - needsInternet = voice.isNetworkConnectionRequired, - ) - } - val auxiliary = synchronized(auxiliaryLock) { - auxiliaryVoices.mapValues { it.value } - } - return ttsVoiceCatalog(id, current, auxiliary) - } - - override val engines: List - get() { - val default = defaultEngineId - return tts?.engines.orEmpty() - .map { TtsEngineInfo(id = it.name, label = it.label, isDefault = it.name == default) } - .sortedWith(compareBy({ !it.isDefault }, { it.label })) - } - - override fun refreshEngines() { - val platform = tts ?: return - val installed = platform.engines.orEmpty().map { it.name } - // Debug-only evidence: which engines the platform actually exposes to - // this app (package visibility matters on Android 11+). - MiruLog.d( - "tts", - "event=tts_engines count=${installed.size} ids=${installed.joinToString(",")}", - ) - // The selected engine may have been uninstalled while the app was - // running; fall back to the system engine instead of keeping a dead - // package id in settings. - val selected = engineId - if (selected != null && installed.isNotEmpty() && selected !in installed) { - initEngine(null) - return - } - refreshAuxiliaryVoices() - mainHandler.post { listener?.onVoicesChanged() } - } - - private fun refreshAuxiliaryVoices() { - val installed = tts?.engines.orEmpty().map { it.name } - if (installed.isEmpty()) return - val current = currentEngineId - val missing = synchronized(auxiliaryLock) { - installed.filter { it != current && it !in auxiliaryRequested } - } - missing.forEach(::loadAuxiliaryVoices) - var removed = false - synchronized(auxiliaryLock) { - val keep = installed.toSet() - auxiliaryRequested.retainAll(keep) - if (auxiliaryVoices.keys.any { it !in keep }) { - auxiliaryVoices.keys.retainAll(keep) - removed = true - } - val stale = auxiliaryEngines.keys.filter { it !in keep } - stale.forEach { id -> auxiliaryEngines.remove(id)?.shutdown() } - } - if (removed) mainHandler.post { listener?.onVoicesChanged() } - } - - private fun loadAuxiliaryVoices(engine: String) { - synchronized(auxiliaryLock) { - if (!auxiliaryRequested.add(engine)) return - } - // TextToSpeech reports readiness asynchronously, so the callback needs - // a holder instead of a self-reference in the constructor expression. - val holder = arrayOfNulls(1) - val instance = TextToSpeech( - appContext, - { status -> - val auxiliary = holder[0] - val voices = if (status == TextToSpeech.SUCCESS) { - auxiliary?.voices.orEmpty() - .filter { it.locale != null } - .map { voice -> - TtsVoice( - id = voice.name, - name = voice.name, - locale = voice.locale, - quality = voice.quality, - engineId = engine, - needsInternet = voice.isNetworkConnectionRequired, - ) - } - } else { - emptyList() - } - synchronized(auxiliaryLock) { - auxiliaryEngines.remove(engine) - if (voices.isNotEmpty()) { - auxiliaryVoices[engine] = voices - } else { - // Allow a later refresh to retry a failed scan. - auxiliaryRequested.remove(engine) - } - } - MiruLog.d( - "tts", - "event=tts_engine_voices engine=$engine status=$status " + - "count=${voices.size} ids=${voices.joinToString(",") { it.id }}", - ) - auxiliary?.shutdown() - mainHandler.post { listener?.onVoicesChanged() } - }, - engine, - ) - holder[0] = instance - synchronized(auxiliaryLock) { - auxiliaryEngines[engine] = instance - } - } - - // Engine callbacks arrive on binder threads; the controller is main-confined. - private val mainHandler = Handler(Looper.getMainLooper()) - - // Diagnostic: the platform may deliver these on a binder thread, not Main. - private fun logProgressThread(role: String, utteranceId: String?) { - MiruLog.d( - "tts", - "event=tts-thread role=$role thread=${Thread.currentThread().name} " + - "utterance=${utteranceId ?: "-"}", - ) - } - - // Incremented on every init/shutdown: a late onInit from an old engine - // must never mark the current (or a shut-down) engine ready. - @Volatile - private var engineGeneration = 0 - - private val progress = object : UtteranceProgressListener() { - override fun onStart(utteranceId: String?) { - logProgressThread("onStart", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onStart(value) } - } - - override fun onDone(utteranceId: String?) { - logProgressThread("onDone", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onDone(value) } - } - - @Deprecated("Deprecated in Java") - override fun onError(utteranceId: String?) { - logProgressThread("onError", utteranceId) - // Preview ("tts-preview") and foreign ids must not fail the book. - if (!shouldReportPlaybackError(utteranceId)) return - val value = utteranceId?.toIntOrNull() - mainHandler.post { listener?.onError(value) } - } - - override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) { - logProgressThread("onRangeStart", utteranceId) - val value = utteranceId?.toIntOrNull() ?: return - mainHandler.post { listener?.onRangeStart(value, start, end) } - } - } - - init { - initEngine(null) - } - - private fun initEngine(enginePackage: String?) { - val generation = ++engineGeneration - ready = false - tts?.stop() - tts?.shutdown() - engineId = enginePackage - tts = TextToSpeech( - appContext, - { status -> - if (generation == engineGeneration) { - ready = status == TextToSpeech.SUCCESS - if (ready) { - tts?.language = Locale.getDefault() - tts?.setOnUtteranceProgressListener(progress) - refreshAuxiliaryVoices() - } - mainHandler.post { listener?.onReady(ready) } - } - }, - enginePackage, - ) - } - - override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { - val queueMode = if (flush) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD - return tts?.speak(text, queueMode, Bundle(), utteranceId.toString()) == - TextToSpeech.SUCCESS - } - - // QUEUE_FLUSH: a test utterance must be heard now, not after the book queue. - override fun preview(text: String): Boolean = - tts?.speak(text, TextToSpeech.QUEUE_FLUSH, Bundle(), PREVIEW_UTTERANCE) == - TextToSpeech.SUCCESS - - override fun stop() { - tts?.stop() - } - - override fun setVoice(name: String?): Boolean { - val engine = tts ?: return false - val voice = if (name == null) { - engine.defaultVoice ?: engine.voices?.firstOrNull() - } else { - engine.voices?.firstOrNull { it.name == name } - } ?: return false - return engine.setVoice(voice) == TextToSpeech.SUCCESS - } - - override fun setRate(rate: Float) { - tts?.setSpeechRate(rate) - } - - override fun setPitch(pitch: Float) { - tts?.setPitch(pitch) - } - - override fun selectEngine(engineId: String): Boolean { - if (engineId.isBlank()) return false - if (engineId == currentEngineId && ready) return true - initEngine(engineId) - return true - } - - override fun restart() { - initEngine(engineId) - } - - override fun shutdown() { - engineGeneration += 1 - tts?.stop() - tts?.shutdown() - tts = null - ready = false - synchronized(auxiliaryLock) { - auxiliaryEngines.values.forEach { it.shutdown() } - auxiliaryEngines.clear() - } - } - - private companion object { - const val PREVIEW_UTTERANCE = "tts-preview" - } -} - -/** Only a real playback utterance id may fail the active session. */ -internal fun shouldReportPlaybackError(utteranceId: String?): Boolean = - utteranceId?.toIntOrNull() != null From 63dcba3448f36015efebebec99e7f01b81d42a04 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 21:58:45 +0530 Subject: [PATCH 08/16] Add files via upload --- .../dev/mirutime/feature/tts/TtsController.kt | 52 ++++++++++++++----- .../dev/mirutime/feature/tts/TtsEngine.kt | 9 ++-- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt index 98c37f7..b83bcb4 100644 --- a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt +++ b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt @@ -201,6 +201,7 @@ class TtsController( // one. Cleared whenever the queue is paused/skipped/replaced. private val utteranceChunks = java.util.concurrent.ConcurrentHashMap() private var nextUtteranceId = 0 + private var queuedUpTo = -1 private var bookUrl = "" private var chapterIndex = 0 private var voiceId: String? = _settings.value.voiceId @@ -734,20 +735,43 @@ class TtsController( // cursor if speech never starts (engine race, process death). persist(wasPlaying = true, immediate = true, background = true) engine.stop() - for (i in current until chunks.size) { + val end = minOf(current + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + enqueueRange(current, end, flushFirst = true) + } + + private fun enqueueRange(startIndex: Int, endIndex: Int, flushFirst: Boolean): Boolean { + for (i in startIndex..endIndex) { val utteranceId = ++nextUtteranceId utteranceChunks[utteranceId] = i - if (!engine.speak(chunks[i].text, utteranceId)) { - // Chunks already queued before the failure must stop too. - engine.stop() - setState( - _state.value.copy( - status = TtsStatus.Failed, - message = "TTS speak failed", - ), - ) - active = false - return + val flush = flushFirst && i == startIndex + if (!engine.speak(chunks[i].text, utteranceId, flush)) { + utteranceChunks.remove(utteranceId) + if (i == current) { + // Only abort playback if the active chunk itself failed to queue. + engine.stop() + setState( + _state.value.copy( + status = TtsStatus.Failed, + message = "TTS speak failed", + ), + ) + active = false + return false + } + return true + } + queuedUpTo = i + } + return true + } + + private fun topUpQueue(fromIndex: Int) { + if (!active || !ready || chunks.isEmpty()) return + val targetEnd = minOf(fromIndex + LOOKAHEAD_CHUNKS - 1, chunks.lastIndex) + if (queuedUpTo < targetEnd) { + val start = maxOf(fromIndex, queuedUpTo + 1) + if (start <= targetEnd) { + enqueueRange(start, targetEnd, flushFirst = false) } } } @@ -825,6 +849,7 @@ class TtsController( private fun invalidateUtterances() { utteranceChunks.clear() + queuedUpTo = -1 } private fun onEngineReady() { @@ -1007,6 +1032,7 @@ class TtsController( current = index setState(chunkState(index, TtsStatus.Playing)) persist(wasPlaying = true, immediate = true, background = true) + topUpQueue(index) } override fun onDone(utteranceId: Int) { @@ -1136,3 +1162,5 @@ internal fun ttsStartIndex( /** A chapter hand-off that never arrives must not hold Loading forever. */ private const val HandoffTimeoutMs = 30_000L +private const val LOOKAHEAD_CHUNKS = 4 + diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsEngine.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsEngine.kt index 63dbfdc..1301a32 100644 --- a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsEngine.kt +++ b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsEngine.kt @@ -33,7 +33,7 @@ interface TtsEngine { /** Re-reads the installed engines from the platform (no app restart). */ fun refreshEngines() - fun speak(text: String, utteranceId: Int): Boolean + fun speak(text: String, utteranceId: Int, flush: Boolean = false): Boolean fun preview(text: String): Boolean fun stop() fun setVoice(name: String?): Boolean @@ -278,9 +278,11 @@ class AndroidTtsEngine(context: Context) : TtsEngine { ) } - override fun speak(text: String, utteranceId: Int): Boolean = - tts?.speak(text, TextToSpeech.QUEUE_ADD, Bundle(), utteranceId.toString()) == + override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { + val queueMode = if (flush) TextToSpeech.QUEUE_FLUSH else TextToSpeech.QUEUE_ADD + return tts?.speak(text, queueMode, Bundle(), utteranceId.toString()) == TextToSpeech.SUCCESS + } // QUEUE_FLUSH: a test utterance must be heard now, not after the book queue. override fun preview(text: String): Boolean = @@ -340,3 +342,4 @@ class AndroidTtsEngine(context: Context) : TtsEngine { /** Only a real playback utterance id may fail the active session. */ internal fun shouldReportPlaybackError(utteranceId: String?): Boolean = utteranceId?.toIntOrNull() != null + From 4ad10cec8a106bd7122d3f2d028f458466a82db5 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:00:09 +0530 Subject: [PATCH 09/16] Add files via upload --- .../mirutime/feature/tts/TtsControllerTest.kt | 61 ++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt index 7ba22bc..898db6d 100644 --- a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt +++ b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt @@ -57,6 +57,7 @@ class TtsControllerTest { val spoken = mutableListOf() val spokenTexts = mutableListOf() + val flushFlags = mutableListOf() val previews = mutableListOf() var stops = 0 var failSpeak = false @@ -95,9 +96,10 @@ class TtsControllerTest { listener?.onVoicesChanged() } - override fun speak(text: String, utteranceId: Int): Boolean { + override fun speak(text: String, utteranceId: Int, flush: Boolean): Boolean { spoken += utteranceId spokenTexts += text + flushFlags += flush return !failSpeak } @@ -1656,4 +1658,61 @@ private class RecordingSessionStore : TtsSessionStore { override fun clear(immediate: Boolean, background: Boolean) { saved = null } + + @Test + fun `play queues only a bounded lookahead window and tops up on onStart`() = runTest { + val engine = FakeEngine() + val controller = createController(engine) + val doc = ReaderDocument( + bookUrl = "book://1", + chapterUrl = "ch://1", + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId("ch://1", 0), + original = "One. Two. Three. Four. Five. Six.", + ), + ), + ) + + controller.play(doc) + assertEquals(4, engine.spoken.size) + assertEquals(listOf(true, false, false, false), engine.flushFlags) + + engine.listener?.onStart(engine.spoken[1]) + assertEquals(5, engine.spoken.size) + assertEquals("Five.", engine.spokenTexts.last()) + } + + @Test + fun `rapid skipNextChunk fast-forward uses flush on first chunk and stays Playing`() = runTest { + val engine = FakeEngine() + val controller = createController(engine) + val doc = ReaderDocument( + bookUrl = "book://1", + chapterUrl = "ch://1", + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId("ch://1", 0), + original = "Line 1. Line 2. Line 3. Line 4. Line 5. Line 6.", + ), + ), + ) + + controller.play(doc) + engine.spoken.clear() + engine.spokenTexts.clear() + engine.flushFlags.clear() + + controller.skipNextChunk() + controller.skipNextChunk() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(2, controller.state.value.currentChunk) + assertTrue(engine.flushFlags.first()) + assertEquals("Line 3.", engine.spokenTexts.first()) + } } From 7c86560d38e14e37a843718668219f52357e9efe Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:02:13 +0530 Subject: [PATCH 10/16] Add GitHub Actions workflow for building arm64 APK --- .github/workflows/build-arm64.yml. | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/build-arm64.yml. diff --git a/.github/workflows/build-arm64.yml. b/.github/workflows/build-arm64.yml. new file mode 100644 index 0000000..6c9d10c --- /dev/null +++ b/.github/workflows/build-arm64.yml. @@ -0,0 +1,24 @@ +name: Build arm64-v8a Debug APK + +on: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + - name: Run TTS tests & build arm64-v8a APK + run: | + chmod +x gradlew + ./gradlew --no-daemon :feature-tts:testDebugUnitTest :app:assembleDebug + - name: Upload arm64-v8a APK + uses: actions/upload-artifact@v4 + with: + name: mirutime-arm64-v8a-debug + path: app/build/outputs/apk/debug/*arm64-v8a*.apk From cb31afa9d01e33b67272adb968389beae3a694d8 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:06:28 +0530 Subject: [PATCH 11/16] Rename build-arm64.yml. to build-arm64.yml --- .github/workflows/{build-arm64.yml. => build-arm64.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{build-arm64.yml. => build-arm64.yml} (100%) diff --git a/.github/workflows/build-arm64.yml. b/.github/workflows/build-arm64.yml similarity index 100% rename from .github/workflows/build-arm64.yml. rename to .github/workflows/build-arm64.yml From 94f2472cb0e74e35555c5ca55e3cdc166cb069c7 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:29:15 +0530 Subject: [PATCH 12/16] Add files via upload --- .../mirutime/feature/tts/TtsControllerTest.kt | 118 +++++++++--------- 1 file changed, 61 insertions(+), 57 deletions(-) diff --git a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt index 898db6d..8c3840e 100644 --- a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt +++ b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt @@ -1607,6 +1607,66 @@ class TtsControllerTest { assertEquals(document.chapterIndex, stopped?.chapterIndex) } + @Test + fun `play queues only a bounded lookahead window and tops up on onStart`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + val chUrl = "local://book#chapter=1" + val doc = ReaderDocument( + bookUrl = "local://book", + chapterUrl = chUrl, + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId(chUrl, 0), + kind = BlockKind.Paragraph, + original = "One. Two. Three. Four. Five. Six.", + ), + ), + ) + + controller.play(doc, emptyMap()) + assertEquals(4, engine.spoken.size) + assertEquals(listOf(true, false, false, false), engine.flushFlags) + + engine.listener?.onStart(engine.spoken[1]) + assertEquals(5, engine.spoken.size) + assertEquals("Five.", engine.spokenTexts.last()) + } + + @Test + fun `rapid skipNextChunk fast-forward uses flush on first chunk and stays Playing`() = runTest { + val engine = FakeEngine() + val controller = TtsController(engine, this, InMemoryTtsSessionStore()) + val chUrl = "local://book#chapter=1" + val doc = ReaderDocument( + bookUrl = "local://book", + chapterUrl = chUrl, + chapterIndex = 0, + title = "Ch 1", + blocks = listOf( + ReaderBlock( + id = BlockId(chUrl, 0), + kind = BlockKind.Paragraph, + original = "Line 1. Line 2. Line 3. Line 4. Line 5. Line 6.", + ), + ), + ) + + controller.play(doc, emptyMap()) + engine.spoken.clear() + engine.spokenTexts.clear() + engine.flushFlags.clear() + + controller.skipNextChunk() + controller.skipNextChunk() + + assertEquals(TtsStatus.Playing, controller.state.value.status) + assertEquals(2, controller.state.value.currentChunk) + assertTrue(engine.flushFlags.first()) + assertEquals("Line 3.", engine.spokenTexts.first()) + } } private class FakeVoicePreviewer : TtsVoicePreviewer { @@ -1658,61 +1718,5 @@ private class RecordingSessionStore : TtsSessionStore { override fun clear(immediate: Boolean, background: Boolean) { saved = null } - - @Test - fun `play queues only a bounded lookahead window and tops up on onStart`() = runTest { - val engine = FakeEngine() - val controller = createController(engine) - val doc = ReaderDocument( - bookUrl = "book://1", - chapterUrl = "ch://1", - chapterIndex = 0, - title = "Ch 1", - blocks = listOf( - ReaderBlock( - id = BlockId("ch://1", 0), - original = "One. Two. Three. Four. Five. Six.", - ), - ), - ) - - controller.play(doc) - assertEquals(4, engine.spoken.size) - assertEquals(listOf(true, false, false, false), engine.flushFlags) - - engine.listener?.onStart(engine.spoken[1]) - assertEquals(5, engine.spoken.size) - assertEquals("Five.", engine.spokenTexts.last()) - } - - @Test - fun `rapid skipNextChunk fast-forward uses flush on first chunk and stays Playing`() = runTest { - val engine = FakeEngine() - val controller = createController(engine) - val doc = ReaderDocument( - bookUrl = "book://1", - chapterUrl = "ch://1", - chapterIndex = 0, - title = "Ch 1", - blocks = listOf( - ReaderBlock( - id = BlockId("ch://1", 0), - original = "Line 1. Line 2. Line 3. Line 4. Line 5. Line 6.", - ), - ), - ) - - controller.play(doc) - engine.spoken.clear() - engine.spokenTexts.clear() - engine.flushFlags.clear() - - controller.skipNextChunk() - controller.skipNextChunk() - - assertEquals(TtsStatus.Playing, controller.state.value.status) - assertEquals(2, controller.state.value.currentChunk) - assertTrue(engine.flushFlags.first()) - assertEquals("Line 3.", engine.spokenTexts.first()) - } } + From 58424cbfa65a43ef3ffd22a7cafbaa042571f060 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:41:32 +0530 Subject: [PATCH 13/16] Enable ABI splits for arm64-v8a APK build --- .github/workflows/build-arm64.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-arm64.yml b/.github/workflows/build-arm64.yml index 6c9d10c..d3aaf4f 100644 --- a/.github/workflows/build-arm64.yml +++ b/.github/workflows/build-arm64.yml @@ -16,9 +16,10 @@ jobs: - name: Run TTS tests & build arm64-v8a APK run: | chmod +x gradlew - ./gradlew --no-daemon :feature-tts:testDebugUnitTest :app:assembleDebug + ./gradlew --no-daemon -PabiSplits=true :feature-tts:testDebugUnitTest :app:assembleDebug - name: Upload arm64-v8a APK uses: actions/upload-artifact@v4 with: name: mirutime-arm64-v8a-debug path: app/build/outputs/apk/debug/*arm64-v8a*.apk + From d08ed10a33bb969f6101b1adcb604a6ad68add18 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 22:43:31 +0530 Subject: [PATCH 14/16] Add files via upload --- .../java/dev/mirutime/feature/tts/TtsControllerTest.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt index 8c3840e..8d80b10 100644 --- a/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt +++ b/feature-tts/src/test/java/dev/mirutime/feature/tts/TtsControllerTest.kt @@ -1664,8 +1664,11 @@ class TtsControllerTest { assertEquals(TtsStatus.Playing, controller.state.value.status) assertEquals(2, controller.state.value.currentChunk) - assertTrue(engine.flushFlags.first()) - assertEquals("Line 3.", engine.spokenTexts.first()) + assertEquals( + listOf("Line 3.", "Line 4.", "Line 5.", "Line 6."), + engine.spokenTexts.takeLast(4), + ) + assertEquals(listOf(true, false, false, false), engine.flushFlags.takeLast(4)) } } From 8238f53686823551411afb75ba70fdb1b3300f1d Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Thu, 26 Nov 2026 23:38:56 +0530 Subject: [PATCH 15/16] Add files via upload --- .../src/main/java/dev/mirutime/feature/tts/TtsController.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt index b83bcb4..c59123f 100644 --- a/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt +++ b/feature-tts/src/main/java/dev/mirutime/feature/tts/TtsController.kt @@ -316,6 +316,12 @@ class TtsController( language: TtsLanguage = TtsLanguage.from(translations), ) { if (_state.value.status != TtsStatus.Paused) { + val sameChapter = chunks.firstOrNull()?.blockId?.chapterUrl == document.chapterUrl + if (ready && sameChapter && sessionLanguage == language && chunks.isNotEmpty()) { + val target = ttsStartIndex(chunks, blockIndex, charOffset) + speakFrom(target) + return + } playFrom(document, translations, blockIndex, charOffset, language) return } From 2f594d5dcd16409523cddf6919418173b9796e02 Mon Sep 17 00:00:00 2001 From: MrGodFavourite Date: Fri, 27 Nov 2026 08:50:29 +0530 Subject: [PATCH 16/16] Delete .github/workflows/build-arm64.yml --- .github/workflows/build-arm64.yml | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 .github/workflows/build-arm64.yml diff --git a/.github/workflows/build-arm64.yml b/.github/workflows/build-arm64.yml deleted file mode 100644 index d3aaf4f..0000000 --- a/.github/workflows/build-arm64.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Build arm64-v8a Debug APK - -on: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - uses: gradle/actions/setup-gradle@v4 - - name: Run TTS tests & build arm64-v8a APK - run: | - chmod +x gradlew - ./gradlew --no-daemon -PabiSplits=true :feature-tts:testDebugUnitTest :app:assembleDebug - - name: Upload arm64-v8a APK - uses: actions/upload-artifact@v4 - with: - name: mirutime-arm64-v8a-debug - path: app/build/outputs/apk/debug/*arm64-v8a*.apk -