PlayerServicesBinding.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerServicesBinding.kt
1package eu.friedcutlet.yokan.ui.screens.player23import androidx.compose.runtime.Composable4import androidx.compose.runtime.DisposableEffect5import androidx.compose.runtime.LaunchedEffect6import androidx.compose.runtime.remember7import eu.friedcutlet.yokan.database.DbSettings8import eu.friedcutlet.yokan.database.withPlayer9import eu.friedcutlet.yokan.domain.Chapter10import eu.friedcutlet.yokan.domain.Manga11import eu.friedcutlet.yokan.services.logging.AppLogger12import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices13import eu.friedcutlet.yokan.services.media.player.SleepTimer14import eu.friedcutlet.yokan.services.media.player.isDue15import eu.friedcutlet.yokan.util.nowMillis16import eu.friedcutlet.yokan.services.media.player.preferredSubtitle17import eu.friedcutlet.yokan.services.media.player.setPlayerScreenBrightness18import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration19import eu.friedcutlet.yokan.services.media.player.MediaPlayerController20import kotlinx.coroutines.CancellationException21import kotlinx.coroutines.Job22import kotlinx.coroutines.NonCancellable23import kotlinx.coroutines.awaitCancellation24import kotlinx.coroutines.currentCoroutineContext25import kotlinx.coroutines.delay26import kotlinx.coroutines.ensureActive27import kotlinx.coroutines.withContext28import org.jetbrains.compose.resources.getString29import yokan.composeapp.generated.resources.Res30import yokan.composeapp.generated.resources.player_screenshot_failed31import yokan.composeapp.generated.resources.player_screenshot_saved32import yokan.composeapp.generated.resources.player_screenshot_unavailable3334@Composable35internal fun rememberPlayerServices(services: ProfilePlayerServices, chapterId: Long): ProfilePlayerServices.Reader {36 val reader = remember(services, chapterId) { services.reader() }37 DisposableEffect(reader) {38 onDispose { reader.retire() }39 }40 return reader41}4243/** The captured callback saves this episode before its owned controller is released. */44@Composable45internal fun PlayerControllerEffect(46 player: ProfilePlayerServices.Reader,47 configuration: MediaPlayerConfiguration,48 initializationAttempt: Int,49 onController: (MediaPlayerController?) -> Unit,50 onSavePosition: (Long, Long) -> Unit,51 onInitializationError: (Throwable?) -> Unit,52) {53 LaunchedEffect(player, configuration, initializationAttempt) {54 val uiContext = currentCoroutineContext().minusKey(Job)55 onInitializationError(null)56 try {57 player.prepareConfiguration(configuration)58 player.withController(configuration) { controller ->59 withContext(uiContext) {60 currentCoroutineContext().ensureActive()61 player.ensureOpen()62 onController(controller)63 try { awaitCancellation() }64 finally {65 withContext(NonCancellable) {66 try { onSavePosition(controller.currentPositionMs(), controller.durationMs()) }67 finally { onController(null) }68 }69 }70 }71 }72 } catch (failure: CancellationException) {73 throw failure74 } catch (failure: Throwable) {75 currentCoroutineContext().ensureActive()76 player.ensureOpen()77 onInitializationError(failure)78 }79 }80}8182/** Effects that drive the controller from [state], [tracks] and the settings. */83@Composable84internal fun PlayerPlaybackEffects(85 player: ProfilePlayerServices.Reader,86 controller: MediaPlayerController,87 configuration: MediaPlayerConfiguration,88 state: PlayerState,89 settings: DbSettings,90 tracks: PlayerTrackState,91 episodeListOpen: Boolean,92 setPlaying: (Boolean) -> Unit,93 /** True where the screen brightness can't be set, so the video is dimmed instead. */94 onDimVideo: (Boolean) -> Unit,95 onEvent: (PlayerEvent) -> Unit,96 onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,97) {98 val playerPreferences = settings.features.player99 LaunchedEffect(player, controller, state.selectedVideo) {100 player.ensureOpen()101 val video = state.selectedVideo ?: return@LaunchedEffect102 controller.load(video.url, video.headers.orEmpty(), state.startPositionMs)103 tracks.applyStreamDefaults(104 controller = controller,105 subtitle = preferredSubtitle(106 tracks = video.subtitles,107 languages = playerPreferences.subtitleLanguages.ifEmpty { listOfNotNull(settings.defaultSubtitleLang?.languageCode) },108 whitelist = playerPreferences.subtitleWhitelist,109 blacklist = playerPreferences.subtitleBlacklist,110 ),111 audio = video.audios.firstOrNull(),112 )113 controller.setVolume(tracks.volume)114 controller.setPlaybackSpeed(tracks.playbackSpeed)115 if (state.autoplay && !episodeListOpen) controller.play() else controller.pause()116 }117 LaunchedEffect(player, controller, state.customButtons, configuration.useMpvConfig) {118 player.installCustomButtons(controller, state.customButtons, configuration)119 }120 LaunchedEffect(player, controller, tracks.playbackSpeed) {121 player.ensureOpen()122 if (state.selectedVideo != null) controller.setPlaybackSpeed(tracks.playbackSpeed)123 }124 val volume = tracks.volume125 LaunchedEffect(player, controller, volume) {126 controller.setVolume(volume)127 if (!playerPreferences.rememberVolume || volume == playerPreferences.volume) return@LaunchedEffect128 delay(500) // persist once the slider settles129 onUpdateSettings { db -> db.withPlayer { it.copy(volume = volume) } }130 }131 DisposableEffect(player) { onDispose { setPlayerScreenBrightness(null) } }132 val brightness = tracks.brightness133 LaunchedEffect(brightness) {134 onDimVideo(!setPlayerScreenBrightness(brightness) && brightness != null)135 val level = brightness ?: return@LaunchedEffect136 if (!playerPreferences.rememberBrightness || level == playerPreferences.brightness) return@LaunchedEffect137 delay(500)138 onUpdateSettings { db -> db.withPlayer { it.copy(brightness = level) } }139 }140 val playbackError = controller.playbackError141 LaunchedEffect(playbackError) {142 if (playbackError != null) onEvent(PlayerEvent.PlaybackFailed(playbackError, controller.currentPositionMs()))143 }144 // The receiver plays the episode while a cast session is active.145 val casting = state.castStatus != null146 LaunchedEffect(controller, casting) {147 if (casting) setPlaying(false)148 }149}150151/** The notice for a screenshot of the current frame. */152internal suspend fun takeScreenshot(153 player: ProfilePlayerServices.Reader,154 controller: MediaPlayerController,155 manga: Manga,156 chapter: Chapter,157 includeSubtitles: Boolean,158): String {159 val notice = try {160 val path = player.requestScreenshot(controller, manga.name, chapter.name, includeSubtitles)161 when {162 path != null -> getString(Res.string.player_screenshot_saved, path)163 controller.isMpvBackend -> getString(Res.string.player_screenshot_failed)164 else -> getString(Res.string.player_screenshot_unavailable)165 }166 } catch (cancelled: CancellationException) {167 throw cancelled168 } catch (failure: Throwable) {169 currentCoroutineContext().ensureActive()170 player.ensureOpen()171 AppLogger.error("[player] screenshot failed: ${failure.message.orEmpty()}")172 getString(Res.string.player_screenshot_failed)173 }174 currentCoroutineContext().ensureActive()175 player.ensureOpen()176 return notice177}178179/** Polls a pending [timer] each second and reports it once due. */180@Composable181internal fun PlayerSleepTimerEffect(timer: SleepTimer?, controller: MediaPlayerController, onDue: (SleepTimer) -> Unit) {182 LaunchedEffect(timer, controller) {183 val pending = timer ?: return@LaunchedEffect184 while (!pending.isDue(nowMillis(), controller.currentPositionMs(), controller.durationMs())) delay(1_000)185 onDue(pending)186 }187}188