package eu.friedcutlet.yokan.ui.screens.player import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material3.Icon import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.navigationevent.NavigationEventInfo import androidx.navigationevent.compose.NavigationBackHandler import androidx.navigationevent.compose.rememberNavigationEventState import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.media.cast.CastDevice import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration import eu.friedcutlet.yokan.services.media.player.MediaPlayerController import eu.friedcutlet.yokan.services.media.player.MpvChapterMark import eu.friedcutlet.yokan.services.media.player.MpvPanel import eu.friedcutlet.yokan.services.media.player.PictureInPictureAction import eu.friedcutlet.yokan.services.media.player.PlayerBridgeCommand import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices import eu.friedcutlet.yokan.services.media.player.SleepTimer import eu.friedcutlet.yokan.services.media.player.pictureInPicturePlatform import eu.friedcutlet.yokan.services.media.player.toCommand import eu.friedcutlet.yokan.ui.screens.reader.ApplyReaderSystemUi import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** Keeps a room's playback in step with the local controller; supplied by the route. */ internal typealias PlayerPlaybackSync = @Composable ( controller: MediaPlayerController?, isPlaying: Boolean, speed: Float, onFollowPlaying: (Boolean) -> Unit, ) -> Unit /** * Binds this episode's media controller and shows it with the player chrome. [playerServices] * stays a parameter because the controller lives exactly as long as this composition: it is * created and released by [PlayerControllerEffect] and drawn by [MediaPlayerSurface]. */ @OptIn(ExperimentalComposeUiApi::class) @Composable internal fun AnimePlayerScreen( manga: Manga, chapter: Chapter, state: PlayerState, settings: DbSettings, minimized: Boolean, notice: String?, playerServices: ProfilePlayerServices, onEvent: (PlayerEvent) -> Unit, onNotice: (String) -> Unit, onBack: () -> Unit, onRestore: () -> Unit, onDismiss: () -> Unit, /** Shrinks to the in-app mini player; the PiP-on-exit fallback where the OS has no PiP. */ onMinimize: () -> Unit, onOpenEpisode: (Chapter) -> Unit, onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit, onOpenPlayerSettings: () -> Unit, playbackSync: PlayerPlaybackSync, ) { val player = rememberPlayerServices(playerServices, chapter.id) val playerPreferences = settings.features.player val tracks = remember(player, chapter.id) { PlayerTrackState( playbackSpeed = settings.defaultPlaybackSpeed.toFloat(), volume = playerPreferences.volume.takeIf { playerPreferences.rememberVolume && it >= 0 } ?: 100, brightness = playerPreferences.brightness.takeIf { playerPreferences.rememberBrightness && it >= 0f }, ) } var isPlaying by remember(player, chapter.id) { mutableStateOf(true) } val mediaConfiguration = remember(player, chapter.id) { player.configuration(settings) } ApplyReaderSystemUi(fullscreen = settings.fullScreenPlayer, keepScreenOn = true) var initializationError by remember(player, chapter.id, mediaConfiguration) { mutableStateOf(null) } var initializationAttempt by remember(player, chapter.id, mediaConfiguration) { mutableIntStateOf(0) } var mediaControllerState by remember(player, chapter.id, mediaConfiguration) { mutableStateOf(null) } val callbacks = rememberPlayerUiBinding(player, mediaControllerState) val requestPictureInPicture = rememberPlayerPictureInPicture(callbacks, isPlaying && playerPreferences.pipEnabled) playbackSync(mediaControllerState, isPlaying, tracks.playbackSpeed) { isPlaying = it } PlayerControllerEffect( player = player, configuration = mediaConfiguration, initializationAttempt = initializationAttempt, onController = { mediaControllerState = it }, onSavePosition = { positionMs, durationMs -> onEvent(PlayerEvent.SavePosition(positionMs, durationMs)) }, onInitializationError = { failure -> initializationError = failure?.let { it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty().ifBlank { "Unknown error" } } } if (failure != null) AppLogger.error("Player initialization failed: ${initializationError.orEmpty()}") }, ) val mediaController = mediaControllerState if (mediaController == null) { PlayerInitError(initializationError, onBack = onBack, onRetry = { initializationAttempt += 1 }) return } val setPlaying: (Boolean) -> Unit = { playing -> isPlaying = playing if (playing) mediaController.play() else mediaController.pause() } val sleepTimer by playerServices.sleepTimer.collectAsStateWithLifecycle() PlayerSleepTimerEffect(sleepTimer, mediaController) { timer -> setPlaying(false) playerServices.sleepTimer.compareAndSet(timer, null) onNotice("Sleep timer ended") } LaunchedEffect(isPlaying, playerPreferences.pipReplaceWithPrevious) { pictureInPicturePlatform.updateActions(isPlaying, playerPreferences.pipReplaceWithPrevious) } LaunchedEffect(mediaController) { pictureInPicturePlatform.actions.collect { action -> when (action) { PictureInPictureAction.SkipForward -> mediaController.seekTo(mediaController.currentPositionMs() + 10_000L) PictureInPictureAction.Previous -> onEvent(PlayerEvent.SwitchEpisode(-1)) PictureInPictureAction.Next -> onEvent(PlayerEvent.SwitchEpisode(1)) PictureInPictureAction.Play -> setPlaying(true) PictureInPictureAction.Pause -> setPlaying(false) } } } val pictureInPictureActive by pictureInPicturePlatform.active.collectAsStateWithLifecycle() LaunchedEffect(chapter.id) { if (pictureInPictureActive && playerPreferences.pipEpisodeToasts) onNotice(chapter.name) } // PiP on exit: back while playing enters system PiP, or the in-app mini player without one. val exitToPictureInPicture = playerPreferences.pipOnExit && playerPreferences.pipEnabled && isPlaying && !minimized val leavePlayer: () -> Unit = { if (!exitToPictureInPicture) onBack() else if (!(pictureInPicturePlatform.isSupported && requestPictureInPicture())) onMinimize() } NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None), isBackEnabled = exitToPictureInPicture) { leavePlayer() } AnimePlayerContent( manga = manga, chapter = chapter, state = state, settings = settings, minimized = minimized, notice = notice, player = player, controller = mediaController, configuration = mediaConfiguration, callbacks = callbacks, tracks = tracks, isPlaying = isPlaying, setPlaying = setPlaying, sleepTimer = sleepTimer, onSetSleepTimer = { minutes -> playerServices.sleepTimer.value = SleepTimer(minutes?.let { nowMillis() + it * 60_000L }) onNotice(minutes?.let { "Pausing in $it minutes" } ?: "Pausing at the end of this episode") }, onCancelSleepTimer = { playerServices.sleepTimer.value = null }, onLeave = leavePlayer, onPictureInPicture = if (playerPreferences.pipEnabled && pictureInPicturePlatform.isSupported) { { if (!requestPictureInPicture()) onNotice("Picture-in-picture is unavailable for this video") } } else { null }, onEvent = onEvent, onNotice = onNotice, onRestore = onRestore, onDismiss = onDismiss, onOpenEpisode = onOpenEpisode, onUpdateSettings = onUpdateSettings, onOpenPlayerSettings = onOpenPlayerSettings, ) } /** The player once its controller exists: video surface, chrome, dialogs and the mpv bridge. */ @Composable private fun AnimePlayerContent( manga: Manga, chapter: Chapter, state: PlayerState, settings: DbSettings, minimized: Boolean, notice: String?, player: ProfilePlayerServices.Reader, controller: MediaPlayerController, configuration: MediaPlayerConfiguration, callbacks: PlayerUiBinding, tracks: PlayerTrackState, isPlaying: Boolean, setPlaying: (Boolean) -> Unit, sleepTimer: SleepTimer?, onSetSleepTimer: (minutes: Int?) -> Unit, onCancelSleepTimer: () -> Unit, onLeave: () -> Unit, onPictureInPicture: (() -> Unit)?, onEvent: (PlayerEvent) -> Unit, onNotice: (String) -> Unit, onRestore: () -> Unit, onDismiss: () -> Unit, onOpenEpisode: (Chapter) -> Unit, onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit, onOpenPlayerSettings: () -> Unit, ) { val playerPreferences = settings.features.player var dialog by remember(player) { mutableStateOf(null) } var dimVideo by remember(player) { mutableStateOf(false) } PlayerPlaybackEffects( player = player, controller = controller, configuration = configuration, state = state, settings = settings, tracks = tracks, episodeListOpen = dialog is PlayerDialog.Episodes, setPlaying = setPlaying, onDimVideo = { dimVideo = it }, onEvent = onEvent, onUpdateSettings = onUpdateSettings, ) var selectedShader by remember(player) { mutableStateOf("") } var chapterMarks by remember(player) { mutableStateOf>(emptyList()) } var currentChapterMark by remember(player) { mutableIntStateOf(0) } val primaryCustomButton = state.customButtons.firstOrNull { it.isFavourite } ?: state.customButtons.firstOrNull() var activeCustomButtonTitle by remember(player, primaryCustomButton?.id) { mutableStateOf(primaryCustomButton?.title.orEmpty()) } var customButtonVisible by remember(player, primaryCustomButton?.id) { mutableStateOf(true) } var showChrome by remember(player) { mutableStateOf(true) } var lastInteractionAt by remember(player) { mutableLongStateOf(0L) } val interacted = { lastInteractionAt = nowMillis() } LaunchedEffect(lastInteractionAt) { if (!showChrome) return@LaunchedEffect delay(3_500) showChrome = false } PlayerBridgeEffect(callbacks) { event -> when (val command = event.toCommand() ?: return@PlayerBridgeEffect) { is PlayerBridgeCommand.ShowText -> onNotice(command.text) is PlayerBridgeCommand.SetUiVisible -> showChrome = command.visible ?: !showChrome is PlayerBridgeCommand.ShowPanel -> dialog = PlayerDialog.Sheet( when (command.panel) { MpvPanel.Video -> PlayerSheetTab.Quality MpvPanel.Subtitles -> PlayerSheetTab.Subtitles MpvPanel.Audio -> PlayerSheetTab.Audio }, ) is PlayerBridgeCommand.SetButtonTitle -> activeCustomButtonTitle = command.title PlayerBridgeCommand.ResetButtonTitle -> activeCustomButtonTitle = primaryCustomButton?.title.orEmpty() is PlayerBridgeCommand.SetButtonVisible -> customButtonVisible = command.visible ?: !customButtonVisible is PlayerBridgeCommand.SwitchEpisode -> onEvent(PlayerEvent.SwitchEpisode(command.offset)) is PlayerBridgeCommand.SetPaused -> setPlaying(command.paused?.not() ?: !isPlaying) is PlayerBridgeCommand.Seek -> { val base = if (command.relative) controller.currentPositionMs() else 0L controller.seekTo((base + command.seconds * 1000L).coerceAtLeast(0L)) command.text?.let(onNotice) } is PlayerBridgeCommand.LaunchIntPicker -> dialog = PlayerDialog.IntPicker(command.request) is PlayerBridgeCommand.ChapterTitles -> chapterMarks = command.marks is PlayerBridgeCommand.CurrentChapter -> currentChapterMark = command.index is PlayerBridgeCommand.SelectedShader -> selectedShader = command.label } } val startCasting: (CastDevice?) -> Unit = { device -> dialog = null onEvent(PlayerEvent.StartCasting(device, controller.currentPositionMs(), tracks.subtitleFile)) } dialog?.let { PlayerDialogHost( dialog = it, state = state, settings = settings, chapter = chapter, controller = controller, tracks = tracks, isPlaying = isPlaying, onDialog = { next -> dialog = next }, onStartCasting = startCasting, onEvent = onEvent, onNotice = onNotice, onOpenEpisode = onOpenEpisode, onOpenPlayerSettings = onOpenPlayerSettings, onInteraction = interacted, ) } val screenshotScope = rememberCoroutineScope() Box( modifier = Modifier .then( if (minimized) { Modifier .fillMaxSize() .wrapContentSize(Alignment.BottomEnd) .padding(MinimizedAnimePlayerMargin) .size(width = 320.dp, height = MinimizedAnimePlayerHeight) } else Modifier.fillMaxSize() ) .background(LocalYokanScaffoldColor.current.copy(alpha = 0.92f)) .clickable( interactionSource = remember(player) { MutableInteractionSource() }, indication = null, ) { showChrome = !showChrome interacted() }, ) { // Center video surface (mpv with a platform fallback). Composed regardless of // chrome visibility so the picture stays steady; chrome layers float on top. Surface(modifier = Modifier.fillMaxSize(), color = Color.Black) { if (state.selectedVideo != null) { MediaPlayerSurface(controller = controller, modifier = Modifier.fillMaxSize()) } else { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Icon(Icons.Filled.VideoLibrary, contentDescription = null, tint = Color.White, modifier = Modifier.size(56.dp)) Text("No stream", color = Color.White, fontWeight = FontWeight.SemiBold) } } } } if (dimVideo) { Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = (1f - (tracks.brightness ?: 1f)) * 0.85f))) } AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut()) { Box(modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.40f))) } AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.TopCenter)) { PlayerTopBar( title = manga.name, episodeName = chapter.name, minimized = minimized, sleepTimer = sleepTimer, castSupported = state.castSupported, casting = state.castStatus != null, onLeave = onLeave, onRestore = onRestore, onDismiss = onDismiss, onSetSleepTimer = onSetSleepTimer, onCancelSleepTimer = onCancelSleepTimer, onCast = { when { state.castStatus != null -> Unit // the cast panel holds the controls state.castUsesSystemPicker -> startCasting(null) else -> dialog = PlayerDialog.Cast } }, onOpenEpisodes = { if (isPlaying) controller.pause() dialog = PlayerDialog.Episodes(resume = isPlaying) }, onScreenshot = { screenshotScope.launch { onNotice(takeScreenshot(player, controller, manga, chapter, playerPreferences.screenshotSubtitles)) interacted() } }, ) } notice?.let { PlayerNotice(it, Modifier.align(Alignment.TopCenter).padding(top = 64.dp, start = 16.dp, end = 16.dp)) } state.castStatus?.let { status -> CastPanel( status = status, compact = minimized, onPlayPause = { onEvent(PlayerEvent.CastPlayPause) }, onSeek = { onEvent(PlayerEvent.CastSeek(it)) }, onPrevious = { onEvent(PlayerEvent.CastPrevious) }, onNext = { onEvent(PlayerEvent.CastNext) }, onJumpTo = { onEvent(PlayerEvent.CastJumpTo(it)) }, onDisconnect = { // Continue locally from the receiver's position when it was playing this episode. val item = status.queue.getOrNull(status.currentIndex) if (item?.itemKey == chapter.id.toString() && status.positionMs > 0L) controller.seekTo(status.positionMs) onEvent(PlayerEvent.StopCasting) }, modifier = Modifier.align(Alignment.Center).padding(16.dp).widthIn(max = 480.dp), ) } AnimatedVisibility( visible = showChrome && state.castStatus == null, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.Center), ) { PlayerCenterControls( isPlaying = isPlaying, onPrevious = { onEvent(PlayerEvent.SwitchEpisode(-1)); interacted() }, onPlayPause = { setPlaying(!isPlaying); interacted() }, onNext = { onEvent(PlayerEvent.SwitchEpisode(1)); interacted() }, onPictureInPicture = onPictureInPicture?.let { request -> { request(); interacted() } }, ) } AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter)) { PlayerBottomControls( state = state, settings = settings, controller = controller, tracks = tracks, chapterMarks = chapterMarks, currentChapterMark = currentChapterMark, selectedShader = selectedShader, onShaderSelected = { selectedShader = it }, customButtonVisible = customButtonVisible, primaryCustomButtonId = primaryCustomButton?.id, activeCustomButtonTitle = activeCustomButtonTitle, onOpenSettings = { dialog = PlayerDialog.Sheet(PlayerSheetTab.Quality) }, onEvent = onEvent, onNotice = onNotice, onUpdateSettings = onUpdateSettings, onInteraction = interacted, ) } } } internal val MinimizedAnimePlayerHeight = 190.dp internal val MinimizedAnimePlayerMargin = 16.dp