Yokan / rebuild
Course 1 8624561

LocalVideoDesktopTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoDesktopTest.kt

test / fixture149 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.data.DefaultYokanRepository5import eu.friedcutlet.yokan.database.*6import eu.friedcutlet.yokan.domain.Chapter7import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver8import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent9import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest10import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService11import eu.friedcutlet.yokan.services.files.JvmLocalFileService12import eu.friedcutlet.yokan.services.media.MpvVideoFrameExtractor13import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration14import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController15import eu.friedcutlet.yokan.services.media.player.NoopMediaStreamProxy16import eu.friedcutlet.yokan.services.media.player.createMpvMediaPlayerController17import io.github.kmpmpv.MpvPlayer18import java.io.ByteArrayInputStream19import java.io.File20import java.nio.file.Files21import javax.imageio.ImageIO22import kotlinx.coroutines.CoroutineScope23import kotlinx.coroutines.SupervisorJob24import kotlinx.coroutines.cancelAndJoin25import kotlinx.coroutines.delay26import kotlinx.coroutines.runBlocking27import kotlinx.coroutines.withTimeout28import org.junit.Assume.assumeTrue29import kotlin.test.*3031/** Real files, the real scanner, the player's resolution path and (when installed or bundled) real libmpv. */32class LocalVideoDesktopTest {33    @Test fun scannedLocalVideosResolveToTheirFilesAndPlayInTheMpvController() = runBlocking {34        withLibrary { library ->35            val urls = library.playableUrls()36            assertEquals(library.expectedUrls.toSet(), urls.toSet())37            assumeLibmpv()38            urls.forEach { url ->39                val controller = createMpvMediaPlayerController(40                    MediaPlayerConfiguration(useMpvConfig = false, hwdecMode = "no"),41                    NoopMediaStreamProxy,42                    mapOf("vo" to "libmpv", "ao" to "null"),43                ) as MpvMediaPlayerController44                try {45                    controller.withSoftwareRendering { renderer ->46                        // Like the desktop surface: the render context exists before the file loads.47                        renderer.renderFrame(1, 1)48                        controller.load(url)49                        withTimeout(20_000) { while (controller.durationMs() <= 0L) delay(20) }50                        assertTrue(controller.durationMs() in 800L..1200L, "duration of $url: ${controller.durationMs()}")51                        val deadline = System.currentTimeMillis() + 10_00052                        var red = false53                        while (!red && System.currentTimeMillis() < deadline) {54                            val frame = renderer.renderFrame(16, 12)55                            val center = 6 * frame.strideBytes + 8 * 456                            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)57                            red = r > 200 && g < 60 && b < 6058                            if (!red) delay(50)59                        }60                        assertTrue(red, "the decoded red frame of $url was never rendered")61                    }62                } finally { controller.releaseAndJoin() }63            }64        }65    }6667    @Test fun libmpvExtractsBoundedRedJpegFramesFromMkvAndMp4() = runBlocking {68        withLibrary { library ->69            assumeLibmpv()70            val extractor = MpvVideoFrameExtractor()71            library.expectedUrls.forEach { url ->72                assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 512), url), 64, 48)73                assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 32), url), 32, 24)74            }75            assertNull(extractor.extractJpeg("file://${library.root.path}/missing.mkv", 512))76        }77    }7879    @Test fun artworkRunGivesTheTitleACoverAndEpisodesThumbnailsFromRealFrames() = runBlocking {80        withLibrary { library ->81            assumeLibmpv()82            val artwork = LocalVideoArtwork(library.db, library.files, library.scanner, MpvVideoFrameExtractor())83            assertTrue(artwork.generate())84            val title = library.db.mangas().single()85            assertRedJpeg(assertNotNull(title.customCoverImage), 64, 48)86            library.db.chapters(title.id).forEach { episode ->87                val thumbnail = assertNotNull(episode.thumbnailUrl).removePrefix("file://")88                assertTrue(thumbnail.startsWith(File(library.files.downloadRoot, ".yokan-artwork").path), thumbnail)89                assertRedJpeg(File(thumbnail).readBytes(), 64, 48)90            }91            // A rescan keeps the frame artwork and a new run reuses the cache.92            library.scanner.scan()93            val cached = File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() }94            assertTrue(LocalVideoArtwork(library.db, library.files, library.scanner, { _, _ -> error("must not decode") }).generate())95            assertEquals(cached, File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() })96            assertNotNull(library.db.mangas().single().customCoverImage)97        }98    }99100    private class Library(val root: File, val files: JvmLocalFileService, val db: InMemoryYokanDatabase, val scanner: DefaultLocalLibraryService) {101        // '%20' in a name: mpv percent-decodes file:// URLs, so the player must hand it the raw path.102        val expectedUrls = listOf("Episode 1.mkv", "Episode 2 100%20.mp4").map { "file://${File(root, "Show/$it").path}" }103104        suspend fun playableUrls(): List<String> {105            val factory = ProfileReaderContentTest.RuntimeFactory(db, "local")106            val owner = SupervisorJob()107            val content = ProfileReaderContent(108                ProfileId.Default, db, factory, ChapterPageResolver(DefaultYokanRepository(db), db, factory),109                files, JvmLocalArchiveService(files.cacheRoot), CoroutineScope(owner),110            )111            return try {112                val title = db.mangas().single()113                db.chapters(title.id).sortedBy { it.number }.map { stored ->114                    val episode = Chapter(id = stored.id, mangaId = title.id, name = stored.name.orEmpty(), url = stored.url, archivePath = stored.archivePath)115                    content.videos(null, episode).single().url116                }.also { assertEquals(0, factory.created) }117            } finally { content.closeAndJoin(); owner.cancelAndJoin() }118        }119    }120121    private suspend fun withLibrary(block: suspend (Library) -> Unit) {122        val temp = Files.createTempDirectory("yokan-local-video").toFile()123        try {124            val root = File(temp, "anime")125            File(root, "Show").mkdirs()126            File(root, "Show/Episode 1.mkv").writeBytes(RedVideoFixtures.mkv)127            File(root, "Show/Episode 2 100%20.mp4").writeBytes(RedVideoFixtures.mp4)128            val files = JvmLocalFileService(File(temp, "downloads").path, File(temp, "backups").path, File(temp, "cache").path)129            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root.path)))))130            val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot))131            scanner.scan()132            assertEquals(2, db.chapters(db.mangas().single().id).size)133            block(Library(root, files, db, scanner))134        } finally { temp.deleteRecursively() }135    }136137    private suspend fun assumeLibmpv() {138        val probe = runCatching { MpvPlayer.create() }139        assumeTrue("libmpv is neither bundled nor installed on this machine: ${probe.exceptionOrNull()}", probe.isSuccess)140        probe.getOrNull()?.release()141    }142143    private fun assertRedJpeg(bytes: ByteArray, width: Int, height: Int) {144        val image = assertNotNull(ImageIO.read(ByteArrayInputStream(bytes)), "not a decodable image")145        assertEquals(width to height, image.width to image.height)146        val pixel = java.awt.Color(image.getRGB(width / 2, height / 2))147        assertTrue(pixel.red > 200 && pixel.green < 60 && pixel.blue < 60, "center pixel $pixel")148    }149}150

Search chapters, reference and source filenames.