package eu.friedcutlet.yokan.ui.screens.player import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.isIncognitoFor import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ChapterRecognition import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.domain.Track import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionLogger import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.library.readingChapterSequence import eu.friedcutlet.yokan.services.library.sortedChapters import eu.friedcutlet.yokan.services.library.visibleChapters import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.redactUrlForLog import eu.friedcutlet.yokan.services.media.AniSkipMarker import eu.friedcutlet.yokan.services.media.cast.CastController import eu.friedcutlet.yokan.services.media.player.externalPlayerChoices import eu.friedcutlet.yokan.services.media.player.nextFailoverVideo import eu.friedcutlet.yokan.services.media.player.parseThumbnailVtt import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.compose.resources.decodeToImageBitmap /** Player ordering stays user-controlled while release selection matches the readers. */ internal fun playerEpisodeSequence( manga: Manga, currentChapterId: Long, all: List, db: DbSettings, downloadedIds: Set, ): List = sortedChapters( manga, readingChapterSequence(manga, currentChapterId, all, db, downloadedIds), db, ) /** * The player's streams, library reads, progress writes, AniSkip markers and casting. Work that * needs the media controller (loading it, tracks, chrome, screenshots) stays in [AnimePlayerScreen]. */ internal class PlayerViewModel( private val manga: Manga, private val chapter: Chapter, private val repository: YokanRepository, private val settings: SettingsStore, libraryIndex: LibraryIndexStore, private val http: HttpService, private val loadVideos: suspend (Source?, Chapter) -> List, private val aniSkipMarkers: suspend (malId: Long, episode: Int) -> List, /** Hands [DbVideo] to the external player `playerId` (blank: the platform default); false when none opened. */ private val openExternalPlayer: (video: DbVideo, playerId: String) -> Boolean, private val cast: CastController, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { // ponytail: sprites stay decoded for the stream's lifetime; a few sheets per episode in practice. private var streamScope = newStreamScope() private var streamHeaders: Map = emptyMap() private val spriteRequests = mutableSetOf() /** Streams of this episode that failed; failover tries each remaining one once. */ private val failedStreams = mutableSetOf() private val source: Source? = manga.sourceId?.let(repository::source) ?: repository.sources(manga.itemType).firstOrNull { it.name.equals(manga.source, ignoreCase = true) && it.lang.equals(manga.lang, ignoreCase = true) } private val _state = MutableStateFlow( PlayerState( startPositionMs = savedVideoPositionMs( lastPageRead = chapter.lastPageRead, isRead = chapter.isRead, incognitoMode = settings.db.value.isIncognitoFor(manga.sourceId), ), castUsesSystemPicker = cast.usesSystemPicker, ), ) val state: StateFlow = _state.asStateFlow() private val _effects = Channel(Channel.BUFFERED) val effects: Flow = _effects.receiveAsFlow() init { repository.chapterOpened(chapter.id) viewModelScope.launch { combine(libraryIndex.index, settings.db) { index, db -> val all = index.chapters(manga.id) playerEpisodeSequence(manga, chapter.id, all, db, index.downloadedChapterIds) to visibleChapters(manga, all, db, index.downloadedChapterIds) } .flowOn(workDispatcher) .collect { (episodes, visible) -> _state.update { it.copy(episodes = episodes, visibleEpisodes = visible) } } } viewModelScope.launch { repository.snapshots .map { it.customButtons } .distinctUntilChanged() .collect { buttons -> _state.update { it.copy(customButtons = buttons.sortedBy(DbCustomButton::position)) } } } viewModelScope.launch { combine(cast.status, cast.isSupported, cast.devices) { status, supported, devices -> Triple(status, supported, devices) }.collect { (status, supported, devices) -> _state.update { it.copy(castStatus = status, castSupported = supported, castDevices = devices) } } } viewModelScope.launch { loadStreams() } viewModelScope.launch { loadAniSkipMarkers() } } override fun onCleared() { repository.chapterClosed(chapter.id) super.onCleared() } fun onEvent(event: PlayerEvent) { when (event) { is PlayerEvent.SwitchEpisode -> adjacentEpisode(event.offset)?.let { _effects.trySend(PlayerEffect.OpenEpisode(it)) } is PlayerEvent.SavePosition -> savePosition(event.positionMs, event.durationMs) is PlayerEvent.LoadSeekSprite -> loadSeekSprite(event.url) is PlayerEvent.SelectVideo -> selectVideo(event.video, event.startPositionMs, event.autoplay) is PlayerEvent.PlaybackFailed -> failOver(event.error, event.positionMs) // Launched: proxying through a retired reader throws CancellationException. is PlayerEvent.OpenExternalPlayer -> viewModelScope.launch { openExternalPlayer(event.video, settings.db.value.features.player.externalPlayer) } is PlayerEvent.SetCastDiscovery -> if (event.active) cast.startDiscovery() else cast.stopDiscovery() is PlayerEvent.StartCasting -> startCasting(event) PlayerEvent.StopCasting -> viewModelScope.launch { catchingNonCancellation { cast.disconnect() } } PlayerEvent.CastPlayPause -> if (state.value.castStatus?.playing == true) cast.pause() else cast.play() is PlayerEvent.CastSeek -> cast.seekTo(event.positionMs) PlayerEvent.CastPrevious -> cast.previous() PlayerEvent.CastNext -> cast.next() is PlayerEvent.CastJumpTo -> cast.jumpTo(event.index) } } /** The episode [offset] steps from the current one in title order, or null past either end. */ private fun adjacentEpisode(offset: Int): Chapter? { val all = state.value.episodes val index = all.indexOfFirst { it.id == chapter.id } return if (index < 0) null else all.getOrNull(index + offset) } /** Persists the watched position on leave so History resumes mid-episode. */ private fun savePosition(positionMs: Long, durationMs: Long) { val db = settings.db.value if (!shouldSaveVideoPosition(chapter.isRead, db.isIncognitoFor(manga.sourceId), positionMs)) return repository.setChaptersRead( chapterIds = setOf(chapter.id), isRead = isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType), lastPageRead = positionMs.toString(), // Anime watch time is tracked elsewhere; counting it on every exit would inflate the stat. readingTimeSeconds = 0, ) if (isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType)) repository.recordChapterConsumption(setOf(chapter.id)) } private suspend fun loadStreams() { val startedAt = nowMillis() AppLogger.info( "Episode load start mangaId=${manga.id} manga='${manga.name}' chapterId=${chapter.id} " + "chapter='${chapter.name}' source=${source?.name ?: "unknown"} url=${redactUrlForLog(chapter.url)}", ) var error: String? = null val videos = catchingNonCancellation { loadEpisodeVideos(chapter) } .onFailure { throwable -> error = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() } AppLogger.error("Episode load failed chapterId=${chapter.id}: ${error.orEmpty()}") } .getOrElse { emptyList() } if (videos.isEmpty() && error == null) { error = "No streams were returned by ${source?.name ?: "this source"}." AppLogger.warn("Episode load returned no streams chapterId=${chapter.id}") } val first = videos.firstOrNull() val preferences = settings.db.value.features.player if (first != null && preferences.alwaysUseExternalPlayer && externalPlayerChoices().isNotEmpty()) { if (openExternalPlayer(first, preferences.externalPlayer)) { _state.update { it.copy(videos = videos, loading = false) } _effects.send(PlayerEffect.Exit) return } error = "The external player could not be opened; playing here instead." } _state.update { it.copy(videos = videos, error = error, loading = false) } selectVideo(first, state.value.startPositionMs, autoplay = true) AppLogger.info( "Episode load complete chapterId=${chapter.id} streams=${videos.size} " + "qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}", ) } private fun selectVideo(video: DbVideo?, startPositionMs: Long, autoplay: Boolean) { val previous = state.value.selectedVideo _state.update { it.copy(selectedVideo = video, startPositionMs = startPositionMs, autoplay = autoplay) } if (video == null) return val index = state.value.videos.indexOf(video).takeIf { it >= 0 } AppLogger.info( "Episode player handoff mangaId=${manga.id} chapterId=${chapter.id} " + "source=${source?.name ?: "unknown"} stream=${video.playerLogSummary(index)}", ) if (video != previous) loadSeekThumbnails(video) } /** Each failed stream is recorded once, so switching stops when every stream failed. */ private fun failOver(error: String, positionMs: Long) { val failed = state.value.selectedVideo ?: return failedStreams += failed.url val next = if (settings.db.value.features.player.switchStreamOnFailure) { nextFailoverVideo(state.value.videos, failedStreams) } else { null } if (next == null) { _effects.trySend(PlayerEffect.ShowNotice("Playback failed: $error")) return } AppLogger.warn("[player] stream failed ($error); switching to ${next.quality}") _effects.trySend(PlayerEffect.ShowNotice("Stream failed; switching to ${next.quality.ifBlank { "the next stream" }}")) selectVideo(next, positionMs.takeIf { it > 0L } ?: state.value.startPositionMs, autoplay = true) } private suspend fun loadAniSkipMarkers() { val malId = malId(repository.tracks()) // ChapterRecognition matches Mangayomi's parser, so "Episode 12 - Recovery point" yields 12; // naive digit-stripping returned 1212, which AniSkip rejected with HTTP 404. val episode = ChapterRecognition.parseEpisodeNumber(manga.name, chapter).toInt() settings.db.map { it.enableAniSkip == true }.distinctUntilChanged().collectLatest { enabled -> _state.update { it.copy(aniSkipMarkers = emptyList()) } if (!enabled || malId <= 0 || episode <= 0) return@collectLatest val markers = catchingNonCancellation { aniSkipMarkers(malId, episode) }.getOrDefault(emptyList()) _state.update { it.copy(aniSkipMarkers = markers) } } } private fun startCasting(event: PlayerEvent.StartCasting) { val current = state.value val video = current.selectedVideo?.takeIf { it.isCastable() } ?: current.videos.firstOrNull { it.isCastable() } if (video == null) { _effects.trySend(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast")) return } viewModelScope.launch { try { cast.connect(event.device) val subtitleIndex = video.subtitles.filter { it.file != null } .indexOfFirst { it.file == event.subtitleFile }.takeIf { it >= 0 } cast.loadQueue( listOf(video.toCastMedia(manga, chapter)), 0, event.startPositionMs, settings.db.value.playerSubtitleSettings.toCastTextStyle(), subtitleIndex, ) // Queue the following episodes as their streams resolve; extraction is per-episode work. val following = state.value.episodes.dropWhile { it.id != chapter.id }.drop(1).take(CastQueueAhead) for (episode in following) { val next = catchingNonCancellation { loadEpisodeVideos(episode) } .getOrNull()?.firstOrNull { it.isCastable() } ?: continue cast.append(listOf(next.toCastMedia(manga, episode))) } } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { AppLogger.error("[cast] start failed: ${failure.message.orEmpty()}") _effects.send( PlayerEffect.ShowNotice("Casting failed: ${failure.message.orEmpty().ifBlank { failure::class.simpleName.orEmpty() }}"), ) } } } /** One selected stream's preview loads, cancelled together on the next selection or [onCleared]. */ private fun newStreamScope() = CoroutineScope(viewModelScope.coroutineContext + SupervisorJob(viewModelScope.coroutineContext.job)) /** Replaces the seek-preview track with [video]'s; earlier stream loads are cancelled. */ private fun loadSeekThumbnails(video: DbVideo) { streamScope.cancel() streamScope = newStreamScope() spriteRequests.clear() _state.update { it.copy(seekThumbnails = emptyList(), seekSprites = emptyMap()) } val track = video.thumbnailTrack?.takeIf(String::isNotBlank) ?: return streamHeaders = video.headers.orEmpty() streamScope.launch { val content = fetch(track)?.decodeToString() ?: return@launch val cues = withContext(workDispatcher) { parseThumbnailVtt(content, track) } _state.update { it.copy(seekThumbnails = cues) } } } /** Loads a sprite sheet once per stream; failures are logged and not retried. */ private fun loadSeekSprite(url: String) { if (!spriteRequests.add(url)) return streamScope.launch { val bytes = fetch(url) ?: return@launch val image = withContext(workDispatcher) { catchingNonCancellation { bytes.decodeToImageBitmap() }.getOrNull() } ?: return@launch AppLogger.warn("[player] undecodable seek sprite") _state.update { it.copy(seekSprites = it.seekSprites + (url to image)) } } } private suspend fun fetch(url: String): ByteArray? { val response = catchingNonCancellation { http.request(HttpRequest(url, headers = streamHeaders)) } .onFailure { AppLogger.warn("[player] seek preview request failed: ${it.message.orEmpty()}") } .getOrNull() ?: return null if (response.statusCode !in 200..299) { AppLogger.warn("[player] seek preview request returned HTTP ${response.statusCode}") return null } return response.bodyBytes } private fun malId(tracks: List): Long { val titleTracks = tracks.filter { it.mangaId == manga.id } if (titleTracks.none { it.itemType == manga.itemType }) return 0L return titleTracks.firstOrNull { it.syncId == 1 }?.mediaId ?: 0L } private suspend fun loadEpisodeVideos(episode: Chapter): List { val titleSource = source ?: run { AppLogger.warn("Episode videoList skipped: no source chapterId=${episode.id} url=${redactUrlForLog(episode.url)}") return loadVideos(null, episode) } ExtensionLogger.log( titleSource.name, "videoList start sourceId=${titleSource.id} lang=${titleSource.lang} runtime=${titleSource.sourceCodeLanguage} " + "chapterId=${episode.id} url=${redactUrlForLog(episode.url)}", ) val startedAt = nowMillis() // Unlike pages and details, videos have no database-backed cache, so there is no fallback: // do not pass a failed extension's HTML episode page to the media player. return catchingNonCancellation { loadVideos(titleSource, episode) } .onSuccess { videos -> ExtensionLogger.log( titleSource.name, "videoList returned count=${videos.size} qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}", ) } .onFailure { ExtensionLogger.error(titleSource.name, "videoList", it) } .getOrThrow() } } /** Following episodes resolved and appended to a new cast queue. */ private const val CastQueueAhead = 2 private fun DbVideo.playerLogSummary(index: Int?): String { val indexPart = index?.let { "index=$it " }.orEmpty() return "${indexPart}quality='${quality.ifBlank { "Auto" }}' url=${redactUrlForLog(url)} " + "original=${redactUrlForLog(originalUrl)} headers=${headers?.size ?: 0} subtitles=${subtitles.size} audios=${audios.size}" } private fun List.qualityLogSummary(limit: Int = 8): String { if (isEmpty()) return "none" val base = take(limit).joinToString(prefix = "[", postfix = "]") { it.quality.ifBlank { "Auto" } } return if (size > limit) "$base +${size - limit} more" else base }