# Architecture

## Module layout

`kmp-mpv` contains the public KMP API, common state/event handling, desktop JNA implementation, Android implementation, and iOS dynamic C implementation. `android-bridge` is an Android AAR with a small C++ JNI shim plus the pinned media-kit Android native JARs.

Native downloads are build products:

- `android-bridge` fetches mpv 0.39.0 for four Android ABIs.
- desktop resource generation fetches the host's Windows or macOS set; Linux records that a system library is required.
- the iOS shell preparation step fetches the device XCFramework set for the final Xcode application.

## Lifecycle and threading

`MpvPlayer.create` creates the native client, sets options, requests logs, initializes it, registers internal property observations, and then starts the event coroutine.

Native calls are dispatched to the player dispatcher and serialized with a coroutine `Mutex`. Commands wake `mpv_wait_event`; the event job polls with a bounded timeout and yields during event bursts so commands are not starved. `release()` runs non-cancellably on the player dispatcher: it wakes mpv, cancels and joins the event job, destroys the handle, and clears playback state. Concurrent or repeated release destroys the handle once. Player creation is synchronous, so callers should create players off the UI thread.

The common layer observes pause, path, title, position, duration, seekability, volume, mute, speed, and video dimensions. These properties drive `MpvPlaybackState`; every observed property also remains available through `MpvEvent.PropertyChanged`.

## Native transports

- Desktop uses JNA. Bundled Windows/macOS resources are extracted atomically to a process temporary directory; explicit library paths still take priority. Event structs are decoded directly from native pointer offsets and their payloads are copied before mpv reuses them, avoiding reflective access to JNA `Structure` fields.
- Android's C++ bridge owns the `dlopen` handle, mpv client, and JNI global `Surface` reference. It copies event payloads into JVM objects.
- iOS compiles a header-only dynamic bridge that uses `dlopen`/`dlsym` for both the Client API and render API. This lets simulator code compile even though the selected binary archive only supports devices.

No backend calls into Kotlin from an mpv-owned thread. This avoids callback lifetime issues on Kotlin/Native and keeps wakeup callbacks unnecessary.

## Video output

Desktop supports two output paths. Native embedding sets mpv's writable `wid` option to the AWT component's native HWND, X11 Window, or NSView; `window-id` is a separate read-only property and detach uses mpv's documented `-1` sentinel. Compose-native consumers can instead set `vo=libmpv` and render aligned `bgr0` frames without introducing a heavyweight AWT surface. The backend creates the software `mpv_render_context` during initialization, before a media load can wait on or fail for lack of a video output.

Android passes the JNI global `Surface` reference through the `wid` option. Surface destruction switches `vo` to `null` before releasing the global reference; reattachment restores the configured output.

Android retains a Surface until the VO has stopped using it. Failed detach retains ownership for retry or final destruction. Final destruction terminates mpv before deleting the global reference. Replacing an attached Surface first detaches the old output.

The selected iOS build has no consumer-native view output suitable for Compose. Its backend uses the same `vo=libmpv` software render path. Desktop and iOS consumers convert the frames to their UI toolkit's image representation. This copy-based path prioritizes portability and correct UI composition over zero-copy GPU rendering.

Desktop owns and reuses aligned native software-render buffers and their parameter arrays. Resize and release close those allocations deterministically. Each returned frame owns a separate managed array. The common layer enforces the configured byte limit before allocation, and desktop/iOS propagate native render errors instead of returning an apparently successful frame.

## Offline processing

`MpvMediaProcessor` is independent of player state and lifetime. Its desktop implementation invokes FFmpeg for timestamped PNGs and Lanczos MP4 export; subtitle generation extracts mono PCM to disk and invokes a caller-provided whisper.cpp CLI/model for SRT. The shared interface allows applications to supply mobile backends without pretending that desktop executables work on Android or iOS.

One reusable processor shares a semaphore across its jobs. Each job owns its subprocesses, streams and temporary sibling directory. Processes are launched with argument arrays, output is drained into a bounded diagnostic ring, and cancellation reaps the process before deleting its temporary files. Completed outputs are moved to the caller's destination without requesting replacement. There is no decoded-frame cache or resident model in the Kotlin process.

## Artifact loading details

The macOS Mpv framework's arm64 slice uses Lua without an `LC_LOAD_DYLIB` entry for `Lua.framework`. The JVM loader therefore preloads Lua before Mpv initialization. iOS applications must likewise explicitly link or load Lua in addition to embedding it.

All Darwin dependency frameworks are kept next to `Mpv.framework`. The generated macOS resources add an rpath so each extracted framework can resolve siblings. Windows packages the archive's `libmpv-2.dll`. Linux intentionally follows media-kit's CI and resolves the distribution libmpv.
