Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package xyz.libravault.core.cloudtts

import android.media.AudioAttributes
import android.media.MediaDataSource
import android.media.MediaPlayer
import android.util.Log
import javax.inject.Inject

private const val TAG = "CloudPlayback"

/**
* Plays a vendor-encoded audio buffer (mp3, typically) received from
* [CloudTtsProvider.synthesize]. A real player needs Android runtime
* (Robolectric or a device), so [CloudTtsEngine] depends on this interface
* rather than [MediaPlayerCloudPlayback] directly — tests substitute a fake
* without ever touching `android.media.*`, the same interface-plus-fake
* shape this codebase already uses for `HardwareKeyWrap`/`TtsEngine` itself.
*/
interface CloudPlayback {
fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit)
fun pause()
fun resume()
fun stop()
}

/**
* Real implementation, wrapping [MediaPlayer]. Unlike `core:tts`'s
* `PocketPlayback` (raw PCM float samples over `AudioTrack`), cloud vendors
* return already-encoded audio, so this wraps [MediaPlayer] — its own
* decoder handles whatever format each vendor sends back.
*
* Feeds the byte array via [MediaDataSource] rather than writing a temp
* file: no cache-file cleanup to get wrong, and the audio (synthesized
* speech from the user's own reading material) never touches disk.
*
* All methods `synchronized(lock)`: [MediaPlayer] "objects are not
* thread-safe" per its own docs, and this class is genuinely called from
* two different threads — `play()` from [CloudTtsEngine]'s background
* `scope`, `pause()`/`resume()`/`stop()` directly from whatever thread the
* [xyz.libravault.core.tts.TtsEngine] caller is on (typically Main, same as
* `AndroidTtsEngine`/`PocketTtsEngine`) — a race here could pause/resume a
* stale reference or call `release()` on a player still mid-`start()` on
* the other thread (found in review).
*/
class MediaPlayerCloudPlayback @Inject constructor() : CloudPlayback {
private val lock = Any()
private var mediaPlayer: MediaPlayer? = null

override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) = synchronized(lock) {
stopLocked()
val player = MediaPlayer()
try {
player.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build(),
)
player.setDataSource(ByteArrayMediaDataSource(audioBytes))
player.setOnCompletionListener { onCompletion() }
player.setOnErrorListener { _, what, extra ->
Log.e(TAG, "MediaPlayer error: what=$what extra=$extra")
onError("MediaPlayer error $what/$extra")
true
}
// Synchronous prepare(), not prepareAsync(): this always runs
// from CloudTtsEngine's background scope, never the caller's
// thread, and the byte array is already fully in memory (no
// network/disk I/O left for prepare() to block on).
player.prepare()
player.start()
mediaPlayer = player
} catch (e: Exception) {
Log.e(TAG, "Failed to start playback: ${e.message}", e)
player.release()
onError(e.message ?: "Failed to start playback")
}
}

override fun pause() {
synchronized(lock) { mediaPlayer?.pause() }
}

override fun resume() {
synchronized(lock) { mediaPlayer?.start() }
}

override fun stop() {
synchronized(lock) { stopLocked() }
}

private fun stopLocked() {
mediaPlayer?.apply {
runCatching { stop() }
release()
}
mediaPlayer = null
}
}

private class ByteArrayMediaDataSource(private val data: ByteArray) : MediaDataSource() {
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
if (position >= data.size) return -1
val length = minOf(size.toLong(), data.size - position).toInt()
System.arraycopy(data, position.toInt(), buffer, offset, length)
return length
}

override fun getSize(): Long = data.size.toLong()

override fun close() = Unit
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
package xyz.libravault.core.cloudtts

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
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.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import xyz.libravault.core.tts.TtsAudioFocusManager
import xyz.libravault.core.tts.TtsEngine
import xyz.libravault.core.tts.TtsEngineType
import xyz.libravault.core.tts.TtsPreferences
import xyz.libravault.core.tts.TtsState
import xyz.libravault.core.tts.TtsStatus
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton

// Chunking mirrors AndroidTtsEngine's own MAX_UTTERANCE_CHARS — PRD §3
// ("no new segmentation logic needed"). Not shared as a public constant
// between the two engines since core:cloudtts intentionally doesn't depend
// on AndroidTtsEngine directly; this is a reasonable, independently
// documented value for the same reason (avoid one HTTP call per whole
// chapter, keep individual vendor requests small).
private const val MAX_CHUNK_CHARS = 3900

