package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.util.sha256 import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.media.VideoFrameExtractor import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.withContext import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo /** * Frame-derived artwork for local anime that ships none: a cover for titles without any cover, and a * thumbnail for episodes without a preview. One decode at a time, at most [maxDecodesPerRun] per run. * Frames are cached under `/.yokan-artwork`, keyed by the episode's virtual path, size and * modification time, so later runs reuse them instead of decoding again. Existing artwork always wins. */ class LocalVideoArtwork( private val database: YokanDatabase, private val files: LocalFileService, private val library: LocalLibraryService, private val extractor: VideoFrameExtractor, private val maxDecodesPerRun: Int = 12, ) { private val running = Mutex() // ponytail: failures are remembered for this session only; persist markers if restarts re-decoding broken files matters. private val failed = mutableSetOf() private var budget = 0 /** False when a run is already in progress; that run (or the next scan) picks up new episodes. */ suspend fun generate(): Boolean { if (!running.tryLock()) return false try { budget = maxDecodesPerRun files.prepare() val settings = database.settings() val titles = database.mangas(DbItemType.Anime).filter(DbManga::isLocalAnime) for (title in titles) { catchingNonCancellation { decorate(title, titles, settings) } .onFailure { AppLogger.warn("[local] video artwork failed for title ${title.id}: ${it.message.orEmpty()}") } } } finally { running.unlock() } return true } private suspend fun decorate(title: DbManga, titles: List, settings: DbSettings) { val episodes = episodes(title.id) var needsCover = title.needsCover() for (episode in episodes) { val needsThumbnail = episode.thumbnailUrl == null if (!needsThumbnail && !needsCover) continue val frame = frame(episode, settings) ?: continue if (needsThumbnail) { val url = files.readableUrl(frame) write { val current = database.chapter(episode.id) ?: return@write if (current.mangaId == title.id && current.archivePath == episode.archivePath && current.thumbnailUrl == null) { database.upsertChapter(current.copy(thumbnailUrl = url)) } } } if (needsCover) { setCover(title.id, frame) needsCover = false } } // Seasons parents own no episodes: their first season's first frame stands in. if (needsCover && episodes.isEmpty()) { val season = titles.filter { it.parentId == title.id }.minByOrNull { it.id } ?: return episodes(season.id).firstNotNullOfOrNull { frame(it, settings) }?.let { setCover(title.id, it) } } } private fun episodes(titleId: Long): List = database.chapters(titleId).sortedWith(compareBy({ it.season ?: 0 }, { it.number ?: Double.MAX_VALUE }, { it.archivePath })) private suspend fun setCover(titleId: Long, frame: String) { val bytes = files.readBytesAsync(frame, MaxFrameBytes.toLong()) write { val current = database.manga(titleId) ?: return@write // A cover the user picked, a scanned cover file or metadata artwork that arrived meanwhile wins. if (current.isLocalAnime() && current.needsCover()) database.upsertManga(current.copy(customCoverImage = bytes)) } } /** The scanner and entry management hold this lock, so writes never interleave with a scan's read-modify-write. */ private suspend fun write(block: () -> Unit) = library.withOperationLock { database.batch(block) } /** Path of the cached frame, decoding it when absent; null when unavailable, failed or over budget. */ private suspend fun frame(episode: DbChapter, settings: DbSettings): String? { val video = resolveLocalEpisodeVideo(episode.archivePath, files, settings) ?: return null val name = video.substringAfterLast('/') val fingerprint = files.listFiles(video.substringBeforeLast('/', "")).firstOrNull { it.name == name } val key = sha256("${episode.archivePath}|${fingerprint?.sizeBytes}|${fingerprint?.lastModified}".encodeToByteArray()).toHexString().take(32) val target = "${files.downloadRoot.trimEnd('/')}/$ArtworkDirectory/$key.jpg" if (files.exists(target)) return target if (key in failed || budget <= 0) return null budget-- val bytes = catchingNonCancellation { extractor.extractJpeg(files.readableUrl(video), MaxFrameDimension) } .onFailure { AppLogger.warn("[local] frame extraction failed: ${it.message.orEmpty()}") } .getOrNull()?.takeIf { it.size in 1..MaxFrameBytes } if (bytes == null) { failed += key return null } val partial = "$target.part" try { files.writeBytesAsync(partial, bytes) check(files.promoteAsync(partial, target)) { "Artwork cache could not be written" } } finally { withContext(NonCancellable) { if (files.exists(partial)) files.deleteRecursivelyAsync(partial) } } return target } internal companion object { const val ArtworkDirectory = ".yokan-artwork" const val MaxFrameDimension = 512 const val MaxFrameBytes = 1024 * 1024 } } private fun DbManga.isLocalAnime(): Boolean = isLocalArchive && source == "local" && itemType == DbItemType.Anime private fun DbManga.needsCover(): Boolean = customCoverImage == null && imageUrl.isNullOrBlank() && customCoverFromTracker.isNullOrBlank()