# kmp-mpv

`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.

| Platform | Kotlin target | Native transport | Native library policy | Video output |
|---|---|---|---|---|
| Windows x64 | JVM desktop | JNA | bundled `libmpv-2.dll` | native window or software render API |
| Linux | JVM desktop | JNA | system `libmpv` (matching media-kit) | native window or software render API |
| macOS universal | JVM desktop | JNA | bundled XCFramework binaries | native window or software render API |
| Android | Android KMP | JNI bridge | bundled for 4 ABIs | `MpvSurfaceView` |
| iOS device arm64 | Kotlin/Native | dynamic C bridge | app-embedded XCFrameworks | software render API |
| iOS simulator | Kotlin/Native | dynamic C bridge | no compatible media-kit slice | consumer fallback |

Downloads 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.

## Implemented API

- Deterministic player creation/release and serialized native calls
- Commands and typed scalar properties (`String`, `Boolean`, `Long`, `Double`)
- Property observation, event `SharedFlow`, and high-level playback `StateFlow`
- Load, play/pause, stop, seek, playback speed, logging, and raw commands
- Desktop native-window attachment and BGRA software-frame rendering
- Android surface lifecycle integration through `MpvSurfaceView`
- iOS BGRA software-frame rendering through libmpv's render API
- Android arm64-v8a, armeabi-v7a, x86, and x86_64 packaging
- Multiplatform Maven publications and an iOS `KmpMpv` framework

## Add the library

Use a composite build while developing both repositories:

```kotlin
// settings.gradle.kts
includeBuild("../kmp-mpv") {
    dependencySubstitution {
        substitute(module("io.github.kmpmpv:kmp-mpv"))
            .using(project(":kmp-mpv"))
    }
}
```

Then add the root KMP coordinate to `commonMain`:

```kotlin
commonMain.dependencies {
    implementation("io.github.kmpmpv:kmp-mpv:0.1.0-SNAPSHOT")
}
```

Alternatively, run `./gradlew publishToMavenLocal` and resolve the same coordinate from Maven Local.

## Common usage

Creating a player loads and initializes libmpv immediately. Control methods are suspending.

```kotlin
val player = MpvPlayer.create(
    MpvConfiguration(
        options = MpvConfiguration.DefaultOptions + mapOf(
            "hwdec" to "auto-safe",
            "keep-open" to "yes",
        ),
    ),
)

val stateJob = scope.launch {
    player.state.collect { state ->
        println("${state.status}: ${state.positionSeconds}/${state.durationSeconds}")
    }
}

player.load("https://example.com/video.m3u8")
player.seek(30.0)
player.setProperty("volume", MpvValue.Decimal(75.0))

player.release()
stateJob.cancel()
```

Every mpv command remains available:

```kotlin
player.command("sub-add", "/path/to/subtitles.ass", "select")
val decoder = player.getStringProperty("video-codec")
val observationId = player.observeProperty("estimated-vf-fps", MpvFormat.Double)
```

## Platform integration

### Desktop

The 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.

Attach a displayable AWT component:

```kotlin
val canvas = Canvas()
val player = MpvPlayer.create()
player.attachRenderTarget(MpvRenderTarget(canvas))
```

For a Compose-native surface, configure `vo=libmpv` before initialization and copy software frames into an `ImageBitmap`. This avoids heavyweight AWT components covering Compose controls:

```kotlin
val player = MpvPlayer.create(
    MpvConfiguration(
        options = MpvConfiguration.DefaultOptions + ("vo" to "libmpv"),
    ),
)
val frame = player.renderSoftwareFrame(width = 1280, height = 720)
// frame.pixels contains aligned BGR0/BGRA-compatible data.
```

On 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.

### Android

The 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.

```kotlin
val player = MpvPlayer.create(
    MpvConfiguration(
        options = MpvConfiguration.DefaultOptions + mapOf(
            "hwdec" to "mediacodec-copy",
        ),
    ),
)

