package tv.tivilux.nativeplayer.ui.components import android.view.LayoutInflater import android.view.ViewGroup import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.media3.common.MediaItem import androidx.media3.common.PlaybackException import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.DefaultLoadControl import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.DefaultRenderersFactory import androidx.media3.exoplayer.source.DefaultMediaSourceFactory import androidx.media3.datasource.DefaultHttpDataSource import androidx.media3.ui.AspectRatioFrameLayout import androidx.media3.ui.PlayerView import coil.compose.AsyncImage import tv.tivilux.nativeplayer.R import tv.tivilux.nativeplayer.BuildConfig import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.ui.theme.LuxBg import tv.tivilux.nativeplayer.ui.theme.LuxGold import tv.tivilux.nativeplayer.ui.theme.LuxLine import tv.tivilux.nativeplayer.ui.theme.LuxMuted import tv.tivilux.nativeplayer.ui.theme.LuxPanel import tv.tivilux.nativeplayer.ui.theme.LuxPanel2 import tv.tivilux.nativeplayer.ui.theme.LuxText /** Short reveal; animation state is read only by the graphics layer, never the content tree. */ @Composable fun Modifier.panelReveal(): Modifier { var revealed by remember { mutableStateOf(false) } val opacity = androidx.compose.animation.core.animateFloatAsState( targetValue = if (revealed) 1f else 0f, animationSpec = androidx.compose.animation.core.tween(120), label = "panel-reveal", ) LaunchedEffect(Unit) { revealed = true } return this.graphicsLayer { alpha = opacity.value } } @Composable fun LuxBackground(content: @Composable () -> Unit) { Box( modifier = Modifier .fillMaxSize() .background( Brush.radialGradient( colors = listOf(Color(0xFF202B35), Color(0xFF111820), LuxBg), radius = 1650f, ) ) ) { content() } } @Composable fun LuxButton( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, primary: Boolean = false, enabled: Boolean = true, focusRequester: FocusRequester? = null, illuminateOnFocus: Boolean = false, ) { var focused by remember { mutableStateOf(false) } val illuminated = enabled && focused && illuminateOnFocus val scale = if (illuminated) 1.025f else if (focused) 1.008f else 1f val bg = when { illuminated -> Color(0xFFFFE28A) primary -> LuxGold focused -> Color(0xFF2A303A) else -> Color(0x141FFFFFF) } val fg = if (primary || illuminated) Color(0xFF191714) else LuxText val shape = RoundedCornerShape(14.dp) Box( modifier = modifier .scale(scale) .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier) .onFocusChanged { focused = it.isFocused } .clip(shape) .background(bg) .then(if (focused && !primary) Modifier.background( Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.10f), Color.Transparent)) ) else Modifier) .border(if (illuminated) 2.dp else 1.dp, if (illuminated) Color.White else if (focused) LuxGold else LuxLine, shape) .clickable(enabled = enabled, onClick = onClick) .heightIn(min = 52.dp) .padding(horizontal = 20.dp, vertical = 12.dp), contentAlignment = Alignment.Center, ) { Text( text, color = if (enabled) fg else LuxMuted, fontWeight = if (illuminated) FontWeight.Bold else FontWeight.SemiBold, fontSize = 14.sp, lineHeight = 22.sp, maxLines = 1, softWrap = false, ) } } @Composable fun LuxNavItem( text: String, active: Boolean, requestFocus: Boolean = false, modifier: Modifier = Modifier, focusRequester: FocusRequester? = null, onClick: () -> Unit, ) { var focused by remember { mutableStateOf(false) } val internalFocusRequester = remember { FocusRequester() } val requester = focusRequester ?: internalFocusRequester LaunchedEffect(requestFocus) { if (requestFocus) runCatching { requester.requestFocus() } } Row( modifier = modifier .fillMaxWidth() .focusRequester(requester) .clip(RoundedCornerShape(12.dp)) .background(if (active || focused) Color(0x1FE8C38B) else Color.Transparent) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else Color.Transparent, RoundedCornerShape(12.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onClick) .padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { if (active) { Box(Modifier.size(6.dp).clip(RoundedCornerShape(50)).background(LuxGold)) Spacer(Modifier.width(10.dp)) } Text(text, color = if (active || focused) LuxText else LuxMuted, fontWeight = if (active) FontWeight.Bold else FontWeight.Medium) } } @Composable fun LuxCard( modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, content: @Composable () -> Unit, ) { var focused by remember { mutableStateOf(false) } val scale = if (focused) 1.012f else 1f var m = modifier .scale(scale) .clip(RoundedCornerShape(18.dp)) .background(if (focused) Color(0xFF26323D) else LuxPanel) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(18.dp)) .onFocusChanged { focused = it.isFocused } if (onClick != null) m = m.focusable().clickable(onClick = onClick) Box(m) { content() } } @Composable fun PosterCard( item: MediaEntry, onClick: () -> Unit, modifier: Modifier = Modifier, onFocus: (() -> Unit)? = null, ) { var focused by remember { mutableStateOf(false) } val scale = if (focused) 1.012f else 1f Box( modifier = modifier .scale(scale) .clip(RoundedCornerShape(18.dp)) .background(if (focused) Color(0xFF26323D) else LuxPanel) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(18.dp)) .onFocusChanged { focused = it.isFocused if (it.isFocused) onFocus?.invoke() } .focusable() .clickable(onClick = onClick) ) { Column { Box(Modifier.fillMaxWidth().height(220.dp).background(LuxPanel2)) { AsyncImage( model = item.image.takeIf { it.isNotBlank() }, contentDescription = item.name, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop, ) Box( Modifier.fillMaxWidth().height(32.dp).align(Alignment.BottomCenter) .background(Brush.verticalGradient(listOf(Color.Transparent, Color.Black.copy(alpha = 0.28f)))) ) if (item.image.isBlank()) { Text( item.name.take(1).uppercase(), color = Color.White.copy(alpha = .25f), fontSize = 52.sp, modifier = Modifier.align(Alignment.Center), ) } } Text( item.name, modifier = Modifier.padding(12.dp, 10.dp, 12.dp, 2.dp), color = LuxText, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis, fontSize = 14.sp, ) val meta = listOf(item.year, item.rating).filter { it.isNotBlank() }.joinToString(" • ") if (meta.isNotBlank()) Text(meta, color = LuxMuted, fontSize = 11.sp, modifier = Modifier.padding(12.dp, 0.dp, 12.dp, 12.dp)) else Spacer(Modifier.height(10.dp)) } } } @UnstableApi private fun buildTiviLuxPlayer( context: android.content.Context, bufferPreset: String, vodOptimized: Boolean = false, ): ExoPlayer { val memory = context.applicationContext.getSystemService(android.content.Context.ACTIVITY_SERVICE) as? android.app.ActivityManager val bufferTargetBytes = tv.tivilux.nativeplayer.data.PlaybackBufferBudget.targetBytes( vodOptimized, memory?.memoryClass ?: 128, memory?.isLowRamDevice ?: true, ) // 0.4.x fast-start playback core. The important change is that the player no longer // waits for multi-second buffers before showing video. We still keep enough headroom // to absorb ordinary IPTV jitter after playback has started. val loadControl = DefaultLoadControl.Builder().apply { if (vodOptimized) { // Movies/Series deliberately buffer well ahead of the playhead. Keep startup // quick, then maintain a large forward reservoir and a useful back buffer so // ordinary playback and short rewinds do not constantly wait on the provider. when (bufferPreset) { "Resilient", "Large" -> setBufferDurationsMs(30_000, 120_000, 900, 2_500) "Balanced" -> setBufferDurationsMs(22_000, 90_000, 650, 1_800) else -> setBufferDurationsMs(16_000, 75_000, 450, 1_350) } // Retain a short exact back buffer; long/keyframe-retained tails can compete // with the forward buffer on small TV heaps. Longer rewinds still seek normally. setBackBuffer(5_000, false) } else { // Live TV: keep the very fast first frame, but maintain a healthier rolling // reservoir once playback starts. The older Turbo profile could run with barely // ~1s of protected media and was vulnerable to 100-200ms provider/network jitter, // which presents as a tiny video freeze while audio keeps moving. // // bufferForPlayback stays intentionally small for fast channel changes. The larger // min/max buffers are filled *after* startup and protect steady-state playback. when (bufferPreset) { "Turbo", "Small" -> setBufferDurationsMs(8_000, 30_000, 250, 1_800) "Resilient", "Large" -> setBufferDurationsMs(12_000, 50_000, 350, 2_200) else -> setBufferDurationsMs(7_000, 30_000, 250, 1_500) } } // Honor both time and byte targets. Startup thresholds above remain unchanged. // This is a sample-buffer target, not a hard cap on all player/decoder memory. setTargetBufferBytes(bufferTargetBytes) setPrioritizeTimeOverSizeThresholds(true) }.build() // Decoder fallback prevents one bad hardware codec implementation from taking the // whole app down. Media3 can fall back to another decoder instead of crashing out. val renderersFactory = DefaultRenderersFactory(context) .setEnableDecoderFallback(true) // Media3 gets its own keep-alive HTTP stack for streams. Shorter connection/read // timeouts make a dead feed fail quickly so the UI can recover instead of appearing // frozen for 20-30 seconds. val dataSourceFactory = DefaultHttpDataSource.Factory() .setUserAgent("TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") .setConnectTimeoutMs(if (vodOptimized) 10_000 else 6_000) .setReadTimeoutMs(if (vodOptimized) 30_000 else 12_000) .setAllowCrossProtocolRedirects(true) val mediaSourceFactory: androidx.media3.exoplayer.source.MediaSource.Factory = if (vodOptimized) DefaultMediaSourceFactory(dataSourceFactory) else DiagnosticMediaSourceFactory(dataSourceFactory) return ExoPlayer.Builder(context, renderersFactory) .setLoadControl(loadControl) .setMediaSourceFactory(mediaSourceFactory) .build() .apply { setHandleAudioBecomingNoisy(true) } } @androidx.annotation.OptIn(UnstableApi::class) @Composable fun rememberTiviLuxPlayer(bufferPreset: String, vodOptimized: Boolean = false): ExoPlayer { val context = LocalContext.current val player = remember(bufferPreset, vodOptimized) { buildTiviLuxPlayer(context, bufferPreset, vodOptimized) } DisposableEffect(player) { onDispose { player.release() } } return player } @androidx.annotation.OptIn(UnstableApi::class) @Composable fun VideoSurface( url: String?, modifier: Modifier = Modifier, autoPlay: Boolean = true, controller: Boolean = true, bufferPreset: String = "Turbo", externalPlayer: ExoPlayer? = null, startPositionMs: Long = 0L, managedLive: Boolean = false, liveCandidates: List = emptyList(), diagnosticChannelKey: String = "", diagnosticChannelName: String = "Live channel", preferSurfaceView: Boolean = false, ) { val context = LocalContext.current val ownsPlayer = externalPlayer == null val internalPlayer = remember(bufferPreset, ownsPlayer) { if (ownsPlayer) buildTiviLuxPlayer(context, bufferPreset, vodOptimized = false) else null } val player = externalPlayer ?: requireNotNull(internalPlayer) var recoverySignal by remember(url, player) { mutableStateOf(0) } var recoveryCount by remember(url, player) { mutableStateOf(0) } LaunchedEffect(url, autoPlay, player, managedLive) { if (managedLive) return@LaunchedEffect if (url.isNullOrBlank()) { if (ownsPlayer) { player.stop() player.clearMediaItems() } } else { val currentUrl = player.currentMediaItem?.localConfiguration?.uri?.toString() if (currentUrl != url) { player.setMediaItem(MediaItem.fromUri(url)) if (startPositionMs > 0L) player.seekTo(startPositionMs) player.prepare() } else if (startPositionMs > 0L && player.currentPosition < 1_000L) { player.seekTo(startPositionMs) } else if (startPositionMs == 0L && player.playbackState == Player.STATE_ENDED) { player.seekTo(0L) } player.playWhenReady = autoPlay } } // Recover from transient IPTV/network decoder failures without making the user back // out and reopen the channel. Limit retries so a truly dead stream still fails fast. // Rebind the listener when the URL changes so it uses this stream's retry state. DisposableEffect(player, ownsPlayer, url) { val listener = object : Player.Listener { override fun onPlayerError(error: PlaybackException) { if (!managedLive && recoveryCount < 2) { recoveryCount += 1 recoverySignal += 1 } } override fun onPlaybackStateChanged(playbackState: Int) { if (!managedLive && playbackState == Player.STATE_READY) recoveryCount = 0 } } player.addListener(listener) onDispose { player.removeListener(listener) } } // Ownership is independent of the URL: changing channels must not release a // player that the next stream will reuse. DisposableEffect(player, ownsPlayer) { onDispose { if (ownsPlayer) player.release() } } // Cancel pending recovery on stream/player changes and skip redundant prepare // calls when another recovery path has already cleared the player error. LaunchedEffect(recoverySignal, url, player) { if (recoverySignal <= 0 || url.isNullOrBlank()) return@LaunchedEffect kotlinx.coroutines.delay(300L * recoveryCount.coerceAtLeast(1)) val currentUrl = player.currentMediaItem?.localConfiguration?.uri?.toString() if (currentUrl == url && player.playerError != null) { player.prepare() player.playWhenReady = autoPlay } } val liveStatus = if (managedLive) rememberLivePlaybackSessionStatus(player, url, liveCandidates, autoPlay, diagnosticChannelKey, diagnosticChannelName) else null Box( modifier = modifier.background(if (ownsPlayer) Color.Black else Color.Transparent), contentAlignment = Alignment.Center, ) { if (url.isNullOrBlank()) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) { Text("Select something to watch", color = LuxText, fontWeight = FontWeight.SemiBold) Text("TiviLux preview", color = LuxMuted, fontSize = 12.sp) } } else { // Recreate only the lightweight PlayerView wrapper when switching between // Guide preview (TextureView) and fullscreen (SurfaceView). The shared ExoPlayer // is NOT recreated, so playback state and the single provider connection survive. key(preferSurfaceView) { AndroidView( modifier = Modifier.fillMaxSize(), factory = { // Live TV deliberately uses a TextureView-backed PlayerView. Unlike a // SurfaceView, the same texture can be resized from the guide preview // rectangle to fullscreen without tearing down the video surface. This // removes the black transition that used to appear on OK / hold-BACK. // Fullscreen playback prefers PlayerView's SurfaceView for the most direct // hardware-composited video path and steadier frame pacing. The Live TV guide // preview keeps the TextureView because it must resize/move underneath Compose // drawers without the overlay/z-order regressions fixed in earlier builds. val view = if (!ownsPlayer && !preferSurfaceView) { LayoutInflater.from(it).inflate( R.layout.tivilux_live_player_view, null, false, ) as PlayerView } else { PlayerView(it) } view.apply { this.player = player useController = controller controllerAutoShow = controller resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT setShowBuffering(if (ownsPlayer) PlayerView.SHOW_BUFFERING_WHEN_PLAYING else PlayerView.SHOW_BUFFERING_NEVER) setShutterBackgroundColor(android.graphics.Color.TRANSPARENT) setBackgroundColor(android.graphics.Color.TRANSPARENT) setKeepContentOnPlayerReset(true) isFocusable = false isFocusableInTouchMode = false descendantFocusability = android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS keepScreenOn = true layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) } }, update = { it.player = player it.useController = controller it.controllerAutoShow = controller }, ) } } if (liveStatus != null) { Text(liveStatus, color = LuxText, fontSize = 12.sp, modifier = Modifier.align(Alignment.BottomCenter) .padding(12.dp).background(Color.Black.copy(alpha = .75f), RoundedCornerShape(6.dp)) .padding(10.dp, 6.dp)) } } } @Composable fun BusyOverlay(show: Boolean) { if (!show) return Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = .38f)), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = LuxGold) } }