LocalVideoArtwork.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoArtwork.kt
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.database.DbItemType5import eu.friedcutlet.yokan.database.DbManga6import eu.friedcutlet.yokan.database.DbSettings7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.util.sha25610import eu.friedcutlet.yokan.services.files.LocalFileService11import eu.friedcutlet.yokan.services.logging.AppLogger12import eu.friedcutlet.yokan.services.media.VideoFrameExtractor13import kotlinx.coroutines.NonCancellable14import kotlinx.coroutines.sync.Mutex15import kotlinx.coroutines.withContext16import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo1718/**19 * Frame-derived artwork for local anime that ships none: a cover for titles without any cover, and a20 * thumbnail for episodes without a preview. One decode at a time, at most [maxDecodesPerRun] per run.21 * Frames are cached under `<downloadRoot>/.yokan-artwork`, keyed by the episode's virtual path, size and22 * modification time, so later runs reuse them instead of decoding again. Existing artwork always wins.23 */24class LocalVideoArtwork(25 private val database: YokanDatabase,26 private val files: LocalFileService,27 private val library: LocalLibraryService,28 private val extractor: VideoFrameExtractor,29 private val maxDecodesPerRun: Int = 12,30) {31 private val running = Mutex()32 // ponytail: failures are remembered for this session only; persist markers if restarts re-decoding broken files matters.33 private val failed = mutableSetOf<String>()34 private var budget = 03536 /** False when a run is already in progress; that run (or the next scan) picks up new episodes. */37 suspend fun generate(): Boolean {38 if (!running.tryLock()) return false39 try {40 budget = maxDecodesPerRun41 files.prepare()42 val settings = database.settings()43 val titles = database.mangas(DbItemType.Anime).filter(DbManga::isLocalAnime)44 for (title in titles) {45 catchingNonCancellation { decorate(title, titles, settings) }46 .onFailure { AppLogger.warn("[local] video artwork failed for title ${title.id}: ${it.message.orEmpty()}") }47 }48 } finally { running.unlock() }49 return true50 }5152 private suspend fun decorate(title: DbManga, titles: List<DbManga>, settings: DbSettings) {53 val episodes = episodes(title.id)54 var needsCover = title.needsCover()55 for (episode in episodes) {56 val needsThumbnail = episode.thumbnailUrl == null57 if (!needsThumbnail && !needsCover) continue58 val frame = frame(episode, settings) ?: continue59 if (needsThumbnail) {60 val url = files.readableUrl(frame)61 write {62 val current = database.chapter(episode.id) ?: return@write63 if (current.mangaId == title.id && current.archivePath == episode.archivePath && current.thumbnailUrl == null) {64 database.upsertChapter(current.copy(thumbnailUrl = url))65 }66 }67 }68 if (needsCover) {69 setCover(title.id, frame)70 needsCover = false71 }72 }73 // Seasons parents own no episodes: their first season's first frame stands in.74 if (needsCover && episodes.isEmpty()) {75 val season = titles.filter { it.parentId == title.id }.minByOrNull { it.id } ?: return76 episodes(season.id).firstNotNullOfOrNull { frame(it, settings) }?.let { setCover(title.id, it) }77 }78 }7980 private fun episodes(titleId: Long): List<DbChapter> =81 database.chapters(titleId).sortedWith(compareBy<DbChapter>({ it.season ?: 0 }, { it.number ?: Double.MAX_VALUE }, { it.archivePath }))8283 private suspend fun setCover(titleId: Long, frame: String) {84 val bytes = files.readBytesAsync(frame, MaxFrameBytes.toLong())85 write {86 val current = database.manga(titleId) ?: return@write87 // A cover the user picked, a scanned cover file or metadata artwork that arrived meanwhile wins.88 if (current.isLocalAnime() && current.needsCover()) database.upsertManga(current.copy(customCoverImage = bytes))89 }90 }9192 /** The scanner and entry management hold this lock, so writes never interleave with a scan's read-modify-write. */93 private suspend fun write(block: () -> Unit) = library.withOperationLock { database.batch(block) }9495 /** Path of the cached frame, decoding it when absent; null when unavailable, failed or over budget. */96 private suspend fun frame(episode: DbChapter, settings: DbSettings): String? {97 val video = resolveLocalEpisodeVideo(episode.archivePath, files, settings) ?: return null98 val name = video.substringAfterLast('/')99 val fingerprint = files.listFiles(video.substringBeforeLast('/', "")).firstOrNull { it.name == name }100 val key = sha256("${episode.archivePath}|${fingerprint?.sizeBytes}|${fingerprint?.lastModified}".encodeToByteArray()).toHexString().take(32)101 val target = "${files.downloadRoot.trimEnd('/')}/$ArtworkDirectory/$key.jpg"102 if (files.exists(target)) return target103 if (key in failed || budget <= 0) return null104 budget--105 val bytes = catchingNonCancellation { extractor.extractJpeg(files.readableUrl(video), MaxFrameDimension) }106 .onFailure { AppLogger.warn("[local] frame extraction failed: ${it.message.orEmpty()}") }107 .getOrNull()?.takeIf { it.size in 1..MaxFrameBytes }108 if (bytes == null) {109 failed += key110 return null111 }112 val partial = "$target.part"113 try {114 files.writeBytesAsync(partial, bytes)115 check(files.promoteAsync(partial, target)) { "Artwork cache could not be written" }116 } finally {117 withContext(NonCancellable) { if (files.exists(partial)) files.deleteRecursivelyAsync(partial) }118 }119 return target120 }121122 internal companion object {123 const val ArtworkDirectory = ".yokan-artwork"124 const val MaxFrameDimension = 512125 const val MaxFrameBytes = 1024 * 1024126 }127}128129private fun DbManga.isLocalAnime(): Boolean = isLocalArchive && source == "local" && itemType == DbItemType.Anime130131private fun DbManga.needsCover(): Boolean =132 customCoverImage == null && imageUrl.isNullOrBlank() && customCoverFromTracker.isNullOrBlank()133