Yokan / rebuild
Course 1 8624561

PlayerViewModel.kt

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

implementation384 lines
1package eu.friedcutlet.yokan.ui.screens.player23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.LibraryIndexStore6import eu.friedcutlet.yokan.data.SettingsStore7import eu.friedcutlet.yokan.data.YokanRepository8import eu.friedcutlet.yokan.database.DbCustomButton9import eu.friedcutlet.yokan.database.DbSettings10import eu.friedcutlet.yokan.database.DbVideo11import eu.friedcutlet.yokan.database.isIncognitoFor12import eu.friedcutlet.yokan.domain.Chapter13import eu.friedcutlet.yokan.domain.ChapterRecognition14import eu.friedcutlet.yokan.domain.Manga15import eu.friedcutlet.yokan.domain.Source16import eu.friedcutlet.yokan.domain.Track17import eu.friedcutlet.yokan.services.catchingNonCancellation18import eu.friedcutlet.yokan.services.extensions.ExtensionLogger19import eu.friedcutlet.yokan.services.http.HttpRequest20import eu.friedcutlet.yokan.services.http.HttpService21import eu.friedcutlet.yokan.services.library.readingChapterSequence22import eu.friedcutlet.yokan.services.library.sortedChapters23import eu.friedcutlet.yokan.services.library.visibleChapters24import eu.friedcutlet.yokan.services.logging.AppLogger25import eu.friedcutlet.yokan.services.logging.redactUrlForLog26import eu.friedcutlet.yokan.services.media.AniSkipMarker27import eu.friedcutlet.yokan.services.media.cast.CastController28import eu.friedcutlet.yokan.services.media.player.externalPlayerChoices29import eu.friedcutlet.yokan.services.media.player.nextFailoverVideo30import eu.friedcutlet.yokan.services.media.player.parseThumbnailVtt31import eu.friedcutlet.yokan.util.nowMillis32import kotlinx.coroutines.CancellationException33import kotlinx.coroutines.CoroutineDispatcher34import kotlinx.coroutines.CoroutineScope35import kotlinx.coroutines.Dispatchers36import kotlinx.coroutines.cancel37import kotlinx.coroutines.job38import kotlinx.coroutines.SupervisorJob39import kotlinx.coroutines.channels.Channel40import kotlinx.coroutines.flow.Flow41import kotlinx.coroutines.flow.MutableStateFlow42import kotlinx.coroutines.flow.StateFlow43import kotlinx.coroutines.flow.asStateFlow44import kotlinx.coroutines.flow.collectLatest45import kotlinx.coroutines.flow.combine46import kotlinx.coroutines.flow.distinctUntilChanged47import kotlinx.coroutines.flow.flowOn48import kotlinx.coroutines.flow.map49import kotlinx.coroutines.flow.receiveAsFlow50import kotlinx.coroutines.flow.update51import kotlinx.coroutines.launch52import kotlinx.coroutines.withContext53import org.jetbrains.compose.resources.decodeToImageBitmap5455/** Player ordering stays user-controlled while release selection matches the readers. */56internal fun playerEpisodeSequence(57    manga: Manga,58    currentChapterId: Long,59    all: List<Chapter>,60    db: DbSettings,61    downloadedIds: Set<Long>,62): List<Chapter> = sortedChapters(63    manga, readingChapterSequence(manga, currentChapterId, all, db, downloadedIds), db,64)6566/**67 * The player's streams, library reads, progress writes, AniSkip markers and casting. Work that68 * needs the media controller (loading it, tracks, chrome, screenshots) stays in [AnimePlayerScreen].69 */70internal class PlayerViewModel(71    private val manga: Manga,72    private val chapter: Chapter,73    private val repository: YokanRepository,74    private val settings: SettingsStore,75    libraryIndex: LibraryIndexStore,76    private val http: HttpService,77    private val loadVideos: suspend (Source?, Chapter) -> List<DbVideo>,78    private val aniSkipMarkers: suspend (malId: Long, episode: Int) -> List<AniSkipMarker>,79    /** Hands [DbVideo] to the external player `playerId` (blank: the platform default); false when none opened. */80    private val openExternalPlayer: (video: DbVideo, playerId: String) -> Boolean,81    private val cast: CastController,82    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,83) : ViewModel() {84    // ponytail: sprites stay decoded for the stream's lifetime; a few sheets per episode in practice.85    private var streamScope = newStreamScope()86    private var streamHeaders: Map<String, String> = emptyMap()87    private val spriteRequests = mutableSetOf<String>()88    /** Streams of this episode that failed; failover tries each remaining one once. */89    private val failedStreams = mutableSetOf<String>()90    private val source: Source? = manga.sourceId?.let(repository::source)91        ?: repository.sources(manga.itemType).firstOrNull {92            it.name.equals(manga.source, ignoreCase = true) && it.lang.equals(manga.lang, ignoreCase = true)93        }9495    private val _state = MutableStateFlow(96        PlayerState(97            startPositionMs = savedVideoPositionMs(98                lastPageRead = chapter.lastPageRead,99                isRead = chapter.isRead,100                incognitoMode = settings.db.value.isIncognitoFor(manga.sourceId),101            ),102            castUsesSystemPicker = cast.usesSystemPicker,103        ),104    )105    val state: StateFlow<PlayerState> = _state.asStateFlow()106107    private val _effects = Channel<PlayerEffect>(Channel.BUFFERED)108    val effects: Flow<PlayerEffect> = _effects.receiveAsFlow()109110    init {111        repository.chapterOpened(chapter.id)112        viewModelScope.launch {113            combine(libraryIndex.index, settings.db) { index, db ->114                val all = index.chapters(manga.id)115                playerEpisodeSequence(manga, chapter.id, all, db, index.downloadedChapterIds) to116                    visibleChapters(manga, all, db, index.downloadedChapterIds)117            }118                .flowOn(workDispatcher)119                .collect { (episodes, visible) -> _state.update { it.copy(episodes = episodes, visibleEpisodes = visible) } }120        }121        viewModelScope.launch {122            repository.snapshots123                .map { it.customButtons }124                .distinctUntilChanged()125                .collect { buttons -> _state.update { it.copy(customButtons = buttons.sortedBy(DbCustomButton::position)) } }126        }127        viewModelScope.launch {128            combine(cast.status, cast.isSupported, cast.devices) { status, supported, devices ->129                Triple(status, supported, devices)130            }.collect { (status, supported, devices) ->131                _state.update { it.copy(castStatus = status, castSupported = supported, castDevices = devices) }132            }133        }134        viewModelScope.launch { loadStreams() }135        viewModelScope.launch { loadAniSkipMarkers() }136    }137138    override fun onCleared() {139        repository.chapterClosed(chapter.id)140        super.onCleared()141    }142143    fun onEvent(event: PlayerEvent) {144        when (event) {145            is PlayerEvent.SwitchEpisode -> adjacentEpisode(event.offset)?.let { _effects.trySend(PlayerEffect.OpenEpisode(it)) }146            is PlayerEvent.SavePosition -> savePosition(event.positionMs, event.durationMs)147            is PlayerEvent.LoadSeekSprite -> loadSeekSprite(event.url)148            is PlayerEvent.SelectVideo -> selectVideo(event.video, event.startPositionMs, event.autoplay)149            is PlayerEvent.PlaybackFailed -> failOver(event.error, event.positionMs)150            // Launched: proxying through a retired reader throws CancellationException.151            is PlayerEvent.OpenExternalPlayer -> viewModelScope.launch {152                openExternalPlayer(event.video, settings.db.value.features.player.externalPlayer)153            }154            is PlayerEvent.SetCastDiscovery -> if (event.active) cast.startDiscovery() else cast.stopDiscovery()155            is PlayerEvent.StartCasting -> startCasting(event)156            PlayerEvent.StopCasting -> viewModelScope.launch { catchingNonCancellation { cast.disconnect() } }157            PlayerEvent.CastPlayPause -> if (state.value.castStatus?.playing == true) cast.pause() else cast.play()158            is PlayerEvent.CastSeek -> cast.seekTo(event.positionMs)159            PlayerEvent.CastPrevious -> cast.previous()160            PlayerEvent.CastNext -> cast.next()161            is PlayerEvent.CastJumpTo -> cast.jumpTo(event.index)162        }163    }164165    /** The episode [offset] steps from the current one in title order, or null past either end. */166    private fun adjacentEpisode(offset: Int): Chapter? {167        val all = state.value.episodes168        val index = all.indexOfFirst { it.id == chapter.id }169        return if (index < 0) null else all.getOrNull(index + offset)170    }171172    /** Persists the watched position on leave so History resumes mid-episode. */173    private fun savePosition(positionMs: Long, durationMs: Long) {174        val db = settings.db.value175        if (!shouldSaveVideoPosition(chapter.isRead, db.isIncognitoFor(manga.sourceId), positionMs)) return176        repository.setChaptersRead(177            chapterIds = setOf(chapter.id),178            isRead = isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType),179            lastPageRead = positionMs.toString(),180            // Anime watch time is tracked elsewhere; counting it on every exit would inflate the stat.181            readingTimeSeconds = 0,182        )183        if (isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType)) repository.recordChapterConsumption(setOf(chapter.id))184    }185186    private suspend fun loadStreams() {187        val startedAt = nowMillis()188        AppLogger.info(189            "Episode load start mangaId=${manga.id} manga='${manga.name}' chapterId=${chapter.id} " +190                "chapter='${chapter.name}' source=${source?.name ?: "unknown"} url=${redactUrlForLog(chapter.url)}",191        )192        var error: String? = null193        val videos = catchingNonCancellation { loadEpisodeVideos(chapter) }194            .onFailure { throwable ->195                error = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }196                AppLogger.error("Episode load failed chapterId=${chapter.id}: ${error.orEmpty()}")197            }198            .getOrElse { emptyList() }199        if (videos.isEmpty() && error == null) {200            error = "No streams were returned by ${source?.name ?: "this source"}."201            AppLogger.warn("Episode load returned no streams chapterId=${chapter.id}")202        }203        val first = videos.firstOrNull()204        val preferences = settings.db.value.features.player205        if (first != null && preferences.alwaysUseExternalPlayer && externalPlayerChoices().isNotEmpty()) {206            if (openExternalPlayer(first, preferences.externalPlayer)) {207                _state.update { it.copy(videos = videos, loading = false) }208                _effects.send(PlayerEffect.Exit)209                return210            }211            error = "The external player could not be opened; playing here instead."212        }213        _state.update { it.copy(videos = videos, error = error, loading = false) }214        selectVideo(first, state.value.startPositionMs, autoplay = true)215        AppLogger.info(216            "Episode load complete chapterId=${chapter.id} streams=${videos.size} " +217                "qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}",218        )219    }220221    private fun selectVideo(video: DbVideo?, startPositionMs: Long, autoplay: Boolean) {222        val previous = state.value.selectedVideo223        _state.update { it.copy(selectedVideo = video, startPositionMs = startPositionMs, autoplay = autoplay) }224        if (video == null) return225        val index = state.value.videos.indexOf(video).takeIf { it >= 0 }226        AppLogger.info(227            "Episode player handoff mangaId=${manga.id} chapterId=${chapter.id} " +228                "source=${source?.name ?: "unknown"} stream=${video.playerLogSummary(index)}",229        )230        if (video != previous) loadSeekThumbnails(video)231    }232233    /** Each failed stream is recorded once, so switching stops when every stream failed. */234    private fun failOver(error: String, positionMs: Long) {235        val failed = state.value.selectedVideo ?: return236        failedStreams += failed.url237        val next = if (settings.db.value.features.player.switchStreamOnFailure) {238            nextFailoverVideo(state.value.videos, failedStreams)239        } else {240            null241        }242        if (next == null) {243            _effects.trySend(PlayerEffect.ShowNotice("Playback failed: $error"))244            return245        }246        AppLogger.warn("[player] stream failed ($error); switching to ${next.quality}")247        _effects.trySend(PlayerEffect.ShowNotice("Stream failed; switching to ${next.quality.ifBlank { "the next stream" }}"))248        selectVideo(next, positionMs.takeIf { it > 0L } ?: state.value.startPositionMs, autoplay = true)249    }250251    private suspend fun loadAniSkipMarkers() {252        val malId = malId(repository.tracks())253        // ChapterRecognition matches Mangayomi's parser, so "Episode 12 - Recovery point" yields 12;254        // naive digit-stripping returned 1212, which AniSkip rejected with HTTP 404.255        val episode = ChapterRecognition.parseEpisodeNumber(manga.name, chapter).toInt()256        settings.db.map { it.enableAniSkip == true }.distinctUntilChanged().collectLatest { enabled ->257            _state.update { it.copy(aniSkipMarkers = emptyList()) }258            if (!enabled || malId <= 0 || episode <= 0) return@collectLatest259            val markers = catchingNonCancellation { aniSkipMarkers(malId, episode) }.getOrDefault(emptyList())260            _state.update { it.copy(aniSkipMarkers = markers) }261        }262    }263264    private fun startCasting(event: PlayerEvent.StartCasting) {265        val current = state.value266        val video = current.selectedVideo?.takeIf { it.isCastable() } ?: current.videos.firstOrNull { it.isCastable() }267        if (video == null) {268            _effects.trySend(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast"))269            return270        }271        viewModelScope.launch {272            try {273                cast.connect(event.device)274                val subtitleIndex = video.subtitles.filter { it.file != null }275                    .indexOfFirst { it.file == event.subtitleFile }.takeIf { it >= 0 }276                cast.loadQueue(277                    listOf(video.toCastMedia(manga, chapter)), 0, event.startPositionMs,278                    settings.db.value.playerSubtitleSettings.toCastTextStyle(), subtitleIndex,279                )280                // Queue the following episodes as their streams resolve; extraction is per-episode work.281                val following = state.value.episodes.dropWhile { it.id != chapter.id }.drop(1).take(CastQueueAhead)282                for (episode in following) {283                    val next = catchingNonCancellation { loadEpisodeVideos(episode) }284                        .getOrNull()?.firstOrNull { it.isCastable() } ?: continue285                    cast.append(listOf(next.toCastMedia(manga, episode)))286                }287            } catch (cancelled: CancellationException) {288                throw cancelled289            } catch (failure: Throwable) {290                AppLogger.error("[cast] start failed: ${failure.message.orEmpty()}")291                _effects.send(292                    PlayerEffect.ShowNotice("Casting failed: ${failure.message.orEmpty().ifBlank { failure::class.simpleName.orEmpty() }}"),293                )294            }295        }296    }297298    /** One selected stream's preview loads, cancelled together on the next selection or [onCleared]. */299    private fun newStreamScope() =300        CoroutineScope(viewModelScope.coroutineContext + SupervisorJob(viewModelScope.coroutineContext.job))301302    /** Replaces the seek-preview track with [video]'s; earlier stream loads are cancelled. */303    private fun loadSeekThumbnails(video: DbVideo) {304        streamScope.cancel()305        streamScope = newStreamScope()306        spriteRequests.clear()307        _state.update { it.copy(seekThumbnails = emptyList(), seekSprites = emptyMap()) }308        val track = video.thumbnailTrack?.takeIf(String::isNotBlank) ?: return309        streamHeaders = video.headers.orEmpty()310        streamScope.launch {311            val content = fetch(track)?.decodeToString() ?: return@launch312            val cues = withContext(workDispatcher) { parseThumbnailVtt(content, track) }313            _state.update { it.copy(seekThumbnails = cues) }314        }315    }316317    /** Loads a sprite sheet once per stream; failures are logged and not retried. */318    private fun loadSeekSprite(url: String) {319        if (!spriteRequests.add(url)) return320        streamScope.launch {321            val bytes = fetch(url) ?: return@launch322            val image = withContext(workDispatcher) {323                catchingNonCancellation { bytes.decodeToImageBitmap() }.getOrNull()324            } ?: return@launch AppLogger.warn("[player] undecodable seek sprite")325            _state.update { it.copy(seekSprites = it.seekSprites + (url to image)) }326        }327    }328329    private suspend fun fetch(url: String): ByteArray? {330        val response = catchingNonCancellation { http.request(HttpRequest(url, headers = streamHeaders)) }331            .onFailure { AppLogger.warn("[player] seek preview request failed: ${it.message.orEmpty()}") }332            .getOrNull() ?: return null333        if (response.statusCode !in 200..299) {334            AppLogger.warn("[player] seek preview request returned HTTP ${response.statusCode}")335            return null336        }337        return response.bodyBytes338    }339340    private fun malId(tracks: List<Track>): Long {341        val titleTracks = tracks.filter { it.mangaId == manga.id }342        if (titleTracks.none { it.itemType == manga.itemType }) return 0L343        return titleTracks.firstOrNull { it.syncId == 1 }?.mediaId ?: 0L344    }345346    private suspend fun loadEpisodeVideos(episode: Chapter): List<DbVideo> {347        val titleSource = source ?: run {348            AppLogger.warn("Episode videoList skipped: no source chapterId=${episode.id} url=${redactUrlForLog(episode.url)}")349            return loadVideos(null, episode)350        }351        ExtensionLogger.log(352            titleSource.name,353            "videoList start sourceId=${titleSource.id} lang=${titleSource.lang} runtime=${titleSource.sourceCodeLanguage} " +354                "chapterId=${episode.id} url=${redactUrlForLog(episode.url)}",355        )356        val startedAt = nowMillis()357        // Unlike pages and details, videos have no database-backed cache, so there is no fallback:358        // do not pass a failed extension's HTML episode page to the media player.359        return catchingNonCancellation { loadVideos(titleSource, episode) }360            .onSuccess { videos ->361                ExtensionLogger.log(362                    titleSource.name,363                    "videoList returned count=${videos.size} qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}",364                )365            }366            .onFailure { ExtensionLogger.error(titleSource.name, "videoList", it) }367            .getOrThrow()368    }369}370371/** Following episodes resolved and appended to a new cast queue. */372private const val CastQueueAhead = 2373374private fun DbVideo.playerLogSummary(index: Int?): String {375    val indexPart = index?.let { "index=$it " }.orEmpty()376    return "${indexPart}quality='${quality.ifBlank { "Auto" }}' url=${redactUrlForLog(url)} " +377        "original=${redactUrlForLog(originalUrl)} headers=${headers?.size ?: 0} subtitles=${subtitles.size} audios=${audios.size}"378}379380private fun List<DbVideo>.qualityLogSummary(limit: Int = 8): String {381    if (isEmpty()) return "none"382    val base = take(limit).joinToString(prefix = "[", postfix = "]") { it.quality.ifBlank { "Auto" } }383    return if (size > limit) "$base +${size - limit} more" else base384}385

Search chapters, reference and source filenames.