Yokan / rebuild
Course 1 8624561

MpvSurfaceView.kt

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

implementation72 lines
1package io.github.kmpmpv23import android.content.Context4import android.util.AttributeSet5import android.view.SurfaceHolder6import android.view.SurfaceView7import kotlinx.coroutines.CoroutineExceptionHandler8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.SupervisorJob11import kotlinx.coroutines.cancel12import kotlinx.coroutines.launch1314/**15 * Minimal Android View adapter. It owns only Surface attachment; the caller owns the player.16 */17public class MpvSurfaceView @JvmOverloads constructor(18    context: Context,19    attrs: AttributeSet? = null,20    defStyleAttr: Int = 0,21) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback {22    private val exceptionHandler = CoroutineExceptionHandler { _, failure -> onError(failure) }23    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate + exceptionHandler)24    private var boundPlayer: MpvPlayer? = null2526    /** Called when a suspend bridge operation fails. */27    public var onError: (Throwable) -> Unit = { throw it }2829    init {30        holder.addCallback(this)31    }3233    public fun bind(player: MpvPlayer) {34        boundPlayer = player35        if (holder.surface.isValid) attach(player, holder)36    }3738    public fun unbind() {39        val player = boundPlayer ?: return40        boundPlayer = null41        scope.launch { player.detachRenderTarget() }42    }4344    /** Remove callbacks and cancel pending Surface operations. Does not release the player. */45    public fun dispose() {46        holder.removeCallback(this)47        boundPlayer = null48        scope.cancel()49    }5051    override fun surfaceCreated(holder: SurfaceHolder) {52        boundPlayer?.let { attach(it, holder) }53    }5455    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {56        val player = boundPlayer ?: return57        if (width > 0 && height > 0) {58            scope.launch { player.updateRenderTargetSize(width, height) }59        }60    }6162    override fun surfaceDestroyed(holder: SurfaceHolder) {63        boundPlayer?.let { player -> scope.launch { player.detachRenderTarget() } }64    }6566    private fun attach(player: MpvPlayer, holder: SurfaceHolder) {67        scope.launch {68            player.attachRenderTarget(MpvRenderTarget(holder.surface))69            if (width > 0 && height > 0) player.updateRenderTargetSize(width, height)70        }71    }72}73

Search chapters, reference and source filenames.