package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.util.PlatformLock /** PiP is installation-owned; its eligibility and requests retain the current player capability. */ internal class PictureInPicturePlaybackOwners( private val publish: (active: Boolean, eligible: Boolean, admitted: () -> Boolean) -> Unit, private val request: (MediaPlayerController?) -> Boolean, ) { private val lock = PlatformLock() private var current: Owner? = null fun create(admitted: () -> Boolean, controller: MediaPlayerController? = null): Owner = Owner(admitted, controller) fun acquire(admitted: () -> Boolean): Owner = create(admitted).also { it.activate() } inner class Owner internal constructor(private val admitted: () -> Boolean, private val controller: MediaPlayerController?) { internal var retired = false fun activate() = lock.withLock { if (retired || current === this) return@withLock current?.retired = true current = this publish(false, false, this::active) } fun active(): Boolean = lock.withLock { !retired && admitted() && current === this } fun update(playing: Boolean) = lock.withLock { if (retired || current !== this) return@withLock val active = active() publish(active, active && playing, this::active) } // Eligibility rules stay platform-specific (browser PiP can be toggled while paused). fun request(): Boolean = lock.withLock { active() && this@PictureInPicturePlaybackOwners.request.invoke(controller) } fun close() = lock.withLock { retired = true if (current === this) { current = null publish(false, false) { false } } } } } internal val PlayerPictureInPictureOwners = PictureInPicturePlaybackOwners( publish = pictureInPicturePlatform::setPlaybackState, request = pictureInPicturePlatform::request, )