package eu.friedcutlet.yokan.services.media import eu.friedcutlet.yokan.services.blockingDispatcher import eu.friedcutlet.yokan.services.logging.AppLogger import io.github.kmpmpv.MpvConfiguration import io.github.kmpmpv.MpvEvent import io.github.kmpmpv.MpvException import io.github.kmpmpv.MpvLifecycleEvent import io.github.kmpmpv.MpvPlayer import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.jetbrains.skia.ColorAlphaType import org.jetbrains.skia.ColorType import org.jetbrains.skia.EncodedImageFormat import org.jetbrains.skia.Image import org.jetbrains.skia.ImageInfo actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = MpvVideoFrameExtractor() /** * A headless instance of the player's own libmpv. mpv's software render API scales the frame and Skia encodes it: * the media-kit libmpv bundled for macOS/Windows has neither lavfi `scale` nor image encoders, so * `screenshot-to-file` fails there. Linux uses the system libmpv; without one, extraction returns null. */ internal class MpvVideoFrameExtractor(private val timeoutMillis: Long = 20_000) : VideoFrameExtractor { override suspend fun extractJpeg(url: String, maxDimension: Int): ByteArray? = withContext(blockingDispatcher) { val player = try { MpvPlayer.create(MpvConfiguration(options = MpvConfiguration.DefaultOptions + FrameOptions)) } catch (unavailable: MpvException) { AppLogger.warn("[local] libmpv unavailable for video frames: ${unavailable.message.orEmpty()}") return@withContext null } try { // vo=libmpv refuses to start a video before its render context exists. player.renderSoftwareFrame(1, 1) val started = withTimeoutOrNull(timeoutMillis) { coroutineScope { val restart = async(start = CoroutineStart.UNDISPATCHED) { player.events.first { it == PlaybackRestart || it is MpvEvent.EndFile } } // mpv percent-decodes file:// URLs; the raw path also opens names containing '%'. player.load(url.removePrefix("file://")) restart.await() } } if (started != PlaybackRestart) return@withContext null val width = player.getLongProperty("dwidth")?.takeIf { it > 0 } ?: return@withContext null val height = player.getLongProperty("dheight")?.takeIf { it > 0 } ?: return@withContext null val scale = minOf(1.0, maxDimension.toDouble() / maxOf(width, height)) val frame = player.renderSoftwareFrame( (width * scale).toInt().coerceAtLeast(1), (height * scale).toInt().coerceAtLeast(1), ) val image = Image.makeRaster( ImageInfo(frame.width, frame.height, ColorType.BGRA_8888, ColorAlphaType.OPAQUE), frame.pixels, frame.strideBytes, ) try { image.encodeToData(EncodedImageFormat.JPEG, 85)?.bytes } finally { image.close() } } finally { player.release() } } private companion object { val PlaybackRestart = MpvEvent.Lifecycle(MpvLifecycleEvent.PlaybackRestart) val FrameOptions = mapOf( "vo" to "libmpv", "ao" to "null", "audio" to "no", "sub" to "no", "pause" to "yes", "start" to "10%", "hr-seek" to "yes", "hwdec" to "no", "config" to "no", ) } }