/**
* `TtsEngineType.CLOUD`'s [TtsEngine]. Bound into `core:tts`'s
* [xyz.libravault.core.tts.TtsEngineFactory] multibinding map from this
* module's own (unflavored) Hilt module — see [TtsEngineFactory][
* xyz.libravault.core.tts.TtsEngineFactory]'s class doc for why.
*
* [CloudTtsGate.observeCanUseCloudTts] is re-checked before every chunk in
* [speak], not just once at the top — a subscription lapsing or consent
* being revoked mid-session stops new cloud calls immediately. Provider,
* voice, and credentials are resolved once per [speak] call, not re-read
* per chunk (they can't change mid-utterance — no setter is exposed for
* them — so re-reading per chunk was only redundant DataStore/Keystore
* work, caught in review).
*
* On gate failure, missing provider/voice selection, missing credentials,
* or any HTTP failure, delegates the rest of the utterance to the on-device
* fallback engine ([TtsEngineType.ANDROID], resolved from the SAME
* multibinding map this class is itself bound into — Provider-based
* multibinding maps can reference their own other entries without a cycle,
* so no separate DI qualifier is needed) rather than retrying cloud or
* silently stalling (PRD §3).
*
* The whole per-chunk loop runs as ONE coroutine (not a chain of
* `scope.launch{}` calls from playback callbacks) specifically so
* [speakJob]`.cancel()` (from [stop]) reliably interrupts whatever chunk is
* currently fetching or playing — an earlier version launched each
* subsequent chunk from `onCompletion`/`onError` outside [speakJob]'s
* tracking, so `stop()` could not prevent an already-in-flight later chunk
* from starting to play (found in review). [CloudPlayback.play]'s
* callback-based API is bridged into a single suspension point via
* [suspendCancellableCoroutine] so playback itself is a real, cancellable
* part of that one coroutine.
*/
@Singleton
class CloudTtsEngine @Inject constructor(
private val gate: CloudTtsGate,
private val cloudTtsProvider: CloudTtsProvider,
private val apiKeyStore: CloudApiKeyStore,
private val preferences: TtsPreferences,
private val engines: Map<TtsEngineType, @JvmSuppressWildcards Provider<TtsEngine>>,
private val scope: CoroutineScope,
private val audioFocusManager: TtsAudioFocusManager,
private val playback: CloudPlayback,
) : TtsEngine {

private val _state = MutableStateFlow(TtsState())
override val state: StateFlow<TtsState> = _state.asStateFlow()

private val _completionEvent = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
override val completionEvent: SharedFlow<Unit> = _completionEvent.asSharedFlow()

private val _stopEvent = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
override val stopEvent: SharedFlow<Unit> = _stopEvent.asSharedFlow()

private val fallbackEngine: TtsEngine by lazy {
engines[TtsEngineType.ANDROID]?.get()
?: error("No on-device fallback (TtsEngineType.ANDROID) bound — cannot safely run CloudTtsEngine without one")
}

private var isFallenBack = false
private var fallbackForwardingJob: Job? = null
private var speakJob: Job? = null

/** Why the most recent fallback happened, if any — e.g. "cloud voices
* gate is closed", "no saved credentials for OPENAI". Settings UI
* (follow-up PR) can surface this; not part of [TtsState] since it's
* diagnostic, not itself playback status. */
var lastFallbackReason: String? = null
private set

override fun initialize() {
// No network call here — nothing to fetch a voice catalog from
// without a selected provider/credentials, and the PRD's five voice
// presets are fixed per vendor (Settings UI follow-up owns
// presenting them, not this engine).
_state.value = _state.value.copy(status = TtsStatus.IDLE, error = null)
}

override fun speak(text: String) {
speakJob?.cancel()
fallbackForwardingJob?.cancel()
isFallenBack = false
audioFocusManager.requestFocus { stop() }
_state.value = _state.value.copy(status = TtsStatus.PLAYING, error = null)

speakJob = scope.launch {
val providerId = preferences.selectedCloudProviderFlow.first()
?.let { runCatching { CloudProviderId.valueOf(it) }.getOrNull() }
val voiceId = preferences.selectedVoiceFlow.first()
if (providerId == null || voiceId == null) {
fallBackTo(text, "no cloud voice selected")
return@launch
}
val credentials = apiKeyStore.loadCredentials(providerId)
if (credentials == null) {
fallBackTo(text, "no saved credentials for $providerId")
return@launch
}

val chunks = splitIntoChunks(text)
for (index in chunks.indices) {
if (!gate.observeCanUseCloudTts().first()) {
fallBackTo(chunks, index, "cloud voices gate is closed (subscription lapsed or consent revoked)")
return@launch
}

// CancellationException propagates straight through (not
// caught here, and the vendor adapters no longer swallow it
// either — see runCatchingCancellable) so stop() cancelling
// this coroutine ends the loop instead of looking like an
// ordinary synthesis failure that should fall back.
val audioBytes = cloudTtsProvider.synthesize(providerId, chunks[index], voiceId, credentials)
.getOrElse {
fallBackTo(chunks, index, "cloud synthesis failed: ${it.message}")
return@launch
}

val playError = awaitPlayback(audioBytes)
if (playError != null) {
fallBackTo(chunks, index, "playback error: $playError")
return@launch
}
}

_state.value = _state.value.copy(status = TtsStatus.IDLE)
_completionEvent.tryEmit(Unit)
}
}

/** Bridges [CloudPlayback]'s callback API into one suspension point, so
* playback is a real part of [speakJob]'s single coroutine — cancelling
* it (via [stop]) reliably stops in-flight playback rather than racing
* an untracked callback. Returns the error message, or null on success. */
private suspend fun awaitPlayback(audioBytes: ByteArray): String? =
suspendCancellableCoroutine { continuation ->
playback.play(
audioBytes,
onCompletion = { if (continuation.isActive) continuation.resumeWith(Result.success(null)) },
onError = { message -> if (continuation.isActive) continuation.resumeWith(Result.success(message)) },
)
continuation.invokeOnCancellation { playback.stop() }
}

/** Delegates chunks `[index, chunks.size)` to the on-device engine and
* forwards its state/events into this engine's own flows for as long as
* fallback stays active, so a caller observing THIS engine's flows sees
* accurate status rather than freezing at the moment of fallback.
*
* Deliberately no `android.util.Log` call here (unlike `AndroidTtsEngine`/
* `PocketTtsEngine`): [reason] is instead surfaced via [lastFallbackReason]
* — real diagnostic value (visible to QA/UI, not just logcat) without
* `core:cloudtts` needing Robolectric just to unit-test this one path
* (`android.util.Log` throws "not mocked" in a plain JVM test — same
* reasoning as [RealCloudApiKeyStore] using `java.util.Base64`, not
* `android.util.Base64`). */
/** Convenience for a fallback decided before any chunking happened
* (e.g. no provider/voice selected) — the whole [text] goes to the
* fallback engine untouched. */
private fun fallBackTo(text: String, reason: String) = fallBackTo(listOf(text), 0, reason)

private fun fallBackTo(chunks: List<String>, index: Int, reason: String) {
lastFallbackReason = reason
isFallenBack = true
val remainingText = chunks.subList(index, chunks.size).joinToString(" ")

fallbackForwardingJob?.cancel()
fallbackForwardingJob = scope.launch {
launch { fallbackEngine.state.collect { _state.value = it } }
launch { fallbackEngine.completionEvent.collect { _completionEvent.tryEmit(Unit) } }
launch { fallbackEngine.stopEvent.collect { _stopEvent.tryEmit(Unit) } }
}
if (fallbackEngine.state.value.status == TtsStatus.UNINITIALIZED) {
fallbackEngine.initialize()
}
fallbackEngine.speak(remainingText)
}

override fun pause() {
if (isFallenBack) {
fallbackEngine.pause()
} else {
playback.pause()
_state.value = _state.value.copy(status = TtsStatus.PAUSED)
}
}

override fun resume() {
if (isFallenBack) {
fallbackEngine.resume()
} else {
playback.resume()
_state.value = _state.value.copy(status = TtsStatus.PLAYING)
}
}

override fun stop() {
speakJob?.cancel()
fallbackForwardingJob?.cancel()
if (isFallenBack) {
fallbackEngine.stop()
isFallenBack = false
}
playback.stop()
audioFocusManager.abandonFocus()
_state.value = _state.value.copy(status = TtsStatus.IDLE)
_stopEvent.tryEmit(Unit)
}

override fun setVoice(voiceId: String) {
_state.value = _state.value.copy(selectedVoiceId = voiceId)
if (isFallenBack) fallbackEngine.setVoice(voiceId)
}

override fun setSpeechRate(rate: Float) {
_state.value = _state.value.copy(speechRate = rate)
if (isFallenBack) fallbackEngine.setSpeechRate(rate)
}

override fun shutdown() {
speakJob?.cancel()
fallbackForwardingJob?.cancel()
playback.stop()
audioFocusManager.abandonFocus()
_state.value = TtsState()
}

private fun splitIntoChunks(text: String): List<String> {
if (text.length <= MAX_CHUNK_CHARS) return listOf(text)

val chunks = mutableListOf<String>()
var remaining = text.trim()
while (remaining.isNotEmpty()) {
if (remaining.length <= MAX_CHUNK_CHARS) {
chunks += remaining
break
}
val window = remaining.substring(0, MAX_CHUNK_CHARS)
val cut = window.indexOfLast { it == '.' || it == '!' || it == '?' }
val splitAt = if (cut > 0) cut + 1 else MAX_CHUNK_CHARS
chunks += remaining.substring(0, splitAt).trim()
remaining = remaining.substring(splitAt).trim()
}
return chunks
}
}
Loading
Loading