Yokan / rebuild
Course 1 8624561

README.md

vendor/kmp-mpv/README.md

documentation / design asset302 lines
1# kmp-mpv23`kmp-mpv` is a Kotlin Multiplatform wrapper around libmpv's stable Client API. It ships a coroutine-based player API and reuses the Lua-enabled native artifacts selected by the sibling `media-kit` project.45| Platform | Kotlin target | Native transport | Native library policy | Video output |6|---|---|---|---|---|7| Windows x64 | JVM desktop | JNA | bundled `libmpv-2.dll` | native window or software render API |8| Linux | JVM desktop | JNA | system `libmpv` (matching media-kit) | native window or software render API |9| macOS universal | JVM desktop | JNA | bundled XCFramework binaries | native window or software render API |10| Android | Android KMP | JNI bridge | bundled for 4 ABIs | `MpvSurfaceView` |11| iOS device arm64 | Kotlin/Native | dynamic C bridge | app-embedded XCFrameworks | software render API |12| iOS simulator | Kotlin/Native | dynamic C bridge | no compatible media-kit slice | consumer fallback |1314Downloads are pinned by URL and SHA-256 and happen during the relevant build task. The downloaded files stay under `build/`; they are not checked into Git.1516## Implemented API1718- Deterministic player creation/release and serialized native calls19- Commands and typed scalar properties (`String`, `Boolean`, `Long`, `Double`)20- Property observation, event `SharedFlow`, and high-level playback `StateFlow`21- Load, play/pause, stop, seek, playback speed, logging, and raw commands22- Desktop native-window attachment and BGRA software-frame rendering23- Android surface lifecycle integration through `MpvSurfaceView`24- iOS BGRA software-frame rendering through libmpv's render API25- Android arm64-v8a, armeabi-v7a, x86, and x86_64 packaging26- Multiplatform Maven publications and an iOS `KmpMpv` framework2728## Add the library2930Use a composite build while developing both repositories:3132```kotlin33// settings.gradle.kts34includeBuild("../kmp-mpv") {35    dependencySubstitution {36        substitute(module("io.github.kmpmpv:kmp-mpv"))37            .using(project(":kmp-mpv"))38    }39}40```4142Then add the root KMP coordinate to `commonMain`:4344```kotlin45commonMain.dependencies {46    implementation("io.github.kmpmpv:kmp-mpv:0.1.0-SNAPSHOT")47}48```4950Alternatively, run `./gradlew publishToMavenLocal` and resolve the same coordinate from Maven Local.5152## Common usage5354Creating a player loads and initializes libmpv immediately. Control methods are suspending.5556```kotlin57val player = MpvPlayer.create(58    MpvConfiguration(59        options = MpvConfiguration.DefaultOptions + mapOf(60            "hwdec" to "auto-safe",61            "keep-open" to "yes",62        ),63    ),64)6566val stateJob = scope.launch {67    player.state.collect { state ->68        println("${state.status}: ${state.positionSeconds}/${state.durationSeconds}")69    }70}7172player.load("https://example.com/video.m3u8")73player.seek(30.0)74player.setProperty("volume", MpvValue.Decimal(75.0))7576player.release()77stateJob.cancel()78```7980Every mpv command remains available:8182```kotlin83player.command("sub-add", "/path/to/subtitles.ass", "select")84val decoder = player.getStringProperty("video-codec")85val observationId = player.observeProperty("estimated-vf-fps", MpvFormat.Double)86```8788## Platform integration8990### Desktop9192The desktop artifact embeds media-kit's Windows x64 or macOS universal framework binaries as JVM resources. At runtime they are extracted to a temporary directory and loaded before the player is initialized. The macOS loader also preloads `Lua.framework`, matching CocoaPods' treatment of the original vendored frameworks.9394Attach a displayable AWT component:9596```kotlin97val canvas = Canvas()98val player = MpvPlayer.create()99player.attachRenderTarget(MpvRenderTarget(canvas))100```101102For a Compose-native surface, configure `vo=libmpv` before initialization and copy software frames into an `ImageBitmap`. This avoids heavyweight AWT components covering Compose controls:103104```kotlin105val player = MpvPlayer.create(106    MpvConfiguration(107        options = MpvConfiguration.DefaultOptions + ("vo" to "libmpv"),108    ),109)110val frame = player.renderSoftwareFrame(width = 1280, height = 720)111// frame.pixels contains aligned BGR0/BGRA-compatible data.112```113114On Linux, install the distribution libmpv package, exactly as media-kit does. For example, Debian/Ubuntu builds require `libmpv-dev` at build time and `libmpv2` or the distribution-equivalent runtime package. X11 foreign-window embedding is supported; Wayland compositors may require XWayland or an mpv-owned window.115116### Android117118The Android AAR fetches and republishes media-kit's pinned mpv 0.39.0 JARs for all four ABIs. The JNI shim registers Android's Java VM with libmpv and passes a global `android.view.Surface` reference through mpv's Android `wid` contract.119120```kotlin121val player = MpvPlayer.create(122    MpvConfiguration(123        options = MpvConfiguration.DefaultOptions + mapOf(124            "hwdec" to "mediacodec-copy",125        ),126    ),127)128129val view = MpvSurfaceView(context).apply { bind(player) }130player.load(uri.toString())131132// Owning lifecycle shutdown:133view.dispose()134player.release()135```136137The default Android backend options are `vo=gpu` and `gpu-context=android`; caller options override them.138139### iOS140141Run the preparation script before linking an iOS device application:142143```shell144./scripts/prepare-media-kit-ios.sh145```146147It expands the pinned media-kit XCFramework archive under `build/media-kit-mpv/ios`. Copy every device framework to the application framework directory, embed/sign them, and link at least `Mpv` and `Lua`. The arm64 Mpv binary resolves Lua lazily, so embedding Lua without linking/loading it is insufficient.148149The current media-kit archive contains only an `ios-arm64` device slice despite its `universal` filename. iOS simulator targets compile, but runtime media playback requires a physical device unless a simulator-compatible libmpv build is supplied separately.150151The iOS backend defaults to `vo=libmpv`, which is required before creating a render context. Caller options may override it.152153iOS consumers use the same software-frame contract as Compose-native desktop surfaces:154155```kotlin156val frame = player.renderSoftwareFrame(width = 1280, height = 720)157// frame.pixels is aligned BGR0/BGRA-compatible data with frame.strideBytes.158```159160## Reused native artifacts161162The exact artifact URLs and checksums live beside the download tasks:163164- Android: `android-bridge/build.gradle.kts`165- Windows and macOS: `kmp-mpv/build.gradle.kts`166- iOS: `scripts/prepare-media-kit-ios.sh`167168All selected artifacts were inspected for `-Dlua=enabled`. Linux uses the installed system libmpv, so Lua availability depends on that distribution build.169170## Prerequisites171172- JDK 21.173- Android SDK platform 36, build-tools 36.1.0, NDK 28.2.13676358, and CMake 3.22.1.174- macOS/Xcode for Apple targets; run `./scripts/prepare-media-kit-ios.sh` for iOS.175- Linux libmpv runtime and development packages.176177On JDK 24 and later, JNA may require `--enable-native-access=ALL-UNNAMED`.178179## Quick verification180181```shell182./gradlew :kmp-mpv:desktopTest183./gradlew :android-bridge:assembleRelease :kmp-mpv:assembleAndroidMain184./gradlew :kmp-mpv:compileKotlinIosArm64185./gradlew :kmp-mpv:compileKotlinIosSimulatorArm64186./gradlew :kmp-mpv:compileKotlinIosX64187```188189Set `KMP_MPV_RUN_NATIVE_TESTS=1` when running `desktopTest` to initialize a real bundled/system mpv library in addition to the pure Kotlin tests.190191## Media processing and playback helpers192193The shared `MpvMediaProcessor` interface provides thumbnail extraction, video scaling,194and subtitle generation without changing an active player's position. The supplied195`DesktopMpvMediaProcessor` runs local FFmpeg and whisper.cpp executables. Android and196iOS applications need their own implementation of this processing interface; these197tools are not bundled into mobile binaries.198199| Feature | Available implementation | Requirements |200| --- | --- | --- |201| PNG thumbnail at a timestamp; sequential thumbnail flow | Desktop | FFmpeg |202| Lanczos scaling to a letterboxed H.264/AAC MP4 | Desktop | FFmpeg with libx264/AAC |203| Speech transcription or translation to English, saved as SRT | Desktop | FFmpeg, whisper.cpp `whisper-cli`, local GGML model |204| Screenshots, external subtitles, frame stepping | Shared player extensions | Native mpv and compatible video output |205| Fast / balanced / high-quality playback scaling | Shared player extensions | GPU video output; does not affect software rendering |206207```kotlin208// desktopMain; call from an application-owned coroutine scope.209val processor = DesktopMpvMediaProcessor(210    MpvMediaToolsConfiguration(211        ffmpegExecutable = "/path/to/ffmpeg",212        whisperExecutable = "/path/to/whisper-cli",213        threads = 2,214        maxConcurrentJobs = 1,215    ),216)217val thumbnail = processor.extractThumbnail(218    MpvThumbnailRequest("/media/episode.mkv", "/output/preview.png", positionSeconds = 60.0),219)220val scaledVideo = processor.upscaleVideo(221    MpvUpscaleRequest("/media/episode.mkv", "/output/episode-1080p.mp4"),222)223val subtitles = processor.generateSubtitles(224    MpvSubtitleRequest(225        "/media/episode.mkv", "/output/episode.srt", "/models/ggml-base.bin",226        language = "ja",227    ),228)229player.addSubtitles(subtitles)230player.setUpscalingPreset(MpvUpscalingPreset.HighQuality)231player.stepFrame()232```233234Use `processor.extractThumbnails(requests).collect { path -> ... }` for batches.235The cold flow processes one request at a time and stops when its collector cancels.236It emits file paths, not decoded images, and keeps no thumbnail cache. Completed237files belong to the caller, including completed entries of a cancelled batch.238239Processing accepts readable local files and requires an existing output directory.240It refuses to replace existing output, writes in a temporary sibling directory, and241publishes only completed files. Thumbnails preserve display aspect ratio, including242anamorphic sources. Video export keeps the first video and optional first audio track;243it does not retain subtitles, attachments, or additional tracks. Scaling is conventional244Lanczos interpolation, not neural super-resolution, and can also resize downwards.245246Whisper executables and models are application-managed: the library never downloads247them or uploads media. Generated text and timing depend on the model and should be248reviewed. Audio is extracted as 16 kHz mono PCM into a temporary file. Whisper's own249memory use depends on model size and recording length; the configured thread and job250limits are not a hard memory cap for external tools. See the official251[FFmpeg filters](https://ffmpeg.org/ffmpeg-filters.html) and252[whisper.cpp CLI](https://github.com/ggml-org/whisper.cpp/tree/v1.8.3/examples/cli)253documentation for tool requirements.254255`player.saveScreenshot(path, includeSubtitles = false)` captures the current frame256through mpv. Unlike offline jobs, mpv's screenshot command can overwrite that path.257258## Resource ownership and verification259260Always call `player.release()` in `finally`. Cleanup completes even when the calling261coroutine is already cancelled. Native operations run on the player dispatcher;262`MpvPlayer.create()` is synchronous and should be called off the UI thread.263Software frames own their returned byte arrays, so consumers may retain a frame264without later renders modifying it. Retaining many frames still consumes heap memory.265266Desktop software rendering reuses a 64-byte-aligned native pixel buffer and render267parameters until dimensions change, and frees them on resize/release. Property-read268allocations are freed immediately. `maxSoftwareFrameBytes` defaults to 128 MiB and269rejects oversized render requests before allocation. At 1920×1080 the native pixel270buffer is about 7.9 MiB; each returned frame still requires another 7.9 MiB managed271array, plus any consumer UI/image copies.272273Processing jobs default to one concurrent process pipeline and two worker threads.274They drain process output into a 16 KiB diagnostic tail. Cancelling or timing out a275job terminates and waits for its tool process, closes pipes, and removes temporary276audio and unfinished output. Reuse a processor instance to share the concurrency limit.277278The desktop tests cover cancelled/concurrent release, oversized frames, subprocess279cancellation, bounded diagnostics, output ownership, and batch backpressure. Enable280real mpv rendering and FFmpeg tests with:281282```shell283./gradlew :kmp-mpv:desktopTest -PKMP_MPV_RUN_NATIVE_TESTS=1 -PKMP_MPV_RUN_MEDIA_TESTS=1284```285286For speech transcription, also set `KMP_MPV_RUN_WHISPER_TESTS=1`, `KMP_MPV_WHISPER`,287`KMP_MPV_WHISPER_MODEL`, and `KMP_MPV_SPEECH_SAMPLE` (a local speech recording).288All test settings accept either environment variables or Gradle `-P` properties.289Optional executable override: `KMP_MPV_FFMPEG`.290291Tests exercise resource lifetimes; they do not establish absence of native leaks on292every platform. For device profiling, repeatedly open/play/resize/close media and293cancel processing while recording native allocations with Instruments or Android294Studio's native memory profiler. Compare retained allocations after warm-up and full295release; JVM heap measurements alone miss mpv/JNA allocations. Software rendering296remains a CPU copy path, not zero-copy GPU output.297298## Licensing299300The Kotlin library and JNI/C shim are MIT licensed. The downloaded native artifacts retain their own licenses. In particular, the selected Windows binary reports GPL features enabled and must be treated as GPL-distributed mpv; Android and Darwin report non-GPL mpv configurations, but their FFmpeg/codec dependency licenses still require review. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) before distributing an application.301302See [ARCHITECTURE.md](ARCHITECTURE.md) for backend and threading details.303

Search chapters, reference and source filenames.