From c732a81f6cb3fbb6762adca0c1c421d12d0658f0 Mon Sep 17 00:00:00 2001 From: Dave Lane <42013603+ReenigneArcher@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:08:31 -0400 Subject: [PATCH] refactor: clarify optional checks, reduce copies, and tighten macro scopes (#5936) --- src/config.cpp | 49 ++++++++----- src/config.h | 4 +- src/crypto.cpp | 2 - src/nvenc/nvenc_base.cpp | 8 +-- src/nvhttp.cpp | 21 +++--- src/nvhttp.h | 2 +- src/platform/common.h | 15 ++-- src/platform/linux/graphics.cpp | 2 +- src/platform/linux/graphics.h | 1 - src/platform/linux/kmsgrab.cpp | 18 ++--- src/platform/linux/misc.cpp | 4 +- src/platform/linux/publish.cpp | 26 +++---- src/platform/linux/wayland.cpp | 49 +++++++------ src/platform/linux/wayland.h | 26 ++++--- src/platform/linux/wlgrab.cpp | 12 ++-- src/platform/linux/x11grab.cpp | 1 - src/platform/windows/misc.cpp | 20 +++--- .../windows/nvprefs/driver_settings.cpp | 2 +- .../windows/nvprefs/driver_settings.h | 1 + .../nvprefs/nvapi_opensource_wrapper.cpp | 49 ++++++------- src/platform/windows/nvprefs/undo_file.cpp | 4 +- src/platform/windows/nvprefs/undo_file.h | 8 +-- src/process.cpp | 2 +- src/rtsp.cpp | 4 +- src/stream.cpp | 9 ++- src/task_pool.h | 2 - src/thread_safe.h | 8 +-- src/utility.h | 19 +++-- src/video.cpp | 2 +- src/video.h | 10 +-- src/video_colorspace.cpp | 18 ++--- .../windows/test_nvprefs_undo_data.cpp | 72 +++++++++++++++++++ tests/unit/test_config.cpp | 25 +++++++ tests/unit/test_display_device.cpp | 26 ++++--- tests/unit/test_http_pairing.cpp | 15 ++++ tests/unit/test_nvenc_dynamic_factory.cpp | 2 + tests/unit/test_nvenc_utils.cpp | 62 +++++++++++++++- tests/unit/test_nvhttp_client_auth.cpp | 3 + tests/unit/test_thread_safe.cpp | 19 +++++ tests/unit/test_utility.cpp | 28 ++++++++ tests/unit/test_video.cpp | 55 +++++++++----- tests/unit/test_video_colorspace.cpp | 15 ++++ 42 files changed, 511 insertions(+), 209 deletions(-) create mode 100644 tests/unit/platform/windows/test_nvprefs_undo_data.cpp diff --git a/src/config.cpp b/src/config.cpp index bceda6d94..7705aa649 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -273,7 +273,9 @@ namespace config { _CONVERT_(balanced); _CONVERT_(quality); _CONVERT_(speed); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return original; } @@ -295,7 +297,9 @@ namespace config { _CONVERT_(cqp); _CONVERT_(vbr_latency); _CONVERT_(vbr_peak); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return original; } @@ -318,7 +322,9 @@ namespace config { _CONVERT_(transcoding); _CONVERT_(ultralowlatency); _CONVERT_(webcam); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return original; } @@ -385,7 +391,9 @@ namespace config { _CONVERT_(fast); _CONVERT_(faster); _CONVERT_(veryfast); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return std::nullopt; } @@ -590,7 +598,9 @@ namespace config { _CONVERT_(veryfast, 10); _CONVERT_(superfast, 11); _CONVERT_(ultrafast, 12); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return 11; // Default to superfast } } // namespace sw @@ -613,7 +623,9 @@ namespace config { _CONVERT_(ensure_active); _CONVERT_(ensure_primary); _CONVERT_(ensure_only_display); -#undef _CONVERT_ +#ifndef DOXYGEN + #undef _CONVERT_ +#endif return video_t::dd_t::config_option_e::disabled; // Default to this if value is invalid } @@ -633,8 +645,10 @@ namespace config { _CONVERT_(disabled); _CONVERT_2_ARG_(auto, automatic); _CONVERT_(manual); -#undef _CONVERT_ -#undef _CONVERT_2_ARG_ +#ifndef DOXYGEN + #undef _CONVERT_ + #undef _CONVERT_2_ARG_ +#endif return video_t::dd_t::resolution_option_e::disabled; // Default to this if value is invalid } @@ -654,8 +668,10 @@ namespace config { _CONVERT_(disabled); _CONVERT_2_ARG_(auto, automatic); _CONVERT_(manual); -#undef _CONVERT_ -#undef _CONVERT_2_ARG_ +#ifndef DOXYGEN + #undef _CONVERT_ + #undef _CONVERT_2_ARG_ +#endif return video_t::dd_t::refresh_rate_option_e::disabled; // Default to this if value is invalid } @@ -674,8 +690,10 @@ namespace config { #endif _CONVERT_(disabled); _CONVERT_2_ARG_(auto, automatic); -#undef _CONVERT_ -#undef _CONVERT_2_ARG_ +#ifndef DOXYGEN + #undef _CONVERT_ + #undef _CONVERT_2_ARG_ +#endif return video_t::dd_t::hdr_option_e::disabled; // Default to this if value is invalid } @@ -1028,7 +1046,6 @@ namespace config { auto end = std::end(file_content); while (pos < end) { - // auto newline = std::find_if(pos, end, [](auto ch) { return ch == '\n' || ch == '\r'; }); TUPLE_2D(endl, var, parse_option(pos, end)); pos = endl; @@ -1040,7 +1057,7 @@ namespace config { continue; } - vars.emplace(std::move(*var)); + vars.try_emplace(std::move(var->first), std::move(var->second)); } return vars; @@ -2025,7 +2042,7 @@ namespace config { cmd_vars.erase(it); } - cmd_vars.emplace(std::move(*var)); + cmd_vars.try_emplace(std::move(var->first), std::move(var->second)); } } } @@ -2044,7 +2061,7 @@ namespace config { auto vars = parse_config(file_handler::read_file(sunshine.config_file.c_str())); for (auto &[name, value] : cmd_vars) { - vars.insert_or_assign(std::move(name), std::move(value)); + vars.insert_or_assign(name, std::move(value)); } // Apply the config. Note: This will try to create any paths diff --git a/src/config.h b/src/config.h index 2062d6fd9..d13ddfd4e 100644 --- a/src/config.h +++ b/src/config.h @@ -348,7 +348,7 @@ namespace config { prep_cmd_t(std::string &&do_cmd, std::string &&undo_cmd, bool &&elevated): do_cmd(std::move(do_cmd)), undo_cmd(std::move(undo_cmd)), - elevated(std::move(elevated)) { + elevated(elevated) { } /** @@ -359,7 +359,7 @@ namespace config { */ explicit prep_cmd_t(std::string &&do_cmd, bool &&elevated): do_cmd(std::move(do_cmd)), - elevated(std::move(elevated)) { + elevated(elevated) { } std::string do_cmd; ///< Command to run before the application starts. diff --git a/src/crypto.cpp b/src/crypto.cpp index 452efbd14..3e113b2b1 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -402,8 +402,6 @@ namespace crypto { * @brief Return the certificate signature bytes. */ std::string_view signature(const x509_t &x) { - // X509_ALGOR *_ = nullptr; - const ASN1_BIT_STRING *asn1 = nullptr; X509_get0_signature(&asn1, nullptr, x.get()); diff --git a/src/nvenc/nvenc_base.cpp b/src/nvenc/nvenc_base.cpp index 31cb2e6a6..42101b626 100644 --- a/src/nvenc/nvenc_base.cpp +++ b/src/nvenc/nvenc_base.cpp @@ -127,10 +127,6 @@ namespace { } switch (number) { - case 1: - default: - return NV_ENC_PRESET_P1_GUID; - case 2: return NV_ENC_PRESET_P2_GUID; @@ -148,6 +144,10 @@ namespace { case 7: return NV_ENC_PRESET_P7_GUID; + + case 1: + default: + return NV_ENC_PRESET_P1_GUID; } }; diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 30df74805..8872b13dc 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -630,7 +630,7 @@ namespace nvhttp { sess.async_insert_pin.id = pairing_id; sess.async_insert_pin.expires_at = now + PAIRING_SESSION_TIMEOUT; - map_id_sess.emplace(sess.client.uniqueID, std::move(sess)); + map_id_sess.try_emplace(sess.client.uniqueID, std::move(sess)); return pair_session_insert_e::ADDED; } @@ -734,7 +734,7 @@ namespace nvhttp { * @param tree XML property tree used for the response body. * @param status_msg Status msg. */ - void fail_pair(pair_session_t &sess, pt::ptree &tree, const std::string status_msg) { + void fail_pair(pair_session_t &sess, pt::ptree &tree, const std::string &status_msg) { tree.put("root.paired", 0); tree.put("root..status_code", 400); tree.put("root..status_message", status_msg); @@ -1126,15 +1126,14 @@ namespace nvhttp { } bool pairing_complete = false; - args_t::const_iterator it; - if (it = args.find("clientchallenge"); it != std::end(args)) { - auto challenge = util::from_hex_vec(it->second, true); + if (const auto challenge_it = args.find("clientchallenge"); challenge_it != std::end(args)) { + auto challenge = util::from_hex_vec(challenge_it->second, true); clientchallenge(sess_it->second, tree, challenge); - } else if (it = args.find("serverchallengeresp"); it != std::end(args)) { - auto encrypted_response = util::from_hex_vec(it->second, true); + } else if (const auto response_it = args.find("serverchallengeresp"); response_it != std::end(args)) { + auto encrypted_response = util::from_hex_vec(response_it->second, true); serverchallengeresp(sess_it->second, tree, encrypted_response); - } else if (it = args.find("clientpairingsecret"); it != std::end(args)) { - auto pairingsecret = util::from_hex_vec(it->second, true); + } else if (const auto secret_it = args.find("clientpairingsecret"); secret_it != std::end(args)) { + auto pairingsecret = util::from_hex_vec(secret_it->second, true); clientpairingsecret(sess_it->second, tree, pairingsecret); pairing_complete = true; } else { @@ -1146,7 +1145,7 @@ namespace nvhttp { } } - bool pin(const std::string_view pairing_id, std::string pin, std::string name) { + bool pin(const std::string_view pairing_id, const std::string &pin, std::string name) { if (!is_valid_pairing_id(pairing_id) || !is_valid_pairing_pin(pin) || !is_valid_pairing_name(name)) { return false; } @@ -1360,7 +1359,7 @@ namespace nvhttp { app.put("AppTitle"s, proc.name); app.put("ID", proc.id); - apps.push_back(std::make_pair("App", std::move(app))); + apps.push_back(std::make_pair("App", app)); } } diff --git a/src/nvhttp.h b/src/nvhttp.h index e8d50c595..2b31a35ff 100644 --- a/src/nvhttp.h +++ b/src/nvhttp.h @@ -334,7 +334,7 @@ namespace nvhttp { * bool pin_status = nvhttp::pin("0123456789abcdef0123456789abcdef", "1234", "laptop"); * @examples_end */ - bool pin(std::string_view pairing_id, std::string pin, std::string name); + bool pin(std::string_view pairing_id, const std::string &pin, std::string name); /** * @brief Remove single client. diff --git a/src/platform/common.h b/src/platform/common.h index cb492ba1b..62961d7a3 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -375,7 +375,9 @@ namespace platf { _CONVERT(y410); _CONVERT(unknown); } -#undef _CONVERT +#ifndef DOXYGEN + #undef _CONVERT +#endif return "unknown"sv; } @@ -617,6 +619,7 @@ namespace platf { * @brief Apply the configured colorspace metadata to the active frame. */ virtual void apply_colorspace() { + // Backends without additional colorspace state need no update here. } /** @@ -638,16 +641,20 @@ namespace platf { * * @param frames FFmpeg hardware frames context to initialize. */ - virtual void init_hwframes(AVHWFramesContext *frames) {}; + virtual void init_hwframes(AVHWFramesContext *frames) { + // The base implementation leaves FFmpeg's hardware-frame parameters unchanged. + }; /** - * @brief Provides a hook for allow platform-specific code to adjust codec options. + * @brief Allow platform-specific code to adjust codec options. * @note Implementations may set or modify codec options prior to codec initialization. * * @param ctx Native context object used by the operation or callback. * @param options Request options or socket options to apply. */ - virtual void init_codec_options(AVCodecContext *ctx, AVDictionary **options) {}; + virtual void init_codec_options(AVCodecContext *ctx, AVDictionary **options) { + // The base implementation requires no platform-specific codec options. + }; /** * @brief Prepare to derive a context. diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index a4410ea35..24b33139c 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -514,7 +514,7 @@ namespace egl { return nullptr; } - // native_display.left() equals native_display.right() + // Initialize EGL with the selected platform and its native display handle. EGLDisplay raw_display = EGL_NO_DISPLAY; if (eglGetPlatformDisplayEXT) { diff --git a/src/platform/linux/graphics.h b/src/platform/linux/graphics.h index 2e8c28b1e..7b33ad8b2 100644 --- a/src/platform/linux/graphics.h +++ b/src/platform/linux/graphics.h @@ -408,7 +408,6 @@ namespace egl { gl::tex_t tex; ///< Textures containing the imported Y and UV planes. gl::frame_buf_t buf; ///< OpenGL framebuffer object used for rendering. - // sizeof(va::DRMPRIMESurfaceDescriptor::objects) / sizeof(va::DRMPRIMESurfaceDescriptor::objects[0]); static constexpr std::size_t num_fds = 4; ///< Maximum number of DMA-BUF plane file descriptors exported by VAAPI. std::array fds; ///< DMA-BUF file descriptors for each exported plane. diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 61d375611..0274f0b75 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -854,7 +854,7 @@ namespace platf { std::uint32_t get_panel_orientation(std::uint32_t plane_id) { auto props = plane_props(plane_id); auto value = prop_value_by_name(props, "rotation"sv); - if (value) { + if (value.has_value()) { return *value; } @@ -1050,10 +1050,10 @@ namespace platf { std::map result; for (auto &connector : connectors) { - result.emplace(connector.crtc_id, monitor_t { - .type = connector.type, - .index = connector.index, - }); + result.try_emplace(connector.crtc_id, monitor_t { + .type = connector.type, + .index = connector.index, + }); } return result; @@ -1368,7 +1368,7 @@ namespace platf { * @return True when the active display mode is HDR. */ bool is_hdr() override { - if (!hdr_metadata_blob_id || *hdr_metadata_blob_id == 0) { + if (!hdr_metadata_blob_id.has_value() || *hdr_metadata_blob_id == 0) { return false; } @@ -1489,14 +1489,14 @@ namespace platf { } } - if (!prop_crtc_w || !prop_crtc_h || !prop_crtc_x || !prop_crtc_y) { + if (!prop_crtc_w.has_value() || !prop_crtc_h.has_value() || !prop_crtc_x.has_value() || !prop_crtc_y.has_value()) { BOOST_LOG(error) << "Cursor plane is missing required plane CRTC properties!"sv; BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv; cursor_plane_id = -1; captured_cursor.visible = false; return; } - if (!prop_src_x || !prop_src_y || !prop_src_w || !prop_src_h) { + if (!prop_src_x.has_value() || !prop_src_y.has_value() || !prop_src_w.has_value() || !prop_src_h.has_value()) { BOOST_LOG(error) << "Cursor plane is missing required plane SRC properties!"sv; BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv; cursor_plane_id = -1; @@ -1650,7 +1650,7 @@ namespace platf { */ inline capture_e refresh(file_t *file, egl::surface_descriptor_t *sd, std::optional &frame_timestamp) { // Check for a change in HDR metadata - if (connector_id) { + if (connector_id.has_value()) { auto connector_props = card.connector_props(*connector_id); if (hdr_metadata_blob_id != card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv)) { BOOST_LOG(info) << "Reinitializing capture after HDR metadata change"sv; diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 8ffdb7b2a..b89b9b97d 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -1032,9 +1032,9 @@ namespace platf { * @brief Apply Linux socket priority and DSCP QoS settings for scoped cleanup. * * @param sockfd Native socket descriptor whose options are updated. - * @param options Request options or socket options to apply. + * @param options Socket options copied into this cleanup object's owned storage. */ - qos_t(int sockfd, std::vector> options): + qos_t(int sockfd, const std::vector> &options): sockfd(sockfd), options(options) { qos_ref_count++; diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index ec74da297..f5109f6f3 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -19,7 +19,9 @@ using namespace std::literals; namespace avahi { /** - * @brief Error codes used by avahi. + * @brief Error codes used by Avahi. + * @see https://www.rfc-editor.org/rfc/rfc2136.html#section-2.2 + * @see https://www.iana.org/assignments/dns-parameters/ */ enum err_e { OK = 0, ///< OK @@ -67,11 +69,11 @@ namespace avahi { ERR_DNS_NOTIMP = -39, ///< DNS Error: Not implemented ERR_DNS_REFUSED = -40, ///< DNS Error: Operation refused - ERR_DNS_YXDOMAIN = -41, ///< TODO - ERR_DNS_YXRRSET = -42, ///< TODO - ERR_DNS_NXRRSET = -43, ///< TODO - ERR_DNS_NOTAUTH = -44, ///< DNS Error: Not authorized - ERR_DNS_NOTZONE = -45, ///< TODO + ERR_DNS_YXDOMAIN = -41, ///< DNS Error: A name exists despite a prerequisite requiring its absence + ERR_DNS_YXRRSET = -42, ///< DNS Error: A resource record set exists despite a prerequisite requiring its absence + ERR_DNS_NXRRSET = -43, ///< DNS Error: A required resource record set is missing or has different records + ERR_DNS_NOTAUTH = -44, ///< DNS Error: The server lacks zone authority or TSIG authorization failed + ERR_DNS_NOTZONE = -45, ///< DNS Error: An update or prerequisite name lies outside the target DNS zone ERR_INVALID_RDATA = -46, ///< Invalid RDATA ERR_INVALID_DNS_CLASS = -47, ///< Invalid DNS class ERR_INVALID_DNS_TYPE = -48, ///< Invalid DNS type @@ -82,13 +84,13 @@ namespace avahi { ERR_IS_EMPTY = -52, ///< Is empty ERR_NO_CHANGE = -53, ///< The requested operation is invalid because it is redundant - ERR_MAX = -54 ///< TODO + ERR_MAX = -54 ///< Sentinel below the valid Avahi error-code range; not an error code }; - constexpr auto IF_UNSPEC = -1; ///< Protocol or platform constant for if unspec. + constexpr auto IF_UNSPEC = -1; ///< Select all network interfaces instead of a specific interface index. /** - * @brief Enumerates supported proto options. + * @brief Avahi address-family selectors. */ enum proto { PROTO_INET = 0, ///< IPv4 @@ -97,7 +99,7 @@ namespace avahi { }; /** - * @brief Enumerates supported server state options. + * @brief Avahi daemon lifecycle states. */ enum ServerState { SERVER_INVALID, ///< Invalid state (initial) @@ -285,7 +287,7 @@ namespace avahi { simple_poll_free_fn simple_poll_free; ///< Simple poll free. /** - * @brief Load common Avahi client and entry-group function pointers. + * @brief Load Avahi common-library memory, naming, error, and simple-poll functions. * * @return 0 when common Avahi functions are available; nonzero otherwise. */ @@ -324,7 +326,7 @@ namespace avahi { } /** - * @brief Load Avahi threaded-poll and client function pointers. + * @brief Load Avahi client and service-publication function pointers. * * @return 0 when all client functions are available; nonzero otherwise. */ diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index f9362ce7e..904c4f15d 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -58,17 +58,17 @@ namespace wl { reset(); } - bool gbm_device_t::init(const std::string &render_path, const gbm_device_accessors_t &accessors) { + bool gbm_device_t::init(const std::string &render_path, const gbm_device_accessors_t &device_accessors) { reset(); - this->accessors = accessors; + accessors = device_accessors; - drm_fd = accessors.open_render_node(render_path.c_str()); + drm_fd = device_accessors.open_render_node(render_path.c_str()); if (drm_fd < 0) { BOOST_LOG(error) << "[wayland] Failed to open DRM render node: "sv << render_path; return false; } - device = accessors.create_device(drm_fd); + device = device_accessors.create_device(drm_fd); if (!device) { BOOST_LOG(error) << "[wayland] Failed to create GBM device"sv; reset(); @@ -257,6 +257,7 @@ namespace wl { } void interface_t::dmabuf_format(zwp_linux_dmabuf_v1 *zwp_linux_dmabuf, uint32_t format) { + // Modifier events supply the explicit format/modifier pairs used for allocation. } void interface_t::dmabuf_modifier(zwp_linux_dmabuf_v1 *zwp_linux_dmabuf, uint32_t format, uint32_t modifier_hi, uint32_t modifier_lo) { @@ -269,35 +270,35 @@ namespace wl { void interface_t::add_interface( wl_registry *registry, std::uint32_t id, - const char *interface, + const char *interface_name, std::uint32_t version ) { - BOOST_LOG(debug) << "[wayland] Available interface: "sv << interface << '(' << id << ") version "sv << version; + BOOST_LOG(debug) << "[wayland] Available interface: "sv << interface_name << '(' << id << ") version "sv << version; - if (!std::strcmp(interface, wl_output_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + if (!std::strcmp(interface_name, wl_output_interface.name)) { + BOOST_LOG(info) << "[wayland] Found interface: "sv << interface_name << '(' << id << ") version "sv << version; monitors.emplace_back( std::make_unique( (wl_output *) wl_registry_bind(registry, id, &wl_output_interface, 2) ) ); - } else if (!std::strcmp(interface, zxdg_output_manager_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + } else if (!std::strcmp(interface_name, zxdg_output_manager_v1_interface.name)) { + BOOST_LOG(info) << "[wayland] Found interface: "sv << interface_name << '(' << id << ") version "sv << version; output_manager = (zxdg_output_manager_v1 *) wl_registry_bind(registry, id, &zxdg_output_manager_v1_interface, version); - this->interface[XDG_OUTPUT] = true; - } else if (!std::strcmp(interface, zwlr_screencopy_manager_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + interface[XDG_OUTPUT] = true; + } else if (!std::strcmp(interface_name, zwlr_screencopy_manager_v1_interface.name)) { + BOOST_LOG(info) << "[wayland] Found interface: "sv << interface_name << '(' << id << ") version "sv << version; screencopy_manager = (zwlr_screencopy_manager_v1 *) wl_registry_bind(registry, id, &zwlr_screencopy_manager_v1_interface, version); screencopy_version = version; - this->interface[WLR_EXPORT_DMABUF] = true; - } else if (!std::strcmp(interface, zwp_linux_dmabuf_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + interface[WLR_EXPORT_DMABUF] = true; + } else if (!std::strcmp(interface_name, zwp_linux_dmabuf_v1_interface.name)) { + BOOST_LOG(info) << "[wayland] Found interface: "sv << interface_name << '(' << id << ") version "sv << version; dmabuf_interface = (zwp_linux_dmabuf_v1 *) wl_registry_bind(registry, id, &zwp_linux_dmabuf_v1_interface, std::min(version, 3u)); zwp_linux_dmabuf_v1_add_listener(dmabuf_interface, &dmabuf_listener, this); - this->interface[LINUX_DMABUF] = true; + interface[LINUX_DMABUF] = true; } } @@ -375,14 +376,14 @@ namespace wl { void dmabuf_t::listen( zwlr_screencopy_manager_v1 *screencopy_manager, zwp_linux_dmabuf_v1 *dmabuf_interface, - const std::map> *supported_modifiers, + const std::map> *compositor_formats, wl_output *output, bool blend_cursor, - const std::map> *encoder_modifiers + const std::map> *encoder_formats ) { this->dmabuf_interface = dmabuf_interface; - this->supported_modifiers = supported_modifiers; - this->encoder_modifiers = encoder_modifiers; + supported_modifiers = compositor_formats; + encoder_modifiers = encoder_formats; // Reset state shm_info.supported = false; dmabuf_info.supported = false; @@ -504,7 +505,7 @@ namespace wl { // Export every memory plane into the surface descriptor auto next_frame = get_next_frame(); const auto plane_count = export_gbm_bo_planes(current_bo, *next_frame, gbm_bo_accessors); - if (!plane_count) { + if (!plane_count.has_value()) { gbm_bo_destroy(current_bo); current_bo = nullptr; zwlr_screencopy_frame_v1_destroy(frame); @@ -664,7 +665,9 @@ namespace wl { std::uint32_t y, std::uint32_t width, std::uint32_t height - ) {}; + ) { + // Capture and encoding consume the whole buffer, so no damage rectangles are tracked. + }; void frame_t::destroy() { for (auto x = 0; x < 4; ++x) { diff --git a/src/platform/linux/wayland.h b/src/platform/linux/wayland.h index aba5fc0e0..3177a3032 100644 --- a/src/platform/linux/wayland.h +++ b/src/platform/linux/wayland.h @@ -214,10 +214,10 @@ namespace wl { * @brief Open the render node and create the GBM device on it. * * @param render_path Path of the DRM render node. - * @param accessors Functions used to open the node and create the device. + * @param device_accessors Functions used to open the node and create the device. * @return `true` when the device is ready, `false` when nothing is held. */ - bool init(const std::string &render_path, const gbm_device_accessors_t &accessors); + bool init(const std::string &render_path, const gbm_device_accessors_t &device_accessors); /** * @brief Destroy the GBM device and close the render-node descriptor. @@ -303,12 +303,12 @@ namespace wl { * * @param screencopy_manager Compositor screencopy manager used to request frames. * @param dmabuf_interface Compositor DMA-BUF interface used to allocate buffers. - * @param supported_modifiers DMA-BUF format modifiers supported by the compositor. + * @param compositor_formats DMA-BUF format modifiers supported by the compositor. * @param output Wayland output to capture. * @param blend_cursor Whether the compositor should include the cursor in the frame. - * @param encoder_modifiers Optional modifiers supported by the encoder for format intersection. + * @param encoder_formats Optional modifiers supported by the encoder for format intersection. */ - void listen(zwlr_screencopy_manager_v1 *screencopy_manager, zwp_linux_dmabuf_v1 *dmabuf_interface, const std::map> *supported_modifiers, wl_output *output, bool blend_cursor = false, const std::map> *encoder_modifiers = nullptr); + void listen(zwlr_screencopy_manager_v1 *screencopy_manager, zwp_linux_dmabuf_v1 *dmabuf_interface, const std::map> *compositor_formats, wl_output *output, bool blend_cursor = false, const std::map> *encoder_formats = nullptr); /** * @brief Store the Wayland buffer created for a DMA-BUF parameter request. * @@ -489,9 +489,11 @@ namespace wl { void xdg_size(zxdg_output_v1 *, std::int32_t width, std::int32_t height); /** - * @brief Acknowledge completion of an xdg-output metadata update. + * @brief Receive completion of an xdg-output metadata update. */ - void xdg_done(zxdg_output_v1 *) {} + void xdg_done(zxdg_output_v1 *) { + // Size and position callbacks already store the metadata; completion needs no action. + } /** * @brief Ignore physical wl-output geometry; monitor placement comes from xdg-output metadata. @@ -607,7 +609,15 @@ namespace wl { zxdg_output_manager_v1 *output_manager {nullptr}; ///< xdg-output global used to query monitor names and sizes. private: - void add_interface(wl_registry *registry, std::uint32_t id, const char *interface, std::uint32_t version); + /** + * @brief Bind supported globals advertised by the Wayland registry. + * + * @param registry Registry advertising the global. + * @param id Numeric name used to bind the global. + * @param interface_name Protocol interface name advertised by the compositor. + * @param version Protocol version advertised for the global. + */ + void add_interface(wl_registry *registry, std::uint32_t id, const char *interface_name, std::uint32_t version); void del_interface(wl_registry *registry, uint32_t id); std::bitset interface; diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index e2ad5c430..7d2d31a52 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -21,16 +21,17 @@ namespace wl { static int env_height; bool use_vram_capture(platf::mem_type_e hwdevice_type) { - if (hwdevice_type == platf::mem_type_e::vaapi) { + using enum platf::mem_type_e; + if (hwdevice_type == vaapi) { return true; } - if (hwdevice_type == platf::mem_type_e::vulkan) { + if (hwdevice_type == vulkan) { return true; } #ifdef SUNSHINE_BUILD_CUDA - if (hwdevice_type == platf::mem_type_e::cuda) { + if (hwdevice_type == cuda) { return true; } #endif @@ -63,8 +64,9 @@ namespace wl { } screencopy_request_e next_screencopy_request(bool pending, bool requested_cursor, bool cursor, bool event_driven, bool have_frame) { + using enum screencopy_request_e; if (pending) { - return requested_cursor == cursor ? screencopy_request_e::keep : screencopy_request_e::copy; + return requested_cursor == cursor ? keep : copy; } // The first frame is asked for outright, and so is the first one after @@ -72,7 +74,7 @@ namespace wl { // request for the next change would leave the stream without anything // to show, or with the cursor as it was, until something moved. const bool up_to_date = have_frame && requested_cursor == cursor; - return event_driven && up_to_date ? screencopy_request_e::copy_with_damage : screencopy_request_e::copy; + return event_driven && up_to_date ? copy_with_damage : copy; } bool should_wait_for_damage_request( diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 19b7b9979..a81b1b89d 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -511,7 +511,6 @@ namespace platf { * Last X (NOT the streamed monitor!) size. * This way we can trigger reinitialization if the dimensions changed while streaming */ - // int env_width, env_height; /** * @brief Explicitly open the X11 display and initialize capture attributes. diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 405c67618..955627582 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -2,6 +2,16 @@ * @file src/platform/windows/misc.cpp * @brief Miscellaneous definitions for Windows. */ + +// TODO: Revisit this override when formalizing the Windows 11 minimum API target. +#ifndef NTDDI_VERSION + /** + * @def NTDDI_VERSION + * @brief Target Windows 10 APIs before Boost or Windows headers select a default. + */ + #define NTDDI_VERSION NTDDI_WIN10 +#endif + // standard includes #include #include @@ -37,16 +47,8 @@ #include #include #include -// clang-format on - -// Boost overrides NTDDI_VERSION, so we re-override it here -#undef NTDDI_VERSION -/** - * @def NTDDI_VERSION - * @brief Macro for NTDDI VERSION. - */ -#define NTDDI_VERSION NTDDI_WIN10 #include +// clang-format on // local includes #include "misc.h" diff --git a/src/platform/windows/nvprefs/driver_settings.cpp b/src/platform/windows/nvprefs/driver_settings.cpp index 3e4eecd1a..7e5f5ef97 100644 --- a/src/platform/windows/nvprefs/driver_settings.cpp +++ b/src/platform/windows/nvprefs/driver_settings.cpp @@ -115,7 +115,7 @@ namespace nvprefs { status = NvAPI_DRS_GetSetting(session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID, &setting); if (status == NVAPI_OK && setting.settingLocation == NVDRS_CURRENT_PROFILE_LOCATION && setting.u32CurrentValue == swapchain_data->our_value) { - if (swapchain_data->undo_value) { + if (swapchain_data->undo_value.has_value()) { setting = {}; setting.version = NVDRS_SETTING_VER1; setting.settingId = OGL_CPL_PREFER_DXPRESENT_ID; diff --git a/src/platform/windows/nvprefs/driver_settings.h b/src/platform/windows/nvprefs/driver_settings.h index 7e1f4b214..a111aeb6f 100644 --- a/src/platform/windows/nvprefs/driver_settings.h +++ b/src/platform/windows/nvprefs/driver_settings.h @@ -71,6 +71,7 @@ namespace nvprefs { /** * @brief Restore global NVIDIA profile settings from undo data. + * @details A saved value of zero is restored; only an absent value removes the setting. * * @param undo_data Driver settings captured before Sunshine modified them. * @return True when the NVIDIA driver-settings operation succeeds. diff --git a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp index bf9f8f212..ba2ada20a 100644 --- a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp +++ b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp @@ -30,13 +30,6 @@ namespace { } // namespace -#undef NVAPI_INTERFACE -/** - * @def NVAPI_INTERFACE - * @brief Macro for NVAPI INTERFACE. - */ -#define NVAPI_INTERFACE NvAPI_Status __cdecl - /** * @brief NVAPI export used to resolve function pointers by interface ID. * @@ -45,14 +38,14 @@ namespace { */ extern void *__cdecl nvapi_QueryInterface(NvU32 id); -NVAPI_INTERFACE +NvAPI_Status __cdecl -/** - * @brief Load NVAPI and resolve the subset of interfaces used by Sunshine. - * - * @return NVAPI_OK on success, or NVAPI_LIBRARY_NOT_FOUND when the DLL cannot be loaded. - */ -NvAPI_Initialize() { + /** + * @brief Load NVAPI and resolve the subset of interfaces used by Sunshine. + * + * @return NVAPI_OK on success, or NVAPI_LIBRARY_NOT_FOUND when the DLL cannot be loaded. + */ + NvAPI_Initialize() { if (dll) { return NVAPI_OK; } @@ -84,7 +77,7 @@ NvAPI_Initialize() { * * @return NVAPI_OK after cleanup. */ -NVAPI_INTERFACE NvAPI_Unload() { +NvAPI_Status __cdecl NvAPI_Unload() { if (dll) { interfaces.clear(); FreeLibrary(dll); @@ -100,7 +93,7 @@ NVAPI_INTERFACE NvAPI_Unload() { * @param szDesc Output buffer receiving the human-readable error string. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_GetErrorMessage(NvAPI_Status nr, NvAPI_ShortString szDesc) { +NvAPI_Status __cdecl NvAPI_GetErrorMessage(NvAPI_Status nr, NvAPI_ShortString szDesc) { return call_interface("NvAPI_GetErrorMessage", nr, szDesc); } @@ -112,7 +105,7 @@ NVAPI_INTERFACE NvAPI_GetErrorMessage(NvAPI_Status nr, NvAPI_ShortString szDesc) * @param phSession Output handle for the created DRS session. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_CreateSession(NvDRSSessionHandle *phSession) { +NvAPI_Status __cdecl NvAPI_DRS_CreateSession(NvDRSSessionHandle *phSession) { return call_interface("NvAPI_DRS_CreateSession", phSession); } @@ -122,7 +115,7 @@ NVAPI_INTERFACE NvAPI_DRS_CreateSession(NvDRSSessionHandle *phSession) { * @param hSession DRS session handle to destroy. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_DestroySession(NvDRSSessionHandle hSession) { +NvAPI_Status __cdecl NvAPI_DRS_DestroySession(NvDRSSessionHandle hSession) { return call_interface("NvAPI_DRS_DestroySession", hSession); } @@ -132,7 +125,7 @@ NVAPI_INTERFACE NvAPI_DRS_DestroySession(NvDRSSessionHandle hSession) { * @param hSession DRS session whose settings are loaded. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_LoadSettings(NvDRSSessionHandle hSession) { +NvAPI_Status __cdecl NvAPI_DRS_LoadSettings(NvDRSSessionHandle hSession) { return call_interface("NvAPI_DRS_LoadSettings", hSession); } @@ -142,7 +135,7 @@ NVAPI_INTERFACE NvAPI_DRS_LoadSettings(NvDRSSessionHandle hSession) { * @param hSession DRS session whose settings are saved. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_SaveSettings(NvDRSSessionHandle hSession) { +NvAPI_Status __cdecl NvAPI_DRS_SaveSettings(NvDRSSessionHandle hSession) { return call_interface("NvAPI_DRS_SaveSettings", hSession); } @@ -154,7 +147,7 @@ NVAPI_INTERFACE NvAPI_DRS_SaveSettings(NvDRSSessionHandle hSession) { * @param phProfile Output handle for the created profile. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_CreateProfile(NvDRSSessionHandle hSession, NVDRS_PROFILE *pProfileInfo, NvDRSProfileHandle *phProfile) { +NvAPI_Status __cdecl NvAPI_DRS_CreateProfile(NvDRSSessionHandle hSession, NVDRS_PROFILE *pProfileInfo, NvDRSProfileHandle *phProfile) { return call_interface("NvAPI_DRS_CreateProfile", hSession, pProfileInfo, phProfile); } @@ -166,7 +159,7 @@ NVAPI_INTERFACE NvAPI_DRS_CreateProfile(NvDRSSessionHandle hSession, NVDRS_PROFI * @param phProfile Output handle for the matched profile. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_FindProfileByName(NvDRSSessionHandle hSession, NvAPI_UnicodeString profileName, NvDRSProfileHandle *phProfile) { +NvAPI_Status __cdecl NvAPI_DRS_FindProfileByName(NvDRSSessionHandle hSession, NvAPI_UnicodeString profileName, NvDRSProfileHandle *phProfile) { return call_interface("NvAPI_DRS_FindProfileByName", hSession, profileName, phProfile); } @@ -178,7 +171,7 @@ NVAPI_INTERFACE NvAPI_DRS_FindProfileByName(NvDRSSessionHandle hSession, NvAPI_U * @param pApplication Application entry to create. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_CreateApplication(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_APPLICATION *pApplication) { +NvAPI_Status __cdecl NvAPI_DRS_CreateApplication(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_APPLICATION *pApplication) { return call_interface("NvAPI_DRS_CreateApplication", hSession, hProfile, pApplication); } @@ -191,7 +184,7 @@ NVAPI_INTERFACE NvAPI_DRS_CreateApplication(NvDRSSessionHandle hSession, NvDRSPr * @param pApplication Output application information. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_GetApplicationInfo(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvAPI_UnicodeString appName, NVDRS_APPLICATION *pApplication) { +NvAPI_Status __cdecl NvAPI_DRS_GetApplicationInfo(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvAPI_UnicodeString appName, NVDRS_APPLICATION *pApplication) { return call_interface("NvAPI_DRS_GetApplicationInfo", hSession, hProfile, appName, pApplication); } @@ -203,7 +196,7 @@ NVAPI_INTERFACE NvAPI_DRS_GetApplicationInfo(NvDRSSessionHandle hSession, NvDRSP * @param pSetting Setting value to apply. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_SetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_SETTING *pSetting) { +NvAPI_Status __cdecl NvAPI_DRS_SetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_SETTING *pSetting) { return call_interface("NvAPI_DRS_SetSetting", hSession, hProfile, pSetting); } @@ -216,7 +209,7 @@ NVAPI_INTERFACE NvAPI_DRS_SetSetting(NvDRSSessionHandle hSession, NvDRSProfileHa * @param pSetting Output setting value. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_GetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId, NVDRS_SETTING *pSetting) { +NvAPI_Status __cdecl NvAPI_DRS_GetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId, NVDRS_SETTING *pSetting) { return call_interface("NvAPI_DRS_GetSetting", hSession, hProfile, settingId, pSetting); } @@ -228,7 +221,7 @@ NVAPI_INTERFACE NvAPI_DRS_GetSetting(NvDRSSessionHandle hSession, NvDRSProfileHa * @param settingId Setting ID. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_DeleteProfileSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId) { +NvAPI_Status __cdecl NvAPI_DRS_DeleteProfileSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId) { return call_interface("NvAPI_DRS_DeleteProfileSetting", hSession, hProfile, settingId); } @@ -239,6 +232,6 @@ NVAPI_INTERFACE NvAPI_DRS_DeleteProfileSetting(NvDRSSessionHandle hSession, NvDR * @param phProfile Output handle for the base profile. * @return NVAPI status returned by the loaded function. */ -NVAPI_INTERFACE NvAPI_DRS_GetBaseProfile(NvDRSSessionHandle hSession, NvDRSProfileHandle *phProfile) { +NvAPI_Status __cdecl NvAPI_DRS_GetBaseProfile(NvDRSSessionHandle hSession, NvDRSProfileHandle *phProfile) { return call_interface("NvAPI_DRS_GetBaseProfile", hSession, phProfile); } diff --git a/src/platform/windows/nvprefs/undo_file.cpp b/src/platform/windows/nvprefs/undo_file.cpp index 41fd41b38..950a2f245 100644 --- a/src/platform/windows/nvprefs/undo_file.cpp +++ b/src/platform/windows/nvprefs/undo_file.cpp @@ -48,7 +48,7 @@ namespace { namespace nvprefs { - std::optional undo_file_t::open_existing_file(std::filesystem::path file_path, bool &access_denied) { + std::optional undo_file_t::open_existing_file(const std::filesystem::path &file_path, bool &access_denied) { undo_file_t file; file.file_handle.reset(CreateFileW(file_path.c_str(), GENERIC_READ | DELETE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (file.file_handle) { @@ -61,7 +61,7 @@ namespace nvprefs { } } - std::optional undo_file_t::create_new_file(std::filesystem::path file_path) { + std::optional undo_file_t::create_new_file(const std::filesystem::path &file_path) { undo_file_t file; file.file_handle.reset(CreateFileW(file_path.c_str(), GENERIC_WRITE | STANDARD_RIGHTS_ALL, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr)); diff --git a/src/platform/windows/nvprefs/undo_file.h b/src/platform/windows/nvprefs/undo_file.h index fdf4e85d4..599caa50c 100644 --- a/src/platform/windows/nvprefs/undo_file.h +++ b/src/platform/windows/nvprefs/undo_file.h @@ -21,19 +21,19 @@ namespace nvprefs { /** * @brief Open existing file. * - * @param file_path File path. + * @param file_path File path inspected without copying or modifying it. * @param access_denied Access denied. * @return Open undo file wrapper, or std::nullopt when the file cannot be opened. */ - static std::optional open_existing_file(std::filesystem::path file_path, bool &access_denied); + static std::optional open_existing_file(const std::filesystem::path &file_path, bool &access_denied); /** * @brief Create new file. * - * @param file_path File path. + * @param file_path File path inspected without copying or modifying it. * @return Created new file object or status. */ - static std::optional create_new_file(std::filesystem::path file_path); + static std::optional create_new_file(const std::filesystem::path &file_path); /** * @brief Delete the persisted NVIDIA settings undo file. diff --git a/src/process.cpp b/src/process.cpp index 8d3432618..867b64588 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -824,7 +824,7 @@ namespace proc { } return proc::proc_t { - std::move(this_env), + this_env, std::move(apps) }; } catch (std::exception &e) { diff --git a/src/rtsp.cpp b/src/rtsp.cpp index c654415c6..71253733c 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -533,7 +533,7 @@ namespace rtsp_stream { * @param cb Callback invoked for each matching message or session. */ void map(const std::string_view &type, cmd_func_t cb) { - _map_cmd_cb.emplace(type, std::move(cb)); + _map_cmd_cb.try_emplace(type, std::move(cb)); } /** @@ -1068,7 +1068,7 @@ namespace rtsp_stream { if (val[val.size() - 1] == ' ') { val = val.substr(0, val.size() - 1); } - args.emplace(name, val); + args.try_emplace(name, val); } } diff --git a/src/stream.cpp b/src/stream.cpp index 546041392..2f2db0c2f 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -438,7 +438,7 @@ namespace stream { * @param cb Callback invoked for each matching message or session. */ void map(uint16_t type, std::function cb) { - _map_type_cb.emplace(type, std::move(cb)); + _map_type_cb.try_emplace(type, std::move(cb)); } /** @@ -536,8 +536,7 @@ namespace stream { std::string ping_payload; ///< Payload expected from audio-channel ping packets. std::uint16_t sequenceNumber; ///< Next RTP sequence number for an audio packet. - // avRiKeyId == util::endian::big(First (sizeof(avRiKeyId)) bytes of launch_session->iv) - std::uint32_t avRiKeyId; ///< Base audio encryption key identifier derived from the launch-session IV. + std::uint32_t avRiKeyId; ///< Base audio encryption key identifier decoded from the first four IV bytes in big-endian order. std::uint32_t timestamp; ///< RTP timestamp for the next audio packet. udp::endpoint peer; ///< Client UDP endpoint for the audio channel. @@ -1461,14 +1460,14 @@ namespace stream { switch (socket_type) { case socket_e::video: if (message_queue) { - peer_to_video_session.emplace(session_id, message_queue); + peer_to_video_session.try_emplace(session_id, message_queue); } else { peer_to_video_session.erase(session_id); } break; case socket_e::audio: if (message_queue) { - peer_to_audio_session.emplace(session_id, message_queue); + peer_to_audio_session.try_emplace(session_id, message_queue); } else { peer_to_audio_session.erase(session_id); } diff --git a/src/task_pool.h b/src/task_pool.h index 49ac192d5..3827fbc78 100644 --- a/src/task_pool.h +++ b/src/task_pool.h @@ -26,8 +26,6 @@ namespace task_pool_util { */ class _ImplBase { public: - // _unique_base_type _this_ptr; - /** * @brief Destroy a queued callable through its polymorphic base. */ diff --git a/src/thread_safe.h b/src/thread_safe.h index d3fac2bb3..a2fc99e74 100644 --- a/src/thread_safe.h +++ b/src/thread_safe.h @@ -813,7 +813,7 @@ namespace safe { using queue_t = std::shared_ptr>>; /** - * @brief Create a typed event channel from the raw mailbox. + * @brief Create a typed event channel or reuse the live channel with the same identifier. * * @param id Identifier for the controller, session, display, or resource. * @return Typed event channel associated with the supplied identifier. @@ -827,13 +827,13 @@ namespace safe { } auto post = std::make_shared::element_type>(shared_from_this()); - id_to_post.emplace(std::pair> {std::string {id}, post}); + id_to_post.try_emplace(std::string {id}, post); return post; } /** - * @brief Create a typed queue channel from the raw mailbox. + * @brief Create a typed queue channel or reuse the live channel with the same identifier. * * @param id Identifier for the controller, session, display, or resource. * @return Typed queue channel associated with the supplied identifier. @@ -847,7 +847,7 @@ namespace safe { } auto post = std::make_shared::element_type>(shared_from_this(), 32); - id_to_post.emplace(std::pair> {std::string {id}, post}); + id_to_post.try_emplace(std::string {id}, post); return post; } diff --git a/src/utility.h b/src/utility.h index 1ff9fe371..d9a4dfa2d 100644 --- a/src/utility.h +++ b/src/utility.h @@ -1426,15 +1426,17 @@ namespace util { * @brief Helper specialization for optional values. */ template - struct __false_v>> { + requires instantiation_of_v + struct __false_v { static constexpr std::nullopt_t value = std::nullopt; ///< Value. }; /** - * @brief Enables an overload only when the provided type is a pointer. + * @brief Select a null sentinel for raw and supported smart pointer types. */ template - struct __false_v>> { + requires is_pointer_v + struct __false_v { static constexpr std::nullptr_t value = nullptr; ///< Value. }; @@ -1442,7 +1444,8 @@ namespace util { * @brief Type trait comparing a value with a boolean template argument. */ template - struct __false_v>> { + requires std::is_same_v + struct __false_v { static constexpr bool value = false; ///< Trait value for the false specialization. }; @@ -1773,10 +1776,11 @@ namespace util { struct endian_helper {}; /** - * @brief Helper specialization for optional values. + * @brief Convert non-optional values between native and requested byte order. */ template - struct endian_helper)>> { + requires(!instantiation_of_v) + struct endian_helper { /** * @brief Convert a value to or from big-endian byte order. * @@ -1814,7 +1818,8 @@ namespace util { * @brief Helper specialization for optional values. */ template - struct endian_helper>> { + requires instantiation_of_v + struct endian_helper { /** * @brief Convert a value to or from little-endian byte order. * diff --git a/src/video.cpp b/src/video.cpp index 73bacdb66..82a1a4adc 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -2172,7 +2172,7 @@ namespace video { av_dict_set_int(&options, option.name.c_str(), *v, 0); }, [&options, &option](std::optional *v) { - if (*v) { + if (v->has_value()) { av_dict_set_int(&options, option.name.c_str(), **v, 0); } }, diff --git a/src/video.h b/src/video.h index 857e12b4d..a6073b0c4 100644 --- a/src/video.h +++ b/src/video.h @@ -328,7 +328,9 @@ namespace video { _CONVERT(VUI_PARAMETERS); _CONVERT(MAX_FLAGS); } -#undef _CONVERT +#ifndef DOXYGEN + #undef _CONVERT +#endif return {"unknown"}; } @@ -520,14 +522,14 @@ namespace video { KITTY_DEFAULT_CONSTR_MOVE(replace_t) /** - * @brief Store an encoded-byte replacement rule. + * @brief Copy the non-owning byte views for an encoded-byte replacement rule. * * @param old Byte sequence to replace in encoded packets. * @param _new Replacement byte sequence inserted into encoded packets. */ replace_t(std::string_view old, std::string_view _new) noexcept: - old {std::move(old)}, - _new {std::move(_new)} { + old {old}, + _new {_new} { } }; diff --git a/src/video_colorspace.cpp b/src/video_colorspace.cpp index db8456858..5479a77d0 100644 --- a/src/video_colorspace.cpp +++ b/src/video_colorspace.cpp @@ -166,16 +166,16 @@ namespace video { Kr = 0.299; Kb = 0.114; break; - case rec709: - default: - Kr = 0.2126; - Kb = 0.0722; - break; case bt2020: case bt2020sdr: Kr = 0.2627; Kb = 0.0593; break; + case rec709: + default: + Kr = 0.2126; + Kb = 0.0722; + break; } double Kg = 1.0 - Kr - Kb; @@ -269,14 +269,14 @@ namespace video { case rec601: result = &colors[0]; break; - case rec709: - default: - result = &colors[4]; - break; case bt2020: case bt2020sdr: result = &colors[8]; break; + case rec709: + default: + result = &colors[4]; + break; } if (colorspace.bit_depth == 10) { diff --git a/tests/unit/platform/windows/test_nvprefs_undo_data.cpp b/tests/unit/platform/windows/test_nvprefs_undo_data.cpp new file mode 100644 index 000000000..59721347b --- /dev/null +++ b/tests/unit/platform/windows/test_nvprefs_undo_data.cpp @@ -0,0 +1,72 @@ +/** + * @file tests/unit/platform/windows/test_nvprefs_undo_data.cpp + * @brief Regression coverage for absent and zero NVIDIA preference restore values. + */ + +// test includes +#include "../../../tests_common.h" + +#ifdef _WIN32 + + // standard includes + #include + + // lib includes + #include + + // local includes + #include "src/platform/windows/nvprefs/undo_data.h" + #include "src/platform/windows/nvprefs/undo_file.h" + +static_assert(std::is_same_v (*)(const std::filesystem::path &, bool &)>); +static_assert(std::is_same_v (*)(const std::filesystem::path &)>); + +/** + * @brief Input-only paths preserve creation, sharing-error, and missing-file behavior. + */ +TEST_F(BaseTest, NvPrefsUndoFilesAcceptConstPathsAndReportOpenFailures) { + const auto path = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "nvprefs_const_path_test.json"; + std::filesystem::remove(path); + auto cleanup = util::fail_guard([&path] { + std::error_code ignored; + std::filesystem::remove(path, ignored); + }); + + { + const auto created = nvprefs::undo_file_t::create_new_file(path); + ASSERT_TRUE(created.has_value()); + bool access_denied = false; + EXPECT_FALSE(nvprefs::undo_file_t::open_existing_file(path, access_denied).has_value()); + EXPECT_TRUE(access_denied); + } + + bool access_denied = true; + auto reopened = nvprefs::undo_file_t::open_existing_file(path, access_denied); + ASSERT_TRUE(reopened.has_value()); + EXPECT_FALSE(access_denied); + reopened.reset(); + EXPECT_FALSE(nvprefs::undo_file_t::create_new_file(path).has_value()); + + ASSERT_TRUE(std::filesystem::remove(path)); + EXPECT_FALSE(nvprefs::undo_file_t::open_existing_file(path, access_denied).has_value()); + EXPECT_FALSE(access_denied); +} + +/** + * @brief Serialization preserves the distinction between zero and an absent driver setting. + */ +TEST(NvPrefsUndoDataTest, PreservesZeroAndAbsentRestoreValues) { + for (const auto value : {std::optional {}, std::optional {0}, std::optional {7}}) { + nvprefs::undo_data_t original; + original.set_opengl_swapchain(1, value); + const auto serialized = original.write(); + nvprefs::undo_data_t restored; + restored.read(std::vector {serialized.begin(), serialized.end()}); + const auto setting = restored.get_opengl_swapchain(); + ASSERT_TRUE(setting.has_value()); + EXPECT_EQ(setting->our_value, 1); + EXPECT_EQ(setting->undo_value, value); + } +} + +#endif diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp index 6bbd82faf..89cf41b8c 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -20,6 +20,21 @@ using namespace std::literals; +/** + * @brief Preparation commands own their command strings and copy privilege settings. + */ +TEST(ConfigPrepCommandTest, PreservesCommandsAndElevationWithBothConstructors) { + const config::prep_cmd_t paired {"launch"s, "undo"s, true}; + EXPECT_EQ(paired.do_cmd, "launch"); + EXPECT_EQ(paired.undo_cmd, "undo"); + EXPECT_TRUE(paired.elevated); + + const config::prep_cmd_t single {"launch-only"s, false}; + EXPECT_EQ(single.do_cmd, "launch-only"); + EXPECT_TRUE(single.undo_cmd.empty()); + EXPECT_FALSE(single.elevated); +} + TEST(ConfigParsingTest, ParsedEntriesOwnKeysAndSupportStringViewLookup) { std::string input = "encoder = software\nencoder = nvenc\n"; const auto entries = config::parse_config(input); @@ -34,6 +49,16 @@ TEST(ConfigParsingTest, ParsedEntriesOwnKeysAndSupportStringViewLookup) { EXPECT_EQ(entries.size(), 1); } +/** + * @brief Duplicate configuration keys retain their first nonempty entry. + */ +TEST(ConfigParsingTest, DuplicateKeysPreserveFirstValueAfterIgnoredEmptyEntry) { + const auto entries = config::parse_config("encoder = software\nencoder = nvenc\noutput_name =\noutput_name = later\noutput_name = ignored\n"); + EXPECT_EQ(entries.at("encoder"), "software"); + EXPECT_EQ(entries.at("output_name"), "later"); + EXPECT_EQ(entries.size(), 2); +} + TEST(ConfigDefaultsTest, UsesAutomaticGamepadSelection) { EXPECT_EQ(config::input.gamepad, "auto"); } diff --git a/tests/unit/test_display_device.cpp b/tests/unit/test_display_device.cpp index 5bf999343..7044e64b9 100644 --- a/tests/unit/test_display_device.cpp +++ b/tests/unit/test_display_device.cpp @@ -7,6 +7,7 @@ #include "../tests_common.h" // standard includes +#include #include #include #include @@ -109,20 +110,23 @@ TEST_P(ParseConfigOption, IntegrationTest) { } using ParseHdrOption = DisplayDeviceConfigTest, std::optional>>; +/** + * @brief HDR parsing cases, including the platform-specific automatic policy. + */ +const auto hdr_option_cases = std::to_array({std::make_pair(std::make_pair(hdr_option_e::disabled, client_wants_hdr_t {true}), std::nullopt), std::make_pair(std::make_pair(hdr_option_e::disabled, client_wants_hdr_t {false}), std::nullopt), +#ifdef __APPLE__ + std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {true}), std::nullopt), + std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {false}), std::nullopt) +#else + std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {true}), hdr_state_e::Enabled), + std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {false}), hdr_state_e::Disabled) +#endif +}); + INSTANTIATE_TEST_SUITE_P( DisplayDeviceConfigTest, ParseHdrOption, - testing::Values( - std::make_pair(std::make_pair(hdr_option_e::disabled, client_wants_hdr_t {true}), std::nullopt), - std::make_pair(std::make_pair(hdr_option_e::disabled, client_wants_hdr_t {false}), std::nullopt), -#ifdef __APPLE__ - std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {true}), std::nullopt), - std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {false}), std::nullopt) -#else - std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {true}), hdr_state_e::Enabled), - std::make_pair(std::make_pair(hdr_option_e::automatic, client_wants_hdr_t {false}), hdr_state_e::Disabled) -#endif - ) + testing::ValuesIn(hdr_option_cases) ); TEST_P(ParseHdrOption, IntegrationTest) { diff --git a/tests/unit/test_http_pairing.cpp b/tests/unit/test_http_pairing.cpp index 024592131..142e3d59f 100644 --- a/tests/unit/test_http_pairing.cpp +++ b/tests/unit/test_http_pairing.cpp @@ -521,6 +521,21 @@ TEST_F(PairingHttpHandlerTest, ImmediateRequestsReturnExpectedStatus) { EXPECT_NE(request("/pair?uniqueid=out-of-order&clientchallenge=00"sv).find("Out of order"), std::string::npos); } +/** + * @brief HTTP dispatch reaches every pairing phase and rejects an unknown phase. + */ +TEST_F(PairingHttpHandlerTest, DispatchesEachPhaseAndRejectsUnknownRequests) { + for (const auto phase : {"clientchallenge", "serverchallengeresp", "clientpairingsecret", "unknown"}) { + std::string pairing_id; + ASSERT_EQ(insert_pair_session(pending_session(phase, "Client", "192.0.2.10"), pairing_id), pair_session_insert_e::ADDED); + const auto response = request(std::format("/pair?uniqueid={}&{}=00", phase, phase)); + EXPECT_NE(response.find("status_code=\"400\""), std::string::npos); + const auto expected = std::string_view {phase} == "unknown" ? "Invalid pairing request" : "Out of order"; + EXPECT_NE(response.find(expected), std::string::npos) << phase; + EXPECT_TRUE(get_pending_pairings().empty()); + } +} + TEST_F(PairingHttpHandlerTest, WebApprovalRequestRemainsPendingUntilCancelled) { std::packaged_task request_task {[this]() { return request(server_certificate_target("pending")); diff --git a/tests/unit/test_nvenc_dynamic_factory.cpp b/tests/unit/test_nvenc_dynamic_factory.cpp index 4b3637dca..e67be1992 100644 --- a/tests/unit/test_nvenc_dynamic_factory.cpp +++ b/tests/unit/test_nvenc_dynamic_factory.cpp @@ -49,6 +49,7 @@ namespace { } void destroy_encoder() override { + // The fake encoder allocates no driver resources to release. } nvenc::nvenc_encoded_frame encode_frame(std::uint64_t frame_index, bool force_idr) override { @@ -74,6 +75,7 @@ namespace { return { reinterpret_cast(fake_handle_value), [](HMODULE) { + // The synthetic handle is not an owned module, so it must not be unloaded. }, }; } diff --git a/tests/unit/test_nvenc_utils.cpp b/tests/unit/test_nvenc_utils.cpp index 8e72a0d01..f59b8428a 100644 --- a/tests/unit/test_nvenc_utils.cpp +++ b/tests/unit/test_nvenc_utils.cpp @@ -8,6 +8,8 @@ #include #include #include + #include + #include #include #include @@ -30,6 +32,8 @@ namespace { 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. + GUID selected_preset {}; ///< Preset GUID forwarded to the driver. + int preset_queries = 0; ///< Preset configuration calls observed by the driver. }; driver_state_t driver; ///< Fake driver state and opaque session identity. @@ -78,13 +82,35 @@ namespace { /** * @brief Install fake driver callbacks for one native device type. * @param cuda Whether the test uses a CUDA context instead of a D3D11 device. + * @param observe_preset Whether the driver should continue through preset selection. + * @note Unused session parameter types are inferred from the SDK callback signatures. */ - explicit fake_session_encoder_t(bool cuda): + explicit fake_session_encoder_t(bool cuda, bool observe_preset = false): 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; + if (observe_preset) { + nvenc->nvEncGetEncodeGUIDCount = [](auto *, std::uint32_t *count) { + *count = 1; + return NV_ENC_SUCCESS; + }; + nvenc->nvEncGetEncodeGUIDs = [](auto *, GUID *guids, std::uint32_t, std::uint32_t *count) { + *guids = NV_ENC_CODEC_H264_GUID; + *count = 1; + return NV_ENC_SUCCESS; + }; + nvenc->nvEncGetEncodeCaps = [](auto *, GUID, NV_ENC_CAPS_PARAM *params, int *value) { + *value = params->capsToQuery == NV_ENC_CAPS_WIDTH_MAX || params->capsToQuery == NV_ENC_CAPS_HEIGHT_MAX ? 4096 : 0; + return NV_ENC_SUCCESS; + }; + nvenc->nvEncGetEncodePresetConfigEx = [](auto *, GUID, GUID preset, NV_ENC_TUNING_INFO, NV_ENC_PRESET_CONFIG *) { + driver.selected_preset = preset; + ++driver.preset_queries; + return NV_ENC_ERR_GENERIC; + }; + } constexpr std::uintptr_t device_address = 0x1234; if (cuda) { device = std::bit_cast(device_address); @@ -137,6 +163,40 @@ namespace { }; } // namespace +/** + * @brief Preset selection forwards every supported GUID and both boundary fallbacks to the driver. + */ +TEST(NvencPresetTest, PreservesGuidMappingsAndBoundaryFallbacks) { + using namespace nvenc_1301; + const std::array cases { + std::pair {0, NV_ENC_PRESET_P1_GUID}, + std::pair {1, NV_ENC_PRESET_P1_GUID}, + std::pair {2, NV_ENC_PRESET_P2_GUID}, + std::pair {3, NV_ENC_PRESET_P3_GUID}, + std::pair {4, NV_ENC_PRESET_P4_GUID}, + std::pair {5, NV_ENC_PRESET_P5_GUID}, + std::pair {6, NV_ENC_PRESET_P6_GUID}, + std::pair {7, NV_ENC_PRESET_P7_GUID}, + std::pair {8, NV_ENC_PRESET_P7_GUID}, + std::pair {-1, NV_ENC_PRESET_P7_GUID}, + std::pair {std::numeric_limits::max(), NV_ENC_PRESET_P7_GUID}, + }; + for (const auto &[number, expected] : cases) { + driver = {}; + fake_session_encoder_t encoder {false, true}; + nvenc::nvenc_config config {}; + config.quality_preset = number; + 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(config, client_config, colorspace, platf::pix_fmt_e::nv12)); + EXPECT_EQ(driver.preset_queries, 1); + EXPECT_EQ(std::memcmp(&driver.selected_preset, &expected, sizeof(GUID)), 0) << number; + EXPECT_EQ(driver.destructions, 1); + } +} + TEST(NvencCompletionEventTest, TypedEventCanBeSignaledAndIsClosedWithTheEncoder) { nvenc_1301::completion_event_t *event = nullptr; { diff --git a/tests/unit/test_nvhttp_client_auth.cpp b/tests/unit/test_nvhttp_client_auth.cpp index 96bfcae7e..6cf416dd8 100644 --- a/tests/unit/test_nvhttp_client_auth.cpp +++ b/tests/unit/test_nvhttp_client_auth.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include // local includes @@ -18,6 +19,8 @@ namespace fs = std::filesystem; +static_assert(std::is_same_v); + /** * @brief Isolate paired-client authorization tests from the user's Sunshine state. */ diff --git a/tests/unit/test_thread_safe.cpp b/tests/unit/test_thread_safe.cpp index 322227439..2ec90318c 100644 --- a/tests/unit/test_thread_safe.cpp +++ b/tests/unit/test_thread_safe.cpp @@ -53,6 +53,25 @@ TEST(ThreadSafeMail, CleanupPreservesLivePostsAndRemovesExpiredPosts) { EXPECT_EQ(mailbox.id_to_post.size(), 1); } +/** + * @brief Repeated lookups reuse each live mailbox channel and preserve queued values. + */ +TEST(ThreadSafeMail, ReusesExistingEventAndQueueForDuplicateIdentifiers) { + const auto mailbox = std::make_shared(); + const auto event = mailbox->event("event"); + event->raise(0); + const auto same_event = mailbox->event("event"); + EXPECT_EQ(same_event, event); + EXPECT_EQ(same_event->pop(), 0); + + const auto queue = mailbox->queue("queue"); + ASSERT_TRUE(queue->raise(7)); + const auto same_queue = mailbox->queue("queue"); + EXPECT_EQ(same_queue, queue); + EXPECT_EQ(same_queue->pop(), 7); + EXPECT_EQ(mailbox->id_to_post.size(), 2); +} + TEST(ThreadSafeQueue, RejectsNewestItemAtCapacity) { safe::queue_t queue {1, safe::queue_t::overflow_policy_e::reject}; diff --git a/tests/unit/test_utility.cpp b/tests/unit/test_utility.cpp index 52b94f586..c5069795a 100644 --- a/tests/unit/test_utility.cpp +++ b/tests/unit/test_utility.cpp @@ -11,16 +11,44 @@ #include #include #include +#include #include #include #include #include +#include #include #include // local includes #include +/** + * @brief Whether a type has a supported empty-state sentinel. + */ +template +concept has_false_value = requires { util::__false_v::value; }; + +/** + * @brief Sentinel constraints select empty states without accepting unrelated values. + */ +TEST(UtilityFalseValueTests, SelectsSentinelsForOptionalPointerAndBooleanTypes) { + static_assert(std::is_same_v>), const std::nullopt_t>); + static_assert(std::is_same_v), const std::nullptr_t>); + static_assert(std::is_same_v>), const std::nullptr_t>); + static_assert(std::is_same_v>), const std::nullptr_t>); + static_assert(std::is_same_v>), const std::nullptr_t>); + static_assert(std::is_same_v), const bool>); + static_assert(!has_false_value); + + EXPECT_FALSE(std::optional {util::false_v>}); + EXPECT_EQ(util::false_v, nullptr); + EXPECT_EQ(util::false_v>, nullptr); + EXPECT_EQ(util::false_v>, nullptr); + EXPECT_EQ(util::false_v>, nullptr); + EXPECT_FALSE(util::false_v); +} + /** * @brief A const resource deleter invokes its release function exactly once per call. */ diff --git a/tests/unit/test_video.cpp b/tests/unit/test_video.cpp index 73297ca97..d03dfc40e 100644 --- a/tests/unit/test_video.cpp +++ b/tests/unit/test_video.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -26,6 +27,23 @@ extern "C" { using namespace std::literals; +/** + * @brief Packet replacement rules retain the original non-owning byte views. + */ +TEST(VideoPacketReplacementTest, CopiesViewsWithoutCopyingTheirBackingBytes) { + std::string original = "__old__"; + std::string replacement = "__new__"; + const video::packet_raw_t::replace_t rule {std::string_view(original).substr(2, 3), std::string_view(replacement).substr(2, 3)}; + EXPECT_EQ(rule.old, "old"); + EXPECT_EQ(rule._new, "new"); + EXPECT_EQ(rule.old.data(), original.data() + 2); + EXPECT_EQ(rule._new.data(), replacement.data() + 2); + original[2] = 'O'; + replacement[2] = 'N'; + EXPECT_EQ(rule.old, "Old"); + EXPECT_EQ(rule._new, "New"); +} + TEST(VideoFormatMappingTest, MapsSupportedHardwareDevicesAndRejectsUnsupportedOnes) { using enum platf::mem_type_e; const std::array cases { @@ -83,25 +101,30 @@ struct EncoderTest: PlatformTestSuite, testing::WithParamInterface({ +#if !defined(__APPLE__) + &video::nvenc, +#endif +#ifdef _WIN32 + &video::amdvce, + &video::quicksync, +#endif +#if defined(__linux__) || defined(__FreeBSD__) + &video::vaapi, +#endif +#ifdef __APPLE__ + &video::videotoolbox, +#endif + &video::software +}); + INSTANTIATE_TEST_SUITE_P( EncoderVariants, EncoderTest, - testing::Values( -#if !defined(__APPLE__) - &video::nvenc, -#endif -#ifdef _WIN32 - &video::amdvce, - &video::quicksync, -#endif -#if defined(__linux__) || defined(__FreeBSD__) - &video::vaapi, -#endif -#ifdef __APPLE__ - &video::videotoolbox, -#endif - &video::software - ), + testing::ValuesIn(encoder_variants), [](const auto &info) { return std::string(info.param->name); } diff --git a/tests/unit/test_video_colorspace.cpp b/tests/unit/test_video_colorspace.cpp index 1b34eee96..45e1f6aad 100644 --- a/tests/unit/test_video_colorspace.cpp +++ b/tests/unit/test_video_colorspace.cpp @@ -114,3 +114,18 @@ TEST(VideoColorspaceTest, ConvertsBlackWhiteAndPrimaryRedInEveryOutputRange) { } } } + +/** + * @brief Unknown colorspaces reuse the Rec. 709 matrix for every range and depth. + */ +TEST(VideoColorspaceTest, UnknownColorspaceUsesTheRec709Fallback) { + for (unsigned bit_depth : {8U, 10U}) { + for (bool full_range : {false, true}) { + for (bool unorm_output : {false, true}) { + const video::sunshine_colorspace_t fallback {video::colorspace_e::rec709, full_range, bit_depth}; + const video::sunshine_colorspace_t unknown {static_cast(-1), full_range, bit_depth}; + EXPECT_EQ(video::color_vectors_from_colorspace(unknown, unorm_output), video::color_vectors_from_colorspace(fallback, unorm_output)); + } + } + } +}