Yokan / rebuild
Course 1 8624561

Reimplement the kmp-mpv submodule

111 min read + implementationSnapshot 8624561Markdown

Pinned commit: 41e5a2a867191baaeb343e1490566a8bbd83eb3c. Every submodule file.

How to write this chapter

Recreate kmp-mpv independently: typed common API, serialized native commands/events, platform transports and rendering, then offline processing and native packaging.

The 58 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

  • Step 1: Define mpv values, state, events, player and raw engine interfaces.
  • Step 2: Serialize native calls and map events into public state.
  • Step 3: Implement desktop JNA, bundled libraries and software/native rendering.
  • Step 4: Write Android Java/JNI/C++ and Surface lifetime.
  • Step 5: Implement dynamic iOS client/render transport and cinterop.
  • Step 6: Add offline processing, build pins, samples and artifact preparation.
  • Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #

Step 1: define the public API and a fake engine

Create the independent Gradle build with kmp-mpv and android-bridge. Define MpvConfiguration, MpvValue/format, errors, events, playback state, render targets, software frame, feature contracts and MpvPlayer. Include load modes, seek modes, typed properties, observe/unobserve, logs, commands, render attach/detach/resize, software rendering and release. The public command API is suspending; factory creation is synchronous and should be called away from the UI thread.

Define internal MpvEngine, EngineResult, RawMpvEvent and raw software frame. Implement a fake engine for DefaultMpvPlayer tests. Native event IDs and format codes are ABI values, not arbitrary enum ordinals.

Follow the code

Write the public value/format/event/state types before the engine implementation. Numeric native IDs/formats are ABI constants, not freely reorderable Kotlin enum values. The internal engine returns copied raw data to the common layer, allowing fake-engine tests without libmpv. Keep configuration, render target, feature and software-frame contracts complete: main-app adapters depend on more than load/play/pause.

Write these files in this order:

  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvValue.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvConfiguration.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvEvent.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlaybackState.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvRenderTarget.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvSoftwareFrame.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlayerFeatures.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlayer.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/internal/MpvEngine.kt
  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvException.kt

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvValue.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvValue, None, Text, Flag, Integer, Decimal, MpvFormat.

The source describes its contract as:

Values supported by libmpv's scalar property formats.

package io.github.kmpmpv

/** Values supported by libmpv's scalar property formats. */
public sealed interface MpvValue {
    public data object None : MpvValue

    public data class Text(val value: String) : MpvValue

    public data class Flag(val value: Boolean) : MpvValue

    public data class Integer(val value: Long) : MpvValue

    public data class Decimal(val value: Double) : MpvValue
}

public enum class MpvFormat(internal val nativeValue: Int) {
    None(0),
    String(1),
    OsdString(2),
    Flag(3),
    Int64(4),
    Double(5),
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvConfiguration.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvConfiguration, MpvLogLevel.

The source describes its contract as:

Configuration applied before the libmpv client is initialized.

package io.github.kmpmpv

/** Configuration applied before the libmpv client is initialized. */
public data class MpvConfiguration(
    /** Explicit library/framework path. When null, platform-specific names are searched. */
    val libraryPath: String? = null,
    /** mpv options, without the leading `--`. */
    val options: Map<String, String> = DefaultOptions,
    val logLevel: MpvLogLevel = MpvLogLevel.Warn,
    val eventBufferCapacity: Int = 128,
    val eventPollTimeoutSeconds: Double = 0.05,
    /** Reject oversized software renders before either native or managed allocation. */
    val maxSoftwareFrameBytes: Int = 128 * 1024 * 1024,
) {
    init {
        require(eventBufferCapacity > 0) { "eventBufferCapacity must be positive" }
        require(maxSoftwareFrameBytes > 0) { "maxSoftwareFrameBytes must be positive" }
        require(eventPollTimeoutSeconds in 0.001..1.0) {
            "eventPollTimeoutSeconds must be between 0.001 and 1.0"
        }
        require(options.keys.none(String::isBlank)) { "mpv option names must not be blank" }
    }

    public companion object {
        public val DefaultOptions: Map<String, String> = mapOf(
            "idle" to "yes",
            "terminal" to "no",
            "input-default-bindings" to "no",
            "input-vo-keyboard" to "no",
        )
    }
}

public enum class MpvLogLevel(public val mpvName: String) {
    None("no"),
    Fatal("fatal"),
    Error("error"),
    Warn("warn"),
    Info("info"),
    Verbose("v"),
    Debug("debug"),
    Trace("trace"),
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvEvent.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvEvent, Lifecycle, PropertyChanged, LogMessage, EndFile, ClientMessage, Reply, QueueOverflow, Unknown, MpvLifecycleEvent and 2 further declarations.

package io.github.kmpmpv

/** Events emitted by a libmpv client. */
public sealed interface MpvEvent {
    public data class Lifecycle(val kind: MpvLifecycleEvent) : MpvEvent

    public data class PropertyChanged(
        val observationId: Long,
        val name: String,
        val value: MpvValue,
    ) : MpvEvent

    public data class LogMessage(
        val prefix: String,
        val level: MpvLogLevel,
        val text: String,
    ) : MpvEvent

    public data class EndFile(
        val reason: MpvEndFileReason,
        val errorCode: Int = 0,
        val errorMessage: String? = null,
    ) : MpvEvent

    public data class ClientMessage(val arguments: List<String>) : MpvEvent

    public data class Reply(
        val kind: MpvReplyKind,
        val requestId: Long,
        val errorCode: Int,
        val errorMessage: String? = null,
    ) : MpvEvent

    public data object QueueOverflow : MpvEvent

