Yokan / rebuild
Course 1 8624561

AnimePlayerScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerScreen.kt

implementation454 lines
1package eu.friedcutlet.yokan.ui.screens.player23import androidx.compose.animation.AnimatedVisibility4import androidx.compose.animation.fadeIn5import androidx.compose.animation.fadeOut6import androidx.compose.foundation.background7import androidx.compose.foundation.clickable8import androidx.compose.foundation.interaction.MutableInteractionSource9import androidx.compose.foundation.layout.Arrangement10import androidx.compose.foundation.layout.Box11import androidx.compose.foundation.layout.Column12import androidx.compose.foundation.layout.fillMaxSize13import androidx.compose.foundation.layout.padding14import androidx.compose.foundation.layout.size15import androidx.compose.foundation.layout.widthIn16import androidx.compose.foundation.layout.wrapContentSize17import androidx.compose.material.icons.Icons18import androidx.compose.material.icons.filled.VideoLibrary19import androidx.compose.material3.Icon20import androidx.compose.material3.Surface21import androidx.compose.material3.Text22import androidx.compose.runtime.Composable23import androidx.compose.runtime.LaunchedEffect24import androidx.compose.runtime.getValue25import androidx.compose.runtime.mutableIntStateOf26import androidx.compose.runtime.mutableLongStateOf27import androidx.compose.runtime.mutableStateOf28import androidx.compose.runtime.remember29import androidx.compose.runtime.rememberCoroutineScope30import androidx.compose.runtime.setValue31import androidx.compose.ui.Alignment32import androidx.compose.ui.ExperimentalComposeUiApi33import androidx.compose.ui.Modifier34import androidx.navigationevent.NavigationEventInfo35import androidx.navigationevent.compose.NavigationBackHandler36import androidx.navigationevent.compose.rememberNavigationEventState37import androidx.compose.ui.graphics.Color38import androidx.compose.ui.text.font.FontWeight39import androidx.compose.ui.unit.dp40import androidx.lifecycle.compose.collectAsStateWithLifecycle41import eu.friedcutlet.yokan.database.DbSettings42import eu.friedcutlet.yokan.domain.Chapter43import eu.friedcutlet.yokan.domain.Manga44import eu.friedcutlet.yokan.services.logging.AppLogger45import eu.friedcutlet.yokan.services.media.cast.CastDevice46import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration47import eu.friedcutlet.yokan.services.media.player.MediaPlayerController48import eu.friedcutlet.yokan.services.media.player.MpvChapterMark49import eu.friedcutlet.yokan.services.media.player.MpvPanel50import eu.friedcutlet.yokan.services.media.player.PictureInPictureAction51import eu.friedcutlet.yokan.services.media.player.PlayerBridgeCommand52import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices53import eu.friedcutlet.yokan.services.media.player.SleepTimer54import eu.friedcutlet.yokan.services.media.player.pictureInPicturePlatform55import eu.friedcutlet.yokan.services.media.player.toCommand56import eu.friedcutlet.yokan.ui.screens.reader.ApplyReaderSystemUi57import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor58import eu.friedcutlet.yokan.util.nowMillis59import kotlinx.coroutines.delay60import kotlinx.coroutines.launch6162/** Keeps a room's playback in step with the local controller; supplied by the route. */63internal typealias PlayerPlaybackSync = @Composable (64    controller: MediaPlayerController?,65    isPlaying: Boolean,66    speed: Float,67    onFollowPlaying: (Boolean) -> Unit,68) -> Unit6970/**71 * Binds this episode's media controller and shows it with the player chrome. [playerServices]72 * stays a parameter because the controller lives exactly as long as this composition: it is73 * created and released by [PlayerControllerEffect] and drawn by [MediaPlayerSurface].74 */75@OptIn(ExperimentalComposeUiApi::class)76@Composable77internal fun AnimePlayerScreen(78    manga: Manga,79    chapter: Chapter,80    state: PlayerState,81    settings: DbSettings,82    minimized: Boolean,83    notice: String?,84    playerServices: ProfilePlayerServices,85    onEvent: (PlayerEvent) -> Unit,86    onNotice: (String) -> Unit,87    onBack: () -> Unit,88    onRestore: () -> Unit,89    onDismiss: () -> Unit,90    /** Shrinks to the in-app mini player; the PiP-on-exit fallback where the OS has no PiP. */91    onMinimize: () -> Unit,92    onOpenEpisode: (Chapter) -> Unit,93    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,94    onOpenPlayerSettings: () -> Unit,95    playbackSync: PlayerPlaybackSync,96) {97    val player = rememberPlayerServices(playerServices, chapter.id)98    val playerPreferences = settings.features.player99    val tracks = remember(player, chapter.id) {100        PlayerTrackState(101            playbackSpeed = settings.defaultPlaybackSpeed.toFloat(),102            volume = playerPreferences.volume.takeIf { playerPreferences.rememberVolume && it >= 0 } ?: 100,103            brightness = playerPreferences.brightness.takeIf { playerPreferences.rememberBrightness && it >= 0f },104        )105    }106    var isPlaying by remember(player, chapter.id) { mutableStateOf(true) }107    val mediaConfiguration = remember(player, chapter.id) { player.configuration(settings) }108    ApplyReaderSystemUi(fullscreen = settings.fullScreenPlayer, keepScreenOn = true)109110    var initializationError by remember(player, chapter.id, mediaConfiguration) { mutableStateOf<String?>(null) }111    var initializationAttempt by remember(player, chapter.id, mediaConfiguration) { mutableIntStateOf(0) }112    var mediaControllerState by remember(player, chapter.id, mediaConfiguration) {113        mutableStateOf<MediaPlayerController?>(null)114    }115    val callbacks = rememberPlayerUiBinding(player, mediaControllerState)116    val requestPictureInPicture = rememberPlayerPictureInPicture(callbacks, isPlaying && playerPreferences.pipEnabled)117    playbackSync(mediaControllerState, isPlaying, tracks.playbackSpeed) { isPlaying = it }118    PlayerControllerEffect(119        player = player,120        configuration = mediaConfiguration,121        initializationAttempt = initializationAttempt,122        onController = { mediaControllerState = it },123        onSavePosition = { positionMs, durationMs -> onEvent(PlayerEvent.SavePosition(positionMs, durationMs)) },124        onInitializationError = { failure ->125            initializationError = failure?.let {126                it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty().ifBlank { "Unknown error" } }127            }128            if (failure != null) AppLogger.error("Player initialization failed: ${initializationError.orEmpty()}")129        },130    )131132    val mediaController = mediaControllerState133    if (mediaController == null) {134        PlayerInitError(initializationError, onBack = onBack, onRetry = { initializationAttempt += 1 })135        return136    }137    val setPlaying: (Boolean) -> Unit = { playing ->138        isPlaying = playing139        if (playing) mediaController.play() else mediaController.pause()140    }141    val sleepTimer by playerServices.sleepTimer.collectAsStateWithLifecycle()142    PlayerSleepTimerEffect(sleepTimer, mediaController) { timer ->143        setPlaying(false)144        playerServices.sleepTimer.compareAndSet(timer, null)145        onNotice("Sleep timer ended")146    }147    LaunchedEffect(isPlaying, playerPreferences.pipReplaceWithPrevious) {148        pictureInPicturePlatform.updateActions(isPlaying, playerPreferences.pipReplaceWithPrevious)149    }150    LaunchedEffect(mediaController) {151        pictureInPicturePlatform.actions.collect { action ->152            when (action) {153                PictureInPictureAction.SkipForward -> mediaController.seekTo(mediaController.currentPositionMs() + 10_000L)154                PictureInPictureAction.Previous -> onEvent(PlayerEvent.SwitchEpisode(-1))155                PictureInPictureAction.Next -> onEvent(PlayerEvent.SwitchEpisode(1))156                PictureInPictureAction.Play -> setPlaying(true)157                PictureInPictureAction.Pause -> setPlaying(false)158            }159        }160    }161    val pictureInPictureActive by pictureInPicturePlatform.active.collectAsStateWithLifecycle()162    LaunchedEffect(chapter.id) {163        if (pictureInPictureActive && playerPreferences.pipEpisodeToasts) onNotice(chapter.name)164    }165    // PiP on exit: back while playing enters system PiP, or the in-app mini player without one.166    val exitToPictureInPicture = playerPreferences.pipOnExit && playerPreferences.pipEnabled && isPlaying && !minimized167    val leavePlayer: () -> Unit = {168        if (!exitToPictureInPicture) onBack()169        else if (!(pictureInPicturePlatform.isSupported && requestPictureInPicture())) onMinimize()170    }171    NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None), isBackEnabled = exitToPictureInPicture) { leavePlayer() }172173    AnimePlayerContent(174        manga = manga,175        chapter = chapter,176        state = state,177        settings = settings,178        minimized = minimized,179        notice = notice,180        player = player,181        controller = mediaController,182        configuration = mediaConfiguration,183        callbacks = callbacks,184        tracks = tracks,185        isPlaying = isPlaying,186        setPlaying = setPlaying,187        sleepTimer = sleepTimer,188        onSetSleepTimer = { minutes ->189            playerServices.sleepTimer.value = SleepTimer(minutes?.let { nowMillis() + it * 60_000L })190            onNotice(minutes?.let { "Pausing in $it minutes" } ?: "Pausing at the end of this episode")191        },192        onCancelSleepTimer = { playerServices.sleepTimer.value = null },193        onLeave = leavePlayer,194        onPictureInPicture = if (playerPreferences.pipEnabled && pictureInPicturePlatform.isSupported) {195            { if (!requestPictureInPicture()) onNotice("Picture-in-picture is unavailable for this video") }196        } else {197            null198        },199        onEvent = onEvent,200        onNotice = onNotice,201        onRestore = onRestore,202        onDismiss = onDismiss,203        onOpenEpisode = onOpenEpisode,204        onUpdateSettings = onUpdateSettings,205        onOpenPlayerSettings = onOpenPlayerSettings,206    )207}208209/** The player once its controller exists: video surface, chrome, dialogs and the mpv bridge. */210@Composable211private fun AnimePlayerContent(212    manga: Manga,213    chapter: Chapter,214    state: PlayerState,215    settings: DbSettings,216    minimized: Boolean,217    notice: String?,218    player: ProfilePlayerServices.Reader,219    controller: MediaPlayerController,220    configuration: MediaPlayerConfiguration,221    callbacks: PlayerUiBinding,222    tracks: PlayerTrackState,223    isPlaying: Boolean,224    setPlaying: (Boolean) -> Unit,225    sleepTimer: SleepTimer?,226    onSetSleepTimer: (minutes: Int?) -> Unit,227    onCancelSleepTimer: () -> Unit,228    onLeave: () -> Unit,229    onPictureInPicture: (() -> Unit)?,230    onEvent: (PlayerEvent) -> Unit,231    onNotice: (String) -> Unit,232    onRestore: () -> Unit,233    onDismiss: () -> Unit,234    onOpenEpisode: (Chapter) -> Unit,235    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,236    onOpenPlayerSettings: () -> Unit,237) {238    val playerPreferences = settings.features.player239    var dialog by remember(player) { mutableStateOf<PlayerDialog?>(null) }240    var dimVideo by remember(player) { mutableStateOf(false) }241    PlayerPlaybackEffects(242        player = player,243        controller = controller,244        configuration = configuration,245        state = state,246        settings = settings,247        tracks = tracks,248        episodeListOpen = dialog is PlayerDialog.Episodes,249        setPlaying = setPlaying,250        onDimVideo = { dimVideo = it },251        onEvent = onEvent,252        onUpdateSettings = onUpdateSettings,253    )254    var selectedShader by remember(player) { mutableStateOf("") }255    var chapterMarks by remember(player) { mutableStateOf<List<MpvChapterMark>>(emptyList()) }256    var currentChapterMark by remember(player) { mutableIntStateOf(0) }257    val primaryCustomButton = state.customButtons.firstOrNull { it.isFavourite } ?: state.customButtons.firstOrNull()258    var activeCustomButtonTitle by remember(player, primaryCustomButton?.id) {259        mutableStateOf(primaryCustomButton?.title.orEmpty())260    }261    var customButtonVisible by remember(player, primaryCustomButton?.id) { mutableStateOf(true) }262    var showChrome by remember(player) { mutableStateOf(true) }263    var lastInteractionAt by remember(player) { mutableLongStateOf(0L) }264    val interacted = { lastInteractionAt = nowMillis() }265    LaunchedEffect(lastInteractionAt) {266        if (!showChrome) return@LaunchedEffect267        delay(3_500)268        showChrome = false269    }270    PlayerBridgeEffect(callbacks) { event ->271        when (val command = event.toCommand() ?: return@PlayerBridgeEffect) {272            is PlayerBridgeCommand.ShowText -> onNotice(command.text)273            is PlayerBridgeCommand.SetUiVisible -> showChrome = command.visible ?: !showChrome274            is PlayerBridgeCommand.ShowPanel -> dialog = PlayerDialog.Sheet(275                when (command.panel) {276                    MpvPanel.Video -> PlayerSheetTab.Quality277                    MpvPanel.Subtitles -> PlayerSheetTab.Subtitles278                    MpvPanel.Audio -> PlayerSheetTab.Audio279                },280            )281            is PlayerBridgeCommand.SetButtonTitle -> activeCustomButtonTitle = command.title282            PlayerBridgeCommand.ResetButtonTitle -> activeCustomButtonTitle = primaryCustomButton?.title.orEmpty()283            is PlayerBridgeCommand.SetButtonVisible -> customButtonVisible = command.visible ?: !customButtonVisible284            is PlayerBridgeCommand.SwitchEpisode -> onEvent(PlayerEvent.SwitchEpisode(command.offset))285            is PlayerBridgeCommand.SetPaused -> setPlaying(command.paused?.not() ?: !isPlaying)286            is PlayerBridgeCommand.Seek -> {287                val base = if (command.relative) controller.currentPositionMs() else 0L288                controller.seekTo((base + command.seconds * 1000L).coerceAtLeast(0L))289                command.text?.let(onNotice)290            }291            is PlayerBridgeCommand.LaunchIntPicker -> dialog = PlayerDialog.IntPicker(command.request)292            is PlayerBridgeCommand.ChapterTitles -> chapterMarks = command.marks293            is PlayerBridgeCommand.CurrentChapter -> currentChapterMark = command.index294            is PlayerBridgeCommand.SelectedShader -> selectedShader = command.label295        }296    }297298    val startCasting: (CastDevice?) -> Unit = { device ->299        dialog = null300        onEvent(PlayerEvent.StartCasting(device, controller.currentPositionMs(), tracks.subtitleFile))301    }302    dialog?.let {303        PlayerDialogHost(304            dialog = it,305            state = state,306            settings = settings,307            chapter = chapter,308            controller = controller,309            tracks = tracks,310            isPlaying = isPlaying,311            onDialog = { next -> dialog = next },312            onStartCasting = startCasting,313            onEvent = onEvent,314            onNotice = onNotice,315            onOpenEpisode = onOpenEpisode,316            onOpenPlayerSettings = onOpenPlayerSettings,317            onInteraction = interacted,318        )319    }320321    val screenshotScope = rememberCoroutineScope()322    Box(323        modifier = Modifier324            .then(325                if (minimized) {326                    Modifier327                        .fillMaxSize()328                        .wrapContentSize(Alignment.BottomEnd)329                        .padding(MinimizedAnimePlayerMargin)330                        .size(width = 320.dp, height = MinimizedAnimePlayerHeight)331                } else Modifier.fillMaxSize()332            )333            .background(LocalYokanScaffoldColor.current.copy(alpha = 0.92f))334            .clickable(335                interactionSource = remember(player) { MutableInteractionSource() },336                indication = null,337            ) {338                showChrome = !showChrome339                interacted()340            },341    ) {342        // Center video surface (mpv with a platform fallback). Composed regardless of343        // chrome visibility so the picture stays steady; chrome layers float on top.344        Surface(modifier = Modifier.fillMaxSize(), color = Color.Black) {345            if (state.selectedVideo != null) {346                MediaPlayerSurface(controller = controller, modifier = Modifier.fillMaxSize())347            } else {348                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {349                    Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {350                        Icon(Icons.Filled.VideoLibrary, contentDescription = null, tint = Color.White, modifier = Modifier.size(56.dp))351                        Text("No stream", color = Color.White, fontWeight = FontWeight.SemiBold)352                    }353                }354            }355        }356        if (dimVideo) {357            Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = (1f - (tracks.brightness ?: 1f)) * 0.85f)))358        }359        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut()) {360            Box(modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.40f)))361        }362        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.TopCenter)) {363            PlayerTopBar(364                title = manga.name,365                episodeName = chapter.name,366                minimized = minimized,367                sleepTimer = sleepTimer,368                castSupported = state.castSupported,369                casting = state.castStatus != null,370                onLeave = onLeave,371                onRestore = onRestore,372                onDismiss = onDismiss,373                onSetSleepTimer = onSetSleepTimer,374                onCancelSleepTimer = onCancelSleepTimer,375                onCast = {376                    when {377                        state.castStatus != null -> Unit // the cast panel holds the controls378                        state.castUsesSystemPicker -> startCasting(null)379                        else -> dialog = PlayerDialog.Cast380                    }381                },382                onOpenEpisodes = {383                    if (isPlaying) controller.pause()384                    dialog = PlayerDialog.Episodes(resume = isPlaying)385                },386                onScreenshot = {387                    screenshotScope.launch {388                        onNotice(takeScreenshot(player, controller, manga, chapter, playerPreferences.screenshotSubtitles))389                        interacted()390                    }391                },392            )393        }394        notice?.let {395            PlayerNotice(it, Modifier.align(Alignment.TopCenter).padding(top = 64.dp, start = 16.dp, end = 16.dp))396        }397        state.castStatus?.let { status ->398            CastPanel(399                status = status,400                compact = minimized,401                onPlayPause = { onEvent(PlayerEvent.CastPlayPause) },402                onSeek = { onEvent(PlayerEvent.CastSeek(it)) },403                onPrevious = { onEvent(PlayerEvent.CastPrevious) },404                onNext = { onEvent(PlayerEvent.CastNext) },405                onJumpTo = { onEvent(PlayerEvent.CastJumpTo(it)) },406                onDisconnect = {407                    // Continue locally from the receiver's position when it was playing this episode.408                    val item = status.queue.getOrNull(status.currentIndex)409                    if (item?.itemKey == chapter.id.toString() && status.positionMs > 0L) controller.seekTo(status.positionMs)410                    onEvent(PlayerEvent.StopCasting)411                },412                modifier = Modifier.align(Alignment.Center).padding(16.dp).widthIn(max = 480.dp),413            )414        }415        AnimatedVisibility(416            visible = showChrome && state.castStatus == null,417            enter = fadeIn(),418            exit = fadeOut(),419            modifier = Modifier.align(Alignment.Center),420        ) {421            PlayerCenterControls(422                isPlaying = isPlaying,423                onPrevious = { onEvent(PlayerEvent.SwitchEpisode(-1)); interacted() },424                onPlayPause = { setPlaying(!isPlaying); interacted() },425                onNext = { onEvent(PlayerEvent.SwitchEpisode(1)); interacted() },426                onPictureInPicture = onPictureInPicture?.let { request -> { request(); interacted() } },427            )428        }429        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter)) {430            PlayerBottomControls(431                state = state,432                settings = settings,433                controller = controller,434                tracks = tracks,435                chapterMarks = chapterMarks,436                currentChapterMark = currentChapterMark,437                selectedShader = selectedShader,438                onShaderSelected = { selectedShader = it },439                customButtonVisible = customButtonVisible,440                primaryCustomButtonId = primaryCustomButton?.id,441                activeCustomButtonTitle = activeCustomButtonTitle,442                onOpenSettings = { dialog = PlayerDialog.Sheet(PlayerSheetTab.Quality) },443                onEvent = onEvent,444                onNotice = onNotice,445                onUpdateSettings = onUpdateSettings,446                onInteraction = interacted,447            )448        }449    }450}451452internal val MinimizedAnimePlayerHeight = 190.dp453454internal val MinimizedAnimePlayerMargin = 16.dp455

Search chapters, reference and source filenames.