From 1925909fbc19014b236ac0d17e18bce1a3d90ecb Mon Sep 17 00:00:00 2001 From: Dave Lane <42013603+ReenigneArcher@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:09:32 -0400 Subject: [PATCH] refactor: resolve Sonar cpp:S5008 findings (#5909) --- src/audio.cpp | 6 +- src/audio.h | 12 +- src/cbs.cpp | 32 ++-- src/input.cpp | 10 +- src/logging.cpp | 2 +- src/nvenc/nvenc_base.cpp | 10 +- src/nvenc/nvenc_base.h | 23 ++- src/nvenc/nvenc_d3d11.cpp | 2 +- src/nvenc/nvenc_d3d11_on_cuda.cpp | 5 +- src/platform/common.h | 12 +- src/platform/linux/audio.cpp | 4 +- src/platform/linux/cuda.cpp | 6 +- src/platform/linux/graphics.cpp | 2 +- src/platform/linux/kwingrab.cpp | 28 +-- src/platform/linux/misc.cpp | 10 +- src/platform/linux/misc.h | 20 ++- src/platform/linux/pipewire.cpp | 10 +- src/platform/linux/publish.cpp | 8 +- src/platform/linux/vaapi.cpp | 5 +- src/platform/linux/vulkan_encode.cpp | 3 +- src/platform/linux/wayland.cpp | 2 +- src/platform/linux/x11grab.cpp | 70 ++++++-- src/platform/macos/display.mm | 10 +- src/platform/macos/nv12_zero_device.cpp | 6 +- src/platform/macos/nv12_zero_device.h | 19 ++- src/platform/macos/publish.cpp | 2 +- src/platform/windows/audio.cpp | 2 +- src/platform/windows/display_vram.cpp | 3 +- src/platform/windows/display_wgc.cpp | 2 +- src/platform/windows/input.cpp | 4 +- src/platform/windows/nvprefs/nvprefs_common.h | 4 +- src/platform/windows/publish.cpp | 2 +- src/stream.cpp | 4 +- src/utility.h | 6 +- src/video.cpp | 50 +++--- src/video.h | 10 +- .../platform/linux/test_dynamic_loader.cpp | 48 ++++++ tests/unit/test_audio.cpp | 29 ++++ tests/unit/test_cbs.cpp | 116 +++++++++++++ tests/unit/test_encode_device.cpp | 112 ++++++++++++ tests/unit/test_nvenc_utils.cpp | 160 +++++++++++++++++- 41 files changed, 722 insertions(+), 149 deletions(-) create mode 100644 tests/unit/platform/linux/test_dynamic_loader.cpp create mode 100644 tests/unit/test_cbs.cpp create mode 100644 tests/unit/test_encode_device.cpp diff --git a/src/audio.cpp b/src/audio.cpp index 62d4cabbc..112dffb19 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -105,9 +105,9 @@ namespace audio { * * @param samples Queue of captured PCM sample buffers to encode. * @param config Audio stream settings negotiated with the client. - * @param channel_data Platform-specific audio capture context passed to packet metadata. + * @param channel_data Stream session carried with each encoded packet. */ - void encodeThread(sample_queue_t samples, config_t config, void *channel_data) { + void encodeThread(sample_queue_t samples, config_t config, stream::session_t *channel_data) { auto packets = mail::man->queue(mail::audio_packets); auto stream = stream_configs[map_stream(config.channels, config.flags[config_t::HIGH_QUALITY])]; if (config.flags[config_t::CUSTOM_SURROUND_PARAMS]) { @@ -155,7 +155,7 @@ namespace audio { /** * @brief Run the capture loop for this backend. */ - void capture(safe::mail_t mail, config_t config, void *channel_data) { + void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data) { auto shutdown_event = mail->event(mail::shutdown); if (!config::audio.stream) { shutdown_event->view(); diff --git a/src/audio.h b/src/audio.h index f21417283..a67092510 100644 --- a/src/audio.h +++ b/src/audio.h @@ -12,6 +12,10 @@ #include #include +namespace stream { + struct session_t; +} + namespace audio { /** * @brief Supported Opus channel layouts advertised to Moonlight clients. @@ -95,9 +99,9 @@ namespace audio { */ using buffer_t = util::buffer_t; /** - * @brief Encoded audio packet paired with platform channel metadata. + * @brief Encoded audio packet paired with its owning stream session. */ - using packet_t = std::pair; + using packet_t = std::pair; /** * @brief Shared mailbox reference to the global audio context. */ @@ -108,9 +112,9 @@ namespace audio { * * @param mail Mailbox used to publish encoded audio packets. * @param config Audio capture and encoder settings. - * @param channel_data Platform-specific capture channel pointer. + * @param channel_data Stream session that receives the encoded packets. */ - void capture(safe::mail_t mail, config_t config, void *channel_data); + void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data); /** * @brief Get the reference to the audio context. diff --git a/src/cbs.cpp b/src/cbs.cpp index 9d98da561..54464e949 100644 --- a/src/cbs.cpp +++ b/src/cbs.cpp @@ -78,17 +78,21 @@ namespace cbs { }; /** - * @brief Serialize a prepared coded bitstream unit with an existing context. + * @brief Serialize a mutable copy of a coded bitstream unit without modifying its source. * * @param cbs_ctx Coded bitstream context initialized for the codec. * @param nal NAL unit type to insert into the fragment. - * @param uh Pointer to the FFmpeg raw unit header/content structure. + * @tparam Unit Complete codec-specific parameter-set type. + * @param unit Parameter set to copy for FFmpeg's mutable writer interface. * @param codec_id FFmpeg codec identifier used by the context. * @return Serialized NAL unit bytes, or an empty buffer if FFmpeg rejects the fragment. */ - util::buffer_t write(cbs::ctx_t &cbs_ctx, std::uint8_t nal, void *uh, AVCodecID codec_id) { + template + util::buffer_t write(cbs::ctx_t &cbs_ctx, std::uint8_t nal, const Unit &unit, AVCodecID codec_id) { + // Parameter sets can be too large for the stack, and the fragment borrows this mutable copy. + auto content = std::make_unique(unit); cbs::frag_t frag; - auto err = ff_cbs_insert_unit_content(&frag, -1, nal, uh, nullptr); + auto err = ff_cbs_insert_unit_content(&frag, -1, nal, content.get(), nullptr); if (err < 0) { std::array err_str {0}; BOOST_LOG(error) << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); @@ -115,15 +119,17 @@ namespace cbs { * @brief Serialize a prepared coded bitstream unit with a temporary context. * * @param nal NAL unit type to insert into the fragment. - * @param uh Pointer to the FFmpeg raw unit header/content structure. + * @tparam Unit Complete codec-specific parameter-set type. + * @param unit Parameter set to copy for FFmpeg's mutable writer interface. * @param codec_id FFmpeg codec identifier used to initialize the temporary context. * @return Serialized NAL unit bytes, or an empty buffer if FFmpeg rejects the fragment. */ - util::buffer_t write(std::uint8_t nal, void *uh, AVCodecID codec_id) { + template + util::buffer_t write(std::uint8_t nal, const Unit &unit, AVCodecID codec_id) { cbs::ctx_t cbs_ctx; ff_cbs_init(&cbs_ctx, codec_id, nullptr); - return write(cbs_ctx, nal, uh, codec_id); + return write(cbs_ctx, nal, unit, codec_id); } /** @@ -180,8 +186,8 @@ namespace cbs { ff_cbs_init(&write_ctx, AV_CODEC_ID_H264, nullptr); return h264_t { - write(write_ctx, sps->nal_unit_header.nal_unit_type, (void *) &sps->nal_unit_header, AV_CODEC_ID_H264), - write(ctx, sps_p->nal_unit_header.nal_unit_type, (void *) &sps_p->nal_unit_header, AV_CODEC_ID_H264) + write(write_ctx, sps->nal_unit_header.nal_unit_type, *sps, AV_CODEC_ID_H264), + write(ctx, sps_p->nal_unit_header.nal_unit_type, *sps_p, AV_CODEC_ID_H264) }; } @@ -249,13 +255,13 @@ namespace cbs { return hevc_t { nal_t { - write(write_ctx, vps->nal_unit_header.nal_unit_type, (void *) &vps->nal_unit_header, AV_CODEC_ID_H265), - write(ctx, vps_p->nal_unit_header.nal_unit_type, (void *) &vps_p->nal_unit_header, AV_CODEC_ID_H265), + write(write_ctx, vps->nal_unit_header.nal_unit_type, *vps, AV_CODEC_ID_H265), + write(ctx, vps_p->nal_unit_header.nal_unit_type, *vps_p, AV_CODEC_ID_H265), }, nal_t { - write(write_ctx, sps->nal_unit_header.nal_unit_type, (void *) &sps->nal_unit_header, AV_CODEC_ID_H265), - write(ctx, sps_p->nal_unit_header.nal_unit_type, (void *) &sps_p->nal_unit_header, AV_CODEC_ID_H265), + write(write_ctx, sps->nal_unit_header.nal_unit_type, *sps, AV_CODEC_ID_H265), + write(ctx, sps_p->nal_unit_header.nal_unit_type, *sps_p, AV_CODEC_ID_H265), }, }; } diff --git a/src/input.cpp b/src/input.cpp index 4653a9b43..6c677dcc1 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -684,10 +684,12 @@ namespace input { } /** - * @brief Write a debug log representation of the input packet. + * @brief Decode the input header and log the matching packet representation. + * + * @param payload Header at the start of the input packet. */ - void print(void *payload) { - auto header = (PNV_INPUT_HEADER) payload; + void print(PNV_INPUT_HEADER payload) { + auto header = payload; switch (util::endian::little(header->magic)) { case MOUSE_MOVE_REL_MAGIC_GEN5: @@ -2152,7 +2154,7 @@ namespace input { } // Print the final input packet - input::print((void *) payload); + input::print(payload); #ifdef SUNSHINE_TESTS if (const auto &hook = input_packet_hook(); hook) { diff --git a/src/logging.cpp b/src/logging.cpp index da6b17d6b..57bdb5fe9 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -203,7 +203,7 @@ namespace logging { } else { av_log_set_level(AV_LOG_DEBUG); } - av_log_set_callback([](void *ptr, int level, const char *fmt, va_list vl) { + av_log_set_callback([](void *ptr, int level, const char *fmt, va_list vl) { // NOSONAR(cpp:S5008): FFmpeg's av_log_set_callback requires a void pointer to its logging context. static int print_prefix = 1; std::array buffer; diff --git a/src/nvenc/nvenc_base.cpp b/src/nvenc/nvenc_base.cpp index d20ca836c..d877de159 100644 --- a/src/nvenc/nvenc_base.cpp +++ b/src/nvenc/nvenc_base.cpp @@ -590,10 +590,16 @@ namespace NVENC_NAMESPACE { encoder_params.rfi = true; NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = {.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER}; - session_params.device = device; + std::visit([&session_params](auto *native_device) { + session_params.device = native_device; + }, + device); session_params.deviceType = device_type; session_params.apiVersion = NVENCAPI_VERSION; - if (nvenc_failed(nvenc->nvEncOpenEncodeSessionEx(&session_params, &encoder))) { + void *native_encoder = nullptr; + const auto open_status = nvenc->nvEncOpenEncodeSessionEx(&session_params, &native_encoder); + encoder = static_cast(native_encoder); + if (nvenc_failed(open_status)) { BOOST_LOG(error) << "NvEnc: NvEncOpenEncodeSessionEx() failed: " << last_nvenc_error_string; return false; } diff --git a/src/nvenc/nvenc_base.h b/src/nvenc/nvenc_base.h index 8f9c8b01b..a05a47383 100644 --- a/src/nvenc/nvenc_base.h +++ b/src/nvenc/nvenc_base.h @@ -4,6 +4,9 @@ */ #pragma once +// standard includes +#include + // local includes #include "nvenc_colorspace.h" #include "nvenc_config.h" @@ -14,11 +17,22 @@ #include "src/video.h" #include "src/video_colorspace.h" +struct ID3D11Device; + /** * @brief Standalone NVENC encoder */ namespace NVENC_NAMESPACE { + /** + * @brief Opaque encoder session created and destroyed by the NVENC driver. + */ + struct encoder_session_t; + /** + * @brief Opaque native event registered for asynchronous NVENC completion. + */ + struct completion_event_t; + /** * @brief Abstract platform-agnostic base of standalone NVENC encoder. * Derived classes perform platform-specific operations. @@ -120,7 +134,7 @@ namespace NVENC_NAMESPACE { const NV_ENC_DEVICE_TYPE device_type; ///< NVENC device backend used by this encoder instance. - void *encoder = nullptr; ///< Opaque NVENC encoder session handle returned by the driver. + encoder_session_t *encoder = nullptr; ///< Opaque NVENC encoder session handle returned by the driver. struct { uint32_t width = 0; @@ -133,14 +147,13 @@ namespace NVENC_NAMESPACE { std::string last_nvenc_error_string; ///< Last NVENC error string. // Derived classes set these variables - void *device = nullptr; ///< Platform-specific handle of encoding device. - ///< Should be set in constructor or `init_library()`. + std::variant device {static_cast(nullptr)}; ///< Native D3D11 device or CUDA context, set by the derived backend. std::shared_ptr nvenc; ///< Function pointers list produced by `NvEncodeAPICreateInstance()`. ///< Should be set in `init_library()`. NV_ENC_REGISTERED_PTR registered_input_buffer = nullptr; ///< Platform-specific input surface registered with `NvEncRegisterResource()`. ///< Should be set in `create_and_register_input_buffer()`. - void *async_event_handle = nullptr; ///< (optional) Platform-specific handle of event object event. - ///< Can be set in constructor or `init_library()`, must override `wait_for_async_event()`. + completion_event_t *async_event_handle = nullptr; ///< (optional) Native event registered for encode completion. + ///< Can be set in constructor or `init_library()`, must override `wait_for_async_event()`. private: /** diff --git a/src/nvenc/nvenc_d3d11.cpp b/src/nvenc/nvenc_d3d11.cpp index 64829e25e..d0f2bf948 100644 --- a/src/nvenc/nvenc_d3d11.cpp +++ b/src/nvenc/nvenc_d3d11.cpp @@ -13,7 +13,7 @@ namespace NVENC_NAMESPACE { nvenc_d3d11::nvenc_d3d11(NV_ENC_DEVICE_TYPE device_type, ::nvenc::shared_dll dll): nvenc_base(device_type), dll(std::move(dll)) { - async_event_handle = CreateEvent(nullptr, FALSE, FALSE, nullptr); + async_event_handle = static_cast(CreateEvent(nullptr, FALSE, FALSE, nullptr)); } nvenc_d3d11::~nvenc_d3d11() { diff --git a/src/nvenc/nvenc_d3d11_on_cuda.cpp b/src/nvenc/nvenc_d3d11_on_cuda.cpp index 6738957da..634a67287 100644 --- a/src/nvenc/nvenc_d3d11_on_cuda.cpp +++ b/src/nvenc/nvenc_d3d11_on_cuda.cpp @@ -92,7 +92,10 @@ namespace NVENC_NAMESPACE { } } - return device != nullptr; + return std::visit([](auto *native_device) { + return native_device != nullptr; + }, + device); } bool nvenc_d3d11_on_cuda::create_and_register_input_buffer() { diff --git a/src/platform/common.h b/src/platform/common.h index b349c924b..bdad5ae12 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -42,6 +42,8 @@ struct AVCodecContext; struct AVDictionary; #ifdef _WIN32 +struct ID3D11Device; + // Forward declarations of boost classes to avoid having to include boost headers // here, which results in issues with Windows.h and WinSock2.h include order. namespace boost { @@ -590,7 +592,15 @@ namespace platf { * @brief AVCodec-backed encode device and frame state. */ struct avcodec_encode_device_t: encode_device_t { - void *data {}; ///< Backend-specific conversion state. + bool hardware = false; ///< Whether this device supplies hardware frames instead of software conversion. + /** + * @brief Callback signature for backend-specific FFmpeg hardware device initialization. + */ + using init_hw_device_fn_t = int (*)(avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf); + init_hw_device_fn_t init_hw_device = nullptr; ///< Optional backend-specific hardware device initializer. +#ifdef _WIN32 + ID3D11Device *d3d11_device = nullptr; ///< Native D3D11 device borrowed while the encode device is alive. +#endif AVFrame *frame {}; ///< FFmpeg frame currently owned by the encode device. /** diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 92d4126c9..30c285372 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -246,7 +246,7 @@ namespace platf { * @param userdata Caller-provided pointer passed through the callback. */ template - void cb(ctx_t::pointer ctx, add_const_t i, void *userdata) { + void cb(ctx_t::pointer ctx, add_const_t i, void *userdata) { // NOSONAR(cpp:S5008): PulseAudio introspection callbacks require a void pointer for user data. auto &f = *(cb_simple_t *) userdata; // Cannot similarly filter on eol here. Unless reported otherwise assume @@ -269,7 +269,7 @@ namespace platf { * @param userdata Caller-provided pointer passed through the callback. */ template - void cb(ctx_t::pointer ctx, add_const_t i, int eol, void *userdata) { + void cb(ctx_t::pointer ctx, add_const_t i, int eol, void *userdata) { // NOSONAR(cpp:S5008): PulseAudio introspection callbacks require a void pointer for user data. auto &f = *(cb_t *) userdata; // For some reason, pulseaudio calls this callback after disconnecting diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 10f38bbed..3b5114a36 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -170,7 +170,7 @@ namespace cuda { return -1; } - data = (void *) 0x1; + hardware = true; width = in_width; height = in_height; @@ -418,7 +418,7 @@ namespace cuda { */ int init(int in_width, int in_height, int in_offset_x, int in_offset_y) { // This must be non-zero to tell the video core that it's a hardware encoding device. - data = (void *) 0x1; + hardware = true; // TODO: Support more than one CUDA device file = std::move(open_drm_fd_for_cuda_device(0)); @@ -701,7 +701,7 @@ namespace cuda { return b ? NVFBC_TRUE : NVFBC_FALSE; } - static void *library_handle {nullptr}; ///< Loaded NvFBC library retained while its function table is in use. + static dyn::library_t *library_handle {nullptr}; ///< Loaded NvFBC library retained while its function table is in use. /** * @brief Load NvFBC and create the CUDA capture helper. diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index 74a4c8b24..70484b873 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -307,7 +307,7 @@ namespace gbm { * @brief Load GBM symbols required for EGL device creation. */ int init() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { diff --git a/src/platform/linux/kwingrab.cpp b/src/platform/linux/kwingrab.cpp index f7c3b08c7..0fcfb507d 100644 --- a/src/platform/linux/kwingrab.cpp +++ b/src/platform/linux/kwingrab.cpp @@ -523,7 +523,7 @@ namespace kwin { } // Registry listener - static void on_registry_global(void *data, struct wl_registry *reg, const uint32_t name, const char *interface, const uint32_t version) { + static void on_registry_global(void *data, struct wl_registry *reg, const uint32_t name, const char *interface, const uint32_t version) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); if (!std::strcmp(interface, kde_output_order_v1_interface.name)) { // Bind version 1 @@ -560,7 +560,7 @@ namespace kwin { } } - static void on_registry_global_remove(void *data [[maybe_unused]], struct wl_registry *reg [[maybe_unused]], uint32_t name [[maybe_unused]]) { + static void on_registry_global_remove(void *data [[maybe_unused]], struct wl_registry *reg [[maybe_unused]], uint32_t name [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. // We don't handle output hot-unplug during init } @@ -570,14 +570,14 @@ namespace kwin { }; // wl_output listener (for mode/dimensions/name) - static void on_output_geometry(void *data, struct wl_output *output, int32_t x, int32_t y, int32_t pw [[maybe_unused]], int32_t ph [[maybe_unused]], int32_t subpixel [[maybe_unused]], const char *make [[maybe_unused]], const char *model [[maybe_unused]], int32_t transform [[maybe_unused]]) { + static void on_output_geometry(void *data, struct wl_output *output, int32_t x, int32_t y, int32_t pw [[maybe_unused]], int32_t ph [[maybe_unused]], int32_t subpixel [[maybe_unused]], const char *make [[maybe_unused]], const char *model [[maybe_unused]], int32_t transform [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. const auto *self = static_cast(data); const auto output_parameter = self->outputs.at(output); output_parameter->pos_x = x; output_parameter->pos_y = y; } - static void on_output_mode(void *data, struct wl_output *output, uint32_t flags, int32_t width, int32_t height, int32_t refresh [[maybe_unused]]) { + static void on_output_mode(void *data, struct wl_output *output, uint32_t flags, int32_t width, int32_t height, int32_t refresh [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. if (!(flags & WL_OUTPUT_MODE_CURRENT)) { return; } @@ -587,20 +587,20 @@ namespace kwin { output_parameter->height = height; } - static void on_output_done(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]]) { + static void on_output_done(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. // Currently unused } - static void on_output_scale(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]], int32_t factor [[maybe_unused]]) { + static void on_output_scale(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]], int32_t factor [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. // Currently unused } - static void on_output_name(void *data, struct wl_output *output, const char *name) { + static void on_output_name(void *data, struct wl_output *output, const char *name) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. const auto *self = static_cast(data); self->outputs.at(output)->name = name; } - static void on_output_description(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]], const char *description [[maybe_unused]]) { + static void on_output_description(void *data [[maybe_unused]], struct wl_output *output [[maybe_unused]], const char *description [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. // Currently unused } @@ -614,12 +614,12 @@ namespace kwin { }; // Output order listener - static void on_output_order_output(void *data, struct kde_output_order_v1 *kde_output_order_v1 [[maybe_unused]], const char *output_name) { + static void on_output_order_output(void *data, struct kde_output_order_v1 *kde_output_order_v1 [[maybe_unused]], const char *output_name) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); self->output_order.emplace_back(output_name); } - static void on_output_order_done(void *data [[maybe_unused]], struct kde_output_order_v1 *kde_output_order_v1 [[maybe_unused]]) { + static void on_output_order_done(void *data [[maybe_unused]], struct kde_output_order_v1 *kde_output_order_v1 [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. // Currently unused } @@ -629,7 +629,7 @@ namespace kwin { }; // ScreenCast v1 stream listener - static void on_stream_closed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]]) { + static void on_stream_closed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]]) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); BOOST_LOG(warning) << "[kwingrab] stream closed by server"sv; self->stream_failed = false; @@ -637,7 +637,7 @@ namespace kwin { self->stream_error_msg = "stream closed by server"; } - static void on_stream_created(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], const uint32_t node) { + static void on_stream_created(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], const uint32_t node) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); self->out_node_id = node; self->stream_failed = false; @@ -645,7 +645,7 @@ namespace kwin { BOOST_LOG(debug) << "[kwingrab] created event, node_id="sv << node; } - static void on_stream_failed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], const char *err_msg) { + static void on_stream_failed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], const char *err_msg) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); self->stream_failed = true; self->stream_ready = false; @@ -653,7 +653,7 @@ namespace kwin { BOOST_LOG(error) << "[kwingrab] failed event: "sv << self->stream_error_msg; } - static void on_stream_serial(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], uint32_t object_serial_hi, uint32_t object_serial_low) { + static void on_stream_serial(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], uint32_t object_serial_hi, uint32_t object_serial_low) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. auto *self = static_cast(data); self->out_objectserial = static_cast(object_serial_hi) << 32 | object_serial_low; // serial event always preceded the created event with the node id, so we only set stream_ready in created for v1 diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 0d49aa872..82baf1b81 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -107,15 +107,15 @@ window_system_e window_system; ///< Window system. namespace dyn { /** - * @brief Return the native handle owned by the wrapper. + * @brief Open the first available shared library from a nonempty list. */ - void *handle(const std::vector &libs) { + library_t *handle(const std::vector &libs) { void *handle; for (auto lib : libs) { handle = dlopen(lib, RTLD_LAZY | RTLD_LOCAL); if (handle) { - return handle; + return static_cast(handle); } } @@ -133,9 +133,9 @@ namespace dyn { } /** - * @brief Load persisted state from its backing store. + * @brief Load named functions from an open shared library. */ - int load(void *handle, const std::vector> &funcs, bool strict) { + int load(library_t *handle, const std::vector> &funcs, bool strict) { int err = 0; for (auto &func : funcs) { TUPLE_2D_REF(fn, name, func); diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index d9c542534..056db4dd0 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -40,13 +40,29 @@ enum class window_system_e { extern window_system_e window_system; ///< Window system. namespace dyn { + /** + * @brief Opaque shared-library handle returned by the dynamic loader. + */ + struct library_t; + /** * @brief Generic GLX procedure pointer returned by the loader. */ using apiproc = void (*)(void); - int load(void *handle, const std::vector> &funcs, bool strict = true); - void *handle(const std::vector &libs); + /** + * @brief Load named functions from an open shared library. + * @param handle Library whose symbols are queried. + * @param funcs Function pointer destinations and corresponding symbol names. + * @param strict Whether missing symbols make the operation fail. + * @return Zero on success or minus one when a required symbol is missing. + */ + int load(library_t *handle, const std::vector> &funcs, bool strict = true); + /** + * @brief Open the first available shared library from a nonempty list. + * @return Open library handle, or null if none could be loaded. + */ + library_t *handle(const std::vector &libs); } // namespace dyn diff --git a/src/platform/linux/pipewire.cpp b/src/platform/linux/pipewire.cpp index 3836a002b..ec53d245d 100644 --- a/src/platform/linux/pipewire.cpp +++ b/src/platform/linux/pipewire.cpp @@ -762,11 +762,11 @@ namespace pipewire { return static_cast(spa_pod_builder_pop(b, &object_frame)); } - static void on_core_info_cb([[maybe_unused]] void *user_data, const struct pw_core_info *pw_info) { + static void on_core_info_cb([[maybe_unused]] void *user_data, const struct pw_core_info *pw_info) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data. BOOST_LOG(info) << "[pipewire] Connected to pipewire version "sv << pw_info->version; } - static void on_core_error_cb([[maybe_unused]] void *user_data, const uint32_t id, const int seq, [[maybe_unused]] int res, const char *message) { + static void on_core_error_cb([[maybe_unused]] void *user_data, const uint32_t id, const int seq, [[maybe_unused]] int res, const char *message) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data. BOOST_LOG(info) << "[pipewire] Pipewire Error, id:"sv << id << " seq:"sv << seq << " message: "sv << message; } @@ -776,7 +776,7 @@ namespace pipewire { .error = on_core_error_cb, }; - static void on_stream_state_changed(void *user_data, enum pw_stream_state old, enum pw_stream_state state, const char *err_msg) { + static void on_stream_state_changed(void *user_data, enum pw_stream_state old, enum pw_stream_state state, const char *err_msg) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data. if (err_msg != nullptr) { BOOST_LOG(info) << "[pipewire] PipeWire stream error '" << err_msg << "' on state: " << pw_stream_state_as_string(old) << " -> " << pw_stream_state_as_string(state); @@ -821,7 +821,7 @@ namespace pipewire { } } - static void on_process(void *user_data) { + static void on_process(void *user_data) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data. const auto d = static_cast(user_data); struct pw_buffer *b = nullptr; @@ -873,7 +873,7 @@ namespace pipewire { d->frame_cv.notify_one(); } - static void on_param_changed(void *user_data, uint32_t id, const struct spa_pod *param) { + static void on_param_changed(void *user_data, uint32_t id, const struct spa_pod *param) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data. const auto d = static_cast(user_data); d->current_buffer = nullptr; diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index 0393e5aca..ea00bd240 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -290,7 +290,7 @@ namespace avahi { * @return 0 when common Avahi functions are available; nonzero otherwise. */ int init_common() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -334,7 +334,7 @@ namespace avahi { return -1; } - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -415,7 +415,7 @@ namespace platf::publish { * @param g Entry group that emitted the state change. * @param state Avahi entry-group state reported by the callback. */ - void entry_group_callback(avahi::EntryGroup *g, avahi::EntryGroupState state, void *) { + void entry_group_callback(avahi::EntryGroup *g, avahi::EntryGroupState state, void *) { // NOSONAR(cpp:S5008): Avahi callbacks require a void pointer for user data. group = g; switch (state) { @@ -505,7 +505,7 @@ namespace platf::publish { * @param c Avahi client that emitted the state change. * @param state Avahi client state reported by the callback. */ - void client_callback(avahi::Client *c, avahi::ClientState state, void *) { + void client_callback(avahi::Client *c, avahi::ClientState state, void *) { // NOSONAR(cpp:S5008): Avahi callbacks require a void pointer for user data. switch (state) { case avahi::CLIENT_S_RUNNING: create_services(c); diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index 6cf70068e..eb89fff06 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -77,7 +77,7 @@ namespace va { /** * @brief Native VA display handle. */ - using VADisplay = void *; + using VADisplay = void *; // NOSONAR(cpp:S5008): The libva ABI defines VADisplay as a void pointer. /** * @brief Status code returned by VAAPI functions. */ @@ -186,7 +186,8 @@ namespace va { return -1; } - this->data = (void *) vaapi_init_avcodec_hardware_input_buffer; + hardware = true; + init_hw_device = &vaapi_init_avcodec_hardware_input_buffer; gbm.reset(gbm::create_device(file.el)); if (!gbm) { diff --git a/src/platform/linux/vulkan_encode.cpp b/src/platform/linux/vulkan_encode.cpp index cc1b7972f..b7c9c6d21 100644 --- a/src/platform/linux/vulkan_encode.cpp +++ b/src/platform/linux/vulkan_encode.cpp @@ -450,7 +450,8 @@ namespace vk { height = in_height; offset_x = in_offset_x; offset_y = in_offset_y; - this->data = (void *) &init_hw_device; + hardware = true; + avcodec_encode_device_t::init_hw_device = &init_hw_device; return 0; } diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 46b5eefd3..686d32f57 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -93,7 +93,7 @@ namespace wl { // Helper to call C++ method from wayland C callback template - static auto classCall(void *data, Params... params) -> decltype(((*reinterpret_cast(data)).*m)(params...)) { + static auto classCall(void *data, Params... params) -> decltype(((*reinterpret_cast(data)).*m)(params...)) { // NOSONAR(cpp:S5008): Wayland listener callbacks require a void pointer for user data. return ((*reinterpret_cast(data)).*m)(params...); } diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index f29384781..7f7587a7f 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -3,10 +3,17 @@ * @brief Definitions for x11 capture. */ // standard includes +#include +#include +#include #include #include #include +#ifdef SUNSHINE_TESTS + #include +#endif + // plaform includes #include #include @@ -80,7 +87,7 @@ namespace platf { _FN(FreeCrtcInfo, void, (XRRCrtcInfo * crtcInfo)); static int init() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -117,7 +124,7 @@ namespace platf { _FN(GetCursorImage, XFixesCursorImage *, (Display * dpy)); static int init() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -145,7 +152,7 @@ namespace platf { } // namespace fix static int init() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -201,7 +208,7 @@ namespace platf { * @return 0 when XCB shared-memory functions are loaded; nonzero otherwise. */ int init_shm() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -236,7 +243,7 @@ namespace platf { * @return 0 on success; nonzero or negative platform status on failure. */ int init() { - static void *handle {nullptr}; + static dyn::library_t *handle {nullptr}; static bool funcs_loaded = false; if (funcs_loaded) { @@ -354,12 +361,12 @@ namespace platf { }; /** - * @brief RAII wrapper that detaches mapped SysV shared memory. + * @brief RAII wrapper that detaches mapped SysV shared memory, with null representing an empty mapping. */ class shm_data_t { public: shm_data_t(): - data {(void *) -1} { + data {nullptr} { } /** @@ -367,7 +374,7 @@ namespace platf { * * @param data Pointer returned by shmat. */ - shm_data_t(void *data): + shm_data_t(std::uint8_t *data): data {data} { } @@ -378,18 +385,54 @@ namespace platf { */ shm_data_t(shm_data_t &&other) noexcept: data(other.data) { - other.data = (void *) -1; + other.data = nullptr; } ~shm_data_t() { - if ((std::uintptr_t) data != -1) { + if (data) { shmdt(data); } } - void *data; ///< Address returned by shmat for the shared-memory segment. + std::uint8_t *data; ///< Attached shared-memory bytes, or null when this wrapper owns no attachment. }; +#ifdef SUNSHINE_TESTS + TEST(X11SharedMemoryMappingTest, EmptyAndMovedEmptyMappingsDoNotDetachMemory) { + errno = 0; + { + shm_data_t empty; + EXPECT_EQ(empty.data, nullptr); + shm_data_t moved {std::move(empty)}; + EXPECT_EQ(empty.data, nullptr); + EXPECT_EQ(moved.data, nullptr); + } + EXPECT_EQ(errno, 0); + } + + TEST(X11SharedMemoryMappingTest, MoveTransfersTheOnlyAttachment) { + const auto segment = shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0600); + ASSERT_NE(segment, -1); + auto remove_segment = util::fail_guard([segment] { + shmctl(segment, IPC_RMID, nullptr); + }); + auto *mapping = shmat(segment, nullptr, 0); + ASSERT_NE(std::bit_cast(mapping), -1); + auto *bytes = static_cast(mapping); + { + shm_data_t owner {bytes}; + owner.data[0] = 42; + shm_data_t moved {std::move(owner)}; + EXPECT_EQ(owner.data, nullptr); + EXPECT_EQ(moved.data, bytes); + EXPECT_EQ(moved.data[0], 42); + } + errno = 0; + EXPECT_EQ(shmdt(mapping), -1); + EXPECT_EQ(errno, EINVAL); + } +#endif + /** * @brief X11 image wrapper used by the software capture path. */ @@ -806,7 +849,7 @@ namespace platf { return platf::capture_e::interrupted; } - std::copy_n((std::uint8_t *) data.data, frame_size(), img_out->data); + std::copy_n(data.data, frame_size(), img_out->data); img_out->frame_timestamp = frame_timestamp; if (cursor) { @@ -878,9 +921,10 @@ namespace platf { } xcb::shm_attach(xcb.get(), seg, shm_id.id, false); - data.data = shmat(shm_id.id, nullptr, 0); + data.data = static_cast(shmat(shm_id.id, nullptr, 0)); if ((uintptr_t) data.data == -1) { + data.data = nullptr; BOOST_LOG(error) << "shmat failed"sv; return -1; diff --git a/src/platform/macos/display.mm b/src/platform/macos/display.mm index 903a139fe..4aec4ebed 100644 --- a/src/platform/macos/display.mm +++ b/src/platform/macos/display.mm @@ -160,7 +160,7 @@ namespace platf { } else if (pix_fmt == pix_fmt_e::nv12 || pix_fmt == pix_fmt_e::p010) { auto device = std::make_unique(); - device->init(static_cast(av_capture), pix_fmt, setResolution, setPixelFormat); + device->init(av_capture, pix_fmt, setResolution, setPixelFormat); return device; } else { @@ -225,8 +225,8 @@ namespace platf { * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. */ - static void setResolution(void *display, int width, int height) { - [static_cast(display) setFrameWidth:width frameHeight:height]; + static void setResolution(AVVideo *display, int width, int height) { + [display setFrameWidth:width frameHeight:height]; } /** @@ -235,8 +235,8 @@ namespace platf { * @param display Display object or identifier associated with the operation. * @param pixelFormat Pixel format. */ - static void setPixelFormat(void *display, OSType pixelFormat) { - static_cast(display).pixelFormat = pixelFormat; + static void setPixelFormat(AVVideo *display, OSType pixelFormat) { + display.pixelFormat = pixelFormat; } }; diff --git a/src/platform/macos/nv12_zero_device.cpp b/src/platform/macos/nv12_zero_device.cpp index 055fa5944..80b98e60a 100644 --- a/src/platform/macos/nv12_zero_device.cpp +++ b/src/platform/macos/nv12_zero_device.cpp @@ -64,15 +64,13 @@ namespace platf { return 0; } - int nv12_zero_device::init(void *capture_display, pix_fmt_e pix_fmt, resolution_fn_t set_resolution, const pixel_format_fn_t &pixel_format_fn) { + int nv12_zero_device::init(AVVideo *capture_display, pix_fmt_e pix_fmt, resolution_fn_t set_resolution, const pixel_format_fn_t &pixel_format_fn) { pixel_format_fn(capture_display, pix_fmt == pix_fmt_e::nv12 ? kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange : kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange); this->display = capture_display; this->resolution_fn = std::move(set_resolution); - // we never use this pointer, but its existence is checked/used - // by the platform independent code - data = this; + hardware = true; return 0; } diff --git a/src/platform/macos/nv12_zero_device.h b/src/platform/macos/nv12_zero_device.h index 7857f74d8..693ab6f4f 100644 --- a/src/platform/macos/nv12_zero_device.h +++ b/src/platform/macos/nv12_zero_device.h @@ -9,6 +9,15 @@ struct AVFrame; +#ifdef __OBJC__ +@class AVVideo; +#else +/** + * @brief Opaque AVFoundation capture controller, defined in Objective-C. + */ +struct AVVideo; +#endif + namespace platf { /** * @brief Release an FFmpeg frame allocated by the capture or conversion backend. @@ -21,9 +30,7 @@ namespace platf { * @brief macOS zero-copy encode device that forwards NV12 frames from AVFoundation to FFmpeg. */ class nv12_zero_device: public avcodec_encode_device_t { - // display holds a pointer to an av_video object. Since the namespaces of AVFoundation - // and FFMPEG collide, we need this opaque pointer and cannot use the definition - void *display; + AVVideo *display = nullptr; ///< Borrowed AVFoundation controller, forward-declared to avoid FFmpeg name conflicts. public: // this function is used to set the resolution on an av_video object that we cannot @@ -31,12 +38,12 @@ namespace platf { /** * @brief Callback signature used to update the opaque AVFoundation display resolution. */ - using resolution_fn_t = std::function; + using resolution_fn_t = std::function; resolution_fn_t resolution_fn; ///< Callback stored for later AVFoundation resolution updates. /** * @brief Callback signature used to update the opaque AVFoundation pixel format. */ - using pixel_format_fn_t = std::function; + using pixel_format_fn_t = std::function; /** * @brief Initialize zero-copy NV12 encoding for an AVFoundation display. @@ -47,7 +54,7 @@ namespace platf { * @param pixel_format_fn Pixel format. * @return 0 on success; nonzero or negative platform status on failure. */ - int init(void *capture_display, pix_fmt_e pix_fmt, resolution_fn_t set_resolution, const pixel_format_fn_t &pixel_format_fn); + int init(AVVideo *capture_display, pix_fmt_e pix_fmt, resolution_fn_t set_resolution, const pixel_format_fn_t &pixel_format_fn); /** * @brief Forward a captured AVFoundation frame to FFmpeg without copying. diff --git a/src/platform/macos/publish.cpp b/src/platform/macos/publish.cpp index 812c4a763..1ce5429b5 100644 --- a/src/platform/macos/publish.cpp +++ b/src/platform/macos/publish.cpp @@ -81,7 +81,7 @@ namespace platf::publish { /** @brief Callback that will be invoked when the mDNS service finishes registering our service. * @param errorCode Describes whether the registration was successful. */ - void registrationCallback(DNSServiceRef /*serviceRef*/, DNSServiceFlags /*flags*/, DNSServiceErrorType errorCode, const char * /*name*/, const char * /*regtype*/, const char * /*domain*/, void * /*context*/) { + void registrationCallback(DNSServiceRef /*serviceRef*/, DNSServiceFlags /*flags*/, DNSServiceErrorType errorCode, const char * /*name*/, const char * /*regtype*/, const char * /*domain*/, void * /*context*/) { // NOSONAR(cpp:S5008): DNSServiceRegister callbacks require a void pointer for user data. if (errorCode != kDNSServiceErr_NoError) { BOOST_LOG(error) << "Failed to register DNS service: Error "sv << errorCode; return; diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index 7a3e0c9ac..b0cd28b80 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -470,7 +470,7 @@ namespace platf::audio { * @param ppvInterface Output pointer receiving the requested interface. * @return S_OK when the interface is supported; E_NOINTERFACE otherwise. */ - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) { + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. if (IID_IUnknown == riid) { AddRef(); *ppvInterface = (IUnknown *) this; diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 4ce41ca14..98bc10450 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -1120,7 +1120,8 @@ namespace platf::dxgi { */ int init(std::shared_ptr display, adapter_t::pointer adapter_p, pix_fmt_e pix_fmt) { int result = base.init(display, adapter_p, pix_fmt); - data = base.device.get(); + d3d11_device = base.device.get(); + hardware = d3d11_device != nullptr; return result; } diff --git a/src/platform/windows/display_wgc.cpp b/src/platform/windows/display_wgc.cpp index e2d850932..26fcb3b54 100644 --- a/src/platform/windows/display_wgc.cpp +++ b/src/platform/windows/display_wgc.cpp @@ -56,7 +56,7 @@ namespace winrt { * @param object Output pointer that receives the requested COM interface. * @return HRESULT from the WinRT object's interface query. */ - virtual HRESULT __stdcall GetInterface(REFIID id, void **object) = 0; + virtual HRESULT __stdcall GetInterface(REFIID id, void **object) = 0; // NOSONAR(cpp:S5008): IDirect3DDxgiInterfaceAccess::GetInterface requires a void double pointer in the WinRT ABI. }; } // namespace winrt #if !WINRT_IMPL_HAS_DECLSPEC_UUID diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 96387d25c..3a581d9f0 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -489,7 +489,7 @@ namespace platf { std::uint8_t largeMotor, std::uint8_t smallMotor, std::uint8_t /* led_number */, - void *userdata + void *userdata // NOSONAR(cpp:S5008): ViGEm notification callbacks require a void pointer for user data. ) { BOOST_LOG(debug) << "largeMotor: "sv << (int) largeMotor << std::endl @@ -504,7 +504,7 @@ namespace platf { std::uint8_t largeMotor, std::uint8_t smallMotor, DS4_LIGHTBAR_COLOR led_color, - void *userdata + void *userdata // NOSONAR(cpp:S5008): ViGEm notification callbacks require a void pointer for user data. ) { BOOST_LOG(debug) << "largeMotor: "sv << (int) largeMotor << std::endl diff --git a/src/platform/windows/nvprefs/nvprefs_common.h b/src/platform/windows/nvprefs/nvprefs_common.h index 3ba41398b..48e644324 100644 --- a/src/platform/windows/nvprefs/nvprefs_common.h +++ b/src/platform/windows/nvprefs/nvprefs_common.h @@ -38,9 +38,11 @@ namespace nvprefs { /** * @brief Free memory allocated by Windows local-memory APIs. * + * @tparam T Native allocation type returned by the Windows API. * @param p LocalAlloc-compatible pointer to release. */ - void operator()(void *p) { + template + void operator()(T *p) { LocalFree(p); } }; diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index 7347b5a49..2cc164be7 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -139,7 +139,7 @@ namespace platf::publish { * @param pInstance Registered DNS-SD service instance returned by Windows. * @return Callback has no return value; completion is reported through the alarm. */ - VOID WINAPI register_cb(DWORD status, PVOID pQueryContext, PDNS_SERVICE_INSTANCE pInstance) { + VOID WINAPI register_cb(DWORD status, PVOID pQueryContext, PDNS_SERVICE_INSTANCE pInstance) { // NOSONAR(cpp:S5008): DnsServiceRegister completion callbacks require PVOID user data. auto alarm = (safe::alarm_t::element_type *) pQueryContext; if (status) { diff --git a/src/stream.cpp b/src/stream.cpp index 0a65a5c19..aedb3f2a1 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -1567,7 +1567,7 @@ namespace stream { frame_network_latency_logger.first_point_now(); - auto session = (session_t *) packet->channel_data; + auto *session = packet->channel_data; auto lowseq = session->video.lowseq; std::string_view payload {(char *) packet->data(), packet->data_size()}; @@ -1892,7 +1892,7 @@ namespace stream { } TUPLE_2D_REF(channel_data, packet_data, *packet); - auto session = (session_t *) channel_data; + auto *session = channel_data; auto sequenceNumber = session->audio.sequenceNumber; auto timestamp = session->audio.timestamp; diff --git a/src/utility.h b/src/utility.h index 3fae2582f..5cfcec9f8 100644 --- a/src/utility.h +++ b/src/utility.h @@ -900,11 +900,11 @@ namespace util { /** * @brief Pointer type stored by the unique pointer wrapper. */ - using pointer = element_type *; + using pointer = element_type *; // NOSONAR(cpp:S5008): Native C handle instantiations must retain HANDLE, PSID, EGLDisplay and VADisplay pointer types. /** * @brief Const pointer type exposed by the unique pointer wrapper. */ - using const_pointer = element_type const *; + using const_pointer = element_type const *; // NOSONAR(cpp:S5008): Native C handle instantiations must retain HANDLE, PSID, EGLDisplay and VADisplay pointer types. /** * @brief Callable type used to release the managed pointer. */ @@ -1641,7 +1641,7 @@ namespace util { /** * @brief Pointer type accepted by this deleter. */ - using pointer = T; + using pointer = T; // NOSONAR(cpp:S5008): Native C handle instantiations must retain HANDLE, PSID, EGLDisplay and VADisplay pointer types. /** * @brief Invoke the configured destroy function on a pointer. diff --git a/src/video.cpp b/src/video.cpp index 87e827d02..a1dce4c55 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -327,9 +327,9 @@ namespace video { av_image_fill_black(active_frame->data, linesize.data(), static_cast(active_frame->format), active_frame->color_range, active_frame->width, active_frame->height); } - int avcodec_software_encode_device_t::init(int in_width, int in_height, AVFrame *in_frame, AVPixelFormat format, bool hardware) { + int avcodec_software_encode_device_t::init(int in_width, int in_height, AVFrame *in_frame, AVPixelFormat format, bool hardware_frame) { // If the device used is hardware, yet the image resides on main memory - if (hardware) { + if (hardware_frame) { sw_frame.reset(av_frame_alloc()); sw_frame->width = in_frame->width; @@ -631,7 +631,7 @@ namespace video { config_t config; ///< Stream or encoder configuration captured for the worker. int frame_nr; ///< Next capture-frame number assigned to encoded packets. - void *channel_data; ///< Platform-specific channel data forwarded to packet senders. + stream::session_t *channel_data; ///< Stream session forwarded to packet senders. }; /** @@ -1821,11 +1821,11 @@ namespace video { * @param frame_nr Monotonic frame index assigned by the video pipeline. * @param session Active FFmpeg encoder session. * @param packets Output queue that receives encoded packets. - * @param channel_data Platform or protocol state attached to each packet. + * @param channel_data Stream session that receives each encoded packet. * @param frame_timestamp Capture timestamp associated with the encoded frame. * @return 0 when packets are queued; nonzero when encoding or packetization fails. */ - int encode_avcodec(int64_t frame_nr, avcodec_encode_session_t &session, safe::mail_raw_t::queue_t &packets, void *channel_data, std::optional frame_timestamp) { + int encode_avcodec(int64_t frame_nr, avcodec_encode_session_t &session, safe::mail_raw_t::queue_t &packets, stream::session_t *channel_data, std::optional frame_timestamp) { auto &frame = session.device->frame; frame->pts = frame_nr; @@ -1905,11 +1905,11 @@ namespace video { * @param frame_nr Monotonic frame index assigned by the video pipeline. * @param session Active NVENC encoder session. * @param packets Output queue that receives the encoded packet. - * @param channel_data Platform or protocol state attached to the packet. + * @param channel_data Stream session that receives the encoded packet. * @param frame_timestamp Capture timestamp associated with the encoded frame. * @return 0 when packets are queued; nonzero when NVENC encoding fails. */ - int encode_nvenc(int64_t frame_nr, nvenc_encode_session_t &session, safe::mail_raw_t::queue_t &packets, void *channel_data, std::optional frame_timestamp) { + int encode_nvenc(int64_t frame_nr, nvenc_encode_session_t &session, safe::mail_raw_t::queue_t &packets, stream::session_t *channel_data, std::optional frame_timestamp) { auto encoded_frame = session.encode_frame(frame_nr); if (encoded_frame.data.empty()) { BOOST_LOG(error) << "NvENC returned empty packet"; @@ -1939,7 +1939,7 @@ namespace video { * @param frame_timestamp Frame timestamp. * @return 0 when the frame is encoded and queued; nonzero on encoder failure. */ - int encode(int64_t frame_nr, encode_session_t &session, safe::mail_raw_t::queue_t &packets, void *channel_data, std::optional frame_timestamp) { + int encode(int64_t frame_nr, encode_session_t &session, safe::mail_raw_t::queue_t &packets, stream::session_t *channel_data, std::optional frame_timestamp) { if (auto avcodec_session = dynamic_cast(&session)) { return encode_avcodec(frame_nr, *avcodec_session, packets, channel_data, frame_timestamp); } else if (auto nvenc_session = dynamic_cast(&session)) { @@ -2318,7 +2318,7 @@ namespace video { std::unique_ptr encode_device_final; - if (!encode_device->data) { + if (!encode_device->hardware) { auto software_encode_device = std::make_unique(); if (software_encode_device->init(width, height, frame.get(), sw_fmt, hardware)) { @@ -2397,7 +2397,7 @@ namespace video { * @param encode_device Platform encode device. * @param reinit_event Signal raised while the encoder/display is reinitializing. * @param encoder Selected encoder. - * @param channel_data Opaque channel data passed to packets. + * @param channel_data Stream session carried with each encoded packet. */ void encode_run( int &frame_nr, // Store progress of the frame number @@ -2408,7 +2408,7 @@ namespace video { std::unique_ptr encode_device, safe::signal_t &reinit_event, const encoder_t &encoder, - void *channel_data + stream::session_t *channel_data ) { auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { @@ -2868,12 +2868,12 @@ namespace video { * * @param mail Session mail bus. * @param config Video configuration. - * @param channel_data Opaque channel data passed to packets. + * @param channel_data Stream session carried with each encoded packet. */ void capture_async( safe::mail_t mail, config_t &config, - void *channel_data + stream::session_t *channel_data ) { auto shutdown_event = mail->event(mail::shutdown); @@ -2959,12 +2959,12 @@ namespace video { * * @param mail Session mail bus. * @param config Client-requested video configuration, normalized before capture begins. - * @param channel_data Opaque channel data passed to packets. + * @param channel_data Stream session carried with each encoded packet. */ void capture( safe::mail_t mail, config_t config, - void *channel_data + stream::session_t *channel_data ) { config = resolve_dynamic_range(*chosen_encoder, config); @@ -3503,12 +3503,6 @@ namespace video { return 0; } - // Linux only declaration - /** - * @brief Callback signature for VA-API AVCodec hardware input initialization. - */ - using vaapi_init_avcodec_hardware_input_buffer_fn = int (*)(platf::avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf); - /** * @brief Initialize AVCodec hardware input buffers for VA-API. */ @@ -3516,8 +3510,8 @@ namespace video { avcodec_buffer_t hw_device_buf; // If an egl hwdevice - if (encode_device->data) { - if (((vaapi_init_avcodec_hardware_input_buffer_fn) encode_device->data)(encode_device, &hw_device_buf)) { + if (encode_device->init_hw_device) { + if (encode_device->init_hw_device(encode_device, &hw_device_buf)) { return -1; } @@ -3537,13 +3531,11 @@ namespace video { } #ifdef SUNSHINE_BUILD_VULKAN - using vulkan_init_avcodec_hardware_input_buffer_fn = int (*)(platf::avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf); - util::Either vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; - if (encode_device && encode_device->data) { - if (((vulkan_init_avcodec_hardware_input_buffer_fn) encode_device->data)(encode_device, &hw_device_buf)) { + if (encode_device && encode_device->init_hw_device) { + if (encode_device->init_hw_device(encode_device, &hw_device_buf)) { return -1; } return hw_device_buf; @@ -3611,7 +3603,7 @@ namespace video { /** * @brief No-op lock callback used when FFmpeg requires a D3D11VA lock function. */ -void do_nothing(void *) { +void do_nothing(void *) { // NOSONAR(cpp:S5008): FFmpeg's D3D11VA lock callbacks require a void pointer for user data. } namespace video { @@ -3624,7 +3616,7 @@ namespace video { std::fill_n((std::uint8_t *) ctx, sizeof(AVD3D11VADeviceContext), 0); - auto device = static_cast(encode_device->data); + auto device = encode_device->d3d11_device; device->AddRef(); ctx->device = device; diff --git a/src/video.h b/src/video.h index 006fb9f0b..857e12b4d 100644 --- a/src/video.h +++ b/src/video.h @@ -21,6 +21,10 @@ extern "C" { struct AVPacket; +namespace stream { + struct session_t; +} + namespace video { /** @@ -528,7 +532,7 @@ namespace video { }; std::vector *replacements = nullptr; ///< Optional encoded-byte substitutions applied before packetization. - void *channel_data = nullptr; ///< Platform or protocol state carried with this packet. + stream::session_t *channel_data = nullptr; ///< Stream session that receives this packet. bool after_ref_frame_invalidation = false; ///< Whether the frame follows reference-frame invalidation. std::optional frame_timestamp; ///< Capture timestamp associated with the frame. }; @@ -697,12 +701,12 @@ namespace video { * * @param mail Session mail bus. * @param config Client-requested video configuration, normalized before capture begins. - * @param channel_data Opaque channel data passed to packets. + * @param channel_data Stream session carried with each encoded packet. */ void capture( safe::mail_t mail, config_t config, - void *channel_data + stream::session_t *channel_data ); /** diff --git a/tests/unit/platform/linux/test_dynamic_loader.cpp b/tests/unit/platform/linux/test_dynamic_loader.cpp new file mode 100644 index 000000000..9a9008db2 --- /dev/null +++ b/tests/unit/platform/linux/test_dynamic_loader.cpp @@ -0,0 +1,48 @@ +/** + * @file tests/unit/platform/linux/test_dynamic_loader.cpp + * @brief Tests for opaque Linux shared-library handles and symbol loading. + */ +#ifdef __linux__ + + // standard includes + #include + + // platform includes + #include + + // lib includes + #include + + // local includes + #include "src/platform/linux/misc.h" + +TEST(DynamicLibraryTest, FallsBackToAnAvailableLibraryAndLoadsCallableSymbols) { + auto *library = dyn::handle({"libsunshine-does-not-exist.so", "libc.so.6"}); + ASSERT_NE(library, nullptr); + auto close_library = util::fail_guard([library] { + dlclose(library); + }); + dyn::apiproc symbol = nullptr; + ASSERT_EQ(dyn::load(library, {{&symbol, "getpid"}}), 0); + ASSERT_NE(symbol, nullptr); + const auto loaded_getpid = std::bit_cast(symbol); + EXPECT_EQ(loaded_getpid(), getpid()); +} + +TEST(DynamicLibraryTest, MissingOptionalSymbolDoesNotFailLoading) { + auto *library = dyn::handle({"libc.so.6"}); + ASSERT_NE(library, nullptr); + auto close_library = util::fail_guard([library] { + dlclose(library); + }); + dyn::apiproc symbol = nullptr; + EXPECT_EQ(dyn::load(library, {{&symbol, "sunshine_missing_symbol"}}, false), 0); + EXPECT_EQ(symbol, nullptr); + EXPECT_EQ(dyn::load(library, {{&symbol, "sunshine_missing_symbol"}}, true), -1); +} + +TEST(DynamicLibraryTest, MissingLibraryReturnsNull) { + EXPECT_EQ(dyn::handle({"libsunshine-does-not-exist.so", "libsunshine-also-does-not-exist.so"}), nullptr); +} + +#endif diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 851f250d4..bc0ce1c5d 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -8,6 +8,12 @@ // local includes #include +#include +#include + +namespace audio { + void encodeThread(std::shared_ptr>> samples, config_t config, stream::session_t *channel_data); +} using namespace audio; @@ -26,6 +32,29 @@ TEST(AudioLayoutTest, CustomMappingRemainsContiguousAndUsesAllEightChannels) { EXPECT_EQ(stream_configs[HIGH_SURROUND71].channelCount, 8); } +TEST(AudioPacketSessionTest, EncoderPreservesTheReceivingSession) { + stream::config_t stream_config {}; + rtsp_stream::launch_session_t launch_session {}; + launch_session.gcm_key.resize(16); + launch_session.iv.resize(16); + auto session = stream::session::alloc(stream_config, launch_session); + ASSERT_NE(session.get(), nullptr); + config_t config {.packetDuration = 5, .channels = 2, .mask = 0x3}; + auto samples = std::make_shared>>(); + auto packets = mail::man->queue(mail::audio_packets); + std::jthread worker([&samples, &config, &session] { + audio::encodeThread(samples, config, session.get()); + }); + auto stop_worker = util::fail_guard([&samples] { + samples->stop(); + }); + ASSERT_TRUE(samples->raise(std::vector(480, 0.0F))); + auto packet = packets->pop(2s); + ASSERT_TRUE(packet); + EXPECT_EQ(packet->first, session.get()); + EXPECT_GT(packet->second.size(), 0U); +} + struct AudioTest: PlatformTestSuite, testing::WithParamInterface, config_t>> { void SetUp() override { BaseTest::SetUp(); diff --git a/tests/unit/test_cbs.cpp b/tests/unit/test_cbs.cpp new file mode 100644 index 000000000..cd70525f8 --- /dev/null +++ b/tests/unit/test_cbs.cpp @@ -0,0 +1,116 @@ +/** + * @file tests/unit/test_cbs.cpp + * @brief Regression tests for typed H.264 and HEVC parameter-set serialization. + */ + +// test includes +#include "../tests_common.h" + +// standard includes +#include +#include +#include +#include + +// local includes +#include +#include + +namespace { + /** + * @brief Release a packet allocated by FFmpeg. + * @param packet Packet whose encoded payload is released. + */ + void release_packet(AVPacket *packet) { + av_packet_free(&packet); + } + + /** + * @brief Verify parameter-set rewriting with real software-encoder output. + */ + struct CodedBitstreamTest: testing::TestWithParam {}; +} // namespace + +TEST_P(CodedBitstreamTest, RewrittenParameterSetsRetainValidVuiMetadata) { + const auto codec_id = GetParam(); + const auto *codec = avcodec_find_encoder_by_name(codec_id == AV_CODEC_ID_H264 ? "libx264" : "libx265"); + ASSERT_NE(codec, nullptr); + video::avcodec_ctx_t context {avcodec_alloc_context3(codec)}; + ASSERT_NE(context.get(), nullptr); + context->width = 64; + context->height = 64; + context->pix_fmt = AV_PIX_FMT_YUV420P; + context->time_base = {1, 30}; + context->framerate = {30, 1}; + context->gop_size = 1; + context->max_b_frames = 0; + context->refs = 1; + context->color_range = AVCOL_RANGE_MPEG; + context->color_primaries = AVCOL_PRI_BT709; + context->color_trc = AVCOL_TRC_BT709; + context->colorspace = AVCOL_SPC_BT709; + + AVDictionary *options = nullptr; + auto free_options = util::fail_guard([&options] { + av_dict_free(&options); + }); + av_dict_set(&options, "preset", "ultrafast", 0); + av_dict_set(&options, "tune", "zerolatency", 0); + if (codec_id == AV_CODEC_ID_H264) { + av_dict_set(&options, "x264-params", "repeat-headers=1:threads=1", 0); + } else { + av_dict_set(&options, "x265-params", "repeat-headers=1:pools=none:frame-threads=1", 0); + } + ASSERT_EQ(avcodec_open2(context.get(), codec, &options), 0); + + video::avcodec_frame_t frame {av_frame_alloc()}; + ASSERT_NE(frame.get(), nullptr); + frame->width = context->width; + frame->height = context->height; + frame->format = context->pix_fmt; + frame->pts = 0; + ASSERT_EQ(av_frame_get_buffer(frame.get(), 0), 0); + for (int plane = 0; plane < 3; ++plane) { + const auto height = plane == 0 ? frame->height : frame->height / 2; + std::fill_n(frame->data[plane], frame->linesize[plane] * height, plane == 0 ? 16 : 128); + } + ASSERT_EQ(avcodec_send_frame(context.get(), frame.get()), 0); + util::safe_ptr packet {av_packet_alloc()}; + ASSERT_NE(packet.get(), nullptr); + ASSERT_EQ(avcodec_receive_packet(context.get(), packet.get()), 0); + ASSERT_TRUE(cbs::validate_sps(packet.get(), codec_id)); + + const std::vector original_packet(packet->data, packet->data + packet->size); + std::vector rewritten(packet->data, packet->data + packet->size); + const auto replace_unit = [&rewritten](const cbs::nal_t &unit) { + const auto original = std::ranges::search(rewritten, unit.old); + if (original.empty()) { + return false; + } + const auto position = rewritten.erase(original.begin(), original.end()); + rewritten.insert(position, unit._new.begin(), unit._new.end()); + return true; + }; + if (codec_id == AV_CODEC_ID_H264) { + const auto result = cbs::make_sps_h264(context.get(), packet.get()); + ASSERT_GT(result.sps.old.size(), 0U); + ASSERT_GT(result.sps._new.size(), 0U); + ASSERT_TRUE(replace_unit(result.sps)); + } else { + const auto result = cbs::make_sps_hevc(context.get(), packet.get()); + ASSERT_GT(result.vps.old.size(), 0U); + ASSERT_GT(result.vps._new.size(), 0U); + ASSERT_GT(result.sps.old.size(), 0U); + ASSERT_GT(result.sps._new.size(), 0U); + ASSERT_TRUE(replace_unit(result.vps)); + ASSERT_TRUE(replace_unit(result.sps)); + } + EXPECT_TRUE(std::ranges::equal(original_packet, std::span(packet->data, packet->size))); + util::safe_ptr rewritten_packet {av_packet_alloc()}; + ASSERT_NE(rewritten_packet.get(), nullptr); + ASSERT_EQ(av_new_packet(rewritten_packet.get(), static_cast(rewritten.size())), 0); + std::ranges::copy(rewritten, rewritten_packet->data); + EXPECT_TRUE(cbs::validate_sps(rewritten_packet.get(), codec_id)); +} + +INSTANTIATE_TEST_SUITE_P(SoftwareCodecs, CodedBitstreamTest, testing::Values(AV_CODEC_ID_H264, AV_CODEC_ID_HEVC)); diff --git a/tests/unit/test_encode_device.cpp b/tests/unit/test_encode_device.cpp new file mode 100644 index 000000000..f17bdc314 --- /dev/null +++ b/tests/unit/test_encode_device.cpp @@ -0,0 +1,112 @@ +/** + * @file tests/unit/test_encode_device.cpp + * @brief Tests for typed AVCodec hardware device initialization. + */ + +// test includes +#include "../tests_common.h" + +// standard includes +#include +#include + +// local includes +#include +#include + +namespace video { + util::Either vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device); +#ifdef SUNSHINE_BUILD_VULKAN + util::Either vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device); +#endif +} // namespace video + +namespace { + /** + * @brief Fake backend that records initialization and supplies an FFmpeg buffer. + */ + struct tracked_encode_device_t: platf::avcodec_encode_device_t { + int calls = 0; ///< Number of backend initialization calls. + int status = 0; ///< Status returned by the fake backend. + AVBufferRef *created_buffer = nullptr; ///< Non-owning identity of the buffer returned to FFmpeg. + + tracked_encode_device_t() { + hardware = true; + init_hw_device = &initialize; + } + + /** + * @brief Initialize a tracked hardware buffer or return the configured error. + * @param device Fake encode device whose invocation is recorded. + * @param buffer Receives the hardware buffer on success. + * @return Configured failure status or zero on success. + */ + static int initialize(platf::avcodec_encode_device_t *device, AVBufferRef **buffer) { + auto *tracked = static_cast(device); + ++tracked->calls; + if (tracked->status) { + return tracked->status; + } + tracked->created_buffer = av_buffer_alloc(1); + *buffer = tracked->created_buffer; + return *buffer ? 0 : AVERROR(ENOMEM); + } + }; + + /** + * @brief Supported hardware initialization entry points under test. + */ + using initializer_t = util::Either (*)(platf::avcodec_encode_device_t *); + + /** + * @brief Hardware initialization entry points available in this build. + */ + constexpr std::array hardware_initializers { + &video::vaapi_init_avcodec_hardware_input_buffer, +#ifdef SUNSHINE_BUILD_VULKAN + &video::vulkan_init_avcodec_hardware_input_buffer, +#endif + }; + + /** + * @brief Exercise the same typed backend contract for each hardware entry point. + */ + struct EncodeDeviceInitializationTest: testing::TestWithParam {}; +} // namespace + +static_assert(std::is_same_v); +static_assert(std::is_same_v); + +TEST(EncodeDeviceStateTest, SoftwareDeviceDoesNotAdvertiseHardwareResources) { + platf::avcodec_encode_device_t device; + EXPECT_FALSE(device.hardware); + EXPECT_EQ(device.init_hw_device, nullptr); +#ifdef _WIN32 + EXPECT_EQ(device.d3d11_device, nullptr); +#endif +} + +TEST_P(EncodeDeviceInitializationTest, UsesBackendBufferWithoutOpeningAnotherDevice) { + tracked_encode_device_t device; + auto result = GetParam()(&device); + ASSERT_TRUE(result.has_left()); + ASSERT_NE(result.left().get(), nullptr); + EXPECT_EQ(result.left().get(), device.created_buffer); + EXPECT_EQ(device.calls, 1); +} + +TEST_P(EncodeDeviceInitializationTest, PropagatesBackendFailureWithoutUsingFallback) { + tracked_encode_device_t device; + device.status = AVERROR(EINVAL); + auto result = GetParam()(&device); + ASSERT_FALSE(result.has_left()); + EXPECT_EQ(result.right(), -1); + EXPECT_EQ(device.created_buffer, nullptr); + EXPECT_EQ(device.calls, 1); +} + +INSTANTIATE_TEST_SUITE_P( + HardwareBackends, + EncodeDeviceInitializationTest, + testing::ValuesIn(hardware_initializers) +); diff --git a/tests/unit/test_nvenc_utils.cpp b/tests/unit/test_nvenc_utils.cpp index e371254b3..8e72a0d01 100644 --- a/tests/unit/test_nvenc_utils.cpp +++ b/tests/unit/test_nvenc_utils.cpp @@ -1,19 +1,177 @@ /** * @file tests/unit/test_nvenc_utils.cpp - * @brief Tests for Sunshine pixel format conversion in the NVENC SDK 13.1 implementation. + * @brief Tests for NVENC SDK 13.1 format conversion and native handle forwarding. */ #ifdef _WIN32 // standard includes #include + #include + #include + #include #include // lib includes #include // local includes + #include "src/nvenc/nvenc_base.h" + #include "src/nvenc/nvenc_d3d11.h" #include "src/nvenc/nvenc_utils.h" +namespace { + using namespace nvenc_1301; + + /** + * @brief Driver observations used to verify opaque encoder-session cleanup. + */ + struct driver_state_t { + NVENCSTATUS open_status = NV_ENC_SUCCESS; ///< Status returned by the fake session-open callback. + std::uintptr_t opened_device = 0; ///< Address of the native device forwarded to NVENC. + int opens = 0; ///< Session-open calls observed by the driver. + int destructions = 0; ///< Session-destroy calls observed by the driver. + }; + + driver_state_t driver; ///< Fake driver state and opaque session identity. + + /** + * @brief Return an opaque session and record the underlying native device. + * @param params NVENC parameters supplied by the base encoder. + * @param encoder Receives the fake driver's opaque session identity. + * @return Configured session-open status. + */ + NVENCSTATUS NVENCAPI open_session(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS *params, void **encoder) { // NOSONAR(cpp:S5008): NVENC's session-open callback requires a void double pointer for its opaque encoder handle. + driver.opened_device = std::bit_cast(params->device); + ++driver.opens; + *encoder = &driver; + return driver.open_status; + } + + /** + * @brief Stop initialization after the session has been opened. + * @param encoder Opaque session supplied by NVENC. + * @param count Receives the number of supported codec GUIDs. + * @return An error that forces the base encoder to release the session. + */ + NVENCSTATUS NVENCAPI fail_guid_count(void *encoder, std::uint32_t *count) { // NOSONAR(cpp:S5008): NVENC's GUID-count callback requires a void pointer for its opaque encoder handle. + EXPECT_EQ(encoder, &driver); + *count = 0; + return NV_ENC_ERR_GENERIC; + } + + /** + * @brief Verify and release the opaque session returned by the fake driver. + * @param encoder Opaque session identity being destroyed. + * @return Success after recording the destruction. + */ + NVENCSTATUS NVENCAPI destroy_session(void *encoder) { // NOSONAR(cpp:S5008): NVENC's session-destroy callback requires a void pointer for its opaque encoder handle. + EXPECT_EQ(encoder, &driver); + ++driver.destructions; + return NV_ENC_SUCCESS; + } + + /** + * @brief Base encoder with a fake driver and a typed D3D11 or CUDA device. + */ + class fake_session_encoder_t: public nvenc_base { + public: + /** + * @brief Install fake driver callbacks for one native device type. + * @param cuda Whether the test uses a CUDA context instead of a D3D11 device. + */ + explicit fake_session_encoder_t(bool cuda): + nvenc_base(cuda ? NV_ENC_DEVICE_TYPE_CUDA : NV_ENC_DEVICE_TYPE_DIRECTX) { + nvenc = std::make_shared(); + nvenc->nvEncOpenEncodeSessionEx = &open_session; + nvenc->nvEncGetEncodeGUIDCount = &fail_guid_count; + nvenc->nvEncDestroyEncoder = &destroy_session; + constexpr std::uintptr_t device_address = 0x1234; + if (cuda) { + device = std::bit_cast(device_address); + } else { + device = std::bit_cast(device_address); + } + } + + protected: + bool init_library() override { + return false; + } + + bool create_and_register_input_buffer() override { + ADD_FAILURE() << "Initialization should stop before registering an input buffer"; + return false; + } + }; + + /** + * @brief Device type and session-open status exercised by the fake driver. + */ + struct NvencNativeHandleTest: testing::TestWithParam> {}; + + /** + * @brief Native encoder exposing its typed completion event for lifetime checks. + */ + class completion_event_encoder_t: public nvenc_d3d11 { + public: + completion_event_encoder_t(): + nvenc_d3d11(NV_ENC_DEVICE_TYPE_DIRECTX, {}) { + } + + ID3D11Texture2D *get_input_texture() override { + return nullptr; + } + + /** + * @brief Borrow the event registered for asynchronous encoding. + * @return Native completion event owned by this encoder. + */ + completion_event_t *completion_event() const { + return async_event_handle; + } + + protected: + bool create_and_register_input_buffer() override { + return false; + } + }; +} // namespace + +TEST(NvencCompletionEventTest, TypedEventCanBeSignaledAndIsClosedWithTheEncoder) { + nvenc_1301::completion_event_t *event = nullptr; + { + completion_event_encoder_t encoder; + event = encoder.completion_event(); + ASSERT_NE(event, nullptr); + EXPECT_EQ(WaitForSingleObject(event, 0), WAIT_TIMEOUT); + ASSERT_TRUE(SetEvent(event)); + EXPECT_EQ(WaitForSingleObject(event, 0), WAIT_OBJECT_0); + } + EXPECT_EQ(WaitForSingleObject(event, 0), WAIT_FAILED); + EXPECT_EQ(GetLastError(), ERROR_INVALID_HANDLE); +} + +TEST_P(NvencNativeHandleTest, PreservesNativeDeviceAndReleasesReturnedSessionOnFailure) { + const auto &[cuda, status] = GetParam(); + driver = {}; + driver.open_status = status; + fake_session_encoder_t encoder {cuda}; + video::config_t client_config {}; + client_config.width = 64; + client_config.height = 64; + const auto colorspace = video::colorspace_from_client_config(client_config, false); + EXPECT_FALSE(encoder.create_encoder({}, client_config, colorspace, platf::pix_fmt_e::nv12)); + EXPECT_EQ(driver.opened_device, 0x1234U); + EXPECT_EQ(driver.opens, 1); + EXPECT_EQ(driver.destructions, 1); +} + +INSTANTIATE_TEST_SUITE_P( + DeviceTypesAndOpenStatuses, + NvencNativeHandleTest, + testing::Combine(testing::Bool(), testing::Values(NV_ENC_SUCCESS, NV_ENC_ERR_GENERIC)) +); + TEST(NvencFormatMappingTest, MapsSupportedFormatsAndRejectsUnsupportedOnes) { using enum platf::pix_fmt_e; using enum nvenc_1301::NV_ENC_BUFFER_FORMAT;