Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Offer real-time translation as a subtitle-menu track

a6521e51e9cd2
diff --git a/app/src/main/java/com/streamvault/app/player/LiveTranslationSession.kt b/app/src/main/java/com/streamvault/app/player/LiveTranslationSession.kt
index 2d176e40..ec699a8f 100644
--- a/app/src/main/java/com/streamvault/app/player/LiveTranslationSession.kt
+++ b/app/src/main/java/com/streamvault/app/player/LiveTranslationSession.kt
@@ -5,10 +5,12 @@ import androidx.media3.common.text.Cue
import com.streamvault.player.LiveAudioPcmBuffer
import com.streamvault.player.PlayerEngine
import java.io.ByteArrayOutputStream
+import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
@@ -33,7 +35,7 @@ private const val MIN_PARTIAL_DISPLAY_MS = 1_500L
// Clear the caption after this much idle time with no new text (TV-caption feel).
private const val SUBTITLE_LINGER_MS = 20_000L
-private data class CaptionTick(
+internal data class CaptionTick(
val text: String,
val isFinal: Boolean,
val chunkId: Long
@@ -55,7 +57,6 @@ class LiveTranslationSession(
// Latest pending caption text waiting to be displayed. Conflated: if several
// updates arrive during a dwell, only the most recent is kept.
private var captionUpdates = newCaptionChannel()
- private var hasVisibleCaption = false
fun start() {
stop()
@@ -151,30 +152,17 @@ class LiveTranslationSession(
)
}
- /**
- * Paces caption changes for readability: every rendered text dwells on screen
- * (finals [MIN_CAPTION_DISPLAY_MS], partials [MIN_PARTIAL_DISPLAY_MS]) before
- * the line may change. The channel is conflated, so after a dwell we always
- * jump straight to the newest text — pacing can never build up a backlog.
- * Clears after [SUBTITLE_LINGER_MS] of no updates.
- */
+ // Pacing/coalescing of caption changes lives in [runCaptionDisplayLoop] so it
+ // can be unit-tested without the audio/network plumbing.
private suspend fun displayLoop() {
- while (scope.isActive) {
- val result = withTimeoutOrNull(SUBTITLE_LINGER_MS) { captionUpdates.receiveCatching() }
- if (result == null) {
- if (hasVisibleCaption) clearCues()
- continue
- }
- val tick = result.getOrNull() ?: break // channel closed -> session ended
- showCaptionTick(tick)
- }
- }
-
- private suspend fun showCaptionTick(tick: CaptionTick) {
- if (tick.text.isBlank()) return
- renderCaption(tick.text)
- hasVisibleCaption = true
- delay(if (tick.isFinal) MIN_CAPTION_DISPLAY_MS else MIN_PARTIAL_DISPLAY_MS)
+ runCaptionDisplayLoop(
+ captionUpdates = captionUpdates,
+ lingerMs = SUBTITLE_LINGER_MS,
+ finalDwellMs = MIN_CAPTION_DISPLAY_MS,
+ partialDwellMs = MIN_PARTIAL_DISPLAY_MS,
+ render = ::renderCaption,
+ clear = ::clearCues
+ )
}
private fun renderCaption(text: String) {
@@ -184,11 +172,52 @@ class LiveTranslationSession(
}
private fun clearCues() {
- hasVisibleCaption = false
playerEngine.clearInjectedSubtitleCues()
}
}
+/**
+ * Paces caption changes for readability: each rendered line dwells on screen
+ * ([finalDwellMs] for finals, [partialDwellMs] for partials) before the line may
+ * change, and [clear] is invoked after [lingerMs] of no new text.
+ *
+ * [captionUpdates] is expected to be a *conflated* channel: while a line is
+ * dwelling, newer updates collapse to the most recent one, so after the dwell we
+ * jump straight to the latest text and pacing can never build up a backlog.
+ *
+ * Intentional tradeoff: because only the newest pending update survives the dwell
+ * window, a finalized phrase can be skipped entirely if a newer (partial) update
+ * arrives before its predecessor's dwell elapses. This is deliberate — we favour
+ * showing the most current state over replaying superseded revisions, accepting
+ * that an occasional finalized phrase is never rendered. See
+ * LiveTranslationCaptionPacingTest for the behavior this guarantees.
+ */
+internal suspend fun runCaptionDisplayLoop(
+ captionUpdates: ReceiveChannel<CaptionTick>,
+ lingerMs: Long,
+ finalDwellMs: Long,
+ partialDwellMs: Long,
+ render: (String) -> Unit,
+ clear: () -> Unit
+) {
+ var hasVisibleCaption = false
+ while (coroutineContext.isActive) {
+ val result = withTimeoutOrNull(lingerMs) { captionUpdates.receiveCatching() }
+ if (result == null) {
+ if (hasVisibleCaption) {
+ clear()
+ hasVisibleCaption = false
+ }
+ continue
+ }
+ val tick = result.getOrNull() ?: break // channel closed -> session ended
+ if (tick.text.isBlank()) continue
+ render(tick.text)
+ hasVisibleCaption = true
+ delay(if (tick.isFinal) finalDwellMs else partialDwellMs)
+ }
+}
+
private data class ConvertedPcmChunk(
val data: ByteArray,
val startMs: Long,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
index 9853ad86..b77820b5 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
@@ -101,7 +101,7 @@ fun PlayerViewModel.onPlayerScreenDisposed() {
}
}
playerEngine.stopLiveTimeshift()
- stopLiveTranslationSession(clearEnabledState = false)
+ stopLiveTranslationSession()
stopActiveStalkerPlaybackFetchDeferral()
clearPlaybackTimers()
}
@@ -153,7 +153,7 @@ fun PlayerViewModel.handOffPlaybackToMultiView() {
viewModelScope.launch { persistPlaybackProgress() }
}
playerEngine.stopLiveTimeshift()
- stopLiveTranslationSession(clearEnabledState = false)
+ stopLiveTranslationSession()
stopActiveStalkerPlaybackFetchDeferral()
livePreviewHandoffManager.clear(playerEngine)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
index 70c6737f..f0b8bc27 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
@@ -8,24 +8,47 @@ import com.streamvault.domain.model.ProviderType
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
-internal fun PlayerViewModel.toggleLiveTranslation() {
+/**
+ * Recomputes whether real-time translation can be offered for the current stream. The Settings >
+ * Playback toggle only makes the feature *available*; it no longer starts translation on its own.
+ * Translation only runs once the user picks "Real-time translation" from the subtitle ("Subs")
+ * menu. If the feature stops being available (preference turned off, or the channel is not a
+ * supported live stream) any running session is stopped.
+ */
+internal suspend fun PlayerViewModel.refreshLiveTranslationAvailability() {
+ val enabled = preferencesRepository.playerLiveTranslationEnabled.first()
+ val provider = if (currentProviderId > 0L) providerRepository.getProvider(currentProviderId) else null
+ val available = shouldEnableLiveTranslationSession(enabled, currentContentType, provider?.type)
+ _liveTranslationAvailable.value = available
+ if (!available && liveTranslationActive.value) {
+ stopLiveTranslationSession()
+ }
+}
+
+/** Invoked when the user selects "Real-time translation" from the subtitle menu. */
+internal fun PlayerViewModel.activateLiveTranslation() {
viewModelScope.launch {
- val nextEnabled = !liveTranslationEnabled.value
- preferencesRepository.setPlayerLiveTranslationEnabled(nextEnabled)
- if (!nextEnabled) {
- stopLiveTranslationSession()
- } else {
- evaluateLiveTranslationSession()
- }
+ _liveTranslationActive.value = true
+ evaluateLiveTranslationSession()
}
}
+/** Invoked when the user picks a regular subtitle track or "Off" from the subtitle menu. */
+internal fun PlayerViewModel.deactivateLiveTranslation() {
+ if (!liveTranslationActive.value && liveTranslationSession == null) return
+ stopLiveTranslationSession()
+}
+
internal suspend fun PlayerViewModel.evaluateLiveTranslationSession() {
- val enabled = preferencesRepository.playerLiveTranslationEnabled.first()
+ if (!liveTranslationActive.value) {
+ stopLiveTranslationSession(clearActiveState = false)
+ return
+ }
if (currentProviderId <= 0L) {
stopLiveTranslationSession()
return
}
+ val enabled = preferencesRepository.playerLiveTranslationEnabled.first()
val provider = providerRepository.getProvider(currentProviderId)
if (!shouldEnableLiveTranslationSession(enabled, currentContentType, provider?.type)) {
stopLiveTranslationSession()
@@ -50,18 +73,18 @@ internal suspend fun PlayerViewModel.evaluateLiveTranslationSession() {
showPlayerNotice(message = message, recoveryType = PlayerRecoveryType.NETWORK)
}
)
- stopLiveTranslationSession(clearEnabledState = false)
+ stopLiveTranslationSession(clearActiveState = false)
liveTranslationSession = session
session.start()
}
-internal fun PlayerViewModel.stopLiveTranslationSession(clearEnabledState: Boolean = true) {
+internal fun PlayerViewModel.stopLiveTranslationSession(clearActiveState: Boolean = true) {
liveTranslationSession?.stop()
liveTranslationSession = null
playerEngine.clearInjectedSubtitleCues()
_liveTranslationDetectedLanguage.value = null
- if (clearEnabledState) {
- _liveTranslationEnabled.value = false
+ if (clearActiveState) {
+ _liveTranslationActive.value = false
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index a0c36075..f9a5fa67 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
@@ -215,6 +215,8 @@ fun PlayerScreen(
val availableAudioTracks by viewModel.availableAudioTracks.collectAsStateWithLifecycle()
val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsStateWithLifecycle()
val availableVideoQualities by viewModel.availableVideoQualities.collectAsStateWithLifecycle()
+ val liveTranslationAvailable by viewModel.liveTranslationAvailable.collectAsStateWithLifecycle()
+ val liveTranslationActive by viewModel.liveTranslationActive.collectAsStateWithLifecycle()
val aspectRatio by viewModel.aspectRatio.collectAsStateWithLifecycle()
val showDiagnostics by viewModel.showDiagnostics.collectAsStateWithLifecycle()
val playerDiagnostics by viewModel.playerDiagnostics.collectAsStateWithLifecycle()
@@ -1121,6 +1123,7 @@ fun PlayerScreen(
displayChannelNumber = displayChannelNumber,
aspectRatioLabel = aspectRatio.modeName,
subtitleTrackCount = availableSubtitleTracks.size,
+ liveTranslationAvailable = liveTranslationAvailable,
audioTrackCount = availableAudioTracks.size,
videoQualityCount = availableVideoQualities.size,
currentRecordingStatus = currentChannelRecording?.status,
@@ -1257,10 +1260,19 @@ fun PlayerScreen(
audioTracks = availableAudioTracks,
subtitleTracks = availableSubtitleTracks,
videoTracks = availableVideoQualities,
+ liveTranslationAvailable = liveTranslationAvailable,
+ liveTranslationActive = liveTranslationActive,
onDismiss = { showTrackSelection = null },
onSelectAudio = viewModel::selectAudioTrack,
onSelectVideo = viewModel::selectVideoQuality,
- onSelectSubtitle = viewModel::selectSubtitleTrack
+ onSelectSubtitle = { trackId ->
+ viewModel.deactivateLiveTranslation()
+ viewModel.selectSubtitleTrack(trackId)
+ },
+ onSelectLiveTranslation = {
+ viewModel.selectSubtitleTrack(null)
+ viewModel.activateLiveTranslation()
+ }
)
ChannelVariantSelectionDialog(
visible = showVariantSelection,
@@ -1534,6 +1546,7 @@ fun PlayerScreen(
isDiagnosticsEnabled = showDiagnostics,
onOpenSplitScreen = { showSplitDialog = true },
subtitleTrackCount = availableSubtitleTracks.size,
+ liveTranslationAvailable = liveTranslationAvailable,
audioTrackCount = availableAudioTracks.size,
videoQualityCount = availableVideoQualities.size,
channelVariantCount = currentChannel?.variants?.size ?: 0,
@@ -1593,6 +1606,7 @@ private fun PlayerControlsOverlayHost(
displayChannelNumber: Int,
aspectRatioLabel: String,
subtitleTrackCount: Int,
+ liveTranslationAvailable: Boolean,
audioTrackCount: Int,
videoQualityCount: Int,
currentRecordingStatus: com.streamvault.domain.model.RecordingStatus?,
@@ -1655,6 +1669,7 @@ private fun PlayerControlsOverlayHost(
duration = duration,
aspectRatioLabel = aspectRatioLabel,
subtitleTrackCount = subtitleTrackCount,
+ liveTranslationAvailable = liveTranslationAvailable,
audioTrackCount = audioTrackCount,
videoQualityCount = videoQualityCount,
currentRecordingStatus = currentRecordingStatus,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index b4d16346..fcbd6bdf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -359,8 +359,10 @@ class PlayerViewModel @Inject constructor(
internal var playbackTimerDefaultsApplied = false
internal var sleepTimerExitEmitted = false
internal var activeStalkerPlaybackProviderId: Long? = null
- internal val _liveTranslationEnabled = MutableStateFlow(false)
- val liveTranslationEnabled: StateFlow<Boolean> = _liveTranslationEnabled.asStateFlow()
+ internal val _liveTranslationAvailable = MutableStateFlow(false)
+ val liveTranslationAvailable: StateFlow<Boolean> = _liveTranslationAvailable.asStateFlow()
+ internal val _liveTranslationActive = MutableStateFlow(false)
+ val liveTranslationActive: StateFlow<Boolean> = _liveTranslationActive.asStateFlow()
internal val _liveTranslationDetectedLanguage = MutableStateFlow<String?>(null)
val liveTranslationDetectedLanguage: StateFlow<String?> = _liveTranslationDetectedLanguage.asStateFlow()
internal var liveTranslationSession: LiveTranslationSession? = null
@@ -546,9 +548,8 @@ class PlayerViewModel @Inject constructor(
.collect { (engine, style) -> engine.setSubtitleStyle(style) }
}
viewModelScope.launch {
- preferencesRepository.playerLiveTranslationEnabled.collect { enabled ->
- _liveTranslationEnabled.value = enabled
- evaluateLiveTranslationSession()
+ preferencesRepository.playerLiveTranslationEnabled.collect {
+ refreshLiveTranslationAvailability()
}
}
viewModelScope.launch {
@@ -996,7 +997,7 @@ class PlayerViewModel @Inject constructor(
internal fun beginPlaybackSession(): Long {
recoveryJob?.cancel()
thumbnailPreloadJob?.cancel()
- stopLiveTranslationSession(clearEnabledState = false)
+ stopLiveTranslationSession()
hasRetriedXtreamAuthRefresh = false
lastRecordedVariantObservationSignature = null
livePlaybackReadyForCurrentSession = false
@@ -1275,7 +1276,7 @@ class PlayerViewModel @Inject constructor(
currentResolvedStreamInfo = preparedStreamInfo
readySideEffectsRequestVersion = requestVersion
playerEngine.prepare(preparedStreamInfo)
- evaluateLiveTranslationSession()
+ refreshLiveTranslationAvailability()
startTokenRenewalMonitoring(preparedStreamInfo.expirationTime)
maybeStartLiveTimeshift(preparedStreamInfo)
return true
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
index 2c940fba..85d52124 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
@@ -93,6 +93,7 @@ fun ChannelInfoOverlay(
isDiagnosticsEnabled: Boolean,
onOpenSplitScreen: () -> Unit = {},
subtitleTrackCount: Int = 0,
+ liveTranslationAvailable: Boolean = false,
audioTrackCount: Int = 0,
videoQualityCount: Int = 0,
channelVariantCount: Int = 0,
@@ -422,7 +423,7 @@ fun ChannelInfoOverlay(
onInteraction = { handleMainActionFocus(null) }
)
}
- if (subtitleTrackCount > 0) {
+ if (subtitleTrackCount > 0 || liveTranslationAvailable) {
item {
QuickActionButton(
icon = stringResource(R.string.player_subs),
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
index 8835b36f..b231b308 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt
@@ -109,6 +109,7 @@ fun PlayerControlsOverlay(
duration: Long,
aspectRatioLabel: String,
subtitleTrackCount: Int,
+ liveTranslationAvailable: Boolean = false,
audioTrackCount: Int,
videoQualityCount: Int,
currentRecordingStatus: RecordingStatus?,
@@ -201,6 +202,7 @@ fun PlayerControlsOverlay(
duration = duration,
aspectRatioLabel = aspectRatioLabel,
subtitleTrackCount = subtitleTrackCount,
+ liveTranslationAvailable = liveTranslationAvailable,
audioTrackCount = audioTrackCount,
videoQualityCount = videoQualityCount,
currentRecordingStatus = currentRecordingStatus,
@@ -533,6 +535,7 @@ private fun PlayerBottomBar(
duration: Long,
aspectRatioLabel: String,
subtitleTrackCount: Int,
+ liveTranslationAvailable: Boolean = false,
audioTrackCount: Int,
videoQualityCount: Int,
currentRecordingStatus: RecordingStatus?,
@@ -629,6 +632,7 @@ private fun PlayerBottomBar(
displayChannelNumber = displayChannelNumber,
aspectRatioLabel = aspectRatioLabel,
subtitleTrackCount = subtitleTrackCount,
+ liveTranslationAvailable = liveTranslationAvailable,
audioTrackCount = audioTrackCount,
videoQualityCount = videoQualityCount,
currentRecordingStatus = currentRecordingStatus,
@@ -725,6 +729,7 @@ private fun PlayerLiveInfo(
displayChannelNumber: Int,
aspectRatioLabel: String,
subtitleTrackCount: Int,
+ liveTranslationAvailable: Boolean,
audioTrackCount: Int,
videoQualityCount: Int,
currentRecordingStatus: RecordingStatus?,
@@ -821,7 +826,7 @@ private fun PlayerLiveInfo(
}
val secondaryActions = buildList {
add(PlayerActionSpec(stringResource(R.string.player_aspect_ratio_label, aspectRatioLabel), onToggleAspectRatio))
- if (subtitleTrackCount > 0) {
+ if (subtitleTrackCount > 0 || liveTranslationAvailable) {
add(PlayerActionSpec(stringResource(R.string.player_subs), onOpenSubtitleTracks))
}
if (audioTrackCount > 0) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
index 804ff58e..8ce7f643 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
@@ -239,10 +239,13 @@ fun PlayerTrackSelectionDialog(
audioTracks: List<PlayerTrack>,
subtitleTracks: List<PlayerTrack>,
videoTracks: List<PlayerTrack>,
+ liveTranslationAvailable: Boolean = false,
+ liveTranslationActive: Boolean = false,
onDismiss: () -> Unit,
onSelectAudio: (String) -> Unit,
onSelectVideo: (String) -> Unit,
- onSelectSubtitle: (String?) -> Unit
+ onSelectSubtitle: (String?) -> Unit,
+ onSelectLiveTranslation: () -> Unit = {}
) {
if (trackType == null) return
@@ -309,7 +312,7 @@ fun PlayerTrackSelectionDialog(
item {
TrackSelectionItem(
name = stringResource(R.string.player_track_off),
- isSelected = tracks.none { it.isSelected },
+ isSelected = tracks.none { it.isSelected } && !liveTranslationActive,
onClick = {
onSelectSubtitle(null)
onDismiss()
@@ -322,7 +325,7 @@ fun PlayerTrackSelectionDialog(
items(tracks, key = { it.id }) { track ->
TrackSelectionItem(
name = track.name,
- isSelected = track.isSelected,
+ isSelected = track.isSelected && !(trackType == TrackType.TEXT && liveTranslationActive),
onClick = {
when (trackType) {
TrackType.AUDIO -> onSelectAudio(track.id)
@@ -338,6 +341,19 @@ fun PlayerTrackSelectionDialog(
}
)
}
+
+ if (trackType == TrackType.TEXT && liveTranslationAvailable) {
+ item {
+ TrackSelectionItem(
+ name = stringResource(R.string.player_track_live_translation),
+ isSelected = liveTranslationActive,
+ onClick = {
+ onSelectLiveTranslation()
+ onDismiss()
+ }
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 1f1617b1..21a00cd4 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1110,6 +1110,7 @@
<string name="player_track_audio">Select Audio Track</string>
<string name="player_track_subs">Select Subtitles</string>
<string name="player_track_off">Off</string>
+ <string name="player_track_live_translation">Real-time translation</string>
<string name="player_video_quality">Video Quality</string>
<string name="player_stream_format">Stream Format</string>
<string name="player_channel_variants">Channel Variants</string>
diff --git a/app/src/test/java/com/streamvault/app/player/LiveTranslationCaptionPacingTest.kt b/app/src/test/java/com/streamvault/app/player/LiveTranslationCaptionPacingTest.kt
new file mode 100644
index 00000000..381515ee
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/player/LiveTranslationCaptionPacingTest.kt
@@ -0,0 +1,151 @@
+package com.streamvault.app.player
+
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+/**
+ * Behavior tests for [runCaptionDisplayLoop], the caption pacing/coalescing logic
+ * extracted from [LiveTranslationSession]. These run on virtual time so the dwell
+ * windows are exercised deterministically.
+ */
+class LiveTranslationCaptionPacingTest {
+
+ private val lingerMs = 20_000L
+ private val finalDwellMs = 2_200L
+ private val partialDwellMs = 1_500L
+
+ @Test
+ fun rendersEachCaptionAndHoldsItForItsDwellWindow() = runTest {
+ val rendered = mutableListOf<String>()
+ val channel = Channel<CaptionTick>(Channel.CONFLATED)
+
+ channel.trySend(CaptionTick("Hello", isFinal = false, chunkId = 1))
+ val job = launch {
+ runCaptionDisplayLoop(
+ captionUpdates = channel,
+ lingerMs = lingerMs,
+ finalDwellMs = finalDwellMs,
+ partialDwellMs = partialDwellMs,
+ render = { rendered += it },
+ clear = {}
+ )
+ }
+
+ // First partial renders immediately, then dwells for partialDwellMs.
+ runCurrent()
+ assertThat(rendered).containsExactly("Hello")
+
+ // A second caption sent before the dwell elapses must not render yet.
+ channel.trySend(CaptionTick("Hello there", isFinal = true, chunkId = 2))
+ advanceTimeBy(partialDwellMs - 1)
+ runCurrent()
+ assertThat(rendered).containsExactly("Hello")
+
+ // Once the dwell elapses the newer caption is shown, in order.
+ advanceTimeBy(1)
+ runCurrent()
+ assertThat(rendered).containsExactly("Hello", "Hello there").inOrder()
+
+ job.cancel()
+ }
+
+ @Test
+ fun finalizedPhraseIsSkippedWhenANewerPartialArrivesDuringTheDwell() = runTest {
+ // Documents the intentional tradeoff: the conflated channel only keeps the
+ // newest pending caption, so a finalized phrase can be dropped if a newer
+ // partial supersedes it before the previous line's dwell elapses.
+ val rendered = mutableListOf<String>()
+ val channel = Channel<CaptionTick>(Channel.CONFLATED)
+
+ channel.trySend(CaptionTick("Bonjour", isFinal = false, chunkId = 1))
+ val job = launch {
+ runCaptionDisplayLoop(
+ captionUpdates = channel,
+ lingerMs = lingerMs,
+ finalDwellMs = finalDwellMs,
+ partialDwellMs = partialDwellMs,
+ render = { rendered += it },
+ clear = {}
+ )
+ }
+ runCurrent()
+ assertThat(rendered).containsExactly("Bonjour")
+
+ // While "Bonjour" is dwelling, a finalized phrase arrives and is then
+ // immediately superseded by a newer partial. Conflation keeps only the last.
+ channel.trySend(CaptionTick("Bonjour le monde.", isFinal = true, chunkId = 2))
+ channel.trySend(CaptionTick("Bonjour le monde, comment", isFinal = false, chunkId = 3))
+
+ advanceTimeBy(partialDwellMs)
+ runCurrent()
+
+ // The finalized "Bonjour le monde." is never rendered; we jump to the latest.
+ assertThat(rendered).containsExactly("Bonjour", "Bonjour le monde, comment").inOrder()
+ assertThat(rendered).doesNotContain("Bonjour le monde.")
+
+ job.cancel()
+ }
+
+ @Test
+ fun clearsCaptionAfterLingerTimeoutWithNoNewText() = runTest {
+ val rendered = mutableListOf<String>()
+ var clears = 0
+ val channel = Channel<CaptionTick>(Channel.CONFLATED)
+
+ channel.trySend(CaptionTick("Final line.", isFinal = true, chunkId = 1))
+ val job = launch {
+ runCaptionDisplayLoop(
+ captionUpdates = channel,
+ lingerMs = lingerMs,
+ finalDwellMs = finalDwellMs,
+ partialDwellMs = partialDwellMs,
+ render = { rendered += it },
+ clear = { clears++ }
+ )
+ }
+ runCurrent()
+ assertThat(rendered).containsExactly("Final line.")
+
+ // No further updates: after the dwell and a full linger window with nothing
+ // received, the caption is cleared exactly once.
+ advanceTimeBy(finalDwellMs + lingerMs)
+ runCurrent()
+ assertThat(clears).isEqualTo(1)
+
+ // Idle thereafter must not clear again (nothing visible to clear).
+ advanceTimeBy(lingerMs * 2)
+ runCurrent()
+ assertThat(clears).isEqualTo(1)
+
+ job.cancel()
+ }
+
+ @Test
+ fun stopsWhenChannelIsClosed() = runTest {
+ val rendered = mutableListOf<String>()
+ val channel = Channel<CaptionTick>(Channel.CONFLATED)
+
+ val job = launch {
+ runCaptionDisplayLoop(
+ captionUpdates = channel,
+ lingerMs = lingerMs,
+ finalDwellMs = finalDwellMs,
+ partialDwellMs = partialDwellMs,
+ render = { rendered += it },
+ clear = {}
+ )
+ }
+
+ channel.close()
+ advanceUntilIdle()
+
+ assertThat(job.isActive).isFalse()
+ assertThat(rendered).isEmpty()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/player/LiveTranslationClientTest.kt b/app/src/test/java/com/streamvault/app/player/LiveTranslationClientTest.kt
index cf148cbe..20b96c39 100644
--- a/app/src/test/java/com/streamvault/app/player/LiveTranslationClientTest.kt
+++ b/app/src/test/java/com/streamvault/app/player/LiveTranslationClientTest.kt
@@ -1,11 +1,13 @@
package com.streamvault.app.player
-import kotlin.test.Test
-import kotlin.test.assertEquals
-import kotlin.test.assertFalse
-import kotlin.test.assertNull
-import kotlin.test.assertTrue
-
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+// parseTranslationUpdate relies on org.json, which is only a throwing stub in
+// plain JVM unit tests; Robolectric supplies a real implementation.
+@RunWith(RobolectricTestRunner::class)
class LiveTranslationClientTest {
@Test
@@ -22,10 +24,10 @@ class LiveTranslationClientTest {
val update = parseTranslationUpdate(payload)
- assertEquals(7L, update.chunkId)
- assertTrue(update.isFinal)
- assertEquals("hello world", update.text)
- assertEquals("es", update.sourceLanguage)
+ assertThat(update.chunkId).isEqualTo(7L)
+ assertThat(update.isFinal).isTrue()
+ assertThat(update.text).isEqualTo("hello world")
+ assertThat(update.sourceLanguage).isEqualTo("es")
}
@Test
@@ -41,9 +43,9 @@ class LiveTranslationClientTest {
val update = parseTranslationUpdate(payload)
- assertEquals(8L, update.chunkId)
- assertFalse(update.isFinal)
- assertEquals("", update.text)
- assertNull(update.sourceLanguage)
+ assertThat(update.chunkId).isEqualTo(8L)
+ assertThat(update.isFinal).isFalse()
+ assertThat(update.text).isEqualTo("")
+ assertThat(update.sourceLanguage).isNull()
}
}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActionsTest.kt
index cf307088..36769007 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActionsTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActionsTest.kt
@@ -1,53 +1,52 @@
package com.streamvault.app.ui.screens.player
+import com.google.common.truth.Truth.assertThat
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ProviderType
-import kotlin.test.Test
-import kotlin.test.assertFalse
-import kotlin.test.assertTrue
+import org.junit.Test
class PlayerLiveTranslationActionsTest {
@Test
fun shouldEnableLiveTranslationSession_requiresEnabledSupportedProviderAndLiveContent() {
- assertTrue(
+ assertThat(
shouldEnableLiveTranslationSession(
enabledPreference = true,
contentType = ContentType.LIVE,
providerType = ProviderType.XTREAM_CODES
)
- )
+ ).isTrue()
- assertFalse(
+ assertThat(
shouldEnableLiveTranslationSession(
enabledPreference = false,
contentType = ContentType.LIVE,
providerType = ProviderType.XTREAM_CODES
)
- )
+ ).isFalse()
- assertFalse(
+ assertThat(
shouldEnableLiveTranslationSession(
enabledPreference = true,
contentType = ContentType.MOVIE,
providerType = ProviderType.XTREAM_CODES
)
- )
+ ).isFalse()
- assertFalse(
+ assertThat(
shouldEnableLiveTranslationSession(
enabledPreference = true,
contentType = ContentType.LIVE,
providerType = ProviderType.STALKER_PORTAL
)
- )
+ ).isFalse()
- assertTrue(
+ assertThat(
shouldEnableLiveTranslationSession(
enabledPreference = true,
contentType = ContentType.LIVE,
providerType = ProviderType.M3U
)
- )
+ ).isTrue()
}
}
diff --git a/docs/TRANSLATION_SERVICE_OPERATIONS.md b/docs/TRANSLATION_SERVICE_OPERATIONS.md
index 9d373d1c..a3896097 100644
--- a/docs/TRANSLATION_SERVICE_OPERATIONS.md
+++ b/docs/TRANSLATION_SERVICE_OPERATIONS.md
@@ -11,15 +11,17 @@ model, tuning), see [LOCAL_LIVE_TRANSLATION.md](LOCAL_LIVE_TRANSLATION.md).
## Start
+Run from the repository root:
+
```bash
-/Users/a/Desktop/iptv-ui/tools/live-translation-service/run-native.sh
+./tools/live-translation-service/run-native.sh
```
Runs in the foreground on port **8765** (Ctrl-C to stop). To keep it running
after the terminal closes, start it in the background with logging:
```bash
-nohup /Users/a/Desktop/iptv-ui/tools/live-translation-service/run-native.sh \
+nohup ./tools/live-translation-service/run-native.sh \
>> ~/Library/Logs/live-translation.log 2>&1 &
```
@@ -66,9 +68,11 @@ Sessions are in-memory only; stopping mid-playback is safe. The app shows
## Restart (e.g. after changing settings)
+From the repository root:
+
```bash
kill $(lsof -ti :8765)
-nohup /Users/a/Desktop/iptv-ui/tools/live-translation-service/run-native.sh \
+nohup ./tools/live-translation-service/run-native.sh \
>> ~/Library/Logs/live-translation.log 2>&1 &
sleep 5 && curl -s http://localhost:8765/health
```
@@ -76,11 +80,12 @@ sleep 5 && curl -s http://localhost:8765/health
## After a reboot
The service does **not** start automatically — you must rerun the start
-command. A LaunchAgent can't do it: macOS privacy protection (TCC) blocks
-launchd background processes from reading anything under `~/Desktop`, where
-this repo lives ("Operation not permitted"). If auto-start ever matters,
-either move the repo out of `~/Desktop` or grant `/bin/zsh` Full Disk Access
-in System Settings → Privacy & Security.
+command. A LaunchAgent can't reliably do it if the repo is checked out under a
+TCC-protected location such as `~/Desktop`, `~/Documents`, or `~/Downloads`:
+macOS privacy protection blocks launchd background processes from reading those
+directories ("Operation not permitted"). If auto-start matters, check the repo
+out somewhere unprotected (e.g. `~/src`) or grant `/bin/zsh` Full Disk Access in
+System Settings → Privacy & Security.
## Endpoints the app uses
diff --git a/tools/live-translation-service/.gitignore b/tools/live-translation-service/.gitignore
index bd7a8363..aa55f563 100644
--- a/tools/live-translation-service/.gitignore
+++ b/tools/live-translation-service/.gitignore
@@ -2,3 +2,4 @@
.venv/
__pycache__/
*.pyc
+*.log