Yokan / rebuild
Course 1 8624561

MpvSoftwareRenderingTest.kt

composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/media/player/MpvSoftwareRenderingTest.kt

test / fixture204 lines
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.media.player45import io.github.kmpmpv.MpvSoftwareFrame6import kotlinx.coroutines.CancellationException7import kotlinx.coroutines.CompletableDeferred8import kotlinx.coroutines.CoroutineName9import kotlinx.coroutines.NonCancellable10import kotlinx.coroutines.async11import kotlinx.coroutines.awaitCancellation12import kotlinx.coroutines.cancel13import kotlinx.coroutines.cancelAndJoin14import kotlinx.coroutines.currentCoroutineContext15import kotlinx.coroutines.launch16import kotlinx.coroutines.test.StandardTestDispatcher17import kotlinx.coroutines.test.runCurrent18import kotlinx.coroutines.test.runTest19import kotlinx.coroutines.withContext20import kotlin.test.Test21import kotlin.test.assertEquals22import kotlin.test.assertFalse23import kotlin.test.assertIs24import kotlin.test.assertSame25import kotlin.test.assertTrue2627class MpvSoftwareRenderingTest {28    @Test fun frameWorkKeepsTheCapturedUiContextAndDoesNotWaitForLoadCommands() = runTest {29        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()30        val expected = frame(4, 2)31        player.onRender = { width, height ->32            assertEquals(4, width); assertEquals(2, height)33            expected34        }35        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))36        try {37            controller.load("https://example.test/stalled.mp4")38            runCurrent()39            val render = async(CoroutineName("captured-ui")) {40                controller.withSoftwareRendering { renderer ->41                    assertEquals("captured-ui", currentCoroutineContext()[CoroutineName]?.name)42                    assertSame(expected, renderer.renderFrame(4, 2))43                }44            }45            runCurrent()46            render.await()47            assertFalse(player.played.isCompleted)48        } finally { controller.releaseAndJoin() }49    }5051    @Test fun retirementJoinsNativeFinalizersAndUiPixelCleanupBeforeNativeRelease() = runTest {52        val nativeStarted = CompletableDeferred<Unit>()53        val nativeCleanup = CompletableDeferred<Unit>()54        val allowNativeCleanup = CompletableDeferred<Unit>()55        val pixelCleanup = CompletableDeferred<Unit>()56        val allowPixelCleanup = CompletableDeferred<Unit>()57        val order = mutableListOf<String>()58        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {59            onRender = { _, _ ->60                try { nativeStarted.complete(Unit); awaitCancellation() }61                finally { withContext(NonCancellable) {62                    nativeCleanup.complete(Unit); allowNativeCleanup.await(); order += "frame"63                } }64            }65            onRelease = { order += "release" }66        }67        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))68        val render = launch {69            controller.withSoftwareRendering { renderer ->70                try { renderer.renderFrame(4, 2) }71                finally { withContext(NonCancellable) {72                    pixelCleanup.complete(Unit); allowPixelCleanup.await(); order += "pixels"73                } }74            }75        }76        nativeStarted.await()77        val retire = async { controller.releaseAndJoin() }78        nativeCleanup.await()79        assertFalse(retire.isCompleted); assertEquals(0, player.releaseCount)80        allowNativeCleanup.complete(Unit); pixelCleanup.await()81        assertFalse(retire.isCompleted); assertEquals(0, player.releaseCount)82        allowPixelCleanup.complete(Unit); retire.await(); render.join()83        assertEquals(listOf("frame", "pixels", "release"), order)84    }8586    @Test fun callerCancellationJoinsItsRenderLoopWithoutRetiringTheController() = runTest {87        val entered = CompletableDeferred<Unit>()88        val cleanup = CompletableDeferred<Unit>()89        val finish = CompletableDeferred<Unit>()90        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()91        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))92        try {93            val render = launch {94                controller.withSoftwareRendering {95                    try { entered.complete(Unit); awaitCancellation() }96                    finally { withContext(NonCancellable) { cleanup.complete(Unit); finish.await() } }97                }98            }99            entered.await()100            val cancel = async { render.cancelAndJoin() }101            cleanup.await(); assertFalse(cancel.isCompleted)102            finish.complete(Unit); cancel.await()103            controller.play(); runCurrent()104            assertTrue(player.played.isCompleted); assertEquals(0, player.releaseCount)105        } finally { controller.releaseAndJoin() }106    }107108    @Test fun lateNativeSuccessCannotPublishAFrameAfterCallerExpiry() = runTest {109        checkLateResult(throwFailure = false, retireController = false)110    }111112    @Test fun lateNativeFailureBecomesCancellationBeforeUiErrorHandling() = runTest {113        checkLateResult(throwFailure = true, retireController = true)114    }115116    private suspend fun kotlinx.coroutines.test.TestScope.checkLateResult(throwFailure: Boolean, retireController: Boolean) {117        val entered = CompletableDeferred<Unit>()118        val finish = CompletableDeferred<Unit>()119        var published = 0120        var errors = 0121        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {122            onRender = { width, height -> withContext(NonCancellable) {123                entered.complete(Unit); finish.await()124                if (throwFailure) error("late native failure")125                frame(width, height)126            } }127        }128        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))129        val render = launch {130            controller.withSoftwareRendering { renderer ->131                try { renderer.renderFrame(4, 2); published++ }132                catch (cancelled: CancellationException) { throw cancelled }133                catch (_: Throwable) { errors++ }134            }135        }136        entered.await()137        if (retireController) controller.release() else render.cancel()138        runCurrent(); assertFalse(render.isCompleted); assertEquals(0, player.releaseCount)139        finish.complete(Unit); render.join(); controller.releaseAndJoin()140        assertEquals(0, published); assertEquals(0, errors); assertTrue(render.isCancelled)141    }142143    @Test fun completedLoopExpiresRetainedRendererCallbacks() = runTest {144        var retained: MpvSoftwareRenderer? = null145        var calls = 0146        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {147            onRender = { width, height -> calls++; frame(width, height) }148        }149        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))150        try {151            controller.withSoftwareRendering { retained = it }152            val failure = runCatching { checkNotNull(retained).renderFrame(4, 2) }.exceptionOrNull()153            assertIs<CancellationException>(failure); assertEquals(0, calls)154        } finally { controller.releaseAndJoin() }155    }156157    @Test fun liveRendererCannotEscapeIntoUntrackedCoroutineWork() = runTest {158        val admitted = CompletableDeferred<MpvSoftwareRenderer>()159        var calls = 0160        val player = MediaPlayerInitializationTest.RecordingMpvPlayer().apply {161            onRender = { width, height -> calls++; frame(width, height) }162        }163        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))164        val render = launch { controller.withSoftwareRendering { admitted.complete(it); awaitCancellation() } }165        try {166            val retained = admitted.await()167            assertIs<CancellationException>(runCatching { retained.renderFrame(4, 2) }.exceptionOrNull())168            assertEquals(0, calls)169        } finally { render.cancelAndJoin(); controller.releaseAndJoin() }170    }171172    @Test fun retiredControllerAndCancelledCallerCannotStartRenderLoops() = runTest {173        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()174        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))175        var started = 0176        val cancelled = launch {177            currentCoroutineContext().cancel()178            assertIs<CancellationException>(runCatching {179                controller.withSoftwareRendering { started++ }180            }.exceptionOrNull())181        }182        cancelled.join()183        controller.releaseAndJoin()184        assertIs<CancellationException>(runCatching {185            controller.withSoftwareRendering { started++ }186        }.exceptionOrNull())187        assertEquals(0, started)188    }189190    @Test fun cancellingOneLoopLeavesAnotherLoopAndControllerAlive() = runTest {191        val player = MediaPlayerInitializationTest.RecordingMpvPlayer()192        val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, StandardTestDispatcher(testScheduler))193        val firstStarted = CompletableDeferred<Unit>()194        val secondStarted = CompletableDeferred<Unit>()195        val first = launch { controller.withSoftwareRendering { firstStarted.complete(Unit); awaitCancellation() } }196        val second = launch { controller.withSoftwareRendering { secondStarted.complete(Unit); awaitCancellation() } }197        try {198            firstStarted.await(); secondStarted.await(); first.cancelAndJoin()199            assertTrue(second.isActive); assertEquals(0, player.releaseCount)200        } finally { second.cancelAndJoin(); controller.releaseAndJoin() }201    }202203    private fun frame(width: Int, height: Int) = MpvSoftwareFrame(width, height, width * 4, ByteArray(width * height * 4))204}205

Search chapters, reference and source filenames.