From 2abb690c2a4b96fafbaba45a7711728852ffe749 Mon Sep 17 00:00:00 2001 From: Niewiarowski <21334271+Niewiarowski@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:46:42 -0500 Subject: [PATCH] test(linux/cuda): cover the GL->CUDA frame handoff Move the per-frame handoff and the GL fence wait into functions that take their GL and CUDA calls as parameters, and test them with fakes: the order of GL and CUDA work with two and three planes, every failing step, and every GL wait status. The mapped path now unmaps the textures when getting a mapped array fails, instead of returning with them still mapped. --- src/platform/linux/cuda.cpp | 162 +++++++++------ src/platform/linux/cuda.h | 45 ++++ tests/unit/platform/linux/test_cuda.cpp | 261 ++++++++++++++++++++++++ 3 files changed, 404 insertions(+), 64 deletions(-) diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 7ee821ba2..88a42fd1a 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -503,6 +503,44 @@ namespace cuda { registered_resource_t uv_res; ///< Uv res. }; + int wait_for_gl_fence(const gl_fence_ops_t &ops) { + auto fence = ops.create(); + if (!fence) { + BOOST_LOG(error) << "Couldn't create GL fence"sv; + return -1; + } + + auto status = ops.client_wait(fence); + ops.destroy(fence); + if (status != GL_ALREADY_SIGNALED && status != GL_CONDITION_SATISFIED) { + BOOST_LOG(error) << "Waiting for GL fence failed: "sv << util::hex(status).to_string_view(); + return -1; + } + + return 0; + } + + int gl_cuda_handoff(bool shared_planes, int plane_count, const gl_cuda_handoff_ops_t &ops) { + if (shared_planes && ops.wait_for_cuda()) { + return -1; + } + + ops.render(); + + if (shared_planes ? ops.wait_for_gl() : ops.map()) { + return -1; + } + + int status = 0; + for (int plane = 0; plane < plane_count && status == 0; ++plane) { + status = ops.copy(plane); + } + + // Release what this frame acquired even when a copy failed. + const int release_status = shared_planes ? ops.record_copies() : ops.unmap(); + return status || release_status ? -1 : 0; + } + /** * @brief Output plane textures shared by GL and CUDA through external memory. * @@ -750,21 +788,19 @@ namespace cuda { * @return 0 on success or -1 on failure. */ int wait_for_gl() { - auto fence = gl::ctx.FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); - if (!fence) { - BOOST_LOG(error) << "Couldn't create GL fence: "sv << gl::ctx.GetError(); - return -1; - } - - // Generous timeout: this only guards against a hung GPU. - auto status = gl::ctx.ClientWaitSync(fence, GL_SYNC_FLUSH_COMMANDS_BIT, std::chrono::nanoseconds(1s).count()); - gl::ctx.DeleteSync(fence); - if (status == GL_TIMEOUT_EXPIRED || status == GL_WAIT_FAILED) { - BOOST_LOG(error) << "Waiting for GL fence failed: "sv << util::hex(status).to_string_view(); - return -1; - } - - return 0; + static const gl_fence_ops_t ops { + .create = [] { + return (void *) gl::ctx.FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + }, + // Generous timeout: this only guards against a hung GPU. + .client_wait = [](void *fence) { + return (std::uint32_t) gl::ctx.ClientWaitSync((GLsync) fence, GL_SYNC_FLUSH_COMMANDS_BIT, std::chrono::nanoseconds(1s).count()); + }, + .destroy = [](void *fence) { + gl::ctx.DeleteSync((GLsync) fence); + }, + }; + return wait_for_gl_fence(ops); } /** @@ -1085,61 +1121,59 @@ namespace cuda { sws.load_vram(descriptor, offset_x, offset_y, rgb->tex[0], is_yuv444); - // Perform the color conversion and scaling in GL, once CUDA is done reading the previous frame - if (shared.is_active() && shared.wait_for_cuda()) { - return -1; - } - if (is_yuv444) { - sws.convert_yuv444(yuv444->buf); - } else { - sws.convert_nv12(nv12->buf); - } - - std::array arrays {}; std::array resources {}; - if (shared.is_active()) { - if (shared.wait_for_gl()) { - return -1; - } - for (int i = 0; i < plane_count; i++) { - arrays[i] = shared.array(i); - } + if (is_yuv444) { + resources = {{cu_res.y_res.get(), cu_res.u_res.get(), cu_res.v_res.get()}}; } else { - // Map the GL textures to read for CUDA - if (is_yuv444) { - resources = {{cu_res.y_res.get(), cu_res.u_res.get(), cu_res.v_res.get()}}; - } else { - resources = {{cu_res.y_res.get(), cu_res.uv_res.get(), nullptr}}; - } - CU_CHECK(cdf->cuGraphicsMapResources(plane_count, resources.data(), stream.get()), "Couldn't map GL textures in CUDA"); - for (int i = 0; i < plane_count; i++) { - CU_CHECK(cdf->cuGraphicsSubResourceGetMappedArray(&arrays[i], resources[i], 0, 0), "Couldn't get mapped plane array"); - } + resources = {{cu_res.y_res.get(), cu_res.uv_res.get(), nullptr}}; } - // Copy from the GL textures to the target CUDA frame - for (int i = 0; i < plane_count; i++) { - CUDA_MEMCPY2D cpy = {}; - cpy.srcMemoryType = CU_MEMORYTYPE_ARRAY; - cpy.srcArray = arrays[i]; + return gl_cuda_handoff(shared.is_active(), plane_count, { + .wait_for_cuda = [this] { + return shared.wait_for_cuda(); + }, + // Perform the color conversion and scaling in GL + .render = [this] { + if (is_yuv444) { + sws.convert_yuv444(yuv444->buf); + } else { + sws.convert_nv12(nv12->buf); + } + }, + .wait_for_gl = [this] { + return shared.wait_for_gl(); + }, + .map = [&] { + CU_CHECK(cdf->cuGraphicsMapResources(plane_count, resources.data(), stream.get()), "Couldn't map GL textures in CUDA"); + return 0; + }, + // Copy from the GL textures to the target CUDA frame + .copy = [&](int plane) { + CUDA_MEMCPY2D cpy = {}; + cpy.srcMemoryType = CU_MEMORYTYPE_ARRAY; + if (shared.is_active()) { + cpy.srcArray = shared.array(plane); + } else { + CU_CHECK(cdf->cuGraphicsSubResourceGetMappedArray(&cpy.srcArray, resources[plane], 0, 0), "Couldn't get mapped plane array"); + } - cpy.dstMemoryType = CU_MEMORYTYPE_DEVICE; - cpy.dstDevice = (CUdeviceptr) frame->data[i]; - cpy.dstPitch = frame->linesize[i]; - cpy.WidthInBytes = (frame->width * fmt_desc->comp[i].step) >> (i ? fmt_desc->log2_chroma_w : 0); - cpy.Height = frame->height >> (i ? fmt_desc->log2_chroma_h : 0); + cpy.dstMemoryType = CU_MEMORYTYPE_DEVICE; + cpy.dstDevice = (CUdeviceptr) frame->data[plane]; + cpy.dstPitch = frame->linesize[plane]; + cpy.WidthInBytes = (frame->width * fmt_desc->comp[plane].step) >> (plane ? fmt_desc->log2_chroma_w : 0); + cpy.Height = frame->height >> (plane ? fmt_desc->log2_chroma_h : 0); - CU_CHECK_IGNORE(cdf->cuMemcpy2DAsync(&cpy, stream.get()), "Couldn't copy texture to CUDA frame"); - } - - if (shared.is_active()) { - return shared.record_copies(stream.get()); - } - - // Unmap the textures to allow modification from GL again - CU_CHECK(cdf->cuGraphicsUnmapResources(plane_count, resources.data(), stream.get()), "Couldn't unmap GL textures from CUDA"); - - return 0; + CU_CHECK_IGNORE(cdf->cuMemcpy2DAsync(&cpy, stream.get()), "Couldn't copy texture to CUDA frame"); + return 0; + }, + .unmap = [&] { + CU_CHECK(cdf->cuGraphicsUnmapResources(plane_count, resources.data(), stream.get()), "Couldn't unmap GL textures from CUDA"); + return 0; + }, + .record_copies = [this] { + return shared.record_copies(stream.get()); + }, + }); } /** diff --git a/src/platform/linux/cuda.h b/src/platform/linux/cuda.h index 61be5488c..4e300b77d 100644 --- a/src/platform/linux/cuda.h +++ b/src/platform/linux/cuda.h @@ -11,6 +11,7 @@ // standard includes #include #include + #include #include #include #include @@ -92,6 +93,50 @@ namespace cuda { */ std::optional device_pci_bus_id(int index, const cuda_pci_accessors_t &accessors); + /** + * @brief GL fence calls used to wait for GL on the CPU. + */ + struct gl_fence_ops_t { + std::function create; ///< Insert a fence after the submitted GL commands, returning null on failure. + std::function client_wait; ///< Wait for the fence, returning the GL wait status. + std::function destroy; ///< Delete the fence. + }; + + /** + * @brief Block until GL has finished the commands submitted so far. + * + * @param ops GL fence calls. + * @return 0 on success or -1 when the fence couldn't be created, timed out or failed. + */ + int wait_for_gl_fence(const gl_fence_ops_t &ops); + + /** + * @brief Steps of handing one converted frame from GL to CUDA. + */ + struct gl_cuda_handoff_ops_t { + std::function wait_for_cuda; ///< Shared planes: block until the previous frame's copies are done. + std::function render; ///< Render the frame into the plane textures with GL. + std::function wait_for_gl; ///< Shared planes: block until GL has finished rendering. + std::function map; ///< Mapped planes: map the plane textures into CUDA. + std::function copy; ///< Queue the copy of one plane into the frame. + std::function unmap; ///< Mapped planes: unmap the plane textures. + std::function record_copies; ///< Shared planes: record the queued copies for the next wait_for_cuda. + }; + + /** + * @brief Hand one converted frame from GL to CUDA. + * + * With shared planes, GL and CUDA take turns through CPU waits. Otherwise the plane + * textures are mapped into CUDA for the copies only. Whatever a frame acquires is + * released even when a copy fails. + * + * @param shared_planes Whether the planes are shared through external memory. + * @param plane_count Number of planes to copy. + * @param ops Steps of the handoff. + * @return 0 on success or -1 on failure. + */ + int gl_cuda_handoff(bool shared_planes, int plane_count, const gl_cuda_handoff_ops_t &ops); + int init(); } // namespace cuda diff --git a/tests/unit/platform/linux/test_cuda.cpp b/tests/unit/platform/linux/test_cuda.cpp index ec6cabc47..6effd186f 100644 --- a/tests/unit/platform/linux/test_cuda.cpp +++ b/tests/unit/platform/linux/test_cuda.cpp @@ -11,6 +11,11 @@ // standard includes #include #include + #include + #include + + // lib includes + #include // local includes #include "src/platform/linux/cuda.h" @@ -46,4 +51,260 @@ TEST(NvFbcDisplaySelectionTest, OffersVirtualDesktopOnlyForValidNoOutputCapture) } } + #ifdef SUNSHINE_BUILD_CUDA +namespace { + /** + * @brief Fake GL->CUDA handoff steps that record their order and check plane access. + * + * GL must not render into the planes while they are mapped into CUDA or before + * CUDA has copied the previous frame out, and CUDA must not copy them before GL + * has finished rendering. + */ + struct fake_handoff_t { + std::vector calls; ///< Steps in the order they ran. + std::string failing_step; ///< Step that returns an error, or empty. + int failing_plane = -1; ///< Plane whose copy returns an error, or -1. + bool mapped = false; ///< Whether the planes are mapped into CUDA. + bool gl_finished = false; ///< Whether GL has finished the current frame's rendering. + bool copies_finished = true; ///< Whether CUDA has finished the previous frame's copies. + + /** + * @brief Record a step and return its result. + * + * @param name Step name. + * @return -1 when `name` is the failing step, 0 otherwise. + */ + int step(const std::string &name) { + calls.push_back(name); + return name == failing_step ? -1 : 0; + } + + /** + * @brief Handoff steps backed by this fake. + * + * @return The steps. + */ + cuda::gl_cuda_handoff_ops_t ops() { + return { + .wait_for_cuda = [this] { + const int status = step("wait_for_cuda"); + copies_finished = copies_finished || status == 0; + return status; + }, + .render = [this] { + calls.emplace_back("render"); + EXPECT_FALSE(mapped) << "GL rendered into planes mapped into CUDA"; + EXPECT_TRUE(copies_finished) << "GL rendered before CUDA copied the previous frame"; + gl_finished = false; + }, + .wait_for_gl = [this] { + const int status = step("wait_for_gl"); + gl_finished = status == 0; + return status; + }, + .map = [this] { + const int status = step("map"); + mapped = status == 0; + gl_finished = mapped; // Mapping waits for GL. + return status; + }, + .copy = [this](int plane) { + calls.push_back("copy" + std::to_string(plane)); + EXPECT_TRUE(gl_finished) << "CUDA copied before GL finished rendering"; + copies_finished = false; + return plane == failing_plane ? -1 : 0; + }, + .unmap = [this] { + EXPECT_TRUE(mapped) << "unmapped planes that weren't mapped"; + mapped = false; + copies_finished = true; // Unmapping orders the copies before later GL work. + return step("unmap"); + }, + .record_copies = [this] { + return step("record_copies"); + }, + }; + } + }; + + /** + * @brief Expected steps of one successful frame. + * + * @param shared_planes Whether the planes are shared through external memory. + * @param plane_count Number of planes. + * @return The steps in order. + */ + std::vector successful_frame(bool shared_planes, int plane_count) { + std::vector steps; + if (shared_planes) { + steps.emplace_back("wait_for_cuda"); + } + steps.emplace_back("render"); + steps.emplace_back(shared_planes ? "wait_for_gl" : "map"); + for (int plane = 0; plane < plane_count; ++plane) { + steps.push_back("copy" + std::to_string(plane)); + } + steps.emplace_back(shared_planes ? "record_copies" : "unmap"); + return steps; + } + + /** + * @brief Plane counts: two for NV12 and P010, three for YUV 4:4:4. + */ + class GlCudaHandoffPlanesTest: public testing::TestWithParam {}; +} // namespace + +TEST_P(GlCudaHandoffPlanesTest, SharedPlanesTakeTurnsAcrossFrames) { + const int plane_count = GetParam(); + fake_handoff_t fake; + + ASSERT_EQ(cuda::gl_cuda_handoff(true, plane_count, fake.ops()), 0); + ASSERT_EQ(cuda::gl_cuda_handoff(true, plane_count, fake.ops()), 0); + + auto expected = successful_frame(true, plane_count); + const auto second_frame = expected; + expected.insert(expected.end(), second_frame.begin(), second_frame.end()); + EXPECT_EQ(fake.calls, expected); +} + +TEST_P(GlCudaHandoffPlanesTest, MappedPlanesAreMappedOnlyForTheCopies) { + const int plane_count = GetParam(); + fake_handoff_t fake; + + ASSERT_EQ(cuda::gl_cuda_handoff(false, plane_count, fake.ops()), 0); + ASSERT_EQ(cuda::gl_cuda_handoff(false, plane_count, fake.ops()), 0); + + auto expected = successful_frame(false, plane_count); + const auto second_frame = expected; + expected.insert(expected.end(), second_frame.begin(), second_frame.end()); + EXPECT_EQ(fake.calls, expected); + EXPECT_FALSE(fake.mapped); +} + +INSTANTIATE_TEST_SUITE_P(PlaneCounts, GlCudaHandoffPlanesTest, testing::Values(2, 3)); + +TEST(GlCudaHandoffTest, SharedPlanesStopWhenWaitingForCudaFails) { + fake_handoff_t fake {.failing_step = "wait_for_cuda"}; + + EXPECT_EQ(cuda::gl_cuda_handoff(true, 2, fake.ops()), -1); + EXPECT_EQ(fake.calls, (std::vector {"wait_for_cuda"})); +} + +TEST(GlCudaHandoffTest, SharedPlanesSkipTheCopiesWhenWaitingForGlFails) { + fake_handoff_t fake {.failing_step = "wait_for_gl"}; + + EXPECT_EQ(cuda::gl_cuda_handoff(true, 2, fake.ops()), -1); + EXPECT_EQ(fake.calls, (std::vector {"wait_for_cuda", "render", "wait_for_gl"})); +} + +TEST(GlCudaHandoffTest, SharedPlanesRecordQueuedCopiesWhenACopyFails) { + fake_handoff_t fake {.failing_plane = 0}; + + EXPECT_EQ(cuda::gl_cuda_handoff(true, 3, fake.ops()), -1); + EXPECT_EQ(fake.calls, (std::vector {"wait_for_cuda", "render", "wait_for_gl", "copy0", "record_copies"})); +} + +TEST(GlCudaHandoffTest, SharedPlanesFailWhenRecordingTheCopiesFails) { + fake_handoff_t fake {.failing_step = "record_copies"}; + + EXPECT_EQ(cuda::gl_cuda_handoff(true, 2, fake.ops()), -1); + EXPECT_EQ(fake.calls, successful_frame(true, 2)); +} + +TEST(GlCudaHandoffTest, MappedPlanesSkipTheCopiesWhenMappingFails) { + fake_handoff_t fake {.failing_step = "map"}; + + EXPECT_EQ(cuda::gl_cuda_handoff(false, 2, fake.ops()), -1); + EXPECT_EQ(fake.calls, (std::vector {"render", "map"})); + EXPECT_FALSE(fake.mapped); +} + +TEST(GlCudaHandoffTest, MappedPlanesAreUnmappedOnceWhenACopyFails) { + fake_handoff_t fake {.failing_plane = 1}; + + EXPECT_EQ(cuda::gl_cuda_handoff(false, 3, fake.ops()), -1); + EXPECT_EQ(fake.calls, (std::vector {"render", "map", "copy0", "copy1", "unmap"})); + EXPECT_FALSE(fake.mapped); + + // The next frame starts with the planes back in GL's hands. + fake.failing_plane = -1; + EXPECT_EQ(cuda::gl_cuda_handoff(false, 3, fake.ops()), 0); +} + +TEST(GlCudaHandoffTest, MappedPlanesFailWhenUnmappingFails) { + fake_handoff_t fake {.failing_step = "unmap"}; + + EXPECT_EQ(cuda::gl_cuda_handoff(false, 2, fake.ops()), -1); + EXPECT_EQ(fake.calls, successful_frame(false, 2)); +} + +namespace { + /** + * @brief Fake GL fence that records how it was used. + */ + struct fake_fence_t { + bool create_fails = false; ///< Whether creating the fence fails. + std::uint32_t wait_status = GL_ALREADY_SIGNALED; ///< Status the wait returns. + int waits = 0; ///< Number of waits. + int destroys = 0; ///< Number of deletions. + void *destroyed = nullptr; ///< Fence passed to the last deletion. + + /** + * @brief Fence calls backed by this fake. + * + * @return The calls. + */ + cuda::gl_fence_ops_t ops() { + return { + .create = [this]() -> void * { + return create_fails ? nullptr : this; + }, + .client_wait = [this](void *) { + ++waits; + return wait_status; + }, + .destroy = [this](void *fence) { + ++destroys; + destroyed = fence; + }, + }; + } + }; + + /** + * @brief GL wait statuses and whether waiting for GL succeeds with them. + */ + class GlFenceWaitStatusTest: public testing::TestWithParam> {}; +} // namespace + +TEST(GlFenceWaitTest, FailsWithoutWaitingWhenTheFenceCannotBeCreated) { + fake_fence_t fake {.create_fails = true}; + + EXPECT_EQ(cuda::wait_for_gl_fence(fake.ops()), -1); + EXPECT_EQ(fake.waits, 0); + EXPECT_EQ(fake.destroys, 0); +} + +TEST_P(GlFenceWaitStatusTest, DeletesTheFenceOnceAndReportsTheStatus) { + const auto [status, expected] = GetParam(); + fake_fence_t fake {.wait_status = status}; + + EXPECT_EQ(cuda::wait_for_gl_fence(fake.ops()), expected); + EXPECT_EQ(fake.waits, 1); + EXPECT_EQ(fake.destroys, 1); + EXPECT_EQ(fake.destroyed, &fake); +} + +INSTANTIATE_TEST_SUITE_P( + Statuses, + GlFenceWaitStatusTest, + testing::Values( + std::pair {GL_ALREADY_SIGNALED, 0}, + std::pair {GL_CONDITION_SATISFIED, 0}, + std::pair {GL_TIMEOUT_EXPIRED, -1}, + std::pair {GL_WAIT_FAILED, -1} + ) +); + #endif // SUNSHINE_BUILD_CUDA + #endif // __linux__