    public data class Unknown(val nativeEventId: Int) : MpvEvent
}

public enum class MpvLifecycleEvent {
    Shutdown,
    StartFile,
    FileLoaded,
    VideoReconfigured,
    AudioReconfigured,
    Seek,
    PlaybackRestart,
}

public enum class MpvReplyKind {
    GetProperty,
    SetProperty,
    Command,
}

public enum class MpvEndFileReason {
    Eof,
    Stop,
    Quit,
    Error,
    Redirect,
    Unknown,
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlaybackState.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvPlaybackState, MpvPlaybackStatus.

package io.github.kmpmpv

public data class MpvPlaybackState(
    val status: MpvPlaybackStatus = MpvPlaybackStatus.Idle,
    val mediaPath: String? = null,
    val mediaTitle: String? = null,
    val positionSeconds: Double = 0.0,
    val durationSeconds: Double? = null,
    val paused: Boolean = false,
    val seeking: Boolean = false,
    val seekable: Boolean = false,
    val volume: Double = 100.0,
    val muted: Boolean = false,
    val speed: Double = 1.0,
    val videoWidth: Long? = null,
    val videoHeight: Long? = null,
    val lastError: String? = null,
)

public enum class MpvPlaybackStatus {
    Idle,
    Loading,
    Playing,
    Paused,
    Ended,
    Error,
    Released,
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvRenderTarget.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvRenderTarget.

The source describes its contract as:

Platform render destination: a native desktop/iOS view handle or an Android Surface.

package io.github.kmpmpv

/** Platform render destination: a native desktop/iOS view handle or an Android Surface. */
public expect class MpvRenderTarget

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvSoftwareFrame.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvSoftwareFrame.

The source describes its contract as:

A software-rendered BGRA frame. The alpha byte is undefined and should be treated as opaque.

package io.github.kmpmpv

/** A software-rendered BGRA frame. The alpha byte is undefined and should be treated as opaque. */
public data class MpvSoftwareFrame(
    public val width: Int,
    public val height: Int,
    public val strideBytes: Int,
    public val pixels: ByteArray,
)

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlayerFeatures.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvUpscalingPreset, MpvPlayer.setUpscalingPreset, MpvPlayer.saveScreenshot, MpvPlayer.addSubtitles, MpvPlayer.stepFrame.

The source describes its contract as:

GPU video scaling presets. These do not affect the software render API or encode video.

package io.github.kmpmpv

/** GPU video scaling presets. These do not affect the software render API or encode video. */
public enum class MpvUpscalingPreset(public val options: Map<String, String>) {
    Fast(mapOf("scale" to "bilinear", "cscale" to "bilinear")),
    Balanced(mapOf("scale" to "spline36", "cscale" to "bilinear")),
    HighQuality(mapOf("scale" to "ewa_lanczossharp", "cscale" to "spline36")),
}

/** Requires a GPU video output. Native mpv reports unsupported options through [MpvException]. */
public suspend fun MpvPlayer.setUpscalingPreset(preset: MpvUpscalingPreset) {
    for ((name, value) in preset.options) setProperty(name, MpvValue.Text(value))
}

/** Captures the current frame at source resolution. mpv may overwrite the supplied path. */
public suspend fun MpvPlayer.saveScreenshot(path: String, includeSubtitles: Boolean = false) {
    require(path.isNotBlank() && '\u0000' !in path) { "path must be valid" }
    command("screenshot-to-file", path, if (includeSubtitles) "subtitles" else "video")
}

/** Adds an external subtitle file, including an SRT created by [MpvMediaProcessor]. */
public suspend fun MpvPlayer.addSubtitles(path: String, select: Boolean = true) {
    require(path.isNotBlank() && '\u0000' !in path) { "path must be valid" }
    command("sub-add", path, if (select) "select" else "auto")
}

/** Advances one decoded frame and pauses playback. */
public suspend fun MpvPlayer.stepFrame(backwards: Boolean = false) {
    command(if (backwards) "frame-back-step" else "frame-step")
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvPlayer.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvPlayer, load, play, pause, togglePause, stop, seek, command, getProperty, setProperty and 15 further declarations.

The source describes its contract as:

Updates Android's android-surface-size; harmless on other platforms.

package io.github.kmpmpv

import io.github.kmpmpv.internal.createPlatformMpvEngine
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow

public interface MpvPlayer {
    public val events: SharedFlow<MpvEvent>

    public val state: StateFlow<MpvPlaybackState>

    public suspend fun load(
        path: String,
        mode: MpvLoadMode = MpvLoadMode.Replace,
    )

    public suspend fun play()

    public suspend fun pause()

    public suspend fun togglePause()

    public suspend fun stop()

    public suspend fun seek(
        seconds: Double,
        mode: MpvSeekMode = MpvSeekMode.Absolute,
    )

    public suspend fun command(vararg arguments: String)

    public suspend fun getProperty(name: String, format: MpvFormat): MpvValue

    public suspend fun setProperty(name: String, value: MpvValue)

    public suspend fun getStringProperty(name: String): String?

    public suspend fun getBooleanProperty(name: String): Boolean?

    public suspend fun getLongProperty(name: String): Long?

    public suspend fun getDoubleProperty(name: String): Double?

    public suspend fun observeProperty(name: String, format: MpvFormat): Long

    public suspend fun unobserveProperty(observationId: Long)

    public suspend fun requestLogMessages(level: MpvLogLevel)

    public suspend fun attachRenderTarget(target: MpvRenderTarget)

    public suspend fun detachRenderTarget()

    /** Updates Android's `android-surface-size`; harmless on other platforms. */
    public suspend fun updateRenderTargetSize(width: Int, height: Int)

    /**
     * Renders the current video image through mpv's software render API.
     *
     * This is primarily intended for iOS, where libmpv does not provide a native window output.
     */
    public suspend fun renderSoftwareFrame(width: Int, height: Int): MpvSoftwareFrame

    /** Stops event delivery and destroys the underlying mpv client. Idempotent. */
    public suspend fun release()

    public companion object {
        @Throws(MpvException::class)
        public fun create(configuration: MpvConfiguration = MpvConfiguration()): MpvPlayer =
            DefaultMpvPlayer(createPlatformMpvEngine(configuration), configuration)
    }
}

public enum class MpvLoadMode(internal val commandValue: String) {
    Replace("replace"),
    Append("append"),
    AppendAndPlay("append-play"),
    InsertNext("insert-next"),
    InsertNextAndPlay("insert-next-play"),
}

public enum class MpvSeekMode(internal val commandValue: String) {
    Relative("relative"),
    Absolute("absolute"),
    AbsolutePercent("absolute-percent"),
    RelativePercent("relative-percent"),
}

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/internal/MpvEngine.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

This internal interface isolates raw/native behavior so fake engines can exercise the public player. Copy payloads into managed values at the transport boundary.

The implementation below defines MpvEngine, command, getProperty, setProperty, observeProperty, unobserveProperty, requestLogMessages, waitEvent, attachRenderTarget, detachRenderTarget and 10 further declarations.

package io.github.kmpmpv.internal

import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvValue

internal interface MpvEngine {
    fun command(arguments: List<String>): Int

    fun getProperty(name: String, format: MpvFormat): EngineResult<MpvValue>

    fun setProperty(name: String, value: MpvValue): Int

    fun observeProperty(observationId: Long, name: String, format: MpvFormat): Int

    fun unobserveProperty(observationId: Long): Int

    fun requestLogMessages(level: String): Int

    fun waitEvent(timeoutSeconds: Double): RawMpvEvent

    fun attachRenderTarget(target: MpvRenderTarget): Int

    fun detachRenderTarget(): Int

    fun updateRenderTargetSize(width: Int, height: Int): Int

    fun renderSoftwareFrame(width: Int, height: Int): EngineResult<RawSoftwareFrame> =
        EngineResult(ERROR_NOT_IMPLEMENTED)

    fun errorString(errorCode: Int): String

    fun wakeup()

    fun close()
}

internal data class RawSoftwareFrame(
    val strideBytes: Int,
    val pixels: ByteArray,
)

internal data class EngineResult<T>(
    val errorCode: Int,
    val value: T? = null,
)

internal data class RawMpvEvent(
    val eventId: Int,
    val errorCode: Int = 0,
    val replyUserData: Long = 0,
    val propertyName: String? = null,
    val propertyValue: MpvValue = MpvValue.None,
    val logPrefix: String? = null,
    val logLevel: Int = 0,
    val logText: String? = null,
    val endReason: Int = 0,
    val endError: Int = 0,
    val clientArguments: List<String> = emptyList(),
)

internal object NativeEventId {
    const val NONE: Int = 0
    const val SHUTDOWN: Int = 1
    const val LOG_MESSAGE: Int = 2
    const val GET_PROPERTY_REPLY: Int = 3
    const val SET_PROPERTY_REPLY: Int = 4
    const val COMMAND_REPLY: Int = 5
    const val START_FILE: Int = 6
    const val END_FILE: Int = 7
    const val FILE_LOADED: Int = 8
    const val CLIENT_MESSAGE: Int = 16
    const val VIDEO_RECONFIG: Int = 17
    const val AUDIO_RECONFIG: Int = 18
    const val SEEK: Int = 20
    const val PLAYBACK_RESTART: Int = 21
    const val PROPERTY_CHANGE: Int = 22
    const val QUEUE_OVERFLOW: Int = 24
}

internal const val ERROR_NOT_IMPLEMENTED: Int = -12

internal expect fun createPlatformMpvEngine(configuration: MpvConfiguration): MpvEngine

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvException.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MpvException.

package io.github.kmpmpv

public class MpvException(
    public val errorCode: Int,
    message: String,
    cause: Throwable? = null,
) : RuntimeException(message, cause)

Check your understanding

Use a fake engine to emit a typed property and an end-file/error event. Verify public state/events without loading a native library. [chapter-content-end]: #

Step 2: implement common player serialization

Initialize native client/options/logs/property observations before starting the event coroutine. Serialize native calls on the player dispatcher using a mutex. Commands wake waiting native event polling. Use bounded wait time and yield during bursts so events cannot starve commands.

Map observed pause/path/title/position/duration/seekability/volume/mute/speed/video dimensions into StateFlow; also emit raw typed property changes as events. Copy native event data before the next wait reuses it. Handle shutdown/end-file/load failure consistently.

Release non-cancellably: wake native wait, cancel and join the event job, destroy native handle once, clear state. Repeated/concurrent release must be safe. Enforce software-frame byte limits before allocation and propagate native errors.

Follow the code

DefaultMpvPlayer owns a dispatcher, mutex and event coroutine. Initialization configures observations before event processing begins. Commands wake native event waits; bounded polling/yielding prevents events from starving commands. Native payloads must be copied before another wait reuses them. Release wakes polling, cancels/joins the event job and destroys the engine once under non-cancellable cleanup.

Write these files in this order:

  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/DefaultMpvPlayer.kt

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/DefaultMpvPlayer.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The player coordinates native initialization, event polling and command serialization. Treat wakeup, mutex/dispatcher order and joined release as observable correctness, not performance-only details.

The implementation below defines DefaultMpvPlayer, load, play, pause, togglePause, stop, seek, command, getProperty, setProperty and 23 further declarations.

package io.github.kmpmpv

import io.github.kmpmpv.internal.MpvEngine
import io.github.kmpmpv.internal.NativeEventId
import io.github.kmpmpv.internal.RawMpvEvent
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield

internal class DefaultMpvPlayer(
    private val engine: MpvEngine,
    private val configuration: MpvConfiguration,
    private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
) : MpvPlayer {
    private val engineMutex = Mutex()
    private val lifecycleMutex = Mutex()
    private val scope = CoroutineScope(SupervisorJob() + dispatcher)
    private val mutableEvents = MutableSharedFlow<MpvEvent>(
        extraBufferCapacity = configuration.eventBufferCapacity,
        onBufferOverflow = BufferOverflow.DROP_OLDEST,
    )
    private val mutableState = MutableStateFlow(MpvPlaybackState())
    private var released = false
    private var engineClosed = false
    private var nextObservationId = USER_OBSERVATION_START

    override val events: SharedFlow<MpvEvent> = mutableEvents.asSharedFlow()
    override val state: StateFlow<MpvPlaybackState> = mutableState.asStateFlow()

    private val eventJob: Job

    init {
        try {
            INTERNAL_PROPERTIES.forEachIndexed { index, property ->
                val result = engine.observeProperty(
                    INTERNAL_OBSERVATION_START + index,
                    property.first,
                    property.second,
                )
                checkError(result, "observe property '${property.first}'")
            }
            eventJob = scope.launch { eventLoop() }
        } catch (failure: Throwable) {
            scope.cancel()
            engine.close()
            throw failure
        }
    }

    override suspend fun load(path: String, mode: MpvLoadMode) {
        require(path.isNotBlank()) { "path must not be blank" }
        command("loadfile", path, mode.commandValue)
    }

    override suspend fun play() {
        setProperty("pause", MpvValue.Flag(false))
    }

    override suspend fun pause() {
        setProperty("pause", MpvValue.Flag(true))
    }

    override suspend fun togglePause() {
        command("cycle", "pause")
    }

    override suspend fun stop() {
        command("stop")
    }

    override suspend fun seek(seconds: Double, mode: MpvSeekMode) {
        require(seconds.isFinite()) { "seconds must be finite" }
        command("seek", seconds.toString(), mode.commandValue)
    }

    override suspend fun command(vararg arguments: String) {
        require(arguments.isNotEmpty()) { "an mpv command needs at least one argument" }
        require(arguments.none(String::isEmpty)) { "mpv command arguments must not be empty" }
        withEngine { checkError(it.command(arguments.toList()), "execute '${arguments.first()}'") }
    }

    override suspend fun getProperty(name: String, format: MpvFormat): MpvValue {
        requirePropertyName(name)
        require(format != MpvFormat.None) { "None is not a readable property format" }
        return withEngine { native ->
            val result = native.getProperty(name, format)
            checkError(result.errorCode, "read property '$name'")
            result.value ?: MpvValue.None
        }
    }

    override suspend fun setProperty(name: String, value: MpvValue) {
        requirePropertyName(name)
        require(value != MpvValue.None) { "None cannot be written as a property value" }
        withEngine { checkError(it.setProperty(name, value), "write property '$name'") }
    }

    override suspend fun getStringProperty(name: String): String? =
        (getProperty(name, MpvFormat.String) as? MpvValue.Text)?.value

    override suspend fun getBooleanProperty(name: String): Boolean? =
        (getProperty(name, MpvFormat.Flag) as? MpvValue.Flag)?.value

    override suspend fun getLongProperty(name: String): Long? =
        (getProperty(name, MpvFormat.Int64) as? MpvValue.Integer)?.value

    override suspend fun getDoubleProperty(name: String): Double? =
        (getProperty(name, MpvFormat.Double) as? MpvValue.Decimal)?.value

    override suspend fun observeProperty(name: String, format: MpvFormat): Long {
        requirePropertyName(name)
        require(format != MpvFormat.None) { "None is not an observable property format" }
        return withEngine { native ->
            val id = nextObservationId++
            checkError(native.observeProperty(id, name, format), "observe property '$name'")
            id
        }
    }

    override suspend fun unobserveProperty(observationId: Long) {
        require(observationId >= USER_OBSERVATION_START) { "cannot remove an internal observation" }
        withEngine { checkError(it.unobserveProperty(observationId), "remove observation $observationId") }
    }

    override suspend fun requestLogMessages(level: MpvLogLevel) {
        withEngine { checkError(it.requestLogMessages(level.mpvName), "request log messages") }
    }

    override suspend fun attachRenderTarget(target: MpvRenderTarget) {
        withEngine { checkError(it.attachRenderTarget(target), "attach render target") }
    }

    override suspend fun detachRenderTarget() {
        withEngine { checkError(it.detachRenderTarget(), "detach render target") }
    }

    override suspend fun updateRenderTargetSize(width: Int, height: Int) {
        require(width > 0 && height > 0) { "render target dimensions must be positive" }
        withEngine { checkError(it.updateRenderTargetSize(width, height), "update render target size") }
    }

    override suspend fun renderSoftwareFrame(width: Int, height: Int): MpvSoftwareFrame {
        require(width > 0 && height > 0) { "software frame dimensions must be positive" }
        val stride = (width.toLong() * 4 + 63) / 64 * 64
        require(stride <= configuration.maxSoftwareFrameBytes / height.toLong()) {
            "software frame exceeds maxSoftwareFrameBytes (${configuration.maxSoftwareFrameBytes})"
        }
        return withEngine { native ->
            val result = native.renderSoftwareFrame(width, height)
            checkError(result.errorCode, "render a software frame")
            val frame = checkNotNull(result.value) { "libmpv returned no software frame" }
            MpvSoftwareFrame(width, height, frame.strideBytes, frame.pixels)
        }
    }

    override suspend fun release(): Unit = withContext(dispatcher + NonCancellable) {
        lifecycleMutex.withLock {
            if (engineClosed) return@withLock
            released = true
            try {
                engine.wakeup()
            } finally {
                try {
                    eventJob.cancelAndJoin()
                    engineMutex.withLock { engine.close(); engineClosed = true }
                } finally {
                    mutableState.value = MpvPlaybackState(status = MpvPlaybackStatus.Released)
                    scope.cancel()
                }
            }
        }
    }

    private suspend fun <T> withEngine(block: (MpvEngine) -> T): T = withContext(dispatcher) {
        lifecycleMutex.withLock {
            ensureNotReleased()
            engine.wakeup()
            engineMutex.withLock { block(engine) }
        }
    }

    private suspend fun eventLoop() {
        try {
            var eventsSinceYield = 0
            while (true) {
                currentCoroutineContext().ensureActive()
                val event = engineMutex.withLock {
                    engine.waitEvent(configuration.eventPollTimeoutSeconds)
                }
                if (event.eventId == NativeEventId.NONE) {
                    delay(1)
                    continue
                }
                handleEvent(event)
                if (event.eventId == NativeEventId.SHUTDOWN) break
                if (++eventsSinceYield == 32) {
                    eventsSinceYield = 0
                    yield()
                }
            }
        } catch (cancelled: CancellationException) {
            throw cancelled
        } catch (failure: Throwable) {
            val message = failure.message ?: failure::class.simpleName ?: "mpv event loop failed"
            mutableState.value = mutableState.value.copy(
                status = MpvPlaybackStatus.Error,
                lastError = message,
            )
            mutableEvents.tryEmit(
                MpvEvent.LogMessage("kmp-mpv", MpvLogLevel.Error, message),
            )
        }
    }

    private fun handleEvent(raw: RawMpvEvent) {
        val event = raw.toPublicEvent(engine::errorString)
        if (event != null) mutableEvents.tryEmit(event)

        when (raw.eventId) {
            NativeEventId.SHUTDOWN -> updateStatus(MpvPlaybackStatus.Released)
            NativeEventId.START_FILE -> updateStatus(MpvPlaybackStatus.Loading)
            NativeEventId.FILE_LOADED -> {
                mutableState.value = mutableState.value.copy(
                    status = if (mutableState.value.paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing,
                    lastError = null,
                )
            }
            NativeEventId.SEEK -> mutableState.value = mutableState.value.copy(seeking = true)
            NativeEventId.PLAYBACK_RESTART -> {
                mutableState.value = mutableState.value.copy(
                    seeking = false,
                    status = if (mutableState.value.paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing,
                )
            }
            NativeEventId.END_FILE -> {
                val failed = raw.endReason == 4 || raw.endError < 0
                mutableState.value = mutableState.value.copy(
                    status = if (failed) MpvPlaybackStatus.Error else MpvPlaybackStatus.Ended,
                    seeking = false,
                    lastError = raw.endError.takeIf { it < 0 }?.let(engine::errorString),
                )
            }
            NativeEventId.PROPERTY_CHANGE -> updateStateFromProperty(raw.propertyName, raw.propertyValue)
        }
    }

    private fun updateStateFromProperty(name: String?, value: MpvValue) {
        val current = mutableState.value
        mutableState.value = when (name) {
            "pause" -> {
                val paused = (value as? MpvValue.Flag)?.value ?: current.paused
                current.copy(
                    paused = paused,
                    status = when (current.status) {
                        MpvPlaybackStatus.Playing,
                        MpvPlaybackStatus.Paused,
                        -> if (paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing
                        else -> current.status
                    },
                )
            }
            "path" -> current.copy(mediaPath = (value as? MpvValue.Text)?.value)
            "media-title" -> current.copy(mediaTitle = (value as? MpvValue.Text)?.value)
            "time-pos" -> current.copy(positionSeconds = (value as? MpvValue.Decimal)?.value ?: 0.0)
            "duration" -> current.copy(durationSeconds = (value as? MpvValue.Decimal)?.value)
            "seekable" -> current.copy(seekable = (value as? MpvValue.Flag)?.value ?: false)
            "volume" -> current.copy(volume = (value as? MpvValue.Decimal)?.value ?: current.volume)
            "mute" -> current.copy(muted = (value as? MpvValue.Flag)?.value ?: current.muted)
            "speed" -> current.copy(speed = (value as? MpvValue.Decimal)?.value ?: current.speed)
            "video-params/w" -> current.copy(videoWidth = (value as? MpvValue.Integer)?.value)
            "video-params/h" -> current.copy(videoHeight = (value as? MpvValue.Integer)?.value)
            else -> current
        }
    }

    private fun updateStatus(status: MpvPlaybackStatus) {
        mutableState.value = mutableState.value.copy(status = status)
    }

    private fun ensureNotReleased() {
        check(!released) { "MpvPlayer has been released" }
    }

    private fun checkError(errorCode: Int, action: String) {
        if (errorCode < 0) throw MpvException(errorCode, "Failed to $action: ${engine.errorString(errorCode)}")
    }

    private fun requirePropertyName(name: String) {
        require(name.isNotBlank()) { "property name must not be blank" }
    }

    private companion object {
        const val INTERNAL_OBSERVATION_START = 1L
        const val USER_OBSERVATION_START = 10_000L

        val INTERNAL_PROPERTIES = listOf(
            "pause" to MpvFormat.Flag,
            "path" to MpvFormat.String,
            "media-title" to MpvFormat.String,
            "time-pos" to MpvFormat.Double,
            "duration" to MpvFormat.Double,
            "seekable" to MpvFormat.Flag,
            "volume" to MpvFormat.Double,
            "mute" to MpvFormat.Flag,
            "speed" to MpvFormat.Double,
            "video-params/w" to MpvFormat.Int64,
            "video-params/h" to MpvFormat.Int64,
        )
    }
}

private fun RawMpvEvent.toPublicEvent(errorString: (Int) -> String): MpvEvent? = when (eventId) {
    NativeEventId.NONE -> null
    NativeEventId.SHUTDOWN -> MpvEvent.Lifecycle(MpvLifecycleEvent.Shutdown)
    NativeEventId.START_FILE -> MpvEvent.Lifecycle(MpvLifecycleEvent.StartFile)
    NativeEventId.FILE_LOADED -> MpvEvent.Lifecycle(MpvLifecycleEvent.FileLoaded)
    NativeEventId.VIDEO_RECONFIG -> MpvEvent.Lifecycle(MpvLifecycleEvent.VideoReconfigured)
    NativeEventId.AUDIO_RECONFIG -> MpvEvent.Lifecycle(MpvLifecycleEvent.AudioReconfigured)
    NativeEventId.SEEK -> MpvEvent.Lifecycle(MpvLifecycleEvent.Seek)
    NativeEventId.PLAYBACK_RESTART -> MpvEvent.Lifecycle(MpvLifecycleEvent.PlaybackRestart)
    NativeEventId.PROPERTY_CHANGE -> MpvEvent.PropertyChanged(
        replyUserData,
        propertyName.orEmpty(),
        propertyValue,
    )
    NativeEventId.LOG_MESSAGE -> MpvEvent.LogMessage(
        logPrefix.orEmpty(),
        logLevel.toLogLevel(),
        logText.orEmpty(),
    )
    NativeEventId.END_FILE -> MpvEvent.EndFile(
        reason = when (endReason) {
            0 -> MpvEndFileReason.Eof
            2 -> MpvEndFileReason.Stop
            3 -> MpvEndFileReason.Quit
            4 -> MpvEndFileReason.Error
            5 -> MpvEndFileReason.Redirect
            else -> MpvEndFileReason.Unknown
        },
        errorCode = endError,
        errorMessage = endError.takeIf { it < 0 }?.let(errorString),
    )
    NativeEventId.CLIENT_MESSAGE -> MpvEvent.ClientMessage(clientArguments)
    NativeEventId.GET_PROPERTY_REPLY -> reply(MpvReplyKind.GetProperty, errorString)
    NativeEventId.SET_PROPERTY_REPLY -> reply(MpvReplyKind.SetProperty, errorString)
    NativeEventId.COMMAND_REPLY -> reply(MpvReplyKind.Command, errorString)
    NativeEventId.QUEUE_OVERFLOW -> MpvEvent.QueueOverflow
    else -> MpvEvent.Unknown(eventId)
}

private fun RawMpvEvent.reply(kind: MpvReplyKind, errorString: (Int) -> String): MpvEvent.Reply =
    MpvEvent.Reply(
        kind = kind,
        requestId = replyUserData,
        errorCode = errorCode,
        errorMessage = errorCode.takeIf { it < 0 }?.let(errorString),
    )

private fun Int.toLogLevel(): MpvLogLevel = when (this) {
    10 -> MpvLogLevel.Fatal
    20 -> MpvLogLevel.Error
    30 -> MpvLogLevel.Warn
    40 -> MpvLogLevel.Info
    50 -> MpvLogLevel.Verbose
    60 -> MpvLogLevel.Debug
    70 -> MpvLogLevel.Trace
    else -> MpvLogLevel.None
}

Check your understanding

Race a command with an event burst and concurrent release. Confirm no native call occurs after destruction and repeated release remains safe. [chapter-content-end]: #

Step 3: implement desktop JNA transport

Rebuild JnaMpvEngine, MpvBundledLibrary and render-target actuals. Resolve explicit library paths first; otherwise extract pinned Windows/macOS resources atomically. Linux expects a system libmpv. Decode native structures with the source's verified layouts and copy payloads rather than retaining reused pointers.

Support native window wid embedding and Compose-compatible software rendering with vo=libmpv. Create the software render context before a media load can wait on a missing video output. Use aligned bgr0 native buffers/stride and an independently owned managed frame array; close allocations on resize and release. Detach native windows using wid=-1, not the read-only window-id property.

On macOS, keep sibling frameworks/rpaths and preload Lua when required by the selected binary. Windows packages libmpv-2.dll; do not substitute a differently shaped ABI silently.

Follow the code

The desktop transport maps client/render APIs and native structures through JNA. Library resolution honors an explicit path before bundled resources/system lookup. Native window embedding uses writable wid; software rendering owns its aligned buffer and copied managed frame. Recreate render-context creation before loads that wait for VO, plus resize/detach/release ordering. Package the sibling native dependencies expected by the chosen binary.

Write these files in this order:

  • vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/JnaMpvEngine.kt
  • vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/MpvBundledLibrary.kt
  • vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/MpvRenderTarget.desktop.kt
  • vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/MediaProcessRunner.kt
  • vendor/kmp-mpv/samples/desktop/Main.kt

Write vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/JnaMpvEngine.kt

Create this path in your reconstruction project. Source set: desktopMain. Exact file download.

The implementation below defines createPlatformMpvEngine, JnaMpvEngine, command, getProperty, setProperty, observeProperty, unobserveProperty, requestLogMessages, waitEvent, attachRenderTarget and 48 further declarations.

package io.github.kmpmpv.internal

import com.sun.jna.Library
import com.sun.jna.Memory
import com.sun.jna.Native
import com.sun.jna.NativeLibrary
import com.sun.jna.Platform
import com.sun.jna.Pointer
import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvException
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvValue
import java.io.File

internal actual fun createPlatformMpvEngine(configuration: MpvConfiguration): MpvEngine =
    JnaMpvEngine(configuration)

private class JnaMpvEngine(configuration: MpvConfiguration) : MpvEngine {
    private val library = loadLibrary(configuration.libraryPath)
    private val handle: Pointer
    private var softwareRenderContext: Pointer? = null
    private var softwareBuffer: SoftwareRenderBuffer? = null
    private var closed = false

    init {
        pinNumericLocale()
        handle = library.mpv_create()
            ?: throw MpvException(ERROR_UNINITIALIZED, "libmpv could not create a client context")
        try {
            val platformOptions = mapOf("vo" to "gpu") + configuration.options
            platformOptions.forEach { (name, value) ->
                check(library.mpv_set_option_string(handle, name, value), "set option '$name'")
            }
            check(library.mpv_request_log_messages(handle, configuration.logLevel.mpvName), "configure logging")
            check(library.mpv_initialize(handle), "initialize libmpv")
            if (platformOptions["vo"] == "libmpv") {
                check(createSoftwareRenderContext(), "create software render context")
            }
        } catch (failure: Throwable) {
            library.mpv_terminate_destroy(handle)
            closed = true
            throw failure
        }
    }

    override fun command(arguments: List<String>): Int =
        library.mpv_command(handle, (arguments + null).toTypedArray())

    override fun getProperty(name: String, format: MpvFormat): EngineResult<MpvValue> = when (format) {
        MpvFormat.String,
        MpvFormat.OsdString,
        -> {
            Memory(Native.POINTER_SIZE.toLong()).useMemory {
                val result = library.mpv_get_property(handle, name, format.nativeValue, this)
                if (result < 0) {
                    EngineResult(result)
                } else {
                    val value = getPointer(0)
                    try {
                        EngineResult(result, MpvValue.Text(value?.getString(0, Charsets.UTF_8.name()).orEmpty()))
                    } finally {
                        if (value != null) library.mpv_free(value)
                    }
                }
            }
        }
        MpvFormat.Flag -> scalarProperty(name, format, 4) { MpvValue.Flag(it.getInt(0) != 0) }
        MpvFormat.Int64 -> scalarProperty(name, format, 8) { MpvValue.Integer(it.getLong(0)) }
        MpvFormat.Double -> scalarProperty(name, format, 8) { MpvValue.Decimal(it.getDouble(0)) }
        MpvFormat.None -> EngineResult(ERROR_INVALID_PARAMETER)
    }

    override fun setProperty(name: String, value: MpvValue): Int = when (value) {
        is MpvValue.Text -> library.mpv_set_property_string(handle, name, value.value)
        is MpvValue.Flag -> Memory(4).useMemory {
            setInt(0, if (value.value) 1 else 0)
            library.mpv_set_property(handle, name, MpvFormat.Flag.nativeValue, this)
        }
        is MpvValue.Integer -> Memory(8).useMemory {
            setLong(0, value.value)
            library.mpv_set_property(handle, name, MpvFormat.Int64.nativeValue, this)
        }
        is MpvValue.Decimal -> Memory(8).useMemory {
            setDouble(0, value.value)
            library.mpv_set_property(handle, name, MpvFormat.Double.nativeValue, this)
        }
        MpvValue.None -> ERROR_INVALID_PARAMETER
    }

    override fun observeProperty(
        observationId: Long,
        name: String,
        format: MpvFormat,
    ): Int = library.mpv_observe_property(handle, observationId, name, format.nativeValue)

    override fun unobserveProperty(observationId: Long): Int =
        library.mpv_unobserve_property(handle, observationId)

    override fun requestLogMessages(level: String): Int = library.mpv_request_log_messages(handle, level)

    override fun waitEvent(timeoutSeconds: Double): RawMpvEvent {
        val pointer = library.mpv_wait_event(handle, timeoutSeconds) ?: return RawMpvEvent(NativeEventId.NONE)
        val event = pointer.readNativeMpvEvent()
        return when (event.eventId) {
            NativeEventId.PROPERTY_CHANGE -> parsePropertyEvent(event)
            NativeEventId.LOG_MESSAGE -> parseLogEvent(event)
            NativeEventId.END_FILE -> parseEndFileEvent(event)
            NativeEventId.CLIENT_MESSAGE -> parseClientMessageEvent(event)
            else -> RawMpvEvent(
                eventId = event.eventId,
                errorCode = event.error,
                replyUserData = event.replyUserData,
            )
        }
    }

    override fun attachRenderTarget(target: MpvRenderTarget): Int = Memory(8).useMemory {
        setLong(0, target.nativeWindowHandle)
        library.mpv_set_option(handle, "wid", MpvFormat.Int64.nativeValue, this)
    }

    override fun detachRenderTarget(): Int = Memory(8).useMemory {
        // mpv reserves -1 for detaching to its own window. Zero means the X11
        // root window or Windows desktop, which is not a safe generic detach.
        setLong(0, -1)
        library.mpv_set_option(handle, "wid", MpvFormat.Int64.nativeValue, this)
    }

    override fun updateRenderTargetSize(width: Int, height: Int): Int = 0

    override fun renderSoftwareFrame(width: Int, height: Int): EngineResult<RawSoftwareFrame> {
        val createResult = createSoftwareRenderContext()
        if (createResult < 0) return EngineResult(createResult)
        val context = softwareRenderContext ?: return EngineResult(ERROR_UNINITIALIZED)

        var buffer = softwareBuffer
        if (buffer == null || buffer.width != width || buffer.height != height) {
            softwareBuffer = null
            buffer?.close()
            buffer = SoftwareRenderBuffer(width, height)
            softwareBuffer = buffer
        }
        library.mpv_render_context_update(context)
        val result = library.mpv_render_context_render(context, buffer.params)
        if (result < 0) return EngineResult(result)
        // Each returned frame owns its pixels; future renders cannot mutate retained frames.
        return EngineResult(0, RawSoftwareFrame(buffer.stride, buffer.pixels.getByteArray(0, buffer.byteCount)))
    }

    private fun createSoftwareRenderContext(): Int {
        if (softwareRenderContext != null) return 0
        return Memory(Native.POINTER_SIZE.toLong()).useMemory {
            val output = this
            clear()
            Memory(3).useMemory {
                setString(0, "sw")
                renderParams(RENDER_PARAM_API_TYPE to this).useMemory {
                    val result = library.mpv_render_context_create(output, handle, this)
                    if (result < 0) result else {
                        softwareRenderContext = output.getPointer(0)
                        if (softwareRenderContext == null) ERROR_UNINITIALIZED else 0
                    }
                }
            }
        }
    }

    override fun errorString(errorCode: Int): String =
        library.mpv_error_string(errorCode)?.getString(0, Charsets.UTF_8.name())
            ?: "unknown mpv error ($errorCode)"

    override fun wakeup() {
        if (!closed) library.mpv_wakeup(handle)
    }

    override fun close() {
        if (closed) return
        closed = true
        softwareRenderContext?.let(library::mpv_render_context_free)
        softwareRenderContext = null
        softwareBuffer?.close()
        softwareBuffer = null
        library.mpv_terminate_destroy(handle)
    }

    private fun scalarProperty(
        name: String,
        format: MpvFormat,
        bytes: Long,
        convert: (Memory) -> MpvValue,
    ): EngineResult<MpvValue> = Memory(bytes).useMemory {
        val result = library.mpv_get_property(handle, name, format.nativeValue, this)
        EngineResult(result, if (result < 0) null else convert(this))
    }

    private fun parsePropertyEvent(event: NativeMpvEvent): RawMpvEvent {
        val property = event.data?.let(::NativeMpvEventProperty)
        return RawMpvEvent(
            eventId = event.eventId,
            errorCode = event.error,
            replyUserData = event.replyUserData,
            propertyName = property?.name?.getString(0, Charsets.UTF_8.name()),
            propertyValue = property?.toValue() ?: MpvValue.None,
        )
    }

    private fun parseLogEvent(event: NativeMpvEvent): RawMpvEvent {
        val log = event.data?.let(::NativeMpvEventLogMessage)
        return RawMpvEvent(
            eventId = event.eventId,
            errorCode = event.error,
            replyUserData = event.replyUserData,
            logPrefix = log?.prefix?.getString(0, Charsets.UTF_8.name()),
            logLevel = log?.logLevel ?: 0,
            logText = log?.text?.getString(0, Charsets.UTF_8.name()),
        )
    }

    private fun parseEndFileEvent(event: NativeMpvEvent): RawMpvEvent {
        val endFile = event.data?.let(::NativeMpvEventEndFile)
        return RawMpvEvent(
            eventId = event.eventId,
            errorCode = event.error,
            replyUserData = event.replyUserData,
            endReason = endFile?.reason ?: 0,
            endError = endFile?.error ?: 0,
        )
    }

    private fun parseClientMessageEvent(event: NativeMpvEvent): RawMpvEvent {
        val message = event.data?.let(::NativeMpvEventClientMessage)
        val argumentPointers = message?.arguments
        val arguments = if (argumentPointers == null) {
            emptyList()
        } else {
            (0 until message.count).mapNotNull { index ->
                argumentPointers.getPointer(index.toLong() * Native.POINTER_SIZE)
                    ?.getString(0, Charsets.UTF_8.name())
            }
        }
        return RawMpvEvent(
            eventId = event.eventId,
            errorCode = event.error,
            replyUserData = event.replyUserData,
            clientArguments = arguments,
        )
    }

    private fun check(errorCode: Int, action: String) {
        if (errorCode < 0) throw MpvException(errorCode, "Failed to $action: ${errorString(errorCode)}")
    }

    private companion object {
        const val ERROR_UNINITIALIZED = -3
        const val ERROR_INVALID_PARAMETER = -4

        const val RENDER_PARAM_API_TYPE = 1
    }
}

private interface LibMpv : Library {
    fun mpv_create(): Pointer?

    fun mpv_initialize(handle: Pointer): Int

    fun mpv_set_option_string(handle: Pointer, name: String, value: String): Int

    fun mpv_set_option(handle: Pointer, name: String, format: Int, data: Pointer): Int

    fun mpv_command(handle: Pointer, arguments: Array<String?>): Int

    fun mpv_get_property(handle: Pointer, name: String, format: Int, data: Pointer): Int

    fun mpv_set_property(handle: Pointer, name: String, format: Int, data: Pointer): Int

    fun mpv_set_property_string(handle: Pointer, name: String, value: String): Int

    fun mpv_observe_property(handle: Pointer, replyUserData: Long, name: String, format: Int): Int

    fun mpv_unobserve_property(handle: Pointer, replyUserData: Long): Int

    fun mpv_request_log_messages(handle: Pointer, minLevel: String): Int

    fun mpv_wait_event(handle: Pointer, timeoutSeconds: Double): Pointer?

    fun mpv_error_string(errorCode: Int): Pointer?

    fun mpv_free(data: Pointer)

    fun mpv_wakeup(handle: Pointer)

    fun mpv_terminate_destroy(handle: Pointer)

    fun mpv_render_context_create(context: Pointer, handle: Pointer, params: Pointer): Int

    fun mpv_render_context_update(context: Pointer): Long

    fun mpv_render_context_render(context: Pointer, params: Pointer): Int

    fun mpv_render_context_free(context: Pointer)
}

private data class NativeMpvEvent(
    val eventId: Int,
    val error: Int,
    val replyUserData: Long,
    val data: Pointer?,
)

private data class NativeMpvEventProperty(
    val name: Pointer?,
    val format: Int,
    val data: Pointer?,
) {

    fun toValue(): MpvValue = when (format) {
        MpvFormat.String.nativeValue,
        MpvFormat.OsdString.nativeValue,
        -> data?.getString(0, Charsets.UTF_8.name())?.let(MpvValue::Text) ?: MpvValue.None
        MpvFormat.Flag.nativeValue -> data?.getInt(0)?.let { MpvValue.Flag(it != 0) } ?: MpvValue.None
        MpvFormat.Int64.nativeValue -> data?.getLong(0)?.let(MpvValue::Integer) ?: MpvValue.None
        MpvFormat.Double.nativeValue -> data?.getDouble(0)?.let(MpvValue::Decimal) ?: MpvValue.None
        else -> MpvValue.None
    }
}

private data class NativeMpvEventLogMessage(
    val prefix: Pointer?,
    val level: Pointer?,
    val text: Pointer?,
    val logLevel: Int,
)

private data class NativeMpvEventEndFile(
    val reason: Int,
    val error: Int,
    val playlistEntryId: Long,
    val playlistInsertId: Long,
    val playlistInsertNumEntries: Int,
)

private data class NativeMpvEventClientMessage(
    val count: Int,
    val arguments: Pointer?,
)

private fun Pointer.readNativeMpvEvent(): NativeMpvEvent = NativeMpvEvent(
    eventId = getInt(0),
    error = getInt(4),
    replyUserData = getLong(8),
    data = getPointer(16),
)

private fun NativeMpvEventProperty(pointer: Pointer): NativeMpvEventProperty = NativeMpvEventProperty(
    name = pointer.getPointer(0),
    format = pointer.getInt(Native.POINTER_SIZE.toLong()),
    data = pointer.getPointer(Native.POINTER_SIZE.toLong() * 2),
)

private fun NativeMpvEventLogMessage(pointer: Pointer): NativeMpvEventLogMessage =
    NativeMpvEventLogMessage(
        prefix = pointer.getPointer(0),
        level = pointer.getPointer(Native.POINTER_SIZE.toLong()),
        text = pointer.getPointer(Native.POINTER_SIZE.toLong() * 2),
        logLevel = pointer.getInt(Native.POINTER_SIZE.toLong() * 3),
    )

private fun NativeMpvEventEndFile(pointer: Pointer): NativeMpvEventEndFile = NativeMpvEventEndFile(
    reason = pointer.getInt(0),
    error = pointer.getInt(4),
    playlistEntryId = pointer.getLong(8),
    playlistInsertId = pointer.getLong(16),
    playlistInsertNumEntries = pointer.getInt(24),
)

private fun NativeMpvEventClientMessage(pointer: Pointer): NativeMpvEventClientMessage =
    NativeMpvEventClientMessage(
        count = pointer.getInt(0),
        arguments = pointer.getPointer(if (Native.POINTER_SIZE == Long.SIZE_BYTES) 8 else 4),
    )

private fun renderParams(vararg values: Pair<Int, Pointer>): Memory {
    val pointerOffset = if (Native.POINTER_SIZE == Long.SIZE_BYTES) 8L else 4L
    val parameterSize = pointerOffset + Native.POINTER_SIZE
    return Memory(parameterSize * (values.size + 1)).apply {
        clear()
        values.forEachIndexed { index, (type, data) ->
            val offset = parameterSize * index
            setInt(offset, type)
            setPointer(offset + pointerOffset, data)
        }
    }
}

private fun loadLibrary(explicitPath: String?): LibMpv {
    val candidates = explicitPath?.let(::listOf)
        ?: listOfNotNull(MpvBundledLibrary.resolve()) + defaultLibraryCandidates()
    val failures = mutableListOf<String>()
    for (candidate in candidates) {
        try {
            return Native.load(
                candidate,
                LibMpv::class.java,
                mapOf(Library.OPTION_STRING_ENCODING to Charsets.UTF_8.name()),
            )
        } catch (failure: UnsatisfiedLinkError) {
            failures += "$candidate (${failure.message})"
        }
    }
    throw MpvException(
        -3,
        "Unable to load libmpv. Tried: ${failures.joinToString()}. " +
            "Install libmpv or set MpvConfiguration.libraryPath.",
    )
}

/**
 * libmpv refuses to create a client unless LC_NUMERIC is "C", but the JVM adopts the user's locale
 * (e.g. LANG=en_US.UTF-8). Java formatting uses its own Locale, so pinning the C category is safe.
 */
private fun pinNumericLocale() {
    val lcNumeric = when {
        Platform.isWindows() -> return
        Platform.isMac() -> 4
        else -> 1
    }
    runCatching {
        NativeLibrary.getInstance(Platform.C_LIBRARY_NAME).getFunction("setlocale").invoke(Pointer::class.java, arrayOf<Any>(lcNumeric, "C"))
    }
}

private fun defaultLibraryCandidates(): List<String> {
    val os = System.getProperty("os.name", "").lowercase()
    return when {
        os.contains("win") -> listOf("mpv-2", "mpv-1", "libmpv-2.dll", "libmpv-1.dll")
        os.contains("mac") -> listOf(
            "mpv",
            "/opt/homebrew/lib/libmpv.dylib",
            "/usr/local/lib/libmpv.dylib",
        ).filter { !it.startsWith(File.separator) || File(it).exists() }
        else -> listOf("mpv", "libmpv.so.2", "libmpv.so.1")
    }
}

private inline fun <T> Memory.useMemory(block: Memory.() -> T): T = try {
    block()
} finally {
    close()
}

/** Owns all native render allocations, reused until size changes or the player is released. */
private class SoftwareRenderBuffer(val width: Int, val height: Int) : AutoCloseable {
    val stride = Math.addExact(Math.multiplyExact(width, 4), 63) and -64
    val byteCount = Math.multiplyExact(stride, height)
    private val allocations = ArrayList<Memory>(6)
    val pixels: Memory
    val params: Memory

    init {
        try {
            pixels = allocate(byteCount.toLong() + 63).apply { clear() }.align(64)
            val size = allocate(8).apply {
                setInt(0, width)
                setInt(4, height)
            }
            val format = allocate(5).apply { setString(0, "bgr0") }
            val nativeStride = allocate(Native.POINTER_SIZE.toLong()).apply {
                if (Native.POINTER_SIZE == 8) setLong(0, stride.toLong()) else setInt(0, stride)
            }
            params = renderParams(17 to size, 18 to format, 19 to nativeStride, 20 to pixels)
                .also(allocations::add)
        } catch (failure: Throwable) {
            close()
            throw failure
        }
    }

    private fun allocate(bytes: Long): Memory = Memory(bytes).also(allocations::add)

    override fun close() {
        allocations.asReversed().forEach(Memory::close)
        allocations.clear()
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/MpvBundledLibrary.kt

Create this path in your reconstruction project. Source set: desktopMain. Exact file download.

The implementation below defines MpvBundledLibrary, resolve.

package io.github.kmpmpv.internal

import com.sun.jna.NativeLibrary
import java.nio.file.Files
import java.nio.file.StandardCopyOption

internal object MpvBundledLibrary {
    private const val BUNDLE_ID = "media-kit-mpv-2025-08"

    @Volatile
    private var resolved: String? = null
    private val preloadedLibraries = mutableListOf<NativeLibrary>()

    @Synchronized
    fun resolve(): String? {
        resolved?.let { return it }
        val os = System.getProperty("os.name", "").lowercase()
        if ("linux" in os || "freebsd" in os) return null

        val manifest = MpvBundledLibrary::class.java.getResourceAsStream("/native/manifest.txt")
            ?.bufferedReader()
            ?.useLines { lines -> lines.filter(String::isNotBlank).toList() }
            .orEmpty()
        if (manifest.isEmpty()) return null

        val root = Files.createTempDirectory(BUNDLE_ID).toFile().apply { deleteOnExit() }
        manifest.forEach { resource ->
            val destination = root.resolve(resource)
            destination.parentFile.mkdirs()
            val input = checkNotNull(MpvBundledLibrary::class.java.getResourceAsStream("/$resource")) {
                "Bundled mpv resource is missing: $resource"
            }
            input.use {
                Files.copy(it, destination.toPath(), StandardCopyOption.REPLACE_EXISTING)
            }
            destination.setExecutable(true)
            destination.deleteOnExit()
        }

        val library = when {
            "win" in os -> root.resolve("native/windows-x86_64/libmpv-2.dll")
            "mac" in os || "darwin" in os -> {
                // The media-kit arm64 Mpv framework resolves Lua lazily and does not list it in
                // LC_LOAD_DYLIB. CocoaPods normally links every vendored framework into the app;
                // reproduce that behavior before JNA initializes mpv's script subsystem.
                val lua = root.resolve("native/macos/Frameworks/Lua.framework/Versions/A/Lua")
                preloadedLibraries += NativeLibrary.getInstance(lua.absolutePath)
                root.resolve("native/macos/Frameworks/Mpv.framework/Versions/A/Mpv")
            }
            else -> return null
        }
        return library.takeIf { it.isFile }?.absolutePath.also { resolved = it }
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/MpvRenderTarget.desktop.kt

Create this path in your reconstruction project. Source set: desktopMain. Exact file download.

The implementation below defines MpvRenderTarget.

The source describes its contract as:

A native parent window handle: HWND on Windows, X11 Window on Linux, or NSView on macOS.

package io.github.kmpmpv

import com.sun.jna.Native
import com.sun.jna.Pointer
import java.awt.Component

/**
 * A native parent window handle: HWND on Windows, X11 Window on Linux, or NSView on macOS.
 */
public actual class MpvRenderTarget(public val nativeWindowHandle: Long) {
    /** Creates a render target from a displayable AWT component. */
    public constructor(component: Component) : this(
        Pointer.nativeValue(Native.getComponentPointer(component)),
    )
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/internal/MediaProcessRunner.kt

Create this path in your reconstruction project. Source set: desktopMain. Exact file download.

The implementation below defines interface, run, SystemMediaProcessRunner, DiagnosticTail, append, text.

The source describes its contract as:

Drains both output streams with a fixed-size diagnostic tail; never invokes a shell.

package io.github.kmpmpv.internal

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException

internal fun interface MediaProcessRunner {
    suspend fun run(arguments: List<String>)
}

/** Drains both output streams with a fixed-size diagnostic tail; never invokes a shell. */
internal class SystemMediaProcessRunner : MediaProcessRunner {
    override suspend fun run(arguments: List<String>): Unit = withContext(Dispatchers.IO) {
        currentCoroutineContext().ensureActive()
        val process = try {
            ProcessBuilder(arguments).redirectErrorStream(true).start()
        } catch (failure: IOException) {
            throw IOException("Cannot start ${arguments.first()}; install it or configure its executable path", failure)
        }
        val tail = DiagnosticTail(16 * 1024)
        try {
            process.outputStream.close()
            coroutineScope {
                val reader = launch(Dispatchers.IO) {
                    try {
                        process.inputStream.use { input ->
                            val buffer = ByteArray(4096)
                            while (true) {
                                val count = input.read(buffer)
                                if (count < 0) break
                                tail.append(buffer, count)
                            }
                        }
                    } catch (failure: IOException) {
                        // destroy() can close a pipe while read() is blocked. Keep cancellation
                        // as cancellation instead of surfacing an unrelated "stream closed".
                        currentCoroutineContext().ensureActive()
                        throw failure
                    }
                }
                // A cancellable wait allows finally to terminate the process before joining
                // the blocking pipe reader. Waiting for the reader first would deadlock.
                try {
                    while (process.isAlive) delay(25)
                } finally {
                    withContext(NonCancellable) {
                        if (process.isAlive) {
                            process.destroy()
                            repeat(10) { if (process.isAlive) delay(25) }
                            if (process.isAlive) process.destroyForcibly()
                        }
                        while (process.isAlive) delay(25)
                    }
                }
                reader.join()
            }
            check(process.exitValue() == 0) {
                "${arguments.first()} exited with ${process.exitValue()}: ${tail.text()}"
            }
        } finally {
            if (process.isAlive) {
                process.destroyForcibly()
                withContext(NonCancellable) { while (process.isAlive) delay(25) }
            }
            process.inputStream.close()
            process.errorStream.close()
            process.outputStream.close()
        }
    }
}

internal class DiagnosticTail(private val capacity: Int) {
    private val bytes = ByteArray(capacity)
    private var cursor = 0
    private var size = 0

    fun append(source: ByteArray, count: Int) {
        for (index in 0 until count) {
            bytes[cursor] = source[index]
            cursor = (cursor + 1) % capacity
        }
        size = (size + count).coerceAtMost(capacity)
    }

    fun text(): String = ByteArray(size) { bytes[(cursor - size + it + capacity) % capacity] }
        .toString(Charsets.UTF_8)
}

Write vendor/kmp-mpv/samples/desktop/Main.kt

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

The implementation below defines main.

import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvPlayer
import kotlinx.coroutines.runBlocking

fun main(args: Array<String>) = runBlocking {
    require(args.isNotEmpty()) { "Pass a media path or URL" }
    val player = MpvPlayer.create(
        MpvConfiguration(
            options = MpvConfiguration.DefaultOptions + mapOf(
                "force-window" to "yes",
                "keep-open" to "yes",
            ),
        ),
    )
    try {
        player.load(args.first())
        player.events.collect(::println)
    } finally {
        player.release()
    }
}

Check your understanding

Resize software rendering repeatedly and detach a native window. Check old allocations/handles are released and no frame points into a reused native buffer. [chapter-content-end]: #

Step 4: implement Android JNI and surfaces

Write Java MpvNative/MpvNativeEvent, CMake, ABI header and C++ shim. The shim owns dlopen, the mpv client and JNI global Surface reference; copy event payloads to JVM objects. AndroidMpvEngine bridges this to the common engine.

Surface attach sets the writable wid. Before releasing a Surface reference, stop VO use (vo=null) and detach correctly. Failed detach retains ownership for retry/final destruction. Destroy mpv before deleting the final global reference. Replace an attached surface by detaching the prior one first. Recreate resize and MpvSurfaceView lifecycle ordering.

Follow the code

The C++ bridge owns dynamic library access, mpv client handles and global Surface references. Java event objects copy native payloads across JNI. AndroidMpvEngine adapts this to the common engine contract. Surface replacement detaches the prior target before releasing its reference; failed detach retains ownership for retry/destruction. Destroy the player before deleting its last global Surface reference.

Write these files in this order:

  • vendor/kmp-mpv/android-bridge/build.gradle.kts
  • vendor/kmp-mpv/android-bridge/consumer-rules.pro
  • vendor/kmp-mpv/android-bridge/src/main/AndroidManifest.xml
  • vendor/kmp-mpv/android-bridge/src/main/cpp/CMakeLists.txt
  • vendor/kmp-mpv/android-bridge/src/main/cpp/kmpmpv_bridge.cpp
  • vendor/kmp-mpv/android-bridge/src/main/cpp/mpv_abi.h
  • vendor/kmp-mpv/android-bridge/src/main/java/io/github/kmpmpv/bridge/MpvNative.java
  • vendor/kmp-mpv/android-bridge/src/main/java/io/github/kmpmpv/bridge/MpvNativeEvent.java
  • vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/MpvRenderTarget.android.kt
  • vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/MpvSurfaceView.kt
  • vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/internal/AndroidMpvEngine.kt
  • vendor/kmp-mpv/samples/android/MpvActivitySnippet.kt

Write vendor/kmp-mpv/android-bridge/build.gradle.kts

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

import java.net.URI
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest

plugins {
    alias(libs.plugins.android.library)
    `maven-publish`
}

data class MediaKitAndroidArtifact(
    val abi: String,
    val url: String,
    val sha256: String,
)

val mediaKitAndroidArtifacts = listOf(
    MediaKitAndroidArtifact(
        "arm64-v8a",
        "https://github.com/Schnitzel5/libmpv-android-video-build/releases/download/0.39.0/default-arm64-v8a.jar",
        "db5cf9abd385771092921dff6db0a216a8926deba4d683698d7f8d13467063b7",
    ),
    MediaKitAndroidArtifact(
        "armeabi-v7a",
        "https://github.com/Schnitzel5/libmpv-android-video-build/releases/download/0.39.0/default-armeabi-v7a.jar",
        "130d77e4ecf9f4c83c5b49fa6f9774004bb9a6def684f4381e4a38e6e21ae752",
    ),
    MediaKitAndroidArtifact(
        "x86_64",
        "https://github.com/Schnitzel5/libmpv-android-video-build/releases/download/0.39.0/default-x86_64.jar",
        "faf41da663c2b70c11acb665918b484c28e8392e4be26fdbf8c7994af0054fd9",
    ),
    MediaKitAndroidArtifact(
        "x86",
        "https://github.com/Schnitzel5/libmpv-android-video-build/releases/download/0.39.0/default-x86.jar",
        "0bf2693c5830af3d1619b359c6d6a6eff804a9753ea31b36a2ecabc14359a44b",
    ),
)

val mediaKitAndroidDirectory = layout.buildDirectory.dir("media-kit-mpv/android-0.39.0")
val mediaKitAndroidJars = mediaKitAndroidArtifacts.map { artifact ->
    mediaKitAndroidDirectory.map { it.file("default-${artifact.abi}.jar") }
}

val fetchMediaKitAndroidMpv = tasks.register("fetchMediaKitAndroidMpv") {
    description = "Downloads the Lua-enabled Android libmpv artifacts pinned by media-kit."
    group = "mpv binaries"
    outputs.files(mediaKitAndroidJars)

    doLast {
        val digest = MessageDigest.getInstance("SHA-256")
        mediaKitAndroidArtifacts.zip(mediaKitAndroidJars).forEach { (artifact, destinationProvider) ->
            val destination = destinationProvider.get().asFile
            destination.parentFile.mkdirs()

            fun checksum(file: File): String = digest.digest(Files.readAllBytes(file.toPath()))
                .joinToString("") { byte -> "%02x".format(byte) }

            if (destination.isFile && checksum(destination) == artifact.sha256) return@forEach

            val temporary = destination.resolveSibling("${destination.name}.part")
            temporary.delete()
            URI(artifact.url).toURL().openStream().use { input ->
                Files.copy(input, temporary.toPath(), StandardCopyOption.REPLACE_EXISTING)
            }
            val actual = checksum(temporary)
            check(actual == artifact.sha256) {
                "SHA-256 mismatch for ${artifact.abi}: expected ${artifact.sha256}, got $actual"
            }
            Files.move(
                temporary.toPath(),
                destination.toPath(),
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE,
            )
        }
    }
}

val bundledMediaKitAndroidMpv = files(mediaKitAndroidJars).builtBy(fetchMediaKitAndroidMpv)

dependencies {
    api(bundledMediaKitAndroidMpv)
}

android {
    namespace = "io.github.kmpmpv.bridge"
    compileSdk = 36
    buildToolsVersion = "36.1.0"
    ndkVersion = "28.2.13676358"

    defaultConfig {
        minSdk = 24
        externalNativeBuild {
            cmake {
                // No C++ objects cross the bridge ABI, so static libc++ avoids app packaging collisions.
                arguments += "-DANDROID_STL=c++_static"
                abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
            }
        }
        consumerProguardFiles("consumer-rules.pro")
    }

    externalNativeBuild {
        cmake {
            path = file("src/main/cpp/CMakeLists.txt")
            version = "3.22.1"
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }

    publishing {
        singleVariant("release") {
            withSourcesJar()
        }
    }
}

afterEvaluate {
    publishing {
        publications {
            register<MavenPublication>("release") {
                from(components["release"])
                artifactId = "kmp-mpv-android-bridge"
            }
        }
    }
}

Write vendor/kmp-mpv/android-bridge/consumer-rules.pro

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

-keep class io.github.kmpmpv.bridge.MpvNative { *; }
-keep class io.github.kmpmpv.bridge.MpvNativeEvent { *; }

Write vendor/kmp-mpv/android-bridge/src/main/AndroidManifest.xml

Create this path in your reconstruction project. Source set: main. Exact file download.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" />

Write vendor/kmp-mpv/android-bridge/src/main/cpp/CMakeLists.txt

Create this path in your reconstruction project. Source set: main. Exact file download.

cmake_minimum_required(VERSION 3.22.1)
project(kmpmpv_bridge LANGUAGES CXX)

add_library(kmpmpv_bridge SHARED kmpmpv_bridge.cpp)

target_compile_features(kmpmpv_bridge PRIVATE cxx_std_17)
target_compile_options(kmpmpv_bridge PRIVATE -Wall -Wextra -Werror=return-type)
target_link_libraries(kmpmpv_bridge PRIVATE android log dl)

Write vendor/kmp-mpv/android-bridge/src/main/cpp/kmpmpv_bridge.cpp

Create this path in your reconstruction project. Source set: main. Exact file download.

The implementation below defines UtfChars.

#include <jni.h>

#include <dlfcn.h>

#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "mpv_abi.h"

namespace {

constexpr int MPV_EVENT_LOG_MESSAGE = 2;
constexpr int MPV_EVENT_END_FILE = 7;
constexpr int MPV_EVENT_CLIENT_MESSAGE = 16;
constexpr int MPV_EVENT_PROPERTY_CHANGE = 22;
constexpr int MPV_ERROR_UNINITIALIZED = -3;
constexpr int MPV_ERROR_INVALID_PARAMETER = -4;

struct Api {
    mpv_handle *(*create)();
    int (*set_java_vm)(void *, void *);
    int (*initialize)(mpv_handle *);
    int (*set_option_string)(mpv_handle *, const char *, const char *);
    int (*set_option)(mpv_handle *, const char *, int, void *);
    int (*command)(mpv_handle *, const char **);
    int (*get_property)(mpv_handle *, const char *, int, void *);
    int (*set_property)(mpv_handle *, const char *, int, void *);
    int (*set_property_string)(mpv_handle *, const char *, const char *);
    int (*observe_property)(mpv_handle *, std::uint64_t, const char *, int);
    int (*unobserve_property)(mpv_handle *, std::uint64_t);
    int (*request_log_messages)(mpv_handle *, const char *);
    mpv_event *(*wait_event)(mpv_handle *, double);
    const char *(*error_string)(int);
    void (*free_data)(void *);
    void (*wakeup)(mpv_handle *);
    void (*terminate_destroy)(mpv_handle *);
};

struct Context {
    void *library = nullptr;
    Api api{};
    mpv_handle *handle = nullptr;
    jobject surface = nullptr;
    int last_result = 0;
};

thread_local std::string last_error;

template <typename T>
bool resolve(void *library, const char *name, T *target) {
    *target = reinterpret_cast<T>(dlsym(library, name));
    if (*target) return true;
    last_error = "Missing libmpv symbol: ";
    last_error += name;
    return false;
}

bool resolve_api(void *library, Api *api) {
    return resolve(library, "av_jni_set_java_vm", &api->set_java_vm) &&
           resolve(library, "mpv_create", &api->create) &&
           resolve(library, "mpv_initialize", &api->initialize) &&
           resolve(library, "mpv_set_option_string", &api->set_option_string) &&
           resolve(library, "mpv_set_option", &api->set_option) &&
           resolve(library, "mpv_command", &api->command) &&
           resolve(library, "mpv_get_property", &api->get_property) &&
           resolve(library, "mpv_set_property", &api->set_property) &&
           resolve(library, "mpv_set_property_string", &api->set_property_string) &&
           resolve(library, "mpv_observe_property", &api->observe_property) &&
           resolve(library, "mpv_unobserve_property", &api->unobserve_property) &&
           resolve(library, "mpv_request_log_messages", &api->request_log_messages) &&
           resolve(library, "mpv_wait_event", &api->wait_event) &&
           resolve(library, "mpv_error_string", &api->error_string) &&
           resolve(library, "mpv_free", &api->free_data) &&
           resolve(library, "mpv_wakeup", &api->wakeup) &&
           resolve(library, "mpv_terminate_destroy", &api->terminate_destroy);
}

Context *from_handle(jlong value) {
    return reinterpret_cast<Context *>(static_cast<std::intptr_t>(value));
}

jlong to_handle(Context *context) {
    return static_cast<jlong>(reinterpret_cast<std::intptr_t>(context));
}

class UtfChars {
public:
    UtfChars(JNIEnv *env, jstring value) : env_(env), value_(value) {
        chars_ = value ? env->GetStringUTFChars(value, nullptr) : nullptr;
    }

    ~UtfChars() {
        if (chars_) env_->ReleaseStringUTFChars(value_, chars_);
    }

    const char *get() const { return chars_; }

private:
    JNIEnv *env_;
    jstring value_;
    const char *chars_ = nullptr;
};

jstring new_utf8_string(JNIEnv *env, const char *value) {
    if (!value) return nullptr;
    const jsize length = static_cast<jsize>(std::strlen(value));
    jbyteArray bytes = env->NewByteArray(length);
    if (!bytes) return nullptr;
    env->SetByteArrayRegion(bytes, 0, length, reinterpret_cast<const jbyte *>(value));
    jclass string_type = env->FindClass("java/lang/String");
    jstring charset = env->NewStringUTF("UTF-8");
    jmethodID constructor = env->GetMethodID(string_type, "<init>", "([BLjava/lang/String;)V");
    jstring result = static_cast<jstring>(env->NewObject(string_type, constructor, bytes, charset));
    env->DeleteLocalRef(charset);
    env->DeleteLocalRef(string_type);
    env->DeleteLocalRef(bytes);
    return result;
}

jobject box_long(JNIEnv *env, std::int64_t value) {
    jclass type = env->FindClass("java/lang/Long");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(J)Ljava/lang/Long;");
    return env->CallStaticObjectMethod(type, method, static_cast<jlong>(value));
}

jobject box_boolean(JNIEnv *env, bool value) {
    jclass type = env->FindClass("java/lang/Boolean");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(Z)Ljava/lang/Boolean;");
    return env->CallStaticObjectMethod(type, method, static_cast<jboolean>(value));
}

jobject box_double(JNIEnv *env, double value) {
    jclass type = env->FindClass("java/lang/Double");
    jmethodID method = env->GetStaticMethodID(type, "valueOf", "(D)Ljava/lang/Double;");
    return env->CallStaticObjectMethod(type, method, static_cast<jdouble>(value));
}

jobject property_value(JNIEnv *env, int format, void *data) {
    if (!data) return nullptr;
    switch (format) {
        case MPV_FORMAT_STRING:
        case MPV_FORMAT_OSD_STRING:
            return new_utf8_string(env, static_cast<const char *>(data));
        case MPV_FORMAT_FLAG:
            return box_boolean(env, *static_cast<int *>(data) != 0);
        case MPV_FORMAT_INT64:
            return box_long(env, *static_cast<std::int64_t *>(data));
        case MPV_FORMAT_DOUBLE:
            return box_double(env, *static_cast<double *>(data));
        default:
            return nullptr;
    }
}

jobject read_boxed_value(JNIEnv *env, jobject value, int format, std::int64_t *integer, double *decimal) {
    if (!value) return nullptr;
    switch (format) {
        case MPV_FORMAT_FLAG: {
            jclass type = env->FindClass("java/lang/Boolean");
            jmethodID method = env->GetMethodID(type, "booleanValue", "()Z");
            *integer = env->CallBooleanMethod(value, method) ? 1 : 0;
            return value;
        }
        case MPV_FORMAT_INT64: {
            jclass type = env->FindClass("java/lang/Number");
            jmethodID method = env->GetMethodID(type, "longValue", "()J");
            *integer = env->CallLongMethod(value, method);
            return value;
        }
        case MPV_FORMAT_DOUBLE: {
            jclass type = env->FindClass("java/lang/Number");
            jmethodID method = env->GetMethodID(type, "doubleValue", "()D");
            *decimal = env->CallDoubleMethod(value, method);
            return value;
        }
        default:
            return nullptr;
    }
}

jobjectArray make_string_array(JNIEnv *env, const mpv_event_client_message *message) {
    if (!message || message->num_args <= 0 || !message->args) return nullptr;
    jclass string_type = env->FindClass("java/lang/String");
    jobjectArray result = env->NewObjectArray(message->num_args, string_type, nullptr);
    for (int i = 0; i < message->num_args; ++i) {
        jstring item = new_utf8_string(env, message->args[i]);
        env->SetObjectArrayElement(result, i, item);
        if (item) env->DeleteLocalRef(item);
    }
    return result;
}

jobject make_event(JNIEnv *env, const mpv_event *event) {
    const mpv_event_property *property = nullptr;
    const mpv_event_log_message *log = nullptr;
    const mpv_event_end_file *end_file = nullptr;
    const mpv_event_client_message *client_message = nullptr;

    if (event->event_id == MPV_EVENT_PROPERTY_CHANGE)
        property = static_cast<const mpv_event_property *>(event->data);
    if (event->event_id == MPV_EVENT_LOG_MESSAGE)
        log = static_cast<const mpv_event_log_message *>(event->data);
    if (event->event_id == MPV_EVENT_END_FILE)
        end_file = static_cast<const mpv_event_end_file *>(event->data);
    if (event->event_id == MPV_EVENT_CLIENT_MESSAGE)
        client_message = static_cast<const mpv_event_client_message *>(event->data);

    jstring property_name = property ? new_utf8_string(env, property->name) : nullptr;
    jobject value = property ? property_value(env, property->format, property->data) : nullptr;
    jstring log_prefix = log ? new_utf8_string(env, log->prefix) : nullptr;
    jstring log_text = log ? new_utf8_string(env, log->text) : nullptr;
    jobjectArray arguments = make_string_array(env, client_message);

    jclass type = env->FindClass("io/github/kmpmpv/bridge/MpvNativeEvent");
    jmethodID constructor = env->GetMethodID(
        type,
        "<init>",
        "(IIJLjava/lang/String;Ljava/lang/Object;Ljava/lang/String;ILjava/lang/String;II[Ljava/lang/String;)V");
    jobject result = env->NewObject(
        type,
        constructor,
        event->event_id,
        event->error,
        static_cast<jlong>(event->reply_userdata),
        property_name,
        value,
        log_prefix,
        log ? log->log_level : 0,
        log_text,
        end_file ? end_file->reason : 0,
        end_file ? end_file->error : 0,
        arguments);

    if (property_name) env->DeleteLocalRef(property_name);
    if (value) env->DeleteLocalRef(value);
    if (log_prefix) env->DeleteLocalRef(log_prefix);
    if (log_text) env->DeleteLocalRef(log_text);
    if (arguments) env->DeleteLocalRef(arguments);
    return result;
}

}  // namespace

extern "C" JNIEXPORT jlong JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_create(JNIEnv *env, jclass, jstring library_path) {
    UtfChars requested_path(env, library_path);
    const char *path = requested_path.get() ? requested_path.get() : "libmpv.so";
    void *library = dlopen(path, RTLD_NOW | RTLD_LOCAL);
    if (!library) {
        const char *error = dlerror();
        last_error = error ? error : "dlopen(libmpv) failed";
        return 0;
    }

    std::unique_ptr<Context> context(new Context());
    context->library = library;
    if (!resolve_api(library, &context->api)) {
        dlclose(library);
        return 0;
    }
    JavaVM *java_vm = nullptr;
    if (env->GetJavaVM(&java_vm) != JNI_OK || !java_vm ||
        context->api.set_java_vm(java_vm, nullptr) < 0) {
        last_error = "Failed to register the Android Java VM with libmpv";
        dlclose(library);
        return 0;
    }
    context->handle = context->api.create();
    if (!context->handle) {
        last_error = "mpv_create returned null";
        dlclose(library);
        return 0;
    }
    return to_handle(context.release());
}

extern "C" JNIEXPORT jstring JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_lastError(JNIEnv *env, jclass) {
    return new_utf8_string(env, last_error.c_str());
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_initialize(JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    return context->api.initialize(context->handle);
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_setOptionString(
    JNIEnv *env, jclass, jlong value, jstring name, jstring option_value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    UtfChars native_value(env, option_value);
    return context->api.set_option_string(context->handle, native_name.get(), native_value.get());
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_command(
    JNIEnv *env, jclass, jlong value, jobjectArray arguments) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    const jsize count = env->GetArrayLength(arguments);
    std::vector<std::string> strings;
    strings.reserve(static_cast<std::size_t>(count));
    for (jsize i = 0; i < count; ++i) {
        auto item = static_cast<jstring>(env->GetObjectArrayElement(arguments, i));
        {
            UtfChars text(env, item);
            strings.emplace_back(text.get() ? text.get() : "");
        }
        env->DeleteLocalRef(item);
    }
    std::vector<const char *> pointers;
    pointers.reserve(strings.size() + 1);
    for (const std::string &item : strings) pointers.push_back(item.c_str());
    pointers.push_back(nullptr);
    return context->api.command(context->handle, pointers.data());
}

extern "C" JNIEXPORT jobject JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_getProperty(
    JNIEnv *env, jclass, jlong value, jstring name, jint format) {
    Context *context = from_handle(value);
    if (!context) return nullptr;
    UtfChars native_name(env, name);

    if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {
        char *result = nullptr;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        if (context->last_result < 0 || !result) return nullptr;
        jstring text = new_utf8_string(env, result);
        context->api.free_data(result);
        return text;
    }
    if (format == MPV_FORMAT_FLAG) {
        int result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_boolean(env, result != 0);
    }
    if (format == MPV_FORMAT_INT64) {
        std::int64_t result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_long(env, result);
    }
    if (format == MPV_FORMAT_DOUBLE) {
        double result = 0;
        context->last_result = context->api.get_property(
            context->handle, native_name.get(), format, &result);
        return context->last_result < 0 ? nullptr : box_double(env, result);
    }
    context->last_result = MPV_ERROR_INVALID_PARAMETER;
    return nullptr;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_lastOperationResult(
    JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    return context ? context->last_result : MPV_ERROR_UNINITIALIZED;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_setProperty(
    JNIEnv *env, jclass, jlong value, jstring name, jint format, jobject property_value_object) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    if (format == MPV_FORMAT_STRING || format == MPV_FORMAT_OSD_STRING) {
        UtfChars text(env, static_cast<jstring>(property_value_object));
        return context->api.set_property_string(context->handle, native_name.get(), text.get());
    }
    std::int64_t integer = 0;
    double decimal = 0;
    if (!read_boxed_value(env, property_value_object, format, &integer, &decimal))
        return MPV_ERROR_INVALID_PARAMETER;
    if (format == MPV_FORMAT_FLAG) {
        int flag = integer != 0;
        return context->api.set_property(context->handle, native_name.get(), format, &flag);
    }
    if (format == MPV_FORMAT_INT64)
        return context->api.set_property(context->handle, native_name.get(), format, &integer);
    if (format == MPV_FORMAT_DOUBLE)
        return context->api.set_property(context->handle, native_name.get(), format, &decimal);
    return MPV_ERROR_INVALID_PARAMETER;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_observeProperty(
    JNIEnv *env, jclass, jlong value, jlong id, jstring name, jint format) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_name(env, name);
    return context->api.observe_property(context->handle, id, native_name.get(), format);
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_unobserveProperty(
    JNIEnv *, jclass, jlong value, jlong id) {
    Context *context = from_handle(value);
    return context ? context->api.unobserve_property(context->handle, id) : MPV_ERROR_UNINITIALIZED;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_requestLogMessages(
    JNIEnv *env, jclass, jlong value, jstring level) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    UtfChars native_level(env, level);
    return context->api.request_log_messages(context->handle, native_level.get());
}

extern "C" JNIEXPORT jobject JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_waitEvent(
    JNIEnv *env, jclass, jlong value, jdouble timeout_seconds) {
    Context *context = from_handle(value);
    if (!context) return nullptr;
    mpv_event *event = context->api.wait_event(context->handle, timeout_seconds);
    return event ? make_event(env, event) : nullptr;
}

extern "C" JNIEXPORT jstring JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_errorString(
    JNIEnv *env, jclass, jlong value, jint error_code) {
    Context *context = from_handle(value);
    const char *message = context ? context->api.error_string(error_code) : "mpv client is not initialized";
    return new_utf8_string(env, message ? message : "unknown mpv error");
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_attachSurface(
    JNIEnv *env, jclass, jlong value, jobject surface) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    jobject replacement = env->NewGlobalRef(surface);
    if (!replacement) return MPV_ERROR_INVALID_PARAMETER;
    std::int64_t wid = reinterpret_cast<std::intptr_t>(replacement);
    int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);
    if (result < 0) {
        env->DeleteGlobalRef(replacement);
        return result;
    }
    if (context->surface) env->DeleteGlobalRef(context->surface);
    context->surface = replacement;
    return result;
}

extern "C" JNIEXPORT jint JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_detachSurface(
    JNIEnv *env, jclass, jlong value) {
    Context *context = from_handle(value);
    if (!context) return MPV_ERROR_UNINITIALIZED;
    std::int64_t wid = 0;
    int result = context->api.set_option(context->handle, "wid", MPV_FORMAT_INT64, &wid);
    if (result >= 0 && context->surface) {
        env->DeleteGlobalRef(context->surface);
        context->surface = nullptr;
    }
    return result;
}

extern "C" JNIEXPORT void JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_wakeup(JNIEnv *, jclass, jlong value) {
    Context *context = from_handle(value);
    if (context) context->api.wakeup(context->handle);
}

extern "C" JNIEXPORT void JNICALL
Java_io_github_kmpmpv_bridge_MpvNative_destroy(JNIEnv *env, jclass, jlong value) {
    std::unique_ptr<Context> context(from_handle(value));
    if (!context) return;
    // mpv's video output can still use the Surface during termination.
    if (context->handle) context->api.terminate_destroy(context->handle);
    if (context->surface) env->DeleteGlobalRef(context->surface);
    if (context->library) dlclose(context->library);
}

Write vendor/kmp-mpv/android-bridge/src/main/cpp/mpv_abi.h

Create this path in your reconstruction project. Source set: main. Exact file download.

#ifndef KMPMPV_MPV_ABI_H
#define KMPMPV_MPV_ABI_H

#include <cstdint>

struct mpv_handle;

enum mpv_format {
    MPV_FORMAT_NONE = 0,
    MPV_FORMAT_STRING = 1,
    MPV_FORMAT_OSD_STRING = 2,
    MPV_FORMAT_FLAG = 3,
    MPV_FORMAT_INT64 = 4,
    MPV_FORMAT_DOUBLE = 5,
};

struct mpv_event {
    int event_id;
    int error;
    std::uint64_t reply_userdata;
    void *data;
};

struct mpv_event_property {
    const char *name;
    int format;
    void *data;
};

struct mpv_event_log_message {
    const char *prefix;
    const char *level;
    const char *text;
    int log_level;
};

struct mpv_event_end_file {
    int reason;
    int error;
    std::int64_t playlist_entry_id;
    std::int64_t playlist_insert_id;
    int playlist_insert_num_entries;
};

struct mpv_event_client_message {
    int num_args;
    const char **args;
};

#endif

Write vendor/kmp-mpv/android-bridge/src/main/java/io/github/kmpmpv/bridge/MpvNative.java

Create this path in your reconstruction project. Source set: main. Exact file download.

The implementation below defines MpvNative.

The source describes its contract as:

Internal JNI entry points used by the KMP Android target.

package io.github.kmpmpv.bridge;

import android.view.Surface;

/** Internal JNI entry points used by the KMP Android target. */
public final class MpvNative {
    static {
        System.loadLibrary("kmpmpv_bridge");
    }

    private MpvNative() {}

    public static native long create(String libraryPath);

    public static native String lastError();

    public static native int initialize(long context);

    public static native int setOptionString(long context, String name, String value);

    public static native int command(long context, String[] arguments);

    public static native Object getProperty(long context, String name, int format);

    public static native int lastOperationResult(long context);

    public static native int setProperty(long context, String name, int format, Object value);

    public static native int observeProperty(long context, long id, String name, int format);

    public static native int unobserveProperty(long context, long id);

    public static native int requestLogMessages(long context, String level);

    public static native MpvNativeEvent waitEvent(long context, double timeoutSeconds);

    public static native String errorString(long context, int errorCode);

    public static native int attachSurface(long context, Surface surface);

    public static native int detachSurface(long context);

    public static native void wakeup(long context);

    public static native void destroy(long context);
}

Write vendor/kmp-mpv/android-bridge/src/main/java/io/github/kmpmpv/bridge/MpvNativeEvent.java

Create this path in your reconstruction project. Source set: main. Exact file download.

The implementation below defines MpvNativeEvent.

The source describes its contract as:

A copied event payload. It remains valid after the next mpv_wait_event call.

package io.github.kmpmpv.bridge;

/** A copied event payload. It remains valid after the next mpv_wait_event call. */
public final class MpvNativeEvent {
    public final int eventId;
    public final int errorCode;
    public final long replyUserData;
    public final String propertyName;
    public final Object propertyValue;
    public final String logPrefix;
    public final int logLevel;
    public final String logText;
    public final int endReason;
    public final int endError;
    public final String[] clientArguments;

    public MpvNativeEvent(
            int eventId,
            int errorCode,
            long replyUserData,
            String propertyName,
            Object propertyValue,
            String logPrefix,
            int logLevel,
            String logText,
            int endReason,
            int endError,
            String[] clientArguments) {
        this.eventId = eventId;
        this.errorCode = errorCode;
        this.replyUserData = replyUserData;
        this.propertyName = propertyName;
        this.propertyValue = propertyValue;
        this.logPrefix = logPrefix;
        this.logLevel = logLevel;
        this.logText = logText;
        this.endReason = endReason;
        this.endError = endError;
        this.clientArguments = clientArguments;
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/MpvRenderTarget.android.kt

Create this path in your reconstruction project. Source set: androidMain. Exact file download.

The implementation below defines MpvRenderTarget.

The source describes its contract as:

An Android video Surface. The bridge keeps a global JNI reference until detachment.

package io.github.kmpmpv

import android.view.Surface

/** An Android video Surface. The bridge keeps a global JNI reference until detachment. */
public actual class MpvRenderTarget(public val surface: Surface)

Write vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/MpvSurfaceView.kt

Create this path in your reconstruction project. Source set: androidMain. Exact file download.

The implementation below defines MpvSurfaceView, bind, unbind, dispose, surfaceCreated, surfaceChanged, surfaceDestroyed, attach.

The source describes its contract as:

Minimal Android View adapter. It owns only Surface attachment; the caller owns the player.

package io.github.kmpmpv

import android.content.Context
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

/**
 * Minimal Android View adapter. It owns only Surface attachment; the caller owns the player.
 */
public class MpvSurfaceView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback {
    private val exceptionHandler = CoroutineExceptionHandler { _, failure -> onError(failure) }
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate + exceptionHandler)
    private var boundPlayer: MpvPlayer? = null

    /** Called when a suspend bridge operation fails. */
    public var onError: (Throwable) -> Unit = { throw it }

    init {
        holder.addCallback(this)
    }

    public fun bind(player: MpvPlayer) {
        boundPlayer = player
        if (holder.surface.isValid) attach(player, holder)
    }

    public fun unbind() {
        val player = boundPlayer ?: return
        boundPlayer = null
        scope.launch { player.detachRenderTarget() }
    }

    /** Remove callbacks and cancel pending Surface operations. Does not release the player. */
    public fun dispose() {
        holder.removeCallback(this)
        boundPlayer = null
        scope.cancel()
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        boundPlayer?.let { attach(it, holder) }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        val player = boundPlayer ?: return
        if (width > 0 && height > 0) {
            scope.launch { player.updateRenderTargetSize(width, height) }
        }
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        boundPlayer?.let { player -> scope.launch { player.detachRenderTarget() } }
    }

    private fun attach(player: MpvPlayer, holder: SurfaceHolder) {
        scope.launch {
            player.attachRenderTarget(MpvRenderTarget(holder.surface))
            if (width > 0 && height > 0) player.updateRenderTargetSize(width, height)
        }
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/androidMain/kotlin/io/github/kmpmpv/internal/AndroidMpvEngine.kt

Create this path in your reconstruction project. Source set: androidMain. Exact file download.

The implementation below defines createPlatformMpvEngine, AndroidMpvEngine, command, getProperty, setProperty, observeProperty, unobserveProperty, requestLogMessages, waitEvent, attachRenderTarget and 7 further declarations.

package io.github.kmpmpv.internal

import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvException
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvValue
import io.github.kmpmpv.bridge.MpvNative
import io.github.kmpmpv.bridge.MpvNativeEvent

internal actual fun createPlatformMpvEngine(configuration: MpvConfiguration): MpvEngine =
    AndroidMpvEngine(configuration)

private class AndroidMpvEngine(configuration: MpvConfiguration) : MpvEngine {
    private var context: Long = MpvNative.create(configuration.libraryPath)
    private var closed = false
    private val videoOutput = configuration.options["vo"] ?: "gpu"
    private var targetWasDetached = false
    private var surfaceAttached = false

    init {
        if (context == 0L) {
            throw MpvException(
                ERROR_UNINITIALIZED,
                "Unable to load libmpv.so: ${MpvNative.lastError()}. " +
                    "Package libmpv.so and its dependencies in your app's jniLibs directory.",
            )
        }
        try {
            val platformOptions = mapOf(
                "vo" to "gpu",
                "gpu-context" to "android",
            ) + configuration.options
            platformOptions.forEach { (name, value) ->
                check(MpvNative.setOptionString(context, name, value), "set option '$name'")
            }
            check(
                MpvNative.requestLogMessages(context, configuration.logLevel.mpvName),
                "configure logging",
            )
            check(MpvNative.initialize(context), "initialize libmpv")
        } catch (failure: Throwable) {
            MpvNative.destroy(context)
            context = 0
            closed = true
            throw failure
        }
    }

    override fun command(arguments: List<String>): Int =
        MpvNative.command(context, arguments.toTypedArray())

    override fun getProperty(name: String, format: MpvFormat): EngineResult<MpvValue> {
        val value = MpvNative.getProperty(context, name, format.nativeValue)
        val result = MpvNative.lastOperationResult(context)
        if (result < 0) return EngineResult(result)
        val converted = when (format) {
            MpvFormat.String,
            MpvFormat.OsdString,
            -> (value as? String)?.let(MpvValue::Text)
            MpvFormat.Flag -> (value as? Boolean)?.let(MpvValue::Flag)
            MpvFormat.Int64 -> (value as? Number)?.toLong()?.let(MpvValue::Integer)
            MpvFormat.Double -> (value as? Number)?.toDouble()?.let(MpvValue::Decimal)
            MpvFormat.None -> null
        }
        return EngineResult(result, converted ?: MpvValue.None)
    }

    override fun setProperty(name: String, value: MpvValue): Int = when (value) {
        is MpvValue.Text -> MpvNative.setProperty(
            context,
            name,
            MpvFormat.String.nativeValue,
            value.value,
        )
        is MpvValue.Flag -> MpvNative.setProperty(
            context,
            name,
            MpvFormat.Flag.nativeValue,
            value.value,
        )
        is MpvValue.Integer -> MpvNative.setProperty(
            context,
            name,
            MpvFormat.Int64.nativeValue,
            value.value,
        )
        is MpvValue.Decimal -> MpvNative.setProperty(
            context,
            name,
            MpvFormat.Double.nativeValue,
            value.value,
        )
        MpvValue.None -> ERROR_INVALID_PARAMETER
    }

    override fun observeProperty(
        observationId: Long,
        name: String,
        format: MpvFormat,
    ): Int = MpvNative.observeProperty(context, observationId, name, format.nativeValue)

    override fun unobserveProperty(observationId: Long): Int =
        MpvNative.unobserveProperty(context, observationId)

    override fun requestLogMessages(level: String): Int = MpvNative.requestLogMessages(context, level)

    override fun waitEvent(timeoutSeconds: Double): RawMpvEvent =
        MpvNative.waitEvent(context, timeoutSeconds)?.toRawEvent() ?: RawMpvEvent(NativeEventId.NONE)

    override fun attachRenderTarget(target: MpvRenderTarget): Int {
        if (surfaceAttached) {
            val detach = detachRenderTarget()
            if (detach < 0) return detach
        }
        val result = MpvNative.attachSurface(context, target.surface)
        if (result < 0) return result
        surfaceAttached = true
        MpvNative.setProperty(context, "force-window", MpvFormat.String.nativeValue, "yes")
        if (targetWasDetached) {
            val restore = MpvNative.setProperty(
                context,
                "vo",
                MpvFormat.String.nativeValue,
                videoOutput,
            )
            if (restore < 0) return restore
        }
        targetWasDetached = false
        return result
    }

    override fun detachRenderTarget(): Int {
        // Deinitialize the VO before releasing its global Surface reference.
        val disable = MpvNative.setProperty(context, "vo", MpvFormat.String.nativeValue, "null")
        if (disable < 0) return disable
        targetWasDetached = true
        MpvNative.setProperty(context, "force-window", MpvFormat.String.nativeValue, "no")
        val detach = MpvNative.detachSurface(context)
        if (detach >= 0) surfaceAttached = false
        return detach
    }

    override fun updateRenderTargetSize(width: Int, height: Int): Int =
        MpvNative.setProperty(
            context,
            "android-surface-size",
            MpvFormat.String.nativeValue,
            "${width}x$height",
        )

    override fun errorString(errorCode: Int): String = MpvNative.errorString(context, errorCode)

    override fun wakeup() {
        if (!closed) MpvNative.wakeup(context)
    }

    override fun close() {
        if (closed) return
        closed = true
        MpvNative.destroy(context)
        context = 0
    }

    private fun check(errorCode: Int, action: String) {
        if (errorCode < 0) throw MpvException(errorCode, "Failed to $action: ${errorString(errorCode)}")
    }

    private companion object {
        const val ERROR_UNINITIALIZED = -3
        const val ERROR_INVALID_PARAMETER = -4
    }
}

private fun MpvNativeEvent.toRawEvent(): RawMpvEvent = RawMpvEvent(
    eventId = eventId,
    errorCode = errorCode,
    replyUserData = replyUserData,
    propertyName = propertyName,
    propertyValue = when (val value = propertyValue) {
        is String -> MpvValue.Text(value)
        is Boolean -> MpvValue.Flag(value)
        is Long -> MpvValue.Integer(value)
        is Int -> MpvValue.Integer(value.toLong())
        is Double -> MpvValue.Decimal(value)
        is Float -> MpvValue.Decimal(value.toDouble())
        else -> MpvValue.None
    },
    logPrefix = logPrefix,
    logLevel = logLevel,
    logText = logText,
    endReason = endReason,
    endError = endError,
    clientArguments = clientArguments?.toList().orEmpty(),
)

Write vendor/kmp-mpv/samples/android/MpvActivitySnippet.kt

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

The implementation below defines PlayerActivity, onCreate, onDestroy.

import android.app.Activity
import android.os.Bundle
import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvPlayer
import io.github.kmpmpv.MpvSurfaceView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class PlayerActivity : Activity() {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
    private lateinit var player: MpvPlayer
    private lateinit var video: MpvSurfaceView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        player = MpvPlayer.create(
            MpvConfiguration(
                options = MpvConfiguration.DefaultOptions + mapOf("hwdec" to "mediacodec-copy"),
            ),
        )
        video = MpvSurfaceView(this).apply { bind(player) }
        setContentView(video)
        scope.launch { player.load(intent.data.toString()) }
    }

    override fun onDestroy() {
        video.dispose()
        scope.launch {
            player.release()
            scope.cancel()
        }
        super.onDestroy()
    }
}

Check your understanding

Force attach/detach failure and recreate the Surface. Verify that neither a leaked reference nor a dangling native window is reported as successful cleanup. [chapter-content-end]: #

Step 5: implement iOS dynamic C transport

Rebuild the header-only dynamic bridge, cinterop definition, IosMpvEngine and render target. Use dlopen/dlsym for client/render APIs so simulator compilation does not require a device-only binary slice. Use the software render path for Compose. Do not call Kotlin from mpv-owned threads. The selected native artifact has device arm64 support, while simulator consumers require fallback.

Follow the code

The iOS bridge resolves native symbols dynamically so a simulator build need not link a device-only binary. Kotlin never runs directly from arbitrary mpv-owned callbacks; the transport copies/polls data through the controlled engine boundary. Software rendering supplies Compose frames. Keep device artifact support and simulator fallback distinct when implementing factories and errors.

Write these files in this order:

  • vendor/kmp-mpv/kmp-mpv/src/iosMain/kotlin/io/github/kmpmpv/MpvRenderTarget.ios.kt
  • vendor/kmp-mpv/kmp-mpv/src/iosMain/kotlin/io/github/kmpmpv/internal/IosMpvEngine.kt
  • vendor/kmp-mpv/kmp-mpv/src/nativeInterop/cinterop/include/kmp_mpv_dynamic.h
  • vendor/kmp-mpv/kmp-mpv/src/nativeInterop/cinterop/mpvDynamic.def

Write vendor/kmp-mpv/kmp-mpv/src/iosMain/kotlin/io/github/kmpmpv/MpvRenderTarget.ios.kt

Create this path in your reconstruction project. Source set: iosMain. Exact file download.

The implementation below defines MpvRenderTarget.

The source describes its contract as:

Pointer value of the native view expected by the video output in the bundled iOS libmpv build.

package io.github.kmpmpv

/** Pointer value of the native view expected by the video output in the bundled iOS libmpv build. */
public actual class MpvRenderTarget(public val nativeViewHandle: Long)

Write vendor/kmp-mpv/kmp-mpv/src/iosMain/kotlin/io/github/kmpmpv/internal/IosMpvEngine.kt

Create this path in your reconstruction project. Source set: iosMain. Exact file download.

The implementation below defines createPlatformMpvEngine, IosMpvEngine, command, getProperty, setProperty, observeProperty, unobserveProperty, requestLogMessages, waitEvent, attachRenderTarget and 10 further declarations.

@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package io.github.kmpmpv.internal

import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvException
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvValue
import io.github.kmpmpv.internal.cinterop.kmp_mpv_command
import io.github.kmpmpv.internal.cinterop.kmp_mpv_context
import io.github.kmpmpv.internal.cinterop.kmp_mpv_create_dynamic
import io.github.kmpmpv.internal.cinterop.kmp_mpv_create_sw_render_context
import io.github.kmpmpv.internal.cinterop.kmp_mpv_destroy_dynamic
import io.github.kmpmpv.internal.cinterop.kmp_mpv_dynamic_error
import io.github.kmpmpv.internal.cinterop.kmp_mpv_error_string
import io.github.kmpmpv.internal.cinterop.kmp_mpv_event_client_message
import io.github.kmpmpv.internal.cinterop.kmp_mpv_event_end_file
import io.github.kmpmpv.internal.cinterop.kmp_mpv_event_log_message
import io.github.kmpmpv.internal.cinterop.kmp_mpv_event_property
import io.github.kmpmpv.internal.cinterop.kmp_mpv_free
import io.github.kmpmpv.internal.cinterop.kmp_mpv_get_double
import io.github.kmpmpv.internal.cinterop.kmp_mpv_get_flag
import io.github.kmpmpv.internal.cinterop.kmp_mpv_get_int64
import io.github.kmpmpv.internal.cinterop.kmp_mpv_get_string
import io.github.kmpmpv.internal.cinterop.kmp_mpv_initialize
import io.github.kmpmpv.internal.cinterop.kmp_mpv_observe_property
import io.github.kmpmpv.internal.cinterop.kmp_mpv_request_log_messages
import io.github.kmpmpv.internal.cinterop.kmp_mpv_render_sw
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_double
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_flag
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_int64
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_option_string
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_string
import io.github.kmpmpv.internal.cinterop.kmp_mpv_set_wid
import io.github.kmpmpv.internal.cinterop.kmp_mpv_unobserve_property
import io.github.kmpmpv.internal.cinterop.kmp_mpv_wait_event
import io.github.kmpmpv.internal.cinterop.kmp_mpv_wakeup
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.CPointerVar
import kotlinx.cinterop.DoubleVar
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.LongVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.cstr
import kotlinx.cinterop.get
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.set
import kotlinx.cinterop.toKString
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.value

internal actual fun createPlatformMpvEngine(configuration: MpvConfiguration): MpvEngine =
    IosMpvEngine(configuration)

private class IosMpvEngine(configuration: MpvConfiguration) : MpvEngine {
    private var context: CPointer<kmp_mpv_context>? = kmp_mpv_create_dynamic(configuration.libraryPath)
    private var closed = false

    init {
        val native = requireContext()
        try {
            val platformOptions = mapOf("vo" to "libmpv") + configuration.options
            platformOptions.forEach { (name, value) ->
                val result = kmp_mpv_set_option_string(native, name, value)
                check(result, "set option '$name'")
            }
            val logResult = kmp_mpv_request_log_messages(native, configuration.logLevel.mpvName)
            check(logResult, "configure logging")
            check(kmp_mpv_initialize(native), "initialize libmpv")
            if (platformOptions["vo"] == "libmpv") {
                check(kmp_mpv_create_sw_render_context(native), "create software render context")
            }
        } catch (failure: Throwable) {
            kmp_mpv_destroy_dynamic(native)
            context = null
            closed = true
            throw failure
        }
    }

    override fun command(arguments: List<String>): Int = memScoped {
        val pointers = allocArray<CPointerVar<ByteVar>>(arguments.size + 1)
        arguments.forEachIndexed { index, argument -> pointers[index] = argument.cstr.ptr }
        pointers[arguments.size] = null
        kmp_mpv_command(requireContext(), pointers)
    }

    override fun getProperty(name: String, format: MpvFormat): EngineResult<MpvValue> = memScoped {
        val native = requireContext()
        when (format) {
            MpvFormat.String,
            MpvFormat.OsdString,
            -> {
                val output = alloc<CPointerVar<ByteVar>>()
                val result = kmp_mpv_get_string(native, name, format.nativeValue, output.ptr)
                if (result < 0) return@memScoped EngineResult(result)
                val pointer = output.value
                try {
                    EngineResult(result, MpvValue.Text(pointer?.toKString().orEmpty()))
                } finally {
                    if (pointer != null) kmp_mpv_free(native, pointer)
                }
            }
            MpvFormat.Flag -> {
                val output = alloc<IntVar>()
                val result = kmp_mpv_get_flag(native, name, output.ptr)
                EngineResult(result, if (result < 0) null else MpvValue.Flag(output.value != 0))
            }
            MpvFormat.Int64 -> {
                val output = alloc<LongVar>()
                val result = kmp_mpv_get_int64(native, name, output.ptr)
                EngineResult(result, if (result < 0) null else MpvValue.Integer(output.value))
            }
            MpvFormat.Double -> {
                val output = alloc<DoubleVar>()
                val result = kmp_mpv_get_double(native, name, output.ptr)
                EngineResult(result, if (result < 0) null else MpvValue.Decimal(output.value))
            }
            MpvFormat.None -> EngineResult(ERROR_INVALID_PARAMETER)
        }
    }

    override fun setProperty(name: String, value: MpvValue): Int = memScoped {
        val native = requireContext()
        when (value) {
            is MpvValue.Text -> kmp_mpv_set_string(native, name, value.value)
            is MpvValue.Flag -> kmp_mpv_set_flag(native, name, if (value.value) 1 else 0)
            is MpvValue.Integer -> kmp_mpv_set_int64(native, name, value.value)
            is MpvValue.Decimal -> kmp_mpv_set_double(native, name, value.value)
            MpvValue.None -> ERROR_INVALID_PARAMETER
        }
    }

    override fun observeProperty(
        observationId: Long,
        name: String,
        format: MpvFormat,
    ): Int = kmp_mpv_observe_property(requireContext(), observationId.toULong(), name, format.nativeValue)

    override fun unobserveProperty(observationId: Long): Int =
        kmp_mpv_unobserve_property(requireContext(), observationId.toULong())

    override fun requestLogMessages(level: String): Int =
        kmp_mpv_request_log_messages(requireContext(), level)

    override fun waitEvent(timeoutSeconds: Double): RawMpvEvent {
        val event = kmp_mpv_wait_event(requireContext(), timeoutSeconds)?.pointed
            ?: return RawMpvEvent(NativeEventId.NONE)
        return when (event.event_id) {
            NativeEventId.PROPERTY_CHANGE -> {
                val property = event.data?.reinterpret<kmp_mpv_event_property>()?.pointed
                RawMpvEvent(
                    eventId = event.event_id,
                    errorCode = event.error,
                    replyUserData = event.reply_userdata.toLong(),
                    propertyName = property?.name?.toKString(),
                    propertyValue = property?.toMpvValue() ?: MpvValue.None,
                )
            }
            NativeEventId.LOG_MESSAGE -> {
                val log = event.data?.reinterpret<kmp_mpv_event_log_message>()?.pointed
                RawMpvEvent(
                    eventId = event.event_id,
                    errorCode = event.error,
                    replyUserData = event.reply_userdata.toLong(),
                    logPrefix = log?.prefix?.toKString(),
                    logLevel = log?.log_level ?: 0,
                    logText = log?.text?.toKString(),
                )
            }
            NativeEventId.END_FILE -> {
                val endFile = event.data?.reinterpret<kmp_mpv_event_end_file>()?.pointed
                RawMpvEvent(
                    eventId = event.event_id,
                    errorCode = event.error,
                    replyUserData = event.reply_userdata.toLong(),
                    endReason = endFile?.reason ?: 0,
                    endError = endFile?.error ?: 0,
                )
            }
            NativeEventId.CLIENT_MESSAGE -> {
                val message = event.data?.reinterpret<kmp_mpv_event_client_message>()?.pointed
                RawMpvEvent(
                    eventId = event.event_id,
                    errorCode = event.error,
                    replyUserData = event.reply_userdata.toLong(),
                    clientArguments = message?.arguments().orEmpty(),
                )
            }
            else -> RawMpvEvent(
                eventId = event.event_id,
                errorCode = event.error,
                replyUserData = event.reply_userdata.toLong(),
            )
        }
    }

    override fun attachRenderTarget(target: MpvRenderTarget): Int =
        kmp_mpv_set_wid(requireContext(), target.nativeViewHandle)

    override fun detachRenderTarget(): Int = kmp_mpv_set_wid(requireContext(), 0)

    override fun updateRenderTargetSize(width: Int, height: Int): Int = 0

    override fun renderSoftwareFrame(width: Int, height: Int): EngineResult<RawSoftwareFrame> {
        val alignedStride = (width.toLong() * BYTES_PER_PIXEL + 63L) / 64L * 64L
        if (width <= 0 || height <= 0 || alignedStride > Int.MAX_VALUE / height.toLong()) {
            return EngineResult(ERROR_INVALID_PARAMETER)
        }
        val stride = alignedStride.toInt()
        val byteCount = alignedStride * height
        val pixels = ByteArray(byteCount.toInt())
        val result = pixels.usePinned { pinned ->
            kmp_mpv_render_sw(requireContext(), width, height, stride.toULong(), pinned.addressOf(0))
        }
        return EngineResult(result, if (result < 0) null else RawSoftwareFrame(stride, pixels))
    }

    override fun errorString(errorCode: Int): String =
        kmp_mpv_error_string(requireContext(), errorCode)?.toKString()
            ?: "unknown mpv error ($errorCode)"

    override fun wakeup() {
        if (!closed) context?.let(::kmp_mpv_wakeup)
    }

    override fun close() {
        if (closed) return
        closed = true
        context?.let(::kmp_mpv_destroy_dynamic)
        context = null
    }

    private fun requireContext(): CPointer<kmp_mpv_context> = context
        ?: throw MpvException(
            ERROR_UNINITIALIZED,
            kmp_mpv_dynamic_error()?.toKString() ?: "Unable to locate libmpv symbols in the iOS app",
        )

    private fun check(errorCode: Int, action: String) {
        if (errorCode < 0) throw MpvException(errorCode, "Failed to $action: ${errorString(errorCode)}")
    }

    private companion object {
        const val ERROR_UNINITIALIZED = -3
        const val ERROR_INVALID_PARAMETER = -4
        const val BYTES_PER_PIXEL = 4L
    }
}

private fun kmp_mpv_event_property.toMpvValue(): MpvValue = when (format) {
    MpvFormat.String.nativeValue,
    MpvFormat.OsdString.nativeValue,
    -> data?.reinterpret<ByteVar>()?.toKString()?.let(MpvValue::Text) ?: MpvValue.None
    MpvFormat.Flag.nativeValue -> data?.reinterpret<IntVar>()?.pointed?.value
        ?.let { MpvValue.Flag(it != 0) } ?: MpvValue.None
    MpvFormat.Int64.nativeValue -> data?.reinterpret<LongVar>()?.pointed?.value
        ?.let(MpvValue::Integer) ?: MpvValue.None
    MpvFormat.Double.nativeValue -> data?.reinterpret<DoubleVar>()?.pointed?.value
        ?.let(MpvValue::Decimal) ?: MpvValue.None
    else -> MpvValue.None
}

private fun kmp_mpv_event_client_message.arguments(): List<String> {
    val nativeArguments = args ?: return emptyList()
    return (0 until num_args).mapNotNull { index -> nativeArguments[index]?.toKString() }
}

Write vendor/kmp-mpv/kmp-mpv/src/nativeInterop/cinterop/include/kmp_mpv_dynamic.h

Create this path in your reconstruction project. Source set: nativeInterop. Exact file download.

#ifndef KMP_MPV_DYNAMIC_H
#define KMP_MPV_DYNAMIC_H

#include <dlfcn.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct mpv_handle mpv_handle;
typedef struct mpv_render_context mpv_render_context;

typedef struct kmp_mpv_render_param {
    int type;
    void *data;
} kmp_mpv_render_param;

enum {
    KMP_MPV_FORMAT_NONE = 0,
    KMP_MPV_FORMAT_STRING = 1,
    KMP_MPV_FORMAT_OSD_STRING = 2,
    KMP_MPV_FORMAT_FLAG = 3,
    KMP_MPV_FORMAT_INT64 = 4,
    KMP_MPV_FORMAT_DOUBLE = 5,
};

typedef struct kmp_mpv_event {
    int event_id;
    int error;
    uint64_t reply_userdata;
    void *data;
} kmp_mpv_event;

typedef struct kmp_mpv_event_property {
    const char *name;
    int format;
    void *data;
} kmp_mpv_event_property;

typedef struct kmp_mpv_event_log_message {
    const char *prefix;
    const char *level;
    const char *text;
    int log_level;
} kmp_mpv_event_log_message;

typedef struct kmp_mpv_event_end_file {
    int reason;
    int error;
    int64_t playlist_entry_id;
    int64_t playlist_insert_id;
    int playlist_insert_num_entries;
} kmp_mpv_event_end_file;

typedef struct kmp_mpv_event_client_message {
    int num_args;
    const char **args;
} kmp_mpv_event_client_message;

typedef struct kmp_mpv_context {
    void *library;
    int owns_library;
    mpv_handle *handle;
    mpv_render_context *render_context;
    mpv_handle *(*create)(void);
    int (*initialize)(mpv_handle *);
    int (*set_option_string)(mpv_handle *, const char *, const char *);
    int (*set_option)(mpv_handle *, const char *, int, void *);
    int (*command)(mpv_handle *, const char **);
    int (*get_property)(mpv_handle *, const char *, int, void *);
    int (*set_property)(mpv_handle *, const char *, int, void *);
    int (*set_property_string)(mpv_handle *, const char *, const char *);
    int (*observe_property)(mpv_handle *, uint64_t, const char *, int);
    int (*unobserve_property)(mpv_handle *, uint64_t);
    int (*request_log_messages)(mpv_handle *, const char *);
    const kmp_mpv_event *(*wait_event)(mpv_handle *, double);
    const char *(*error_string)(int);
    void (*free_data)(void *);
    void (*wakeup)(mpv_handle *);
    void (*terminate_destroy)(mpv_handle *);
    int (*render_context_create)(mpv_render_context **, mpv_handle *, kmp_mpv_render_param *);
    uint64_t (*render_context_update)(mpv_render_context *);
    int (*render_context_render)(mpv_render_context *, kmp_mpv_render_param *);
    void (*render_context_free)(mpv_render_context *);
} kmp_mpv_context;

static char kmp_mpv_dynamic_error_buffer[512];

static inline void kmp_mpv_capture_dynamic_error(const char *fallback) {
    const char *error = dlerror();
    const char *message = error ? error : fallback;
    if (!message) {
        kmp_mpv_dynamic_error_buffer[0] = '\0';
        return;
    }
    strncpy(kmp_mpv_dynamic_error_buffer, message, sizeof(kmp_mpv_dynamic_error_buffer) - 1);
    kmp_mpv_dynamic_error_buffer[sizeof(kmp_mpv_dynamic_error_buffer) - 1] = '\0';
}

static inline const char *kmp_mpv_dynamic_error(void) {
    return kmp_mpv_dynamic_error_buffer[0] ? kmp_mpv_dynamic_error_buffer : NULL;
}
#if defined(__APPLE__)
static void *kmp_mpv_lua_library;

static inline void kmp_mpv_preload_apple_lua(const char *requested_path) {
    if (kmp_mpv_lua_library) return;

    const char *lua_path = "@rpath/Lua.framework/Lua";
    char sibling_path[4096];
    if (requested_path && requested_path[0]) {
        const char *marker = strstr(requested_path, "/Mpv.framework/Mpv");
        if (marker) {
            size_t prefix_length = (size_t)(marker - requested_path);
            const char *suffix = "/Lua.framework/Lua";
            if (prefix_length + strlen(suffix) < sizeof(sibling_path)) {
                memcpy(sibling_path, requested_path, prefix_length);
                strcpy(sibling_path + prefix_length, suffix);
                lua_path = sibling_path;
            }
        }
    }

    dlerror();
    kmp_mpv_lua_library = dlopen(lua_path, RTLD_NOW | RTLD_GLOBAL);
}
#endif


static inline int kmp_mpv_resolve(kmp_mpv_context *context) {
#define KMP_MPV_SYMBOL(field, name)                                                   \
    do {                                                                              \
        *(void **)(&context->field) = dlsym(context->library, name);                   \
        if (!context->field) return 0;                                                 \
    } while (0)
    KMP_MPV_SYMBOL(create, "mpv_create");
    KMP_MPV_SYMBOL(initialize, "mpv_initialize");
    KMP_MPV_SYMBOL(set_option_string, "mpv_set_option_string");
    KMP_MPV_SYMBOL(set_option, "mpv_set_option");
    KMP_MPV_SYMBOL(command, "mpv_command");
    KMP_MPV_SYMBOL(get_property, "mpv_get_property");
    KMP_MPV_SYMBOL(set_property, "mpv_set_property");
    KMP_MPV_SYMBOL(set_property_string, "mpv_set_property_string");
    KMP_MPV_SYMBOL(observe_property, "mpv_observe_property");
    KMP_MPV_SYMBOL(unobserve_property, "mpv_unobserve_property");
    KMP_MPV_SYMBOL(request_log_messages, "mpv_request_log_messages");
    KMP_MPV_SYMBOL(wait_event, "mpv_wait_event");
    KMP_MPV_SYMBOL(error_string, "mpv_error_string");
    KMP_MPV_SYMBOL(free_data, "mpv_free");
    KMP_MPV_SYMBOL(wakeup, "mpv_wakeup");
    KMP_MPV_SYMBOL(terminate_destroy, "mpv_terminate_destroy");
    KMP_MPV_SYMBOL(render_context_create, "mpv_render_context_create");
    KMP_MPV_SYMBOL(render_context_update, "mpv_render_context_update");
    KMP_MPV_SYMBOL(render_context_render, "mpv_render_context_render");
    KMP_MPV_SYMBOL(render_context_free, "mpv_render_context_free");
#undef KMP_MPV_SYMBOL
    return 1;
}

static inline kmp_mpv_context *kmp_mpv_create_dynamic(const char *requested_path) {
    static const char *candidates[] = {
        "@rpath/Mpv.framework/Mpv",
        "@rpath/MPVKit.framework/MPVKit",
        "@rpath/libmpv.framework/libmpv",
        "libmpv.dylib",
        NULL,
    };
    kmp_mpv_dynamic_error_buffer[0] = '\0';
#if defined(__APPLE__)
    kmp_mpv_preload_apple_lua(requested_path);
#endif
    kmp_mpv_context *context = (kmp_mpv_context *)calloc(1, sizeof(kmp_mpv_context));
    if (!context) {
        kmp_mpv_capture_dynamic_error("Unable to allocate the libmpv bridge");
        return NULL;
    }

    if (requested_path && requested_path[0]) {
        dlerror();
        context->library = dlopen(requested_path, RTLD_NOW | RTLD_LOCAL);
        context->owns_library = context->library != NULL;
        if (!context->library) kmp_mpv_capture_dynamic_error("Unable to load the requested libmpv library");
    } else {
        for (int index = 0; candidates[index] && !context->library; ++index) {
            dlerror();
            context->library = dlopen(candidates[index], RTLD_NOW | RTLD_LOCAL);
            context->owns_library = context->library != NULL;
            if (!context->library) kmp_mpv_capture_dynamic_error("Unable to load a libmpv candidate");
        }
    }

    /* Also supports libmpv linked into the final app/framework image. */
    if (!context->library) {
        context->library = dlopen(NULL, RTLD_NOW | RTLD_LOCAL);
        context->owns_library = context->library != NULL;
    }
    if (!context->library || !kmp_mpv_resolve(context)) {
        if (context->library && context->owns_library) dlclose(context->library);
        if (kmp_mpv_dynamic_error_buffer[0] == '\0') {
            kmp_mpv_capture_dynamic_error("Unable to resolve required libmpv symbols");
        }
        free(context);
        return NULL;
    }
    context->handle = context->create();
    if (!context->handle) {
        if (context->owns_library) dlclose(context->library);
        kmp_mpv_capture_dynamic_error("libmpv could not create a client handle");
        free(context);
        return NULL;
    }
    return context;
}

static inline int kmp_mpv_initialize(kmp_mpv_context *context) {
    return context->initialize(context->handle);
}

static inline int kmp_mpv_set_option_string(
    kmp_mpv_context *context,
    const char *name,
    const char *value
) {
    return context->set_option_string(context->handle, name, value);
}

static inline int kmp_mpv_command(kmp_mpv_context *context, const char **arguments) {
    return context->command(context->handle, arguments);
}

static inline int kmp_mpv_get_string(
    kmp_mpv_context *context,
    const char *name,
    int format,
    const char **value
) {
    return context->get_property(context->handle, name, format, value);
}

static inline int kmp_mpv_get_flag(kmp_mpv_context *context, const char *name, int *value) {
    return context->get_property(context->handle, name, KMP_MPV_FORMAT_FLAG, value);
}

static inline int kmp_mpv_get_int64(kmp_mpv_context *context, const char *name, int64_t *value) {
    return context->get_property(context->handle, name, KMP_MPV_FORMAT_INT64, value);
}

static inline int kmp_mpv_get_double(kmp_mpv_context *context, const char *name, double *value) {
    return context->get_property(context->handle, name, KMP_MPV_FORMAT_DOUBLE, value);
}

static inline int kmp_mpv_set_string(
    kmp_mpv_context *context,
    const char *name,
    const char *value
) {
    return context->set_property_string(context->handle, name, value);
}

static inline int kmp_mpv_set_flag(kmp_mpv_context *context, const char *name, int value) {
    return context->set_property(context->handle, name, KMP_MPV_FORMAT_FLAG, &value);
}

static inline int kmp_mpv_set_int64(kmp_mpv_context *context, const char *name, int64_t value) {
    return context->set_property(context->handle, name, KMP_MPV_FORMAT_INT64, &value);
}

static inline int kmp_mpv_set_double(kmp_mpv_context *context, const char *name, double value) {
    return context->set_property(context->handle, name, KMP_MPV_FORMAT_DOUBLE, &value);
}

static inline int kmp_mpv_observe_property(
    kmp_mpv_context *context,
    uint64_t id,
    const char *name,
    int format
) {
    return context->observe_property(context->handle, id, name, format);
}

static inline int kmp_mpv_unobserve_property(kmp_mpv_context *context, uint64_t id) {
    return context->unobserve_property(context->handle, id);
}

static inline int kmp_mpv_request_log_messages(kmp_mpv_context *context, const char *level) {
    return context->request_log_messages(context->handle, level);
}

static inline const kmp_mpv_event *kmp_mpv_wait_event(kmp_mpv_context *context, double timeout) {
    return context->wait_event(context->handle, timeout);
}

static inline const char *kmp_mpv_error_string(kmp_mpv_context *context, int error) {
    return context->error_string(error);
}

static inline void kmp_mpv_free(kmp_mpv_context *context, void *data) {
    context->free_data(data);
}

static inline int kmp_mpv_set_wid(kmp_mpv_context *context, int64_t wid) {
    return context->set_option(context->handle, "wid", KMP_MPV_FORMAT_INT64, &wid);
}

static inline int kmp_mpv_create_sw_render_context(kmp_mpv_context *context) {
    if (context->render_context) return 0;
    char api[] = "sw";
    kmp_mpv_render_param create_params[] = {
        {1, api},
        {0, NULL},
    };
    return context->render_context_create(
        &context->render_context,
        context->handle,
        create_params
    );
}

static inline int kmp_mpv_render_sw(
    kmp_mpv_context *context,
    int width,
    int height,
    size_t stride,
    void *pixels
) {
    int create_result = kmp_mpv_create_sw_render_context(context);
    if (create_result < 0) return create_result;

    int size[] = {width, height};
    char format[] = "bgr0";
    kmp_mpv_render_param render_params[] = {
        {17, size},
        {18, format},
        {19, &stride},
        {20, pixels},
        {0, NULL},
    };
    context->render_context_update(context->render_context);
    return context->render_context_render(context->render_context, render_params);
}

static inline void kmp_mpv_wakeup(kmp_mpv_context *context) {
    context->wakeup(context->handle);
}

static inline void kmp_mpv_destroy_dynamic(kmp_mpv_context *context) {
    if (!context) return;
    if (context->render_context) context->render_context_free(context->render_context);
    if (context->handle) context->terminate_destroy(context->handle);
    if (context->library && context->owns_library) dlclose(context->library);
    free(context);
}

#ifdef __cplusplus
}
#endif

#endif

Write vendor/kmp-mpv/kmp-mpv/src/nativeInterop/cinterop/mpvDynamic.def

Create this path in your reconstruction project. Source set: nativeInterop. Exact file download.

headers = kmp_mpv_dynamic.h
package = io.github.kmpmpv.internal.cinterop

Check your understanding

Compile the simulator target without the device runtime, then test actual device loading separately. Record which path supplies software frames and which reports unavailable native support. [chapter-content-end]: #

Step 6: implement offline processing and packaging

MpvMediaProcessor is independent of playback. Desktop processing invokes FFmpeg for timestamped PNG and scaled MP4, and caller-provided whisper.cpp/model for subtitles after PCM extraction. Use argument arrays, bounded diagnostic output, shared concurrency semaphore, owned subprocesses/temp directories and cancellation that reaps processes before cleanup. Move completed output without unintended replacement.

Recreate pinned native download URLs/checksums and platform packaging tasks, iOS preparation script, samples and publication configuration. Downloaded binary artifacts stay under build outputs; they are dependencies rather than manually reimplemented libmpv.

Follow the code

Offline processing owns subprocesses/temp outputs independently of live playback. Desktop FFmpeg and optional whisper/model commands use argument arrays, bounded diagnostics and joined cancellation. Output publication must happen only after successful completion, preserving prior output unless replacement is intended. Recreate the library build, checksummed native preparation and sample consumers so API and packaging are exercised together.

Write these files in this order:

  • vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvMediaProcessor.kt
  • vendor/kmp-mpv
  • vendor/kmp-mpv/.github/workflows/build.yml
  • vendor/kmp-mpv/.gitignore
  • vendor/kmp-mpv/ARCHITECTURE.md
  • vendor/kmp-mpv/LICENSE
  • vendor/kmp-mpv/README.md
  • vendor/kmp-mpv/THIRD_PARTY_NOTICES.md
  • vendor/kmp-mpv/build.gradle.kts
  • vendor/kmp-mpv/gradle.properties
  • vendor/kmp-mpv/gradle/libs.versions.toml
  • vendor/kmp-mpv/gradle/wrapper/gradle-wrapper.jar
  • vendor/kmp-mpv/gradle/wrapper/gradle-wrapper.properties
  • vendor/kmp-mpv/gradlew
  • vendor/kmp-mpv/gradlew.bat
  • vendor/kmp-mpv/kmp-mpv/build.gradle.kts
  • vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/DesktopMpvMediaProcessor.kt
  • vendor/kmp-mpv/scripts/prepare-media-kit-ios.sh
  • vendor/kmp-mpv/settings.gradle.kts

Write vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/MpvMediaProcessor.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

Processing owns its external commands and temporary outputs. Cancellation must wait for child termination before releasing paths that the process may still be writing.

The implementation below defines MpvMediaProcessor, extractThumbnail, upscaleVideo, generateSubtitles, MpvThumbnailRequest, MpvUpscaleRequest, MpvSubtitleRequest, MpvMediaProcessor.extractThumbnails, requireMediaPaths.

The source describes its contract as:

Offline media jobs, independent of any playing [MpvPlayer]. Paths refer to local files. Implementations must preserve cancellation, clean up partial output, and refuse to overwrite existing files. Desktop ships DesktopMpvMediaProcessor; mobile applications can implement this interface using their own native processing backend.

package io.github.kmpmpv

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/**
 * Offline media jobs, independent of any playing [MpvPlayer].
 *
 * Paths refer to local files. Implementations must preserve cancellation, clean up partial
 * output, and refuse to overwrite existing files. Desktop ships `DesktopMpvMediaProcessor`;
 * mobile applications can implement this interface using their own native processing backend.
 */
public interface MpvMediaProcessor {
    /** Writes one PNG, preserving aspect ratio within the requested bounding box. */
    public suspend fun extractThumbnail(request: MpvThumbnailRequest): String

    /** Writes H.264/AAC MP4 with Lanczos scaling and letterboxing to the requested dimensions. */
    public suspend fun upscaleVideo(request: MpvUpscaleRequest): String

    /** Transcribes the first audio track to SRT using a caller-supplied local Whisper model. */
    public suspend fun generateSubtitles(request: MpvSubtitleRequest): String
}

public data class MpvThumbnailRequest(
    public val inputPath: String,
    public val outputPath: String,
    public val positionSeconds: Double,
    public val maxWidth: Int = 320,
    public val maxHeight: Int = 180,
) {
    init {
        requireMediaPaths(inputPath, outputPath)
        require(positionSeconds.isFinite() && positionSeconds >= 0) { "positionSeconds must be finite and nonnegative" }
        require(maxWidth in 1..4096 && maxHeight in 1..4096) { "thumbnail dimensions must be in 1..4096" }
    }
}

public data class MpvUpscaleRequest(
    public val inputPath: String,
    public val outputPath: String,
    public val width: Int = 1920,
    public val height: Int = 1080,
    /** x264 constant rate factor: lower is higher quality and a larger file. */
    public val quality: Int = 20,
) {
    init {
        requireMediaPaths(inputPath, outputPath)
        require(width in 2..7680 && height in 2..4320 && width % 2 == 0 && height % 2 == 0) {
            "video dimensions must be even, within 2..7680 by 2..4320"
        }
        require(quality in 0..51) { "quality must be in 0..51" }
    }
}

public data class MpvSubtitleRequest(
    public val inputPath: String,
    public val outputPath: String,
    public val modelPath: String,
    /** Whisper language code, or auto for detection. */
    public val language: String = "auto",
    /** Translate speech to English instead of transcribing in its original language. */
    public val translateToEnglish: Boolean = false,
) {
    init {
        requireMediaPaths(inputPath, outputPath)
        require(modelPath.isNotBlank() && '\u0000' !in modelPath) { "modelPath must be a valid local path" }
        require(language == "auto" || language.length in 2..3 && language.all { it in 'a'..'z' }) {
            "language must be auto or a lowercase Whisper language code"
        }
    }
}

/** Cold, sequential extraction: emits file paths, without caching decoded frames or results. */
public fun MpvMediaProcessor.extractThumbnails(requests: Iterable<MpvThumbnailRequest>): Flow<String> = flow {
    for (request in requests) emit(extractThumbnail(request))
}

private fun requireMediaPaths(input: String, output: String) {
    require(input.isNotBlank() && output.isNotBlank() && '\u0000' !in input && '\u0000' !in output) {
        "inputPath and outputPath must be valid local paths"
    }
    require(input != output) { "input and output must be different files" }
}

Write vendor/kmp-mpv

This is a separate repository/build boundary: revision 41e5a2a867191baaeb343e1490566a8bbd83eb3c. Recreate its directory and build independently. Its tracked contents are included individually in this chapter. chapter-file-end: #

Write vendor/kmp-mpv/.github/workflows/build.yml

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

name: build

on:
  push:
  pull_request:

jobs:
  desktop:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v6
        with:
          distribution: temurin
          java-version: 21
      - uses: gradle/actions/setup-gradle@v6
      - run: ./gradlew :kmp-mpv:desktopTest

  android:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v6
        with:
          distribution: temurin
          java-version: 21
      - uses: android-actions/setup-android@v4
      - run: sdkmanager "platforms;android-36" "build-tools;36.1.0" "ndk;28.2.13676358" "cmake;3.22.1"
      - uses: gradle/actions/setup-gradle@v6
      - run: ./gradlew :android-bridge:assembleRelease :kmp-mpv:compileAndroidMain

  ios:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v6
        with:
          distribution: temurin
          java-version: 21
      - uses: gradle/actions/setup-gradle@v6
      - run: ./gradlew :kmp-mpv:compileKotlinIosSimulatorArm64

Write vendor/kmp-mpv/.gitignore

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

.gradle/
.idea/
.settings/
.project
**/.classpath
.kotlin/
**/build/
local.properties
*.iml
*.log
.DS_Store
DerivedData/
xcuserdata/
*.xcuserstate
.cxx

Write vendor/kmp-mpv/ARCHITECTURE.md

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

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

Write vendor/kmp-mpv/LICENSE

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

MIT License

Copyright (c) 2026 FriedCutlet

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Write vendor/kmp-mpv/README.md

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

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

Write vendor/kmp-mpv/THIRD_PARTY_NOTICES.md

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

# Third-party notices

The source in this repository is MIT licensed, but its build downloads and packages native artifacts originally selected by the upstream media-kit project. Those binaries and their transitive libraries are not covered by this repository's MIT license.

## Pinned binary sets

| Target | Upstream artifact set | mpv/Lua configuration observed |
|---|---|---|
| Android (4 ABIs) | Schnitzel5 `libmpv-android-video-build` 0.39.0 `default-*.jar` | `gpl=false`, `lua=enabled` |
| macOS universal | Schnitzel5 `libmpv-darwin-build` `develop` default-video XCFramework archive | `gpl=false`, `lua=enabled` |
| iOS arm64 device | Schnitzel5 `libmpv-darwin-build` `develop` default-video XCFramework archive | `gpl=false`, `lua=enabled` |
| Windows x86_64 | Schnitzel5 `mpv-winbuild-cmake` 2025-08-27 archive | GPL features enabled, `lua=enabled` |
| Linux | distribution-provided libmpv | depends on the distribution |

URLs and SHA-256 values are pinned in `android-bridge/build.gradle.kts`, `kmp-mpv/build.gradle.kts`, and `scripts/prepare-media-kit-ios.sh`. Preserve those checksums when auditing or reproducing a release.

## Distribution obligations

- mpv can be LGPL-2.1-or-later or GPL-2.0-or-later depending on its build configuration. Treat the selected Windows artifact as GPL, not LGPL-only.
- A non-GPL mpv configuration does not establish the license of the complete archive. FFmpeg, codecs, subtitle/font libraries, TLS libraries, Lua, and other packaged frameworks retain their respective terms.
- FFmpeg licensing depends on its configuration and enabled external libraries.
- Codec use can carry separate patent or regional legal considerations.
- Redistributors should generate and preserve notices, license texts, corresponding-source/source-offer materials, and relinking materials as required by every library actually shipped.
- JNA is available under Apache-2.0 or LGPL-2.1-or-later terms and is used by the JVM desktop artifact.
- kotlinx.coroutines is Apache-2.0 licensed.

The build recipes and binary publishers are provenance references, not a substitute for a release-specific license audit. Nothing in this notice is legal advice.

Write vendor/kmp-mpv/build.gradle.kts

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

plugins {
    alias(libs.plugins.kotlin.multiplatform) apply false
    alias(libs.plugins.android.library) apply false
    alias(libs.plugins.android.kotlin.multiplatform.library) apply false
}

allprojects {
    group = "io.github.kmpmpv"
    version = providers.gradleProperty("VERSION_NAME").getOrElse("0.1.0-SNAPSHOT")
}

Write vendor/kmp-mpv/gradle.properties

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
org.gradle.caching=true
org.gradle.configuration-cache=false
kotlin.code.style=official
kotlin.mpp.enableCInteropCommonization=true
VERSION_NAME=0.1.0-SNAPSHOT

Write vendor/kmp-mpv/gradle/libs.versions.toml

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

[versions]
kotlin = "2.4.21"
agp = "9.4.1"
coroutines = "1.11.0"
jna = "5.19.1"

[libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }

[plugins]
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
android-library = { id = "com.android.library", version.ref = "agp" }
android-kotlin-multiplatform-library = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" }

Write vendor/kmp-mpv/gradle/wrapper/gradle-wrapper.jar

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

This file is binary. Retain the downloaded asset at this exact path, with its applicable license. It is an input to the code/configuration in this step; it cannot be recreated by typing a Kotlin snippet. chapter-file-end: #

Write vendor/kmp-mpv/gradle/wrapper/gradle-wrapper.properties

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Write vendor/kmp-mpv/gradlew

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

#!/bin/sh

#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
#   gradlew start up script for POSIX generated by Gradle.
#
#   Important for running:
#
#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
#       noncompliant, but you have some other compliant shell such as ksh or
#       bash, then to run this script, type that shell name before the whole
#       command line, like:
#
#           ksh gradlew
#
#       Busybox and similar reduced shells will NOT work, because this script
#       requires all of these POSIX shell features:
#         * functions;
#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
#         * compound commands having a testable exit status, especially «case»;
#         * various built-in commands including «command», «set», and «ulimit».
#
#   Important for patching:
#
#   (2) This script targets any POSIX shell, so it avoids extensions provided
#       by Bash, Ksh, etc; in particular arrays are avoided.
#
#       The "traditional" practice of packing multiple parameters into a
#       space-separated string is a well documented source of bugs and security
#       problems, so this is (mostly) avoided, by progressively accumulating
#       options in "$@", and eventually passing that to Java.
#
#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
#       see the in-line comments for details.
#
#       There are tweaks for specific operating systems such as AIX, CygWin,
#       Darwin, MinGW, and NonStop.
#
#   (3) This script is generated from the Groovy template
#       https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
#       within the Gradle project.
#
#       You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
app_path=$0

# Need this for daisy-chained symlinks.
while
    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
    [ -h "$app_path" ]
do
    ls=$( ls -ld "$app_path" )
    link=${ls#*' -> '}
    case $link in             #(
      /*)   app_path=$link ;; #(
      *)    app_path=$APP_HOME$link ;;
    esac
done

# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

warn () {
    echo "$*"
} >&2

die () {
    echo
    echo "$*"
    echo
    exit 1
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in                #(
  CYGWIN* )         cygwin=true  ;; #(
  Darwin* )         darwin=true  ;; #(
  MSYS* | MINGW* )  msys=true    ;; #(
  NONSTOP* )        nonstop=true ;;
esac



# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD=$JAVA_HOME/jre/sh/java
    else
        JAVACMD=$JAVA_HOME/bin/java
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD=java
    if ! command -v java >/dev/null 2>&1
    then
        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
    case $MAX_FD in #(
      max*)
        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        MAX_FD=$( ulimit -H -n ) ||
            warn "Could not query maximum file descriptor limit"
    esac
    case $MAX_FD in  #(
      '' | soft) :;; #(
      *)
        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        ulimit -n "$MAX_FD" ||
            warn "Could not set maximum file descriptor limit to $MAX_FD"
    esac
fi

# Collect all arguments for the java command, stacking in reverse order:
#   * args from the command line
#   * the main class name
#   * -classpath
#   * -D...appname settings
#   * --module-path (only if needed)
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )

    JAVACMD=$( cygpath --unix "$JAVACMD" )

    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    for arg do
        if
            case $arg in                                #(
              -*)   false ;;                            # don't mess with options #(
              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
                    [ -e "$t" ] ;;                      #(
              *)    false ;;
            esac
        then
            arg=$( cygpath --path --ignore --mixed "$arg" )
        fi
        # Roll the args list around exactly as many times as the number of
        # args, so each arg winds up back in the position where it started, but
        # possibly modified.
        #
        # NB: a `for` loop captures its iteration list before it begins, so
        # changing the positional parameters here affects neither the number of
        # iterations, nor the values presented in `arg`.
        shift                   # remove old arg
        set -- "$@" "$arg"      # push replacement arg
    done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
#     and any embedded shellness will be escaped.
#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
#     treated as '${Hostname}' itself on the command line.

set -- \
        "-Dorg.gradle.appname=$APP_BASE_NAME" \
        -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
        "$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
    die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
#   set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
        xargs -n1 |
        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
        tr '\n' ' '
    )" '"$@"'

exec "$JAVACMD" "$@"

Write vendor/kmp-mpv/gradlew.bat

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem  gradlew startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions

@rem Catch executions from older scripts and ensure they exit cleanly.
@rem This can be removed once we can be reasonably confident that few people
@rem will be migrating directly to this new wrapper.
goto afterSafetyNet
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto exitWithErrorLevel
:afterSafetyNet

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

1>&2 echo.
1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
1>&2 echo.
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
1>&2 echo location of your Java installation.

"%COMSPEC%" /c exit 1
goto exitWithErrorLevel

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

1>&2 echo.
1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
1>&2 echo.
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
1>&2 echo location of your Java installation.

"%COMSPEC%" /c exit 1
goto exitWithErrorLevel

:execute
@rem Setup the command line



@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel

@rem This label must not be changed. We rely on old scripts being able to jump to this point.
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%

Write vendor/kmp-mpv/kmp-mpv/build.gradle.kts

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.gradle.api.tasks.testing.Test
import java.net.URI
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest

plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.android.kotlin.multiplatform.library)
    `maven-publish`
}

val generatedDesktopResources = layout.buildDirectory.dir("generated/mediaKitDesktopResources")
val mediaKitBinaryCache = layout.buildDirectory.dir("media-kit-mpv/downloads")

val prepareMediaKitDesktopMpv = tasks.register("prepareMediaKitDesktopMpv") {
    description = "Prepares the host desktop libmpv binary pinned by media-kit."
    group = "mpv binaries"
    outputs.dir(generatedDesktopResources)

    doLast {
        val output = generatedDesktopResources.get().asFile
        output.deleteRecursively()
        output.mkdirs()

        fun download(url: String, fileName: String, sha256: String): File {
            val destination = mediaKitBinaryCache.get().file(fileName).asFile
            destination.parentFile.mkdirs()
            fun checksum(file: File): String = MessageDigest.getInstance("SHA-256")
                .digest(Files.readAllBytes(file.toPath()))
                .joinToString("") { byte -> "%02x".format(byte) }

            if (destination.isFile && checksum(destination) == sha256) return destination
            val temporary = destination.resolveSibling("${destination.name}.part")
            temporary.delete()
            URI(url).toURL().openStream().use { input ->
                Files.copy(input, temporary.toPath(), StandardCopyOption.REPLACE_EXISTING)
            }
            val actual = checksum(temporary)
            check(actual == sha256) {
                "SHA-256 mismatch for $fileName: expected $sha256, got $actual"
            }
            Files.move(
                temporary.toPath(),
                destination.toPath(),
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE,
            )
            return destination
        }

        val os = System.getProperty("os.name").lowercase()
        val manifest = mutableListOf<String>()
        when {
            "mac" in os || "darwin" in os -> {
                val archive = download(
                    "https://github.com/Schnitzel5/libmpv-darwin-build/releases/download/develop/" +
                        "libmpv-xcframeworks_develop_macos-universal-video-default.tar.gz",
                    "libmpv-xcframeworks_develop_macos-universal-video-default.tar.gz",
                    "2fa164b1083fb5895085047672ae446aad4903bfee5816276d6a7f6613b31acd",
                )
                val extracted = layout.buildDirectory.dir("media-kit-mpv/macos-extracted").get().asFile
                extracted.deleteRecursively()
                copy {
                    from(tarTree(resources.gzip(archive)))
                    into(extracted)
                }

                val archiveRoot = extracted.resolve(
                    "libmpv-xcframeworks_develop_macos-universal-video-default",
                )
                val frameworks = listOf(
                    "Ass", "Avcodec", "Avfilter", "Avformat", "Avutil", "Dav1d", "Freetype",
                    "Fribidi", "Harfbuzz", "Lua", "Mbedcrypto", "Mbedtls", "Mbedx509", "Mpv",
                    "Png16", "Swresample", "Swscale", "Uchardet", "Xml2",
                )
                frameworks.forEach { name ->
                    val source = archiveRoot.resolve(
                        "$name.xcframework/macos-arm64_x86_64/$name.framework/Versions/A/$name",
                    )
                    check(source.isFile) { "Missing $name framework in ${archive.name}" }
                    val relative = "native/macos/Frameworks/$name.framework/Versions/A/$name"
                    val destination = output.resolve(relative)
                    destination.parentFile.mkdirs()
                    source.copyTo(destination, overwrite = true)
                    destination.setExecutable(true)

                    val patchResult = ProcessBuilder(
                        "/usr/bin/install_name_tool",
                        "-add_rpath",
                        "@loader_path/../../..",
                        destination.absolutePath,
                    ).inheritIO().start().waitFor()
                    check(patchResult == 0) { "install_name_tool failed for $name" }
                    manifest += relative
                }
            }
            "win" in os -> {
                val archive = download(
                    "https://github.com/Schnitzel5/mpv-winbuild-cmake/releases/download/20250727/" +
                        "mpv-dev-x86_64-20250827-git-9f153e2.7z",
                    "mpv-dev-x86_64-20250827-git-9f153e2.7z",
                    "b008c8301b83060c809d3fe7b26a135bc82d77e970b21d2c6d91cb1413d20dd3",
                )
                val extracted = layout.buildDirectory.dir("media-kit-mpv/windows-extracted").get().asFile
                extracted.deleteRecursively()
                extracted.mkdirs()
                val extractResult = ProcessBuilder(
                    "cmake", "-E", "tar", "xf", archive.absolutePath,
                ).directory(extracted).inheritIO().start().waitFor()
                check(extractResult == 0) { "CMake could not extract ${archive.name}" }
                val relative = "native/windows-x86_64/libmpv-2.dll"
                extracted.resolve("libmpv-2.dll").copyTo(output.resolve(relative).also {
                    it.parentFile.mkdirs()
                })
                manifest += relative
            }
            else -> {
                output.resolve("native/linux-system.txt").apply {
                    parentFile.mkdirs()
                    writeText("media-kit uses the distribution-provided libmpv on Linux.\n")
                }
            }
        }
        output.resolve("native/manifest.txt").apply {
            parentFile.mkdirs()
            writeText(manifest.joinToString(separator = "\n", postfix = if (manifest.isEmpty()) "" else "\n"))
        }
    }
}

kotlin {
    explicitApi()
    jvmToolchain(21)
    compilerOptions {
        freeCompilerArgs.add("-Xexpect-actual-classes")
    }

    jvm("desktop") {
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }

    android {
        namespace = "io.github.kmpmpv"
        compileSdk = 36
        minSdk = 24
        withHostTest {}
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }

    val iosTargets = listOf(
        iosArm64(),
        iosSimulatorArm64(),
        iosX64(),
    )

    iosTargets.forEach { target ->
        target.compilations.getByName("main").cinterops.create("mpvDynamic") {
            definitionFile.set(project.file("src/nativeInterop/cinterop/mpvDynamic.def"))
            includeDirs(project.file("src/nativeInterop/cinterop/include"))
        }
        target.binaries.framework {
            baseName = "KmpMpv"
            isStatic = false
        }
    }

    sourceSets {
        commonMain.dependencies {
            api(libs.kotlinx.coroutines.core)
        }
        commonTest.dependencies {
            implementation(libs.kotlin.test)
            implementation(libs.kotlinx.coroutines.test)
        }
        getByName("desktopMain").dependencies {
            implementation(libs.jna)
        }
        getByName("desktopMain").resources.srcDir(generatedDesktopResources)
        getByName("desktopTest").dependencies {
            implementation(libs.kotlin.test)
        }
        androidMain.dependencies {
            api(project(":android-bridge"))
        }
    }
}

tasks.matching { it.name == "desktopProcessResources" }.configureEach {
    dependsOn(prepareMediaKitDesktopMpv)
}

tasks.withType<Test>().configureEach {
    // Opt-in integration tests must rerun when their tools, model, or enable flags change.
    listOf(
        "KMP_MPV_RUN_NATIVE_TESTS", "KMP_MPV_LIBRARY_PATH", "KMP_MPV_RUN_MEDIA_TESTS",
        "KMP_MPV_RUN_WHISPER_TESTS", "KMP_MPV_FFMPEG", "KMP_MPV_WHISPER",
        "KMP_MPV_WHISPER_MODEL", "KMP_MPV_SPEECH_SAMPLE",
    ).forEach { name ->
        val value = providers.gradleProperty(name).orElse(providers.environmentVariable(name)).orElse("")
        inputs.property(name, value)
        value.get().takeIf(String::isNotEmpty)?.let { environment(name, it) }
    }
}

publishing {
    publications.withType<MavenPublication>().configureEach {
        pom {
            name.set("kmp-mpv")
            description.set("Kotlin Multiplatform bindings and player API for libmpv")
            url.set("https://github.com/kmp-mpv/kmp-mpv")
            licenses {
                license {
                    name.set("MIT License")
                    url.set("https://opensource.org/license/mit")
                }
            }
        }
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopMain/kotlin/io/github/kmpmpv/DesktopMpvMediaProcessor.kt

Create this path in your reconstruction project. Source set: desktopMain. Exact file download.

The implementation below defines DesktopMpvMediaProcessor, extractThumbnail, upscaleVideo, generateSubtitles, fitScale, ffmpegPrefix, job, localInput, MpvMediaToolsConfiguration.

The source describes its contract as:

Local FFmpeg/whisper.cpp processing. Executables and models are supplied by the application; nothing is downloaded or uploaded. Calls suspend, can be cancelled, and run off the UI thread. Reuse one processor to share its concurrency limit. No close is needed: jobs own their processes.

package io.github.kmpmpv

import io.github.kmpmpv.internal.MediaProcessRunner
import io.github.kmpmpv.internal.SystemMediaProcessRunner
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.nio.file.Files
import java.nio.file.Path

/**
 * Local FFmpeg/whisper.cpp processing. Executables and models are supplied by the application;
 * nothing is downloaded or uploaded. Calls suspend, can be cancelled, and run off the UI thread.
 * Reuse one processor to share its concurrency limit. No close is needed: jobs own their processes.
 */
public class DesktopMpvMediaProcessor internal constructor(
    private val configuration: MpvMediaToolsConfiguration,
    private val runner: MediaProcessRunner,
) : MpvMediaProcessor {
    public constructor(configuration: MpvMediaToolsConfiguration = MpvMediaToolsConfiguration()) :
        this(configuration, SystemMediaProcessRunner())

    private val permits = Semaphore(configuration.maxConcurrentJobs)

    override suspend fun extractThumbnail(request: MpvThumbnailRequest): String =
        job(request.inputPath, request.outputPath, ".png") { input, temporary ->
            runner.run(ffmpegPrefix() + listOf(
                "-ss", request.positionSeconds.toString(), "-i", input.toString(),
                "-map", "0:v:0", "-an", "-sn", "-dn", "-frames:v", "1",
                "-vf", fitScale(request.maxWidth, request.maxHeight, 1),
                "-threads", configuration.threads.toString(), "-c:v", "png", "-update", "1",
                "-f", "image2", temporary.toString(),
            ))
        }

    override suspend fun upscaleVideo(request: MpvUpscaleRequest): String =
        job(request.inputPath, request.outputPath, ".mp4") { input, temporary ->
            val dimensions = "${request.width}:${request.height}"
            runner.run(ffmpegPrefix() + listOf(
                "-i", input.toString(), "-map", "0:v:0", "-map", "0:a:0?", "-sn", "-dn",
                "-vf", fitScale(request.width, request.height, 2) + ",pad=$dimensions:(ow-iw)/2:(oh-ih)/2",
                "-c:v", "libx264", "-preset", "fast", "-crf", request.quality.toString(),
                "-pix_fmt", "yuv420p", "-threads", configuration.threads.toString(),
                "-c:a", "aac", "-movflags", "+faststart", "-f", "mp4", temporary.toString(),
            ))
        }

    override suspend fun generateSubtitles(request: MpvSubtitleRequest): String =
        job(request.inputPath, request.outputPath, ".srt") { input, temporary ->
            val model = localInput(request.modelPath)
            val audio = temporary.resolveSibling("audio.wav")
            runner.run(ffmpegPrefix() + listOf(
                "-i", input.toString(), "-map", "0:a:0", "-vn", "-sn", "-dn",
                "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "wav", audio.toString(),
            ))
            val outputBase = temporary.resolveSibling("transcript")
            runner.run(listOf(
                configuration.whisperExecutable, "-m", model.toString(), "-f", audio.toString(),
                "-l", request.language, "-t", configuration.threads.toString(),
                "-osrt", "-of", outputBase.toString(),
            ) + if (request.translateToEnglish) listOf("-tr") else emptyList())
            Files.move(outputBase.resolveSibling("transcript.srt"), temporary)
        }

    // dar includes sample aspect ratio: anamorphic sources must not be stretched when
    // producing square-pixel PNG/H.264 output. Round down for the encoder's chroma alignment.
    private fun fitScale(width: Int, height: Int, multiple: Int): String =
        "scale=w='max($multiple,trunc(min($width,$height*dar)/$multiple)*$multiple)':" +
            "h='max($multiple,trunc(min($height,$width/dar)/$multiple)*$multiple)':flags=lanczos,setsar=1"

    private fun ffmpegPrefix(): List<String> = listOf(
        configuration.ffmpegExecutable, "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
        "-threads", configuration.threads.toString(), "-filter_threads", configuration.threads.toString(),
    )

    private suspend fun job(
        inputPath: String,
        outputPath: String,
        extension: String,
        process: suspend (Path, Path) -> Unit,
    ): String = permits.withPermit {
        withTimeout(configuration.timeoutMillis) {
            withContext(Dispatchers.IO) {
                val input = localInput(inputPath)
                val output = Path.of(outputPath).toAbsolutePath().normalize()
                require(output.fileName.toString().endsWith(extension, ignoreCase = true)) {
                    "outputPath must end with $extension"
                }
                require(!Files.exists(output)) { "output already exists: $output" }
                require(Files.isDirectory(output.parent)) { "output parent directory must exist" }
                val directory = Files.createTempDirectory(output.parent, ".kmp-mpv-")
                try {
                    val temporary = directory.resolve("output$extension")
                    process(input, temporary)
                    currentCoroutineContext().ensureActive()
                    check(Files.isRegularFile(temporary) && (extension == ".srt" || Files.size(temporary) > 0)) {
                        "media tool produced no output (the timestamp may be past the end of the video)"
                    }
                    // Deliberately omit REPLACE_EXISTING, including for races with another job.
                    Files.move(temporary, output)
                    output.toString()
                } finally {
                    Files.newDirectoryStream(directory).use { files ->
                        files.forEach { Files.deleteIfExists(it) }
                    }
                    Files.deleteIfExists(directory)
                }
            }
        }
    }

    private fun localInput(path: String): Path = Path.of(path).toAbsolutePath().normalize().also {
        require(Files.isRegularFile(it) && Files.isReadable(it)) { "input must be a readable local file: $it" }
    }
}

public data class MpvMediaToolsConfiguration(
    public val ffmpegExecutable: String = "ffmpeg",
    public val whisperExecutable: String = "whisper-cli",
    public val threads: Int = 2,
    public val maxConcurrentJobs: Int = 1,
    /** Per job, excluding time waiting for a concurrency permit. */
    public val timeoutMillis: Long = 60 * 60 * 1000L,
) {
    init {
        require(ffmpegExecutable.isNotBlank() && '\u0000' !in ffmpegExecutable) { "invalid FFmpeg executable" }
        require(whisperExecutable.isNotBlank() && '\u0000' !in whisperExecutable) { "invalid Whisper executable" }
        require(threads in 1..64) { "threads must be in 1..64" }
        require(maxConcurrentJobs in 1..8) { "maxConcurrentJobs must be in 1..8" }
        require(timeoutMillis > 0) { "timeoutMillis must be positive" }
    }
}

Write vendor/kmp-mpv/scripts/prepare-media-kit-ios.sh

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

#!/bin/sh
set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
CACHE_DIR="$ROOT_DIR/build/media-kit-mpv/downloads"
OUTPUT_DIR="$ROOT_DIR/build/media-kit-mpv/ios"
ARCHIVE="$CACHE_DIR/libmpv-xcframeworks_develop_ios-universal-video-default.tar.gz"
URL="https://github.com/Schnitzel5/libmpv-darwin-build/releases/download/develop/libmpv-xcframeworks_develop_ios-universal-video-default.tar.gz"
SHA256="54a3430972367f88cf2efdf53621ee11d7d663f4e2b1d0860950278fc7d136eb"

mkdir -p "$CACHE_DIR"

actual_checksum() {
    shasum -a 256 "$1" | awk '{print $1}'
}

if [ ! -f "$ARCHIVE" ] || [ "$(actual_checksum "$ARCHIVE")" != "$SHA256" ]; then
    curl -L --fail --retry 3 "$URL" -o "$ARCHIVE.part"
    if [ "$(actual_checksum "$ARCHIVE.part")" != "$SHA256" ]; then
        echo "SHA-256 verification failed for the media-kit iOS libmpv archive" >&2
        exit 1
    fi
    mv "$ARCHIVE.part" "$ARCHIVE"
fi

if [ -f "$OUTPUT_DIR/.complete-$SHA256" ]; then
    exit 0
fi

rm -rf "$OUTPUT_DIR"
mkdir -p "$OUTPUT_DIR"
tar -xzf "$ARCHIVE" --strip-components 1 -C "$OUTPUT_DIR"
touch "$OUTPUT_DIR/.complete-$SHA256"

echo "$OUTPUT_DIR"

Write vendor/kmp-mpv/settings.gradle.kts

Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.

pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "kmp-mpv"

include(":kmp-mpv")
include(":android-bridge")

Check your understanding

Cancel frame extraction or transcoding after temporary output appears. Confirm the child process is reaped before temp cleanup and no incomplete final file is published. [chapter-content-end]: #

Recreate the tests and verify the chapter

Run the submodule's fake-engine, state/event, release and offline-processor tests from vendor/kmp-mpv. Add native desktop render/smoke tests, Android Surface recreation and iOS device playback after dependencies are prepared. Downloaded libmpv/FFmpeg/whisper/model artifacts are external prerequisites, not generated by typing the Kotlin API.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

Write vendor/kmp-mpv/kmp-mpv/src/commonTest/kotlin/io/github/kmpmpv/DefaultMpvPlayerTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines DefaultMpvPlayerTest, releaseCompletesEvenFromAnAlreadyCancelledCaller, failedNativeCloseRetriesWithoutAdmittingPlaybackAgain, concurrentReleaseDestroysTheClientOnlyOnce, refusesOversizedFramesBeforeCallingNativeCode, playbackFeaturesAcceptPathsWithSpacesAsSingleArguments, delegatesPlaybackCommandsAndReleasesOnce, mapsNativeEventsIntoPublicState, typedPropertyReadsPreserveValues, FakeMpvEngine and 13 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • releaseCompletesEvenFromAnAlreadyCancelledCaller
  • failedNativeCloseRetriesWithoutAdmittingPlaybackAgain
  • concurrentReleaseDestroysTheClientOnlyOnce
  • refusesOversizedFramesBeforeCallingNativeCode
  • playbackFeaturesAcceptPathsWithSpacesAsSingleArguments
  • delegatesPlaybackCommandsAndReleasesOnce
  • mapsNativeEventsIntoPublicState
  • typedPropertyReadsPreserveValues
package io.github.kmpmpv

import io.github.kmpmpv.internal.EngineResult
import io.github.kmpmpv.internal.MpvEngine
import io.github.kmpmpv.internal.NativeEventId
import io.github.kmpmpv.internal.RawMpvEvent
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertIs
import kotlin.test.assertTrue

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class DefaultMpvPlayerTest {
    @Test
    fun releaseCompletesEvenFromAnAlreadyCancelledCaller() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(engine, MpvConfiguration(), StandardTestDispatcher(testScheduler))
        launch {
            cancel()
            player.release()
        }.join()
        player.release()
        assertEquals(1, engine.closeCount)
        assertEquals(MpvPlaybackStatus.Released, player.state.value.status)
        assertFailsWith<IllegalStateException> { player.play() }
    }

    @Test
    fun failedNativeCloseRetriesWithoutAdmittingPlaybackAgain() = runTest {
        val engine = FakeMpvEngine()
        engine.onClose = { check(engine.closeCount > 1) { "Native close failed" } }
        val player = DefaultMpvPlayer(engine, MpvConfiguration(), StandardTestDispatcher(testScheduler))
        assertFailsWith<IllegalStateException> { player.release() }
        assertEquals(MpvPlaybackStatus.Released, player.state.value.status)
        assertFailsWith<IllegalStateException> { player.play() }
        player.release(); player.release()
        assertEquals(2, engine.closeCount)
        assertTrue(engine.commands.isEmpty())
    }

    @Test
    fun concurrentReleaseDestroysTheClientOnlyOnce() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(engine, MpvConfiguration(), StandardTestDispatcher(testScheduler))
        List(10) { launch { player.release() } }.forEach { it.join() }
        assertEquals(1, engine.closeCount)
    }

    @Test
    fun refusesOversizedFramesBeforeCallingNativeCode() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(
            engine, MpvConfiguration(maxSoftwareFrameBytes = 1024), StandardTestDispatcher(testScheduler),
        )
        try {
            assertFailsWith<IllegalArgumentException> { player.renderSoftwareFrame(100, 100) }
            assertFailsWith<IllegalArgumentException> { player.renderSoftwareFrame(Int.MAX_VALUE, Int.MAX_VALUE) }
        } finally {
            player.release()
        }
    }

    @Test
    fun playbackFeaturesAcceptPathsWithSpacesAsSingleArguments() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(engine, MpvConfiguration(), StandardTestDispatcher(testScheduler))
        try {
            player.saveScreenshot("/tmp/my frame.png")
            player.addSubtitles("/tmp/my subtitles.srt")
            player.stepFrame(backwards = true)
            player.setUpscalingPreset(MpvUpscalingPreset.HighQuality)
            assertEquals(listOf("screenshot-to-file", "/tmp/my frame.png", "video"), engine.commands[0])
            assertEquals(listOf("sub-add", "/tmp/my subtitles.srt", "select"), engine.commands[1])
            assertEquals(listOf("frame-back-step"), engine.commands[2])
            assertEquals(MpvValue.Text("ewa_lanczossharp"), engine.writtenProperties["scale"])
        } finally {
            player.release()
        }
    }

    @Test
    fun delegatesPlaybackCommandsAndReleasesOnce() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(
            engine,
            MpvConfiguration(eventPollTimeoutSeconds = 0.001),
            StandardTestDispatcher(testScheduler),
        )

        player.load("movie.mkv", MpvLoadMode.AppendAndPlay)
        player.seek(12.5, MpvSeekMode.Absolute)
        player.pause()
        player.release()
        player.release()

        assertEquals(listOf("loadfile", "movie.mkv", "append-play"), engine.commands[0])
        assertEquals(listOf("seek", "12.5", "absolute"), engine.commands[1])
        assertEquals(MpvValue.Flag(true), engine.writtenProperties["pause"])
        assertEquals(1, engine.closeCount)
        assertEquals(MpvPlaybackStatus.Released, player.state.value.status)
    }

    @Test
    fun mapsNativeEventsIntoPublicState() = runTest {
        val engine = FakeMpvEngine()
        val player = DefaultMpvPlayer(
            engine,
            MpvConfiguration(eventPollTimeoutSeconds = 0.001),
            StandardTestDispatcher(testScheduler),
        )
        engine.events += RawMpvEvent(NativeEventId.START_FILE)
        engine.events += RawMpvEvent(NativeEventId.FILE_LOADED)
        engine.events += RawMpvEvent(
            eventId = NativeEventId.PROPERTY_CHANGE,
            propertyName = "duration",
            propertyValue = MpvValue.Decimal(90.0),
        )
        engine.events += RawMpvEvent(
            eventId = NativeEventId.PROPERTY_CHANGE,
            propertyName = "pause",
            propertyValue = MpvValue.Flag(true),
        )

        runCurrent()

        assertEquals(MpvPlaybackStatus.Paused, player.state.value.status)
        assertEquals(90.0, player.state.value.durationSeconds)
        assertTrue(player.state.value.paused)
        player.release()
    }

    @Test
    fun typedPropertyReadsPreserveValues() = runTest {
        val engine = FakeMpvEngine().apply {
            readableProperties["media-title"] = MpvValue.Text("Example")
            readableProperties["duration"] = MpvValue.Decimal(42.0)
        }
        val player = DefaultMpvPlayer(
            engine,
            MpvConfiguration(eventPollTimeoutSeconds = 0.001),
            StandardTestDispatcher(testScheduler),
        )

        assertEquals("Example", player.getStringProperty("media-title"))
        assertEquals(42.0, player.getDoubleProperty("duration"))
        assertIs<MpvValue.Text>(player.getProperty("media-title", MpvFormat.String))
        player.release()
    }
}

private class FakeMpvEngine : MpvEngine {
    val commands = mutableListOf<List<String>>()
    val writtenProperties = mutableMapOf<String, MpvValue>()
    val readableProperties = mutableMapOf<String, MpvValue>()
    val observations = mutableMapOf<Long, Pair<String, MpvFormat>>()
    val events = ArrayDeque<RawMpvEvent>()
    var closeCount = 0
    var onClose: () -> Unit = {}

    override fun command(arguments: List<String>): Int {
        commands += arguments
        return 0
    }

    override fun getProperty(name: String, format: MpvFormat): EngineResult<MpvValue> =
        readableProperties[name]?.let { EngineResult(0, it) } ?: EngineResult(-10)

    override fun setProperty(name: String, value: MpvValue): Int {
        writtenProperties[name] = value
        return 0
    }

    override fun observeProperty(
        observationId: Long,
        name: String,
        format: MpvFormat,
    ): Int {
        observations[observationId] = name to format
        return 0
    }

    override fun unobserveProperty(observationId: Long): Int {
        observations.remove(observationId)
        return 0
    }

    override fun requestLogMessages(level: String): Int = 0

    override fun waitEvent(timeoutSeconds: Double): RawMpvEvent =
        if (events.isEmpty()) RawMpvEvent(NativeEventId.NONE) else events.removeFirst()

    override fun attachRenderTarget(target: MpvRenderTarget): Int = 0

    override fun detachRenderTarget(): Int = 0

    override fun updateRenderTargetSize(width: Int, height: Int): Int = 0

    override fun errorString(errorCode: Int): String = "error $errorCode"

    override fun wakeup() = Unit

    override fun close() {
        closeCount += 1
        onClose()
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/commonTest/kotlin/io/github/kmpmpv/MpvConfigurationTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines MpvConfigurationTest, defaultsAreSafeForAnEmbeddedClient, rejectsInvalidPollingConfiguration.

Read the setup, action and assertions in these cases before implementing their production paths:

  • defaultsAreSafeForAnEmbeddedClient
  • rejectsInvalidPollingConfiguration
package io.github.kmpmpv

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class MpvConfigurationTest {
    @Test
    fun defaultsAreSafeForAnEmbeddedClient() {
        val configuration = MpvConfiguration()

        assertEquals("yes", configuration.options["idle"])
        assertEquals("no", configuration.options["terminal"])
        assertTrue(configuration.eventBufferCapacity > 0)
    }

    @Test
    fun rejectsInvalidPollingConfiguration() {
        assertFailsWith<IllegalArgumentException> {
            MpvConfiguration(eventPollTimeoutSeconds = 0.0)
        }
        assertFailsWith<IllegalArgumentException> {
            MpvConfiguration(eventBufferCapacity = 0)
        }
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopTest/kotlin/io/github/kmpmpv/DesktopMpvMediaProcessorTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines DesktopMpvMediaProcessorTest, publishesOnlyFinishedOutputsAndPreservesExistingFiles, removesPartialOutputAfterFailureAndCancellation, callerCancellationReleasesPermitAndCleansAudio, subtitlePipelineUsesMonoAudioAndLocalModelAndCleansIntermediates, thumbnailFlowStopsProducingWhenCollectorStops, diagnosticOutputHasAFixedMemoryBound, processor, assertNoTemporaryFiles, withWorkspace.

Read the setup, action and assertions in these cases before implementing their production paths:

  • publishesOnlyFinishedOutputsAndPreservesExistingFiles
  • removesPartialOutputAfterFailureAndCancellation
  • callerCancellationReleasesPermitAndCleansAudio
  • subtitlePipelineUsesMonoAudioAndLocalModelAndCleansIntermediates
  • thumbnailFlowStopsProducingWhenCollectorStops
  • diagnosticOutputHasAFixedMemoryBound
package io.github.kmpmpv

import io.github.kmpmpv.internal.DiagnosticTail
import io.github.kmpmpv.internal.MediaProcessRunner
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.nio.file.Files
import java.nio.file.Path
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class DesktopMpvMediaProcessorTest {
    @Test
    fun publishesOnlyFinishedOutputsAndPreservesExistingFiles() = withWorkspace { root, input ->
        val commands = mutableListOf<List<String>>()
        val processor = processor { args ->
            commands += args
            Files.writeString(Path.of(args.last()), "png")
        }
        val output = root.resolve("thumbnail.png")
        val request = MpvThumbnailRequest(input.toString(), output.toString(), 2.5)
        assertEquals(output.toString(), processor.extractThumbnail(request))
        assertEquals("png", Files.readString(output))
        assertTrue(input.toString() in commands.single())
        assertFailsWith<IllegalArgumentException> { processor.extractThumbnail(request) }
        assertEquals(1, commands.size)
        assertNoTemporaryFiles(root)
    }

    @Test
    fun removesPartialOutputAfterFailureAndCancellation() = withWorkspace { root, input ->
        val output = root.resolve("thumbnail.png")
        for (failure in listOf(IllegalStateException("tool failed"), CancellationException("cancelled"))) {
            val processor = processor { args ->
                Files.writeString(Path.of(args.last()), "partial")
                throw failure
            }
            assertFailsWith<Exception> {
                processor.extractThumbnail(MpvThumbnailRequest(input.toString(), output.toString(), 0.0))
            }
            assertFalse(Files.exists(output))
            assertNoTemporaryFiles(root)
        }
    }

    @Test
    fun callerCancellationReleasesPermitAndCleansAudio() = withWorkspace { root, input ->
        val started = CompletableDeferred<Unit>()
        var firstCall = true
        val processor = processor { args ->
            Files.writeString(Path.of(args.last()), "partial")
            if (firstCall) {
                firstCall = false
                started.complete(Unit)
                awaitCancellation()
            }
        }
        val job = launch(Dispatchers.Default) {
            processor.extractThumbnail(MpvThumbnailRequest(input.toString(), root.resolve("one.png").toString(), 0.0))
        }
        started.await()
        job.cancelAndJoin()
        processor.extractThumbnail(MpvThumbnailRequest(input.toString(), root.resolve("two.png").toString(), 0.0))
        assertNoTemporaryFiles(root)
    }

    @Test
    fun subtitlePipelineUsesMonoAudioAndLocalModelAndCleansIntermediates() = withWorkspace { root, input ->
        val model = Files.writeString(root.resolve("local model.bin"), "model")
        val commands = mutableListOf<List<String>>()
        val processor = processor { args ->
            commands += args
            if ("-osrt" in args) {
                val base = args[args.indexOf("-of") + 1]
                Files.writeString(Path.of("$base.srt"), "1\n00:00:00,000 --> 00:00:01,000\nHello\n")
            } else Files.writeString(Path.of(args.last()), "wav")
        }
        val output = root.resolve("subtitles.srt")
        processor.generateSubtitles(MpvSubtitleRequest(input.toString(), output.toString(), model.toString()))
        assertTrue(Files.readString(output).contains("Hello"))
        assertEquals("1", commands[0][commands[0].indexOf("-ac") + 1])
        assertEquals("16000", commands[0][commands[0].indexOf("-ar") + 1])
        assertTrue(model.toString() in commands[1])
        assertNoTemporaryFiles(root)
    }

    @Test
    fun thumbnailFlowStopsProducingWhenCollectorStops() = withWorkspace { root, input ->
        var calls = 0
        val processor = processor { args ->
            calls++
            Files.writeString(Path.of(args.last()), "png")
        }
        val requests = (0..10).map {
            MpvThumbnailRequest(input.toString(), root.resolve("$it.png").toString(), it.toDouble())
        }
        assertEquals(1, processor.extractThumbnails(requests).take(1).toList().size)
        assertEquals(1, calls)
    }

    @Test
    fun diagnosticOutputHasAFixedMemoryBound() {
        val tail = DiagnosticTail(16)
        repeat(1000) { tail.append("0123456789".toByteArray(), 10) }
        assertEquals("4567890123456789", tail.text())
    }

    private fun processor(run: suspend (List<String>) -> Unit): DesktopMpvMediaProcessor =
        DesktopMpvMediaProcessor(MpvMediaToolsConfiguration(), MediaProcessRunner(run))

    private fun assertNoTemporaryFiles(root: Path) {
        Files.list(root).use { files ->
            assertFalse(files.anyMatch { it.fileName.toString().startsWith(".kmp-mpv-") })
        }
    }

    private fun withWorkspace(block: suspend kotlinx.coroutines.CoroutineScope.(Path, Path) -> Unit) = runBlocking {
        val root = Files.createTempDirectory("kmp-mpv-processing-test-")
        try {
            val input = Files.writeString(root.resolve("movie with spaces.mkv"), "input")
            block(root, input)
        } finally {
            root.toFile().deleteRecursively()
        }
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopTest/kotlin/io/github/kmpmpv/MediaProcessRunnerTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines MediaProcessRunnerTest, cancellationReapsTheProcessEvenWithAFullOutputPipe, reportsFailureWithBoundedDiagnostics, childCommand, MediaProcessTestChild, main.

The source describes its contract as:

A real child JVM, so process cleanup is tested without optional media tools or shell syntax.

Read the setup, action and assertions in these cases before implementing their production paths:

  • cancellationReapsTheProcessEvenWithAFullOutputPipe
  • reportsFailureWithBoundedDiagnostics
package io.github.kmpmpv

import io.github.kmpmpv.internal.SystemMediaProcessRunner
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import java.nio.file.Files
import java.nio.file.Path
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class MediaProcessRunnerTest {
    @Test
    fun cancellationReapsTheProcessEvenWithAFullOutputPipe() = runBlocking {
        val pidFile = Files.createTempFile("kmp-mpv-child-", ".pid")
        try {
            val job = async(Dispatchers.Default) {
                SystemMediaProcessRunner().run(childCommand("wait", pidFile.toString()))
            }
            val pid = withTimeout(10_000) {
                var text = ""
                while (text.isBlank()) {
                    delay(20)
                    text = Files.readString(pidFile)
                }
                text.toLong()
            }
            withTimeout(10_000) { job.cancelAndJoin() }
            assertFalse(ProcessHandle.of(pid).map { it.isAlive }.orElse(false))
        } finally {
            Files.deleteIfExists(pidFile)
        }
    }

    @Test
    fun reportsFailureWithBoundedDiagnostics() = runBlocking {
        val failure = assertFailsWith<IllegalStateException> {
            SystemMediaProcessRunner().run(childCommand("fail"))
        }
        assertTrue(failure.message.orEmpty().contains("exited with 7"))
        assertTrue(failure.message.orEmpty().length < 17_000)
    }

    private fun childCommand(vararg args: String): List<String> = listOf(
        Path.of(System.getProperty("java.home"), "bin", "java").toString(),
        "-cp", MediaProcessTestChild::class.java.protectionDomain.codeSource.location.toURI().let(Path::of).toString() +
            java.io.File.pathSeparator + kotlin.Unit::class.java.protectionDomain.codeSource.location.toURI().let(Path::of),
        MediaProcessTestChild::class.java.name,
    ) + args
}

/** A real child JVM, so process cleanup is tested without optional media tools or shell syntax. */
object MediaProcessTestChild {
    @JvmStatic
    fun main(args: Array<String>) {
        if (args[0] == "wait") Files.writeString(Path.of(args[1]), ProcessHandle.current().pid().toString())
        val bytes = ByteArray(8192) { 65 }
        repeat(256) { System.out.write(bytes) }
        System.out.flush()
        if (args[0] == "fail") kotlin.system.exitProcess(7)
        Thread.sleep(60_000)
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopTest/kotlin/io/github/kmpmpv/MpvRenderTargetTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines MpvRenderTargetTest, preservesUnsignedNativeHandleBits.

Read the setup, action and assertions in these cases before implementing their production paths:

  • preservesUnsignedNativeHandleBits
package io.github.kmpmpv

import kotlin.test.Test
import kotlin.test.assertEquals

class MpvRenderTargetTest {
    @Test
    fun preservesUnsignedNativeHandleBits() {
        val handle = Long.MAX_VALUE
        assertEquals(handle, MpvRenderTarget(handle).nativeWindowHandle)
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopTest/kotlin/io/github/kmpmpv/NativeDesktopSmokeTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines NativeDesktopSmokeTest, initializesInstalledLibmpvWhenExplicitlyEnabled, rendersSoftwareFrameWhenExplicitlyEnabled.

Read the setup, action and assertions in these cases before implementing their production paths:

  • initializesInstalledLibmpvWhenExplicitlyEnabled
  • rendersSoftwareFrameWhenExplicitlyEnabled
package io.github.kmpmpv

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import java.nio.file.Files
import java.util.Base64
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue

class NativeDesktopSmokeTest {
    @Test
    fun initializesInstalledLibmpvWhenExplicitlyEnabled() = runTest {
        if (System.getenv("KMP_MPV_RUN_NATIVE_TESTS") != "1") return@runTest

        val player = MpvPlayer.create(
            MpvConfiguration(libraryPath = System.getenv("KMP_MPV_LIBRARY_PATH")),
        )
        try {
            val version = player.getStringProperty("mpv-version")
            assertNotNull(version)
            assertTrue(version.startsWith("mpv ") || version.first().isDigit(), version)
            // -1 is mpv's documented safe detach/own-window sentinel. This
            // exercises the writable `wid` option without requiring a GUI.
            player.attachRenderTarget(MpvRenderTarget(-1))
            player.detachRenderTarget()
            withContext(Dispatchers.Default) { delay(250) }
            assertNull(player.state.value.lastError)
        } finally {
            player.release()
        }
    }

    @Test
    fun rendersSoftwareFrameWhenExplicitlyEnabled() = runTest {
        if (System.getenv("KMP_MPV_RUN_NATIVE_TESTS") != "1") return@runTest

        val player = MpvPlayer.create(
            MpvConfiguration(
                libraryPath = System.getenv("KMP_MPV_LIBRARY_PATH"),
                options = MpvConfiguration.DefaultOptions + mapOf(
                    "vo" to "libmpv",
                    "ao" to "null",
                    "keep-open" to "yes",
                ),
            ),
        )
        val media = Files.createTempFile("kmp-mpv-render-test-", ".mp4")
        try {
            Files.write(media, Base64.getMimeDecoder().decode(TEST_VIDEO_BASE64))
            player.load(media.toString())
            player.play()
            val frame = withContext(Dispatchers.Default) {
                var candidate = player.renderSoftwareFrame(width = 32, height = 18)
                repeat(100) {
                    if (candidate.pixels.any { pixel -> pixel != 0.toByte() }) return@withContext candidate
                    delay(50)
                    candidate = player.renderSoftwareFrame(width = 32, height = 18)
                }
                candidate
            }
            assertEquals(32, frame.width)
            assertEquals(18, frame.height)
            assertTrue(frame.strideBytes >= frame.width * 4)
            assertEquals(frame.strideBytes * frame.height, frame.pixels.size)
            assertTrue(
                frame.pixels.any { it != 0.toByte() },
                "mpv did not render decoded video pixels; " +
                    "state=${player.state.value}, " +
                    "path=${runCatching { player.getStringProperty("path") }.getOrNull()}, " +
                    "videoCodec=${runCatching { player.getStringProperty("video-codec") }.getOrNull()}, " +
                    "paused=${runCatching { player.getBooleanProperty("pause") }.getOrNull()}, " +
                    "idle=${runCatching { player.getBooleanProperty("idle-active") }.getOrNull()}",
            )
            assertNull(player.state.value.lastError)
            player.pause()
            val retainedPixels = frame.pixels.copyOf()
            repeat(120) { index ->
                val width = if (index % 30 == 0) 640 else 1280
                val rendered = player.renderSoftwareFrame(width, 720)
                assertEquals(rendered.strideBytes * 720, rendered.pixels.size)
            }
            assertContentEquals(retainedPixels, frame.pixels)
        } finally {
            player.release()
            Files.deleteIfExists(media)
        }
    }

    private companion object {
        // One second, 32x18 H.264 test pattern. Keeping the opt-in native test
        // self-contained avoids relying on optional mpv protocols or host files.
        const val TEST_VIDEO_BASE64 = "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAANvbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAA+gAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAApl0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+gAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAACAAAAASAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPoAAAQAAABAAAAAAIRbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAAoAAAAMABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABvG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAXxzdGJsAAAAwHN0c2QAAAAAAAAAAQAAALBhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAACAAEgBIAAAASAAAAAAAAAABFUxhdmM2Mi4yOC4xMDIgbGlieDI2NAAAAAAAAAAAAAAAGP//AAAANmF2Y0MBZAAK/+EAGWdkAAqs2Ul+IwEQAAADABAAAAMAoPEiWWABAAZo6+PLIsD9+PgAAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAAKQAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAUAAAgAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAwY3R0cwAAAAAAAAAEAAAAAQAAEAAAAAABAAAgAAAAAAIAAAgAAAAAAQAAEAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAUAAAABAAAAKHN0c3oAAAAAAAAAAAAAAAUAAAR9AAAAXwAAAA0AAAANAAAAKgAAABRzdGNvAAAAAAAAAAEAAAOfAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY2Mi4xMi4xMDIAAAAIZnJlZQAABShtZGF0AAACrQYF//+p3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE2NSByMzIyMiBiMzU2MDVhIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAyNSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTUgc2NlbmVjdXQ9NDAgaW50cmFfcmVmc mVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIzLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAAHIZYiEAX/UV2xH13ejSpNLz+O9yOTlmr1UCb4IUAYGeSEzE07vaUKCRt13HUVI64f5uo6/YF4m31VLhxnB+tpobCrjTjPNehwevadZCbEhAoOsGFRrDH/Js4dI7xa279w/QRN0dK3Ia8hFzunSXWjnLMaUnjaorkgb6/WGbXF9T0/ZMzuxSlgSVYcjF0R39p4EA3HRwKzyyQkluTF3zz00F3FP5tPtSSZihW/Kl1xRQde5IVFN841RlQEFr7kS3pnjuz3GZ+AQ2lV6V3YnukUUxkHYbB2c59jVjFB74Ux/+waeUnCqKOPQYNSJwFShPpSthUwMmTsaS2iGRmianqm5yak49ntzvGV8tZflgPdnKXBTjdvnclqqIw2Z+HRPp/q1CCwYUPdsk7fBAOfRzPwZXO4wGiOA83fTCb4KkHXs6GAYYdLldBkm9Fb3DdebxLiTYIFpSBxFZK2ExA11us67CM9HYI+6PUsrcqLIRa6liVpS3+elM1QAwLfjKANewT0gsPJOTE/GKn8U7i1oTn9LDqUrZMiIcj1Kxb8hNUACyLokSOrUBPaTQOSxycDHAOPUsXl50+1n6Od8FKjVes4lybG6qGWATrPtAAAAW0GaI2xN/8EKUVL1Kat9W+EPX0jldx9dkTL7W/g9O7jqshINqCuvb9lD0p7CdxDwI9zu38OqFLYLXxc47EBslcf7OAJziGtNyTYoL7zdEAW9ajCQ7B6q9mPN9DAAAAAJQZ5BeIr/8+h9AAAACQGeYmpFf+oEuAAAACZBmmRJqEFomUwIr7wQ6DkW6t4iB1/34if7Sz6xLhrdRVcRNFhRwQ=="
    }
}

Write vendor/kmp-mpv/kmp-mpv/src/desktopTest/kotlin/io/github/kmpmpv/NativeMediaProcessingTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines NativeMediaProcessingTest, extractsTimestampedThumbnailsAndUpscalesRealVideo, transcribesSpeechWithARealWhisperModel.

Read the setup, action and assertions in these cases before implementing their production paths:

  • extractsTimestampedThumbnailsAndUpscalesRealVideo
  • transcribesSpeechWithARealWhisperModel
package io.github.kmpmpv

import io.github.kmpmpv.internal.SystemMediaProcessRunner
import kotlinx.coroutines.runBlocking
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class NativeMediaProcessingTest {
    @Test
    fun extractsTimestampedThumbnailsAndUpscalesRealVideo() = runBlocking {
        if (System.getenv("KMP_MPV_RUN_MEDIA_TESTS") != "1") return@runBlocking
        val root = Files.createTempDirectory("kmp-mpv-real-media-")
        try {
            val input = root.resolve("test video.mp4")
            val ffmpeg = System.getenv("KMP_MPV_FFMPEG") ?: "ffmpeg"
            SystemMediaProcessRunner().run(listOf(
                ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", "-f", "lavfi",
                "-i", "color=red:s=64x36:r=5:d=1", "-f", "lavfi", "-i", "color=blue:s=64x36:r=5:d=1",
                "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0,setsar=2", "-c:v", "libx264", input.toString(),
            ))
            val processor = DesktopMpvMediaProcessor(MpvMediaToolsConfiguration(ffmpegExecutable = ffmpeg))
            val red = processor.extractThumbnail(MpvThumbnailRequest(input.toString(), root.resolve("red.png").toString(), 0.2))
            val blue = processor.extractThumbnail(MpvThumbnailRequest(input.toString(), root.resolve("blue.png").toString(), 1.2))
            val redImage = ImageIO.read(java.io.File(red))
            val blueImage = ImageIO.read(java.io.File(blue))
            assertEquals(320, redImage.width)
            assertEquals(90, redImage.height)
            val redPixel = java.awt.Color(redImage.getRGB(100, 45))
            val bluePixel = java.awt.Color(blueImage.getRGB(100, 45))
            assertTrue(redPixel.red > 200 && redPixel.blue < 30)
            assertTrue(bluePixel.blue > 200 && bluePixel.red < 30)
            val scaled = processor.upscaleVideo(MpvUpscaleRequest(input.toString(), root.resolve("upscaled.mp4").toString(), 640, 360))
            val verification = root.resolve("verify.png")
            // Decode without a scale filter to check the actual encoded dimensions.
            SystemMediaProcessRunner().run(listOf(
                ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", "-i", scaled,
                "-frames:v", "1", "-update", "1", verification.toString(),
            ))
            val scaledImage = ImageIO.read(verification.toFile())
            assertEquals(640, scaledImage.width)
            assertEquals(360, scaledImage.height)
            assertTrue(java.awt.Color(scaledImage.getRGB(320, 10)).red < 20)
            assertTrue(java.awt.Color(scaledImage.getRGB(320, 180)).red > 200)
        } finally {
            root.toFile().deleteRecursively()
        }
    }

    @Test
    fun transcribesSpeechWithARealWhisperModel() = runBlocking {
        if (System.getenv("KMP_MPV_RUN_WHISPER_TESTS") != "1") return@runBlocking
        val model = requireNotNull(System.getenv("KMP_MPV_WHISPER_MODEL"))
        val speech = requireNotNull(System.getenv("KMP_MPV_SPEECH_SAMPLE"))
        val root = Files.createTempDirectory("kmp-mpv-real-whisper-")
        try {
            val processor = DesktopMpvMediaProcessor(MpvMediaToolsConfiguration(
                ffmpegExecutable = System.getenv("KMP_MPV_FFMPEG") ?: "ffmpeg",
                whisperExecutable = System.getenv("KMP_MPV_WHISPER") ?: "whisper-cli",
            ))
            val output = processor.generateSubtitles(MpvSubtitleRequest(speech, root.resolve("speech.srt").toString(), model, "en"))
            val subtitles = Files.readString(java.nio.file.Path.of(output))
            assertTrue("-->" in subtitles)
            assertTrue(subtitles.any(Char::isLetter))
        } finally {
            root.toFile().deleteRecursively()
        }
    }
}

Completion record

  • [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
  • [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
  • [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
  • [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #

Gate: fake-engine state/release tests pass, then native desktop smoke and render tests; validate Android Surface recreation and iOS device playback. Independently test processor cancellation/output ownership. Preserve the library license and third-party notices.

Ready to move on?

Check the chapter’s verification gate before marking it complete.

Search chapters, reference and source filenames.