# 16 — Anime player, streams, casting and torrents

Prerequisites: media controller contracts; chapters 17–18 supply real backends. [File workbook](../reference/16-files.md).

[chapter-content-start]: #
## How to write this chapter

Build backend-neutral playback and then connect extraction, owned surfaces, PiP, Cast and torrents. Keep stream identity, time units and playback preparation consistent across native and compatibility backends.

The 125 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 controller/state contracts and profile/surface ownership.
- Step 2: Resolve extractor results, stream headers, subtitles and thumbnails.
- Step 3: Connect player ViewModel, policies, UI and media surfaces.
- Step 4: Implement PiP/external playback as explicit ownership transfers.
- Step 5: Discover receivers and synchronize the Cast session.
- Step 6: Normalize torrent input and expose TorrServer streams.
- Verification: recreate the full test/fixture listings and run the relevant target tasks.
[chapter-content-end]: #


## Step 1: define a backend-neutral controller

Implement MediaPlayerController and state/command policies with a fake player first. The app uses milliseconds, while mpv uses seconds; convert once at the boundary. Separate load preparation, requested autoplay, pending resume seek and observed playing state. Load must complete the reference preparation/resume sequence before play; timeout/failure must unblock the command queue without starting an unintended stream.

Implement ProfilePlayerServices, surface-resource ownership and awaited release. UI surface disposal, request jobs, stream proxy and native player lifetime are connected but distinct. Leaving a composable must not destroy a player still legitimately owned by PiP/minimized playback, nor leave native work alive after final retirement.

[chapter-content-start]: #
### Follow the code

Begin with the controller/state interface and a fake implementation. Loading a stream includes preparation, resume position and requested autoplay; observed playing state arrives later from the backend. Keep milliseconds at the app boundary and conversion inside adapters. Profile/surface wrappers prevent a disposed composition from releasing a player still legitimately owned by minimized/PiP playback, while final retirement joins native/network resources.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResources.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServices.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeatures.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.ios.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.ios.kt`
- `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.jvm.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.wasm.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.kt).

The implementation below defines `MediaPlayerConfiguration`, `from`, `mpvOptions`, `MpvBridgeEvent`, `MpvVideoFit`, `MediaPlayerController`, `load`, `play`, `pause`, `seekTo` and 36 further declarations.

The source describes its contract as:

> Embedded-track subtitle priority (mpv `slang`); external tracks use \[preferredSubtitle\].

Cross-chapter imports used by this file: [`DbAudioChannel`](../chapters/02-domain-and-settings-models.md), [`DbDebandingType`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`AppLogger`](../chapters/24-settings-and-integrations.md), [`redactUrlForLog`](../chapters/24-settings-and-integrations.md), [`SubtitleTrack`](../chapters/18-media-compat-vendor.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.friedcutlet.yokan.database.DbAudioChannel
import eu.friedcutlet.yokan.database.DbDebandingType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.withTimeoutOrNull
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack

data class MediaPlayerConfiguration(
    val useLibass: Boolean = true,
    val useMpvConfig: Boolean = true,
    val mpvConfigDirectory: String = "",
    val hwdecMode: String = "auto",
    val enableHardwareAcceleration: Boolean? = null,
    val enableGpuNext: Boolean = false,
    val debandingType: DbDebandingType = DbDebandingType.None,
    val useYuv420p: Boolean = false,
    val audioPreferredLanguages: String? = null,
    val enableAudioPitchCorrection: Boolean? = null,
    val audioChannels: DbAudioChannel = DbAudioChannel.AutoSafe,
    val volumeBoostCap: Int? = null,
    /** Embedded-track subtitle priority (mpv `slang`); external tracks use [preferredSubtitle]. */
    val subtitleLanguages: List<String> = emptyList(),
) {
    companion object {
        fun from(settings: DbSettings, cacheRoot: String): MediaPlayerConfiguration =
            MediaPlayerConfiguration(
                useLibass = settings.useLibass,
                useMpvConfig = settings.useMpvConfig,
                mpvConfigDirectory = "${cacheRoot.trimEnd('/')}/mpv",
                hwdecMode = settings.hwdecMode,
                enableHardwareAcceleration = settings.enableHardwareAcceleration,
                enableGpuNext = settings.enableGpuNext,
                debandingType = settings.debandingType,
                useYuv420p = settings.useYuv420p,
                audioPreferredLanguages = settings.audioPreferredLanguages,
                enableAudioPitchCorrection = settings.enableAudioPitchCorrection,
                audioChannels = settings.audioChannels,
                volumeBoostCap = settings.volumeBoostCap,
                subtitleLanguages = settings.features.player.subtitleLanguages,
            )
    }

    internal fun mpvOptions(): Map<String, String> = buildMap {
        put("keep-open", "yes")
        put("load-stats-overlay", "yes")
        put("sub-ass", if (useLibass) "yes" else "no")
        put("hwdec", if (enableHardwareAcceleration == false) "no" else hwdecMode.ifBlank { "auto" })
        put("audio-pitch-correction", if (enableAudioPitchCorrection != false) "yes" else "no")
        put("volume-max", ((volumeBoostCap ?: 30).coerceIn(0, 200) + 100).toString())

        val videoFilters = buildList {
            if (useYuv420p) add("format=yuv420p")
            if (debandingType == DbDebandingType.Cpu) add("gradfun=radius=12")
        }
        if (videoFilters.isNotEmpty()) put("vf", videoFilters.joinToString(","))
        if (debandingType == DbDebandingType.Gpu) put("deband", "yes")
        audioPreferredLanguages?.trim()?.takeIf(String::isNotEmpty)?.let { put("alang", it) }
        if (subtitleLanguages.isNotEmpty()) put("slang", subtitleLanguages.joinToString(","))
        if (audioChannels == DbAudioChannel.ReverseStereo) {
            put("af", audioChannels.mpvName)
        } else {
            put("audio-channels", audioChannels.mpvName)
        }
        if (useMpvConfig && mpvConfigDirectory.isNotBlank()) {
            put("config", "yes")
            put("config-dir", mpvConfigDirectory)
        } else {
            put("config", "no")
        }
    }
}

data class MpvBridgeEvent(val name: String, val value: String)

enum class MpvVideoFit(val label: String) {
    Contain("Fit"),
    Cover("Crop"),
    Original("100%"),
}

/**
 * Media engine handle. Each platform's actual factory picks the best
 * backend. libmpv is primary on Android, iOS devices, macOS and Windows. The
 * previous ComposeMediaPlayer path remains as a fallback for iOS simulators
 * and Linux machines where the distribution libmpv package is unavailable.
 */
interface MediaPlayerController {
    val isMpvBackend: Boolean get() = false
    val mpvBridgeEvents: Flow<MpvBridgeEvent> get() = emptyFlow()

    fun load(url: String, headers: Map<String, String> = emptyMap(), initialPositionMs: Long = 0L)
    fun play()
    fun pause()
    fun seekTo(positionMs: Long)
    fun setPlaybackSpeed(speed: Float)
    /** Queues a raw libmpv command. Returns false on the compatibility backend. */
    fun executeMpvCommand(vararg arguments: String): Boolean = false
    /** Await the native command call and join cleanup on expiry. Script/background work has its own lifetime. */
    suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean = false
    fun release()
    /** Await controller work, surface finalizers and native release. */
    suspend fun releaseAndJoin() { release() }

    /** Current position in milliseconds (best-effort; 0 if not started or unsupported). */
    fun currentPositionMs(): Long
    /** Total duration in milliseconds; 0 if unknown. */
    fun durationMs(): Long
    /** True when the engine is currently playing. */
    fun isPlaying(): Boolean

    /** The current stream's playback failure (observable Compose state); null while healthy. */
    val playbackError: String? get() = null

    /** Selects an external subtitle file as the primary track; null disables subtitles. */
    fun selectSubtitleTrack(file: String?, title: String? = null): Boolean =
        if (file.isNullOrBlank()) {
            executeMpvCommand("set", "sid", "no")
        } else {
            executeMpvCommand("sub-add", file, "select", title.orEmpty(), title.orEmpty())
        }

    /** Shows a second external subtitle file alongside the primary one; null hides it. */
    fun selectSecondarySubtitle(file: String?, title: String? = null): Boolean = false

    fun setSecondarySubtitleDelay(milliseconds: Int): Boolean =
        executeMpvCommand("set", "secondary-sub-delay", (milliseconds / 1000.0).toString())

    /** Output volume in percent, 0..100. */
    fun setVolume(percent: Int): Boolean = executeMpvCommand("set", "volume", percent.coerceIn(0, 100).toString())
}


internal enum class PlaybackAction {
    Play,
    Pause,
    Stop,
}

internal data class MediaRequest(
    val id: Long,
    val url: String,
    val originalUrl: String,
    val headers: Map<String, String>,
    val proxied: Boolean,
    val initialPositionMs: Long,
)

internal data class PlaybackCommand(
    val id: Long,
    val action: PlaybackAction,
)

internal data class SeekCommand(
    val id: Long,
    val positionMs: Long,
)
internal class PendingSeekState {
    private var requestedGeneration = 0L
    private var dispatchedGeneration = 0L
    private var positionMs = 0L

    fun request(positionMs: Long) {
        requestedGeneration += 1L
        this.positionMs = positionMs.coerceAtLeast(0L)
    }

    fun pendingPositionMs(): Long? =
        positionMs.takeIf { requestedGeneration > dispatchedGeneration }

    fun markDispatched() {
        dispatchedGeneration = requestedGeneration
    }

    fun reset() {
        dispatchedGeneration = requestedGeneration
        positionMs = 0L
    }
}


internal class InitialPlaybackState {
    var autoplayRequested: Boolean = false
        private set
    var mediaPrepared by mutableStateOf(false)
        private set

    fun beginPreparation() {
        autoplayRequested = false
        mediaPrepared = false
    }

    fun requestPlay() {
        autoplayRequested = true
    }

    fun requestPause() {
        autoplayRequested = false
    }

    fun finishPreparation(): Boolean {
        mediaPrepared = true
        return autoplayRequested
    }

    fun reset() {
        autoplayRequested = false
        mediaPrepared = false
    }
}

internal suspend fun awaitInitialMediaDuration(
    durationMs: () -> Long?,
    isUsable: () -> Boolean,
    hasError: () -> Boolean,
    requireDuration: Boolean,
    readinessGraceMs: Long = 250L,
    timeoutMs: Long = 5_000L,
    pollIntervalMs: Long = 16L,
): Long? = withTimeoutOrNull<Long>(timeoutMs) {
    var resolvedDurationMs = 0L
    var waiting = true
    while (waiting) {
        val knownDurationMs = durationMs()?.takeIf { it > 0L }
        when {
            knownDurationMs != null -> {
                resolvedDurationMs = knownDurationMs
                waiting = false
            }
            hasError() -> waiting = false
            !requireDuration && isUsable() -> {
                delay(readinessGraceMs)
                val settledDurationMs = durationMs()?.takeIf { it > 0L }
                if (settledDurationMs != null) {
                    resolvedDurationMs = settledDurationMs
                    waiting = false
                } else if (hasError() || (!requireDuration && isUsable())) {
                    waiting = false
                }
            }
            else -> delay(pollIntervalMs)
        }
    }
    resolvedDurationMs
}?.takeIf { it > 0L }

internal fun parsePlaybackPositionMs(positionText: String): Long {
    val parts = positionText.trim().split(':')
    if (parts.size !in 2..3) return 0L
    val values = parts.map { it.toLongOrNull() ?: return 0L }
    val hours = if (values.size == 3) values[0] else 0L
    val minutes = values[values.size - 2]
    val seconds = values.last()
    if (hours < 0L || minutes !in 0L..59L || seconds !in 0L..59L) return 0L
    return ((hours * 60L + minutes) * 60L + seconds) * 1000L
}

internal class ComposeMediaPlayerController(
    private val streamProxy: MediaStreamProxy,
) : MediaPlayerController {
    internal val surfaces = PlayerSurfaceResources()
    internal var mediaRequest by mutableStateOf<MediaRequest?>(null)
        private set
    internal var playbackCommand by mutableStateOf<PlaybackCommand?>(null)
        private set
    internal var seekCommand by mutableStateOf<SeekCommand?>(null)
        private set
    internal var speed by mutableStateOf(1.0f)
        private set
    internal var released by mutableStateOf(false)
        private set
    /** compose-mediaplayer draws these with its own cue layer; the secondary one is offset by [secondaryDelayMs]. */
    internal var subtitle by mutableStateOf<SubtitleTrack?>(null)
        private set
    internal var secondarySubtitle by mutableStateOf<SubtitleTrack?>(null)
        private set
    internal var secondaryDelayMs by mutableIntStateOf(0)
        private set
    internal var volume by mutableFloatStateOf(1f)
        private set
    internal var error by mutableStateOf<String?>(null)
    override val playbackError: String? get() = error
    private val initialPlaybackState = InitialPlaybackState()
    internal val autoplayRequested: Boolean get() = initialPlaybackState.autoplayRequested
    internal val mediaPrepared: Boolean get() = initialPlaybackState.mediaPrepared
    internal fun finishMediaPreparation(): Boolean = !released && initialPlaybackState.finishPreparation()
    private val pendingSeekState = PendingSeekState()
    internal fun pendingSeekPositionMs(): Long? = pendingSeekState.pendingPositionMs()
    internal fun markPendingSeekDispatched() = pendingSeekState.markDispatched()

    private var nextCommandId = 0L
    // Observable Compose state so reads in @Composable callers subscribe and
    // recompose as playback progresses. The Surface composable writes to these
    // every time the underlying VideoPlayerState ticks.
    private var cachedPositionMs by mutableLongStateOf(0L)
    private var cachedDurationMs by mutableLongStateOf(0L)
    private var cachedIsPlaying by mutableStateOf(false)
    // kdroidfilter compose-mediaplayer 0.7.11 has two unit bugs in its Linux
    // backend that don't match its KDoc:
    //   • `metadata.duration` is raw GStreamer nanoseconds, not milliseconds
    //   • `sliderPos` ranges 0..1000, not 0..1
    // Android/iOS backends do follow the docs. Auto-detect once per session
    // by sniffing the first sane value we see, then reuse for `seekTo` math.
    internal var durationScaleToMs: Long = 1L
        private set
    internal var sliderScale: Float = 1f
        private set

    override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) {
        if (released) return
        initialPlaybackState.beginPreparation()
        pendingSeekState.reset()
        val playableUrl = if (headers.isNotEmpty()) streamProxy.proxyUrl(url, headers) else url
        val proxied = playableUrl != url
        val startPositionMs = initialPositionMs.coerceAtLeast(0L)
        AppLogger.info(
            "[player] load request url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" +
                if (proxied) " proxy=${redactUrlForLog(playableUrl)}" else "",
        )
        error = null
        subtitle = null
        secondarySubtitle = null
        mediaRequest = MediaRequest(nextId(), playableUrl, url, headers, proxied, startPositionMs)
    }

    override fun selectSubtitleTrack(file: String?, title: String?): Boolean {
        if (released) return false
        subtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) }
        return true
    }

    override fun selectSecondarySubtitle(file: String?, title: String?): Boolean {
        if (released) return false
        secondarySubtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) }
        return true
    }

    override fun setSecondarySubtitleDelay(milliseconds: Int): Boolean {
        if (released) return false
        secondaryDelayMs = milliseconds
        return true
    }

    override fun setVolume(percent: Int): Boolean {
        if (released) return false
        volume = percent.coerceIn(0, 100) / 100f
        return true
    }

    override fun play() {
        if (released) return
        initialPlaybackState.requestPlay()
        AppLogger.info("[player] play request")
        playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Play)
    }

    override fun pause() {
        if (released) return
        initialPlaybackState.requestPause()
        AppLogger.info("[player] pause request")
        playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Pause)
    }

    override fun seekTo(positionMs: Long) {
        if (released) return
        val targetMs = positionMs.coerceAtLeast(0L)
        pendingSeekState.request(targetMs)
        AppLogger.info("[player] seek request positionMs=$targetMs")
        seekCommand = SeekCommand(nextId(), targetMs)
    }

    override fun setPlaybackSpeed(speed: Float) {
        if (released) return
        val nextSpeed = speed.coerceIn(0.25f, 4.0f)
        if (this.speed != nextSpeed) AppLogger.info("[player] speed request speed=$nextSpeed")
        this.speed = nextSpeed
    }

    override fun release() {
        if (released) return
        AppLogger.info("[player] release request")
        released = true
        surfaces.retire()
        initialPlaybackState.reset()
        pendingSeekState.reset()
        mediaRequest = null
        playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Stop)
        cachedPositionMs = 0L
        cachedDurationMs = 0L
        cachedIsPlaying = false
    }

    override suspend fun releaseAndJoin() {
        release()
        surfaces.closeAndJoin()
    }

    override fun currentPositionMs(): Long = cachedPositionMs

    override fun durationMs(): Long = cachedDurationMs

    override fun isPlaying(): Boolean = cachedIsPlaying

    internal fun updateSnapshot(rawDuration: Long, rawSlider: Float, positionText: String, isPlaying: Boolean) {
        if (released) return
        // Anything > 24h has to be the nanosecond bug — no manga episode is
        // a day long. Lock the scale on first detection so it stays stable
        // even if the player briefly reports 0.
        if (durationScaleToMs == 1L && rawDuration > 24L * 3600L * 1000L) {
            durationScaleToMs = 1_000_000L
        }
        val durationMs = if (rawDuration > 0L) rawDuration / durationScaleToMs else 0L

        if (sliderScale == 1f && rawSlider > 1.5f) {
            sliderScale = 1000f
        }
        val normalizedSlider = (rawSlider / sliderScale).coerceIn(0f, 1f)

        cachedDurationMs = durationMs
        cachedPositionMs = if (durationMs > 0L) {
            (normalizedSlider * durationMs).toLong()
        } else {
            parsePlaybackPositionMs(positionText)
        }
        cachedIsPlaying = isPlaying
    }

    private fun nextId(): Long = ++nextCommandId
}

fun createComposeMediaPlayerController(streamProxy: MediaStreamProxy): MediaPlayerController =
    ComposeMediaPlayerController(streamProxy)

/**
 * Platform factory; mpv is primary and ComposeMediaPlayer is the compatibility fallback.
 * [streamProxy] serves streams that need request headers the backend can't send itself.
 */
expect fun createMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
): MediaPlayerController
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResources.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResources.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResources.kt).

The implementation below defines `PlayerSurfaceResources`, `register`, `retire`, `closeAndJoin`, `ensureOpen`, `runOwned`, `launch`, `finalizeOnce`.

The source describes its contract as:

> Controller-owned surface lifetimes, retained until cleanup succeeds.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md), [`PlatformLock`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.coroutines.CoroutineContext

/** Controller-owned surface lifetimes, retained until cleanup succeeds. */
internal class PlayerSurfaceResources {
    private val lock = PlatformLock()
    private val closeMutex = Mutex()
    private var retired = false
    private val resources = mutableSetOf<Resource>()
    fun register(context: CoroutineContext, cleanup: suspend () -> Unit): Resource? = lock.withLock {
        if (retired) return@withLock null
        Resource(context, cleanup).also { resources += it }
    }
    fun retire() {
        val captured = lock.withLock { retired = true; resources.toList() }
        captured.forEach { it.retire() }
    }
    suspend fun closeAndJoin() = withContext(NonCancellable) {
        retire()
        closeMutex.withLock {
            val captured = lock.withLock { resources.toList() }
            captured.forEach { it.closeAndJoin() }
        }
    }
    internal inner class Resource(private val context: CoroutineContext, private val finalize: suspend () -> Unit) {
        private val available = MutableStateFlow(true)
        private val owner = SupervisorJob()
        private val workJob = SupervisorJob(owner)
        private val scope = CoroutineScope(context.minusKey(Job) + workJob)
        private val signal = CompletableDeferred<Unit>()
        private val cleanupMutex = Mutex()
        private var complete = false
        private val cleanup = CoroutineScope(context.minusKey(Job) + owner).async(start = CoroutineStart.UNDISPATCHED) {
            signal.await()
            workJob.join()
            finalizeOnce()
        }
        init { owner.invokeOnCompletion { lock.withLock { resources.remove(this@Resource) } } }
        val isAvailable: Boolean get() = available.value && workJob.isActive
        fun ensureOpen() {
            workJob.ensureActive()
            if (!available.value) throw CancellationException("Player surface is retired.")
        }
        fun retire() {
            available.value = false
            workJob.cancel()
            signal.complete(Unit)
        }
        suspend fun <T> runOwned(action: suspend (() -> Unit) -> T): T {
            val callerContext = currentCoroutineContext()
            val caller = requireNotNull(callerContext[Job])
            caller.ensureActive(); ensureOpen()
            val work = scope.async(callerContext.minusKey(Job)) {
                val job = requireNotNull(currentCoroutineContext()[Job])
                val current = { job.ensureActive(); caller.ensureActive(); ensureOpen() }
                current()
                try { action(current).also { current() } }
                finally { current() }
            }
            return try { work.await() }
            finally {
                withContext(NonCancellable) { work.cancelAndJoin() }
                caller.ensureActive()
            }
        }
        fun launch(action: suspend (() -> Unit) -> Unit): Boolean {
            if (!isAvailable) return false
            scope.launch {
                val job = requireNotNull(currentCoroutineContext()[Job])
                val current = { job.ensureActive(); ensureOpen() }
                try { current(); action(current); current() }
                catch (cancelled: CancellationException) { throw cancelled }
                catch (failure: Throwable) {
                    current()
                    AppLogger.error("[player] surface operation failed: ${failure.message.orEmpty()}")
                }
            }
            return true
        }
        suspend fun closeAndJoin() = withContext(NonCancellable) {
            retire()
            cleanup.join()
            finalizeOnce()
            owner.complete()
            owner.join()
        }
        private suspend fun finalizeOnce() = withContext(context.minusKey(Job) + NonCancellable) {
            cleanupMutex.withLock {
                if (!complete) {
                    finalize()
                    complete = true
                    owner.complete()
                }
            }
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServices.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServices.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServices.kt).

The implementation below defines `ProfilePlayerServices`, `ensureOpen`, `reader`, `closeAndJoin`, `retryControllerCleanup`, `retire`, `proxyUrl`, `stop`, `configuration`, `validate` and 7 further declarations.

The source describes its contract as:

> Player auxiliary requests retain one session's files, AniSkip transport and stream proxy.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`LocalFileService`](../chapters/12-local-library.md), [`PlatformLock`](../chapters/10-navigation-and-design-system.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.media.AniSkipMarker
import eu.friedcutlet.yokan.services.media.AniSkipService
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.util.nowMillis
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.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** Player auxiliary requests retain one session's files, AniSkip transport and stream proxy. */
class ProfilePlayerServices internal constructor(
    val profileId: ProfileId,
    private val files: LocalFileService,
    private val aniSkip: AniSkipService,
    private val proxy: MediaStreamProxy,
    ownerScope: CoroutineScope,
    private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val controllerFactory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController,
    private val isOwnerOpen: () -> Boolean = { true },
) {
    private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])
    private val job = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(ownerScope.coroutineContext + job)
    private val proxyGate = PlatformLock()
    private val cacheRoot = files.cacheRoot.trimEnd('/')
    private val screenshotId = MutableStateFlow(0L)
    private val controllerCleanupLock = Mutex()
    private val failedControllers = mutableSetOf<MediaPlayerController>()
    internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen()
    /** Session-wide so the timer keeps running when the player moves to another episode. */
    val sleepTimer = MutableStateFlow<SleepTimer?>(null)

    private fun ensureOpen() {
        ownerJob.ensureActive()
        job.ensureActive()
        if (!isOwnerOpen()) throw CancellationException("Player services owner is retiring.")
    }

    internal fun reader(): Reader {
        ensureOpen()
        return Reader().also { if (!isAvailable) { it.retire(); ensureOpen() } }
    }

    internal suspend fun closeAndJoin() {
        job.cancel()
        withContext(NonCancellable) {
            job.join()
            retryControllerCleanup()
            // Synchronous proxy registration can come from a native player thread.
            // Drain that gate before the session releases its captured native proxy.
            withContext(fileDispatcher) { proxyGate.withLock { } }
        }
    }

    private suspend fun retryControllerCleanup() = withContext(NonCancellable) {
        controllerCleanupLock.withLock {
            failedControllers.toList().forEach { controller ->
                controller.releaseAndJoin()
                failedControllers.remove(controller)
            }
        }
    }

    internal inner class Reader {
        private val readerJob = SupervisorJob(job)
        private val readerScope = CoroutineScope(scope.coroutineContext + readerJob)
        val isAvailable: Boolean get() = readerJob.isActive && this@ProfilePlayerServices.isAvailable

        fun ensureOpen() { readerJob.ensureActive(); this@ProfilePlayerServices.ensureOpen() }
        fun retire() { readerJob.cancel() }
        suspend fun closeAndJoin() {
            retire()
            withContext(NonCancellable) { readerJob.join(); retryControllerCleanup() }
        }

        /** Retiring a reader's proxy handle never stops the session's shared proxy. */
        val streamProxy: MediaStreamProxy = object : MediaStreamProxy {
            override fun proxyUrl(url: String, headers: Map<String, String>): String = proxyGate.withLock {
                ensureOpen()
                try { proxy.proxyUrl(url, headers) }
                finally { ensureOpen() }
            }
            override fun stop() = retire()
        }

        fun configuration(settings: DbSettings): MediaPlayerConfiguration {
            ensureOpen()
            return MediaPlayerConfiguration.from(settings, cacheRoot).also { ensureOpen() }
        }

        private fun validate(configuration: MediaPlayerConfiguration) {
            ensureOpen()
            require(configuration.mpvConfigDirectory == "$cacheRoot/mpv") { "Player configuration belongs to another file root." }
        }

        private suspend fun <T> runOwned(action: suspend (() -> Unit) -> T): T {
            val caller = requireNotNull(currentCoroutineContext()[Job])
            try {
                return readerScope.runJoined(admit = { ensureOpen() }) { call ->
                    val current = { call.ensureActive(); caller.ensureActive(); ensureOpen() }
                    current()
                    action(current).also { current() }
                }
            } finally {
                caller.ensureActive(); ensureOpen()
            }
        }

        suspend fun prepareConfiguration(configuration: MediaPlayerConfiguration) = runOwned { current ->
            validate(configuration)
            withContext(fileDispatcher) { prepareMpvConfiguration(configuration, files, current) }
        }

        /** The callback owns the controller's active lifetime; expiry joins allocation and native cleanup. */
        suspend fun withController(configuration: MediaPlayerConfiguration, use: suspend (MediaPlayerController) -> Unit) =
            runOwned { current ->
                validate(configuration)
                retryControllerCleanup()
                var created: MediaPlayerController? = null
                try {
                    withContext(fileDispatcher) {
                        current()
                        // Capture inside the dispatcher block: prompt cancellation must not lose a late allocation.
                        created = controllerFactory(configuration, streamProxy)
                    }
                    current()
                    use(checkNotNull(created))
                } finally {
                    created?.let { controller -> withContext(NonCancellable) {
                        try { controller.releaseAndJoin() }
                        catch (failure: Throwable) {
                            controllerCleanupLock.withLock { failedControllers += controller }
                            throw failure
                        }
                    } }
                }
            }

        suspend fun installCustomButtons(
            controller: MediaPlayerController,
            buttons: List<DbCustomButton>,
            configuration: MediaPlayerConfiguration,
        ): Boolean = runOwned { current ->
            validate(configuration)
            withContext(fileDispatcher) { installMpvCustomButtons(controller, buttons, configuration, files, current) }
        }

        suspend fun markers(malId: Long, episode: Int, episodeLengthSeconds: Int): List<AniSkipMarker> =
            runOwned { current ->
                aniSkip.markers(malId, episode, episodeLengthSeconds).also { current() }
            }

        /** Collection belongs to this reader; delivery retains the caller's UI context. */
        suspend fun collectBridgeEvents(controller: MediaPlayerController, onEvent: suspend (MpvBridgeEvent) -> Unit) {
            val deliveryContext = currentCoroutineContext().minusKey(Job)
            runOwned { current ->
                controller.mpvBridgeEvents.collect { event ->
                    current()
                    withContext(deliveryContext) { current(); onEvent(event) }
                }
            }
        }

        /** Publish the path only after native capture completes; expiry joins capture before removing its file. */
        suspend fun requestScreenshot(
            controller: MediaPlayerController,
            mangaName: String,
            chapterName: String,
            includeSubtitles: Boolean = false,
        ): String? =
            runOwned { current -> withContext(fileDispatcher) {
                current()
                val timestamp = nowMillis()
                val fileName = "$mangaName-$chapterName"
                    .replace(Regex("[^A-Za-z0-9._-]+"), "-").trim('-').take(80)
                    .ifBlank { "screenshot" }
                val id = screenshotId.updateAndGet { it + 1 }
                val path = "$cacheRoot/screenshots/$fileName-$timestamp-$id.png"
                var completed = false
                try {
                    files.writeBytes(path, ByteArray(0))
                    current()
                    val captured = controller.takeMpvScreenshotAndJoin(path, includeSubtitles)
                    current()
                    completed = captured
                    if (completed) path else null
                } finally {
                    if (!completed) withContext(NonCancellable) { files.deleteRecursively(path) }
                }
            } }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.kt).

The proxy is a compatibility boundary for header-bearing streams. Its listener/client lifetime is owned and released; it should not become a process-global server shared across retired profiles.

The implementation below defines `MediaStreamProxy`, `proxyUrl`, `stop`, `closeAndJoin`, `NoopMediaStreamProxy`, `createPlatformMediaStreamProxy`.

The source describes its contract as:

> Wait for sockets, workers and upstream call finalizers before releasing the owner.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger


interface MediaStreamProxy {
    fun proxyUrl(url: String, headers: Map<String, String>): String
    fun stop()
    /** Wait for sockets, workers and upstream call finalizers before releasing the owner. */
    suspend fun closeAndJoin() { stop() }
}

object NoopMediaStreamProxy : MediaStreamProxy {
    override fun proxyUrl(url: String, headers: Map<String, String>): String {
        if (headers.isNotEmpty()) {
            AppLogger.warn("[player-proxy] stream headers are required but this platform has no local stream proxy")
        }
        return url
    }

    override fun stop() = Unit
}

expect fun createPlatformMediaStreamProxy(): MediaStreamProxy
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeatures.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeatures.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeatures.kt).

The implementation below defines `MpvMenuAction`, `prepareMpvConfiguration`, `MediaPlayerController.showMpvStats`, `MediaPlayerController.selectMpvShader`, `MediaPlayerController.selectAudioTrack`, `MediaPlayerController.setSubtitleDelay`, `MediaPlayerController.setSubtitleSpeed`, `MediaPlayerController.setAudioDelay`, `MediaPlayerController.setMpvVideoFit`, `MediaPlayerController.takeMpvScreenshotAndJoin` and 26 further declarations.

The source describes its contract as:

> Explicit sync covers screenshot encoding/writing as well as native dispatch.

Cross-chapter imports used by this file: [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`LocalFileService`](../chapters/12-local-library.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

data class MpvMenuAction(val label: String, val command: String)

val MpvStatsActions: List<MpvMenuAction> = listOf(
    MpvMenuAction("Stats toggle", "stats/display-stats-toggle"),
    MpvMenuAction("Stats page 1", "stats/display-page-1"),
    MpvMenuAction("Stats page 2", "stats/display-page-2"),
    MpvMenuAction("Stats page 3", "stats/display-page-3"),
    MpvMenuAction("Stats page 4", "stats/display-page-4"),
    MpvMenuAction("Stats page 5", "stats/display-page-5"),
)

val MpvShaderActions: List<MpvMenuAction> = listOf(
    MpvMenuAction("Anime4K: Mode A (Fast)", "set_anime_a"),
    MpvMenuAction("Anime4K: Mode B (Fast)", "set_anime_b"),
    MpvMenuAction("Anime4K: Mode C (Fast)", "set_anime_c"),
    MpvMenuAction("Anime4K: Mode A+A (Fast)", "set_anime_aa"),
    MpvMenuAction("Anime4K: Mode B+B (Fast)", "set_anime_bb"),
    MpvMenuAction("Anime4K: Mode C+A (Fast)", "set_anime_ca"),
    MpvMenuAction("Anime4K: Mode A (HQ)", "set_anime_hq_a"),
    MpvMenuAction("Anime4K: Mode B (HQ)", "set_anime_hq_b"),
    MpvMenuAction("Anime4K: Mode C (HQ)", "set_anime_hq_c"),
    MpvMenuAction("Anime4K: Mode A+A (HQ)", "set_anime_hq_aa"),
    MpvMenuAction("Anime4K: Mode B+B (HQ)", "set_anime_hq_bb"),
    MpvMenuAction("Anime4K: Mode C+A (HQ)", "set_anime_hq_ca"),
    MpvMenuAction("AMD FSR", "set_fsr"),
    MpvMenuAction("Luma Upscaling", "set_luma"),
    MpvMenuAction("Qualcomm Snapdragon GSR", "set_snapdragon"),
    MpvMenuAction("NVIDIA Image Scaling", "set_nvidia"),
    MpvMenuAction("Clear GLSL shaders", "clear_anime"),
)

fun prepareMpvConfiguration(
    configuration: MediaPlayerConfiguration,
    files: LocalFileService,
    ensureCurrent: () -> Unit = {},
) {
    ensureCurrent()
    if (!configuration.useMpvConfig || configuration.mpvConfigDirectory.isBlank()) return
    val mpvConf = "${configuration.mpvConfigDirectory}/mpv.conf"
    val inputConf = "${configuration.mpvConfigDirectory}/input.conf"
    val hasMpvConf = files.exists(mpvConf)
    ensureCurrent()
    if (!hasMpvConf) files.writeBytes(mpvConf, DefaultMpvConf.encodeToByteArray())
    ensureCurrent()
    val hasInputConf = files.exists(inputConf)
    ensureCurrent()
    if (!hasInputConf) files.writeBytes(inputConf, DefaultMpvInputConf.encodeToByteArray())
    ensureCurrent()
}

fun MediaPlayerController.showMpvStats(binding: String): Boolean =
    executeMpvCommand("script-binding", binding)

fun MediaPlayerController.selectMpvShader(scriptMessage: String): Boolean =
    executeMpvCommand("script-message", scriptMessage)

fun MediaPlayerController.selectAudioTrack(file: String?, title: String? = null): Boolean =
    if (file.isNullOrBlank()) {
        executeMpvCommand("set", "aid", "no")
    } else {
        executeMpvCommand("audio-add", file, "select", title.orEmpty(), title.orEmpty())
    }

fun MediaPlayerController.setSubtitleDelay(milliseconds: Int): Boolean =
    executeMpvCommand("set", "sub-delay", (milliseconds / 1000.0).toString())

fun MediaPlayerController.setSubtitleSpeed(speed: Double): Boolean =
    executeMpvCommand("set", "sub-speed", speed.coerceIn(0.1, 10.0).toString())

fun MediaPlayerController.setAudioDelay(milliseconds: Int): Boolean =
    executeMpvCommand("set", "audio-delay", (milliseconds / 1000.0).toString())

fun MediaPlayerController.setMpvVideoFit(fit: MpvVideoFit): Boolean = when (fit) {
    MpvVideoFit.Contain -> {
        executeMpvCommand("set", "video-unscaled", "no") &&
            executeMpvCommand("set", "panscan", "0")
    }
    MpvVideoFit.Cover -> {
        executeMpvCommand("set", "video-unscaled", "no") &&
            executeMpvCommand("set", "panscan", "1")
    }
    MpvVideoFit.Original -> {
        executeMpvCommand("set", "panscan", "0") &&
            executeMpvCommand("set", "video-unscaled", "yes")
    }
}

/** Explicit sync covers screenshot encoding/writing as well as native dispatch. */
suspend fun MediaPlayerController.takeMpvScreenshotAndJoin(path: String, includeSubtitles: Boolean = false): Boolean =
    executeMpvCommandAndJoin("sync", "screenshot-to-file", path, if (includeSubtitles) "subtitles" else "video")

fun installMpvCustomButtons(
    controller: MediaPlayerController,
    buttons: List<DbCustomButton>,
    configuration: MediaPlayerConfiguration,
    files: LocalFileService,
    ensureCurrent: () -> Unit = {},
): Boolean {
    ensureCurrent()
    if (!controller.isMpvBackend || !configuration.useMpvConfig) return false
    val chapterScriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_chapter_titles.js"
    files.writeBytes(chapterScriptPath, ChapterTitlesJavaScript.encodeToByteArray())
    ensureCurrent()
    val chapterScriptLoaded = controller.executeMpvCommand("load-script", chapterScriptPath)
    ensureCurrent()
    if (buttons.isEmpty()) return chapterScriptLoaded
    val primary = buttons.firstOrNull(DbCustomButton::isFavourite) ?: buttons.first()
    val scriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_custom_buttons.js"
    files.writeBytes(scriptPath, buildMpvCustomButtonsScript(buttons, primary.id).encodeToByteArray())
    ensureCurrent()
    val customScriptLoaded = controller.executeMpvCommand("load-script", scriptPath)
    ensureCurrent()
    return customScriptLoaded && chapterScriptLoaded
}

internal fun buildMpvCustomButtonsScript(buttons: List<DbCustomButton>, primaryId: Long): String = buildString {
    appendLine(AniyomiJavaScriptBridge)
    buttons.forEach { button ->
        appendLine(button.startupCode(primaryId))
        appendLine("function button_${button.id}() {")
        appendLine(button.pressCode(primaryId).prependIndent("  "))
        appendLine("}")
        appendLine("mp.register_script_message('call_button_${button.id}', button_${button.id});")
        appendLine("function button_${button.id}_long() {")
        appendLine(button.longPressCode(primaryId).prependIndent("  "))
        appendLine("}")
        appendLine("mp.register_script_message('call_button_${button.id}_long', button_${button.id}_long);")
    }
}

val DefaultMpvConf: String = """
# Generated mpv defaults. Lines starting with # are ignored.
profile=gpu-hq
keep-open=yes
load-stats-overlay=yes
""".trimIndent()

val DefaultMpvInputConf: String = """
# Generated input bindings.
SPACE cycle pause
RIGHT seek 10
LEFT seek -10
""".trimIndent()

private val AniyomiJavaScriptBridge = """
var aniyomi = {};
aniyomi.show_text = function(text) { mp.set_property('user-data/aniyomi/show_text', String(text)); };
aniyomi.hide_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'hide'); };
aniyomi.show_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'show'); };
aniyomi.toggle_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'toggle'); };
aniyomi.show_subtitle_settings = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_settings'); };
aniyomi.show_subtitle_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_delay'); };
aniyomi.show_audio_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'audio_delay'); };
aniyomi.show_video_filters = function() { mp.set_property('user-data/aniyomi/show_panel', 'video_filters'); };
aniyomi.show_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'show'); };
aniyomi.hide_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'hide'); };
aniyomi.toggle_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'toggle'); };
aniyomi.set_button_title = function(text) { mp.set_property('user-data/aniyomi/set_button_title', String(text)); };
aniyomi.reset_button_title = function() { mp.set_property('user-data/aniyomi/reset_button_title', 'unused'); };
aniyomi.hide_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'hide'); };
aniyomi.show_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'show'); };
aniyomi.toggle_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'toggle'); };
aniyomi.previous_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'p'); };
aniyomi.next_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'n'); };
aniyomi.pause = function() { mp.set_property('user-data/aniyomi/pause', 'pause'); };
aniyomi.unpause = function() { mp.set_property('user-data/aniyomi/pause', 'unpause'); };
aniyomi.pauseunpause = function() { mp.set_property('user-data/aniyomi/pause', 'pauseunpause'); };
aniyomi.seek_by = function(value) { mp.set_property('user-data/aniyomi/seek_by', String(value)); };
aniyomi.seek_to = function(value) { mp.set_property('user-data/aniyomi/seek_to', String(value)); };
aniyomi.seek_by_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_by_with_text', value + '|' + text); };
aniyomi.seek_to_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_to_with_text', value + '|' + text); };
aniyomi.int_picker = function(title, nameFormat, start, stop, step, property) {
  mp.set_property('user-data/aniyomi/launch_int_picker', [title, nameFormat, start, stop, step, property].join('|'));
};
aniyomi.left_seek_by = function(value) { aniyomi.seek_by(-value); };
aniyomi.right_seek_by = function(value) { aniyomi.seek_by(value); };
""".trimIndent()

private val ChapterTitlesJavaScript = """
function publishChapterTitles() {
  var count = mp.get_property_number('chapter-list/count', 0);
  var chapters = [];
  for (var index = 0; index < count; index++) {
    chapters.push({
      title: mp.get_property_native('chapter-list/' + index + '/title') || ('Chapter ' + (index + 1)),
      timestamp: mp.get_property_native('chapter-list/' + index + '/time') || 0
    });
  }
  mp.set_property('user-data/mangayomi/chapter_titles', mp.utils.format_json(chapters));
}

function publishCurrentChapter(name, value) {
  if (value !== undefined && value !== null) {
    mp.set_property_number('user-data/mangayomi/current_chapter', Math.max(value, 0));
  }
}

mp.register_event('file-loaded', publishChapterTitles);
mp.observe_property('chapter', 'number', publishCurrentChapter);
""".trimIndent()

/** Player sheet pages the mpv scripts can open. */
internal enum class MpvPanel { Video, Subtitles, Audio }

/** A typed request from the in-player mpv scripts, decoded from an [MpvBridgeEvent]. */
internal sealed interface PlayerBridgeCommand {
    data class ShowText(val text: String) : PlayerBridgeCommand
    /** [visible] null toggles the chrome. */
    data class SetUiVisible(val visible: Boolean?) : PlayerBridgeCommand
    data class ShowPanel(val panel: MpvPanel) : PlayerBridgeCommand
    data class SetButtonTitle(val title: String) : PlayerBridgeCommand
    data object ResetButtonTitle : PlayerBridgeCommand
    /** [visible] null toggles the custom button. */
    data class SetButtonVisible(val visible: Boolean?) : PlayerBridgeCommand
    data class SwitchEpisode(val offset: Int) : PlayerBridgeCommand
    /** [paused] null toggles playback. */
    data class SetPaused(val paused: Boolean?) : PlayerBridgeCommand
    /** Seeks by [seconds] from the current position when [relative], otherwise to [seconds]; [text] is shown alongside. */
    data class Seek(val seconds: Long, val relative: Boolean, val text: String? = null) : PlayerBridgeCommand
    data class LaunchIntPicker(val request: MpvIntPickerRequest) : PlayerBridgeCommand
    data class ChapterTitles(val marks: List<MpvChapterMark>) : PlayerBridgeCommand
    data class CurrentChapter(val index: Int) : PlayerBridgeCommand
    data class SelectedShader(val label: String) : PlayerBridgeCommand
}

/** Every bridge property the scripts write, as `user-data/<key>`; the mpv backend observes exactly these. */
private enum class MpvBridgeName(val key: String) {
    ShowText("aniyomi/show_text"),
    ToggleUi("aniyomi/toggle_ui"),
    ShowPanel("aniyomi/show_panel"),
    SoftwareKeyboard("aniyomi/software_keyboard"),
    SetButtonTitle("aniyomi/set_button_title"),
    ResetButtonTitle("aniyomi/reset_button_title"),
    ToggleButton("aniyomi/toggle_button"),
    SwitchEpisode("aniyomi/switch_episode"),
    Pause("aniyomi/pause"),
    SeekBy("aniyomi/seek_by"),
    SeekTo("aniyomi/seek_to"),
    SeekByWithText("aniyomi/seek_by_with_text"),
    SeekToWithText("aniyomi/seek_to_with_text"),
    LaunchIntPicker("aniyomi/launch_int_picker"),
    ChapterTitles("mangayomi/chapter_titles"),
    CurrentChapter("mangayomi/current_chapter"),
    SelectedShader("mangayomi/selected_shader"),
}

private val MpvBridgeNamesByKey = MpvBridgeName.entries.associateBy(MpvBridgeName::key)

internal val MpvBridgePropertyNames: Set<String> = MpvBridgeName.entries.mapTo(HashSet()) { "user-data/${it.key}" }

/** Null for unknown names, malformed values, and requests the player has no surface for (software keyboard). */
internal fun MpvBridgeEvent.toCommand(): PlayerBridgeCommand? = when (MpvBridgeNamesByKey[name] ?: return null) {
    MpvBridgeName.ShowText -> PlayerBridgeCommand.ShowText(value)
    MpvBridgeName.ToggleUi -> PlayerBridgeCommand.SetUiVisible(parseVisibility(value))
    MpvBridgeName.ShowPanel -> PlayerBridgeCommand.ShowPanel(
        when (value) {
            "subtitle_settings", "subtitle_delay" -> MpvPanel.Subtitles
            "audio_delay" -> MpvPanel.Audio
            else -> MpvPanel.Video
        },
    )
    MpvBridgeName.SoftwareKeyboard -> null
    MpvBridgeName.SetButtonTitle -> PlayerBridgeCommand.SetButtonTitle(value)
    MpvBridgeName.ResetButtonTitle -> PlayerBridgeCommand.ResetButtonTitle
    MpvBridgeName.ToggleButton -> PlayerBridgeCommand.SetButtonVisible(parseVisibility(value))
    MpvBridgeName.SwitchEpisode -> PlayerBridgeCommand.SwitchEpisode(if (value == "p") -1 else 1)
    MpvBridgeName.Pause -> PlayerBridgeCommand.SetPaused(
        when (value) {
            "pause" -> true
            "unpause" -> false
            else -> null
        },
    )
    MpvBridgeName.SeekBy -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = true) }
    MpvBridgeName.SeekTo -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = false) }
    MpvBridgeName.SeekByWithText -> parseSeekWithText(value, relative = true)
    MpvBridgeName.SeekToWithText -> parseSeekWithText(value, relative = false)
    MpvBridgeName.LaunchIntPicker -> MpvIntPickerRequest.parse(value)?.let(PlayerBridgeCommand::LaunchIntPicker)
    MpvBridgeName.ChapterTitles -> PlayerBridgeCommand.ChapterTitles(MpvChapterMark.parseList(value))
    MpvBridgeName.CurrentChapter -> PlayerBridgeCommand.CurrentChapter(value.toDoubleOrNull()?.toInt()?.coerceAtLeast(0) ?: 0)
    MpvBridgeName.SelectedShader -> PlayerBridgeCommand.SelectedShader(value)
}

private fun parseVisibility(value: String): Boolean? = when (value) {
    "show" -> true
    "hide" -> false
    else -> null
}

private fun parseSeconds(value: String): Long? = value.trim().trim('"').toDoubleOrNull()?.toLong()

/** `seconds|text`: an unparsable position still shows the text. */
private fun parseSeekWithText(value: String, relative: Boolean): PlayerBridgeCommand? {
    val pieces = value.split('|', limit = 2)
    val text = pieces.getOrNull(1)
    val seconds = parseSeconds(pieces.first()) ?: return text?.let(PlayerBridgeCommand::ShowText)
    return PlayerBridgeCommand.Seek(seconds, relative, text)
}

/** `title|valueFormat|start|stop|step|property`, as written by `aniyomi.int_picker`. */
internal data class MpvIntPickerRequest(
    val title: String,
    val valueFormat: String,
    val start: Int,
    val stop: Int,
    val step: Int,
    val property: String,
) {
    companion object {
        fun parse(value: String): MpvIntPickerRequest? {
            val pieces = value.split('|')
            if (pieces.size < 6) return null
            val start = pieces[2].toIntOrNull() ?: return null
            val stop = pieces[3].toIntOrNull() ?: return null
            val step = pieces[4].toIntOrNull()?.takeIf { it > 0 } ?: return null
            if (stop <= start || pieces[5].isBlank()) return null
            return MpvIntPickerRequest(
                title = pieces[0],
                valueFormat = pieces[1],
                start = start,
                stop = stop,
                step = step,
                property = pieces[5],
            )
        }
    }
}

internal data class MpvChapterMark(val title: String, val positionMs: Long) {
    companion object {
        /** The JSON array published by the chapter-titles script; malformed input yields no marks. */
        fun parseList(value: String): List<MpvChapterMark> = runCatching {
            Json.parseToJsonElement(value).jsonArray.mapNotNull { element ->
                val objectValue = element.jsonObject
                val timestampSeconds = objectValue["timestamp"]?.jsonPrimitive?.doubleOrNull
                    ?: return@mapNotNull null
                MpvChapterMark(
                    title = objectValue["title"]?.jsonPrimitive?.contentOrNull.orEmpty().ifBlank { "Chapter" },
                    positionMs = (timestampSeconds * 1000.0).toLong().coerceAtLeast(0L),
                )
            }
        }.getOrDefault(emptyList())
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.android.kt).

The implementation below defines `createMediaPlayerController`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger

actual fun createMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
): MediaPlayerController =
    runCatching {
        createMpvMediaPlayerController(
            configuration,
            streamProxy,
            mapOf("vo" to if (configuration.enableGpuNext) "gpu-next" else "gpu"),
        )
    }
        .onFailure { AppLogger.warn("[player] Android mpv unavailable: ${it.message.orEmpty()}") }
        .getOrElse { createComposeMediaPlayerController(streamProxy) }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.desktop.kt).

The implementation below defines `createMediaPlayerController`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger

actual fun createMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
): MediaPlayerController =
    runCatching {
        // A Compose-native software surface avoids heavyweight AWT Canvas
        // z-order/input problems. mpv requires this VO before initialization.
        createMpvMediaPlayerController(configuration, streamProxy, mapOf("vo" to "libmpv"))
    }
        .onFailure { AppLogger.warn("[player] desktop mpv unavailable: ${it.message.orEmpty()}") }
        .getOrElse { createComposeMediaPlayerController(streamProxy) }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.ios.kt).

The implementation below defines `createMediaPlayerController`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger
import platform.Foundation.NSBundle

actual fun createMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
): MediaPlayerController =
    runCatching {
        val mpvPath = NSBundle.mainBundle.privateFrameworksPath?.let { "$it/Mpv.framework/Mpv" }
        createMpvMediaPlayerController(configuration, streamProxy, mapOf("vo" to "libmpv"), mpvPath)
    }
        .onFailure { AppLogger.warn("[player] iOS mpv unavailable; using AVPlayer: ${it.message.orEmpty()}") }
        .getOrElse { createComposeMediaPlayerController(streamProxy) }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.ios.kt).

The implementation below defines `createPlatformMediaStreamProxy`.

```kotlin
package eu.friedcutlet.yokan.services.media.player

actual fun createPlatformMediaStreamProxy(): MediaStreamProxy = NoopMediaStreamProxy
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.jvm.kt
### Write `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.jvm.kt`

Create this path in your reconstruction project. Source set: **jvmCommonMain**. [Exact file download](../reference/source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.jvm.kt).

The implementation below defines `createPlatformMediaStreamProxy`.

```kotlin
package eu.friedcutlet.yokan.services.media.player

actual fun createPlatformMediaStreamProxy(): MediaStreamProxy = JvmMediaStreamProxy()
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.wasm.kt).

The implementation below defines `createMediaPlayerController`.

The source describes its contract as:

> libmpv has no browser build; the ComposeMediaPlayer HTML5 backend is primary.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/** libmpv has no browser build; the ComposeMediaPlayer HTML5 backend is primary. */
actual fun createMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
): MediaPlayerController = createComposeMediaPlayerController(streamProxy)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaStreamProxy.wasm.kt).

The implementation below defines `createPlatformMediaStreamProxy`.

```kotlin
package eu.friedcutlet.yokan.services.media.player

actual fun createPlatformMediaStreamProxy(): MediaStreamProxy = NoopMediaStreamProxy
```
[chapter-file-end]: #

### Check your understanding

Delay backend preparation, request a resume seek and then cancel load. Verify the command queue unblocks and never starts unintended autoplay.
[chapter-content-end]: #


## Step 2: resolve streams

PlayerViewModel obtains remote/local episode video candidates, selected quality, subtitles and headers through ProfileReaderContent. Implement extractor interface and the individual host adapters in the workbook (StreamTape, Voe, StreamWish, Filemoon, GogoCdn, Dood, Mp4Upload, MyStream, Mytv, Okru, Sendvid, Sibnet, Streamlare, VidBom, YourUpload, QuarkUc and Kwik). Recreate shared JS unpacking and HLS master parsing; each site's edge cases belong in fixtures.

Preserve Referer/cookies and source headers across redirects, extractor calls, subtitles and playback. Use MediaStreamProxy where the compatibility player cannot apply headers directly. The proxy must be owned, bounded and closed with the session. External sites can change after this snapshot; live compatibility is a separate acceptance check.

[chapter-content-start]: #
### Follow the code

Each extractor maps one host's response into ordinary video candidates; common JS unpacking and HLS parsing supply reusable pieces. Preserve Referer/cookies/headers through extractor calls, subtitles and playback. Thumbnail VTT cues identify a time interval plus an optional sprite rectangle; lookup chooses a cue covering the requested time, not simply the nearest image. Cancel resolution/prefetch from an old episode or stream.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AnimeExtractorService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/JsPacker.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8Master.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/SubtitleService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AniSkipService.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/DoodExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/FilemoonExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/GogoCdnExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/Mp4UploadExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MyStreamExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MytvExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/OkruExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/QuarkUcExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SendvidExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SibnetExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamTapeExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamWishExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamlareExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VidBomExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VoeExtractor.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/YourUploadExtractor.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.ios.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AnimeExtractorService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AnimeExtractorService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AnimeExtractorService.kt).

The implementation below defines `AnimeExtractorService`, `extract`, `ExtractorResult`, `AnimeExtractorService.extractVideos`.

The source describes its contract as:

> Runs \[block\] for \[AnimeExtractorService.extract\]: failures are logged and yield no videos, cancellation propagates. \[headers\] are returned either way.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`ExtensionLogger`](../chapters/06-extension-runtimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionLogger

interface AnimeExtractorService {
    val hostName: String
    suspend fun extract(url: String, headers: Map<String, String> = emptyMap()): ExtractorResult
}

data class ExtractorResult(
    val videos: List<DbVideo>,
    val headers: Map<String, String> = emptyMap(),
)

/**
 * Runs [block] for [AnimeExtractorService.extract]: failures are logged and
 * yield no videos, cancellation propagates. [headers] are returned either way.
 */
internal inline fun AnimeExtractorService.extractVideos(
    headers: Map<String, String>,
    block: () -> List<DbVideo>,
): ExtractorResult {
    val videos = catchingNonCancellation(block)
        .onFailure { ExtensionLogger.error(hostName, "extract", it) }
        .getOrDefault(emptyList())
    return ExtractorResult(videos = videos, headers = headers)
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/JsPacker.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/JsPacker.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/JsPacker.kt).

The implementation below defines `JsPacker`, `unpack`, `unbase`, `String.unescape`.

The source describes its contract as:

> Kotlin port of Dean Edwards' `p,a,c,k,e,d` JavaScript unpacker — the same algorithm Filemoon and StreamWish payloads ship through. The packer wraps the original script in a self-executing function whose tail looks like `}('payload', radix, count, 'sym1|sym2|…'.split('|'), 0, {}))`. We slice those four arguments out, then substitute each `\b\w+\b` token in the payload with `symbolTable\[unbase(token, radix)\]`. Returns the unpacked source on success, or null when the input is not in the packed shape we recognise.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

/**
 * Kotlin port of Dean Edwards' `p,a,c,k,e,d` JavaScript unpacker — the same
 * algorithm Filemoon and StreamWish payloads ship through.
 *
 * The packer wraps the original script in a self-executing function whose tail
 * looks like `}('payload', radix, count, 'sym1|sym2|…'.split('|'), 0, {}))`.
 * We slice those four arguments out, then substitute each `\b\w+\b` token in
 * the payload with `symbolTable[unbase(token, radix)]`.
 *
 * Returns the unpacked source on success, or null when the input is not in
 * the packed shape we recognise.
 */
internal object JsPacker {

    private val HEAD_REGEX = Regex(
        """\}\s*\(\s*'([\s\S]+?)'\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*'([\s\S]+?)'\.split\('\|'\)\s*,\s*0\s*,\s*\{\}\s*\)\s*\)""",
    )

    private val TOKEN_REGEX = Regex("""\b\w+\b""")

    fun unpack(source: String): String? {
        val match = HEAD_REGEX.find(source) ?: return null
        val payload = match.groupValues[1].unescape()
        val radix = match.groupValues[2].toIntOrNull() ?: return null
        // Group 3 is the symbol count; it may disagree with `symbols.size` (some
        // payloads still unpack correctly) and `getOrNull` below keeps indexing in bounds.
        match.groupValues[3].toIntOrNull() ?: return null
        val symbols = match.groupValues[4].split('|')
        return TOKEN_REGEX.replace(payload) { mr ->
            val token = mr.value
            val index = unbase(token, radix) ?: return@replace token
            val sym = symbols.getOrNull(index)
            // Empty string in the table means "leave the original token in".
            if (sym.isNullOrEmpty()) token else sym
        }
    }

    /** Inverse of Dean Edwards' radix-N alphabet used by the packer. */
    private fun unbase(token: String, radix: Int): Int? {
        var result = 0
        for (ch in token) {
            val digit = when {
                ch in '0'..'9' -> ch - '0'
                ch in 'a'..'z' -> ch - 'a' + 10
                ch in 'A'..'Z' -> ch - 'A' + 36
                else -> return null
            }
            if (digit >= radix) return null
            result = result * radix + digit
        }
        return result
    }

    /**
     * Undo the standard escape characters the packer uses inside its first
     * argument: `\'` `\\` `\n` `\t` `\r`. We don't try to be a full JS string
     * literal parser — the packer only ever emits these escapes.
     */
    private fun String.unescape(): String {
        val sb = StringBuilder(length)
        var i = 0
        while (i < length) {
            val ch = this[i]
            if (ch == '\\' && i + 1 < length) {
                when (val next = this[i + 1]) {
                    '\\' -> sb.append('\\')
                    '\'' -> sb.append('\'')
                    '"' -> sb.append('"')
                    'n' -> sb.append('\n')
                    't' -> sb.append('\t')
                    'r' -> sb.append('\r')
                    '/' -> sb.append('/')
                    else -> {
                        sb.append('\\')
                        sb.append(next)
                    }
                }
                i += 2
            } else {
                sb.append(ch)
                i++
            }
        }
        return sb.toString()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8Master.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8Master.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8Master.kt).

The implementation below defines `hostOf`, `HttpService.m3u8Videos`, `parseM3u8MasterToVideos`.

The source describes its contract as:

> Captures the body of every `\<script\>` tag in an HTML page.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.parseUrl

/** Captures the body of every `<script>` tag in an HTML page. */
internal val ScriptTagRegex = Regex("""<script[^>]*>([\s\S]*?)</script>""", RegexOption.IGNORE_CASE)

/** Host of an absolute http(s) [url], or null when it isn't one. */
internal fun hostOf(url: String): String? =
    if (url.startsWith("http", ignoreCase = true)) parseUrl(url)?.host?.takeIf { it.isNotEmpty() } else null

/**
 * Fetches the HLS master at [masterUrl] (with [requestHeaders]) and returns one
 * [DbVideo] per variant via [parseM3u8MasterToVideos]. Returns an empty list on
 * a non-2xx response. When the playlist has no variants and [fallbackQuality]
 * is set, the master URL itself is returned as the only video.
 */
internal suspend fun HttpService.m3u8Videos(
    masterUrl: String,
    labelPrefix: String = "",
    labelSuffix: String = "",
    headers: Map<String, String>? = null,
    requestHeaders: Map<String, String> = emptyMap(),
    subtitles: List<DbVideoTrack> = emptyList(),
    fallbackQuality: String? = null,
): List<DbVideo> {
    val master = request(HttpRequest(masterUrl, headers = requestHeaders))
    if (master.statusCode !in 200..299) return emptyList()
    val variants = parseM3u8MasterToVideos(
        masterUrl = masterUrl,
        masterPlaylist = master.body,
        labelPrefix = labelPrefix,
        labelSuffix = labelSuffix,
        headers = headers,
        subtitles = subtitles,
    )
    if (variants.isNotEmpty() || fallbackQuality == null) return variants
    return listOf(
        DbVideo(
            url = masterUrl,
            quality = fallbackQuality,
            originalUrl = masterUrl,
            headers = headers,
            subtitles = subtitles,
        ),
    )
}

/**
 * Shared helper that slices a HLS master playlist into one [DbVideo] per
 * `#EXT-X-STREAM-INF` variant. Reused by Voe, StreamWish, Filemoon and
 * GoGoCDN — they all dump the same master shape.
 *
 * - [labelPrefix] is glued onto each variant (e.g. `"Voe: "`).
 * - [labelSuffix] is appended after the resolution (e.g. trailing language hints).
 * - [headers] / [subtitles] / [audios] are passed through to each emitted variant.
 * - When a variant URL is relative we resolve it against [resolveBase], which
 *   should be the master URL minus the trailing filename (i.e. the directory it
 *   lives in).
 *
 * If the master playlist has no `#EXT-X-STREAM-INF` markers (a single rendition
 * playlist), the function returns an empty list — see [m3u8Videos]' `fallbackQuality`.
 */
internal fun parseM3u8MasterToVideos(
    masterUrl: String,
    masterPlaylist: String,
    labelPrefix: String = "",
    labelSuffix: String = "",
    headers: Map<String, String>? = null,
    subtitles: List<DbVideoTrack> = emptyList(),
    audios: List<DbVideoTrack> = emptyList(),
    resolveBase: String = masterUrl.substringBeforeLast('/') + "/",
): List<DbVideo> {
    val separator = "#EXT-X-STREAM-INF"
    if (!masterPlaylist.contains(separator)) return emptyList()
    // `substringAfter` first to drop everything before the first marker, then
    // split on the separator so each chunk corresponds to one variant.
    return masterPlaylist
        .substringAfter(separator)
        .split(separator)
        .mapNotNull { chunk ->
            val resolutionPart = chunk.substringAfter("RESOLUTION=", missingDelimiterValue = "")
            // resolution looks like "1280x720" → take the height.
            val resolution = resolutionPart.substringAfter("x", missingDelimiterValue = "")
                .substringBefore(",")
                .substringBefore("\n")
                .trim()
            // The first non-empty line after the meta line is the variant URL.
            val urlLine = chunk
                .substringAfter("\n", missingDelimiterValue = "")
                .lineSequence()
                .map { it.trim() }
                .firstOrNull { it.isNotEmpty() && !it.startsWith("#") }
                ?: return@mapNotNull null
            val variantUrl = if (urlLine.startsWith("http", ignoreCase = true)) urlLine
            else resolveBase + urlLine.removePrefix("/")
            val quality = buildString {
                append(labelPrefix)
                if (resolution.isNotEmpty()) {
                    if (isNotEmpty()) append(' ')
                    append(resolution).append('p')
                }
                if (labelSuffix.isNotEmpty()) {
                    if (isNotEmpty()) append(' ')
                    append(labelSuffix)
                }
            }.ifBlank { "Stream" }
            DbVideo(
                url = variantUrl,
                quality = quality,
                originalUrl = variantUrl,
                headers = headers,
                subtitles = subtitles,
                audios = audios,
            )
        }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/SubtitleService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/SubtitleService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/SubtitleService.kt).

The implementation below defines `SubtitleSearchResult`, `SubtitleService`, `search`.

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

data class SubtitleSearchResult(
    val language: String,
    val title: String,
    val url: String,
)

class SubtitleService(
    private val http: HttpService,
) {
    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    suspend fun search(title: String, language: String): List<SubtitleSearchResult> {
        if (title.isBlank()) return emptyList()
        val encoded = title.replace(" ", "+")
        val langParam = language.takeIf { it.isNotBlank() }?.let { "&language=$it" } ?: ""
        val response = catchingNonCancellation {
            http.request(HttpRequest("https://subs.wyzie.ru/search?q=$encoded$langParam", headers = mapOf("Accept" to "application/json")))
        }.getOrNull() ?: return emptyList()
        if (response.statusCode !in 200..299) return emptyList()
        val parsed = runCatching { json.parseToJsonElement(response.body) }.getOrNull() ?: return emptyList()
        val items = (parsed as? JsonArray)
            ?: ((parsed as? JsonObject)?.get("results") as? JsonArray)
            ?: ((parsed as? JsonObject)?.get("subtitles") as? JsonArray)
            ?: return emptyList()
        return items.mapNotNull { item ->
            val obj = item as? JsonObject ?: return@mapNotNull null
            val display = (obj["display"] as? JsonPrimitive)?.contentOrNull
                ?: (obj["title"] as? JsonPrimitive)?.contentOrNull
                ?: (obj["filename"] as? JsonPrimitive)?.contentOrNull
                ?: title
            val url = (obj["url"] as? JsonPrimitive)?.contentOrNull
                ?: (obj["link"] as? JsonPrimitive)?.contentOrNull
                ?: return@mapNotNull null
            val lang = (obj["language"] as? JsonPrimitive)?.contentOrNull
                ?: (obj["lang"] as? JsonPrimitive)?.contentOrNull
                ?: language.ifBlank { "auto" }
            SubtitleSearchResult(language = lang, title = display, url = url)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AniSkipService.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AniSkipService.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/AniSkipService.kt).

The implementation below defines `AniSkipMarker`, `AniSkipService`, `markers`.

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull

data class AniSkipMarker(
    val type: String,
    val startSeconds: Double,
    val endSeconds: Double,
    val episodeLengthSeconds: Double,
)

class AniSkipService(
    private val http: HttpService,
) {
    private val base = "https://api.aniskip.com/v2"
    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    suspend fun markers(malId: Long, episode: Int, episodeLengthSeconds: Int): List<AniSkipMarker> {
        if (malId <= 0L || episode <= 0) return emptyList()
        val length = episodeLengthSeconds.coerceAtLeast(0)
        val url = "$base/skip-times/$malId/$episode?types[]=op&types[]=ed&types[]=mixed-op&types[]=mixed-ed&types[]=recap&episodeLength=$length"
        val response = catchingNonCancellation {
            http.request(HttpRequest(url, headers = mapOf("Accept" to "application/json")))
        }.getOrNull() ?: return emptyList()
        if (response.statusCode !in 200..299) return emptyList()
        val parsed = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return emptyList()
        val found = (parsed["found"] as? JsonPrimitive)?.contentOrNull?.lowercase() == "true"
            || (parsed["found"] as? JsonPrimitive)?.contentOrNull == "true"
        if (!found) return emptyList()
        val results = parsed["results"] as? JsonArray ?: return emptyList()
        return results.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val type = (obj["skipType"] as? JsonPrimitive)?.contentOrNull.orEmpty()
            val interval = obj["interval"] as? JsonObject ?: return@mapNotNull null
            val start = (interval["startTime"] as? JsonPrimitive)?.doubleOrNull ?: 0.0
            val end = (interval["endTime"] as? JsonPrimitive)?.doubleOrNull ?: 0.0
            val length = (obj["episodeLength"] as? JsonPrimitive)?.doubleOrNull ?: 0.0
            AniSkipMarker(type = type, startSeconds = start, endSeconds = end, episodeLengthSeconds = length)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.kt).

The implementation below defines `interface`, `extractJpeg`, `createPlatformVideoFrameExtractor`.

The source describes its contract as:

> Decodes one representative frame (about 10% into the video) of a local file into a JPEG.

```kotlin
package eu.friedcutlet.yokan.services.media

/** Decodes one representative frame (about 10% into the video) of a local file into a JPEG. */
fun interface VideoFrameExtractor {
    /**
     * [url] is the address the player opens ([eu.friedcutlet.yokan.services.files.LocalFileService.readableUrl]).
     * The image fits within [maxDimension] pixels on both axes. Null (or a failure) means no frame on this platform.
     */
    suspend fun extractJpeg(url: String, maxDimension: Int): ByteArray?
}

expect fun createPlatformVideoFrameExtractor(): VideoFrameExtractor
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/DoodExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/DoodExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/DoodExtractor.kt).

The implementation below defines `DoodExtractor`, `extract`, `videosFromUrl`, `randomString`.

The source describes its contract as:

> DoodStream / mirror embed extractor. Strategy: 1. GET the embed; remember the post-redirect URL (Dood serves the actual player from one of dozens of mirror domains). 2. Locate the `'/pass_md5/\<key\>'` literal in the page, derive the trailing token from the last path segment. 3. GET `https://\<host\>/pass_md5/\<key\>` with the embed as `Referer` — the response body is the URL prefix Dood expects us to glue together with a random 10-char salt, the token and an epoch timestamp. 4. Emit one direct video with `User-Agent` + `Referer` headers.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`md5`](../chapters/06-extension-runtimes.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.extensions.js.md5
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.random.Random

/**
 * DoodStream / mirror embed extractor.
 *
 * Strategy:
 *   1. GET the embed; remember the post-redirect URL (Dood serves the actual
 *      player from one of dozens of mirror domains).
 *   2. Locate the `'/pass_md5/<key>'` literal in the page, derive the trailing
 *      token from the last path segment.
 *   3. GET `https://<host>/pass_md5/<key>` with the embed as `Referer` — the
 *      response body is the URL prefix Dood expects us to glue together with
 *      a random 10-char salt, the token and an epoch timestamp.
 *   4. Emit one direct video with `User-Agent` + `Referer` headers.
 */
class DoodExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "dood"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, redirect = true) }

    private suspend fun videosFromUrl(
        url: String,
        quality: String? = null,
        redirect: Boolean = true,
    ): List<DbVideo> {
        val resolvedQuality = quality ?: ("Doodstream" + if (redirect) " mirror" else "")
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        // We don't currently expose the final post-redirect URL through
        // HttpResponse, so use the input URL as the referer/page URL for the
        // header set. Mirror hosts still work because the regex below picks
        // their hostname out of the embedded `/pass_md5/` literal.
        val pageUrl = url
        val doodHost = hostOf(pageUrl) ?: return emptyList()
        val body = response.body
        if (!body.contains("'/pass_md5/")) return emptyList()
        val md5 = body.substringAfter("'/pass_md5/", "").substringBefore("',", "")
        if (md5.isBlank()) return emptyList()
        val token = md5.substringAfterLast('/', missingDelimiterValue = md5)

        val randomSalt = randomString(10)
        val expiry = nowMillis()
        val passResponse = http.request(
            HttpRequest(
                url = "https://$doodHost/pass_md5/$md5",
                headers = mapOf("Referer" to pageUrl),
            ),
        )
        if (passResponse.statusCode !in 200..299) return emptyList()
        val videoUrl = "${passResponse.body}$randomSalt?token=$token&expiry=$expiry"
        return listOf(
            DbVideo(
                url = videoUrl,
                quality = resolvedQuality,
                originalUrl = pageUrl,
                headers = mapOf(
                    "User-Agent" to "Mangayomi",
                    "Referer" to "https://$doodHost/",
                ),
            ),
        )
    }

    private fun randomString(length: Int): String {
        val allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
        return buildString(length) { repeat(length) { append(allowed[Random.nextInt(allowed.length)]) } }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/FilemoonExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/FilemoonExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/FilemoonExtractor.kt).

The implementation below defines `FilemoonExtractor`, `extract`, `videosFromUrl`, `subtitleTracksFor`.

The source describes its contract as:

> Filemoon embed extractor. Filemoon ships the m3u8 URL inside a packed `eval(function(p,a,c,k,e,d)…)` script. After unpacking we look for `{file:"…m3u8…"}` and, optionally, subtitle tracks via a `fetch('…');` call (or a `sub.info` query param).

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive

/**
 * Filemoon embed extractor.
 *
 * Filemoon ships the m3u8 URL inside a packed `eval(function(p,a,c,k,e,d)…)`
 * script. After unpacking we look for `{file:"…m3u8…"}` and, optionally,
 * subtitle tracks via a `fetch('…');` call (or a `sub.info` query param).
 */
class FilemoonExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "filemoon"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, prefix = "Filemoon", suffix = "") }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String,
        suffix: String,
    ): List<DbVideo> {
        val host = hostOf(url) ?: return emptyList()
        val videoHeaders = mapOf(
            "Referer" to url,
            "Origin" to "https://$host",
        )
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        // Filemoon ships exactly one packed script that contains "eval(".
        val packed = ScriptTagRegex.findAll(response.body)
            .map { it.groupValues[1] }
            .firstOrNull { it.contains("eval(") }
            ?: return emptyList()
        val unpacked = JsPacker.unpack(packed) ?: return emptyList()

        val masterUrl = unpacked
            .substringAfter("{file:\"", "")
            .substringBefore("\"}", "")
        if (masterUrl.isBlank()) return emptyList()

        val subtitleTracks = subtitleTracksFor(url, unpacked, videoHeaders)

        return http.m3u8Videos(
            masterUrl = masterUrl,
            labelPrefix = (prefix.ifBlank { "Filemoon" }) + " -",
            labelSuffix = suffix,
            headers = videoHeaders,
            subtitles = subtitleTracks,
        )
    }

    private suspend fun subtitleTracksFor(
        embedUrl: String,
        unpacked: String,
        videoHeaders: Map<String, String>,
    ): List<DbVideoTrack> {
        // Prefer the explicit `sub.info` query param if the source provided one;
        // fall back to the inline `fetch('…')` URL the unpacked script ships.
        val explicit = SUB_INFO_REGEX.find(embedUrl)?.groupValues?.get(1).orEmpty()
        val inline = unpacked.substringAfter("fetch('", "").substringBefore("').", "")
        val subUrl = listOf(explicit, inline).firstOrNull { it.isNotBlank() } ?: return emptyList()
        return catchingNonCancellation {
            val res = http.request(HttpRequest(subUrl, headers = videoHeaders))
            if (res.statusCode !in 200..299) return@catchingNonCancellation emptyList<DbVideoTrack>()
            val arr = Json.parseToJsonElement(res.body) as? JsonArray ?: return@catchingNonCancellation emptyList()
            arr.mapNotNull { entry ->
                val obj = entry as? JsonObject ?: return@mapNotNull null
                val file = obj["file"]?.jsonPrimitive?.content
                val label = obj["label"]?.jsonPrimitive?.content
                if (file.isNullOrBlank()) null else DbVideoTrack(file = file, label = label)
            }
        }.getOrDefault(emptyList())
    }

    private companion object {
        val SUB_INFO_REGEX = Regex("""[?&]sub\.info=([^&#]+)""")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/GogoCdnExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/GogoCdnExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/GogoCdnExtractor.kt).

The implementation below defines `GogoCdnExtractor`, `extract`, `videosFromUrl`, `buildSources`, `splitHostAndId`, `paddedKey`, `decryptToString`, `encryptToBase64`.

The source describes its contract as:

> GoGoCDN / Vidstreaming embed extractor. The player negotiates the actual stream URL via a pair of AES-CBC roundtrips. 1. Scrape `iv`, `secretKey`, `decryptionKey` and the `data-value` blob out of the embed page. 2. AES-CBC-decrypt `data-value` with (secretKey, iv) → the query params that have to be appended to `encrypt-ajax.php`. 3. AES-CBC-encrypt the `id` query param with the same (secretKey, iv) → the `encryptedId` we send to `encrypt-ajax.php`. 4. Decrypt the response's `data` field with (decryptionKey, iv) → JSON containing the source list (either an HLS master URL or one or more labelled stream URLs). AES key + IV come through as raw ASCII strings, which we right-pad with null bytes (or truncate) to AES-128's 16-byte requirement — matching how the Flutter `encrypt` package handles undersized inputs.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`aesDecrypt`](../chapters/06-extension-runtimes.md), [`aesEncrypt`](../chapters/06-extension-runtimes.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.extensions.js.aesDecrypt
import eu.friedcutlet.yokan.services.extensions.js.aesEncrypt
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive

/**
 * GoGoCDN / Vidstreaming embed extractor.
 *
 * The player negotiates the actual stream URL via a pair of AES-CBC roundtrips.
 *
 *   1. Scrape `iv`, `secretKey`, `decryptionKey` and the `data-value` blob out
 *      of the embed page.
 *   2. AES-CBC-decrypt `data-value` with (secretKey, iv) → the query params
 *      that have to be appended to `encrypt-ajax.php`.
 *   3. AES-CBC-encrypt the `id` query param with the same (secretKey, iv) →
 *      the `encryptedId` we send to `encrypt-ajax.php`.
 *   4. Decrypt the response's `data` field with (decryptionKey, iv) → JSON
 *      containing the source list (either an HLS master URL or one or more
 *      labelled stream URLs).
 *
 * AES key + IV come through as raw ASCII strings, which we right-pad with null
 * bytes (or truncate) to AES-128's 16-byte requirement — matching how the
 * Flutter `encrypt` package handles undersized inputs.
 */
class GogoCdnExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "gogocdn"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    @OptIn(ExperimentalEncodingApi::class)
    private suspend fun videosFromUrl(serverUrl: String): List<DbVideo> {
        val response = http.request(HttpRequest(serverUrl))
        if (response.statusCode !in 200..299) return emptyList()
        val document = response.body

        val iv = WRAPPER_REGEX.find(document)?.groupValues?.get(1)?.removePrefix("container-")
            ?: return emptyList()
        val secretKey = BODY_REGEX.find(document)?.groupValues?.get(1)?.removePrefix("container-")
            ?: return emptyList()
        val decryptionKey = DECRYPTION_KEY_REGEX.find(document)?.groupValues?.get(1)
            ?: return emptyList()
        val dataValue = DATA_VALUE_REGEX.find(document)?.groupValues?.get(1).orEmpty()

        val ivBytes = paddedKey(iv, 16)
        val secretKeyBytes = paddedKey(secretKey, 16)
        val decryptionKeyBytes = paddedKey(decryptionKey, 16)

        // Decrypt data-value to learn the extra query params for encrypt-ajax.php.
        val decryptedDataValue = decryptToString(secretKeyBytes, ivBytes, dataValue) ?: return emptyList()
        val encryptAjaxParams = decryptedDataValue.substringAfter("&", missingDelimiterValue = "")
        if (encryptAjaxParams.isBlank()) return emptyList()

        val (host, idParam) = splitHostAndId(serverUrl) ?: return emptyList()
        val encryptedId = encryptToBase64(secretKeyBytes, ivBytes, idParam) ?: return emptyList()
        val isGogostream = serverUrl.contains("token=", ignoreCase = true)
        val qualityPrefix = if (isGogostream) "Gogostream - " else "Vidstreaming - "

        val encryptAjaxUrl = "${host}encrypt-ajax.php?id=$encryptedId&$encryptAjaxParams&alias=$idParam"
        val ajaxResponse = http.request(
            HttpRequest(
                url = encryptAjaxUrl,
                headers = mapOf("X-Requested-With" to "XMLHttpRequest"),
            ),
        )
        if (ajaxResponse.statusCode !in 200..299) return emptyList()
        val ajaxRoot = runCatching { Json.parseToJsonElement(ajaxResponse.body) as? JsonObject }.getOrNull()
            ?: return emptyList()
        val encryptedData = ajaxRoot["data"]?.jsonPrimitive?.content ?: return emptyList()
        val decryptedJson = decryptToString(decryptionKeyBytes, ivBytes, encryptedData) ?: return emptyList()
        val payload = runCatching { Json.parseToJsonElement(decryptedJson) as? JsonObject }.getOrNull()
            ?: return emptyList()
        val sources = payload["source"] as? JsonArray ?: return emptyList()

        return buildSources(sources, qualityPrefix, serverUrl)
    }

    private suspend fun buildSources(
        sources: JsonArray,
        qualityPrefix: String,
        serverUrl: String,
    ): List<DbVideo> {
        val (hls, others) = sources.partition { it is JsonObject && (it["type"]?.jsonPrimitive?.content == "hls") }
        val videos = mutableListOf<DbVideo>()
        // Single HLS master URL — fan out to per-resolution variants.
        if (hls.size == 1) {
            val fileUrl = (hls[0] as JsonObject)["file"]?.jsonPrimitive?.content?.trim().orEmpty()
            if (fileUrl.isNotBlank()) {
                // Single-rendition playlist — fall back to the master URL itself.
                videos += http.m3u8Videos(
                    masterUrl = fileUrl,
                    labelPrefix = qualityPrefix,
                    fallbackQuality = "${qualityPrefix}Original",
                )
            }
        }
        // Labelled streams — emit one DbVideo per entry, with "auto" pushed last
        // so per-quality selectors default to a real resolution.
        val autoVideos = mutableListOf<DbVideo>()
        for (entry in others) {
            val obj = entry as? JsonObject ?: continue
            val label = obj["label"]?.jsonPrimitive?.content.orEmpty()
                .lowercase().trim().replace(" ", "")
            val fileUrl = obj["file"]?.jsonPrimitive?.content.orEmpty().trim()
            if (fileUrl.isBlank()) continue
            val video = DbVideo(
                url = fileUrl,
                quality = "$qualityPrefix$label",
                originalUrl = fileUrl,
                headers = mapOf("Referer" to serverUrl),
            )
            if (label == "auto") autoVideos += video else videos += video
        }
        return videos + autoVideos
    }

    private fun splitHostAndId(serverUrl: String): Pair<String, String>? {
        val host = "https://${hostOf(serverUrl) ?: return null}/"
        val idParam = QUERY_ID_REGEX.find(serverUrl)?.groupValues?.get(1) ?: return null
        return host to idParam
    }

    private fun paddedKey(value: String, target: Int): ByteArray {
        val raw = value.encodeToByteArray()
        return when {
            raw.size == target -> raw
            raw.size > target -> raw.copyOf(target)
            else -> ByteArray(target).also { out -> raw.copyInto(out) }
        }
    }

    @OptIn(ExperimentalEncodingApi::class)
    private fun decryptToString(key: ByteArray, iv: ByteArray, base64Cipher: String): String? {
        if (base64Cipher.isBlank()) return null
        val cipherBytes = runCatching { Base64.decode(base64Cipher) }.getOrNull() ?: return null
        val plain = aesDecrypt(key, iv, cipherBytes) ?: return null
        return runCatching { plain.decodeToString() }.getOrNull()
    }

    @OptIn(ExperimentalEncodingApi::class)
    private fun encryptToBase64(key: ByteArray, iv: ByteArray, plain: String): String? {
        val enc = aesEncrypt(key, iv, plain.encodeToByteArray()) ?: return null
        return Base64.encode(enc)
    }

    private companion object {
        val WRAPPER_REGEX = Regex("""<div[^>]*class="([^"]*container-[^"\s]+)[^"]*"""", RegexOption.IGNORE_CASE)
        val BODY_REGEX = Regex("""<body[^>]*class="([^"]*container-[^"\s]+)[^"]*"""", RegexOption.IGNORE_CASE)
        val DECRYPTION_KEY_REGEX = Regex("""videocontent-(\d+)""")
        val DATA_VALUE_REGEX = Regex("""data-value="([^"]+)"""")
        val QUERY_ID_REGEX = Regex("""[?&]id=([^&#]+)""")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractor.kt).

The implementation below defines `KwikExtractor`, `extract`, `extractHls`, `extractHlsUrl`, `extractM3u8`, `extractMp4`, `decrypt`, `ePageHeaders`, `kwikHeaders`, `urlEncode`.

The source describes its contract as:

> Kwik / Pahewin embed extractor for AnimePahe. Kwik wraps its stream URL behind two distinct obfuscation schemes: - **`kwik.cx/e/\<id\>`** (HLS path) — the embed page ships a Dean Edwards `eval(function(p,a,c,k,e,d){…})` packed script. After unpacking, the `.m3u8` master is at `const source='…'`. - **`pahe.win/\<id\>`** (MP4 / download path) — `GET /i` returns a 302 to the canonical Kwik URL. The Kwik page contains a custom obfuscator invocation `("\<fullString\>",N,"\<key\>",v1,v2,N)`; decrypting that yields a `\<form action="https://kwik.si/d/\<token\>"\>\<input value="\<tok\>"\>` snippet. Posting `_token=\<tok\>` to the action returns a 302 whose `Location` header is the direct CDN .mp4 URL. Cloudflare handling is delegated to \[HttpService\], which retries challenged requests through the platform WebView with the same headers and cookies.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`EnhancedHttpService`](../chapters/05-http-cookies-and-webviews.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Kwik / Pahewin embed extractor for AnimePahe.
 *
 * Kwik wraps its stream URL behind two distinct obfuscation schemes:
 *
 *  - **`kwik.cx/e/<id>`** (HLS path) — the embed page ships a Dean Edwards
 *    `eval(function(p,a,c,k,e,d){…})` packed script. After unpacking, the
 *    `.m3u8` master is at `const source='…'`.
 *  - **`pahe.win/<id>`** (MP4 / download path) — `GET /i` returns a 302 to
 *    the canonical Kwik URL. The Kwik page contains a custom obfuscator
 *    invocation `("<fullString>",N,"<key>",v1,v2,N)`; decrypting that
 *    yields a `<form action="https://kwik.si/d/<token>"><input
 *    value="<tok>">` snippet. Posting `_token=<tok>` to the action returns
 *    a 302 whose `Location` header is the direct CDN .mp4 URL.
 *
 * Cloudflare handling is delegated to [HttpService], which retries challenged
 * requests through the platform WebView with the same headers and cookies.
 */
class KwikExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "kwik"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult {
        // AnimePahe hands us either a `pahe.win/<id>` download wrapper or a
        // `kwik.cx/e/<id>` HLS embed. Pick the right path per URL shape;
        // both end up producing a list of DbVideo entries.
        val cleanUrl = url.trim()
        val isDownload = cleanUrl.contains("pahe.win", ignoreCase = true)
        return extractVideos(headers + kwikHeaders()) {
            if (isDownload) extractMp4(cleanUrl, headers) else extractHls(cleanUrl, headers)
        }
    }

    /** HLS extraction — unpack the packed eval() and read `const source='…'`. */
    suspend fun extractHls(
        kwikUrl: String,
        callerHeaders: Map<String, String>,
        qualityHint: String = "",
    ): List<DbVideo> {
        val pageHeaders = ePageHeaders() + callerHeaders + mapOf(
            "Referer" to (callerHeaders["Referer"] ?: "https://kwik.cx/"),
        )
        var embedRes = http.request(HttpRequest(kwikUrl, headers = pageHeaders))
        var masterUrl = embedRes.takeIf { it.statusCode in 200..299 }?.let { extractHlsUrl(it.body) }
        if (masterUrl == null) {
            embedRes = http.request(
                HttpRequest(
                    kwikUrl,
                    headers = pageHeaders + ("X-Yokan-Resolve-Cloudflare" to "1"),
                ),
            )
            masterUrl = embedRes.takeIf { it.statusCode in 200..299 }?.let { extractHlsUrl(it.body) }
        }
        masterUrl ?: return emptyList()
        val playbackHeaders = kwikHeaders()
        val labelPrefix = "Kwik" + (if (qualityHint.isBlank()) "" else " - $qualityHint")
        return http.m3u8Videos(
            masterUrl = masterUrl,
            labelPrefix = labelPrefix,
            headers = playbackHeaders,
            requestHeaders = playbackHeaders,
        ).ifEmpty {
            // Master fetch failed (some Kwik nodes only allow the player UA) or
            // it's a non-master single-variant playlist: hand the URL back
            // directly so the player still gets a usable URL.
            listOf(
                DbVideo(
                    url = masterUrl,
                    originalUrl = masterUrl,
                    quality = labelPrefix,
                    headers = playbackHeaders,
                ),
            )
        }
    }


    private fun extractHlsUrl(body: String): String? {
        for (match in ScriptTagRegex.findAll(body)) {
            val script = match.groupValues[1]
            var searchFrom = script.lastIndex
            while (searchFrom >= 0) {
                val evalPosition = script.lastIndexOf("eval(function(", searchFrom)
                if (evalPosition < 0) break
                JsPacker.unpack(script.substring(evalPosition))
                    ?.let(::extractM3u8)
                    ?.let { return it }
                searchFrom = evalPosition - 1
            }
        }
        return null
    }

    private fun extractM3u8(unpacked: String): String? =
        SOURCE_REGEX.find(unpacked)?.groupValues?.get(1)
            ?: M3U8_REGEX.find(unpacked)?.groupValues?.get(1)

    /** MP4 / download extraction via `pahe.win/<id>` → Kwik → custom decrypt → POST. */
    suspend fun extractMp4(
        paheUrl: String,
        callerHeaders: Map<String, String>,
        qualityHint: String = "",
    ): List<DbVideo> {
        // Phase 1: pahe.win /i returns a 302 to the canonical Kwik URL. Our
        // HttpService follows redirects transparently, but we need the
        // pre-redirect Location to peel off any wrapper, so we issue the
        // initial request and read its final URL from the response chain.
        // EnhancedHttpService doesn't expose the redirect chain, so instead
        // hit /i and use the response URL — or, if that's not exposed,
        // probe the embed URL from the page body itself.
        val initRes = http.request(
            HttpRequest(
                url = "${paheUrl.trimEnd('/')}/i",
                headers = callerHeaders + mapOf("Referer" to "https://animepahe.ru/"),
            ),
        )
        // Locate the canonical Kwik URL. The first preference is the response
        // body's own form/script references; failing that we accept the
        // request URL itself if it already resolves to a Kwik host.
        val kwikUrl = KWIK_URL_REGEX.find(initRes.body)?.value
            ?: paheUrl.takeIf { it.contains("kwik.", ignoreCase = true) }
            ?: return emptyList()

        // Phase 2: fetch the Kwik HTML and pull the obfuscator tuple.
        val embedHeaders = kwikHeaders() + mapOf("Referer" to "https://kwik.cx/")
        val embedRes = http.request(HttpRequest(kwikUrl, headers = embedHeaders))
        if (embedRes.statusCode !in 200..299) return emptyList()
        val match = PARAMS_REGEX.find(embedRes.body) ?: return emptyList()
        val (fullString, key, v1Str, v2Str) = match.destructured
        val v1 = v1Str.toIntOrNull() ?: return emptyList()
        val v2 = v2Str.toIntOrNull() ?: return emptyList()
        val decrypted = decrypt(fullString, key, v1, v2)
        val action = ACTION_REGEX.find(decrypted)?.groupValues?.get(1) ?: return emptyList()
        val token = VALUE_REGEX.find(decrypted)?.groupValues?.get(1) ?: return emptyList()

        // Phase 3: POST `_token=<tok>` and use the redirect target.
        // We follow redirects via the HttpService and read the final URL
        // from the response body when available; if HttpService transparently
        // followed the 302 already, the body may be the actual file. To
        // keep things simple, we attempt the POST and treat the request URL
        // surfaced via response headers / inferred body as the stream URL.
        val postHeaders = kwikHeaders() + mapOf(
            "Referer" to kwikUrl,
            "Cookie" to listOf(
                embedRes.setCookies.joinToString("; ") { it.substringBefore(";") },
                callerHeaders["Cookie"].orEmpty(),
            ).filter { it.isNotBlank() }.joinToString("; "),
            "Content-Type" to "application/x-www-form-urlencoded",
        )
        val body = "_token=${urlEncode(token)}"
        val postRes = http.request(
            HttpRequest(
                url = action,
                method = "POST",
                headers = postHeaders,
                body = body,
            ),
        )
        // Kwik returns 302 → Location: <cdn>. HttpService follows redirects;
        // the final stream URL is whatever the response carries as
        // `request.url` (some HttpService implementations) or the Location
        // header if the redirect wasn't auto-followed.
        // EnhancedHttpService follows redirects transparently, which means
        // we usually won't see the Location header here. The fallback path
        // — sniffing the final URL from the response — isn't available
        // through our HttpService surface, so MP4 download extraction
        // returns the Location only when redirects weren't auto-followed.
        // The HLS path above is the canonical in-app playback route.
        val streamUrl = postRes.headers["location"]
            ?: postRes.headers["Location"]
            ?: return emptyList()
        val playbackHeaders = kwikHeaders() + mapOf("Referer" to "https://kwik.cx/")
        val label = "Kwik MP4" + (if (qualityHint.isBlank()) "" else " - $qualityHint")
        return listOf(
            DbVideo(
                url = streamUrl,
                originalUrl = streamUrl,
                quality = label,
                headers = playbackHeaders,
            ),
        )
    }

    /**
     * Base-`v2` digit decoder using `key` as the alphabet. The packed string
     * splits on `key[v2]` as a separator; each segment between separators is
     * a base-`v2` number whose digit values come from `keyIndexMap`. Subtract
     * `v1` and cast to Char to recover one source character.
     */
    private fun decrypt(fullString: String, key: String, v1: Int, v2: Int): String {
        if (v2 < 2 || v2 > key.length) return ""
        val keyIndexMap = key.withIndex().associate { it.value to it.index }
        val separator = key[v2]
        val sb = StringBuilder()
        var i = 0
        while (i < fullString.length) {
            val next = fullString.indexOf(separator, i)
            if (next == -1) break
            val digits = StringBuilder()
            for (j in i until next) {
                val v = keyIndexMap[fullString[j]] ?: return sb.toString()
                digits.append(v.toString())
            }
            i = next + 1
            val n = digits.toString().toIntOrNull(v2) ?: return sb.toString()
            sb.append((n - v1).toChar())
        }
        return sb.toString()
    }

    private fun ePageHeaders(): Map<String, String> = mapOf(
        "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language" to "en-US,en;q=0.9",
        "Sec-Fetch-Dest" to "iframe",
        "Sec-Fetch-Mode" to "navigate",
        "Sec-Fetch-Site" to "cross-site",
        "Sec-Fetch-User" to "?1",
        "Upgrade-Insecure-Requests" to "1",
    )

    private fun kwikHeaders(): Map<String, String> = mapOf(
        "Origin" to "https://kwik.cx",
        "Referer" to "https://kwik.cx/",
    )

    private fun urlEncode(value: String): String {
        // Minimal application/x-www-form-urlencoded encoder — KMP-friendly
        // (no java.net.URLEncoder dependency).
        val sb = StringBuilder()
        for (c in value) {
            when {
                c.isLetterOrDigit() || c == '-' || c == '_' || c == '.' || c == '~' -> sb.append(c)
                else -> for (b in c.toString().encodeToByteArray()) {
                    sb.append('%').append(b.toUByte().toString(16).padStart(2, '0').uppercase())
                }
            }
        }
        return sb.toString()
    }

    private companion object {
        val SOURCE_REGEX = Regex("""(?:(?:const|var)\s+source\s*=|source\s*:\s*)\\?['"](https?://[^\s\\'"]+\.m3u8[^\s\\'"]*)""")
        val M3U8_REGEX = Regex("""(https?://[^\s\\'"]+\.m3u8[^\s\\'"]*)""")
        val PARAMS_REGEX = Regex("""\("(\w+)",\d+,"(\w+)",(\d+),(\d+),\d+\)""")
        val ACTION_REGEX = Regex("""action="([^"]+)"""")
        val VALUE_REGEX = Regex("""value="([^"]+)"""")
        val KWIK_URL_REGEX = Regex("""https?://kwik\.[a-z]+/[^\s"'<>)]+""", RegexOption.IGNORE_CASE)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/Mp4UploadExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/Mp4UploadExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/Mp4UploadExtractor.kt).

The implementation below defines `Mp4UploadExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> Mp4Upload embed extractor. The player serves the source URL via one of two script shapes: - **Packed**: `eval(function(p,a,c,k,e,d){…})('payload', …)` — unpack first. - **Plain**: a script that contains `player.src({ src: "\<url\>" })`. Quality is the `HEIGHT=` value inside the same script's m3u8 metadata.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Mp4Upload embed extractor.
 *
 * The player serves the source URL via one of two script shapes:
 *  - **Packed**: `eval(function(p,a,c,k,e,d){…})('payload', …)` — unpack first.
 *  - **Plain**: a script that contains `player.src({ src: "<url>" })`.
 *
 * Quality is the `HEIGHT=` value inside the same script's m3u8 metadata.
 */
class Mp4UploadExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "mp4upload"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers) }

    private suspend fun videosFromUrl(
        url: String,
        headers: Map<String, String>,
        prefix: String = "",
        suffix: String = "",
    ): List<DbVideo> {
        val mergedHeaders = headers.toMutableMap().apply { put("referer", REFERER) }
        val response = http.request(HttpRequest(url, headers = mergedHeaders))
        if (response.statusCode !in 200..299) return emptyList()
        val body = response.body

        val packed = ScriptTagRegex.findAll(body)
            .map { it.groupValues[1] }
            .firstOrNull { it.contains("eval") && it.contains("p,a,c,k,e,d") }
        val plain = ScriptTagRegex.findAll(body)
            .map { it.groupValues[1] }
            .firstOrNull { it.contains("player.src") }
        val script = when {
            packed != null -> JsPacker.unpack(packed) ?: return emptyList()
            plain != null -> plain
            else -> return emptyList()
        }

        val videoUrl = script
            .substringAfter(".src(", "")
            .substringBefore(")", "")
            .substringAfter("src:", "")
            .substringAfter("\"", "")
            .substringBefore("\"", "")
        if (videoUrl.isBlank()) return emptyList()
        val resolution = HEIGHT_REGEX.find(script)?.groupValues?.get(1) ?: "Unknown resolution"
        val quality = buildString {
            if (prefix.isNotBlank()) append(prefix).append(' ')
            append("Mp4Upload - ${resolution}p")
            if (suffix.isNotBlank()) append(' ').append(suffix)
        }
        return listOf(DbVideo(url = videoUrl, quality = quality, originalUrl = videoUrl, headers = mergedHeaders))
    }

    private companion object {
        const val REFERER = "https://mp4upload.com/"
        val HEIGHT_REGEX = Regex("""\WHEIGHT=(\d+)""")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MyStreamExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MyStreamExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MyStreamExtractor.kt).

The implementation below defines `MyStreamExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> MyStream embed extractor. The page embeds the stream code as `\<videoId\>", "\<streamCode\>",null,null` so the extractor splices it out, then builds the master URL at `/m3u8/\<code\>/master.txt`. The master playlist responds with `PHPSESSID` — we forward that as a `Cookie` header on the playlist + variant requests because MyStream 403s without it.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * MyStream embed extractor.
 *
 * The page embeds the stream code as `<videoId>", "<streamCode>",null,null` so
 * the extractor splices it out, then builds the master URL at `/m3u8/<code>/master.txt`.
 *
 * The master playlist responds with `PHPSESSID` — we forward that as a
 * `Cookie` header on the playlist + variant requests because MyStream
 * 403s without it.
 */
class MyStreamExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "mystream"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers) }

    private suspend fun videosFromUrl(
        url: String,
        headers: Map<String, String>,
    ): List<DbVideo> {
        val host = url.substringBefore("/watch")
        val embedId = url.substringAfter("?v=", missingDelimiterValue = "")
        if (embedId.isBlank()) return emptyList()
        val response = http.request(HttpRequest(url, headers = headers))
        if (response.statusCode !in 200..299) return emptyList()
        val body = response.body
        val streamCode = body
            .substringAfter("$embedId\", \"", "")
            .substringBefore("\",null,null", "")
        if (streamCode.isBlank()) return emptyList()
        val streamUrl = "$host/m3u8/$streamCode/master.txt?s=1&cache=1"

        // Walk Set-Cookie for the PHPSESSID entry. HttpResponse merges duplicate
        // headers comma-separated, so we lowercase + scan tokens defensively.
        val rawCookie = response.headers.entries.firstOrNull { it.key.equals("Set-Cookie", ignoreCase = true) }
            ?.value.orEmpty()
        val phpSession = rawCookie.split(',', ';')
            .map { it.trim() }
            .firstOrNull { it.startsWith("PHPSESSID", ignoreCase = true) }
            .orEmpty()
        val newHeaders = headers.toMutableMap().apply {
            if (phpSession.isNotBlank()) put("cookie", phpSession)
            put("accept", "*/*")
        }
        return http.m3u8Videos(
            masterUrl = streamUrl,
            labelPrefix = "MyStream - ",
            headers = newHeaders,
            requestHeaders = newHeaders,
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MytvExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MytvExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/MytvExtractor.kt).

The implementation below defines `MytvExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> Mytv embed extractor. Walks every `\<script\>` for `CreatePlayer("v=…&tp=video…")` calls — the `v=` field is a URL-encoded video URL that we just decode in-place. If the decoded URL doesn't start with `https:` the source labels it as a generic `Stream`; otherwise it's labelled `Mytv`.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Mytv embed extractor.
 *
 * Walks every `<script>` for `CreatePlayer("v=…&tp=video…")` calls — the
 * `v=` field is a URL-encoded video URL that we just decode in-place.
 *
 * If the decoded URL doesn't start with `https:` the source labels it as a
 * generic `Stream`; otherwise it's labelled `Mytv`.
 */
class MytvExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "mytv"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    private suspend fun videosFromUrl(url: String): List<DbVideo> {
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        val videos = mutableListOf<DbVideo>()
        ScriptTagRegex.findAll(response.body).forEach { match ->
            val text = match.groupValues[1]
            if (!text.contains("CreatePlayer(\"v")) return@forEach
            val rawUrl = text
                .substringAfter("\"v=", "")
                .substringBefore("\\u0026tp=video", "")
            if (rawUrl.isBlank()) return@forEach
            val decoded = rawUrl
                .replace("%26", "&")
                .replace("%3a", ":")
                .replace("%2f", "/")
                .replace("%3f", "?")
                .replace("%3d", "=")
            val label = if (decoded.contains("https:")) "Mytv" else "Stream"
            videos += DbVideo(url = decoded, quality = label, originalUrl = decoded)
        }
        return videos
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/OkruExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/OkruExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/OkruExtractor.kt).

The implementation below defines `OkruExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> OK.ru video embed extractor. The player ships its config in a `\<div data-options="…"\>` attribute. The value is a giant JSON blob with all quote characters double-escaped — we only need the `ondemandHls` URL, which is encoded as `&` between query params. The HLS master is then parsed normally; relative variant URLs are resolved against the master's directory.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * OK.ru video embed extractor.
 *
 * The player ships its config in a `<div data-options="…">` attribute. The
 * value is a giant JSON blob with all quote characters double-escaped — we
 * only need the `ondemandHls` URL, which is encoded as `&` between query
 * params.
 *
 * The HLS master is then parsed normally; relative variant URLs are resolved
 * against the master's directory.
 */
class OkruExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "okru"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String = "",
    ): List<DbVideo> {
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        val attribute = DATA_OPTIONS_REGEX.find(response.body)?.groupValues?.get(1).orEmpty()
        if (attribute.isBlank() || !attribute.contains("ondemandHls")) return emptyList()
        val playlistUrl = attribute
            .substringAfter("ondemandHls\\\":\\\"", "")
            .substringBefore("\\\"", "")
            .replace("\\\\u0026", "&")
        if (playlistUrl.isBlank()) return emptyList()
        return http.m3u8Videos(masterUrl = playlistUrl, labelPrefix = prefix + "Okru:")
    }

    private companion object {
        val DATA_OPTIONS_REGEX = Regex("""data-options="([^"]+)"""", RegexOption.IGNORE_CASE)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/QuarkUcExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/QuarkUcExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/QuarkUcExtractor.kt).

The implementation below defines `QuarkUcExtractor`, `extract`, `videosFromUrl`, `pickCookie`, `Drive`, `headers`, `forLabel`, `QualityEntry`, `ExtractState`, `api` and 7 further declarations.

The source describes its contract as:

> Quark Pan / UC Pan cloud-drive video extractor — covers two backends from one class because they share the same API shape, only differing in base URL, user-agent, and referer. Yokan's HTTP layer has no equivalent of the Flutter app's per-host cookie store, so this extractor expects the calling source (JavaScript extension or native caller) to pass a valid drive cookie via the `Cookie` header on the incoming `headers` map — same way Mihon's JS extensions handle session tokens. Without a cookie the API returns auth errors and we fall through to an empty list. Input URL format (matches Flutter): `type++fileId++fileToken++shareId++stoken\[++subtitles\]` — where `type` is either `quark` or `uc`, and `subtitles` (optional) is a `+`-separated list of `name@@@ext@@@fileId` triples.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos
import kotlinx.coroutines.delay
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.add
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

/**
 * Quark Pan / UC Pan cloud-drive video extractor — covers two backends from
 * one class because they share the same API shape, only differing in base URL,
 * user-agent, and referer.
 *
 * Yokan's HTTP layer has no equivalent of the Flutter app's per-host cookie
 * store, so this extractor expects the calling source (JavaScript extension or
 * native caller) to pass a valid drive cookie via the `Cookie` header on the
 * incoming `headers` map — same way Mihon's JS extensions handle session
 * tokens. Without a cookie the API returns auth errors and we fall through
 * to an empty list.
 *
 * Input URL format (matches Flutter): `type++fileId++fileToken++shareId++stoken[++subtitles]`
 * — where `type` is either `quark` or `uc`, and `subtitles` (optional) is a
 * `+`-separated list of `name@@@ext@@@fileId` triples.
 */
class QuarkUcExtractor(
    private val http: HttpService,
    private val cookieJar: eu.friedcutlet.yokan.services.http.cookies.CookieJar? = null,
) : AnimeExtractorService {

    override val hostName: String get() = "quarkuc"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers) }

    private suspend fun videosFromUrl(url: String, callerHeaders: Map<String, String> = emptyMap()): List<DbVideo> {
        val parts = url.split("++")
        if (parts.size < 5) return emptyList()
        val driveLabel = parts[0]
        val fileId = parts[1]
        val fileToken = parts[2]
        val shareId = parts[3]
        val stoken = parts[4]
        val subtitleParts = if (parts.size > 5) parts[5].split("+").filter { it.isNotBlank() } else emptyList()

        val drive = Drive.forLabel(driveLabel)
        // Honour an explicit Cookie header first (sources that mint their own
        // token still control the call). Fall through to the shared cookie jar
        // so users who logged in via the in-app WebView are reused
        // automatically; without either we bail out — the drive API returns
        // auth errors and there's nothing to extract.
        val cookie = pickCookie(callerHeaders) ?: drive.cookieDomains
            .firstNotNullOfOrNull { cookieJar?.rawCookieFor(it) }
        if (cookie.isNullOrBlank()) return emptyList()
        val apiHeaders = drive.headers(cookie)

        val state = ExtractState(drive, apiHeaders, mutableMapOf(), null)

        // Ensure we have a save directory and the share token; then ask the
        // cloud drive to mint per-resolution transcoding URLs.
        val quality = liveTranscoding(state, shareId, stoken, fileId, fileToken) ?: return emptyList()
        if (quality.isEmpty()) return emptyList()

        val videoHeaders = apiHeaders.toMutableMap().apply { remove("Content-Type") }
        val originalUrl = quality.firstOrNull()?.url.orEmpty()
        val videos = quality.map { entry ->
            DbVideo(
                url = entry.url,
                quality = entry.quality,
                originalUrl = originalUrl,
                headers = videoHeaders,
                subtitles = emptyList(),
            )
        }

        // Subtitle bundles ride along under the same headers — fetch each
        // download URL and attach the full subtitle list to every video so
        // the player can switch tracks without re-fetching.
        val subtitles = subtitleParts.mapNotNull { entry ->
            val triple = entry.split("@@@")
            if (triple.size != 3) return@mapNotNull null
            val subName = triple[0]
            val subFileId = triple[2]
            val download = downloadInfo(state, shareId, stoken, subFileId, "", clean = false)
            val subUrl = download?.get("download_url")?.jsonPrimitive?.content
            subUrl?.let { DbVideoTrack(file = it, label = subName) }
        }
        return if (subtitles.isEmpty()) videos
        else videos.map { it.copy(subtitles = subtitles) }
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Drive setup

    private fun pickCookie(headers: Map<String, String>): String? {
        val candidate = headers.entries.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value
        return candidate?.takeIf { it.isNotBlank() }
    }

    private enum class Drive(
        val apiBase: String,
        val pr: String,
        val userAgent: String,
        val referer: String,
        val label: String,
        /**
         * Hosts the cookie jar may already hold sessions for after the user
         * logged in via the in-app WebView. We probe these in order — the
         * UA-bearing API hosts first, then the user-facing pages users see in
         * the browser.
         */
        val cookieDomains: List<String>,
    ) {
        Quark(
            apiBase = "https://drive-pc.quark.cn/1/clouddrive/",
            pr = "pr=ucpro&fr=pc",
            userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch",
            referer = "https://pan.quark.cn/",
            label = "quark",
            cookieDomains = listOf("drive-pc.quark.cn", "pan.quark.cn", "quark.cn"),
        ),
        UC(
            apiBase = "https://pc-api.uc.cn/1/clouddrive/",
            pr = "pr=UCBrowser&fr=pc",
            userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) uc-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch",
            referer = "https://drive.uc.cn/",
            label = "uc",
            cookieDomains = listOf("pc-api.uc.cn", "drive.uc.cn", "uc.cn"),
        );

        fun headers(cookie: String): Map<String, String> = mapOf(
            "User-Agent" to userAgent,
            "Referer" to referer,
            "Content-Type" to "application/json",
            "Cookie" to cookie,
        )

        companion object {
            fun forLabel(label: String): Drive = entries.firstOrNull { it.label.equals(label, ignoreCase = true) } ?: Quark
        }
    }

    private data class QualityEntry(val url: String, val quality: String)

    private class ExtractState(
        val drive: Drive,
        val headers: Map<String, String>,
        val saveFileIdCache: MutableMap<String, String>,
        var saveDirId: String?,
    )

    // ─────────────────────────────────────────────────────────────────────────
    // Network helpers

    /** POSTs [body] when non-null, otherwise GETs. */
    private suspend fun api(state: ExtractState, path: String, body: JsonElement? = null): JsonObject? {
        val url = state.drive.apiBase + path
        val request = if (body == null) {
            HttpRequest(url = url, method = "GET", headers = state.headers)
        } else {
            HttpRequest(url = url, method = "POST", headers = state.headers, body = body.toString())
        }
        val response = http.request(request)
        if (response.statusCode !in 200..299) return null
        return runCatching { Json.parseToJsonElement(response.body) as? JsonObject }.getOrNull()
    }

    private suspend fun shareToken(state: ExtractState, shareId: String): String? {
        val result = api(
            state,
            "share/sharepage/token?${state.drive.pr}",
            buildJsonObject {
                put("pwd_id", shareId)
                put("passcode", "")
            },
        ) ?: return null
        return (result["data"] as? JsonObject)?.get("stoken")?.jsonPrimitive?.content?.takeIf { it.isNotBlank() }
    }

    /** Saves [fileId] into the drive (once per extraction) and returns the saved file id. */
    private suspend fun savedFileId(
        state: ExtractState,
        shareId: String,
        stoken: String,
        fileId: String,
        fileToken: String,
        clean: Boolean,
    ): String? {
        state.saveFileIdCache[fileId]?.let { return it }
        val saved = save(state, shareId, stoken, fileId, fileToken, clean) ?: return null
        state.saveFileIdCache[fileId] = saved
        return saved
    }

    private suspend fun liveTranscoding(
        state: ExtractState,
        shareId: String,
        stoken: String,
        fileId: String,
        fileToken: String,
    ): List<QualityEntry>? {
        val fid = savedFileId(state, shareId, stoken, fileId, fileToken, clean = true) ?: return null
        val transcoding = api(
            state,
            "file/v2/play?${state.drive.pr}",
            buildJsonObject {
                put("fid", fid)
                put("resolutions", "normal,low,high,super,2k,4k")
                put("supports", "fmp4")
            },
        ) ?: return null
        val list = (transcoding["data"] as? JsonObject)?.get("video_list") as? JsonArray ?: return null
        return list.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val info = obj["video_info"] as? JsonObject ?: return@mapNotNull null
            val u = info["url"]?.jsonPrimitive?.content ?: return@mapNotNull null
            val q = obj["resolution"]?.jsonPrimitive?.content.orEmpty()
            QualityEntry(url = u, quality = q.ifBlank { "Original" })
        }
    }

    private suspend fun save(
        state: ExtractState,
        shareId: String,
        stoken: String,
        fileId: String,
        fileToken: String,
        clean: Boolean,
    ): String? {
        ensureSaveDir(state, clean)
        val dirId = state.saveDirId ?: return null
        // The share token rides with every save call; mint it if the caller
        // didn't already.
        val effectiveStoken = stoken.ifBlank { shareToken(state, shareId) ?: return null }
        val saveResult = api(
            state,
            "share/sharepage/save?${state.drive.pr}",
            buildJsonObject {
                put("fid_list", buildJsonArray { add(fileId) })
                put("fid_token_list", buildJsonArray { add(fileToken) })
                put("to_pdir_fid", dirId)
                put("pwd_id", shareId)
                put("stoken", effectiveStoken)
                put("pdir_fid", "0")
                put("scene", "link")
            },
        ) ?: return null
        val taskId = (saveResult["data"] as? JsonObject)?.get("task_id")?.jsonPrimitive?.content ?: return null
        // Poll the task endpoint up to three times — Quark/UC sometimes takes
        // a beat to materialise the saved file. The Flutter version uses the
        // same retry budget.
        repeat(3) { retry ->
            val taskResult = api(state, "task?${state.drive.pr}&task_id=$taskId&retry_index=$retry")
            val savedAs = ((taskResult?.get("data") as? JsonObject)?.get("save_as") as? JsonObject)
                ?.get("save_as_top_fids") as? JsonArray
            val firstFid = savedAs?.firstOrNull()?.jsonPrimitive?.content
            if (!firstFid.isNullOrBlank()) return firstFid
            delay(1_000)
        }
        return null
    }

    private suspend fun ensureSaveDir(state: ExtractState, clean: Boolean) {
        if (state.saveDirId != null) {
            if (clean) clearSaveDir(state)
            return
        }
        val list = api(
            state,
            "file/sort?${state.drive.pr}&pdir_fid=0&_page=1&_size=200&_sort=file_type:asc,updated_at:desc",
        )
        val items = (list?.get("data") as? JsonObject)?.get("list") as? JsonArray
        items?.forEach { item ->
            val obj = item as? JsonObject ?: return@forEach
            if (obj["file_name"]?.jsonPrimitive?.content == SAVE_DIR_NAME) {
                state.saveDirId = obj["fid"]?.jsonPrimitive?.content
                clearSaveDir(state)
                return
            }
        }
        val create = api(
            state,
            "file?${state.drive.pr}",
            buildJsonObject {
                put("pdir_fid", "0")
                put("file_name", SAVE_DIR_NAME)
                put("dir_path", "")
                put("dir_init_lock", false)
            },
        )
        state.saveDirId = (create?.get("data") as? JsonObject)?.get("fid")?.jsonPrimitive?.content
    }

    private suspend fun clearSaveDir(state: ExtractState) {
        val saveDirId = state.saveDirId ?: return
        val list = api(
            state,
            "file/sort?${state.drive.pr}&pdir_fid=$saveDirId&_page=1&_size=200&_sort=file_type:asc,updated_at:desc",
        )
        val rows = (list?.get("data") as? JsonObject)?.get("list") as? JsonArray ?: return
        if (rows.isEmpty()) return
        val deleteBody = buildJsonObject {
            put("action_type", 2)
            put("filelist", buildJsonArray {
                rows.forEach { row ->
                    val fid = (row as? JsonObject)?.get("fid")?.jsonPrimitive?.content ?: return@forEach
                    add(fid)
                }
            })
            put("exclude_fids", buildJsonArray { })
        }
        api(state, "file/delete?${state.drive.pr}", deleteBody)
    }

    private suspend fun downloadInfo(
        state: ExtractState,
        shareId: String,
        stoken: String,
        fileId: String,
        fileToken: String,
        clean: Boolean,
    ): JsonObject? {
        val fid = savedFileId(state, shareId, stoken, fileId, fileToken, clean) ?: return null
        val down = api(
            state,
            "file/download?${state.drive.pr}&uc_param_str=",
            buildJsonObject { put("fids", buildJsonArray { add(fid) }) },
        ) ?: return null
        return (down["data"] as? JsonArray)?.firstOrNull() as? JsonObject
    }

    private companion object {
        const val SAVE_DIR_NAME = "TV"
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SendvidExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SendvidExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SendvidExtractor.kt).

The implementation below defines `SendvidExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> Sendvid embed extractor. The HTML ships the master URL on a `\<source id="video_source"\>` element. The master + variants are fetched with `Origin`/`Referer`/`Host` headers because Sendvid 403s on plain GETs.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Sendvid embed extractor.
 *
 * The HTML ships the master URL on a `<source id="video_source">` element.
 * The master + variants are fetched with `Origin`/`Referer`/`Host` headers
 * because Sendvid 403s on plain GETs.
 */
class SendvidExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "sendvid"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers = headers) }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String = "",
        headers: Map<String, String>,
    ): List<DbVideo> {
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        val masterUrl = VIDEO_SOURCE_REGEX.find(response.body)?.groupValues?.get(1) ?: return emptyList()
        val masterHost = hostOf(masterUrl) ?: return emptyList()
        val embedHost = hostOf(url) ?: return emptyList()
        val masterHeaders = headers.toMutableMap().apply {
            put("Accept", "*/*")
            put("Host", masterHost)
            put("Origin", "https://$embedHost")
            put("Referer", "https://$embedHost/")
        }
        return http.m3u8Videos(
            masterUrl = masterUrl,
            labelPrefix = (if (prefix.isNotBlank()) "$prefix - " else "") + "Sendvid:",
            headers = masterHeaders,
            requestHeaders = masterHeaders,
        )
    }

    private companion object {
        val VIDEO_SOURCE_REGEX = Regex(
            """<source[^>]+id=["']video_source["'][^>]+src=["']([^"']+)["']""",
            RegexOption.IGNORE_CASE,
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SibnetExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SibnetExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/SibnetExtractor.kt).

The implementation below defines `SibnetExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> Video.sibnet.ru embed extractor. The single-source player declares `player.src(\[{ src: "\<slug\>" }\])` in the page. The slug may be either an absolute URL or a host-relative path; in the latter case we join it back onto the embed origin.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Video.sibnet.ru embed extractor.
 *
 * The single-source player declares `player.src([{ src: "<slug>" }])` in the
 * page. The slug may be either an absolute URL or a host-relative path; in
 * the latter case we join it back onto the embed origin.
 */
class SibnetExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "sibnet"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String = "",
    ): List<DbVideo> {
        val response = http.request(HttpRequest(url))
        if (response.statusCode != 200) return emptyList()
        val script = response.body
        val slug = script
            .substringAfter("player.src", "")
            .substringAfter("src:", "")
            .substringAfter("\"", "")
            .substringBefore("\"", "")
        if (slug.isBlank()) return emptyList()
        val host = hostOf(url) ?: return emptyList()
        val videoUrl = if (slug.startsWith("http", ignoreCase = true)) slug else "https://$host$slug"
        val quality = if (prefix.isNotBlank()) "$prefix - Sibnet" else "Sibnet"
        return listOf(
            DbVideo(
                url = videoUrl,
                quality = quality,
                originalUrl = videoUrl,
                headers = mapOf("Referer" to url),
            ),
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamTapeExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamTapeExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamTapeExtractor.kt).

The implementation below defines `StreamTapeExtractor`, `extract`, `videosFromUrl`, `normaliseEmbed`.

The source describes its contract as:

> StreamTape embed extractor. Strategy (matches the Flutter implementation): 1. Normalise the embed URL to `https://streamtape.com/e/\<id\>`. 2. Fetch the embed page and find the script that builds `robotlink`. 3. The script ends with `document.getElementById('robotlink').innerHTML = '\<link\>' + ('xcd\<suffix\>')` where the runtime concatenates the two halves into a full media URL. 4. Recombine and emit a single direct video URL.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * StreamTape embed extractor.
 *
 * Strategy (matches the Flutter implementation):
 *   1. Normalise the embed URL to `https://streamtape.com/e/<id>`.
 *   2. Fetch the embed page and find the script that builds `robotlink`.
 *   3. The script ends with `document.getElementById('robotlink').innerHTML = '<link>' + ('xcd<suffix>')`
 *      where the runtime concatenates the two halves into a full media URL.
 *   4. Recombine and emit a single direct video URL.
 */
class StreamTapeExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "streamtape"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers) }

    private suspend fun videosFromUrl(
        url: String,
        headers: Map<String, String> = emptyMap(),
        quality: String = "StreamTape",
    ): List<DbVideo> {
        val embedUrl = normaliseEmbed(url) ?: return emptyList()
        val response = http.request(HttpRequest(embedUrl, headers = headers))
        if (response.statusCode !in 200..299) return emptyList()
        val body = response.body
        val target = "document.getElementById('robotlink')"
        val scripts = ScriptTagRegex.findAll(body)
            .map { it.groupValues[1] }
            .filter { it.contains(target) }
            .toList()
        if (scripts.isEmpty()) return emptyList()
        val script = scripts.first()
        val afterAssign = script.substringAfter("$target.innerHTML = '", missingDelimiterValue = "")
        if (afterAssign.isBlank()) return emptyList()
        // The first chunk is everything up to the closing single-quote.
        val firstHalf = afterAssign.substringBefore("'", missingDelimiterValue = "")
        // The second half ships as `+ ('xcd<suffix>'` — the page strips the leading `xcd` literal
        // before appending. Mirror the Flutter behaviour: take what comes after `+ ('xcd`.
        val secondHalfRaw = afterAssign.substringAfter("+ ('xcd", missingDelimiterValue = "")
        val secondHalf = secondHalfRaw.substringBefore("'", missingDelimiterValue = "")
        val videoUrl = "https:$firstHalf$secondHalf"
        if (firstHalf.isBlank() || secondHalf.isBlank()) return emptyList()
        return listOf(DbVideo(url = videoUrl, quality = quality, originalUrl = videoUrl))
    }

    private fun normaliseEmbed(url: String): String? {
        if (url.startsWith(EMBED_BASE)) return url
        // streamtape.com/<path>/<id> → grab the id segment (index 4 in the split).
        val parts = url.split("/")
        val id = parts.getOrNull(4) ?: return null
        return EMBED_BASE + id
    }

    private companion object {
        const val EMBED_BASE = "https://streamtape.com/e/"
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamWishExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamWishExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamWishExtractor.kt).

The implementation below defines `StreamWishExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> StreamWish embed extractor — also covers other Wish-family hosts (sfastwish, doodstream-mirror, etc.) that ship the same packed-JS player. Strategy: 1. Fetch the embed and find the `\<script\>` whose body contains "m3u8". 2. If it's wrapped in `function(p,a,c,k,e,d)…` run the unpacker. 3. Pull `source…file:"…m3u8…"` from the unpacked source. 4. Fetch the master playlist with sensible Origin/Referer headers and emit one variant per `#EXT-X-STREAM-INF`.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * StreamWish embed extractor — also covers other Wish-family hosts (sfastwish,
 * doodstream-mirror, etc.) that ship the same packed-JS player.
 *
 * Strategy:
 *   1. Fetch the embed and find the `<script>` whose body contains "m3u8".
 *   2. If it's wrapped in `function(p,a,c,k,e,d)…` run the unpacker.
 *   3. Pull `source…file:"…m3u8…"` from the unpacked source.
 *   4. Fetch the master playlist with sensible Origin/Referer headers and emit
 *      one variant per `#EXT-X-STREAM-INF`.
 */
class StreamWishExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "streamwish"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, prefix = "StreamWish", headers = headers) }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String,
        headers: Map<String, String> = emptyMap(),
    ): List<DbVideo> {
        val response = http.request(HttpRequest(url, headers = headers))
        if (response.statusCode !in 200..299) return emptyList()
        val body = response.body
        val scripts = ScriptTagRegex.findAll(body)
            .map { it.groupValues[1] }
            .filter { it.contains("m3u8") }
            .toList()
        if (scripts.isEmpty()) return emptyList()

        val script = scripts.first().let { raw ->
            if (raw.contains("function(p,a,c")) JsPacker.unpack(raw) ?: raw
            else raw
        }
        val masterUrl = script
            .substringAfter("source", "")
            .substringAfter("file:\"", "")
            .substringBefore("\"", "")
        if (masterUrl.isBlank()) return emptyList()

        val embedHost = hostOf(url) ?: return emptyList()
        val masterHost = hostOf(masterUrl) ?: return emptyList()
        val playlistHeaders = buildMap {
            putAll(headers)
            put("Accept", "*/*")
            put("Host", masterHost)
            put("Origin", "https://$embedHost")
            put("Referer", "https://$embedHost/")
        }
        return http.m3u8Videos(
            masterUrl = masterUrl,
            labelPrefix = "$prefix - ",
            headers = playlistHeaders,
            requestHeaders = playlistHeaders,
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamlareExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamlareExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/StreamlareExtractor.kt).

The implementation below defines `StreamlareExtractor`, `extract`, `videosFromUrl`, `extractHls`, `extractLabelled`, `labelPrefix`.

The source describes its contract as:

> Streamlare / slwatch.co extractor. Posts the trailing id segment to `/api/video/stream/get` and reads the JSON envelope. Two response shapes: - `type == "hls"` → parse the master URL out of `"file":"…"`, fan out variants via the m3u8 helper. - Anything else → walk every `"label":"…"`/`"file":"…"` pair, follow the API URL with a POST and emit each as a single video.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * Streamlare / slwatch.co extractor.
 *
 * Posts the trailing id segment to `/api/video/stream/get` and reads the JSON
 * envelope. Two response shapes:
 *  - `type == "hls"` → parse the master URL out of `"file":"…"`, fan out
 *    variants via the m3u8 helper.
 *  - Anything else → walk every `"label":"…"`/`"file":"…"` pair, follow the
 *    API URL with a POST and emit each as a single video.
 */
class StreamlareExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "streamlare"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    private suspend fun videosFromUrl(
        url: String,
        prefix: String = "",
        suffix: String = "",
    ): List<DbVideo> {
        val id = url.substringAfterLast('/', missingDelimiterValue = "")
        if (id.isBlank()) return emptyList()
        val playlistResponse = http.request(
            HttpRequest(
                url = API_ENDPOINT,
                method = "POST",
                headers = mapOf("Content-Type" to "application/json"),
                body = "{\"id\":\"$id\"}",
            ),
        )
        if (playlistResponse.statusCode !in 200..299) return emptyList()
        val playlist = playlistResponse.body
        val type = playlist.substringAfter("\"type\":\"", "").substringBefore("\"", "")

        return if (type == "hls") {
            extractHls(playlist, prefix, suffix)
        } else {
            extractLabelled(playlist, prefix, suffix)
        }
    }

    private suspend fun extractHls(playlist: String, prefix: String, suffix: String): List<DbVideo> {
        val masterUrl = playlist
            .substringAfter("\"file\":\"", "")
            .substringBefore("\"", "")
            .replace("""\/""", "/")
        if (masterUrl.isBlank()) return emptyList()
        val master = http.request(HttpRequest(masterUrl))
        if (master.statusCode !in 200..299) return emptyList()
        // The master URL ends in `master.m3u8`; the source resolves relative
        // variant paths against everything before that filename.
        val resolveBase = masterUrl.substringBefore("master.m3u8", missingDelimiterValue = masterUrl.substringBeforeLast('/') + "/")
        return parseM3u8MasterToVideos(
            masterUrl = masterUrl,
            masterPlaylist = master.body,
            labelPrefix = labelPrefix(prefix),
            labelSuffix = suffix,
            resolveBase = resolveBase,
        )
    }

    private suspend fun extractLabelled(playlist: String, prefix: String, suffix: String): List<DbVideo> {
        // Original Flutter source slices on `"label":"` repeatedly. We mirror
        // the pattern but use a tighter regex over the JSON envelope so we
        // don't double-slice between label/file pairs.
        val pairs = ENTRY_REGEX.findAll(playlist).toList()
        if (pairs.isEmpty()) return emptyList()
        val videos = mutableListOf<DbVideo>()
        for (match in pairs) {
            val label = match.groupValues[1]
            val apiUrl = match.groupValues[2].replace("\\", "")
            val mp4 = http.request(HttpRequest(apiUrl, method = "POST"))
            if (mp4.statusCode !in 200..299) continue
            // The Flutter implementation reads the post-redirect URL — we
            // don't expose that, so reuse the API URL as the playable handle.
            // Most Streamlare hosts return playable mp4 from the same URL.
            val quality = buildString {
                if (prefix.isNotBlank()) append(prefix).append(' ')
                append("Streamlare:$label")
                if (suffix.isNotBlank()) append(' ').append(suffix)
            }
            videos += DbVideo(url = apiUrl, quality = quality, originalUrl = apiUrl)
        }
        return videos
    }

    private fun labelPrefix(prefix: String): String = buildString {
        if (prefix.isNotBlank()) append(prefix).append(' ')
        append("Streamlare:")
    }

    private companion object {
        const val API_ENDPOINT = "https://slwatch.co/api/video/stream/get"
        // Captures `"label":"<lbl>",…,"file":"<url>"` pairs in either order.
        val ENTRY_REGEX = Regex(""""label"\s*:\s*"([^"]+)"[^}]*?"file"\s*:\s*"([^"]+)"""")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VidBomExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VidBomExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VidBomExtractor.kt).

The implementation below defines `VidBomExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> VidBom (and VidShare) embed extractor. The player exposes its `sources: \[ { file: "…", label: "…" }, … \]` block inside a `\<script\>` tag. We slice the block out and split on `file:"` to iterate the entries. The Flutter source keys VidShare off "the label longer than 15 characters" — we preserve that quirk because it's what shipped sources rely on.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * VidBom (and VidShare) embed extractor.
 *
 * The player exposes its `sources: [ { file: "…", label: "…" }, … ]` block
 * inside a `<script>` tag. We slice the block out and split on `file:"` to
 * iterate the entries.
 *
 * The Flutter source keys VidShare off "the label longer than 15 characters"
 * — we preserve that quirk because it's what shipped sources rely on.
 */
class VidBomExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "vidbom"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url) }

    private suspend fun videosFromUrl(url: String): List<DbVideo> {
        val response = http.request(HttpRequest(url))
        if (response.statusCode !in 200..299) return emptyList()
        val script = ScriptTagRegex.findAll(response.body)
            .map { it.groupValues[1] }
            .firstOrNull { it.contains("sources") } ?: return emptyList()
        val block = script
            .substringAfter("sources: [", "")
            .substringBefore("],", "")
        if (block.isBlank()) return emptyList()
        return block.split("file:\"").drop(1).mapNotNull { entry ->
            val src = entry.substringBefore("\"", "")
            if (src.isBlank()) return@mapNotNull null
            val rawLabel = entry.substringAfter("label:\"", "").substringBefore("\"", "")
            val quality = if (rawLabel.length > 15) "Vidshare - 480p" else "Vidbom - $rawLabel"
            DbVideo(url = src, quality = quality, originalUrl = src)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VoeExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VoeExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/VoeExtractor.kt).

The implementation below defines `VoeExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> Voe embed extractor. Voe ships several script shapes that all end at an HLS master URL. We mirror the Flutter implementation's branch logic: - If the page contains a localStorage-stamp redirect script, we follow `window.location.href = '…'` once and re-parse. - If the script contains `sources` / `'hls'`, the master URL is inlined (sometimes raw, sometimes base64-encoded with no scheme). - Otherwise the player uses the `wc0` flow: pull the only `'…'` literal out of the script, base64-decode it, then read the JSON `file` field. A handful of newer scripts ship the JSON reversed — alternativeScript branch covers that. Then we fetch the master playlist and emit one \[DbVideo\] per variant.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

/**
 * Voe embed extractor.
 *
 * Voe ships several script shapes that all end at an HLS master URL. We
 * mirror the Flutter implementation's branch logic:
 *
 *   - If the page contains a localStorage-stamp redirect script, we follow
 *     `window.location.href = '…'` once and re-parse.
 *   - If the script contains `sources` / `'hls'`, the master URL is inlined
 *     (sometimes raw, sometimes base64-encoded with no scheme).
 *   - Otherwise the player uses the `wc0` flow: pull the only `'…'` literal
 *     out of the script, base64-decode it, then read the JSON `file` field.
 *     A handful of newer scripts ship the JSON reversed — alternativeScript
 *     branch covers that.
 *
 * Then we fetch the master playlist and emit one [DbVideo] per variant.
 */
class VoeExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "voe"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, prefix = null) }

    @OptIn(ExperimentalEncodingApi::class)
    private suspend fun videosFromUrl(url: String, prefix: String? = null): List<DbVideo> {
        val initial = http.request(HttpRequest(url))
        var body = initial.body
        // Handle the localStorage redirect Voe sometimes ships.
        val firstScript = ScriptTagRegex.find(body)?.groupValues?.get(1).orEmpty()
        if (firstScript.contains("if (typeof localStorage !== 'undefined')")) {
            val redirect = firstScript.substringAfter("window.location.href = '", "")
                .substringBefore("';", "")
            if (redirect.isNotBlank()) {
                body = http.request(HttpRequest(redirect)).body
            }
        }

        val scripts = ScriptTagRegex.findAll(body).map { it.groupValues[1] }.toList()
        val primaryScript = scripts.firstOrNull { s ->
            s.contains("const sources") || s.contains("var sources") || s.contains("wc0")
        }
        // "Alternative" payload — a let/var assigned to a base64 string literal.
        val alternativeScripts = scripts.filter { BASE64_VAR_REGEX.containsMatchIn(it) }
        val script = primaryScript ?: alternativeScripts.firstOrNull() ?: return emptyList()

        val playlistUrl = when {
            script.contains("sources") -> {
                val raw = script.substringAfter("hls': '", "").substringBefore("'", "")
                if (raw.startsWith("http", ignoreCase = true)) raw
                else runCatching { Base64.decode(raw).decodeToString() }.getOrNull().orEmpty()
            }
            script.contains("wc0") || primaryScript == null -> {
                val literal = SINGLE_QUOTED_REGEX.find(script)?.value
                    ?.removePrefix("'")?.removeSuffix("'")
                    ?: return emptyList()
                val decoded = runCatching { Base64.decode(literal).decodeToString() }.getOrNull()
                    ?: return emptyList()
                // The alternative shape stores the JSON reversed.
                val maybeJson = if (primaryScript == null) decoded.reversed() else decoded
                FILE_REGEX.find(maybeJson)?.groupValues?.get(1).orEmpty()
            }
            else -> ""
        }
        if (playlistUrl.isBlank()) return emptyList()

        val labelPrefix = listOfNotNull(prefix?.takeIf { it.isNotBlank() }, "Voe:").joinToString(" ")
        return http.m3u8Videos(masterUrl = playlistUrl, labelPrefix = labelPrefix)
    }

    private companion object {
        val BASE64_VAR_REGEX = Regex(
            """(let|var)\s+\w+\s*=\s*'(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)';""",
        )
        // Greedy enough to pick the long base64 literal Voe inlines.
        val SINGLE_QUOTED_REGEX = Regex("""'.*'""")
        val FILE_REGEX = Regex(""""file"\s*:\s*"([^"]+)"""")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/YourUploadExtractor.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/YourUploadExtractor.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/extractors/YourUploadExtractor.kt).

The implementation below defines `YourUploadExtractor`, `extract`, `videosFromUrl`.

The source describes its contract as:

> YourUpload embed extractor. Finds the `jwplayerOptions` script and reads its `file: '…'` literal. YourUpload 403s without `Referer: https://www.yourupload.com/`, which we always set on both the embed fetch and the emitted video headers.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.media.ExtractorResult
import eu.friedcutlet.yokan.services.media.extractVideos

/**
 * YourUpload embed extractor.
 *
 * Finds the `jwplayerOptions` script and reads its `file: '…'` literal.
 * YourUpload 403s without `Referer: https://www.yourupload.com/`, which we
 * always set on both the embed fetch and the emitted video headers.
 */
class YourUploadExtractor(
    private val http: HttpService,
) : AnimeExtractorService {

    override val hostName: String get() = "yourupload"

    override suspend fun extract(url: String, headers: Map<String, String>): ExtractorResult =
        extractVideos(headers) { videosFromUrl(url, headers) }

    private suspend fun videosFromUrl(
        url: String,
        headers: Map<String, String>,
        name: String = "YourUpload",
        prefix: String = "",
    ): List<DbVideo> {
        val merged = headers.toMutableMap().apply { put("referer", REFERER) }
        val response = http.request(HttpRequest(url, headers = merged))
        if (response.statusCode !in 200..299) return emptyList()
        val script = ScriptTagRegex.findAll(response.body)
            .map { it.groupValues[1] }
            .firstOrNull { it.contains("jwplayerOptions") } ?: return emptyList()
        val file = script.substringAfter("file: '", "").substringBefore("',", "")
        if (file.isBlank()) return emptyList()
        val quality = prefix + name
        return listOf(DbVideo(url = file, quality = quality, originalUrl = file, headers = merged))
    }

    private companion object {
        const val REFERER = "https://www.yourupload.com/"
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.android.kt).

The implementation below defines `createPlatformVideoFrameExtractor`.

The source describes its contract as:

> \[MediaMetadataRetriever\] reads file paths and SAF `content://` documents; failures throw (no artwork).

Cross-chapter imports used by this file: [`AndroidAppContext`](../chapters/23-platform-hosts-and-adapters.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.services.blockingDispatcher
import java.io.ByteArrayOutputStream
import kotlinx.coroutines.withContext

/** [MediaMetadataRetriever] reads file paths and SAF `content://` documents; failures throw (no artwork). */
actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = VideoFrameExtractor { url, maxDimension ->
    withContext(blockingDispatcher) {
        val retriever = MediaMetadataRetriever()
        try {
            if (url.startsWith("content://")) {
                retriever.setDataSource(checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }, Uri.parse(url))
            } else {
                // A raw path: Uri decoding would corrupt names containing '%'.
                retriever.setDataSource(url.removePrefix("file://"))
            }
            val durationMs = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
            val timeUs = durationMs * 100 // 10% of the duration, in microseconds
            val frame = if (Build.VERSION.SDK_INT >= 27) {
                retriever.getScaledFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC, maxDimension, maxDimension)
            } else {
                retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)?.let { full ->
                    val scale = minOf(1f, maxDimension.toFloat() / maxOf(full.width, full.height))
                    if (scale >= 1f) full else Bitmap.createScaledBitmap(
                        full, (full.width * scale).toInt().coerceAtLeast(1), (full.height * scale).toInt().coerceAtLeast(1), true,
                    ).also { full.recycle() }
                }
            } ?: return@withContext null
            try {
                ByteArrayOutputStream().use { output ->
                    frame.compress(Bitmap.CompressFormat.JPEG, 85, output)
                    output.toByteArray()
                }
            } finally { frame.recycle() }
        } finally {
            runCatching { retriever.release() }
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.desktop.kt).

The implementation below defines `createPlatformVideoFrameExtractor`, `MpvVideoFrameExtractor`, `extractJpeg`.

The source describes its contract as:

> A headless instance of the player's own libmpv. mpv's software render API scales the frame and Skia encodes it: the media-kit libmpv bundled for macOS/Windows has neither lavfi `scale` nor image encoders, so `screenshot-to-file` fails there. Linux uses the system libmpv; without one, extraction returns null.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md), [`MpvConfiguration`](../chapters/17-kmp-mpv-submodule.md), [`MpvEvent`](../chapters/17-kmp-mpv-submodule.md), [`MpvException`](../chapters/17-kmp-mpv-submodule.md), [`MpvLifecycleEvent`](../chapters/17-kmp-mpv-submodule.md), [`MpvPlayer`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media

import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.logging.AppLogger
import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvEvent
import io.github.kmpmpv.MpvException
import io.github.kmpmpv.MpvLifecycleEvent
import io.github.kmpmpv.MpvPlayer
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.Image
import org.jetbrains.skia.ImageInfo

actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = MpvVideoFrameExtractor()

/**
 * A headless instance of the player's own libmpv. mpv's software render API scales the frame and Skia encodes it:
 * the media-kit libmpv bundled for macOS/Windows has neither lavfi `scale` nor image encoders, so
 * `screenshot-to-file` fails there. Linux uses the system libmpv; without one, extraction returns null.
 */
internal class MpvVideoFrameExtractor(private val timeoutMillis: Long = 20_000) : VideoFrameExtractor {
    override suspend fun extractJpeg(url: String, maxDimension: Int): ByteArray? = withContext(blockingDispatcher) {
        val player = try {
            MpvPlayer.create(MpvConfiguration(options = MpvConfiguration.DefaultOptions + FrameOptions))
        } catch (unavailable: MpvException) {
            AppLogger.warn("[local] libmpv unavailable for video frames: ${unavailable.message.orEmpty()}")
            return@withContext null
        }
        try {
            // vo=libmpv refuses to start a video before its render context exists.
            player.renderSoftwareFrame(1, 1)
            val started = withTimeoutOrNull(timeoutMillis) {
                coroutineScope {
                    val restart = async(start = CoroutineStart.UNDISPATCHED) {
                        player.events.first { it == PlaybackRestart || it is MpvEvent.EndFile }
                    }
                    // mpv percent-decodes file:// URLs; the raw path also opens names containing '%'.
                    player.load(url.removePrefix("file://"))
                    restart.await()
                }
            }
            if (started != PlaybackRestart) return@withContext null
            val width = player.getLongProperty("dwidth")?.takeIf { it > 0 } ?: return@withContext null
            val height = player.getLongProperty("dheight")?.takeIf { it > 0 } ?: return@withContext null
            val scale = minOf(1.0, maxDimension.toDouble() / maxOf(width, height))
            val frame = player.renderSoftwareFrame(
                (width * scale).toInt().coerceAtLeast(1),
                (height * scale).toInt().coerceAtLeast(1),
            )
            val image = Image.makeRaster(
                ImageInfo(frame.width, frame.height, ColorType.BGRA_8888, ColorAlphaType.OPAQUE),
                frame.pixels,
                frame.strideBytes,
            )
            try { image.encodeToData(EncodedImageFormat.JPEG, 85)?.bytes } finally { image.close() }
        } finally {
            player.release()
        }
    }

    private companion object {
        val PlaybackRestart = MpvEvent.Lifecycle(MpvLifecycleEvent.PlaybackRestart)
        val FrameOptions = mapOf(
            "vo" to "libmpv",
            "ao" to "null",
            "audio" to "no",
            "sub" to "no",
            "pause" to "yes",
            "start" to "10%",
            "hr-seek" to "yes",
            "hwdec" to "no",
            "config" to "no",
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.ios.kt).

The implementation below defines `createPlatformVideoFrameExtractor`, `NSData.toByteArray`.

The source describes its contract as:

> AVFoundation decodes inside the folder's security scope (open-in-place and bookmarked folders).

Cross-chapter imports used by this file: [`IosSecurityScopedBookmarks`](../chapters/12-local-library.md). Keep those contracts available as you connect this step.

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

package eu.friedcutlet.yokan.services.media

import eu.friedcutlet.yokan.services.files.IosSecurityScopedBookmarks
import kotlin.coroutines.resume
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.suspendCancellableCoroutine
import platform.AVFoundation.AVAssetImageGenerator
import platform.AVFoundation.AVAssetImageGeneratorSucceeded
import platform.AVFoundation.AVURLAsset
import platform.AVFoundation.valueWithCMTime
import platform.CoreGraphics.CGSizeMake
import platform.CoreMedia.CMTimeGetSeconds
import platform.CoreMedia.CMTimeMakeWithSeconds
import platform.Foundation.NSData
import platform.Foundation.NSURL
import platform.Foundation.NSValue
import platform.UIKit.UIImage
import platform.UIKit.UIImageJPEGRepresentation
import platform.posix.memcpy

/** AVFoundation decodes inside the folder's security scope (open-in-place and bookmarked folders). */
actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = VideoFrameExtractor { url, maxDimension ->
    IosSecurityScopedBookmarks.withAccessAsync(url.removePrefix("file://")) { path ->
        val asset = AVURLAsset.URLAssetWithURL(NSURL.fileURLWithPath(path), options = null)
        val generator = AVAssetImageGenerator.assetImageGeneratorWithAsset(asset).apply {
            appliesPreferredTrackTransform = true
            maximumSize = CGSizeMake(maxDimension.toDouble(), maxDimension.toDouble())
        }
        val seconds = CMTimeGetSeconds(asset.duration).takeIf { it.isFinite() && it > 0 } ?: 0.0
        val time = NSValue.valueWithCMTime(CMTimeMakeWithSeconds(seconds * 0.1, 600))
        suspendCancellableCoroutine<ByteArray?> { continuation ->
            continuation.invokeOnCancellation { generator.cancelAllCGImageGeneration() }
            generator.generateCGImagesAsynchronouslyForTimes(listOf(time)) { _, image, _, result, _ ->
                // The CGImage is only valid inside this handler.
                val bytes = if (result == AVAssetImageGeneratorSucceeded && image != null) {
                    UIImageJPEGRepresentation(UIImage.imageWithCGImage(image), 0.85)?.toByteArray()
                } else null
                if (continuation.isActive) continuation.resume(bytes)
            }
        }
    }
}

private fun NSData.toByteArray(): ByteArray = ByteArray(length.toInt()).also { output ->
    if (output.isNotEmpty()) output.usePinned { memcpy(it.addressOf(0), bytes, length) }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/VideoFrameExtractor.wasm.kt).

The implementation below defines `createPlatformVideoFrameExtractor`, `browserVideoFrame`.

The source describes its contract as:

> A detached muted `\<video\>` reads the same-origin OPFS media-worker URL; a canvas scales the frame and encodes JPEG. Null when the browser cannot decode the container/codec (for example MKV/HEVC in most browsers) or within 20 s. Cancelling the coroutine abandons, but cannot abort, the browser's decode; the timeout bounds it.

```kotlin
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)

package eu.friedcutlet.yokan.services.media

import kotlin.io.encoding.Base64
import kotlin.js.JsString
import kotlin.js.Promise
import kotlinx.coroutines.await

/**
 * A detached muted `<video>` reads the same-origin OPFS media-worker URL; a canvas scales the frame and encodes JPEG.
 * Null when the browser cannot decode the container/codec (for example MKV/HEVC in most browsers) or within 20 s.
 * Cancelling the coroutine abandons, but cannot abort, the browser's decode; the timeout bounds it.
 */
actual fun createPlatformVideoFrameExtractor(): VideoFrameExtractor = VideoFrameExtractor { url, maxDimension ->
    browserVideoFrame(url, maxDimension).await<JsString?>()?.toString()?.let(Base64::decode)
}

private fun browserVideoFrame(url: String, maxDimension: Int): Promise<JsString?> = js("""
    (async () => {
        if (typeof document === 'undefined') return null;
        const video = document.createElement('video');
        video.muted = true; video.preload = 'auto'; video.playsInline = true;
        const next = name => new Promise((resolve, reject) => {
            const done = () => { clearTimeout(timer); video.removeEventListener(name, ok); video.removeEventListener('error', fail); };
            const ok = () => { done(); resolve(); };
            const fail = () => { done(); reject(new Error('The video could not be decoded.')); };
            const timer = setTimeout(() => { done(); reject(new Error('The video frame timed out.')); }, 20000);
            video.addEventListener(name, ok); video.addEventListener('error', fail);
        });
        try {
            const loaded = next('loadeddata');
            video.src = url;
            await loaded;
            const seeked = next('seeked');
            video.currentTime = Number.isFinite(video.duration) ? video.duration * 0.1 : 0;
            await seeked;
            const width = video.videoWidth, height = video.videoHeight;
            if (!width || !height) return null;
            const scale = Math.min(1, maxDimension / Math.max(width, height));
            const canvas = document.createElement('canvas');
            canvas.width = Math.max(1, Math.floor(width * scale));
            canvas.height = Math.max(1, Math.floor(height * scale));
            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.85));
            if (!blob) return null;
            const bytes = new Uint8Array(await blob.arrayBuffer());
            let binary = '';
            for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
            return btoa(binary);
        } catch (_) {
            return null;
        } finally {
            video.removeAttribute('src');
            video.load();
        }
    })()
""")
```
[chapter-file-end]: #

### Check your understanding

Feed controlled host HTML and HLS/VTT fixtures, including relative URLs and missing data. Check that a quality switch cancels obsolete thumbnail/subtitle loads.
[chapter-content-end]: #


## Step 3: implement player UI/state

Build PlayerContract, ViewModel, UI/services bindings, AnimePlayerRoute, owned surface and MediaSurface actuals. Add controls/chrome/dialogs/settings for play/pause, seek, episode navigation, quality, speed presets, volume/brightness, lock/fullscreen and minimized view. Persist resume/history and completion with incognito policy and accurate units. Progress restoration must tolerate initially unknown duration.

Add subtitle selection/language policy, primary/secondary tracks, secondary delay, style and subtitle service. Seek previews parse thumbnail VTT/sprite coordinates and fetch with stream headers; cancel old-stream loads on quality/episode change. Add AniSkip intervals, playback policies, custom mpv buttons/commands and features only on capable backends. Unsupported commands return unsupported, not pretend success.

[chapter-content-start]: #
### Follow the code

The ViewModel receives selected episode/candidate state and sends commands through the captured controller. UI/services bindings keep render state separate from command/native lifetime. PlaybackPolicies contains deterministic pieces: valid speed presets, subtitle blacklist/language/whitelist order, bounded failover and thumbnail selection. Progress/position policy handles unknown duration and resume in app units. Expose backend capability before enabling mpv-only controls.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPolicies.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerContract.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerPositionPolicy.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModel.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerRoute.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurface.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerScreen.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerAddons.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerChrome.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerDialogs.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerServicesBinding.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerSettingsSheet.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBinding.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.android.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.desktop.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.ios.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.ios.kt`
- `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxy.kt`
- `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvMediaPlayerController.kt`
- `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBinding.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.wasm.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPolicies.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPolicies.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPolicies.kt).

Speed presets accept only the shared 0.25–4.0 range and normalize/deduplicate values. Subtitle choice filters blacklisted tracks first, then respects language order and whitelist preference. Thumbnail lookup uses the last starting cue whose end still covers the position.

The implementation below defines `parseSpeedPresets`, `parseTermList`, `preferredSubtitle`, `pick`, `DbVideoTrack.hasTerm`, `DbVideoTrack.isLanguage`, `nextFailoverVideo`, `SleepTimer`, `SleepTimer.isDue`, `SeekThumbnail` and 4 further declarations.

The source describes its contract as:

> Parses a comma-separated preset list; null when empty or any value is invalid.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md), [`languageName`](../chapters/06-extension-runtimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.extensions.languageName
import kotlin.math.roundToInt

/** Range accepted by both player backends. */
val PlaybackSpeedRange: ClosedFloatingPointRange<Double> = 0.25..4.0

/** Parses a comma-separated preset list; null when empty or any value is invalid. */
fun parseSpeedPresets(text: String): List<Double>? {
    val values = text.split(',', ';', ' ').map(String::trim).filter(String::isNotEmpty).map { token ->
        token.removeSuffix("x").removePrefix("x").toDoubleOrNull()?.takeIf { it in PlaybackSpeedRange } ?: return null
    }
    return values.map { (it * 100).roundToInt() / 100.0 }.distinct().sorted().ifEmpty { null }
}

/** Splits a comma-separated preference into its trimmed, non-empty terms. */
fun parseTermList(text: String): List<String> = text.split(',').map(String::trim).filter(String::isNotEmpty).distinct()

/**
 * Auto-selected subtitle: blacklisted tracks are never chosen; the first [languages] entry that has
 * an allowed track wins, preferring whitelisted names. Without a language match the first allowed
 * track is used, as before languages were configurable.
 */
fun preferredSubtitle(
    tracks: List<DbVideoTrack>,
    languages: List<String>,
    whitelist: List<String> = emptyList(),
    blacklist: List<String> = emptyList(),
): DbVideoTrack? {
    val allowed = tracks.filter { track -> !track.file.isNullOrBlank() && blacklist.none { track.hasTerm(it) } }
    fun pick(candidates: List<DbVideoTrack>) =
        candidates.firstOrNull { track -> whitelist.any { track.hasTerm(it) } } ?: candidates.firstOrNull()
    return languages.firstNotNullOfOrNull { language -> pick(allowed.filter { it.isLanguage(language) }) } ?: pick(allowed)
}

private fun DbVideoTrack.hasTerm(term: String): Boolean =
    label.orEmpty().contains(term, ignoreCase = true) || file.orEmpty().contains(term, ignoreCase = true)

private fun DbVideoTrack.isLanguage(language: String): Boolean {
    val text = label.orEmpty().ifBlank { file.orEmpty() }
    val code = language.trim().lowercase()
    if (code.isEmpty()) return false
    val name = languageName(code).substringBefore(" (")
    return Regex("\\b${Regex.escape(code)}\\b", RegexOption.IGNORE_CASE).containsMatchIn(text) ||
        (name.length > 3 && text.contains(name, ignoreCase = true))
}

/** The next stream to try after [failedUrls] failed; each stream is tried once, so failover terminates. */
fun nextFailoverVideo(videos: List<DbVideo>, failedUrls: Set<String>): DbVideo? = videos.firstOrNull { it.url !in failedUrls }

/** A pending sleep timer: a wall-clock [deadlineMs], or the end of the current episode when null. */
data class SleepTimer(val deadlineMs: Long?)

fun SleepTimer.isDue(nowMs: Long, positionMs: Long, durationMs: Long): Boolean =
    deadlineMs?.let { nowMs >= it } ?: (durationMs > 0L && positionMs >= durationMs - 500L)

/** One seek-preview tile: [imageUrl] cropped to x/y/width/height (width 0 = whole image). */
data class SeekThumbnail(
    val startMs: Long,
    val endMs: Long,
    val imageUrl: String,
    val x: Int = 0,
    val y: Int = 0,
    val width: Int = 0,
    val height: Int = 0,
)

/** Parses a WebVTT thumbnail track (`sprite.jpg#xywh=0,0,160,90` cues); relative URLs resolve against [baseUrl]. */
fun parseThumbnailVtt(content: String, baseUrl: String): List<SeekThumbnail> {
    val lines = content.replace("\r\n", "\n").replace('\r', '\n').lines()
    val result = mutableListOf<SeekThumbnail>()
    for ((index, line) in lines.withIndex()) {
        if ("-->" !in line) continue
        val start = parseVttTime(line.substringBefore("-->")) ?: continue
        val end = parseVttTime(line.substringAfter("-->").trim().substringBefore(' ')) ?: continue
        val target = lines.getOrNull(index + 1)?.trim().orEmpty()
        if (target.isEmpty()) continue
        val image = resolveUrl(baseUrl, target.substringBefore("#xywh="))
        val box = target.substringAfter("#xywh=", "").split(',').mapNotNull { it.trim().toIntOrNull() }
        result += if (box.size == 4 && box[2] > 0 && box[3] > 0 && box[0] >= 0 && box[1] >= 0) {
            SeekThumbnail(start, end, image, box[0], box[1], box[2], box[3])
        } else {
            SeekThumbnail(start, end, image)
        }
    }
    return result.sortedBy { it.startMs }
}

/** The tile shown at [positionMs]: the last cue starting at or before it, within its end time. */
fun List<SeekThumbnail>.at(positionMs: Long): SeekThumbnail? {
    var low = 0
    var high = lastIndex
    var found: SeekThumbnail? = null
    while (low <= high) {
        val mid = (low + high) ushr 1
        if (this[mid].startMs <= positionMs) { found = this[mid]; low = mid + 1 } else high = mid - 1
    }
    return found?.takeIf { positionMs < it.endMs }
}

private fun parseVttTime(text: String): Long? {
    val parts = text.trim().split(':')
    if (parts.size !in 2..3) return null
    val seconds = parts.last().replace(',', '.').toDoubleOrNull() ?: return null
    val minutes = parts[parts.size - 2].toLongOrNull() ?: return null
    val hours = if (parts.size == 3) parts[0].toLongOrNull() ?: return null else 0L
    return (hours * 3_600_000L) + (minutes * 60_000L) + (seconds * 1000).roundToInt()
}

private fun resolveUrl(base: String, reference: String): String {
    if (Regex("^[a-zA-Z][a-zA-Z0-9+.-]*:").containsMatchIn(reference)) return reference
    val scheme = base.substringBefore("://", "")
    if (reference.startsWith("//")) return "${scheme.ifEmpty { "https" }}:$reference"
    val withoutQuery = base.substringBefore('?').substringBefore('#')
    if (reference.startsWith("/")) {
        val origin = if (scheme.isEmpty()) "" else "$scheme://" + withoutQuery.substringAfter("://").substringBefore('/')
        return origin + reference
    }
    val directory = withoutQuery.substringBeforeLast('/', "")
    return if (directory.isEmpty()) reference else "$directory/$reference"
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerContract.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerContract.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerContract.kt).

The implementation below defines `PlayerState`, `PlayerEvent`, `SwitchEpisode`, `SavePosition`, `LoadSeekSprite`, `SelectVideo`, `PlaybackFailed`, `OpenExternalPlayer`, `SetCastDiscovery`, `StartCasting` and 10 further declarations.

The source describes its contract as:

> Selected releases in the title's sort order, retaining the opened alternate.

Cross-chapter imports used by this file: [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.ui.graphics.ImageBitmap
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.media.AniSkipMarker
import eu.friedcutlet.yokan.services.media.cast.CastDevice
import eu.friedcutlet.yokan.services.media.cast.CastStatus
import eu.friedcutlet.yokan.services.media.player.SeekThumbnail

internal data class PlayerState(
    /** Selected releases in the title's sort order, retaining the opened alternate. */
    val episodes: List<Chapter> = emptyList(),
    /** The episode list dialog: the title's filters applied. */
    val visibleEpisodes: List<Chapter> = emptyList(),
    val customButtons: List<DbCustomButton> = emptyList(),
    /** Streams of this episode in the source's order. */
    val videos: List<DbVideo> = emptyList(),
    /** The stream the controller plays; null while loading, without streams, or after an external handoff. */
    val selectedVideo: DbVideo? = null,
    val loading: Boolean = true,
    val error: String? = null,
    /** Where [selectedVideo] starts when the controller loads it, and whether it plays at once. */
    val startPositionMs: Long = 0L,
    val autoplay: Boolean = true,
    val aniSkipMarkers: List<AniSkipMarker> = emptyList(),
    /** Seek-preview tiles of the selected stream, sorted by start time. */
    val seekThumbnails: List<SeekThumbnail> = emptyList(),
    /** Decoded sprite sheets by URL, loaded on first use while seeking. */
    val seekSprites: Map<String, ImageBitmap> = emptyMap(),
    /** Null when no cast session is active. */
    val castStatus: CastStatus? = null,
    val castSupported: Boolean = false,
    /** The platform shows its own device picker, so casting starts without [castDevices]. */
    val castUsesSystemPicker: Boolean = false,
    val castDevices: List<CastDevice> = emptyList(),
)

internal sealed interface PlayerEvent {
    /** Opens the episode [offset] steps away in title order, when there is one. */
    data class SwitchEpisode(val offset: Int) : PlayerEvent
    data class SavePosition(val positionMs: Long, val durationMs: Long) : PlayerEvent
    data class LoadSeekSprite(val url: String) : PlayerEvent
    /** A quality change: [video] continues from [startPositionMs]. */
    data class SelectVideo(val video: DbVideo, val startPositionMs: Long, val autoplay: Boolean) : PlayerEvent
    /** The controller reported [error] at [positionMs]; fails over to the next stream when enabled. */
    data class PlaybackFailed(val error: String, val positionMs: Long) : PlayerEvent
    data class OpenExternalPlayer(val video: DbVideo) : PlayerEvent
    data class SetCastDiscovery(val active: Boolean) : PlayerEvent
    /** Casts the episode from [startPositionMs], then queues the following episodes. */
    data class StartCasting(val device: CastDevice?, val startPositionMs: Long, val subtitleFile: String?) : PlayerEvent
    data object StopCasting : PlayerEvent
    data object CastPlayPause : PlayerEvent
    data class CastSeek(val positionMs: Long) : PlayerEvent
    data object CastPrevious : PlayerEvent
    data object CastNext : PlayerEvent
    data class CastJumpTo(val index: Int) : PlayerEvent
}

internal sealed interface PlayerEffect {
    data class ShowNotice(val text: String) : PlayerEffect
    /** The episode plays in an external player instead. */
    data object Exit : PlayerEffect
    data class OpenEpisode(val episode: Chapter) : PlayerEffect
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerPositionPolicy.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerPositionPolicy.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerPositionPolicy.kt).

The implementation below defines `savedVideoPositionMs`, `shouldSaveVideoPosition`, `isVideoPositionComplete`, `VideoHandoff`, `qualityVideoHandoff`.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

internal fun savedVideoPositionMs(
    lastPageRead: String,
    isRead: Boolean,
    incognitoMode: Boolean,
): Long {
    if (isRead || incognitoMode) return 0L
    return lastPageRead.toLongOrNull()?.coerceAtLeast(0L) ?: 0L
}

internal fun shouldSaveVideoPosition(
    isRead: Boolean,
    incognitoMode: Boolean,
    positionMs: Long,
): Boolean = !isRead && !incognitoMode && positionMs > 0L

internal fun isVideoPositionComplete(
    positionMs: Long,
    durationMs: Long,
    seenThresholdPercent: Int,
): Boolean {
    if (durationMs <= 0L || positionMs <= 0L) return false
    val percent = ((positionMs.toDouble() / durationMs.toDouble()) * 100.0)
        .toInt().coerceIn(0, 100)
    return percent >= seenThresholdPercent
}

internal data class VideoHandoff(
    val startPositionMs: Long,
    val autoplay: Boolean,
)

internal fun qualityVideoHandoff(currentPositionMs: Long, isPlaying: Boolean): VideoHandoff =
    VideoHandoff(currentPositionMs.coerceAtLeast(0L), isPlaying)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModel.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModel.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModel.kt).

Read episode/quality loading, command preparation and final progress together. Captured identity and cancellation guards prevent a response from an old stream from changing the current player.

The implementation below defines `playerEpisodeSequence`, `PlayerViewModel`, `onCleared`, `onEvent`, `adjacentEpisode`, `savePosition`, `loadStreams`, `selectVideo`, `failOver`, `loadAniSkipMarkers` and 9 further declarations.

The source describes its contract as:

> Player ordering stays user-controlled while release selection matches the readers.

Cross-chapter imports used by this file: [`LibraryIndexStore`](../chapters/09-repository-and-library.md), [`SettingsStore`](../chapters/09-repository-and-library.md), [`YokanRepository`](../chapters/09-repository-and-library.md), [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`DbVideo`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.isIncognitoFor
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ChapterRecognition
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionLogger
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.library.readingChapterSequence
import eu.friedcutlet.yokan.services.library.sortedChapters
import eu.friedcutlet.yokan.services.library.visibleChapters
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.services.media.AniSkipMarker
import eu.friedcutlet.yokan.services.media.cast.CastController
import eu.friedcutlet.yokan.services.media.player.externalPlayerChoices
import eu.friedcutlet.yokan.services.media.player.nextFailoverVideo
import eu.friedcutlet.yokan.services.media.player.parseThumbnailVtt
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.decodeToImageBitmap

/** Player ordering stays user-controlled while release selection matches the readers. */
internal fun playerEpisodeSequence(
    manga: Manga,
    currentChapterId: Long,
    all: List<Chapter>,
    db: DbSettings,
    downloadedIds: Set<Long>,
): List<Chapter> = sortedChapters(
    manga, readingChapterSequence(manga, currentChapterId, all, db, downloadedIds), db,
)

/**
 * The player's streams, library reads, progress writes, AniSkip markers and casting. Work that
 * needs the media controller (loading it, tracks, chrome, screenshots) stays in [AnimePlayerScreen].
 */
internal class PlayerViewModel(
    private val manga: Manga,
    private val chapter: Chapter,
    private val repository: YokanRepository,
    private val settings: SettingsStore,
    libraryIndex: LibraryIndexStore,
    private val http: HttpService,
    private val loadVideos: suspend (Source?, Chapter) -> List<DbVideo>,
    private val aniSkipMarkers: suspend (malId: Long, episode: Int) -> List<AniSkipMarker>,
    /** Hands [DbVideo] to the external player `playerId` (blank: the platform default); false when none opened. */
    private val openExternalPlayer: (video: DbVideo, playerId: String) -> Boolean,
    private val cast: CastController,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    // ponytail: sprites stay decoded for the stream's lifetime; a few sheets per episode in practice.
    private var streamScope = newStreamScope()
    private var streamHeaders: Map<String, String> = emptyMap()
    private val spriteRequests = mutableSetOf<String>()
    /** Streams of this episode that failed; failover tries each remaining one once. */
    private val failedStreams = mutableSetOf<String>()
    private val source: Source? = manga.sourceId?.let(repository::source)
        ?: repository.sources(manga.itemType).firstOrNull {
            it.name.equals(manga.source, ignoreCase = true) && it.lang.equals(manga.lang, ignoreCase = true)
        }

    private val _state = MutableStateFlow(
        PlayerState(
            startPositionMs = savedVideoPositionMs(
                lastPageRead = chapter.lastPageRead,
                isRead = chapter.isRead,
                incognitoMode = settings.db.value.isIncognitoFor(manga.sourceId),
            ),
            castUsesSystemPicker = cast.usesSystemPicker,
        ),
    )
    val state: StateFlow<PlayerState> = _state.asStateFlow()

    private val _effects = Channel<PlayerEffect>(Channel.BUFFERED)
    val effects: Flow<PlayerEffect> = _effects.receiveAsFlow()

    init {
        repository.chapterOpened(chapter.id)
        viewModelScope.launch {
            combine(libraryIndex.index, settings.db) { index, db ->
                val all = index.chapters(manga.id)
                playerEpisodeSequence(manga, chapter.id, all, db, index.downloadedChapterIds) to
                    visibleChapters(manga, all, db, index.downloadedChapterIds)
            }
                .flowOn(workDispatcher)
                .collect { (episodes, visible) -> _state.update { it.copy(episodes = episodes, visibleEpisodes = visible) } }
        }
        viewModelScope.launch {
            repository.snapshots
                .map { it.customButtons }
                .distinctUntilChanged()
                .collect { buttons -> _state.update { it.copy(customButtons = buttons.sortedBy(DbCustomButton::position)) } }
        }
        viewModelScope.launch {
            combine(cast.status, cast.isSupported, cast.devices) { status, supported, devices ->
                Triple(status, supported, devices)
            }.collect { (status, supported, devices) ->
                _state.update { it.copy(castStatus = status, castSupported = supported, castDevices = devices) }
            }
        }
        viewModelScope.launch { loadStreams() }
        viewModelScope.launch { loadAniSkipMarkers() }
    }

    override fun onCleared() {
        repository.chapterClosed(chapter.id)
        super.onCleared()
    }

    fun onEvent(event: PlayerEvent) {
        when (event) {
            is PlayerEvent.SwitchEpisode -> adjacentEpisode(event.offset)?.let { _effects.trySend(PlayerEffect.OpenEpisode(it)) }
            is PlayerEvent.SavePosition -> savePosition(event.positionMs, event.durationMs)
            is PlayerEvent.LoadSeekSprite -> loadSeekSprite(event.url)
            is PlayerEvent.SelectVideo -> selectVideo(event.video, event.startPositionMs, event.autoplay)
            is PlayerEvent.PlaybackFailed -> failOver(event.error, event.positionMs)
            // Launched: proxying through a retired reader throws CancellationException.
            is PlayerEvent.OpenExternalPlayer -> viewModelScope.launch {
                openExternalPlayer(event.video, settings.db.value.features.player.externalPlayer)
            }
            is PlayerEvent.SetCastDiscovery -> if (event.active) cast.startDiscovery() else cast.stopDiscovery()
            is PlayerEvent.StartCasting -> startCasting(event)
            PlayerEvent.StopCasting -> viewModelScope.launch { catchingNonCancellation { cast.disconnect() } }
            PlayerEvent.CastPlayPause -> if (state.value.castStatus?.playing == true) cast.pause() else cast.play()
            is PlayerEvent.CastSeek -> cast.seekTo(event.positionMs)
            PlayerEvent.CastPrevious -> cast.previous()
            PlayerEvent.CastNext -> cast.next()
            is PlayerEvent.CastJumpTo -> cast.jumpTo(event.index)
        }
    }

    /** The episode [offset] steps from the current one in title order, or null past either end. */
    private fun adjacentEpisode(offset: Int): Chapter? {
        val all = state.value.episodes
        val index = all.indexOfFirst { it.id == chapter.id }
        return if (index < 0) null else all.getOrNull(index + offset)
    }

    /** Persists the watched position on leave so History resumes mid-episode. */
    private fun savePosition(positionMs: Long, durationMs: Long) {
        val db = settings.db.value
        if (!shouldSaveVideoPosition(chapter.isRead, db.isIncognitoFor(manga.sourceId), positionMs)) return
        repository.setChaptersRead(
            chapterIds = setOf(chapter.id),
            isRead = isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType),
            lastPageRead = positionMs.toString(),
            // Anime watch time is tracked elsewhere; counting it on every exit would inflate the stat.
            readingTimeSeconds = 0,
        )
        if (isVideoPositionComplete(positionMs, durationMs, db.markEpisodeAsSeenType)) repository.recordChapterConsumption(setOf(chapter.id))
    }

    private suspend fun loadStreams() {
        val startedAt = nowMillis()
        AppLogger.info(
            "Episode load start mangaId=${manga.id} manga='${manga.name}' chapterId=${chapter.id} " +
                "chapter='${chapter.name}' source=${source?.name ?: "unknown"} url=${redactUrlForLog(chapter.url)}",
        )
        var error: String? = null
        val videos = catchingNonCancellation { loadEpisodeVideos(chapter) }
            .onFailure { throwable ->
                error = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }
                AppLogger.error("Episode load failed chapterId=${chapter.id}: ${error.orEmpty()}")
            }
            .getOrElse { emptyList() }
        if (videos.isEmpty() && error == null) {
            error = "No streams were returned by ${source?.name ?: "this source"}."
            AppLogger.warn("Episode load returned no streams chapterId=${chapter.id}")
        }
        val first = videos.firstOrNull()
        val preferences = settings.db.value.features.player
        if (first != null && preferences.alwaysUseExternalPlayer && externalPlayerChoices().isNotEmpty()) {
            if (openExternalPlayer(first, preferences.externalPlayer)) {
                _state.update { it.copy(videos = videos, loading = false) }
                _effects.send(PlayerEffect.Exit)
                return
            }
            error = "The external player could not be opened; playing here instead."
        }
        _state.update { it.copy(videos = videos, error = error, loading = false) }
        selectVideo(first, state.value.startPositionMs, autoplay = true)
        AppLogger.info(
            "Episode load complete chapterId=${chapter.id} streams=${videos.size} " +
                "qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}",
        )
    }

    private fun selectVideo(video: DbVideo?, startPositionMs: Long, autoplay: Boolean) {
        val previous = state.value.selectedVideo
        _state.update { it.copy(selectedVideo = video, startPositionMs = startPositionMs, autoplay = autoplay) }
        if (video == null) return
        val index = state.value.videos.indexOf(video).takeIf { it >= 0 }
        AppLogger.info(
            "Episode player handoff mangaId=${manga.id} chapterId=${chapter.id} " +
                "source=${source?.name ?: "unknown"} stream=${video.playerLogSummary(index)}",
        )
        if (video != previous) loadSeekThumbnails(video)
    }

    /** Each failed stream is recorded once, so switching stops when every stream failed. */
    private fun failOver(error: String, positionMs: Long) {
        val failed = state.value.selectedVideo ?: return
        failedStreams += failed.url
        val next = if (settings.db.value.features.player.switchStreamOnFailure) {
            nextFailoverVideo(state.value.videos, failedStreams)
        } else {
            null
        }
        if (next == null) {
            _effects.trySend(PlayerEffect.ShowNotice("Playback failed: $error"))
            return
        }
        AppLogger.warn("[player] stream failed ($error); switching to ${next.quality}")
        _effects.trySend(PlayerEffect.ShowNotice("Stream failed; switching to ${next.quality.ifBlank { "the next stream" }}"))
        selectVideo(next, positionMs.takeIf { it > 0L } ?: state.value.startPositionMs, autoplay = true)
    }

    private suspend fun loadAniSkipMarkers() {
        val malId = malId(repository.tracks())
        // ChapterRecognition matches Mangayomi's parser, so "Episode 12 - Recovery point" yields 12;
        // naive digit-stripping returned 1212, which AniSkip rejected with HTTP 404.
        val episode = ChapterRecognition.parseEpisodeNumber(manga.name, chapter).toInt()
        settings.db.map { it.enableAniSkip == true }.distinctUntilChanged().collectLatest { enabled ->
            _state.update { it.copy(aniSkipMarkers = emptyList()) }
            if (!enabled || malId <= 0 || episode <= 0) return@collectLatest
            val markers = catchingNonCancellation { aniSkipMarkers(malId, episode) }.getOrDefault(emptyList())
            _state.update { it.copy(aniSkipMarkers = markers) }
        }
    }

    private fun startCasting(event: PlayerEvent.StartCasting) {
        val current = state.value
        val video = current.selectedVideo?.takeIf { it.isCastable() } ?: current.videos.firstOrNull { it.isCastable() }
        if (video == null) {
            _effects.trySend(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast"))
            return
        }
        viewModelScope.launch {
            try {
                cast.connect(event.device)
                val subtitleIndex = video.subtitles.filter { it.file != null }
                    .indexOfFirst { it.file == event.subtitleFile }.takeIf { it >= 0 }
                cast.loadQueue(
                    listOf(video.toCastMedia(manga, chapter)), 0, event.startPositionMs,
                    settings.db.value.playerSubtitleSettings.toCastTextStyle(), subtitleIndex,
                )
                // Queue the following episodes as their streams resolve; extraction is per-episode work.
                val following = state.value.episodes.dropWhile { it.id != chapter.id }.drop(1).take(CastQueueAhead)
                for (episode in following) {
                    val next = catchingNonCancellation { loadEpisodeVideos(episode) }
                        .getOrNull()?.firstOrNull { it.isCastable() } ?: continue
                    cast.append(listOf(next.toCastMedia(manga, episode)))
                }
            } catch (cancelled: CancellationException) {
                throw cancelled
            } catch (failure: Throwable) {
                AppLogger.error("[cast] start failed: ${failure.message.orEmpty()}")
                _effects.send(
                    PlayerEffect.ShowNotice("Casting failed: ${failure.message.orEmpty().ifBlank { failure::class.simpleName.orEmpty() }}"),
                )
            }
        }
    }

    /** One selected stream's preview loads, cancelled together on the next selection or [onCleared]. */
    private fun newStreamScope() =
        CoroutineScope(viewModelScope.coroutineContext + SupervisorJob(viewModelScope.coroutineContext.job))

    /** Replaces the seek-preview track with [video]'s; earlier stream loads are cancelled. */
    private fun loadSeekThumbnails(video: DbVideo) {
        streamScope.cancel()
        streamScope = newStreamScope()
        spriteRequests.clear()
        _state.update { it.copy(seekThumbnails = emptyList(), seekSprites = emptyMap()) }
        val track = video.thumbnailTrack?.takeIf(String::isNotBlank) ?: return
        streamHeaders = video.headers.orEmpty()
        streamScope.launch {
            val content = fetch(track)?.decodeToString() ?: return@launch
            val cues = withContext(workDispatcher) { parseThumbnailVtt(content, track) }
            _state.update { it.copy(seekThumbnails = cues) }
        }
    }

    /** Loads a sprite sheet once per stream; failures are logged and not retried. */
    private fun loadSeekSprite(url: String) {
        if (!spriteRequests.add(url)) return
        streamScope.launch {
            val bytes = fetch(url) ?: return@launch
            val image = withContext(workDispatcher) {
                catchingNonCancellation { bytes.decodeToImageBitmap() }.getOrNull()
            } ?: return@launch AppLogger.warn("[player] undecodable seek sprite")
            _state.update { it.copy(seekSprites = it.seekSprites + (url to image)) }
        }
    }

    private suspend fun fetch(url: String): ByteArray? {
        val response = catchingNonCancellation { http.request(HttpRequest(url, headers = streamHeaders)) }
            .onFailure { AppLogger.warn("[player] seek preview request failed: ${it.message.orEmpty()}") }
            .getOrNull() ?: return null
        if (response.statusCode !in 200..299) {
            AppLogger.warn("[player] seek preview request returned HTTP ${response.statusCode}")
            return null
        }
        return response.bodyBytes
    }

    private fun malId(tracks: List<Track>): Long {
        val titleTracks = tracks.filter { it.mangaId == manga.id }
        if (titleTracks.none { it.itemType == manga.itemType }) return 0L
        return titleTracks.firstOrNull { it.syncId == 1 }?.mediaId ?: 0L
    }

    private suspend fun loadEpisodeVideos(episode: Chapter): List<DbVideo> {
        val titleSource = source ?: run {
            AppLogger.warn("Episode videoList skipped: no source chapterId=${episode.id} url=${redactUrlForLog(episode.url)}")
            return loadVideos(null, episode)
        }
        ExtensionLogger.log(
            titleSource.name,
            "videoList start sourceId=${titleSource.id} lang=${titleSource.lang} runtime=${titleSource.sourceCodeLanguage} " +
                "chapterId=${episode.id} url=${redactUrlForLog(episode.url)}",
        )
        val startedAt = nowMillis()
        // Unlike pages and details, videos have no database-backed cache, so there is no fallback:
        // do not pass a failed extension's HTML episode page to the media player.
        return catchingNonCancellation { loadVideos(titleSource, episode) }
            .onSuccess { videos ->
                ExtensionLogger.log(
                    titleSource.name,
                    "videoList returned count=${videos.size} qualities=${videos.qualityLogSummary()} elapsedMs=${nowMillis() - startedAt}",
                )
            }
            .onFailure { ExtensionLogger.error(titleSource.name, "videoList", it) }
            .getOrThrow()
    }
}

/** Following episodes resolved and appended to a new cast queue. */
private const val CastQueueAhead = 2

private fun DbVideo.playerLogSummary(index: Int?): String {
    val indexPart = index?.let { "index=$it " }.orEmpty()
    return "${indexPart}quality='${quality.ifBlank { "Auto" }}' url=${redactUrlForLog(url)} " +
        "original=${redactUrlForLog(originalUrl)} headers=${headers?.size ?: 0} subtitles=${subtitles.size} audios=${audios.size}"
}

private fun List<DbVideo>.qualityLogSummary(limit: Int = 8): String {
    if (isEmpty()) return "none"
    val base = take(limit).joinToString(prefix = "[", postfix = "]") { it.quality.ifBlank { "Auto" } }
    return if (size > limit) "$base +${size - limit} more" else base
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerRoute.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerRoute.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerRoute.kt).

The implementation below defines `AnimePlayerRoute`.

The source describes its contract as:

> Route boundary for the anime player: resolves \[PlayerViewModel\], wires navigation and shows its notices.

Cross-chapter imports used by this file: [`ProfileSession`](../chapters/04-profiles-and-lifetimes.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`Navigator`](../chapters/10-navigation-and-design-system.md), [`Route`](../chapters/10-navigation-and-design-system.md), [`SettingsPage`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.media.player.launchExternalPlayer
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.screens.together.TogetherPlaybackSync
import eu.friedcutlet.yokan.ui.screens.together.rememberOpenRoomMedia
import kotlinx.coroutines.delay

/** Route boundary for the anime player: resolves [PlayerViewModel], wires navigation and shows its notices. */
@Composable
internal fun AnimePlayerRoute(manga: Manga, chapter: Chapter, nav: Navigator, owner: ProfileSession) {
    val viewModel = viewModel {
        // The ViewModel's own reader: AniSkip and external-player proxying outlive the composition's controller.
        val services = owner.playerServices.reader()
        PlayerViewModel(
            manga,
            chapter,
            owner.repository,
            owner.settings,
            owner.libraryIndex,
            owner.services.http,
            loadVideos = owner.readerContent::videos,
            aniSkipMarkers = { malId, episode -> services.markers(malId, episode, 0) },
            openExternalPlayer = { video, playerId ->
                val headers = video.headers.orEmpty()
                launchExternalPlayer(services.streamProxy.proxyUrl(video.url, headers), headers, playerId)
            },
            cast = owner.cast,
        ).apply { addCloseable(AutoCloseable(services::retire)) }
    }
    val state by viewModel.state.collectAsStateWithLifecycle()
    val settings by owner.settings.db.collectAsStateWithLifecycle()
    val minimized by nav.playerMinimized.collectAsStateWithLifecycle()
    var notice by remember { mutableStateOf<String?>(null) }
    val openEpisode: (Chapter) -> Unit = { episode -> nav.navigate(Route.Reader(episode.mangaId, episode.id)) }

    val lifecycleOwner = LocalLifecycleOwner.current
    LaunchedEffect(lifecycleOwner, viewModel) {
        lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.effects.collect { effect ->
                when (effect) {
                    is PlayerEffect.ShowNotice -> notice = effect.text
                    PlayerEffect.Exit -> nav.back()
                    is PlayerEffect.OpenEpisode -> openEpisode(effect.episode)
                }
            }
        }
    }
    LaunchedEffect(notice) {
        if (notice == null) return@LaunchedEffect
        delay(2_500)
        notice = null
    }

    val together = remember(owner) { owner.together }
    val onOpenRoomMedia = rememberOpenRoomMedia(owner, nav)
    AnimePlayerScreen(
        manga = manga,
        chapter = chapter,
        state = state,
        settings = settings,
        minimized = minimized,
        notice = notice,
        playerServices = remember(owner) { owner.playerServices },
        onEvent = viewModel::onEvent,
        onNotice = { notice = it },
        onBack = nav::back,
        onRestore = nav::restorePlayer,
        onDismiss = nav::dismissPlayer,
        onMinimize = nav::minimizePlayer,
        onOpenEpisode = openEpisode,
        onUpdateSettings = owner.settings::updateDb,
        onOpenPlayerSettings = { nav.navigate(Route.Settings(SettingsPage.Player)) },
        playbackSync = { controller, playing, speed, onFollowPlaying ->
            TogetherPlaybackSync(together, manga, chapter, controller, playing, speed, onOpenRoomMedia, onFollowPlaying)
        },
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurface.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurface.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurface.kt).

The implementation below defines `OwnedPlayerSurface`, `initialize`, `mounted`, `detached`, `retire`, `OwnedPlayerSurfaceContent`.

The source describes its contract as:

> Capture allocation before publication, then detach the platform view before native disposal.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.*
import eu.friedcutlet.yokan.services.media.player.PlayerSurfaceResources
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.yield
import kotlin.coroutines.CoroutineContext

/** Capture allocation before publication, then detach the platform view before native disposal. */
internal class OwnedPlayerSurface<T : Any>(
    registry: PlayerSurfaceResources,
    context: CoroutineContext,
    private val dispose: suspend (T) -> Unit,
) {
    var state by mutableStateOf<T?>(null)
        private set
    private var allocated: T? = null
    private var mounted = false
    private val detached = CompletableDeferred<Unit>()
    val resource = registry.register(context) {
        state = null
        if (mounted) detached.await()
        // Complete the Compose apply/disposal pass before calling native release.
        yield()
        allocated?.let { dispose(it) }
        allocated = null
    }
    suspend fun initialize(factory: () -> T) {
        resource?.runOwned { current ->
            allocated = factory()
            current()
            state = allocated
        }
    }
    fun mounted() { mounted = true }
    fun detached() { mounted = false; detached.complete(Unit) }
    fun retire() { resource?.retire() }
}

@Composable
internal fun <T : Any> OwnedPlayerSurfaceContent(
    registry: PlayerSurfaceResources,
    factory: () -> T,
    dispose: suspend (T) -> Unit,
    content: @Composable (T, PlayerSurfaceResources.Resource) -> Unit,
) {
    val scope = rememberCoroutineScope()
    val surface = remember(registry) { OwnedPlayerSurface(registry, scope.coroutineContext, dispose) }
    DisposableEffect(surface) { onDispose { surface.retire() } }
    LaunchedEffect(surface) { surface.initialize(factory) }
    val state = surface.state
    val resource = surface.resource
    if (state != null && resource != null) {
        key(surface, state) {
            // Compose forgets effects in reverse order: acknowledge after child disposal.
            DisposableEffect(surface, state) {
                surface.mounted()
                onDispose { surface.detached() }
            }
            content(state, resource)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.kt).

The implementation below defines `MediaPlayerSurface`, `ComposeMediaPlayerSurface`, `ComposeMediaPlayerSurfaceContent`, `SurfaceEffect`, `ComposeMediaPlayerController.syncFrom`.

The source describes its contract as:

> Platform surface backed by a native surface or Compose software frames.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md), [`redactUrlForLog`](../chapters/24-settings-and-integrations.md), [`VideoPlayerState`](../chapters/18-media-compat-vendor.md), [`VideoPlayerSurface`](../chapters/18-media-compat-vendor.md), [`ComposeSubtitleLayer`](../chapters/18-media-compat-vendor.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.key
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.services.media.player.ComposeMediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.PlaybackAction
import eu.friedcutlet.yokan.services.media.player.awaitInitialMediaDuration
import io.github.kdroidfilter.composemediaplayer.VideoPlayerState
import io.github.kdroidfilter.composemediaplayer.VideoPlayerSurface as ComposeVideoPlayerSurface
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import eu.friedcutlet.yokan.services.media.player.PlayerSurfaceResources
import eu.friedcutlet.yokan.services.media.player.pictureInPicturePlatform

/** Platform surface backed by a native surface or Compose software frames. */
@Composable
expect fun MediaPlayerSurface(controller: MediaPlayerController, modifier: Modifier = Modifier)

/**
 * Renders a [ComposeMediaPlayerController] through compose-mediaplayer and replays
 * its queued commands. The controller joins UI detachment and backend disposal.
 */
@Composable
internal fun ComposeMediaPlayerSurface(
    controller: MediaPlayerController,
    modifier: Modifier = Modifier,
) {
    val composeController = controller as? ComposeMediaPlayerController ?: return
    key(composeController) {
        OwnedPlayerSurfaceContent(
            registry = composeController.surfaces,
            factory = { VideoPlayerState() },
            dispose = { it.disposeAndJoin() },
        ) { playerState, resource ->
            ComposeMediaPlayerSurfaceContent(composeController, playerState, resource, modifier)
        }
    }
}

@Composable
private fun ComposeMediaPlayerSurfaceContent(
    composeController: ComposeMediaPlayerController,
    playerState: VideoPlayerState,
    resource: PlayerSurfaceResources.Resource,
    modifier: Modifier,
) {
    DisposableEffect(composeController, playerState) {
        val unbind = pictureInPicturePlatform.bindSurface(composeController, playerState)
        onDispose { unbind() }
    }
    val mediaRequest = composeController.mediaRequest
    val playbackCommand = composeController.playbackCommand
    val seekCommand = composeController.seekCommand
    val speed = composeController.speed
    val playerError = playerState.error
    val hasMedia = playerState.hasMedia
    val durationMs = playerState.metadata.duration

    SideEffect { if (resource.isAvailable) composeController.syncFrom(playerState) }

    SurfaceEffect(resource, mediaRequest) { current ->
        val request = mediaRequest ?: return@SurfaceEffect
        if (request.proxied) {
            AppLogger.info("[player] using local stream proxy for ${redactUrlForLog(request.originalUrl)}")
        } else if (request.headers.isNotEmpty()) {
            AppLogger.warn("[player] ComposeMediaPlayer does not expose custom stream headers; loading URL directly.")
        }
        AppLogger.info("[player] openUri start requestId=${request.id} url=${redactUrlForLog(request.url)}")
        current()
        playerState.openUri(request.url)
        // openUri auto-plays. Pause synchronously before the first prepared
        // frame can be presented, then seek exactly once after metadata exists.
        current()
        playerState.pause()
        current()
        playerState.playbackSpeed = speed
        val rawDurationMs = awaitInitialMediaDuration(
            durationMs = { current(); playerState.metadata.duration },
            isUsable = { current(); playerState.hasMedia && !playerState.isLoading },
            hasError = { current(); playerState.error != null },
            requireDuration = request.initialPositionMs > 0L,
        )
        current()
        composeController.syncFrom(playerState)
        val scaledDurationMs = composeController.durationMs()
        val pendingSeekPositionMs = composeController.pendingSeekPositionMs()
        val targetPositionMs = pendingSeekPositionMs ?: request.initialPositionMs
        if (rawDurationMs != null && scaledDurationMs > 0L) {
            val fraction = (targetPositionMs.toFloat() / scaledDurationMs.toFloat()).coerceIn(0f, 1f)
            val seekValue = fraction * composeController.sliderScale
            AppLogger.info(
                "[player] initial seek requestId=${request.id} positionMs=$targetPositionMs " +
                    "rawDurationMs=$rawDurationMs durationMs=$scaledDurationMs seekValue=$seekValue",
            )
            current()
            playerState.seekTo(seekValue)
            if (pendingSeekPositionMs != null) composeController.markPendingSeekDispatched()
        } else {
            AppLogger.info(
                "[player] initial seek skipped requestId=${request.id}; duration unavailable",
            )
        }
        if (composeController.finishMediaPreparation()) { current(); playerState.play() }
        AppLogger.info("[player] openUri initialized requestId=${request.id}")
    }

    SurfaceEffect(resource, playbackCommand) { current ->
        val command = playbackCommand ?: return@SurfaceEffect
        when (command.action) {
            PlaybackAction.Play -> {
                if (composeController.mediaPrepared) {
                    AppLogger.info("[player] play dispatch commandId=${command.id}")
                    current()
                    playerState.play()
                } else {
                    AppLogger.info("[player] play deferred commandId=${command.id}; media is still preparing")
                }
            }
            PlaybackAction.Pause -> {
                AppLogger.info("[player] pause dispatch commandId=${command.id}")
                current()
                playerState.pause()
            }
            PlaybackAction.Stop -> {
                AppLogger.info("[player] stop dispatch commandId=${command.id}")
                current()
                playerState.stop()
            }
        }
    }

    SurfaceEffect(resource, seekCommand, durationMs, composeController.mediaPrepared) { current ->
        val command = seekCommand ?: return@SurfaceEffect
        if (!composeController.mediaPrepared || composeController.pendingSeekPositionMs() == null) {
            return@SurfaceEffect
        }
        // durationMs() returns the SCALED (real) duration; sliderScale tells
        // us what the underlying backend expects (1f for the documented 0..1
        // range, 1000f for the Linux backend's 0..1000 bug).
        val scaledDurationMs = composeController.durationMs()
        if (scaledDurationMs > 0L) {
            val fraction = (command.positionMs.toFloat() / scaledDurationMs.toFloat()).coerceIn(0f, 1f)
            val seekValue = fraction * composeController.sliderScale
            AppLogger.info("[player] seek dispatch commandId=${command.id} positionMs=${command.positionMs} durationMs=$scaledDurationMs fraction=$fraction seekValue=$seekValue")
            current()
            playerState.seekTo(seekValue)
            composeController.markPendingSeekDispatched()
        } else {
            AppLogger.info("[player] seek pending commandId=${command.id} positionMs=${command.positionMs}; duration unknown")
        }
    }

    SurfaceEffect(resource, speed) { current ->
        AppLogger.info("[player] speed dispatch speed=$speed")
        current()
        playerState.playbackSpeed = speed
    }

    SurfaceEffect(resource, playerError) {
        playerError?.let { AppLogger.error("[player] error $it") }
        composeController.error = playerError?.toString()
    }

    SurfaceEffect(resource, composeController.subtitle) { current ->
        current()
        val track = composeController.subtitle
        if (track == null) playerState.disableSubtitles() else playerState.selectSubtitleTrack(track)
    }

    SurfaceEffect(resource, composeController.volume) { current ->
        current()
        playerState.volume = composeController.volume
    }

    SurfaceEffect(resource, hasMedia) {
        if (hasMedia) AppLogger.info("[player] media attached")
    }

    SurfaceEffect(resource, durationMs) {
        durationMs?.takeIf { it > 0L }?.let { AppLogger.info("[player] metadata durationMs=$it") }
    }

    Box(
        modifier = modifier.background(Color.Black),
        contentAlignment = Alignment.Center,
    ) {
        ComposeVideoPlayerSurface(
            playerState = playerState,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Fit,
        )
        composeController.secondarySubtitle?.let { track ->
            ComposeSubtitleLayer(
                currentTimeMs = composeController.currentPositionMs() - composeController.secondaryDelayMs,
                durationMs = composeController.durationMs(),
                isPlaying = composeController.isPlaying(),
                subtitleTrack = track,
                subtitlesEnabled = true,
                // The cue layer bottom-aligns text; a top band keeps it clear of the primary track.
                modifier = Modifier.align(Alignment.TopCenter).fillMaxWidth().fillMaxHeight(0.25f),
            )
        }
        if (playerState.isLoading) {
            CircularProgressIndicator(color = Color.White)
        }
    }
}

@Composable
private fun SurfaceEffect(
    resource: PlayerSurfaceResources.Resource,
    vararg keys: Any?,
    action: suspend (() -> Unit) -> Unit,
) {
    LaunchedEffect(resource, *keys) { resource.runOwned(action) }
}

private fun ComposeMediaPlayerController.syncFrom(playerState: VideoPlayerState) = updateSnapshot(
    rawDuration = playerState.metadata.duration ?: 0L,
    rawSlider = playerState.sliderPos,
    positionText = playerState.positionText,
    isPlaying = playerState.isPlaying,
)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerScreen.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerScreen.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/AnimePlayerScreen.kt).

The implementation below defines `PlayerPlaybackSync`, `AnimePlayerScreen`, `AnimePlayerContent`.

The source describes its contract as:

> Keeps a room's playback in step with the local controller; supplied by the route.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`AppLogger`](../chapters/24-settings-and-integrations.md), [`ApplyReaderSystemUi`](../chapters/14-manga-reader.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.VideoLibrary
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.navigationevent.NavigationEventInfo
import androidx.navigationevent.compose.NavigationBackHandler
import androidx.navigationevent.compose.rememberNavigationEventState
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.cast.CastDevice
import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvChapterMark
import eu.friedcutlet.yokan.services.media.player.MpvPanel
import eu.friedcutlet.yokan.services.media.player.PictureInPictureAction
import eu.friedcutlet.yokan.services.media.player.PlayerBridgeCommand
import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices
import eu.friedcutlet.yokan.services.media.player.SleepTimer
import eu.friedcutlet.yokan.services.media.player.pictureInPicturePlatform
import eu.friedcutlet.yokan.services.media.player.toCommand
import eu.friedcutlet.yokan.ui.screens.reader.ApplyReaderSystemUi
import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/** Keeps a room's playback in step with the local controller; supplied by the route. */
internal typealias PlayerPlaybackSync = @Composable (
    controller: MediaPlayerController?,
    isPlaying: Boolean,
    speed: Float,
    onFollowPlaying: (Boolean) -> Unit,
) -> Unit

/**
 * Binds this episode's media controller and shows it with the player chrome. [playerServices]
 * stays a parameter because the controller lives exactly as long as this composition: it is
 * created and released by [PlayerControllerEffect] and drawn by [MediaPlayerSurface].
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun AnimePlayerScreen(
    manga: Manga,
    chapter: Chapter,
    state: PlayerState,
    settings: DbSettings,
    minimized: Boolean,
    notice: String?,
    playerServices: ProfilePlayerServices,
    onEvent: (PlayerEvent) -> Unit,
    onNotice: (String) -> Unit,
    onBack: () -> Unit,
    onRestore: () -> Unit,
    onDismiss: () -> Unit,
    /** Shrinks to the in-app mini player; the PiP-on-exit fallback where the OS has no PiP. */
    onMinimize: () -> Unit,
    onOpenEpisode: (Chapter) -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onOpenPlayerSettings: () -> Unit,
    playbackSync: PlayerPlaybackSync,
) {
    val player = rememberPlayerServices(playerServices, chapter.id)
    val playerPreferences = settings.features.player
    val tracks = remember(player, chapter.id) {
        PlayerTrackState(
            playbackSpeed = settings.defaultPlaybackSpeed.toFloat(),
            volume = playerPreferences.volume.takeIf { playerPreferences.rememberVolume && it >= 0 } ?: 100,
            brightness = playerPreferences.brightness.takeIf { playerPreferences.rememberBrightness && it >= 0f },
        )
    }
    var isPlaying by remember(player, chapter.id) { mutableStateOf(true) }
    val mediaConfiguration = remember(player, chapter.id) { player.configuration(settings) }
    ApplyReaderSystemUi(fullscreen = settings.fullScreenPlayer, keepScreenOn = true)

    var initializationError by remember(player, chapter.id, mediaConfiguration) { mutableStateOf<String?>(null) }
    var initializationAttempt by remember(player, chapter.id, mediaConfiguration) { mutableIntStateOf(0) }
    var mediaControllerState by remember(player, chapter.id, mediaConfiguration) {
        mutableStateOf<MediaPlayerController?>(null)
    }
    val callbacks = rememberPlayerUiBinding(player, mediaControllerState)
    val requestPictureInPicture = rememberPlayerPictureInPicture(callbacks, isPlaying && playerPreferences.pipEnabled)
    playbackSync(mediaControllerState, isPlaying, tracks.playbackSpeed) { isPlaying = it }
    PlayerControllerEffect(
        player = player,
        configuration = mediaConfiguration,
        initializationAttempt = initializationAttempt,
        onController = { mediaControllerState = it },
        onSavePosition = { positionMs, durationMs -> onEvent(PlayerEvent.SavePosition(positionMs, durationMs)) },
        onInitializationError = { failure ->
            initializationError = failure?.let {
                it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty().ifBlank { "Unknown error" } }
            }
            if (failure != null) AppLogger.error("Player initialization failed: ${initializationError.orEmpty()}")
        },
    )

    val mediaController = mediaControllerState
    if (mediaController == null) {
        PlayerInitError(initializationError, onBack = onBack, onRetry = { initializationAttempt += 1 })
        return
    }
    val setPlaying: (Boolean) -> Unit = { playing ->
        isPlaying = playing
        if (playing) mediaController.play() else mediaController.pause()
    }
    val sleepTimer by playerServices.sleepTimer.collectAsStateWithLifecycle()
    PlayerSleepTimerEffect(sleepTimer, mediaController) { timer ->
        setPlaying(false)
        playerServices.sleepTimer.compareAndSet(timer, null)
        onNotice("Sleep timer ended")
    }
    LaunchedEffect(isPlaying, playerPreferences.pipReplaceWithPrevious) {
        pictureInPicturePlatform.updateActions(isPlaying, playerPreferences.pipReplaceWithPrevious)
    }
    LaunchedEffect(mediaController) {
        pictureInPicturePlatform.actions.collect { action ->
            when (action) {
                PictureInPictureAction.SkipForward -> mediaController.seekTo(mediaController.currentPositionMs() + 10_000L)
                PictureInPictureAction.Previous -> onEvent(PlayerEvent.SwitchEpisode(-1))
                PictureInPictureAction.Next -> onEvent(PlayerEvent.SwitchEpisode(1))
                PictureInPictureAction.Play -> setPlaying(true)
                PictureInPictureAction.Pause -> setPlaying(false)
            }
        }
    }
    val pictureInPictureActive by pictureInPicturePlatform.active.collectAsStateWithLifecycle()
    LaunchedEffect(chapter.id) {
        if (pictureInPictureActive && playerPreferences.pipEpisodeToasts) onNotice(chapter.name)
    }
    // PiP on exit: back while playing enters system PiP, or the in-app mini player without one.
    val exitToPictureInPicture = playerPreferences.pipOnExit && playerPreferences.pipEnabled && isPlaying && !minimized
    val leavePlayer: () -> Unit = {
        if (!exitToPictureInPicture) onBack()
        else if (!(pictureInPicturePlatform.isSupported && requestPictureInPicture())) onMinimize()
    }
    NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None), isBackEnabled = exitToPictureInPicture) { leavePlayer() }

    AnimePlayerContent(
        manga = manga,
        chapter = chapter,
        state = state,
        settings = settings,
        minimized = minimized,
        notice = notice,
        player = player,
        controller = mediaController,
        configuration = mediaConfiguration,
        callbacks = callbacks,
        tracks = tracks,
        isPlaying = isPlaying,
        setPlaying = setPlaying,
        sleepTimer = sleepTimer,
        onSetSleepTimer = { minutes ->
            playerServices.sleepTimer.value = SleepTimer(minutes?.let { nowMillis() + it * 60_000L })
            onNotice(minutes?.let { "Pausing in $it minutes" } ?: "Pausing at the end of this episode")
        },
        onCancelSleepTimer = { playerServices.sleepTimer.value = null },
        onLeave = leavePlayer,
        onPictureInPicture = if (playerPreferences.pipEnabled && pictureInPicturePlatform.isSupported) {
            { if (!requestPictureInPicture()) onNotice("Picture-in-picture is unavailable for this video") }
        } else {
            null
        },
        onEvent = onEvent,
        onNotice = onNotice,
        onRestore = onRestore,
        onDismiss = onDismiss,
        onOpenEpisode = onOpenEpisode,
        onUpdateSettings = onUpdateSettings,
        onOpenPlayerSettings = onOpenPlayerSettings,
    )
}

/** The player once its controller exists: video surface, chrome, dialogs and the mpv bridge. */
@Composable
private fun AnimePlayerContent(
    manga: Manga,
    chapter: Chapter,
    state: PlayerState,
    settings: DbSettings,
    minimized: Boolean,
    notice: String?,
    player: ProfilePlayerServices.Reader,
    controller: MediaPlayerController,
    configuration: MediaPlayerConfiguration,
    callbacks: PlayerUiBinding,
    tracks: PlayerTrackState,
    isPlaying: Boolean,
    setPlaying: (Boolean) -> Unit,
    sleepTimer: SleepTimer?,
    onSetSleepTimer: (minutes: Int?) -> Unit,
    onCancelSleepTimer: () -> Unit,
    onLeave: () -> Unit,
    onPictureInPicture: (() -> Unit)?,
    onEvent: (PlayerEvent) -> Unit,
    onNotice: (String) -> Unit,
    onRestore: () -> Unit,
    onDismiss: () -> Unit,
    onOpenEpisode: (Chapter) -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onOpenPlayerSettings: () -> Unit,
) {
    val playerPreferences = settings.features.player
    var dialog by remember(player) { mutableStateOf<PlayerDialog?>(null) }
    var dimVideo by remember(player) { mutableStateOf(false) }
    PlayerPlaybackEffects(
        player = player,
        controller = controller,
        configuration = configuration,
        state = state,
        settings = settings,
        tracks = tracks,
        episodeListOpen = dialog is PlayerDialog.Episodes,
        setPlaying = setPlaying,
        onDimVideo = { dimVideo = it },
        onEvent = onEvent,
        onUpdateSettings = onUpdateSettings,
    )
    var selectedShader by remember(player) { mutableStateOf("") }
    var chapterMarks by remember(player) { mutableStateOf<List<MpvChapterMark>>(emptyList()) }
    var currentChapterMark by remember(player) { mutableIntStateOf(0) }
    val primaryCustomButton = state.customButtons.firstOrNull { it.isFavourite } ?: state.customButtons.firstOrNull()
    var activeCustomButtonTitle by remember(player, primaryCustomButton?.id) {
        mutableStateOf(primaryCustomButton?.title.orEmpty())
    }
    var customButtonVisible by remember(player, primaryCustomButton?.id) { mutableStateOf(true) }
    var showChrome by remember(player) { mutableStateOf(true) }
    var lastInteractionAt by remember(player) { mutableLongStateOf(0L) }
    val interacted = { lastInteractionAt = nowMillis() }
    LaunchedEffect(lastInteractionAt) {
        if (!showChrome) return@LaunchedEffect
        delay(3_500)
        showChrome = false
    }
    PlayerBridgeEffect(callbacks) { event ->
        when (val command = event.toCommand() ?: return@PlayerBridgeEffect) {
            is PlayerBridgeCommand.ShowText -> onNotice(command.text)
            is PlayerBridgeCommand.SetUiVisible -> showChrome = command.visible ?: !showChrome
            is PlayerBridgeCommand.ShowPanel -> dialog = PlayerDialog.Sheet(
                when (command.panel) {
                    MpvPanel.Video -> PlayerSheetTab.Quality
                    MpvPanel.Subtitles -> PlayerSheetTab.Subtitles
                    MpvPanel.Audio -> PlayerSheetTab.Audio
                },
            )
            is PlayerBridgeCommand.SetButtonTitle -> activeCustomButtonTitle = command.title
            PlayerBridgeCommand.ResetButtonTitle -> activeCustomButtonTitle = primaryCustomButton?.title.orEmpty()
            is PlayerBridgeCommand.SetButtonVisible -> customButtonVisible = command.visible ?: !customButtonVisible
            is PlayerBridgeCommand.SwitchEpisode -> onEvent(PlayerEvent.SwitchEpisode(command.offset))
            is PlayerBridgeCommand.SetPaused -> setPlaying(command.paused?.not() ?: !isPlaying)
            is PlayerBridgeCommand.Seek -> {
                val base = if (command.relative) controller.currentPositionMs() else 0L
                controller.seekTo((base + command.seconds * 1000L).coerceAtLeast(0L))
                command.text?.let(onNotice)
            }
            is PlayerBridgeCommand.LaunchIntPicker -> dialog = PlayerDialog.IntPicker(command.request)
            is PlayerBridgeCommand.ChapterTitles -> chapterMarks = command.marks
            is PlayerBridgeCommand.CurrentChapter -> currentChapterMark = command.index
            is PlayerBridgeCommand.SelectedShader -> selectedShader = command.label
        }
    }

    val startCasting: (CastDevice?) -> Unit = { device ->
        dialog = null
        onEvent(PlayerEvent.StartCasting(device, controller.currentPositionMs(), tracks.subtitleFile))
    }
    dialog?.let {
        PlayerDialogHost(
            dialog = it,
            state = state,
            settings = settings,
            chapter = chapter,
            controller = controller,
            tracks = tracks,
            isPlaying = isPlaying,
            onDialog = { next -> dialog = next },
            onStartCasting = startCasting,
            onEvent = onEvent,
            onNotice = onNotice,
            onOpenEpisode = onOpenEpisode,
            onOpenPlayerSettings = onOpenPlayerSettings,
            onInteraction = interacted,
        )
    }

    val screenshotScope = rememberCoroutineScope()
    Box(
        modifier = Modifier
            .then(
                if (minimized) {
                    Modifier
                        .fillMaxSize()
                        .wrapContentSize(Alignment.BottomEnd)
                        .padding(MinimizedAnimePlayerMargin)
                        .size(width = 320.dp, height = MinimizedAnimePlayerHeight)
                } else Modifier.fillMaxSize()
            )
            .background(LocalYokanScaffoldColor.current.copy(alpha = 0.92f))
            .clickable(
                interactionSource = remember(player) { MutableInteractionSource() },
                indication = null,
            ) {
                showChrome = !showChrome
                interacted()
            },
    ) {
        // Center video surface (mpv with a platform fallback). Composed regardless of
        // chrome visibility so the picture stays steady; chrome layers float on top.
        Surface(modifier = Modifier.fillMaxSize(), color = Color.Black) {
            if (state.selectedVideo != null) {
                MediaPlayerSurface(controller = controller, modifier = Modifier.fillMaxSize())
            } else {
                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Icon(Icons.Filled.VideoLibrary, contentDescription = null, tint = Color.White, modifier = Modifier.size(56.dp))
                        Text("No stream", color = Color.White, fontWeight = FontWeight.SemiBold)
                    }
                }
            }
        }
        if (dimVideo) {
            Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = (1f - (tracks.brightness ?: 1f)) * 0.85f)))
        }
        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut()) {
            Box(modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.40f)))
        }
        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.TopCenter)) {
            PlayerTopBar(
                title = manga.name,
                episodeName = chapter.name,
                minimized = minimized,
                sleepTimer = sleepTimer,
                castSupported = state.castSupported,
                casting = state.castStatus != null,
                onLeave = onLeave,
                onRestore = onRestore,
                onDismiss = onDismiss,
                onSetSleepTimer = onSetSleepTimer,
                onCancelSleepTimer = onCancelSleepTimer,
                onCast = {
                    when {
                        state.castStatus != null -> Unit // the cast panel holds the controls
                        state.castUsesSystemPicker -> startCasting(null)
                        else -> dialog = PlayerDialog.Cast
                    }
                },
                onOpenEpisodes = {
                    if (isPlaying) controller.pause()
                    dialog = PlayerDialog.Episodes(resume = isPlaying)
                },
                onScreenshot = {
                    screenshotScope.launch {
                        onNotice(takeScreenshot(player, controller, manga, chapter, playerPreferences.screenshotSubtitles))
                        interacted()
                    }
                },
            )
        }
        notice?.let {
            PlayerNotice(it, Modifier.align(Alignment.TopCenter).padding(top = 64.dp, start = 16.dp, end = 16.dp))
        }
        state.castStatus?.let { status ->
            CastPanel(
                status = status,
                compact = minimized,
                onPlayPause = { onEvent(PlayerEvent.CastPlayPause) },
                onSeek = { onEvent(PlayerEvent.CastSeek(it)) },
                onPrevious = { onEvent(PlayerEvent.CastPrevious) },
                onNext = { onEvent(PlayerEvent.CastNext) },
                onJumpTo = { onEvent(PlayerEvent.CastJumpTo(it)) },
                onDisconnect = {
                    // Continue locally from the receiver's position when it was playing this episode.
                    val item = status.queue.getOrNull(status.currentIndex)
                    if (item?.itemKey == chapter.id.toString() && status.positionMs > 0L) controller.seekTo(status.positionMs)
                    onEvent(PlayerEvent.StopCasting)
                },
                modifier = Modifier.align(Alignment.Center).padding(16.dp).widthIn(max = 480.dp),
            )
        }
        AnimatedVisibility(
            visible = showChrome && state.castStatus == null,
            enter = fadeIn(),
            exit = fadeOut(),
            modifier = Modifier.align(Alignment.Center),
        ) {
            PlayerCenterControls(
                isPlaying = isPlaying,
                onPrevious = { onEvent(PlayerEvent.SwitchEpisode(-1)); interacted() },
                onPlayPause = { setPlaying(!isPlaying); interacted() },
                onNext = { onEvent(PlayerEvent.SwitchEpisode(1)); interacted() },
                onPictureInPicture = onPictureInPicture?.let { request -> { request(); interacted() } },
            )
        }
        AnimatedVisibility(visible = showChrome, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter)) {
            PlayerBottomControls(
                state = state,
                settings = settings,
                controller = controller,
                tracks = tracks,
                chapterMarks = chapterMarks,
                currentChapterMark = currentChapterMark,
                selectedShader = selectedShader,
                onShaderSelected = { selectedShader = it },
                customButtonVisible = customButtonVisible,
                primaryCustomButtonId = primaryCustomButton?.id,
                activeCustomButtonTitle = activeCustomButtonTitle,
                onOpenSettings = { dialog = PlayerDialog.Sheet(PlayerSheetTab.Quality) },
                onEvent = onEvent,
                onNotice = onNotice,
                onUpdateSettings = onUpdateSettings,
                onInteraction = interacted,
            )
        }
    }
}

internal val MinimizedAnimePlayerHeight = 190.dp

internal val MinimizedAnimePlayerMargin = 16.dp
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.kt).

The implementation below defines `setPlayerScreenBrightness`.

The source describes its contract as:

> Sets the screen brightness (0..1) while the player is shown; null restores the system value. Returns false where the platform cannot control it, and the player dims the video instead.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/**
 * Sets the screen brightness (0..1) while the player is shown; null restores the system value.
 * Returns false where the platform cannot control it, and the player dims the video instead.
 */
internal expect fun setPlayerScreenBrightness(level: Float?): Boolean
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerAddons.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerAddons.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerAddons.kt).

The implementation below defines `DbVideo.isCastable`, `DbVideo.toCastMedia`, `DbPlayerSubtitleSettings`, `argb`, `CastDeviceDialog`, `CastPanel`, `CastButton`, `SeekPreview`, `SleepTimerButton`, `SpeedPresetButton`.

The source describes its contract as:

> The Default Media Receiver fetches the URL itself: no request headers, no device-local addresses.

Cross-chapter imports used by this file: [`DbPlayerSubtitleSettings`](../chapters/02-domain-and-settings-models.md), [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`formatDecimal`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bedtime
import androidx.compose.material.icons.filled.Cast
import androidx.compose.material.icons.filled.CastConnected
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Speed
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbPlayerSubtitleSettings
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.media.cast.CastDevice
import eu.friedcutlet.yokan.services.media.cast.CastMedia
import eu.friedcutlet.yokan.services.media.cast.CastStatus
import eu.friedcutlet.yokan.services.media.cast.CastSubtitle
import eu.friedcutlet.yokan.services.media.cast.CastTextStyle
import eu.friedcutlet.yokan.services.media.player.SeekThumbnail
import eu.friedcutlet.yokan.ui.formatDecimal
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel

/** The Default Media Receiver fetches the URL itself: no request headers, no device-local addresses. */
internal fun DbVideo.isCastable(): Boolean {
    if (!headers.isNullOrEmpty()) return false
    val host = url.substringAfter("://", "").substringBefore('/').substringBefore(':').lowercase()
    return (url.startsWith("http://") || url.startsWith("https://")) &&
        host.isNotEmpty() && host != "localhost" && host != "127.0.0.1" && host != "[::1]"
}

internal fun DbVideo.toCastMedia(manga: Manga, episode: Chapter): CastMedia = CastMedia(
    url = url,
    title = episode.name,
    subtitle = manga.name,
    posterUrl = manga.imageUrl?.takeIf { it.startsWith("http") },
    subtitles = subtitles.mapNotNull { track -> track.file?.let { CastSubtitle(it, track.label ?: "Subtitle") } },
    itemKey = episode.id.toString(),
)

internal fun DbPlayerSubtitleSettings?.toCastTextStyle(): CastTextStyle {
    val style = this ?: DbPlayerSubtitleSettings()
    fun argb(a: Int, r: Int, g: Int, b: Int) = (a shl 24) or (r shl 16) or (g shl 8) or b
    return CastTextStyle(
        foregroundArgb = argb(style.textColorA, style.textColorR, style.textColorG, style.textColorB),
        edgeArgb = argb(style.borderColorA, style.borderColorR, style.borderColorG, style.borderColorB),
        backgroundArgb = argb(style.backgroundColorA, style.backgroundColorR, style.backgroundColorG, style.backgroundColorB),
        fontScale = style.fontSize / 45.0,
        bold = style.useBold,
        italic = style.useItalic,
    )
}

/** Lists discovered receivers; [onDiscovery] runs discovery while the dialog is composed. */
@Composable
internal fun CastDeviceDialog(
    devices: List<CastDevice>,
    onDiscovery: (active: Boolean) -> Unit,
    onSelect: (CastDevice) -> Unit,
    onDismiss: () -> Unit,
) {
    val discovery by rememberUpdatedState(onDiscovery)
    DisposableEffect(Unit) {
        discovery(true)
        onDispose { discovery(false) }
    }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Cast to") },
        text = {
            if (devices.isEmpty()) {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    LinearProgressIndicator(Modifier.fillMaxWidth())
                    Text("Searching for Chromecast devices on this network…", style = MaterialTheme.typography.bodySmall)
                }
            } else {
                LazyColumn(Modifier.heightIn(max = 320.dp)) {
                    items(devices, key = { it.id }) { device ->
                        TextButton(onClick = { onSelect(device) }, modifier = Modifier.fillMaxWidth()) {
                            Text(device.name, modifier = Modifier.fillMaxWidth(), maxLines = 1, overflow = TextOverflow.Ellipsis)
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
    )
}

/** Remote playback controls; doubles as the mini controls when the player is minimized. */
@Composable
internal fun CastPanel(
    status: CastStatus,
    compact: Boolean,
    onPlayPause: () -> Unit,
    onSeek: (Long) -> Unit,
    onPrevious: () -> Unit,
    onNext: () -> Unit,
    onJumpTo: (Int) -> Unit,
    onDisconnect: () -> Unit,
    modifier: Modifier = Modifier,
) {
    var dragFraction by remember { mutableStateOf<Float?>(null) }
    var queueOpen by remember { mutableStateOf(false) }
    val current = status.queue.getOrNull(status.currentIndex)
    Surface(modifier = modifier, color = Color.Black.copy(alpha = 0.85f), shape = RoundedCornerShape(12.dp)) {
        Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(Icons.Filled.CastConnected, contentDescription = null, tint = Color.White)
                Column(Modifier.weight(1f).padding(horizontal = 8.dp)) {
                    Text("Casting to ${status.device.name}", color = Color.White, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
                    current?.let { Text(it.title, color = Color.White.copy(alpha = 0.7f), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis) }
                }
                TextButton(onClick = onDisconnect) { Text("Stop casting") }
            }
            status.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
            if (!compact && status.durationMs > 0) {
                Slider(
                    value = dragFraction ?: (status.positionMs.toFloat() / status.durationMs).coerceIn(0f, 1f),
                    onValueChange = { dragFraction = it },
                    onValueChangeFinished = {
                        dragFraction?.let { onSeek((it * status.durationMs).toLong()) }
                        dragFraction = null
                    },
                )
            }
            Row(horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                IconButton(onClick = onPrevious, enabled = status.currentIndex > 0) {
                    Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous in cast queue", tint = Color.White)
                }
                IconButton(onClick = onPlayPause) {
                    Icon(if (status.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow, contentDescription = if (status.playing) "Pause" else "Play", tint = Color.White)
                }
                IconButton(onClick = onNext, enabled = status.currentIndex in 0 until status.queue.lastIndex) {
                    Icon(Icons.Filled.SkipNext, contentDescription = "Next in cast queue", tint = Color.White)
                }
                if (status.queue.size > 1) {
                    Box {
                        TextButton(onClick = { queueOpen = true }) { Text("Queue (${status.queue.size})") }
                        DropdownMenu(expanded = queueOpen, onDismissRequest = { queueOpen = false }) {
                            status.queue.forEachIndexed { index, item ->
                                DropdownMenuItem(
                                    text = { Text(item.title, fontWeight = if (index == status.currentIndex) FontWeight.Bold else FontWeight.Normal) },
                                    onClick = { queueOpen = false; onJumpTo(index) },
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
internal fun CastButton(casting: Boolean, onClick: () -> Unit) {
    IconButton(onClick = onClick) {
        Icon(if (casting) Icons.Filled.CastConnected else Icons.Filled.Cast, contentDescription = "Cast", tint = Color.White)
    }
}

/** A cropped sprite tile above the seek bar; nothing until the sheet has loaded. */
@Composable
internal fun SeekPreview(tile: SeekThumbnail, sprite: ImageBitmap, modifier: Modifier = Modifier) {
    val width = if (tile.width > 0) tile.width.coerceAtMost(sprite.width - tile.x) else sprite.width
    val height = if (tile.height > 0) tile.height.coerceAtMost(sprite.height - tile.y) else sprite.height
    if (width <= 0 || height <= 0) return
    val painter = remember(sprite, tile) { BitmapPainter(sprite, IntOffset(tile.x, tile.y), IntSize(width, height)) }
    Image(
        painter = painter,
        contentDescription = null,
        modifier = modifier
            .width(160.dp)
            .background(Color.Black, RoundedCornerShape(6.dp))
            .padding(2.dp),
    )
}

/** Sleep timer menu: fixed durations, end of episode, or off. */
@Composable
internal fun SleepTimerButton(remainingLabel: String?, onSelect: (minutes: Int?) -> Unit, onCancel: () -> Unit) {
    var open by remember { mutableStateOf(false) }
    Box {
        IconButton(onClick = { open = true }) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Icon(Icons.Filled.Bedtime, contentDescription = "Sleep timer", tint = Color.White, modifier = Modifier.size(22.dp))
                remainingLabel?.let { Text(it, color = Color.White, style = MaterialTheme.typography.labelSmall) }
            }
        }
        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            DropdownMenuItem(text = { Text("Off") }, onClick = { open = false; onCancel() })
            SleepTimerMinutes.forEach { minutes ->
                DropdownMenuItem(text = { Text("$minutes minutes") }, onClick = { open = false; onSelect(minutes) })
            }
            DropdownMenuItem(text = { Text("End of episode") }, onClick = { open = false; onSelect(null) })
        }
    }
}

private val SleepTimerMinutes = listOf(5, 15, 30, 45, 60, 90)

@Composable
internal fun SpeedPresetButton(speed: Float, presets: List<Double>, onSelect: (Float) -> Unit) {
    var open by remember { mutableStateOf(false) }
    Box {
        IconButton(onClick = { open = true }) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Icon(Icons.Filled.Speed, contentDescription = "Playback speed", tint = Color.White)
                Text("${formatDecimal(speed.toDouble(), 2)}x", color = Color.White, style = MaterialTheme.typography.labelSmall)
            }
        }
        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            presets.forEach { preset ->
                DropdownMenuItem(
                    text = { Text("${formatDecimal(preset, 2)}x", fontWeight = if (preset.toFloat() == speed) FontWeight.Bold else FontWeight.Normal) },
                    onClick = { open = false; onSelect(preset.toFloat()) },
                )
            }
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerChrome.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerChrome.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerChrome.kt).

The implementation below defines `PlayerTopBar`, `PlayerNotice`, `PlayerCenterControls`, `PlayerTimeline`, `PlayerActionRow`, `PlayerChapterMenu`, `PlayerMpvMenus`, `PlayerMenuButton`, `formatPlayerTime`, `PlayerTimePill` and 1 further declarations.

The source describes its contract as:

> Flutter's player used a transparent top button bar over one dimmed full-screen backdrop, rather than an opaque Material app bar.

Cross-chapter imports used by this file: [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`AppLogger`](../chapters/24-settings-and-integrations.md), [`GlobalStatusAccessButton`](../chapters/24-settings-and-integrations.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.PlaylistPlay
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.FitScreen
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.HighQuality
import androidx.compose.material.icons.filled.Memory
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PictureInPictureAlt
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Screenshot
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.VideoLibrary
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.BiasAlignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvChapterMark
import eu.friedcutlet.yokan.services.media.player.MpvMenuAction
import eu.friedcutlet.yokan.services.media.player.MpvShaderActions
import eu.friedcutlet.yokan.services.media.player.MpvStatsActions
import eu.friedcutlet.yokan.services.media.player.MpvVideoFit
import eu.friedcutlet.yokan.services.media.player.SeekThumbnail
import eu.friedcutlet.yokan.services.media.player.SleepTimer
import eu.friedcutlet.yokan.services.media.player.at
import eu.friedcutlet.yokan.services.media.player.selectMpvShader
import eu.friedcutlet.yokan.services.media.player.setMpvVideoFit
import eu.friedcutlet.yokan.services.media.player.showMpvStats
import eu.friedcutlet.yokan.ui.status.GlobalStatusAccessButton
import eu.friedcutlet.yokan.util.nowMillis
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.custom_buttons
import yokan.composeapp.generated.resources.player_screenshot
import yokan.composeapp.generated.resources.ui_player_settings

/**
 * Flutter's player used a transparent top button bar over one dimmed full-screen backdrop,
 * rather than an opaque Material app bar.
 */
@Composable
internal fun PlayerTopBar(
    title: String,
    episodeName: String,
    minimized: Boolean,
    sleepTimer: SleepTimer?,
    castSupported: Boolean,
    casting: Boolean,
    onLeave: () -> Unit,
    onRestore: () -> Unit,
    onDismiss: () -> Unit,
    onSetSleepTimer: (minutes: Int?) -> Unit,
    onCancelSleepTimer: () -> Unit,
    onCast: () -> Unit,
    onOpenEpisodes: () -> Unit,
    onScreenshot: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 4.dp, vertical = 6.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        IconButton(onClick = onLeave) {
            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back), tint = Color.White)
        }
        if (minimized) {
            IconButton(
                onClick = onRestore,
                modifier = Modifier.semantics { contentDescription = "Restore full player" },
            ) {
                Icon(Icons.Filled.Fullscreen, contentDescription = "Restore full player", tint = Color.White)
            }
            IconButton(
                onClick = onDismiss,
                modifier = Modifier.semantics { contentDescription = "Dismiss mini player" },
            ) {
                Icon(Icons.Filled.Close, contentDescription = "Dismiss mini player", tint = Color.White)
            }
        }
        Column(modifier = Modifier.weight(1f)) {
            Text(
                title,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                color = Color.White,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
            )
            Text(
                episodeName,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                style = MaterialTheme.typography.bodySmall,
                color = Color.White.copy(alpha = 0.70f),
            )
        }
        SleepTimerButton(
            remainingLabel = sleepTimer?.let { timer ->
                timer.deadlineMs?.let { "${((it - nowMillis()).coerceAtLeast(0L) + 59_999L) / 60_000L}m" } ?: "End"
            },
            onSelect = onSetSleepTimer,
            onCancel = onCancelSleepTimer,
        )
        if (castSupported) CastButton(casting = casting, onClick = onCast)
        GlobalStatusAccessButton(tint = Color.White)
        IconButton(onClick = onOpenEpisodes) {
            Icon(Icons.AutoMirrored.Filled.PlaylistPlay, contentDescription = "Episodes", tint = Color.White)
        }
        IconButton(onClick = onScreenshot) {
            Icon(Icons.Filled.Screenshot, contentDescription = stringResource(Res.string.player_screenshot), tint = Color.White)
        }
    }
}

@Composable
internal fun PlayerNotice(text: String, modifier: Modifier = Modifier) {
    Surface(
        modifier = modifier,
        color = Color.Black.copy(alpha = 0.78f),
        shape = RoundedCornerShape(8.dp),
    ) {
        Text(
            text,
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
            color = Color.White,
            style = MaterialTheme.typography.bodySmall,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

/**
 * Mobile controls in Mangayomi: previous episode / play-pause / next episode, with double-tap
 * seeking handled by the video gesture layer. [onPictureInPicture] null hides the PiP button.
 */
@Composable
internal fun PlayerCenterControls(
    isPlaying: Boolean,
    onPrevious: () -> Unit,
    onPlayPause: () -> Unit,
    onNext: () -> Unit,
    onPictureInPicture: (() -> Unit)?,
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(32.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        IconButton(onClick = onPrevious) {
            Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous episode", tint = Color.White, modifier = Modifier.size(40.dp))
        }
        IconButton(onClick = onPlayPause, modifier = Modifier.size(72.dp)) {
            Icon(
                imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow,
                contentDescription = if (isPlaying) "Pause" else "Play",
                tint = Color.White,
                modifier = Modifier.size(56.dp),
            )
        }
        IconButton(onClick = onNext) {
            Icon(Icons.Filled.SkipNext, contentDescription = "Next episode", tint = Color.White, modifier = Modifier.size(40.dp))
        }
        if (onPictureInPicture != null) {
            IconButton(onClick = onPictureInPicture) {
                Icon(Icons.Filled.PictureInPictureAlt, contentDescription = "Enter picture-in-picture", tint = Color.White)
            }
        }
    }
}

/**
 * Loading bar, stream error, seek preview and the seek slider. While the user drags,
 * [dragFraction] holds the in-flight value so the slider doesn't fight the player's tick.
 */
@Composable
internal fun PlayerTimeline(
    loading: Boolean,
    error: String?,
    position: Float,
    dragFraction: Float?,
    durationMs: Long,
    seekThumbnails: List<SeekThumbnail>,
    seekSprites: Map<String, ImageBitmap>,
    onDrag: (Float) -> Unit,
    onDragFinished: () -> Unit,
    onLoadSeekSprite: (url: String) -> Unit,
) {
    if (loading) {
        LinearProgressIndicator(
            modifier = Modifier
                .fillMaxWidth()
                .height(4.dp)
                .clip(RoundedCornerShape(50))
                .padding(bottom = 4.dp),
        )
    }
    if (!error.isNullOrBlank()) {
        Surface(
            shape = RoundedCornerShape(50),
            color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.9f),
        ) {
            Text(
                error,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
                color = MaterialTheme.colorScheme.onErrorContainer,
                style = MaterialTheme.typography.bodySmall,
            )
        }
    }
    val previewTile = dragFraction?.let { seekThumbnails.at((it * durationMs).toLong()) }
    if (dragFraction != null && previewTile != null) {
        LaunchedEffect(previewTile.imageUrl) { onLoadSeekSprite(previewTile.imageUrl) }
        seekSprites[previewTile.imageUrl]?.let { sprite ->
            // Align over the thumb; the 70 dp padding matches the time pills around the slider.
            Box(Modifier.fillMaxWidth().padding(horizontal = 70.dp)) {
                SeekPreview(previewTile, sprite, Modifier.align(BiasAlignment(dragFraction * 2f - 1f, 0f)))
            }
        }
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        PlayerTimePill(formatPlayerTime(((position * durationMs) / 1000L).toLong()))
        Slider(
            value = position,
            onValueChange = onDrag,
            onValueChangeFinished = onDragFinished,
            modifier = Modifier.weight(1f),
        )
        PlayerTimePill(formatPlayerTime(durationMs / 1000L))
    }
}

/**
 * Bottom actions of the old mobile player: skip, chapter, settings, [mpvMenus], speed, fit and
 * fullscreen. [aniSkipType] names the active AniSkip segment; otherwise skip jumps [skipIntroSeconds].
 */
@Composable
internal fun PlayerActionRow(
    aniSkipType: String?,
    skipIntroSeconds: Int,
    onSkip: () -> Unit,
    chapterMarks: List<MpvChapterMark>,
    currentChapterMark: Int,
    onSeekToMark: (positionMs: Long) -> Unit,
    onOpenSettings: () -> Unit,
    speed: Float,
    speedPresets: List<Double>,
    onSelectSpeed: (Float) -> Unit,
    videoFit: MpvVideoFit,
    onCycleVideoFit: () -> Unit,
    onToggleFullscreen: () -> Unit,
    mpvMenus: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.End,
    ) {
        Button(
            onClick = onSkip,
            modifier = Modifier.height(35.dp),
            contentPadding = PaddingValues(horizontal = 12.dp, vertical = 0.dp),
        ) {
            Text(aniSkipType?.let { "AniSkip $it" } ?: "+$skipIntroSeconds", fontWeight = FontWeight.Light)
        }
        if (aniSkipType != null) Spacer(Modifier.width(4.dp))
        chapterMarks.getOrNull(currentChapterMark)?.let { currentMark ->
            PlayerChapterMenu(currentMark, chapterMarks, onSeekToMark)
        }
        Spacer(Modifier.weight(1f))
        IconButton(onClick = onOpenSettings) {
            Icon(Icons.Filled.VideoLibrary, contentDescription = stringResource(Res.string.ui_player_settings), tint = Color.White)
        }
        mpvMenus()
        SpeedPresetButton(speed = speed, presets = speedPresets, onSelect = onSelectSpeed)
        IconButton(onClick = onCycleVideoFit) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Icon(Icons.Filled.FitScreen, contentDescription = "Fit / Zoom", tint = Color.White)
                Text(videoFit.label, color = Color.White, style = MaterialTheme.typography.labelSmall)
            }
        }
        IconButton(onClick = onToggleFullscreen) {
            Icon(Icons.Filled.Fullscreen, contentDescription = "Fullscreen", tint = Color.White)
        }
    }
}

@Composable
private fun PlayerChapterMenu(current: MpvChapterMark, marks: List<MpvChapterMark>, onSeekToMark: (Long) -> Unit) {
    var open by remember { mutableStateOf(false) }
    Box {
        TextButton(onClick = { open = true }, modifier = Modifier.height(35.dp)) {
            Text(
                "${current.title} · ${formatPlayerTime(current.positionMs / 1000L)}",
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                color = Color.White,
                style = MaterialTheme.typography.labelSmall,
            )
        }
        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            marks.forEach { mark ->
                DropdownMenuItem(
                    text = { Text("${mark.title} · ${formatPlayerTime(mark.positionMs / 1000L)}") },
                    onClick = {
                        open = false
                        onSeekToMark(mark.positionMs)
                    },
                )
            }
        }
    }
}

/**
 * mpv-only menus: shaders and stats when [shadersAndStats], and the user's custom buttons while
 * [customButtonVisible]. [onCustomButton] runs a button's press or long-press script.
 */
@Composable
internal fun PlayerMpvMenus(
    shadersAndStats: Boolean,
    selectedShader: String,
    onShader: (MpvMenuAction) -> Unit,
    onStats: (MpvMenuAction) -> Unit,
    customButtons: List<DbCustomButton>,
    customButtonVisible: Boolean,
    primaryCustomButtonId: Long?,
    activeCustomButtonTitle: String,
    onCustomButton: (button: DbCustomButton, longPress: Boolean) -> Unit,
) {
    if (shadersAndStats) {
        PlayerMenuButton(
            icon = { Icon(Icons.Filled.HighQuality, contentDescription = "Shaders", tint = Color.White) },
            actions = MpvShaderActions,
            label = { action ->
                Text(action.label, fontWeight = if (selectedShader == action.label) FontWeight.Bold else FontWeight.Normal)
            },
            onSelect = onShader,
        )
        PlayerMenuButton(
            icon = { Icon(Icons.Filled.Memory, contentDescription = "Stats", tint = Color.White) },
            actions = MpvStatsActions,
            label = { action -> Text(action.label) },
            onSelect = onStats,
        )
    }
    if (customButtons.isEmpty() || !customButtonVisible) return
    var open by remember { mutableStateOf(false) }
    Box {
        IconButton(onClick = { open = true }) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Icon(Icons.Filled.Terminal, contentDescription = stringResource(Res.string.custom_buttons), tint = Color.White)
                activeCustomButtonTitle.takeIf { it.isNotBlank() }?.let {
                    Text(it, maxLines = 1, color = Color.White, style = MaterialTheme.typography.labelSmall)
                }
            }
        }
        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            customButtons.forEach { button ->
                val label = if (button.id == primaryCustomButtonId) {
                    activeCustomButtonTitle.ifBlank { button.title ?: "Button" }
                } else {
                    button.title ?: "Button"
                }
                DropdownMenuItem(
                    text = { Text(label) },
                    onClick = {
                        open = false
                        AppLogger.info("custom-button press '$label'")
                        onCustomButton(button, false)
                    },
                )
                if (button.codeLongPress.isNotBlank()) {
                    DropdownMenuItem(
                        text = { Text("$label (long press)") },
                        onClick = {
                            open = false
                            onCustomButton(button, true)
                        },
                    )
                }
            }
        }
    }
}

@Composable
private fun PlayerMenuButton(
    icon: @Composable () -> Unit,
    actions: List<MpvMenuAction>,
    label: @Composable (MpvMenuAction) -> Unit,
    onSelect: (MpvMenuAction) -> Unit,
) {
    var open by remember { mutableStateOf(false) }
    Box {
        IconButton(onClick = { open = true }, content = icon)
        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            actions.forEach { action ->
                DropdownMenuItem(
                    text = { label(action) },
                    onClick = {
                        open = false
                        onSelect(action)
                    },
                )
            }
        }
    }
}

private fun formatPlayerTime(seconds: Long): String {
    val s = seconds.coerceAtLeast(0)
    val mm = s / 60
    val ss = s % 60
    return "${mm.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')}"
}

/** Fixed-width timestamp used by Mangayomi's mobile seek bar. */
@Composable
private fun PlayerTimePill(text: String) {
    Box(
        modifier = Modifier.width(70.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            text = text,
            color = Color.White,
            style = MaterialTheme.typography.labelSmall,
        )
    }
}

/**
 * Timeline and action row. Reads the controller's position on every tick; the drag position and
 * the fit mode are local to the controller.
 */
@Composable
internal fun PlayerBottomControls(
    state: PlayerState,
    settings: DbSettings,
    controller: MediaPlayerController,
    tracks: PlayerTrackState,
    chapterMarks: List<MpvChapterMark>,
    currentChapterMark: Int,
    selectedShader: String,
    onShaderSelected: (String) -> Unit,
    customButtonVisible: Boolean,
    primaryCustomButtonId: Long?,
    activeCustomButtonTitle: String,
    onOpenSettings: () -> Unit,
    onEvent: (PlayerEvent) -> Unit,
    onNotice: (String) -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onInteraction: () -> Unit,
) {
    val playerPreferences = settings.features.player
    var dragPosition by remember(controller) { mutableStateOf<Float?>(null) }
    var videoFit by remember(controller) { mutableStateOf(MpvVideoFit.Contain) }
    // Subscribed reads: these recompose as the player ticks.
    val positionMs = controller.currentPositionMs()
    val durationMs = controller.durationMs()
    val aniSkipEpisodeLength = state.aniSkipMarkers.firstOrNull()?.episodeLengthSeconds?.takeIf { it > 0 } ?: 0.0
    // Prefer the file's real duration; fall back to AniSkip's reported episode length, then a
    // 10-minute sentinel so the slider isn't zero-width before metadata arrives.
    val effectiveDurationMs = when {
        durationMs > 0L -> durationMs
        aniSkipEpisodeLength > 0.0 -> (aniSkipEpisodeLength * 1000).toLong()
        else -> 600_000L
    }
    val position = dragPosition ?: (positionMs.toFloat() / effectiveDurationMs.toFloat()).coerceIn(0f, 1f)
    // The AniSkip segment around the current position powers the "Skip" button. Markers are scoped
    // to AniSkip's own episode length, which can differ from the file's duration.
    val activeAniSkipMarker = state.aniSkipMarkers.firstOrNull { marker ->
        if (marker.episodeLengthSeconds <= 0) return@firstOrNull false
        positionMs / 1000.0 in marker.startSeconds..marker.endSeconds
    }
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 18.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        PlayerTimeline(
            loading = state.loading,
            error = state.error,
            position = position,
            dragFraction = dragPosition,
            durationMs = effectiveDurationMs,
            seekThumbnails = state.seekThumbnails,
            seekSprites = state.seekSprites,
            onDrag = {
                dragPosition = it
                onInteraction()
            },
            onDragFinished = {
                controller.seekTo(((dragPosition ?: position) * effectiveDurationMs).toLong())
                dragPosition = null
            },
            onLoadSeekSprite = { onEvent(PlayerEvent.LoadSeekSprite(it)) },
        )
        PlayerActionRow(
            aniSkipType = activeAniSkipMarker?.type,
            skipIntroSeconds = settings.defaultSkipIntroLength,
            onSkip = {
                val targetMs = activeAniSkipMarker?.let { (it.endSeconds * 1000).toLong() }
                    ?: (positionMs + settings.defaultSkipIntroLength * 1000L)
                controller.seekTo(targetMs.coerceAtMost(effectiveDurationMs))
                onInteraction()
            },
            chapterMarks = chapterMarks,
            currentChapterMark = currentChapterMark,
            onSeekToMark = {
                controller.seekTo(it)
                onInteraction()
            },
            onOpenSettings = onOpenSettings,
            speed = tracks.playbackSpeed,
            speedPresets = playerPreferences.speedPresets,
            onSelectSpeed = { selected ->
                tracks.playbackSpeed = selected
                onUpdateSettings { it.copy(defaultPlaybackSpeed = selected.toDouble()) }
                onInteraction()
            },
            videoFit = videoFit,
            onCycleVideoFit = {
                videoFit = MpvVideoFit.entries[(videoFit.ordinal + 1) % MpvVideoFit.entries.size]
                if (!controller.setMpvVideoFit(videoFit)) onNotice("Fit modes require the mpv backend")
                onInteraction()
            },
            onToggleFullscreen = {
                onUpdateSettings { it.copy(fullScreenPlayer = !it.fullScreenPlayer) }
                onInteraction()
            },
        ) {
            PlayerMpvMenus(
                shadersAndStats = controller.isMpvBackend && settings.useMpvConfig,
                selectedShader = selectedShader,
                onShader = { action ->
                    onShaderSelected(action.label)
                    controller.selectMpvShader(action.command)
                    onInteraction()
                },
                onStats = { action ->
                    controller.showMpvStats(action.command)
                    onInteraction()
                },
                customButtons = state.customButtons,
                customButtonVisible = customButtonVisible,
                primaryCustomButtonId = primaryCustomButtonId,
                activeCustomButtonTitle = activeCustomButtonTitle,
                onCustomButton = { button, longPress ->
                    val sent = controller.executeMpvCommand("script-message", "call_button_${button.id}${if (longPress) "_long" else ""}")
                    if (!sent && !longPress) onNotice("Custom buttons require the mpv backend")
                },
            )
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerDialogs.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerDialogs.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerDialogs.kt).

The implementation below defines `EpisodeListDialog`, `PlayerDialog`, `Sheet`, `Cast`, `Episodes`, `IntPicker`, `PlayerDialogHost`, `PlayerInitError`, `MpvIntPickerDialog`.

The source describes its contract as:

> In-player episode picker, opened scrolled to \[currentEpisodeId\].

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`ScrollbarBox`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.PlaylistPlay
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.VideoLibrary
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.media.cast.CastDevice
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvIntPickerRequest
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.episodes
import yokan.composeapp.generated.resources.ok
import yokan.composeapp.generated.resources.retry
import yokan.composeapp.generated.resources.ui_close

/** In-player episode picker, opened scrolled to [currentEpisodeId]. */
@Composable
internal fun EpisodeListDialog(
    episodes: List<Chapter>,
    currentEpisodeId: Long,
    onEpisodeClick: (Chapter) -> Unit,
    onDismiss: () -> Unit,
) {
    val currentEpisodeIndex = episodes.indexOfFirst { it.id == currentEpisodeId }.coerceAtLeast(0)
    val episodeListState = rememberLazyListState(initialFirstVisibleItemIndex = currentEpisodeIndex)

    AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    Icons.AutoMirrored.Filled.PlaylistPlay,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                )
                Spacer(Modifier.width(12.dp))
                Text(
                    stringResource(Res.string.episodes),
                    modifier = Modifier.weight(1f),
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold,
                )
                IconButton(onClick = onDismiss) {
                    Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close))
                }
            }
        },
        text = {
            ScrollbarBox(
                state = episodeListState,
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 480.dp),
            ) {
                LazyColumn(
                    state = episodeListState,
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(6.dp),
                ) {
                    items(episodes, key = { it.id }) { episode ->
                        val isCurrent = episode.id == currentEpisodeId
                        ListItem(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(MaterialTheme.shapes.medium)
                                .clickable { onEpisodeClick(episode) },
                            colors = ListItemDefaults.colors(
                                containerColor = if (isCurrent) {
                                    MaterialTheme.colorScheme.primaryContainer
                                } else {
                                    Color.Transparent
                                },
                            ),
                            headlineContent = {
                                Text(
                                    episode.name,
                                    maxLines = 2,
                                    overflow = TextOverflow.Ellipsis,
                                    fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,
                                )
                            },
                            trailingContent = {
                                if (isCurrent) {
                                    Icon(
                                        Icons.Filled.PlayArrow,
                                        contentDescription = "Currently playing",
                                        tint = MaterialTheme.colorScheme.primary,
                                    )
                                }
                            },
                        )
                    }
                }
            }
        },
        confirmButton = {},
    )
}

/** The player's one open dialog or sheet. */
internal sealed interface PlayerDialog {
    data class Sheet(val tab: PlayerSheetTab) : PlayerDialog
    data object Cast : PlayerDialog
    /** [resume] restarts playback the list paused when it closes without switching episodes. */
    data class Episodes(val resume: Boolean) : PlayerDialog
    data class IntPicker(val request: MpvIntPickerRequest) : PlayerDialog
}

@Composable
internal fun PlayerDialogHost(
    dialog: PlayerDialog,
    state: PlayerState,
    settings: DbSettings,
    chapter: Chapter,
    controller: MediaPlayerController,
    tracks: PlayerTrackState,
    isPlaying: Boolean,
    onDialog: (PlayerDialog?) -> Unit,
    onStartCasting: (CastDevice?) -> Unit,
    onEvent: (PlayerEvent) -> Unit,
    onNotice: (String) -> Unit,
    onOpenEpisode: (Chapter) -> Unit,
    onOpenPlayerSettings: () -> Unit,
    onInteraction: () -> Unit,
) {
    when (dialog) {
        is PlayerDialog.IntPicker -> MpvIntPickerDialog(
            request = dialog.request,
            onConfirm = { value ->
                controller.executeMpvCommand("set", dialog.request.property, value.toString())
                onDialog(null)
            },
            onDismiss = { onDialog(null) },
        )
        PlayerDialog.Cast -> CastDeviceDialog(
            devices = state.castDevices,
            onDiscovery = { onEvent(PlayerEvent.SetCastDiscovery(it)) },
            onSelect = onStartCasting,
            onDismiss = { onDialog(null) },
        )
        is PlayerDialog.Sheet -> PlayerSettingsSheet(
            tab = dialog.tab,
            tracks = tracks,
            videos = state.videos,
            selectedVideo = state.selectedVideo,
            audioPreferredLanguages = settings.audioPreferredLanguages,
            onEvent = { event ->
                when (event) {
                    is PlayerSheetEvent.SelectTab -> onDialog(PlayerDialog.Sheet(event.tab))
                    is PlayerSheetEvent.SelectVideo -> {
                        val handoff = qualityVideoHandoff(controller.currentPositionMs(), isPlaying)
                        onEvent(PlayerEvent.SelectVideo(event.video, handoff.startPositionMs, handoff.autoplay))
                        onDialog(null)
                    }
                    PlayerSheetEvent.OpenExternalPlayer -> state.selectedVideo?.let { video ->
                        controller.pause()
                        onDialog(null)
                        onEvent(PlayerEvent.OpenExternalPlayer(video))
                    }
                    PlayerSheetEvent.OpenPlayerSettings -> {
                        onDialog(null)
                        onOpenPlayerSettings()
                    }
                    is PlayerTrackEvent -> if (!tracks.apply(controller, event)) {
                        onNotice("Secondary subtitles are unavailable on this backend")
                    }
                }
            },
            onDismiss = { onDialog(null) },
        )
        is PlayerDialog.Episodes -> {
            val close: (resume: Boolean) -> Unit = { resume ->
                onDialog(null)
                if (resume && dialog.resume) controller.play()
            }
            EpisodeListDialog(
                episodes = state.visibleEpisodes,
                currentEpisodeId = chapter.id,
                onEpisodeClick = { episode ->
                    close(episode.id == chapter.id)
                    if (episode.id != chapter.id) onOpenEpisode(episode)
                },
                onDismiss = {
                    close(true)
                    onInteraction()
                },
            )
        }
    }
}

/** The controller is being created, or failed to: [error] with back and retry. */
@Composable
internal fun PlayerInitError(error: String?, onBack: () -> Unit, onRetry: () -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black),
        contentAlignment = Alignment.Center,
    ) {
        if (error == null) {
            LinearProgressIndicator(modifier = Modifier.width(160.dp))
            return@Box
        }
        Column(
            modifier = Modifier.padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Icon(
                Icons.Filled.VideoLibrary,
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier.size(56.dp),
            )
            Text(
                "Unable to initialize video player",
                color = Color.White,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
            Text(
                error,
                color = Color.White.copy(alpha = 0.7f),
                style = MaterialTheme.typography.bodySmall,
                textAlign = TextAlign.Center,
            )
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                OutlinedButton(onClick = onBack) {
                    Text(stringResource(Res.string.action_back))
                }
                Button(onClick = onRetry) {
                    Text(stringResource(Res.string.retry))
                }
            }
        }
    }
}

/** An mpv script's `aniyomi.int_picker`: confirming sets the request's property to the picked value. */
@Composable
internal fun MpvIntPickerDialog(request: MpvIntPickerRequest, onConfirm: (Int) -> Unit, onDismiss: () -> Unit) {
    var value by remember(request) { mutableIntStateOf(request.start) }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(request.title) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Text(request.valueFormat.replace("%d", value.toString()))
                Slider(
                    value = value.toFloat(),
                    onValueChange = { raw ->
                        val stepsFromStart = ((raw - request.start) / request.step).toInt()
                        value = (request.start + stepsFromStart * request.step).coerceIn(request.start, request.stop)
                    },
                    valueRange = request.start.toFloat()..request.stop.toFloat(),
                    steps = (((request.stop - request.start) / request.step) - 1).coerceAtLeast(0),
                )
            }
        },
        confirmButton = {
            TextButton(onClick = { onConfirm(value) }) { Text(stringResource(Res.string.ok)) }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
        },
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerServicesBinding.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerServicesBinding.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerServicesBinding.kt).

The implementation below defines `rememberPlayerServices`, `PlayerControllerEffect`, `PlayerPlaybackEffects`, `takeScreenshot`, `PlayerSleepTimerEffect`.

The source describes its contract as:

> The captured callback saves this episode before its owned controller is released.

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`AppLogger`](../chapters/24-settings-and-integrations.md), [`nowMillis`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.withPlayer
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices
import eu.friedcutlet.yokan.services.media.player.SleepTimer
import eu.friedcutlet.yokan.services.media.player.isDue
import eu.friedcutlet.yokan.util.nowMillis
import eu.friedcutlet.yokan.services.media.player.preferredSubtitle
import eu.friedcutlet.yokan.services.media.player.setPlayerScreenBrightness
import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.player_screenshot_failed
import yokan.composeapp.generated.resources.player_screenshot_saved
import yokan.composeapp.generated.resources.player_screenshot_unavailable

@Composable
internal fun rememberPlayerServices(services: ProfilePlayerServices, chapterId: Long): ProfilePlayerServices.Reader {
    val reader = remember(services, chapterId) { services.reader() }
    DisposableEffect(reader) {
        onDispose { reader.retire() }
    }
    return reader
}

/** The captured callback saves this episode before its owned controller is released. */
@Composable
internal fun PlayerControllerEffect(
    player: ProfilePlayerServices.Reader,
    configuration: MediaPlayerConfiguration,
    initializationAttempt: Int,
    onController: (MediaPlayerController?) -> Unit,
    onSavePosition: (Long, Long) -> Unit,
    onInitializationError: (Throwable?) -> Unit,
) {
    LaunchedEffect(player, configuration, initializationAttempt) {
        val uiContext = currentCoroutineContext().minusKey(Job)
        onInitializationError(null)
        try {
            player.prepareConfiguration(configuration)
            player.withController(configuration) { controller ->
                withContext(uiContext) {
                    currentCoroutineContext().ensureActive()
                    player.ensureOpen()
                    onController(controller)
                    try { awaitCancellation() }
                    finally {
                        withContext(NonCancellable) {
                            try { onSavePosition(controller.currentPositionMs(), controller.durationMs()) }
                            finally { onController(null) }
                        }
                    }
                }
            }
        } catch (failure: CancellationException) {
            throw failure
        } catch (failure: Throwable) {
            currentCoroutineContext().ensureActive()
            player.ensureOpen()
            onInitializationError(failure)
        }
    }
}

/** Effects that drive the controller from [state], [tracks] and the settings. */
@Composable
internal fun PlayerPlaybackEffects(
    player: ProfilePlayerServices.Reader,
    controller: MediaPlayerController,
    configuration: MediaPlayerConfiguration,
    state: PlayerState,
    settings: DbSettings,
    tracks: PlayerTrackState,
    episodeListOpen: Boolean,
    setPlaying: (Boolean) -> Unit,
    /** True where the screen brightness can't be set, so the video is dimmed instead. */
    onDimVideo: (Boolean) -> Unit,
    onEvent: (PlayerEvent) -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
) {
    val playerPreferences = settings.features.player
    LaunchedEffect(player, controller, state.selectedVideo) {
        player.ensureOpen()
        val video = state.selectedVideo ?: return@LaunchedEffect
        controller.load(video.url, video.headers.orEmpty(), state.startPositionMs)
        tracks.applyStreamDefaults(
            controller = controller,
            subtitle = preferredSubtitle(
                tracks = video.subtitles,
                languages = playerPreferences.subtitleLanguages.ifEmpty { listOfNotNull(settings.defaultSubtitleLang?.languageCode) },
                whitelist = playerPreferences.subtitleWhitelist,
                blacklist = playerPreferences.subtitleBlacklist,
            ),
            audio = video.audios.firstOrNull(),
        )
        controller.setVolume(tracks.volume)
        controller.setPlaybackSpeed(tracks.playbackSpeed)
        if (state.autoplay && !episodeListOpen) controller.play() else controller.pause()
    }
    LaunchedEffect(player, controller, state.customButtons, configuration.useMpvConfig) {
        player.installCustomButtons(controller, state.customButtons, configuration)
    }
    LaunchedEffect(player, controller, tracks.playbackSpeed) {
        player.ensureOpen()
        if (state.selectedVideo != null) controller.setPlaybackSpeed(tracks.playbackSpeed)
    }
    val volume = tracks.volume
    LaunchedEffect(player, controller, volume) {
        controller.setVolume(volume)
        if (!playerPreferences.rememberVolume || volume == playerPreferences.volume) return@LaunchedEffect
        delay(500) // persist once the slider settles
        onUpdateSettings { db -> db.withPlayer { it.copy(volume = volume) } }
    }
    DisposableEffect(player) { onDispose { setPlayerScreenBrightness(null) } }
    val brightness = tracks.brightness
    LaunchedEffect(brightness) {
        onDimVideo(!setPlayerScreenBrightness(brightness) && brightness != null)
        val level = brightness ?: return@LaunchedEffect
        if (!playerPreferences.rememberBrightness || level == playerPreferences.brightness) return@LaunchedEffect
        delay(500)
        onUpdateSettings { db -> db.withPlayer { it.copy(brightness = level) } }
    }
    val playbackError = controller.playbackError
    LaunchedEffect(playbackError) {
        if (playbackError != null) onEvent(PlayerEvent.PlaybackFailed(playbackError, controller.currentPositionMs()))
    }
    // The receiver plays the episode while a cast session is active.
    val casting = state.castStatus != null
    LaunchedEffect(controller, casting) {
        if (casting) setPlaying(false)
    }
}

/** The notice for a screenshot of the current frame. */
internal suspend fun takeScreenshot(
    player: ProfilePlayerServices.Reader,
    controller: MediaPlayerController,
    manga: Manga,
    chapter: Chapter,
    includeSubtitles: Boolean,
): String {
    val notice = try {
        val path = player.requestScreenshot(controller, manga.name, chapter.name, includeSubtitles)
        when {
            path != null -> getString(Res.string.player_screenshot_saved, path)
            controller.isMpvBackend -> getString(Res.string.player_screenshot_failed)
            else -> getString(Res.string.player_screenshot_unavailable)
        }
    } catch (cancelled: CancellationException) {
        throw cancelled
    } catch (failure: Throwable) {
        currentCoroutineContext().ensureActive()
        player.ensureOpen()
        AppLogger.error("[player] screenshot failed: ${failure.message.orEmpty()}")
        getString(Res.string.player_screenshot_failed)
    }
    currentCoroutineContext().ensureActive()
    player.ensureOpen()
    return notice
}

/** Polls a pending [timer] each second and reports it once due. */
@Composable
internal fun PlayerSleepTimerEffect(timer: SleepTimer?, controller: MediaPlayerController, onDue: (SleepTimer) -> Unit) {
    LaunchedEffect(timer, controller) {
        val pending = timer ?: return@LaunchedEffect
        while (!pending.isDue(nowMillis(), controller.currentPositionMs(), controller.durationMs())) delay(1_000)
        onDue(pending)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerSettingsSheet.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerSettingsSheet.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerSettingsSheet.kt).

The implementation below defines `PlayerSheetTab`, `PlayerSheetEvent`, `SelectTab`, `SelectVideo`, `OpenExternalPlayer`, `OpenPlayerSettings`, `PlayerTrackEvent`, `SelectSubtitle`, `SelectSecondarySubtitle`, `SelectAudio` and 11 further declarations.

The source describes its contract as:

> Changes to \[PlayerTrackState\]; \[PlayerTrackState.apply\] forwards them to the controller.

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md), [`ScrollbarBox`](../chapters/10-navigation-and-design-system.md), [`formatDecimal`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Slider
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.selectAudioTrack
import eu.friedcutlet.yokan.services.media.player.setAudioDelay
import eu.friedcutlet.yokan.services.media.player.setSubtitleDelay
import eu.friedcutlet.yokan.services.media.player.setSubtitleSpeed
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.ui.formatDecimal
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_player_settings
import yokan.composeapp.generated.resources.ui_subtitles

/** Pages of [PlayerSettingsSheet]. */
internal enum class PlayerSheetTab { Quality, Subtitles, Audio }

internal sealed interface PlayerSheetEvent {
    data class SelectTab(val tab: PlayerSheetTab) : PlayerSheetEvent
    data class SelectVideo(val video: DbVideo) : PlayerSheetEvent
    data object OpenExternalPlayer : PlayerSheetEvent
    data object OpenPlayerSettings : PlayerSheetEvent
}

/** Changes to [PlayerTrackState]; [PlayerTrackState.apply] forwards them to the controller. */
internal sealed interface PlayerTrackEvent : PlayerSheetEvent {
    data class SelectSubtitle(val file: String?, val label: String?) : PlayerTrackEvent
    data class SelectSecondarySubtitle(val file: String?, val label: String?) : PlayerTrackEvent
    data class SelectAudio(val file: String?, val label: String?) : PlayerTrackEvent
    data class SetSubtitleDelay(val ms: Int) : PlayerTrackEvent
    data class SetSecondarySubtitleDelay(val ms: Int) : PlayerTrackEvent
    data class SetSubtitleSpeed(val speed: Float) : PlayerTrackEvent
    data class SetAudioDelay(val ms: Int) : PlayerTrackEvent
    data class SetVolume(val percent: Int) : PlayerTrackEvent
    data class SetBrightness(val level: Float?) : PlayerTrackEvent
}

/**
 * One controller's track, delay and level choices, kept by the screen per player and episode.
 * Speed, volume and brightness are applied by the screen's effects; the rest by [apply].
 */
@Stable
internal class PlayerTrackState(playbackSpeed: Float, volume: Int, brightness: Float?) {
    var subtitleFile by mutableStateOf<String?>(null)
        private set
    var secondarySubtitleFile by mutableStateOf<String?>(null)
        private set
    var audioFile by mutableStateOf<String?>(null)
        private set
    var subtitleDelayMs by mutableIntStateOf(0)
        private set
    var secondarySubtitleDelayMs by mutableIntStateOf(0)
        private set
    var subtitleSpeed by mutableFloatStateOf(1f)
        private set
    var audioDelayMs by mutableIntStateOf(0)
        private set
    var playbackSpeed by mutableFloatStateOf(playbackSpeed)
    /** Percent, 0..100. */
    var volume by mutableIntStateOf(volume)
        private set
    /** 0..1, or null for the system brightness. */
    var brightness by mutableStateOf(brightness)
        private set

    /** Selects [subtitle] and [audio] for a newly loaded stream and drops the secondary subtitle. */
    fun applyStreamDefaults(controller: MediaPlayerController, subtitle: DbVideoTrack?, audio: DbVideoTrack?) {
        subtitleFile = subtitle?.file
        audioFile = audio?.file
        secondarySubtitleFile = null
        subtitle?.file?.let { controller.selectSubtitleTrack(it, subtitle.label) }
        audio?.file?.let { controller.selectAudioTrack(it, audio.label) }
    }

    /** False when the backend has no secondary subtitles. */
    fun apply(controller: MediaPlayerController, event: PlayerTrackEvent): Boolean {
        when (event) {
            is PlayerTrackEvent.SelectSubtitle -> {
                subtitleFile = event.file
                controller.selectSubtitleTrack(event.file, event.label)
            }
            is PlayerTrackEvent.SelectSecondarySubtitle -> {
                secondarySubtitleFile = event.file
                return controller.selectSecondarySubtitle(event.file, event.label)
            }
            is PlayerTrackEvent.SelectAudio -> {
                audioFile = event.file
                controller.selectAudioTrack(event.file, event.label)
            }
            is PlayerTrackEvent.SetSubtitleDelay -> {
                subtitleDelayMs = event.ms
                controller.setSubtitleDelay(event.ms)
            }
            is PlayerTrackEvent.SetSecondarySubtitleDelay -> {
                secondarySubtitleDelayMs = event.ms
                controller.setSecondarySubtitleDelay(event.ms)
            }
            is PlayerTrackEvent.SetSubtitleSpeed -> {
                subtitleSpeed = event.speed
                controller.setSubtitleSpeed(event.speed.toDouble())
            }
            is PlayerTrackEvent.SetAudioDelay -> {
                audioDelayMs = event.ms
                controller.setAudioDelay(event.ms)
            }
            is PlayerTrackEvent.SetVolume -> volume = event.percent
            is PlayerTrackEvent.SetBrightness -> brightness = event.level
        }
        return true
    }
}

/** Player bottom sheet with quality, subtitle, and audio tabs. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun PlayerSettingsSheet(
    tab: PlayerSheetTab,
    tracks: PlayerTrackState,
    videos: List<DbVideo>,
    selectedVideo: DbVideo?,
    audioPreferredLanguages: String?,
    onEvent: (PlayerSheetEvent) -> Unit,
    onDismiss: () -> Unit,
) {
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactSheetWidth(),
    ) {
        val sheetScroll = rememberScrollState()
        ScrollbarBox(state = sheetScroll, modifier = Modifier.fillMaxWidth()) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(sheetScroll),
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    SecondaryTabRow(
                        selectedTabIndex = tab.ordinal,
                        modifier = Modifier.weight(1f),
                    ) {
                        val labels = listOf("Video quality", stringResource(Res.string.ui_subtitles), "Video audio")
                        PlayerSheetTab.entries.forEach { entry ->
                            Tab(
                                selected = tab == entry,
                                onClick = { onEvent(PlayerSheetEvent.SelectTab(entry)) },
                                text = { Text(labels[entry.ordinal], maxLines = 1) },
                            )
                        }
                    }
                    IconButton(onClick = { onEvent(PlayerSheetEvent.OpenPlayerSettings) }) {
                        Icon(Icons.Filled.Settings, contentDescription = stringResource(Res.string.ui_player_settings))
                    }
                }
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 12.dp, vertical = 15.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp),
                ) {
                    when (tab) {
                        PlayerSheetTab.Quality -> {
                            videos.forEach { video ->
                                PlayerSheetOption(
                                    text = video.quality.ifBlank { "Auto" },
                                    selected = selectedVideo == video,
                                    onClick = { onEvent(PlayerSheetEvent.SelectVideo(video)) },
                                )
                            }
                            if (selectedVideo != null) {
                                PlayerSheetOption(
                                    text = "Open in external player",
                                    selected = false,
                                    onClick = { onEvent(PlayerSheetEvent.OpenExternalPlayer) },
                                )
                            }
                            val brightness = tracks.brightness
                            Text(
                                "Brightness: ${brightness?.let { "${(it * 100).toInt()}%" } ?: "System"}",
                                style = MaterialTheme.typography.labelLarge,
                            )
                            Slider(
                                value = brightness ?: 1f,
                                onValueChange = { onEvent(PlayerTrackEvent.SetBrightness(it)) },
                                valueRange = 0f..1f,
                            )
                            if (brightness != null) {
                                PlayerSheetOption(text = "Use system brightness", selected = false, onClick = { onEvent(PlayerTrackEvent.SetBrightness(null)) })
                            }
                        }

                        PlayerSheetTab.Subtitles -> {
                            PlayerSheetOption(
                                text = "None",
                                selected = tracks.subtitleFile == null,
                                onClick = { onEvent(PlayerTrackEvent.SelectSubtitle(null, null)) },
                            )
                            selectedVideo?.subtitles.orEmpty().forEach { subtitle ->
                                PlayerSheetOption(
                                    text = subtitle.label ?: subtitle.file ?: "Subtitle",
                                    selected = tracks.subtitleFile == subtitle.file,
                                    onClick = { onEvent(PlayerTrackEvent.SelectSubtitle(subtitle.file, subtitle.label)) },
                                )
                            }
                            Text("Subtitle delay: ${tracks.subtitleDelayMs}ms", style = MaterialTheme.typography.labelLarge)
                            Slider(
                                value = tracks.subtitleDelayMs.toFloat(),
                                onValueChange = { onEvent(PlayerTrackEvent.SetSubtitleDelay(it.toInt())) },
                                valueRange = -10_000f..10_000f,
                            )
                            Text("Subtitle speed: ${formatDecimal(tracks.subtitleSpeed.toDouble(), 2)}x", style = MaterialTheme.typography.labelLarge)
                            Slider(
                                value = tracks.subtitleSpeed,
                                onValueChange = { onEvent(PlayerTrackEvent.SetSubtitleSpeed(it)) },
                                valueRange = 0.1f..10f,
                            )
                            Text("Secondary subtitle", style = MaterialTheme.typography.titleSmall)
                            PlayerSheetOption(
                                text = "None",
                                selected = tracks.secondarySubtitleFile == null,
                                onClick = { onEvent(PlayerTrackEvent.SelectSecondarySubtitle(null, null)) },
                            )
                            selectedVideo?.subtitles.orEmpty().filter { it.file != tracks.subtitleFile }.forEach { subtitle ->
                                PlayerSheetOption(
                                    text = subtitle.label ?: subtitle.file ?: "Subtitle",
                                    selected = tracks.secondarySubtitleFile == subtitle.file,
                                    onClick = { onEvent(PlayerTrackEvent.SelectSecondarySubtitle(subtitle.file, subtitle.label)) },
                                )
                            }
                            if (tracks.secondarySubtitleFile != null) {
                                Text("Secondary delay: ${tracks.secondarySubtitleDelayMs}ms", style = MaterialTheme.typography.labelLarge)
                                Slider(
                                    value = tracks.secondarySubtitleDelayMs.toFloat(),
                                    onValueChange = { onEvent(PlayerTrackEvent.SetSecondarySubtitleDelay(it.toInt())) },
                                    valueRange = -10_000f..10_000f,
                                )
                            }
                        }

                        PlayerSheetTab.Audio -> {
                            Text("Volume: ${tracks.volume}%", style = MaterialTheme.typography.labelLarge)
                            Slider(
                                value = tracks.volume.toFloat(),
                                onValueChange = { onEvent(PlayerTrackEvent.SetVolume(it.toInt())) },
                                valueRange = 0f..100f,
                            )
                            PlayerSheetOption(
                                text = "None",
                                selected = tracks.audioFile == null,
                                onClick = { onEvent(PlayerTrackEvent.SelectAudio(null, null)) },
                            )
                            selectedVideo?.audios.orEmpty().forEach { audio ->
                                PlayerSheetOption(
                                    text = audio.label ?: audio.file ?: "Audio",
                                    selected = tracks.audioFile == audio.file,
                                    onClick = { onEvent(PlayerTrackEvent.SelectAudio(audio.file, audio.label)) },
                                )
                            }
                            Text("Audio delay: ${tracks.audioDelayMs}ms", style = MaterialTheme.typography.labelLarge)
                            Slider(
                                value = tracks.audioDelayMs.toFloat(),
                                onValueChange = { onEvent(PlayerTrackEvent.SetAudioDelay(it.toInt())) },
                                valueRange = -10_000f..10_000f,
                            )
                            audioPreferredLanguages?.takeIf { it.isNotBlank() }?.let { langs ->
                                Text(
                                    "Preferred: $langs",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun PlayerSheetOption(
    text: String,
    selected: Boolean,
    onClick: () -> Unit = {},
) {
    Text(
        text = text,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clickable(onClick = onClick),
        color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
        fontStyle = if (selected) androidx.compose.ui.text.font.FontStyle.Italic else androidx.compose.ui.text.font.FontStyle.Normal,
        style = MaterialTheme.typography.bodyLarge,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBinding.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBinding.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBinding.kt).

The implementation below defines `PlayerUiBinding`, `active`, `close`, `collectBridgeEvents`, `rememberPlayerUiBinding`, `PlayerBridgeEffect`, `rememberPlayerPictureInPicture`.

The source describes its contract as:

> UI callbacks retain one reader/controller and expire independently of native playback.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvBridgeEvent
import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServices
import eu.friedcutlet.yokan.services.media.player.PlayerPictureInPictureOwners
import eu.friedcutlet.yokan.services.media.player.PictureInPicturePlaybackOwners
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext

/** UI callbacks retain one reader/controller and expire independently of native playback. */
internal class PlayerUiBinding(
    private val reader: ProfilePlayerServices.Reader,
    internal val controller: MediaPlayerController?,
    ownerScope: CoroutineScope,
    private val isUiActive: () -> Boolean = { true },
) {
    private val job = SupervisorJob(requireNotNull(ownerScope.coroutineContext[Job]))
    private val scope = CoroutineScope(ownerScope.coroutineContext + job)

    fun active(): Boolean = job.isActive && reader.isAvailable && controller != null && isUiActive()
    fun close() { job.cancel() }

    suspend fun collectBridgeEvents(onEvent: (MpvBridgeEvent) -> Unit) {
        currentCoroutineContext().ensureActive()
        val captured = controller ?: return
        if (!active()) return
        val work = scope.async {
            reader.collectBridgeEvents(captured) { event -> if (active()) onEvent(event) }
        }
        try { work.await() }
        finally { withContext(NonCancellable) { work.cancelAndJoin() } }
    }
}

@Composable
internal fun rememberPlayerUiBinding(
    reader: ProfilePlayerServices.Reader,
    controller: MediaPlayerController?,
): PlayerUiBinding {
    val scope = rememberCoroutineScope()
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    var epoch by remember(lifecycle) { mutableIntStateOf(0) }
    val state by lifecycle.currentStateFlow.collectAsStateWithLifecycle(minActiveState = Lifecycle.State.CREATED)
    val started = state.isAtLeast(Lifecycle.State.STARTED)
    val binding = remember(reader, controller, lifecycle, started, epoch) {
        PlayerUiBinding(reader, controller, scope) { lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) }
    }
    DisposableEffect(binding) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_STOP || event == Lifecycle.Event.ON_DESTROY) {
                binding.close()
                epoch += 1
            }
        }
        lifecycle.addObserver(observer)
        onDispose { lifecycle.removeObserver(observer); binding.close() }
    }
    return binding
}

@Composable
internal fun PlayerBridgeEffect(binding: PlayerUiBinding, onEvent: (MpvBridgeEvent) -> Unit) {
    val latestHandler by rememberUpdatedState(onEvent)
    LaunchedEffect(binding) { binding.collectBridgeEvents { latestHandler(it) } }
}

@Composable
internal fun rememberPlayerPictureInPicture(
    binding: PlayerUiBinding,
    playing: Boolean,
    owners: PictureInPicturePlaybackOwners = PlayerPictureInPictureOwners,
): () -> Boolean {
    val owner = remember(owners, binding) { owners.create(binding::active, binding.controller) }
    DisposableEffect(owner) { owner.activate(); onDispose { owner.close() } }
    SideEffect { owner.update(playing) }
    return remember(owner) { { owner.request() } }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.android.kt).

The implementation below defines `setPlayerScreenBrightness`.

Cross-chapter imports used by this file: [`AndroidForegroundActivity`](../chapters/23-platform-hosts-and-adapters.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import android.view.WindowManager
import eu.friedcutlet.yokan.AndroidForegroundActivity

internal actual fun setPlayerScreenBrightness(level: Float?): Boolean {
    val activity = AndroidForegroundActivity.activity ?: return false
    activity.runOnUiThread {
        val window = activity.window ?: return@runOnUiThread
        window.attributes = window.attributes.apply {
            screenBrightness = level?.coerceIn(0.01f, 1f) ?: WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
        }
    }
    return true
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.android.kt).

The implementation below defines `MediaPlayerSurface`, `OwnedMpvSurfaceView`, `surfaceCreated`, `surfaceChanged`, `surfaceDestroyed`, `retire`.

Cross-chapter imports used by this file: [`MpvRenderTarget`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import android.content.Context
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController
import io.github.kmpmpv.MpvRenderTarget
import kotlin.coroutines.CoroutineContext

@Composable
actual fun MediaPlayerSurface(controller: MediaPlayerController, modifier: Modifier) {
    when (controller) {
        is MpvMediaPlayerController -> key(controller) {
            val scope = rememberCoroutineScope()
            AndroidView(
                modifier = modifier,
                factory = { context -> OwnedMpvSurfaceView(context, controller, scope.coroutineContext) },
                onRelease = { it.retire() },
            )
        }
        else -> ComposeMediaPlayerSurface(controller, modifier)
    }
}

private class OwnedMpvSurfaceView(
    context: Context,
    controller: MpvMediaPlayerController,
    coroutineContext: CoroutineContext,
) : SurfaceView(context), SurfaceHolder.Callback {
    private val binding = controller.bindNativeSurface(coroutineContext) { holder.removeCallback(this) }
    init {
        if (binding != null) {
            holder.addCallback(this)
            if (holder.surface.isValid) surfaceCreated(holder)
        }
    }
    override fun surfaceCreated(holder: SurfaceHolder) {
        binding?.attach(MpvRenderTarget(holder.surface), width, height)
    }
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        binding?.resize(width, height)
    }
    override fun surfaceDestroyed(holder: SurfaceHolder) { binding?.detach() }
    fun retire() {
        holder.removeCallback(this)
        binding?.retire()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.desktop.kt).

The implementation below defines `setPlayerScreenBrightness`.

The source describes its contract as:

> No application-controlled display brightness here; the player dims the video instead.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/** No application-controlled display brightness here; the player dims the video instead. */
internal actual fun setPlayerScreenBrightness(level: Float?): Boolean = false
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.desktop.kt).

The implementation below defines `MediaPlayerSurface`, `MpvDesktopSoftwareSurface`, `IntSize.cappedTo`, `DrawScope.drawFitted`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageBitmapConfig
import androidx.compose.ui.graphics.asSkiaBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.currentCoroutineContext
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorInfo
import org.jetbrains.skia.ColorSpace
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.ImageInfo

@Composable
actual fun MediaPlayerSurface(controller: MediaPlayerController, modifier: Modifier) {
    when (controller) {
        is MpvMediaPlayerController -> MpvDesktopSoftwareSurface(controller, modifier)
        else -> ComposeMediaPlayerSurface(controller, modifier)
    }
}

@Composable
private fun MpvDesktopSoftwareSurface(
    controller: MpvMediaPlayerController,
    modifier: Modifier,
) {
    var outputSize by remember { mutableStateOf(IntSize.Zero) }
    // Each render effect owns its state; an old effect's cleanup cannot close a new frame.
    var bitmap by remember(controller, outputSize) { mutableStateOf<ImageBitmap?>(null) }
    var bitmapSize by remember(controller, outputSize) { mutableStateOf(IntSize.Zero) }
    var revision by remember(controller) { mutableLongStateOf(0L) }
    var renderError by remember(controller, outputSize) { mutableStateOf<String?>(null) }

    Box(modifier = modifier.background(Color.Black)) {
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .onSizeChanged { outputSize = it },
        ) {
            revision
            bitmap?.let { frame -> drawFitted(frame, size) }
        }
        renderError?.let { message ->
            Text(
                text = message,
                color = Color.White,
                modifier = Modifier.align(Alignment.Center),
            )
        }
    }

    LaunchedEffect(controller, outputSize) {
        if (outputSize.width <= 0 || outputSize.height <= 0) return@LaunchedEffect
        val renderSize = outputSize.cappedTo(1920, 1080)
        renderError = null
        val imageInfo = ImageInfo(
            ColorInfo(ColorType.BGRA_8888, ColorAlphaType.OPAQUE, ColorSpace.sRGB),
            renderSize.width,
            renderSize.height,
        )
        controller.withSoftwareRendering { renderer ->
            try {
                while (currentCoroutineContext().isActive) {
                    val frame = try {
                        renderer.renderFrame(renderSize.width, renderSize.height)
                    } catch (cancelled: CancellationException) {
                        throw cancelled
                    } catch (failure: Throwable) {
                        val detail = failure.message.orEmpty()
                        AppLogger.error("[player] desktop mpv render failed: $detail")
                        renderError = "Video renderer failed${detail.takeIf(String::isNotBlank)?.let { ": $it" }.orEmpty()}"
                        return@withSoftwareRendering
                    }

                    val target = if (bitmap == null || bitmapSize != renderSize) {
                        bitmap?.asSkiaBitmap()?.close()
                        ImageBitmap(
                            width = renderSize.width,
                            height = renderSize.height,
                            config = ImageBitmapConfig.Argb8888,
                            hasAlpha = false,
                        ).also {
                            bitmap = it
                            bitmapSize = renderSize
                        }
                    } else {
                        checkNotNull(bitmap)
                    }
                    check(target.asSkiaBitmap().installPixels(imageInfo, frame.pixels, frame.strideBytes)) {
                        "Skia rejected the mpv software frame"
                    }
                    revision++
                    // Keep paused OSD/subtitle updates responsive without copying 1080p frames 30 times/sec.
                    delay(if (controller.player.state.value.paused) 250L else 33L)
                }
            } finally {
                // Remove pixels from the canvas before closing them on this UI context.
                val retiredBitmap = bitmap
                bitmap = null
                bitmapSize = IntSize.Zero
                retiredBitmap?.asSkiaBitmap()?.close()
            }
        }
    }
}

private fun IntSize.cappedTo(maxWidth: Int, maxHeight: Int): IntSize {
    val scale = minOf(1.0, maxWidth.toDouble() / width, maxHeight.toDouble() / height)
    return IntSize(
        width = (width * scale).toInt().coerceAtLeast(1),
        height = (height * scale).toInt().coerceAtLeast(1),
    )
}

private fun DrawScope.drawFitted(frame: ImageBitmap, destination: Size) {
    val scale = minOf(destination.width / frame.width, destination.height / frame.height)
    val width = (frame.width * scale).toInt().coerceAtLeast(1)
    val height = (frame.height * scale).toInt().coerceAtLeast(1)
    val left = ((destination.width - width) / 2f).toInt()
    val top = ((destination.height - height) / 2f).toInt()
    drawImage(
        image = frame,
        dstOffset = IntOffset(left, top),
        dstSize = IntSize(width, height),
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.ios.kt).

The implementation below defines `setPlayerScreenBrightness`.

The source describes its contract as:

> UIScreen brightness is system-wide, so the value before the first change is restored on exit.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import platform.UIKit.UIScreen

/** UIScreen brightness is system-wide, so the value before the first change is restored on exit. */
private var systemBrightness: Double? = null

internal actual fun setPlayerScreenBrightness(level: Float?): Boolean {
    val screen = UIScreen.mainScreen
    if (level == null) {
        systemBrightness?.let { screen.brightness = it }
        systemBrightness = null
    } else {
        if (systemBrightness == null) systemBrightness = screen.brightness
        screen.brightness = level.coerceIn(0f, 1f).toDouble()
    }
    return true
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.ios.kt).

The implementation below defines `MediaPlayerSurface`, `MpvIosSoftwareSurface`, `IntSize.cappedTo`, `DrawScope.drawFitted`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageBitmapConfig
import androidx.compose.ui.graphics.asSkiaBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntSize
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.currentCoroutineContext
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorInfo
import org.jetbrains.skia.ColorSpace
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.ImageInfo

@Composable
actual fun MediaPlayerSurface(controller: MediaPlayerController, modifier: Modifier) {
    when (controller) {
        is MpvMediaPlayerController -> MpvIosSoftwareSurface(controller, modifier)
        else -> ComposeMediaPlayerSurface(controller, modifier)
    }
}

@Composable
private fun MpvIosSoftwareSurface(
    controller: MpvMediaPlayerController,
    modifier: Modifier,
) {
    var outputSize by remember { mutableStateOf(IntSize.Zero) }
    // Each render effect owns its state; an old effect's cleanup cannot close a new frame.
    var bitmap by remember(controller, outputSize) { mutableStateOf<ImageBitmap?>(null) }
    var bitmapSize by remember(controller, outputSize) { mutableStateOf(IntSize.Zero) }
    var revision by remember(controller) { mutableLongStateOf(0L) }

    Canvas(
        modifier = modifier
            .background(Color.Black)
            .onSizeChanged { outputSize = it },
    ) {
        revision
        bitmap?.let { frame -> drawFitted(frame, size) }
    }

    LaunchedEffect(controller, outputSize) {
        if (outputSize.width <= 0 || outputSize.height <= 0) return@LaunchedEffect
        val renderSize = outputSize.cappedTo(1920, 1080)
        val imageInfo = ImageInfo(
            ColorInfo(ColorType.BGRA_8888, ColorAlphaType.OPAQUE, ColorSpace.sRGB),
            renderSize.width,
            renderSize.height,
        )
        controller.withSoftwareRendering { renderer ->
            try {
                while (currentCoroutineContext().isActive) {
                    val frame = try {
                        renderer.renderFrame(renderSize.width, renderSize.height)
                    } catch (cancelled: CancellationException) {
                        throw cancelled
                    } catch (failure: Throwable) {
                        AppLogger.error("[player] iOS mpv render failed: ${failure.message.orEmpty()}")
                        return@withSoftwareRendering
                    }

                    val target = if (bitmap == null || bitmapSize != renderSize) {
                        bitmap?.asSkiaBitmap()?.close()
                        ImageBitmap(
                            width = renderSize.width,
                            height = renderSize.height,
                            config = ImageBitmapConfig.Argb8888,
                            hasAlpha = false,
                        ).also {
                            bitmap = it
                            bitmapSize = renderSize
                        }
                    } else {
                        checkNotNull(bitmap)
                    }
                    check(target.asSkiaBitmap().installPixels(imageInfo, frame.pixels, frame.strideBytes)) {
                        "Skia rejected the mpv software frame"
                    }
                    revision++
                    // Keep paused OSD/subtitle updates responsive without copying 1080p frames 30 times/sec.
                    delay(if (controller.player.state.value.paused) 250L else 33L)
                }
            } finally {
                // Remove pixels from the canvas before closing them on this UI context.
                val retiredBitmap = bitmap
                bitmap = null
                bitmapSize = IntSize.Zero
                retiredBitmap?.asSkiaBitmap()?.close()
            }
        }
    }
}

private fun IntSize.cappedTo(maxWidth: Int, maxHeight: Int): IntSize {
    val scale = minOf(1.0, maxWidth.toDouble() / width, maxHeight.toDouble() / height)
    return IntSize(
        width = (width * scale).toInt().coerceAtLeast(1),
        height = (height * scale).toInt().coerceAtLeast(1),
    )
}

private fun DrawScope.drawFitted(frame: ImageBitmap, destination: Size) {
    val scale = minOf(destination.width / frame.width, destination.height / frame.height)
    val width = (frame.width * scale).toInt().coerceAtLeast(1)
    val height = (frame.height * scale).toInt().coerceAtLeast(1)
    val left = ((destination.width - width) / 2f).toInt()
    val top = ((destination.height - height) / 2f).toInt()
    drawImage(
        image = frame,
        dstOffset = IntSize(left, top).let { androidx.compose.ui.unit.IntOffset(it.width, it.height) },
        dstSize = IntSize(width, height),
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxy.kt
### Write `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxy.kt`

Create this path in your reconstruction project. Source set: **jvmCommonMain**. [Exact file download](../reference/source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxy.kt).

The implementation below defines `JvmMediaStreamProxy`, `proxyUrl`, `retire`, `stop`, `closeAndJoin`, `ensureStarted`, `acceptLoop`, `handleClient`, `proxy`, `rewritePlaylist` and 19 further declarations.

The source describes its contract as:

> Legacy immediate shutdown; session retirement uses the awaited path below.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md), [`redactUrlForLog`](../chapters/24-settings-and-integrations.md), [`ProfileHttpEngine`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.services.http.ProfileHttpEngine
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.request.headers
import io.ktor.client.request.prepareRequest
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.utils.io.jvm.javaio.toInputStream
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.URI
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

class JvmMediaStreamProxy internal constructor(engine: HttpClientEngine) : MediaStreamProxy {
    constructor() : this(OkHttp.create())

    private val workerJob = SupervisorJob()
    private val transport = ProfileHttpEngine(engine, workerJob)
    private val retirementLock = Mutex()
    private val http = HttpClient(transport) {
        expectSuccess = false
        followRedirects = true
        install(HttpTimeout) {
            connectTimeoutMillis = 15_000L
            requestTimeoutMillis = 60_000L
            socketTimeoutMillis = 45_000L
        }
    }
    private val entries = ConcurrentHashMap<String, ProxyEntry>()
    private val entryIds = mutableMapOf<ProxyKey, String>()
    private val clients = ConcurrentHashMap.newKeySet<Socket>()
    private val workers = ThreadPoolExecutor(
        4, 16, 30L, TimeUnit.SECONDS, ArrayBlockingQueue(32),
        { task -> Thread(task, "yokan-media-stream-proxy-client").apply { isDaemon = true } },
    ).apply { allowCoreThreadTimeOut(true) }
    private var stopped = false
    private var lastCleanupMs = 0L
    private val nextId = AtomicLong()
    private val running = AtomicBoolean(false)
    private val lock = Any()
    private var acceptThread: Thread? = null

    @Volatile
    private var serverSocket: ServerSocket? = null

    @Volatile
    private var port: Int = 0

    override fun proxyUrl(url: String, headers: Map<String, String>): String {
        if (headers.isEmpty()) return synchronized(lock) {
            check(!stopped) { "Media stream proxy has been stopped" }
            url
        }
        ensureStarted()
        val id = register(url, headers)
        // ExoPlayer's DefaultMediaSourceFactory picks Progressive vs HLS vs
        // DASH by URL extension (no Content-Type sniff happens before the
        // factory pick). Without an extension hint the player treats /media/1
        // as opaque bytes and rejects an HLS playlist with "no extractor
        // could read the stream". Embedding the upstream's extension in the
        // proxy URL fixes the auto-detection.
        val localUrl = localUrlForId(id, extensionHint(url))
        AppLogger.info("[player-proxy] registered id=$id target=${redactUrlForLog(url)} headers=${headers.size}")
        return localUrl
    }

    private fun retire() {
        synchronized(lock) {
            if (stopped) return
            stopped = true
            running.set(false)
            runCatching { serverSocket?.close() }
            serverSocket = null
            clients.forEach { runCatching { it.close() } }
            clients.clear()
            entries.clear()
            entryIds.clear()
        }
        workerJob.cancel()
        workers.shutdownNow()
    }

    /** Legacy immediate shutdown; session retirement uses the awaited path below. */
    override fun stop() {
        retire()
        transport.close()
        http.close()
    }

    override suspend fun closeAndJoin() = retirementLock.withLock {
        withContext(NonCancellable) {
            retire()
            workerJob.cancelAndJoin()
            // Ktor response producers can outlive execute() and its blocking worker.
            transport.closeAndJoin()
            withContext(Dispatchers.IO) {
                synchronized(lock) { acceptThread }?.join()
                while (!workers.awaitTermination(1, TimeUnit.SECONDS)) { /* await owned threads */ }
            }
            http.coroutineContext[Job]?.cancelAndJoin()
            http.close()
        }
    }

    private fun ensureStarted() {
        if (running.get()) return
        synchronized(lock) {
            check(!stopped) { "Media stream proxy has been stopped" }
            if (running.get()) return
            val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
            serverSocket = socket
            port = socket.localPort
            running.set(true)
            acceptThread = thread(name = "yokan-media-stream-proxy", isDaemon = true) { acceptLoop(socket) }
            AppLogger.info("[player-proxy] listening on 127.0.0.1:$port")
        }
    }

    private fun acceptLoop(socket: ServerSocket) {
        while (running.get()) {
            val client = runCatching { socket.accept() }
                .onFailure { error ->
                    if (running.get()) AppLogger.warn("[player-proxy] accept failed: ${error.message.orEmpty()}")
                }
                .getOrNull() ?: if (socket.isClosed) return else continue
            synchronized(lock) {
                if (!running.get()) {
                    client.close()
                    return
                }
                clients.add(client)
                try {
                    workers.execute {
                        try {
                            handleClient(client)
                        } catch (_: java.io.IOException) {
                            // Disconnects and stop() closing an idle socket are normal.
                        } finally {
                            clients.remove(client)
                            runCatching { client.close() }
                        }
                    }
                } catch (_: RejectedExecutionException) {
                    clients.remove(client)
                    client.close()
                }
            }
        }
    }

    private fun handleClient(socket: Socket) {
        socket.soTimeout = 30_000
        socket.use { client ->
            val input = BufferedInputStream(client.getInputStream())
            // BufferedOutputStream is NOT auto-flushed when the socket closes;
            // without an explicit flush GStreamer's hlsdemux sees a truncated
            // response and bails with "Stream doesn't contain enough data".
            val output = BufferedOutputStream(client.getOutputStream())
            try {
                val request = readHttpRequest(input) ?: run {
                    writeError(output, 400, "Bad Request")
                    return@use
                }
                if (request.method == "OPTIONS") {
                    writeResponseHeaders(output, 204, emptyMap(), 0)
                    return@use
                }
                // Strip query string and the optional extension hint we
                // append in proxyUrl / localUrl when registering. The first
                // dot in /media/<id>.<ext> is always the extension boundary.
                val rawPath = request.path.removePrefix("/media/").substringBefore('?')
                val id = (if ('.' in rawPath) rawPath.substringBeforeLast('.') else rawPath)
                    .takeIf { it.isNotBlank() }
                val entry = id?.let(entries::get)
                if (entry == null) {
                    writeError(output, 404, "Unknown media proxy entry")
                    return@use
                }
                entry.lastAccessMs.set(System.currentTimeMillis())
                proxy(entry, request, output)
            } finally {
                runCatching { output.flush() }
            }
        }
    }

    private fun proxy(entry: ProxyEntry, request: ProxyRequest, output: OutputStream) {
        runCatching {
            runBlocking(workerJob) {
                val playlistRequest = isPlaylist(entry.url, "")
                http.prepareRequest(entry.url) {
                    method = if (request.method == "HEAD") HttpMethod.Head else HttpMethod.Get
                    headers {
                        request.headers.forEach { (name, value) ->
                            val rangeHeader = name.equals("Range", ignoreCase = true) ||
                                name.equals("If-Range", ignoreCase = true)
                            if (shouldForwardRequestHeader(name) && !(playlistRequest && rangeHeader)) {
                                append(name, value)
                            }
                        }
                        entry.headers.forEach { (name, value) ->
                            if (name.isNotBlank()) {
                                remove(name)
                                append(name, value)
                            }
                        }
                    }
                }.execute { response ->
                    val status = response.status.value
                    val responseHeaders = response.headers.entries()
                        .associate { (name, values) -> name to values.joinToString(",") }
                    val contentType = response.headers[HttpHeaders.ContentType].orEmpty()
                    val body = if (request.method == "HEAD") null else response.bodyAsChannel().toInputStream()
                    if (isPlaylist(entry.url, contentType)) {
                        val raw = body?.use { it.readBytes() }?.decodeToString().orEmpty()
                        // Strip UTF-8 BOM + leading whitespace — GStreamer's typefind
                        // only recognizes the playlist when the first bytes are `#EXTM3U`.
                        val text = raw.removePrefix("﻿").trimStart()
                        val rewritten = rewritePlaylist(text, entry.url, entry.headers).encodeToByteArray()
                        val headers = responseHeaders
                            .filterKeys {
                                shouldForwardResponseHeader(it) &&
                                    !it.equals("Content-Length", ignoreCase = true) &&
                                    !it.equals("Content-Range", ignoreCase = true) &&
                                    !it.equals("Accept-Ranges", ignoreCase = true)
                            }
                            .toMutableMap()
                        headers["Content-Type"] = "application/vnd.apple.mpegurl"
                        headers["Content-Length"] = rewritten.size.toString()
                        writeResponseHeaders(output, status, headers, rewritten.size)
                        if (request.method != "HEAD") output.write(rewritten)
                        output.flush()
                        AppLogger.info(
                            "[player-proxy] playlist proxied status=$status " +
                                "target=${redactUrlForLog(entry.url)} bytes=${rewritten.size}",
                        )
                    } else {
                        val headers = responseHeaders.filterKeys(::shouldForwardResponseHeader)
                        writeResponseHeaders(output, status, headers, null)
                        body?.use { it.copyTo(output) }
                        output.flush()
                        AppLogger.info("[player-proxy] stream proxied status=$status target=${redactUrlForLog(entry.url)}")
                    }
                }
            }
        }.onFailure { error ->
            if (error is CancellationException || !running.get()) return@onFailure
            // Broken pipe = client closed first (seeking, switching streams,
            // player error). Anything else is worth surfacing.
            val isBrokenPipe = error is java.io.IOException &&
                error.message.orEmpty().contains("broken pipe", ignoreCase = true)
            if (isBrokenPipe) {
                AppLogger.info("[player-proxy] client disconnected target=${redactUrlForLog(entry.url)}")
            } else {
                AppLogger.error("[player-proxy] request failed target=${redactUrlForLog(entry.url)}: ${error.message.orEmpty()}")
                runCatching { writeError(output, 502, "Media proxy request failed") }
            }
        }
    }

    private fun rewritePlaylist(body: String, baseUrl: String, headers: Map<String, String>): String {
        val base = runCatching { URI(baseUrl) }.getOrNull() ?: return body
        return body.lineSequence().joinToString("\n") { line ->
            val tagLine = uriAttributeRegex.replace(line) { match ->
                val raw = match.groupValues[1]
                val resolved = resolvePlaylistUrl(base, raw)
                if (shouldProxyUrl(resolved)) "URI=\"${localUrl(resolved, headers)}\"" else match.value
            }
            val trimmed = tagLine.trim()
            when {
                trimmed.isBlank() || trimmed.startsWith("#") -> tagLine
                else -> resolvePlaylistUrl(base, trimmed).let { resolved ->
                    if (shouldProxyUrl(resolved)) localUrl(resolved, headers) else tagLine
                }
            }
        }
    }

    private fun resolvePlaylistUrl(base: URI, value: String): String =
        runCatching { base.resolve(value).toString() }.getOrDefault(value)

    private fun shouldProxyUrl(url: String): Boolean =
        url.startsWith("http://", ignoreCase = true) || url.startsWith("https://", ignoreCase = true)

    private fun localUrl(url: String, headers: Map<String, String>): String {
        val id = register(url, headers)
        return localUrlForId(id, extensionHint(url))
    }

    private fun localUrlForId(id: String, ext: String = ""): String {
        val suffix = if (ext.isNotBlank()) ".$ext" else ""
        return "http://127.0.0.1:$port/media/$id$suffix"
    }

    /**
     * Picks the canonical file extension off the upstream URL so the proxy
     * URL we hand the player carries the same hint. Container types that
     * ExoPlayer / GStreamer / AVPlayer dispatch on by extension only need
     * to be enumerated here; everything else degrades to the legacy "no
     * suffix" form, which is fine for direct MP4 / WebM byte streams.
     */
    private fun extensionHint(url: String): String {
        val cleanPath = url.substringBefore('?').lowercase()
        return when {
            cleanPath.endsWith(".m3u8") -> "m3u8"
            cleanPath.endsWith(".m3u") -> "m3u"
            cleanPath.endsWith(".mpd") -> "mpd"
            cleanPath.endsWith(".mp4") -> "mp4"
            cleanPath.endsWith(".m4s") -> "m4s"
            cleanPath.endsWith(".mkv") -> "mkv"
            cleanPath.endsWith(".webm") -> "webm"
            cleanPath.endsWith(".ts") -> "ts"
            cleanPath.endsWith(".aac") -> "aac"
            cleanPath.endsWith(".vtt") -> "vtt"
            else -> ""
        }
    }

    private fun register(url: String, headers: Map<String, String>): String = synchronized(lock) {
        check(!stopped) { "Media stream proxy has been stopped" }
        val now = System.currentTimeMillis()
        cleanupIfNeeded(now)
        val key = ProxyKey(url, headers.toMap())
        entryIds[key]?.let { id ->
            entries[id]?.let { entry ->
                entry.lastAccessMs.set(now)
                return@synchronized id
            }
        }
        val id = nextId.incrementAndGet().toString()
        entries[id] = ProxyEntry(url, key.headers, AtomicLong(now))
        entryIds[key] = id
        id
    }

    // Live playlists repeatedly name the same segments. Reuse those registrations, and
    // scan for expired entries at most once a minute rather than on every segment.
    private fun cleanupIfNeeded(now: Long) {
        if (now - lastCleanupMs < 60_000L) return
        lastCleanupMs = now
        val cutoff = now - 30 * 60 * 1_000L
        val iterator = entryIds.iterator()
        while (iterator.hasNext()) {
            val (_, id) = iterator.next()
            val entry = entries[id]
            if (entry == null || entry.lastAccessMs.get() < cutoff) {
                entries.remove(id)
                iterator.remove()
            }
        }
    }

    private data class ProxyKey(val url: String, val headers: Map<String, String>)

    private fun readHttpRequest(input: InputStream): ProxyRequest? {
        val requestLine = readLine(input)?.takeIf { it.isNotBlank() } ?: return null
        val parts = requestLine.split(' ')
        if (parts.size < 2) return null
        val headers = linkedMapOf<String, String>()
        while (true) {
            val line = readLine(input) ?: return null
            if (line.isBlank()) break
            val separator = line.indexOf(':')
            if (separator > 0) {
                headers[line.take(separator).trim()] = line.drop(separator + 1).trim()
            }
        }
        return ProxyRequest(
            method = parts[0].uppercase(Locale.US),
            path = parts[1],
            headers = headers,
        )
    }

    private fun readLine(input: InputStream): String? {
        val bytes = java.io.ByteArrayOutputStream()
        while (true) {
            val next = input.read()
            if (next < 0) return if (bytes.size() == 0) null else bytes.toByteArray().decodeToString()
            if (next == '\n'.code) break
            if (next != '\r'.code) bytes.write(next)
            if (bytes.size() > 16_384) return null
        }
        return bytes.toByteArray().decodeToString()
    }

    private fun isPlaylist(url: String, contentType: String): Boolean {
        val lowerType = contentType.lowercase()
        val lowerUrl = url.substringBefore("?").lowercase()
        return "mpegurl" in lowerType || lowerUrl.endsWith(".m3u8")
    }

    private fun shouldForwardRequestHeader(name: String): Boolean = when (name.lowercase()) {
        "host", "connection", "proxy-connection", "content-length", "accept-encoding" -> false
        else -> true
    }

    private fun shouldForwardResponseHeader(name: String): Boolean = when (name.lowercase()) {
        "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
        "transfer-encoding", "upgrade", "content-encoding" -> false
        else -> true
    }

    private fun writeError(output: OutputStream, status: Int, message: String) {
        val body = message.encodeToByteArray()
        writeResponseHeaders(
            output = output,
            status = status,
            headers = mapOf("Content-Type" to "text/plain; charset=utf-8", "Content-Length" to body.size.toString()),
            contentLength = body.size,
        )
        output.write(body)
    }

    private fun writeResponseHeaders(
        output: OutputStream,
        status: Int,
        headers: Map<String, String>,
        contentLength: Int?,
    ) {
        output.writeAscii("HTTP/1.1 $status ${reasonPhrase(status)}\r\n")
        output.writeAscii("Connection: close\r\n")
        output.writeAscii("Access-Control-Allow-Origin: *\r\n")
        val hasLength = headers.keys.any { it.equals("Content-Length", ignoreCase = true) }
        if (contentLength != null && !hasLength) output.writeAscii("Content-Length: $contentLength\r\n")
        headers.forEach { (name, value) ->
            if (name.isNotBlank() && value.isNotBlank()) output.writeAscii("$name: $value\r\n")
        }
        output.writeAscii("\r\n")
    }

    private fun OutputStream.writeAscii(value: String) {
        write(value.encodeToByteArray())
    }

    private fun reasonPhrase(status: Int): String = when (status) {
        200 -> "OK"
        204 -> "No Content"
        206 -> "Partial Content"
        400 -> "Bad Request"
        404 -> "Not Found"
        500 -> "Internal Server Error"
        502 -> "Bad Gateway"
        else -> "Status"
    }

    private data class ProxyEntry(
        val url: String,
        val headers: Map<String, String>,
        val lastAccessMs: AtomicLong,
    )

    private data class ProxyRequest(
        val method: String,
        val path: String,
        val headers: Map<String, String>,
    )

    private companion object {
        val uriAttributeRegex = Regex("URI=\"([^\"]+)\"")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvMediaPlayerController.kt
### Write `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvMediaPlayerController.kt`

Create this path in your reconstruction project. Source set: **nonWebMain**. [Exact file download](../reference/source/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvMediaPlayerController.kt).

The implementation below defines `MpvMediaPlayerController`, `load`, `play`, `pause`, `seekTo`, `setPlaybackSpeed`, `executeMpvCommand`, `selectSecondarySubtitle`, `executeMpvCommandAndJoin`, `withSoftwareRendering` and 14 further declarations.

The source describes its contract as:

> External files need their track id, which mpv only exposes through `track-list`.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md), [`redactUrlForLog`](../chapters/24-settings-and-integrations.md), [`PlatformLock`](../chapters/10-navigation-and-design-system.md), [`MpvConfiguration`](../chapters/17-kmp-mpv-submodule.md), [`MpvEvent`](../chapters/17-kmp-mpv-submodule.md), [`MpvFormat`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import kotlin.coroutines.CoroutineContext
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.util.PlatformLock
import io.github.kmpmpv.MpvConfiguration
import io.github.kmpmpv.MpvEvent
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvPlaybackStatus
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvPlayer
import io.github.kmpmpv.MpvSoftwareFrame
import io.github.kmpmpv.MpvValue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.dropWhile
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

internal class MpvMediaPlayerController(
    internal val player: MpvPlayer,
    private val streamProxy: MediaStreamProxy,
    private val dispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1),
    private val loadTimeoutMs: Long = 30_000L,
) : MediaPlayerController {
    // Preserve UI command order (load -> speed -> play, for example) while the
    // library independently serializes access to the native mpv handle.
    private val ownerJob = SupervisorJob()
    private val commandJob = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(commandJob + dispatcher)
    private val releaseRequested = kotlinx.coroutines.CompletableDeferred<Unit>()
    private val cleanup: kotlinx.coroutines.Deferred<Unit>
    private val retirementLock = Mutex()
    private val surfaces = PlayerSurfaceResources()
    private val surfaceMutex = Mutex()
    private var surfaceTarget: Any? = null
    private var nativeReleased = false
    private val lifecycleLock = PlatformLock()
    private var seekJob: Job? = null
    private val commandMutex = Mutex()
    private var cachedPositionMs by mutableLongStateOf(0L)
    private var cachedDurationMs by mutableLongStateOf(0L)
    private var cachedIsPlaying by mutableStateOf(false)
    private var cachedError by mutableStateOf<String?>(null)
    private val mutableMpvBridgeEvents = MutableSharedFlow<MpvBridgeEvent>(extraBufferCapacity = 32)
    private var releasedState = false
    private val released: Boolean get() = lifecycleLock.withLock { releasedState }

    override val isMpvBackend: Boolean = true
    override val mpvBridgeEvents: Flow<MpvBridgeEvent> = mutableMpvBridgeEvents.asSharedFlow()

    init {
        require(loadTimeoutMs > 0)
        // Cleanup is an owned sibling: it must join command/observer finalizers before native release.
        cleanup = CoroutineScope(ownerJob + dispatcher).async(start = CoroutineStart.UNDISPATCHED) {
            releaseRequested.await()
            commandJob.join()
            releaseNative()
        }
        scope.launch {
            var lastLoggedError: String? = null
            player.state.collect { state ->
                lifecycleLock.withLock {
                    if (releasedState) return@withLock
                    cachedPositionMs = (state.positionSeconds * 1000.0).toLong().coerceAtLeast(0L)
                    cachedDurationMs = ((state.durationSeconds ?: 0.0) * 1000.0).toLong().coerceAtLeast(0L)
                    cachedIsPlaying = state.status == MpvPlaybackStatus.Playing && !state.paused
                    if (state.status == MpvPlaybackStatus.Error) cachedError = state.lastError ?: "mpv playback failed"
                }
                if (state.lastError != lastLoggedError) {
                    state.lastError?.let { AppLogger.error("[player] mpv error $it") }
                    lastLoggedError = state.lastError
                }
            }
        }
        scope.launch {
            MpvBridgePropertyNames.forEach { property ->
                kotlinx.coroutines.currentCoroutineContext().ensureActive()
                runPlayerOperation("observe $property") { player.observeProperty(property, MpvFormat.String) }
            }
            player.events.collect { event ->
                val changed = event as? MpvEvent.PropertyChanged ?: return@collect
                if (changed.name !in MpvBridgePropertyNames) return@collect
                val text = when (val value = changed.value) {
                    is MpvValue.Text -> value.value
                    is MpvValue.Integer -> value.value.toString()
                    is MpvValue.Decimal -> value.value.toString()
                    is MpvValue.Flag -> value.value.toString()
                    MpvValue.None -> ""
                }
                if (text.isBlank()) return@collect
                kotlinx.coroutines.currentCoroutineContext().ensureActive()
                if (released) return@collect
                mutableMpvBridgeEvents.emit(MpvBridgeEvent(changed.name.removePrefix("user-data/"), text))
                runPlayerOperation("clear ${changed.name}") { player.setProperty(changed.name, MpvValue.Text("")) }
            }
        }
    }

    override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) {
        if (released) return
        // mpv percent-decodes file:// URLs, so a local name containing e.g. "%20" would not open; give it the path.
        val playableUrl = if (headers.isNotEmpty()) {
            streamProxy.proxyUrl(url, headers)
        } else {
            url.removePrefix("file://")
        }
        val startPositionMs = initialPositionMs.coerceAtLeast(0L)
        lifecycleLock.withLock { cachedError = null }
        AppLogger.info(
            "[player] mpv load url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" +
                if (headers.isNotEmpty() && playableUrl != url) " proxy=${redactUrlForLog(playableUrl)}" else "",
        )
        launchCommand("load") {
            val completed = withTimeoutOrNull(loadTimeoutMs) {
                coroutineScope {
                    val loadFinished = async(start = CoroutineStart.UNDISPATCHED) {
                        player.events
                            .dropWhile { event ->
                                event !is MpvEvent.Lifecycle ||
                                    event.kind != io.github.kmpmpv.MpvLifecycleEvent.StartFile
                            }
                            .first { event ->
                                event is MpvEvent.Lifecycle &&
                                    event.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded ||
                                    event is MpvEvent.EndFile
                            }
                    }
                    player.pause()
                    player.load(playableUrl)
                    val terminalEvent = loadFinished.await()
                    if (
                        terminalEvent is MpvEvent.Lifecycle &&
                        terminalEvent.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded &&
                        startPositionMs > 0L
                    ) {
                        player.seek(startPositionMs / 1000.0)
                    }
                }
                true
            }
            if (completed == null) {
                AppLogger.error("[player] mpv load timed out after ${loadTimeoutMs}ms")
                lifecycleLock.withLock { if (!releasedState) cachedError = "Timed out loading the stream" }
            }
        }
    }

    override fun play() = launchCommand("play") { player.play() }

    override fun pause() = launchCommand("pause") { player.pause() }

    override fun seekTo(positionMs: Long) {
        lifecycleLock.withLock {
            if (releasedState) return@withLock
            // Scrubbing should not accumulate obsolete seek jobs behind an in-flight load.
            seekJob?.cancel()
            seekJob = scope.launch {
                commandMutex.withLock {
                    kotlinx.coroutines.currentCoroutineContext().ensureActive()
                    runPlayerOperation("seek") { player.seek(positionMs.coerceAtLeast(0L) / 1000.0) }
                }
            }
        }
    }

    override fun setPlaybackSpeed(speed: Float) = launchCommand("speed") {
        player.setProperty("speed", MpvValue.Decimal(speed.coerceIn(0.25f, 4.0f).toDouble()))
    }

    override fun executeMpvCommand(vararg arguments: String): Boolean {
        if (arguments.isEmpty()) return false
        return queueCommand(arguments.first()) { player.command(*arguments) }
    }

    override val playbackError: String? get() = cachedError

    /** External files need their track id, which mpv only exposes through `track-list`. */
    override fun selectSecondarySubtitle(file: String?, title: String?): Boolean = queueCommand("secondary-sid") {
        if (file.isNullOrBlank()) {
            player.setProperty("secondary-sid", MpvValue.Text("no"))
        } else {
            player.command("sub-add", file, "auto", title.orEmpty())
            val count = player.getLongProperty("track-list/count") ?: 0L
            val id = (count - 1 downTo 0L).firstNotNullOfOrNull { index ->
                player.getLongProperty("track-list/$index/id")?.takeIf {
                    player.getStringProperty("track-list/$index/type") == "sub" &&
                        player.getStringProperty("track-list/$index/external-filename") == file
                }
            }
            if (id != null) player.setProperty("secondary-sid", MpvValue.Integer(id))
            else AppLogger.warn("[player] secondary subtitle track was not added")
        }
    }

    override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean {
        val caller = requireNotNull(currentCoroutineContext()[Job])
        caller.ensureActive()
        if (arguments.isEmpty()) return false
        val work = lifecycleLock.withLock {
            if (releasedState) return@withLock null
            scope.async {
                commandMutex.withLock {
                    currentCoroutineContext().ensureActive()
                    caller.ensureActive()
                    if (released) throw CancellationException("Player controller is retired.")
                    try {
                        player.command(*arguments)
                        currentCoroutineContext().ensureActive()
                        caller.ensureActive()
                        true
                    } catch (cancelled: CancellationException) {
                        throw cancelled
                    } catch (failure: Throwable) {
                        AppLogger.error("[player] mpv ${arguments.first()} failed: ${failure.message.orEmpty()}")
                        false
                    }
                }
            }
        } ?: return false
        return try { work.await() }
        finally {
            // Native calls may finish blocking work or non-cancelable finalizers after cancellation.
            withContext(NonCancellable) { work.cancelAndJoin() }
            caller.ensureActive()
        }
    }

    /** Own the complete UI render loop, including its pixel finalizer, before releasing libmpv. */
    internal suspend fun withSoftwareRendering(use: suspend (MpvSoftwareRenderer) -> Unit) {
        val callerContext = currentCoroutineContext()
        val caller = requireNotNull(callerContext[Job])
        caller.ensureActive()
        val work = lifecycleLock.withLock {
            if (releasedState) throw CancellationException("Player controller is retired.")
            // Keep canvas publication/cleanup on the captured UI context, with controller ownership.
            scope.async(callerContext.minusKey(Job)) {
                val renderJob = requireNotNull(currentCoroutineContext()[Job])
                fun ensureCurrent() {
                    renderJob.ensureActive()
                    caller.ensureActive()
                    if (released) throw CancellationException("Player controller is retired.")
                }
                ensureCurrent()
                val renderer = MpvSoftwareRenderer { width, height ->
                    ensureCurrent()
                    // Escaped callbacks cannot start untracked frame work in another coroutine.
                    if (currentCoroutineContext()[Job] !== renderJob) {
                        throw CancellationException("Software renderer belongs to its render loop.")
                    }
                    try {
                        withContext(dispatcher) {
                            ensureCurrent()
                            player.renderSoftwareFrame(width, height)
                        }
                    } finally {
                        // A late frame or native failure must become cancellation before UI handling.
                        ensureCurrent()
                    }
                }
                use(renderer)
            }
        }
        try { work.await() }
        finally {
            withContext(NonCancellable) { work.cancelAndJoin() }
            caller.ensureActive()
        }
    }

    internal fun bindNativeSurface(context: CoroutineContext, removeCallbacks: () -> Unit): MpvNativeSurfaceBinding? {
        val identity = Any()
        val resource = surfaces.register(context) {
            removeCallbacks()
            withContext(dispatcher) {
                surfaceMutex.withLock {
                    if (surfaceTarget === identity) {
                        player.detachRenderTarget()
                        surfaceTarget = null
                    }
                }
            }
        } ?: return null
        return MpvNativeSurfaceBinding(resource) { operation, current ->
            withContext(dispatcher) {
                surfaceMutex.withLock {
                    current()
                    operation()
                }
            }
        }.also { binding ->
            binding.attachTarget = { target ->
                // Record ownership before attachment so partial native failure still detaches on cleanup.
                surfaceTarget = identity
                player.attachRenderTarget(target)
            }
            binding.resizeTarget = { width, height ->
                if (surfaceTarget === identity) player.updateRenderTargetSize(width, height)
            }
            binding.detachTarget = {
                if (surfaceTarget === identity) {
                    player.detachRenderTarget()
                    surfaceTarget = null
                }
            }
        }
    }

    override fun release() {
        lifecycleLock.withLock {
            if (releasedState) return@withLock
            releasedState = true
            cachedPositionMs = 0L
            cachedDurationMs = 0L
            cachedIsPlaying = false
            seekJob = null
        }
        surfaces.retire()
        scope.cancel()
        releaseRequested.complete(Unit)
    }

    override suspend fun releaseAndJoin() {
        release()
        withContext(NonCancellable) {
            cleanup.join()
            releaseNative() // Retry failed immediate cleanup without reopening command admission.
            ownerJob.join()
        }
    }

    private suspend fun releaseNative() = withContext(NonCancellable) {
        retirementLock.withLock {
            if (!nativeReleased) {
                surfaces.closeAndJoin()
                player.release()
                nativeReleased = true
                ownerJob.complete()
            }
        }
    }

    override fun currentPositionMs(): Long = cachedPositionMs

    override fun durationMs(): Long = cachedDurationMs

    override fun isPlaying(): Boolean = cachedIsPlaying

    private fun launchCommand(name: String, command: suspend () -> Unit) {
        queueCommand(name, command)
    }

    private fun queueCommand(name: String, command: suspend () -> Unit): Boolean = lifecycleLock.withLock {
        if (releasedState) return@withLock false
        scope.launch {
            commandMutex.withLock command@{
                kotlinx.coroutines.currentCoroutineContext().ensureActive()
                if (released) return@command
                runPlayerOperation(name, command)
            }
        }
        true
    }

    private suspend fun runPlayerOperation(name: String, command: suspend () -> Unit) {
        try {
            command()
        } catch (cancelled: CancellationException) {
            throw cancelled
        } catch (failure: Throwable) {
            AppLogger.error("[player] mpv $name failed: ${failure.message.orEmpty()}")
        }
    }
}

/** This capability expires when its render loop, UI caller or controller finishes. */
internal class MpvSoftwareRenderer internal constructor(
    private val render: suspend (Int, Int) -> MpvSoftwareFrame,
) {
    suspend fun renderFrame(width: Int, height: Int): MpvSoftwareFrame = render(width, height)
}

internal fun createMpvMediaPlayerController(
    configuration: MediaPlayerConfiguration,
    streamProxy: MediaStreamProxy,
    platformOptions: Map<String, String> = emptyMap(),
    libraryPath: String? = null,
): MediaPlayerController =
    MpvMediaPlayerController(
        MpvPlayer.create(
            MpvConfiguration(
                libraryPath = libraryPath,
                options = MpvConfiguration.DefaultOptions + configuration.mpvOptions() + platformOptions,
                eventPollTimeoutSeconds = 0.01,
            ),
        ),
        streamProxy,
    )
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBinding.kt
### Write `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBinding.kt`

Create this path in your reconstruction project. Source set: **nonWebMain**. [Exact file download](../reference/source/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBinding.kt).

The implementation below defines `MpvNativeSurfaceBinding`, `attach`, `resize`, `detach`, `retire`, `closeAndJoin`.

The source describes its contract as:

> Surface callbacks expire by identity and generation; all native work and detachment are joined.

Cross-chapter imports used by this file: [`MpvRenderTarget`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import io.github.kmpmpv.MpvRenderTarget
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.updateAndGet

/** Surface callbacks expire by identity and generation; all native work and detachment are joined. */
internal class MpvNativeSurfaceBinding(
    private val resource: PlayerSurfaceResources.Resource,
    private val serialized: suspend (suspend () -> Unit, () -> Unit) -> Unit,
) {
    internal var attachTarget: suspend (MpvRenderTarget) -> Unit = {}
    internal var resizeTarget: suspend (Int, Int) -> Unit = { _, _ -> }
    internal var detachTarget: suspend () -> Unit = {}
    private val generation = MutableStateFlow(0L)
    fun attach(target: MpvRenderTarget, width: Int, height: Int): Boolean {
        val captured = generation.updateAndGet { it + 1L }
        return resource.launch { current ->
            serialized({
                if (generation.value == captured) {
                    attachTarget(target)
                    current()
                    if (generation.value == captured && width > 0 && height > 0) resizeTarget(width, height)
                }
            }, current)
        }
    }
    fun resize(width: Int, height: Int): Boolean {
        if (width <= 0 || height <= 0) return false
        val captured = generation.value
        return resource.launch { current ->
            serialized({ if (generation.value == captured) resizeTarget(width, height) }, current)
        }
    }
    fun detach(): Boolean {
        val captured = generation.updateAndGet { it + 1L }
        return resource.launch { current ->
            serialized({ if (generation.value == captured) detachTarget() }, current)
        }
    }
    fun retire() { generation.updateAndGet { it + 1L }; resource.retire() }
    suspend fun closeAndJoin() { retire(); resource.closeAndJoin() }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerScreenBrightness.wasm.kt).

The implementation below defines `setPlayerScreenBrightness`.

The source describes its contract as:

> No application-controlled display brightness here; the player dims the video instead.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/** No application-controlled display brightness here; the player dims the video instead. */
internal actual fun setPlayerScreenBrightness(level: Float?): Boolean = false
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/MediaSurface.wasm.kt).

The implementation below defines `MediaPlayerSurface`.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController

@Composable
actual fun MediaPlayerSurface(controller: MediaPlayerController, modifier: Modifier) {
    ComposeMediaPlayerSurface(controller, modifier)
}
```
[chapter-file-end]: #

### Check your understanding

Try invalid speed presets, blacklisted subtitle tracks and a failing candidate already in failedUrls. The policies should reject or choose an untried alternative without an infinite retry loop.
[chapter-content-end]: #


## Step 4: implement PiP and external playback

Define platform PiP support/entry and ownership tokens, automatic transitions and recovery. Browser PiP uses owned promises; Android native PiP needs activity integration. Recreate the actual iOS support boundary instead of assuming API parity. External-player intents/URLs must include the supported headers/position fields and handle missing apps. Do not claim external playback reports reliable progress unless its integration does.

[chapter-content-start]: #
### Follow the code

PiP entry is asynchronous on some hosts and must retain the owner until completion or cleanup. Native activity integration, HTML video PiP and compatibility fallback have different capabilities. External-player launch includes only fields the target integration supports and reports missing applications. Do not derive reliable progress from a launch-only integration. Recovery after PiP or return must still match episode/controller identity.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwners.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.android.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.desktop.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.ios.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.ios.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.wasm.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwners.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwners.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwners.kt).

The implementation below defines `PictureInPicturePlaybackOwners`, `create`, `acquire`, `activate`, `active`, `update`, `request`, `close`.

The source describes its contract as:

> PiP is installation-owned; its eligibility and requests retain the current player capability.

Cross-chapter imports used by this file: [`PlatformLock`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
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,
)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.kt).

The implementation below defines `PictureInPictureAction`, `PictureInPicturePlatform`, `request`, `setPlaybackState`, `updateActions`, `bindSurface`, `NoPictureInPicture`.

The source describes its contract as:

> Remote controls shown in the system PiP window (Android) or the browser's PiP window (web).

Cross-chapter imports used by this file: [`VideoPlayerState`](../chapters/18-media-compat-vendor.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import io.github.kdroidfilter.composemediaplayer.VideoPlayerState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.emptyFlow

/** Remote controls shown in the system PiP window (Android) or the browser's PiP window (web). */
enum class PictureInPictureAction { SkipForward, Previous, Next, Play, Pause }

/** System picture-in-picture. The defaults describe a platform without it; see [NoPictureInPicture]. */
internal interface PictureInPicturePlatform {
    val isSupported: Boolean get() = false
    val active: StateFlow<Boolean>
    val actions: Flow<PictureInPictureAction> get() = emptyFlow()

    fun request(controller: MediaPlayerController? = null): Boolean = false
    fun setPlaybackState(active: Boolean, eligible: Boolean, admitted: () -> Boolean) = Unit

    /** [replaceWithPrevious] swaps the first action from +10 s to the previous episode. */
    fun updateActions(playing: Boolean, replaceWithPrevious: Boolean) = Unit

    /** Bind platform callbacks to this exact controller/state pair; return its identity-safe removal. */
    fun bindSurface(controller: MediaPlayerController, state: VideoPlayerState): () -> Unit = {}
}

internal object NoPictureInPicture : PictureInPicturePlatform {
    override val active: StateFlow<Boolean> = MutableStateFlow(false).asStateFlow()
}

internal expect val pictureInPicturePlatform: PictureInPicturePlatform
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.kt).

The implementation below defines `ExternalPlayerChoice`, `externalPlayerChoices`, `launchExternalPlayer`.

The source describes its contract as:

> A launchable external player; \[id\] is what the preference stores.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/** A launchable external player; [id] is what the preference stores. */
data class ExternalPlayerChoice(val id: String, val label: String)

/** External players this device can hand streams to; empty where apps cannot be launched (web). */
expect fun externalPlayerChoices(): List<ExternalPlayerChoice>

/**
 * Hand a video stream to an external media player (mpv / VLC / MX Player / etc.). A blank
 * [playerId] keeps the platform's default handler order; otherwise only that player is tried.
 *
 * Callers should already have proxied the URL if it needs request headers;
 * platform actuals are free to ignore [headers] when the OS handler doesn't
 * support per-request headers.
 *
 * Returns true if a launcher was found and dispatched, false otherwise.
 */
expect fun launchExternalPlayer(url: String, headers: Map<String, String> = emptyMap(), playerId: String = ""): Boolean
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.android.kt).

The implementation below defines `externalPlayerChoices`, `launchExternalPlayer`.

The source describes its contract as:

> Installed apps that open video streams; ids are package names.

Cross-chapter imports used by this file: [`AndroidAppContext`](../chapters/23-platform-hosts-and-adapters.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import android.content.Intent
import android.net.Uri
import eu.friedcutlet.yokan.AndroidAppContext

/** Installed apps that open video streams; ids are package names. */
actual fun externalPlayerChoices(): List<ExternalPlayerChoice> {
    val context = AndroidAppContext.appContext ?: return emptyList()
    val probe = Intent(Intent.ACTION_VIEW).setDataAndType(Uri.parse("https://example.invalid/video.mp4"), "video/*")
    val packageManager = context.packageManager
    return packageManager.queryIntentActivities(probe, 0)
        .map { ExternalPlayerChoice(it.activityInfo.packageName, it.loadLabel(packageManager).toString()) }
        .filter { it.id != context.packageName }
        .distinctBy { it.id }
        .sortedBy { it.label.lowercase() }
}

actual fun launchExternalPlayer(url: String, headers: Map<String, String>, playerId: String): Boolean {
    val context = AndroidAppContext.appContext ?: return false
    if (url.isBlank()) return false
    return runCatching {
        val intent = Intent(Intent.ACTION_VIEW).apply {
            // MIME hint biases the chooser toward video players (mpv-android,
            // VLC, MX Player, Just Player) instead of browsers.
            setDataAndType(Uri.parse(url), "video/*")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            if (playerId.isNotBlank()) setPackage(playerId)
            if (headers.isNotEmpty()) {
                // mpv-android / VLC honor android.intent.extra.headers as a
                // string array of alternating name/value pairs.
                val flat = headers.entries.flatMap { listOf(it.key, it.value) }.toTypedArray()
                putExtra("headers", flat)
            }
        }
        context.startActivity(intent)
        true
    }.getOrDefault(false)
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.android.kt).

The implementation below defines `AndroidPictureInPictureController`, `onReceive`, `attach`, `detach`, `unregister`, `onUserLeaveHint`, `setState`, `setActions`, `onPictureInPictureModeChanged`, `enterIfEligible` and 5 further declarations.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import android.app.Activity
import android.app.PendingIntent
import android.app.PictureInPictureParams
import android.app.RemoteAction
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.Icon
import android.os.Build
import android.util.Rational
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

object AndroidPictureInPictureController {
    private const val ActionIntent = "eu.friedcutlet.yokan.PICTURE_IN_PICTURE_ACTION"
    private const val ActionExtra = "action"
    private var activity: Activity? = null
    private var animePlayerActive = false
    private var playbackEligible = false
    private var playbackAdmitted: () -> Boolean = { false }
    private var playing = false
    private var replaceWithPrevious = false
    private val _isActive = MutableStateFlow(false)
    val isActive = _isActive.asStateFlow()
    internal val actions = MutableSharedFlow<PictureInPictureAction>(extraBufferCapacity = 8)
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = PictureInPictureAction.entries.getOrNull(intent?.getIntExtra(ActionExtra, -1) ?: -1) ?: return
            actions.tryEmit(action)
        }
    }

    fun attach(activity: Activity) {
        if (this.activity === activity) return
        this.activity?.let(::unregister)
        this.activity = activity
        animePlayerActive = false
        playbackEligible = false
        playbackAdmitted = { false }
        _isActive.update { false }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            activity.registerReceiver(receiver, IntentFilter(ActionIntent), Context.RECEIVER_NOT_EXPORTED)
        } else {
            activity.registerReceiver(receiver, IntentFilter(ActionIntent))
        }
    }
    fun detach(activity: Activity) {
        if (this.activity !== activity) return
        unregister(activity)
        this.activity = null
        animePlayerActive = false
        playbackEligible = false
        playbackAdmitted = { false }
        _isActive.update { false }
    }
    private fun unregister(activity: Activity) {
        runCatching { activity.unregisterReceiver(receiver) }
    }
    fun onUserLeaveHint(activity: Activity) {
        if (this.activity === activity) enterIfEligible()
    }

    fun setState(active: Boolean, eligible: Boolean, admitted: () -> Boolean) {
        animePlayerActive = active
        playbackEligible = eligible
        playbackAdmitted = admitted
    }

    fun setActions(playing: Boolean, replaceWithPrevious: Boolean) {
        if (this.playing == playing && this.replaceWithPrevious == replaceWithPrevious) return
        this.playing = playing
        this.replaceWithPrevious = replaceWithPrevious
        val host = activity ?: return
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && host.isInPictureInPictureMode) {
            runCatching { host.setPictureInPictureParams(params(host)) }
        }
    }

    fun onPictureInPictureModeChanged(activity: Activity, active: Boolean) {
        if (this.activity !== activity) return
        _isActive.update { active }
    }

    fun enterIfEligible(): Boolean {
        val host = activity ?: return false
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
            !animePlayerActive || !playbackEligible || !playbackAdmitted() || host.isFinishing || host.isInPictureInPictureMode
        ) return false
        return host.enterPictureInPictureMode(params(host))
    }

    private fun params(host: Activity): PictureInPictureParams {
        val first = if (replaceWithPrevious) {
            action(host, PictureInPictureAction.Previous, android.R.drawable.ic_media_previous, "Previous episode")
        } else {
            action(host, PictureInPictureAction.SkipForward, android.R.drawable.ic_media_ff, "+10 s")
        }
        val toggle = if (playing) {
            action(host, PictureInPictureAction.Pause, android.R.drawable.ic_media_pause, "Pause")
        } else {
            action(host, PictureInPictureAction.Play, android.R.drawable.ic_media_play, "Play")
        }
        val next = action(host, PictureInPictureAction.Next, android.R.drawable.ic_media_next, "Next episode")
        return PictureInPictureParams.Builder()
            .setAspectRatio(Rational(16, 9))
            .setActions(listOf(first, toggle, next))
            .build()
    }

    private fun action(host: Activity, action: PictureInPictureAction, icon: Int, title: String): RemoteAction {
        val intent = Intent(ActionIntent).setPackage(host.packageName).putExtra(ActionExtra, action.ordinal)
        val pending = PendingIntent.getBroadcast(
            host, action.ordinal, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
        )
        return RemoteAction(Icon.createWithResource(host, icon), title, title, pending)
    }
}

internal actual val pictureInPicturePlatform: PictureInPicturePlatform = object : PictureInPicturePlatform {
    override val isSupported: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
    override val active: StateFlow<Boolean> = AndroidPictureInPictureController.isActive
    override val actions: Flow<PictureInPictureAction> = AndroidPictureInPictureController.actions

    override fun request(controller: MediaPlayerController?): Boolean = AndroidPictureInPictureController.enterIfEligible()
    override fun setPlaybackState(active: Boolean, eligible: Boolean, admitted: () -> Boolean) =
        AndroidPictureInPictureController.setState(active, eligible, admitted)
    override fun updateActions(playing: Boolean, replaceWithPrevious: Boolean) =
        AndroidPictureInPictureController.setActions(playing, replaceWithPrevious)
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.desktop.kt).

The implementation below defines `desktopLaunchers`, `externalPlayerChoices`, `isExecutable`, `launchExternalPlayer`, `mpvHeaderArgs`.

The source describes its contract as:

> Ordered launchers per OS: mpv first (takes headers), then other players, then the default handler.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.logging.AppLogger
import java.io.File
import java.util.Locale

/** Ordered launchers per OS: mpv first (takes headers), then other players, then the default handler. */
private fun desktopLaunchers(url: String, headers: Map<String, String>): List<Pair<ExternalPlayerChoice, List<String>>> {
    val os = System.getProperty("os.name").orEmpty().lowercase(Locale.US)
    val mpv = ExternalPlayerChoice("mpv", "mpv") to (listOf("mpv") + mpvHeaderArgs(headers) + url)
    return when {
        "mac" in os || "darwin" in os -> listOf(
            mpv,
            ExternalPlayerChoice("iina", "IINA") to listOf("/Applications/IINA.app/Contents/MacOS/iina-cli", url),
            ExternalPlayerChoice("vlc", "VLC") to listOf("/Applications/VLC.app/Contents/MacOS/VLC", url),
            ExternalPlayerChoice("system", "System default") to listOf("open", url),
        )
        "win" in os -> listOf(
            mpv,
            ExternalPlayerChoice("mpv.exe", "mpv.exe") to (listOf("mpv.exe") + mpvHeaderArgs(headers) + url),
            ExternalPlayerChoice("system", "System default") to listOf("cmd", "/c", "start", "", url),
        )
        else -> listOf( // assume Linux / *BSD
            mpv,
            ExternalPlayerChoice("vlc", "VLC") to listOf("vlc", url),
            ExternalPlayerChoice("system", "System default") to listOf("xdg-open", url),
        )
    }
}

/** Players whose executable exists (absolute path or on PATH), plus the system default handler. */
actual fun externalPlayerChoices(): List<ExternalPlayerChoice> =
    desktopLaunchers("", emptyMap()).filter { (choice, command) -> choice.id == "system" || isExecutable(command.first()) }
        .map { it.first }

private fun isExecutable(command: String): Boolean {
    if (File(command).isAbsolute) return File(command).canExecute()
    return System.getenv("PATH").orEmpty().split(File.pathSeparator).any { File(it, command).canExecute() }
}

actual fun launchExternalPlayer(url: String, headers: Map<String, String>, playerId: String): Boolean {
    if (url.isBlank()) return false
    val candidates = desktopLaunchers(url, headers).filter { playerId.isBlank() || it.first.id == playerId }
    for ((_, cmd) in candidates) {
        val started = runCatching {
            // Nobody reads the player's console output; an undrained pipe fills
            // up and stalls the player, so discard it and close its stdin.
            ProcessBuilder(cmd)
                .redirectErrorStream(true)
                .redirectOutput(ProcessBuilder.Redirect.DISCARD)
                .start()
                .outputStream
                .close()
            AppLogger.info("[player] handed to external launcher ${cmd.first()}")
            true
        }.getOrDefault(false)
        if (started) return true
    }
    AppLogger.warn("[player] no external launcher succeeded for url")
    return false
}

private fun mpvHeaderArgs(headers: Map<String, String>): List<String> {
    if (headers.isEmpty()) return emptyList()
    // mpv accepts `--http-header-fields=Header1: v1,Header2: v2`. Commas in
    // header values would break the parser, but standard streaming headers
    // (User-Agent, Referer, Origin, Cookie) never legitimately contain them.
    val joined = headers.entries.joinToString(",") { "${it.key}: ${it.value}" }
    return listOf("--http-header-fields=$joined")
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.desktop.kt).

```kotlin
package eu.friedcutlet.yokan.services.media.player

internal actual val pictureInPicturePlatform: PictureInPicturePlatform = NoPictureInPicture
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.ios.kt).

The implementation below defines `externalPlayerChoices`, `launchExternalPlayer`.

The source describes its contract as:

> URL-scheme players; each scheme is listed in Info.plist `LSApplicationQueriesSchemes`.

Cross-chapter imports used by this file: [`openSystemBrowser`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.system.openSystemBrowser
import io.ktor.http.encodeURLParameter

/** URL-scheme players; each scheme is listed in Info.plist `LSApplicationQueriesSchemes`. */
private val IosPlayers = listOf(
    ExternalPlayerChoice("vlc", "VLC") to { url: String -> "vlc-x-callback://x-callback-url/stream?url=${url.encodeURLParameter()}" },
    ExternalPlayerChoice("infuse", "Infuse") to { url: String -> "infuse://x-callback-url/play?url=${url.encodeURLParameter()}" },
    ExternalPlayerChoice("outplayer", "Outplayer") to { url: String -> "outplayer://$url" },
)

actual fun externalPlayerChoices(): List<ExternalPlayerChoice> =
    IosPlayers.map { it.first } + ExternalPlayerChoice("system", "System default")

actual fun launchExternalPlayer(url: String, headers: Map<String, String>, playerId: String): Boolean {
    // iOS won't honor per-request HTTP headers via openURL; the proxy URL
    // already has them injected, so a blank id hands it to the default
    // handler — VLC / Infuse / etc. will pick it up if installed.
    val player = IosPlayers.firstOrNull { it.first.id == playerId } ?: return openSystemBrowser(url)
    return openSystemBrowser(player.second(url))
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.ios.kt).

```kotlin
package eu.friedcutlet.yokan.services.media.player

internal actual val pictureInPicturePlatform: PictureInPicturePlatform = NoPictureInPicture
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/ExternalPlayer.wasm.kt).

The implementation below defines `externalPlayerChoices`, `launchExternalPlayer`.

The source describes its contract as:

> Browsers cannot launch native applications with a stream URL.

```kotlin
package eu.friedcutlet.yokan.services.media.player

/** Browsers cannot launch native applications with a stream URL. */
actual fun externalPlayerChoices(): List<ExternalPlayerChoice> = emptyList()

actual fun launchExternalPlayer(url: String, headers: Map<String, String>, playerId: String): Boolean = false
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlatformPictureInPicture.wasm.kt).

The implementation below defines `WasmPictureInPicture`, `bindSurface`, `request`, `setPlaybackState`, `updateActions`, `setMediaSessionAction`, `clearMediaSessionAction`.

The source describes its contract as:

> The browser PiP window shows Media Session track/seek handlers; play/pause stays on the video element.

Cross-chapter imports used by this file: [`VideoPlayerState`](../chapters/18-media-compat-vendor.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import io.github.kdroidfilter.composemediaplayer.VideoPlayerState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.update

internal actual val pictureInPicturePlatform: PictureInPicturePlatform = WasmPictureInPicture

private object WasmPictureInPicture : PictureInPicturePlatform {
    private val activeState = MutableStateFlow(false)
    private val actionEvents = MutableSharedFlow<PictureInPictureAction>(extraBufferCapacity = 8)
    private var playbackAdmitted: () -> Boolean = { false }
    private val surfaces = mutableMapOf<MediaPlayerController, VideoPlayerState>()
    private var requestedSurface: VideoPlayerState? = null

    override val isSupported: Boolean get() = surfaces.values.any { it.isPictureInPictureSupported() }
    override val active: StateFlow<Boolean> = activeState
    override val actions: Flow<PictureInPictureAction> = actionEvents

    override fun bindSurface(controller: MediaPlayerController, state: VideoPlayerState): () -> Unit {
        surfaces[controller] = state
        state.onPictureInPictureChanged = { active ->
            if (surfaces[controller] === state && requestedSurface === state) activeState.update { active }
        }
        return {
            if (surfaces[controller] === state) surfaces.remove(controller)
            state.onPictureInPictureChanged = {}
            if (requestedSurface === state) {
                requestedSurface = null
                activeState.update { false }
            }
        }
    }

    override fun request(controller: MediaPlayerController?): Boolean {
        if (!playbackAdmitted()) return false
        val surface = surfaces[controller] ?: return false
        val previous = requestedSurface
        requestedSurface = surface
        val accepted = surface.requestPictureInPicture()
        if (!accepted && requestedSurface === surface) requestedSurface = previous
        return accepted
    }

    override fun setPlaybackState(active: Boolean, eligible: Boolean, admitted: () -> Boolean) {
        playbackAdmitted = { active && admitted() }
    }

    /** The browser PiP window shows Media Session track/seek handlers; play/pause stays on the video element. */
    override fun updateActions(playing: Boolean, replaceWithPrevious: Boolean) {
        setMediaSessionAction("nexttrack") { actionEvents.tryEmit(PictureInPictureAction.Next) }
        if (replaceWithPrevious) {
            clearMediaSessionAction("seekforward")
            setMediaSessionAction("previoustrack") { actionEvents.tryEmit(PictureInPictureAction.Previous) }
        } else {
            clearMediaSessionAction("previoustrack")
            setMediaSessionAction("seekforward") { actionEvents.tryEmit(PictureInPictureAction.SkipForward) }
        }
    }
}

@OptIn(ExperimentalWasmJsInterop::class)
private fun setMediaSessionAction(action: String, handler: () -> Unit): Unit =
    js("{ try { if (navigator.mediaSession) navigator.mediaSession.setActionHandler(action, () => handler()); } catch (e) {} }")

@OptIn(ExperimentalWasmJsInterop::class)
private fun clearMediaSessionAction(action: String): Unit =
    js("{ try { if (navigator.mediaSession) navigator.mediaSession.setActionHandler(action, null); } catch (e) {} }")
```
[chapter-file-end]: #

### Check your understanding

Leave the surface while PiP entry is pending, then retire the profile. Verify the native/browser operation is joined and cannot revive the old player.
[chapter-content-end]: #


## Step 5: implement Cast

Recreate CastController, mDNS, framing/protobuf protocol, session and platform network/browser adapters. Discovery runs while device selection is open. Starting Cast pauses local playback and loads at current position; queue the following episodes as they resolve. Handle status/seek/queue/stop, subtitles and receiver styling. The source uses Default Media Receiver `CC1AD845`. Leaving the local player can cancel pending extraction without stopping an established cast. Stopping Cast can restore local position for the matching episode.

[chapter-content-start]: #
### Follow the code

Discovery, transport framing and media session control are distinct components. A Cast load starts from the local episode/position and pauses local playback; subsequent media status and queue operations belong to the receiver session. Resolve queue entries under the owner, but do not stop an established cast merely because local extraction/UI work is disposed. Return-to-local position is applied only to the matching episode.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocol.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdns.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSession.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.ios.kt`
- `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.jvmCommon.kt`
- `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/cast/NetworkCastController.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocol.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocol.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocol.kt).

The implementation below defines `CastTransport`, `write`, `read`, `close`, `CastMessage`, `CastMessage.toFrame`, `byte`, `string`, `varintSize`, `decodeCastMessage` and 13 further declarations.

The source describes its contract as:

> Receivers reject messages above 64 KiB, so anything larger is a corrupt stream.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject

// CASTV2: TLS on port 8009 carrying length-prefixed CastMessage protobufs with JSON payloads.

internal const val DEFAULT_MEDIA_RECEIVER_APP_ID = "CC1AD845"
internal const val NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection"
internal const val NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat"
internal const val NS_RECEIVER = "urn:x-cast:com.google.cast.receiver"
internal const val NS_MEDIA = "urn:x-cast:com.google.cast.media"
internal const val SENDER_ID = "sender-0"
internal const val RECEIVER_ID = "receiver-0"

/** Receivers reject messages above 64 KiB, so anything larger is a corrupt stream. */
private const val MAX_FRAME_BYTES = 64 * 1024

/** Byte stream to a receiver (TLS socket on port 8009). */
internal interface CastTransport {
    /** Writes one length-prefixed frame. */
    suspend fun write(frame: ByteArray)
    /** Returns the next non-empty chunk of the stream (frame boundaries are not preserved); throws at end of stream. */
    suspend fun read(): ByteArray
    fun close()
}

/** STRING-payload CastMessage; device-auth BINARY payloads are not used by this client. */
internal data class CastMessage(
    val sourceId: String,
    val destinationId: String,
    val namespace: String,
    val payload: String,
)

/** Encodes as a 4-byte big-endian length followed by the protobuf (fields 1..6 in order). */
internal fun CastMessage.toFrame(): ByteArray {
    val strings = arrayOf(sourceId, destinationId, namespace, payload).map { it.encodeToByteArray() }
    val bodySize = 4 + strings.sumOf { 1 + varintSize(it.size) + it.size }
    val out = ByteArray(4 + bodySize)
    var p = 0
    fun byte(value: Int) { out[p++] = value.toByte() }
    fun string(field: Int, bytes: ByteArray) {
        byte(field shl 3 or 2)
        var n = bytes.size
        while (n >= 0x80) { byte((n and 0x7F) or 0x80); n = n ushr 7 }
        byte(n)
        bytes.copyInto(out, p)
        p += bytes.size
    }
    for (shift in intArrayOf(24, 16, 8, 0)) byte(bodySize ushr shift)
    byte(0x08); byte(0) // protocol_version = CASTV2_1_0
    string(2, strings[0])
    string(3, strings[1])
    string(4, strings[2])
    byte(0x28); byte(0) // payload_type = STRING
    string(6, strings[3])
    return out
}

private fun varintSize(value: Int): Int {
    var n = value ushr 7
    var size = 1
    while (n != 0) { n = n ushr 7; size++ }
    return size
}

internal fun decodeCastMessage(bytes: ByteArray, start: Int = 0, end: Int = bytes.size): CastMessage {
    var p = start
    fun varint(): Long {
        var result = 0L
        var shift = 0
        while (true) {
            check(p < end && shift < 64) { "Truncated Cast message" }
            val b = bytes[p++].toInt()
            result = result or ((b and 0x7F).toLong() shl shift)
            if ((b and 0x80) == 0) return result
            shift += 7
        }
    }
    var source: String? = null
    var destination: String? = null
    var namespace: String? = null
    var payload = ""
    while (p < end) {
        val key = varint().toInt()
        when (key and 7) {
            0 -> varint()
            1 -> p += 8
            5 -> p += 4
            2 -> {
                val length = varint()
                check(length in 0..(end - p).toLong()) { "Truncated Cast message" }
                val valueEnd = p + length.toInt()
                when (key ushr 3) {
                    2 -> source = bytes.decodeToString(p, valueEnd)
                    3 -> destination = bytes.decodeToString(p, valueEnd)
                    4 -> namespace = bytes.decodeToString(p, valueEnd)
                    6 -> payload = bytes.decodeToString(p, valueEnd)
                }
                p = valueEnd
            }
            else -> error("Unsupported protobuf wire type ${key and 7}")
        }
        check(p <= end) { "Truncated Cast message" }
    }
    return CastMessage(
        checkNotNull(source) { "Cast message without source" },
        checkNotNull(destination) { "Cast message without destination" },
        checkNotNull(namespace) { "Cast message without namespace" },
        payload,
    )
}

/** Reassembles frames from arbitrarily split transport chunks. */
internal class CastFrameReader(private val transport: CastTransport) {
    private var buffer = ByteArray(0)

    suspend fun next(): CastMessage {
        while (true) {
            if (buffer.size >= 4) {
                val length = ((buffer[0].toInt() and 0xFF) shl 24) or ((buffer[1].toInt() and 0xFF) shl 16) or
                    ((buffer[2].toInt() and 0xFF) shl 8) or (buffer[3].toInt() and 0xFF)
                check(length in 0..MAX_FRAME_BYTES) { "Invalid Cast frame length $length" }
                if (buffer.size >= 4 + length) {
                    val message = decodeCastMessage(buffer, 4, 4 + length)
                    buffer = buffer.copyOfRange(4 + length, buffer.size)
                    return message
                }
            }
            buffer += transport.read()
        }
    }
}

/** `{"type":type,"requestId":…,"mediaSessionId":…, …extra}`; ids are omitted when null. */
internal fun castJson(
    type: String,
    requestId: Int? = null,
    mediaSessionId: Int? = null,
    extra: JsonObjectBuilder.() -> Unit = {},
): String = buildJsonObject {
    put("type", type)
    requestId?.let { put("requestId", it) }
    mediaSessionId?.let { put("mediaSessionId", it) }
    extra()
}.toString()

internal fun queueLoadJson(
    requestId: Int,
    items: List<CastMedia>,
    startIndex: Int,
    startPositionMs: Long,
    style: CastTextStyle,
    activeSubtitleIndex: Int?,
): String = castJson("QUEUE_LOAD", requestId) {
    put("items", queueItemsJson(items, style, startIndex, startPositionMs, activeSubtitleIndex))
    put("startIndex", startIndex)
    put("repeatMode", "REPEAT_OFF")
}

/** QueueItem objects; the start item carries the resume position and active subtitle. */
internal fun queueItemsJson(
    items: List<CastMedia>,
    style: CastTextStyle,
    startIndex: Int = -1,
    startPositionMs: Long = 0,
    activeSubtitleIndex: Int? = null,
): JsonArray = buildJsonArray {
    items.forEachIndexed { index, media ->
        val start = index == startIndex
        // Track ids are 1-based subtitle indexes so the active index maps without a lookup table.
        val tracks = media.subtitles.withIndex().filter { isWebVtt(it.value.url) }
        add(buildJsonObject {
            putJsonObject("media") {
                put("contentId", media.url)
                put("contentUrl", media.url)
                put("streamType", "BUFFERED")
                put("contentType", media.contentType ?: guessContentType(media.url))
                putJsonObject("metadata") {
                    put("metadataType", 0)
                    put("title", media.title)
                    media.subtitle?.let { put("subtitle", it) }
                    media.posterUrl?.let { url -> putJsonArray("images") { add(buildJsonObject { put("url", url) }) } }
                }
                putJsonArray("tracks") {
                    tracks.forEach { (i, subtitle) ->
                        add(buildJsonObject {
                            put("trackId", i + 1)
                            put("type", "TEXT")
                            put("trackContentId", subtitle.url)
                            put("trackContentType", "text/vtt")
                            put("subtype", "SUBTITLES")
                            put("name", subtitle.label)
                            subtitle.language?.let { put("language", it) }
                        })
                    }
                }
                putJsonObject("textTrackStyle") {
                    put("foregroundColor", castColor(style.foregroundArgb))
                    put("edgeType", if ((style.edgeArgb ushr 24) == 0) "NONE" else "OUTLINE")
                    put("edgeColor", castColor(style.edgeArgb))
                    put("backgroundColor", castColor(style.backgroundArgb))
                    put("fontScale", style.fontScale)
                    put("fontStyle", when {
                        style.bold && style.italic -> "BOLD_ITALIC"
                        style.bold -> "BOLD"
                        style.italic -> "ITALIC"
                        else -> "NORMAL"
                    })
                }
            }
            put("autoplay", true)
            if (start) {
                put("startTime", startPositionMs / 1000.0)
                activeSubtitleIndex
                    ?.takeIf { active -> tracks.any { it.index == active } }
                    ?.let { putJsonArray("activeTrackIds") { add(it + 1) } }
            }
        })
    }
}

/** The Default Media Receiver only renders WebVTT side-loaded text tracks. */
private fun isWebVtt(url: String) = url.substringBefore('#').substringBefore('?').endsWith(".vtt", ignoreCase = true)

private fun guessContentType(url: String): String {
    val path = url.substringBefore('#').substringBefore('?').lowercase()
    return when {
        path.endsWith(".m3u8") -> "application/x-mpegURL"
        path.endsWith(".mpd") -> "application/dash+xml"
        path.endsWith(".webm") -> "video/webm"
        else -> "video/mp4"
    }
}

/** ARGB int → Cast `#RRGGBBAA`. */
internal fun castColor(argb: Int): String =
    "#" + ((argb shl 8) or (argb ushr 24)).toUInt().toString(16).padStart(8, '0').uppercase()

internal fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content
internal fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull
internal fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.doubleOrNull

/**
 * Applies one MEDIA_STATUS `status[]` entry (null when the receiver has no media session) to the previous status.
 * [itemIds] are the receiver's queue item ids in queue order, so their positions index [CastStatus.queue].
 */
internal fun CastStatus.withMediaStatus(entry: JsonObject?, itemIds: List<Int>): CastStatus {
    if (entry == null) return copy(playing = false, buffering = false)
    val state = entry.string("playerState")
    val idleReason = entry.string("idleReason")
    val index = entry.int("currentItemId")?.let(itemIds::indexOf) ?: currentIndex
    val duration = (entry["media"] as? JsonObject)?.double("duration")
    val idle = state == "IDLE"
    return copy(
        playing = state == "PLAYING",
        buffering = state == "BUFFERING" || state == "LOADING",
        positionMs = entry.double("currentTime")?.let { (it * 1000).toLong() } ?: positionMs,
        durationMs = duration?.let { (it * 1000).toLong() } ?: if (index == currentIndex) durationMs else 0,
        currentIndex = index,
        finished = idle && idleReason == "FINISHED" && (index == -1 || index == queue.lastIndex),
        error = if (idle && idleReason == "ERROR") "Cast device could not play this media" else error.takeIf { idle },
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdns.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdns.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdns.kt).

The implementation below defines `castMdnsQuery`, `parseCastMdnsResponse`, `MdnsReader`, `u8`, `u16`, `skip`, `name`, `castDevices`, `txt`.

The source describes its contract as:

> One-question mDNS query: PTR `_googlecast._tcp.local` IN.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

internal const val CAST_MDNS_SERVICE = "_googlecast._tcp.local"
private const val TYPE_A = 1
private const val TYPE_PTR = 12
private const val TYPE_TXT = 16
private const val TYPE_SRV = 33

/** One-question mDNS query: PTR `_googlecast._tcp.local` IN. */
internal fun castMdnsQuery(): ByteArray {
    val labels = CAST_MDNS_SERVICE.split('.').map { it.encodeToByteArray() }
    val out = ByteArray(12 + labels.sumOf { it.size + 1 } + 1 + 4)
    out[5] = 1 // QDCOUNT
    var p = 12
    for (label in labels) {
        out[p++] = label.size.toByte()
        label.copyInto(out, p)
        p += label.size
    }
    p++ // root label
    out[p + 1] = TYPE_PTR.toByte()
    out[p + 3] = 1 // class IN
    return out
}

/**
 * Cast devices announced in an mDNS response. Host comes from the SRV target's A record, falling back to
 * [sourceHost] (the responder's address). Malformed or truncated packets yield an empty list.
 */
internal fun parseCastMdnsResponse(packet: ByteArray, sourceHost: String): List<CastDevice> = try {
    MdnsReader(packet).castDevices(sourceHost)
} catch (_: IllegalArgumentException) {
    emptyList()
}

private class MdnsReader(private val bytes: ByteArray) {
    var pos = 0

    fun u8(): Int {
        require(pos < bytes.size) { "Truncated mDNS packet" }
        return bytes[pos++].toInt() and 0xFF
    }

    fun u16() = (u8() shl 8) or u8()

    fun skip(count: Int) {
        require(count in 0..bytes.size - pos) { "Truncated mDNS packet" }
        pos += count
    }

    /** Reads a possibly compressed name (RFC 1035 §4.1.4). */
    fun name(): String {
        val labels = mutableListOf<String>()
        var cursor = pos
        var jumps = 0
        var end = -1
        while (true) {
            require(cursor < bytes.size) { "Truncated mDNS name" }
            val length = bytes[cursor].toInt() and 0xFF
            when {
                length == 0 -> { cursor++; break }
                (length and 0xC0) == 0xC0 -> {
                    require(cursor + 1 < bytes.size && ++jumps <= 32) { "Bad mDNS name pointer" }
                    if (end < 0) end = cursor + 2
                    cursor = ((length and 0x3F) shl 8) or (bytes[cursor + 1].toInt() and 0xFF)
                }
                (length and 0xC0) != 0 -> throw IllegalArgumentException("Bad mDNS label")
                else -> {
                    require(cursor + 1 + length <= bytes.size) { "Truncated mDNS label" }
                    labels += bytes.decodeToString(cursor + 1, cursor + 1 + length)
                    cursor += 1 + length
                }
            }
        }
        pos = if (end < 0) cursor else end
        return labels.joinToString(".")
    }

    fun castDevices(sourceHost: String): List<CastDevice> {
        skip(2) // id
        require((u16() and 0x8000) != 0) { "Not an mDNS response" }
        val questions = u16()
        val records = u16() + u16() + u16()
        repeat(questions) { name(); skip(4) }
        val instances = linkedSetOf<String>()
        val services = mutableMapOf<String, Pair<String, Int>>()
        val texts = mutableMapOf<String, Map<String, String>>()
        val addresses = mutableMapOf<String, String>()
        repeat(records) {
            val owner = name()
            val type = u16()
            skip(2) // class (with cache-flush bit)
            val ttl = (u16().toLong() shl 16) or u16().toLong()
            val length = u16()
            val end = pos + length
            require(end <= bytes.size) { "Truncated mDNS record" }
            val key = owner.lowercase()
            when (type) {
                TYPE_PTR -> if (key == CAST_MDNS_SERVICE && ttl > 0) instances += name()
                TYPE_SRV -> { skip(4); val port = u16(); services[key] = name().lowercase() to port }
                TYPE_TXT -> texts[key] = txt(end)
                TYPE_A -> if (length == 4) addresses[key] = List(4) { u8() }.joinToString(".")
            }
            require(pos <= end) { "mDNS record overruns its length" }
            pos = end
        }
        return instances.map { instance ->
            val key = instance.lowercase()
            val suffix = ".$CAST_MDNS_SERVICE"
            val label = if (instance.endsWith(suffix, ignoreCase = true)) instance.dropLast(suffix.length) else instance
            val txt = texts[key].orEmpty()
            val srv = services[key]
            CastDevice(
                id = txt["id"] ?: label,
                name = txt["fn"] ?: label,
                host = srv?.first?.let(addresses::get) ?: sourceHost,
                port = srv?.second ?: 8009,
            )
        }
    }

    private fun txt(end: Int): Map<String, String> {
        val entries = mutableMapOf<String, String>()
        while (pos < end) {
            val length = u8()
            require(pos + length <= end) { "Truncated TXT entry" }
            val entry = bytes.decodeToString(pos, pos + length)
            pos += length
            val separator = entry.indexOf('=')
            if (separator > 0) entries[entry.substring(0, separator).lowercase()] = entry.substring(separator + 1)
        }
        return entries
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSession.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSession.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSession.kt).

The implementation below defines `CastSession`, `nextId`, `connect`, `loadQueue`, `append`, `play`, `pause`, `seekTo`, `next`, `previous` and 12 further declarations.

The source describes its contract as:

> One CASTV2 session over \[transport\]: CONNECT → LAUNCH Default Media Receiver → CONNECT to its transportId → media commands. Not thread-safe: every call must run on \[scope\]'s dispatcher, which must be single-threaded. Failures are thrown from suspend calls and surfaced as \[CastStatus.error\]; nothing is retried.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.put

internal const val CAST_CONNECT_TIMEOUT_MS = 15_000L
private const val TICK_MS = 1_000L
private const val HEARTBEAT_TICKS = 5
private const val MAX_MISSED_HEARTBEATS = 3

/**
 * One CASTV2 session over [transport]: CONNECT → LAUNCH Default Media Receiver → CONNECT to its transportId → media
 * commands. Not thread-safe: every call must run on [scope]'s dispatcher, which must be single-threaded.
 * Failures are thrown from suspend calls and surfaced as [CastStatus.error]; nothing is retried.
 */
internal class CastSession(
    private val device: CastDevice,
    private val transport: CastTransport,
    private val scope: CoroutineScope,
) {
    private val reader = CastFrameReader(transport)
    private val writeLock = Mutex()
    private val launched = CompletableDeferred<Unit>()
    private val mediaSessionId = MutableStateFlow<Int?>(null)
    private val _status = MutableStateFlow<CastStatus?>(null)
    val status: StateFlow<CastStatus?> = _status.asStateFlow()

    private var requestId = 0
    private var transportId: String? = null
    private var appSessionId: String? = null
    private var currentItemId: Int? = null
    private var itemIds = emptyList<Int>()
    private var itemIdsRequested = false
    private var style = CastTextStyle()
    private var missedHeartbeats = 0
    private var closed = false
    private val jobs = mutableListOf<Job>()

    private fun nextId() = ++requestId

    suspend fun connect() {
        jobs += scope.launch { readLoop() }
        try {
            withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) {
                send(NS_CONNECTION, RECEIVER_ID, castJson("CONNECT"))
                send(NS_RECEIVER, RECEIVER_ID, castJson("LAUNCH", nextId()) { put("appId", DEFAULT_MEDIA_RECEIVER_APP_ID) })
                launched.await()
                send(NS_CONNECTION, checkNotNull(transportId), castJson("CONNECT"))
            } ?: error("Timed out connecting to ${device.name}")
        } catch (e: Throwable) {
            close()
            throw e
        }
        _status.value = CastStatus(device)
        jobs += scope.launch { tickLoop() }
    }

    suspend fun loadQueue(
        items: List<CastMedia>,
        startIndex: Int,
        startPositionMs: Long,
        style: CastTextStyle,
        activeSubtitleIndex: Int?,
    ) {
        require(startIndex in items.indices) { "Start index $startIndex outside queue of ${items.size}" }
        this.style = style
        itemIds = emptyList()
        currentItemId = null
        itemIdsRequested = false
        _status.update {
            it?.copy(
                queue = items, currentIndex = startIndex, positionMs = startPositionMs, durationMs = 0,
                playing = false, buffering = true, finished = false, error = null,
            )
        }
        send(NS_MEDIA, connectedTransportId(), queueLoadJson(nextId(), items, startIndex, startPositionMs, style, activeSubtitleIndex))
    }

    suspend fun append(items: List<CastMedia>) {
        if (items.isEmpty()) return
        // The media session id arrives with the first MEDIA_STATUS after QUEUE_LOAD.
        val sessionId = withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) { mediaSessionId.filterNotNull().first() }
            ?: error("No media loaded on ${device.name}")
        send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_INSERT", nextId(), sessionId) {
            put("items", queueItemsJson(items, style))
        })
        _status.update { it?.copy(queue = it.queue + items, finished = false) }
    }

    suspend fun play() = mediaCommand("PLAY")
    suspend fun pause() = mediaCommand("PAUSE")
    suspend fun seekTo(positionMs: Long) = mediaCommand("SEEK") { put("currentTime", positionMs / 1000.0) }
    suspend fun next() = mediaCommand("QUEUE_UPDATE") { put("jump", 1) }
    suspend fun previous() = mediaCommand("QUEUE_UPDATE") { put("jump", -1) }

    suspend fun jumpTo(index: Int) {
        val itemId = itemIds.getOrNull(index)
        val current = _status.value?.currentIndex ?: -1
        when {
            itemId != null -> mediaCommand("QUEUE_UPDATE") { put("currentItemId", itemId) }
            current >= 0 -> mediaCommand("QUEUE_UPDATE") { put("jump", index - current) }
        }
    }

    suspend fun disconnect() {
        try {
            if (!closed) {
                appSessionId?.let { send(NS_RECEIVER, RECEIVER_ID, castJson("STOP", nextId()) { put("sessionId", it) }) }
                transportId?.let { send(NS_CONNECTION, it, castJson("CLOSE")) }
                send(NS_CONNECTION, RECEIVER_ID, castJson("CLOSE"))
            }
        } catch (e: CancellationException) {
            throw e
        } catch (e: Throwable) {
            AppLogger.warn("Cast: stopping receiver on ${device.name} failed: ${e.message}")
        } finally {
            close()
            _status.value = null
        }
    }

    fun close() {
        closed = true
        launched.cancel()
        jobs.forEach { it.cancel() }
        transport.close()
    }

    /** No media session means there is nothing to control yet. */
    private suspend fun mediaCommand(type: String, extra: JsonObjectBuilder.() -> Unit = {}) {
        val sessionId = mediaSessionId.value ?: return
        send(NS_MEDIA, connectedTransportId(), castJson(type, nextId(), sessionId, extra))
    }

    private fun connectedTransportId() = checkNotNull(transportId.takeIf { !closed }) { "Not connected to ${device.name}" }

    private suspend fun send(namespace: String, destination: String, payload: String) {
        val frame = CastMessage(SENDER_ID, destination, namespace, payload).toFrame()
        try {
            writeLock.withLock { transport.write(frame) }
        } catch (e: CancellationException) {
            throw e
        } catch (e: Throwable) {
            fail("Lost connection to ${device.name}: ${e.message}", e)
            throw e
        }
    }

    private fun fail(message: String, cause: Throwable?) {
        if (closed) return
        AppLogger.warn("Cast: $message")
        launched.completeExceptionally(IllegalStateException(message, cause))
        _status.update { it?.copy(playing = false, buffering = false, error = message) }
        close()
    }

    private suspend fun readLoop() {
        try {
            while (true) handle(reader.next())
        } catch (e: CancellationException) {
            throw e
        } catch (e: Throwable) {
            fail("Lost connection to ${device.name}: ${e.message}", e)
        }
    }

    /** Polls media status each second while playing (receivers only push on state changes) and pings every 5s. */
    private suspend fun tickLoop() {
        var tick = 0
        try {
            while (true) {
                delay(TICK_MS)
                if (++tick % HEARTBEAT_TICKS == 0) {
                    if (++missedHeartbeats > MAX_MISSED_HEARTBEATS) {
                        fail("${device.name} stopped responding", null)
                        return
                    }
                    send(NS_HEARTBEAT, RECEIVER_ID, castJson("PING"))
                }
                val sessionId = mediaSessionId.value
                if (sessionId != null && _status.value?.playing == true) {
                    send(NS_MEDIA, connectedTransportId(), castJson("GET_STATUS", nextId(), sessionId))
                }
            }
        } catch (e: CancellationException) {
            throw e
        } catch (_: Throwable) {
            // send() already failed the session.
        }
    }

    private suspend fun handle(message: CastMessage) {
        missedHeartbeats = 0
        val json = try {
            Json.parseToJsonElement(message.payload) as? JsonObject
        } catch (_: IllegalArgumentException) {
            null
        } ?: return
        when (json.string("type")) {
            "PING" -> send(NS_HEARTBEAT, message.sourceId, castJson("PONG"))
            "CLOSE" -> if (message.sourceId == transportId || message.sourceId == RECEIVER_ID) {
                fail("${device.name} closed the Cast session", null)
            }
            "RECEIVER_STATUS" -> receiverStatus(json)
            "LAUNCH_ERROR" -> launched.completeExceptionally(
                IllegalStateException("${device.name} refused to launch the media receiver: ${json.string("reason")}"),
            )
            "MEDIA_STATUS" -> mediaStatus(json)
            "QUEUE_ITEM_IDS" -> {
                itemIds = (json["itemIds"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.intOrNull }.orEmpty()
                itemIdsRequested = false
                _status.update { status -> status?.copy(currentIndex = currentItemId?.let(itemIds::indexOf) ?: status.currentIndex) }
            }
            "LOAD_FAILED", "INVALID_REQUEST", "INVALID_PLAYER_STATE" -> {
                val reason = json.string("reason")?.let { " ($it)" }.orEmpty()
                _status.update { it?.copy(buffering = false, error = "Cast device rejected the request: ${json.string("type")}$reason") }
            }
        }
    }

    private fun receiverStatus(json: JsonObject) {
        val applications = ((json["status"] as? JsonObject)?.get("applications") as? JsonArray).orEmpty()
        val app = applications.firstNotNullOfOrNull { entry ->
            (entry as? JsonObject)?.takeIf { it.string("appId") == DEFAULT_MEDIA_RECEIVER_APP_ID }
        }
        if (app == null) {
            // Before launch completes the receiver may still report its idle backdrop app.
            if (transportId != null) fail("Media receiver on ${device.name} was stopped", null)
            return
        }
        val id = app.string("transportId") ?: return
        appSessionId = app.string("sessionId")
        if (transportId == null) {
            transportId = id
            launched.complete(Unit)
        }
    }

    private suspend fun mediaStatus(json: JsonObject) {
        val entry = (json["status"] as? JsonArray)?.firstOrNull() as? JsonObject
        mediaSessionId.value = entry?.int("mediaSessionId")
        entry?.int("currentItemId")?.let { currentItemId = it }
        val queueSize = _status.value?.queue?.size ?: 0
        // Receivers may send only a window of items; only a complete list maps positions to queue indexes.
        (entry?.get("items") as? JsonArray)
            ?.mapNotNull { (it as? JsonObject)?.int("itemId") }
            ?.takeIf { it.size == queueSize }
            ?.let { itemIds = it }
        _status.update { it?.withMediaStatus(entry, itemIds) }
        val sessionId = mediaSessionId.value
        val itemId = currentItemId
        if (sessionId != null && itemId != null && itemId !in itemIds && !itemIdsRequested) {
            itemIdsRequested = true
            send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_GET_ITEM_IDS", nextId(), sessionId))
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.kt).

The implementation below defines `CastDevice`, `CastSubtitle`, `CastTextStyle`, `CastMedia`, `CastStatus`, `CastController`, `startDiscovery`, `stopDiscovery`, `connect`, `loadQueue` and 10 further declarations.

The source describes its contract as:

> Index into \[queue\] of the receiver's current item, -1 when idle/unknown.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow

data class CastDevice(val id: String, val name: String, val host: String = "", val port: Int = 8009)

data class CastSubtitle(val url: String, val label: String, val language: String? = null)

data class CastTextStyle(
    val foregroundArgb: Int = 0xFFFFFFFF.toInt(),
    val edgeArgb: Int = 0xFF000000.toInt(),
    val backgroundArgb: Int = 0,
    val fontScale: Double = 1.0,
    val bold: Boolean = false,
    val italic: Boolean = false,
)

data class CastMedia(
    val url: String,
    val title: String,
    val subtitle: String? = null,
    val contentType: String? = null,
    val posterUrl: String? = null,
    val subtitles: List<CastSubtitle> = emptyList(),
    val itemKey: String = url,
)

data class CastStatus(
    val device: CastDevice,
    val playing: Boolean = false,
    val buffering: Boolean = false,
    val positionMs: Long = 0,
    val durationMs: Long = 0,
    val queue: List<CastMedia> = emptyList(),
    /** Index into [queue] of the receiver's current item, -1 when idle/unknown. */
    val currentIndex: Int = -1,
    /** Receiver went IDLE with reason FINISHED after the last item. */
    val finished: Boolean = false,
    val error: String? = null,
)

/**
 * Casts to Chromecast's Default Media Receiver. The receiver fetches media URLs itself, so streams that need
 * request headers (referer, cookies, auth) or are only reachable from this device cannot play there.
 */
interface CastController {
    /** False where the platform has no casting path at runtime (e.g. non-Chromium browser). */
    val isSupported: StateFlow<Boolean>
    /** True when the platform shows its own device picker (web Cast SDK); connect(null) opens it. */
    val usesSystemPicker: Boolean
    val devices: StateFlow<List<CastDevice>>
    /** Null when no session. */
    val status: StateFlow<CastStatus?>
    fun startDiscovery()
    fun stopDiscovery()
    /** Throws on failure; launches the Default Media Receiver (app id CC1AD845). */
    suspend fun connect(device: CastDevice?)
    suspend fun loadQueue(
        items: List<CastMedia>,
        startIndex: Int,
        startPositionMs: Long,
        style: CastTextStyle,
        activeSubtitleIndex: Int?,
    )
    /** Queue insert at end. */
    suspend fun append(items: List<CastMedia>)
    fun play()
    fun pause()
    fun seekTo(positionMs: Long)
    fun next()
    fun previous()
    fun jumpTo(index: Int)
    /** Stops the receiver app and closes the transport. */
    suspend fun disconnect()
    /** Owner shutdown: cancels jobs and closes sockets; idempotent. */
    fun close()
}

expect fun createCastController(scope: CoroutineScope): CastController
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.android.kt).

The implementation below defines `holdCastMulticastLock`.

The source describes its contract as:

> Wi-Fi drivers filter multicast to save power; mDNS discovery needs it delivered while browsing.

Cross-chapter imports used by this file: [`AndroidAppContext`](../chapters/23-platform-hosts-and-adapters.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import android.content.Context
import android.net.wifi.WifiManager
import eu.friedcutlet.yokan.AndroidAppContext

/** Wi-Fi drivers filter multicast to save power; mDNS discovery needs it delivered while browsing. */
internal actual fun holdCastMulticastLock(): () -> Unit {
    val wifi = AndroidAppContext.appContext?.applicationContext?.getSystemService(Context.WIFI_SERVICE) as? WifiManager
        ?: return {}
    val lock = wifi.createMulticastLock("yokan-cast-discovery").apply {
        setReferenceCounted(false)
        acquire()
    }
    return { lock.release() }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMulticastLock.desktop.kt).

The implementation below defines `holdCastMulticastLock`.

The source describes its contract as:

> Desktop network stacks deliver multicast without an explicit lock.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

/** Desktop network stacks deliver multicast without an explicit lock. */
internal actual fun holdCastMulticastLock(): () -> Unit = {}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.ios.kt).

The implementation below defines `createCastController`, `BonjourCast`, `devices`, `open`, `browseCastServices`, `serviceName`, `castDevice`, `txtValue`, `openNetworkTransport`, `NetworkCastTransport` and 4 further declarations.

The source describes its contract as:

> Browses with nw_browser and connects straight to the service endpoint, so no separate host resolution.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

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

package eu.friedcutlet.yokan.services.media.cast

import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.readBytes
import kotlinx.cinterop.toKString
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import platform.Network.NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT
import platform.Network.NW_PARAMETERS_DEFAULT_CONFIGURATION
import platform.Network.nw_browse_descriptor_create_bonjour_service
import platform.Network.nw_browse_descriptor_set_include_txt_record
import platform.Network.nw_browse_result_copy_endpoint
import platform.Network.nw_browse_result_copy_txt_record_object
import platform.Network.nw_browse_result_t
import platform.Network.nw_browser_cancel
import platform.Network.nw_browser_create
import platform.Network.nw_browser_set_browse_results_changed_handler
import platform.Network.nw_browser_set_queue
import platform.Network.nw_browser_set_state_changed_handler
import platform.Network.nw_browser_start
import platform.Network.nw_browser_state_failed
import platform.Network.nw_browser_state_waiting
import platform.Network.nw_connection_cancel
import platform.Network.nw_connection_create
import platform.Network.nw_connection_receive
import platform.Network.nw_connection_send
import platform.Network.nw_connection_set_queue
import platform.Network.nw_connection_set_state_changed_handler
import platform.Network.nw_connection_start
import platform.Network.nw_connection_state_cancelled
import platform.Network.nw_connection_state_failed
import platform.Network.nw_connection_state_ready
import platform.Network.nw_connection_state_waiting
import platform.Network.nw_connection_t
import platform.Network.nw_endpoint_create_bonjour_service
import platform.Network.nw_endpoint_create_host
import platform.Network.nw_endpoint_get_bonjour_service_name
import platform.Network.nw_endpoint_t
import platform.Network.nw_error_get_error_code
import platform.Network.nw_parameters_create
import platform.Network.nw_parameters_create_secure_tcp
import platform.Network.nw_tls_copy_sec_protocol_options
import platform.Network.nw_txt_record_access_key
import platform.Network.nw_txt_record_find_key_non_empty_value
import platform.Network.nw_txt_record_t
import platform.Security.sec_protocol_options_set_verify_block
import platform.darwin.dispatch_data_apply
import platform.darwin.dispatch_data_create
import platform.darwin.dispatch_data_get_size
import platform.darwin.dispatch_data_t
import platform.darwin.dispatch_queue_create

private const val CAST_SERVICE_TYPE = "_googlecast._tcp"
private const val BONJOUR_DOMAIN = "local."

actual fun createCastController(scope: CoroutineScope): CastController {
    val bonjour = BonjourCast()
    return NetworkCastController(scope, bonjour::devices, bonjour::open)
}

/** Browses with nw_browser and connects straight to the service endpoint, so no separate host resolution. */
private class BonjourCast {
    // Device id → Bonjour instance name; only touched on the controller's confined dispatcher.
    private val serviceNames = mutableMapOf<String, String>()

    fun devices(): Flow<List<CastDevice>> = browseCastServices().map { found ->
        found.forEach { (device, service) -> serviceNames[device.id] = service }
        found.map { it.first }.sortedBy { it.name.lowercase() }
    }

    suspend fun open(device: CastDevice): CastTransport = openNetworkTransport(
        serviceNames[device.id]?.let { nw_endpoint_create_bonjour_service(it, CAST_SERVICE_TYPE, BONJOUR_DOMAIN) }
            ?: nw_endpoint_create_host(device.host, device.port.toString()),
    )
}

private fun browseCastServices(): Flow<List<Pair<CastDevice, String>>> = callbackFlow {
    val queue = dispatch_queue_create("eu.friedcutlet.yokan.cast.browse", null)
    val descriptor = nw_browse_descriptor_create_bonjour_service(CAST_SERVICE_TYPE, BONJOUR_DOMAIN)
    nw_browse_descriptor_set_include_txt_record(descriptor, true)
    val browser = nw_browser_create(descriptor, nw_parameters_create())
    val found = mutableMapOf<String, Pair<CastDevice, String>>() // only touched on `queue`
    nw_browser_set_browse_results_changed_handler(browser) { old, new, batchComplete ->
        old?.let(::serviceName)?.let { found.remove(it) }
        new?.let { result -> serviceName(result)?.let { name -> found[name] = castDevice(result, name) to name } }
        if (batchComplete) trySend(found.values.toList())
    }
    nw_browser_set_state_changed_handler(browser) { state, error ->
        when (state) {
            // Typically the Local Network permission was denied.
            nw_browser_state_waiting -> AppLogger.warn("Cast: Bonjour browsing waiting (error ${nw_error_get_error_code(error)})")
            nw_browser_state_failed -> close(IllegalStateException("Bonjour browsing failed (error ${nw_error_get_error_code(error)})"))
            else -> Unit
        }
    }
    nw_browser_set_queue(browser, queue)
    nw_browser_start(browser)
    awaitClose { nw_browser_cancel(browser) }
}

private fun serviceName(result: nw_browse_result_t): String? =
    nw_endpoint_get_bonjour_service_name(nw_browse_result_copy_endpoint(result))?.toKString()

private fun castDevice(result: nw_browse_result_t, serviceName: String): CastDevice {
    val txt = nw_browse_result_copy_txt_record_object(result)
    return CastDevice(id = txtValue(txt, "id") ?: serviceName, name = txtValue(txt, "fn") ?: serviceName)
}

private fun txtValue(txt: nw_txt_record_t, key: String): String? {
    if (txt == null) return null
    var value: String? = null
    nw_txt_record_access_key(txt, key) { _, found, bytes, length ->
        if (found == nw_txt_record_find_key_non_empty_value && bytes != null) {
            value = bytes.readBytes(length.toInt()).decodeToString()
        }
        true
    }
    return value
}

private suspend fun openNetworkTransport(endpoint: nw_endpoint_t): CastTransport {
    val queue = dispatch_queue_create("eu.friedcutlet.yokan.cast.connection", null)
    val parameters = nw_parameters_create_secure_tcp(
        { tls ->
            // Receivers present a self-signed per-device certificate (authenticity is Google's separate device-auth
            // challenge, not implemented here), so the system trust evaluation always rejects it. Accept it for
            // this connection only.
            sec_protocol_options_set_verify_block(
                nw_tls_copy_sec_protocol_options(tls),
                { _, _, complete -> complete?.invoke(true) },
                queue,
            )
        },
        NW_PARAMETERS_DEFAULT_CONFIGURATION,
    )
    val connection = nw_connection_create(endpoint, parameters)
    val ready = CompletableDeferred<Unit>()
    nw_connection_set_state_changed_handler(connection) { state, error ->
        when (state) {
            nw_connection_state_ready -> ready.complete(Unit)
            nw_connection_state_waiting, nw_connection_state_failed, nw_connection_state_cancelled -> ready.completeExceptionally(
                IllegalStateException("Could not connect to the Cast device (error ${nw_error_get_error_code(error)})"),
            )
            else -> Unit
        }
    }
    nw_connection_set_queue(connection, queue)
    nw_connection_start(connection)
    try {
        withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) { ready.await() } ?: error("Timed out connecting to the Cast device")
    } catch (e: Throwable) {
        nw_connection_cancel(connection)
        throw e
    }
    return NetworkCastTransport(connection)
}

private class NetworkCastTransport(private val connection: nw_connection_t) : CastTransport {
    override suspend fun write(frame: ByteArray): Unit = suspendCancellableCoroutine { continuation ->
        // A null destructor (DISPATCH_DATA_DESTRUCTOR_DEFAULT) makes dispatch copy the pinned bytes.
        val data = frame.usePinned { dispatch_data_create(it.addressOf(0), frame.size.toULong(), null, null) }
        nw_connection_send(connection, data, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true) { error ->
            if (error == null) {
                continuation.resume(Unit)
            } else {
                continuation.resumeWithException(IllegalStateException("Cast send failed (error ${nw_error_get_error_code(error)})"))
            }
        }
    }

    override suspend fun read(): ByteArray = suspendCancellableCoroutine { continuation ->
        nw_connection_receive(connection, 1u, 65536u) { content, _, _, error ->
            val size = content?.let { dispatch_data_get_size(it) } ?: 0uL
            when {
                size > 0uL -> continuation.resume(bytesOf(content, size))
                error != null -> continuation.resumeWithException(
                    IllegalStateException("Cast receive failed (error ${nw_error_get_error_code(error)})"),
                )
                else -> continuation.resumeWithException(IllegalStateException("Cast device closed the connection"))
            }
        }
    }

    // Pending receive/send completions fire with an error after cancel.
    override fun close() = nw_connection_cancel(connection)
}

private fun bytesOf(data: dispatch_data_t, size: ULong): ByteArray {
    val out = ByteArray(size.toInt())
    dispatch_data_apply(data) { _, offset, buffer, length ->
        buffer?.readBytes(length.toInt())?.copyInto(out, offset.toInt())
        true
    }
    return out
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.jvmCommon.kt
### Write `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.jvmCommon.kt`

Create this path in your reconstruction project. Source set: **jvmCommonMain**. [Exact file download](../reference/source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.jvmCommon.kt).

The implementation below defines `createCastController`, `holdCastMulticastLock`, `discoverCastDevices`, `SocketCastTransport`, `write`, `read`, `close`, `openCastSocket`, `AcceptReceiverCertificate`, `checkClientTrusted` and 2 further declarations.

The source describes its contract as:

> Holds whatever the platform needs to receive multicast while discovering; returns the release action.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import java.io.EOFException
import java.net.DatagramPacket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.MulticastSocket
import java.net.SocketTimeoutException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
import kotlin.time.TimeSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext

actual fun createCastController(scope: CoroutineScope): CastController =
    NetworkCastController(scope, ::discoverCastDevices, ::openCastSocket)

/** Holds whatever the platform needs to receive multicast while discovering; returns the release action. */
internal expect fun holdCastMulticastLock(): () -> Unit

private val MDNS_GROUP: InetAddress = InetAddress.getByName("224.0.0.251")
private const val MDNS_PORT = 5353
private val QUERY_INTERVAL = 3.seconds
private val DEVICE_EXPIRY = 30.seconds

/**
 * Re-sends the `_googlecast._tcp` PTR query every 3s from an ephemeral port, so responders answer by unicast
 * (RFC 6762 §6.7 legacy queries) and port 5353 never has to be shared with the OS responder.
 * Devices not heard from for 30s are dropped.
 */
internal fun discoverCastDevices(): Flow<List<CastDevice>> = flow {
    val release = holdCastMulticastLock()
    try {
        MulticastSocket().use { socket ->
            socket.timeToLive = 255
            socket.soTimeout = 1000
            val query = castMdnsQuery()
            val buffer = ByteArray(9000)
            val packet = DatagramPacket(buffer, buffer.size)
            val seen = linkedMapOf<String, Pair<CastDevice, TimeMark>>()
            var lastQuery: TimeMark? = null
            while (true) {
                currentCoroutineContext().ensureActive()
                if (lastQuery == null || lastQuery.elapsedNow() >= QUERY_INTERVAL) {
                    socket.send(DatagramPacket(query, query.size, MDNS_GROUP, MDNS_PORT))
                    lastQuery = TimeSource.Monotonic.markNow()
                }
                try {
                    packet.setLength(buffer.size)
                    socket.receive(packet)
                    val now = TimeSource.Monotonic.markNow()
                    parseCastMdnsResponse(buffer.copyOf(packet.length), packet.address.hostAddress.orEmpty())
                        .forEach { seen[it.id] = it to now }
                } catch (_: SocketTimeoutException) {
                    // Wake up to re-query, expire devices and observe cancellation.
                }
                seen.values.removeAll { it.second.elapsedNow() > DEVICE_EXPIRY }
                emit(seen.values.map { it.first }.sortedBy { it.name.lowercase() })
            }
        }
    } finally {
        release()
    }
}.flowOn(Dispatchers.IO).distinctUntilChanged()

private class SocketCastTransport(private val socket: SSLSocket) : CastTransport {
    private val input = socket.inputStream
    private val output = socket.outputStream
    private val buffer = ByteArray(16 * 1024)

    override suspend fun write(frame: ByteArray) = withContext(Dispatchers.IO) {
        output.write(frame)
        output.flush()
    }

    // Blocking read; close() unblocks it with a SocketException.
    override suspend fun read(): ByteArray = withContext(Dispatchers.IO) {
        val count = input.read(buffer)
        if (count < 0) throw EOFException("Cast device closed the connection")
        buffer.copyOf(count)
    }

    override fun close() = socket.close()
}

private suspend fun openCastSocket(device: CastDevice): CastTransport = withContext(Dispatchers.IO) {
    val context = SSLContext.getInstance("TLS").apply { init(null, arrayOf<TrustManager>(AcceptReceiverCertificate), null) }
    // A plain SSLSocket performs no hostname verification (no endpoint identification algorithm is set),
    // which is required: receivers are addressed by LAN IP, not by a name on their certificate.
    val socket = context.socketFactory.createSocket() as SSLSocket
    try {
        socket.connect(InetSocketAddress(device.host, device.port), CAST_CONNECT_TIMEOUT_MS.toInt())
        socket.soTimeout = CAST_CONNECT_TIMEOUT_MS.toInt()
        socket.startHandshake()
        socket.soTimeout = 0
        SocketCastTransport(socket)
    } catch (e: Throwable) {
        socket.close()
        throw e
    }
}

/**
 * Chromecast receivers present a self-signed per-device TLS certificate (authenticity is proven separately by
 * Google's device-auth challenge, which this client does not implement), so platform trust stores always reject
 * it. Installed only on the Cast socket's own SSLContext; no other connection is affected.
 */
private object AcceptReceiverCertificate : X509TrustManager {
    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
    override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/cast/NetworkCastController.kt
### Write `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/cast/NetworkCastController.kt`

Create this path in your reconstruction project. Source set: **nonWebMain**. [Exact file download](../reference/source/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/cast/NetworkCastController.kt).

The implementation below defines `NetworkCastController`, `startDiscovery`, `stopDiscovery`, `connect`, `loadQueue`, `append`, `play`, `pause`, `seekTo`, `next` and 6 further declarations.

The source describes its contract as:

> Native CASTV2 sender shared by Android, desktop and iOS: platform code supplies only device discovery and the TLS byte stream. Android deliberately uses this instead of the proprietary Google Cast SDK, so there is no Play Services dependency and one code path to maintain.

Cross-chapter imports used by this file: [`AppLogger`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Native CASTV2 sender shared by Android, desktop and iOS: platform code supplies only device discovery and the
 * TLS byte stream. Android deliberately uses this instead of the proprietary Google Cast SDK, so there is no
 * Play Services dependency and one code path to maintain.
 */
@OptIn(ExperimentalCoroutinesApi::class)
internal class NetworkCastController(
    parentScope: CoroutineScope,
    private val discover: () -> Flow<List<CastDevice>>,
    private val openTransport: suspend (CastDevice) -> CastTransport,
) : CastController {
    // CastSession is single-threaded by contract; every session call is confined here.
    private val dispatcher = Dispatchers.Default.limitedParallelism(1)
    private val scope = CoroutineScope(parentScope.coroutineContext + SupervisorJob(parentScope.coroutineContext[Job]) + dispatcher)
    private val session = MutableStateFlow<CastSession?>(null)
    private val _devices = MutableStateFlow(emptyList<CastDevice>())
    private var discoveryJob: Job? = null

    override val isSupported: StateFlow<Boolean> = MutableStateFlow(true).asStateFlow()
    override val usesSystemPicker = false
    override val devices: StateFlow<List<CastDevice>> = _devices.asStateFlow()
    override val status: StateFlow<CastStatus?> =
        session.flatMapLatest { it?.status ?: flowOf(null) }.stateIn(scope, SharingStarted.Eagerly, null)

    override fun startDiscovery() {
        scope.launch {
            if (discoveryJob?.isActive == true) return@launch
            discoveryJob = scope.launch {
                discover()
                    .catch { AppLogger.warn("Cast discovery failed: ${it.message}") }
                    .collect { _devices.value = it }
            }
        }
    }

    override fun stopDiscovery() {
        scope.launch {
            discoveryJob?.cancel()
            discoveryJob = null
        }
    }

    override suspend fun connect(device: CastDevice?) = withContext(dispatcher) {
        requireNotNull(device) { "Choose a Cast device" }
        session.value?.disconnect()
        session.value = null
        val next = CastSession(device, openTransport(device), scope)
        next.connect()
        session.value = next
    }

    override suspend fun loadQueue(
        items: List<CastMedia>,
        startIndex: Int,
        startPositionMs: Long,
        style: CastTextStyle,
        activeSubtitleIndex: Int?,
    ) = withContext(dispatcher) {
        connected().loadQueue(items, startIndex, startPositionMs, style, activeSubtitleIndex)
    }

    override suspend fun append(items: List<CastMedia>) = withContext(dispatcher) { connected().append(items) }

    override fun play() = command { it.play() }
    override fun pause() = command { it.pause() }
    override fun seekTo(positionMs: Long) = command { it.seekTo(positionMs) }
    override fun next() = command { it.next() }
    override fun previous() = command { it.previous() }
    override fun jumpTo(index: Int) = command { it.jumpTo(index) }

    override suspend fun disconnect() = withContext(dispatcher) {
        session.value?.disconnect()
        session.value = null
    }

    override fun close() {
        session.value?.close()
        session.value = null
        scope.cancel()
    }

    private fun connected() = checkNotNull(session.value) { "No Cast session" }

    /** Commands run in call order on the confined dispatcher; failures already land in [CastStatus.error]. */
    private fun command(block: suspend (CastSession) -> Unit) {
        scope.launch {
            val current = session.value ?: return@launch
            try {
                block(current)
            } catch (e: CancellationException) {
                throw e
            } catch (e: Throwable) {
                AppLogger.warn("Cast command failed: ${e.message}")
            }
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.wasm.kt).

The implementation below defines `createCastController`, `WebCastController`, `startDiscovery`, `stopDiscovery`, `connect`, `loadQueue`, `append`, `play`, `pause`, `seekTo` and 16 further declarations.

The source describes its contract as:

> Chrome's own device picker and session handling; discovery is the browser's job, so \[devices\] stays empty and \[startDiscovery\]/\[stopDiscovery\] have nothing to drive.

```kotlin
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.services.media.cast

import kotlin.js.JsAny
import kotlin.js.Promise
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.await
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject

// The browser cannot open raw TLS sockets, so the web build casts through Chrome's Cast Web Sender SDK.
actual fun createCastController(scope: CoroutineScope): CastController = WebCastController()

/**
 * Chrome's own device picker and session handling; discovery is the browser's job, so [devices] stays empty and
 * [startDiscovery]/[stopDiscovery] have nothing to drive.
 */
private class WebCastController : CastController {
    private val _isSupported = MutableStateFlow(false)
    private val _status = MutableStateFlow<CastStatus?>(null)
    private var queue = emptyList<CastMedia>()
    private var style = CastTextStyle()
    private val bridge: JsAny = createCastBridge(
        onAvailable = { _isSupported.value = it },
        onChange = ::onSnapshot,
        onError = { message -> _status.update { it?.copy(buffering = false, error = message) } },
    )

    override val isSupported: StateFlow<Boolean> = _isSupported.asStateFlow()
    override val usesSystemPicker = true
    override val devices: StateFlow<List<CastDevice>> = MutableStateFlow(emptyList<CastDevice>()).asStateFlow()
    override val status: StateFlow<CastStatus?> = _status.asStateFlow()

    override fun startDiscovery() = Unit
    override fun stopDiscovery() = Unit

    // requestSession() opens Chrome's picker; it runs before the first suspension so the click's activation holds.
    override suspend fun connect(device: CastDevice?) {
        check(_isSupported.value) { "Casting is not available in this browser" }
        castRequestSession().await<JsAny?>()
    }

    override suspend fun loadQueue(
        items: List<CastMedia>,
        startIndex: Int,
        startPositionMs: Long,
        style: CastTextStyle,
        activeSubtitleIndex: Int?,
    ) {
        require(startIndex in items.indices) { "Start index $startIndex outside queue of ${items.size}" }
        queue = items
        this.style = style
        _status.update {
            it?.copy(queue = items, currentIndex = startIndex, positionMs = startPositionMs, durationMs = 0, finished = false, error = null)
        }
        val json = queueItemsJson(items, style, startIndex, startPositionMs, activeSubtitleIndex).toString()
        castQueueLoad(bridge, json, startIndex).await<JsAny?>()
    }

    override suspend fun append(items: List<CastMedia>) {
        if (items.isEmpty()) return
        castQueueInsert(bridge, queueItemsJson(items, style).toString()).await<JsAny?>()
        queue = queue + items
        _status.update { it?.copy(queue = queue, finished = false) }
    }

    override fun play() = castSetPlaying(bridge, true)
    override fun pause() = castSetPlaying(bridge, false)
    override fun seekTo(positionMs: Long) = castSeek(bridge, positionMs / 1000.0)
    override fun next() = castQueueStep(bridge, true)
    override fun previous() = castQueueStep(bridge, false)
    override fun jumpTo(index: Int) = castQueueJump(bridge, index)

    override suspend fun disconnect() {
        castEndSession()
        _status.value = null
    }

    override fun close() {
        disposeCastBridge(bridge)
        _status.value = null
    }

    /** [json] is `{id,name,media}` with `media` shaped like a MEDIA_STATUS entry, or empty when no session. */
    private fun onSnapshot(json: String) {
        if (json.isEmpty()) {
            _status.value = null
            return
        }
        val snapshot = Json.parseToJsonElement(json) as? JsonObject ?: return
        val device = CastDevice(id = snapshot.string("id").orEmpty(), name = snapshot.string("name").orEmpty())
        val entry = snapshot["media"] as? JsonObject
        val itemIds = (entry?.get("items") as? JsonArray)?.mapNotNull { (it as? JsonObject)?.int("itemId") }.orEmpty()
        val previous = _status.value?.takeIf { it.device == device } ?: CastStatus(device)
        _status.value = previous.copy(queue = queue).withMediaStatus(entry, itemIds)
    }
}

private fun createCastBridge(onAvailable: (Boolean) -> Unit, onChange: (String) -> Unit, onError: (String) -> Unit): JsAny = js("""
    (() => {
        const g = globalThis;
        const bridge = { disposed: false, dispose: () => { bridge.disposed = true; } };
        bridge.fail = (prefix) => (e) => onError(prefix + ': ' + ((e && (e.description || e.code || e.message)) || 'unknown error'));
        bridge.toItems = (json) => JSON.parse(json).map((item) => {
            const m = item.media;
            const info = Object.assign(new chrome.cast.media.MediaInfo(m.contentId, m.contentType), m);
            info.metadata = Object.assign(new chrome.cast.media.GenericMediaMetadata(), m.metadata);
            info.metadata.images = (m.metadata.images || []).map((image) => new chrome.cast.Image(image.url));
            info.tracks = (m.tracks || []).map((t) => Object.assign(new chrome.cast.media.Track(t.trackId, t.type), t));
            info.textTrackStyle = Object.assign(new chrome.cast.media.TextTrackStyle(), m.textTrackStyle);
            return Object.assign(new chrome.cast.media.QueueItem(info), item, { media: info });
        });
        const attach = () => {
            if (bridge.disposed) return;
            const context = cast.framework.CastContext.getInstance();
            context.setOptions({
                receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,
                autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,
            });
            const player = new cast.framework.RemotePlayer();
            const controller = new cast.framework.RemotePlayerController(player);
            const emit = () => {
                const session = context.getCurrentSession();
                if (!session) { onChange(''); return; }
                const device = session.getCastDevice() || {};
                const media = session.getMediaSession();
                onChange(JSON.stringify({
                    id: device.deviceId || '',
                    name: device.friendlyName || '',
                    media: media ? {
                        playerState: media.playerState,
                        idleReason: media.idleReason,
                        currentTime: player.isMediaLoaded ? player.currentTime : media.getEstimatedTime(),
                        media: { duration: player.duration || (media.media && media.media.duration) || null },
                        currentItemId: media.currentItemId,
                        items: (media.items || []).map((i) => ({ itemId: i.itemId })),
                    } : null,
                }));
            };
            const playerEvent = cast.framework.RemotePlayerEventType.ANY_CHANGE;
            const sessionEvent = cast.framework.CastContextEventType.SESSION_STATE_CHANGED;
            controller.addEventListener(playerEvent, emit);
            context.addEventListener(sessionEvent, emit);
            Object.assign(bridge, { player, controller });
            bridge.dispose = () => {
                bridge.disposed = true;
                controller.removeEventListener(playerEvent, emit);
                context.removeEventListener(sessionEvent, emit);
            };
            onAvailable(true);
            emit();
        };
        const settle = (available) => available ? attach() : onAvailable(false);
        if (g.__yokanCastAvailable !== undefined) { settle(g.__yokanCastAvailable); return bridge; }
        (g.__yokanCastWaiters = g.__yokanCastWaiters || []).push(settle);
        if (!g.__yokanCastScript) {
            g.__yokanCastScript = true;
            const done = (available) => {
                g.__yokanCastAvailable = !!(available && g.cast && g.cast.framework);
                g.__yokanCastWaiters.splice(0).forEach((waiter) => waiter(g.__yokanCastAvailable));
            };
            g.__onGCastApiAvailable = done;
            const script = document.createElement('script');
            script.src = 'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1';
            script.async = true;
            script.onerror = () => done(false);
            document.head.appendChild(script);
        }
        return bridge;
    })()
""")

private fun disposeCastBridge(bridge: JsAny): Unit = js("bridge.dispose()")

private fun castRequestSession(): Promise<JsAny?> = js("""
    cast.framework.CastContext.getInstance().requestSession().then(
        () => null,
        (code) => { throw new Error('Cast session request failed: ' + code); }
    )
""")

private fun castEndSession(): Unit = js("""{
    const context = globalThis.cast && cast.framework && cast.framework.CastContext.getInstance();
    if (context && context.getCurrentSession()) context.endCurrentSession(true);
}""")

private fun castQueueLoad(bridge: JsAny, items: String, startIndex: Int): Promise<JsAny?> = js("""
    new Promise((resolve, reject) => {
        const session = cast.framework.CastContext.getInstance().getCurrentSession();
        if (!session) { reject(new Error('No Cast session')); return; }
        const request = new chrome.cast.media.QueueLoadRequest(bridge.toItems(items));
        request.startIndex = startIndex;
        request.repeatMode = chrome.cast.media.RepeatMode.OFF;
        session.getSessionObj().queueLoad(request, () => resolve(null), (e) => {
            reject(new Error('Cast load failed: ' + ((e && (e.description || e.code)) || 'unknown error')));
        });
    })
""")

private fun castQueueInsert(bridge: JsAny, items: String): Promise<JsAny?> = js("""
    new Promise((resolve, reject) => {
        const session = cast.framework.CastContext.getInstance().getCurrentSession();
        const media = session && session.getMediaSession();
        if (!media) { reject(new Error('No media loaded on the Cast device')); return; }
        media.queueInsertItems(new chrome.cast.media.QueueInsertItemsRequest(bridge.toItems(items)), () => resolve(null), (e) => {
            reject(new Error('Cast queue insert failed: ' + ((e && (e.description || e.code)) || 'unknown error')));
        });
    })
""")

private fun castSetPlaying(bridge: JsAny, playing: Boolean): Unit = js("""{
    const player = bridge.player;
    if (player && player.isMediaLoaded && player.isPaused === playing) bridge.controller.playOrPause();
}""")

private fun castSeek(bridge: JsAny, seconds: Double): Unit = js("""{
    const player = bridge.player;
    if (player && player.isMediaLoaded && player.canSeek) {
        player.currentTime = seconds;
        bridge.controller.seek();
    }
}""")

private fun castQueueStep(bridge: JsAny, forward: Boolean): Unit = js("""{
    const session = globalThis.cast && cast.framework.CastContext.getInstance().getCurrentSession();
    const media = session && session.getMediaSession();
    if (!media) return;
    if (forward) media.queueNext(() => {}, bridge.fail('Cast next failed'));
    else media.queuePrev(() => {}, bridge.fail('Cast previous failed'));
}""")

private fun castQueueJump(bridge: JsAny, index: Int): Unit = js("""{
    const session = globalThis.cast && cast.framework.CastContext.getInstance().getCurrentSession();
    const media = session && session.getMediaSession();
    const item = media && media.items && media.items[index];
    if (item) media.queueJumpToItem(item.itemId, () => {}, bridge.fail('Cast jump failed'));
}""")
```
[chapter-file-end]: #

### Check your understanding

Start casting episode A, switch local selection to B and stop casting. A's receiver position must not be written as B's local resume point.
[chapter-content-end]: #


## Step 6: implement torrent playback

Implement TorrServer client, magnet/torrent normalization, stream expansion and platform host management. Resolve selected torrent entries to ordinary stream URLs with metadata/headers, then use the same playback/download pipeline. Preserve per-profile host state and process cleanup. Configure remote servers and unsupported local-host modes through capability checks.

[chapter-content-start]: #
### Follow the code

Torrent normalization selects a magnet/torrent and file entry, then turns it into an ordinary playable stream URL with metadata/headers. The player should not need a second torrent-specific time/progress model. Platform management owns a supervised server process where supported; remote-server configuration uses the same client contract. Keep server/profile lifetime separate from one selected stream.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerClient.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreams.kt`
- `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.android.kt`
- `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.desktop.kt`
- `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.ios.kt`
- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.wasm.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerClient.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerClient.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerClient.kt).

The implementation below defines `TorrServerTorrent`, `TorrServerFile`, `TorrServerException`, `TorrServerClient`, `echo`, `add`, `get`, `list`, `remove`, `upload` and 6 further declarations.

The source describes its contract as:

> TorrServer file ids start at 1 and are the `index` of stream URLs.

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.encodeURLParameter
import io.ktor.http.encodeURLPathPart
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put
import kotlin.io.encoding.Base64
import kotlin.random.Random

@Serializable
data class TorrServerTorrent(
    val title: String = "",
    val hash: String = "",
    @SerialName("stat_string") val state: String = "",
    @SerialName("torrent_size") val size: Long = 0,
    @SerialName("file_stats") val files: List<TorrServerFile> = emptyList(),
)

/** TorrServer file ids start at 1 and are the `index` of stream URLs. */
@Serializable
data class TorrServerFile(val id: Int, val path: String, val length: Long = 0) {
    val name: String get() = path.substringAfterLast('/')
}

class TorrServerException(val status: Int, message: String) : IllegalStateException(message)

/** TorrServer's HTTP API (github.com/YouROK/TorrServer `server/web/api`). */
class TorrServerClient(
    private val http: HttpService,
    baseUrl: String,
    username: String = "",
    password: String = "",
) {
    val baseUrl = baseUrl.trim().trimEnd('/')
    private val auth = if (username.isEmpty()) emptyMap()
    else mapOf("Authorization" to "Basic " + Base64.encode("$username:$password".encodeToByteArray()))

    /** Health check; TorrServer answers its version. */
    suspend fun echo(): String = call("GET", "/echo").trim()

    suspend fun add(link: String, title: String): TorrServerTorrent = torrent("add") { put("link", link); put("title", title) }

    suspend fun get(hash: String): TorrServerTorrent = torrent("get") { put("hash", hash) }

    suspend fun list(): List<TorrServerTorrent> =
        json.decodeFromString(call("POST", "/torrents", json = buildJsonObject { put("action", "list") }))

    suspend fun remove(hash: String) {
        call("POST", "/torrents", json = buildJsonObject { put("action", "rem"); put("hash", hash) })
    }

    /** Adds a local `.torrent` file the server cannot read itself. */
    suspend fun upload(torrent: ByteArray, fileName: String, title: String): TorrServerTorrent {
        val boundary = "yokan" + Random.nextLong().toULong().toString(16)
        fun part(name: String, extra: String = "") = "--$boundary\r\nContent-Disposition: form-data; name=\"$name\"$extra\r\n"
        val body = (part("title") + "\r\n$title\r\n" +
            part("file", "; filename=\"${fileName.replace("\"", "")}\"") + "Content-Type: application/x-bittorrent\r\n\r\n").encodeToByteArray() +
            torrent + "\r\n--$boundary--\r\n".encodeToByteArray()
        return json.decodeFromString(call("POST", "/torrent/upload", body, "multipart/form-data; boundary=$boundary"))
    }

    /** Full `BTSets`; `set` replaces every field, so callers modify this object rather than build a partial one. */
    suspend fun settings(): JsonObject =
        json.parseToJsonElement(call("POST", "/settings", json = buildJsonObject { put("action", "get") })).jsonObject

    suspend fun setSettings(sets: JsonObject) {
        call("POST", "/settings", json = JsonObject(mapOf("action" to JsonPrimitive("set"), "sets" to sets)))
    }

    /** `play` URLs stream with Range support and need no credentials (TorrServer `streamNoAuth`). */
    fun streamUrl(hash: String, file: TorrServerFile): String =
        "$baseUrl/stream/${file.name.encodeURLPathPart()}?link=${hash.encodeURLParameter()}&index=${file.id}&play"

    private suspend fun torrent(action: String, fields: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): TorrServerTorrent =
        json.decodeFromJsonElement(json.parseToJsonElement(call("POST", "/torrents", json = buildJsonObject { put("action", action); fields() })))

    private suspend fun call(method: String, path: String, bytes: ByteArray? = null, contentType: String? = null, json: JsonObject? = null): String {
        val type = contentType ?: if (json != null) "application/json" else null
        val response = http.request(HttpRequest(
            url = baseUrl + path,
            method = method,
            headers = auth + listOfNotNull(type?.let { "Content-Type" to it }),
            body = json?.toString(),
            bodyBytes = bytes,
        ))
        val text = response.bodyBytes.decodeToString()
        if (response.statusCode !in 200..299) {
            val detail = runCatching { Json.parseToJsonElement(text).jsonObject["error"]?.toString()?.trim('"') }.getOrNull() ?: text.take(200)
            throw TorrServerException(response.statusCode, "TorrServer $path failed (HTTP ${response.statusCode})${detail.takeIf(String::isNotBlank)?.let { ": $it" }.orEmpty()}")
        }
        return text
    }

    private companion object {
        val json = Json { ignoreUnknownKeys = true }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreams.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreams.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreams.kt).

The implementation below defines `TorrServerLaunch`, `TorrServerHost`, `executable`, `install`, `ensureRunning`, `stop`, `createPlatformTorrServerHost`, `TorrentStreams`, `prefs`, `client` and 7 further declarations.

The source describes its contract as:

> Launch options of a TorrServer process Yokan supervises.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`DbTorrentPreferences`](../chapters/02-domain-and-settings-models.md), [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`YokanDatabase`](../chapters/03-persistence-and-migrations.md), [`LocalFileService`](../chapters/12-local-library.md), [`TorrentUtils`](../chapters/09-repository-and-library.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbTorrentPreferences
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.TorrServerMode
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.library.TorrentUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

/** Launch options of a TorrServer process Yokan supervises. */
data class TorrServerLaunch(val port: Int, val executablePath: String, val proxyMode: String?, val proxyUrl: String)

/** A TorrServer process owned by this profile; only platforms that can spawn one provide it. */
interface TorrServerHost {
    val status: StateFlow<String>
    /** Installed or user-provided executable, or null when neither exists yet. */
    fun executable(userPath: String): String?
    /** Downloads the pinned official release after SHA-256 verification; returns its path. */
    suspend fun install(onProgress: (downloaded: Long, total: Long) -> Unit): String
    /** Starts, or restarts after a crash or option change, and returns the server's base URL once healthy. */
    suspend fun ensureRunning(launch: TorrServerLaunch): String
    suspend fun stop()
}

/** Desktop supervises a subprocess; Android, iOS and the browser have no host and use a remote server. */
expect fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost?

/** Turns magnet/`.torrent` references into TorrServer stream URLs for playback, casting and downloads. */
class TorrentStreams(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val files: LocalFileService,
    val host: TorrServerHost?,
    private val pollMillis: Long = 1_000,
    private val metadataTimeoutMillis: Long = 90_000,
) {
    private val lock = Mutex()
    /** Server URL and tracker list last pushed; the server persists its settings itself. */
    private var pushed: Pair<String, String>? = null

    private fun prefs(): DbTorrentPreferences = database.settings().features.torrent

    /** Client for the configured server, starting or recovering the managed process first. Hostless platforms are remote-only. */
    suspend fun client(): TorrServerClient = lock.withLock {
        val prefs = prefs()
        check(prefs.enabled) { "Torrent streaming is off. Enable TorrServer in Settings → Player → Torrent streaming." }
        val host = host
        val client = if (prefs.mode == TorrServerMode.Managed && host != null) {
            TorrServerClient(http, host.ensureRunning(prefs.launch()))
        } else {
            host?.stop()
            check(prefs.remoteUrl.startsWith("http://", true) || prefs.remoteUrl.startsWith("https://", true)) { "Set the remote TorrServer URL (http://host:8090) in Settings → Player → Torrent streaming." }
            TorrServerClient(http, prefs.remoteUrl, prefs.username, prefs.password)
        }
        if (pushed != client.baseUrl to prefs.trackers) {
            pushTrackers(client, prefs.trackers)
            pushed = client.baseUrl to prefs.trackers
        }
        client
    }

    /** Re-pushes the tracker list, e.g. after a reset, and returns the server version. */
    suspend fun applySettings(): String {
        lock.withLock { pushed = null }
        return client().echo()
    }

    suspend fun stop() = lock.withLock {
        pushed = null
        host?.stop()
    }

    /** Playable files of [link]; multi-file torrents list each video file (Animetail's `index=` picks one). */
    suspend fun videos(link: String, title: String): List<DbVideo> {
        val client = client()
        val added = if (isRemoteLink(link)) client.add(link, title) else {
            files.prepare()
            client.upload(files.readBytesAsync(link, MaxTorrentFileBytes), link.substringAfterLast('/'), title)
        }
        val torrent = if (added.files.isNotEmpty()) added else awaitFiles(client, added.hash)
        val wanted = TorrentUtils.fileIndex(link)
        val playable = torrent.files.filter { it.id == wanted }
            .ifEmpty { torrent.files.filter { it.name.substringAfterLast('.', "").lowercase() in VideoExtensions } }
            .ifEmpty { torrent.files }
        return playable.map { DbVideo(url = client.streamUrl(torrent.hash, it), quality = it.name, originalUrl = link) }
    }

    /** Replaces torrent entries of an extension's video list; without the engine they are dropped. */
    suspend fun expand(videos: List<DbVideo>, title: String): List<DbVideo> {
        if (videos.none { TorrentUtils.isTorrentLink(it.url) }) return videos
        if (!prefs().enabled) {
            return videos.filterNot { TorrentUtils.isTorrentLink(it.url) }
                .ifEmpty { error("This source only offers torrents. Enable TorrServer in Settings → Player → Torrent streaming.") }
        }
        return videos.flatMap { video ->
            if (!TorrentUtils.isTorrentLink(video.url)) listOf(video)
            else videos(video.url, title).map { file ->
                file.copy(quality = if (video.quality.isBlank()) file.quality else "${video.quality} · ${file.quality}", subtitles = video.subtitles, audios = video.audios)
            }
        }
    }

    private suspend fun awaitFiles(client: TorrServerClient, hash: String): TorrServerTorrent =
        withTimeoutOrNull(metadataTimeoutMillis) {
            var torrent = client.get(hash)
            while (torrent.files.isEmpty()) {
                delay(pollMillis)
                torrent = client.get(hash)
            }
            torrent
        } ?: error("TorrServer found no metadata for this torrent in ${metadataTimeoutMillis / 1000} s (no peers?).")

    private suspend fun pushTrackers(client: TorrServerClient, trackers: String) {
        val sets = client.settings()
        check("DefaultTrackers" in sets) { "This TorrServer does not support tracker lists; update it to a current MatriX release." }
        val list = trackers.lines().map(String::trim).filter(String::isNotEmpty).joinToString("\n")
        // RetrackersMode 1 adds the list to every torrent's own trackers.
        client.setSettings(JsonObject(sets + mapOf("DefaultTrackers" to JsonPrimitive(list), "RetrackersMode" to JsonPrimitive(1))))
    }

    private fun isRemoteLink(link: String) =
        link.startsWith("magnet:", true) || link.startsWith("http://", true) || link.startsWith("https://", true)

    private companion object {
        const val MaxTorrentFileBytes = 16L * 1024 * 1024
        val VideoExtensions = setOf("mkv", "mp4", "m4v", "avi", "webm", "mov", "ts", "m2ts", "wmv", "flv", "ogv", "mpg", "mpeg")
    }
}

fun DbTorrentPreferences.launch() = TorrServerLaunch(port, executablePath, proxyMode.flag?.takeIf { proxyUrl.isNotBlank() }, proxyUrl)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.android.kt
### Write `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.android.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.android.kt).

The implementation below defines `createPlatformTorrServerHost`.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.domain.ProfileId

// Not bundled: the official arm64 binary alone is ~64 MB and Android 10+ (W^X) refuses to exec
// app-writable files, so Android uses a remote TorrServer (e.g. the TorrServer app on 127.0.0.1:8090).
actual fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost? = null
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.desktop.kt
### Write `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.desktop.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.desktop.kt).

The implementation below defines `TorrServerAsset`, `currentTorrServerAsset`, `createPlatformTorrServerHost`, `DesktopTorrServerHost`, `executable`, `install`, `ensureRunning`, `stop`, `startLocked`, `onExit` and 5 further declarations.

The source describes its contract as:

> Official release pinned with its SHA-256 digests (github.com/YouROK/TorrServer, GPL-3.0, not bundled).

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`ProfileStorageNamespace`](../chapters/04-profiles-and-lifetimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import java.io.File
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.time.Duration
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

/** Official release pinned with its SHA-256 digests (github.com/YouROK/TorrServer, GPL-3.0, not bundled). */
internal const val TorrServerVersion = "MatriX.147"

internal data class TorrServerAsset(val name: String, val sha256: String)

// ponytail: pinned release; bump version + digests from the GitHub release `digest` fields when updating.
private val TorrServerAssets = mapOf(
    "darwin-arm64" to TorrServerAsset("TorrServer-darwin-arm64", "3e13a04e5e9e9bee044b15829fa13769c7c385bc71e8227f010434e1038ef172"),
    "darwin-amd64" to TorrServerAsset("TorrServer-darwin-amd64", "5cf02d76b6037a6a0f0cf8bafda0a9dbe34fb10149aed998f422cb26f7225608"),
    "linux-amd64" to TorrServerAsset("TorrServer-linux-amd64", "2f20fcb1fcacc9b61b7ca4bb6d5b7933547bd7f447b5cc77a84406faa9e6a4e8"),
    "linux-arm64" to TorrServerAsset("TorrServer-linux-arm64", "fbe0f668a2a22801db891afb52e1b96e4ec762dcbf979bec2a45917848456a1c"),
    "windows-amd64" to TorrServerAsset("TorrServer-windows-amd64.exe", "2a67f19266f111f00828857e7e37c233a509c0def4f6254fd564a1761f35b47d"),
)

internal fun currentTorrServerAsset(): TorrServerAsset? {
    val os = System.getProperty("os.name").lowercase().let {
        when { "mac" in it || "darwin" in it -> "darwin"; "win" in it -> "windows"; "linux" in it -> "linux"; else -> return null }
    }
    val arch = when (System.getProperty("os.arch").lowercase()) { "aarch64", "arm64" -> "arm64"; "x86_64", "amd64" -> "amd64"; else -> return null }
    return TorrServerAssets["$os-$arch"]
}

/** Per-profile state lives under the profile's owned root, so profile deletion removes it. */
actual fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost? = DesktopTorrServerHost(
    dataDir = File(ProfileStorageNamespace(profileId).ownedRoot(desktopDataRoot.path), "torrserver"),
    installRoot = File(desktopDataRoot, "torrserver-bin"),
)

/**
 * Supervises one TorrServer subprocess: health-checked start, automatic restart after a crash,
 * orphan cleanup after a Yokan crash (pid file + start instant), and a JVM shutdown hook.
 */
internal class DesktopTorrServerHost(
    private val dataDir: File,
    private val installRoot: File,
    private val asset: TorrServerAsset? = currentTorrServerAsset(),
    private val downloadBase: String = "https://github.com/YouROK/TorrServer/releases/download/$TorrServerVersion",
    private val startTimeoutMillis: Long = 20_000,
    private val maxRestarts: Int = 3,
) : TorrServerHost {
    private val lock = Mutex()
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).followRedirects(HttpClient.Redirect.NORMAL).build()
    private val _status = MutableStateFlow("Stopped")
    override val status: StateFlow<String> = _status
    private var process: Process? = null
    private var active: TorrServerLaunch? = null
    private var restarts = 0
    private val shutdownHook = Thread { process?.destroyForcibly() }
    private val pidFile get() = File(dataDir, "torrserver.pid")
    internal val logFile get() = File(dataDir, "torrserver.log")
    internal val pid: Long? get() = process?.takeIf { it.isAlive }?.pid()

    override fun executable(userPath: String): String? =
        if (userPath.isNotBlank()) userPath.takeIf { File(it).isFile }
        else asset?.let { File(installRoot, "$TorrServerVersion/${it.name}") }?.takeIf(File::isFile)?.path

    override suspend fun install(onProgress: (Long, Long) -> Unit): String = withContext(Dispatchers.IO) {
        val asset = checkNotNull(asset) { "TorrServer publishes no build for ${System.getProperty("os.name")} ${System.getProperty("os.arch")}; set a binary path or use a remote server." }
        val target = File(installRoot, "$TorrServerVersion/${asset.name}")
        if (target.isFile && sha256(target) == asset.sha256) return@withContext target.path
        target.parentFile.mkdirs()
        val part = File(target.parentFile, "${asset.name}.part")
        try {
            val response = runInterruptible {
                http.send(HttpRequest.newBuilder(URI.create("$downloadBase/${asset.name}")).header("User-Agent", "Yokan").build(), HttpResponse.BodyHandlers.ofInputStream())
            }
            response.body().use { input ->
                check(response.statusCode() in 200..299) { "TorrServer download failed with HTTP ${response.statusCode()}" }
                val total = response.headers().firstValueAsLong("content-length").orElse(-1)
                part.outputStream().use { output ->
                    val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                    var done = 0L
                    while (true) {
                        val read = input.read(buffer).takeIf { it >= 0 } ?: break
                        output.write(buffer, 0, read)
                        done += read
                        onProgress(done, total)
                    }
                }
            }
            val actual = sha256(part)
            check(actual == asset.sha256) { "TorrServer SHA-256 mismatch: expected ${asset.sha256}, got $actual" }
            part.setExecutable(true, true)
            Files.move(part.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
            target.path
        } finally {
            part.delete()
        }
    }

    override suspend fun ensureRunning(launch: TorrServerLaunch): String = lock.withLock {
        val url = "http://127.0.0.1:${launch.port}"
        restarts = 0
        if (process?.isAlive == true && active == launch && healthy(url)) return@withLock url
        stopLocked()
        startLocked(launch)
        url
    }

    override suspend fun stop() = lock.withLock { stopLocked() }

    private suspend fun startLocked(launch: TorrServerLaunch): Unit = withContext(Dispatchers.IO) {
        val url = "http://127.0.0.1:${launch.port}"
        val exe = executable(launch.executablePath)
            ?: error(if (launch.executablePath.isBlank()) "Download TorrServer or set its binary path first." else "TorrServer binary not found: ${launch.executablePath}")
        dataDir.mkdirs()
        killOrphan()
        if (healthy(url)) fail("Port ${launch.port} is already used by another server; change the port or use it as a remote TorrServer.")
        _status.value = "Starting on port ${launch.port}"
        val command = listOf(exe, "--port", launch.port.toString(), "--path", dataDir.absolutePath) +
            (launch.proxyMode?.let { listOf("--proxyurl", launch.proxyUrl, "--proxymode", it) } ?: emptyList())
        val started = runCatching {
            ProcessBuilder(command).directory(dataDir).redirectErrorStream(true)
                .redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)).start()
        }.getOrElse { fail("Cannot launch TorrServer ($exe): ${it.message}") }
        process = started
        active = launch
        pidFile.writeText("${started.pid()} ${started.info().startInstant().map { it.toEpochMilli() }.orElse(0)}")
        runCatching { Runtime.getRuntime().addShutdownHook(shutdownHook) }
        val deadline = System.currentTimeMillis() + startTimeoutMillis
        while (!healthy(url)) {
            if (!started.isAlive) {
                process = null
                fail("TorrServer exited with code ${started.exitValue()}: ${logFile.readLines().takeLast(3).joinToString(" ")}")
            }
            if (System.currentTimeMillis() > deadline) {
                started.destroyForcibly()
                process = null
                fail("TorrServer did not answer on port ${launch.port} within ${startTimeoutMillis / 1000} s")
            }
            delay(200)
        }
        _status.value = "Running on port ${launch.port} (pid ${started.pid()})"
        started.onExit().thenRun { scope.launch { onExit(started, launch) } }
    }

    /** Unexpected exits restart with backoff; [maxRestarts] consecutive crashes leave it stopped until next use. */
    private suspend fun onExit(exited: Process, launch: TorrServerLaunch): Unit = lock.withLock {
        if (process !== exited) return@withLock
        process = null
        if (restarts >= maxRestarts) {
            _status.value = "Crashed (exit ${exited.exitValue()}); restarts on next use"
            return@withLock
        }
        restarts++
        _status.value = "Crashed (exit ${exited.exitValue()}); restarting ($restarts/$maxRestarts)"
        delay(500L shl restarts)
        catchingNonCancellation { startLocked(launch) }
    }

    private suspend fun stopLocked() = withContext(Dispatchers.IO) {
        val current = process
        process = null
        active = null
        if (current != null) {
            current.destroy()
            if (!current.waitFor(5, TimeUnit.SECONDS)) current.destroyForcibly().waitFor(5, TimeUnit.SECONDS)
        }
        killOrphan()
        runCatching { Runtime.getRuntime().removeShutdownHook(shutdownHook) }
        _status.value = "Stopped"
    }

    /** A server left behind by a crashed Yokan still holds the port and its database. */
    private fun killOrphan() {
        val (pid, started) = pidFile.takeIf(File::isFile)?.readText()?.split(' ')?.mapNotNull(String::toLongOrNull)
            ?.takeIf { it.size == 2 } ?: return
        ProcessHandle.of(pid).filter { handle -> handle.info().startInstant().map { it.toEpochMilli() }.orElse(-1) == started }
            .ifPresent { handle ->
                handle.destroy()
                runCatching { handle.onExit().get(5, TimeUnit.SECONDS) }.onFailure {
                    handle.destroyForcibly()
                    runCatching { handle.onExit().get(5, TimeUnit.SECONDS) }
                }
            }
        pidFile.delete()
    }

    private fun healthy(url: String): Boolean = runCatching {
        http.send(HttpRequest.newBuilder(URI.create("$url/echo")).timeout(Duration.ofSeconds(2)).build(), HttpResponse.BodyHandlers.discarding())
            .statusCode() == 200
    }.getOrDefault(false)

    private fun fail(message: String): Nothing {
        _status.value = message
        error(message)
    }

    private fun sha256(file: File): String {
        val digest = MessageDigest.getInstance("SHA-256")
        file.inputStream().use { input ->
            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
            while (true) digest.update(buffer, 0, input.read(buffer).takeIf { it >= 0 } ?: break)
        }
        return digest.digest().toHexString()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.ios.kt
### Write `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.ios.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.ios.kt).

The implementation below defines `createPlatformTorrServerHost`.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.domain.ProfileId

// iOS forbids spawning processes; TorrServerKit.xcframework (~75 MB, GPL-3.0) is not embedded, so iOS uses a remote server.
actual fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost? = null
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.wasm.kt
### Write `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.wasm.kt`

Create this path in your reconstruction project. Source set: **wasmJsMain**. [Exact file download](../reference/source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.wasm.kt).

The implementation below defines `createPlatformTorrServerHost`.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.domain.ProfileId

// Browsers cannot spawn processes or accept BitTorrent peers; the web app uses a remote TorrServer (it sends CORS headers).
actual fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost? = null
```
[chapter-file-end]: #

### Check your understanding

Select two entries from the same torrent, then close playback and retire the profile. Verify correct file selection and appropriate server/process cleanup.
[chapter-content-end]: #


[chapter-content-start]: #
## Recreate the tests and verify the chapter

Recreate fake-controller preparation/resume/command, player retirement/surface/position, extractor, Cast and torrent fixtures. Run deterministic common/JVM tests before native media smoke tests. Then test real mpv/compatibility, PiP, Cast and external-player behavior on capable devices; unsupported backends must expose unavailable commands honestly.

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.

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdnsTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdnsTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdnsTest.kt).

The implementation below defines `CastMdnsTest`, `DnsBuilder`, `u8`, `u16`, `strings`, `pointer`, `record`, `bytes`, `castResponse`, `parsesCompressedCastResponse` and 2 further declarations.

The source describes its contract as:

> Writes TYPE, CLASS IN, TTL 120 and RDATA with its length patched in afterwards.

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

- `parsesCompressedCastResponse`
- `missingAdditionalsFallBackToInstanceNameAndSourceAddress`
- `truncatedAndMalformedPacketsAreRejected`

```kotlin
package eu.friedcutlet.yokan.services.media.cast

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

class CastMdnsTest {
    private class DnsBuilder {
        private val out = mutableListOf<Byte>()
        val offset get() = out.size

        fun u8(value: Int) = apply { out += value.toByte() }
        fun u16(value: Int) = u8(value ushr 8).u8(value and 0xFF)
        fun strings(vararg values: String) = apply {
            values.forEach { value -> value.encodeToByteArray().let { u8(it.size); out += it.toList() } }
        }
        fun pointer(offset: Int) = u16(0xC000 or offset)

        /** Writes TYPE, CLASS IN, TTL 120 and RDATA with its length patched in afterwards. */
        fun record(type: Int, rdata: DnsBuilder.() -> Unit) = apply {
            u16(type).u16(1).u16(0).u16(120)
            val lengthAt = offset
            u16(0)
            rdata()
            val length = offset - lengthAt - 2
            out[lengthAt] = (length ushr 8).toByte()
            out[lengthAt + 1] = length.toByte()
        }

        fun bytes() = out.toByteArray()
    }

    /** PTR answer plus SRV/TXT/A additionals, all owner and target names compressed against earlier names. */
    private fun castResponse(): ByteArray {
        val packet = DnsBuilder().u16(0).u16(0x8400).u16(0).u16(1).u16(0).u16(3)
        val serviceAt = packet.offset
        packet.strings("_googlecast", "_tcp")
        val localAt = packet.offset
        packet.strings("local").u8(0)
        var instanceAt = 0
        var hostAt = 0
        packet.record(12) { instanceAt = offset; strings("Chromecast-abc123"); pointer(serviceAt) }
        packet.pointer(instanceAt).record(33) { u16(0).u16(0).u16(8010); hostAt = offset; strings("abc-host"); pointer(localAt) }
        packet.pointer(instanceAt).record(16) { strings("id=deadbeef", "fn=Living Room", "md=Chromecast") }
        packet.pointer(hostAt).record(1) { u8(192).u8(168).u8(1).u8(20) }
        return packet.bytes()
    }

    @Test
    fun parsesCompressedCastResponse() {
        assertEquals(
            listOf(CastDevice(id = "deadbeef", name = "Living Room", host = "192.168.1.20", port = 8010)),
            parseCastMdnsResponse(castResponse(), sourceHost = "10.0.0.9"),
        )
    }

    @Test
    fun missingAdditionalsFallBackToInstanceNameAndSourceAddress() {
        val packet = DnsBuilder().u16(0).u16(0x8400).u16(0).u16(1).u16(0).u16(0)
        val serviceAt = packet.offset
        packet.strings("_googlecast", "_tcp", "local").u8(0)
        packet.record(12) { strings("Chromecast-abc123"); pointer(serviceAt) }
        assertEquals(
            listOf(CastDevice(id = "Chromecast-abc123", name = "Chromecast-abc123", host = "10.0.0.9", port = 8009)),
            parseCastMdnsResponse(packet.bytes(), sourceHost = "10.0.0.9"),
        )
    }

    @Test
    fun truncatedAndMalformedPacketsAreRejected() {
        val full = castResponse()
        for (length in 0 until full.size) {
            assertEquals(emptyList(), parseCastMdnsResponse(full.copyOf(length), "10.0.0.9"), "truncated at $length")
        }
        // A name pointer that points at itself must not loop forever.
        val loop = DnsBuilder().u16(0).u16(0x8400).u16(0).u16(1).u16(0).u16(0).pointer(12).bytes()
        assertEquals(emptyList(), parseCastMdnsResponse(loop, "10.0.0.9"))
        // Our own query (QR bit clear) is not a response.
        assertTrue(parseCastMdnsResponse(castMdnsQuery(), "10.0.0.9").isEmpty())
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocolTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocolTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastProtocolTest.kt).

The implementation below defines `CastProtocolTest`, `chunkedTransport`, `write`, `read`, `close`, `json`, `frameMatchesCastMessageProtobufLayout`, `framesSurviveArbitraryChunkSplits`, `oversizedOrTruncatedFramesAreRejected`, `mediaStatusMapsPlayerStatesAndQueueIndex` and 2 further declarations.

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

- `frameMatchesCastMessageProtobufLayout`
- `framesSurviveArbitraryChunkSplits`
- `oversizedOrTruncatedFramesAreRejected`
- `mediaStatusMapsPlayerStatesAndQueueIndex`
- `idleFinishedOnlyAfterLastItemAndIdleErrorSurfaces`
- `queueLoadSideLoadsOnlyWebVttTracksWithCastStyleColors`

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class CastProtocolTest {
    private val device = CastDevice("id", "TV")
    private val queue = listOf(CastMedia("https://x/1.mp4", "E1"), CastMedia("https://x/2.mp4", "E2"))

    private fun chunkedTransport(chunks: List<ByteArray>) = object : CastTransport {
        val pending = ArrayDeque(chunks)
        override suspend fun write(frame: ByteArray) = Unit
        override suspend fun read(): ByteArray = pending.removeFirst()
        override fun close() = Unit
    }

    private fun json(text: String) = Json.parseToJsonElement(text).jsonObject

    @Test
    fun frameMatchesCastMessageProtobufLayout() {
        val expected = byteArrayOf(
            0, 0, 0, 16,
            0x08, 0, 0x12, 1, 'a'.code.toByte(), 0x1a, 1, 'b'.code.toByte(), 0x22, 1, 'c'.code.toByte(),
            0x28, 0, 0x32, 1, 'd'.code.toByte(),
        )
        assertContentEquals(expected, CastMessage("a", "b", "c", "d").toFrame())
    }

    @Test
    fun framesSurviveArbitraryChunkSplits() = runTest {
        // Multi-byte UTF-8 payload longer than 127 bytes exercises two-byte varint lengths.
        val first = CastMessage(SENDER_ID, RECEIVER_ID, NS_MEDIA, """{"type":"PING","text":"${"é".repeat(200)}"}""")
        val second = CastMessage("web-1", SENDER_ID, NS_HEARTBEAT, """{"type":"PONG"}""")
        val stream = first.toFrame() + second.toFrame()
        val reader = CastFrameReader(chunkedTransport(stream.toList().chunked(3) { it.toByteArray() }))
        assertEquals(first, reader.next())
        assertEquals(second, reader.next())
    }

    @Test
    fun oversizedOrTruncatedFramesAreRejected() = runTest {
        val oversized = CastFrameReader(chunkedTransport(listOf(byteArrayOf(0x7F, 0, 0, 0))))
        assertFailsWith<IllegalStateException> { oversized.next() }
        val frame = CastMessage(SENDER_ID, RECEIVER_ID, NS_MEDIA, "{}").toFrame()
        assertFailsWith<IllegalStateException> { decodeCastMessage(frame, 4, frame.size - 3) }
    }

    @Test
    fun mediaStatusMapsPlayerStatesAndQueueIndex() {
        val itemIds = listOf(7, 8)
        val playing = CastStatus(device, queue = queue).withMediaStatus(
            json("""{"playerState":"PLAYING","currentTime":12.5,"currentItemId":8,"media":{"duration":1400.0}}"""),
            itemIds,
        )
        assertTrue(playing.playing)
        assertFalse(playing.buffering)
        assertEquals(12_500, playing.positionMs)
        assertEquals(1_400_000, playing.durationMs)
        assertEquals(1, playing.currentIndex)

        val paused = playing.withMediaStatus(json("""{"playerState":"PAUSED","currentTime":13,"currentItemId":8}"""), itemIds)
        assertFalse(paused.playing)
        assertEquals(1_400_000, paused.durationMs)

        val buffering = paused.withMediaStatus(json("""{"playerState":"BUFFERING","currentItemId":7}"""), itemIds)
        assertTrue(buffering.buffering)
        assertEquals(0, buffering.currentIndex)
        assertEquals(0, buffering.durationMs) // item changed and the receiver has not sent its media yet

        assertFalse(playing.withMediaStatus(null, itemIds).playing)
    }

    @Test
    fun idleFinishedOnlyAfterLastItemAndIdleErrorSurfaces() {
        val itemIds = listOf(7, 8)
        val base = CastStatus(device, queue = queue)
        val midQueue = base.withMediaStatus(json("""{"playerState":"IDLE","idleReason":"FINISHED","currentItemId":7}"""), itemIds)
        assertFalse(midQueue.finished)
        val end = base.withMediaStatus(json("""{"playerState":"IDLE","idleReason":"FINISHED","currentItemId":8}"""), itemIds)
        assertTrue(end.finished)

        val failed = base.withMediaStatus(json("""{"playerState":"IDLE","idleReason":"ERROR","currentItemId":7}"""), itemIds)
        assertTrue(failed.error != null)
        assertFalse(failed.finished)
        assertNull(failed.withMediaStatus(json("""{"playerState":"PLAYING","currentItemId":7}"""), itemIds).error)
    }

    @Test
    fun queueLoadSideLoadsOnlyWebVttTracksWithCastStyleColors() {
        val media = CastMedia(
            url = "https://x/show.m3u8?sig=1",
            title = "Episode",
            subtitles = listOf(
                CastSubtitle("https://x/en.vtt?token=1", "English", "en"),
                CastSubtitle("https://x/fr.ass", "French", "fr"),
                CastSubtitle("https://x/de.VTT", "German"),
            ),
        )
        val style = CastTextStyle(foregroundArgb = 0xFFFFFF00.toInt(), edgeArgb = 0x80000000.toInt(), backgroundArgb = 0, bold = true)
        val load = json(queueLoadJson(3, listOf(media), 0, 90_000, style, activeSubtitleIndex = 2))
        assertEquals("QUEUE_LOAD", load["type"]!!.jsonPrimitive.content)
        val item = load["items"]!!.jsonArray.single().jsonObject
        val info = item["media"]!!.jsonObject
        assertEquals("application/x-mpegURL", info.string("contentType"))
        val tracks = info["tracks"]!!.jsonArray.map { it.jsonObject }
        assertEquals(listOf(1, 3), tracks.map { it.int("trackId") })
        assertEquals(listOf("https://x/en.vtt?token=1", "https://x/de.VTT"), tracks.map { it.string("trackContentId") })
        assertTrue(tracks.all { it.string("trackContentType") == "text/vtt" && it.string("type") == "TEXT" })
        assertEquals(listOf(3), item["activeTrackIds"]!!.jsonArray.map { it.jsonPrimitive.content.toInt() })
        assertEquals(90.0, item.double("startTime"))

        val textStyle = info["textTrackStyle"] as JsonObject
        assertEquals("#FFFF00FF", textStyle.string("foregroundColor"))
        assertEquals("#00000080", textStyle.string("edgeColor"))
        assertEquals("#00000000", textStyle.string("backgroundColor"))
        assertEquals("OUTLINE", textStyle.string("edgeType"))
        assertEquals("BOLD", textStyle.string("fontStyle"))

        // A selected subtitle that cannot be side-loaded is not activated.
        val nonVtt = json(queueLoadJson(4, listOf(media), 0, 0, style, activeSubtitleIndex = 1))
        assertNull(nonVtt["items"]!!.jsonArray.single().jsonObject["activeTrackIds"])
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSessionTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSessionTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSessionTest.kt).

The implementation below defines `CastSessionTest`, `FakeTransport`, `write`, `read`, `close`, `deliver`, `next`, `TestScope.connectedSession`, `handshakeLaunchesReceiverThenControlsMediaOnItsTransport`, `answersReceiverPingWithPong` and 4 further declarations.

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

- `handshakeLaunchesReceiverThenControlsMediaOnItsTransport`
- `answersReceiverPingWithPong`
- `connectTimesOutWhenReceiverNeverLaunches`
- `transportFailureDuringConnectIsThrown`
- `lostConnectionAfterConnectSurfacesStatusError`
- `silentReceiverFailsSessionAfterMissedHeartbeats`

```kotlin
package eu.friedcutlet.yokan.services.media.cast

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class CastSessionTest {
    private val device = CastDevice("id", "TV", "192.168.1.20")
    private val queue = listOf(CastMedia("https://x/1.mp4", "E1"), CastMedia("https://x/2.mp4", "E2"))

    private class FakeTransport : CastTransport {
        val incoming = Channel<ByteArray>(Channel.UNLIMITED)
        val sent = Channel<CastMessage>(Channel.UNLIMITED)
        var closed = false

        override suspend fun write(frame: ByteArray) {
            check(!closed) { "transport closed" }
            sent.send(decodeCastMessage(frame, 4))
        }

        override suspend fun read(): ByteArray = incoming.receive()

        override fun close() {
            closed = true
            incoming.close()
        }

        fun deliver(source: String, namespace: String, payload: String) {
            incoming.trySend(CastMessage(source, SENDER_ID, namespace, payload).toFrame())
        }

        suspend fun next(): Pair<CastMessage, JsonObject> =
            sent.receive().let { it to Json.parseToJsonElement(it.payload).jsonObject }
    }

    private suspend fun TestScope.connectedSession(transport: FakeTransport): CastSession {
        val session = CastSession(device, transport, backgroundScope)
        val connecting = async { session.connect() }

        val (connect, connectJson) = transport.next()
        assertEquals(Triple(NS_CONNECTION, RECEIVER_ID, "CONNECT"), Triple(connect.namespace, connect.destinationId, connectJson.string("type")))
        val (launch, launchJson) = transport.next()
        assertEquals(NS_RECEIVER to "LAUNCH", launch.namespace to launchJson.string("type"))
        assertEquals(DEFAULT_MEDIA_RECEIVER_APP_ID, launchJson.string("appId"))

        // The receiver first reports its idle backdrop, then the launched media receiver.
        transport.deliver(RECEIVER_ID, NS_RECEIVER, """{"type":"RECEIVER_STATUS","status":{"applications":[{"appId":"E8C28D3C","transportId":"backdrop"}]}}""")
        transport.deliver(
            RECEIVER_ID,
            NS_RECEIVER,
            """{"type":"RECEIVER_STATUS","requestId":1,"status":{"applications":[{"appId":"CC1AD845","sessionId":"app-1","transportId":"web-5"}]}}""",
        )
        val (appConnect, appConnectJson) = transport.next()
        assertEquals(Triple(NS_CONNECTION, "web-5", "CONNECT"), Triple(appConnect.namespace, appConnect.destinationId, appConnectJson.string("type")))
        connecting.await()
        return session
    }

    @Test
    fun handshakeLaunchesReceiverThenControlsMediaOnItsTransport() = runTest {
        val transport = FakeTransport()
        val session = connectedSession(transport)
        assertEquals(CastStatus(device), session.status.value)

        session.loadQueue(queue, 1, 5_000, CastTextStyle(), null)
        val (load, loadJson) = transport.next()
        assertEquals(Triple(NS_MEDIA, "web-5", "QUEUE_LOAD"), Triple(load.namespace, load.destinationId, loadJson.string("type")))
        assertEquals(1, loadJson.int("startIndex"))

        transport.deliver(
            "web-5",
            NS_MEDIA,
            """{"type":"MEDIA_STATUS","status":[{"mediaSessionId":3,"playerState":"PLAYING","currentTime":5,"currentItemId":11,"items":[{"itemId":10},{"itemId":11}]}]}""",
        )
        runCurrent()
        val status = session.status.value!!
        assertTrue(status.playing)
        assertEquals(1, status.currentIndex)
        assertEquals(queue, status.queue)

        session.pause()
        val (_, pauseJson) = transport.next()
        assertEquals("PAUSE" to 3, pauseJson.string("type") to pauseJson.int("mediaSessionId"))

        session.jumpTo(0)
        val (_, jumpJson) = transport.next()
        assertEquals("QUEUE_UPDATE" to 10, jumpJson.string("type") to jumpJson.int("currentItemId"))
    }

    @Test
    fun answersReceiverPingWithPong() = runTest {
        val transport = FakeTransport()
        connectedSession(transport)
        transport.deliver(RECEIVER_ID, NS_HEARTBEAT, """{"type":"PING"}""")
        val (pong, pongJson) = transport.next()
        assertEquals(Triple(NS_HEARTBEAT, RECEIVER_ID, "PONG"), Triple(pong.namespace, pong.destinationId, pongJson.string("type")))
    }

    @Test
    fun connectTimesOutWhenReceiverNeverLaunches() = runTest {
        val transport = FakeTransport()
        val session = CastSession(device, transport, backgroundScope)
        val failure = assertFailsWith<IllegalStateException> { session.connect() }
        assertTrue(failure.message!!.contains("Timed out"), failure.message)
        assertTrue(transport.closed)
    }

    @Test
    fun transportFailureDuringConnectIsThrown() = runTest {
        val transport = FakeTransport()
        transport.incoming.close(IllegalStateException("connection reset"))
        val session = CastSession(device, transport, backgroundScope)
        val failure = assertFailsWith<IllegalStateException> { session.connect() }
        assertTrue(failure.message!!.contains("connection reset"), failure.message)
        assertTrue(transport.closed)
    }

    @Test
    fun lostConnectionAfterConnectSurfacesStatusError() = runTest {
        val transport = FakeTransport()
        val session = connectedSession(transport)
        transport.incoming.close(IllegalStateException("connection reset"))
        runCurrent()
        assertTrue(session.status.value?.error.orEmpty().contains("connection reset"), session.status.value?.error)
        assertTrue(transport.closed)
    }

    @Test
    fun silentReceiverFailsSessionAfterMissedHeartbeats() = runTest {
        val transport = FakeTransport()
        val session = connectedSession(transport)
        advanceTimeBy(20_001)
        assertTrue(session.status.value?.error.orEmpty().contains("stopped responding"), session.status.value?.error)
        assertTrue(transport.closed)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ComposeControllerRetirementTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ComposeControllerRetirementTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ComposeControllerRetirementTest.kt).

The implementation below defines `ComposeControllerRetirementTest`, `proxyUrl`, `stop`.

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

- `retainedCommandsAndSnapshotsCannotReviveReleasedCompatibilityController`
- `newStreamClearsPreviousTracksAndFailureWhileReleasedControllerRejectsThem`

```kotlin
package eu.friedcutlet.yokan.services.media.player

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class ComposeControllerRetirementTest {
    @Test fun retainedCommandsAndSnapshotsCannotReviveReleasedCompatibilityController() {
        var registrations = 0
        val proxy = object : MediaStreamProxy {
            override fun proxyUrl(url: String, headers: Map<String, String>): String { registrations++; return url }
            override fun stop() = Unit
        }
        val controller = ComposeMediaPlayerController(proxy)
        controller.load("https://stream.test/live"); controller.play()
        controller.updateSnapshot(100_000L, 0.42f, "", true)
        controller.release()
        val stop = controller.playbackCommand
        controller.load("https://stream.test/late", mapOf("Referer" to "expired"))
        controller.play(); controller.pause(); controller.seekTo(50_000L); controller.setPlaybackSpeed(2f)
        controller.updateSnapshot(100_000L, 0.8f, "", true); controller.release()
        assertTrue(controller.released); assertSame(stop, controller.playbackCommand)
        assertNull(controller.mediaRequest); assertFalse(controller.finishMediaPreparation())
        assertEquals(0L, controller.currentPositionMs()); assertEquals(0L, controller.durationMs())
        assertFalse(controller.isPlaying()); assertEquals(0, registrations); assertEquals(1f, controller.speed)
    }

    @Test fun newStreamClearsPreviousTracksAndFailureWhileReleasedControllerRejectsThem() {
        val controller = ComposeMediaPlayerController(NoopMediaStreamProxy)
        controller.load("https://stream.test/a")
        assertTrue(controller.selectSubtitleTrack("https://stream.test/en.vtt", "English"))
        assertTrue(controller.selectSecondarySubtitle("https://stream.test/ja.vtt", "Japanese"))
        assertTrue(controller.setVolume(140))
        controller.error = "network"
        assertEquals("https://stream.test/en.vtt", controller.subtitle?.src)
        assertEquals("network", controller.playbackError)
        assertEquals(1f, controller.volume, "volume is capped at 100 %")

        controller.load("https://stream.test/b")
        assertNull(controller.subtitle); assertNull(controller.secondarySubtitle); assertNull(controller.playbackError)

        controller.release()
        assertFalse(controller.selectSubtitleTrack("https://stream.test/en.vtt"))
        assertFalse(controller.setVolume(10))
        assertNull(controller.subtitle); assertEquals(1f, controller.volume)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeaturesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeaturesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeaturesTest.kt).

The implementation below defines `MpvFeaturesTest`, `savedPlayerSettingsBecomeMpvOptions`, `disablingHardwareAndConfigIsExplicit`, `typedFeaturesSendTheOldMpvBindings`, `subtitlePrioritySecondaryDelayAndVolumeUseMpvProperties`, `customButtonsKeepAniyomiCompatibilityAndInterpolation`, `RecordingController`, `load`, `play`, `pause` and 7 further declarations.

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

- `savedPlayerSettingsBecomeMpvOptions`
- `disablingHardwareAndConfigIsExplicit`
- `typedFeaturesSendTheOldMpvBindings`
- `subtitlePrioritySecondaryDelayAndVolumeUseMpvProperties`
- `customButtonsKeepAniyomiCompatibilityAndInterpolation`

Cross-chapter imports used by this file: [`DbAudioChannel`](../chapters/02-domain-and-settings-models.md), [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbDebandingType`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbAudioChannel
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbDebandingType
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MpvFeaturesTest {
    @Test
    fun savedPlayerSettingsBecomeMpvOptions() {
        val options = MediaPlayerConfiguration(
            useLibass = false,
            useMpvConfig = true,
            mpvConfigDirectory = "/tmp/yokan/mpv",
            hwdecMode = "mediacodec-copy",
            enableHardwareAcceleration = true,
            debandingType = DbDebandingType.Cpu,
            useYuv420p = true,
            audioPreferredLanguages = "jpn,eng",
            enableAudioPitchCorrection = false,
            audioChannels = DbAudioChannel.ReverseStereo,
            volumeBoostCap = 40,
        ).mpvOptions()

        assertEquals("mediacodec-copy", options["hwdec"])
        assertEquals("no", options["sub-ass"])
        assertEquals("format=yuv420p,gradfun=radius=12", options["vf"])
        assertEquals("jpn,eng", options["alang"])
        assertEquals("no", options["audio-pitch-correction"])
        assertEquals("140", options["volume-max"])
        assertEquals("pan=[stereo|c0=c1|c1=c0]", options["af"])
        assertFalse(options.containsKey("audio-channels"))
        assertEquals("yes", options["config"])
        assertEquals("/tmp/yokan/mpv", options["config-dir"])
    }

    @Test
    fun disablingHardwareAndConfigIsExplicit() {
        val options = MediaPlayerConfiguration(
            useMpvConfig = false,
            enableHardwareAcceleration = false,
        ).mpvOptions()

        assertEquals("no", options["hwdec"])
        assertEquals("no", options["config"])
        assertFalse(options.containsKey("config-dir"))
        assertEquals("130", options["volume-max"])
        assertEquals("yes", options["load-stats-overlay"])
    }

    @Test
    fun typedFeaturesSendTheOldMpvBindings() {
        val controller = RecordingController()

        assertTrue(controller.showMpvStats("stats/display-page-3"))
        assertTrue(controller.selectSubtitleTrack("https://example.test/sub.vtt", "English"))
        assertTrue(controller.setMpvVideoFit(MpvVideoFit.Cover))

        assertEquals(listOf("script-binding", "stats/display-page-3"), controller.commands[0])
        assertEquals(
            listOf("sub-add", "https://example.test/sub.vtt", "select", "English", "English"),
            controller.commands[1],
        )
        assertEquals(listOf("set", "video-unscaled", "no"), controller.commands[2])
        assertEquals(listOf("set", "panscan", "1"), controller.commands[3])
    }

    @Test
    fun subtitlePrioritySecondaryDelayAndVolumeUseMpvProperties() {
        assertEquals("jpn,eng", MediaPlayerConfiguration(subtitleLanguages = listOf("jpn", "eng")).mpvOptions()["slang"])
        assertFalse(MediaPlayerConfiguration().mpvOptions().containsKey("slang"), "no priority keeps mpv's default selection")

        val controller = RecordingController()
        assertTrue(controller.setSecondarySubtitleDelay(-1500))
        assertTrue(controller.setVolume(250))
        assertEquals(listOf("set", "secondary-sub-delay", "-1.5"), controller.commands[0])
        assertEquals(listOf("set", "volume", "100"), controller.commands[1])
    }

    @Test
    fun customButtonsKeepAniyomiCompatibilityAndInterpolation() {
        val script = buildMpvCustomButtonsScript(
            listOf(
                DbCustomButton(
                    id = 7,
                    title = "Skip",
                    codePress = "aniyomi.seek_by(\$id)",
                    codeLongPress = "aniyomi.show_text(String(\$isPrimary))",
                    position = 0,
                    isFavourite = true,
                ),
            ),
            primaryId = 7,
        )

        assertTrue("aniyomi.seek_by = function" in script)
        assertTrue("aniyomi.seek_by(7)" in script)
        assertTrue("aniyomi.show_text(String(true))" in script)
        assertTrue("call_button_7_long" in script)
    }

    private class RecordingController : MediaPlayerController {
        val commands = mutableListOf<List<String>>()

        override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
        override fun play() = Unit
        override fun pause() = Unit
        override fun seekTo(positionMs: Long) = Unit
        override fun setPlaybackSpeed(speed: Float) = Unit
        override fun executeMpvCommand(vararg arguments: String): Boolean {
            commands += arguments.toList()
            return true
        }
        override fun release() = Unit
        override fun currentPositionMs(): Long = 0
        override fun durationMs(): Long = 0
        override fun isPlaying(): Boolean = false
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwnersTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwnersTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePlaybackOwnersTest.kt).

The implementation below defines `PictureInPicturePlaybackOwnersTest`, `Platform`.

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

- `uncommittedOwnerCannotRevokeLivePlaybackOrPublishState`
- `requestRetainsItsExactControllerAndExpiredOwnerCannotBorrowReplacement`
- `replacedOwnersCannotRequestPublishOrClearNewPlaybackState`
- `retainedNativeAdmissionRechecksOriginalOwnerAtDispatch`
- `oldNativeCallbackCannotBorrowReplacementAdmission`
- `closureClearsOnlyItsOwnStateAndCannotRevive`
- `playingControlsEligibilityWithoutChangingPlatformManualRequestPolicy`
- `inactiveOwnersCannotEnterEvenWithRetainedPlayingState`

```kotlin
package eu.friedcutlet.yokan.services.media.player

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PictureInPicturePlaybackOwnersTest {
    @Test fun uncommittedOwnerCannotRevokeLivePlaybackOrPublishState() {
        val platform = Platform()
        val live = platform.owners.acquire { true }; live.update(true)
        val uncommitted = platform.owners.create(admitted = { true })
        val published = platform.states.toList()
        uncommitted.update(true); assertFalse(uncommitted.request()); assertTrue(live.active())
        assertEquals(published, platform.states)
        uncommitted.activate(); uncommitted.update(true)
        assertFalse(live.active()); assertTrue(uncommitted.request()); uncommitted.close()
    }

    @Test fun requestRetainsItsExactControllerAndExpiredOwnerCannotBorrowReplacement() {
        val first = ComposeMediaPlayerController(NoopMediaStreamProxy)
        val second = ComposeMediaPlayerController(NoopMediaStreamProxy)
        val requested = mutableListOf<MediaPlayerController?>()
        val owners = PictureInPicturePlaybackOwners(publish = { _, _, _ -> }, request = { requested += it; true })
        val a = owners.create(admitted = { true }, controller = first); a.activate()
        assertTrue(a.request())
        val b = owners.create(admitted = { true }, controller = second); b.activate()
        assertFalse(a.request()); assertTrue(b.request())
        assertEquals<List<MediaPlayerController?>>(listOf(first, second), requested)
        a.close(); assertTrue(b.active()); b.close(); first.release(); second.release()
    }

    @Test fun replacedOwnersCannotRequestPublishOrClearNewPlaybackState() {
        val platform = Platform()
        val first = platform.owners.acquire { true }; first.update(true)
        val second = platform.owners.acquire { true }; second.update(true)
        val published = platform.states.toList()
        first.update(false); first.close()
        assertEquals(published, platform.states); assertFalse(first.request()); assertFalse(first.active())
        assertTrue(second.request()); assertEquals(1, platform.requests); assertTrue(platform.admitted())
    }

    @Test fun retainedNativeAdmissionRechecksOriginalOwnerAtDispatch() {
        val platform = Platform(); var available = true
        val owner = platform.owners.acquire { available }; owner.update(true)
        val nativeCallback = platform.admitted
        assertTrue(nativeCallback()); available = false
        assertFalse(nativeCallback()); assertFalse(owner.request()); assertEquals(0, platform.requests)
    }

    @Test fun oldNativeCallbackCannotBorrowReplacementAdmission() {
        val platform = Platform()
        val first = platform.owners.acquire { true }; first.update(true)
        val retained = platform.admitted
        val next = platform.owners.acquire { true }; next.update(true)
        assertFalse(retained()); assertTrue(platform.admitted()); assertFalse(first.request())
        assertTrue(next.request()); next.close(); assertFalse(platform.admitted())
    }

    @Test fun closureClearsOnlyItsOwnStateAndCannotRevive() {
        val platform = Platform()
        val owner = platform.owners.acquire { true }; owner.update(true); owner.close()
        assertEquals(false to false, platform.states.last()); assertFalse(platform.admitted())
        val count = platform.states.size
        owner.close(); owner.update(true)
        assertEquals(count, platform.states.size); assertFalse(owner.request())
    }

    @Test fun playingControlsEligibilityWithoutChangingPlatformManualRequestPolicy() {
        val platform = Platform()
        val owner = platform.owners.acquire { true }
        owner.update(false); assertEquals(true to false, platform.states.last()); assertTrue(owner.request())
        owner.update(true); assertEquals(true to true, platform.states.last())
        owner.close()
    }

    @Test fun inactiveOwnersCannotEnterEvenWithRetainedPlayingState() {
        val platform = Platform(); var active = true
        val owner = platform.owners.acquire { active }; owner.update(true)
        active = false; assertFalse(owner.request()); assertFalse(platform.admitted())
        owner.update(true); assertEquals(false to false, platform.states.last())
        assertEquals(0, platform.requests); owner.close()
    }

    private class Platform {
        val states = mutableListOf<Pair<Boolean, Boolean>>()
        var admitted: () -> Boolean = { false }
        var requests = 0
        val owners = PictureInPicturePlaybackOwners(
            publish = { active, eligible, callback -> states += active to eligible; admitted = callback },
            request = { requests++; true },
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePolicyTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePolicyTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PictureInPicturePolicyTest.kt).

The implementation below defines `PictureInPicturePolicyTest`, `nonSupportedTargetsDoNotAdvertisePictureInPicture`.

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

- `nonSupportedTargetsDoNotAdvertisePictureInPicture`

```kotlin
package eu.friedcutlet.yokan.services.media.player

import kotlin.test.Test
import kotlin.test.assertFalse

class PictureInPicturePolicyTest {
    @Test
    fun nonSupportedTargetsDoNotAdvertisePictureInPicture() {
        assertFalse(pictureInPicturePlatform.isSupported)
        assertFalse(pictureInPicturePlatform.request())
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPoliciesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPoliciesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPoliciesTest.kt).

The implementation below defines `PlaybackPoliciesTest`, `speedPresetsAreValidatedSortedAndDeduplicated`, `subtitleLanguagePriorityWhitelistAndBlacklist`, `subtitleFallbackKeepsPreviousBehaviorAndBlacklistCanDisable`, `failoverTriesEachStreamOnceAndStops`, `sleepTimerDeadlineAndEndOfEpisode`, `thumbnailVttParsesSpriteTilesAndResolvesUrls`.

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

- `speedPresetsAreValidatedSortedAndDeduplicated`
- `subtitleLanguagePriorityWhitelistAndBlacklist`
- `subtitleFallbackKeepsPreviousBehaviorAndBlacklistCanDisable`
- `failoverTriesEachStreamOnceAndStops`
- `sleepTimerDeadlineAndEndOfEpisode`
- `thumbnailVttParsesSpriteTilesAndResolvesUrls`

Cross-chapter imports used by this file: [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`DbVideoTrack`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue

class PlaybackPoliciesTest {
    @Test
    fun speedPresetsAreValidatedSortedAndDeduplicated() {
        assertEquals(listOf(0.5, 1.0, 1.25, 2.0), parseSpeedPresets("2, 1x, 0.5;1.25 1.0"))
        assertEquals(listOf(0.33), parseSpeedPresets("0.333"))
        assertNull(parseSpeedPresets("1, 5"), "out-of-range values reject the whole list")
        assertNull(parseSpeedPresets("1, fast"))
        assertNull(parseSpeedPresets(" , "))
    }

    private val tracks = listOf(
        DbVideoTrack("en-signs.vtt", "English [Signs]"),
        DbVideoTrack("en-full.vtt", "English [Full]"),
        DbVideoTrack("ja.vtt", "Japanese"),
        DbVideoTrack("pt.vtt", "pt-BR"),
        DbVideoTrack(null, "Broken"),
    )

    @Test
    fun subtitleLanguagePriorityWhitelistAndBlacklist() {
        assertEquals("ja.vtt", preferredSubtitle(tracks, listOf("de", "ja", "en"))?.file, "first language with a track wins")
        assertEquals("en-full.vtt", preferredSubtitle(tracks, listOf("en"), whitelist = listOf("full"))?.file)
        assertEquals("en-full.vtt", preferredSubtitle(tracks, listOf("English"), blacklist = listOf("signs"))?.file)
        assertEquals("pt.vtt", preferredSubtitle(tracks, listOf("pt"))?.file, "codes match as words")
        assertEquals("ja.vtt", preferredSubtitle(tracks, listOf("en"), blacklist = listOf("english"))?.file,
            "a fully blacklisted language falls through to the first allowed track")
    }

    @Test
    fun subtitleFallbackKeepsPreviousBehaviorAndBlacklistCanDisable() {
        assertEquals("en-signs.vtt", preferredSubtitle(tracks, emptyList())?.file)
        assertEquals("en-signs.vtt", preferredSubtitle(tracks, listOf("ko"))?.file)
        assertNull(preferredSubtitle(tracks, emptyList(), blacklist = listOf(".vtt")))
        assertNull(preferredSubtitle(emptyList(), listOf("en")))
    }

    @Test
    fun failoverTriesEachStreamOnceAndStops() {
        val videos = listOf("a", "b", "c").map { DbVideo(url = it, quality = it, originalUrl = it) }
        val failed = mutableSetOf<String>()
        val tried = mutableListOf<String>()
        var current = videos.first()
        while (true) {
            failed += current.url
            current = nextFailoverVideo(videos, failed) ?: break
            tried += current.url
        }
        assertEquals(listOf("b", "c"), tried)
        assertNull(nextFailoverVideo(emptyList(), emptySet()))
    }

    @Test
    fun sleepTimerDeadlineAndEndOfEpisode() {
        assertFalse(SleepTimer(10_000).isDue(nowMs = 9_999, positionMs = 0, durationMs = 0))
        assertTrue(SleepTimer(10_000).isDue(nowMs = 10_000, positionMs = 0, durationMs = 0))
        val endOfEpisode = SleepTimer(null)
        assertFalse(endOfEpisode.isDue(nowMs = Long.MAX_VALUE, positionMs = 0, durationMs = 0), "unknown duration never fires")
        assertFalse(endOfEpisode.isDue(0, positionMs = 59_000, durationMs = 60_000))
        assertTrue(endOfEpisode.isDue(0, positionMs = 59_600, durationMs = 60_000))
    }

    @Test
    fun thumbnailVttParsesSpriteTilesAndResolvesUrls() {
        val vtt = """
            WEBVTT

            1
            00:00:00.000 --> 00:00:05.000
            sprite-0.jpg#xywh=0,0,160,90

            00:05.000 --> 00:10.000
            /img/sprite-0.jpg#xywh=160,0,160,90

            01:00:10.000 --> 01:00:15.000
            https://cdn.example/full.jpg

            00:00:20.000 --> bogus
            broken.jpg
        """.trimIndent()
        val tiles = parseThumbnailVtt(vtt, "https://host.example/path/thumbs.vtt?token=1")
        assertEquals(3, tiles.size)
        assertEquals(SeekThumbnail(0, 5_000, "https://host.example/path/sprite-0.jpg", 0, 0, 160, 90), tiles[0])
        assertEquals(SeekThumbnail(5_000, 10_000, "https://host.example/img/sprite-0.jpg", 160, 0, 160, 90), tiles[1])
        assertEquals(SeekThumbnail(3_610_000, 3_615_000, "https://cdn.example/full.jpg"), tiles[2])

        assertEquals(tiles[0], tiles.at(4_999))
        assertEquals(tiles[1], tiles.at(5_000))
        assertNull(tiles.at(20_000), "gaps between cues show no preview")
        assertNull(emptyList<SeekThumbnail>().at(0))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerBridgeCommandTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerBridgeCommandTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerBridgeCommandTest.kt).

The implementation below defines `PlayerBridgeCommandTest`, `command`, `everyPropertyTheScriptBridgeWritesIsObserved`, `observedPropertiesDecodeUnderTheirEventName`, `togglesDistinguishShowHideAndToggle`, `panelsMapToTheirSheetPage`, `seeksParseQuotedFractionalSecondsAndKeepTextWhenThePositionIsMalformed`, `intPickerRequiresAnAscendingRangePositiveStepAndProperty`, `chapterTitlesSkipEntriesWithoutTimestampsAndDefaultBlankTitles`.

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

- `everyPropertyTheScriptBridgeWritesIsObserved`
- `observedPropertiesDecodeUnderTheirEventName`
- `togglesDistinguishShowHideAndToggle`
- `panelsMapToTheirSheetPage`
- `seeksParseQuotedFractionalSecondsAndKeepTextWhenThePositionIsMalformed`
- `intPickerRequiresAnAscendingRangePositiveStepAndProperty`
- `chapterTitlesSkipEntriesWithoutTimestampsAndDefaultBlankTitles`

```kotlin
package eu.friedcutlet.yokan.services.media.player

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class PlayerBridgeCommandTest {
    private fun command(name: String, value: String) = MpvBridgeEvent(name, value).toCommand()

    @Test
    fun everyPropertyTheScriptBridgeWritesIsObserved() {
        val written = Regex("user-data/([a-z_]+/[a-z_]+)")
            .findAll(buildMpvCustomButtonsScript(emptyList(), 0))
            .map { "user-data/${it.groupValues[1]}" }
            .toSet()

        assertTrue(written.isNotEmpty())
        assertTrue(MpvBridgePropertyNames.containsAll(written), (written - MpvBridgePropertyNames).toString())
    }

    @Test
    fun observedPropertiesDecodeUnderTheirEventName() {
        assertEquals(PlayerBridgeCommand.ShowText("hi"), command("aniyomi/show_text", "hi"))
        assertNull(command("aniyomi/software_keyboard", "show"))
        assertNull(command("aniyomi/unknown", "x"))
    }

    @Test
    fun togglesDistinguishShowHideAndToggle() {
        assertEquals(PlayerBridgeCommand.SetUiVisible(true), command("aniyomi/toggle_ui", "show"))
        assertEquals(PlayerBridgeCommand.SetUiVisible(false), command("aniyomi/toggle_ui", "hide"))
        assertEquals(PlayerBridgeCommand.SetButtonVisible(null), command("aniyomi/toggle_button", "toggle"))
        assertEquals(PlayerBridgeCommand.SetPaused(true), command("aniyomi/pause", "pause"))
        assertEquals(PlayerBridgeCommand.SetPaused(false), command("aniyomi/pause", "unpause"))
        assertEquals(PlayerBridgeCommand.SetPaused(null), command("aniyomi/pause", "pauseunpause"))
        assertEquals(PlayerBridgeCommand.SwitchEpisode(-1), command("aniyomi/switch_episode", "p"))
        assertEquals(PlayerBridgeCommand.SwitchEpisode(1), command("aniyomi/switch_episode", "n"))
    }

    @Test
    fun panelsMapToTheirSheetPage() {
        assertEquals(PlayerBridgeCommand.ShowPanel(MpvPanel.Subtitles), command("aniyomi/show_panel", "subtitle_delay"))
        assertEquals(PlayerBridgeCommand.ShowPanel(MpvPanel.Audio), command("aniyomi/show_panel", "audio_delay"))
        assertEquals(PlayerBridgeCommand.ShowPanel(MpvPanel.Video), command("aniyomi/show_panel", "video_filters"))
    }

    @Test
    fun seeksParseQuotedFractionalSecondsAndKeepTextWhenThePositionIsMalformed() {
        assertEquals(PlayerBridgeCommand.Seek(-5, relative = true), command("aniyomi/seek_by", "\"-5.7\""))
        assertEquals(PlayerBridgeCommand.Seek(90, relative = false), command("aniyomi/seek_to", " 90 "))
        assertNull(command("aniyomi/seek_to", "soon"))
        assertEquals(PlayerBridgeCommand.Seek(10, relative = true, text = "+10s"), command("aniyomi/seek_by_with_text", "10|+10s"))
        assertEquals(PlayerBridgeCommand.ShowText("later"), command("aniyomi/seek_to_with_text", "x|later"))
    }

    @Test
    fun intPickerRequiresAnAscendingRangePositiveStepAndProperty() {
        assertEquals(
            PlayerBridgeCommand.LaunchIntPicker(MpvIntPickerRequest("Delay", "%d ms", -100, 100, 10, "sub-delay")),
            command("aniyomi/launch_int_picker", "Delay|%d ms|-100|100|10|sub-delay"),
        )
        assertNull(MpvIntPickerRequest.parse("Delay|%d|5|5|1|p"))
        assertNull(MpvIntPickerRequest.parse("Delay|%d|0|5|0|p"))
        assertNull(MpvIntPickerRequest.parse("Delay|%d|0|5|1| "))
        assertNull(MpvIntPickerRequest.parse("Delay|%d|0|5"))
    }

    @Test
    fun chapterTitlesSkipEntriesWithoutTimestampsAndDefaultBlankTitles() {
        val marks = MpvChapterMark.parseList("""[{"title":"Intro","timestamp":0},{"title":"","timestamp":61.5},{"title":"x"}]""")

        assertEquals(listOf(MpvChapterMark("Intro", 0), MpvChapterMark("Chapter", 61_500)), marks)
        assertEquals(emptyList(), MpvChapterMark.parseList("not json"))
        assertEquals(PlayerBridgeCommand.CurrentChapter(2), command("mangayomi/current_chapter", "2.0"))
        assertEquals(PlayerBridgeCommand.CurrentChapter(0), command("mangayomi/current_chapter", "-1"))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResourcesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResourcesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResourcesTest.kt).

The implementation below defines `PlayerSurfaceResourcesTest`.

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

- `retirementJoinsWorkFinalizersBeforeResourceCleanup`
- `callerExpiryJoinsItsFinalizerAndPreservesSurfaceAdmission`
- `lateFailureBecomesCancellationBeforeUiErrorPublication`
- `failedCleanupIsRetainedForControllerRetry`
- `failedCleanupRetryRetainsTheCapturedUiContext`
- `oldSurfaceCleanupCannotRetireAnotherResource`
- `cancelledCleanupAwaiterStillWaitsForFinalNativeRelease`
- `queuedCallbacksAndCancelledCallersCannotReachRetiredResources`
- `compatibilityControllerAwaitedReleaseJoinsItsActualSurfaceResources`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.media.player

import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class PlayerSurfaceResourcesTest {
    @Test fun retirementJoinsWorkFinalizersBeforeResourceCleanup() = runTest {
        val registry = PlayerSurfaceResources(); val entered = CompletableDeferred<Unit>()
        val finish = CompletableDeferred<Unit>(); val order = mutableListOf<String>()
        val resource = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) { order += "native" })
        val call = launch { resource.runOwned {
            try { entered.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { finish.await(); order += "work" } }
        } }
        entered.await(); val close = async { registry.closeAndJoin() }; runCurrent()
        assertFalse(close.isCompleted); assertFalse(resource.isAvailable); assertTrue(order.isEmpty())
        finish.complete(Unit); close.await(); call.join(); assertEquals(listOf("work", "native"), order)
    }
    @Test fun callerExpiryJoinsItsFinalizerAndPreservesSurfaceAdmission() = runTest {
        val registry = PlayerSurfaceResources(); val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        var closes = 0
        val resource = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) { closes++ })
        val call = launch { resource.runOwned { try { entered.complete(Unit); awaitCancellation() }
            finally { withContext(NonCancellable) { finish.await() } } } }
        entered.await(); call.cancel(); runCurrent(); assertFalse(call.isCompleted)
        finish.complete(Unit); call.join(); assertTrue(resource.isAvailable); assertEquals(0, closes)
        registry.closeAndJoin(); assertEquals(1, closes)
    }
    @Test fun lateFailureBecomesCancellationBeforeUiErrorPublication() = runTest {
        val registry = PlayerSurfaceResources(); val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        var errors = 0
        val resource = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) {})
        val call = launch {
            try { resource.runOwned { withContext(NonCancellable) { entered.complete(Unit); finish.await(); error("late") } } }
            catch (cancelled: CancellationException) { throw cancelled }
            catch (_: Throwable) { errors++ }
        }
        entered.await(); resource.retire(); runCurrent(); finish.complete(Unit); call.join()
        assertTrue(call.isCancelled); assertEquals(0, errors); registry.closeAndJoin()
    }
    @Test fun failedCleanupIsRetainedForControllerRetry() = runTest {
        val registry = PlayerSurfaceResources(); var attempts = 0; var fail = true
        val resource = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) {
            attempts++; if (fail) error("native release failed")
        })
        resource.retire(); runCurrent()
        assertFailsWith<IllegalStateException> { registry.closeAndJoin() }
        assertFalse(resource.isAvailable); assertNull(registry.register(coroutineContext) {})
        fail = false; registry.closeAndJoin(); registry.closeAndJoin(); assertEquals(3, attempts)
    }
    @Test fun failedCleanupRetryRetainsTheCapturedUiContext() = runTest {
        val registry = PlayerSurfaceResources(); var fail = true; val names = mutableListOf<String?>()
        registry.register(StandardTestDispatcher(testScheduler) + CoroutineName("surface-ui")) {
            names += currentCoroutineContext()[CoroutineName]?.name
            if (fail) error("native close failed")
        }
        assertFailsWith<IllegalStateException> { withContext(CoroutineName("retiring-controller")) { registry.closeAndJoin() } }
        fail = false
        withContext(CoroutineName("retry-controller")) { registry.closeAndJoin() }
        assertEquals<List<String?>>(listOf("surface-ui", "surface-ui", "surface-ui"), names)
    }

    @Test fun oldSurfaceCleanupCannotRetireAnotherResource() = runTest {
        val registry = PlayerSurfaceResources(); val closed = mutableListOf<String>()
        val a = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) { closed += "A" })
        val b = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) { closed += "B" })
        a.closeAndJoin(); assertEquals(listOf("A"), closed); assertTrue(b.isAvailable)
        b.runOwned { }; registry.closeAndJoin(); assertEquals(listOf("A", "B"), closed)
    }
    @Test fun cancelledCleanupAwaiterStillWaitsForFinalNativeRelease() = runTest {
        val registry = PlayerSurfaceResources(); val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) { entered.complete(Unit); finish.await() })
        val close = launch { registry.closeAndJoin() }; entered.await(); close.cancel(); runCurrent()
        assertFalse(close.isCompleted); finish.complete(Unit); close.join(); registry.closeAndJoin()
    }
    @Test fun queuedCallbacksAndCancelledCallersCannotReachRetiredResources() = runTest {
        val registry = PlayerSurfaceResources(); var dispatched = 0
        val resource = checkNotNull(registry.register(StandardTestDispatcher(testScheduler)) {})
        resource.launch { dispatched++ }; resource.retire(); runCurrent()
        assertFalse(resource.launch { dispatched++ })
        assertFailsWith<CancellationException> { resource.runOwned { dispatched++ } }
        val cancelled = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { resource.runOwned { dispatched++ } }
        }
        cancelled.join(); assertEquals(0, dispatched); registry.closeAndJoin()
    }
    @Test fun compatibilityControllerAwaitedReleaseJoinsItsActualSurfaceResources() = runTest {
        val controller = ComposeMediaPlayerController(NoopMediaStreamProxy)
        val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        checkNotNull(controller.surfaces.register(StandardTestDispatcher(testScheduler)) { entered.complete(Unit); finish.await() })
        controller.release(); entered.await()
        val close = async { controller.releaseAndJoin() }; runCurrent(); assertFalse(close.isCompleted)
        finish.complete(Unit); close.await(); assertTrue(controller.released)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerControllerTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerControllerTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerControllerTest.kt).

The implementation below defines `ProfilePlayerControllerTest`, `Controller`, `release`, `releaseAndJoin`, `load`, `play`, `pause`, `seekTo`, `setPlaybackSpeed`, `currentPositionMs` and 2 further declarations.

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

- `allocationCapturesConfigurationAndReaderProxyAndReleasesOnNormalReturn`
- `expiredCallerCannotAllocateIntoLiveOwner`
- `foreignConfigurationCannotAllocateNativeController`
- `retirementDuringFactoryJoinsLateControllerWithoutPublishingIt`
- `callbackFinalizerSavesPositionBeforeNativeRelease`
- `callerCancellationWaitsForNativeCleanupAndPreservesSession`
- `sessionCloseJoinsControllerCleanupBeforeReturningAndPreservesParent`
- `failedControllerCleanupRetriesBeforeAnotherAllocationAndAtSessionClose`
- `retiringOneOwnerDoesNotReleaseAnotherOwnersController`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbSettings
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue

class ProfilePlayerControllerTest {
    @Test fun allocationCapturesConfigurationAndReaderProxyAndReleasesOnNormalReturn() = runTest {
        val controller = Controller(); var calls = 0
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { config, proxy ->
            calls++; assertEquals("/A/cache/mpv", config.mpvConfigDirectory)
            assertEquals("proxy:owned", proxy.proxyUrl("owned", emptyMap())); controller
        })
        try {
            f.reader.withController(f.reader.configuration(DbSettings())) { assertSame(controller, it) }
            assertEquals(1, calls); assertEquals(1, controller.closes); assertTrue(controller.released)
        } finally { f.close() }
    }

    @Test fun expiredCallerCannotAllocateIntoLiveOwner() = runTest {
        var calls = 0
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> calls++; Controller() })
        val configuration = f.reader.configuration(DbSettings())
        try {
            val call = async(UnconfinedTestDispatcher(testScheduler)) {
                requireNotNull(currentCoroutineContext()[Job]).cancel()
                f.reader.withController(configuration) { error("Expired callback") }
            }
            call.join(); assertTrue(call.isCancelled); assertEquals(0, calls); assertTrue(f.owner.isActive)
        } finally { f.close() }
    }

    @Test fun foreignConfigurationCannotAllocateNativeController() = runTest {
        var calls = 0
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> calls++; Controller() })
        try {
            assertFailsWith<IllegalArgumentException> {
                f.reader.withController(MediaPlayerConfiguration(mpvConfigDirectory = "/foreign/mpv")) {}
            }
            assertEquals(0, calls)
        } finally { f.close() }
    }

    @Test fun retirementDuringFactoryJoinsLateControllerWithoutPublishingIt() = runTest {
        val controller = Controller()
        lateinit var f: ProfilePlayerServicesTest.Fixture
        f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> f.open = false; controller })
        val configuration = f.reader.configuration(DbSettings())
        try {
            assertFailsWith<CancellationException> { f.reader.withController(configuration) { error("Late controller") } }
            assertEquals(1, controller.closes); assertTrue(controller.released)
        } finally { f.close() }
    }

    @Test fun callbackFinalizerSavesPositionBeforeNativeRelease() = runTest {
        val controller = Controller(); val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>(); var saved = 0L
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> controller })
        val call = async {
            f.reader.withController(f.reader.configuration(DbSettings())) { native ->
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { release.await(); saved = native.currentPositionMs() } }
            }
        }
        try {
            entered.await(); f.reader.retire(); runCurrent()
            assertFalse(call.isCompleted); assertFalse(controller.released)
            release.complete(Unit); call.join()
            assertEquals(42_000L, saved); assertEquals(1, controller.closes)
        } finally { release.complete(Unit); call.cancelAndJoin(); f.close() }
    }

    @Test fun callerCancellationWaitsForNativeCleanupAndPreservesSession() = runTest {
        val controller = Controller(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        controller.onClose = { release.await() }
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> controller })
        val call = async { f.reader.withController(f.reader.configuration(DbSettings())) { entered.complete(Unit); awaitCancellation() } }
        try {
            entered.await(); call.cancel(); runCurrent()
            assertFalse(call.isCompleted); assertTrue(controller.released); assertTrue(f.service.isAvailable)
            release.complete(Unit); call.join(); assertEquals(1, controller.closes)
        } finally { release.complete(Unit); call.cancelAndJoin(); f.close() }
    }

    @Test fun sessionCloseJoinsControllerCleanupBeforeReturningAndPreservesParent() = runTest {
        val controller = Controller(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        controller.onClose = { release.await() }
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> controller })
        val call = async { f.reader.withController(f.reader.configuration(DbSettings())) { entered.complete(Unit); awaitCancellation() } }
        try {
            entered.await(); val close = async { f.service.closeAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertFalse(call.isCompleted); assertTrue(controller.released)
            release.complete(Unit); close.await(); call.join(); assertTrue(f.owner.isActive)
            assertFailsWith<CancellationException> { f.reader.withController(MediaPlayerConfiguration()) {} }
        } finally { release.complete(Unit); call.cancelAndJoin(); f.close() }
    }

    @Test fun failedControllerCleanupRetriesBeforeAnotherAllocationAndAtSessionClose() = runTest {
        val old = Controller(); var fail = true; var allocations = 0
        old.onClose = { check(!fail) { "Native release failed" } }
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> allocations++; if (allocations == 1) old else Controller() })
        val configuration = f.reader.configuration(DbSettings())
        try {
            assertFailsWith<IllegalStateException> { f.reader.withController(configuration) {} }
            assertFailsWith<IllegalStateException> { f.reader.withController(configuration) {} }
            assertEquals(1, allocations)
            assertFailsWith<IllegalStateException> { f.service.closeAndJoin() }
            fail = false; f.service.closeAndJoin(); f.service.closeAndJoin()
            assertEquals(4, old.closes); assertTrue(f.owner.isActive)
        } finally { fail = false; f.close() }
    }

    @Test fun retiringOneOwnerDoesNotReleaseAnotherOwnersController() = runTest {
        val first = Controller(); val second = Controller(); val enteredA = CompletableDeferred<Unit>(); val enteredB = CompletableDeferred<Unit>()
        val a = ProfilePlayerServicesTest.Fixture(this, "A", factory = { _, _ -> first })
        val b = ProfilePlayerServicesTest.Fixture(this, "B", factory = { _, _ -> second })
        val callA = async { a.reader.withController(a.reader.configuration(DbSettings())) { enteredA.complete(Unit); awaitCancellation() } }
        val callB = async { b.reader.withController(b.reader.configuration(DbSettings())) { enteredB.complete(Unit); awaitCancellation() } }
        try {
            enteredA.await(); enteredB.await(); a.service.closeAndJoin(); callA.join()
            assertTrue(first.released); assertFalse(second.released); assertTrue(callB.isActive)
        } finally { callA.cancelAndJoin(); callB.cancelAndJoin(); a.close(); b.close() }
    }

    internal class Controller : MediaPlayerController {
        var released = false
        var closes = 0
        var onClose: suspend () -> Unit = {}
        override fun release() { released = true }
        override suspend fun releaseAndJoin() { release(); closes++; onClose() }
        override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
        override fun play() = Unit
        override fun pause() = Unit
        override fun seekTo(positionMs: Long) = Unit
        override fun setPlaybackSpeed(speed: Float) = Unit
        override fun currentPositionMs(): Long = if (released) 0L else 42_000L
        override fun durationMs(): Long = if (released) 0L else 100_000L
        override fun isPlaying(): Boolean = !released
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerScreenshotTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerScreenshotTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerScreenshotTest.kt).

The implementation below defines `ProfilePlayerScreenshotTest`, `executeMpvCommand`.

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

- `screenshotPathIsPublishedOnlyAfterNativeCaptureCompletes`
- `canceledCaptureJoinsLateNativeWriteBeforeRemovingItsFile`
- `serviceRetirementJoinsCaptureAndPreservesAnotherOwnersFiles`
- `failedCaptureRemovesOnlyItsOwnPartialFile`
- `thrownCaptureFailureRemovesItsSeedWithoutRetiringOwner`
- `expiryAfterNativeSuccessCannotPublishOrKeepCapturedFile`
- `queueAdmissionAloneCannotReportCaptureSuccess`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ProfilePlayerScreenshotTest {
    @Test fun screenshotPathIsPublishedOnlyAfterNativeCaptureCompletes() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        val controller = ProfilePlayerServicesTest.Controller()
        val finish = CompletableDeferred<Unit>()
        controller.onAwaitedCommand = { args ->
            finish.await()
            f.files.bytes[args[2]] = byteArrayOf(1, 2, 3)
            true
        }
        val request = async { f.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent()
            assertFalse(request.isCompleted)
            assertEquals(0, f.files.bytes.values.single().size)
            finish.complete(Unit)
            val path = requireNotNull(request.await())
            assertEquals(listOf("sync", "screenshot-to-file", path, "video"), controller.commands.single())
            assertEquals(listOf<Byte>(1, 2, 3), f.files.bytes.getValue(path).toList())
            assertTrue(f.files.deletions.isEmpty())
        } finally { finish.complete(Unit); request.cancelAndJoin(); f.close() }
    }

    @Test fun canceledCaptureJoinsLateNativeWriteBeforeRemovingItsFile() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        val controller = ProfilePlayerServicesTest.Controller()
        val finish = CompletableDeferred<Unit>()
        controller.onAwaitedCommand = { args ->
            try { awaitCancellation() }
            finally { withContext(NonCancellable) {
                finish.await()
                assertTrue(f.files.deletions.isEmpty())
                f.files.bytes[args[2]] = byteArrayOf(1)
            } }
        }
        val request = async { f.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent(); request.cancel(); runCurrent()
            assertFalse(request.isCompleted)
            assertTrue(f.files.deletions.isEmpty())
            finish.complete(Unit); request.join()
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.files.bytes.isEmpty())
            assertTrue(f.service.isAvailable)
        } finally { finish.complete(Unit); request.cancelAndJoin(); f.close() }
    }

    @Test fun serviceRetirementJoinsCaptureAndPreservesAnotherOwnersFiles() = runTest {
        val a = ProfilePlayerServicesTest.Fixture(this, "A")
        val b = ProfilePlayerServicesTest.Fixture(this, "B")
        val controller = ProfilePlayerServicesTest.Controller()
        val finish = CompletableDeferred<Unit>()
        controller.onAwaitedCommand = {
            try { awaitCancellation() }
            finally { withContext(NonCancellable) { finish.await() } }
        }
        val request = async { a.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent()
            val close = async { a.service.closeAndJoin() }
            runCurrent()
            assertFalse(close.isCompleted); assertFalse(request.isCompleted)
            val otherPath = requireNotNull(b.reader.requestScreenshot(ProfilePlayerServicesTest.Controller(), "Other", "Episode"))
            finish.complete(Unit); close.await()
            assertFailsWith<CancellationException> { request.await() }
            assertTrue(a.files.bytes.isEmpty()); assertTrue(a.owner.isActive)
            assertTrue(b.files.bytes.containsKey(otherPath)); assertTrue(b.service.isAvailable)
            assertTrue(b.files.deletions.isEmpty())
        } finally { finish.complete(Unit); request.cancelAndJoin(); a.close(); b.close() }
    }

    @Test fun failedCaptureRemovesOnlyItsOwnPartialFile() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        val controller = ProfilePlayerServicesTest.Controller()
        try {
            val prior = requireNotNull(f.reader.requestScreenshot(controller, "Book", "Episode"))
            controller.onAwaitedCommand = { args -> f.files.bytes[args[2]] = byteArrayOf(1); false }
            assertEquals(null, f.reader.requestScreenshot(controller, "Book", "Episode"))
            assertEquals(listOf(f.files.writes.last()), f.files.deletions)
            assertTrue(f.files.bytes.containsKey(prior))
        } finally { f.close() }
    }

    @Test fun thrownCaptureFailureRemovesItsSeedWithoutRetiringOwner() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        val controller = ProfilePlayerServicesTest.Controller()
        controller.onAwaitedCommand = { throw IllegalStateException("Capture failed") }
        try {
            assertFailsWith<IllegalStateException> { f.reader.requestScreenshot(controller, "Book", "Episode") }
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.files.bytes.isEmpty()); assertTrue(f.service.isAvailable)
        } finally { f.close() }
    }

    @Test fun expiryAfterNativeSuccessCannotPublishOrKeepCapturedFile() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        val controller = ProfilePlayerServicesTest.Controller()
        controller.onAwaitedCommand = { args ->
            f.files.bytes[args[2]] = byteArrayOf(1)
            f.reader.retire()
            true
        }
        try {
            assertFailsWith<CancellationException> { f.reader.requestScreenshot(controller, "Book", "Episode") }
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.files.bytes.isEmpty())
        } finally { f.close() }
    }

    @Test fun queueAdmissionAloneCannotReportCaptureSuccess() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        var queued = false
        val fallback = createComposeMediaPlayerController(NoopMediaStreamProxy)
        val queueOnly = object : MediaPlayerController by fallback {
            override val isMpvBackend = true
            override fun executeMpvCommand(vararg arguments: String): Boolean { queued = true; return true }
        }
        try {
            assertEquals(null, f.reader.requestScreenshot(queueOnly, "Book", "Episode"))
            assertFalse(queued)
            assertEquals(f.files.writes, f.files.deletions)
        } finally { fallback.releaseAndJoin(); f.close() }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesTest.kt).

The implementation below defines `ProfilePlayerServicesTest`, `Fixture`, `close`, `Files`, `writeBytes`, `exists`, `deleteRecursively`, `readBytes`, `canonicalPath`, `directorySize` and 20 further declarations.

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

- `alreadyCanceledCallerCannotWriteIntoLiveOwner`
- `configurationUsesCapturedRootAndPreservesExistingUserFiles`
- `disabledConfigurationDoesNotTouchFiles`
- `retirementAfterInventoryCannotWriteConfiguration`
- `readerExpiryBetweenConfigurationFilesStopsFurtherWork`
- `scriptInstallationUsesCapturedFilesAndExistingButtonPolicy`
- `canceledScriptWriteCannotQueueNativeCommand`
- `retirementAfterFirstScriptCommandCannotWriteOrDispatchSecondScript`
- `screenshotUsesCapturedRootAndSanitizesTitlePath`
- `unsupportedScreenshotRemovesOnlyItsSeededFile`
- `screenshotSeedExpiryJoinsCleanupWithoutDispatchingNativeCommand`
- `longTitleScreenshotsRetainUniqueSuffixAndFailedShotCannotDeletePriorShot`
- `proxyRetirementDuringRegistrationRejectsLateUrl`
- `markersUseCapturedHttpAndPreserveAniSkipParsing`
- `canceledMarkerCallerJoinsTransportFinalizer`
- `retiringMarkersCannotDeliverLateResponseOrFailureFallback`
- The remaining 4 cases are included in the complete listing below.

Cross-chapter imports used by this file: [`ProfileId`](../chapters/04-profiles-and-lifetimes.md), [`DbCustomButton`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`LocalFileService`](../chapters/12-local-library.md), [`LocalFileEntry`](../chapters/12-local-library.md), [`LocalEntry`](../chapters/12-local-library.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.media.AniSkipService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.Job
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext

class ProfilePlayerServicesTest {
    @Test fun alreadyCanceledCallerCannotWriteIntoLiveOwner() = runTest {
        val f = Fixture(this)
        val configuration = f.reader.configuration(DbSettings())
        try {
            val caller = async(UnconfinedTestDispatcher(testScheduler)) {
                requireNotNull(currentCoroutineContext()[Job]).cancel()
                assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }
            }
            caller.join()
            assertTrue(f.files.writes.isEmpty())
            assertTrue(f.owner.isActive)
        } finally { f.close() }
    }

    @Test fun configurationUsesCapturedRootAndPreservesExistingUserFiles() = runTest {
        val f = Fixture(this)
        try {
            val configuration = f.reader.configuration(DbSettings(hwdecMode = "custom"))
            assertEquals("/A/cache/mpv", configuration.mpvConfigDirectory)
            assertEquals("custom", configuration.hwdecMode)
            f.files.bytes["/A/cache/mpv/mpv.conf"] = "user config".encodeToByteArray()
            f.reader.prepareConfiguration(configuration)
            assertEquals("user config", f.files.bytes.getValue("/A/cache/mpv/mpv.conf").decodeToString())
            assertEquals(listOf("/A/cache/mpv/input.conf"), f.files.writes)
        } finally { f.close() }
    }

    @Test fun disabledConfigurationDoesNotTouchFiles() = runTest {
        val f = Fixture(this)
        try {
            f.reader.prepareConfiguration(f.reader.configuration(DbSettings(useMpvConfig = false)))
            assertTrue(f.files.writes.isEmpty())
            assertTrue(f.files.existsReads.isEmpty())
        } finally { f.close() }
    }

    @Test fun retirementAfterInventoryCannotWriteConfiguration() = runTest {
        val f = Fixture(this)
        val configuration = f.reader.configuration(DbSettings())
        f.files.onExists = { f.open = false }
        try {
            assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }
            assertTrue(f.files.writes.isEmpty())
            assertTrue(f.owner.isActive)
        } finally { f.close() }
    }

    @Test fun readerExpiryBetweenConfigurationFilesStopsFurtherWork() = runTest {
        val f = Fixture(this)
        val configuration = f.reader.configuration(DbSettings())
        f.files.onWrite = { f.reader.retire() }
        try {
            assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }
            assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.writes)
            assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.existsReads)
        } finally { f.close() }
    }

    @Test fun scriptInstallationUsesCapturedFilesAndExistingButtonPolicy() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        try {
            val button = DbCustomButton(id = 7, title = "Skip", codePress = "aniyomi.seek_by(7)", isFavourite = true, position = 0)
            assertTrue(f.reader.installCustomButtons(controller, listOf(button), f.reader.configuration(DbSettings())))
            assertEquals(listOf(
                listOf("load-script", "/A/cache/mpv/scripts/yokan_chapter_titles.js"),
                listOf("load-script", "/A/cache/mpv/scripts/yokan_custom_buttons.js"),
            ), controller.commands)
            assertTrue("aniyomi.seek_by(7)" in f.files.bytes.getValue(f.files.writes.last()).decodeToString())
        } finally { f.close() }
    }

    @Test fun canceledScriptWriteCannotQueueNativeCommand() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        val configuration = f.reader.configuration(DbSettings())
        f.files.onWrite = { f.reader.retire() }
        try {
            assertFailsWith<CancellationException> { f.reader.installCustomButtons(controller, emptyList(), configuration) }
            assertTrue(controller.commands.isEmpty())
        } finally { f.close() }
    }

    @Test fun retirementAfterFirstScriptCommandCannotWriteOrDispatchSecondScript() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        val configuration = f.reader.configuration(DbSettings())
        controller.onCommand = { f.open = false }
        try {
            assertFailsWith<CancellationException> {
                f.reader.installCustomButtons(controller, listOf(DbCustomButton(id = 1, position = 0)), configuration)
            }
            assertEquals(1, controller.commands.size)
            assertEquals(1, f.files.writes.size)
        } finally { f.close() }
    }

    @Test fun screenshotUsesCapturedRootAndSanitizesTitlePath() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        try {
            val path = requireNotNull(f.reader.requestScreenshot(controller, "../Book/名", "Episode 1"))
            assertTrue(path.startsWith("/A/cache/screenshots/"))
            assertTrue('/' !in path.removePrefix("/A/cache/screenshots/"))
            assertEquals(listOf("sync", "screenshot-to-file", path, "video"), controller.commands.single())
            assertTrue(f.files.bytes.containsKey(path))
        } finally { f.close() }
    }

    @Test fun unsupportedScreenshotRemovesOnlyItsSeededFile() = runTest {
        val f = Fixture(this)
        val controller = Controller().apply { accepted = false }
        try {
            assertEquals(null, f.reader.requestScreenshot(controller, "Book", "Episode"))
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.files.bytes.isEmpty())
        } finally { f.close() }
    }

    @Test fun screenshotSeedExpiryJoinsCleanupWithoutDispatchingNativeCommand() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        f.files.onWrite = { f.reader.retire() }
        try {
            assertFailsWith<CancellationException> { f.reader.requestScreenshot(controller, "Book", "Episode") }
            assertTrue(controller.commands.isEmpty())
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.files.bytes.isEmpty())
        } finally { f.close() }
    }

    @Test fun longTitleScreenshotsRetainUniqueSuffixAndFailedShotCannotDeletePriorShot() = runTest {
        val f = Fixture(this)
        val controller = Controller()
        try {
            val title = "Long title ".repeat(30)
            val first = requireNotNull(f.reader.requestScreenshot(controller, title, "Episode"))
            controller.accepted = false
            assertEquals(null, f.reader.requestScreenshot(controller, title, "Episode"))
            val second = f.files.writes.last()
            assertTrue(first != second)
            assertTrue(f.files.bytes.containsKey(first))
            assertEquals(listOf(second), f.files.deletions)
        } finally { f.close() }
    }

    @Test fun proxyRetirementDuringRegistrationRejectsLateUrl() = runTest {
        val f = Fixture(this)
        f.proxy.onRegister = { f.open = false }
        try {
            assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://stream.test", emptyMap()) }
            assertEquals(listOf("https://stream.test"), f.proxy.urls)
            assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) }
            assertEquals(1, f.proxy.urls.size)
        } finally { f.close() }
    }

    @Test fun markersUseCapturedHttpAndPreserveAniSkipParsing() = runTest {
        val f = Fixture(this)
        try {
            val result = f.reader.markers(42, 12, 1500)
            assertEquals("op", result.single().type)
            assertEquals(90.0, result.single().endSeconds)
            val request = f.http.requests.single()
            assertTrue("/42/12?" in request.url)
            assertTrue("episodeLength=1500" in request.url)
            assertEquals("application/json", request.headers["Accept"])
        } finally { f.close() }
    }

    @Test fun canceledMarkerCallerJoinsTransportFinalizer() = runTest {
        val f = Fixture(this)
        val release = CompletableDeferred<Unit>()
        f.http.response = {
            try { awaitCancellation() }
            finally { withContext(NonCancellable) { release.await() } }
        }
        try {
            val call = async { f.reader.markers(42, 1, 0) }
            runCurrent(); call.cancel(); runCurrent()
            assertFalse(call.isCompleted)
            release.complete(Unit); call.join()
            assertTrue(call.isCancelled)
            assertTrue(f.service.isAvailable)
        } finally { release.complete(Unit); f.close() }
    }

    @Test fun retiringMarkersCannotDeliverLateResponseOrFailureFallback() = runTest {
        val f = Fixture(this)
        val release = CompletableDeferred<Unit>()
        f.http.response = { withContext(NonCancellable) { release.await(); error("late transport failure") } }
        try {
            val call = async { f.reader.markers(42, 1, 0) }
            runCurrent()
            f.open = false
            val close = async { f.service.closeAndJoin() }
            runCurrent()
            assertFalse(close.isCompleted)
            release.complete(Unit); close.await()
            assertFailsWith<CancellationException> { call.await() }
        } finally { release.complete(Unit); f.close() }
    }

    @Test fun foreignConfigurationIsRejectedBeforeFilesOrNativeCommands() = runTest {
        val f = Fixture(this)
        val foreign = MediaPlayerConfiguration(mpvConfigDirectory = "/B/cache/mpv")
        val controller = Controller()
        try {
            assertFailsWith<IllegalArgumentException> { f.reader.prepareConfiguration(foreign) }
            assertFailsWith<IllegalArgumentException> { f.reader.installCustomButtons(controller, emptyList(), foreign) }
            assertTrue(f.files.writes.isEmpty())
            assertTrue(controller.commands.isEmpty())
        } finally { f.close() }
    }

    @Test fun retiredReaderRejectsEveryAuxiliaryEntryPoint() = runTest {
        val f = Fixture(this)
        val configuration = f.reader.configuration(DbSettings())
        val controller = Controller()
        try {
            f.reader.closeAndJoin()
            assertFailsWith<CancellationException> { f.reader.configuration(DbSettings()) }
            assertFailsWith<CancellationException> { f.reader.prepareConfiguration(configuration) }
            assertFailsWith<CancellationException> { f.reader.installCustomButtons(controller, emptyList(), configuration) }
            assertFailsWith<CancellationException> { f.reader.markers(42, 1, 0) }
            assertFailsWith<CancellationException> { f.reader.requestScreenshot(controller, "Book", "Episode") }
            assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A")) }
            assertTrue(f.files.writes.isEmpty())
            assertTrue(f.http.requests.isEmpty())
            assertTrue(f.proxy.urls.isEmpty())
            assertTrue(f.owner.isActive)
        } finally { f.close() }
    }

    @Test fun stoppingOldProxyHandleCannotStopSiblingOrSharedProxy() = runTest {
        val f = Fixture(this)
        try {
            val current = f.service.reader()
            f.reader.streamProxy.stop()
            assertEquals("proxy:https://stream.test", current.streamProxy.proxyUrl("https://stream.test", mapOf("Referer" to "A")))
            assertEquals(0, f.proxy.stops)
            assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("https://late.test", emptyMap()) }
        } finally { f.close() }
    }

    @Test fun independentServicesKeepTheirOwnFilesAndProxyAndPreserveParentsOnClose() = runTest {
        val a = Fixture(this, "A")
        val b = Fixture(this, "B")
        try {
            a.reader.prepareConfiguration(a.reader.configuration(DbSettings()))
            b.reader.prepareConfiguration(b.reader.configuration(DbSettings()))
            a.service.closeAndJoin()
            assertTrue(a.owner.isActive)
            assertFailsWith<CancellationException> { a.reader.configuration(DbSettings()) }
            assertEquals("/B/cache/mpv", b.reader.configuration(DbSettings()).mpvConfigDirectory)
            assertEquals("proxy:B", b.reader.streamProxy.proxyUrl("B", emptyMap()))
            assertTrue(a.files.writes.all { it.startsWith("/A/") })
            assertTrue(b.files.writes.all { it.startsWith("/B/") })
        } finally { a.close(); b.close() }
    }

    internal class Fixture(test: TestScope, label: String = "A", dispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler),
        factory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController) {
        val owner = SupervisorJob()
        var open = true
        val files = Files(label)
        val http = Http()
        val proxy = Proxy()
        val service = ProfilePlayerServices(ProfileId.Default, files, AniSkipService(http), proxy,
            CoroutineScope(owner + StandardTestDispatcher(test.testScheduler)), dispatcher, factory) { open }
        val reader = service.reader()
        suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() }
    }
    internal class Files(label: String) : LocalFileService {
        override val downloadRoot = "/$label/downloads"
        override val backupRoot = "/$label/backups"
        override val cacheRoot = "/$label/cache"
        val bytes = mutableMapOf<String, ByteArray>()
        val writes = mutableListOf<String>()
        val deletions = mutableListOf<String>()
        val existsReads = mutableListOf<String>()
        var onWrite: (String) -> Unit = { }
        var onExists: (String) -> Unit = { }
        override fun writeBytes(path: String, bytes: ByteArray) { writes += path; this.bytes[path] = bytes; onWrite(path) }
        override fun exists(path: String): Boolean { existsReads += path; onExists(path); return bytes.containsKey(path) }
        override fun deleteRecursively(path: String): Boolean { deletions += path; return bytes.remove(path) != null }
        override fun readBytes(path: String) = bytes.getValue(path)
        override fun canonicalPath(path: String): String = path
        override fun directorySize(path: String): Long = 0
        override fun openLocation(path: String): Boolean = false
        override fun listLocalEntries(root: String): List<LocalEntry> = emptyList()
        override fun listFiles(root: String): List<LocalFileEntry> = emptyList()
    }
    internal class Http : HttpService {
        val requests = mutableListOf<HttpRequest>()
        var response: suspend () -> HttpResponse = {
            HttpResponse(statusCode = 200, body = """{"found":true,"results":[{"skipType":"op","interval":{"startTime":0,"endTime":90},"episodeLength":1500}]}""")
        }
        override suspend fun request(request: HttpRequest): HttpResponse { requests += request; return response() }
    }
    internal class Proxy : MediaStreamProxy {
        val urls = mutableListOf<String>()
        var stops = 0
        var onRegister: () -> Unit = { }
        override fun proxyUrl(url: String, headers: Map<String, String>): String { urls += url; onRegister(); return "proxy:$url" }
        override fun stop() { stops++ }
    }
    internal class Controller : MediaPlayerController {
        override val isMpvBackend = true
        val commands = mutableListOf<List<String>>()
        var accepted = true
        var onCommand: () -> Unit = { }
        var onAwaitedCommand: suspend (List<String>) -> Boolean = { true }
        override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
        override fun play() = Unit
        override fun pause() = Unit
        override fun seekTo(positionMs: Long) = Unit
        override fun setPlaybackSpeed(speed: Float) = Unit
        override fun executeMpvCommand(vararg arguments: String): Boolean { commands += arguments.toList(); onCommand(); return accepted }
        override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean =
            executeMpvCommand(*arguments) && onAwaitedCommand(arguments.toList())
        override fun release() = Unit
        override fun currentPositionMs(): Long = 0
        override fun durationMs(): Long = 0
        override fun isPlaying(): Boolean = false
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreamsTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreamsTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/torrent/TorrentStreamsTest.kt).

The implementation below defines `FakeTorrServer`, `route`, `FakeHost`, `executable`, `install`, `ensureRunning`, `stop`, `TorrentStreamsTest`, `configure`, `streams` and 10 further declarations.

The source describes its contract as:

> TorrServer API fixture: `add` returns before metadata, `get` exposes files after \[getsBeforeFiles\] polls.

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

- `hostlessPlatformsUseTheRemoteServerAndListEachVideoFile`
- `trackerListIsPushedOnceIntoTheFullServerSettings`
- `animetailIndexSelectsOneFileAndLocalTorrentFilesAreUploaded`
- `managedModeStartsTheHostWithProxyOptionsAndRemoteModeStopsIt`
- `proxyModeWithoutUrlLaunchesWithoutProxy`
- `disabledEngineDropsTorrentVideosAndFailsTorrentOnlyResults`
- `enabledEngineExpandsSourceTorrentsKeepingTheirTracks`
- `serverErrorsAndOldServersAreReported`
- `missingMetadataTimesOut`

Cross-chapter imports used by this file: [`DbTorrentPreferences`](../chapters/02-domain-and-settings-models.md), [`DbVideo`](../chapters/02-domain-and-settings-models.md), [`InMemoryYokanDatabase`](../chapters/03-persistence-and-migrations.md), [`MemoryVideoFiles`](../chapters/12-local-library.md), [`MockTrackerHttp`](../chapters/19-metadata-discovery-and-trackers.md), [`RecordedRequest`](../chapters/19-metadata-discovery-and-trackers.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.torrent

import eu.friedcutlet.yokan.database.DbTorrentPreferences
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.TorrServerMode
import eu.friedcutlet.yokan.database.TorrServerProxyMode
import eu.friedcutlet.yokan.services.library.MemoryVideoFiles
import eu.friedcutlet.yokan.services.tracking.MockTrackerHttp
import eu.friedcutlet.yokan.services.tracking.RecordedRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

private const val Hash = "4c811ca573a16a00f742512f58900609b2de4190"
private const val Magnet = "magnet:?xt=urn:btih:$Hash&dn=Show"
private const val Files = """[{"id":1,"path":"Show/Show - 01.mkv","length":10},{"id":2,"path":"Show/Show - 02 [x].mkv","length":10},{"id":3,"path":"Show/info.nfo","length":1}]"""

/** TorrServer API fixture: `add` returns before metadata, `get` exposes files after [getsBeforeFiles] polls. */
private class FakeTorrServer(
    var getsBeforeFiles: Int = 1,
    val settings: String = """{"CacheSize":67108864,"DefaultTrackers":"old","RetrackersMode":0}""",
) {
    var gets = 0
    val http = MockTrackerHttp(::route)
    val requests get() = http.requests

    fun route(request: RecordedRequest): Pair<Int, String> {
        val body = request.body.takeIf { it.startsWith("{") }?.let { Json.parseToJsonElement(it).jsonObject }
        return when {
            request.url.endsWith("/echo") -> 200 to "MatriX.147"
            request.url.endsWith("/settings") -> if (body!!["action"]!!.jsonPrimitive.content == "get") 200 to settings else 200 to ""
            request.url.endsWith("/torrent/upload") -> 200 to """{"title":"Uploaded","hash":"$Hash","file_stats":[{"id":1,"path":"movie.mp4","length":5}]}"""
            body?.get("action")?.jsonPrimitive?.content == "add" ->
                if (body["link"]!!.jsonPrimitive.content.startsWith("magnet:")) 200 to """{"title":"Show","hash":"$Hash","stat_string":"Torrent getting info"}"""
                else 400 to """{"error":"error parse link: bad"}"""
            body?.get("action")?.jsonPrimitive?.content == "get" ->
                200 to if (gets++ < getsBeforeFiles) """{"title":"Show","hash":"$Hash"}""" else """{"title":"Show","hash":"$Hash","file_stats":$Files}"""
            else -> 404 to ""
        }
    }
}

private class FakeHost : TorrServerHost {
    override val status = MutableStateFlow("Stopped")
    val launches = mutableListOf<TorrServerLaunch>()
    var stops = 0
    override fun executable(userPath: String) = "/bin/TorrServer"
    override suspend fun install(onProgress: (Long, Long) -> Unit) = "/bin/TorrServer"
    override suspend fun ensureRunning(launch: TorrServerLaunch): String { launches += launch; return "http://127.0.0.1:${launch.port}" }
    override suspend fun stop() { stops++ }
}

class TorrentStreamsTest {
    private val database = InMemoryYokanDatabase()
    private val files = MemoryVideoFiles()

    private fun configure(prefs: DbTorrentPreferences) =
        database.updateSettings(database.settings().let { it.copy(features = it.features.copy(torrent = prefs)) })

    private fun streams(server: FakeTorrServer, host: TorrServerHost? = null) =
        TorrentStreams(database, server.http.http, files, host, pollMillis = 1, metadataTimeoutMillis = 5_000)

    private val remote = DbTorrentPreferences(enabled = true, remoteUrl = "http://ts.lan:8090/", username = "user", password = "pass")

    @Test
    fun hostlessPlatformsUseTheRemoteServerAndListEachVideoFile() = realTime {
        configure(remote) // Managed is the default mode; without a host it means the remote server.
        val server = FakeTorrServer()
        val videos = streams(server).videos(Magnet, "Show")

        assertEquals(listOf("Show - 01.mkv", "Show - 02 [x].mkv"), videos.map(DbVideo::quality))
        assertEquals("http://ts.lan:8090/stream/Show%20-%2001.mkv?link=$Hash&index=1&play", videos[0].url)
        assertEquals("http://ts.lan:8090/stream/Show%20-%2002%20%5Bx%5D.mkv?link=$Hash&index=2&play", videos[1].url)
        assertTrue(videos.all { it.originalUrl == Magnet && it.headers == null })
        assertTrue(server.requests.all { it.headers["Authorization"] == "Basic dXNlcjpwYXNz" })
        assertEquals(2, server.gets) // polled until metadata arrived
    }

    @Test
    fun trackerListIsPushedOnceIntoTheFullServerSettings() = realTime {
        configure(remote.copy(trackers = " udp://a:1/announce \n\nhttp://b/announce\n"))
        val server = FakeTorrServer(getsBeforeFiles = 0)
        val streams = streams(server)
        streams.videos(Magnet, "Show")
        streams.videos(Magnet, "Show")

        val sets = server.requests.filter { it.url.endsWith("/settings") }
        assertEquals(2, sets.size)
        val pushed = Json.parseToJsonElement(sets[1].body).jsonObject
        assertEquals("set", pushed["action"]!!.jsonPrimitive.content)
        val values = pushed["sets"]!!.jsonObject
        assertEquals("udp://a:1/announce\nhttp://b/announce", values["DefaultTrackers"]!!.jsonPrimitive.content)
        assertEquals(1, values["RetrackersMode"]!!.jsonPrimitive.int)
        assertEquals(67108864, values["CacheSize"]!!.jsonPrimitive.int) // `set` replaces everything: other fields survive

        streams.applySettings() // explicit reset/check pushes again
        assertEquals(4, server.requests.count { it.url.endsWith("/settings") })
    }

    @Test
    fun animetailIndexSelectsOneFileAndLocalTorrentFilesAreUploaded() = realTime {
        configure(remote)
        val server = FakeTorrServer(getsBeforeFiles = 0)
        val one = streams(server).videos("$Magnet&index=2", "Show")
        assertEquals(listOf("Show - 02 [x].mkv"), one.map(DbVideo::quality))

        files.put("/media/movie.torrent", "d4:infod4:name5:movieee".encodeToByteArray())
        val uploaded = streams(server).videos("/media/movie.torrent", "Movie")
        assertEquals(listOf("http://ts.lan:8090/stream/movie.mp4?link=$Hash&index=1&play"), uploaded.map(DbVideo::url))
        val upload = server.requests.single { it.url.endsWith("/torrent/upload") }
        assertTrue(upload.headers["Content-Type"]!!.startsWith("multipart/form-data; boundary="))
    }

    @Test
    fun managedModeStartsTheHostWithProxyOptionsAndRemoteModeStopsIt() = realTime {
        val host = FakeHost()
        configure(DbTorrentPreferences(enabled = true, port = 9123, proxyMode = TorrServerProxyMode.Full, proxyUrl = "socks5://p:1080"))
        val server = FakeTorrServer(getsBeforeFiles = 0)
        val videos = streams(server, host).videos(Magnet, "Show")
        assertEquals(TorrServerLaunch(9123, "", "full", "socks5://p:1080"), host.launches.single())
        assertTrue(videos.first().url.startsWith("http://127.0.0.1:9123/stream/"))
        assertTrue(server.requests.none { "Authorization" in it.headers })

        configure(remote.copy(mode = TorrServerMode.Remote))
        streams(server, host).videos(Magnet, "Show")
        assertEquals(1, host.stops)
        assertEquals(1, host.launches.size)
    }

    @Test
    fun proxyModeWithoutUrlLaunchesWithoutProxy() {
        assertEquals(null, DbTorrentPreferences(proxyMode = TorrServerProxyMode.Peers).launch().proxyMode)
    }

    @Test
    fun disabledEngineDropsTorrentVideosAndFailsTorrentOnlyResults() = realTime {
        val server = FakeTorrServer()
        val streams = streams(server)
        val http = DbVideo(url = "https://cdn/video.mp4", quality = "720p", originalUrl = "")
        val torrent = DbVideo(url = Magnet, quality = "1080p", originalUrl = "")

        assertEquals(listOf(http), streams.expand(listOf(torrent, http), "Show"))
        assertTrue(assertFailsWith<IllegalStateException> { streams.expand(listOf(torrent), "Show") }.message!!.contains("Enable TorrServer"))
        assertTrue(assertFailsWith<IllegalStateException> { streams.videos(Magnet, "Show") }.message!!.contains("off"))
        assertTrue(server.requests.isEmpty())
    }

    @Test
    fun enabledEngineExpandsSourceTorrentsKeepingTheirTracks() = realTime {
        configure(remote)
        val streams = streams(FakeTorrServer(getsBeforeFiles = 0))
        val subtitle = eu.friedcutlet.yokan.database.DbVideoTrack("https://cdn/sub.ass", "English")
        val expanded = streams.expand(listOf(DbVideo(url = Magnet, quality = "1080p", originalUrl = "", subtitles = listOf(subtitle))), "Show")
        assertEquals(listOf("1080p · Show - 01.mkv", "1080p · Show - 02 [x].mkv"), expanded.map(DbVideo::quality))
        assertTrue(expanded.all { it.subtitles == listOf(subtitle) })
    }

    @Test
    fun serverErrorsAndOldServersAreReported() = realTime {
        configure(remote)
        val error = assertFailsWith<TorrServerException> { streams(FakeTorrServer()).videos("https://bad/x.torrent", "X") }
        assertEquals(400, error.status)
        assertTrue(error.message!!.contains("error parse link: bad"))

        val old = FakeTorrServer(settings = """{"CacheSize":1}""")
        assertTrue(assertFailsWith<IllegalStateException> { streams(old).videos(Magnet, "Show") }.message!!.contains("tracker lists"))
        assertTrue(old.requests.none { "\"set\"" in it.body })

        configure(remote.copy(remoteUrl = "ts.lan"))
        assertTrue(assertFailsWith<IllegalStateException> { streams(FakeTorrServer()).videos(Magnet, "Show") }.message!!.contains("remote TorrServer URL"))
    }

    @Test
    fun missingMetadataTimesOut() = realTime {
        configure(remote)
        val server = FakeTorrServer(getsBeforeFiles = Int.MAX_VALUE)
        val streams = TorrentStreams(database, server.http.http, files, null, pollMillis = 5, metadataTimeoutMillis = 100)
        val error = runCatching { streams.videos(Magnet, "Show") }.exceptionOrNull()
        assertTrue(error is IllegalStateException && error.message!!.contains("no metadata"), "$error")
    }
}

/** The Ktor engine answers on real threads; virtual time would fire the metadata timeout at once. */
private fun realTime(block: suspend () -> Unit) = runTest { withContext(Dispatchers.Default) { block() } }
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBindingTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBindingTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiBindingTest.kt).

The implementation below defines `PlayerUiBindingTest`, `collect`, `controller`.

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

- `bridgeDeliveryUsesCapturedUiContextAndExpiresOnClose`
- `readerDeliveryRetainsCallersContextAcrossOwnedCollection`
- `disposedBindingJoinsFinalizerAndRejectsItsLateEvent`
- `callerCancellationJoinsCollectionWithoutCancelingSiblingBinding`
- `sessionRetirementJoinsBridgeFinalizerBeforeReturning`
- `inactiveOrExpiredBindingsCannotSubscribe`
- `alreadyCanceledCallerCannotSubscribeIntoLiveBinding`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, kotlinx.coroutines.InternalCoroutinesApi::class)

package eu.friedcutlet.yokan.ui.screens.player

import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvBridgeEvent
import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServicesTest
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PlayerUiBindingTest {
    @Test fun bridgeDeliveryUsesCapturedUiContextAndExpiresOnClose() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob()
        val events = MutableSharedFlow<MpvBridgeEvent>(); val delivered = mutableListOf<MpvBridgeEvent>()
        val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler) + CoroutineName("captured-ui")))
        val collect = async { binding.collectBridgeEvents {
            delivered += it
        } }
        try {
            runCurrent(); assertEquals(1, events.subscriptionCount.value)
            events.emit(Event); runCurrent(); assertEquals(listOf(Event), delivered)
            binding.close(); collect.join(); events.emit(Event)
            assertEquals(listOf(Event), delivered); assertEquals(0, events.subscriptionCount.value)
            assertTrue(parent.isActive); assertTrue(f.service.isAvailable)
        } finally { binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() }
    }

    @Test fun readerDeliveryRetainsCallersContextAcrossOwnedCollection() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this)
        var deliveredContext: String? = null
        val source = flow { emit(Event); awaitCancellation() }
        val collect = async(CoroutineName("captured-ui")) {
            f.reader.collectBridgeEvents(controller(source)) { deliveredContext = currentCoroutineContext()[CoroutineName]?.name }
        }
        try { runCurrent(); assertEquals("captured-ui", deliveredContext) }
        finally { collect.cancelAndJoin(); f.close() }
    }

    @Test fun disposedBindingJoinsFinalizerAndRejectsItsLateEvent() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred<Unit>()
        val delivered = mutableListOf<MpvBridgeEvent>(); var rejectedLate = false
        val source = object : Flow<MpvBridgeEvent> {
            override suspend fun collect(collector: FlowCollector<MpvBridgeEvent>) {
                collector.emit(Event)
                try { awaitCancellation() }
                finally { withContext(NonCancellable) {
                    finish.await()
                    try { collector.emit(Event.copy(value = "late")) } catch (_: CancellationException) { rejectedLate = true }
                } }
            }
        }
        val binding = PlayerUiBinding(f.reader, controller(source), CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        val collect = async { binding.collectBridgeEvents { delivered += it } }
        try {
            runCurrent(); binding.close(); runCurrent()
            assertFalse(collect.isCompleted); assertFalse(binding.active()); assertTrue(parent.isActive)
            finish.complete(Unit); collect.join()
            assertEquals(listOf(Event), delivered); assertTrue(rejectedLate)
        } finally { finish.complete(Unit); binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() }
    }

    @Test fun callerCancellationJoinsCollectionWithoutCancelingSiblingBinding() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred<Unit>()
        val uiScope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val source = flow<MpvBridgeEvent> { try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() } } }
        val first = PlayerUiBinding(f.reader, controller(source), uiScope)
        val events = MutableSharedFlow<MpvBridgeEvent>(); val delivered = mutableListOf<MpvBridgeEvent>()
        val sibling = PlayerUiBinding(f.reader, controller(events), uiScope)
        val a = async { first.collectBridgeEvents { } }; val b = async { sibling.collectBridgeEvents { delivered += it } }
        try {
            runCurrent(); a.cancel(); runCurrent(); assertFalse(a.isCompleted)
            events.emit(Event); runCurrent(); assertEquals(listOf(Event), delivered); assertTrue(sibling.active())
            finish.complete(Unit); a.join(); assertTrue(first.active()); assertTrue(parent.isActive)
        } finally { finish.complete(Unit); first.close(); sibling.close(); a.cancelAndJoin(); b.cancelAndJoin(); parent.cancelAndJoin(); f.close() }
    }

    @Test fun sessionRetirementJoinsBridgeFinalizerBeforeReturning() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred<Unit>()
        val source = flow<MpvBridgeEvent> { try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() } } }
        val binding = PlayerUiBinding(f.reader, controller(source), CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        val collect = async { binding.collectBridgeEvents { } }
        try {
            runCurrent(); val close = async { f.service.closeAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertFalse(collect.isCompleted); assertFalse(binding.active())
            finish.complete(Unit); close.await(); collect.join()
            assertTrue(parent.isActive); assertTrue(f.owner.isActive)
        } finally { finish.complete(Unit); binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() }
    }

    @Test fun inactiveOrExpiredBindingsCannotSubscribe() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); var active = false
        val events = MutableSharedFlow<MpvBridgeEvent>()
        val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { active }
        try {
            binding.collectBridgeEvents { error("Inactive delivery") }; assertEquals(0, events.subscriptionCount.value)
            active = true; f.reader.retire()
            binding.collectBridgeEvents { error("Expired delivery") }; assertEquals(0, events.subscriptionCount.value)
        } finally { binding.close(); parent.cancelAndJoin(); f.close() }
    }

    @Test fun alreadyCanceledCallerCannotSubscribeIntoLiveBinding() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob()
        val events = MutableSharedFlow<MpvBridgeEvent>()
        val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        try {
            val call = async(UnconfinedTestDispatcher(testScheduler)) {
                requireNotNull(currentCoroutineContext()[Job]).cancel()
                assertFailsWith<CancellationException> { binding.collectBridgeEvents { } }
            }
            call.join(); assertEquals(0, events.subscriptionCount.value); assertTrue(binding.active())
        } finally { binding.close(); parent.cancelAndJoin(); f.close() }
    }

    companion object {
        val Event = MpvBridgeEvent("aniyomi/switch_episode", "n")
        fun controller(events: Flow<MpvBridgeEvent>): MediaPlayerController = object : MediaPlayerController by ProfilePlayerServicesTest.Controller() {
            override val mpvBridgeEvents = events
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModelTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModelTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModelTest.kt).

The implementation below defines `PlayerViewModelTest`, `tearDown`, `episode`, `viewModel`, `CoroutineScope.effectsOf`, `loadingSelectsTheFirstStreamAtTheSavedPosition`, `failedOrEmptyLoadsReportAnErrorWithoutAStream`, `playbackFailureSwitchesToEachRemainingStreamOnceThenReports`, `playbackFailureWithoutFailoverOnlyReports`, `castingQueuesThisEpisodeThenTheNextTwoInTitleOrder` and 15 further declarations.

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

- `loadingSelectsTheFirstStreamAtTheSavedPosition`
- `failedOrEmptyLoadsReportAnErrorWithoutAStream`
- `playbackFailureSwitchesToEachRemainingStreamOnceThenReports`
- `playbackFailureWithoutFailoverOnlyReports`
- `castingQueuesThisEpisodeThenTheNextTwoInTitleOrder`
- `castingStreamsThatNeedHeadersIsRefused`

Cross-chapter imports used by this file: [`DefaultYokanRepository`](../chapters/09-repository-and-library.md), [`LibraryIndexStore`](../chapters/09-repository-and-library.md), [`SettingsStore`](../chapters/09-repository-and-library.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.database.withPlayer
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.testManga
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.cast.CastController
import eu.friedcutlet.yokan.services.media.cast.CastDevice
import eu.friedcutlet.yokan.services.media.cast.CastMedia
import eu.friedcutlet.yokan.services.media.cast.CastStatus
import eu.friedcutlet.yokan.services.media.cast.CastTextStyle
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest

class PlayerViewModelTest {
    private val database = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Show", link = "/s", source = "Src", itemType = DbItemType.Anime, favorite = true)),
            chapters = (1L..5L).map { DbChapter(id = it, mangaId = 1, url = "/e$it", name = "Episode $it") },
        ),
    )
    private val repository = DefaultYokanRepository(database)
    private val host = ViewModelTestHost()
    private val manga = testManga(1, name = "Show", itemType = ItemType.Anime)
    private val noHttp = HttpService { error("no seek previews in these tests") }
    private val cast = RecordingCast()
    private val sd = DbVideo(url = "https://cdn.example/sd.m3u8", quality = "480p", originalUrl = "")
    private val hd = DbVideo(url = "https://cdn.example/hd.m3u8", quality = "1080p", originalUrl = "")

    @AfterTest
    fun tearDown() = host.close()

    private fun episode(id: Long, lastPageRead: String = "") =
        Chapter(id = id, mangaId = 1, name = "Episode $id", url = "/e$id", lastPageRead = lastPageRead)

    private fun viewModel(
        scope: CoroutineScope,
        chapter: Chapter = episode(3),
        settings: SettingsStore = SettingsStore(repository, scope, onSchedulingChanged = {}),
        loadVideos: suspend (Source?, Chapter) -> List<DbVideo>,
    ): PlayerViewModel = host.create {
        PlayerViewModel(
            manga = manga,
            chapter = chapter,
            repository = repository,
            settings = settings,
            libraryIndex = LibraryIndexStore(repository, scope),
            http = noHttp,
            loadVideos = loadVideos,
            aniSkipMarkers = { _, _ -> emptyList() },
            openExternalPlayer = { _, _ -> false },
            cast = cast,
            workDispatcher = host.dispatcher,
        )
    }

    private fun CoroutineScope.effectsOf(vm: PlayerViewModel): List<PlayerEffect> =
        mutableListOf<PlayerEffect>().also { effects -> launch(host.dispatcher) { vm.effects.collect { effects += it } } }

    @Test
    fun loadingSelectsTheFirstStreamAtTheSavedPosition() = runTest {
        val requested = mutableListOf<Long>()
        val vm = viewModel(backgroundScope, chapter = episode(3, lastPageRead = "65000")) { _, chapter ->
            requested += chapter.id
            listOf(sd, hd)
        }

        val loaded = vm.state.first { !it.loading }

        assertEquals(listOf(3L), requested)
        assertEquals(listOf(sd, hd), loaded.videos)
        assertEquals(sd, loaded.selectedVideo)
        assertEquals(65_000L, loaded.startPositionMs)
        assertTrue(loaded.autoplay)
        assertNull(loaded.error)
    }

    @Test
    fun failedOrEmptyLoadsReportAnErrorWithoutAStream() = runTest {
        val failed = viewModel(backgroundScope) { _, _ -> error("extension crashed") }.state.first { !it.loading }
        val empty = viewModel(backgroundScope) { _, _ -> emptyList() }.state.first { !it.loading }

        assertEquals("extension crashed", failed.error)
        assertNull(failed.selectedVideo)
        assertEquals("No streams were returned by this source.", empty.error)
        assertNull(empty.selectedVideo)
    }

    @Test
    fun playbackFailureSwitchesToEachRemainingStreamOnceThenReports() = runTest {
        val settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {})
        settings.updateDb { db -> db.withPlayer { it.copy(switchStreamOnFailure = true) } }
        val vm = viewModel(backgroundScope, settings = settings) { _, _ -> listOf(sd, hd) }
        val effects = backgroundScope.effectsOf(vm)
        vm.state.first { !it.loading }

        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000))
        val switched = vm.state.value
        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 50_000))

        assertEquals(hd, switched.selectedVideo)
        assertEquals(42_000L, switched.startPositionMs)
        assertEquals(hd, vm.state.value.selectedVideo)
        assertEquals(
            listOf(
                PlayerEffect.ShowNotice("Stream failed; switching to 1080p"),
                PlayerEffect.ShowNotice("Playback failed: decoder"),
            ),
            effects,
        )
    }

    @Test
    fun playbackFailureWithoutFailoverOnlyReports() = runTest {
        val vm = viewModel(backgroundScope) { _, _ -> listOf(sd, hd) }
        val effects = backgroundScope.effectsOf(vm)
        vm.state.first { !it.loading }

        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000))

        assertEquals(sd, vm.state.value.selectedVideo)
        assertEquals(listOf(PlayerEffect.ShowNotice("Playback failed: decoder")), effects)
    }

    @Test
    fun castingQueuesThisEpisodeThenTheNextTwoInTitleOrder() = runTest {
        val vm = viewModel(backgroundScope) { _, chapter ->
            listOf(DbVideo(url = "https://cdn.example/${chapter.id}.mp4", quality = "720p", originalUrl = ""))
        }
        val episodes = vm.state.first { !it.loading && it.episodes.size == 5 }.episodes.map { it.id }
        val following = episodes.dropWhile { it != 3L }.drop(1).take(2)

        vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 12_000, subtitleFile = null))

        assertEquals(2, following.size)
        assertEquals(listOf("connect"), cast.calls)
        assertEquals(listOf("3"), cast.loaded.map { it.itemKey })
        assertEquals(12_000L, cast.loadedAtMs)
        assertEquals(following.map { it.toString() }, cast.appended.map { it.itemKey })
    }

    @Test
    fun castingStreamsThatNeedHeadersIsRefused() = runTest {
        val vm = viewModel(backgroundScope) { _, _ -> listOf(sd.copy(headers = mapOf("Referer" to "x"))) }
        val effects = backgroundScope.effectsOf(vm)
        vm.state.first { !it.loading }

        vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 0, subtitleFile = null))

        assertTrue(cast.calls.isEmpty())
        assertEquals(
            listOf(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast")),
            effects,
        )
    }

    private class RecordingCast : CastController {
        val calls = mutableListOf<String>()
        val loaded = mutableListOf<CastMedia>()
        val appended = mutableListOf<CastMedia>()
        var loadedAtMs = -1L
        override val isSupported = MutableStateFlow(true)
        override val usesSystemPicker = false
        override val devices = MutableStateFlow(emptyList<CastDevice>())
        override val status = MutableStateFlow<CastStatus?>(null)
        override fun startDiscovery() { calls += "discover" }
        override fun stopDiscovery() { calls += "stop-discovery" }
        override suspend fun connect(device: CastDevice?) { calls += "connect" }
        override suspend fun loadQueue(
            items: List<CastMedia>,
            startIndex: Int,
            startPositionMs: Long,
            style: CastTextStyle,
            activeSubtitleIndex: Int?,
        ) {
            loaded += items
            loadedAtMs = startPositionMs
        }
        override suspend fun append(items: List<CastMedia>) { appended += items }
        override fun play() = Unit
        override fun pause() = Unit
        override fun seekTo(positionMs: Long) = Unit
        override fun next() = Unit
        override fun previous() = Unit
        override fun jumpTo(index: Int) = Unit
        override suspend fun disconnect() { calls += "disconnect" }
        override fun close() = Unit
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/VideoResumeTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/VideoResumeTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/VideoResumeTest.kt).

The implementation below defines `VideoResumeTest`, `savedElapsedMillisecondsAreRestored`, `completedIncognitoAndMissingHistoryStartAtZero`, `completedEpisodesStayCompleteWhileUnknownDurationProgressStillSaves`, `qualitySwitchKeepsCurrentPositionAndPlaybackIntent`, `savedElapsedMillisecondsRenderAsEpisodeTimestamp`.

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

- `savedElapsedMillisecondsAreRestored`
- `completedIncognitoAndMissingHistoryStartAtZero`
- `completedEpisodesStayCompleteWhileUnknownDurationProgressStillSaves`
- `qualitySwitchKeepsCurrentPositionAndPlaybackIntent`
- `savedElapsedMillisecondsRenderAsEpisodeTimestamp`

Cross-chapter imports used by this file: [`formatAnimeProgress`](../chapters/11-browse-detail-and-migration.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.player

import eu.friedcutlet.yokan.ui.screens.detail.formatAnimeProgress
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class VideoResumeTest {
    @Test
    fun savedElapsedMillisecondsAreRestored() {
        assertEquals(
            75_432L,
            savedVideoPositionMs(
                lastPageRead = "75432",
                isRead = false,
                incognitoMode = false,
            ),
        )
    }

    @Test
    fun completedIncognitoAndMissingHistoryStartAtZero() {
        assertEquals(0L, savedVideoPositionMs("75432", isRead = true, incognitoMode = false))
        assertEquals(0L, savedVideoPositionMs("75432", isRead = false, incognitoMode = true))
        assertEquals(0L, savedVideoPositionMs("", isRead = false, incognitoMode = false))
        assertEquals(0L, savedVideoPositionMs("75%", isRead = false, incognitoMode = false))
    }

    @Test
    fun completedEpisodesStayCompleteWhileUnknownDurationProgressStillSaves() {
        assertFalse(
            shouldSaveVideoPosition(
                isRead = true,
                incognitoMode = false,
                positionMs = 120_000L,
            ),
        )
        assertTrue(
            shouldSaveVideoPosition(
                isRead = false,
                incognitoMode = false,
                positionMs = 120_000L,
            ),
        )
        assertFalse(
            isVideoPositionComplete(
                positionMs = 120_000L,
                durationMs = 0L,
                seenThresholdPercent = 85,
            ),
        )
    }
    @Test
    fun qualitySwitchKeepsCurrentPositionAndPlaybackIntent() {
        assertEquals(
            VideoHandoff(startPositionMs = 120_000L, autoplay = false),
            qualityVideoHandoff(currentPositionMs = 120_000L, isPlaying = false),
        )
        assertEquals(
            VideoHandoff(startPositionMs = 120_000L, autoplay = true),
            qualityVideoHandoff(currentPositionMs = 120_000L, isPlaying = true),
        )
    }


    @Test
    fun savedElapsedMillisecondsRenderAsEpisodeTimestamp() {
        assertEquals("0:01:15", formatAnimeProgress(75_432L))
        assertEquals("1:01:01", formatAnimeProgress(3_661_000L))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractorTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractorTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/KwikExtractorTest.kt).

The implementation below defines `KwikExtractorTest`, `skipsPackedScriptsWithoutAStream`, `scansPackedEvaluationsFromLastToFirst`, `retriesMissingStreamThroughCloudflareResolver`, `packedScript`, `packedEval`, `QueueHttpService`, `request`.

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

- `skipsPackedScriptsWithoutAStream`
- `scansPackedEvaluationsFromLastToFirst`
- `retriesMissingStreamThroughCloudflareResolver`

Cross-chapter imports used by this file: [`HttpRequest`](../chapters/05-http-cookies-and-webviews.md), [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking

class KwikExtractorTest {
    @Test
    fun skipsPackedScriptsWithoutAStream() = runBlocking {
        val masterUrl = "https://cdn.example/master.m3u8"
        val http = QueueHttpService(
            HttpResponse(
                statusCode = 200,
                body = packedScript("cookie", "ignored") + packedScript("source", masterUrl),
            ),
            HttpResponse(statusCode = 500, body = ""),
        )

        val videos = KwikExtractor(http).extractHls("https://kwik.cx/e/example", emptyMap())

        assertEquals(masterUrl, videos.single().url)
        assertEquals("iframe", http.requests.first().headers["Sec-Fetch-Dest"])
        assertEquals("cross-site", http.requests.first().headers["Sec-Fetch-Site"])
    }

    @Test
    fun scansPackedEvaluationsFromLastToFirst() = runBlocking {
        val masterUrl = "https://cdn.example/master.m3u8"
        val http = QueueHttpService(
            HttpResponse(
                statusCode = 200,
                body = "<script>${packedEval("cookie", "ignored")};${packedEval("source", masterUrl)}</script>",
            ),
            HttpResponse(statusCode = 500, body = ""),
        )

        val videos = KwikExtractor(http).extractHls("https://kwik.cx/e/example", emptyMap())

        assertEquals(masterUrl, videos.single().url)
    }

    @Test
    fun retriesMissingStreamThroughCloudflareResolver() = runBlocking {
        val masterUrl = "https://cdn.example/master.m3u8"
        val http = QueueHttpService(
            HttpResponse(statusCode = 200, body = packedScript("cookie", "ignored")),
            HttpResponse(statusCode = 200, body = packedScript("source", masterUrl)),
            HttpResponse(statusCode = 500, body = ""),
        )

        val videos = KwikExtractor(http).extractHls("https://kwik.cx/e/example", emptyMap())

        assertEquals(masterUrl, videos.single().url)
        assertTrue(http.requests[1].headers["X-Yokan-Resolve-Cloudflare"] == "1")
    }

    private fun packedScript(name: String, value: String): String = "<script>${packedEval(name, value)}</script>"

    private fun packedEval(name: String, value: String): String =
        """eval(function(p,a,c,k,e,d){return p}('0:"1"',62,2,'$name|$value'.split('|'),0,{}))"""

    private class QueueHttpService(
        vararg responses: HttpResponse,
    ) : HttpService {
        private val responses = ArrayDeque(responses.toList())
        val requests = mutableListOf<HttpRequest>()

        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            return responses.removeFirst()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8MasterTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8MasterTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/extractors/M3u8MasterTest.kt).

The implementation below defines `M3u8MasterTest`, `serving`, `m3u8VideosSplitsVariantsAndResolvesRelativeUrls`, `m3u8VideosFallsBackToMasterOnlyWhenRequested`, `m3u8VideosReturnsNothingOnHttpError`, `hostOfMatchesOnlyAbsoluteHttpUrls`.

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

- `m3u8VideosSplitsVariantsAndResolvesRelativeUrls`
- `m3u8VideosFallsBackToMasterOnlyWhenRequested`
- `m3u8VideosReturnsNothingOnHttpError`
- `hostOfMatchesOnlyAbsoluteHttpUrls`

Cross-chapter imports used by this file: [`HttpResponse`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.extractors

import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class M3u8MasterTest {
    private val masterUrl = "https://cdn.example/hls/master.m3u8"

    private fun serving(status: Int, body: String) = HttpService { HttpResponse(statusCode = status, body = body) }

    @Test
    fun m3u8VideosSplitsVariantsAndResolvesRelativeUrls() = runTest {
        val body = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=1280x720\n720.m3u8\n"
        val videos = serving(200, body).m3u8Videos(masterUrl, labelPrefix = "Voe:", fallbackQuality = "unused")
        assertEquals("https://cdn.example/hls/720.m3u8", videos.single().url)
        assertEquals("Voe: 720p", videos.single().quality)
    }

    @Test
    fun m3u8VideosFallsBackToMasterOnlyWhenRequested() = runTest {
        val http = serving(200, "#EXTM3U\n#EXTINF:10,\nseg.ts\n")
        assertTrue(http.m3u8Videos(masterUrl).isEmpty())
        val fallback = http.m3u8Videos(masterUrl, fallbackQuality = "Original").single()
        assertEquals(masterUrl, fallback.url)
        assertEquals("Original", fallback.quality)
    }

    @Test
    fun m3u8VideosReturnsNothingOnHttpError() = runTest {
        assertTrue(serving(404, "").m3u8Videos(masterUrl, fallbackQuality = "Original").isEmpty())
    }

    @Test
    fun hostOfMatchesOnlyAbsoluteHttpUrls() {
        assertEquals("sendvid.com", hostOf("https://sendvid.com/embed/abc"))
        assertNull(hostOf("/relative/path"))
        assertNull(hostOf("not a url"))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandBlockingTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandBlockingTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandBlockingTest.kt).

The implementation below defines `MpvCommandBlockingTest`.

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

- `retirementWaitsForBlockingNativeCaptureBeforeDeletingFileAndReleasingPlayer`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbSettings
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MpvCommandBlockingTest {
    @Test fun retirementWaitsForBlockingNativeCaptureBeforeDeletingFileAndReleasingPlayer() = runTest {
        val entered = CountDownLatch(1); val finish = CountDownLatch(1)
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, Dispatchers.IO)
        val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO, factory = { _, _ -> controller })
        val published = CompletableDeferred<Unit>()
        val lifetime = async { f.reader.withController(f.reader.configuration(DbSettings())) {
            published.complete(Unit); awaitCancellation()
        } }
        player.onCommand = {
            entered.countDown(); check(finish.await(10, TimeUnit.SECONDS))
            assertTrue(f.files.deletions.isEmpty()); assertEquals(0, player.releaseCount)
            f.files.bytes[f.files.writes.single()] = byteArrayOf(1)
        }
        val capture = async { published.await(); f.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent(); withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) }
            val close = async { f.service.closeAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertFalse(capture.isCompleted)
            assertTrue(f.files.deletions.isEmpty()); assertEquals(0, player.releaseCount)
            finish.countDown(); close.await()
            assertFailsWith<CancellationException> { capture.await() }
            assertTrue(f.files.bytes.isEmpty()); assertEquals(f.files.writes, f.files.deletions)
            assertEquals(1, player.releaseCount); assertTrue(f.owner.isActive)
        } finally { finish.countDown(); capture.cancelAndJoin(); lifetime.cancelAndJoin(); f.close(); controller.releaseAndJoin() }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBindingTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBindingTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvNativeSurfaceBindingTest.kt).

The implementation below defines `MpvNativeSurfaceBindingTest`, `Fixture`, `bind`.

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

- `destructionSupersedesQueuedAttachmentAndResize`
- `oldCleanupDoesNotDetachAReplacementTarget`
- `retirementJoinsNativeAttachmentBeforeDetachmentAndPlayerRelease`
- `failedDetachmentRetriesBeforeNativePlayerRelease`
- `partialAttachmentFailureStillOwnsFinalDetachment`

Cross-chapter imports used by this file: [`MpvRenderTarget`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.media.player

import io.github.kmpmpv.MpvRenderTarget
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class MpvNativeSurfaceBindingTest {
    @Test fun destructionSupersedesQueuedAttachmentAndResize() = runTest {
        val f = Fixture(this)
        try {
            val binding = checkNotNull(f.bind())
            binding.attach(MpvRenderTarget(1L), 100, 100); binding.resize(200, 200); binding.detach()
            runCurrent(); assertTrue(f.events.isEmpty())
            binding.attach(MpvRenderTarget(2L), 300, 300); runCurrent()
            assertEquals(listOf("attach:2", "resize:300x300"), f.events)
            binding.closeAndJoin(); assertEquals("detach", f.events.last())
            assertFalse(binding.attach(MpvRenderTarget(3L), 1, 1))
        } finally { f.controller.releaseAndJoin() }
    }
    @Test fun oldCleanupDoesNotDetachAReplacementTarget() = runTest {
        val f = Fixture(this)
        try {
            val old = checkNotNull(f.bind()); old.attach(MpvRenderTarget(1L), 10, 10); runCurrent()
            val fresh = checkNotNull(f.bind()); fresh.attach(MpvRenderTarget(2L), 20, 20); runCurrent()
            old.closeAndJoin()
            assertEquals(listOf("attach:1", "resize:10x10", "attach:2", "resize:20x20"), f.events)
            fresh.closeAndJoin(); assertEquals("detach", f.events.last())
        } finally { f.controller.releaseAndJoin() }
    }
    @Test fun retirementJoinsNativeAttachmentBeforeDetachmentAndPlayerRelease() = runTest {
        val f = Fixture(this); val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        f.player.onAttach = { f.events += "attach:${it.nativeWindowHandle}"; withContext(NonCancellable) { entered.complete(Unit); finish.await() } }
        val binding = checkNotNull(f.bind()); binding.attach(MpvRenderTarget(1L), 10, 10); entered.await()
        val close = async { f.controller.releaseAndJoin() }; runCurrent()
        assertFalse(close.isCompleted); assertEquals(0, f.player.releaseCount)
        finish.complete(Unit); close.await()
        assertEquals(listOf("attach:1", "detach", "release"), f.events)
        assertNull(f.bind())
    }
    @Test fun failedDetachmentRetriesBeforeNativePlayerRelease() = runTest {
        val f = Fixture(this); var attempts = 0; var fail = true
        f.player.onDetach = { attempts++; if (fail) error("detach failed") }
        val binding = checkNotNull(f.bind()); binding.attach(MpvRenderTarget(1L), 10, 10); runCurrent()
        assertFailsWith<IllegalStateException> { f.controller.releaseAndJoin() }
        assertEquals(0, f.player.releaseCount)
        fail = false; f.controller.releaseAndJoin(); assertTrue(attempts >= 2); assertEquals(1, f.player.releaseCount)
    }
    @Test fun partialAttachmentFailureStillOwnsFinalDetachment() = runTest {
        val f = Fixture(this); f.player.onAttach = { f.events += "attach:${it.nativeWindowHandle}"; error("partial native attachment") }
        val binding = checkNotNull(f.bind()); binding.attach(MpvRenderTarget(1L), 10, 10); runCurrent()
        binding.closeAndJoin(); assertEquals(listOf("attach:1", "detach"), f.events)
        f.controller.releaseAndJoin()
    }
    private class Fixture(test: TestScope) {
        val events = mutableListOf<String>()
        var removals = 0
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onAttach = { this@Fixture.events += "attach:${it.nativeWindowHandle}" }
            onResize = { width, height -> this@Fixture.events += "resize:${width}x$height" }
            onDetach = { this@Fixture.events += "detach" }
            onRelease = { this@Fixture.events += "release" }
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(test.testScheduler))
        private val context = StandardTestDispatcher(test.testScheduler)
        fun bind() = controller.bindNativeSurface(context) { removals++ }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareSurfaceCompositionTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareSurfaceCompositionTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareSurfaceCompositionTest.kt).

The implementation below defines `MpvSoftwareSurfaceCompositionTest`, `Scene`, `frame`, `pixel`, `pump`, `close`, `ui`.

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

- `controllerRetirementClearsPixelsWhileTheSurfaceIsStillMounted`
- `resizeCannotLetOldCleanupCloseTheReplacementBitmap`
- `lateOldNativeFailureCannotReplaceTheNewSurfaceOrFinishRetirementEarly`

Cross-chapter imports used by this file: [`MpvSoftwareFrame`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)

package eu.friedcutlet.yokan.services.media.player

import androidx.compose.foundation.layout.size
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toComposeImageBitmap
import androidx.compose.ui.graphics.toPixelMap
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.screens.player.MediaPlayerSurface
import io.github.kmpmpv.MpvSoftwareFrame
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MpvSoftwareSurfaceCompositionTest {
    @Test fun controllerRetirementClearsPixelsWhileTheSurfaceIsStillMounted() = runTest {
        val f = Scene(this)
        try {
            assertEquals(Color.Red, f.pixel())
            f.controllerA.releaseAndJoin(); f.pump()
            assertEquals(Color.Black, f.pixel())
            assertEquals(1, f.playerA.releaseCount)
        } finally { f.close() }
    }

    @Test fun resizeCannotLetOldCleanupCloseTheReplacementBitmap() = runTest {
        val f = Scene(this)
        val finish = CompletableDeferred<Unit>()
        var delayed = false
        f.playerA.onRender = { width, height ->
            f.sizesA += width to height
            if (!delayed) {
                delayed = true
                withContext(NonCancellable) { finish.await() }
            }
            f.frame(width, height, red = true)
        }
        try {
            testScheduler.advanceTimeBy(250); f.pump()
            assertTrue(delayed)
            f.ui { f.side.value = 80 }; f.pump()
            assertEquals(Color.Red, f.pixel())
            finish.complete(Unit); f.pump()
            assertEquals(Color.Red, f.pixel())
            assertTrue(f.sizesA.contains(80 to 80), "Requested frame sizes: ${f.sizesA}")
        } finally { finish.complete(Unit); f.close() }
    }

    @Test fun lateOldNativeFailureCannotReplaceTheNewSurfaceOrFinishRetirementEarly() = runTest {
        val f = Scene(this)
        val finish = CompletableDeferred<Unit>()
        var delayed = false
        f.playerA.onRender = { _, _ ->
            delayed = true
            withContext(NonCancellable) { finish.await(); error("late old renderer failure") }
        }
        try {
            testScheduler.advanceTimeBy(250); f.pump()
            assertTrue(delayed)
            f.ui { f.current.value = f.controllerB }; f.pump()
            assertEquals(Color.Green, f.pixel())
            val retire = async { f.controllerA.releaseAndJoin() }
            f.pump()
            assertFalse(retire.isCompleted); assertEquals(0, f.playerA.releaseCount)
            finish.complete(Unit); f.pump(); retire.await()
            assertEquals(Color.Green, f.pixel()); assertEquals(0, f.playerB.releaseCount)
        } finally { finish.complete(Unit); f.close() }
    }

    private class Scene(val test: TestScope) {
        val sizesA = mutableListOf<Pair<Int, Int>>()
        val playerA = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { width, height -> sizesA += width to height; frame(width, height, true) }
        }
        val playerB = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { width, height -> frame(width, height, false) }
        }
        val controllerA = MpvMediaPlayerController(playerA, NoopMediaStreamProxy, StandardTestDispatcher(test.testScheduler))
        val controllerB = MpvMediaPlayerController(playerB, NoopMediaStreamProxy, StandardTestDispatcher(test.testScheduler))
        val current = mutableStateOf(controllerA)
        val side = mutableStateOf(100)
        val scene = ui {
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                MediaPlayerSurface(current.value, Modifier.size(side.value.dp))
            }
        }
        init { pump() }
        fun frame(width: Int, height: Int, red: Boolean): MpvSoftwareFrame {
            val pixels = ByteArray(width * height * 4)
            for (offset in pixels.indices step 4) {
                pixels[offset + if (red) 2 else 1] = 255.toByte()
                pixels[offset + 3] = 255.toByte()
            }
            return MpvSoftwareFrame(width, height, width * 4, pixels)
        }
        fun pixel(): Color = ui {
            val image = scene.render(test.testScheduler.currentTime * 1_000_000)
            try { image.toComposeImageBitmap().toPixelMap()[50, 50] }
            finally { image.close() }
        }
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        suspend fun close() {
            ui { scene.close() }
            controllerA.releaseAndJoin(); controllerB.releaseAndJoin()
        }
        fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block)
            SwingUtilities.invokeAndWait(task)
            return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerControllerCompositionTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerControllerCompositionTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerControllerCompositionTest.kt).

The implementation below defines `PlayerControllerCompositionTest`, `Scene`, `pump`, `close`, `ui`.

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

- `disposalSavesBeforeReleaseAndRemountAllocatesFreshController`
- `chapterAndOwnerReplacementSaveOnlyTheirCapturedEpisodeAndController`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)

package eu.friedcutlet.yokan.services.media.player

import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.ImageComposeScene
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.screens.player.PlayerControllerEffect
import eu.friedcutlet.yokan.ui.screens.player.rememberPlayerServices
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PlayerControllerCompositionTest {
    @Test fun disposalSavesBeforeReleaseAndRemountAllocatesFreshController() = runTest {
        val f = Scene(this)
        try {
            val old = f.controllersA.single()
            f.ui { f.visible.value = false }; f.pump()
            assertTrue(old.released); assertEquals(listOf("A:10:42000"), f.saved)
            f.ui { f.visible.value = true }; f.pump()
            assertEquals(2, f.controllersA.size); assertFalse(f.controllersA.last().released)
            assertTrue(f.errors.isEmpty())
        } finally { f.close() }
    }

    @Test fun chapterAndOwnerReplacementSaveOnlyTheirCapturedEpisodeAndController() = runTest {
        val f = Scene(this)
        try {
            val first = f.controllersA.single()
            f.ui { f.chapter.value = 20L }; f.pump()
            assertTrue(first.released); assertFalse(f.controllersA.last().released)
            f.ui { f.current.value = f.b.service }; f.pump()
            assertTrue(f.controllersA.last().released); assertFalse(f.controllersB.single().released)
            assertEquals(listOf("A:10:42000", "A:20:42000"), f.saved)
            assertEquals(listOf("A:10", "A:20", "B:20"), f.published)
            assertTrue(f.errors.isEmpty())
        } finally { f.close() }
    }

    private class Scene(val test: TestScope) {
        val controllersA = mutableListOf<ProfilePlayerControllerTest.Controller>()
        val controllersB = mutableListOf<ProfilePlayerControllerTest.Controller>()
        val a = ProfilePlayerServicesTest.Fixture(test, "A", factory = { _, _ ->
            ProfilePlayerControllerTest.Controller().also { controllersA += it }
        })
        val b = ProfilePlayerServicesTest.Fixture(test, "B", factory = { _, _ ->
            ProfilePlayerControllerTest.Controller().also { controllersB += it }
        })
        val current = mutableStateOf(a.service)
        val chapter = mutableStateOf(10L)
        val visible = mutableStateOf(true)
        val saved = mutableListOf<String>()
        val published = mutableListOf<String>()
        val errors = mutableListOf<Throwable>()
        val scene = ui {
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                if (visible.value) {
                    val owner = current.value
                    val id = chapter.value
                    val label = if (owner === a.service) "A" else "B"
                    val reader = rememberPlayerServices(owner, id)
                    val config = remember(reader) { reader.configuration(DbSettings()) }
                    PlayerControllerEffect(reader, config, 0,
                        onController = { if (it != null) published += "$label:$id" },
                        onSavePosition = { position, _ -> saved += "$label:$id:$position" },
                        onInitializationError = { if (it != null) errors += it },
                    )
                }
            }
        }
        init { pump() }
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        suspend fun close() { ui { scene.close() }; a.close(); b.close() }
        fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block)
            SwingUtilities.invokeAndWait(task)
            return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesLifecycleTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesLifecycleTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServicesLifecycleTest.kt).

The implementation below defines `ProfilePlayerServicesLifecycleTest`, `UiFixture`, `show`, `pump`, `ui`, `close`, `onUi`.

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

- `canceledFactoryCallerJoinsBlockingAllocationAndLateNativeCleanup`
- `canceledConfigurationCallerJoinsBlockingWriteAndSkipsSecondFile`
- `retirementJoinsBlockingScreenshotSeedAndDeletesItWithoutDispatch`
- `closeDrainsNativeThreadProxyRegistrationOffUiThread`
- `compositionDisposalExpiresCallsAndRemountGetsFreshHandle`
- `chapterReplacementRejectsOldConfigurationAndProxyWithoutStoppingSession`
- `serviceReplacementWithSameChapterUsesNewFilesAndRejectsOldScreenshot`
- `retiringStatusRejectsVisibleHandleBeforeOwnerScopeCancellation`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)

package eu.friedcutlet.yokan.services.media.player

import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.screens.player.rememberPlayerServices
import java.util.concurrent.CountDownLatch
import java.util.concurrent.FutureTask
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotSame
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext

class ProfilePlayerServicesLifecycleTest {
    @Test fun canceledFactoryCallerJoinsBlockingAllocationAndLateNativeCleanup() = runTest {
        val entered = CountDownLatch(1); val release = CountDownLatch(1)
        val controller = ProfilePlayerControllerTest.Controller()
        val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO, factory = { _, _ ->
            entered.countDown(); check(release.await(10, TimeUnit.SECONDS)); controller
        })
        var published = false
        val configuration = f.reader.configuration(DbSettings())
        val call = async { f.reader.withController(configuration) { published = true } }
        try {
            runCurrent(); withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) }
            call.cancel(); runCurrent(); assertFalse(call.isCompleted)
            release.countDown(); call.join()
            assertFalse(published); assertEquals(1, controller.closes); assertTrue(controller.released)
            assertTrue(f.service.isAvailable)
        } finally { release.countDown(); call.cancelAndJoin(); f.close() }
    }

    @Test fun canceledConfigurationCallerJoinsBlockingWriteAndSkipsSecondFile() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO)
        val entered = CountDownLatch(1)
        val release = CountDownLatch(1)
        f.files.onWrite = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) }
        val configuration = f.reader.configuration(DbSettings())
        val request = async { f.reader.prepareConfiguration(configuration) }
        try {
            runCurrent()
            withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) }
            request.cancel(); runCurrent()
            assertFalse(request.isCompleted)
            release.countDown()
            request.join()
            assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.writes)
            assertTrue(f.service.isAvailable)
        } finally { release.countDown(); request.cancelAndJoin(); f.close() }
    }

    @Test fun retirementJoinsBlockingScreenshotSeedAndDeletesItWithoutDispatch() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO)
        val controller = ProfilePlayerServicesTest.Controller()
        val entered = CountDownLatch(1)
        val release = CountDownLatch(1)
        f.files.onWrite = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) }
        val request = async { f.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent()
            withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) }
            val close = async { f.service.closeAndJoin() }
            runCurrent()
            assertFalse(close.isCompleted)
            assertFalse(request.isCompleted)
            release.countDown()
            close.await()
            assertFailsWith<CancellationException> { request.await() }
            assertTrue(controller.commands.isEmpty())
            assertEquals(f.files.writes, f.files.deletions)
            assertTrue(f.owner.isActive)
        } finally { release.countDown(); request.cancelAndJoin(); f.close() }
    }

    @Test fun closeDrainsNativeThreadProxyRegistrationOffUiThread() = runTest {
        val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO)
        val entered = CountDownLatch(1)
        val release = CountDownLatch(1)
        f.proxy.onRegister = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) }
        val request = async(Dispatchers.IO) { f.reader.streamProxy.proxyUrl("https://stream.test", emptyMap()) }
        try {
            withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) }
            val close = async { f.service.closeAndJoin() }
            runCurrent()
            assertFalse(close.isCompleted)
            assertFalse(f.service.isAvailable)
            release.countDown()
            close.await()
            assertFailsWith<CancellationException> { request.await() }
            assertEquals(0, f.proxy.stops)
        } finally { release.countDown(); request.cancelAndJoin(); f.close() }
    }

    @Test fun compositionDisposalExpiresCallsAndRemountGetsFreshHandle() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.reader
            f.show(false)
            assertFalse(old.isAvailable)
            assertFailsWith<CancellationException> { old.markers(42, 1, 0) }
            assertFailsWith<CancellationException> { old.streamProxy.proxyUrl("Old", emptyMap()) }
            assertTrue(f.a.http.requests.isEmpty())
            assertTrue(f.a.proxy.urls.isEmpty())
            f.show(true)
            assertNotSame(old, f.reader)
            assertEquals("proxy:New", f.reader.streamProxy.proxyUrl("New", emptyMap()))
        } finally { f.close() }
    }

    @Test fun chapterReplacementRejectsOldConfigurationAndProxyWithoutStoppingSession() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.reader
            val configuration = old.configuration(DbSettings())
            f.ui { f.chapter.value = 20L }; f.pump()
            assertNotSame(old, f.reader)
            assertFailsWith<CancellationException> { old.prepareConfiguration(configuration) }
            old.streamProxy.stop()
            assertEquals("proxy:New chapter", f.reader.streamProxy.proxyUrl("New chapter", emptyMap()))
            assertEquals(0, f.a.proxy.stops)
            assertTrue(f.a.files.writes.isEmpty())
        } finally { f.close() }
    }

    @Test fun serviceReplacementWithSameChapterUsesNewFilesAndRejectsOldScreenshot() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.reader
            f.ui { f.current.value = f.b.service }; f.pump()
            assertNotSame(old, f.reader)
            assertFailsWith<CancellationException> {
                old.requestScreenshot(ProfilePlayerServicesTest.Controller(), "Book", "Episode")
            }
            f.reader.prepareConfiguration(f.reader.configuration(DbSettings()))
            assertTrue(f.a.files.writes.isEmpty())
            assertEquals(listOf("/B/cache/mpv/mpv.conf", "/B/cache/mpv/input.conf"), f.b.files.writes)
        } finally { f.close() }
    }

    @Test fun retiringStatusRejectsVisibleHandleBeforeOwnerScopeCancellation() = runTest {
        val f = UiFixture(this)
        try {
            f.a.open = false
            assertTrue(f.a.owner.isActive)
            assertFailsWith<CancellationException> { f.reader.markers(42, 1, 0) }
            assertFailsWith<CancellationException> { f.reader.streamProxy.proxyUrl("Late", emptyMap()) }
            assertTrue(f.a.http.requests.isEmpty())
            assertTrue(f.a.proxy.urls.isEmpty())
        } finally { f.close() }
    }

    private class UiFixture(val test: TestScope) {
        val a = ProfilePlayerServicesTest.Fixture(test, "A")
        val b = ProfilePlayerServicesTest.Fixture(test, "B")
        val current = mutableStateOf(a.service)
        val chapter = mutableStateOf(10L)
        val visible = mutableStateOf(true)
        lateinit var reader: ProfilePlayerServices.Reader
        val scene = ui {
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                if (visible.value) {
                    val binding = rememberPlayerServices(current.value, chapter.value)
                    SideEffect { reader = binding }
                }
            }
        }
        init { pump() }
        fun show(value: Boolean) { ui { visible.value = value }; pump() }
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        fun <T> ui(block: () -> T): T = onUi(block)
        suspend fun close() { ui { scene.close() }; a.close(); b.close() }
    }

    private companion object {
        fun <T> onUi(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block)
            SwingUtilities.invokeAndWait(task)
            return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/torrent/DesktopTorrServerHostTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/torrent/DesktopTorrServerHostTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/torrent/DesktopTorrServerHostTest.kt).

The implementation below defines `DesktopTorrServerHostTest`, `tearDown`, `freePort`, `fakeServer`, `FakeTorrServer`, `host`, `echo`, `startsWithProxyFlagsRestartsAfterCrashAndStops`, `optionChangeRestartsAndOrphanFromCrashedAppIsKilled`, `foreignServerOnThePortStartupCrashAndMissingBinaryFail` and 1 further declarations.

The source describes its contract as:

> Real subprocess supervision against a fake TorrServer (a Java single-file program behind a shell script).

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

- `startsWithProxyFlagsRestartsAfterCrashAndStops`
- `optionChangeRestartsAndOrphanFromCrashedAppIsKilled`
- `foreignServerOnThePortStartupCrashAndMissingBinaryFail`
- `installVerifiesSha256BeforePublishingTheBinary`

```kotlin
package eu.friedcutlet.yokan.services.torrent

import com.sun.net.httpserver.HttpServer
import java.io.File
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.URI
import java.nio.file.Files
import java.security.MessageDigest
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout

/** Real subprocess supervision against a fake TorrServer (a Java single-file program behind a shell script). */
class DesktopTorrServerHostTest {
    private val root = Files.createTempDirectory("torrserver-host").toFile()
    private val java = ProcessHandle.current().info().command().get()
    private val cleanup = mutableListOf<() -> Unit>()

    @AfterTest
    fun tearDown() {
        cleanup.forEach { runCatching(it) }
        root.deleteRecursively()
    }

    private fun freePort() = ServerSocket(0).use { it.localPort }

    private fun fakeServer(exitCode: Int? = null): File {
        val source = File(root, "FakeTorrServer.java")
        source.writeText(
            """
            import com.sun.net.httpserver.HttpServer;
            import java.net.InetSocketAddress;
            import java.nio.file.*;
            public class FakeTorrServer {
                public static void main(String[] args) throws Exception {
                    ${exitCode?.let { "System.out.println(\"bad flag\"); System.exit($it);" }.orEmpty()}
                    int port = Integer.parseInt(args[java.util.Arrays.asList(args).indexOf("--port") + 1]);
                    String path = args[java.util.Arrays.asList(args).indexOf("--path") + 1];
                    Files.writeString(Path.of(path, "args.txt"), String.join(" ", args));
                    HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
                    server.createContext("/echo", ex -> { byte[] b = "MatriX.fake".getBytes(); ex.sendResponseHeaders(200, b.length); ex.getResponseBody().write(b); ex.close(); });
                    server.start();
                }
            }
            """.trimIndent(),
        )
        return File(root, "TorrServer").apply {
            writeText("#!/bin/sh\nexec \"$java\" \"${source.absolutePath}\" \"$@\"\n")
            setExecutable(true)
        }
    }

    private fun host(dataDir: File = File(root, "data"), asset: TorrServerAsset? = null, base: String = "http://127.0.0.1:1") =
        DesktopTorrServerHost(dataDir, File(root, "bin"), asset, base, startTimeoutMillis = 30_000).also { host ->
            cleanup += { runBlocking { host.stop() } }
        }

    private fun echo(url: String) = URI.create("$url/echo").toURL().readText()

    @Test
    fun startsWithProxyFlagsRestartsAfterCrashAndStops(): Unit = runBlocking {
        val exe = fakeServer()
        val host = host()
        val port = freePort()
        val url = host.ensureRunning(TorrServerLaunch(port, exe.path, "full", "socks5://127.0.0.1:1080"))

        assertEquals("http://127.0.0.1:$port", url)
        assertEquals("MatriX.fake", echo(url))
        val args = File(root, "data/args.txt").readText()
        assertTrue("--proxyurl socks5://127.0.0.1:1080 --proxymode full" in args, args)
        assertTrue(File(root, "data/torrserver.pid").isFile)

        val first = host.pid!!
        ProcessHandle.of(first).get().destroyForcibly()
        withTimeout(30_000) { host.status.first { it.startsWith("Crashed") } }
        withTimeout(30_000) { host.status.first { it.startsWith("Running") } }
        assertNotEquals(first, host.pid)
        assertEquals("MatriX.fake", echo(url))

        host.stop()
        assertEquals("Stopped", host.status.value)
        assertFalse(File(root, "data/torrserver.pid").exists())
        assertFailsWith<Exception> { echo(url) }
    }

    @Test
    fun optionChangeRestartsAndOrphanFromCrashedAppIsKilled(): Unit = runBlocking {
        val exe = fakeServer()
        val port = freePort()
        val dataDir = File(root, "data").apply { mkdirs() }
        // A server left by a crashed Yokan: running, with its pid file.
        val orphan = ProcessBuilder(exe.path, "--port", port.toString(), "--path", dataDir.path).start()
        cleanup += { orphan.destroyForcibly() }
        withTimeout(30_000) { while (runCatching { echo("http://127.0.0.1:$port") }.isFailure) delay(100) }
        File(dataDir, "torrserver.pid").writeText("${orphan.pid()} ${orphan.info().startInstant().get().toEpochMilli()}")

        val host = host(dataDir)
        host.ensureRunning(TorrServerLaunch(port, exe.path, null, ""))
        assertFalse(orphan.isAlive)
        val first = host.pid!!

        host.ensureRunning(TorrServerLaunch(port, exe.path, "tracker", "http://proxy:3128"))
        assertNotEquals(first, host.pid)
        assertTrue("--proxymode tracker" in File(dataDir, "args.txt").readText())
    }

    @Test
    fun foreignServerOnThePortStartupCrashAndMissingBinaryFail(): Unit = runBlocking {
        val foreign = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
            createContext("/echo") { it.sendResponseHeaders(200, -1); it.close() }
            start()
        }
        cleanup += { foreign.stop(0) }
        val exe = fakeServer()
        val busy = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(foreign.address.port, exe.path, null, "")) }
        assertTrue("already used" in busy.message!!, busy.message)

        val crashing = fakeServer(exitCode = 7)
        val crashed = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(freePort(), crashing.path, null, "")) }
        assertTrue("exited with code 7" in crashed.message!! && "bad flag" in crashed.message!!, crashed.message)

        val missing = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(freePort(), "", null, "")) }
        assertTrue("Download TorrServer" in missing.message!!)
    }

    @Test
    fun installVerifiesSha256BeforePublishingTheBinary(): Unit = runBlocking {
        val payload = "#!/bin/sh\necho torrserver\n".encodeToByteArray()
        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
            createContext("/TorrServer-test") { it.sendResponseHeaders(200, payload.size.toLong()); it.responseBody.write(payload); it.close() }
            start()
        }
        cleanup += { server.stop(0) }
        val base = "http://127.0.0.1:${server.address.port}"
        val digest = MessageDigest.getInstance("SHA-256").digest(payload).toHexString()
        val target = File(root, "bin/$TorrServerVersion/TorrServer-test")

        val bad = host(asset = TorrServerAsset("TorrServer-test", "0".repeat(64)), base = base)
        assertTrue("SHA-256 mismatch" in assertFailsWith<IllegalStateException> { bad.install { _, _ -> } }.message!!)
        assertFalse(target.exists())
        assertEquals(emptyList(), target.parentFile.listFiles().orEmpty().toList())

        var progress = 0L
        val good = host(asset = TorrServerAsset("TorrServer-test", digest), base = base)
        assertEquals(target.path, good.install { done, _ -> progress = done })
        assertTrue(payload.contentEquals(target.readBytes()) && target.canExecute())
        assertEquals(payload.size.toLong(), progress)
        assertEquals(target.path, good.executable(""))
        assertEquals(null, good.executable("/does/not/exist"))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurfaceCompositionTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurfaceCompositionTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/OwnedPlayerSurfaceCompositionTest.kt).

The implementation below defines `OwnedPlayerSurfaceCompositionTest`, `Backend`, `Scene`, `pump`, `close`, `ui`.

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

- `controllerRetirementDetachesMountedUiBeforeAwaitedBackendRelease`
- `replacementOwnsFreshStateWhileOldCleanupIsDelayed`
- `disposalAndRemountAllocateSeparateBackendsForTheSameController`
- `failedBackendReleaseIsRetriedByControllerWithoutRevivingUi`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.*
import androidx.compose.ui.ImageComposeScene
import eu.friedcutlet.yokan.services.media.player.ComposeMediaPlayerController
import eu.friedcutlet.yokan.services.media.player.NoopMediaStreamProxy
import eu.friedcutlet.yokan.services.media.player.PlayerSurfaceResources
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class OwnedPlayerSurfaceCompositionTest {
    @Test fun controllerRetirementDetachesMountedUiBeforeAwaitedBackendRelease() = runTest {
        val f = Scene(this); val finish = CompletableDeferred<Unit>(); f.release = { finish.await() }
        try {
            val close = async { f.a.releaseAndJoin() }; f.pump()
            assertEquals(listOf("A1:ui", "A1:close"), f.order)
            assertFalse(close.isCompleted); assertNull(f.active)
            finish.complete(Unit); f.pump(); close.await(); assertEquals(listOf("A1:ui", "A1:close", "A1:done"), f.order)
        } finally { finish.complete(Unit); f.close() }
    }
    @Test fun replacementOwnsFreshStateWhileOldCleanupIsDelayed() = runTest {
        val f = Scene(this); val finish = CompletableDeferred<Unit>()
        val old = checkNotNull(f.active); val oldHandle = checkNotNull(f.handle)
        f.release = { if (it === old) finish.await() }
        try {
            f.ui { f.current.value = f.b }; f.pump()
            assertEquals("B2", f.active?.name); assertFalse(oldHandle.isAvailable)
            finish.complete(Unit); f.pump()
            assertEquals("B2", f.active?.name); assertTrue(checkNotNull(f.handle).isAvailable)
        } finally { finish.complete(Unit); f.close() }
    }
    @Test fun disposalAndRemountAllocateSeparateBackendsForTheSameController() = runTest {
        val f = Scene(this)
        try {
            val old = checkNotNull(f.active)
            f.ui { f.visible.value = false }; f.pump(); assertNull(f.active)
            f.ui { f.visible.value = true }; f.pump()
            assertNotSame(old, f.active); assertEquals("A2", f.active?.name)
            assertEquals(listOf("A1:ui", "A1:close", "A1:done"), f.order)
        } finally { f.close() }
    }
    @Test fun failedBackendReleaseIsRetriedByControllerWithoutRevivingUi() = runTest {
        val f = Scene(this); var fail = true; f.release = { if (fail) error("native close failed") }
        try {
            val close = async { runCatching { f.a.releaseAndJoin() } }; f.pump()
            assertIs<IllegalStateException>(close.await().exceptionOrNull()); assertNull(f.active)
            fail = false; f.a.releaseAndJoin(); f.pump(); assertNull(f.active)
            assertEquals(1, f.order.count { it == "A1:done" })
        } finally { fail = false; f.close() }
    }
    private class Backend(val name: String)
    private class Scene(val test: TestScope) {
        val a = ComposeMediaPlayerController(NoopMediaStreamProxy)
        val b = ComposeMediaPlayerController(NoopMediaStreamProxy)
        val current = mutableStateOf(a)
        val visible = mutableStateOf(true)
        val order = mutableListOf<String>()
        var count = 0
        var active: Backend? = null
        var handle: PlayerSurfaceResources.Resource? = null
        var release: suspend (Backend) -> Unit = {}
        val scene = ui {
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                if (visible.value) {
                    val controller = current.value
                    key(controller) {
                        OwnedPlayerSurfaceContent(controller.surfaces,
                            factory = { Backend("${if (controller === a) "A" else "B"}${++count}") },
                            dispose = { backend ->
                                order += "${backend.name}:close"; release(backend); order += "${backend.name}:done"
                            },
                        ) { backend, resource ->
                            Box {}
                            SideEffect { active = backend; handle = resource }
                            DisposableEffect(backend) { onDispose {
                                order += "${backend.name}:ui"
                                if (active === backend) active = null
                            } }
                        }
                    }
                }
            }
        }
        init { pump() }
        fun pump() = ui { repeat(4) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        suspend fun close() { ui { scene.close() }; a.releaseAndJoin(); b.releaseAndJoin() }
        fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block); SwingUtilities.invokeAndWait(task); return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiCompositionTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiCompositionTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerUiCompositionTest.kt).

The implementation below defines `PlayerUiCompositionTest`, `Owner`, `Scene`, `pump`, `emit`, `close`, `ui`.

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

- `disposalExpiresBridgeAndPipAndRemountGetsFreshCapabilities`
- `controllerChapterAndServiceReplacementExpireOnlyCapturedBindings`
- `stopAndResumeBeforeRecompositionCannotReviveRetainedCallbacks`
- `lifecycleOwnerReplacementRemovesOldObserverAndKeepsFreshBindingLive`
- `latestHandlerAndPlayingUpdatesDoNotRecreateLiveBinding`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)

package eu.friedcutlet.yokan.ui.screens.player

import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.media.player.MpvBridgeEvent
import eu.friedcutlet.yokan.services.media.player.PictureInPicturePlaybackOwners
import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServicesTest
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotSame
import kotlin.test.assertSame
import kotlin.test.assertTrue

class PlayerUiCompositionTest {
    @Test fun disposalExpiresBridgeAndPipAndRemountGetsFreshCapabilities() = runTest {
        val f = Scene(this)
        try {
            val old = f.binding; val request = f.request
            assertTrue(f.ui { request() }); f.emit(f.eventsA)
            f.ui { f.visible.value = false }; f.pump()
            assertFalse(old.active()); assertFalse(f.ui { request() }); assertEquals(false to false, f.states.last())
            f.emit(f.eventsA); assertEquals(listOf("A:10:first"), f.delivered)
            f.ui { f.visible.value = true }; f.pump()
            assertNotSame(old, f.binding); assertTrue(f.binding.active()); assertTrue(f.ui { f.request() })
            f.emit(f.eventsA); assertEquals(listOf("A:10:first", "A:10:first"), f.delivered)
        } finally { f.close() }
    }

    @Test fun controllerChapterAndServiceReplacementExpireOnlyCapturedBindings() = runTest {
        val f = Scene(this)
        try {
            val first = f.binding; val oldRequest = f.request
            f.emit(f.eventsA)
            f.ui { f.controller.value = f.controllerB }; f.pump()
            assertFalse(first.active()); assertFalse(f.ui { oldRequest() })
            f.emit(f.eventsA); assertEquals(1, f.delivered.size)
            f.emit(f.eventsB)
            val second = f.binding
            f.ui { f.chapter.value = 20L }; f.pump(); assertFalse(second.active()); f.emit(f.eventsB)
            val third = f.binding
            f.ui { f.current.value = f.b.service }; f.pump(); assertFalse(third.active()); f.emit(f.eventsB)
            assertEquals(listOf("A:10:first", "A:10:first", "A:20:first", "B:20:first"), f.delivered)
            assertEquals(0, f.eventsA.subscriptionCount.value); assertEquals(1, f.eventsB.subscriptionCount.value)
            assertTrue(f.a.owner.isActive); assertTrue(f.b.owner.isActive); assertTrue(f.ui { f.request() })
        } finally { f.close() }
    }

    @Test fun stopAndResumeBeforeRecompositionCannotReviveRetainedCallbacks() = runTest {
        val f = Scene(this)
        try {
            val old = f.binding; val request = f.request
            f.ui {
                f.lifecycle.value.registry.currentState = Lifecycle.State.CREATED
                assertFalse(old.active()); assertFalse(request()); assertFalse(f.admitted())
                f.lifecycle.value.registry.currentState = Lifecycle.State.RESUMED
                assertFalse(old.active()); assertFalse(request())
            }
            f.pump()
            assertNotSame(old, f.binding); assertTrue(f.binding.active()); assertTrue(f.ui { f.request() })
            f.emit(f.eventsA); assertEquals(listOf("A:10:first"), f.delivered)
        } finally { f.close() }
    }

    @Test fun lifecycleOwnerReplacementRemovesOldObserverAndKeepsFreshBindingLive() = runTest {
        val f = Scene(this)
        try {
            val old = f.binding; val oldLifecycle = f.lifecycle.value
            f.ui { f.lifecycle.value = Owner() }; f.pump()
            val fresh = f.binding
            assertFalse(old.active()); assertTrue(fresh.active())
            f.ui { oldLifecycle.registry.currentState = Lifecycle.State.CREATED }; f.pump()
            assertSame(fresh, f.binding); assertTrue(fresh.active()); f.emit(f.eventsA)
            assertEquals(listOf("A:10:first"), f.delivered)
        } finally { f.close() }
    }

    @Test fun latestHandlerAndPlayingUpdatesDoNotRecreateLiveBinding() = runTest {
        val f = Scene(this)
        try {
            val old = f.binding
            f.ui { f.handler.value = "updated"; f.playing.value = false }; f.pump()
            assertSame(old, f.binding); assertEquals(true to false, f.states.last())
            f.ui { f.lifecycle.value.registry.currentState = Lifecycle.State.STARTED }; f.pump()
            assertSame(old, f.binding); assertTrue(old.active())
            f.emit(f.eventsA); assertEquals(listOf("A:10:updated"), f.delivered)
        } finally { f.close() }
    }

    private class Owner : LifecycleOwner {
        val registry = LifecycleRegistry.createUnsafe(this).also { it.currentState = Lifecycle.State.RESUMED }
        override val lifecycle: Lifecycle get() = registry
    }

    private class Scene(val test: TestScope) {
        val a = ProfilePlayerServicesTest.Fixture(test, "A")
        val b = ProfilePlayerServicesTest.Fixture(test, "B")
        val current = mutableStateOf(a.service)
        val chapter = mutableStateOf(10L)
        val visible = mutableStateOf(true)
        val lifecycle = mutableStateOf(Owner())
        val eventsA = MutableSharedFlow<MpvBridgeEvent>()
        val eventsB = MutableSharedFlow<MpvBridgeEvent>()
        val controllerA = PlayerUiBindingTest.controller(eventsA)
        val controllerB = PlayerUiBindingTest.controller(eventsB)
        val controller: MutableState<MediaPlayerController> = mutableStateOf(controllerA)
        val handler = mutableStateOf("first")
        val playing = mutableStateOf(true)
        val delivered = mutableListOf<String>()
        val states = mutableListOf<Pair<Boolean, Boolean>>()
        var admitted: () -> Boolean = { false }
        val owners = PictureInPicturePlaybackOwners(
            publish = { active, eligible, callback -> states += active to eligible; admitted = callback },
            request = { true },
        )
        lateinit var binding: PlayerUiBinding
        lateinit var request: () -> Boolean
        val scene = ui {
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                CompositionLocalProvider(LocalLifecycleOwner provides lifecycle.value) {
                    if (visible.value) {
                        val owner = current.value
                        val id = chapter.value
                        val label = if (owner === a.service) "A" else "B"
                        val reader = rememberPlayerServices(owner, id)
                        val callbacks = rememberPlayerUiBinding(reader, controller.value)
                        val pip = rememberPlayerPictureInPicture(callbacks, playing.value, owners)
                        val currentHandler = handler.value
                        PlayerBridgeEffect(callbacks) { delivered += "$label:$id:$currentHandler" }
                        SideEffect { binding = callbacks; request = pip }
                    }
                }
            }
        }
        init { pump() }
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        suspend fun emit(events: MutableSharedFlow<MpvBridgeEvent>) {
            events.emit(PlayerUiBindingTest.Event); pump()
        }
        suspend fun close() { ui { scene.close() }; a.close(); b.close() }
        fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block); SwingUtilities.invokeAndWait(task); return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyLifecycleTest.kt
### Write `composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyLifecycleTest.kt`

Create this path in your reconstruction project. Source set: **jvmCommonTest**. [Exact file download](../reference/source/composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyLifecycleTest.kt).

The implementation below defines `JvmMediaStreamProxyLifecycleTest`, `close`, `request`, `response`.

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

- `unusedProxyClosesOnceAndRejectsEvenDirectUrls`
- `retirementJoinsBlockedRequestBeforeReleasingTransport`
- `responseProducerIsJoinedAfterExecuteHasReturned`
- `legacyStopStillAllowsAwaitingOutstandingFinalizers`
- `canceledRetirementCallerStillWaitsForCleanup`
- `failedNativeReleaseCanBeRetriedWithoutRestartingProxy`
- `retiringOneProxyPreservesOtherProxyAndCapturedHeaders`

Cross-chapter imports used by this file: [`ProfileTestEngine`](../chapters/05-http-cookies-and-webviews.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(io.ktor.utils.io.InternalAPI::class)

package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.utils.io.ByteChannel
import io.ktor.utils.io.ByteReadChannel
import java.net.Socket
import java.net.URI
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class JvmMediaStreamProxyLifecycleTest {
    @Test fun unusedProxyClosesOnceAndRejectsEvenDirectUrls() = runBlocking<Unit> {
        val engine = ProfileTestEngine(Dispatchers.IO) { error("No request expected") }
        val proxy = JvmMediaStreamProxy(engine)
        proxy.closeAndJoin(); proxy.closeAndJoin(); proxy.stop()
        assertEquals(1, engine.closeCalls)
        assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
        assertTrue(engine.requests.tryReceive().isFailure)
        assertFailsWith<IllegalStateException> { proxy.proxyUrl("https://source.test/video", emptyMap()) }
    }

    @Test fun retirementJoinsBlockedRequestBeforeReleasingTransport() = runBlocking<Unit> {
        withTimeout(10_000) {
            val entered = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>()
            val release = CompletableDeferred<Unit>(); var finalized = false
            val engine = ProfileTestEngine(Dispatchers.IO) {
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { finalizing.complete(Unit); release.await(); finalized = true } }
            }
            val proxy = JvmMediaStreamProxy(engine)
            val socket = request(proxy)
            try {
                entered.await()
                val retiring = launch { proxy.closeAndJoin() }
                finalizing.await()
                assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)
                assertFailsWith<IllegalStateException> { proxy.proxyUrl("https://source.test/new", mapOf("Referer" to "test")) }
                release.complete(Unit); retiring.join()
                assertTrue(finalized); assertEquals(1, engine.closeCalls)
                assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
            } finally { release.complete(Unit); socket.close(); proxy.closeAndJoin() }
        }
    }

    @Test fun responseProducerIsJoinedAfterExecuteHasReturned() = runBlocking<Unit> {
        withTimeout(10_000) {
            val entered = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>()
            val release = CompletableDeferred<Unit>()
            val engine = ProfileTestEngine(Dispatchers.IO) {
                val context = callContext()
                CoroutineScope(context).launch {
                    try { entered.complete(Unit); awaitCancellation() }
                    finally { withContext(NonCancellable) { finalizing.complete(Unit); release.await() } }
                }
                response(ByteChannel(), context = context)
            }
            val proxy = JvmMediaStreamProxy(engine)
            val socket = request(proxy)
            try {
                entered.await()
                val retiring = launch { proxy.closeAndJoin() }
                finalizing.await()
                assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)
                release.complete(Unit); retiring.join()
                assertEquals(1, engine.closeCalls)
                assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
            } finally { release.complete(Unit); socket.close(); proxy.closeAndJoin() }
        }
    }

    @Test fun legacyStopStillAllowsAwaitingOutstandingFinalizers() = runBlocking<Unit> {
        withTimeout(10_000) {
            val entered = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>()
            val release = CompletableDeferred<Unit>()
            val engine = ProfileTestEngine(Dispatchers.IO) {
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { finalizing.complete(Unit); release.await() } }
            }
            val proxy = JvmMediaStreamProxy(engine)
            val socket = request(proxy)
            try {
                entered.await(); proxy.stop()
                val retiring = launch { proxy.closeAndJoin() }
                finalizing.await()
                assertFalse(retiring.isCompleted)
                release.complete(Unit); retiring.join(); proxy.closeAndJoin()
                assertEquals(1, engine.closeCalls)
            } finally { release.complete(Unit); socket.close(); proxy.closeAndJoin() }
        }
    }

    @Test fun canceledRetirementCallerStillWaitsForCleanup() = runBlocking<Unit> {
        withTimeout(10_000) {
            val entered = CompletableDeferred<Unit>(); val finalizing = CompletableDeferred<Unit>()
            val release = CompletableDeferred<Unit>()
            val engine = ProfileTestEngine(Dispatchers.IO) {
                try { entered.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) { finalizing.complete(Unit); release.await() } }
            }
            val proxy = JvmMediaStreamProxy(engine)
            val socket = request(proxy)
            try {
                entered.await()
                val retiring = launch { proxy.closeAndJoin() }
                finalizing.await(); retiring.cancel()
                assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)
                release.complete(Unit); retiring.join()
                assertEquals(1, engine.closeCalls)
            } finally { release.complete(Unit); socket.close(); proxy.closeAndJoin() }
        }
    }

    @Test fun failedNativeReleaseCanBeRetriedWithoutRestartingProxy() = runBlocking<Unit> {
        val engine = ProfileTestEngine(Dispatchers.IO) { error("No request expected") }
        var attempts = 0
        val failing = object : HttpClientEngine by engine {
            override fun close() { attempts++; check(attempts > 1) { "Native release failed" }; engine.close() }
        }
        val proxy = JvmMediaStreamProxy(failing)
        try {
            assertFailsWith<IllegalStateException> { proxy.closeAndJoin() }
            assertFailsWith<IllegalStateException> { proxy.proxyUrl("https://source.test/video", mapOf("Referer" to "test")) }
            proxy.closeAndJoin(); proxy.closeAndJoin()
            assertEquals(2, attempts); assertEquals(1, engine.closeCalls)
        } finally { proxy.closeAndJoin() }
    }

    @Test fun retiringOneProxyPreservesOtherProxyAndCapturedHeaders() = runBlocking<Unit> {
        withTimeout(10_000) {
            val firstEngine = ProfileTestEngine(Dispatchers.IO) { error("No first request expected") }
            val secondEngine = ProfileTestEngine(Dispatchers.IO) {
                response(ByteReadChannel("#EXTM3U\nsegment.ts\n"), Headers.build {
                    append("Content-Type", "application/vnd.apple.mpegurl")
                })
            }
            val first = JvmMediaStreamProxy(firstEngine); val second = JvmMediaStreamProxy(secondEngine)
            try {
                first.closeAndJoin()
                request(second, "https://source.test/video.m3u8").use { socket ->
                    val result = withContext(Dispatchers.IO) { socket.getInputStream().readBytes().decodeToString() }
                    assertTrue(result.startsWith("HTTP/1.1 200"))
                    assertTrue(result.contains("/media/2.ts"))
                }
                assertEquals("test", secondEngine.requests.receive().headers["Referer"])
                assertEquals(0, secondEngine.closeCalls)
                assertTrue(secondEngine.coroutineContext[Job]?.isActive == true)
            } finally { first.closeAndJoin(); second.closeAndJoin() }
        }
    }

    private suspend fun request(proxy: JvmMediaStreamProxy, url: String = "https://source.test/video.mp4"): Socket =
        withContext(Dispatchers.IO) {
            val local = URI(proxy.proxyUrl(url, mapOf("Referer" to "test")))
            Socket(local.host, local.port).apply {
                soTimeout = 5_000
                getOutputStream().write("GET ${local.rawPath} HTTP/1.1\r\nHost: localhost\r\n\r\n".encodeToByteArray())
                getOutputStream().flush()
            }
        }

    private suspend fun response(body: ByteReadChannel, headers: Headers = Headers.Empty,
        context: kotlin.coroutines.CoroutineContext? = null) =
        HttpResponseData(HttpStatusCode.OK, GMTDate(), headers, HttpProtocolVersion.HTTP_1_1, body, context ?: callContext())
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyTest.kt
### Write `composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyTest.kt`

Create this path in your reconstruction project. Source set: **jvmCommonTest**. [Exact file download](../reference/source/composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxyTest.kt).

The implementation below defines `JvmMediaStreamProxyTest`, `reusesRegistrationsWithoutSharingDifferentAuthenticationHeaders`, `stoppingClosesIdleClientsAndRejectsRestart`.

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

- `reusesRegistrationsWithoutSharingDifferentAuthenticationHeaders`
- `stoppingClosesIdleClientsAndRejectsRestart`

```kotlin
package eu.friedcutlet.yokan.services.media.player

import java.net.Socket
import java.net.URI
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
import kotlinx.coroutines.runBlocking

class JvmMediaStreamProxyTest {
    @Test
    fun reusesRegistrationsWithoutSharingDifferentAuthenticationHeaders() = runBlocking<Unit> {
        val proxy = JvmMediaStreamProxy()
        try {
            val headers = mutableMapOf("Authorization" to "first")
            val first = proxy.proxyUrl("https://example.test/video.m3u8", headers)
            repeat(100) { assertEquals(first, proxy.proxyUrl("https://example.test/video.m3u8", headers)) }
            headers["Authorization"] = "second"
            assertNotEquals(first, proxy.proxyUrl("https://example.test/video.m3u8", headers))
            assertEquals(first, proxy.proxyUrl("https://example.test/video.m3u8", mapOf("Authorization" to "first")))
        } finally {
            proxy.closeAndJoin()
        }
    }

    @Test
    fun stoppingClosesIdleClientsAndRejectsRestart() = runBlocking<Unit> {
        val proxy = JvmMediaStreamProxy()
        try {
            val url = URI(proxy.proxyUrl("https://example.test/video.mp4", mapOf("Referer" to "test")))
            Socket(url.host, url.port).use { client ->
                client.soTimeout = 2_000
                proxy.stop()
                // An accepted socket is closed; an unaccepted connection may be reset by the OS.
                val closed = try { client.getInputStream().read() == -1 } catch (_: java.net.SocketException) { true }
                kotlin.test.assertTrue(closed)
            }
            assertFailsWith<IllegalStateException> {
                proxy.proxyUrl("https://example.test/video.mp4", mapOf("Referer" to "test"))
            }
            assertFailsWith<IllegalStateException> { proxy.proxyUrl("https://example.test/video.mp4", emptyMap()) }
        } finally {
            proxy.closeAndJoin()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayerInitializationTest.kt
### Write `composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayerInitializationTest.kt`

Create this path in your reconstruction project. Source set: **nonWebTest**. [Exact file download](../reference/source/composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayerInitializationTest.kt).

The implementation below defines `MediaPlayerInitializationTest`, `releaseRemovesStateAndEventCollectorsDuringAPendingLoad`, `stalledLoadTimesOutAndUnblocksQueuedCommands`, `scrubbingDuringPreparationOnlySeeksToTheLatestPosition`, `immediateRepeatedReleaseStillRunsOwnedCleanupExactlyOnce`, `loadHoldsPlaybackUntilResumePositionIsPrepared`, `freshLoadUsesTheSameSinglePreparationSequenceWithoutAResumeSeek`, `failedLoadNeverSeeksResumePosition`, `releaseCancelsPendingLoadAndQueuedPlay`, `unknownDurationPreparationCompletesAndHonorsLatestPlaybackIntent` and 27 further declarations.

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

- `releaseRemovesStateAndEventCollectorsDuringAPendingLoad`
- `stalledLoadTimesOutAndUnblocksQueuedCommands`
- `scrubbingDuringPreparationOnlySeeksToTheLatestPosition`
- `immediateRepeatedReleaseStillRunsOwnedCleanupExactlyOnce`
- `loadHoldsPlaybackUntilResumePositionIsPrepared`
- `freshLoadUsesTheSameSinglePreparationSequenceWithoutAResumeSeek`
- `failedLoadNeverSeeksResumePosition`
- `releaseCancelsPendingLoadAndQueuedPlay`
- `unknownDurationPreparationCompletesAndHonorsLatestPlaybackIntent`
- `resumePreparationRequiresDurationUntilTimeout`
- `pendingSeekRetainsOnlyLatestRequestUntilDispatched`

Cross-chapter imports used by this file: [`MpvEvent`](../chapters/17-kmp-mpv-submodule.md), [`MpvFormat`](../chapters/17-kmp-mpv-submodule.md), [`MpvLifecycleEvent`](../chapters/17-kmp-mpv-submodule.md), [`MpvLoadMode`](../chapters/17-kmp-mpv-submodule.md), [`MpvLogLevel`](../chapters/17-kmp-mpv-submodule.md), [`MpvPlaybackState`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.services.media.player

import io.github.kmpmpv.MpvEvent
import io.github.kmpmpv.MpvFormat
import io.github.kmpmpv.MpvLifecycleEvent
import io.github.kmpmpv.MpvLoadMode
import io.github.kmpmpv.MpvLogLevel
import io.github.kmpmpv.MpvPlaybackState
import io.github.kmpmpv.MpvPlayer
import io.github.kmpmpv.MpvRenderTarget
import io.github.kmpmpv.MpvSeekMode
import io.github.kmpmpv.MpvSoftwareFrame
import io.github.kmpmpv.MpvValue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.advanceTimeBy
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue

class MediaPlayerInitializationTest {
    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun releaseRemovesStateAndEventCollectorsDuringAPendingLoad() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            controller.load("https://example.test/stalled.mp4")
            runCurrent()
            assertEquals(1, player.state.subscriptionCount.value)
            assertEquals(2, player.events.subscriptionCount.value)
        } finally {
            controller.release()
            runCurrent()
        }
        assertEquals(0, player.state.subscriptionCount.value)
        assertEquals(0, player.events.subscriptionCount.value)
        assertEquals(1, player.releaseCount)
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun stalledLoadTimesOutAndUnblocksQueuedCommands() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler), loadTimeoutMs = 1_000)
        try {
            controller.load("https://example.test/stalled.mp4")
            controller.play()
            runCurrent()
            assertFalse(player.played.isCompleted)
            advanceTimeBy(1_000)
            runCurrent()
            assertTrue(player.played.isCompleted)
        } finally {
            controller.release()
            runCurrent()
        }
        assertTrue(player.released.isCompleted)
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun scrubbingDuringPreparationOnlySeeksToTheLatestPosition() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            controller.load("https://example.test/episode.mp4")
            runCurrent()
            repeat(100) { controller.seekTo(it * 1_000L) }
            runCurrent()
            player.finishLoad()
            runCurrent()
            assertEquals(listOf(listOf("seek", "99.0", "Absolute")), player.actions.filter { it.first() == "seek" })
        } finally {
            controller.release()
            runCurrent()
        }
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun immediateRepeatedReleaseStillRunsOwnedCleanupExactlyOnce() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        repeat(10) { controller.release() }
        runCurrent()
        assertEquals(1, player.releaseCount)
    }

    @Test
    fun loadHoldsPlaybackUntilResumePositionIsPrepared() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy)

        controller.load("https://example.test/episode.mp4", initialPositionMs = 75_432L)
        player.commandIssued.await()
        val prepareActions = listOf(
            listOf("pause"),
            listOf("load", "https://example.test/episode.mp4", "Replace"),
        )
        assertEquals(prepareActions, player.actions)

        controller.play()
        player.emitStaleEndFile()
        assertFalse(player.played.isCompleted)

        player.finishLoad()
        player.played.await()
        assertEquals(
            prepareActions + listOf(
                listOf("seek", "75.432", "Absolute"),
                listOf("play"),
            ),
            player.actions,
        )
        controller.release()
        player.released.await()
    }

    @Test
    fun freshLoadUsesTheSameSinglePreparationSequenceWithoutAResumeSeek() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy)

        controller.load("https://example.test/episode.mp4")
        player.commandIssued.await()
        val prepareActions = listOf(
            listOf("pause"),
            listOf("load", "https://example.test/episode.mp4", "Replace"),
        )
        assertEquals(prepareActions, player.actions)

        controller.play()
        assertFalse(player.played.isCompleted)
        player.finishLoad()
        player.played.await()

        assertEquals(prepareActions + listOf(listOf("play")), player.actions)
        controller.release()
        player.released.await()
    }

    @Test
    fun failedLoadNeverSeeksResumePosition() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy)

        controller.load("https://example.test/episode.mp4", initialPositionMs = 75_432L)
        player.commandIssued.await()
        controller.play()
        player.failLoad()
        player.played.await()

        assertEquals(
            listOf(
                listOf("pause"),
                listOf("load", "https://example.test/episode.mp4", "Replace"),
                listOf("play"),
            ),
            player.actions,
        )
        controller.release()
        player.released.await()
    }

    @Test
    fun releaseCancelsPendingLoadAndQueuedPlay() = runTest {
        val player = RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy)

        controller.load("https://example.test/episode.mp4", initialPositionMs = 75_432L)
        player.commandIssued.await()
        controller.play()

        controller.release()
        player.released.await()
        assertFalse(player.played.isCompleted)

        player.finishLoad()
        assertFalse(player.played.isCompleted)
    }

    @Test
    fun unknownDurationPreparationCompletesAndHonorsLatestPlaybackIntent() = runTest {
        val playThenPause = InitialPlaybackState().apply {
            beginPreparation()
            requestPlay()
            requestPause()
        }

        val durationMs = awaitInitialMediaDuration(
            durationMs = { null },
            isUsable = { true },
            hasError = { false },
            requireDuration = false,
            readinessGraceMs = 1L,
            timeoutMs = 100L,
            pollIntervalMs = 1L,
        )

        assertNull(durationMs)
        assertEquals(75_000L, parsePlaybackPositionMs("01:15"))
        assertEquals(3_661_000L, parsePlaybackPositionMs("1:01:01"))
        assertEquals(0L, parsePlaybackPositionMs("not-a-position"))
        assertFalse(playThenPause.finishPreparation())

        val pauseThenPlay = InitialPlaybackState().apply {
            beginPreparation()
            requestPause()
            requestPlay()
        }
        assertTrue(pauseThenPlay.finishPreparation())
    }

    @Test
    fun resumePreparationRequiresDurationUntilTimeout() = runTest {
        var usableChecks = 0
        val durationMs = awaitInitialMediaDuration(
            durationMs = { null },
            isUsable = {
                usableChecks += 1
                true
            },
            hasError = { false },
            requireDuration = true,
            readinessGraceMs = 1L,
            timeoutMs = 10L,
            pollIntervalMs = 1L,
        )

        assertNull(durationMs)
        assertEquals(0, usableChecks)
    }

    @Test
    fun pendingSeekRetainsOnlyLatestRequestUntilDispatched() {
        val pendingSeek = PendingSeekState()
        pendingSeek.request(30_000L)
        pendingSeek.request(75_000L)

        assertEquals(75_000L, pendingSeek.pendingPositionMs())
        pendingSeek.markDispatched()
        assertNull(pendingSeek.pendingPositionMs())
    }

    internal class RecordingMpvPlayer : MpvPlayer {
        override val events = MutableSharedFlow<MpvEvent>()
        override val state = MutableStateFlow(MpvPlaybackState())
        val actions = mutableListOf<List<String>>()
        val commandIssued = CompletableDeferred<Unit>()
        val played = CompletableDeferred<Unit>()
        val released = CompletableDeferred<Unit>()
        var releaseCount = 0
        var onRelease: suspend () -> Unit = { }
        var onCommand: suspend () -> Unit = { }
        var onAttach: suspend (MpvRenderTarget) -> Unit = {}
        var onResize: suspend (Int, Int) -> Unit = { _, _ -> }
        var onDetach: suspend () -> Unit = {}
        var onRender: suspend (Int, Int) -> MpvSoftwareFrame = { _, _ ->
            error("Software rendering is not exercised by this controller test")
        }

        override suspend fun load(path: String, mode: MpvLoadMode) {
            actions += listOf("load", path, mode.name)
            commandIssued.complete(Unit)
        }

        override suspend fun play() {
            actions += listOf("play")
            played.complete(Unit)
        }

        override suspend fun pause() {
            actions += listOf("pause")
        }
        override suspend fun togglePause() = Unit
        override suspend fun stop() = Unit
        override suspend fun seek(seconds: Double, mode: MpvSeekMode) {
            actions += listOf("seek", seconds.toString(), mode.name)
        }

        override suspend fun command(vararg arguments: String) {
            actions += arguments.toList()
            onCommand()
        }

        suspend fun emitStaleEndFile() {
            events.emit(MpvEvent.EndFile(io.github.kmpmpv.MpvEndFileReason.Stop))
        }

        suspend fun failLoad() {
            events.emit(MpvEvent.Lifecycle(MpvLifecycleEvent.StartFile))
            events.emit(MpvEvent.EndFile(io.github.kmpmpv.MpvEndFileReason.Stop))
        }

        suspend fun finishLoad() {
            events.emit(MpvEvent.Lifecycle(MpvLifecycleEvent.StartFile))
            events.emit(MpvEvent.Lifecycle(MpvLifecycleEvent.FileLoaded))
        }

        override suspend fun getProperty(name: String, format: MpvFormat): MpvValue = MpvValue.None
        override suspend fun setProperty(name: String, value: MpvValue) = Unit
        override suspend fun getStringProperty(name: String): String? = null
        override suspend fun getBooleanProperty(name: String): Boolean? = null
        override suspend fun getLongProperty(name: String): Long? = null
        override suspend fun getDoubleProperty(name: String): Double? = null
        override suspend fun observeProperty(name: String, format: MpvFormat): Long = 0L
        override suspend fun unobserveProperty(observationId: Long) = Unit
        override suspend fun requestLogMessages(level: MpvLogLevel) = Unit
        override suspend fun attachRenderTarget(target: MpvRenderTarget) = onAttach(target)
        override suspend fun detachRenderTarget() = onDetach()
        override suspend fun updateRenderTargetSize(width: Int, height: Int) = onResize(width, height)
        override suspend fun renderSoftwareFrame(width: Int, height: Int): MpvSoftwareFrame = onRender(width, height)

        override suspend fun release() {
            releaseCount++
            onRelease()
            released.complete(Unit)
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandCompletionTest.kt
### Write `composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandCompletionTest.kt`

Create this path in your reconstruction project. Source set: **nonWebTest**. [Exact file download](../reference/source/composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvCommandCompletionTest.kt).

The implementation below defines `MpvCommandCompletionTest`.

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

- `screenshotUsesSynchronousNativeCaptureAndPreservesPathArguments`
- `awaitedCommandKeepsQueueOrderAndWaitsForNativeCompletion`
- `canceledQueuedCallerCannotReachNativePlayerOrCancelSiblingCommand`
- `canceledActiveCallerJoinsNativeFinalizerWithoutRetiringController`
- `nativeFailureReturnsFalseAndDoesNotPoisonQueue`
- `expiredAndRetiredCallersCannotDispatchNativeCommands`
- `controllerRetirementJoinsCaptureBeforeNativeReleaseAndSuppressesSuccess`
- `sessionRetirementJoinsActualControllerCaptureAndFileCleanup`

Cross-chapter imports used by this file: [`DbSettings`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import eu.friedcutlet.yokan.database.DbSettings
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MpvCommandCompletionTest {
    @Test fun screenshotUsesSynchronousNativeCaptureAndPreservesPathArguments() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val finish = CompletableDeferred<Unit>()
        player.onCommand = { finish.await() }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val capture = async { controller.takeMpvScreenshotAndJoin("/cache/my frame.png") }
        try {
            runCurrent(); assertFalse(capture.isCompleted)
            assertEquals(listOf("sync", "screenshot-to-file", "/cache/my frame.png", "video"), player.actions.single())
            finish.complete(Unit); assertTrue(capture.await())
        } finally { finish.complete(Unit); capture.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun awaitedCommandKeepsQueueOrderAndWaitsForNativeCompletion() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val finishFirst = CompletableDeferred<Unit>(); val finishSecond = CompletableDeferred<Unit>()
        player.onCommand = { if (player.actions.last().first() == "first") finishFirst.await() else finishSecond.await() }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        controller.executeMpvCommand("first")
        val second = async { controller.executeMpvCommandAndJoin("second") }
        try {
            runCurrent(); assertEquals(listOf(listOf("first")), player.actions); assertFalse(second.isCompleted)
            finishFirst.complete(Unit); runCurrent()
            assertEquals(listOf(listOf("first"), listOf("second")), player.actions); assertFalse(second.isCompleted)
            finishSecond.complete(Unit); assertTrue(second.await())
        } finally { finishFirst.complete(Unit); finishSecond.complete(Unit); second.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun canceledQueuedCallerCannotReachNativePlayerOrCancelSiblingCommand() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val finish = CompletableDeferred<Unit>()
        player.onCommand = { finish.await() }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        controller.executeMpvCommand("first")
        val queued = async { controller.executeMpvCommandAndJoin("obsolete") }
        try {
            runCurrent(); queued.cancel(); runCurrent(); queued.join()
            controller.play(); finish.complete(Unit); runCurrent()
            assertEquals(listOf(listOf("first"), listOf("play")), player.actions)
            assertTrue(player.played.isCompleted); assertEquals(0, player.releaseCount)
        } finally { finish.complete(Unit); queued.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun canceledActiveCallerJoinsNativeFinalizerWithoutRetiringController() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val finish = CompletableDeferred<Unit>()
        player.onCommand = { try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() } } }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val call = async { controller.executeMpvCommandAndJoin("capture") }
        try {
            runCurrent(); call.cancel(); runCurrent(); assertFalse(call.isCompleted)
            controller.play(); runCurrent(); assertFalse(player.played.isCompleted)
            finish.complete(Unit); call.join(); runCurrent()
            assertTrue(player.played.isCompleted); assertEquals(0, player.releaseCount)
        } finally { finish.complete(Unit); call.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun nativeFailureReturnsFalseAndDoesNotPoisonQueue() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        player.onCommand = { throw IllegalStateException("Native capture failed") }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            assertFalse(controller.executeMpvCommandAndJoin("capture"))
            controller.play(); runCurrent(); assertTrue(player.played.isCompleted)
            assertEquals(0, player.releaseCount)
        } finally { controller.releaseAndJoin() }
    }

    @Test fun expiredAndRetiredCallersCannotDispatchNativeCommands() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            val canceled = async(UnconfinedTestDispatcher(testScheduler)) {
                requireNotNull(currentCoroutineContext()[Job]).cancel()
                assertFailsWith<CancellationException> { controller.executeMpvCommandAndJoin("expired") }
            }
            canceled.join()
            assertFalse(controller.executeMpvCommandAndJoin())
            controller.releaseAndJoin()
            assertFalse(controller.executeMpvCommandAndJoin("retired"))
            assertTrue(player.actions.isEmpty())
        } finally { controller.releaseAndJoin() }
    }

    @Test fun controllerRetirementJoinsCaptureBeforeNativeReleaseAndSuppressesSuccess() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val finish = CompletableDeferred<Unit>()
        player.onCommand = { withContext(NonCancellable) { finish.await() } }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val call = async { controller.executeMpvCommandAndJoin("capture") }
        try {
            runCurrent()
            val close = async { controller.releaseAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertFalse(call.isCompleted); assertEquals(0, player.releaseCount)
            finish.complete(Unit); close.await()
            assertFailsWith<CancellationException> { call.await() }; assertEquals(1, player.releaseCount)
        } finally { finish.complete(Unit); call.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun sessionRetirementJoinsActualControllerCaptureAndFileCleanup() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val finish = CompletableDeferred<Unit>()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val f = ProfilePlayerServicesTest.Fixture(this, factory = { _, _ -> controller })
        val lifetime = async { f.reader.withController(f.reader.configuration(DbSettings())) { awaitCancellation() } }
        player.onCommand = { withContext(NonCancellable) {
            finish.await()
            assertTrue(f.files.deletions.isEmpty())
            f.files.bytes[f.files.writes.single()] = byteArrayOf(1)
        } }
        val capture = async { f.reader.requestScreenshot(controller, "Book", "Episode") }
        try {
            runCurrent()
            val close = async { f.service.closeAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertFalse(capture.isCompleted); assertEquals(0, player.releaseCount)
            finish.complete(Unit); close.await()
            assertFailsWith<CancellationException> { capture.await() }
            assertTrue(f.files.bytes.isEmpty()); assertEquals(f.files.writes, f.files.deletions)
            assertEquals(1, player.releaseCount); assertTrue(f.owner.isActive)
        } finally { finish.complete(Unit); capture.cancelAndJoin(); lifetime.cancelAndJoin(); f.close(); controller.releaseAndJoin() }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvControllerRetirementTest.kt
### Write `composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvControllerRetirementTest.kt`

Create this path in your reconstruction project. Source set: **nonWebTest**. [Exact file download](../reference/source/composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvControllerRetirementTest.kt).

The implementation below defines `MpvControllerRetirementTest`.

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

- `retirementJoinsCommandFinalizerBeforeReleasingNativePlayer`
- `failedNativeReleaseRetriesWithoutReopeningCommandQueue`
- `legacyReleaseCanBeAwaitedAndCancellationStillJoinsNativeCleanup`
- `independentControllersKeepTheirOwnNativePlayers`

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MpvControllerRetirementTest {
    @Test fun retirementJoinsCommandFinalizerBeforeReleasingNativePlayer() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val release = CompletableDeferred<Unit>()
        player.onCommand = { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            assertTrue(controller.executeMpvCommand("blocked")); runCurrent(); controller.play()
            val close = async { controller.releaseAndJoin() }; runCurrent()
            assertFalse(close.isCompleted); assertEquals(0, player.releaseCount)
            assertFalse(controller.executeMpvCommand("late"))
            release.complete(Unit); close.await()
            assertEquals(1, player.releaseCount); assertFalse(player.played.isCompleted)
            assertEquals(0, player.events.subscriptionCount.value); assertEquals(0, player.state.subscriptionCount.value)
        } finally { release.complete(Unit); controller.releaseAndJoin() }
    }

    @Test fun failedNativeReleaseRetriesWithoutReopeningCommandQueue() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        player.onRelease = { check(player.releaseCount > 2) { "Native release failed" } }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            assertFailsWith<IllegalStateException> { controller.releaseAndJoin() }
            assertEquals(2, player.releaseCount); assertFalse(controller.executeMpvCommand("late"))
            controller.play(); runCurrent(); assertFalse(player.played.isCompleted)
            controller.releaseAndJoin(); controller.releaseAndJoin()
            assertEquals(3, player.releaseCount)
        } finally { controller.releaseAndJoin() }
    }

    @Test fun legacyReleaseCanBeAwaitedAndCancellationStillJoinsNativeCleanup() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer(); val release = CompletableDeferred<Unit>()
        player.onRelease = { release.await() }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        controller.release(); runCurrent()
        val close = async { controller.releaseAndJoin() }
        try {
            runCurrent(); close.cancel(); runCurrent(); assertFalse(close.isCompleted)
            release.complete(Unit); close.join(); controller.releaseAndJoin()
            assertEquals(1, player.releaseCount)
        } finally { release.complete(Unit); close.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun independentControllersKeepTheirOwnNativePlayers() = runTest {
        val a = MediaPlayerInitializationTest.RecordingMpvPlayer(); val b = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val first = MpvMediaPlayerController(a, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val second = MpvMediaPlayerController(b, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            first.releaseAndJoin(); second.play(); runCurrent()
            assertEquals(1, a.releaseCount); assertEquals(0, b.releaseCount); assertTrue(b.played.isCompleted)
        } finally { first.releaseAndJoin(); second.releaseAndJoin() }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareRenderingTest.kt
### Write `composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareRenderingTest.kt`

Create this path in your reconstruction project. Source set: **nonWebTest**. [Exact file download](../reference/source/composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareRenderingTest.kt).

The implementation below defines `MpvSoftwareRenderingTest`, `kotlinx.coroutines.test.TestScope.checkLateResult`, `frame`.

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

- `frameWorkKeepsTheCapturedUiContextAndDoesNotWaitForLoadCommands`
- `retirementJoinsNativeFinalizersAndUiPixelCleanupBeforeNativeRelease`
- `callerCancellationJoinsItsRenderLoopWithoutRetiringTheController`
- `lateNativeSuccessCannotPublishAFrameAfterCallerExpiry`
- `lateNativeFailureBecomesCancellationBeforeUiErrorHandling`
- `completedLoopExpiresRetainedRendererCallbacks`
- `liveRendererCannotEscapeIntoUntrackedCoroutineWork`
- `retiredControllerAndCancelledCallerCannotStartRenderLoops`
- `cancellingOneLoopLeavesAnotherLoopAndControllerAlive`

Cross-chapter imports used by this file: [`MpvSoftwareFrame`](../chapters/17-kmp-mpv-submodule.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.media.player

import io.github.kmpmpv.MpvSoftwareFrame
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertSame
import kotlin.test.assertTrue

class MpvSoftwareRenderingTest {
    @Test fun frameWorkKeepsTheCapturedUiContextAndDoesNotWaitForLoadCommands() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val expected = frame(4, 2)
        player.onRender = { width, height ->
            assertEquals(4, width); assertEquals(2, height)
            expected
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            controller.load("https://example.test/stalled.mp4")
            runCurrent()
            val render = async(CoroutineName("captured-ui")) {
                controller.withSoftwareRendering { renderer ->
                    assertEquals("captured-ui", currentCoroutineContext()[CoroutineName]?.name)
                    assertSame(expected, renderer.renderFrame(4, 2))
                }
            }
            runCurrent()
            render.await()
            assertFalse(player.played.isCompleted)
        } finally { controller.releaseAndJoin() }
    }

    @Test fun retirementJoinsNativeFinalizersAndUiPixelCleanupBeforeNativeRelease() = runTest {
        val nativeStarted = CompletableDeferred<Unit>()
        val nativeCleanup = CompletableDeferred<Unit>()
        val allowNativeCleanup = CompletableDeferred<Unit>()
        val pixelCleanup = CompletableDeferred<Unit>()
        val allowPixelCleanup = CompletableDeferred<Unit>()
        val order = mutableListOf<String>()
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { _, _ ->
                try { nativeStarted.complete(Unit); awaitCancellation() }
                finally { withContext(NonCancellable) {
                    nativeCleanup.complete(Unit); allowNativeCleanup.await(); order += "frame"
                } }
            }
            onRelease = { order += "release" }
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val render = launch {
            controller.withSoftwareRendering { renderer ->
                try { renderer.renderFrame(4, 2) }
                finally { withContext(NonCancellable) {
                    pixelCleanup.complete(Unit); allowPixelCleanup.await(); order += "pixels"
                } }
            }
        }
        nativeStarted.await()
        val retire = async { controller.releaseAndJoin() }
        nativeCleanup.await()
        assertFalse(retire.isCompleted); assertEquals(0, player.releaseCount)
        allowNativeCleanup.complete(Unit); pixelCleanup.await()
        assertFalse(retire.isCompleted); assertEquals(0, player.releaseCount)
        allowPixelCleanup.complete(Unit); retire.await(); render.join()
        assertEquals(listOf("frame", "pixels", "release"), order)
    }

    @Test fun callerCancellationJoinsItsRenderLoopWithoutRetiringTheController() = runTest {
        val entered = CompletableDeferred<Unit>()
        val cleanup = CompletableDeferred<Unit>()
        val finish = CompletableDeferred<Unit>()
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            val render = launch {
                controller.withSoftwareRendering {
                    try { entered.complete(Unit); awaitCancellation() }
                    finally { withContext(NonCancellable) { cleanup.complete(Unit); finish.await() } }
                }
            }
            entered.await()
            val cancel = async { render.cancelAndJoin() }
            cleanup.await(); assertFalse(cancel.isCompleted)
            finish.complete(Unit); cancel.await()
            controller.play(); runCurrent()
            assertTrue(player.played.isCompleted); assertEquals(0, player.releaseCount)
        } finally { controller.releaseAndJoin() }
    }

    @Test fun lateNativeSuccessCannotPublishAFrameAfterCallerExpiry() = runTest {
        checkLateResult(throwFailure = false, retireController = false)
    }

    @Test fun lateNativeFailureBecomesCancellationBeforeUiErrorHandling() = runTest {
        checkLateResult(throwFailure = true, retireController = true)
    }

    private suspend fun kotlinx.coroutines.test.TestScope.checkLateResult(throwFailure: Boolean, retireController: Boolean) {
        val entered = CompletableDeferred<Unit>()
        val finish = CompletableDeferred<Unit>()
        var published = 0
        var errors = 0
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { width, height -> withContext(NonCancellable) {
                entered.complete(Unit); finish.await()
                if (throwFailure) error("late native failure")
                frame(width, height)
            } }
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val render = launch {
            controller.withSoftwareRendering { renderer ->
                try { renderer.renderFrame(4, 2); published++ }
                catch (cancelled: CancellationException) { throw cancelled }
                catch (_: Throwable) { errors++ }
            }
        }
        entered.await()
        if (retireController) controller.release() else render.cancel()
        runCurrent(); assertFalse(render.isCompleted); assertEquals(0, player.releaseCount)
        finish.complete(Unit); render.join(); controller.releaseAndJoin()
        assertEquals(0, published); assertEquals(0, errors); assertTrue(render.isCancelled)
    }

    @Test fun completedLoopExpiresRetainedRendererCallbacks() = runTest {
        var retained: MpvSoftwareRenderer? = null
        var calls = 0
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { width, height -> calls++; frame(width, height) }
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        try {
            controller.withSoftwareRendering { retained = it }
            val failure = runCatching { checkNotNull(retained).renderFrame(4, 2) }.exceptionOrNull()
            assertIs<CancellationException>(failure); assertEquals(0, calls)
        } finally { controller.releaseAndJoin() }
    }

    @Test fun liveRendererCannotEscapeIntoUntrackedCoroutineWork() = runTest {
        val admitted = CompletableDeferred<MpvSoftwareRenderer>()
        var calls = 0
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {
            onRender = { width, height -> calls++; frame(width, height) }
        }
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val render = launch { controller.withSoftwareRendering { admitted.complete(it); awaitCancellation() } }
        try {
            val retained = admitted.await()
            assertIs<CancellationException>(runCatching { retained.renderFrame(4, 2) }.exceptionOrNull())
            assertEquals(0, calls)
        } finally { render.cancelAndJoin(); controller.releaseAndJoin() }
    }

    @Test fun retiredControllerAndCancelledCallerCannotStartRenderLoops() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        var started = 0
        val cancelled = launch {
            currentCoroutineContext().cancel()
            assertIs<CancellationException>(runCatching {
                controller.withSoftwareRendering { started++ }
            }.exceptionOrNull())
        }
        cancelled.join()
        controller.releaseAndJoin()
        assertIs<CancellationException>(runCatching {
            controller.withSoftwareRendering { started++ }
        }.exceptionOrNull())
        assertEquals(0, started)
    }

    @Test fun cancellingOneLoopLeavesAnotherLoopAndControllerAlive() = runTest {
        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()
        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))
        val firstStarted = CompletableDeferred<Unit>()
        val secondStarted = CompletableDeferred<Unit>()
        val first = launch { controller.withSoftwareRendering { firstStarted.complete(Unit); awaitCancellation() } }
        val second = launch { controller.withSoftwareRendering { secondStarted.complete(Unit); awaitCancellation() } }
        try {
            firstStarted.await(); secondStarted.await(); first.cancelAndJoin()
            assertTrue(second.isActive); assertEquals(0, player.releaseCount)
        } finally { second.cancelAndJoin(); controller.releaseAndJoin() }
    }

    private fun frame(width: Int, height: Int) = MpvSoftwareFrame(width, height, width * 4, ByteArray(width * height * 4))
}
```
[chapter-file-end]: #

### 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: prepare→resume→play and quality/episode switches are deterministic; cancellation and native command failure release resources; Cast/PiP do not duplicate players; local files play offline. Use player initialization/retirement/command/surface/position tests, extractor fixtures, Cast codec/session and torrent tests, then real-device/native runs.
