package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService import eu.friedcutlet.yokan.services.files.JvmLocalFileService import eu.friedcutlet.yokan.services.media.MpvVideoFrameExtractor import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController import eu.friedcutlet.yokan.services.media.player.NoopMediaStreamProxy import eu.friedcutlet.yokan.services.media.player.createMpvMediaPlayerController import io.github.kmpmpv.MpvPlayer import java.io.ByteArrayInputStream import java.io.File import java.nio.file.Files import javax.imageio.ImageIO import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.junit.Assume.assumeTrue import kotlin.test.* /** Real files, the real scanner, the player's resolution path and (when installed or bundled) real libmpv. */ class LocalVideoDesktopTest { @Test fun scannedLocalVideosResolveToTheirFilesAndPlayInTheMpvController() = runBlocking { withLibrary { library -> val urls = library.playableUrls() assertEquals(library.expectedUrls.toSet(), urls.toSet()) assumeLibmpv() urls.forEach { url -> val controller = createMpvMediaPlayerController( MediaPlayerConfiguration(useMpvConfig = false, hwdecMode = "no"), NoopMediaStreamProxy, mapOf("vo" to "libmpv", "ao" to "null"), ) as MpvMediaPlayerController try { controller.withSoftwareRendering { renderer -> // Like the desktop surface: the render context exists before the file loads. renderer.renderFrame(1, 1) controller.load(url) withTimeout(20_000) { while (controller.durationMs() <= 0L) delay(20) } assertTrue(controller.durationMs() in 800L..1200L, "duration of $url: ${controller.durationMs()}") val deadline = System.currentTimeMillis() + 10_000 var red = false while (!red && System.currentTimeMillis() < deadline) { val frame = renderer.renderFrame(16, 12) val center = 6 * frame.strideBytes + 8 * 4 val (b, g, r) = Triple(frame.pixels[center].toInt() and 0xff, frame.pixels[center + 1].toInt() and 0xff, frame.pixels[center + 2].toInt() and 0xff) red = r > 200 && g < 60 && b < 60 if (!red) delay(50) } assertTrue(red, "the decoded red frame of $url was never rendered") } } finally { controller.releaseAndJoin() } } } } @Test fun libmpvExtractsBoundedRedJpegFramesFromMkvAndMp4() = runBlocking { withLibrary { library -> assumeLibmpv() val extractor = MpvVideoFrameExtractor() library.expectedUrls.forEach { url -> assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 512), url), 64, 48) assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 32), url), 32, 24) } assertNull(extractor.extractJpeg("file://${library.root.path}/missing.mkv", 512)) } } @Test fun artworkRunGivesTheTitleACoverAndEpisodesThumbnailsFromRealFrames() = runBlocking { withLibrary { library -> assumeLibmpv() val artwork = LocalVideoArtwork(library.db, library.files, library.scanner, MpvVideoFrameExtractor()) assertTrue(artwork.generate()) val title = library.db.mangas().single() assertRedJpeg(assertNotNull(title.customCoverImage), 64, 48) library.db.chapters(title.id).forEach { episode -> val thumbnail = assertNotNull(episode.thumbnailUrl).removePrefix("file://") assertTrue(thumbnail.startsWith(File(library.files.downloadRoot, ".yokan-artwork").path), thumbnail) assertRedJpeg(File(thumbnail).readBytes(), 64, 48) } // A rescan keeps the frame artwork and a new run reuses the cache. library.scanner.scan() val cached = File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() } assertTrue(LocalVideoArtwork(library.db, library.files, library.scanner, { _, _ -> error("must not decode") }).generate()) assertEquals(cached, File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() }) assertNotNull(library.db.mangas().single().customCoverImage) } } private class Library(val root: File, val files: JvmLocalFileService, val db: InMemoryYokanDatabase, val scanner: DefaultLocalLibraryService) { // '%20' in a name: mpv percent-decodes file:// URLs, so the player must hand it the raw path. val expectedUrls = listOf("Episode 1.mkv", "Episode 2 100%20.mp4").map { "file://${File(root, "Show/$it").path}" } suspend fun playableUrls(): List { val factory = ProfileReaderContentTest.RuntimeFactory(db, "local") val owner = SupervisorJob() val content = ProfileReaderContent( ProfileId.Default, db, factory, ChapterPageResolver(DefaultYokanRepository(db), db, factory), files, JvmLocalArchiveService(files.cacheRoot), CoroutineScope(owner), ) return try { val title = db.mangas().single() db.chapters(title.id).sortedBy { it.number }.map { stored -> val episode = Chapter(id = stored.id, mangaId = title.id, name = stored.name.orEmpty(), url = stored.url, archivePath = stored.archivePath) content.videos(null, episode).single().url }.also { assertEquals(0, factory.created) } } finally { content.closeAndJoin(); owner.cancelAndJoin() } } } private suspend fun withLibrary(block: suspend (Library) -> Unit) { val temp = Files.createTempDirectory("yokan-local-video").toFile() try { val root = File(temp, "anime") File(root, "Show").mkdirs() File(root, "Show/Episode 1.mkv").writeBytes(RedVideoFixtures.mkv) File(root, "Show/Episode 2 100%20.mp4").writeBytes(RedVideoFixtures.mp4) val files = JvmLocalFileService(File(temp, "downloads").path, File(temp, "backups").path, File(temp, "cache").path) val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root.path))))) val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot)) scanner.scan() assertEquals(2, db.chapters(db.mangas().single().id).size) block(Library(root, files, db, scanner)) } finally { temp.deleteRecursively() } } private suspend fun assumeLibmpv() { val probe = runCatching { MpvPlayer.create() } assumeTrue("libmpv is neither bundled nor installed on this machine: ${probe.exceptionOrNull()}", probe.isSuccess) probe.getOrNull()?.release() } private fun assertRedJpeg(bytes: ByteArray, width: Int, height: Int) { val image = assertNotNull(ImageIO.read(ByteArrayInputStream(bytes)), "not a decodable image") assertEquals(width to height, image.width to image.height) val pixel = java.awt.Color(image.getRGB(width / 2, height / 2)) assertTrue(pixel.red > 200 && pixel.green < 60 && pixel.blue < 60, "center pixel $pixel") } }