VideoFrameExtractor.desktop.kt
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.desktop.kt
1package eu.friedcutlet.yokan.services.media23import eu.friedcutlet.yokan.services.blockingDispatcher4import eu.friedcutlet.yokan.services.logging.AppLogger5import io.github.kmpmpv.MpvConfiguration6import io.github.kmpmpv.MpvEvent7import io.github.kmpmpv.MpvException8import io.github.kmpmpv.MpvLifecycleEvent9import io.github.kmpmpv.MpvPlayer10import kotlinx.coroutines.CoroutineStart11import kotlinx.coroutines.async12import kotlinx.coroutines.coroutineScope13import kotlinx.coroutines.flow.first14import kotlinx.coroutines.withContext15import kotlinx.coroutines.withTimeoutOrNull16import org.jetbrains.skia.ColorAlphaType17import org.jetbrains.skia.ColorType18import org.jetbrains.skia.EncodedImageFormat19import org.jetbrains.skia.Image20import org.jetbrains.skia.ImageInfo2122actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = MpvVideoFrameExtractor()2324/**25 * A headless instance of the player's own libmpv. mpv's software render API scales the frame and Skia encodes it:26 * the media-kit libmpv bundled for macOS/Windows has neither lavfi `scale` nor image encoders, so27 * `screenshot-to-file` fails there. Linux uses the system libmpv; without one, extraction returns null.28 */29internal class MpvVideoFrameExtractor(private val timeoutMillis: Long = 20_000) : VideoFrameExtractor {30 override suspend fun extractJpeg(url: String, maxDimension: Int): ByteArray? = withContext(blockingDispatcher) {31 val player = try {32 MpvPlayer.create(MpvConfiguration(options = MpvConfiguration.DefaultOptions + FrameOptions))33 } catch (unavailable: MpvException) {34 AppLogger.warn("[local] libmpv unavailable for video frames: ${unavailable.message.orEmpty()}")35 return@withContext null36 }37 try {38 // vo=libmpv refuses to start a video before its render context exists.39 player.renderSoftwareFrame(1, 1)40 val started = withTimeoutOrNull(timeoutMillis) {41 coroutineScope {42 val restart = async(start = CoroutineStart.UNDISPATCHED) {43 player.events.first { it == PlaybackRestart || it is MpvEvent.EndFile }44 }45 // mpv percent-decodes file:// URLs; the raw path also opens names containing '%'.46 player.load(url.removePrefix("file://"))47 restart.await()48 }49 }50 if (started != PlaybackRestart) return@withContext null51 val width = player.getLongProperty("dwidth")?.takeIf { it > 0 } ?: return@withContext null52 val height = player.getLongProperty("dheight")?.takeIf { it > 0 } ?: return@withContext null53 val scale = minOf(1.0, maxDimension.toDouble() / maxOf(width, height))54 val frame = player.renderSoftwareFrame(55 (width * scale).toInt().coerceAtLeast(1),56 (height * scale).toInt().coerceAtLeast(1),57 )58 val image = Image.makeRaster(59 ImageInfo(frame.width, frame.height, ColorType.BGRA_8888, ColorAlphaType.OPAQUE),60 frame.pixels,61 frame.strideBytes,62 )63 try { image.encodeToData(EncodedImageFormat.JPEG, 85)?.bytes } finally { image.close() }64 } finally {65 player.release()66 }67 }6869 private companion object {70 val PlaybackRestart = MpvEvent.Lifecycle(MpvLifecycleEvent.PlaybackRestart)71 val FrameOptions = mapOf(72 "vo" to "libmpv",73 "ao" to "null",74 "audio" to "no",75 "sub" to "no",76 "pause" to "yes",77 "start" to "10%",78 "hr-seek" to "yes",79 "hwdec" to "no",80 "config" to "no",81 )82 }83}84