val view = MpvSurfaceView(context).apply { bind(player) }
player.load(uri.toString())

// Owning lifecycle shutdown:
view.dispose()
player.release()
```

The default Android backend options are `vo=gpu` and `gpu-context=android`; caller options override them.

### iOS

Run the preparation script before linking an iOS device application:

```shell
./scripts/prepare-media-kit-ios.sh
```

It 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.

The 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.

The iOS backend defaults to `vo=libmpv`, which is required before creating a render context. Caller options may override it.

iOS consumers use the same software-frame contract as Compose-native desktop surfaces:

```kotlin
val frame = player.renderSoftwareFrame(width = 1280, height = 720)
// frame.pixels is aligned BGR0/BGRA-compatible data with frame.strideBytes.
```

## Reused native artifacts

The exact artifact URLs and checksums live beside the download tasks:

- Android: `android-bridge/build.gradle.kts`
- Windows and macOS: `kmp-mpv/build.gradle.kts`
- iOS: `scripts/prepare-media-kit-ios.sh`

All selected artifacts were inspected for `-Dlua=enabled`. Linux uses the installed system libmpv, so Lua availability depends on that distribution build.

## Prerequisites

- JDK 21.
- Android SDK platform 36, build-tools 36.1.0, NDK 28.2.13676358, and CMake 3.22.1.
- macOS/Xcode for Apple targets; run `./scripts/prepare-media-kit-ios.sh` for iOS.
- Linux libmpv runtime and development packages.

On JDK 24 and later, JNA may require `--enable-native-access=ALL-UNNAMED`.

## Quick verification

```shell
./gradlew :kmp-mpv:desktopTest
./gradlew :android-bridge:assembleRelease :kmp-mpv:assembleAndroidMain
./gradlew :kmp-mpv:compileKotlinIosArm64
./gradlew :kmp-mpv:compileKotlinIosSimulatorArm64
./gradlew :kmp-mpv:compileKotlinIosX64
```

Set `KMP_MPV_RUN_NATIVE_TESTS=1` when running `desktopTest` to initialize a real bundled/system mpv library in addition to the pure Kotlin tests.

## Media processing and playback helpers

The shared `MpvMediaProcessor` interface provides thumbnail extraction, video scaling,
and subtitle generation without changing an active player's position. The supplied
`DesktopMpvMediaProcessor` runs local FFmpeg and whisper.cpp executables. Android and
iOS applications need their own implementation of this processing interface; these
tools are not bundled into mobile binaries.

| Feature | Available implementation | Requirements |
| --- | --- | --- |
| PNG thumbnail at a timestamp; sequential thumbnail flow | Desktop | FFmpeg |
| Lanczos scaling to a letterboxed H.264/AAC MP4 | Desktop | FFmpeg with libx264/AAC |
| Speech transcription or translation to English, saved as SRT | Desktop | FFmpeg, whisper.cpp `whisper-cli`, local GGML model |
| Screenshots, external subtitles, frame stepping | Shared player extensions | Native mpv and compatible video output |
| Fast / balanced / high-quality playback scaling | Shared player extensions | GPU video output; does not affect software rendering |

```kotlin
// desktopMain; call from an application-owned coroutine scope.
val processor = DesktopMpvMediaProcessor(
    MpvMediaToolsConfiguration(
        ffmpegExecutable = "/path/to/ffmpeg",
        whisperExecutable = "/path/to/whisper-cli",
        threads = 2,
        maxConcurrentJobs = 1,
    ),
)
val thumbnail = processor.extractThumbnail(
    MpvThumbnailRequest("/media/episode.mkv", "/output/preview.png", positionSeconds = 60.0),
)
val scaledVideo = processor.upscaleVideo(
    MpvUpscaleRequest("/media/episode.mkv", "/output/episode-1080p.mp4"),
)
val subtitles = processor.generateSubtitles(
    MpvSubtitleRequest(
        "/media/episode.mkv", "/output/episode.srt", "/models/ggml-base.bin",
        language = "ja",
    ),
)
player.addSubtitles(subtitles)
player.setUpscalingPreset(MpvUpscalingPreset.HighQuality)
player.stepFrame()
```

Use `processor.extractThumbnails(requests).collect { path -> ... }` for batches.
The cold flow processes one request at a time and stops when its collector cancels.
It emits file paths, not decoded images, and keeps no thumbnail cache. Completed
files belong to the caller, including completed entries of a cancelled batch.

Processing accepts readable local files and requires an existing output directory.
It refuses to replace existing output, writes in a temporary sibling directory, and
publishes only completed files. Thumbnails preserve display aspect ratio, including
anamorphic sources. Video export keeps the first video and optional first audio track;
it does not retain subtitles, attachments, or additional tracks. Scaling is conventional
Lanczos interpolation, not neural super-resolution, and can also resize downwards.

Whisper executables and models are application-managed: the library never downloads
them or uploads media. Generated text and timing depend on the model and should be
reviewed. Audio is extracted as 16 kHz mono PCM into a temporary file. Whisper's own
memory use depends on model size and recording length; the configured thread and job
limits are not a hard memory cap for external tools. See the official
[FFmpeg filters](https://ffmpeg.org/ffmpeg-filters.html) and
[whisper.cpp CLI](https://github.com/ggml-org/whisper.cpp/tree/v1.8.3/examples/cli)
documentation for tool requirements.

`player.saveScreenshot(path, includeSubtitles = false)` captures the current frame
through mpv. Unlike offline jobs, mpv's screenshot command can overwrite that path.

## Resource ownership and verification

Always call `player.release()` in `finally`. Cleanup completes even when the calling
coroutine is already cancelled. Native operations run on the player dispatcher;
`MpvPlayer.create()` is synchronous and should be called off the UI thread.
Software frames own their returned byte arrays, so consumers may retain a frame
without later renders modifying it. Retaining many frames still consumes heap memory.

Desktop software rendering reuses a 64-byte-aligned native pixel buffer and render
parameters until dimensions change, and frees them on resize/release. Property-read
allocations are freed immediately. `maxSoftwareFrameBytes` defaults to 128 MiB and
rejects oversized render requests before allocation. At 1920×1080 the native pixel
buffer is about 7.9 MiB; each returned frame still requires another 7.9 MiB managed
array, plus any consumer UI/image copies.

Processing jobs default to one concurrent process pipeline and two worker threads.
They drain process output into a 16 KiB diagnostic tail. Cancelling or timing out a
job terminates and waits for its tool process, closes pipes, and removes temporary
audio and unfinished output. Reuse a processor instance to share the concurrency limit.

The desktop tests cover cancelled/concurrent release, oversized frames, subprocess
cancellation, bounded diagnostics, output ownership, and batch backpressure. Enable
real mpv rendering and FFmpeg tests with:

```shell
./gradlew :kmp-mpv:desktopTest -PKMP_MPV_RUN_NATIVE_TESTS=1 -PKMP_MPV_RUN_MEDIA_TESTS=1
```

For speech transcription, also set `KMP_MPV_RUN_WHISPER_TESTS=1`, `KMP_MPV_WHISPER`,
`KMP_MPV_WHISPER_MODEL`, and `KMP_MPV_SPEECH_SAMPLE` (a local speech recording).
All test settings accept either environment variables or Gradle `-P` properties.
Optional executable override: `KMP_MPV_FFMPEG`.

Tests exercise resource lifetimes; they do not establish absence of native leaks on
every platform. For device profiling, repeatedly open/play/resize/close media and
cancel processing while recording native allocations with Instruments or Android
Studio's native memory profiler. Compare retained allocations after warm-up and full
release; JVM heap measurements alone miss mpv/JNA allocations. Software rendering
remains a CPU copy path, not zero-copy GPU output.

## Licensing

The 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.

See [ARCHITECTURE.md](ARCHITECTURE.md) for backend and threading details.
