@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() val nativeCleanup = CompletableDeferred() val allowNativeCleanup = CompletableDeferred() val pixelCleanup = CompletableDeferred() val allowPixelCleanup = CompletableDeferred() val order = mutableListOf() 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() val cleanup = CompletableDeferred() val finish = CompletableDeferred() 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() val finish = CompletableDeferred() 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(failure); assertEquals(0, calls) } finally { controller.releaseAndJoin() } } @Test fun liveRendererCannotEscapeIntoUntrackedCoroutineWork() = runTest { val admitted = CompletableDeferred() 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(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(runCatching { controller.withSoftwareRendering { started++ } }.exceptionOrNull()) } cancelled.join() controller.releaseAndJoin() assertIs(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() val secondStarted = CompletableDeferred() 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)) }