diff --git a/src/audio.cpp b/src/audio.cpp index f60b9adf2..b41595547 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -29,10 +29,61 @@ namespace audio { */ using sample_queue_t = std::shared_ptr>>; - static int start_audio_control(audio_ctx_t &ctx); - static void stop_audio_control(audio_ctx_t &); + /** + * @brief Initialize one lazy audio control attempt. + * @param ctx Shared sink state to initialize. + * @param settings Startup audio routing policy. + * @param factory Backend creation operation. + * @return Zero; a null context control records initialization failure. + */ + static int start_audio_control(audio_ctx_t &ctx, const config::settings_t &settings, const std::function()> &factory); + /** + * @brief Restore the original sink after the final context reference releases. + * @param ctx Shared sink state to release. + */ + static void stop_audio_control(audio_ctx_t &ctx); + /** + * @brief Apply a client-provided surround channel layout. + * @param stream Encoder layout to update. + * @param params Negotiated surround parameters. + */ static void apply_surround_params(opus_stream_config_t &stream, const stream_params_t ¶ms); + /** + * @brief Configuration and lazy control resources belonging to one application. + */ + struct service_t::impl_t { + const config::settings_t &settings; ///< Stable startup configuration. + safe::mail_t host_mail; ///< Host packet mailbox. + std::function()> factory; ///< Backend creation operation for each lazy initialization. + safe::shared_t control_shared; ///< Lazy sink context shared by this owner's consumers. + + /** + * @brief Attach startup settings before audio control can be initialized. + * @param settings Host configuration. + * @param host_mail Host packet mailbox. + * @param factory Backend creation operation retained for initialization retries. + */ + impl_t(const config::settings_t &settings, safe::mail_t host_mail, std::function()> factory): + settings {settings}, + host_mail {std::move(host_mail)}, + factory {std::move(factory)}, + control_shared {[this](audio_ctx_t &context) { + return start_audio_control(context, this->settings, this->factory); + }, + stop_audio_control} {} + }; + + service_t::service_t(const config::settings_t &settings, safe::mail_t host_mail): + service_t {settings, std::move(host_mail), [&settings]() { + return platf::audio_control(settings); + }} {} + + service_t::service_t(const config::settings_t &settings, safe::mail_t host_mail, std::function()> factory): + impl {std::make_shared(settings, std::move(host_mail), std::move(factory))} {} + + service_t::~service_t() = default; + /** * @brief Select the Opus stream configuration for a channel count and quality tier. * @@ -156,9 +207,11 @@ namespace audio { /** * @brief Run the capture loop for this backend. */ - void capture(safe::mail_t host_mail, safe::mail_t mail, config_t config, void *channel_data) { + void service_t::capture(safe::mail_t mail, config_t config, void *channel_data) { + const auto host_mail = impl->host_mail; + const auto &settings = impl->settings; auto shutdown_event = mail->event(mail::shutdown); - if (!config::audio.stream) { + if (!settings.audio.stream) { shutdown_event->view(); return; } @@ -167,7 +220,7 @@ namespace audio { apply_surround_params(stream, config.customStreamParams); } - auto ref = get_audio_ctx_ref(); + auto ref = context(); if (!ref) { return; } @@ -189,9 +242,9 @@ namespace audio { // 1. Virtual sink // 2. Audio sink // 3. Host - std::string *sink = &ref->sink.host; - if (!config::audio.sink.empty()) { - sink = &config::audio.sink; + const std::string *sink = &ref->sink.host; + if (!settings.audio.sink.empty()) { + sink = &settings.audio.sink; } // Prefer the virtual sink if host playback is disabled or there's no other sink @@ -275,9 +328,20 @@ namespace audio { } } - audio_ctx_ref_t get_audio_ctx_ref() { - static auto control_shared {safe::make_shared(start_audio_control, stop_audio_control)}; - return control_shared.ref(); + audio_ctx_ref_t service_t::context() { + auto ref = impl->control_shared.ref(); + if (!ref) { + return nullptr; + } + + /** @brief Keep the shared wrapper alive until its last control reference is released. */ + struct retained_t { + std::shared_ptr owner; ///< Released after the lazy context reference. + safe::shared_t::ptr_t context; ///< Triggers final sink restoration before owner destruction. + }; + + auto retained = std::make_shared(impl, std::move(ref)); + return audio_ctx_ref_t {retained, retained->context.get()}; } bool is_audio_ctx_sink_available(const audio_ctx_t &ctx) { @@ -285,7 +349,7 @@ namespace audio { return false; } - const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host; + const std::string &sink = ctx.sink.host.empty() ? ctx.fallback_sink : ctx.sink.host; if (sink.empty()) { return false; } @@ -309,7 +373,8 @@ namespace audio { return STEREO; } - int start_audio_control(audio_ctx_t &ctx) { + int start_audio_control(audio_ctx_t &ctx, const config::settings_t &settings, const std::function()> &factory) { + ctx.fallback_sink = settings.audio.sink; auto fg = util::fail_guard([]() { BOOST_LOG(warning) << "There will be no audio"sv; }); @@ -319,7 +384,7 @@ namespace audio { // The default sink has not been replaced yet. ctx.restore_sink = false; - if (!(ctx.control = platf::audio_control())) { + if (!(ctx.control = factory())) { return 0; } @@ -343,7 +408,7 @@ namespace audio { } // Change back to the host sink, unless there was none - const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host; + const std::string &sink = ctx.sink.host.empty() ? ctx.fallback_sink : ctx.sink.host; if (!sink.empty()) { // Best effort, it's allowed to fail ctx.control->set_sink(sink); diff --git a/src/audio.h b/src/audio.h index 794b56d40..2a8831934 100644 --- a/src/audio.h +++ b/src/audio.h @@ -87,6 +87,7 @@ namespace audio { std::unique_ptr control; ///< Platform audio-control implementation. bool restore_sink; ///< Whether Sunshine should restore the original sink when capture ends. + std::string fallback_sink; ///< Configured sink captured for this context lifetime. platf::sink_t sink; ///< Original sink captured before Sunshine switched devices. }; @@ -99,31 +100,49 @@ namespace audio { */ using packet_t = std::pair; /** - * @brief Shared mailbox reference to the global audio context. + * @brief Shared reference retaining one audio owner and its lazy context. */ - using audio_ctx_ref_t = safe::shared_t::ptr_t; + using audio_ctx_ref_t = std::shared_ptr; /** - * @brief Capture, encode, and publish audio packets for a stream. - * - * @param host_mail Host mailbox used to publish encoded audio packets. - * @param mail Session mailbox used for capture shutdown. - * @param config Audio capture and encoder settings. - * @param channel_data Platform-specific capture channel pointer. + * @brief Own the audio control context shared by captures and display restoration. */ - void capture(safe::mail_t host_mail, safe::mail_t mail, config_t config, void *channel_data); + class service_t { + public: + /** + * @brief Bind host configuration and packet delivery without opening audio devices. + * @param settings Application startup settings that outlive this owner and retained contexts. + * @param host_mail Host mailbox receiving encoded packets. + */ + service_t(const config::settings_t &settings, safe::mail_t host_mail); + /** + * @brief Bind an explicit audio backend factory for controlled initialization. + * @param settings Host audio configuration that outlives retained context references. + * @param host_mail Host packet mailbox. + * @param factory Factory invoked when the first context reference is acquired. + */ + service_t(const config::settings_t &settings, safe::mail_t host_mail, std::function()> factory); + /** @brief Release audio resources after retained context references finish. */ + ~service_t(); + service_t(const service_t &) = delete; + service_t &operator=(const service_t &) = delete; + /** + * @brief Capture and publish audio for one transport session. + * @param mail Session shutdown mailbox. + * @param config Negotiated audio layout and encoding settings. + * @param channel_data Session pointer carried by encoded packets. + */ + void capture(safe::mail_t mail, config_t config, void *channel_data); + /** + * @brief Retain the shared audio control and original sink until it can be restored. + * @return Retained context; its control is null when backend initialization failed. + */ + audio_ctx_ref_t context(); - /** - * @brief Get the reference to the audio context. - * @returns A shared pointer reference to audio context. - * @note Aside from the configuration purposes, it can be used to extend the - * audio sink lifetime to capture sink earlier and restore it later. - * - * @examples - * audio_ctx_ref_t audio = get_audio_ctx_ref() - * @examples_end - */ - audio_ctx_ref_t get_audio_ctx_ref(); + private: + struct impl_t; ///< Lazy audio control and its explicit dependencies. + std::shared_ptr impl; ///< Retained by active captures and context references. + }; /** * @brief Check if the audio sink held by audio context is available. @@ -132,7 +151,7 @@ namespace audio { * tries to restore original sink). * * @examples - * audio_ctx_ref_t audio = get_audio_ctx_ref() + * audio_ctx_ref_t audio = audios.context() * if (audio.get()) { * return is_audio_ctx_sink_available(*audio.get()); * } diff --git a/src/config.cpp b/src/config.cpp index 3f6e3782d..ce9fcef92 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -713,186 +713,180 @@ namespace config { } } // namespace dd - /** - * @brief Default video configuration values used before file and CLI overrides. - */ - video_t video { - 28, // qp + settings_t::settings_t(): + video { + 28, // qp - 0, // hevc_mode - 0, // av1_mode + 0, // hevc_mode + 0, // av1_mode - 2, // min_threads - { - "superfast"s, // preset - "zerolatency"s, // tune - 11, // superfast - }, // software + 2, // min_threads + { + "superfast"s, // preset + "zerolatency"s, // tune + 11, // superfast + }, // software - {}, // nv - true, // nv_realtime_hags - true, // nv_opengl_vulkan_on_dxgi - true, // nv_sunshine_high_power_mode - {}, // nv_legacy + {}, // nv + true, // nv_realtime_hags + true, // nv_opengl_vulkan_on_dxgi + true, // nv_sunshine_high_power_mode + {}, // nv_legacy - { - qsv::medium, // preset - qsv::_auto, // cavlc - false, // slow_hevc - }, // qsv + { + qsv::medium, // preset + qsv::_auto, // cavlc + false, // slow_hevc + }, // qsv - { - (int) amd::usage_h264_e::ultralowlatency, // usage (h264) - (int) amd::usage_hevc_e::ultralowlatency, // usage (hevc) - (int) amd::usage_av1_e::ultralowlatency, // usage (av1) - (int) amd::rc_h264_e::vbr_latency, // rate control (h264) - (int) amd::rc_hevc_e::vbr_latency, // rate control (hevc) - (int) amd::rc_av1_e::vbr_latency, // rate control (av1) - 0, // enforce_hrd - (int) amd::quality_h264_e::balanced, // quality (h264) - (int) amd::quality_hevc_e::balanced, // quality (hevc) - (int) amd::quality_av1_e::balanced, // quality (av1) - 0, // preanalysis - 1, // vbaq - {}, // max_au_size (disabled by default) - (int) amd::coder_e::_auto, // coder - }, // amd + { + (int) amd::usage_h264_e::ultralowlatency, // usage (h264) + (int) amd::usage_hevc_e::ultralowlatency, // usage (hevc) + (int) amd::usage_av1_e::ultralowlatency, // usage (av1) + (int) amd::rc_h264_e::vbr_latency, // rate control (h264) + (int) amd::rc_hevc_e::vbr_latency, // rate control (hevc) + (int) amd::rc_av1_e::vbr_latency, // rate control (av1) + 0, // enforce_hrd + (int) amd::quality_h264_e::balanced, // quality (h264) + (int) amd::quality_hevc_e::balanced, // quality (hevc) + (int) amd::quality_av1_e::balanced, // quality (av1) + 0, // preanalysis + 1, // vbaq + {}, // max_au_size (disabled by default) + (int) amd::coder_e::_auto, // coder + }, // amd - { - 0, - 0, - 1, - -1, - }, // vt + { + 0, + 0, + 1, + -1, + }, // vt - { - 0, // blbrc - std::to_underlying(vaapi::quality_e::_auto), // quality - std::to_underlying(vaapi::rc_e::_auto), // rate control - {}, // rate control string - false, // strict_rc_buffer - }, // vaapi + { + 0, // blbrc + std::to_underlying(vaapi::quality_e::_auto), // quality + std::to_underlying(vaapi::rc_e::_auto), // rate control + {}, // rate control string + false, // strict_rc_buffer + }, // vaapi - { - 2, // vk.tune (default: ll - low latency) - 2, // vk.rc_mode (default: cbr) - 2, // vk.quality (default: 2 = balanced, 1 = speed, 3 = quality) - }, + { + 2, // vk.tune (default: ll - low latency) + 2, // vk.rc_mode (default: cbr) + 2, // vk.quality (default: 2 = balanced, 1 = speed, 3 = quality) + }, - {}, // capture - false, // fp16_sdr_gamma_encoded - {}, // encoder - {}, // adapter_name - {}, // output_name + {}, // capture + false, // fp16_sdr_gamma_encoded + {}, // encoder + {}, // adapter_name + {}, // output_name - { - video_t::dd_t::config_option_e::disabled, // configuration_option - video_t::dd_t::resolution_option_e::automatic, // resolution_option - {}, // manual_resolution - video_t::dd_t::refresh_rate_option_e::automatic, // refresh_rate_option - {}, // manual_refresh_rate - video_t::dd_t::hdr_option_e::automatic, // hdr_option - 3s, // config_revert_delay - {}, // config_revert_on_disconnect - {}, // mode_remapping - {} // wa - }, // display_device + { + video_t::dd_t::config_option_e::disabled, // configuration_option + video_t::dd_t::resolution_option_e::automatic, // resolution_option + {}, // manual_resolution + video_t::dd_t::refresh_rate_option_e::automatic, // refresh_rate_option + {}, // manual_refresh_rate + video_t::dd_t::hdr_option_e::automatic, // hdr_option + 3s, // config_revert_delay + {}, // config_revert_on_disconnect + {}, // mode_remapping + {} // wa + }, // display_device - 0, // max_bitrate - 0 // minimum_fps_target (0 = framerate) - }; + 0, // max_bitrate + 0 // minimum_fps_target (0 = framerate) + }, + audio { + {}, // audio_sink + {}, // virtual_sink + true, // stream audio + true, // install_steam_drivers + false, // external_audio + }, + stream { + 10s, // ping_timeout - /** - * @brief Default audio configuration values used before file and CLI overrides. - */ - audio_t audio { - {}, // audio_sink - {}, // virtual_sink - true, // stream audio - true, // install_steam_drivers - false, // external_audio - }; + APPS_JSON_PATH, - /** - * @brief Default stream configuration values used before file and CLI overrides. - */ - stream_t stream { - 10s, // ping_timeout + 20, // fecPercentage - APPS_JSON_PATH, + ENCRYPTION_MODE_NEVER, // lan_encryption_mode + ENCRYPTION_MODE_OPPORTUNISTIC, // wan_encryption_mode + 0, // packetsize + }, + nvhttp { + "lan", // origin web manager - 20, // fecPercentage + PRIVATE_KEY_FILE, + CERTIFICATE_FILE, - ENCRYPTION_MODE_NEVER, // lan_encryption_mode - ENCRYPTION_MODE_OPPORTUNISTIC, // wan_encryption_mode - 0, // packetsize - }; + platf::get_host_name(), // sunshine_name, + "sunshine_state.json"s, // file_state + {}, // external_ip + }, + input { + { + {0x10, 0xA0}, + {0x11, 0xA2}, + {0x12, 0xA4}, + }, + -1ms, // back_button_timeout + 500ms, // key_repeat_delay + std::chrono::duration {1 / 24.9}, // key_repeat_period - /** - * @brief Default NVHTTP server configuration values used before file and CLI overrides. - */ - nvhttp_t nvhttp { - "lan", // origin web manager + "auto", // Default gamepad profile. + {}, // Windows requests a backend choice; macOS defaults to Virtual HID Broker. + true, // back as touchpad click enabled for PlayStation-style gamepads + true, // client gamepads with motion events use PlayStation-style emulation + true, // client gamepads with touchpads use PlayStation-style emulation + true, // virtualhid_randomize_mac - PRIVATE_KEY_FILE, - CERTIFICATE_FILE, + true, // keyboard enabled + false, // key_rightalt_to_key_win + true, // mouse enabled + true, // controller enabled + true, // always send scancodes + true, // high resolution scrolling + true, // native pen/touch support + }, + sunshine { + "en", // locale + 2, // min_log_level + 0, // flags + {}, // User file + platf::appdata().string() + "/sunshine.conf", // config file + {}, // cmd args + 47989, // Base port number + "ipv4", // Address family + {}, // Bind address + platf::appdata().string() + "/sunshine.log", // log file + false, // notify_pre_releases + true, // system_tray + {}, // prep commands + {}, // csrf_allowed_origins + } { + } - platf::get_host_name(), // sunshine_name, - "sunshine_state.json"s, // file_state - {}, // external_ip - }; + const settings_t &store_t::values() const { + return settings_; + } - /** - * @brief Default input configuration values used before file and CLI overrides. - */ - input_t input { - { - {0x10, 0xA0}, - {0x11, 0xA2}, - {0x12, 0xA4}, - }, - -1ms, // back_button_timeout - 500ms, // key_repeat_delay - std::chrono::duration {1 / 24.9}, // key_repeat_period + settings_t &store_t::edit_startup() { + return settings_; + } - "auto", // Default gamepad profile. - {}, // Windows requests a backend choice; macOS defaults to Virtual HID Broker. - true, // back as touchpad click enabled for PlayStation-style gamepads - true, // client gamepads with motion events use PlayStation-style emulation - true, // client gamepads with touchpads use PlayStation-style emulation - true, // virtualhid_randomize_mac + credentials_t store_t::credentials_snapshot() const { + std::lock_guard lock {credentials_mutex_}; + return credentials_; + } - true, // keyboard enabled - false, // key_rightalt_to_key_win - true, // mouse enabled - true, // controller enabled - true, // always send scancodes - true, // high resolution scrolling - true, // native pen/touch support - }; - - /** - * @brief Default top-level Sunshine configuration values used before file and CLI overrides. - */ - sunshine_t sunshine { - "en", // locale - 2, // min_log_level - 0, // flags - {}, // User file - {}, // Username - {}, // Password - {}, // Password Salt - platf::appdata().string() + "/sunshine.conf", // config file - {}, // cmd args - 47989, // Base port number - "ipv4", // Address family - {}, // Bind address - platf::appdata().string() + "/sunshine.log", // log file - false, // notify_pre_releases - true, // system_tray - {}, // prep commands - {}, // csrf_allowed_origins - }; + void store_t::update_credentials(credentials_t credentials) { + std::lock_guard lock {credentials_mutex_}; + credentials_ = std::move(credentials); + } /** * @brief Return whether a character terminates a configuration line. @@ -1046,8 +1040,8 @@ namespace config { return vars; } - bool persist_config_option_if_missing(const std::string_view name, const std::string_view value) { - auto file_content = file_handler::read_file(sunshine.config_file.c_str()); + bool store_t::persist_config_option_if_missing(const std::string_view name, const std::string_view value) { + auto file_content = file_handler::read_file(settings_.sunshine.config_file.c_str()); if (parse_config(file_content).contains(std::string {name})) { return false; } @@ -1056,7 +1050,7 @@ namespace config { file_content += '\n'; } file_content += std::format("{} = {}\n", name, value); - if (file_handler::write_file(sunshine.config_file.c_str(), file_content) != 0) { + if (file_handler::write_file(settings_.sunshine.config_file.c_str(), file_content) != 0) { BOOST_LOG(warning) << "Failed to persist automatically selected config option '"sv << name << "'"sv; return false; } @@ -1065,12 +1059,12 @@ namespace config { return true; } - bool select_all_gamepad_drivers_if_licensed(const bool virtualhid_licensed) { - if (!virtualhid_licensed || !input.gamepad_driver.empty() || !persist_config_option_if_missing("gamepad_driver", GAMEPAD_DRIVER_ALL)) { + bool store_t::select_all_gamepad_drivers_if_licensed(const bool virtualhid_licensed) { + if (!virtualhid_licensed || !settings_.input.gamepad_driver.empty() || !persist_config_option_if_missing("gamepad_driver", GAMEPAD_DRIVER_ALL)) { return false; } - input.gamepad_driver = GAMEPAD_DRIVER_ALL; + settings_.input.gamepad_driver = GAMEPAD_DRIVER_ALL; return true; } @@ -1536,26 +1530,25 @@ namespace config { } /** - * @brief Apply single-character command-line flags to the global Sunshine flags bitset. + * @brief Apply single-character command-line flags to this store's Sunshine flags bitset. * - * @param line Configuration line being parsed. * @return 0 when all flags are recognized; -1 when at least one flag is unknown. */ - int apply_flags(const char *line) { + int store_t::apply_flags(const char *line) { int ret = 0; while (*line != '\0') { switch (*line) { case '0': - config::sunshine.flags[config::flag::PIN_STDIN].flip(); + settings_.sunshine.flags[config::flag::PIN_STDIN].flip(); break; case '1': - config::sunshine.flags[config::flag::FRESH_STATE].flip(); + settings_.sunshine.flags[config::flag::FRESH_STATE].flip(); break; case '2': - config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE].flip(); + settings_.sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE].flip(); break; case 'p': - config::sunshine.flags[config::flag::UPNP].flip(); + settings_.sunshine.flags[config::flag::UPNP].flip(); break; default: BOOST_LOG(warning) << "config: Unrecognized flag: ["sv << *line << ']' << std::endl; @@ -1589,115 +1582,114 @@ namespace config { /** * @brief Log parsed configuration entries and optionally record them as modified. */ - void log_config_settings(const std::unordered_map &vars, bool save) { + void store_t::log_config_settings(const std::unordered_map &vars, bool save) { for (auto &[name, val] : vars) { bool is_redacted = std::ranges::find(config::redacted_config, name) != config::redacted_config.end(); BOOST_LOG(info) << "config: '"sv << name << "' = "sv << (is_redacted ? "[redacted]" : val); if (save) { - modified_config_settings[name] = val; + settings_.modified_config_settings[name] = val; } } } /** - * @brief Apply parsed configuration entries to the global runtime configuration. + * @brief Apply parsed configuration entries to this store's startup configuration. * - * @param vars Parsed configuration entries; consumed keys are erased. */ - void apply_config(std::unordered_map &&vars) { + void store_t::apply_config(std::unordered_map &&vars) { log_config_settings(vars, true); - int_f(vars, "qp", video.qp); - int_between_f(vars, "hevc_mode", video.hevc_mode, {0, 3}); - int_between_f(vars, "av1_mode", video.av1_mode, {0, 3}); - int_f(vars, "min_threads", video.min_threads); - string_f(vars, "sw_preset", video.sw.sw_preset); - if (!video.sw.sw_preset.empty()) { - video.sw.svtav1_preset = sw::svtav1_preset_from_view(video.sw.sw_preset); + int_f(vars, "qp", settings_.video.qp); + int_between_f(vars, "hevc_mode", settings_.video.hevc_mode, {0, 3}); + int_between_f(vars, "av1_mode", settings_.video.av1_mode, {0, 3}); + int_f(vars, "min_threads", settings_.video.min_threads); + string_f(vars, "sw_preset", settings_.video.sw.sw_preset); + if (!settings_.video.sw.sw_preset.empty()) { + settings_.video.sw.svtav1_preset = sw::svtav1_preset_from_view(settings_.video.sw.sw_preset); } - string_f(vars, "sw_tune", video.sw.sw_tune); + string_f(vars, "sw_tune", settings_.video.sw.sw_tune); - int_between_f(vars, "nvenc_preset", video.nv.quality_preset, {1, 7}); - int_between_f(vars, "nvenc_vbv_increase", video.nv.vbv_percentage_increase, {0, 400}); - bool_f(vars, "nvenc_spatial_aq", video.nv.adaptive_quantization); - generic_f(vars, "nvenc_twopass", video.nv.two_pass, nv::twopass_from_view); - bool_f(vars, "nvenc_h264_cavlc", video.nv.h264_cavlc); - generic_f(vars, "nvenc_split_encode", video.nv.split_frame_encoding, nv::split_encode_from_view); - bool_f(vars, "nvenc_realtime_hags", video.nv_realtime_hags); - bool_f(vars, "nvenc_opengl_vulkan_on_dxgi", video.nv_opengl_vulkan_on_dxgi); - bool_f(vars, "nvenc_latency_over_power", video.nv_sunshine_high_power_mode); + int_between_f(vars, "nvenc_preset", settings_.video.nv.quality_preset, {1, 7}); + int_between_f(vars, "nvenc_vbv_increase", settings_.video.nv.vbv_percentage_increase, {0, 400}); + bool_f(vars, "nvenc_spatial_aq", settings_.video.nv.adaptive_quantization); + generic_f(vars, "nvenc_twopass", settings_.video.nv.two_pass, nv::twopass_from_view); + bool_f(vars, "nvenc_h264_cavlc", settings_.video.nv.h264_cavlc); + generic_f(vars, "nvenc_split_encode", settings_.video.nv.split_frame_encoding, nv::split_encode_from_view); + bool_f(vars, "nvenc_realtime_hags", settings_.video.nv_realtime_hags); + bool_f(vars, "nvenc_opengl_vulkan_on_dxgi", settings_.video.nv_opengl_vulkan_on_dxgi); + bool_f(vars, "nvenc_latency_over_power", settings_.video.nv_sunshine_high_power_mode); #if !defined(__ANDROID__) && !defined(__APPLE__) - video.nv_legacy.preset = nv::ffmpeg_preset_from_quality(video.nv.quality_preset); - video.nv_legacy.multipass = video.nv.two_pass == nvenc::nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION : - video.nv.two_pass == nvenc::nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION : - NV_ENC_MULTI_PASS_DISABLED; - video.nv_legacy.h264_coder = video.nv.h264_cavlc ? NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC : NV_ENC_H264_ENTROPY_CODING_MODE_CABAC; - video.nv_legacy.spatial_aq = video.nv.adaptive_quantization; - video.nv_legacy.vbv_percentage_increase = video.nv.vbv_percentage_increase; + settings_.video.nv_legacy.preset = nv::ffmpeg_preset_from_quality(settings_.video.nv.quality_preset); + settings_.video.nv_legacy.multipass = settings_.video.nv.two_pass == nvenc::nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION : + settings_.video.nv.two_pass == nvenc::nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION : + NV_ENC_MULTI_PASS_DISABLED; + settings_.video.nv_legacy.h264_coder = settings_.video.nv.h264_cavlc ? NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC : NV_ENC_H264_ENTROPY_CODING_MODE_CABAC; + settings_.video.nv_legacy.spatial_aq = settings_.video.nv.adaptive_quantization; + settings_.video.nv_legacy.vbv_percentage_increase = settings_.video.nv.vbv_percentage_increase; #endif - int_f(vars, "qsv_preset", video.qsv.qsv_preset, qsv::preset_from_view); - int_f(vars, "qsv_coder", video.qsv.qsv_cavlc, qsv::coder_from_view); - bool_f(vars, "qsv_slow_hevc", video.qsv.qsv_slow_hevc); + int_f(vars, "qsv_preset", settings_.video.qsv.qsv_preset, qsv::preset_from_view); + int_f(vars, "qsv_coder", settings_.video.qsv.qsv_cavlc, qsv::coder_from_view); + bool_f(vars, "qsv_slow_hevc", settings_.video.qsv.qsv_slow_hevc); std::string quality; string_f(vars, "amd_quality", quality); if (!quality.empty()) { - video.amd.amd_quality_h264 = amd::quality_from_view(quality, video.amd.amd_quality_h264); - video.amd.amd_quality_hevc = amd::quality_from_view(quality, video.amd.amd_quality_hevc); - video.amd.amd_quality_av1 = amd::quality_from_view(quality, video.amd.amd_quality_av1); + settings_.video.amd.amd_quality_h264 = amd::quality_from_view(quality, settings_.video.amd.amd_quality_h264); + settings_.video.amd.amd_quality_hevc = amd::quality_from_view(quality, settings_.video.amd.amd_quality_hevc); + settings_.video.amd.amd_quality_av1 = amd::quality_from_view(quality, settings_.video.amd.amd_quality_av1); } std::string rc; string_f(vars, "amd_rc", rc); - int_f(vars, "amd_coder", video.amd.amd_coder, amd::coder_from_view); + int_f(vars, "amd_coder", settings_.video.amd.amd_coder, amd::coder_from_view); if (!rc.empty()) { - video.amd.amd_rc_h264 = amd::rc_from_view(rc, video.amd.amd_rc_h264); - video.amd.amd_rc_hevc = amd::rc_from_view(rc, video.amd.amd_rc_hevc); - video.amd.amd_rc_av1 = amd::rc_from_view(rc, video.amd.amd_rc_av1); + settings_.video.amd.amd_rc_h264 = amd::rc_from_view(rc, settings_.video.amd.amd_rc_h264); + settings_.video.amd.amd_rc_hevc = amd::rc_from_view(rc, settings_.video.amd.amd_rc_hevc); + settings_.video.amd.amd_rc_av1 = amd::rc_from_view(rc, settings_.video.amd.amd_rc_av1); } std::string usage; string_f(vars, "amd_usage", usage); if (!usage.empty()) { - video.amd.amd_usage_h264 = amd::usage_from_view(usage, video.amd.amd_usage_h264); - video.amd.amd_usage_hevc = amd::usage_from_view(usage, video.amd.amd_usage_hevc); - video.amd.amd_usage_av1 = amd::usage_from_view(usage, video.amd.amd_usage_av1); + settings_.video.amd.amd_usage_h264 = amd::usage_from_view(usage, settings_.video.amd.amd_usage_h264); + settings_.video.amd.amd_usage_hevc = amd::usage_from_view(usage, settings_.video.amd.amd_usage_hevc); + settings_.video.amd.amd_usage_av1 = amd::usage_from_view(usage, settings_.video.amd.amd_usage_av1); } - bool_f(vars, "amd_preanalysis", (bool &) video.amd.amd_preanalysis); - bool_f(vars, "amd_vbaq", (bool &) video.amd.amd_vbaq); - bool_f(vars, "amd_enforce_hrd", (bool &) video.amd.amd_enforce_hrd); + bool_f(vars, "amd_preanalysis", (bool &) settings_.video.amd.amd_preanalysis); + bool_f(vars, "amd_vbaq", (bool &) settings_.video.amd.amd_vbaq); + bool_f(vars, "amd_enforce_hrd", (bool &) settings_.video.amd.amd_enforce_hrd); { - auto max_au_size = video.amd.amd_max_au_size; + auto max_au_size = settings_.video.amd.amd_max_au_size; int_f(vars, "amd_max_au_size", max_au_size); if (!max_au_size || *max_au_size >= -1) { - video.amd.amd_max_au_size = max_au_size; + settings_.video.amd.amd_max_au_size = max_au_size; } } - int_f(vars, "vt_coder", video.vt.vt_coder, vt::coder_from_view); - int_f(vars, "vt_software", video.vt.vt_allow_sw, vt::allow_software_from_view); - int_f(vars, "vt_software", video.vt.vt_require_sw, vt::force_software_from_view); - int_f(vars, "vt_realtime", video.vt.vt_realtime, vt::rt_from_view); + int_f(vars, "vt_coder", settings_.video.vt.vt_coder, vt::coder_from_view); + int_f(vars, "vt_software", settings_.video.vt.vt_allow_sw, vt::allow_software_from_view); + int_f(vars, "vt_software", settings_.video.vt.vt_require_sw, vt::force_software_from_view); + int_f(vars, "vt_realtime", settings_.video.vt.vt_realtime, vt::rt_from_view); std::string vaapi_quality; string_f(vars, "vaapi_quality", vaapi_quality); if (!vaapi_quality.empty()) { - video.vaapi.vaapi_quality = vaapi::quality_from_view(vaapi_quality, video.vaapi.vaapi_quality); + settings_.video.vaapi.vaapi_quality = vaapi::quality_from_view(vaapi_quality, settings_.video.vaapi.vaapi_quality); } - string_f(vars, "vaapi_rc", video.vaapi.vaapi_rc_str); - if (!video.vaapi.vaapi_rc_str.empty()) { - video.vaapi.vaapi_rc = vaapi::rc_from_view(video.vaapi.vaapi_rc_str, video.vaapi.vaapi_rc); + string_f(vars, "vaapi_rc", settings_.video.vaapi.vaapi_rc_str); + if (!settings_.video.vaapi.vaapi_rc_str.empty()) { + settings_.video.vaapi.vaapi_rc = vaapi::rc_from_view(settings_.video.vaapi.vaapi_rc_str, settings_.video.vaapi.vaapi_rc); } - bool_f(vars, "vaapi_blbrc", (bool &) video.vaapi.blbrc); - bool_f(vars, "vaapi_strict_rc_buffer", video.vaapi.strict_rc_buffer); + bool_f(vars, "vaapi_blbrc", (bool &) settings_.video.vaapi.blbrc); + bool_f(vars, "vaapi_strict_rc_buffer", settings_.video.vaapi.strict_rc_buffer); - int_f(vars, "vk_tune", video.vk.tune); - int_f(vars, "vk_rc_mode", video.vk.rc_mode); + int_f(vars, "vk_tune", settings_.video.vk.tune); + int_f(vars, "vk_rc_mode", settings_.video.vk.rc_mode); std::string vk_quality; string_f(vars, "vk_quality", vk_quality); static const std::unordered_map vk_quality_map = { @@ -1706,66 +1698,66 @@ namespace config { {"quality"sv, 3} }; if (auto it = vk_quality_map.find(vk_quality); it != vk_quality_map.end()) { - video.vk.quality = it->second; + settings_.video.vk.quality = it->second; } - string_f(vars, "capture", video.capture); - bool_f(vars, "fp16_sdr_gamma_encoded", video.fp16_sdr_gamma_encoded); - string_f(vars, "encoder", video.encoder); - string_f(vars, "adapter_name", video.adapter_name); - string_f(vars, "output_name", video.output_name); + string_f(vars, "capture", settings_.video.capture); + bool_f(vars, "fp16_sdr_gamma_encoded", settings_.video.fp16_sdr_gamma_encoded); + string_f(vars, "encoder", settings_.video.encoder); + string_f(vars, "adapter_name", settings_.video.adapter_name); + string_f(vars, "output_name", settings_.video.output_name); - generic_f(vars, "dd_configuration_option", video.dd.configuration_option, dd::config_option_from_view); - generic_f(vars, "dd_resolution_option", video.dd.resolution_option, dd::resolution_option_from_view); - string_f(vars, "dd_manual_resolution", video.dd.manual_resolution); - generic_f(vars, "dd_refresh_rate_option", video.dd.refresh_rate_option, dd::refresh_rate_option_from_view); - string_f(vars, "dd_manual_refresh_rate", video.dd.manual_refresh_rate); - generic_f(vars, "dd_hdr_option", video.dd.hdr_option, dd::hdr_option_from_view); + generic_f(vars, "dd_configuration_option", settings_.video.dd.configuration_option, dd::config_option_from_view); + generic_f(vars, "dd_resolution_option", settings_.video.dd.resolution_option, dd::resolution_option_from_view); + string_f(vars, "dd_manual_resolution", settings_.video.dd.manual_resolution); + generic_f(vars, "dd_refresh_rate_option", settings_.video.dd.refresh_rate_option, dd::refresh_rate_option_from_view); + string_f(vars, "dd_manual_refresh_rate", settings_.video.dd.manual_refresh_rate); + generic_f(vars, "dd_hdr_option", settings_.video.dd.hdr_option, dd::hdr_option_from_view); { int value = -1; int_between_f(vars, "dd_config_revert_delay", value, {0, std::numeric_limits::max()}); if (value >= 0) { - video.dd.config_revert_delay = std::chrono::milliseconds {value}; + settings_.video.dd.config_revert_delay = std::chrono::milliseconds {value}; } } - bool_f(vars, "dd_config_revert_on_disconnect", video.dd.config_revert_on_disconnect); - generic_f(vars, "dd_mode_remapping", video.dd.mode_remapping, dd::mode_remapping_from_view); + bool_f(vars, "dd_config_revert_on_disconnect", settings_.video.dd.config_revert_on_disconnect); + generic_f(vars, "dd_mode_remapping", settings_.video.dd.mode_remapping, dd::mode_remapping_from_view); { int value = 0; int_between_f(vars, "dd_wa_hdr_toggle_delay", value, {0, 3000}); - video.dd.wa.hdr_toggle_delay = std::chrono::milliseconds {value}; + settings_.video.dd.wa.hdr_toggle_delay = std::chrono::milliseconds {value}; } - int_f(vars, "max_bitrate", video.max_bitrate); - double_between_f(vars, "minimum_fps_target", video.minimum_fps_target, {0.0, 1000.0}); + int_f(vars, "max_bitrate", settings_.video.max_bitrate); + double_between_f(vars, "minimum_fps_target", settings_.video.minimum_fps_target, {0.0, 1000.0}); - path_f(vars, "pkey", nvhttp.pkey); - path_f(vars, "cert", nvhttp.cert); - string_f(vars, "sunshine_name", nvhttp.sunshine_name); - path_f(vars, "log_path", config::sunshine.log_file); - path_f(vars, "file_state", nvhttp.file_state); + path_f(vars, "pkey", settings_.nvhttp.pkey); + path_f(vars, "cert", settings_.nvhttp.cert); + string_f(vars, "sunshine_name", settings_.nvhttp.sunshine_name); + path_f(vars, "log_path", settings_.sunshine.log_file); + path_f(vars, "file_state", settings_.nvhttp.file_state); // Must be run after "file_state" - config::sunshine.credentials_file = config::nvhttp.file_state; - path_f(vars, "credentials_file", config::sunshine.credentials_file); + settings_.sunshine.credentials_file = settings_.nvhttp.file_state; + path_f(vars, "credentials_file", settings_.sunshine.credentials_file); - string_f(vars, "external_ip", nvhttp.external_ip); - list_prep_cmd_f(vars, "global_prep_cmd", config::sunshine.prep_cmds); + string_f(vars, "external_ip", settings_.nvhttp.external_ip); + list_prep_cmd_f(vars, "global_prep_cmd", settings_.sunshine.prep_cmds); - string_f(vars, "audio_sink", audio.sink); - string_f(vars, "virtual_sink", audio.virtual_sink); - bool_f(vars, "stream_audio", audio.stream); - bool_f(vars, "install_steam_audio_drivers", audio.install_steam_drivers); - bool_f(vars, "external_audio", audio.external_audio); + string_f(vars, "audio_sink", settings_.audio.sink); + string_f(vars, "virtual_sink", settings_.audio.virtual_sink); + bool_f(vars, "stream_audio", settings_.audio.stream); + bool_f(vars, "install_steam_audio_drivers", settings_.audio.install_steam_drivers); + bool_f(vars, "external_audio", settings_.audio.external_audio); - string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv}); + string_restricted_f(vars, "origin_web_ui_allowed", settings_.nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv}); // Parse CSRF allowed origins - always include defaults, then append user-configured origins std::vector user_csrf_origins; string_list_f(vars, "csrf_allowed_origins", user_csrf_origins); // Start with default localhost variants - sunshine.csrf_allowed_origins = { + settings_.sunshine.csrf_allowed_origins = { "https://localhost", "https://127.0.0.1", "https://[::1]" @@ -1775,7 +1767,7 @@ namespace config { bool csrf_invalid_config = false; for (const auto &origin : user_csrf_origins) { if (origin.size() > 8 && origin.starts_with("https://")) { - sunshine.csrf_allowed_origins.push_back(origin); + settings_.sunshine.csrf_allowed_origins.push_back(origin); } else { csrf_invalid_config = true; BOOST_LOG(warning) << "Invalid 'csrf_allowed_origins' entry rejected: "sv << origin; @@ -1788,158 +1780,158 @@ namespace config { int to = -1; int_between_f(vars, "ping_timeout", to, {-1, std::numeric_limits::max()}); if (to != -1) { - stream.ping_timeout = std::chrono::milliseconds(to); + settings_.stream.ping_timeout = std::chrono::milliseconds(to); } - int_between_f(vars, "lan_encryption_mode", stream.lan_encryption_mode, {0, 2}); - int_between_f(vars, "wan_encryption_mode", stream.wan_encryption_mode, {0, 2}); - int_between_f(vars, "packetsize", stream.packetsize, {0, PACKETSIZE_MAX}); + int_between_f(vars, "lan_encryption_mode", settings_.stream.lan_encryption_mode, {0, 2}); + int_between_f(vars, "wan_encryption_mode", settings_.stream.wan_encryption_mode, {0, 2}); + int_between_f(vars, "packetsize", settings_.stream.packetsize, {0, PACKETSIZE_MAX}); - path_f(vars, "file_apps", stream.file_apps); + path_f(vars, "file_apps", settings_.stream.file_apps); #ifndef __ANDROID__ // TODO: Android can possibly support this - if (!fs::exists(stream.file_apps.c_str())) { - fs::copy_file(SUNSHINE_ASSETS_DIR "/apps.json", stream.file_apps); + if (!fs::exists(settings_.stream.file_apps.c_str())) { + fs::copy_file(SUNSHINE_ASSETS_DIR "/apps.json", settings_.stream.file_apps); fs::permissions( - stream.file_apps, + settings_.stream.file_apps, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::add ); } #endif - int_between_f(vars, "fec_percentage", stream.fec_percentage, {0, 100}); + int_between_f(vars, "fec_percentage", settings_.stream.fec_percentage, {0, 100}); - map_int_int_f(vars, "keybindings"s, input.keybindings); + map_int_int_f(vars, "keybindings"s, settings_.input.keybindings); // This config option will only be used by the UI // When editing in the config file itself, use "keybindings" - input.key_rightalt_to_key_win = false; - bool_f(vars, "key_rightalt_to_key_win", input.key_rightalt_to_key_win); + settings_.input.key_rightalt_to_key_win = false; + bool_f(vars, "key_rightalt_to_key_win", settings_.input.key_rightalt_to_key_win); - if (input.key_rightalt_to_key_win) { - input.keybindings.emplace(0xA5, 0x5B); + if (settings_.input.key_rightalt_to_key_win) { + settings_.input.keybindings.emplace(0xA5, 0x5B); } to = std::numeric_limits::min(); int_f(vars, "back_button_timeout", to); if (to > std::numeric_limits::min()) { - input.back_button_timeout = std::chrono::milliseconds {to}; + settings_.input.back_button_timeout = std::chrono::milliseconds {to}; } double repeat_frequency {0}; double_between_f(vars, "key_repeat_frequency", repeat_frequency, {0, std::numeric_limits::max()}); if (repeat_frequency > 0) { - config::input.key_repeat_period = std::chrono::duration {1 / repeat_frequency}; + settings_.input.key_repeat_period = std::chrono::duration {1 / repeat_frequency}; } to = -1; int_f(vars, "key_repeat_delay", to); if (to >= 0) { - input.key_repeat_delay = std::chrono::milliseconds {to}; + settings_.input.key_repeat_delay = std::chrono::milliseconds {to}; } - string_restricted_f(vars, "gamepad_driver", input.gamepad_driver, { - GAMEPAD_DRIVER_ALL, - GAMEPAD_DRIVER_VIRTUALHID, - GAMEPAD_DRIVER_VIGEMBUS, - GAMEPAD_DRIVER_NONE, - }); - string_restricted_f(vars, "gamepad"s, input.gamepad, get_supported_gamepad_options()); + string_restricted_f(vars, "gamepad_driver", settings_.input.gamepad_driver, { + GAMEPAD_DRIVER_ALL, + GAMEPAD_DRIVER_VIRTUALHID, + GAMEPAD_DRIVER_VIGEMBUS, + GAMEPAD_DRIVER_NONE, + }); + string_restricted_f(vars, "gamepad"s, settings_.input.gamepad, get_supported_gamepad_options()); #ifdef _WIN32 - if (input.gamepad_driver == GAMEPAD_DRIVER_VIGEMBUS && input.gamepad != "auto"sv && input.gamepad != "x360"sv && input.gamepad != "ds4"sv) { - BOOST_LOG(warning) << "Gamepad type '"sv << input.gamepad << "' is not supported by ViGEmBus; using automatic selection"sv; - input.gamepad = "auto"; + if (settings_.input.gamepad_driver == GAMEPAD_DRIVER_VIGEMBUS && settings_.input.gamepad != "auto"sv && settings_.input.gamepad != "x360"sv && settings_.input.gamepad != "ds4"sv) { + BOOST_LOG(warning) << "Gamepad type '"sv << settings_.input.gamepad << "' is not supported by ViGEmBus; using automatic selection"sv; + settings_.input.gamepad = "auto"; } #endif - bool_f(vars, "ds4_back_as_touchpad_click", input.ds4_back_as_touchpad_click); - bool_f(vars, "motion_as_ds4", input.motion_as_ds4); - bool_f(vars, "touchpad_as_ds4", input.touchpad_as_ds4); - bool_f(vars, "virtualhid_randomize_mac", input.virtualhid_randomize_mac); + bool_f(vars, "ds4_back_as_touchpad_click", settings_.input.ds4_back_as_touchpad_click); + bool_f(vars, "motion_as_ds4", settings_.input.motion_as_ds4); + bool_f(vars, "touchpad_as_ds4", settings_.input.touchpad_as_ds4); + bool_f(vars, "virtualhid_randomize_mac", settings_.input.virtualhid_randomize_mac); - bool_f(vars, "mouse", input.mouse); - bool_f(vars, "keyboard", input.keyboard); - bool_f(vars, "controller", input.controller); + bool_f(vars, "mouse", settings_.input.mouse); + bool_f(vars, "keyboard", settings_.input.keyboard); + bool_f(vars, "controller", settings_.input.controller); - bool_f(vars, "always_send_scancodes", input.always_send_scancodes); + bool_f(vars, "always_send_scancodes", settings_.input.always_send_scancodes); - bool_f(vars, "high_resolution_scrolling", input.high_resolution_scrolling); - bool_f(vars, "native_pen_touch", input.native_pen_touch); + bool_f(vars, "high_resolution_scrolling", settings_.input.high_resolution_scrolling); + bool_f(vars, "native_pen_touch", settings_.input.native_pen_touch); - bool_f(vars, "notify_pre_releases", sunshine.notify_pre_releases); - bool_f(vars, "system_tray", sunshine.system_tray); + bool_f(vars, "notify_pre_releases", settings_.sunshine.notify_pre_releases); + bool_f(vars, "system_tray", settings_.sunshine.system_tray); - int port = sunshine.port; + int port = settings_.sunshine.port; int_between_f(vars, "port"s, port, {1024 + nvhttp::PORT_HTTPS, 65535 - rtsp_stream::RTSP_SETUP_PORT}); - sunshine.port = (std::uint16_t) port; + settings_.sunshine.port = (std::uint16_t) port; // Now that we have the port, add web UI port-specific origins to CSRF allowed list // Web UI runs on port + 1 (PORT_HTTPS offset is 1 for confighttp) - const unsigned short web_ui_port = sunshine.port + 1; - sunshine.csrf_allowed_origins.push_back(std::format("https://localhost:{}", web_ui_port)); - sunshine.csrf_allowed_origins.push_back(std::format("https://127.0.0.1:{}", web_ui_port)); - sunshine.csrf_allowed_origins.push_back(std::format("https://[::1]:{}", web_ui_port)); + const unsigned short web_ui_port = settings_.sunshine.port + 1; + settings_.sunshine.csrf_allowed_origins.push_back(std::format("https://localhost:{}", web_ui_port)); + settings_.sunshine.csrf_allowed_origins.push_back(std::format("https://127.0.0.1:{}", web_ui_port)); + settings_.sunshine.csrf_allowed_origins.push_back(std::format("https://[::1]:{}", web_ui_port)); - string_restricted_f(vars, "address_family", sunshine.address_family, {"ipv4"sv, "both"sv}); - string_f(vars, "bind_address", sunshine.bind_address); + string_restricted_f(vars, "address_family", settings_.sunshine.address_family, {"ipv4"sv, "both"sv}); + string_f(vars, "bind_address", settings_.sunshine.bind_address); bool upnp = false; bool_f(vars, "upnp"s, upnp); if (upnp) { - config::sunshine.flags[config::flag::UPNP].flip(); + settings_.sunshine.flags[config::flag::UPNP].flip(); } - string_restricted_f(vars, "locale", config::sunshine.locale, { - "bg"sv, // Bulgarian - "cs"sv, // Czech - "de"sv, // German - "en"sv, // English - "en_GB"sv, // English (UK) - "en_US"sv, // English (US) - "es"sv, // Spanish - "fr"sv, // French - "hu"sv, // Hungarian - "it"sv, // Italian - "ja"sv, // Japanese - "ko"sv, // Korean - "pl"sv, // Polish - "pt"sv, // Portuguese - "pt_BR"sv, // Portuguese (Brazilian) - "ru"sv, // Russian - "sv"sv, // Swedish - "tr"sv, // Turkish - "uk"sv, // Ukrainian - "vi"sv, // Vietnamese - "zh"sv, // Chinese - "zh_TW"sv, // Chinese (Traditional) - }); + string_restricted_f(vars, "locale", settings_.sunshine.locale, { + "bg"sv, // Bulgarian + "cs"sv, // Czech + "de"sv, // German + "en"sv, // English + "en_GB"sv, // English (UK) + "en_US"sv, // English (US) + "es"sv, // Spanish + "fr"sv, // French + "hu"sv, // Hungarian + "it"sv, // Italian + "ja"sv, // Japanese + "ko"sv, // Korean + "pl"sv, // Polish + "pt"sv, // Portuguese + "pt_BR"sv, // Portuguese (Brazilian) + "ru"sv, // Russian + "sv"sv, // Swedish + "tr"sv, // Turkish + "uk"sv, // Ukrainian + "vi"sv, // Vietnamese + "zh"sv, // Chinese + "zh_TW"sv, // Chinese (Traditional) + }); std::string log_level_string; string_f(vars, "min_log_level", log_level_string); if (!log_level_string.empty()) { if (log_level_string == "verbose"sv) { - sunshine.min_log_level = 0; + settings_.sunshine.min_log_level = 0; } else if (log_level_string == "debug"sv) { - sunshine.min_log_level = 1; + settings_.sunshine.min_log_level = 1; } else if (log_level_string == "info"sv) { - sunshine.min_log_level = 2; + settings_.sunshine.min_log_level = 2; } else if (log_level_string == "warning"sv) { - sunshine.min_log_level = 3; + settings_.sunshine.min_log_level = 3; } else if (log_level_string == "error"sv) { - sunshine.min_log_level = 4; + settings_.sunshine.min_log_level = 4; } else if (log_level_string == "fatal"sv) { - sunshine.min_log_level = 5; + settings_.sunshine.min_log_level = 5; } else if (log_level_string == "none"sv) { - sunshine.min_log_level = 6; + settings_.sunshine.min_log_level = 6; } else { // accept digit directly auto val = log_level_string[0]; if (val >= '0' && val < '7') { - sunshine.min_log_level = val - '0'; + settings_.sunshine.min_log_level = val - '0'; } } } @@ -1951,7 +1943,7 @@ namespace config { vars.erase(it); } - if (sunshine.min_log_level <= 3) { + if (settings_.sunshine.min_log_level <= 3) { for (auto &[var, _] : vars) { std::cout << "Warning: Unrecognized configurable option ["sv << var << ']' << std::endl; } @@ -1964,7 +1956,7 @@ namespace config { * * @param file_content Raw configuration text to parse and apply. */ - void apply_config_for_test(const std::string_view file_content) { + void store_t::apply_config_for_test(const std::string_view file_content) { apply_config(parse_config(file_content)); } #endif @@ -1972,7 +1964,7 @@ namespace config { /** * @brief Parse serialized text into the corresponding runtime representation. */ - int parse(int argc, char *argv[]) { + int store_t::parse(int argc, char *argv[]) { std::unordered_map cmd_vars; #ifdef _WIN32 bool shortcut_launch = false; @@ -1995,9 +1987,9 @@ namespace config { #endif else if (*line == '-') { if (*(line + 1) == '-') { - sunshine.cmd.name = line + 2; - sunshine.cmd.argc = argc - x - 1; - sunshine.cmd.argv = argv + x + 1; + settings_.sunshine.cmd.name = line + 2; + settings_.sunshine.cmd.argc = argc - x - 1; + settings_.sunshine.cmd.argv = argv + x + 1; break; } @@ -2010,7 +2002,7 @@ namespace config { auto pos = std::find(line, line_end, '='); if (pos == line_end) { - sunshine.config_file = line; + settings_.sunshine.config_file = line; } else { TUPLE_EL(var, 1, parse_option(line, line_end)); if (!var) { @@ -2036,12 +2028,12 @@ namespace config { file_handler::make_directory(platf::appdata().string()); // Create empty config file if it does not exist - if (!fs::exists(sunshine.config_file)) { - std::ofstream {sunshine.config_file}; + if (!fs::exists(settings_.sunshine.config_file)) { + std::ofstream {settings_.sunshine.config_file}; } // Read config file - auto vars = parse_config(file_handler::read_file(sunshine.config_file.c_str())); + auto vars = parse_config(file_handler::read_file(settings_.sunshine.config_file.c_str())); for (auto &[name, value] : cmd_vars) { vars.insert_or_assign(std::move(name), std::move(value)); @@ -2108,7 +2100,7 @@ namespace config { CloseHandle(shell_exec_info.hProcess); // Wait for the UI to be ready for connections - service_ctrl::wait_for_ui_ready(); + service_ctrl::wait_for_ui_ready(values()); } // Always return 1 to ensure Sunshine doesn't start normally diff --git a/src/config.h b/src/config.h index d0c8e0016..ba7c62e96 100644 --- a/src/config.h +++ b/src/config.h @@ -7,6 +7,7 @@ // standard includes #include #include +#include #include #include #include @@ -38,9 +39,6 @@ namespace config { inline constexpr std::string_view GAMEPAD_DRIVER_VIGEMBUS = "vigembus"; ///< Allow only ViGEmBus for Windows gamepads. inline constexpr std::string_view GAMEPAD_DRIVER_NONE = "none"; ///< Disable virtual gamepads on Windows and macOS. - // track modified config options - inline std::unordered_map modified_config_settings; ///< Configuration keys changed during the current parse or UI update. - // sensitive values that should be redacted from logging /** * @brief Configuration keys whose values must be hidden in logs. @@ -49,14 +47,6 @@ namespace config { "csrf_allowed_origins" }; - /** - * @brief Log configuration entries and optionally mark them for persistence. - * - * @param vars Parsed configuration entries to log. - * @param save Whether modified configuration values should be written back to disk. - */ - void log_config_settings(const std::unordered_map &vars, bool save); - /** * @brief Video encoder, capture, and color settings loaded from configuration. */ @@ -368,10 +358,6 @@ namespace config { std::bitset flags; ///< Runtime flags parsed from command-line options. std::string credentials_file; ///< Path to the stored pairing credentials file. - std::string username; ///< Username for the local Web UI account. - std::string password; ///< Password hash or secret for the local Web UI account. - std::string salt; ///< Salt used when hashing the Web UI password. - std::string config_file; ///< Path to the active Sunshine configuration file. /** @@ -397,30 +383,119 @@ namespace config { std::vector csrf_allowed_origins; ///< Additional origins allowed by CSRF validation. }; - extern video_t video; - extern audio_t audio; - extern stream_t stream; - extern nvhttp_t nvhttp; - extern input_t input; - extern sunshine_t sunshine; + /** + * @brief Configuration groups owned by one application. + */ + struct settings_t { + /** + * @brief Populate the established defaults before file and command-line overrides. + */ + settings_t(); + + video_t video; ///< Encoder and capture configuration. + audio_t audio; ///< Audio capture configuration. + stream_t stream; ///< Transport and application-list configuration. + nvhttp_t nvhttp; ///< Pairing and GameStream HTTP configuration. + input_t input; ///< Input emulation configuration. + sunshine_t sunshine; ///< Application, startup, and Web UI configuration. + std::unordered_map modified_config_settings; ///< Values recorded during this store's parse or UI updates. + }; + + /** + * @brief Coherent Web UI authentication values. + */ + struct credentials_t { + std::string username; ///< Local Web UI account name. + std::string password; ///< Password hash stored for the account. + std::string salt; ///< Salt used to derive the password hash. + }; + + /** + * @brief Owns startup settings and synchronizes runtime credential updates. + */ + class store_t { + public: + /** + * @brief Read startup configuration after all startup edits have completed. + * @return The configuration groups owned by this store. + */ + const settings_t &values() const; + + /** + * @brief Edit configuration before application workers begin reading it. + * @return Mutable startup configuration; callers must finish edits before starting workers. + */ + settings_t &edit_startup(); + + /** + * @brief Copy all authentication values under one lock. + * @return A consistent account name, password hash, and salt. + */ + credentials_t credentials_snapshot() const; + + /** + * @brief Replace all authentication values as one synchronized update. + * @param credentials Complete account values to install. + */ + void update_credentials(credentials_t credentials); + + /** + * @brief Parse file and command-line overrides into this store. + * @param argc Number of command-line arguments. + * @param argv Command-line argument vector. + * @return Zero on success, or the existing command-line and configuration error status. + */ + int parse(int argc, char *argv[]); + + /** + * @brief Log parsed configuration entries and optionally record them as modified. + * @param vars Parsed entries to log. + * @param save Whether to record the entries for persistence. + */ + void log_config_settings(const std::unordered_map &vars, bool save); + + /** + * @brief Append a configuration option when the active file does not define it. + * @param name Configuration option name. + * @param value Configuration option value. + * @return Whether the option was appended successfully. + */ + bool persist_config_option_if_missing(std::string_view name, std::string_view value); + + /** + * @brief Select all gamepad drivers for a licensed user without a saved choice. + * @param virtualhid_licensed Whether Virtual HID Driver has an active machine license. + * @return Whether the `all` preference was persisted and applied. + */ + bool select_all_gamepad_drivers_if_licensed(bool virtualhid_licensed); #ifdef SUNSHINE_TESTS - /** - * @brief Parse and apply serialized configuration text for unit tests. - * - * @param file_content Raw configuration text to parse and apply. - */ - void apply_config_for_test(std::string_view file_content); + /** + * @brief Parse and apply serialized startup configuration for unit tests. + * @param file_content Configuration text to apply. + */ + void apply_config_for_test(std::string_view file_content); #endif - /** - * @brief Parse serialized text into the corresponding runtime representation. - * - * @param argc Number of command-line arguments. - * @param argv Command-line argument vector. - * @return 0 on success; nonzero when command-line or configuration parsing fails. - */ - int parse(int argc, char *argv[]); + private: + /** + * @brief Apply validated file and command-line values to this store. + * @param vars Parsed entries whose known keys are consumed. + */ + void apply_config(std::unordered_map &&vars); + + /** + * @brief Toggle the command-line flags selected by their character codes. + * @param line Null-terminated flag character sequence. + * @return Zero when all flags are recognized, or minus one otherwise. + */ + int apply_flags(const char *line); + + settings_t settings_; ///< Startup configuration read by application services. + mutable std::mutex credentials_mutex_; ///< Protects the complete authentication tuple. + credentials_t credentials_; ///< Runtime Web UI authentication values. + }; + /** * @brief Parse Sunshine configuration text into key-value entries. * @@ -429,23 +504,4 @@ namespace config { */ std::unordered_map parse_config(const std::string_view &file_content); - /** - * @brief Persist a configuration option when the active file does not already define it. - * - * Existing text and comments are retained because the new setting is appended rather - * than serializing the complete configuration again. - * - * @param name Configuration option name. - * @param value Configuration option value. - * @return True when the option was appended successfully; otherwise, false. - */ - bool persist_config_option_if_missing(std::string_view name, std::string_view value); - - /** - * @brief Select all available gamepad drivers when a licensed user has not made a choice. - * - * @param virtualhid_licensed Whether Virtual HID Driver has an active machine license. - * @return True when the `all` preference was persisted and applied; otherwise, false. - */ - bool select_all_gamepad_drivers_if_licensed(bool virtualhid_licensed); } // namespace config diff --git a/src/confighttp.cpp b/src/confighttp.cpp index d61e9b384..5b31ec9d9 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -614,6 +614,7 @@ namespace confighttp { * @return True if the user is authenticated, false otherwise. */ bool service_t::authenticate(const resp_https_t &response, const req_https_t &request) { + const auto credentials = configuration.credentials_snapshot(); auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); if (const auto ip_type = net::from_address(address); ip_type > http_state.origin_web_ui_allowed()) { @@ -623,7 +624,7 @@ namespace confighttp { } // If credentials are shown, redirect the user to a /welcome page - if (config::sunshine.username.empty()) { + if (credentials.username.empty()) { send_redirect(response, request, "/welcome"); return false; } @@ -648,7 +649,7 @@ namespace confighttp { const auto username = authData.substr(0, index); const auto password = authData.substr(index + 1); - if (const auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); !boost::iequals(username, config::sunshine.username) || hash != config::sunshine.password) { + if (const auto hash = util::hex(crypto::hash(password + credentials.salt)).to_string(); !boost::iequals(username, credentials.username) || hash != credentials.password) { return false; } @@ -734,8 +735,9 @@ namespace confighttp { * @return A unique identifier based on username or IP address. */ std::string service_t::get_client_id(const req_https_t &request) { + const auto credentials = configuration.credentials_snapshot(); // Try to use the authenticated username as client ID - if (const auto auth = request->header.find("authorization"); !config::sunshine.username.empty() && auth != request->header.end()) { + if (const auto auth = request->header.find("authorization"); !credentials.username.empty() && auth != request->header.end()) { if (const auto &rawAuth = auth->second; rawAuth.rfind("Basic "sv, 0) == 0) { auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length())); if (const auto index = static_cast(authData.find(':')); index < authData.size() - 1) { @@ -816,8 +818,8 @@ namespace confighttp { */ bool service_t::validate_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string &client_id) { // Helper function to check if a URL starts with any allowed origin - auto is_allowed_origin = [](const std::string_view url) { - return std::ranges::any_of(config::sunshine.csrf_allowed_origins, [&url](const std::string &allowed_origin) { + auto is_allowed_origin = [this](const std::string_view url) { + return std::ranges::any_of(settings.sunshine.csrf_allowed_origins, [&url](const std::string &allowed_origin) { // Ensure exact prefix match (with ":" or "/" after to prevent malicious.com matching allowed.com) if (url.rfind(allowed_origin, 0) != 0) { // rfind with pos=0 checks if the url starts with allowed_origin return false; @@ -877,7 +879,7 @@ namespace confighttp { * @brief Validates the application index and sends an error response if invalid. */ bool service_t::check_app_index(const resp_https_t &response, const req_https_t &request, int index) { - std::string file = file_handler::read_file(config::stream.file_apps.c_str()); + std::string file = file_handler::read_file(settings.stream.file_apps.c_str()); nlohmann::json file_tree = nlohmann::json::parse(file); if (const auto &apps = file_tree["apps"]; index < 0 || index >= static_cast(apps.size())) { std::string error; @@ -893,8 +895,9 @@ namespace confighttp { } void service_t::getPage(const resp_https_t &response, const req_https_t &request, const bool require_auth, const bool redirect_if_username) { + const auto credentials = configuration.credentials_snapshot(); // Special handling for welcome page: redirect if the username is already set - if (redirect_if_username && !config::sunshine.username.empty()) { + if (redirect_if_username && !credentials.username.empty()) { send_redirect(response, request, "/"); return; } @@ -1057,7 +1060,7 @@ namespace confighttp { print_req(request); try { - std::string content = file_handler::read_file(config::stream.file_apps.c_str()); + std::string content = file_handler::read_file(settings.stream.file_apps.c_str()); nlohmann::json file_tree = nlohmann::json::parse(content); // Legacy versions of Sunshine used strings for boolean and integers, let's convert them @@ -1155,7 +1158,7 @@ namespace confighttp { // TODO: Input Validation nlohmann::json output_tree; nlohmann::json input_tree = nlohmann::json::parse(ss); - std::string file = file_handler::read_file(config::stream.file_apps.c_str()); + std::string file = file_handler::read_file(settings.stream.file_apps.c_str()); BOOST_LOG(info) << file; nlohmann::json file_tree = nlohmann::json::parse(file); @@ -1191,8 +1194,8 @@ namespace confighttp { return a["name"].get() < b["name"].get(); }); - file_handler::write_file(config::stream.file_apps.c_str(), file_tree.dump(4)); - processes.refresh(config::stream.file_apps); + file_handler::write_file(settings.stream.file_apps.c_str(), file_tree.dump(4)); + processes.refresh(settings.stream.file_apps); output_tree["status"] = true; send_response(response, output_tree); @@ -1256,7 +1259,7 @@ namespace confighttp { return; } - std::string file = file_handler::read_file(config::stream.file_apps.c_str()); + std::string file = file_handler::read_file(settings.stream.file_apps.c_str()); nlohmann::json file_tree = nlohmann::json::parse(file); auto &apps = file_tree["apps"]; @@ -1267,8 +1270,8 @@ namespace confighttp { } file_tree["apps"] = new_apps; - file_handler::write_file(config::stream.file_apps.c_str(), file_tree.dump(4)); - processes.refresh(config::stream.file_apps); + file_handler::write_file(settings.stream.file_apps.c_str(), file_tree.dump(4)); + processes.refresh(settings.stream.file_apps); output_tree["status"] = true; output_tree["result"] = std::format("application {} deleted", index); @@ -1452,7 +1455,7 @@ namespace confighttp { output_tree["platform"] = SUNSHINE_PLATFORM; output_tree["version"] = PROJECT_VERSION; - auto vars = config::parse_config(file_handler::read_file(config::sunshine.config_file.c_str())); + auto vars = config::parse_config(file_handler::read_file(settings.sunshine.config_file.c_str())); for (auto &[name, value] : vars) { output_tree[name] = std::move(value); @@ -1475,7 +1478,7 @@ namespace confighttp { nlohmann::json output_tree; output_tree["status"] = true; - output_tree["locale"] = config::sunshine.locale; + output_tree["locale"] = settings.sunshine.locale; send_response(response, output_tree); } @@ -1525,7 +1528,7 @@ namespace confighttp { // we should migrate the config file to straight JSON and get rid of all this nonsense config_stream << k << " = " << (v.is_string() ? v.get() : v.dump()) << std::endl; } - file_handler::write_file(config::sunshine.config_file.c_str(), config_stream.str()); + file_handler::write_file(settings.sunshine.config_file.c_str(), config_stream.str()); output_tree["status"] = true; send_response(response, output_tree); } catch (std::exception &e) { @@ -1556,7 +1559,7 @@ namespace confighttp { return; } - std::string file = file_handler::read_file(config::stream.file_apps.c_str()); + std::string file = file_handler::read_file(settings.stream.file_apps.c_str()); nlohmann::json file_tree = nlohmann::json::parse(file); auto &apps = file_tree["apps"]; @@ -1676,7 +1679,7 @@ namespace confighttp { print_req(request); - std::string content = file_handler::read_file(config::sunshine.log_file.c_str()); + std::string content = file_handler::read_file(settings.sunshine.log_file.c_str()); SimpleWeb::CaseInsensitiveMultimap headers; headers.emplace("Content-Type", "text/plain"); headers.emplace("X-Frame-Options", "DENY"); @@ -1702,10 +1705,11 @@ namespace confighttp { * @api_examples{/api/password|:| POST|:| {"currentUsername":"admin","currentPassword":"admin","newUsername":"admin","newPassword":"admin","confirmNewPassword":"admin"}} */ void service_t::savePassword(const resp_https_t &response, const req_https_t &request) { + const auto credentials = configuration.credentials_snapshot(); if (!check_content_type(response, request, "application/json")) { return; } - if (!config::sunshine.username.empty() && !authenticate(response, request)) { + if (!credentials.username.empty() && !authenticate(response, request)) { return; } @@ -1735,13 +1739,13 @@ namespace confighttp { if (newUsername.empty()) { errors.emplace_back("Invalid Username"); } else { - auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); - if (config::sunshine.username.empty() || (boost::iequals(username, config::sunshine.username) && hash == config::sunshine.password)) { + auto hash = util::hex(crypto::hash(password + credentials.salt)).to_string(); + if (credentials.username.empty() || (boost::iequals(username, credentials.username) && hash == credentials.password)) { if (newPassword.empty() || newPassword != confirmPassword) { errors.emplace_back("Password Mismatch"); } else { - http::save_user_creds(config::sunshine.credentials_file, newUsername, newPassword); - http::reload_user_creds(config::sunshine.credentials_file); + http::save_user_creds(settings.sunshine.credentials_file, newUsername, newPassword); + http::reload_user_creds(settings.sunshine.credentials_file, configuration); output_tree["status"] = true; } } else { @@ -1985,7 +1989,9 @@ namespace confighttp { * @api_examples{/api/permissions|:| GET|:| null} */ void service_t::getPermissions(const resp_https_t &response, const req_https_t &request) { - make_permissions_handler(platf::get_permission_statuses)(response, request); + make_permissions_handler([this]() { + return platf::get_permission_statuses(settings); + })(response, request); } permissions_handler_t service_t::make_permissions_handler(permission_status_provider_t provider) { @@ -2202,10 +2208,12 @@ namespace confighttp { } #ifdef _WIN32 - config::select_all_gamepad_drivers_if_licensed(result.license.licensed()); + inputs.select_all_gamepad_drivers_if_licensed(configuration, result.license.licensed()); #endif #if (defined(_WIN32) || defined(__APPLE__)) && defined(SUNSHINE_TRAY) && SUNSHINE_TRAY >= 1 - system_tray::update_tray_virtualhid_license(result.license, false); + auto tray_settings = settings; + tray_settings.input = inputs.configuration_snapshot(); + system_tray::update_tray_virtualhid_license(tray_settings, result.license, false); #endif #ifdef _WIN32 if (result.status.ok()) { @@ -2408,7 +2416,9 @@ namespace confighttp { /** * @brief Start the HTTPS configuration server. */ - service_t::service_t(nvhttp::service_t &gamestream, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, input::service_t &inputs, rtsp_stream::service_t &rtsp, lifetime::controller_t &lifetime, safe::mail_t host_mail): + service_t::service_t(config::store_t &configuration, nvhttp::service_t &gamestream, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, input::service_t &inputs, rtsp_stream::service_t &rtsp, lifetime::controller_t &lifetime, safe::mail_t host_mail): + configuration {configuration}, + settings {configuration.values()}, gamestream {gamestream}, http_state {http_state}, processes {processes}, @@ -2428,10 +2438,10 @@ namespace confighttp { platf::set_thread_name("confighttp"); const auto shutdown_event = host_mail->event(mail::shutdown); - const auto port_https = net::map_port(PORT_HTTPS); - const auto address_family = net::af_from_enum_string(config::sunshine.address_family); + const auto port_https = net::map_port(settings, PORT_HTTPS); + const auto address_family = net::af_from_enum_string(settings.sunshine.address_family); - https_server_t server {config::nvhttp.cert, config::nvhttp.pkey}; + https_server_t server {settings.nvhttp.cert, settings.nvhttp.pkey}; // Helper to create SPA entry handlers without repeating the signature auto page_handler = [this](bool require_auth = true, bool redirect_if_username = false) { @@ -2497,10 +2507,10 @@ namespace confighttp { server.resource["^/assets\\/.+$"]["GET"] = bind(&service_t::getAsset); server.config.reuse_address = true; - server.config.address = net::get_bind_address(address_family); + server.config.address = net::get_bind_address(settings, address_family); server.config.port = port_https; - const auto display_addr = net::get_bind_address_url_host(); + const auto display_addr = net::get_bind_address_url_host(settings); auto accept_and_run = [&](auto *server) { try { diff --git a/src/confighttp.h b/src/confighttp.h index 2a6f83a6e..c82f00175 100644 --- a/src/confighttp.h +++ b/src/confighttp.h @@ -3,6 +3,7 @@ * @brief Declarations for the Web UI Config HTTP server. */ #pragma once +#include "config.h" // standard includes #include @@ -186,6 +187,7 @@ namespace confighttp { public: /** * @brief Bind dependencies before registering HTTP callbacks. + * @param configuration Owned startup settings and synchronized credentials. * @param gamestream GameStream pairing and client state. * @param http_state Host HTTP identity and origin policy. * @param processes Application process owner. @@ -195,7 +197,7 @@ namespace confighttp { * @param lifetime Application termination controller. * @param host_mail Application shutdown mailbox. */ - service_t(nvhttp::service_t &gamestream, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, input::service_t &inputs, rtsp_stream::service_t &rtsp, lifetime::controller_t &lifetime, safe::mail_t host_mail); + service_t(config::store_t &configuration, nvhttp::service_t &gamestream, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, input::service_t &inputs, rtsp_stream::service_t &rtsp, lifetime::controller_t &lifetime, safe::mail_t host_mail); service_t(const service_t &) = delete; service_t &operator=(const service_t &) = delete; @@ -227,32 +229,9 @@ namespace confighttp { */ void reset_portal_token_path_provider_for_testing(); #endif - /** - * @brief Handle authenticate for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - * @return Result of the request. - */ bool authenticate(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get_client_id for this Web UI service. - * @return Result of the request. - */ std::string get_client_id(const req_https_t &request); - /** - * @brief Handle generate_csrf_token for this Web UI service. - * @return Result of the request. - */ std::string generate_csrf_token(const std::string &client_id); - /** - * @brief Handle validate stored csrf token for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - * @param client_id Identity bound to the CSRF token. - * @param provided_token CSRF token supplied by the client. - * @return Result of the requested operation. - */ bool validate_stored_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string_view client_id, const std::string_view provided_token); /** * @brief Validate CSRF token. @@ -288,135 +267,24 @@ namespace confighttp { * @param request HTTP request data from the client. */ void getFallbackPage(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get favicon image for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getFaviconImage(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get sunshine logo image for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getSunshineLogoImage(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle getAsset for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void getAsset(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle getCSRFToken for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void getCSRFToken(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get apps for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getApps(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle save app for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void saveApp(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle close app for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void closeApp(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle delete app for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void deleteApp(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get clients for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getClients(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle update client for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void updateClient(resp_https_t response, req_https_t request); - /** - * @brief Handle unpair for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void unpair(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle unpair all for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void unpairAll(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get config for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getConfig(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle getLocale for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void getLocale(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle save config for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void saveConfig(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get cover for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getCover(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle upload cover for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void uploadCover(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle get logs for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void getLogs(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle save password for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void savePassword(const resp_https_t &response, const req_https_t &request); /** * @brief List authenticated pairing requests awaiting operator approval. @@ -439,25 +307,8 @@ namespace confighttp { * @param request HTTP request data from the client. */ void savePin(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle reset display device persistence for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void resetDisplayDevicePersistence(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle resetPortalToken for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void resetPortalToken(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle restart for this Web UI service. - * - * @param response HTTPS response to populate. - * @param request HTTPS request from the client. - */ void restart(const resp_https_t &response, const req_https_t &request); /** * @brief Return the host's permission statuses to the Web UI. @@ -480,29 +331,9 @@ namespace confighttp { * @param request Authenticated, CSRF protected request. */ void requestPermission(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle getVirtualInputStatus for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void getVirtualInputStatus(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle getVirtualInputLicense for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void getVirtualInputLicense(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle updateVirtualInputLicense for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void updateVirtualInputLicense(const resp_https_t &response, const req_https_t &request); - /** - * @brief Handle browseDirectory for this Web UI service. - * @param response HTTPS response to populate. - * @param request HTTPS request to process. - */ void browseDirectory(const resp_https_t &response, const req_https_t &request); /** * @brief Handle start for this Web UI service. @@ -510,11 +341,6 @@ namespace confighttp { void start(); private: - /** - * @brief Return current license details after authenticating a request. - * @param response HTTPS response receiving license details. - * @param request HTTPS request to authenticate. - */ void get_virtual_input_license(const resp_https_t &response, const req_https_t &request); /** @@ -539,6 +365,8 @@ namespace confighttp { std::function token_path_provider; ///< Bound portal token path query. #endif std::function license_provider = lvh::get_license_status; ///< Bound license status query. + config::store_t &configuration; ///< Startup settings and synchronized credentials. + const config::settings_t &settings; ///< Settings retained by the application. nvhttp::service_t &gamestream; ///< Pairing and client state. http::state_t &http_state; ///< Host HTTP identity and origin policy. proc::proc_t &processes; ///< Application process owner. diff --git a/src/display_device.cpp b/src/display_device.cpp index 25522b435..5b9648a35 100644 --- a/src/display_device.cpp +++ b/src/display_device.cpp @@ -136,11 +136,18 @@ namespace display_device { */ class sunshine_audio_context_t: public AudioContextInterface { public: + /** + * @brief Bind the host audio owner used to retain sink restoration state. + * @param audios Shared host audio service. + */ + explicit sunshine_audio_context_t(audio::service_t &audios): + audios {audios} {} + [[nodiscard]] bool capture() override { - return context_scheduler.execute([](auto &audio_context) { + return context_scheduler.execute([this](auto &audio_context) { // Explicitly releasing the context first in case it was not release yet so that it can be potentially cleaned up. audio_context = boost::none; - audio_context = audio_context_t {}; + audio_context = audio_context_t {audios.context()}; // Always say that we have captured it successfully as otherwise the settings change procedure will be aborted. return true; @@ -184,9 +191,8 @@ namespace display_device { struct audio_context_t { /** * @brief A reference to the audio context that will automatically extend the audio session. - * @note It is auto-initialized here for convenience. */ - decltype(audio::get_audio_ctx_ref()) audio_ctx_ref {audio::get_audio_ctx_ref()}; + audio::audio_ctx_ref_t audio_ctx_ref; /** * @brief Will be set to true if the capture was released, but we still have to keep the context around, because the device is not available. @@ -199,6 +205,7 @@ namespace display_device { int retry_counter {15}; }; + audio::service_t &audios; ///< Host audio state shared with active capture. RetryScheduler> context_scheduler {std::make_unique>(boost::none)}; }; @@ -382,7 +389,7 @@ namespace display_device { * Empty optional if no preparation nor configuration shall take place. * * @examples - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * const auto device_prep_option = parse_device_prep_option(video_config); * @examples_end */ @@ -415,7 +422,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * * SingleDisplayConfiguration config; * const bool success = parse_resolution_option(video_config, *launch_session, config); @@ -473,7 +480,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * * SingleDisplayConfiguration config; * const bool success = parse_refresh_rate_option(video_config, *launch_session, config); @@ -522,7 +529,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * const auto hdr_option = parse_hdr_option(video_config, *launch_session); * @examples_end */ @@ -630,7 +637,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * * SingleDisplayConfiguration config; * const bool success = remap_display_mode_if_needed(video_config, *launch_session, config); @@ -739,14 +746,16 @@ namespace display_device { * @brief Construct a settings manager interface to manage display device settings. * @param persistence_filepath File location for saving persistent state. * @param video_config User's video related configuration. + * @param persistence_watch Receives the persistence observer used for retry decisions. + * @param audios Host audio owner shared with display recovery. * @return An interface or nullptr if the OS does not support the interface. */ - std::unique_ptr make_settings_manager([[maybe_unused]] const std::filesystem::path &persistence_filepath, [[maybe_unused]] const config::video_t &video_config, std::shared_ptr &persistence_watch) { + std::unique_ptr make_settings_manager([[maybe_unused]] const std::filesystem::path &persistence_filepath, [[maybe_unused]] const config::video_t &video_config, std::shared_ptr &persistence_watch, [[maybe_unused]] audio::service_t &audios) { persistence_watch.reset(); #ifdef _WIN32 return std::make_unique( std::make_shared(std::make_shared(), false), - std::make_shared(), + std::make_shared(audios), std::make_unique(make_persistence_watch(persistence_filepath, persistence_watch)), WinWorkarounds { .m_hdr_blank_delay = video_config.dd.wa.hdr_toggle_delay != std::chrono::milliseconds::zero() ? std::make_optional(video_config.dd.wa.hdr_toggle_delay) : std::nullopt @@ -755,7 +764,7 @@ namespace display_device { #elif defined(__APPLE__) return std::make_unique( std::make_shared(std::make_shared()), - std::make_shared(), + std::make_shared(audios), std::make_unique(make_persistence_watch(persistence_filepath, persistence_watch)), MacWorkarounds {} ); @@ -885,7 +894,7 @@ namespace display_device { impl->sm_instance.reset(); } - void manager_t::initialize(const std::filesystem::path &persistence_filepath, const config::video_t &video_config) { + void manager_t::initialize(const std::filesystem::path &persistence_filepath, const config::video_t &video_config, audio::service_t &audios) { std::lock_guard lock {impl->mutex}; // We can support re-init without any issues, however we should make sure to clean up first! revert_configuration_unlocked(*impl, revert_option_e::try_once); @@ -894,7 +903,7 @@ namespace display_device { // If we fail to create settings manager, this means platform is not supported, and // we will need to provided error-free pass-trough in other methods - if (auto settings_manager {make_settings_manager(persistence_filepath, video_config, impl->persistence_watch)}) { + if (auto settings_manager {make_settings_manager(persistence_filepath, video_config, impl->persistence_watch, audios)}) { impl->sm_instance = std::make_unique>(std::move(settings_manager)); const auto available_devices {impl->sm_instance->execute([](auto &settings_iface) { diff --git a/src/display_device.h b/src/display_device.h index f1e269024..70962a455 100644 --- a/src/display_device.h +++ b/src/display_device.h @@ -27,6 +27,10 @@ namespace rtsp_stream { struct launch_session_t; } +namespace audio { + class service_t; +} + namespace display_device { /** @@ -64,7 +68,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * * const auto config { parse_configuration(video_config, *launch_session) }; * if (const auto *parsed_config { std::get_if(&result) }; parsed_config) { @@ -105,14 +109,15 @@ namespace display_device { * @brief Initialize the implementation and perform the initial state recovery (if needed). * @param persistence_filepath File location for reading/saving persistent state. * @param video_config User's video related configuration. + * @param audios Host audio owner shared with display recovery. * @note Destroy the manager after all consumers stop to restore pending settings. * * @examples - * const config::video_t &video_config { config::video }; - * initialize("/my/persitence/file.state", video_config); + * const config::video_t &video_config { settings.video }; + * initialize("/my/persitence/file.state", video_config, audios); * @examples_end */ - void initialize(const std::filesystem::path &persistence_filepath, const config::video_t &video_config); + void initialize(const std::filesystem::path &persistence_filepath, const config::video_t &video_config, audio::service_t &audios); /** * @brief Map the output name to a specific display. @@ -120,7 +125,7 @@ namespace display_device { * @returns Mapped display name or empty string if the output name could not be mapped. * * @examples - * const auto mapped_name_config { map_output_name(config::video.output_name) }; + * const auto mapped_name_config { displays.map_output_name(settings.video.output_name) }; * const auto mapped_name_custom { map_output_name("{some-device-id}") }; * @examples_end */ @@ -135,7 +140,7 @@ namespace display_device { * * @examples * const std::shared_ptr launch_session; - * const config::video_t &video_config { config::video }; + * const config::video_t &video_config { settings.video }; * * configure_display(video_config, *launch_session); * @examples_end diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp index 117cd1ee4..7947c1401 100644 --- a/src/entry_handler.cpp +++ b/src/entry_handler.cpp @@ -26,25 +26,25 @@ extern "C" { using namespace std::literals; -std::string get_launch_ui_url(const std::optional &path) { - std::string url = std::format("https://{}:{}", net::get_bind_address_url_host(), static_cast(net::map_port(confighttp::PORT_HTTPS))); +std::string get_launch_ui_url(const config::settings_t &settings, const std::optional &path) { + std::string url = std::format("https://{}:{}", net::get_bind_address_url_host(settings), static_cast(net::map_port(settings, confighttp::PORT_HTTPS))); if (path) { url += *path; } return url; } -void launch_ui(const std::optional &path) { - platf::open_url(get_launch_ui_url(path)); +void launch_ui(const config::settings_t &settings, const std::optional &path) { + platf::open_url(get_launch_ui_url(settings, path)); } namespace args { - int creds(const char *name, int argc, char *argv[]) { + int creds(const config::settings_t &settings, const char *name, int argc, char *argv[]) { if (argc < 2 || argv[0] == "help"sv || argv[1] == "help"sv) { - help(name); + return help(name); } - http::save_user_creds(config::sunshine.credentials_file, argv[0], argv[1]); + http::save_user_creds(settings.sunshine.credentials_file, argv[0], argv[1]); return 0; } @@ -311,7 +311,7 @@ namespace service_ctrl { return true; } - bool wait_for_ui_ready() { + bool wait_for_ui_ready(const config::settings_t &settings) { std::cout << "Waiting for Web UI to be ready..."; // Wait up to 30 seconds for the web UI to start @@ -338,7 +338,7 @@ namespace service_ctrl { return false; } - uint16_t port_nbo = htons(net::map_port(confighttp::PORT_HTTPS)); + uint16_t port_nbo = htons(net::map_port(settings, confighttp::PORT_HTTPS)); for (DWORD i = 0; i < tcp_table->dwNumEntries; i++) { auto &entry = tcp_table->table[i]; diff --git a/src/entry_handler.h b/src/entry_handler.h index 01bcdc053..35e70434b 100644 --- a/src/entry_handler.h +++ b/src/entry_handler.h @@ -3,6 +3,7 @@ * @brief Declarations for entry handling functions. */ #pragma once +#include "config.h" // standard includes #include @@ -19,20 +20,22 @@ /** * @brief Build the URL used to launch the Web UI. + * @param settings Application settings containing the bind address and base port. * @param path Optional path to append to the base URL. * @return HTTPS URL using the configured bind address and Web UI port. * @examples - * get_launch_ui_url(); - * get_launch_ui_url("/pin"); + * get_launch_ui_url(settings); + * get_launch_ui_url(settings, "/pin"); * @examples_end */ -std::string get_launch_ui_url(const std::optional &path = std::nullopt); +std::string get_launch_ui_url(const config::settings_t &settings, const std::optional &path = std::nullopt); /** * @brief Launch the Web UI. + * @param settings Application settings containing the bind address and base port. * @param path Optional path to append to the base URL. */ -void launch_ui(const std::optional &path = std::nullopt); +void launch_ui(const config::settings_t &settings, const std::optional &path = std::nullopt); /** * @brief Functions for handling command line arguments. @@ -40,16 +43,17 @@ void launch_ui(const std::optional &path = std::nullopt); namespace args { /** * @brief Reset the user credentials. + * @param settings Application settings containing the credentials file path. * @param name The name of the program. * @param argc The number of arguments. * @param argv The arguments. * @examples - * creds("sunshine", 2, {"new_username", "new_password"}); + * creds(settings, "sunshine", 2, {"new_username", "new_password"}); * @examples_end * * @return Process exit code from updating the stored credentials. */ - int creds(const char *name, int argc, char *argv[]); + int creds(const config::settings_t &settings, const char *name, int argc, char *argv[]); /** * @brief Print help to stdout, then exit. @@ -238,12 +242,13 @@ namespace service_ctrl { /** * @brief Wait for the UI to be ready after Sunshine startup. + * @param settings Application settings containing the Web UI endpoint. * @examples - * wait_for_ui_ready(); + * wait_for_ui_ready(settings); * @examples_end * * @return True when the requested service or UI readiness condition is satisfied. */ - bool wait_for_ui_ready(); + bool wait_for_ui_ready(const config::settings_t &settings); } // namespace service_ctrl #endif diff --git a/src/httpcommon.cpp b/src/httpcommon.cpp index 566ee40c9..48375ec05 100644 --- a/src/httpcommon.cpp +++ b/src/httpcommon.cpp @@ -37,7 +37,7 @@ namespace http { namespace fs = std::filesystem; namespace pt = boost::property_tree; - int reload_user_creds(const std::string &file); + int reload_user_creds(const std::string &file, config::store_t &store); /** * @brief Check whether the Web UI credentials file exists and is readable. * @@ -46,26 +46,30 @@ namespace http { */ bool user_creds_exist(const std::string &file); + state_t::state_t(config::store_t &store): + store {store} {} + /** * @brief Load persisted HTTP credentials and initialize shared request state. */ int state_t::initialize() { - bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; - allowed_origin = net::from_enum_string(config::nvhttp.origin_web_ui_allowed); + auto &settings = store.edit_startup(); + bool clean_slate = settings.sunshine.flags[config::flag::FRESH_STATE]; + allowed_origin = net::from_enum_string(settings.nvhttp.origin_web_ui_allowed); if (clean_slate) { host_unique_id = uuid_util::uuid_t::generate().string(); auto dir = std::filesystem::temp_directory_path() / "Sunshine"sv; - config::nvhttp.cert = (dir / ("cert-"s + host_unique_id)).string(); - config::nvhttp.pkey = (dir / ("pkey-"s + host_unique_id)).string(); + settings.nvhttp.cert = (dir / ("cert-"s + host_unique_id)).string(); + settings.nvhttp.pkey = (dir / ("pkey-"s + host_unique_id)).string(); } - if ((!fs::exists(config::nvhttp.pkey) || !fs::exists(config::nvhttp.cert)) && create_creds(config::nvhttp.pkey, config::nvhttp.cert)) { + if ((!fs::exists(settings.nvhttp.pkey) || !fs::exists(settings.nvhttp.cert)) && create_creds(settings.nvhttp.pkey, settings.nvhttp.cert)) { return -1; } - if (!user_creds_exist(config::sunshine.credentials_file)) { + if (!user_creds_exist(settings.sunshine.credentials_file)) { BOOST_LOG(info) << "Open the Web UI to set your new username and password and getting started"; - } else if (reload_user_creds(config::sunshine.credentials_file)) { + } else if (reload_user_creds(settings.sunshine.credentials_file, store)) { return -1; } return 0; @@ -143,13 +147,12 @@ namespace http { /** * @brief Reload the Web UI credentials from disk. */ - int reload_user_creds(const std::string &file) { + int reload_user_creds(const std::string &file, config::store_t &store) { pt::ptree inputTree; try { pt::read_json(file, inputTree); - config::sunshine.username = inputTree.get("username"); - config::sunshine.password = inputTree.get("password"); - config::sunshine.salt = inputTree.get("salt"); + config::credentials_t credentials {inputTree.get("username"), inputTree.get("password"), inputTree.get("salt")}; + store.update_credentials(std::move(credentials)); } catch (std::exception &e) { BOOST_LOG(error) << "loading user credentials: "sv << e.what(); return -1; @@ -185,26 +188,26 @@ namespace http { } if (file_handler::write_file(pkey.c_str(), creds.pkey)) { - BOOST_LOG(error) << "Couldn't open ["sv << config::nvhttp.pkey << ']'; + BOOST_LOG(error) << "Couldn't open ["sv << pkey << ']'; return -1; } if (file_handler::write_file(cert.c_str(), creds.x509)) { - BOOST_LOG(error) << "Couldn't open ["sv << config::nvhttp.cert << ']'; + BOOST_LOG(error) << "Couldn't open ["sv << cert << ']'; return -1; } fs::permissions(pkey_path, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't change permissions of ["sv << config::nvhttp.pkey << "] :"sv << err_code.message(); + BOOST_LOG(error) << "Couldn't change permissions of ["sv << pkey << "] :"sv << err_code.message(); return -1; } fs::permissions(cert_path, fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't change permissions of ["sv << config::nvhttp.cert << "] :"sv << err_code.message(); + BOOST_LOG(error) << "Couldn't change permissions of ["sv << cert << "] :"sv << err_code.message(); return -1; } diff --git a/src/httpcommon.h b/src/httpcommon.h index 67ca74f3e..13cacad32 100644 --- a/src/httpcommon.h +++ b/src/httpcommon.h @@ -19,7 +19,12 @@ namespace http { class state_t { public: /** - * @brief Initialize credentials and host HTTP policy. + * @brief Bind the configuration and coherent credential store. + * @param store Application configuration owner. + */ + explicit state_t(config::store_t &store); + /** + * @brief Initialize credentials and host HTTP policy before worker threads start. * @return Zero on success, nonzero if credentials cannot be initialized. */ int initialize(); @@ -40,6 +45,7 @@ namespace http { net::net_e origin_web_ui_allowed() const; private: + config::store_t &store; ///< Application settings and authentication owner. std::string host_unique_id; ///< Persistent host identity shared with GameStream clients. net::net_e allowed_origin {}; ///< Web UI origin policy initialized before handlers start. }; @@ -62,10 +68,11 @@ namespace http { /** * @brief Reload Web UI user credentials from disk. * - * @param file Destination path for the downloaded content. + * @param file Credentials file to read. + * @param store Owner receiving the complete authentication tuple. * @return 0 when credentials reload successfully; nonzero on failure. */ - int reload_user_creds(const std::string &file); + int reload_user_creds(const std::string &file, config::store_t &store); /** * @brief Download a URL to a local file using libcurl. * diff --git a/src/input.cpp b/src/input.cpp index 3a36678a3..8076cdf3a 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -207,16 +207,22 @@ namespace input { struct service_t::impl_t: std::enable_shared_from_this { /** * @brief Bind the host dependencies without opening platform devices. + * @param settings Immutable host startup configuration. * @param scheduler Scheduler serializing host input work. * @param mail Host mailbox carrying display selection. * @param cursor Host cursor visibility preference. */ - impl_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): + impl_t(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): + settings {settings}, + gamepad_driver {settings.input.gamepad_driver}, scheduler {scheduler}, mail {std::move(mail)}, cursor {cursor} { } + const config::settings_t &settings; ///< Immutable host startup configuration. + std::string gamepad_driver; ///< Runtime backend choice serialized with host input work. + mutable std::mutex gamepad_driver_mutex; ///< Protects policy snapshots requested by UI threads. thread_pool_util::ThreadPool &scheduler; ///< Host input task scheduler. safe::mail_t mail; ///< Host communication mailbox. bool &cursor; ///< Host cursor visibility preference. @@ -828,7 +834,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_REL_MOUSE_MOVE_PACKET packet) { auto &host = input->host; - if (!config::input.mouse) { + if (!host.settings.input.mouse) { return; } @@ -939,7 +945,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_ABS_MOUSE_MOVE_PACKET packet) { auto &host = input->host; - if (!config::input.mouse) { + if (!host.settings.input.mouse) { return; } @@ -979,7 +985,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_MOUSE_BUTTON_PACKET packet) { auto &host = input->host; - if (!config::input.mouse) { + if (!host.settings.input.mouse) { return; } @@ -1042,12 +1048,13 @@ namespace input { /** * @brief Apply configured keybinding remaps to a platform keycode. * + * @param host Input service providing immutable keybinding settings. * @param keycode Platform keycode being translated or emitted. * @return Remapped keycode when configured, otherwise the original keycode. */ - short map_keycode(short keycode) { - auto it = config::input.keybindings.find(keycode); - if (it != std::end(config::input.keybindings)) { + short map_keycode(service_t::impl_t &host, short keycode) { + auto it = host.settings.input.keybindings.find(keycode); + if (it != std::end(host.settings.input.keybindings)) { return it->second; } @@ -1213,7 +1220,7 @@ namespace input { } } - emit_keyboard_update(host, map_keycode(key_code), release, flags, extended); + emit_keyboard_update(host, map_keycode(host, key_code), release, flags, extended); if (!release) { // Raise any synthetic modifier keys we pressed @@ -1251,7 +1258,7 @@ namespace input { send_key_and_modifiers(host, key_code, false, flags, synthetic_modifiers, state.extended); - host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, config::input.key_repeat_period, std::move(owner), key_code, flags, synthetic_modifiers).task_id; + host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, host.settings.input.key_repeat_period, std::move(owner), key_code, flags, synthetic_modifiers).task_id; } /** @@ -1262,7 +1269,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_KEYBOARD_PACKET packet) { auto &host = input->host; - if (!config::input.keyboard) { + if (!host.settings.input.keyboard) { return; } @@ -1273,7 +1280,7 @@ namespace input { // Right-alt maps to meta, so it must not also register as ALT int modifiers = packet->modifiers; - if (config::input.key_rightalt_to_key_win && input->alt_keys.right_pressed && !input->alt_keys.left_pressed) { + if (host.settings.input.key_rightalt_to_key_win && input->alt_keys.right_pressed && !input->alt_keys.left_pressed) { modifiers &= ~MODIFIER_ALT; } @@ -1307,8 +1314,8 @@ namespace input { host.scheduler.cancel(host.key_press_repeat_id); } - if (config::input.key_repeat_delay.count() > 0) { - host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, config::input.key_repeat_delay, input->owner, keyCode, packet->flags, synthetic_modifiers).task_id; + if (host.settings.input.key_repeat_delay.count() > 0) { + host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, host.settings.input.key_repeat_delay, input->owner, keyCode, packet->flags, synthetic_modifiers).task_id; } } else { // Already released @@ -1336,11 +1343,11 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_SCROLL_PACKET packet) { auto &host = input->host; - if (!config::input.mouse) { + if (!host.settings.input.mouse) { return; } - if (config::input.high_resolution_scrolling) { + if (host.settings.input.high_resolution_scrolling) { platf::scroll(host.platf_input, util::endian::big(packet->scrollAmt1)); } else { input->accumulated_vscroll_delta += util::endian::big(packet->scrollAmt1); @@ -1360,11 +1367,11 @@ namespace input { */ void passthrough(std::shared_ptr &input, PSS_HSCROLL_PACKET packet) { auto &host = input->host; - if (!config::input.mouse) { + if (!host.settings.input.mouse) { return; } - if (config::input.high_resolution_scrolling) { + if (host.settings.input.high_resolution_scrolling) { platf::hscroll(host.platf_input, util::endian::big(packet->scrollAmount)); } else { input->accumulated_hscroll_delta += util::endian::big(packet->scrollAmount); @@ -1384,7 +1391,7 @@ namespace input { * @param host Host input or video service and its capture dependencies. */ void passthrough(service_t::impl_t &host, const NV_UNICODE_PACKET *packet) { - if (!config::input.keyboard) { + if (!host.settings.input.keyboard) { return; } @@ -1433,7 +1440,8 @@ namespace input { * @param packet The controller arrival packet. */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_ARRIVAL_PACKET packet) { - if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + auto &host = input->host; + if (!host.settings.input.controller || host.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1492,7 +1500,8 @@ namespace input { */ template std::optional prepare_absolute_pointer_data(std::shared_ptr &input, Packet packet) { - if (!config::input.mouse) { + auto &host = input->host; + if (!host.settings.input.mouse) { return std::nullopt; } @@ -1584,7 +1593,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_TOUCH_PACKET packet) { auto &host = input->host; - if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + if (!host.settings.input.controller || host.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1618,7 +1627,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_MOTION_PACKET packet) { auto &host = input->host; - if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + if (!host.settings.input.controller || host.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1651,7 +1660,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_BATTERY_PACKET packet) { auto &host = input->host; - if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + if (!host.settings.input.controller || host.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1683,7 +1692,7 @@ namespace input { */ void passthrough(std::shared_ptr &input, PNV_MULTI_CONTROLLER_PACKET packet) { auto &host = input->host; - if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + if (!host.settings.input.controller || host.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1752,7 +1761,7 @@ namespace input { if (platf::BACK & bf) { if (platf::BACK & bf_new) { // Don't emulate home button if timeout < 0 - if (config::input.back_button_timeout >= 0ms) { + if (host.settings.input.back_button_timeout >= 0ms) { auto f = [input, controller = packet->controllerNumber, &host]() { auto &gamepad = input->gamepads[controller]; @@ -1777,7 +1786,7 @@ namespace input { gamepad.back_timeout_id = nullptr; }; - gamepad.back_timeout_id = host.scheduler.pushDelayed(std::move(f), config::input.back_button_timeout).task_id; + gamepad.back_timeout_id = host.scheduler.pushDelayed(std::move(f), host.settings.input.back_button_timeout).task_id; } } else if (gamepad.back_timeout_id) { host.scheduler.cancel(gamepad.back_timeout_id); @@ -2363,7 +2372,7 @@ namespace input { // host.key_press is keyed on the client's unmapped virtual-key code, but the press was // emitted through map_keycode(). Release the host key that actually went down, // otherwise a remapped modifier stays latched after the client disconnects. - emit_keyboard_update(host, map_keycode(vk_from_kpid(key) & 0x00FF), true, flags_from_kpid(key), state.extended); + emit_keyboard_update(host, map_keycode(host, vk_from_kpid(key) & 0x00FF), true, flags_from_kpid(key), state.extended); state.pressed = false; } } @@ -2454,8 +2463,8 @@ namespace input { }); } - service_t::service_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): - impl_ {std::make_shared(scheduler, std::move(mail), cursor)} { + service_t::service_t(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): + impl_ {std::make_shared(settings, scheduler, std::move(mail), cursor)} { } service_t::~service_t() { @@ -2483,7 +2492,7 @@ namespace input { } bool service_t::initialize() { - impl_->platf_input = platf::input(impl_->scheduler); + impl_->platf_input = platf::input(impl_->settings, impl_->scheduler); return static_cast(impl_->platf_input); } @@ -2491,11 +2500,35 @@ namespace input { * @brief Probe connected gamepads and update input capability state. */ bool service_t::probe_gamepads() { - auto &host = *impl_; - const auto &gamepads = platf::supported_gamepads(std::addressof(host.platf_input)); - return std::ranges::none_of(gamepads, [](const auto &gamepad) { - return gamepad.is_enabled && gamepad.name != "auto"; - }); + auto probe = [owner = impl_]() { + const auto gamepads = platf::supported_gamepads(std::addressof(owner->platf_input)); + return std::ranges::none_of(gamepads, [](const auto &gamepad) { + return gamepad.is_enabled && gamepad.name != "auto"; + }); + }; + return impl_->scheduler.running() ? impl_->scheduler.push(std::move(probe)).get() : probe(); + } + + bool service_t::select_all_gamepad_drivers_if_licensed(config::store_t &config, bool licensed) { + auto select = [owner = impl_, &config, licensed]() { + if (!licensed || !owner->gamepad_driver.empty() || !config.persist_config_option_if_missing("gamepad_driver", config::GAMEPAD_DRIVER_ALL)) { + return false; + } + std::lock_guard lock {owner->gamepad_driver_mutex}; + owner->gamepad_driver = config::GAMEPAD_DRIVER_ALL; + if (owner->platf_input) { + platf::virtualhid::get_input_context(owner->platf_input).gamepad_driver = owner->gamepad_driver; + } + return true; + }; + return impl_->scheduler.running() ? impl_->scheduler.push(std::move(select)).get() : select(); + } + + config::input_t service_t::configuration_snapshot() const { + std::lock_guard lock {impl_->gamepad_driver_mutex}; + auto result = impl_->settings.input; + result.gamepad_driver = impl_->gamepad_driver; + return result; } void service_t::refresh_virtual_input() { diff --git a/src/input.h b/src/input.h index a0876c2b3..0b52f00a5 100644 --- a/src/input.h +++ b/src/input.h @@ -33,11 +33,12 @@ namespace input { /** * @brief Bind the host scheduler, mailbox, and cursor preference. + * @param settings Immutable host startup configuration. * @param scheduler Scheduler serializing input work. * @param mail Host mailbox carrying display selection. * @param cursor Host cursor visibility preference. */ - service_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor); + service_t(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor); service_t(const service_t &) = delete; service_t &operator=(const service_t &) = delete; /** @@ -72,6 +73,20 @@ namespace input { */ void refresh_virtual_input(); + /** + * @brief Persist a newly licensed user's backend choice on the input scheduler. + * @param config Store providing the immutable configuration file path. + * @param licensed Whether Virtual HID Driver has an active license. + * @return Whether the preference was persisted and selected for this input service. + */ + bool select_all_gamepad_drivers_if_licensed(config::store_t &config, bool licensed); + + /** + * @brief Copy startup input settings with the service's current backend policy. + * @return Input configuration safe for UI and tray inspection. + */ + config::input_t configuration_snapshot() const; + /** * @brief Allocate or resume input state for a paired client. * @param mail Mailbox for the active transport session. @@ -106,7 +121,7 @@ namespace input { #ifdef SUNSHINE_TESTS namespace testing { /** - * @brief Replace the global platform input backend for a unit test. + * @brief Replace the fixture's platform input backend for a unit test. * * @param input Test-owned platform input backend. * @param service Fixture-owned host input service. diff --git a/src/logging.h b/src/logging.h index 72154980e..5581cbd7a 100644 --- a/src/logging.h +++ b/src/logging.h @@ -148,7 +148,6 @@ inline constexpr logging::logger_t fatal {5}; ///< Fatal. inline constexpr logging::logger_t tests {10}; ///< Automatic test output. #endif -#include "config.h" #include "stat_trackers.h" /** @@ -297,7 +296,7 @@ namespace logging { message(message), units(units), interval(interval_in_seconds), - enabled(config::sunshine.min_log_level <= severity.default_severity()) { + enabled(static_cast(severity.open_record())) { } /** diff --git a/src/main.cpp b/src/main.cpp index 19b167311..9cb9051f4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -32,61 +32,41 @@ #endif // local includes +#include "audio.h" #include "confighttp.h" #include "display_device.h" #include "entry_handler.h" #include "globals.h" #include "httpcommon.h" +#include "input.h" #include "logging.h" #include "main.h" #include "nvhttp.h" #include "platform/permissions.h" #include "process.h" +#include "rtsp.h" +#include "stream.h" #include "system_tray.h" #include "upnp.h" #include "video.h" using namespace std::literals; -std::map> signal_handlers; ///< Signal handlers. - -/** - * @brief Forward a POSIX signal to the registered Sunshine handler. - * - * @param sig Native signal number being handled. - */ -void on_signal_forwarder(int sig) { - signal_handlers.at(sig)(); -} - -/** - * @brief Register the handler invoked for a POSIX signal. - * - * @param sig Native signal number being handled. - * @param fn Signal handler function to install. - */ -template -void on_signal(int sig, FN &&fn) { - signal_handlers.emplace(sig, std::forward(fn)); - - std::signal(sig, on_signal_forwarder); -} - /** * @brief Immutable dispatch table for supported command-line subcommands. */ -const std::map> cmd_to_func { - {"creds"sv, [](const char *name, int argc, char **argv) { - return args::creds(name, argc, argv); +const std::map> cmd_to_func { + {"creds"sv, [](const config::settings_t &settings, const char *name, int argc, char **argv) { + return args::creds(settings, name, argc, argv); }}, - {"help"sv, [](const char *name, int argc, char **argv) { + {"help"sv, [](const config::settings_t &settings, const char *name, int argc, char **argv) { return args::help(name); }}, - {"version"sv, [](const char *name, int argc, char **argv) { + {"version"sv, [](const config::settings_t &settings, const char *name, int argc, char **argv) { return args::version(); }}, #ifdef _WIN32 - {"restore-nvprefs-undo"sv, [](const char *name, int argc, char **argv) { + {"restore-nvprefs-undo"sv, [](const config::settings_t &settings, const char *name, int argc, char **argv) { return args::restore_nvprefs_undo(); }}, #endif @@ -103,6 +83,10 @@ const std::map(lParam); + SetWindowLongPtrA(hwnd, GWLP_USERDATA, reinterpret_cast(create->lpCreateParams)); + } switch (uMsg) { case WM_CLOSE: DestroyWindow(hwnd); @@ -114,7 +98,9 @@ LRESULT CALLBACK SessionMonitorWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, L { // Terminate ourselves with a blocking exit call std::cout << "Received WM_ENDSESSION"sv << std::endl; - lifetime::exit_sunshine(0, false); + if (const auto controller = reinterpret_cast(GetWindowLongPtrA(hwnd, GWLP_USERDATA))) { + controller->exit_sunshine(0, true); + } return 0; } default: @@ -131,7 +117,7 @@ LRESULT CALLBACK SessionMonitorWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, L WINAPI BOOL ConsoleCtrlHandler(DWORD type) { if (type == CTRL_CLOSE_EVENT) { BOOST_LOG(info) << "Console closed handler called"; - lifetime::exit_sunshine(0, false); + lifetime::signal_guard_t::native_exit(0, false); } return FALSE; } @@ -146,14 +132,15 @@ constexpr bool tray_is_enabled = false; /** * @brief Run the main event loop until Sunshine is asked to exit. * + * @param settings Application settings used by the event loop. * @param shutdown_event Shutdown event. */ -void mainThreadLoop(const std::shared_ptr> &shutdown_event) { +void mainThreadLoop(const config::settings_t &settings, const std::shared_ptr> &shutdown_event) { bool run_loop = false; // Conditions that would require the main thread event loop #ifndef _WIN32 - run_loop = tray_is_enabled && config::sunshine.system_tray; // On Windows, tray runs in separate thread, so no main loop needed for tray + run_loop = tray_is_enabled && settings.sunshine.system_tray; // On Windows, tray runs in separate thread, so no main loop needed for tray #endif if (!run_loop) { @@ -226,7 +213,15 @@ int main(int argc, char *argv[]) { } #endif - lifetime::argv = argv; + runtime::infrastructure_t infrastructure {argv}; + auto &task_pool = infrastructure.scheduler(); + auto &lifetime = infrastructure.lifetime(); + const auto host_mail = infrastructure.mailbox(); + config::store_t configuration; + const auto &settings = configuration.values(); +#ifdef _WIN32 + auto &nvprefs_instance = infrastructure.preferences(); +#endif task_pool_util::TaskPool::task_id_t force_shutdown = nullptr; @@ -244,14 +239,12 @@ int main(int argc, char *argv[]) { std::locale::global(std::locale(std::locale(), new std::codecvt_utf8)); #pragma GCC diagnostic pop - mail::man = std::make_shared(); - // parse config file - if (config::parse(argc, argv)) { + if (configuration.parse(argc, argv)) { return 0; } - auto log_deinit_guard = logging::init(config::sunshine.min_log_level, config::sunshine.log_file); + auto log_deinit_guard = logging::init(settings.sunshine.min_log_level, settings.sunshine.log_file); if (!log_deinit_guard) { BOOST_LOG(error) << "Logging failed to initialize"sv; } @@ -265,13 +258,13 @@ int main(int argc, char *argv[]) { log_publisher_data(); // Log modified_config_settings - config::log_config_settings(config::modified_config_settings, false); - config::modified_config_settings.clear(); + configuration.log_config_settings(settings.modified_config_settings, false); + configuration.edit_startup().modified_config_settings.clear(); - if (!config::sunshine.cmd.name.empty()) { - auto fn = cmd_to_func.find(config::sunshine.cmd.name); + if (!settings.sunshine.cmd.name.empty()) { + auto fn = cmd_to_func.find(settings.sunshine.cmd.name); if (fn == std::end(cmd_to_func)) { - BOOST_LOG(fatal) << "Unknown command: "sv << config::sunshine.cmd.name; + BOOST_LOG(fatal) << "Unknown command: "sv << settings.sunshine.cmd.name; BOOST_LOG(info) << "Possible commands:"sv; for (auto &[key, _] : cmd_to_func) { @@ -281,19 +274,30 @@ int main(int argc, char *argv[]) { return 7; } - return fn->second(argv[0], config::sunshine.cmd.argc, config::sunshine.cmd.argv); + return fn->second(settings, argv[0], settings.sunshine.cmd.argc, settings.sunshine.cmd.argv); } #ifdef _WIN32 - config::select_all_gamepad_drivers_if_licensed(lvh::get_license_status().license.licensed()); + configuration.select_all_gamepad_drivers_if_licensed(lvh::get_license_status().license.licensed()); #endif // Adding guard here first as it also performs recovery after crash, // otherwise people could theoretically end up without display output. // It also should be destroyed before forced shutdown to expedite the cleanup. - auto display_device_deinit_guard = display_device::init(platf::appdata() / "display_device.state", config::video); - if (!display_device_deinit_guard) { - BOOST_LOG(error) << "Display device session failed to initialize"sv; + audio::service_t audios {settings, host_mail}; + display_device::manager_t displays; + displays.initialize(platf::appdata() / "display_device.state", settings.video, audios); + + http::state_t http_state {configuration}; + if (http_state.initialize()) { + BOOST_LOG(fatal) << "HTTP interface failed to initialize"sv; + +#ifdef _WIN32 + BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; + std::this_thread::sleep_for(10s); +#endif + + return -1; } #ifdef _WIN32 @@ -302,25 +306,79 @@ int main(int argc, char *argv[]) { // Restore global settings to the undo file left by improper termination of sunshine.exe nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); // Modify application settings for sunshine.exe - nvprefs_instance.modify_application_profile(); + nvprefs_instance.modify_application_profile(settings); // Modify global settings, undo file is produced in the process to restore after improper termination - nvprefs_instance.modify_global_profile(); + nvprefs_instance.modify_global_profile(settings); // Unload dynamic library to survive driver re-installation nvprefs_instance.unload(); } +#endif + + task_pool.start(1); + auto scheduler_guard = util::fail_guard([&task_pool]() { + task_pool.stop(); + task_pool.join(); + }); + + // Create signal handler after logging has been initialized + auto shutdown_event = host_mail->event(mail::shutdown); + lifetime::signal_guard_t signals {lifetime}; + signals.on_signal(SIGINT, [&force_shutdown, &displays, &task_pool, &settings, shutdown_event]() { + BOOST_LOG(info) << "Interrupt handler called"sv; + + auto task = []() { + BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; + logging::log_flush(); + lifetime::debug_trap(); + }; + force_shutdown = task_pool.pushDelayed(task, 10s).task_id; + + // Break out of the main loop + shutdown_event->raise(true); + + if (tray_is_enabled && settings.sunshine.system_tray) { + system_tray::end_tray(); + } + + displays.revert_configuration(); + }); + + signals.on_signal(SIGTERM, [&force_shutdown, &displays, &task_pool, &settings, shutdown_event]() { + BOOST_LOG(info) << "Terminate handler called"sv; + + auto task = []() { + BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; + logging::log_flush(); + lifetime::debug_trap(); + }; + force_shutdown = task_pool.pushDelayed(task, 10s).task_id; + + // Break out of the main loop + shutdown_event->raise(true); + + if (tray_is_enabled && settings.sunshine.system_tray) { + system_tray::end_tray(); + } + + displays.revert_configuration(); + }); + +#ifdef _WIN32 + // Terminate gracefully on Windows when console window is closed + SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); + auto console_handler_guard = util::fail_guard([]() { + SetConsoleCtrlHandler(ConsoleCtrlHandler, FALSE); + }); // Wait as long as possible to terminate Sunshine.exe during logoff/shutdown SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY); // We must create a hidden window to receive shutdown notifications since we load gdi32.dll std::promise session_monitor_hwnd_promise; auto session_monitor_hwnd_future = session_monitor_hwnd_promise.get_future(); - std::promise session_monitor_join_thread_promise; - auto session_monitor_join_thread_future = session_monitor_join_thread_promise.get_future(); std::jthread session_monitor_thread([&]() { platf::set_thread_name("session_monitor"); - session_monitor_join_thread_promise.set_value_at_thread_exit(); WNDCLASSA wnd_class {}; wnd_class.lpszClassName = "SunshineSessionMonitorClass"; @@ -343,7 +401,7 @@ int main(int argc, char *argv[]) { nullptr, nullptr, nullptr, - nullptr + &lifetime ); session_monitor_hwnd_promise.set_value(wnd); @@ -364,151 +422,92 @@ int main(int argc, char *argv[]) { }); auto session_monitor_join_thread_guard = util::fail_guard([&]() { - if (session_monitor_hwnd_future.wait_for(1s) == std::future_status::ready) { - if (HWND session_monitor_hwnd = session_monitor_hwnd_future.get()) { - PostMessage(session_monitor_hwnd, WM_CLOSE, 0, 0); - } - - if (session_monitor_join_thread_future.wait_for(1s) == std::future_status::ready) { - session_monitor_thread.join(); - return; - } else { - BOOST_LOG(warning) << "session_monitor_join_thread_future reached timeout"; - } - } else { - BOOST_LOG(warning) << "session_monitor_hwnd_future reached timeout"; + if (HWND session_monitor_hwnd = session_monitor_hwnd_future.get()) { + PostMessage(session_monitor_hwnd, WM_CLOSE, 0, 0); } - - session_monitor_thread.detach(); + session_monitor_thread.join(); }); - #endif - task_pool.start(1); - - // Create signal handler after logging has been initialized - auto shutdown_event = mail::man->event(mail::shutdown); - on_signal(SIGINT, [&force_shutdown, &display_device_deinit_guard, shutdown_event]() { - BOOST_LOG(info) << "Interrupt handler called"sv; - - auto task = []() { - BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; - logging::log_flush(); - lifetime::debug_trap(); - }; - force_shutdown = task_pool.pushDelayed(task, 10s).task_id; - - // Break out of the main loop - shutdown_event->raise(true); - - if (tray_is_enabled && config::sunshine.system_tray) { - system_tray::end_tray(); - } - - display_device_deinit_guard = nullptr; - }); - - on_signal(SIGTERM, [&force_shutdown, &display_device_deinit_guard, shutdown_event]() { - BOOST_LOG(info) << "Terminate handler called"sv; - - auto task = []() { - BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; - logging::log_flush(); - lifetime::debug_trap(); - }; - force_shutdown = task_pool.pushDelayed(task, 10s).task_id; - - // Break out of the main loop - shutdown_event->raise(true); - - if (tray_is_enabled && config::sunshine.system_tray) { - system_tray::end_tray(); - } - - display_device_deinit_guard = nullptr; - }); - -#ifdef _WIN32 - // Terminate gracefully on Windows when console window is closed - SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); -#endif - - proc::refresh(config::stream.file_apps); + input::service_t inputs {settings, task_pool, host_mail, infrastructure.cursor()}; + proc::proc_t processes {settings, displays, inputs}; + processes.refresh(settings.stream.file_apps); // If any of the following fail, we log an error and continue event though sunshine will not function correctly. // This allows access to the UI to fix configuration problems or view the logs. - auto platf_deinit_guard = platf::init(); - if (!platf_deinit_guard) { + platf::runtime_t platform {settings, host_mail, task_pool, lifetime, displays +#ifdef _WIN32 + , + nvprefs_instance +#endif + }; + if (!platform.initialize()) { BOOST_LOG(error) << "Platform failed to initialize"sv; } // Capture the pre-request state so access granted during this launch causes // one clean restart after every verifiable required permission is available. - const bool permission_restart_needed = !platf::required_permissions_granted(platf::get_permission_statuses()); + const bool permission_restart_needed = !platf::required_permissions_granted(platf::get_permission_statuses(settings)); #ifdef __APPLE__ - platf::request_startup_permissions(tray_is_enabled && config::sunshine.system_tray); + platf::request_startup_permissions(settings, tray_is_enabled && settings.sunshine.system_tray); #endif - auto proc_deinit_guard = proc::init(); - if (!proc_deinit_guard) { - BOOST_LOG(error) << "Proc failed to initialize"sv; - } - reed_solomon_init(); - auto input_deinit_guard = input::init(); + inputs.initialize(); - if (config::input.controller && input::probe_gamepads()) { + if (settings.input.controller && inputs.probe_gamepads()) { BOOST_LOG(warning) << "No gamepad input is available"sv; } - if (video::probe_encoders()) { + video::service_t videos {settings, host_mail, infrastructure.cursor(), displays, platform}; + if (videos.probe_encoders()) { BOOST_LOG(error) << "Video failed to find working encoder"sv; } - if (http::init()) { - BOOST_LOG(fatal) << "HTTP interface failed to initialize"sv; - -#ifdef _WIN32 - BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; - std::this_thread::sleep_for(10s); -#endif - - return -1; - } - std::unique_ptr mDNS; - auto sync_mDNS = std::async(std::launch::async, [&mDNS]() { - mDNS = platf::publish::start(); + auto sync_mDNS = std::async(std::launch::async, [&mDNS, &settings]() { + mDNS = platf::publish::start(settings); }); std::unique_ptr upnp_unmap; - auto sync_upnp = std::async(std::launch::async, [&upnp_unmap]() { - upnp_unmap = upnp::start(); + auto sync_upnp = std::async(std::launch::async, [&upnp_unmap, &settings, host_mail]() { + upnp_unmap = upnp::start(settings, host_mail); }); // FIXME: Temporary workaround: Simple-Web_server needs to be updated or replaced if (shutdown_event->peek()) { - return lifetime::desired_exit_code; + return lifetime.exit_code(); } - std::jthread httpThread {nvhttp::start}; - std::jthread configThread {confighttp::start}; - std::jthread rtspThread {rtsp_stream::start}; + stream::service_t streams {settings, host_mail, task_pool, inputs, videos, processes, displays, platform, audios}; + rtsp_stream::service_t rtsp {settings, streams, inputs, videos, host_mail}; + nvhttp::service_t gamestream {settings, http_state, processes, displays, videos, rtsp, host_mail}; + confighttp::service_t web {configuration, gamestream, http_state, processes, displays, inputs, rtsp, lifetime, host_mail}; + system_tray::application_binding_t tray_binding {settings, lifetime, displays}; + std::jthread httpThread {[&]() { + gamestream.start(); + }}; + std::jthread configThread {[&]() { + web.start(); + }}; + std::jthread rtspThread {[&]() { + rtsp.start(); + }}; #ifdef _WIN32 // If we're using the default port and GameStream is enabled, warn the user - if (config::sunshine.port == 47989 && is_gamestream_enabled()) { + if (settings.sunshine.port == 47989 && is_gamestream_enabled()) { BOOST_LOG(fatal) << "GameStream is still enabled in GeForce Experience! This *will* cause streaming problems with Sunshine!"sv; BOOST_LOG(fatal) << "Disable GameStream on the SHIELD tab in GeForce Experience or change the Port setting on the Advanced tab in the Sunshine Web UI."sv; } #endif - if (tray_is_enabled && config::sunshine.system_tray) { + if (tray_is_enabled && settings.sunshine.system_tray) { BOOST_LOG(info) << "Starting system tray"sv; #if defined(_WIN32) || defined(__APPLE__) - system_tray::prepare_tray_virtualhid_license(); - system_tray::prepare_tray_virtualhid_driver(); + system_tray::prepare_tray_virtualhid_license(settings); + system_tray::prepare_tray_virtualhid_driver(settings); #endif #ifdef _WIN32 // TODO: Windows has a weird bug where when running as a service and on the first Windows boot, @@ -525,19 +524,19 @@ int main(int argc, char *argv[]) { #ifdef __APPLE__ std::jthread macos_audio_permission_requester; if (!permission_restart_needed) { - macos_audio_permission_requester = std::jthread([]() { - platf::request_startup_system_audio_permission(); + macos_audio_permission_requester = std::jthread([&settings]() { + platf::request_startup_system_audio_permission(settings); }); } #endif std::jthread permission_watcher; if (permission_restart_needed) { - permission_watcher = std::jthread([](std::stop_token stop) { + permission_watcher = std::jthread([&lifetime, &settings](std::stop_token stop) { while (!stop.stop_requested()) { - if (platf::required_permissions_granted(platf::get_permission_statuses())) { + if (platf::required_permissions_granted(platf::get_permission_statuses(settings))) { BOOST_LOG(info) << "Required permissions granted; restarting Sunshine"sv; - platf::restart(); + platf::restart(lifetime); return; } std::this_thread::sleep_for(2s); @@ -545,7 +544,7 @@ int main(int argc, char *argv[]) { }); } - mainThreadLoop(shutdown_event); + mainThreadLoop(settings, shutdown_event); permission_watcher.request_stop(); if (permission_watcher.joinable()) { @@ -572,5 +571,5 @@ int main(int argc, char *argv[]) { } #endif - return lifetime::desired_exit_code; + return lifetime.exit_code(); } diff --git a/src/network.cpp b/src/network.cpp index a813a6010..190e226ea 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -126,13 +126,13 @@ namespace net { return BOTH; } - af_e get_effective_address_family(const af_e af) { - if (af != BOTH || config::sunshine.bind_address.empty()) { + af_e get_effective_address_family(const config::settings_t &settings, const af_e af) { + if (af != BOTH || settings.sunshine.bind_address.empty()) { return af; } boost::system::error_code ec; - const auto bind_address = ip::make_address(config::sunshine.bind_address, ec); + const auto bind_address = ip::make_address(settings.sunshine.bind_address, ec); return !ec && bind_address.is_v4() ? IPV4 : af; } @@ -148,10 +148,10 @@ namespace net { return "::"sv; } - std::string get_bind_address(const af_e af) { + std::string get_bind_address(const config::settings_t &settings, const af_e af) { // If bind_address is configured, use it - if (!config::sunshine.bind_address.empty()) { - return config::sunshine.bind_address; + if (!settings.sunshine.bind_address.empty()) { + return settings.sunshine.bind_address; } // Otherwise use the wildcard address for the given address family @@ -185,36 +185,36 @@ namespace net { } } - std::string get_bind_address_url_host() { - if (config::sunshine.bind_address.empty()) { + std::string get_bind_address_url_host(const config::settings_t &settings) { + if (settings.sunshine.bind_address.empty()) { return "localhost"; } boost::system::error_code ec; - const auto bind_address = ip::make_address(config::sunshine.bind_address, ec); - return ec ? config::sunshine.bind_address : addr_to_url_escaped_string(bind_address); + const auto bind_address = ip::make_address(settings.sunshine.bind_address, ec); + return ec ? settings.sunshine.bind_address : addr_to_url_escaped_string(bind_address); } - int encryption_mode_for_address(boost::asio::ip::address address) { + int encryption_mode_for_address(const config::settings_t &settings, boost::asio::ip::address address) { auto nettype = net::from_address(address.to_string()); if (nettype == net::net_e::PC || nettype == net::net_e::LAN) { - return config::stream.lan_encryption_mode; + return settings.stream.lan_encryption_mode; } else { - return config::stream.wan_encryption_mode; + return settings.stream.wan_encryption_mode; } } /** * @brief Create an ENet host with the requested address family. */ - host_t host_create(af_e af, ENetAddress &addr, std::uint16_t port) { + host_t host_create(const config::settings_t &settings, af_e af, ENetAddress &addr, std::uint16_t port) { static std::once_flag enet_init_flag; std::call_once(enet_init_flag, []() { enet_initialize(); }); - af = get_effective_address_family(af); - const auto bind_addr = net::get_bind_address(af); + af = get_effective_address_family(settings, af); + const auto bind_addr = net::get_bind_address(settings, af); enet_address_set_host(&addr, bind_addr.c_str()); enet_address_set_port(&addr, port); @@ -242,9 +242,9 @@ namespace net { enet_host_destroy(host); } - std::uint16_t map_port(int port) { + std::uint16_t map_port(const config::settings_t &settings, int port) { // calculate the port from the config port - auto mapped_port = (std::uint16_t) ((int) config::sunshine.port + port); + auto mapped_port = (std::uint16_t) ((int) settings.sunshine.port + port); // Ensure port is in the range of 1024-65535 if (mapped_port < 1024 || mapped_port > 65535) { diff --git a/src/network.h b/src/network.h index 137dcdef8..31e2dcf3f 100644 --- a/src/network.h +++ b/src/network.h @@ -3,6 +3,7 @@ * @brief Declarations for networking related functions. */ #pragma once +#include "config.h" // standard includes #include @@ -25,14 +26,15 @@ namespace net { /** * @brief Map a specified port based on the base port. + * @param settings Application settings containing the base port. * @param port The port to map as a difference from the base port. * @return The mapped port number. * @examples - * std::uint16_t mapped_port = net::map_port(1); + * std::uint16_t mapped_port = net::map_port(settings, 1); * @examples_end * @todo Ensure port is not already in use by another application. */ - std::uint16_t map_port(int port); + std::uint16_t map_port(const config::settings_t &settings, int port); /** * @brief Owning ENet host pointer released with `enet_host_destroy`. @@ -90,12 +92,13 @@ namespace net { /** * @brief Create an ENet host with the requested address family. * + * @param settings Application network configuration. * @param af Address family used for socket creation or binding. * @param addr Network address to bind, parse, or format. * @param port TCP or UDP port number. * @return ENet host bound to the requested address and port, or an empty handle on failure. */ - host_t host_create(af_e af, ENetAddress &addr, std::uint16_t port); + host_t host_create(const config::settings_t &settings, af_e af, ENetAddress &addr, std::uint16_t port); /** * @brief Convert a config address-family string to the matching enum. @@ -107,10 +110,11 @@ namespace net { /** * @brief Get the effective address family for listening sockets. * @details An IPv4 bind address narrows dual-stack mode to IPv4 so the socket protocol matches the bind endpoint. + * @param settings Application network configuration. * @param af Configured address family. * @return IPv4 for a valid IPv4 bind address in dual-stack mode, or `af` otherwise. */ - af_e get_effective_address_family(af_e af); + af_e get_effective_address_family(const config::settings_t &settings, af_e af); /** * @brief Get the wildcard binding address for a given address family. @@ -121,17 +125,19 @@ namespace net { /** * @brief Get the binding address to use based on config. + * @param settings Application network configuration. * @param af Address family. * @return The configured bind address or wildcard if not configured. */ - std::string get_bind_address(af_e af); + std::string get_bind_address(const config::settings_t &settings, af_e af); /** * @brief Get the configured bind address formatted as a URL host. * @details IPv6 addresses are enclosed in brackets. An empty bind address is represented as `localhost`. + * @param settings Application network configuration. * @return URL host for links to services bound by Sunshine. */ - std::string get_bind_address_url_host(); + std::string get_bind_address_url_host(const config::settings_t &settings); /** * @brief Convert an address to a normalized form. @@ -159,10 +165,11 @@ namespace net { /** * @brief Get the encryption mode for the given remote endpoint address. + * @param settings Application LAN and WAN encryption policies. * @param address The address used to look up the desired encryption mode. * @return The WAN or LAN encryption mode, based on the provided address. */ - int encryption_mode_for_address(boost::asio::ip::address address); + int encryption_mode_for_address(const config::settings_t &settings, boost::asio::ip::address address); /** * @brief Returns a string for use as the instance name for mDNS. diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 49f37a69e..46f27c8f7 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -69,6 +69,7 @@ namespace nvhttp { * @brief Private state and handlers belonging to one GameStream service. */ struct service_t::impl_t { + const config::settings_t &settings; ///< Stable application startup configuration. http::state_t &http_state; ///< Shared host identity. proc::proc_t &processes; ///< Shared application process owner. display_device::manager_t &displays; ///< Display recovery and configuration owner. @@ -80,6 +81,7 @@ namespace nvhttp { /** * @brief Bind the dependencies before any callbacks are registered. + * @param settings Application startup configuration. * @param http_state Shared HTTP identity. * @param processes Shared process owner. * @param displays Shared display owner. @@ -87,7 +89,8 @@ namespace nvhttp { * @param rtsp Pending launch and active-session owner. * @param host_mail Application shutdown mailbox. */ - impl_t(http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail): + impl_t(const config::settings_t &settings, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail): + settings {settings}, http_state {http_state}, processes {processes}, displays {displays}, @@ -312,11 +315,11 @@ namespace nvhttp { void save_state() { pt::ptree root; - if (fs::exists(config::nvhttp.file_state)) { + if (fs::exists(settings.nvhttp.file_state)) { try { - pt::read_json(config::nvhttp.file_state, root); + pt::read_json(settings.nvhttp.file_state, root); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what(); + BOOST_LOG(error) << "Couldn't read "sv << settings.nvhttp.file_state << ": "sv << e.what(); return; } } @@ -339,9 +342,9 @@ namespace nvhttp { root.add_child("root.named_devices"s, named_cert_nodes); try { - pt::write_json(config::nvhttp.file_state, root); + pt::write_json(settings.nvhttp.file_state, root); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't write "sv << config::nvhttp.file_state << ": "sv << e.what(); + BOOST_LOG(error) << "Couldn't write "sv << settings.nvhttp.file_state << ": "sv << e.what(); return; } } @@ -419,17 +422,17 @@ namespace nvhttp { * @brief Load state from its backing store. */ void load_state() { - if (!fs::exists(config::nvhttp.file_state)) { - BOOST_LOG(info) << "File "sv << config::nvhttp.file_state << " doesn't exist"sv; + if (!fs::exists(settings.nvhttp.file_state)) { + BOOST_LOG(info) << "File "sv << settings.nvhttp.file_state << " doesn't exist"sv; http_state.set_unique_id(uuid_util::uuid_t::generate().string()); return; } pt::ptree tree; try { - pt::read_json(config::nvhttp.file_state, tree); + pt::read_json(settings.nvhttp.file_state, tree); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what(); + BOOST_LOG(error) << "Couldn't read "sv << settings.nvhttp.file_state << ": "sv << e.what(); return; } @@ -515,7 +518,7 @@ namespace nvhttp { client_root.named_devices.emplace_back(std::move(named_cert)); rebuild_client_cert_chain(); - if (!config::sunshine.flags[config::flag::FRESH_STATE]) { + if (!settings.sunshine.flags[config::flag::FRESH_STATE]) { save_state(); } return uuid; @@ -653,6 +656,12 @@ namespace nvhttp { } } + /** + * @brief Insert a pending pairing request after expiring stale requests under the session lock. + * @param sess Pairing state to retain until approval or expiry. + * @param pairing_id Receives the generated approval identifier on success. + * @return Whether the request was added, already pending, or exceeds the pending limit. + */ pair_session_insert_e insert_pair_session(pair_session_t sess, std::string &pairing_id) { std::scoped_lock lock {map_id_sess_mutex()}; const auto now = std::chrono::steady_clock::now(); @@ -678,11 +687,19 @@ namespace nvhttp { return pair_session_insert_e::ADDED; } + /** + * @brief Expire pending pairing requests while holding the session lock. + * @param now Monotonic time used to evaluate completion deadlines. + */ void expire_pair_sessions(const std::chrono::steady_clock::time_point now) { std::scoped_lock lock {map_id_sess_mutex()}; expire_pair_sessions_unlocked(now); } + /** + * @brief Snapshot requests awaiting operator approval after expiring stale requests. + * @return Pending requests ordered from oldest to newest. + */ std::vector get_pending_pairings() { std::scoped_lock lock {map_id_sess_mutex()}; expire_pair_sessions_unlocked(std::chrono::steady_clock::now()); @@ -710,6 +727,11 @@ namespace nvhttp { return result; } + /** + * @brief Cancel an unapproved request and complete its pending response and waiter. + * @param pairing_id Approval identifier belonging to the request. + * @return Whether an unapproved request was found and cancelled. + */ bool cancel_pairing(const std::string_view pairing_id) { if (!is_valid_pairing_id(pairing_id)) { return false; @@ -735,6 +757,10 @@ namespace nvhttp { return true; } + /** + * @brief Release a client's temporary pairing state and complete its waiter as unsuccessful. + * @param sess Pairing session identifying the client to remove. + */ void remove_session(const pair_session_t &sess) { std::scoped_lock lock {map_id_sess_mutex()}; if (const auto sess_it = map_id_sess.find(sess.client.uniqueID); sess_it != map_id_sess.end()) { @@ -1006,7 +1032,7 @@ namespace nvhttp { sess.async_insert_pin.address = net::addr_to_normalized_string(request->remote_endpoint().address()); BOOST_LOG(debug) << sess.client.cert; - const bool pin_stdin = config::sunshine.flags[config::flag::PIN_STDIN]; + const bool pin_stdin = settings.sunshine.flags[config::flag::PIN_STDIN]; if (!pin_stdin) { sess.async_insert_pin.response = response; } @@ -1131,6 +1157,14 @@ namespace nvhttp { } } + /** + * @brief Approve one pending request and wait for the client to prove the supplied PIN. + * @param pairing_id Approval identifier belonging to the pending request. + * @param pin PIN supplied by the operator. + * @param name Friendly name to persist after successful pairing. + * @return Whether the client completed pairing before its bounded completion deadline. + * @note The session lock is released while waiting for the client's handshake. + */ bool pin(const std::string_view pairing_id, 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; @@ -1163,7 +1197,7 @@ namespace nvhttp { } completion = sess.completion; - completion_deadline = std::min(sess.async_insert_pin.expires_at, now + config::stream.ping_timeout); + completion_deadline = std::min(sess.async_insert_pin.expires_at, now + settings.stream.ping_timeout); } { @@ -1250,13 +1284,13 @@ namespace nvhttp { pt::ptree tree; tree.put("root..status_code", 200); - tree.put("root.hostname", config::nvhttp.sunshine_name); + tree.put("root.hostname", settings.nvhttp.sunshine_name); tree.put("root.appversion", VERSION); tree.put("root.GfeVersion", GFE_VERSION); tree.put("root.uniqueid", http_state.unique_id()); - tree.put("root.HttpsPort", net::map_port(PORT_HTTPS)); - tree.put("root.ExternalPort", net::map_port(PORT_HTTP)); + tree.put("root.HttpsPort", net::map_port(settings, PORT_HTTPS)); + tree.put("root.ExternalPort", net::map_port(settings, PORT_HTTP)); const auto capabilities = videos.capabilities(); tree.put("root.MaxLumaPixelsHEVC", capabilities.active_hevc_mode > 1 ? "1869449984" : "0"); @@ -1286,8 +1320,8 @@ namespace nvhttp { const uint32_t codec_mode_flags = get_codec_mode_flags(capabilities); tree.put("root.ServerCodecModeSupport", codec_mode_flags); - if (!config::nvhttp.external_ip.empty()) { - tree.put("root.ExternalIP", config::nvhttp.external_ip); + if (!settings.nvhttp.external_ip.empty()) { + tree.put("root.ExternalIP", settings.nvhttp.external_ip); } auto current_appid = processes.running(); @@ -1302,6 +1336,10 @@ namespace nvhttp { response->close_connection_after_response = true; } + /** + * @brief Snapshot paired client names, identities, and authorization state under the client lock. + * @return JSON array containing the paired clients. + */ nlohmann::json get_all_clients() { nlohmann::json named_cert_nodes = nlohmann::json::array(); std::lock_guard lock {client_auth_mutex()}; @@ -1324,7 +1362,7 @@ namespace nvhttp { */ void applist(resp_https_t response, req_https_t request) { print_req(request); - processes.refresh(config::stream.file_apps); + processes.refresh(settings.stream.file_apps); pt::ptree tree; @@ -1414,7 +1452,7 @@ namespace nvhttp { // We want to prepare display only if there are no active sessions at // the moment. This should be done before probing encoders as it could // change the active displays. - displays.configure_display(config::video, *launch_session); + displays.configure_display(settings.video, *launch_session); // Probe encoders again before streaming to ensure our chosen // encoder matches the active GPU (which could have changed @@ -1429,7 +1467,7 @@ namespace nvhttp { } } - auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); + auto encryption_mode = net::encryption_mode_for_address(settings, request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; @@ -1458,7 +1496,7 @@ namespace nvhttp { "{}{}:{}", launch_session->rtsp_url_scheme, net::addr_to_url_escaped_string(request->local_endpoint().address()), - static_cast(net::map_port(rtsp_stream::RTSP_SETUP_PORT)) + static_cast(net::map_port(settings, rtsp_stream::RTSP_SETUP_PORT)) ) ); tree.put("root.gamesession", 1); @@ -1526,7 +1564,7 @@ namespace nvhttp { // We want to prepare display only if there are no active sessions at // the moment. This should be done before probing encoders as it could // change the active displays. - displays.configure_display(config::video, *launch_session); + displays.configure_display(settings.video, *launch_session); // Probe encoders again before streaming to ensure our chosen // encoder matches the active GPU (which could have changed @@ -1541,7 +1579,7 @@ namespace nvhttp { } } - auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); + auto encryption_mode = net::encryption_mode_for_address(settings, request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; @@ -1559,7 +1597,7 @@ namespace nvhttp { "{}{}:{}", launch_session->rtsp_url_scheme, net::addr_to_url_escaped_string(request->local_endpoint().address()), - static_cast(net::map_port(rtsp_stream::RTSP_SETUP_PORT)) + static_cast(net::map_port(settings, rtsp_stream::RTSP_SETUP_PORT)) ) ); tree.put("root.resume", 1); @@ -1617,42 +1655,42 @@ namespace nvhttp { response->close_connection_after_response = true; } + /** + * @brief Retain the host credentials used during client pairing. + * @param pkey PEM-encoded host private key. + * @param cert PEM-encoded host certificate. + */ void setup(const std::string &pkey, const std::string &cert) { conf_intern.pkey = pkey; conf_intern.servercert = cert; } /** - * @brief Check whether a paired client certificate is allowed to connect and retrieve its friendly name. - * - * @param cert_pem PEM-encoded client certificate to look up. - * @return Pair of (bool enabled, string name) where "enabled" is True when the client certificate belongs to an - enabled device and "name" is the friendly client name set during pairing. + * @brief Load pairing state, serve GameStream HTTP requests, and wait for application shutdown. */ - void start() { platf::set_thread_name("nvhttp"); auto shutdown_event = host_mail->event(mail::shutdown); - auto port_http = net::map_port(PORT_HTTP); - auto port_https = net::map_port(PORT_HTTPS); - auto address_family = net::af_from_enum_string(config::sunshine.address_family); + auto port_http = net::map_port(settings, PORT_HTTP); + auto port_https = net::map_port(settings, PORT_HTTPS); + auto address_family = net::af_from_enum_string(settings.sunshine.address_family); - bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; + bool clean_slate = settings.sunshine.flags[config::flag::FRESH_STATE]; if (!clean_slate) { load_state(); } - auto pkey = file_handler::read_file(config::nvhttp.pkey.c_str()); - auto cert = file_handler::read_file(config::nvhttp.cert.c_str()); + auto pkey = file_handler::read_file(settings.nvhttp.pkey.c_str()); + auto cert = file_handler::read_file(settings.nvhttp.cert.c_str()); setup(pkey, cert); // resume doesn't always get the parameter "localAudioPlayMode" // launch will store it in host_audio bool host_audio {}; - https_server_t https_server {config::nvhttp.cert, config::nvhttp.pkey}; + https_server_t https_server {settings.nvhttp.cert, settings.nvhttp.pkey}; http_server_t http_server; // Verify certificates after establishing connection @@ -1743,7 +1781,7 @@ namespace nvhttp { }; https_server.config.reuse_address = true; - https_server.config.address = net::get_bind_address(address_family); + https_server.config.address = net::get_bind_address(settings, address_family); https_server.config.port = port_https; http_server.default_resource["GET"] = [this](auto response, auto request) { @@ -1757,7 +1795,7 @@ namespace nvhttp { }; http_server.config.reuse_address = true; - http_server.config.address = net::get_bind_address(address_family); + http_server.config.address = net::get_bind_address(settings, address_family); http_server.config.port = port_http; auto accept_and_run = [&](auto *http_server) { @@ -1789,6 +1827,9 @@ namespace nvhttp { tcp.join(); } + /** + * @brief Remove paired clients and persist the empty trust state under the client lock. + */ void erase_all_clients() { std::lock_guard lock {client_auth_mutex()}; client_root = {}; @@ -1796,6 +1837,11 @@ namespace nvhttp { save_state(); } + /** + * @brief Remove a paired client, rebuild certificate trust, and persist the updated state. + * @param uuid Identity of the client to remove. + * @return Whether the client entry was found and removed. + */ bool unpair_client(const std::string_view uuid) { std::lock_guard lock {client_auth_mutex()}; bool removed = false; @@ -1813,6 +1859,12 @@ namespace nvhttp { return removed; } + /** + * @brief Update authorization for a paired client and persist the rebuilt certificate trust. + * @param uuid Identity of the client to update. + * @param enabled Whether the client is allowed to connect. + * @return Whether the client entry was found and updated. + */ bool set_client_enabled(const std::string_view uuid, bool enabled) { std::lock_guard lock {client_auth_mutex()}; for (auto &named_cert : client_root.named_devices) { @@ -1827,7 +1879,9 @@ namespace nvhttp { } /** - * @brief Get cert by UUID. + * @brief Look up a paired client's certificate under the client lock. + * @param uuid Identity of the client to inspect. + * @return PEM-encoded certificate, or an empty string when the client is unknown. */ std::string get_cert_by_uuid(const std::string_view uuid) { std::lock_guard lock {client_auth_mutex()}; @@ -1840,7 +1894,10 @@ namespace nvhttp { } /** - * @brief Check whether a paired client certificate is allowed to connect and return its friendly name. + * @brief Look up authorization and the friendly name for a verified client certificate. + * @param cert_pem PEM-encoded client certificate to inspect. + * @return Stored authorization and name, or the legacy enabled result with an empty name when unknown. + * @note The caller holds the client authorization lock. */ std::pair get_client_status(const std::string_view cert_pem) { const client_t &client = client_root; @@ -1919,8 +1976,8 @@ namespace nvhttp { #endif }; - service_t::service_t(http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail): - impl {std::make_unique(http_state, processes, displays, videos, rtsp, std::move(host_mail))} { + service_t::service_t(const config::settings_t &settings, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail): + impl {std::make_unique(settings, http_state, processes, displays, videos, rtsp, std::move(host_mail))} { } service_t::~service_t() = default; diff --git a/src/nvhttp.h b/src/nvhttp.h index 2889a6398..09078159a 100644 --- a/src/nvhttp.h +++ b/src/nvhttp.h @@ -25,6 +25,10 @@ #include "crypto.h" #include "thread_safe.h" +namespace config { + struct settings_t; +} + namespace http { class state_t; } @@ -219,6 +223,7 @@ namespace nvhttp { public: /** * @brief Bind GameStream state to the application services it uses. + * @param settings Application startup configuration. * @param http_state Host identity and Web UI policy. * @param processes Application process owner. * @param displays Display settings owner. @@ -226,7 +231,7 @@ namespace nvhttp { * @param rtsp Pending launch and active session owner. * @param host_mail Application mailbox for shutdown coordination. */ - service_t(http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail); + service_t(const config::settings_t &settings, http::state_t &http_state, proc::proc_t &processes, display_device::manager_t &displays, video::service_t &videos, rtsp_stream::service_t &rtsp, safe::mail_t host_mail); /** * @brief Release pairing state and complete pending waiters after server threads stop. */ diff --git a/src/platform/common.h b/src/platform/common.h index 78d7add3d..40629f69b 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -928,14 +928,16 @@ namespace platf { /** * @brief Create the platform audio controller. * + * @param settings Immutable startup settings for this host. * @return Platform audio controller, or nullptr when audio control is unavailable. */ - std::unique_ptr audio_control(); + std::unique_ptr audio_control(const config::settings_t &settings); /** * @brief Get the display_t instance for the given hwdevice_type. * If display_name is empty, use the first monitor that's compatible you can find * If you require to use this parameter in a separate thread, make a copy of it. + * @param hwdevice_type Memory type requested by the encoder. * @param display_name The name of the monitor that SHOULD be displayed * @param config Stream configuration * @return The display_t instance based on hwdevice_type. @@ -1131,20 +1133,29 @@ namespace platf { */ class runtime_t { public: +#ifdef _WIN32 /** * @brief Bind the application services used by platform resources. + * @param settings Immutable startup settings. * @param mail Application mailbox. * @param scheduler Scheduler for deferred native input and capture work. * @param lifetime Application exit and restart controller. * @param displays Display configuration manager. * @param preferences NVIDIA preference manager on Windows. */ - runtime_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &displays -#ifdef _WIN32 - , - nvprefs::nvprefs_interface &preferences + runtime_t(const config::settings_t &settings, safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &displays, nvprefs::nvprefs_interface &preferences); +#endif +#if !defined(_WIN32) || defined(DOXYGEN) + /** + * @brief Bind the application services used by Unix platform resources. + * @param settings Immutable startup settings. + * @param mail Application mailbox. + * @param scheduler Scheduler for deferred native input and capture work. + * @param lifetime Application exit and restart controller. + * @param displays Display configuration manager. + */ + runtime_t(const config::settings_t &settings, safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &displays); #endif - ); /** * @brief Release platform resources after their consumers stop. */ @@ -1240,9 +1251,11 @@ namespace platf { /** * @brief Create the platform input backend for a stream. * + * @param settings Immutable host input configuration. + * @param scheduler Scheduler serializing platform input callbacks. * @return Platform-specific input backend for the active stream. */ - input_t input(thread_pool_util::ThreadPool &scheduler); + input_t input(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler); /** * @brief Get the current mouse position for platform input tests. * @@ -1404,23 +1417,30 @@ namespace platf { /** * @brief Get the supported platform capabilities to advertise to the client. + * @param settings Immutable startup settings for this host. * @return Capability flags. */ - platform_caps::caps_t get_capabilities(); + platform_caps::caps_t get_capabilities(const config::settings_t &settings); constexpr auto SERVICE_NAME = "Sunshine"; ///< mDNS service instance name advertised for GameStream discovery. constexpr auto SERVICE_TYPE = "_nvstream._tcp"; ///< mDNS service type advertised for GameStream discovery. namespace publish { - [[nodiscard]] std::unique_ptr start(); - } + /** + * @brief Advertise this host's configured HTTP service through mDNS. + * @param settings Immutable startup settings containing the host's listening port. + * @return Registration owner that removes the advertisement when destroyed, or null on failure. + */ + [[nodiscard]] std::unique_ptr start(const config::settings_t &settings); + } // namespace publish /** * @brief Initialize the platform-specific high precision timer. * + * @param settings Immutable startup settings for this host. * @return Cleanup handle for initialized platform resources, or null if none are needed. */ - [[nodiscard]] std::unique_ptr init(); + [[nodiscard]] std::unique_ptr init(const config::settings_t &settings); /** * @brief Returns the current computer name in UTF-8. @@ -1430,12 +1450,13 @@ namespace platf { /** * @brief Resolves the render device path to use for hardware encoding. - * @details If `config::video.adapter_name` is set, returns that. + * @details If the host's video adapter name is set, returns that. * Otherwise, auto-detects the GPU with a connected display via `find_render_node_with_display()`. * Falls back to `/dev/dri/renderD128` if detection fails. + * @param settings Immutable startup settings for this host. * @return Resolved render device path (may be empty on non-Linux platforms). */ - std::string resolve_render_device(); + std::string resolve_render_device(const config::settings_t &settings); /** * @brief Gets the supported gamepads for this platform backend. @@ -1443,7 +1464,7 @@ namespace platf { * @param input Pointer to the platform's `input_t` or `nullptr`. * @return Vector of gamepad options and status. */ - std::vector &supported_gamepads(input_t *input); + std::vector supported_gamepads(input_t *input); /** * @brief Platform timer object used for precise frame pacing. diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 43db87b10..c6a1a999b 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -330,6 +330,15 @@ namespace platf { }; public: + const config::settings_t &settings; ///< Configuration retained until this PulseAudio controller stops. + + /** + * @brief Bind the configured sink before creating PulseAudio resources. + * @param settings Host audio settings. + */ + explicit server_t(const config::settings_t &settings): + settings {settings} {} + loop_t loop; ///< PulseAudio threaded mainloop instance. ctx_t ctx; ///< PulseAudio threaded mainloop context. std::string requested_sink; ///< Requested sink. @@ -642,7 +651,7 @@ namespace platf { // An attempt was made to always use default to match the switching mechanic, // but this happens right after the swap so the default returned by PA was not // the new one just set! - auto sink_name = config::audio.sink; + auto sink_name = settings.audio.sink; if (sink_name.empty()) { sink_name = requested_sink; } @@ -716,8 +725,8 @@ namespace platf { /** * @brief Create the platform audio controller. */ - std::unique_ptr audio_control() { - auto audio = std::make_unique(); + std::unique_ptr audio_control(const config::settings_t &settings) { + auto audio = std::make_unique(settings); if (audio->init()) { return nullptr; diff --git a/src/platform/linux/input/virtualhid.cpp b/src/platform/linux/input/virtualhid.cpp index 88395ab45..ef46acd97 100644 --- a/src/platform/linux/input/virtualhid.cpp +++ b/src/platform/linux/input/virtualhid.cpp @@ -18,17 +18,17 @@ using namespace std::literals; namespace platf { - platform_caps::caps_t get_capabilities() { + platform_caps::caps_t get_capabilities(const config::settings_t &settings) { platform_caps::caps_t caps = 0; const auto runtime = virtualhid::create_runtime(); if (!runtime) { return caps; } - if (const auto &capabilities = runtime->capabilities(); config::input.native_pen_touch && (capabilities.supports_touchscreen || capabilities.supports_pen_tablet)) { + if (const auto &capabilities = runtime->capabilities(); settings.input.native_pen_touch && (capabilities.supports_touchscreen || capabilities.supports_pen_tablet)) { caps |= platform_caps::pen_touch; } - if (virtualhid::configured_gamepad_supports_controller_extensions()) { + if (virtualhid::configured_gamepad_supports_controller_extensions(settings)) { caps |= platform_caps::controller_touch; } @@ -66,8 +66,8 @@ namespace platf { #endif } - std::vector &supported_gamepads(input_t *input) { - static std::vector gamepads; + std::vector supported_gamepads(input_t *input) { + std::vector gamepads; if (!input || !input->get()) { gamepads = virtualhid::static_supported_gamepads(); return gamepads; diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 18166ee8a..19b5cb61c 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -416,6 +416,10 @@ namespace platf { std::vector card_descriptors; ///< Discovered card metadata. }; + /** + * @brief Create independent KMS discovery state for one platform runtime. + * @return Empty discovery owner retained by the runtime. + */ std::shared_ptr make_capture_state() { return std::make_shared(); } @@ -702,10 +706,12 @@ namespace platf { /** * @brief Open a DRM connector and cache its monitor metadata. * + * @param settings Immutable startup settings for this host. * @param path Filesystem path for the DRM device or resource. + * @param window_system Desktop protocol used to select DRM access behavior. * @return 0 on success; nonzero or negative platform status on failure. */ - int init(const char *path, window_system_e window_system) { + int init(const config::settings_t &settings, const char *path, window_system_e window_system) { fd.el = platf::kms::privileged_drm_worker::open_drm_card_fd_privileged(path); if (fd.el < 0) { return -1; @@ -740,7 +746,7 @@ namespace platf { #if defined(SUNSHINE_BUILD_X11) // We won't be able to capture the mouse cursor with KMS on non-atomic drivers, // so fall back to X11 if it's available and the user didn't explicitly force KMS. - if (window_system == window_system_e::X11 && config::video.capture != "kms") { + if (window_system == window_system_e::X11 && settings.video.capture != "kms") { BOOST_LOG(info) << "Avoiding KMS capture under X11 due to lack of atomic mode-setting"sv; return -1; } @@ -1120,6 +1126,7 @@ namespace platf { * @brief Map display name to monitor index * * @param display_name Name of the display to determine monitor index for (or monitor index string value) + * @param state Monitor inventory owned by this capture backend. * @return monitor's display index */ static int64_t map_display_name_to_monitor_index(const std::string_view &display_name, const capture_state_t &state) { @@ -1148,16 +1155,26 @@ namespace platf { /** * @brief Initialize common KMS display state for the requested memory type. * + * @param settings Immutable startup settings for this host. * @param mem_type Mem type. + * @param state Discovery snapshot copied into the capture resource. + * @param window_system Desktop protocol active when capture starts. + * @param hevc_mode Required HEVC capability for VAAPI device validation. */ - display_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): + display_t(const config::settings_t &settings, mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): platf::display_t(), - mem_type {mem_type}, + settings(settings), state(state), window_system(window_system), - hevc_mode(hevc_mode) { + hevc_mode(hevc_mode), + mem_type {mem_type} { } + const config::settings_t &settings; ///< Host encoder and capture settings. + capture_state_t state; ///< Immutable discovery snapshot for this capture resource. + window_system_e window_system; ///< Session type when this resource was created. + int hevc_mode; ///< Codec validation requirement for this resource. + /** * @brief Initialize the base KMS capture state for the selected monitor. * @@ -1165,10 +1182,6 @@ namespace platf { * @param config Configuration values to apply. * @return 0 on success; nonzero or negative platform status on failure. */ - capture_state_t state; ///< Immutable discovery snapshot for this capture resource. - window_system_e window_system; ///< Session type when this resource was created. - int hevc_mode; ///< Codec validation requirement for this resource. - int init(const std::string &display_name, const ::video::config_t &config) { delay = ::video::capture_frame_interval(config); @@ -1185,7 +1198,7 @@ namespace platf { } kms::card_t card; - if (card.init(entry.path().c_str(), window_system)) { + if (card.init(settings, entry.path().c_str(), window_system)) { continue; } @@ -1193,7 +1206,7 @@ namespace platf { // unless NVENC is selected manually by the user if (mem_type == mem_type_e::cuda && !card.is_nvidia()) { BOOST_LOG(debug) << file << " is not a CUDA device"sv; - if (config::video.encoder != "nvenc") { + if (settings.video.encoder != "nvenc") { continue; } } @@ -1767,10 +1780,14 @@ namespace platf { /** * @brief Initialize a KMS display backend that copies frames through RAM. * + * @param settings Immutable startup settings for this host. * @param mem_type Mem type. + * @param state Discovery snapshot copied into the capture resource. + * @param window_system Desktop protocol active when capture starts. + * @param hevc_mode Required HEVC capability for VAAPI device validation. */ - display_ram_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): - display_t(mem_type, state, window_system, hevc_mode) { + display_ram_t(const config::settings_t &settings, mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): + display_t(settings, mem_type, state, window_system, hevc_mode) { } /** @@ -1855,7 +1872,7 @@ namespace platf { std::unique_ptr make_avcodec_encode_device(pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, false); + return va::make_avcodec_encode_device(settings, width, height, false); } #endif @@ -2012,10 +2029,14 @@ namespace platf { /** * @brief Initialize a KMS display backend that exports frames as GPU resources. * + * @param settings Immutable startup settings for this host. * @param mem_type Mem type. + * @param state Discovery snapshot copied into the capture resource. + * @param window_system Desktop protocol active when capture starts. + * @param hevc_mode Required HEVC capability for VAAPI device validation. */ - display_vram_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): - display_t(mem_type, state, window_system, hevc_mode) { + display_vram_t(const config::settings_t &settings, mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): + display_t(settings, mem_type, state, window_system, hevc_mode) { } /** @@ -2027,13 +2048,13 @@ namespace platf { std::unique_ptr make_avcodec_encode_device(pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, dup(card.render_fd.el), img_offset_x, img_offset_y, true); + return va::make_avcodec_encode_device(settings, width, height, dup(card.render_fd.el), img_offset_x, img_offset_y, true); } #endif #ifdef SUNSHINE_BUILD_VULKAN if (mem_type == mem_type_e::vulkan) { - return vk::make_avcodec_encode_device_vram(width, height, img_offset_x, img_offset_y); + return vk::make_avcodec_encode_device_vram(settings, width, height, img_offset_x, img_offset_y); } #endif @@ -2199,14 +2220,18 @@ namespace platf { /** * @brief Create a KMS display capture backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. * @param display_name Display name. * @param config Configuration values to apply. + * @param state Discovery snapshot copied into the capture resource. + * @param window_system Desktop protocol active when capture starts. + * @param hevc_mode Required HEVC capability for VAAPI device validation. * @return KMS display backend, or nullptr when initialization fails. */ - std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode) { + std::shared_ptr kms_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode) { if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda || hwdevice_type == mem_type_e::vulkan) { - auto disp = std::make_shared(hwdevice_type, state, window_system, hevc_mode); + auto disp = std::make_shared(settings, hwdevice_type, state, window_system, hevc_mode); if (!disp->init(display_name, config)) { return disp; @@ -2215,7 +2240,7 @@ namespace platf { // In the case of failure, attempt the old method for VAAPI } - auto disp = std::make_shared(hwdevice_type, state, window_system, hevc_mode); + auto disp = std::make_shared(settings, hwdevice_type, state, window_system, hevc_mode); if (disp->init(display_name, config)) { return nullptr; @@ -2294,10 +2319,13 @@ namespace platf { /** * @brief Enumerate display names accepted by the KMS backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. + * @param state Runtime-owned cache updated with the current discovery snapshot. + * @param window_system Desktop protocol used to select DRM access behavior. * @return KMS display names, or an empty list when KMS capture is unavailable. */ - std::vector kms_display_names(mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system) { + std::vector kms_display_names(const config::settings_t &settings, mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system) { int count = 0; if (!fs::exists("/dev/dri")) { @@ -2325,7 +2353,7 @@ namespace platf { } kms::card_t card; - if (card.init(entry.path().c_str(), window_system)) { + if (card.init(settings, entry.path().c_str(), window_system)) { continue; } @@ -2333,7 +2361,7 @@ namespace platf { // unless NVENC is selected manually by the user if (hwdevice_type == mem_type_e::cuda && !card.is_nvidia()) { BOOST_LOG(debug) << file << " is not a CUDA device"sv; - if (config::video.encoder == "nvenc") { + if (settings.video.encoder == "nvenc") { BOOST_LOG(warning) << "Using NVENC with your display connected to a different GPU may not work properly!"sv; } else { continue; @@ -2370,7 +2398,7 @@ namespace platf { if (!fb->handles[0]) { BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; #if defined(SUNSHINE_BUILD_FLATPAK) || defined(SUNSHINE_BUILD_APPIMAGE) - BOOST_LOG((config::video.capture == "kms") ? fatal : error) + BOOST_LOG((settings.video.capture == "kms") ? fatal : error) << "AppImage and Flatpak do not support KMS capture. Use another capture method."sv; #endif break; diff --git a/src/platform/linux/kwingrab.cpp b/src/platform/linux/kwingrab.cpp index f7c3b08c7..5bb1f0e41 100644 --- a/src/platform/linux/kwingrab.cpp +++ b/src/platform/linux/kwingrab.cpp @@ -534,7 +534,7 @@ namespace kwin { kde_output_order_v1_add_listener(self->kde_output_order, &output_order_listener, self); BOOST_LOG(debug) << "[kwingrab] bound kde_output_order_v1 version "sv << bind_ver; } else if (!std::strcmp(interface, zkde_screencast_unstable_v1_interface.name)) { - // Bind version 1 to 6 — We use stream_output from v1 for node_id (deprecated but good as a fall-back) + // Bind version 1 to 6 — We use stream_output from v1 for node_id (deprecated but good as a fall-back) // but also try to get the newer (re-use safe) pipewire objectserial from v6 uint32_t bind_ver = std::min(version, static_cast(6)); self->kde_screencast_v1_ = static_cast( @@ -675,6 +675,16 @@ namespace kwin { */ class kwin_t: public pipewire::pipewire_display_t { public: + using pipewire::pipewire_display_t::pipewire_display_t; ///< Construct with host codec policy. + + /** + * @brief Start the selected KWin screencast and expose its PipeWire stream. + * @param display_name Selected KWin output name. + * @param out_pipewire_fd Set to -1 to connect to the local PipeWire core. + * @param out_pipewire_node Resulting capture node identifier. + * @param out_pipewire_objectserial Resulting capture object serial. + * @return Zero when the stream is ready, or -1 on failure. + */ int configure_stream(const std::string &display_name, int &out_pipewire_fd, uint32_t &out_pipewire_node, uint64_t &out_pipewire_objectserial) override { screencast = std::make_unique(); if (screencast->init(true) < 0) { @@ -709,18 +719,19 @@ namespace platf { /** * @brief Create a KWin screencast display backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. * @param display_name Display name. * @param config Configuration values to apply. * @return KWin/PipeWire display backend, or nullptr when initialization fails. */ - std::shared_ptr kwin_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { + std::shared_ptr kwin_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (!pipewire::pipewire_display_t::init_pipewire_and_check_hwdevice_type(hwdevice_type)) { BOOST_LOG(error) << "[kwingrab] Could not initialize pipewire-based display with the given hw device type."sv; return nullptr; } - auto display = std::make_shared(); + auto display = std::make_shared(settings); if (display->init(hwdevice_type, display_name, config)) { return nullptr; } diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index c4686e3d2..d00f794a5 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -152,13 +152,13 @@ namespace dyn { } // namespace dyn namespace platf { - std::vector get_permission_statuses() { + std::vector get_permission_statuses(const config::settings_t &settings) { // Match libvirtualhid's device paths and its read/write access check. bool input_access = access("/dev/uinput", R_OK | W_OK) == 0; #ifndef __FreeBSD__ input_access = input_access || access("/dev/input/uinput", R_OK | W_OK) == 0; #endif - return {{"input", input_access ? "granted" : "denied", config::input.keyboard || config::input.mouse || config::input.controller, true}}; + return {{"input", input_access ? "granted" : "denied", settings.input.keyboard || settings.input.mouse || settings.input.controller, true}}; } bool request_permission(std::string_view id) { @@ -632,6 +632,7 @@ namespace platf { /** * @brief Restart the Sunshine process through the platform launcher. + * @param lifetime Application controller that schedules the restart after cleanup. */ void restart(lifetime::controller_t &lifetime) { // Gracefully clean up and restart ourselves instead of exiting @@ -1044,13 +1045,17 @@ namespace platf { * @brief Own capture discovery and deferred portal work for one host. */ struct runtime_t::impl_t { + const config::settings_t &settings; ///< Immutable settings for this platform owner. + /** * @brief Bind narrow host dependencies. + * @param settings Immutable startup settings for this host. * @param mail Host mailbox. * @param scheduler Host scheduler. * @param lifetime Exit controller. */ - impl_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime): + impl_t(const config::settings_t &settings, safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime): + settings(settings), mail(std::move(mail)), scheduler(scheduler), lifetime(lifetime) {} @@ -1129,6 +1134,7 @@ namespace platf { /** * @brief Apply Linux socket priority and DSCP QoS settings for scoped cleanup. * + * @param count Shared number of active socket-priority scopes for this host. * @param sockfd Native socket descriptor whose options are updated. * @param options Request options or socket options to apply. */ @@ -1255,12 +1261,13 @@ namespace platf { /** * @brief Create a Wayland display capture backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. * @param display_name Display name. * @param config Configuration values to apply. * @return Display backend, or nullptr when Wayland capture initialization fails. */ - std::shared_ptr wl_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + std::shared_ptr wl_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); /** * @brief Check whether Wayland capture is available for the current session. @@ -1273,17 +1280,17 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_DRM - std::vector kms_display_names(mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system); - std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode); + std::vector kms_display_names(const config::settings_t &settings, mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system); + std::shared_ptr kms_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode); bool runtime_t::impl_t::verify_kms() { - return !kms_display_names(mem_type_e::unknown, *kms_state, window_system).empty(); + return !kms_display_names(settings, mem_type_e::unknown, *kms_state, window_system).empty(); } #endif #ifdef SUNSHINE_BUILD_X11 std::vector x11_display_names(); - std::shared_ptr x11_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, thread_pool_util::ThreadPool &scheduler); + std::shared_ptr x11_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, thread_pool_util::ThreadPool &scheduler); bool runtime_t::impl_t::verify_x11() { return window_system == window_system_e::X11 && !x11_display_names().empty(); @@ -1292,7 +1299,7 @@ namespace platf { #ifdef SUNSHINE_BUILD_PORTAL std::vector portal_display_names(bool allow_start_timeout, safe::mail_t mail); - std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail); + std::shared_ptr portal_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail); /** * @brief Enumerates possible Portal probe responses. @@ -1371,7 +1378,7 @@ namespace platf { #ifdef SUNSHINE_BUILD_KWIN std::vector kwin_display_names(); - std::shared_ptr kwin_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + std::shared_ptr kwin_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); bool verify_kwin() { return !kwin_display_names().empty(); @@ -1395,7 +1402,7 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { - return kms_display_names(hwdevice_type, *kms_state, window_system); + return kms_display_names(settings, hwdevice_type, *kms_state, window_system); } #endif #ifdef SUNSHINE_BUILD_X11 @@ -1417,15 +1424,15 @@ namespace platf { } /** - * @brief Report whether encoder backends should be probed again before streaming. + * @brief Report whether a render-node change requires another encoder probe. * - * @return Always `true` because Linux GPU changes are not tracked by this backend. + * @return Whether the configured render node differs from the previous probe. */ bool runtime_t::impl_t::needs_encoder_reenumeration() { // Only re-probe if the GPU render device changed (hotplug, driver reload). // Full re-probing on every reconnect leaks ~20 MB due to FFmpeg CBS // allocations during HEVC/AV1 codec validation. - auto current = platf::resolve_render_device(); + auto current = platf::resolve_render_device(settings); if (current == last_render_device) { return false; } @@ -1440,7 +1447,7 @@ namespace platf { #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { BOOST_LOG(info) << "Screencasting with KMS"sv; - return kms_display(hwdevice_type, display_name, config, *kms_state, window_system, hevc_mode); + return kms_display(settings, hwdevice_type, display_name, config, *kms_state, window_system, hevc_mode); } #endif @@ -1459,25 +1466,25 @@ namespace platf { #ifdef SUNSHINE_BUILD_WAYLAND if (sources[source::WAYLAND]) { BOOST_LOG(info) << "Screencasting with Wayland's protocol"sv; - return wl_display(hwdevice_type, display_name, config); + return wl_display(settings, hwdevice_type, display_name, config); } #endif #ifdef SUNSHINE_BUILD_X11 if (sources[source::X11]) { BOOST_LOG(info) << "Screencasting with X11"sv; - return x11_display(hwdevice_type, display_name, config, scheduler); + return x11_display(settings, hwdevice_type, display_name, config, scheduler); } #endif #ifdef SUNSHINE_BUILD_PORTAL if (sources[source::PORTAL]) { BOOST_LOG(info) << "Screencasting with XDG portal"sv; - return portal_display(hwdevice_type, display_name, config, mail); + return portal_display(settings, hwdevice_type, display_name, config, mail); } #endif #ifdef SUNSHINE_BUILD_KWIN if (sources[source::KWIN]) { BOOST_LOG(info) << "Screencasting with KWin ScreenCast"sv; - return kwin_display(hwdevice_type, display_name, config); + return kwin_display(settings, hwdevice_type, display_name, config); } #endif @@ -1500,7 +1507,7 @@ namespace platf { // only if the user explicitly selects Vulkan so that the autoprobe path will select VAAPI on // such systems. // Ref: https://gitlab.freedesktop.org/mesa/mesa/-/work_items/16457 - if (config::video.encoder == "vulkan") { + if (settings.video.encoder == "vulkan") { // enable Vulkan video extensions for AMD RADV lizardbyte::common::set_env("RADV_PERFTEST", "video_encode"); // Above is deprecated on Mesa 26.1+ and replaced by (keep both to ensure best compatibility): @@ -1527,7 +1534,7 @@ namespace platf { #endif // Avoid mutating config directly if Portal needs to run in fallback capture mode. - std::string selected_capture = config::video.capture; + std::string selected_capture = settings.video.capture; // When Portal is explicitly selected, probe it first so other capture methods can be considered for fallback capture. #ifdef SUNSHINE_BUILD_PORTAL @@ -1568,7 +1575,7 @@ namespace platf { } #endif #ifdef SUNSHINE_BUILD_PORTAL - if (portal_available || (config::video.capture.empty() && sources.none() && verify_portal())) { + if (portal_available || (settings.video.capture.empty() && sources.none() && verify_portal())) { sources[source::PORTAL] = true; } #endif @@ -1658,9 +1665,9 @@ namespace platf { #endif } - std::string resolve_render_device() { - if (!config::video.adapter_name.empty()) { - return config::video.adapter_name; + std::string resolve_render_device(const config::settings_t &settings) { + if (!settings.video.adapter_name.empty()) { + return settings.video.adapter_name; } auto detected = find_render_node_with_display(); return detected.empty() ? "/dev/dri/renderD128" : detected; @@ -1735,8 +1742,8 @@ namespace platf { } // namespace platf namespace platf { - runtime_t::runtime_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &): - impl(std::make_shared(std::move(mail), scheduler, lifetime)) {} + runtime_t::runtime_t(const config::settings_t &settings, safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &): + impl(std::make_shared(settings, std::move(mail), scheduler, lifetime)) {} runtime_t::~runtime_t() = default; diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index edcc6b8df..ffb2dbc37 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -145,7 +145,7 @@ namespace platf { } } -#if defined(__linux__) && defined(SUNSHINE_BUILD_DRM) +#ifdef SUNSHINE_BUILD_DRM namespace kms { /** * @brief Runtime-owned KMS discovery cache, snapshotted by capture resources. @@ -156,6 +156,7 @@ namespace platf { * @return Independent discovery state. */ std::shared_ptr make_capture_state(); + #ifdef __linux__ /** * @brief Force-construct the DRM privileged worker thread while the calling * thread still holds CAP_SYS_ADMIN in CAP_PERMITTED. @@ -177,6 +178,7 @@ namespace platf { * @return A file descriptor on success, or `-1` on failure. */ int privileged_open_drm_card_fd(const char *path); + #endif } // namespace kms #endif } // namespace platf diff --git a/src/platform/linux/pipewire.cpp b/src/platform/linux/pipewire.cpp index 6ce9d3e21..855daee65 100644 --- a/src/platform/linux/pipewire.cpp +++ b/src/platform/linux/pipewire.cpp @@ -972,6 +972,15 @@ namespace pipewire { */ class pipewire_display_t: public platf::display_t { public: + /** + * @brief Bind host codec policy to a PipeWire capture. + * @param settings Host settings. + */ + explicit pipewire_display_t(const config::settings_t &settings): + settings(settings) {} + + const config::settings_t &settings; ///< Host codec policy. + /** * @brief Initialize pipewire and check hwdevice type. * @@ -1289,13 +1298,13 @@ namespace pipewire { std::unique_ptr make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == platf::mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, n_dmabuf_infos > 0); + return va::make_avcodec_encode_device(settings, width, height, n_dmabuf_infos > 0); } #endif #ifdef SUNSHINE_BUILD_VULKAN if (mem_type == platf::mem_type_e::vulkan && n_dmabuf_infos > 0) { - return vk::make_avcodec_encode_device_vram(width, height, 0, 0); + return vk::make_avcodec_encode_device_vram(settings, width, height, 0, 0); } #endif diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index b74a6135d..c81f3adc5 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -241,7 +241,7 @@ namespace portal { GVariant *response; ///< DBus response payload returned by the portal. guint subscription_id; ///< Subscription ID. std::string request_path; ///< For Request.Close() on cancellation. - GDBusConnection *conn; ///< Borrowed — owned by the calling dbus_t/portal_t. + GDBusConnection *conn; ///< Borrowed — owned by the calling dbus_t/portal_t. }; /** @@ -1012,9 +1012,11 @@ namespace portal { public: /** * @brief Bind portal response loops to their host. + * @param settings Immutable startup settings for this host. * @param mail Host mailbox. */ - explicit portal_t(safe::mail_t mail): + explicit portal_t(const config::settings_t &settings, safe::mail_t mail): + pipewire::pipewire_display_t(settings), dbus(std::move(mail)) {} int configure_stream(const std::string &display_name, int &out_pipewire_fd, uint32_t &out_pipewire_node, uint64_t &out_pipewire_object_serial [[maybe_unused]]) override { @@ -1104,19 +1106,21 @@ namespace platf { /** * @brief Create a portal-based display capture backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. * @param display_name Display name. * @param config Configuration values to apply. + * @param mail Host mailbox used to stop pending Portal response waits. * @return Display backend backed by xdg-desktop-portal and PipeWire, or nullptr. */ - std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail) { + std::shared_ptr portal_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail) { using enum platf::mem_type_e; if (!pipewire::pipewire_display_t::init_pipewire_and_check_hwdevice_type(hwdevice_type)) { BOOST_LOG(error) << "[portalgrab] Could not initialize pipewire-based display with the given hw device type."sv; return nullptr; } - auto portal = std::make_shared(std::move(mail)); + auto portal = std::make_shared(settings, std::move(mail)); if (portal->init(hwdevice_type, display_name, config)) { return nullptr; } @@ -1128,6 +1132,7 @@ namespace platf { * @brief Enumerate capture targets available through xdg-desktop-portal. * * @param allow_start_timeout True if "Start" DBus call is allowed to time out. + * @param mail Host mailbox used to stop pending Portal response waits. * @return Portal display names, or an empty list when portal discovery fails. */ std::vector portal_display_names(bool allow_start_timeout, safe::mail_t mail) { diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index 6179a2231..0b0511588 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -280,8 +280,8 @@ namespace platf::publish { return publisher; } - [[nodiscard]] std::unique_ptr<::platf::deinit_t> start() { + [[nodiscard]] std::unique_ptr<::platf::deinit_t> start(const config::settings_t &settings) { platf::set_thread_name("publish::avahi"); - return start(avahi::api_t::load(), net::mdns_instance_name(platf::get_host_name()), net::map_port(nvhttp::PORT_HTTP)); + return start(avahi::api_t::load(), net::mdns_instance_name(platf::get_host_name()), net::map_port(settings, nvhttp::PORT_HTTP)); } } // namespace platf::publish diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index 3b5d65528..2394e831f 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -170,6 +170,15 @@ namespace va { */ class va_t: public platf::avcodec_encode_device_t { public: + /** + * @brief Bind immutable codec policy. + * @param settings Host settings. + */ + explicit va_t(const config::settings_t &settings): + settings(settings) {} + + const config::settings_t &settings; ///< Host policy for this encoder device. + /** * @brief Initialize VAAPI display, EGL, and conversion resources. * @@ -333,7 +342,7 @@ namespace va { if (status != VA_STATUS_SUCCESS || quality_attr.value == VA_ATTRIB_NOT_SUPPORTED) { quality_attr.value = 0; } - auto vaapi_quality = config::video.vaapi.vaapi_quality.value_or(0); + auto vaapi_quality = settings.video.vaapi.vaapi_quality.value_or(0); auto target_quality = 0; switch (vaapi_quality) { default: @@ -389,10 +398,10 @@ namespace va { // If a user-supplied rate control is detected, override the whitelist logic to allow // full user control of both the rate control and strict VBV settings. auto auto_whitelist = false; - auto rc_mode = config::video.vaapi.vaapi_rc_str; + auto rc_mode = settings.video.vaapi.vaapi_rc_str; auto rc_vbv = "with standard VBV size"; auto rc_whitelist = ""; - auto rc_val = config::video.vaapi.vaapi_rc.value_or(0); + auto rc_val = settings.video.vaapi.vaapi_rc.value_or(0); // Detect whitelisted configurations if ((vendor && std::string_view(vendor).contains("Intel") == true) || ctx->codec_id == AV_CODEC_ID_AV1) { @@ -416,7 +425,7 @@ namespace va { rc_val = VA_RC_CQP; } - if (config::video.vaapi.strict_rc_buffer || auto_whitelist) { + if (settings.video.vaapi.strict_rc_buffer || auto_whitelist) { ctx->rc_buffer_size = ctx->bit_rate * ctx->framerate.den / ctx->framerate.num; rc_vbv = "with single frame VBV size"; } @@ -427,8 +436,8 @@ namespace va { }); av_dict_set(options, "rc_mode", rc_mode.c_str(), 0); if (rc_val == VA_RC_CQP || rc_val == VA_RC_ICQ || rc_val == VA_RC_QVBR) { - BOOST_LOG(warning) << "[VAAPI] Applying QP for compatible rate control method (QP value: "sv << config::video.qp << ")"sv; - av_dict_set_int(options, "qp", config::video.qp, 0); + BOOST_LOG(warning) << "[VAAPI] Applying QP for compatible rate control method (QP value: "sv << settings.video.qp << ")"sv; + av_dict_set_int(options, "qp", settings.video.qp, 0); } BOOST_LOG(info) << "[VAAPI] Using "sv << rc_mode << " rate control "sv << rc_vbv << rc_whitelist; } @@ -547,6 +556,8 @@ namespace va { */ class va_ram_t: public va_t { public: + using va_t::va_t; ///< Construct with immutable codec policy. + /** * @brief Convert a captured VAAPI frame into system-memory encoder input. * @@ -566,6 +577,8 @@ namespace va { */ class va_vram_t: public va_t { public: + using va_t::va_t; ///< Construct with immutable codec policy. + /** * @brief Convert a captured VAAPI frame into GPU encoder input. * @@ -693,7 +706,7 @@ namespace va { va::display_t display {vaGetDisplayDRM(fd)}; if (!display) { - BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << platf::resolve_render_device(); + BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << platf::resolve_render_device(va->settings); return -1; } @@ -796,9 +809,9 @@ namespace va { /** * @brief Create AVCodec encode device. */ - std::unique_ptr make_avcodec_encode_device(int width, int height, file_t &&card, int offset_x, int offset_y, bool vram) { + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, file_t &&card, int offset_x, int offset_y, bool vram) { if (vram) { - auto egl = std::make_unique(); + auto egl = std::make_unique(settings); if (egl->init(width, height, std::move(card), offset_x, offset_y)) { return nullptr; } @@ -807,7 +820,7 @@ namespace va { } else { - auto egl = std::make_unique(); + auto egl = std::make_unique(settings); if (egl->init(width, height, std::move(card))) { return nullptr; } @@ -819,8 +832,8 @@ namespace va { /** * @brief Create AVCodec encode device. */ - std::unique_ptr make_avcodec_encode_device(int width, int height, int offset_x, int offset_y, bool vram) { - auto render_device = platf::resolve_render_device(); + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, int offset_x, int offset_y, bool vram) { + auto render_device = platf::resolve_render_device(settings); file_t file = ::open(render_device.c_str(), O_RDWR); // NOSONAR(cpp:S1874): `_sopen_s` not available if (file.el < 0) { @@ -830,10 +843,10 @@ namespace va { return nullptr; } - return make_avcodec_encode_device(width, height, std::move(file), offset_x, offset_y, vram); + return make_avcodec_encode_device(settings, width, height, std::move(file), offset_x, offset_y, vram); } - std::unique_ptr make_avcodec_encode_device(int width, int height, bool vram) { - return make_avcodec_encode_device(width, height, 0, 0, vram); + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, bool vram) { + return make_avcodec_encode_device(settings, width, height, 0, 0, vram); } } // namespace va diff --git a/src/platform/linux/vaapi.h b/src/platform/linux/vaapi.h index 5fafe9869..067357a5e 100644 --- a/src/platform/linux/vaapi.h +++ b/src/platform/linux/vaapi.h @@ -20,15 +20,17 @@ namespace va { * offset_y --> Vertical offset of the image in the texture * file_t card --> The file descriptor of the render device used for encoding * + * @param settings Immutable startup settings for this host. * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. * @param vram Whether the image should use GPU memory instead of system memory. * @return Constructed AVCodec encode device object. */ - std::unique_ptr make_avcodec_encode_device(int width, int height, bool vram); + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, bool vram); /** * @brief Create AVCodec encode device. * + * @param settings Immutable startup settings for this host. * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. * @param offset_x Offset x. @@ -36,10 +38,11 @@ namespace va { * @param vram Whether the image should use GPU memory instead of system memory. * @return Constructed AVCodec encode device object. */ - std::unique_ptr make_avcodec_encode_device(int width, int height, int offset_x, int offset_y, bool vram); + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, int offset_x, int offset_y, bool vram); /** * @brief Create AVCodec encode device. * + * @param settings Immutable startup settings for this host. * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. * @param card Video device path or render node used for VAAPI. @@ -48,7 +51,7 @@ namespace va { * @param vram Whether the image should use GPU memory instead of system memory. * @return Constructed AVCodec encode device object. */ - std::unique_ptr make_avcodec_encode_device(int width, int height, file_t &&card, int offset_x, int offset_y, bool vram); + std::unique_ptr make_avcodec_encode_device(const config::settings_t &settings, int width, int height, file_t &&card, int offset_x, int offset_y, bool vram); // Ensure the render device pointed to by fd is capable of encoding h264 with the hevc_mode configured /** diff --git a/src/platform/linux/vulkan_encode.cpp b/src/platform/linux/vulkan_encode.cpp index cc1b7972f..704b4ce85 100644 --- a/src/platform/linux/vulkan_encode.cpp +++ b/src/platform/linux/vulkan_encode.cpp @@ -1,7 +1,7 @@ /** * @file src/platform/linux/vulkan_encode.cpp * @brief Vulkan-native encoder: DMA-BUF -> Vulkan compute (RGB->YUV) -> Vulkan Video encode. - * No EGL/GL dependency — all GPU work stays in a single Vulkan queue. + * No EGL/GL dependency — all GPU work stays in a single Vulkan queue. */ #include #include @@ -116,7 +116,7 @@ namespace vk { * * @return Map of DRM format to supported modifiers, or empty map if query fails. */ - std::map> get_supported_capture_modifiers() { + std::map> get_supported_capture_modifiers(const config::settings_t &settings) { std::map> result; // Create temporary Vulkan instance @@ -143,7 +143,7 @@ namespace vk { vkEnumeratePhysicalDevices(inst, &count, devs.data()); // Find the device matching the render node that will be used for encoding - VkPhysicalDevice phys_dev = find_device_by_render_node(devs, platf::resolve_render_device()); + VkPhysicalDevice phys_dev = find_device_by_render_node(devs, platf::resolve_render_device(settings)); // Common capture formats (ARGB/XRGB variants) static const std::array, 4> formats_to_query = {{ @@ -363,9 +363,9 @@ namespace vk { return result; } - static int create_vulkan_hwdevice(AVBufferRef **hw_device_buf) { + static int create_vulkan_hwdevice(const config::settings_t &settings, AVBufferRef **hw_device_buf) { // Resolve render device path to Vulkan device index - if (auto render_path = platf::resolve_render_device(); render_path[0] == '/') { + if (auto render_path = platf::resolve_render_device(settings); render_path[0] == '/') { if (auto idx = find_vulkan_index_for_render_node(render_path.c_str()); !idx.empty() && av_hwdevice_ctx_create(hw_device_buf, AV_HWDEVICE_TYPE_VULKAN, idx.c_str(), nullptr, 0) >= 0) { return 0; } @@ -432,6 +432,15 @@ namespace vk { */ class vk_vram_t: public platf::avcodec_encode_device_t { public: + /** + * @brief Bind immutable Vulkan encoder policy. + * @param settings Host settings. + */ + explicit vk_vram_t(const config::settings_t &settings): + settings(settings) {} + + const config::settings_t &settings; ///< Host settings retained by hardware callbacks. + ~vk_vram_t() override { cleanup_pipeline(); } @@ -465,14 +474,14 @@ namespace vk { // Having rc_min_rate == rc_max_rate == bit_rate in VBR mode prevents the encoder from // undershooting on simple frames, which builds up headroom that causes large overshoots // on complex frames. - if (config::video.vk.rc_mode == 4) { + if (settings.video.vk.rc_mode == 4) { ctx->rc_min_rate = 0; } // Map quality preset to driver's quality range (same abstraction as VAAPI) // 1 = speed, 2 = balanced (default), 3 = quality // Note: Vulkan quality is 0 = fastest, higher = slower/better quality - int quality_preset = config::video.vk.quality; + int quality_preset = settings.video.vk.quality; if (quality_preset > 0 && ctx->hw_frames_ctx) { // Reuse FFmpeg's Vulkan instance and device instead of creating new ones auto *frames_ctx = (AVHWFramesContext *) ctx->hw_frames_ctx->data; @@ -633,7 +642,7 @@ namespace vk { // Import new DMA-BUF as VkImage when capture sequence changes if (descriptor.sequence == 0) { - // Dummy frame — clear the target + // Dummy frame — clear the target return 0; } @@ -1057,7 +1066,7 @@ namespace vk { } if (num_imgs == 1) { - // Single multiplane image — create plane views + // Single multiplane image — create plane views VkImageViewCreateInfo view_ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; view_ci.image = vk_frame->img[0]; view_ci.viewType = VK_IMAGE_VIEW_TYPE_2D; @@ -1111,7 +1120,7 @@ namespace vk { // Rotate to next command buffer. With CMD_RING_SIZE slots, the buffer // we're about to reuse was submitted CMD_RING_SIZE frames ago. - // At 60fps that's ~50ms for a <1ms compute dispatch — always complete. + // At 60fps that's ~50ms for a <1ms compute dispatch — always complete. // No fences, no semaphore waits, no CPU blocking. auto cmd_buf = cmd.ring[cmd.ring_idx]; cmd.ring_idx = (cmd.ring_idx + 1) % CMD_RING_SIZE; @@ -1249,7 +1258,7 @@ namespace vk { void destroy_src_image() { if (src.image) { - // Defer destruction — the GPU may still be using this image. + // Defer destruction — the GPU may still be using this image. // By the time we wrap around (4 frames later), it's guaranteed done. auto &slot = defer_ring[defer_idx]; if (slot.view) { @@ -1316,8 +1325,8 @@ namespace vk { } } - static int init_hw_device(platf::avcodec_encode_device_t *, AVBufferRef **hw_device_buf) { - return create_vulkan_hwdevice(hw_device_buf); + static int init_hw_device(platf::avcodec_encode_device_t *device, AVBufferRef **hw_device_buf) { + return create_vulkan_hwdevice(static_cast(device)->settings, hw_device_buf); } // Dimensions @@ -1355,7 +1364,7 @@ namespace vk { compute_pipeline_t compute = {}; - // Command submission — ring of buffers to avoid reuse while in-flight. + // Command submission — ring of buffers to avoid reuse while in-flight. // No CPU waits: by the time we wrap around, the old submission is long done. static constexpr int CMD_RING_SIZE = 3; @@ -1407,31 +1416,31 @@ namespace vk { // Free functions - int vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *, AVBufferRef **hw_device_buf) { - return create_vulkan_hwdevice(hw_device_buf); + int vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *device, AVBufferRef **hw_device_buf) { + return create_vulkan_hwdevice(static_cast(device)->settings, hw_device_buf); } - bool validate() { + bool validate(const config::settings_t &settings) { if (!avcodec_find_encoder_by_name("h264_vulkan") && !avcodec_find_encoder_by_name("hevc_vulkan")) { return false; } AVBufferRef *dev = nullptr; - if (create_vulkan_hwdevice(&dev) < 0) { + if (create_vulkan_hwdevice(settings, &dev) < 0) { return false; } av_buffer_unref(&dev); return true; } - std::unique_ptr make_avcodec_encode_device_vram(int w, int h, int offset_x, int offset_y) { - auto dev = std::make_unique(); + std::unique_ptr make_avcodec_encode_device_vram(const config::settings_t &settings, int w, int h, int offset_x, int offset_y) { + auto dev = std::make_unique(settings); if (dev->init(w, h, offset_x, offset_y) < 0) { return nullptr; } return dev; } - std::unique_ptr make_avcodec_encode_device_ram(int, int) { + std::unique_ptr make_avcodec_encode_device_ram(const config::settings_t &, int, int) { return nullptr; } diff --git a/src/platform/linux/vulkan_encode.h b/src/platform/linux/vulkan_encode.h index a8a0028bd..43d01e0ee 100644 --- a/src/platform/linux/vulkan_encode.h +++ b/src/platform/linux/vulkan_encode.h @@ -20,9 +20,10 @@ namespace vk { * This queries the Vulkan driver for modifiers it can import via VK_EXT_image_drm_format_modifier. * The returned map is keyed by DRM fourcc format code (e.g. DRM_FORMAT_ARGB8888). * + * @param settings Immutable startup settings for this host. * @return Map of DRM format to supported modifiers, or empty map if query fails. */ - std::map> get_supported_capture_modifiers(); + std::map> get_supported_capture_modifiers(const config::settings_t &settings); /** * @brief Initialize Vulkan hardware device for FFmpeg encoding. @@ -35,28 +36,31 @@ namespace vk { /** * @brief Create a Vulkan encode device for RAM capture. * + * @param settings Immutable startup settings for this host. * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. * @return Constructed AVCodec encode device ram object. */ - std::unique_ptr make_avcodec_encode_device_ram(int width, int height); + std::unique_ptr make_avcodec_encode_device_ram(const config::settings_t &settings, int width, int height); /** * @brief Create a Vulkan encode device for VRAM capture. * + * @param settings Immutable startup settings for this host. * @param width Frame or display width in pixels. * @param height Frame or display height in pixels. * @param offset_x Offset x. * @param offset_y Offset y. * @return Constructed AVCodec encode device VRAM object. */ - std::unique_ptr make_avcodec_encode_device_vram(int width, int height, int offset_x, int offset_y); + std::unique_ptr make_avcodec_encode_device_vram(const config::settings_t &settings, int width, int height, int offset_x, int offset_y); /** * @brief Check if FFmpeg Vulkan Video encoding is available. * + * @param settings Immutable startup settings for this host. * @return True when FFmpeg Vulkan Video encoding is available. */ - bool validate(); + bool validate(const config::settings_t &settings); } // namespace vk diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 46b5eefd3..01ec86f4d 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -311,7 +311,7 @@ namespace wl { return true; } - return gbm.init(platf::resolve_render_device(), gbm_device_accessors); + return gbm.init(platf::resolve_render_device(settings), gbm_device_accessors); } // Cleanup GBM @@ -358,7 +358,8 @@ namespace wl { return result; } - dmabuf_t::dmabuf_t(): + dmabuf_t::dmabuf_t(const config::settings_t &settings): + settings(settings), status {READY}, frames {}, current_frame {&frames[0]}, diff --git a/src/platform/linux/wayland.h b/src/platform/linux/wayland.h index 0eb4edc9e..391a56808 100644 --- a/src/platform/linux/wayland.h +++ b/src/platform/linux/wayland.h @@ -290,7 +290,11 @@ namespace wl { REINIT, ///< Reinitialize the frame }; - dmabuf_t(); + /** + * @brief Retain the host's render-device policy for DMA-BUF allocation. + * @param settings Immutable settings outliving this capture resource. + */ + explicit dmabuf_t(const config::settings_t &settings); ~dmabuf_t(); dmabuf_t(dmabuf_t &&) = delete; @@ -401,6 +405,7 @@ namespace wl { return current_frame == &frames[0] ? &frames[1] : &frames[0]; } + const config::settings_t &settings; ///< Host GPU selection retained by DMA-BUF callbacks. status_e status; ///< Current state of the active screencopy request. bool with_damage {false}; ///< Ask the compositor for the next frame that differs, rather than for a frame now. std::array frames; ///< Double-buffered frame descriptors. diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index 26aa14b8f..57aec2e08 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -100,6 +100,16 @@ namespace wl { */ class wlr_t: public platf::display_t { public: + /** + * @brief Bind host codec policy to this capture. + * @param settings Host settings. + */ + explicit wlr_t(const config::settings_t &settings): + settings(settings), + dmabuf(settings) {} + + const config::settings_t &settings; ///< Host codec policy. + /** * @brief Initialize Wayland screencopy capture for the selected output. * @@ -372,6 +382,8 @@ namespace wl { */ class wlr_ram_t: public wlr_t { public: + using wlr_t::wlr_t; ///< Construct with host codec policy. + /** * @brief Capture a display frame into the provided image object. * @@ -453,7 +465,7 @@ namespace wl { std::unique_ptr make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == platf::mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, false); + return va::make_avcodec_encode_device(settings, width, height, false); } #endif @@ -491,6 +503,8 @@ namespace wl { */ class wlr_vram_t: public wlr_t { public: + using wlr_t::wlr_t; ///< Construct with host codec policy. + /** * @brief Capture a display frame into the provided image object. * @@ -557,7 +571,7 @@ namespace wl { std::unique_ptr make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == platf::mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, 0, 0, true); + return va::make_avcodec_encode_device(settings, width, height, 0, 0, true); } #endif @@ -568,7 +582,7 @@ namespace wl { #endif if (mem_type == platf::mem_type_e::vulkan) { - return vk::make_avcodec_encode_device_vram(width, height, 0, 0); + return vk::make_avcodec_encode_device_vram(settings, width, height, 0, 0); } return std::make_unique(); @@ -592,7 +606,7 @@ namespace wl { */ void init_encoder_modifiers(platf::mem_type_e hwdevice_type) { if (hwdevice_type == platf::mem_type_e::vulkan) { - encoder_modifiers = vk::get_supported_capture_modifiers(); + encoder_modifiers = vk::get_supported_capture_modifiers(settings); if (!encoder_modifiers.empty()) { intersected_modifiers = wl::intersect_modifiers(interface.supported_modifiers, encoder_modifiers); if (intersected_modifiers.empty()) { @@ -613,14 +627,14 @@ namespace platf { /** * @brief Create a Wayland capture backend for the requested memory type. */ - std::shared_ptr wl_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { + std::shared_ptr wl_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda && hwdevice_type != platf::mem_type_e::vulkan) { BOOST_LOG(error) << "[wlgrab] Could not initialize display with the given hw device type."sv; return nullptr; } if (wl::use_vram_capture(hwdevice_type)) { - auto wlr = std::make_shared(); + auto wlr = std::make_shared(settings); if (wlr->init(hwdevice_type, display_name, config)) { return nullptr; } @@ -637,7 +651,7 @@ namespace platf { } #endif - auto wlr = std::make_shared(); + auto wlr = std::make_shared(settings); if (wlr->init(hwdevice_type, display_name, config)) { return nullptr; } diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 7aa0c57de..02894d283 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -455,6 +455,7 @@ namespace platf { * @brief X11 display, window, and attribute handles for capture. */ struct x11_attr_t: public display_t { + const config::settings_t &settings; ///< Host settings used by encode-device creation. std::chrono::nanoseconds delay; ///< Delay before the timer task becomes eligible to run. x11::xdisplay_t xdisplay; ///< X11 display connection used for capture. @@ -472,9 +473,11 @@ namespace platf { /** * @brief Open the X11 display and initialize capture attributes. * + * @param settings Immutable startup settings for this host. * @param mem_type Requested memory path for the capture backend. */ - x11_attr_t(mem_type_e mem_type): + x11_attr_t(const config::settings_t &settings, mem_type_e mem_type): + settings(settings), xdisplay {x11::OpenDisplay(nullptr)}, xwindow {}, xattr {}, @@ -646,7 +649,7 @@ namespace platf { std::unique_ptr make_avcodec_encode_device(pix_fmt_e pix_fmt) override { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == mem_type_e::vaapi) { - return va::make_avcodec_encode_device(width, height, false); + return va::make_avcodec_encode_device(settings, width, height, false); } #endif @@ -709,12 +712,14 @@ namespace platf { /** * @brief Open an X11 shared-memory capture backend. * + * @param settings Immutable startup settings for this host. * @param mem_type Requested memory path for the capture backend. * @param shm_api Validated API retained for the lifetime of shared-memory capture. + * @param scheduler Host scheduler for periodic display-attribute refreshes. */ - shm_attr_t(mem_type_e mem_type, std::shared_ptr shm_api, thread_pool_util::ThreadPool &scheduler): + shm_attr_t(const config::settings_t &settings, mem_type_e mem_type, std::shared_ptr shm_api, thread_pool_util::ThreadPool &scheduler): scheduler(scheduler), - x11_attr_t(mem_type), + x11_attr_t(settings, mem_type), shm_api {std::move(shm_api)}, shm_xdisplay {x11::OpenDisplay(nullptr)} { refresh_task_id = scheduler.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; @@ -882,12 +887,14 @@ namespace platf { /** * @brief Create an X11 display capture backend. * + * @param settings Immutable startup settings for this host. * @param hwdevice_type Hardware device type requested for capture or encode. * @param display_name Display name. * @param config Configuration values to apply. + * @param scheduler Host scheduler for periodic display-attribute refreshes. * @return X11 display backend, or nullptr when initialization fails. */ - std::shared_ptr x11_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, thread_pool_util::ThreadPool &scheduler) { + std::shared_ptr x11_display(const config::settings_t &settings, platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, thread_pool_util::ThreadPool &scheduler) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda) { BOOST_LOG(error) << "Could not initialize x11 display with the given hw device type"sv; return nullptr; @@ -901,7 +908,7 @@ namespace platf { } // Attempt to use shared memory X11 to avoid copying the frame - auto shm_disp = std::make_shared(hwdevice_type, std::move(shm_api), scheduler); + auto shm_disp = std::make_shared(settings, hwdevice_type, std::move(shm_api), scheduler); auto status = shm_disp->init(display_name, config); if (status > 0) { @@ -914,7 +921,7 @@ namespace platf { } // Fallback - auto x11_disp = std::make_shared(hwdevice_type); + auto x11_disp = std::make_shared(settings, hwdevice_type); if (x11_disp->init(display_name, config)) { return nullptr; } @@ -1056,7 +1063,7 @@ namespace platf { /** * @brief Release cursor context resources. * - * @param ctx Native context object used by the operation or callback. + * @param ctx Cursor context wrapping the X11 display connection to close. */ void freeCursorCtx(cursor_ctx_t::pointer ctx) { CloseDisplay((xdisplay_t::pointer) ctx); diff --git a/src/platform/macos/display.mm b/src/platform/macos/display.mm index 18ad67445..b9a8eac66 100644 --- a/src/platform/macos/display.mm +++ b/src/platform/macos/display.mm @@ -240,6 +240,14 @@ namespace platf { } }; + /** + * @brief Create an AVFoundation capture backend for the selected display. + * @param hwdevice_type Memory type requested by the encoder. + * @param display_name Stable display name or numeric capture selector. + * @param config Stream resolution and capture configuration. + * @param displays Host display manager used to resolve native display identifiers. + * @return Initialized capture backend, or null when capture is unavailable. + */ std::shared_ptr mac_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, display_device::manager_t &displays) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::videotoolbox) { BOOST_LOG(error) << "Could not initialize display with the given hw device type."sv; @@ -321,6 +329,12 @@ namespace platf { return display; } + /** + * @brief Enumerate display names accepted by AVFoundation capture. + * @param hwdevice_type Memory type requested by the encoder. + * @param displays Host display manager providing the current display descriptors. + * @return Display names, or an empty list when the memory type is unsupported. + */ std::vector mac_display_names(mem_type_e hwdevice_type, display_device::manager_t &displays) { std::vector display_names; if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::videotoolbox) { diff --git a/src/platform/macos/input.cpp b/src/platform/macos/input.cpp index dbc19cb27..67826a6bb 100644 --- a/src/platform/macos/input.cpp +++ b/src/platform/macos/input.cpp @@ -32,7 +32,7 @@ namespace platf { return util::point_t {current.x, current.y}; } - platform_caps::caps_t get_capabilities() { + platform_caps::caps_t get_capabilities(const config::settings_t &settings) { platform_caps::caps_t caps = 0; const auto runtime = virtualhid::create_runtime(); if (!runtime) { @@ -40,24 +40,25 @@ namespace platf { } const auto &capabilities = runtime->capabilities(); - if (config::input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && capabilities.supports_gamepad && lvh::get_license_status().license.licensed() && virtualhid::configured_gamepad_supports_controller_extensions()) { + if (settings.input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && capabilities.supports_gamepad && lvh::get_license_status().license.licensed() && virtualhid::configured_gamepad_supports_controller_extensions(settings)) { caps |= platform_caps::controller_touch; } - if (config::input.native_pen_touch && (capabilities.supports_touchscreen || capabilities.supports_pen_tablet)) { + if (settings.input.native_pen_touch && (capabilities.supports_touchscreen || capabilities.supports_pen_tablet)) { caps |= platform_caps::pen_touch; } return caps; } - std::vector &supported_gamepads(input_t *input) { - static std::vector gamepads; + std::vector supported_gamepads(input_t *input) { + std::vector gamepads; if (!input || !input->get()) { gamepads = virtualhid::static_supported_gamepads(); return gamepads; } - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + const auto &driver = virtualhid::get_input_context(*input).gamepad_driver; + if (driver == config::GAMEPAD_DRIVER_NONE) { gamepads.clear(); return gamepads; } diff --git a/src/platform/macos/microphone.mm b/src/platform/macos/microphone.mm index 72776e73d..9e66c58d2 100644 --- a/src/platform/macos/microphone.mm +++ b/src/platform/macos/microphone.mm @@ -67,6 +67,15 @@ namespace platf { * @brief macOS audio control state used to create microphone streams. */ struct macos_audio_control_t: public audio_control_t { + const config::settings_t &settings; ///< Configuration retained for microphone selection. + + /** + * @brief Bind the host audio sink policy without creating a microphone. + * @param settings Host audio configuration. + */ + explicit macos_audio_control_t(const config::settings_t &settings): + settings {settings} {} + AVCaptureDevice *audio_capture_device {}; ///< Audio capture device. public: @@ -100,7 +109,7 @@ namespace platf { mic->av_audio_capture.hostAudioEnabled = host_audio_enabled ? YES : NO; BOOST_LOG(debug) << "Set hostAudioEnabled to: "sv << (host_audio_enabled ? "YES" : "NO"); - if (config::audio.sink.empty()) { + if (settings.audio.sink.empty()) { // Use macOS system-wide audio tap BOOST_LOG(info) << "Using macOS system audio tap for capture."sv; BOOST_LOG(info) << "Sample rate: "sv << sample_rate << ", Frame size: "sv << frame_size << ", Channels: "sv << channels; @@ -111,7 +120,7 @@ namespace platf { } } else { // Use specified macOS audio sink - const char *audio_sink = config::audio.sink.c_str(); + const char *audio_sink = settings.audio.sink.c_str(); BOOST_LOG(info) << "Using configured audio sink "sv << audio_sink << " for capture."sv; if (!request_microphone_permission()) { @@ -155,7 +164,7 @@ namespace platf { } }; - std::unique_ptr audio_control() { - return std::make_unique(); + std::unique_ptr audio_control(const config::settings_t &settings) { + return std::make_unique(settings); } } // namespace platf diff --git a/src/platform/macos/misc.h b/src/platform/macos/misc.h index c3755d288..baae29a80 100644 --- a/src/platform/macos/misc.h +++ b/src/platform/macos/misc.h @@ -8,6 +8,7 @@ #include // local includes +#include "src/config.h" #include "src/platform/permissions.h" namespace platf { @@ -51,17 +52,19 @@ namespace platf { /** * @brief Request missing permissions needed at startup. * + * @param settings Immutable startup settings for this host. * @param notifications_enabled Whether the running build shows tray notifications. */ - void request_startup_permissions(bool notifications_enabled); + void request_startup_permissions(const config::settings_t &settings, bool notifications_enabled); /** * @brief Probe system audio once on startup when no custom sink is configured. * * The operating system has no passive tap authorization query. Later streams * may request access again if the user removes permission. + * @param settings Immutable startup settings for this host. */ - void request_startup_system_audio_permission(); + void request_startup_system_audio_permission(const config::settings_t &settings); /** * @brief Decide whether a one-time startup system audio probe is due. diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 8640b9881..759cc7aaf 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -210,7 +210,7 @@ namespace platf { return !has_custom_sink && !previously_requested; } - std::vector get_permission_statuses() { + std::vector get_permission_statuses(const config::settings_t &settings) { const auto microphone_authorization = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]; std::string microphone_status = "unknown"; switch (microphone_authorization) { @@ -238,9 +238,9 @@ namespace platf { std::vector statuses { {"screen_recording", screen_granted ? "granted" : "denied", true, true, true}, - {"input", input_granted ? "granted" : "denied", config::input.keyboard || config::input.mouse, true, true}, - {"microphone", microphone_status, !config::audio.sink.empty(), true, true}, - {"system_audio", "on_use", config::audio.sink.empty(), false, true}, + {"input", input_granted ? "granted" : "denied", settings.input.keyboard || settings.input.mouse, true, true}, + {"microphone", microphone_status, !settings.audio.sink.empty(), true, true}, + {"system_audio", "on_use", settings.audio.sink.empty(), false, true}, }; if (supports_local_network_privacy(static_cast([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion))) { statuses.push_back({"local_network", "on_use", true, false, true}); @@ -302,8 +302,8 @@ namespace platf { return false; } - void request_startup_permissions(bool notifications_enabled) { - for (const auto &permission : get_permission_statuses()) { + void request_startup_permissions(const config::settings_t &settings, bool notifications_enabled) { + for (const auto &permission : get_permission_statuses(settings)) { if (should_request_startup_permission(permission, notifications_enabled)) { if (permission.id == "screen_recording") { request_screen_recording(true); @@ -316,9 +316,9 @@ namespace platf { } } - void request_startup_system_audio_permission() { + void request_startup_system_audio_permission(const config::settings_t &settings) { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - if (!should_request_startup_system_audio_permission(!config::audio.sink.empty(), [defaults boolForKey:system_audio_requested_key])) { + if (!should_request_startup_system_audio_permission(!settings.audio.sink.empty(), [defaults boolForKey:system_audio_requested_key])) { return; } [defaults setBool:YES forKey:system_audio_requested_key]; @@ -335,7 +335,7 @@ namespace platf { return screen_capture_allowed; } - std::unique_ptr init() { + std::unique_ptr init(const config::settings_t &settings) { if (!screen_recording_granted()) { BOOST_LOG(error) << "No screen capture permission!"sv; BOOST_LOG(error) << "Please activate Sunshine in System Settings -> Privacy & Security -> Screen & System Audio Recording"sv; @@ -550,6 +550,7 @@ namespace platf { * signals (SIGINT, SIGTERM, SIGHUP) to the child and blocks in waitpid(). * This keeps the shell tracking the original PID as its foreground job, * preserving Ctrl+C and terminal log output. + * @param argv Arguments used to launch the replacement Sunshine process. */ void restart_on_exit(char **argv) { char executable[2048]; @@ -898,7 +899,7 @@ namespace platf { return std::make_unique(); } - std::string resolve_render_device() { + std::string resolve_render_device(const config::settings_t &settings) { return {}; } } // namespace platf @@ -950,28 +951,31 @@ namespace platf { * @brief Own the macOS platform initialization and explicit display manager. */ struct runtime_t::impl_t { + const config::settings_t &settings; ///< Immutable settings for this platform owner. display_device::manager_t &displays; ///< Display manager for discovery. std::unique_ptr initialization; ///< Native initialization lifetime. /** * @brief Bind display discovery. + * @param settings Immutable startup settings for this host. * @param displays Display manager. */ - explicit impl_t(display_device::manager_t &displays): + explicit impl_t(const config::settings_t &settings, display_device::manager_t &displays): + settings(settings), displays(displays) {} }; std::shared_ptr mac_display(mem_type_e type, const std::string &name, const video::config_t &config, display_device::manager_t &displays); std::vector mac_display_names(mem_type_e type, display_device::manager_t &displays); - runtime_t::runtime_t(safe::mail_t, thread_pool_util::ThreadPool &, lifetime::controller_t &, display_device::manager_t &displays): - impl(std::make_shared(displays)) {} + runtime_t::runtime_t(const config::settings_t &settings, safe::mail_t, thread_pool_util::ThreadPool &, lifetime::controller_t &, display_device::manager_t &displays): + impl(std::make_shared(settings, displays)) {} runtime_t::~runtime_t() = default; bool runtime_t::initialize() { if (!impl->initialization) { - impl->initialization = platf::init(); + impl->initialization = platf::init(impl->settings); } return static_cast(impl->initialization); } diff --git a/src/platform/macos/publish.cpp b/src/platform/macos/publish.cpp index edd830053..edd09eda7 100644 --- a/src/platform/macos/publish.cpp +++ b/src/platform/macos/publish.cpp @@ -97,11 +97,11 @@ namespace platf::publish { * our Sunshine service. Registration will occur asynchronously (unless it fails immediately, * which is probably only possible if the host machine is misconfigured). * - * @return Either `nullptr` (if the registration fails immediately) or a `uniqur_ptr`, + * @return Either `nullptr` (if the registration fails immediately) or a `unique_ptr`, * which will manage polling for a response from the mDNS service, and then, when * deconstructed, will deregister the service. */ - [[nodiscard]] std::unique_ptr<::platf::deinit_t> start() { + [[nodiscard]] std::unique_ptr<::platf::deinit_t> start(const config::settings_t &settings) { auto serviceRef = DNSServiceRef {}; const auto status = DNSServiceRegister( &serviceRef, @@ -111,7 +111,7 @@ namespace platf::publish { platf::SERVICE_TYPE, nullptr, // domain nullptr, // host - htons(net::map_port(nvhttp::PORT_HTTP)), + htons(net::map_port(settings, nvhttp::PORT_HTTP)), 0, // txtLen nullptr, // txtRecord registrationCallback, diff --git a/src/platform/permissions.h b/src/platform/permissions.h index b6705fd38..25d48476c 100644 --- a/src/platform/permissions.h +++ b/src/platform/permissions.h @@ -3,6 +3,7 @@ * @brief Cross-platform permission status and request interface. */ #pragma once +#include "src/config.h" // standard includes #include @@ -25,9 +26,10 @@ namespace platf { /** * @brief Query access needed by Sunshine on the current platform. * + * @param settings Immutable host configuration determining which permissions are required. * @return Permission status records for the Web UI. */ - std::vector get_permission_statuses(); + std::vector get_permission_statuses(const config::settings_t &settings); /** * @brief Determine whether all verifiable required permissions are granted. diff --git a/src/platform/virtualhid_input.cpp b/src/platform/virtualhid_input.cpp index 419e2efed..6df6ac09f 100644 --- a/src/platform/virtualhid_input.cpp +++ b/src/platform/virtualhid_input.cpp @@ -182,9 +182,15 @@ namespace platf::virtualhid { return gamepad_profiles[3]; // Xbox Series. } - const gamepad_profile_t &profile_for_metadata(const gamepad_arrival_t &metadata) { - if (config::input.gamepad != "auto"sv) { - return profile_for_name(config::input.gamepad); + /** + * @brief Select a configured or client-reported controller profile. + * @param settings Immutable host input configuration. + * @param metadata Client-reported controller type and capabilities. + * @return Profile selected for this controller. + */ + const gamepad_profile_t &profile_for_metadata(const config::settings_t &settings, const gamepad_arrival_t &metadata) { + if (settings.input.gamepad != "auto"sv) { + return profile_for_name(settings.input.gamepad); } if (metadata.type == LI_CTYPE_PS) { @@ -199,11 +205,11 @@ namespace platf::virtualhid { BOOST_LOG(info) << "Gamepad will be Xbox Series controller (auto-selected by client-reported type)"sv; return profile_for_name("xseries"sv); } - if (config::input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { + if (settings.input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { BOOST_LOG(info) << "Gamepad will be DualSense controller (auto-selected by motion sensor presence)"sv; return profile_for_name("ds5"sv); } - if (config::input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { + if (settings.input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { BOOST_LOG(info) << "Gamepad will be DualSense controller (auto-selected by touchpad presence)"sv; return profile_for_name("ds5"sv); } @@ -223,19 +229,34 @@ namespace platf::virtualhid { ); } - std::string gamepad_stable_id(const gamepad_id_t &id, const lvh::DeviceProfile &profile) { + /** + * @brief Generate a controller identity using the host's MAC policy. + * @param settings Immutable host input configuration. + * @param id Controller slot and client index. + * @param profile Virtual controller profile. + * @return Stable identifier or randomized private MAC address. + */ + std::string gamepad_stable_id(const config::settings_t &settings, const gamepad_id_t &id, const lvh::DeviceProfile &profile) { if (profile.gamepad_kind != lvh::GamepadProfileKind::dualshock4 && profile.gamepad_kind != lvh::GamepadProfileKind::dualsense) { return std::format("sunshine-gamepad-{}", id.globalIndex); } - if (config::input.virtualhid_randomize_mac || id.globalIndex < 0 || id.globalIndex > 255) { + if (settings.input.virtualhid_randomize_mac || id.globalIndex < 0 || id.globalIndex > 255) { return random_private_mac(); } return std::format("02:00:00:00:00:{:02x}", id.globalIndex); } - lvh::GamepadMetadata gamepad_metadata(const gamepad_id_t &id, const gamepad_arrival_t &metadata, const lvh::DeviceProfile &profile) { + /** + * @brief Build Virtual HID metadata for one client controller. + * @param settings Immutable host input configuration. + * @param id Controller slot and client index. + * @param metadata Client-reported controller features. + * @param profile Selected virtual controller profile. + * @return Device metadata used by the Virtual HID runtime. + */ + lvh::GamepadMetadata gamepad_metadata(const config::settings_t &settings, const gamepad_id_t &id, const gamepad_arrival_t &metadata, const lvh::DeviceProfile &profile) { lvh::GamepadMetadata result; result.global_index = id.globalIndex; result.client_relative_index = id.clientRelativeIndex; @@ -244,7 +265,7 @@ namespace platf::virtualhid { result.has_touchpad = metadata.capabilities & LI_CCAP_TOUCHPAD; result.has_rgb_led = metadata.capabilities & LI_CCAP_RGB_LED; result.has_battery = metadata.capabilities & LI_CCAP_BATTERY_STATE; - result.stable_id = gamepad_stable_id(id, profile); + result.stable_id = gamepad_stable_id(settings, id, profile); return result; } @@ -269,7 +290,14 @@ namespace platf::virtualhid { } } - lvh::GamepadState make_gamepad_state(const gamepad_state_t &state, const lvh::GamepadProfileSupport &support) { + /** + * @brief Translate controller input using this host's button policy. + * @param settings Immutable host input configuration. + * @param state Client button, stick, and trigger state. + * @param support Features supported by the virtual controller. + * @return State to submit to the Virtual HID adapter. + */ + lvh::GamepadState make_gamepad_state(const config::settings_t &settings, const gamepad_state_t &state, const lvh::GamepadProfileSupport &support) { using enum lvh::GamepadButton; lvh::GamepadState result; @@ -293,7 +321,7 @@ namespace platf::virtualhid { result.buttons.set(misc1, support.supports_misc1_button && (flags & MISC_BUTTON)); result.buttons.set(touchpad, support.supports_touchpad_button && (flags & TOUCHPAD_BUTTON)); - if (support.supports_touchpad_button && config::input.ds4_back_as_touchpad_click && configured_gamepad_supports_touchpad() && (flags & BACK)) { + if (support.supports_touchpad_button && settings.input.ds4_back_as_touchpad_click && configured_gamepad_supports_touchpad(settings) && (flags & BACK)) { result.buttons.set(touchpad); } @@ -370,7 +398,16 @@ namespace platf::virtualhid { }; } - lvh::KeyboardEvent keyboard_event(std::uint16_t modcode, bool release, std::uint8_t flags, bool extended) { + /** + * @brief Translate keyboard input using the host's scan-code preference. + * @param settings Immutable host input configuration. + * @param modcode Client key code. + * @param release Whether this event releases the key. + * @param flags Client key-code flags. + * @param extended Whether the key is an extended scan code. + * @return Event to submit to the Virtual HID keyboard. + */ + lvh::KeyboardEvent keyboard_event(const config::settings_t &settings, std::uint16_t modcode, bool release, std::uint8_t flags, bool extended) { lvh::KeyboardEvent event { .key_code = modcode, .pressed = !release, @@ -379,8 +416,9 @@ namespace platf::virtualhid { #ifdef _WIN32 event.uses_normalized_key_code = (static_cast(flags) & static_cast(SS_KBE_FLAG_NON_NORMALIZED)) == std::byte {}; - event.prefer_native_scan_code = config::input.always_send_scancodes; + event.prefer_native_scan_code = settings.input.always_send_scancodes; #else + (void) settings; (void) flags; #endif return event; @@ -510,10 +548,9 @@ namespace platf::virtualhid { } // namespace - input_context_t::input_context_t(): - input_context_t {lvh::BackendKind::platform_default} {} - - input_context_t::input_context_t(lvh::BackendKind backend): + input_context_t::input_context_t(const config::settings_t &settings, lvh::BackendKind backend): + settings {settings}, + gamepad_driver {settings.input.gamepad_driver}, runtime {create_runtime(backend)} { if (!runtime) { BOOST_LOG(warning) << "Unable to create libvirtualhid runtime"sv; @@ -697,10 +734,11 @@ namespace platf::virtualhid { return -1; } - const auto &selection = profile_for_metadata(metadata); + const auto &settings = context.settings.get(); + const auto &selection = profile_for_metadata(settings, metadata); auto profile = selection.profile(); profile.name = std::format("Sunshine {}", profile.name); - if (config::input.gamepad != "auto"sv) { + if (settings.input.gamepad != "auto"sv) { BOOST_LOG(info) << "Gamepad "sv << id.globalIndex << " will be "sv << profile.name << " (manual selection)"sv; } else { BOOST_LOG(info) << "Gamepad "sv << id.globalIndex << " will be "sv << profile.name; @@ -708,7 +746,7 @@ namespace platf::virtualhid { lvh::CreateGamepadOptions options; options.profile = profile; - options.metadata = gamepad_metadata(id, metadata, profile); + options.metadata = gamepad_metadata(settings, id, metadata, profile); auto created = lvh::GamepadStateAdapter::create(*context.runtime, options); if (!created) { log_failure("create libvirtualhid gamepad"sv, created.status); @@ -781,7 +819,7 @@ namespace platf::virtualhid { } auto &gamepad = context.gamepads[nr]; - auto updated_state = make_gamepad_state(state, gamepad->adapter->support()); + auto updated_state = make_gamepad_state(context.settings.get(), state, gamepad->adapter->support()); const auto &cached_state = gamepad->adapter->state(); updated_state.acceleration = cached_state.acceleration; updated_state.gyroscope = cached_state.gyroscope; @@ -940,7 +978,7 @@ namespace platf::virtualhid { void keyboard_update(input_context_t &context, std::uint16_t modcode, bool release, std::uint8_t flags, bool extended) { if (context.keyboard) { - log_failure("submit libvirtualhid keyboard input"sv, context.keyboard->submit(keyboard_event(modcode, release, flags, extended))); + log_failure("submit libvirtualhid keyboard input"sv, context.keyboard->submit(keyboard_event(context.settings.get(), modcode, release, flags, extended))); } } @@ -1075,21 +1113,21 @@ namespace platf::virtualhid { log_failure("submit libvirtualhid pen state"sv, context.pen->place_tool(state)); } - bool configured_gamepad_supports_touchpad() { - if (config::input.gamepad == "auto"sv) { + bool configured_gamepad_supports_touchpad(const config::settings_t &settings) { + if (settings.input.gamepad == "auto"sv) { return true; } - const auto profile = profile_for_name(config::input.gamepad).profile(); + const auto profile = profile_for_name(settings.input.gamepad).profile(); return lvh::gamepad_profile_support(profile).supports_touchpad; } - bool configured_gamepad_supports_controller_extensions() { - if (config::input.gamepad == "auto"sv) { + bool configured_gamepad_supports_controller_extensions(const config::settings_t &settings) { + if (settings.input.gamepad == "auto"sv) { return true; } - const auto profile = profile_for_name(config::input.gamepad).profile(); + const auto profile = profile_for_name(settings.input.gamepad).profile(); const auto &support = lvh::gamepad_profile_support(profile); return support.supports_touchpad || support.supports_motion; } @@ -1103,6 +1141,13 @@ namespace platf { * @brief Global libvirtualhid devices shared by clients. */ struct input_raw_t { + /** + * @brief Construct virtual devices using this host's startup settings. + * @param settings Immutable host configuration. + */ + explicit input_raw_t(const config::settings_t &settings): + virtualhid {settings} {} + virtualhid::input_context_t virtualhid; ///< libvirtualhid input context. }; @@ -1125,9 +1170,9 @@ namespace platf { } // namespace - input_t input(thread_pool_util::ThreadPool &scheduler) { + input_t input(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler) { (void) scheduler; - return {new input_raw_t {}}; + return {new input_raw_t {settings}}; } std::unique_ptr allocate_client_input_context(input_t &input) { diff --git a/src/platform/virtualhid_input.h b/src/platform/virtualhid_input.h index 47431963b..978ad961b 100644 --- a/src/platform/virtualhid_input.h +++ b/src/platform/virtualhid_input.h @@ -5,6 +5,7 @@ #pragma once // standard includes +#include #include #include #include @@ -25,16 +26,11 @@ namespace platf::virtualhid { */ struct input_context_t { /** - * @brief Construct the libvirtualhid input context using the platform-default backend. - */ - input_context_t(); - - /** - * @brief Construct the libvirtualhid input context using a selected backend. - * + * @brief Bind immutable host settings and construct libvirtualhid devices. + * @param settings Startup configuration owned by the host. * @param backend Backend used to create the libvirtualhid runtime. */ - explicit input_context_t(lvh::BackendKind backend); + explicit input_context_t(const config::settings_t &settings, lvh::BackendKind backend = lvh::BackendKind::platform_default); /** * @brief Recreate the shared keyboard using the runtime's current driver and license state. @@ -61,6 +57,8 @@ namespace platf::virtualhid { */ void update_mouse_viewport(const touch_port_t &touch_port); + std::reference_wrapper settings; ///< Host startup configuration shared by these devices. + std::string gamepad_driver; ///< Runtime backend choice serialized by the host input service. std::unique_ptr runtime; ///< libvirtualhid runtime. std::unique_ptr keyboard; ///< Shared virtual keyboard. std::unique_ptr mouse; ///< Shared virtual mouse. @@ -342,9 +340,10 @@ namespace platf::virtualhid { /** * @brief Return whether the configured gamepad profile can expose touchpad input. * + * @param settings Immutable host controller profile settings. * @return True when controller touchpad input should be advertised. */ - bool configured_gamepad_supports_touchpad(); + bool configured_gamepad_supports_touchpad(const config::settings_t &settings); /** * @brief Return whether the configured gamepad profile needs Moonlight controller extensions. @@ -352,8 +351,19 @@ namespace platf::virtualhid { * Moonlight uses the controller-touch feature flag to authorize both controller * touchpad and motion packets. * + * @param settings Immutable host controller profile settings. * @return True when controller touchpad or motion input should be advertised. */ - bool configured_gamepad_supports_controller_extensions(); + bool configured_gamepad_supports_controller_extensions(const config::settings_t &settings); + +#if defined(_WIN32) && defined(SUNSHINE_TESTS) + /** + * @brief Queue a ViGEm callback using an inactive owner for lifetime tests. + * @param scheduler Fixture scheduler that executes the deferred callback. + * @param callback Recorder invoked only while the returned backend owner is retained. + * @return Inactive backend owner whose reset must suppress its pending feedback. + */ + std::shared_ptr queue_vigem_feedback_for_testing(thread_pool_util::ThreadPool &scheduler, std::function callback); +#endif } // namespace platf::virtualhid diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index 735fef9c5..12748863f 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -867,6 +867,15 @@ namespace platf::audio { */ class audio_control_t: public ::platf::audio_control_t { public: + const config::settings_t &settings; ///< Configuration retained for this controller's lifetime. + + /** + * @brief Bind audio routing policy without initializing Windows resources. + * @param settings Host configuration. + */ + explicit audio_control_t(const config::settings_t &settings): + settings {settings} {} + /** * @brief Query host and virtual sink names available to Sunshine. * @@ -875,12 +884,12 @@ namespace platf::audio { std::optional sink_info() override { sink_t sink; - if (config::audio.external_audio) { - if (config::audio.sink.empty()) { + if (settings.audio.external_audio) { + if (settings.audio.sink.empty()) { BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; return std::nullopt; } - sink.host = config::audio.sink; + sink.host = settings.audio.sink; return sink; } @@ -901,10 +910,10 @@ namespace platf::audio { // this device can be either user-configured or // the Steam Streaming Speakers we use by default. match_fields_list_t match_list; - if (config::audio.virtual_sink.empty()) { + if (settings.audio.virtual_sink.empty()) { match_list = match_steam_speakers(); } else { - match_list = match_all_fields(utf_utils::from_utf8(config::audio.virtual_sink)); + match_list = match_all_fields(utf_utils::from_utf8(settings.audio.virtual_sink)); } // Search for the virtual audio sink device currently present in the system. @@ -919,8 +928,8 @@ namespace platf::audio { "virtual-"s + formats[1].name + device_id, "virtual-"s + formats[2].name + device_id, }); - } else if (!config::audio.virtual_sink.empty()) { - BOOST_LOG(warning) << "Couldn't find the specified virtual audio sink " << config::audio.virtual_sink; + } else if (!settings.audio.virtual_sink.empty()) { + BOOST_LOG(warning) << "Couldn't find the specified virtual audio sink " << settings.audio.virtual_sink; } return sink; @@ -1001,9 +1010,9 @@ namespace platf::audio { auto mic = std::make_unique(); // External routing pins capture to the configured sink; otherwise prefer the session's assigned sink. - const auto &requested_sink = config::audio.external_audio || assigned_sink.empty() ? config::audio.sink : assigned_sink; + const auto &requested_sink = settings.audio.external_audio || assigned_sink.empty() ? settings.audio.sink : assigned_sink; - if (config::audio.external_audio && requested_sink.empty()) { + if (settings.audio.external_audio && requested_sink.empty()) { BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; return nullptr; } @@ -1028,7 +1037,7 @@ namespace platf::audio { // If this is a virtual sink, set a callback that will change the sink back if it's changed auto virtual_sink_info = extract_virtual_sink_info(assigned_sink); - if (virtual_sink_info && !config::audio.external_audio) { + if (virtual_sink_info && !settings.audio.external_audio) { mic->default_endpt_changed_cb = [this] { BOOST_LOG(info) << "Resetting sink to ["sv << assigned_sink << "] after default changed"; set_sink(assigned_sink); @@ -1115,7 +1124,7 @@ namespace platf::audio { * @return Status from updating sink. */ int set_sink(const std::string &sink) override { - if (config::audio.external_audio) { + if (settings.audio.external_audio) { return 0; } @@ -1274,7 +1283,7 @@ namespace platf::audio { * @brief Resets the default audio device from Steam Streaming Speakers. */ void reset_default_device() { - if (config::audio.external_audio) { + if (settings.audio.external_audio) { return; } @@ -1414,7 +1423,7 @@ namespace platf::audio { */ template int init(const CreateInstance &create_instance = &CoCreateInstance) { - if (!config::audio.external_audio) { + if (!settings.audio.external_audio) { auto status = create_instance( CLSID_CPolicyConfigClient, nullptr, @@ -1480,30 +1489,33 @@ namespace platf::audio { /** * @brief Exercise controller initialization with a supplied COM factory. + * @param settings Host audio configuration. * @param create_instance Factory providing or rejecting the requested interfaces. * @return Status from controller initialization. */ - int initialize_audio_control(const std::function> &create_instance) { - audio_control_t control; + int initialize_audio_control(const config::settings_t &settings, const std::function> &create_instance) { + audio_control_t control {settings}; return control.init(create_instance); } /** * @brief Exercise sink discovery without initializing Windows policy interfaces. + * @param settings Host audio configuration. * @return Sinks reported by the production controller for the current configuration. */ - std::optional configured_sink_info() { - audio_control_t control; + std::optional configured_sink_info(const config::settings_t &settings) { + audio_control_t control {settings}; return control.sink_info(); } /** * @brief Exercise the external-routing sink-change guard without policy interfaces. + * @param settings Host audio configuration. * @param sink Sink a caller attempts to select. * @return Status from the production sink setter. */ - int set_external_sink(const std::string &sink) { - audio_control_t control; + int set_external_sink(const config::settings_t &settings, const std::string &sink) { + audio_control_t control {settings}; control.reset_default_device(); return control.set_sink(sink); } @@ -1516,7 +1528,8 @@ namespace platf::audio { * @return `true` when the sink resolves to an active endpoint. */ bool sink_device_available(const std::string &sink, IMMDeviceEnumerator *device_enum) { - audio_control_t control; + const config::settings_t settings; + audio_control_t control {settings}; device_enum->AddRef(); control.device_enum.reset(device_enum); return static_cast(control.get_sink_device(sink)); @@ -1525,20 +1538,21 @@ namespace platf::audio { /** * @brief Exercise microphone creation with controlled assigned and configured sinks. * + * @param base_settings Host audio configuration copied for this test invocation. * @param assigned_sink Sink selected by the shared audio context. * @param configured_sink Sink configured by the user. * @param device_enum Device enumerator supplied by the test. * @return `true` when microphone initialization succeeds. */ - bool microphone_available(const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum) { - audio_control_t control; + bool microphone_available(const config::settings_t &base_settings, const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum) { + auto settings = base_settings; + settings.audio.sink = configured_sink; + audio_control_t control {settings}; device_enum->AddRef(); control.device_enum.reset(device_enum); control.assigned_sink = assigned_sink; - auto previous_configured_sink = std::exchange(config::audio.sink, configured_sink); auto microphone = control.microphone(nullptr, 2, 48000, 240, false, false); - config::audio.sink = std::move(previous_configured_sink); return static_cast(microphone); } @@ -1613,8 +1627,8 @@ namespace platf { int init(); } // namespace dxgi - std::unique_ptr audio_control() { - auto control = std::make_unique(); + std::unique_ptr audio_control(const config::settings_t &settings) { + auto control = std::make_unique(settings); if (control->init()) { return nullptr; @@ -1622,7 +1636,7 @@ namespace platf { // Install Steam Streaming Speakers if needed. We do this during audio_control() to ensure // the sink information returned includes the new Steam Streaming Speakers device. - if (!config::audio.external_audio && config::audio.install_steam_drivers && !control->find_device_id(control->match_steam_speakers())) { + if (!settings.audio.external_audio && settings.audio.install_steam_drivers && !control->find_device_id(control->match_steam_speakers())) { // This is best effort. Don't fail if it doesn't work. control->install_steam_audio_drivers(); } @@ -1630,13 +1644,13 @@ namespace platf { return control; } - std::unique_ptr init() { + std::unique_ptr init(const config::settings_t &settings) { // Initialize COM auto co_init = std::make_unique(); // If Steam Streaming Speakers are currently the default audio device, // change the default to something else (if another device is available). - audio::audio_control_t audio_ctrl; + audio::audio_control_t audio_ctrl {settings}; if (audio_ctrl.init() == 0) { audio_ctrl.reset_default_device(); } diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index e53a14d93..d708a5043 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -211,13 +211,14 @@ namespace platf::dxgi { /** * @brief Construct a Windows capture backend retaining its compiled shader resources. + * @param settings Immutable startup settings for this host. * @param hwdevice_type Encoder memory type. * @param display_name Requested display. * @param config Streaming configuration. * @param shaders Immutable complete bytecode bundle. * @return Initialized capture backend, or null on failure. */ - std::shared_ptr make_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, std::shared_ptr shaders); + std::shared_ptr make_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, std::shared_ptr shaders); /** * @brief D3D depth-stencil state handle type. @@ -397,6 +398,14 @@ namespace platf::dxgi { */ class display_base_t: public display_t { public: + /** + * @brief Retain the host's immutable capture configuration. + * @param settings Host settings. + */ + explicit display_base_t(const config::settings_t &settings): + settings(settings) {} + + const config::settings_t &settings; ///< Host settings outliving this capture resource. /** * @brief Initialize D3D11 desktop duplication for the selected output. * @@ -583,6 +592,7 @@ namespace platf::dxgi { */ class display_ram_t: public display_base_t { public: + using display_base_t::display_base_t; ///< Construct with host settings. /** * @brief Allocate an image buffer compatible with this display backend. * @@ -630,9 +640,11 @@ namespace platf::dxgi { public: /** * @brief Retain the shader bundle for every capture and conversion resource. + * @param settings Immutable startup settings for this host. * @param shaders Complete bytecode compiled by the platform owner. */ - explicit display_vram_t(std::shared_ptr shaders): + explicit display_vram_t(const config::settings_t &settings, std::shared_ptr shaders): + display_base_t(settings), shaders {std::move(shaders)} {} std::shared_ptr shaders; ///< Immutable capture and encoder bytecode. @@ -733,6 +745,7 @@ namespace platf::dxgi { */ class display_ddup_ram_t: public display_ram_t { public: + using display_ram_t::display_ram_t; ///< Construct with host settings. /** * @brief Initialize shared D3D capture resources for a RAM frame. * @@ -869,6 +882,7 @@ namespace platf::dxgi { wgc_capture_t dup; public: + using display_ram_t::display_ram_t; ///< Construct with host settings. /** * @brief Initialize shared D3D capture resources for a GPU frame. * diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 2d688a32d..1f8701d55 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -488,7 +488,7 @@ namespace platf::dxgi { return -1; } - auto adapter_name = utf_utils::from_utf8(config::video.adapter_name); + auto adapter_name = utf_utils::from_utf8(settings.video.adapter_name); auto output_name = utf_utils::from_utf8(display_name); adapter_t::pointer adapter_p; @@ -684,7 +684,7 @@ namespace platf::dxgi { // As of 2023.07, NVIDIA driver has unfixed bug(s) where "realtime" can cause unrecoverable encoding freeze or outright driver crash // This issue happens more frequently with HAGS, in DX12 games or when VRAM is filled close to max capacity // Track OBS to see if they find better workaround or NVIDIA fixes it on their end, they seem to be in communication - if (hags_enabled && !config::video.nv_realtime_hags) { + if (hags_enabled && !settings.video.nv_realtime_hags) { priority = D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH; } } @@ -1014,21 +1014,20 @@ namespace platf::dxgi { namespace platf { /** * Pick a display adapter and capture method. - * @param hwdevice_type enables possible use of hardware encoder */ - std::shared_ptr dxgi::make_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, std::shared_ptr shaders) { + std::shared_ptr dxgi::make_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, std::shared_ptr shaders) { if (hwdevice_type == mem_type_e::dxgi && !shaders) { return nullptr; } - if (config::video.capture == "ddx" || config::video.capture.empty()) { + if (settings.video.capture == "ddx" || settings.video.capture.empty()) { if (hwdevice_type == mem_type_e::dxgi) { - auto disp = std::make_shared(shaders); + auto disp = std::make_shared(settings, shaders); if (!disp->init(config, display_name)) { return disp; } } else if (hwdevice_type == mem_type_e::system) { - auto disp = std::make_shared(); + auto disp = std::make_shared(settings); if (!disp->init(config, display_name)) { return disp; @@ -1036,15 +1035,15 @@ namespace platf { } } - if (config::video.capture == "wgc" || config::video.capture.empty()) { + if (settings.video.capture == "wgc" || settings.video.capture.empty()) { if (hwdevice_type == mem_type_e::dxgi) { - auto disp = std::make_shared(shaders); + auto disp = std::make_shared(settings, shaders); if (!disp->init(config, display_name)) { return disp; } } else if (hwdevice_type == mem_type_e::system) { - auto disp = std::make_shared(); + auto disp = std::make_shared(settings); if (!disp->init(config, display_name)) { return disp; diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index bda8236a3..482046dc2 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -574,7 +574,7 @@ namespace platf::dxgi { const bool downscaling = display->width > width || display->height > height; - const auto fp16_transfer = select_fp16_transfer(format, display->is_hdr(), config::video.fp16_sdr_gamma_encoded); + const auto fp16_transfer = select_fp16_transfer(format, display->is_hdr(), display->settings.video.fp16_sdr_gamma_encoded); if (fp16_transfer == fp16_transfer_e::gamma_encoded) { BOOST_LOG(info) << "Treating FP16 SDR capture as gamma-encoded (fp16_sdr_gamma_encoded)"sv; } @@ -1244,7 +1244,7 @@ namespace platf::dxgi { return false; } - if (!nvenc_d3d->create_encoder(config::video.nv, client_config, colorspace, buffer_format)) { + if (!nvenc_d3d->create_encoder(base.display->settings.video.nv, client_config, colorspace, buffer_format)) { return false; } diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index df65b5b1a..9fc99476b 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -245,7 +245,7 @@ namespace platf { /** * @brief ViGEm client connection and virtual gamepad collection. */ - class vigem_t { + class vigem_t: public std::enable_shared_from_this { public: /** * @brief Bind deferred gamepad work to the application scheduler. @@ -256,6 +256,18 @@ namespace platf { thread_pool_util::ThreadPool &scheduler; ///< Scheduler that outlives this input context. + /** + * @brief Queue native feedback while allowing a replaced backend to expire. + * @param callback Feedback operation invoked only while this owner remains alive. + */ + void defer_feedback(std::function callback) { + scheduler.push([owner = weak_from_this(), callback = std::move(callback)]() { + if (auto context = owner.lock()) { + callback(*context); + } + }); + } + /** * @brief Connect to ViGEm and prepare virtual gamepad slots. * @@ -390,6 +402,9 @@ namespace platf { gamepad.repeat_task = nullptr; } + if (gamepad.gp) { + vigem_target_x360_unregister_notification(gamepad.gp.get()); + } if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { auto status = vigem_target_remove(client.get(), gamepad.gp.get()); if (!VIGEM_SUCCESS(status)) { @@ -475,6 +490,9 @@ namespace platf { ~vigem_t() { if (client) { for (auto &gamepad : gamepads) { + if (gamepad.gp) { + vigem_target_x360_unregister_notification(gamepad.gp.get()); + } if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { auto status = vigem_target_remove(client.get(), gamepad.gp.get()); if (!VIGEM_SUCCESS(status)) { @@ -504,7 +522,10 @@ namespace platf { << "largeMotor: "sv << (int) largeMotor << std::endl << "smallMotor: "sv << (int) smallMotor; - static_cast(userdata)->scheduler.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); + auto *context = static_cast(userdata); + context->defer_feedback([target, largeMotor, smallMotor](vigem_t &context) { + context.rumble(target, largeMotor, smallMotor); + }); } void CALLBACK ds4_notify( @@ -522,8 +543,11 @@ namespace platf { << util::hex(led_color.Green).to_string_view() << ' ' << util::hex(led_color.Blue).to_string_view() << std::endl; - static_cast(userdata)->scheduler.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); - static_cast(userdata)->scheduler.push(&vigem_t::set_rgb_led, (vigem_t *) userdata, target, led_color.Red, led_color.Green, led_color.Blue); + auto *context = static_cast(userdata); + context->defer_feedback([target, largeMotor, smallMotor, led_color](vigem_t &context) { + context.rumble(target, largeMotor, smallMotor); + context.set_rgb_led(target, led_color.Red, led_color.Green, led_color.Blue); + }); } /** @@ -532,14 +556,16 @@ namespace platf { struct input_raw_t { /** * @brief Bind input fallback resources to their scheduler. + * @param settings Immutable host input configuration. * @param scheduler Application scheduler. */ - explicit input_raw_t(thread_pool_util::ThreadPool &scheduler): - scheduler(scheduler) {} + explicit input_raw_t(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler): + scheduler(scheduler), + virtualhid {settings} {} thread_pool_util::ThreadPool &scheduler; ///< Application scheduler. virtualhid::input_context_t virtualhid; ///< libvirtualhid input context. - std::unique_ptr vigem; ///< ViGEm fallback context. + std::shared_ptr vigem; ///< ViGEm fallback owner observed weakly by queued native callbacks. }; /** @@ -558,7 +584,7 @@ namespace platf { const auto &capabilities = raw.virtualhid.runtime->capabilities(); const auto licensed = !capabilities.requires_installed_driver || lvh::get_license_status().license.licensed(); - return virtualhid::should_use_gamepad_runtime(capabilities, config::input.gamepad_driver, licensed); + return virtualhid::should_use_gamepad_runtime(capabilities, raw.virtualhid.gamepad_driver, licensed); } /** @@ -576,16 +602,16 @@ namespace platf { }; } - input_t input(thread_pool_util::ThreadPool &scheduler) { - input_t result {new input_raw_t {scheduler}}; + input_t input(const config::settings_t &settings, thread_pool_util::ThreadPool &scheduler) { + input_t result {new input_raw_t {settings, scheduler}}; - if (auto &raw = *result; config::input.controller && !should_use_virtualhid_gamepads(raw) && virtualhid::should_try_vigembus_fallback(config::input.gamepad, false, config::input.gamepad_driver)) { - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { + if (auto &raw = *result; settings.input.controller && !should_use_virtualhid_gamepads(raw) && virtualhid::should_try_vigembus_fallback(settings.input.gamepad, false, settings.input.gamepad_driver)) { + if (settings.input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { BOOST_LOG(info) << "ViGEmBus is selected as the only virtual gamepad driver"sv; } else if (raw.virtualhid.runtime && raw.virtualhid.runtime->capabilities().supports_gamepad) { BOOST_LOG(info) << "Virtual HID Driver license is not valid; using the ViGEmBus gamepad fallback"sv; } - auto vigem = std::make_unique(scheduler); + auto vigem = std::make_shared(scheduler); if (!vigem->init()) { raw.vigem = std::move(vigem); } @@ -605,7 +631,7 @@ namespace platf { return true; } - auto vigem = std::make_unique(raw->scheduler); + auto vigem = std::make_shared(raw->scheduler); if (vigem->init()) { return false; } @@ -617,21 +643,23 @@ namespace platf { /** * @brief Check and explain whether a gamepad allocation may use ViGEmBus. * + * @param settings Immutable host controller profile settings. + * @param driver Service-owned runtime driver policy. * @param virtualhid_selected Whether Virtual HID Driver was selected for the allocation. * @return True when the allocation may continue through ViGEmBus. */ - bool should_allocate_vigembus_gamepad(const bool virtualhid_selected) { - if (!virtualhid::should_try_vigembus_fallback(config::input.gamepad, virtualhid_selected, config::input.gamepad_driver)) { - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIRTUALHID && !virtualhid_selected) { + bool should_allocate_vigembus_gamepad(const config::settings_t &settings, std::string_view driver, const bool virtualhid_selected) { + if (!virtualhid::should_try_vigembus_fallback(settings.input.gamepad, virtualhid_selected, driver)) { + if (driver == config::GAMEPAD_DRIVER_VIRTUALHID && !virtualhid_selected) { BOOST_LOG(warning) << "Virtual HID Driver is selected but is unavailable or unlicensed; ViGEmBus fallback is disabled by configuration"sv; } else { - BOOST_LOG(warning) << "libvirtualhid could not create the requested gamepad profile, and ViGEm fallback cannot emulate "sv << config::input.gamepad; + BOOST_LOG(warning) << "libvirtualhid could not create the requested gamepad profile, and ViGEm fallback cannot emulate "sv << settings.input.gamepad; } return false; } - if (!virtualhid_selected && !virtualhid::should_try_vigembus_fallback(config::input.gamepad, true, config::input.gamepad_driver)) { - BOOST_LOG(warning) << "Configured gamepad profile '"sv << config::input.gamepad + if (!virtualhid_selected && !virtualhid::should_try_vigembus_fallback(settings.input.gamepad, true, driver)) { + BOOST_LOG(warning) << "Configured gamepad profile '"sv << settings.input.gamepad << "' is unavailable; using ViGEmBus automatic selection because Virtual HID Driver is not usable"sv; } return true; @@ -641,6 +669,16 @@ namespace platf { return input->virtualhid; } +#ifdef SUNSHINE_TESTS + std::shared_ptr virtualhid::queue_vigem_feedback_for_testing(thread_pool_util::ThreadPool &scheduler, std::function callback) { + auto owner = std::make_shared(scheduler); + owner->defer_feedback([callback = std::move(callback)](vigem_t &) { + callback(); + }); + return owner; + } +#endif + std::optional get_mouse_loc(input_t & /*input*/) { POINT p; if (!GetCursorPos(&p)) { @@ -683,13 +721,14 @@ namespace platf { int alloc_gamepad(input_t &input, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue) { auto raw = (input_raw_t *) input.get(); + const auto &settings = raw->virtualhid.settings.get(); const auto use_virtualhid = should_use_virtualhid_gamepads(*raw); if (use_virtualhid && virtualhid::alloc_gamepad(raw->virtualhid, id, metadata, feedback_queue) == 0) { return 0; } - if (!should_allocate_vigembus_gamepad(use_virtualhid)) { + if (!should_allocate_vigembus_gamepad(raw->virtualhid.settings.get(), raw->virtualhid.gamepad_driver, use_virtualhid)) { return -1; } @@ -699,10 +738,10 @@ namespace platf { VIGEM_TARGET_TYPE selectedGamepadType; - if (config::input.gamepad == "x360"sv) { + if (settings.input.gamepad == "x360"sv) { BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox 360 controller (manual selection)"sv; selectedGamepadType = Xbox360Wired; - } else if (config::input.gamepad == "ds4"sv) { + } else if (settings.input.gamepad == "ds4"sv) { BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (manual selection)"sv; selectedGamepadType = DualShock4Wired; } else if (metadata.type == LI_CTYPE_PS) { @@ -711,10 +750,10 @@ namespace platf { } else if (metadata.type == LI_CTYPE_XBOX) { BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox 360 controller (auto-selected by client-reported type)"sv; selectedGamepadType = Xbox360Wired; - } else if (config::input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { + } else if (settings.input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (auto-selected by motion sensor presence)"sv; selectedGamepadType = DualShock4Wired; - } else if (config::input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { + } else if (settings.input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (auto-selected by touchpad presence)"sv; selectedGamepadType = DualShock4Wired; } else { @@ -931,7 +970,13 @@ namespace platf { return (DS4_BUTTONS) buttons; } - static DS4_SPECIAL_BUTTONS ds4_special_buttons(const gamepad_state_t &gamepad_state) { + /** + * @brief Map special DS4 buttons using this host's touchpad preferences. + * @param settings Immutable host input configuration. + * @param gamepad_state Client button and trigger state. + * @return Special button mask for the DS4 report. + */ + static DS4_SPECIAL_BUTTONS ds4_special_buttons(const config::settings_t &settings, const gamepad_state_t &gamepad_state) { int buttons {}; if (gamepad_state.buttonFlags & HOME) { @@ -944,7 +989,7 @@ namespace platf { } // PlayStation-style emulation: check if BACK should also trigger touchpad click - if (config::input.ds4_back_as_touchpad_click && virtualhid::configured_gamepad_supports_touchpad() && (gamepad_state.buttonFlags & BACK)) { + if (settings.input.ds4_back_as_touchpad_click && virtualhid::configured_gamepad_supports_touchpad(settings) && (gamepad_state.buttonFlags & BACK)) { buttons |= DS4_SPECIAL_BUTTON_TOUCHPAD; } @@ -963,14 +1008,15 @@ namespace platf { /** * @brief Update a DS4 report from Sunshine gamepad state. + * @param settings Immutable host input configuration. * @param gamepad The gamepad to update. * @param gamepad_state The gamepad button/axis state sent from the client. */ - static void ds4_update_state(gamepad_context_t &gamepad, const gamepad_state_t &gamepad_state) { + static void ds4_update_state(const config::settings_t &settings, gamepad_context_t &gamepad, const gamepad_state_t &gamepad_state) { auto &report = gamepad.report.ds4.Report; report.wButtons = static_cast(ds4_buttons(gamepad_state)) | static_cast(ds4_dpad(gamepad_state)); - report.bSpecial = ds4_special_buttons(gamepad_state); + report.bSpecial = ds4_special_buttons(settings, gamepad_state); report.bTriggerL = gamepad_state.lt; report.bTriggerR = gamepad_state.rt; @@ -1013,7 +1059,13 @@ namespace platf { // Repeat at least every 100ms to keep the 16-bit timestamp field from overflowing gamepad.last_report_ts = now; - gamepad.repeat_task = vigem->scheduler.pushDelayed(ds4_update_ts_and_send, 100ms, vigem, nr).task_id; + gamepad.repeat_task = vigem->scheduler.pushDelayed([owner = vigem->weak_from_this(), nr]() { + if (auto context = owner.lock()) { + ds4_update_ts_and_send(context.get(), nr); + } + }, + 100ms) + .task_id; } } @@ -1051,7 +1103,7 @@ namespace platf { BOOST_LOG(warning) << "Couldn't send gamepad input to ViGEm ["sv << util::hex(status).to_string_view() << ']'; } } else { - ds4_update_state(gamepad, gamepad_state); + ds4_update_state(raw->virtualhid.settings.get(), gamepad, gamepad_state); ds4_update_ts_and_send(vigem, nr); } } @@ -1284,26 +1336,27 @@ namespace platf { std::default_delete {}(input); } - std::vector &supported_gamepads(input_t *input) { - static std::vector gps; + std::vector supported_gamepads(input_t *input) { + std::vector gps; if (!input || !input->get()) { gps = virtualhid::static_supported_gamepads(); return gps; } const auto raw = (input_raw_t *) input->get(); - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { + const auto &driver = raw->virtualhid.gamepad_driver; + if (driver == config::GAMEPAD_DRIVER_NONE) { gps.clear(); return gps; } - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { + if (driver == config::GAMEPAD_DRIVER_VIGEMBUS) { gps = vigembus_supported_gamepads(raw->vigem != nullptr); return gps; } if (!raw->virtualhid.runtime) { - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIRTUALHID) { + if (driver == config::GAMEPAD_DRIVER_VIRTUALHID) { gps = virtualhid::static_supported_gamepads(); for (auto &gamepad : gps) { gamepad.is_enabled = false; @@ -1317,7 +1370,7 @@ namespace platf { const auto &capabilities = raw->virtualhid.runtime->capabilities(); const auto licensed = !capabilities.requires_installed_driver || lvh::get_license_status().license.licensed(); - if (const auto use_virtualhid = virtualhid::should_use_gamepad_runtime(capabilities, config::input.gamepad_driver, licensed); !use_virtualhid && config::input.gamepad_driver != config::GAMEPAD_DRIVER_VIRTUALHID) { + if (const auto use_virtualhid = virtualhid::should_use_gamepad_runtime(capabilities, driver, licensed); !use_virtualhid && driver != config::GAMEPAD_DRIVER_VIRTUALHID) { gps = vigembus_supported_gamepads(raw->vigem != nullptr); return gps; } @@ -1330,14 +1383,14 @@ namespace platf { * @brief Returns the supported platform capabilities to advertise to the client. * @return Capability flags. */ - platform_caps::caps_t get_capabilities() { + platform_caps::caps_t get_capabilities(const config::settings_t &settings) { platform_caps::caps_t caps = 0; - if (config::input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && virtualhid::configured_gamepad_supports_controller_extensions()) { + if (settings.input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && virtualhid::configured_gamepad_supports_controller_extensions(settings)) { caps |= platform_caps::controller_touch; } - if (config::input.native_pen_touch) { + if (settings.input.native_pen_touch) { const auto runtime = virtualhid::create_runtime(); if (runtime) { const auto &capabilities = runtime->capabilities(); diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 6f0f3c27f..c08dc4913 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -127,7 +127,7 @@ namespace bp = boost::process::v1; using namespace std::literals; namespace platf { - std::vector get_permission_statuses() { + std::vector get_permission_statuses(const config::settings_t &settings) { return {{"config_directory", can_access_directory(appdata()) ? "granted" : "denied", true, true}}; } @@ -147,17 +147,23 @@ namespace platf { * @brief Own Windows process settings and optional networking resources. */ struct runtime_t::impl_t { + const config::settings_t &settings; ///< Immutable settings for this platform owner. + /** * @brief Bind application dependencies. + * @param settings Immutable startup settings for this host. * @param preferences NVIDIA profile owner. */ - explicit impl_t(nvprefs::nvprefs_interface &preferences): + explicit impl_t(const config::settings_t &settings, nvprefs::nvprefs_interface &preferences): + settings(settings), preferences(preferences) {} nvprefs::nvprefs_interface &preferences; ///< NVIDIA profile manager. std::shared_ptr shaders; ///< Compiled capture shaders. std::unique_ptr initialization; ///< COM initialization lifetime. dxgi::factory1_t enumeration_factory; ///< DXGI GPU change tracker for this host. + std::mutex streaming_mutex; ///< Serialize process settings and Mouse Keys changes. + std::mutex qos_mutex; ///< Serialize optional QWAVE client creation. std::mutex enumeration_mutex; ///< Serialize native GPU change tracking. bool streaming {}; ///< Whether native streaming settings are active. bool used_nt_set_timer_resolution {}; ///< Timer request method. @@ -259,6 +265,7 @@ namespace platf { /** * @brief Synchronize thread desktop. + * @return Handle value of the selected desktop, or null if the desktop could not be opened. */ HDESK syncThreadDesktop() { auto hDesk = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, GENERIC_ALL); @@ -1212,8 +1219,8 @@ namespace platf { if (!preferences.owning_undo_file()) { preferences.restore_from_and_delete_undo_file_if_exists(); } - preferences.modify_application_profile(); - preferences.modify_global_profile(); + preferences.modify_application_profile(settings); + preferences.modify_global_profile(settings); preferences.unload(); } @@ -1251,7 +1258,7 @@ namespace platf { } void runtime_t::impl_t::enable_mouse_keys() { - if (enabled_mouse_keys) { + if (!streaming || enabled_mouse_keys) { return; } // If there is no mouse connected, enable Mouse Keys to force the cursor to appear @@ -1319,6 +1326,9 @@ namespace platf { } } + /** + * @brief Launch a replacement Sunshine process after application cleanup completes. + */ void restart_on_exit() { STARTUPINFOEXW startup_info {}; startup_info.StartupInfo.cb = sizeof(startup_info); @@ -1641,6 +1651,7 @@ namespace platf { /** * @brief Store a Windows QoS flow ID for cleanup on destruction. * + * @param api QWAVE client and loaded library retained until the flow is removed. * @param flow_id Flow ID. */ qos_t(std::shared_ptr api, QOS_FLOWID flow_id): @@ -1674,10 +1685,14 @@ namespace platf { return nullptr; } - if (!impl->qos) { - impl->qos = qwave_api_t::load(); + std::shared_ptr api; + { + std::lock_guard guard(impl->qos_mutex); + if (!impl->qos) { + impl->qos = qwave_api_t::load(); + } + api = impl->qos; } - auto api = impl->qos; if (!api) { return nullptr; } @@ -1745,6 +1760,7 @@ namespace platf { /** * @brief Read the current Windows high-resolution performance counter. + * @return Current counter value, or zero when the native query fails. */ int64_t qpc_counter() { LARGE_INTEGER performance_counter; @@ -1756,6 +1772,7 @@ namespace platf { /** * @brief Convert the difference between two QPC readings to nanoseconds. + * @return Elapsed duration, or zero when the counter frequency cannot be queried. */ std::chrono::nanoseconds qpc_time_difference(int64_t performance_counter1, int64_t performance_counter2) { auto get_frequency = []() { @@ -1834,6 +1851,10 @@ namespace platf { return std::make_unique(); } + /** + * @brief Read the four-part version embedded in a Windows executable or library. + * @return Whether a valid version resource was read. + */ bool getFileVersionInfo(const std::filesystem::path &file_path, std::string &version_str) { DWORD handle = 0; DWORD size = GetFileVersionInfoSizeW(file_path.wstring().c_str(), &handle); @@ -1861,16 +1882,17 @@ namespace platf { return true; } - std::string resolve_render_device() { + std::string resolve_render_device(const config::settings_t &settings) { return {}; } } // namespace platf namespace platf { - runtime_t::runtime_t(safe::mail_t, thread_pool_util::ThreadPool &, lifetime::controller_t &, display_device::manager_t &, nvprefs::nvprefs_interface &preferences): - impl(std::make_shared(preferences)) {} + runtime_t::runtime_t(const config::settings_t &settings, safe::mail_t, thread_pool_util::ThreadPool &, lifetime::controller_t &, display_device::manager_t &, nvprefs::nvprefs_interface &preferences): + impl(std::make_shared(settings, preferences)) {} runtime_t::~runtime_t() { + std::lock_guard guard(impl->streaming_mutex); impl->streaming_will_stop(); } @@ -1882,7 +1904,7 @@ namespace platf { if (!impl->shaders) { return false; } - impl->initialization = platf::init(); + impl->initialization = platf::init(impl->settings); return static_cast(impl->initialization); } @@ -1891,13 +1913,11 @@ namespace platf { } std::shared_ptr runtime_t::display(mem_type_e type, const std::string &name, const video::config_t &config) { - return dxgi::make_display(type, name, config, impl->shaders); + return dxgi::make_display(impl->settings, type, name, config, impl->shaders); } /** * @brief Check the runtime's DXGI change tracker. - * @param factory Host factory. - * @param mutex Host synchronization. * @return Whether adapters changed. */ bool dxgi_needs_encoder_reenumeration(dxgi::factory1_t &factory, std::mutex &mutex); @@ -1909,14 +1929,17 @@ namespace platf { void runtime_t::set_capture_requirements(int) {} void runtime_t::streaming_will_start() { + std::lock_guard guard(impl->streaming_mutex); impl->streaming_will_start(); } void runtime_t::streaming_will_stop() { + std::lock_guard guard(impl->streaming_mutex); impl->streaming_will_stop(); } void runtime_t::enable_mouse_keys() { + std::lock_guard guard(impl->streaming_mutex); impl->enable_mouse_keys(); } } // namespace platf diff --git a/src/platform/windows/nvprefs/driver_settings.cpp b/src/platform/windows/nvprefs/driver_settings.cpp index 46110e303..a9fec6067 100644 --- a/src/platform/windows/nvprefs/driver_settings.cpp +++ b/src/platform/windows/nvprefs/driver_settings.cpp @@ -159,7 +159,7 @@ namespace nvprefs { return true; } - bool driver_settings_t::check_and_modify_global_profile(std::optional &undo_data) { + bool driver_settings_t::check_and_modify_global_profile(const config::settings_t &settings, std::optional &undo_data) { if (!session_handle) { return false; } @@ -167,7 +167,7 @@ namespace nvprefs { undo_data.reset(); NvAPI_Status status; - if (!get_nvprefs_options().opengl_vulkan_on_dxgi) { + if (!get_nvprefs_options(settings).opengl_vulkan_on_dxgi) { // User requested to leave OpenGL/Vulkan DXGI swapchain setting alone return true; } @@ -217,7 +217,7 @@ namespace nvprefs { return true; } - bool driver_settings_t::check_and_modify_application_profile(bool &modified) { + bool driver_settings_t::check_and_modify_application_profile(const config::settings_t &settings, bool &modified) { if (!session_handle) { return false; } @@ -273,7 +273,7 @@ namespace nvprefs { setting.version = NVDRS_SETTING_VER1; status = api->call_interface("NvAPI_DRS_GetSetting", session_handle, profile_handle, PREFERRED_PSTATE_ID, &setting); - if (!get_nvprefs_options().sunshine_high_power_mode) { + if (!get_nvprefs_options(settings).sunshine_high_power_mode) { if (status == NVAPI_OK && setting.settingLocation == NVDRS_CURRENT_PROFILE_LOCATION) { // User requested to not use high power mode for sunshine.exe, // remove the setting from application profile if it's been set previously diff --git a/src/platform/windows/nvprefs/driver_settings.h b/src/platform/windows/nvprefs/driver_settings.h index 82b5373f1..018ff74bb 100644 --- a/src/platform/windows/nvprefs/driver_settings.h +++ b/src/platform/windows/nvprefs/driver_settings.h @@ -3,6 +3,7 @@ * @brief Declarations for nvidia driver settings. */ #pragma once +#include "src/config.h" // local includes first so standard library headers are pulled in before nvapi's SAL macros #include "nvapi_opensource_wrapper.h" @@ -64,18 +65,20 @@ namespace nvprefs { /** * @brief Compare and update global NVIDIA profile settings. * + * @param settings Immutable startup settings for this host. * @param undo_data Driver settings captured before Sunshine modified them. * @return True when the NVIDIA driver-settings operation succeeds. */ - bool check_and_modify_global_profile(std::optional &undo_data); + bool check_and_modify_global_profile(const config::settings_t &settings, std::optional &undo_data); /** * @brief Compare and update Sunshine NVIDIA application profile settings. * + * @param settings Immutable startup settings for this host. * @param modified Whether NVIDIA driver settings were changed and need saving. * @return True when the NVIDIA driver-settings operation succeeds. */ - bool check_and_modify_application_profile(bool &modified); + bool check_and_modify_application_profile(const config::settings_t &settings, bool &modified); private: std::shared_ptr api; ///< API owner retained until the DRS session is destroyed. diff --git a/src/platform/windows/nvprefs/nvprefs_common.cpp b/src/platform/windows/nvprefs/nvprefs_common.cpp index 53af20320..8b73b50d6 100644 --- a/src/platform/windows/nvprefs/nvprefs_common.cpp +++ b/src/platform/windows/nvprefs/nvprefs_common.cpp @@ -42,10 +42,10 @@ namespace nvprefs { /** * @brief Get nvprefs options. */ - nvprefs_options get_nvprefs_options() { + nvprefs_options get_nvprefs_options(const config::settings_t &settings) { nvprefs_options options; - options.opengl_vulkan_on_dxgi = config::video.nv_opengl_vulkan_on_dxgi; - options.sunshine_high_power_mode = config::video.nv_sunshine_high_power_mode; + options.opengl_vulkan_on_dxgi = settings.video.nv_opengl_vulkan_on_dxgi; + options.sunshine_high_power_mode = settings.video.nv_sunshine_high_power_mode; return options; } diff --git a/src/platform/windows/nvprefs/nvprefs_common.h b/src/platform/windows/nvprefs/nvprefs_common.h index f422f159b..5e204ae7e 100644 --- a/src/platform/windows/nvprefs/nvprefs_common.h +++ b/src/platform/windows/nvprefs/nvprefs_common.h @@ -3,6 +3,7 @@ * @brief Declarations for common nvidia preferences. */ #pragma once +#include "src/config.h" // platform includes // disable clang-format header reordering @@ -95,8 +96,9 @@ namespace nvprefs { /** * @brief Get nvprefs options. * + * @param settings Immutable startup settings for this host. * @return Parsed command-line options for NVIDIA profile preference handling. */ - nvprefs_options get_nvprefs_options(); + nvprefs_options get_nvprefs_options(const config::settings_t &settings); } // namespace nvprefs diff --git a/src/platform/windows/nvprefs/nvprefs_interface.cpp b/src/platform/windows/nvprefs/nvprefs_interface.cpp index ce27cee09..7b7e7da0b 100644 --- a/src/platform/windows/nvprefs/nvprefs_interface.cpp +++ b/src/platform/windows/nvprefs/nvprefs_interface.cpp @@ -103,14 +103,14 @@ namespace nvprefs { return true; } - bool nvprefs_interface::modify_application_profile() { + bool nvprefs_interface::modify_application_profile(const config::settings_t &settings) { if (!pimpl->loaded) { return false; } // Modify and save sunshine.exe application profile settings, if needed bool modified = false; - if (!pimpl->driver_settings.check_and_modify_application_profile(modified)) { + if (!pimpl->driver_settings.check_and_modify_application_profile(settings, modified)) { error_message("Failed to modify application profile settings"); return false; } else if (modified) { @@ -127,14 +127,14 @@ namespace nvprefs { return true; } - bool nvprefs_interface::modify_global_profile() { + bool nvprefs_interface::modify_global_profile(const config::settings_t &settings) { if (!pimpl->loaded) { return false; } // Modify but not save global profile settings, if needed std::optional undo_data; - if (!pimpl->driver_settings.check_and_modify_global_profile(undo_data)) { + if (!pimpl->driver_settings.check_and_modify_global_profile(settings, undo_data)) { error_message("Couldn't modify global profile settings"); return false; } else if (!undo_data) { diff --git a/src/platform/windows/nvprefs/nvprefs_interface.h b/src/platform/windows/nvprefs/nvprefs_interface.h index 1f682ce29..beb97c3e7 100644 --- a/src/platform/windows/nvprefs/nvprefs_interface.h +++ b/src/platform/windows/nvprefs/nvprefs_interface.h @@ -3,6 +3,7 @@ * @brief Declarations for nvidia preferences interface. */ #pragma once +#include "src/config.h" // standard includes #include @@ -39,16 +40,18 @@ namespace nvprefs { /** * @brief Apply Sunshine-specific NVIDIA application profile changes. * + * @param settings Immutable startup settings for this host. * @return True when the NVIDIA preferences operation succeeds. */ - bool modify_application_profile(); + bool modify_application_profile(const config::settings_t &settings); /** * @brief Apply Sunshine-specific NVIDIA global profile changes. * + * @param settings Immutable startup settings for this host. * @return True when the NVIDIA preferences operation succeeds. */ - bool modify_global_profile(); + bool modify_global_profile(const config::settings_t &settings); /** * @brief Check whether this interface owns the active undo file. diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index 7347b5a49..bccbe7ca4 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -149,7 +149,14 @@ namespace platf::publish { alarm->ring(pInstance); } - static int service(bool enable, PDNS_SERVICE_INSTANCE &existing_instance) { + /** + * @brief Register or remove a service using the registration owner's HTTP port. + * @param port Mapped HTTP port advertised by this registration. + * @param enable Whether to register rather than remove the service. + * @param existing_instance Registered native instance retained until successful removal. + * @return Zero on success, or a negative value when registration or removal fails. + */ + static int service(std::uint16_t port, bool enable, PDNS_SERVICE_INSTANCE &existing_instance) { auto alarm = safe::make_alarm(); std::wstring domain = utf_utils::from_utf8(SERVICE_TYPE_DOMAIN); @@ -160,7 +167,7 @@ namespace platf::publish { DNS_SERVICE_INSTANCE instance {}; instance.pszInstanceName = name.data(); - instance.wPort = net::map_port(nvhttp::PORT_HTTP); + instance.wPort = port; instance.pszHostName = host.data(); // Setting these values ensures Windows mDNS answers comply with RFC 1035. @@ -220,9 +227,14 @@ namespace platf::publish { */ class mdns_registration_t: public ::platf::deinit_t { public: - mdns_registration_t(): + /** + * @brief Register the host's service using a snapshot of its configured port. + * @param settings Immutable startup settings for this host. + */ + explicit mdns_registration_t(const config::settings_t &settings): + port(net::map_port(settings, nvhttp::PORT_HTTP)), existing_instance(nullptr) { - if (service(true, existing_instance)) { + if (service(port, true, existing_instance)) { BOOST_LOG(error) << "Unable to register Sunshine mDNS service"sv; return; } @@ -232,7 +244,7 @@ namespace platf::publish { ~mdns_registration_t() override { if (existing_instance) { - if (service(false, existing_instance)) { + if (service(port, false, existing_instance)) { BOOST_LOG(error) << "Unable to unregister Sunshine mDNS service"sv; return; } @@ -242,7 +254,8 @@ namespace platf::publish { } private: - PDNS_SERVICE_INSTANCE existing_instance; + const std::uint16_t port; ///< Configured HTTP port retained for the registration's lifetime. + PDNS_SERVICE_INSTANCE existing_instance; ///< Native instance removed before releasing this owner. }; /** @@ -269,7 +282,11 @@ namespace platf::publish { return 0; } - std::unique_ptr<::platf::deinit_t> start() { + /** + * @brief Load DNS-SD support and advertise this host's configured HTTP service. + * @return Service registration owner, or null when DNS-SD is unavailable. + */ + std::unique_ptr<::platf::deinit_t> start(const config::settings_t &settings) { HMODULE handle = LoadLibrary("dnsapi.dll"); if (!handle || load_funcs(handle)) { @@ -277,6 +294,6 @@ namespace platf::publish { return nullptr; } - return std::make_unique(); + return std::make_unique(settings); } } // namespace platf::publish diff --git a/src/process.cpp b/src/process.cpp index f3e2acf3b..e7a6a1882 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -46,6 +46,7 @@ namespace proc { namespace pt = boost::property_tree; proc_t::proc_t(proc_t &&other): + settings {other.settings}, _app_id {std::exchange(other._app_id, 0)}, inputs {std::exchange(other.inputs, nullptr)}, displays {std::exchange(other.displays, nullptr)}, @@ -65,6 +66,7 @@ namespace proc { proc_t &proc_t::operator=(proc_t &&other) { if (this != &other) { terminate(); + settings = other.settings; _app_id = std::exchange(other._app_id, 0); inputs = std::exchange(other.inputs, nullptr); displays = std::exchange(other.displays, nullptr); @@ -720,7 +722,7 @@ namespace proc { /** * @brief Parse serialized text into the corresponding runtime representation. */ - std::optional parse(const std::string &file_name) { + std::optional parse(const std::string &file_name, const config::settings_t &settings) { pt::ptree tree; try { @@ -756,15 +758,15 @@ namespace proc { std::vector prep_cmds; if (!exclude_global_prep.value_or(false)) { - prep_cmds.reserve(config::sunshine.prep_cmds.size()); - for (auto &prep_cmd : config::sunshine.prep_cmds) { + prep_cmds.reserve(settings.sunshine.prep_cmds.size()); + for (auto &prep_cmd : settings.sunshine.prep_cmds) { auto do_cmd = parse_env_val(this_env, prep_cmd.do_cmd); auto undo_cmd = parse_env_val(this_env, prep_cmd.undo_cmd); prep_cmds.emplace_back( std::move(do_cmd), std::move(undo_cmd), - std::move(prep_cmd.elevated) + bool {prep_cmd.elevated} ); } } @@ -841,6 +843,7 @@ namespace proc { } return proc::proc_t { + settings, std::move(this_env), std::move(apps) }; @@ -876,7 +879,7 @@ namespace proc { return; } - auto proc_opt = proc::parse(file_name); + auto proc_opt = proc::parse(file_name, *settings); if (proc_opt) { update_apps_and_env(std::move(*proc_opt)); diff --git a/src/process.h b/src/process.h index 7e79c3350..d4e21d847 100644 --- a/src/process.h +++ b/src/process.h @@ -93,8 +93,11 @@ namespace proc { public: /** * @brief Construct an inactive process owner without platform dependencies. + * @param settings Startup preparation commands that outlive this owner. */ - proc_t() = default; + explicit proc_t(const config::settings_t &settings): + settings {&settings} {} + /** * @brief Transfer process ownership and leave the source inactive. * @param other Process owner to adopt. @@ -109,18 +112,22 @@ namespace proc { /** * @brief Construct a process owner with display restoration for completed applications. + * @param settings Startup preparation commands that outlive this owner. * @param displays Display manager that outlives this process owner. */ - explicit proc_t(display_device::manager_t &displays): + proc_t(const config::settings_t &settings, display_device::manager_t &displays): + settings {&settings}, displays {&displays} { } /** * @brief Construct a process owner with input and display cleanup dependencies. + * @param settings Startup preparation commands that outlive this owner. * @param displays Display manager that outlives this owner. * @param inputs Host input service that outlives this owner. */ - proc_t(display_device::manager_t &displays, input::service_t &inputs): + proc_t(const config::settings_t &settings, display_device::manager_t &displays, input::service_t &inputs): + settings {&settings}, inputs {&inputs}, displays {&displays} { } @@ -134,13 +141,16 @@ namespace proc { /** * @brief Construct a process manager. * + * @param settings Startup preparation commands that outlive this owner. * @param env Environment used when launching processes. * @param apps Application launch contexts. */ proc_t( + const config::settings_t &settings, boost::process::v1::environment &&env, std::vector &&apps ): + settings {&settings}, _app_id(0), _env(std::move(env)), _apps(std::move(apps)) { @@ -216,6 +226,7 @@ namespace proc { #endif private: + const config::settings_t *settings; ///< Startup preparation commands shared with application configuration. int _app_id {}; ///< Active application identifier, or zero before the first launch. input::service_t *inputs {}; ///< Optional host input cleanup dependency. display_device::manager_t *displays {}; ///< Optional display restoration dependency. @@ -267,9 +278,10 @@ namespace proc { * @brief Parse serialized text into the corresponding runtime representation. * * @param file_name File name. + * @param settings Startup preparation commands to append to applications. * @return Parsed value or parse status. */ - std::optional parse(const std::string &file_name); + std::optional parse(const std::string &file_name, const config::settings_t &settings); /** * @brief Terminates all child processes in a process group. diff --git a/src/rtsp.cpp b/src/rtsp.cpp index 8fc7ec46a..06f972b9c 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -472,15 +472,18 @@ namespace rtsp_stream { */ class rtsp_server_t { public: + const config::settings_t &settings; ///< Startup transport and encryption policy. stream::service_t &streams; ///< Session allocation owner. video::service_t &videos; ///< Encoder capability owner. /** * @brief Bind the host services used by RTSP handlers. + * @param settings Startup transport and encryption policy. * @param streams Stream allocation owner. * @param videos Encoder capability owner. */ - rtsp_server_t(stream::service_t &streams, video::service_t &videos): + rtsp_server_t(const config::settings_t &settings, stream::service_t &streams, video::service_t &videos): + settings {settings}, streams {streams}, videos {videos} { } @@ -498,7 +501,7 @@ namespace rtsp_stream { * @return Network operation status. */ int bind(net::af_e af, std::uint16_t port, boost::system::error_code &ec) { - af = net::get_effective_address_family(af); + af = net::get_effective_address_family(settings, af); acceptor.open(af == net::IPV4 ? tcp::v4() : tcp::v6(), ec); if (ec) { return -1; @@ -506,7 +509,7 @@ namespace rtsp_stream { acceptor.set_option(boost::asio::socket_base::reuse_address {true}); - auto bind_addr_str = net::get_bind_address(af); + auto bind_addr_str = net::get_bind_address(settings, af); const auto bind_addr = boost::asio::ip::make_address(bind_addr_str, ec); if (ec) { BOOST_LOG(error) << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); @@ -618,7 +621,7 @@ namespace rtsp_stream { launch_event.raise(std::move(launch_session)); // Arm the timer to expire this launch session if the client times out - raised_timer.expires_after(config::stream.ping_timeout); + raised_timer.expires_after(settings.stream.ping_timeout); raised_timer.async_wait([this](const boost::system::error_code &ec) { if (!ec) { auto discarded = launch_event.pop(0s); @@ -763,20 +766,21 @@ namespace rtsp_stream { /** * @brief Bind services before listener callbacks can run. + * @param settings Startup transport and encryption policy. * @param streams Session allocation owner. * @param inputs Host input cleanup owner. * @param videos Encoder capability owner. * @param host_mail Application shutdown mailbox. */ - impl_t(stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail): - server {streams, videos}, + impl_t(const config::settings_t &settings, stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail): + server {settings, streams, videos}, inputs {inputs}, host_mail {std::move(host_mail)} { } }; - service_t::service_t(stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail): - impl {std::make_shared(streams, inputs, videos, std::move(host_mail))} { + service_t::service_t(const config::settings_t &settings, stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail): + impl {std::make_shared(settings, streams, inputs, videos, std::move(host_mail))} { } service_t::~service_t() { @@ -975,14 +979,14 @@ namespace rtsp_stream { std::stringstream ss; // Tell the client about our supported features - ss << "a=x-ss-general.featureFlags:" << (uint32_t) platf::get_capabilities() << std::endl; + ss << "a=x-ss-general.featureFlags:" << (uint32_t) platf::get_capabilities(server->settings) << std::endl; // Always request new control stream encryption if the client supports it uint32_t encryption_flags_supported = SS_ENC_CONTROL_V2 | SS_ENC_AUDIO; uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2; // Determine the encryption desired for this remote endpoint - auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); + auto encryption_mode = net::encryption_mode_for_address(server->settings, sock.remote_endpoint().address()); if (encryption_mode != config::ENCRYPTION_MODE_NEVER) { // Advertise support for video encryption if it's not disabled encryption_flags_supported |= SS_ENC_VIDEO; @@ -1074,11 +1078,11 @@ namespace rtsp_stream { std::uint16_t port; if (type == "audio"sv) { - port = net::map_port(stream::AUDIO_STREAM_PORT); + port = net::map_port(server->settings, stream::AUDIO_STREAM_PORT); } else if (type == "video"sv) { - port = net::map_port(stream::VIDEO_STREAM_PORT); + port = net::map_port(server->settings, stream::VIDEO_STREAM_PORT); } else if (type == "control"sv) { - port = net::map_port(stream::CONTROL_PORT); + port = net::map_port(server->settings, stream::CONTROL_PORT); } else { cmd_not_found(sock, session, std::move(req)); @@ -1217,19 +1221,19 @@ namespace rtsp_stream { } // Limit the packetsize to avoid fragmentation with clients that cannot configure this value - if (config::stream.packetsize && config::stream.packetsize < config.packetsize) { - if (config::stream.packetsize < config::PACKETSIZE_MIN || config::stream.packetsize > config::PACKETSIZE_MAX) { + if (server->settings.stream.packetsize && server->settings.stream.packetsize < config.packetsize) { + if (server->settings.stream.packetsize < config::PACKETSIZE_MIN || server->settings.stream.packetsize > config::PACKETSIZE_MAX) { BOOST_LOG(warning) << "packetsize range: ["sv << config::PACKETSIZE_MIN << "-"sv << config::PACKETSIZE_MAX - << "] invalid value: "sv << config::stream.packetsize; + << "] invalid value: "sv << server->settings.stream.packetsize; } else { - if (config::stream.packetsize < config::PACKETSIZE_SMALL) { + if (server->settings.stream.packetsize < config::PACKETSIZE_SMALL) { BOOST_LOG(info) << "packetsize is small < "sv << config::PACKETSIZE_SMALL << " bytes, reduce bitrate if the stream breaks"sv; - } else if (config::stream.packetsize > config::PACKETSIZE_LARGE) { + } else if (server->settings.stream.packetsize > config::PACKETSIZE_LARGE) { BOOST_LOG(info) << "packetsize is large > "sv << config::PACKETSIZE_LARGE << " bytes, jumbo frames may be used"sv; } - BOOST_LOG(info) << "packetsize limit: "sv << config.packetsize << " -> "sv << config::stream.packetsize << " bytes"sv; - config.packetsize = config::stream.packetsize; + BOOST_LOG(info) << "packetsize limit: "sv << config.packetsize << " -> "sv << server->settings.stream.packetsize << " bytes"sv; + config.packetsize = server->settings.stream.packetsize; } } @@ -1310,8 +1314,8 @@ namespace rtsp_stream { // If the FEC percentage isn't too high, adjust the configured bitrate to ensure video // traffic doesn't exceed the user's selected bitrate when the FEC shards are included. - if (config::stream.fec_percentage <= 80) { - configuredBitrateKbps /= 100.f / (100 - config::stream.fec_percentage); + if (server->settings.stream.fec_percentage <= 80) { + configuredBitrateKbps /= 100.f / (100 - server->settings.stream.fec_percentage); } // Adjust the bitrate to account for audio traffic bandwidth usage (capped at 20% reduction). @@ -1342,7 +1346,7 @@ namespace rtsp_stream { } // Check that any required encryption is enabled - auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); + auto encryption_mode = net::encryption_mode_for_address(server->settings, sock.remote_endpoint().address()); if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY && (config.encryptionFlagsEnabled & (SS_ENC_VIDEO | SS_ENC_AUDIO)) != (SS_ENC_VIDEO | SS_ENC_AUDIO)) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; @@ -1397,8 +1401,8 @@ namespace rtsp_stream { server.map("PLAY"sv, &cmd_play); boost::system::error_code ec; - if (server.bind(net::af_from_enum_string(config::sunshine.address_family), net::map_port(rtsp_stream::RTSP_SETUP_PORT), ec)) { - BOOST_LOG(fatal) << "Couldn't bind RTSP server to port ["sv << net::map_port(rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message(); + if (server.bind(net::af_from_enum_string(server.settings.sunshine.address_family), net::map_port(server.settings, rtsp_stream::RTSP_SETUP_PORT), ec)) { + BOOST_LOG(fatal) << "Couldn't bind RTSP server to port ["sv << net::map_port(server.settings, rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message(); shutdown_event->raise(true); return; diff --git a/src/rtsp.h b/src/rtsp.h index ec5fa1542..f70119313 100644 --- a/src/rtsp.h +++ b/src/rtsp.h @@ -11,6 +11,10 @@ #include "crypto.h" #include "thread_safe.h" +namespace config { + struct settings_t; +} + namespace stream { class service_t; } @@ -66,12 +70,13 @@ namespace rtsp_stream { public: /** * @brief Bind the session owners without opening the listening socket. + * @param settings Startup transport and encryption policy. * @param streams Host stream and broadcast owner. * @param inputs Host input owner for client cleanup. * @param videos Encoder capabilities used in RTSP negotiation. * @param host_mail Host mailbox for listener shutdown. */ - service_t(stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail); + service_t(const config::settings_t &settings, stream::service_t &streams, input::service_t &inputs, video::service_t &videos, safe::mail_t host_mail); /** * @brief Stop and release listener state after the server loop has exited. */ diff --git a/src/stream.cpp b/src/stream.cpp index 4bfd1477e..9eb8c96af 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -387,12 +387,13 @@ namespace stream { /** * @brief Bind the underlying socket or graphics resource to its target. * + * @param settings Startup listener binding policy. * @param address_family Address family. * @param port TCP or UDP port number. * @return Network operation status. */ - int bind(net::af_e address_family, std::uint16_t port) { - _host = net::host_create(address_family, _addr, port); + int bind(const config::settings_t &settings, net::af_e address_family, std::uint16_t port) { + _host = net::host_create(settings, address_family, _addr, port); return !(bool) _host; } @@ -653,6 +654,8 @@ namespace stream { * @brief Explicit host dependencies and lazy broadcast resources shared by stream sessions. */ struct runtime_context_t { + const config::settings_t &settings; ///< Startup transport and capture policy. + audio::service_t &audios; ///< Audio control shared with display restoration. safe::mail_t host_mail; ///< Host packet and shutdown mailbox. thread_pool_util::ThreadPool &scheduler; ///< Host scheduler used for shutdown deadlines. input::service_t &inputs; ///< Shared host input owner. @@ -664,6 +667,7 @@ namespace stream { /** * @brief Bind host services and attach them to each lazy broadcast instance. + * @param settings Startup transport and capture configuration. * @param host_mail Host mailbox. * @param scheduler Host scheduler. * @param inputs Host input owner. @@ -671,8 +675,11 @@ namespace stream { * @param processes Host process owner. * @param displays Host display owner. * @param platform Native streaming resources. + * @param audios Shared host audio capture owner. */ - runtime_context_t(safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform): + runtime_context_t(const config::settings_t &settings, safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform, audio::service_t &audios): + settings {settings}, + audios {audios}, host_mail {std::move(host_mail)}, scheduler {scheduler}, inputs {inputs}, @@ -696,8 +703,8 @@ namespace stream { using runtime_context_t::runtime_context_t; }; - service_t::service_t(safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform): - impl {std::make_shared(std::move(host_mail), scheduler, inputs, videos, processes, displays, platform)} { + service_t::service_t(const config::settings_t &settings, safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform, audio::service_t &audios): + impl {std::make_shared(settings, std::move(host_mail), scheduler, inputs, videos, processes, displays, platform, audios)} { } service_t::~service_t() = default; @@ -831,7 +838,7 @@ namespace stream { return; } - session->pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout; + session->pingTimeout = std::chrono::steady_clock::now() + session->owner->settings.stream.ping_timeout; switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: @@ -1592,8 +1599,10 @@ namespace stream { * @brief Run the broadcast video sender thread. * * @param sock Socket used to read or write the protocol message. + * @param host_mail Host packet and shutdown mailbox. + * @param settings Startup packet redundancy policy. */ - void videoBroadcastThread(udp::socket &sock, safe::mail_t host_mail) { + void videoBroadcastThread(udp::socket &sock, safe::mail_t host_mail, const config::settings_t &settings) { auto shutdown_event = host_mail->event(mail::broadcast_shutdown); auto packets = host_mail->queue(mail::video_packets); auto video_epoch = std::chrono::steady_clock::now(); @@ -1668,7 +1677,7 @@ namespace stream { frame_header.frame_processing_latency = 0; } - auto fecPercentage = config::stream.fec_percentage; + auto fecPercentage = settings.stream.fec_percentage; // Insert space for packet headers auto blocksize = session->config.packetsize + MAX_RTP_HEADER_SIZE; @@ -1919,6 +1928,7 @@ namespace stream { * @brief Run the broadcast audio sender thread. * * @param sock Socket used to read or write the protocol message. + * @param host_mail Host packet and shutdown mailbox. */ void audioBroadcastThread(udp::socket &sock, safe::mail_t host_mail) { auto shutdown_event = host_mail->event(mail::broadcast_shutdown); @@ -2029,13 +2039,13 @@ namespace stream { * @brief Bind the GameStream UDP and control sockets used for a streaming session. */ int start_broadcast(broadcast_ctx_t &ctx) { - auto address_family = net::get_effective_address_family(net::af_from_enum_string(config::sunshine.address_family)); + auto address_family = net::get_effective_address_family(ctx.owner->settings, net::af_from_enum_string(ctx.owner->settings.sunshine.address_family)); auto protocol = address_family == net::IPV4 ? udp::v4() : udp::v6(); - auto control_port = net::map_port(CONTROL_PORT); - auto video_port = net::map_port(VIDEO_STREAM_PORT); - auto audio_port = net::map_port(AUDIO_STREAM_PORT); + auto control_port = net::map_port(ctx.owner->settings, CONTROL_PORT); + auto video_port = net::map_port(ctx.owner->settings, VIDEO_STREAM_PORT); + auto audio_port = net::map_port(ctx.owner->settings, AUDIO_STREAM_PORT); - if (ctx.control_server.bind(address_family, control_port)) { + if (ctx.control_server.bind(ctx.owner->settings, address_family, control_port)) { BOOST_LOG(error) << "Couldn't bind Control server to port ["sv << control_port << "], likely another process already bound to the port"sv; return -1; @@ -2056,7 +2066,7 @@ namespace stream { BOOST_LOG(error) << "Failed to set video socket send buffer size (SO_SENDBUF)"; } - auto bind_addr_str = net::get_bind_address(address_family); + auto bind_addr_str = net::get_bind_address(ctx.owner->settings, address_family); const auto bind_addr = boost::asio::ip::make_address(bind_addr_str, ec); if (ec) { BOOST_LOG(fatal) << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); @@ -2086,7 +2096,7 @@ namespace stream { ctx.message_queue_queue = std::make_shared(30); - ctx.video_thread = std::jthread {videoBroadcastThread, std::ref(ctx.video_sock), ctx.owner->host_mail}; + ctx.video_thread = std::jthread {videoBroadcastThread, std::ref(ctx.video_sock), ctx.owner->host_mail, std::cref(ctx.owner->settings)}; ctx.audio_thread = std::jthread {audioBroadcastThread, std::ref(ctx.audio_sock), ctx.owner->host_mail}; ctx.control_thread = std::jthread {controlBroadcastThread, &ctx.control_server}; @@ -2167,10 +2177,10 @@ namespace stream { auto start_time = std::chrono::steady_clock::now(); auto current_time = start_time; - while (current_time - start_time < config::stream.ping_timeout) { + while (current_time - start_time < session->owner->settings.stream.ping_timeout) { auto delta_time = current_time - start_time; - auto msg_opt = messages->pop(config::stream.ping_timeout - delta_time); + auto msg_opt = messages->pop(session->owner->settings.stream.ping_timeout - delta_time); if (!msg_opt) { break; } @@ -2211,7 +2221,7 @@ namespace stream { while_starting_do_nothing(session->state); auto ref = session->owner->broadcast.ref(); - auto error = recv_ping(session, ref, socket_e::video, session->video.ping_payload, session->video.peer, config::stream.ping_timeout); + auto error = recv_ping(session, ref, socket_e::video, session->video.ping_payload, session->video.peer, session->owner->settings.stream.ping_timeout); if (error < 0) { return; } @@ -2238,7 +2248,7 @@ namespace stream { while_starting_do_nothing(session->state); auto ref = session->owner->broadcast.ref(); - auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, config::stream.ping_timeout); + auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, session->owner->settings.stream.ping_timeout); if (error < 0) { return; } @@ -2248,7 +2258,7 @@ namespace stream { session->audio.qos = session->owner->platform.enable_socket_qos(ref->audio_sock.native_handle(), address, session->audio.peer.port(), platf::qos_data_type_e::audio, session->config.audioQosType != 0); BOOST_LOG(debug) << "Start capturing Audio"sv; - audio::capture(session->owner->host_mail, session->mail, session->config.audio, session); + session->owner->audios.capture(session->mail, session->config.audio, session); } namespace session { @@ -2311,7 +2321,7 @@ namespace stream { // If this is the last session, invoke the platform callbacks if (--session.broadcast_ref->running_sessions == 0) { - bool revert_display_config {config::video.dd.config_revert_on_disconnect}; + bool revert_display_config {session.owner->settings.video.dd.config_revert_on_disconnect}; if (session.owner->processes.running()) { #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 system_tray::update_tray_pausing(session.owner->processes.get_last_run_app_name()); @@ -2359,7 +2369,7 @@ namespace stream { session.audio.peer.address(addr); session.audio.peer.port(0); - session.pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout; + session.pingTimeout = std::chrono::steady_clock::now() + session.owner->settings.stream.ping_timeout; session.audioThread = std::jthread {audioThread, &session}; session.videoThread = std::jthread {videoThread, &session}; @@ -2378,7 +2388,11 @@ namespace stream { } /** - * @brief Allocate and initialize platform input state for a stream. + * @brief Allocate stopped session state and retain its explicit host dependencies. + * @param owner Host service state retained until all session resources release. + * @param config Negotiated transport and encoder settings. + * @param launch_session Client identity, encryption keys, and connection callback. + * @return Newly allocated session; workers and platform input start separately. */ std::shared_ptr alloc(std::shared_ptr owner, config_t &config, rtsp_stream::launch_session_t &launch_session) { auto session = std::make_shared(); diff --git a/src/stream.h b/src/stream.h index 26e7c3e7a..91b0cfd5f 100644 --- a/src/stream.h +++ b/src/stream.h @@ -108,6 +108,7 @@ namespace stream { public: /** * @brief Bind the host dependencies without opening streaming sockets. + * @param settings Startup transport and capture configuration. * @param host_mail Application packet and shutdown mailbox. * @param scheduler Application task scheduler. * @param inputs Host input owner. @@ -115,8 +116,9 @@ namespace stream { * @param processes Application process owner. * @param displays Display settings and restore owner. * @param platform Native streaming hooks and socket priority owner. + * @param audios Shared host audio capture owner. */ - service_t(safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform); + service_t(const config::settings_t &settings, safe::mail_t host_mail, thread_pool_util::ThreadPool &scheduler, input::service_t &inputs, video::service_t &videos, proc::proc_t &processes, display_device::manager_t &displays, platf::runtime_t &platform, audio::service_t &audios); /** * @brief Release the broadcast owner after all session references stop. */ diff --git a/src/system_tray.cpp b/src/system_tray.cpp index 734310309..c18a82caf 100644 --- a/src/system_tray.cpp +++ b/src/system_tray.cpp @@ -185,7 +185,9 @@ namespace system_tray { void tray_open_ui_cb([[maybe_unused]] struct tray_menu *item) { BOOST_LOG(info) << "Opening UI from system tray"sv; - launch_ui(); + if (item && item->context) { + launch_ui(static_cast(item->context)->settings); + } } void tray_donate_github_cb([[maybe_unused]] struct tray_menu *item) { @@ -203,10 +205,14 @@ namespace system_tray { #if defined(_WIN32) || defined(__APPLE__) void tray_virtualhid_license_cb([[maybe_unused]] struct tray_menu *item) { BOOST_LOG(info) << "Opening Virtual HID Broker license settings from system tray"sv; + if (!item || !item->context) { + return; + } + const auto &settings = static_cast(item->context)->settings; #ifdef _WIN32 - launch_ui(config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS ? "/config#gamepad_driver" : "/troubleshooting#virtualhid-license"); + launch_ui(settings, settings.input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS ? "/config#gamepad_driver" : "/troubleshooting#virtualhid-license"); #else - launch_ui("/troubleshooting#virtualhid-license"); + launch_ui(settings, "/troubleshooting#virtualhid-license"); #endif } @@ -244,28 +250,36 @@ namespace system_tray { void tray_reset_display_device_config_cb([[maybe_unused]] struct tray_menu *item) { BOOST_LOG(info) << "Resetting display device config from system tray"sv; - std::ignore = display_device::reset_persistence(); + if (item && item->context) { + std::ignore = static_cast(item->context)->displays.reset_persistence(); + } } void tray_restart_cb([[maybe_unused]] struct tray_menu *item) { BOOST_LOG(info) << "Restarting from system tray"sv; - platf::restart(); + if (item && item->context) { + platf::restart(static_cast(item->context)->lifetime); + } } void tray_quit_cb([[maybe_unused]] struct tray_menu *item) { BOOST_LOG(info) << "Quitting from system tray"sv; + if (!item || !item->context) { + return; + } + auto &lifetime = static_cast(item->context)->lifetime; #ifdef _WIN32 // If we're running in a service, return a special status to // tell it to terminate too, otherwise it will just respawn us. if (GetConsoleWindow() == nullptr) { - lifetime::exit_sunshine(ERROR_SHUTDOWN_IN_PROGRESS, true); + lifetime.exit_sunshine(ERROR_SHUTDOWN_IN_PROGRESS, true); return; } #endif - lifetime::exit_sunshine(0, true); + lifetime.exit_sunshine(0, true); } #if defined(_WIN32) || defined(__APPLE__) @@ -346,6 +360,46 @@ namespace system_tray { #endif }; + application_binding_t::application_binding_t(const config::settings_t &settings, lifetime::controller_t &lifetime, display_device::manager_t &displays): + settings {settings}, + lifetime {lifetime}, + displays {displays} { + for (auto item = tray.menu; item->text; ++item) { + item->context = this; + if (item->submenu) { + for (auto child = item->submenu; child->text; ++child) { + child->context = this; + } + } + } + } + + application_binding_t::~application_binding_t() { + end_tray(); + for (auto item = tray.menu; item->text; ++item) { + if (item->context == this) { + item->context = nullptr; + } + if (item->submenu) { + for (auto child = item->submenu; child->text; ++child) { + if (child->context == this) { + child->context = nullptr; + } + } + } + } + } + + /** + * @brief Open a Web UI route from a native notification lacking a userdata parameter. + * @param path Route opened using the application's bound settings. + */ + void open_bound_ui(const std::optional &path) { + if (tray.menu[0].context) { + launch_ui(static_cast(tray.menu[0].context)->settings, path); + } + } + #ifdef SUNSHINE_TESTS const struct tray &tray_data_for_testing() { return tray; @@ -446,6 +500,7 @@ namespace system_tray { .text = menu_text[index].c_str(), .disabled = disabled, .cb = callback, + .context = tray.menu[0].context, }; } @@ -511,36 +566,36 @@ namespace system_tray { tray.notification_icon = nullptr; } - void update_tray_virtualhid_license(const lvh::LicenseStatus &license, const bool notify_if_unlicensed) { + void update_tray_virtualhid_license(const config::settings_t &settings, const lvh::LicenseStatus &license, const bool notify_if_unlicensed) { const std::scoped_lock lock(tray_state_mutex()); clear_tray_notification(); rebuild_virtualhid_license_menu(license); #ifdef _WIN32 - if (config::input.controller && config::input.gamepad_driver.empty()) { + if (settings.input.controller && settings.input.gamepad_driver.empty()) { tray.notification_title = "Choose a Gamepad Backend"; tray.notification_text = "Choose a gamepad backend in Input settings. Virtual HID Broker is a paid upgrade; ViGEmBus is limited and has reached end of life."; tray.notification_icon = tray.allIconPaths[4]; tray.notification_cb = []() { - launch_ui("/config#gamepad_driver"); + open_bound_ui("/config#gamepad_driver"); }; - } else if (config::input.controller && config::input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && config::input.gamepad_driver != config::GAMEPAD_DRIVER_VIGEMBUS && notify_if_unlicensed && !license.licensed()) { + } else if (settings.input.controller && settings.input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && settings.input.gamepad_driver != config::GAMEPAD_DRIVER_VIGEMBUS && notify_if_unlicensed && !license.licensed()) { tray.notification_title = "Virtual HID Broker License"; tray.notification_text = "Get or manage a license, or use the limited, end-of-life ViGEmBus driver."; tray.notification_icon = tray.allIconPaths[4]; tray.notification_cb = []() { - launch_ui("/troubleshooting#virtualhid-license"); + open_bound_ui("/troubleshooting#virtualhid-license"); }; } #else - if (config::input.controller && config::input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && notify_if_unlicensed && !license.licensed()) { + if (settings.input.controller && settings.input.gamepad_driver != config::GAMEPAD_DRIVER_NONE && notify_if_unlicensed && !license.licensed()) { if (license.service_available) { tray.notification_title = "Virtual HID Broker License"; tray.notification_text = "Activate a machine license to use virtual gamepads. Click to manage the license."; tray.notification_cb = []() { - launch_ui("/troubleshooting#virtualhid-license"); + open_bound_ui("/troubleshooting#virtualhid-license"); }; } else { tray.notification_title = "Virtual HID Broker Is Unavailable"; @@ -558,22 +613,17 @@ namespace system_tray { } } - void prepare_tray_virtualhid_license() { + void prepare_tray_virtualhid_license(const config::settings_t &settings) { const auto result = lvh::get_license_status(); - update_tray_virtualhid_license(result.license, !result.license.licensed()); + update_tray_virtualhid_license(settings, result.license, !result.license.licensed()); } - void update_tray_virtualhid_driver( - const bool installed, - const std::string_view version, - const bool version_compatible, - const std::string_view supported_versions - ) { - if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE || !installed || version_compatible) { + void update_tray_virtualhid_driver(const config::settings_t &settings, const bool installed, const std::string_view version, const bool version_compatible, const std::string_view supported_versions) { + if (settings.input.gamepad_driver == config::GAMEPAD_DRIVER_NONE || !installed || version_compatible) { return; } #ifdef _WIN32 - if (config::input.gamepad_driver.empty() || config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { + if (settings.input.gamepad_driver.empty() || settings.input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { return; } #endif @@ -592,7 +642,7 @@ namespace system_tray { tray.notification_text = notification_text.c_str(); tray.notification_icon = tray.allIconPaths[4]; tray.notification_cb = []() { - launch_ui("/troubleshooting#virtualhid"); + open_bound_ui("/troubleshooting#virtualhid"); }; BOOST_LOG(warning) << notification_text; @@ -601,14 +651,9 @@ namespace system_tray { } } - void prepare_tray_virtualhid_driver() { + void prepare_tray_virtualhid_driver(const config::settings_t &settings) { const auto status = confighttp::get_virtualhid_driver_status(); - update_tray_virtualhid_driver( - status.value("installed", false), - status.value("version", std::string {}), - status.value("version_compatible", false), - status.value("supported_versions", std::string {}) - ); + update_tray_virtualhid_driver(settings, status.value("installed", false), status.value("version", std::string {}), status.value("version_compatible", false), status.value("supported_versions", std::string {})); } #endif @@ -941,7 +986,7 @@ namespace system_tray { tray.notification_icon = tray.allIconPaths[1]; tray.tooltip = PROJECT_NAME; tray.notification_cb = []() { - launch_ui("/pin"); + open_bound_ui("/pin"); }; tray_update(&tray); } @@ -996,3 +1041,16 @@ namespace system_tray { } // namespace system_tray #endif + +#if !defined(SUNSHINE_TRAY) || SUNSHINE_TRAY < 1 + #include "system_tray.h" + +namespace system_tray { + application_binding_t::application_binding_t(const config::settings_t &settings, lifetime::controller_t &lifetime, display_device::manager_t &displays): + settings {settings}, + lifetime {lifetime}, + displays {displays} {} + + application_binding_t::~application_binding_t() = default; +} // namespace system_tray +#endif diff --git a/src/system_tray.h b/src/system_tray.h index e0eaf6e64..2383ceeab 100644 --- a/src/system_tray.h +++ b/src/system_tray.h @@ -3,12 +3,21 @@ * @brief Declarations for the system tray icon and notification system. */ #pragma once +#include "config.h" // standard includes #include #include #include +namespace lifetime { + class controller_t; +} + +namespace display_device { + class manager_t; +} + namespace safe { template class event_t; @@ -24,6 +33,28 @@ namespace lvh { * @brief Handles the system tray icon and notification system. */ namespace system_tray { + /** + * @brief Bind native tray callbacks to the application's scoped owners. + */ + class application_binding_t { + public: + /** + * @brief Attach callback userdata before creating the native tray. + * @param settings Application settings used by native callbacks. + * @param lifetime Application termination controller. + * @param displays Display restoration owner. + */ + application_binding_t(const config::settings_t &settings, lifetime::controller_t &lifetime, display_device::manager_t &displays); + /** @brief Stop native callbacks before their dependencies are destroyed. */ + ~application_binding_t(); + application_binding_t(const application_binding_t &) = delete; + application_binding_t &operator=(const application_binding_t &) = delete; + + const config::settings_t &settings; ///< Settings used by native UI callbacks. + lifetime::controller_t &lifetime; ///< Application termination controller. + display_device::manager_t &displays; ///< Display restoration owner. + }; + /** * @brief Callback for opening the UI from the system tray. * @param item The tray menu item. @@ -132,15 +163,17 @@ namespace system_tray { /** * @brief Update the Virtual HID Broker license submenu and optional notification. * + * @param settings Application input configuration. * @param license Latest machine license details. * @param notify_if_unlicensed Whether to notify the user when the broker needs a license. */ - void update_tray_virtualhid_license(const lvh::LicenseStatus &license, bool notify_if_unlicensed); + void update_tray_virtualhid_license(const config::settings_t &settings, const lvh::LicenseStatus &license, bool notify_if_unlicensed); /** * @brief Query the Virtual HID Broker license and prepare the startup tray state. + * @param settings Application input configuration. */ - void prepare_tray_virtualhid_license(); + void prepare_tray_virtualhid_license(const config::settings_t &settings); /** * @brief Show an update notification for an unsupported Virtual HID Broker. @@ -149,21 +182,18 @@ namespace system_tray { * or the Windows backend choice does not use the broker. * * @param installed Whether the broker is installed. + * @param settings Application input configuration. * @param version Installed broker version. * @param version_compatible Whether Sunshine supports the installed version. * @param supported_versions User-visible supported version range. */ - void update_tray_virtualhid_driver( - bool installed, - std::string_view version, - bool version_compatible, - std::string_view supported_versions - ); + void update_tray_virtualhid_driver(const config::settings_t &settings, bool installed, std::string_view version, bool version_compatible, std::string_view supported_versions); /** * @brief Query the Virtual HID Broker version and prepare its startup notification. + * @param settings Application input configuration. */ - void prepare_tray_virtualhid_driver(); + void prepare_tray_virtualhid_driver(const config::settings_t &settings); #endif /** diff --git a/src/upnp.cpp b/src/upnp.cpp index d983ce15d..b023aa646 100644 --- a/src/upnp.cpp +++ b/src/upnp.cpp @@ -71,14 +71,21 @@ namespace upnp { */ class deinit_t: public platf::deinit_t { public: - deinit_t() { - auto rtsp = std::to_string(net::map_port(rtsp_stream::RTSP_SETUP_PORT)); - auto video = std::to_string(net::map_port(stream::VIDEO_STREAM_PORT)); - auto audio = std::to_string(net::map_port(stream::AUDIO_STREAM_PORT)); - auto control = std::to_string(net::map_port(stream::CONTROL_PORT)); - auto gs_http = std::to_string(net::map_port(nvhttp::PORT_HTTP)); - auto gs_https = std::to_string(net::map_port(nvhttp::PORT_HTTPS)); - auto wm_http = std::to_string(net::map_port(confighttp::PORT_HTTPS)); + /** + * @brief Start port mapping with the application's shutdown event. + * @param settings Application network configuration. + * @param host_mail Application-owned shutdown mailbox. + */ + deinit_t(const config::settings_t &settings, safe::mail_t host_mail): + settings {settings}, + host_mail {std::move(host_mail)} { + auto rtsp = std::to_string(net::map_port(settings, rtsp_stream::RTSP_SETUP_PORT)); + auto video = std::to_string(net::map_port(settings, stream::VIDEO_STREAM_PORT)); + auto audio = std::to_string(net::map_port(settings, stream::AUDIO_STREAM_PORT)); + auto control = std::to_string(net::map_port(settings, stream::CONTROL_PORT)); + auto gs_http = std::to_string(net::map_port(settings, nvhttp::PORT_HTTP)); + auto gs_https = std::to_string(net::map_port(settings, nvhttp::PORT_HTTPS)); + auto wm_http = std::to_string(net::map_port(settings, confighttp::PORT_HTTPS)); mappings.assign({ {{rtsp, rtsp, "TCP"s}, "Sunshine - RTSP"s}, @@ -90,7 +97,7 @@ namespace upnp { }); // Only map port for the Web Manager if it is configured to accept connection from WAN - if (net::from_enum_string(config::nvhttp.origin_web_ui_allowed) > net::LAN) { + if (net::from_enum_string(settings.nvhttp.origin_web_ui_allowed) > net::LAN) { mappings.emplace_back(mapping_t {{wm_http, wm_http, "TCP"s}, "Sunshine - Web UI"s}); } @@ -142,7 +149,7 @@ namespace upnp { if (pinholeAllowed) { // Create pinholes for each port auto mapping_period = std::to_string(PORT_MAPPING_LIFETIME.count()); - auto shutdown_event = mail::man->event(mail::shutdown); + auto shutdown_event = host_mail->event(mail::shutdown); for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) { auto mapping = *it; @@ -311,11 +318,11 @@ namespace upnp { */ void upnp_thread_proc() { platf::set_thread_name("upnp"); - auto shutdown_event = mail::man->event(mail::shutdown); + auto shutdown_event = host_mail->event(mail::shutdown); bool mapped = false; IGDdatas data; urls_t mapped_urls; - auto address_family = net::get_effective_address_family(net::af_from_enum_string(config::sunshine.address_family)); + auto address_family = net::get_effective_address_family(settings, net::af_from_enum_string(settings.sunshine.address_family)); // Refresh UPnP rules every few minutes. They can be lost if the router reboots, // WAN IP address changes, or various other conditions. @@ -374,17 +381,19 @@ namespace upnp { } std::vector mappings; ///< Port mappings Sunshine should keep registered with the gateway. + const config::settings_t &settings; ///< Startup port and address policy. + safe::mail_t host_mail; ///< Application-owned shutdown mailbox. std::jthread upnp_thread; ///< Worker thread that refreshes mappings until shutdown. }; /** * @brief Start UPnP port mapping and return its shutdown guard. */ - std::unique_ptr start() { - if (!config::sunshine.flags[config::flag::UPNP]) { + std::unique_ptr start(const config::settings_t &settings, safe::mail_t host_mail) { + if (!settings.sunshine.flags[config::flag::UPNP]) { return nullptr; } - return std::make_unique(); + return std::make_unique(settings, std::move(host_mail)); } } // namespace upnp diff --git a/src/upnp.h b/src/upnp.h index f34b90fa6..6a854670f 100644 --- a/src/upnp.h +++ b/src/upnp.h @@ -46,7 +46,9 @@ namespace upnp { /** * @brief Start UPnP port mapping and return its shutdown guard. * + * @param settings Application network configuration. + * @param host_mail Application-owned shutdown mailbox. * @return Start status. */ - [[nodiscard]] std::unique_ptr start(); + [[nodiscard]] std::unique_ptr start(const config::settings_t &settings, safe::mail_t host_mail); } // namespace upnp diff --git a/src/video.cpp b/src/video.cpp index 2eb1ad1e3..ea807a274 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -197,10 +197,11 @@ namespace video { /** * @brief Create an FFmpeg hardware device buffer for VA-API input. * + * @param settings Host render-device selection settings. * @param encode_device Encode device. * @return Hardware buffer on success, or an error code on failure. */ - util::Either vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); + util::Either vaapi_init_avcodec_hardware_input_buffer(const config::settings_t &settings, platf::avcodec_encode_device_t *encode_device); /** * @brief Create an FFmpeg hardware device buffer for CUDA input. * @@ -218,9 +219,11 @@ namespace video { /** * @brief Create an FFmpeg hardware device buffer for Vulkan input. * + * @param settings Host render-device selection settings. + * @param encode_device Native encoding device to initialize. * @return Hardware buffer on success, or an error code on failure. */ - util::Either vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); + util::Either vulkan_init_avcodec_hardware_input_buffer(const config::settings_t &settings, platf::avcodec_encode_device_t *encode_device); int avcodec_software_encode_device_t::convert(platf::img_t &img) { // If we need to add aspect ratio padding, we need to scale into an intermediate output buffer @@ -386,7 +389,7 @@ namespace video { av_dict_set_int(&options, "dsth", sws_output_frame->height, 0); av_dict_set_int(&options, "dst_format", sws_output_frame->format, 0); av_dict_set_int(&options, "sws_flags", SWS_LANCZOS | SWS_ACCURATE_RND, 0); - av_dict_set_int(&options, "threads", config::video.min_threads, 0); + av_dict_set_int(&options, "threads", min_threads_, 0); auto status = av_opt_set_dict(sws.get(), &options); av_dict_free(&options); @@ -695,10 +698,11 @@ namespace video { /** * @brief Start the asynchronous capture thread. * - * @param ctx Native context object used by the operation or callback. + * @param host Host video service and its capture dependencies. + * @param capture_thread_ctx Capture coordinator to initialize. * @return 0 when the capture thread is started; nonzero on setup failure. */ - int start_capture_async(service_t::impl_t &host, capture_thread_async_ctx_t &ctx); + int start_capture_async(service_t::impl_t &host, capture_thread_async_ctx_t &capture_thread_ctx); /** * @brief Stop capture async processing. * @@ -708,9 +712,10 @@ namespace video { /** * @brief Copy immutable encoder descriptors for one service's probe state. + * @param settings Immutable host encoder configuration. * @return Independent encoder descriptors with shared immutable format metadata. */ - std::vector make_encoders(); + std::vector make_encoders(const config::settings_t &settings); /** * @brief Capture coordinators and encoder state owned by one video service. @@ -718,16 +723,19 @@ namespace video { struct service_t::impl_t { /** * @brief Bind capture dependencies and construct inactive coordinators. + * @param settings Immutable encoder and capture configuration. * @param mail Host mailbox for encoded packets and display selection. * @param cursor Host cursor visibility preference. * @param displays Display configuration manager. + * @param platform Native capture backend owner. */ - impl_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): + impl_t(const config::settings_t &settings, safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): + settings {settings}, mail {std::move(mail)}, cursor {cursor}, displays {displays}, platform {platform}, - encoders {make_encoders()}, + encoders {make_encoders(settings)}, capture_thread_async { [this](capture_thread_async_ctx_t &ctx) { return start_capture_async(*this, ctx); @@ -746,6 +754,7 @@ namespace video { } { } + const config::settings_t &settings; ///< Host startup encoder and capture configuration. safe::mail_t mail; ///< Host packet and lifecycle mailbox. bool &cursor; ///< Host cursor visibility preference. display_device::manager_t &displays; ///< Display configuration dependency. @@ -761,662 +770,689 @@ namespace video { #ifdef _WIN32 /** - * @brief NVENC. + * @brief Construct an NVENC descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. */ - const encoder_t nvenc { - "nvenc"sv, - std::make_unique( - platf::mem_type_e::dxgi, - platf::pix_fmt_e::nv12, - platf::pix_fmt_e::p010, - platf::pix_fmt_e::ayuv, - platf::pix_fmt_e::yuv444p16 - ), - { - {}, // Common options - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_nvenc"s, - {}, // capabilities - }, - { - {}, // Common options - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_nvenc"s, - {}, // capabilities - }, - { - {}, // Common options - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "h264_nvenc"s, - {}, // capabilities - }, - PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT | ASYNC_TEARDOWN // flags - }; + encoder_t make_nvenc(const config::settings_t &settings) { + return { + "nvenc"sv, + std::make_unique( + platf::mem_type_e::dxgi, + platf::pix_fmt_e::nv12, + platf::pix_fmt_e::p010, + platf::pix_fmt_e::ayuv, + platf::pix_fmt_e::yuv444p16 + ), + { + {}, // Common options + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_nvenc"s, + {}, // capabilities + }, + { + {}, // Common options + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_nvenc"s, + {}, // capabilities + }, + { + {}, // Common options + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "h264_nvenc"s, + {}, // capabilities + }, + PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT | ASYNC_TEARDOWN // flags + }; + } #elif !defined(__APPLE__) - const encoder_t nvenc { - "nvenc"sv, - std::make_unique( + /** + * @brief Construct an NVENC descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_nvenc(const config::settings_t &settings) { + return { + "nvenc"sv, + std::make_unique( #ifdef _WIN32 - AV_HWDEVICE_TYPE_D3D11VA, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_D3D11, + AV_HWDEVICE_TYPE_D3D11VA, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_D3D11, #else - AV_HWDEVICE_TYPE_CUDA, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_CUDA, + AV_HWDEVICE_TYPE_CUDA, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_CUDA, #endif - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_YUV444P, - AV_PIX_FMT_YUV444P16, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_YUV444P, + AV_PIX_FMT_YUV444P16, #ifdef _WIN32 - dxgi_init_avcodec_hardware_input_buffer + dxgi_init_avcodec_hardware_input_buffer #else - cuda_init_avcodec_hardware_input_buffer + cuda_init_avcodec_hardware_input_buffer #endif - ), - { - // Common options + ), { - {"delay"s, 0}, - {"forced-idr"s, 1}, - {"zerolatency"s, 1}, - {"surfaces"s, 1}, - {"cbr_padding"s, false}, - {"preset"s, &config::video.nv_legacy.preset}, - {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, - {"rc"s, NV_ENC_PARAMS_RC_CBR}, - {"multipass"s, &config::video.nv_legacy.multipass}, - {"spatial-aq"s, &config::video.nv_legacy.spatial_aq}, - }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_nvenc"s, - {}, // capabilities - }, - { - // Common options - { - {"delay"s, 0}, - {"forced-idr"s, 1}, - {"zerolatency"s, 1}, - {"surfaces"s, 1}, - {"cbr_padding"s, false}, - {"preset"s, &config::video.nv_legacy.preset}, - {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, - {"rc"s, NV_ENC_PARAMS_RC_CBR}, - {"multipass"s, &config::video.nv_legacy.multipass}, - {"spatial-aq"s, &config::video.nv_legacy.spatial_aq}, + // Common options + { + {"delay"s, 0}, + {"forced-idr"s, 1}, + {"zerolatency"s, 1}, + {"surfaces"s, 1}, + {"cbr_padding"s, false}, + {"preset"s, &settings.video.nv_legacy.preset}, + {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, + {"rc"s, NV_ENC_PARAMS_RC_CBR}, + {"multipass"s, &settings.video.nv_legacy.multipass}, + {"spatial-aq"s, &settings.video.nv_legacy.spatial_aq}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_nvenc"s, + {}, // capabilities }, { - // SDR-specific options - {"profile"s, std::to_underlying(nv::profile_hevc_e::main)}, + // Common options + { + {"delay"s, 0}, + {"forced-idr"s, 1}, + {"zerolatency"s, 1}, + {"surfaces"s, 1}, + {"cbr_padding"s, false}, + {"preset"s, &settings.video.nv_legacy.preset}, + {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, + {"rc"s, NV_ENC_PARAMS_RC_CBR}, + {"multipass"s, &settings.video.nv_legacy.multipass}, + {"spatial-aq"s, &settings.video.nv_legacy.spatial_aq}, + }, + { + // SDR-specific options + {"profile"s, std::to_underlying(nv::profile_hevc_e::main)}, + }, + { + // HDR-specific options + {"profile"s, std::to_underlying(nv::profile_hevc_e::main_10)}, + }, + // libavcodec will automatically use the rext profile for + // YUV444 SDR and HDR content, so it doesn't need to be specified here + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_nvenc"s, + {}, // capabilities }, { - // HDR-specific options - {"profile"s, std::to_underlying(nv::profile_hevc_e::main_10)}, + { + {"delay"s, 0}, + {"forced-idr"s, 1}, + {"zerolatency"s, 1}, + {"surfaces"s, 1}, + {"cbr_padding"s, false}, + {"preset"s, &settings.video.nv_legacy.preset}, + {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, + {"rc"s, NV_ENC_PARAMS_RC_CBR}, + {"coder"s, &settings.video.nv_legacy.h264_coder}, + {"multipass"s, &settings.video.nv_legacy.multipass}, + {"spatial-aq"s, &settings.video.nv_legacy.spatial_aq}, + }, + { + // SDR-specific options + {"profile"s, std::to_underlying(nv::profile_h264_e::high)}, + }, + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "h264_nvenc"s, + {}, // capabilities }, - // libavcodec will automatically use the rext profile for - // YUV444 SDR and HDR content, so it doesn't need to be specified here - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_nvenc"s, - {}, // capabilities - }, - { - { - {"delay"s, 0}, - {"forced-idr"s, 1}, - {"zerolatency"s, 1}, - {"surfaces"s, 1}, - {"cbr_padding"s, false}, - {"preset"s, &config::video.nv_legacy.preset}, - {"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY}, - {"rc"s, NV_ENC_PARAMS_RC_CBR}, - {"coder"s, &config::video.nv_legacy.h264_coder}, - {"multipass"s, &config::video.nv_legacy.multipass}, - {"spatial-aq"s, &config::video.nv_legacy.spatial_aq}, - }, - { - // SDR-specific options - {"profile"s, std::to_underlying(nv::profile_h264_e::high)}, - }, - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "h264_nvenc"s, - {}, // capabilities - }, - PARALLEL_ENCODING | YUV444_SUPPORT - }; + PARALLEL_ENCODING | YUV444_SUPPORT + }; + } #endif #ifdef _WIN32 /** * @brief Quicksync. */ - const encoder_t quicksync { - "quicksync"sv, - std::make_unique( - AV_HWDEVICE_TYPE_D3D11VA, - AV_HWDEVICE_TYPE_QSV, - AV_PIX_FMT_QSV, - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_VUYX, - AV_PIX_FMT_XV30, - dxgi_init_avcodec_hardware_input_buffer - ), - { - // Common options + encoder_t make_quicksync(const config::settings_t &settings) { + return { + "quicksync"sv, + std::make_unique( + AV_HWDEVICE_TYPE_D3D11VA, + AV_HWDEVICE_TYPE_QSV, + AV_PIX_FMT_QSV, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_VUYX, + AV_PIX_FMT_XV30, + dxgi_init_avcodec_hardware_input_buffer + ), { - {"preset"s, &config::video.qsv.qsv_preset}, - {"forced_idr"s, 1}, - {"async_depth"s, 1}, - {"low_delay_brc"s, 1}, - {"low_power"s, 1}, + // Common options + { + {"preset"s, &settings.video.qsv.qsv_preset}, + {"forced_idr"s, 1}, + {"async_depth"s, 1}, + {"low_delay_brc"s, 1}, + {"low_power"s, 1}, + }, + { + // SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_av1_e::main)}, + }, + { + // HDR-specific options + {"profile"s, std::to_underlying(qsv::profile_av1_e::main)}, + }, + { + // YUV444 SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_av1_e::high)}, + }, + { + // YUV444 HDR-specific options + {"profile"s, std::to_underlying(qsv::profile_av1_e::high)}, + }, + {}, // Fallback options + "av1_qsv"s, + {}, // capabilities }, { - // SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_av1_e::main)}, + // Common options + { + {"preset"s, &settings.video.qsv.qsv_preset}, + {"forced_idr"s, 1}, + {"async_depth"s, 1}, + {"low_delay_brc"s, 1}, + {"low_power"s, 1}, + {"recovery_point_sei"s, 0}, + {"pic_timing_sei"s, 0}, + }, + { + // SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_hevc_e::main)}, + }, + { + // HDR-specific options + {"profile"s, std::to_underlying(qsv::profile_hevc_e::main_10)}, + }, + { + // YUV444 SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)}, + }, + { + // YUV444 HDR-specific options + {"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)}, + }, + { + // Fallback options + {"low_power"s, [&settings]() { + return settings.video.qsv.qsv_slow_hevc ? 0 : 1; + }}, + }, + "hevc_qsv"s, + {}, // capabilities }, { - // HDR-specific options - {"profile"s, std::to_underlying(qsv::profile_av1_e::main)}, + // Common options + { + {"preset"s, &settings.video.qsv.qsv_preset}, + {"cavlc"s, &settings.video.qsv.qsv_cavlc}, + {"forced_idr"s, 1}, + {"async_depth"s, 1}, + {"low_delay_brc"s, 1}, + {"low_power"s, 1}, + {"recovery_point_sei"s, 0}, + {"vcm"s, 1}, + {"pic_timing_sei"s, 0}, + {"max_dec_frame_buffering"s, 1}, + }, + { + // SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_h264_e::high)}, + }, + {}, // HDR-specific options + { + // YUV444 SDR-specific options + {"profile"s, std::to_underlying(qsv::profile_h264_e::high_444p)}, + }, + {}, // YUV444 HDR-specific options + { + // Fallback options + {"low_power"s, 0}, // Some old/low-end Intel GPUs don't support low power encoding + }, + "h264_qsv"s, + {}, // capabilities }, - { - // YUV444 SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_av1_e::high)}, - }, - { - // YUV444 HDR-specific options - {"profile"s, std::to_underlying(qsv::profile_av1_e::high)}, - }, - {}, // Fallback options - "av1_qsv"s, - {}, // capabilities - }, - { - // Common options - { - {"preset"s, &config::video.qsv.qsv_preset}, - {"forced_idr"s, 1}, - {"async_depth"s, 1}, - {"low_delay_brc"s, 1}, - {"low_power"s, 1}, - {"recovery_point_sei"s, 0}, - {"pic_timing_sei"s, 0}, - }, - { - // SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_hevc_e::main)}, - }, - { - // HDR-specific options - {"profile"s, std::to_underlying(qsv::profile_hevc_e::main_10)}, - }, - { - // YUV444 SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)}, - }, - { - // YUV444 HDR-specific options - {"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)}, - }, - { - // Fallback options - {"low_power"s, []() { - return config::video.qsv.qsv_slow_hevc ? 0 : 1; - }}, - }, - "hevc_qsv"s, - {}, // capabilities - }, - { - // Common options - { - {"preset"s, &config::video.qsv.qsv_preset}, - {"cavlc"s, &config::video.qsv.qsv_cavlc}, - {"forced_idr"s, 1}, - {"async_depth"s, 1}, - {"low_delay_brc"s, 1}, - {"low_power"s, 1}, - {"recovery_point_sei"s, 0}, - {"vcm"s, 1}, - {"pic_timing_sei"s, 0}, - {"max_dec_frame_buffering"s, 1}, - }, - { - // SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_h264_e::high)}, - }, - {}, // HDR-specific options - { - // YUV444 SDR-specific options - {"profile"s, std::to_underlying(qsv::profile_h264_e::high_444p)}, - }, - {}, // YUV444 HDR-specific options - { - // Fallback options - {"low_power"s, 0}, // Some old/low-end Intel GPUs don't support low power encoding - }, - "h264_qsv"s, - {}, // capabilities - }, - PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT | YUV444_SUPPORT - }; + PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT | YUV444_SUPPORT + }; + } /** * @brief Amdvce. */ - const encoder_t amdvce { - "amdvce"sv, - std::make_unique( - AV_HWDEVICE_TYPE_D3D11VA, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_D3D11, - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_NONE, - AV_PIX_FMT_NONE, - dxgi_init_avcodec_hardware_input_buffer - ), - { - // Common options + encoder_t make_amdvce(const config::settings_t &settings) { + return { + "amdvce"sv, + std::make_unique( + AV_HWDEVICE_TYPE_D3D11VA, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_D3D11, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_NONE, + AV_PIX_FMT_NONE, + dxgi_init_avcodec_hardware_input_buffer + ), { - {"filler_data"s, false}, - {"forced_idr"s, 1}, - {"latency"s, "lowest_latency"s}, - {"async_depth"s, 1}, - {"skip_frame"s, 0}, - {"log_to_dbg"s, []() { - return config::sunshine.min_log_level < 2 ? 1 : 0; - }}, - {"preencode"s, &config::video.amd.amd_preanalysis}, - {"quality"s, &config::video.amd.amd_quality_av1}, - {"rc"s, &config::video.amd.amd_rc_av1}, - {"usage"s, &config::video.amd.amd_usage_av1}, - {"enforce_hrd"s, &config::video.amd.amd_enforce_hrd}, + // Common options + { + {"filler_data"s, false}, + {"forced_idr"s, 1}, + {"latency"s, "lowest_latency"s}, + {"async_depth"s, 1}, + {"skip_frame"s, 0}, + {"log_to_dbg"s, [&settings]() { + return settings.sunshine.min_log_level < 2 ? 1 : 0; + }}, + {"preencode"s, &settings.video.amd.amd_preanalysis}, + {"quality"s, &settings.video.amd.amd_quality_av1}, + {"rc"s, &settings.video.amd.amd_rc_av1}, + {"usage"s, &settings.video.amd.amd_usage_av1}, + {"enforce_hrd"s, &settings.video.amd.amd_enforce_hrd}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_amf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_amf"s, - {}, // capabilities - }, - { - // Common options { - {"filler_data"s, false}, - {"forced_idr"s, 1}, - {"latency"s, 1}, - {"async_depth"s, 1}, - {"skip_frame"s, 0}, - {"log_to_dbg"s, []() { - return config::sunshine.min_log_level < 2 ? 1 : 0; - }}, - {"gops_per_idr"s, 1}, - {"header_insertion_mode"s, "idr"s}, - {"preencode"s, &config::video.amd.amd_preanalysis}, - {"quality"s, &config::video.amd.amd_quality_hevc}, - {"rc"s, &config::video.amd.amd_rc_hevc}, - {"usage"s, &config::video.amd.amd_usage_hevc}, - {"vbaq"s, &config::video.amd.amd_vbaq}, - {"enforce_hrd"s, &config::video.amd.amd_enforce_hrd}, - {"max_au_size"s, &config::video.amd.amd_max_au_size}, - {"level"s, [](const config_t &cfg) { - auto size = cfg.width * cfg.height; - // For 4K and below, try to use level 5.1 or 5.2 if possible - if (size <= 8912896) { - if (size * cfg.framerate <= 534773760) { - return "5.1"s; - } else if (size * cfg.framerate <= 1069547520) { - return "5.2"s; + // Common options + { + {"filler_data"s, false}, + {"forced_idr"s, 1}, + {"latency"s, 1}, + {"async_depth"s, 1}, + {"skip_frame"s, 0}, + {"log_to_dbg"s, [&settings]() { + return settings.sunshine.min_log_level < 2 ? 1 : 0; + }}, + {"gops_per_idr"s, 1}, + {"header_insertion_mode"s, "idr"s}, + {"preencode"s, &settings.video.amd.amd_preanalysis}, + {"quality"s, &settings.video.amd.amd_quality_hevc}, + {"rc"s, &settings.video.amd.amd_rc_hevc}, + {"usage"s, &settings.video.amd.amd_usage_hevc}, + {"vbaq"s, &settings.video.amd.amd_vbaq}, + {"enforce_hrd"s, &settings.video.amd.amd_enforce_hrd}, + {"max_au_size"s, &settings.video.amd.amd_max_au_size}, + {"level"s, [](const config_t &cfg) { + auto size = cfg.width * cfg.height; + // For 4K and below, try to use level 5.1 or 5.2 if possible + if (size <= 8912896) { + if (size * cfg.framerate <= 534773760) { + return "5.1"s; + } else if (size * cfg.framerate <= 1069547520) { + return "5.2"s; + } } - } - return "auto"s; - }}, + return "auto"s; + }}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_amf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_amf"s, - {}, // capabilities - }, - { - // Common options { - {"filler_data"s, false}, - {"forced_idr"s, 1}, - {"latency"s, 1}, - {"async_depth"s, 1}, - {"frame_skipping"s, 0}, - {"log_to_dbg"s, []() { - return config::sunshine.min_log_level < 2 ? 1 : 0; - }}, - {"preencode"s, &config::video.amd.amd_preanalysis}, - {"quality"s, &config::video.amd.amd_quality_h264}, - {"rc"s, &config::video.amd.amd_rc_h264}, - {"usage"s, &config::video.amd.amd_usage_h264}, - {"vbaq"s, &config::video.amd.amd_vbaq}, - {"coder"s, &config::video.amd.amd_coder}, - {"enforce_hrd"s, &config::video.amd.amd_enforce_hrd}, - {"max_au_size"s, &config::video.amd.amd_max_au_size}, + // Common options + { + {"filler_data"s, false}, + {"forced_idr"s, 1}, + {"latency"s, 1}, + {"async_depth"s, 1}, + {"frame_skipping"s, 0}, + {"log_to_dbg"s, [&settings]() { + return settings.sunshine.min_log_level < 2 ? 1 : 0; + }}, + {"preencode"s, &settings.video.amd.amd_preanalysis}, + {"quality"s, &settings.video.amd.amd_quality_h264}, + {"rc"s, &settings.video.amd.amd_rc_h264}, + {"usage"s, &settings.video.amd.amd_usage_h264}, + {"vbaq"s, &settings.video.amd.amd_vbaq}, + {"coder"s, &settings.video.amd.amd_coder}, + {"enforce_hrd"s, &settings.video.amd.amd_enforce_hrd}, + {"max_au_size"s, &settings.video.amd.amd_max_au_size}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + { + // Fallback options + {"usage"s, 2 /* AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY */}, // Workaround for https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/410 + }, + "h264_amf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - { - // Fallback options - {"usage"s, 2 /* AMF_VIDEO_ENCODER_USAGE_LOW_LATENCY */}, // Workaround for https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/410 - }, - "h264_amf"s, - {}, // capabilities - }, - PARALLEL_ENCODING - }; + PARALLEL_ENCODING + }; + } /** * @brief Mediafoundation. */ - const encoder_t mediafoundation { - "mediafoundation"sv, - std::make_unique( - AV_HWDEVICE_TYPE_D3D11VA, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_D3D11, - AV_PIX_FMT_NV12, // SDR 4:2:0 8-bit (only format Qualcomm supports) - AV_PIX_FMT_NONE, // No HDR - Qualcomm MF only supports 8-bit - AV_PIX_FMT_NONE, // No YUV444 SDR - AV_PIX_FMT_NONE, // No YUV444 HDR - dxgi_init_avcodec_hardware_input_buffer - ), - { - // Common options for AV1 - Qualcomm MF encoder + encoder_t make_mediafoundation(const config::settings_t &settings) { + return { + "mediafoundation"sv, + std::make_unique( + AV_HWDEVICE_TYPE_D3D11VA, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_D3D11, + AV_PIX_FMT_NV12, // SDR 4:2:0 8-bit (only format Qualcomm supports) + AV_PIX_FMT_NONE, // No HDR - Qualcomm MF only supports 8-bit + AV_PIX_FMT_NONE, // No YUV444 SDR + AV_PIX_FMT_NONE, // No YUV444 HDR + dxgi_init_avcodec_hardware_input_buffer + ), { - {"hw_encoding"s, 1}, - {"rate_control"s, "cbr"s}, - {"scenario"s, "display_remoting"s}, + // Common options for AV1 - Qualcomm MF encoder + { + {"hw_encoding"s, 1}, + {"rate_control"s, "cbr"s}, + {"scenario"s, "display_remoting"s}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_mf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_mf"s, - {}, // capabilities - }, - { - // Common options for HEVC - Qualcomm MF encoder { - {"hw_encoding"s, 1}, - {"rate_control"s, "cbr"s}, - {"scenario"s, "display_remoting"s}, + // Common options for HEVC - Qualcomm MF encoder + { + {"hw_encoding"s, 1}, + {"rate_control"s, "cbr"s}, + {"scenario"s, "display_remoting"s}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_mf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_mf"s, - {}, // capabilities - }, - { - // Common options for H.264 - Qualcomm MF encoder { - {"hw_encoding"s, 1}, - {"rate_control"s, "cbr"s}, - {"scenario"s, "display_remoting"s}, + // Common options for H.264 - Qualcomm MF encoder + { + {"hw_encoding"s, 1}, + {"rate_control"s, "cbr"s}, + {"scenario"s, "display_remoting"s}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "h264_mf"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "h264_mf"s, - {}, // capabilities - }, - PARALLEL_ENCODING | FIXED_GOP_SIZE // MF encoder doesn't support on-demand IDR frames - }; + PARALLEL_ENCODING | FIXED_GOP_SIZE // MF encoder doesn't support on-demand IDR frames + }; + } #endif /** * @brief Software. */ - const encoder_t software { - "software"sv, - std::make_unique( - AV_HWDEVICE_TYPE_NONE, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_NONE, - AV_PIX_FMT_YUV420P, - AV_PIX_FMT_YUV420P10, - AV_PIX_FMT_YUV444P, - AV_PIX_FMT_YUV444P10, - nullptr - ), - { - // libsvtav1 takes different presets than libx264/libx265. - // We set an infinite GOP length, use a low delay prediction structure, - // force I frames to be key frames, and set max bitrate to default to work - // around a FFmpeg bug with CBR mode. + encoder_t make_software(const config::settings_t &settings) { + return { + "software"sv, + std::make_unique( + AV_HWDEVICE_TYPE_NONE, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_NONE, + AV_PIX_FMT_YUV420P, + AV_PIX_FMT_YUV420P10, + AV_PIX_FMT_YUV444P, + AV_PIX_FMT_YUV444P10, + nullptr + ), { - {"svtav1-params"s, "keyint=-1:pred-struct=1:force-key-frames=1:mbr=0"s}, - {"preset"s, &config::video.sw.svtav1_preset}, - }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options + // libsvtav1 takes different presets than libx264/libx265. + // We set an infinite GOP length, use a low delay prediction structure, + // force I frames to be key frames, and set max bitrate to default to work + // around a FFmpeg bug with CBR mode. + { + {"svtav1-params"s, "keyint=-1:pred-struct=1:force-key-frames=1:mbr=0"s}, + {"preset"s, &settings.video.sw.svtav1_preset}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options #ifdef ENABLE_BROKEN_AV1_ENCODER - // Due to bugs preventing on-demand IDR frames from working and very poor - // real-time encoding performance, we do not enable libsvtav1 by default. - // It is only suitable for testing AV1 until the IDR frame issue is fixed. - "libsvtav1"s, + // Due to bugs preventing on-demand IDR frames from working and very poor + // real-time encoding performance, we do not enable libsvtav1 by default. + // It is only suitable for testing AV1 until the IDR frame issue is fixed. + "libsvtav1"s, #else - {}, + {}, #endif - {}, // capabilities - }, - { - // x265's Info SEI is so long that it causes the IDR picture data to be - // kicked to the 2nd packet in the frame, breaking Moonlight's parsing logic. - // It also looks like gop_size isn't passed on to x265, so we have to set - // 'keyint=-1' in the parameters ourselves. - { - {"forced-idr"s, 1}, - {"x265-params"s, "info=0:keyint=-1"s}, - {"preset"s, &config::video.sw.sw_preset}, - {"tune"s, &config::video.sw.sw_tune}, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "libx265"s, - {}, // capabilities - }, - { - // Common options { - {"preset"s, &config::video.sw.sw_preset}, - {"tune"s, &config::video.sw.sw_tune}, + // x265's Info SEI is so long that it causes the IDR picture data to be + // kicked to the 2nd packet in the frame, breaking Moonlight's parsing logic. + // It also looks like gop_size isn't passed on to x265, so we have to set + // 'keyint=-1' in the parameters ourselves. + { + {"forced-idr"s, 1}, + {"x265-params"s, "info=0:keyint=-1"s}, + {"preset"s, &settings.video.sw.sw_preset}, + {"tune"s, &settings.video.sw.sw_tune}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "libx265"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "libx264"s, - {}, // capabilities - }, - H264_ONLY | PARALLEL_ENCODING | ALWAYS_REPROBE | YUV444_SUPPORT - }; + { + // Common options + { + {"preset"s, &settings.video.sw.sw_preset}, + {"tune"s, &settings.video.sw.sw_tune}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "libx264"s, + {}, // capabilities + }, + H264_ONLY | PARALLEL_ENCODING | ALWAYS_REPROBE | YUV444_SUPPORT + }; + } #if defined(__linux__) || defined(linux) || defined(__linux) || defined(__FreeBSD__) /** * @brief VA-API. */ - const encoder_t vaapi { - "vaapi"sv, - std::make_unique( - AV_HWDEVICE_TYPE_VAAPI, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_VAAPI, - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_NONE, - AV_PIX_FMT_NONE, - vaapi_init_avcodec_hardware_input_buffer - ), - { - // Common options + encoder_t make_vaapi(const config::settings_t &settings) { + return { + "vaapi"sv, + std::make_unique( + AV_HWDEVICE_TYPE_VAAPI, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_VAAPI, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_NONE, + AV_PIX_FMT_NONE, + [&settings](platf::avcodec_encode_device_t *device) { + return vaapi_init_avcodec_hardware_input_buffer(settings, device); + } + ), { - {"async_depth"s, 1}, - {"blbrc"s, &config::video.vaapi.blbrc}, - {"idr_interval"s, std::numeric_limits::max()}, + // Common options + { + {"async_depth"s, 1}, + {"blbrc"s, &settings.video.vaapi.blbrc}, + {"idr_interval"s, std::numeric_limits::max()}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_vaapi"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_vaapi"s, - {}, // capabilities - }, - { - // Common options { - {"async_depth"s, 1}, - {"blbrc"s, &config::video.vaapi.blbrc}, - {"sei"s, 0}, - {"idr_interval"s, std::numeric_limits::max()}, + // Common options + { + {"async_depth"s, 1}, + {"blbrc"s, &settings.video.vaapi.blbrc}, + {"sei"s, 0}, + {"idr_interval"s, std::numeric_limits::max()}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_vaapi"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_vaapi"s, - {}, // capabilities - }, - { - // Common options { - {"async_depth"s, 1}, - {"blbrc"s, &config::video.vaapi.blbrc}, - {"sei"s, 0}, - {"idr_interval"s, std::numeric_limits::max()}, + // Common options + { + {"async_depth"s, 1}, + {"blbrc"s, &settings.video.vaapi.blbrc}, + {"sei"s, 0}, + {"idr_interval"s, std::numeric_limits::max()}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "h264_vaapi"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "h264_vaapi"s, - {}, // capabilities - }, - // RC buffer size will be set in platform code if supported - LIMITED_GOP_SIZE | PARALLEL_ENCODING | NO_RC_BUF_LIMIT - }; + // RC buffer size will be set in platform code if supported + LIMITED_GOP_SIZE | PARALLEL_ENCODING | NO_RC_BUF_LIMIT + }; + } #ifdef SUNSHINE_BUILD_VULKAN - const encoder_t vulkan { - "vulkan"sv, - std::make_unique( - AV_HWDEVICE_TYPE_VULKAN, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_VULKAN, - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_NONE, - AV_PIX_FMT_NONE, - vulkan_init_avcodec_hardware_input_buffer - ), - { - // AV1 + encoder_t make_vulkan(const config::settings_t &settings) { + return { + "vulkan"sv, + std::make_unique( + AV_HWDEVICE_TYPE_VULKAN, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_VULKAN, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_NONE, + AV_PIX_FMT_NONE, + [&settings](platf::avcodec_encode_device_t *device) { + return vulkan_init_avcodec_hardware_input_buffer(settings, device); + } + ), { - {"idr_interval"s, std::numeric_limits::max()}, - {"tune"s, &config::video.vk.tune}, - {"rc_mode"s, &config::video.vk.rc_mode}, - {"units"s, 0}, - {"usage"s, "stream"s}, - {"content"s, "rendered"s}, - {"async_depth"s, 1}, + // AV1 + { + {"idr_interval"s, std::numeric_limits::max()}, + {"tune"s, &settings.video.vk.tune}, + {"rc_mode"s, &settings.video.vk.rc_mode}, + {"units"s, 0}, + {"usage"s, "stream"s}, + {"content"s, "rendered"s}, + {"async_depth"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_vulkan"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_vulkan"s, - {}, // capabilities - }, - { - // HEVC { - {"idr_interval"s, std::numeric_limits::max()}, - {"tune"s, &config::video.vk.tune}, - {"rc_mode"s, &config::video.vk.rc_mode}, - {"units"s, 0}, - {"usage"s, "stream"s}, - {"content"s, "rendered"s}, - {"async_depth"s, 1}, + // HEVC + { + {"idr_interval"s, std::numeric_limits::max()}, + {"tune"s, &settings.video.vk.tune}, + {"rc_mode"s, &settings.video.vk.rc_mode}, + {"units"s, 0}, + {"usage"s, "stream"s}, + {"content"s, "rendered"s}, + {"async_depth"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_vulkan"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_vulkan"s, - {}, // capabilities - }, - { - // H.264 { - {"idr_interval"s, std::numeric_limits::max()}, - {"tune"s, &config::video.vk.tune}, - {"rc_mode"s, &config::video.vk.rc_mode}, - {"units"s, 0}, - {"usage"s, "stream"s}, - {"content"s, "rendered"s}, - {"async_depth"s, 1}, + // H.264 + { + {"idr_interval"s, std::numeric_limits::max()}, + {"tune"s, &settings.video.vk.tune}, + {"rc_mode"s, &settings.video.vk.rc_mode}, + {"units"s, 0}, + {"usage"s, "stream"s}, + {"content"s, "rendered"s}, + {"async_depth"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "h264_vulkan"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "h264_vulkan"s, - {}, // capabilities - }, - LIMITED_GOP_SIZE | PARALLEL_ENCODING - }; + LIMITED_GOP_SIZE | PARALLEL_ENCODING + }; + } #endif // SUNSHINE_BUILD_VULKAN #endif // linux @@ -1424,108 +1460,103 @@ namespace video { /** * @brief Videotoolbox. */ - const encoder_t videotoolbox { - "videotoolbox"sv, - std::make_unique( - AV_HWDEVICE_TYPE_VIDEOTOOLBOX, - AV_HWDEVICE_TYPE_NONE, - AV_PIX_FMT_VIDEOTOOLBOX, - AV_PIX_FMT_NV12, - AV_PIX_FMT_P010, - AV_PIX_FMT_NONE, - AV_PIX_FMT_NONE, - vt_init_avcodec_hardware_input_buffer - ), - { - // Common options + encoder_t make_videotoolbox(const config::settings_t &settings) { + return { + "videotoolbox"sv, + std::make_unique( + AV_HWDEVICE_TYPE_VIDEOTOOLBOX, + AV_HWDEVICE_TYPE_NONE, + AV_PIX_FMT_VIDEOTOOLBOX, + AV_PIX_FMT_NV12, + AV_PIX_FMT_P010, + AV_PIX_FMT_NONE, + AV_PIX_FMT_NONE, + vt_init_avcodec_hardware_input_buffer + ), { - {"allow_sw"s, &config::video.vt.vt_allow_sw}, - {"require_sw"s, &config::video.vt.vt_require_sw}, - {"realtime"s, &config::video.vt.vt_realtime}, - {"prio_speed"s, 1}, - {"max_ref_frames"s, 1}, + // Common options + { + {"allow_sw"s, &settings.video.vt.vt_allow_sw}, + {"require_sw"s, &settings.video.vt.vt_require_sw}, + {"realtime"s, &settings.video.vt.vt_realtime}, + {"prio_speed"s, 1}, + {"max_ref_frames"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "av1_videotoolbox"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "av1_videotoolbox"s, - {}, // capabilities - }, - { - // Common options { - {"allow_sw"s, &config::video.vt.vt_allow_sw}, - {"require_sw"s, &config::video.vt.vt_require_sw}, - {"realtime"s, &config::video.vt.vt_realtime}, - {"prio_speed"s, 1}, - {"max_ref_frames"s, 1}, + // Common options + { + {"allow_sw"s, &settings.video.vt.vt_allow_sw}, + {"require_sw"s, &settings.video.vt.vt_require_sw}, + {"realtime"s, &settings.video.vt.vt_realtime}, + {"prio_speed"s, 1}, + {"max_ref_frames"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + {}, // Fallback options + "hevc_videotoolbox"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - {}, // Fallback options - "hevc_videotoolbox"s, - {}, // capabilities - }, - { - // Common options - // Note: max_ref_frames is intentionally omitted for H.264 because - // VideoToolbox on Apple Silicon produces all-IDR output when - // ReferenceBufferCount=1 is set for H.264, causing massive bandwidth - // inflation (~3x) and frame drops. HEVC and AV1 are unaffected and - // retain max_ref_frames=1. See LizardByte/Sunshine#5013. { - {"allow_sw"s, &config::video.vt.vt_allow_sw}, - {"require_sw"s, &config::video.vt.vt_require_sw}, - {"realtime"s, &config::video.vt.vt_realtime}, - {"prio_speed"s, 1}, + // Common options + // Note: max_ref_frames is intentionally omitted for H.264 because + // VideoToolbox on Apple Silicon produces all-IDR output when + // ReferenceBufferCount=1 is set for H.264, causing massive bandwidth + // inflation (~3x) and frame drops. HEVC and AV1 are unaffected and + // retain max_ref_frames=1. See LizardByte/Sunshine#5013. + { + {"allow_sw"s, &settings.video.vt.vt_allow_sw}, + {"require_sw"s, &settings.video.vt.vt_require_sw}, + {"realtime"s, &settings.video.vt.vt_realtime}, + {"prio_speed"s, 1}, + }, + {}, // SDR-specific options + {}, // HDR-specific options + {}, // YUV444 SDR-specific options + {}, // YUV444 HDR-specific options + { + // Fallback options + {"flags"s, "-low_delay"}, + }, + "h264_videotoolbox"s, + {}, // capabilities }, - {}, // SDR-specific options - {}, // HDR-specific options - {}, // YUV444 SDR-specific options - {}, // YUV444 HDR-specific options - { - // Fallback options - {"flags"s, "-low_delay"}, - }, - "h264_videotoolbox"s, - {}, // capabilities - }, - PARALLEL_ENCODING - }; + PARALLEL_ENCODING + }; + } #endif - static const std::vector encoder_prototypes { + std::vector make_encoders(const config::settings_t &settings) { + return { #ifndef __APPLE__ - &nvenc, + make_nvenc(settings), #endif #ifdef _WIN32 - &quicksync, - &amdvce, - &mediafoundation, + make_quicksync(settings), + make_amdvce(settings), + make_mediafoundation(settings), #endif #if defined(__linux__) || defined(linux) || defined(__linux) || defined(__FreeBSD__) #ifdef SUNSHINE_BUILD_VULKAN - &vulkan, + make_vulkan(settings), #endif - &vaapi, + make_vaapi(settings), #endif #ifdef __APPLE__ - &videotoolbox, + make_videotoolbox(settings), #endif - &software - }; - - std::vector make_encoders() { - std::vector result; - result.reserve(encoder_prototypes.size()); - for (const auto *encoder : encoder_prototypes) { - result.push_back(*encoder); - } - return result; + make_software(settings) + }; } /** @@ -1561,7 +1592,7 @@ namespace video { */ void refresh_displays(service_t::impl_t &host, platf::mem_type_e dev_type, std::vector &display_names, int ¤t_display_index) { // It is possible that the output name may be empty even if it wasn't before (device disconnected) or vice-versa - const auto output_name {host.displays.map_output_name(config::video.output_name)}; + const auto output_name {host.displays.map_output_name(host.settings.video.output_name)}; std::string current_display_name; // If we have a current display index, let's start with that @@ -2003,6 +2034,7 @@ namespace video { /** * @brief Create an AVCodec encode session. * + * @param settings Host encoder settings used by the session. * @param disp Display being encoded. * @param encoder Selected encoder. * @param config Video configuration. @@ -2012,6 +2044,7 @@ namespace video { * @return AVCodec encode session, or nullptr on failure. */ std::unique_ptr make_avcodec_encode_session( + const config::settings_t &settings, platf::display_t *disp, const encoder_t &encoder, const config_t &config, @@ -2082,7 +2115,7 @@ namespace video { case 0: // 10-bit h264 encoding is not supported by our streaming protocol assert(!config.dynamicRange); - ctx->profile = select_h264_profile(video_format.name, config, config::video.amd.amd_coder); + ctx->profile = select_h264_profile(video_format.name, config, settings.video.amd.amd_coder); break; case 1: @@ -2202,7 +2235,7 @@ namespace video { // Clients will request for the fewest slices per frame to get the // most efficient encode, but we may want to provide more slices than // requested to ensure we have enough parallelism for good performance. - ctx->slices = std::max(config.slicesPerFrame, config::video.min_threads); + ctx->slices = std::max(config.slicesPerFrame, settings.video.min_threads); } if (encoder.flags & SINGLE_SLICE_ONLY) { @@ -2219,10 +2252,10 @@ namespace video { [&](int v) { av_dict_set_int(&options, option.name.c_str(), v, 0); }, - [&](int *v) { + [&](const int *v) { av_dict_set_int(&options, option.name.c_str(), *v, 0); }, - [&](std::optional *v) { + [&](const std::optional *v) { if (*v) { av_dict_set_int(&options, option.name.c_str(), **v, 0); } @@ -2233,7 +2266,7 @@ namespace video { [&](const std::string &v) { av_dict_set(&options, option.name.c_str(), v.c_str(), 0); }, - [&](std::string *v) { + [&](const std::string *v) { if (!v->empty()) { av_dict_set(&options, option.name.c_str(), v->c_str(), 0); } @@ -2264,7 +2297,7 @@ namespace video { } } - auto bitrate = ((config::video.max_bitrate > 0) ? std::min(config.bitrate, config::video.max_bitrate) : config.bitrate) * 1000; + auto bitrate = ((settings.video.max_bitrate > 0) ? std::min(config.bitrate, settings.video.max_bitrate) : config.bitrate) * 1000; BOOST_LOG(info) << "Streaming bitrate is " << bitrate; ctx->rc_max_rate = bitrate; ctx->bit_rate = bitrate; @@ -2291,8 +2324,8 @@ namespace video { ctx->rc_buffer_size = bitrate / config.framerate; #ifndef __APPLE__ - if (encoder.name == "nvenc" && config::video.nv_legacy.vbv_percentage_increase > 0) { - ctx->rc_buffer_size += ctx->rc_buffer_size * config::video.nv_legacy.vbv_percentage_increase / 100; + if (encoder.name == "nvenc" && settings.video.nv_legacy.vbv_percentage_increase > 0) { + ctx->rc_buffer_size += ctx->rc_buffer_size * settings.video.nv_legacy.vbv_percentage_increase / 100; } #endif } @@ -2370,7 +2403,7 @@ namespace video { std::unique_ptr encode_device_final; if (!encode_device->data) { - auto software_encode_device = std::make_unique(); + auto software_encode_device = std::make_unique(settings.video.min_threads); if (software_encode_device->init(width, height, frame.get(), sw_fmt, hardware)) { return nullptr; @@ -2417,6 +2450,7 @@ namespace video { /** * @brief Create encode session. * + * @param settings Host encoder settings used by the session. * @param disp Display connection or display handle. * @param encoder Encoder configuration or encoder instance. * @param config Configuration values to apply. @@ -2425,10 +2459,10 @@ namespace video { * @param encode_device Encode device. * @return Constructed encode session object. */ - std::unique_ptr make_encode_session(platf::display_t *disp, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr encode_device) { + std::unique_ptr make_encode_session(const config::settings_t &settings, platf::display_t *disp, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr encode_device) { if (dynamic_cast(encode_device.get())) { auto avcodec_encode_device = boost::dynamic_pointer_cast(std::move(encode_device)); - return make_avcodec_encode_session(disp, encoder, config, width, height, std::move(avcodec_encode_device)); + return make_avcodec_encode_session(settings, disp, encoder, config, width, height, std::move(avcodec_encode_device)); } else if (dynamic_cast(encode_device.get())) { auto nvenc_encode_device = boost::dynamic_pointer_cast(std::move(encode_device)); return make_nvenc_encode_session(config, std::move(nvenc_encode_device)); @@ -2461,7 +2495,7 @@ namespace video { safe::signal_t &reinit_event, const encoder_t &encoder, void *channel_data) { - auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); + auto session = make_encode_session(host.settings, disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { return; } @@ -2484,7 +2518,7 @@ namespace video { }); // set max frame time based on client-requested target framerate. - double minimum_fps_target = (config::video.minimum_fps_target > 0.0) ? config::video.minimum_fps_target : (config.framerate / 2); + double minimum_fps_target = (host.settings.video.minimum_fps_target > 0.0) ? host.settings.video.minimum_fps_target : (config.framerate / 2); std::chrono::duration max_frametime {1000.0 / minimum_fps_target}; BOOST_LOG(info) << "Minimum FPS target set to ~"sv << minimum_fps_target << "fps ("sv << max_frametime.count() << "ms)"sv; @@ -2676,13 +2710,14 @@ namespace video { /** * @brief Create synced session. * + * @param settings Host startup encoder configuration. * @param disp Display connection or display handle. * @param encoder Encoder configuration or encoder instance. * @param img Image or frame object to read from or populate. * @param ctx Native context object used by the operation or callback. * @return Constructed synced session object. */ - std::optional make_synced_session(platf::display_t *disp, const encoder_t &encoder, platf::img_t &img, sync_session_ctx_t &ctx) { + std::optional make_synced_session(const config::settings_t &settings, platf::display_t *disp, const encoder_t &encoder, platf::img_t &img, sync_session_ctx_t &ctx) { sync_session_t encode_session; encode_session.ctx = &ctx; @@ -2706,7 +2741,7 @@ namespace video { } ctx.hdr_events->raise(std::move(hdr_info)); - auto session = make_encode_session(disp, encoder, ctx.config, img.width, img.height, std::move(encode_device)); + auto session = make_encode_session(settings, disp, encoder, ctx.config, img.width, img.height, std::move(encode_device)); if (!session) { return std::nullopt; } @@ -2775,7 +2810,7 @@ namespace video { std::vector synced_sessions; for (auto &ctx : synced_session_ctxs) { - auto synced_session = make_synced_session(disp.get(), encoder, *img, *ctx); + auto synced_session = make_synced_session(host.settings, disp.get(), encoder, *img, *ctx); if (!synced_session) { return encode_e::error; } @@ -2794,7 +2829,7 @@ namespace video { synced_session_ctxs.emplace_back(std::make_unique(std::move(*encode_session_ctx))); - auto encode_session = make_synced_session(disp.get(), encoder, *img, *synced_session_ctxs.back()); + auto encode_session = make_synced_session(host.settings, disp.get(), encoder, *img, *synced_session_ctxs.back()); if (!encode_session) { ec = platf::capture_e::error; return false; @@ -3047,7 +3082,7 @@ namespace video { return -1; } - auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); + auto session = make_encode_session(host.settings, disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { return -1; } @@ -3096,9 +3131,12 @@ namespace video { /** * @brief Validate encoder before it is used. * @param host Host input or video service and its capture dependencies. + * @param encoder Encoder descriptor whose supported formats are probed and updated. + * @param expect_failure Whether an unavailable encoder is expected. + * @return Whether the encoder can produce the requested formats. */ bool validate_encoder(service_t::impl_t &host, encoder_t &encoder, bool expect_failure) { - const auto output_name {host.displays.map_output_name(config::video.output_name)}; + const auto output_name {host.displays.map_output_name(host.settings.video.output_name)}; std::shared_ptr disp; BOOST_LOG(info) << "Trying encoder ["sv << encoder.name << ']'; @@ -3281,8 +3319,8 @@ namespace video { test_yuv444_hdr(encoder.av1, 2); } - encoder.h264[encoder_t::VUI_PARAMETERS] = encoder.h264[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; - encoder.hevc[encoder_t::VUI_PARAMETERS] = encoder.hevc[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; + encoder.h264[encoder_t::VUI_PARAMETERS] = encoder.h264[encoder_t::VUI_PARAMETERS] && !host.settings.sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; + encoder.hevc[encoder_t::VUI_PARAMETERS] = encoder.hevc[encoder_t::VUI_PARAMETERS] && !host.settings.sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; if (!encoder.h264[encoder_t::VUI_PARAMETERS]) { BOOST_LOG(warning) << encoder.name << ": h264 missing sps->vui parameters"sv; @@ -3295,6 +3333,11 @@ namespace video { return true; } + /** + * @brief Select a usable encoder and publish its supported formats for the host. + * @param host Host video service and its capture dependencies. + * @return Zero when a usable encoder is selected, nonzero otherwise. + */ int probe_encoders(service_t::impl_t &host) { if (!allow_encoder_probing(host.displays)) { // Error already logged @@ -3315,8 +3358,8 @@ namespace video { // Restart encoder selection auto previous_encoder = host.chosen_encoder; host.chosen_encoder = nullptr; - host.probed.active_hevc_mode = config::video.hevc_mode; - host.probed.active_av1_mode = config::video.av1_mode; + host.probed.active_hevc_mode = host.settings.video.hevc_mode; + host.probed.active_av1_mode = host.settings.video.av1_mode; host.probed.ref_frames_invalidation = false; host.platform.set_capture_requirements(host.probed.active_hevc_mode); @@ -3354,12 +3397,12 @@ namespace video { } }; - if (!config::video.encoder.empty()) { + if (!host.settings.video.encoder.empty()) { // If there is a specific encoder specified, use it if it passes validation KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; - if (encoder->name == config::video.encoder) { + if (encoder->name == host.settings.video.encoder) { // Remove the encoder from the list entirely if it fails validation if (!validate_encoder(host, *encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); @@ -3378,7 +3421,7 @@ namespace video { }); if (host.chosen_encoder == nullptr) { - BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << config::video.encoder << ']'; + BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << host.settings.video.encoder << ']'; } } @@ -3452,9 +3495,9 @@ namespace video { } if (host.chosen_encoder == nullptr) { - const auto output_name {host.displays.map_output_name(config::video.output_name)}; + const auto output_name {host.displays.map_output_name(host.settings.video.output_name)}; BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv; - if (!config::video.adapter_name.empty() || !output_name.empty()) { + if (!host.settings.video.adapter_name.empty() || !output_name.empty()) { BOOST_LOG(fatal) << "Please ensure your manually chosen GPU and monitor are connected and powered on."sv; } else { BOOST_LOG(fatal) << "Please check that a display is connected and powered on."sv; @@ -3548,10 +3591,7 @@ namespace video { */ typedef int (*vaapi_init_avcodec_hardware_input_buffer_fn)(platf::avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf); - /** - * @brief Initialize AVCodec hardware input buffers for VA-API. - */ - util::Either vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { + util::Either vaapi_init_avcodec_hardware_input_buffer(const config::settings_t &settings, platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; // If an egl hwdevice @@ -3563,7 +3603,7 @@ namespace video { return hw_device_buf; } - auto render_device = platf::resolve_render_device(); + auto render_device = platf::resolve_render_device(settings); auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device.empty() ? nullptr : render_device.c_str(), nullptr, 0); if (status < 0) { @@ -3576,9 +3616,12 @@ namespace video { } #ifdef SUNSHINE_BUILD_VULKAN + /** + * @brief Callback signature for Vulkan AVCodec hardware input initialization. + */ 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) { + util::Either vulkan_init_avcodec_hardware_input_buffer(const config::settings_t &settings, platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; if (encode_device && encode_device->data) { @@ -3589,7 +3632,7 @@ namespace video { } // Try render device path first, auto-detecting the GPU with a connected display - auto render_device = platf::resolve_render_device(); + auto render_device = platf::resolve_render_device(settings); auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VULKAN, render_device.c_str(), nullptr, 0); if (status >= 0) { @@ -3684,10 +3727,6 @@ namespace video { } #endif - /** - * @brief Start capture async. - * @param host Host input or video service and its capture dependencies. - */ int start_capture_async(service_t::impl_t &host, capture_thread_async_ctx_t &capture_thread_ctx) { capture_thread_ctx.encoder_p = host.chosen_encoder; capture_thread_ctx.reinit_event.reset(); @@ -3789,8 +3828,8 @@ namespace video { return unknown; } - service_t::service_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): - impl_ {std::make_unique(std::move(mail), cursor, displays, platform)} { + service_t::service_t(const config::settings_t &settings, safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): + impl_ {std::make_unique(settings, std::move(mail), cursor, displays, platform)} { } service_t::~service_t() = default; @@ -3802,6 +3841,7 @@ namespace video { int service_t::probe_encoders() { std::lock_guard lock {impl_->probe_mutex}; + impl_->platform.set_capture_requirements(impl_->settings.video.hevc_mode); const auto result = ::video::probe_encoders(*impl_); impl_->platform.set_capture_requirements(impl_->probed.active_hevc_mode); return result; diff --git a/src/video.h b/src/video.h index 8f611a7d7..2a368298f 100644 --- a/src/video.h +++ b/src/video.h @@ -132,6 +132,13 @@ namespace video { */ class avcodec_software_encode_device_t: public platf::avcodec_encode_device_t { public: + /** + * @brief Set the number of software color-conversion threads for this device. + * @param min_threads Startup minimum conversion thread count. + */ + explicit avcodec_software_encode_device_t(int min_threads): + min_threads_ {min_threads} {} + /** * @brief Convert a captured image into the encoder input representation. * @@ -187,6 +194,7 @@ namespace video { avcodec_frame_t sw_frame; ///< Sw frame. avcodec_frame_t sws_input_frame; ///< Sws input frame. avcodec_frame_t sws_output_frame; ///< Sws output frame. + int min_threads_; ///< Immutable conversion thread count selected by this host. sws_t sws; ///< Software scaler used when frames need CPU-side pixel conversion. AVPixelFormat sws_src_format {AV_PIX_FMT_BGR0}; ///< Source format the sws context was created with. @@ -348,7 +356,7 @@ namespace video { option_t(const option_t &) = default; std::string name; ///< Encoder command-line option name. - std::variant *, std::function, std::string, std::string *, std::function> value; ///< Literal, pointer, or callback that supplies the option value. + std::variant *, std::function, std::string, const std::string *, std::function> value; ///< Literal, pointer, or callback that supplies the option value. /** * @brief Store a named encoder option and its value source. @@ -460,24 +468,57 @@ namespace video { }; // encoders - extern const encoder_t software; + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_software(const config::settings_t &settings); #if !defined(__APPLE__) - extern const encoder_t nvenc; // available for windows and linux + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + */ + encoder_t make_nvenc(const config::settings_t &settings); #endif #ifdef _WIN32 - extern const encoder_t amdvce; - extern const encoder_t quicksync; - extern const encoder_t mediafoundation; + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_amdvce(const config::settings_t &settings); + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_quicksync(const config::settings_t &settings); + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_mediafoundation(const config::settings_t &settings); #endif #if defined(__linux__) || defined(linux) || defined(__linux) || defined(__FreeBSD__) - extern const encoder_t vaapi; + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_vaapi(const config::settings_t &settings); #endif #ifdef __APPLE__ - extern const encoder_t videotoolbox; + /** + * @brief Construct an encoder descriptor bound to one host's immutable configuration. + * @param settings Host startup configuration. + * @return Encoder descriptor with independent probe capabilities. + */ + encoder_t make_videotoolbox(const config::settings_t &settings); #endif /** @@ -705,11 +746,13 @@ namespace video { /** * @brief Bind host capture dependencies without probing hardware. + * @param settings Immutable encoder and capture configuration. * @param mail Host packet and display-switch mailbox. * @param cursor Host cursor visibility preference. * @param displays Display configuration manager. + * @param platform Native capture backend owner. */ - service_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform); + service_t(const config::settings_t &settings, safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform); service_t(const service_t &) = delete; service_t &operator=(const service_t &) = delete; /** diff --git a/tests/server_test_context.h b/tests/server_test_context.h index 169424c9a..fbe9d4866 100644 --- a/tests/server_test_context.h +++ b/tests/server_test_context.h @@ -5,6 +5,7 @@ #pragma once // local includes +#include #include #include #include @@ -20,22 +21,24 @@ namespace test_utils { * @brief Assemble inactive server services without probing host input or encoders. */ struct server_context_t { + config::store_t configuration; ///< Startup settings and synchronized credentials owned by this fixture. runtime::infrastructure_t infrastructure; ///< Application infrastructure owned by this context. safe::mail_t host_mail {infrastructure.mailbox()}; ///< Host mailbox shared by this context's services. bool &cursor {infrastructure.cursor()}; ///< Host cursor policy owned by the infrastructure. + audio::service_t audios {configuration.values(), host_mail}; ///< Shared inactive audio control. display_device::manager_t displays; ///< Display settings and retry owner. - platf::runtime_t platform {host_mail, infrastructure.scheduler(), infrastructure.lifetime(), displays + platf::runtime_t platform {configuration.values(), host_mail, infrastructure.scheduler(), infrastructure.lifetime(), displays #ifdef _WIN32 , infrastructure.preferences() #endif }; ///< Inactive native capture and application resources. - input::service_t inputs {infrastructure.scheduler(), host_mail, cursor}; ///< Inactive host input owner. - proc::proc_t processes {displays, inputs}; ///< Application process owner. - video::service_t videos {host_mail, cursor, displays, platform}; ///< Inactive encoder and capture owner. - stream::service_t streams {host_mail, infrastructure.scheduler(), inputs, videos, processes, displays, platform}; ///< Stream broadcast owner. - rtsp_stream::service_t rtsp {streams, inputs, videos, host_mail}; ///< RTSP listener and launch-session owner. - http::state_t http_state; ///< Host HTTP identity and origin policy. - nvhttp::service_t gamestream {http_state, processes, displays, videos, rtsp, host_mail}; ///< Pairing and authorization owner. + input::service_t inputs {configuration.values(), infrastructure.scheduler(), host_mail, cursor}; ///< Inactive host input owner. + proc::proc_t processes {configuration.values(), displays, inputs}; ///< Application process owner. + video::service_t videos {configuration.values(), host_mail, cursor, displays, platform}; ///< Inactive encoder and capture owner. + stream::service_t streams {configuration.values(), host_mail, infrastructure.scheduler(), inputs, videos, processes, displays, platform, audios}; ///< Stream broadcast owner. + rtsp_stream::service_t rtsp {configuration.values(), streams, inputs, videos, host_mail}; ///< RTSP listener and launch-session owner. + http::state_t http_state {configuration}; ///< Host HTTP identity and origin policy. + nvhttp::service_t gamestream {configuration.values(), http_state, processes, displays, videos, rtsp, host_mail}; ///< Pairing and authorization owner. }; } // namespace test_utils diff --git a/tests/tests_common.h b/tests/tests_common.h index b93a55ea0..3dcb39e09 100644 --- a/tests/tests_common.h +++ b/tests/tests_common.h @@ -164,9 +164,10 @@ struct PlatformTestSuite: BaseTest { */ static void SetUpTestSuite() { ASSERT_FALSE(platform_); + settings_ = std::make_unique(); infrastructure_ = std::make_unique(); displays_ = std::make_unique(); - platform_ = std::make_unique(infrastructure_->mailbox(), infrastructure_->scheduler(), infrastructure_->lifetime(), *displays_ + platform_ = std::make_unique(settings_->values(), infrastructure_->mailbox(), infrastructure_->scheduler(), infrastructure_->lifetime(), *displays_ #ifdef _WIN32 , infrastructure_->preferences() @@ -182,6 +183,7 @@ struct PlatformTestSuite: BaseTest { platform_.reset(); displays_.reset(); infrastructure_.reset(); + settings_.reset(); } protected: @@ -194,6 +196,7 @@ protected: } private: + inline static std::unique_ptr settings_; ///< Immutable suite configuration. inline static std::unique_ptr infrastructure_; ///< Suite scheduler and mailbox. inline static std::unique_ptr displays_; ///< Suite display manager. inline static std::unique_ptr platform_; ///< Suite platform resources. diff --git a/tests/unit/platform/test_permissions.cpp b/tests/unit/platform/test_permissions.cpp index 3b063bc46..6fca3003e 100644 --- a/tests/unit/platform/test_permissions.cpp +++ b/tests/unit/platform/test_permissions.cpp @@ -56,7 +56,8 @@ TEST(PlatformPermissionsTest, DirectoryAccessRequiresAnExistingDirectory) { #ifdef _WIN32 TEST(PlatformPermissionsTest, WindowsConfigStatusMatchesDirectoryAccess) { - const auto permissions = platf::get_permission_statuses(); + const config::store_t configuration; + const auto permissions = platf::get_permission_statuses(configuration.values()); ASSERT_EQ(permissions.size(), 1U); EXPECT_EQ(permissions.front().id, "config_directory"); EXPECT_EQ(permissions.front().status, platf::can_access_directory(platf::appdata()) ? "granted" : "denied"); @@ -72,11 +73,13 @@ TEST(PlatformPermissionsTest, UnixInputStatusMatchesVirtualInputDeviceAccess) { #ifndef __FreeBSD__ input_access = input_access || access("/dev/input/uinput", R_OK | W_OK) == 0; #endif - const auto permissions = platf::get_permission_statuses(); + const config::store_t configuration; + const auto permissions = platf::get_permission_statuses(configuration.values()); ASSERT_EQ(permissions.size(), 1U); EXPECT_EQ(permissions.front().id, "input"); EXPECT_EQ(permissions.front().status, input_access ? "granted" : "denied"); - EXPECT_EQ(permissions.front().required, config::input.keyboard || config::input.mouse || config::input.controller); + const auto &input = configuration.values().input; + EXPECT_EQ(permissions.front().required, input.keyboard || input.mouse || input.controller); EXPECT_FALSE(permissions.front().requestable); EXPECT_FALSE(platf::request_permission("input")); } diff --git a/tests/unit/platform/test_virtualhid_input.cpp b/tests/unit/platform/test_virtualhid_input.cpp index 5f2d0a0f1..daa14dec9 100644 --- a/tests/unit/platform/test_virtualhid_input.cpp +++ b/tests/unit/platform/test_virtualhid_input.cpp @@ -22,6 +22,7 @@ #include "src/config.h" #include "src/globals.h" #include "src/platform/virtualhid_input.h" +#include "src/utility.h" #if defined(_WIN32) || defined(__APPLE__) #include @@ -46,37 +47,22 @@ namespace { */ class VirtualHidInputTest: public ::testing::TestWithParam { protected: - /** - * @brief Preserve the configured gamepad. - */ - void SetUp() override { - original_gamepad = config::input.gamepad; - } - - /** - * @brief Restore the configured gamepad. - */ - void TearDown() override { - config::input.gamepad = std::move(original_gamepad); - } - - private: - std::string original_gamepad; ///< Configured gamepad restored after each test. + config::store_t config_; ///< Configuration isolated to this profile test. }; } // namespace TEST_P(VirtualHidInputTest, ReportsExpectedTouchpadSupport) { const auto &test_case = GetParam(); - config::input.gamepad = test_case.gamepad; - EXPECT_EQ(platf::virtualhid::configured_gamepad_supports_touchpad(), test_case.expected_touchpad) << test_case.gamepad; + config_.edit_startup().input.gamepad = test_case.gamepad; + EXPECT_EQ(platf::virtualhid::configured_gamepad_supports_touchpad(config_.values()), test_case.expected_touchpad) << test_case.gamepad; } TEST_P(VirtualHidInputTest, ReportsExpectedControllerExtensionSupport) { const auto &test_case = GetParam(); - config::input.gamepad = test_case.gamepad; + config_.edit_startup().input.gamepad = test_case.gamepad; EXPECT_EQ( - platf::virtualhid::configured_gamepad_supports_controller_extensions(), + platf::virtualhid::configured_gamepad_supports_controller_extensions(config_.values()), test_case.expected_controller_extensions ) << test_case.gamepad; } @@ -106,14 +92,14 @@ namespace { */ class VirtualHidDeviceTest: public ::testing::Test { protected: + config::store_t config_; ///< Configuration owned by this device fixture. runtime::infrastructure_t infrastructure_; ///< Host resources owned by this input fixture. /** * @brief Preserve input configuration and create fake virtual devices. */ void SetUp() override { - original_input = config::input; - context_ = std::make_unique(lvh::BackendKind::fake); + context_ = std::make_unique(config_.values(), lvh::BackendKind::fake); client_ = std::make_unique(*context_); const auto *test_info = ::testing::UnitTest::GetInstance()->current_test_info(); const std::string queue_name = std::string {"virtualhid-input-test-"} + test_info->test_suite_name() + '-' + test_info->name(); @@ -133,7 +119,6 @@ namespace { client_.reset(); context_.reset(); feedback_queue_.reset(); - config::input = std::move(original_input); } /** @@ -153,7 +138,7 @@ namespace { int global_index = 0, std::uint8_t client_index = 3 ) { - config::input.gamepad = profile; + config_.edit_startup().input.gamepad = profile; const platf::gamepad_id_t id {global_index, client_index}; const platf::gamepad_arrival_t metadata {type, capabilities, 0}; if (platf::virtualhid::alloc_gamepad(*context_, id, metadata, feedback_queue_) != 0) { @@ -192,7 +177,6 @@ namespace { } private: - config::input_t original_input; ///< Input configuration restored after each test. std::unique_ptr context_; ///< Shared fake virtual devices. std::unique_ptr client_; ///< Per-client fake touch and pen devices. platf::feedback_queue_t feedback_queue_; ///< Captured gamepad feedback messages. @@ -298,12 +282,12 @@ TEST_F(VirtualHidDeviceTest, ReportsStaticAndRuntimeGamepadChoices) { #if defined(_WIN32) || defined(__APPLE__) TEST_F(VirtualHidDeviceTest, NoneSelectionHidesAvailableGamepads) { - config::input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; - auto platform_input = platf::input(infrastructure_.scheduler()); + config_.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + auto platform_input = platf::input(config_.values(), infrastructure_.scheduler()); ASSERT_TRUE(platform_input); EXPECT_TRUE(platf::supported_gamepads(std::addressof(platform_input)).empty()); - EXPECT_EQ(platf::get_capabilities() & platf::platform_caps::controller_touch, 0U); + EXPECT_EQ(platf::get_capabilities(config_.values()) & platf::platform_caps::controller_touch, 0U); } TEST_F(VirtualHidDeviceTest, BrokerCreatesAndUpdatesEveryGamepadProfileWhenLicensed) { @@ -311,8 +295,8 @@ TEST_F(VirtualHidDeviceTest, BrokerCreatesAndUpdatesEveryGamepadProfileWhenLicen GTEST_SKIP() << "Virtual HID Broker is not activated"; } - config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; - auto platform_input = platf::input(infrastructure_.scheduler()); + config_.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; + auto platform_input = platf::input(config_.values(), infrastructure_.scheduler()); ASSERT_TRUE(platform_input); const auto &context = platf::virtualhid::get_input_context(platform_input); if (!context.runtime || !context.runtime->capabilities().supports_gamepad) { @@ -328,7 +312,7 @@ TEST_F(VirtualHidDeviceTest, BrokerCreatesAndUpdatesEveryGamepadProfileWhenLicen const platf::gamepad_id_t id {0, 0}; const platf::gamepad_arrival_t metadata {LI_CTYPE_UNKNOWN, 0, 0}; for (const auto profile : profiles) { - config::input.gamepad = profile; + config_.edit_startup().input.gamepad = profile; ASSERT_EQ(platf::alloc_gamepad(platform_input, id, metadata, nullptr), 0) << profile; platf::gamepad_update(platform_input, 0, {platf::A, 255, 0, 0, 0, 0, 0}); const auto *adapter = platf::virtualhid::gamepad_adapter_for_testing(platf::virtualhid::get_input_context(platform_input), 0); @@ -343,7 +327,7 @@ TEST_F(VirtualHidDeviceTest, RejectsUnavailableAndInvalidGamepadSlots) { const platf::gamepad_arrival_t metadata {LI_CTYPE_XBOX, 0, 0}; const platf::gamepad_id_t valid_id {0, 0}; - platf::virtualhid::input_context_t no_runtime {lvh::BackendKind::fake}; + platf::virtualhid::input_context_t no_runtime {config_.values(), lvh::BackendKind::fake}; no_runtime.runtime.reset(); no_runtime.refresh_keyboard(); no_runtime.refresh_mouse(); @@ -379,8 +363,8 @@ TEST_F(VirtualHidDeviceTest, RoutesLibvirtualhidDiagnosticsToSunshineLog) { TEST_F(VirtualHidDeviceTest, AllocatesManualProfileAndTranslatesFullState) { const auto active_devices_before_gamepad = context()->runtime->active_device_count(); - config::input.ds4_back_as_touchpad_click = true; - config::input.virtualhid_randomize_mac = false; + config_.edit_startup().input.ds4_back_as_touchpad_click = true; + config_.edit_startup().input.virtualhid_randomize_mac = false; const auto capabilities = static_cast(LI_CCAP_ACCEL | LI_CCAP_GYRO | LI_CCAP_TOUCHPAD | LI_CCAP_RGB_LED | LI_CCAP_BATTERY_STATE); auto *adapter = allocate_gamepad("ds5"sv, LI_CTYPE_PS, capabilities, 1, 4); ASSERT_NE(adapter, nullptr); @@ -425,7 +409,7 @@ TEST_F(VirtualHidDeviceTest, AllocatesManualProfileAndTranslatesFullState) { EXPECT_FLOAT_EQ(state.left_trigger, 128.0F / 255.0F); EXPECT_FLOAT_EQ(state.right_trigger, 1.0F); - config::input.ds4_back_as_touchpad_click = false; + config_.edit_startup().input.ds4_back_as_touchpad_click = false; platf::virtualhid::gamepad_update(*context(), 1, {platf::BACK, 0, 0, 0, 0, 0, 0}); EXPECT_FALSE(adapter->state().buttons.test(touchpad)); @@ -467,7 +451,7 @@ TEST_F(VirtualHidDeviceTest, FallsBackForUnknownManualProfileAndRandomizesPlaySt EXPECT_EQ(fallback->gamepad()->metadata().client_type, lvh::ClientControllerType::unknown); EXPECT_EQ(fallback->gamepad()->metadata().stable_id, "sunshine-gamepad-0"); - config::input.virtualhid_randomize_mac = true; + config_.edit_startup().input.virtualhid_randomize_mac = true; auto *randomized = allocate_gamepad("ds4"sv, LI_CTYPE_PS, 0, 1); ASSERT_NE(randomized, nullptr); const auto &stable_id = randomized->gamepad()->metadata().stable_id; @@ -770,7 +754,7 @@ TEST_F(VirtualHidDeviceTest, TranslatesMouseAndKeyboardInput) { EXPECT_EQ(mouse_event.kind, lvh::MouseEventKind::horizontal_scroll); EXPECT_EQ(mouse_event.high_resolution_scroll, -240); - config::input.always_send_scancodes = true; + config_.edit_startup().input.always_send_scancodes = true; platf::virtualhid::keyboard_update(*context(), 0x41, false, 0); auto keyboard_event = context()->keyboard->last_submitted_event(); EXPECT_EQ(keyboard_event.key_code, 0x41); @@ -1034,10 +1018,10 @@ TEST_F(VirtualHidDeviceTest, TranslatesPenButtonsToolsAndTransitions) { } TEST_F(VirtualHidDeviceTest, PlatformWrappersForwardToVirtualHidContext) { - auto platform_input = platf::input(infrastructure_.scheduler()); + auto platform_input = platf::input(config_.values(), infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &platform_context = platf::virtualhid::get_input_context(platform_input); - platform_context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; + platform_context = platf::virtualhid::input_context_t {config_.values(), lvh::BackendKind::fake}; ASSERT_NE(platform_context.mouse, nullptr); ASSERT_NE(platform_context.keyboard, nullptr); @@ -1061,7 +1045,7 @@ TEST_F(VirtualHidDeviceTest, PlatformWrappersForwardToVirtualHidContext) { platf::unicode(platform_input, text.data(), static_cast(text.size())); EXPECT_EQ(platform_context.keyboard->submit_count(), keyboard_count + 1); - config::input.gamepad = "ds5"; + config_.edit_startup().input.gamepad = "ds5"; const auto capabilities = static_cast(LI_CCAP_ACCEL | LI_CCAP_GYRO | LI_CCAP_TOUCHPAD | LI_CCAP_BATTERY_STATE); const platf::gamepad_id_t gamepad_id {0, 2}; const platf::gamepad_arrival_t gamepad_metadata {LI_CTYPE_PS, capabilities, 0}; @@ -1088,23 +1072,23 @@ TEST_F(VirtualHidDeviceTest, PlatformWrappersForwardToVirtualHidContext) { #endif EXPECT_FALSE(platf::supported_gamepads(nullptr).empty()); #ifdef _WIN32 - config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIGEMBUS; + platform_context.gamepad_driver = config::GAMEPAD_DRIVER_VIGEMBUS; const auto &vigembus_gamepads = platf::supported_gamepads(std::addressof(platform_input)); - config::input.gamepad_driver = config::GAMEPAD_DRIVER_ALL; + platform_context.gamepad_driver = config::GAMEPAD_DRIVER_ALL; ASSERT_EQ(vigembus_gamepads.size(), 3U); EXPECT_EQ(vigembus_gamepads[0].name, "auto"); EXPECT_EQ(vigembus_gamepads[1].name, "x360"); EXPECT_EQ(vigembus_gamepads[2].name, "ds4"); #endif #ifdef __APPLE__ - const auto controller_touch = platf::get_capabilities() & platf::platform_caps::controller_touch; + const auto controller_touch = platf::get_capabilities(config_.values()) & platf::platform_caps::controller_touch; if (lvh::get_license_status().license.licensed()) { EXPECT_NE(controller_touch, 0U); } else { EXPECT_EQ(controller_touch, 0U); } #else - EXPECT_NE(platf::get_capabilities() & platf::platform_caps::controller_touch, 0U); + EXPECT_NE(platf::get_capabilities(config_.values()) & platf::platform_caps::controller_touch, 0U); #endif platf::free_gamepad(platform_input, 0); @@ -1125,3 +1109,30 @@ TEST_F(VirtualHidDeviceTest, PlatformWrappersForwardToVirtualHidContext) { platf::pen_update(platform_client.get(), viewport, {LI_TOUCH_EVENT_HOVER, LI_TOOL_TYPE_PEN, 0, LI_TILT_UNKNOWN, LI_ROT_UNKNOWN, 0.25F, 0.5F, 0.5F, 0.0F, 0.0F}); EXPECT_EQ(platform_client_context.pen->last_submitted_tool().tool, lvh::PenToolType::pen); } + +#ifdef _WIN32 +TEST_F(VirtualHidDeviceTest, DeferredVigemFeedbackDropsExpiredOwnersAndRunsForRetainedOwners) { + int callbacks = 0; + auto expired_owner = platf::virtualhid::queue_vigem_feedback_for_testing(infrastructure_.scheduler(), [&]() { + ++callbacks; + }); + expired_owner.reset(); + infrastructure_.scheduler().start(1); + const auto stop_worker = util::fail_guard([&]() { + infrastructure_.scheduler().stop(); + infrastructure_.scheduler().join(); + }); + infrastructure_.scheduler().push([]() { + }) + .get(); + EXPECT_EQ(callbacks, 0); + + auto retained_owner = platf::virtualhid::queue_vigem_feedback_for_testing(infrastructure_.scheduler(), [&]() { + ++callbacks; + }); + infrastructure_.scheduler().push([]() { + }) + .get(); + EXPECT_EQ(callbacks, 1); +} +#endif diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index 192db9051..2adda9726 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -26,11 +26,11 @@ namespace platf::audio::tests { std::vector virtual_sink_waveformats(WORD channel_count); - int initialize_audio_control(const std::function> &create_instance); - std::optional configured_sink_info(); - int set_external_sink(const std::string &sink); + int initialize_audio_control(const config::settings_t &settings, const std::function> &create_instance); + std::optional configured_sink_info(const config::settings_t &settings); + int set_external_sink(const config::settings_t &settings, const std::string &sink); bool sink_device_available(const std::string &sink, IMMDeviceEnumerator *device_enum); - bool microphone_available(const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum); + bool microphone_available(const config::settings_t &settings, const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum); bool capture_follows_default_device(IMMDeviceEnumerator *device_enum, IMMDevice *capture_device); capture_e simulate_default_device_change(bool follows_default_device, bool install_callback, bool render_device_changed, int &callback_count); } // namespace platf::audio::tests @@ -298,47 +298,45 @@ TEST(WindowsAudioTest, PreservesVirtualSpeakerFormatPreferenceAndChannelMasks) { } TEST(WindowsAudioTest, AssignedSinkTakesPriorityOverConfiguredSink) { + const config::settings_t settings; fake_device_enumerator_t enumerator {L"assigned-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, "assigned-id", "configured-id", &enumerator)); EXPECT_EQ(enumerator.get_device_calls, 1); EXPECT_EQ(enumerator.last_requested_id, L"assigned-id"); } TEST(WindowsAudioTest, ConfiguredSinkIsUsedWhenNoSinkWasAssigned) { + const config::settings_t settings; fake_device_enumerator_t enumerator {L"configured-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available({}, "configured-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, {}, "configured-id", &enumerator)); EXPECT_EQ(enumerator.get_device_calls, 1); EXPECT_EQ(enumerator.last_requested_id, L"configured-id"); } TEST(WindowsAudioTest, DefaultDeviceIsUsedWhenNoSinkWasRequested) { + const config::settings_t settings; fake_device_enumerator_t enumerator {L"endpoint-id"}; - platf::audio::tests::microphone_available({}, {}, &enumerator); + platf::audio::tests::microphone_available(settings, {}, {}, &enumerator); EXPECT_EQ(enumerator.get_device_calls, 0); } /** - * @brief Preserve global audio configuration while exercising capture-only mode. + * @brief Exercise capture-only mode with fixture-owned audio configuration. */ class ExternalAudioTest: public testing::Test { protected: void SetUp() override { - previous = config::audio; - config::audio.external_audio = true; - config::audio.sink = "configured-id"; - config::audio.virtual_sink = "ignored-virtual-sink"; + settings.audio.external_audio = true; + settings.audio.sink = "configured-id"; + settings.audio.virtual_sink = "ignored-virtual-sink"; policy_requests = 0; enumerator_requests = 0; enumerator_status = S_OK; } - void TearDown() override { - config::audio = previous; - } - /** * @brief Get the number of policy activation requests. * @return Requests observed by the test factory. @@ -387,38 +385,39 @@ protected: return S_OK; } + config::settings_t settings; ///< Configuration owned by each Windows audio fixture. + private: - config::audio_t previous; ///< Configuration restored after each test. inline static int policy_requests = 0; ///< Requests for the unavailable policy interface. inline static int enumerator_requests = 0; ///< Requests for endpoint enumeration. inline static HRESULT enumerator_status = S_OK; ///< Simulated enumeration initialization result. }; TEST_F(ExternalAudioTest, InitializesWithoutPolicyInterface) { - EXPECT_EQ(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); + EXPECT_EQ(platf::audio::tests::initialize_audio_control(settings, &create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 0); EXPECT_EQ(enumerator_request_count(), 1); } TEST_F(ExternalAudioTest, InitializationRequiresEndpointEnumerator) { fail_enumerator_initialization(); - EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); + EXPECT_NE(platf::audio::tests::initialize_audio_control(settings, &create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 0); EXPECT_EQ(enumerator_request_count(), 1); } TEST_F(ExternalAudioTest, DisabledModeStillRequiresPolicyInterface) { - config::audio.external_audio = false; - EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); + settings.audio.external_audio = false; + EXPECT_NE(platf::audio::tests::initialize_audio_control(settings, &create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 1); EXPECT_EQ(enumerator_request_count(), 0); } TEST_F(ExternalAudioTest, RequiresExplicitSink) { - config::audio.sink.clear(); - EXPECT_EXIT(std::exit(platf::audio::tests::configured_sink_info() ? 1 : 0), testing::ExitedWithCode(0), ""); + settings.audio.sink.clear(); + EXPECT_EXIT(std::exit(platf::audio::tests::configured_sink_info(settings) ? 1 : 0), testing::ExitedWithCode(0), ""); fake_device_enumerator_t enumerator {L"endpoint-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available({}, {}, &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, {}, {}, &enumerator)); EXPECT_EQ(enumerator.get_default_device_calls, 0); EXPECT_EQ(enumerator.get_device_calls, 0); } @@ -426,7 +425,7 @@ TEST_F(ExternalAudioTest, RequiresExplicitSink) { TEST_F(ExternalAudioTest, SkipsDefaultAndVirtualDeviceDiscovery) { EXPECT_EXIT( { - const auto sinks = platf::audio::tests::configured_sink_info(); + const auto sinks = platf::audio::tests::configured_sink_info(settings); std::exit(sinks && sinks->host == "configured-id" && !sinks->null ? 0 : 1); }, testing::ExitedWithCode(0), @@ -435,40 +434,40 @@ TEST_F(ExternalAudioTest, SkipsDefaultAndVirtualDeviceDiscovery) { } TEST_F(ExternalAudioTest, SinkChangesDoNotAccessPolicyOrFormatInterfaces) { - EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), ""); - EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("other-endpoint")), testing::ExitedWithCode(0), ""); + EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink(settings, "virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), ""); + EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink(settings, "other-endpoint")), testing::ExitedWithCode(0), ""); } TEST_F(ExternalAudioTest, ConfiguredSinkWinsOverAssignedSink) { fake_device_enumerator_t enumerator {L"configured-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("virtual-Stereoother-id", "configured-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, "virtual-Stereoother-id", "configured-id", &enumerator)); EXPECT_EQ(enumerator.last_requested_id, L"configured-id"); EXPECT_EQ(enumerator.get_default_device_calls, 0); } TEST_F(ExternalAudioTest, MissingSinkDoesNotFallBackToDefault) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available({}, "missing-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, {}, "missing-id", &enumerator)); EXPECT_EQ(enumerator.get_default_device_calls, 0); } TEST_F(ExternalAudioTest, DisconnectedSinkDoesNotFallBackToDefault) { fake_device_enumerator_t enumerator {L"configured-id"}; enumerator.device.state = DEVICE_STATE_UNPLUGGED; - EXPECT_FALSE(platf::audio::tests::microphone_available({}, "configured-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, {}, "configured-id", &enumerator)); EXPECT_EQ(enumerator.get_default_device_calls, 0); } TEST_F(ExternalAudioTest, DisabledModePreservesAssignedSinkPriority) { - config::audio.external_audio = false; + settings.audio.external_audio = false; fake_device_enumerator_t enumerator {L"assigned-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, "assigned-id", "configured-id", &enumerator)); EXPECT_EQ(enumerator.last_requested_id, L"assigned-id"); EXPECT_EQ(enumerator.get_default_device_calls, 0); } TEST_F(ExternalAudioTest, DisabledModePreservesDefaultFallback) { - config::audio.external_audio = false; + settings.audio.external_audio = false; fake_device_enumerator_t enumerator {L"endpoint-id"}; EXPECT_TRUE(platf::audio::tests::capture_follows_default_device(&enumerator, nullptr)); EXPECT_EQ(enumerator.get_default_device_calls, 1); @@ -499,9 +498,10 @@ TEST(WindowsAudioTest, PinnedCaptureKeepsExplicitEndpoint) { } TEST(WindowsAudioTest, MicrophoneRejectsUnresolvedSink) { + const config::settings_t settings; fake_device_enumerator_t enumerator {L"endpoint-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("unknown", {}, &enumerator)); + EXPECT_FALSE(platf::audio::tests::microphone_available(settings, "unknown", {}, &enumerator)); EXPECT_EQ(enumerator.get_device_calls, 0); } diff --git a/tests/unit/platform/windows/test_display_vram.cpp b/tests/unit/platform/windows/test_display_vram.cpp index d9f4889a6..5cd58edbd 100644 --- a/tests/unit/platform/windows/test_display_vram.cpp +++ b/tests/unit/platform/windows/test_display_vram.cpp @@ -75,6 +75,7 @@ TEST_P(ShaderFailureTest, DoesNotPublishPartialBundleAndCanRetry) { INSTANTIATE_TEST_SUITE_P(EveryShader, ShaderFailureTest, testing::Range(1, 26)); TEST(ShaderBundleTest, CaptureRetainsBytecodeAfterPlatformOwnerReleasesIt) { + config::store_t configuration; auto bundle = platf::dxgi::compile_shaders([](const std::string &, const char *) { return shader_blob(7); }); @@ -82,7 +83,7 @@ TEST(ShaderBundleTest, CaptureRetainsBytecodeAfterPlatformOwnerReleasesIt) { return shader_blob(8); }); std::weak_ptr weak = bundle; - auto display = std::make_shared(bundle); + auto display = std::make_shared(configuration.values(), bundle); bundle.reset(); EXPECT_FALSE(weak.expired()); EXPECT_EQ(*static_cast(display->shaders->cursor_vs_hlsl->GetBufferPointer()), 7); @@ -91,7 +92,6 @@ TEST(ShaderBundleTest, CaptureRetainsBytecodeAfterPlatformOwnerReleasesIt) { EXPECT_TRUE(weak.expired()); } -/** TEST(ShaderBundleTest, NativeCompilerBuildsCompleteBundleWithoutCaptureDevice) { const auto bundle = platf::dxgi::compile_shaders(); ASSERT_NE(bundle, nullptr); @@ -99,6 +99,7 @@ TEST(ShaderBundleTest, NativeCompilerBuildsCompleteBundleWithoutCaptureDevice) { EXPECT_GT(bundle->cursor_vs_hlsl->GetBufferSize(), 0); } +/** * @brief Encoder output format, HDR state, option state, and expected FP16 transfer. */ using Fp16TransferParam = std::tuple; diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 851f250d4..e951aeda2 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -33,6 +33,7 @@ struct AudioTest: PlatformTestSuite, testing::WithParamInterface(); } + config::settings_t settings; ///< Host audio settings owned by this fixture. config_t m_config; safe::mail_t m_mail; }; @@ -80,8 +81,156 @@ TEST_P(AudioTest, TestEncode) { } } }); - audio::capture(m_mail, m_config, nullptr); + audio::service_t audios {settings, m_mail}; + audios.capture(m_mail, m_config, nullptr); timer.join(); capture.join(); } + +namespace { + /** @brief Fake controller retaining observed routing and initialization state. */ + struct fake_audio_control_t: platf::audio_control_t { + std::vector &restored; ///< Sink restoration requests observed by the fixture. + std::optional sinks; ///< Sink discovery result injected by the fixture. + + /** @brief Bind fixture state. @param restored Observed sink changes. @param sinks Sink discovery result. */ + fake_audio_control_t(std::vector &restored, std::optional sinks): + restored {restored}, + sinks {std::move(sinks)} {} + + /** @brief Record a routing request. @param sink Requested endpoint. @return Zero on success. */ + int set_sink(const std::string &sink) override { + restored.push_back(sink); + return 0; + } + + /** @brief Supply no microphone because these tests exercise routing ownership. @return Null microphone. */ + std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override { + return nullptr; + } + + /** @brief Report fixture endpoints as available. @param sink Endpoint to inspect. @return Whether the endpoint is recognized. */ + bool is_sink_available(const std::string &sink) override { + return sink == "original" || sink == "configured"; + } + + /** @brief Return the configured discovery result. @return Injected sink information. */ + std::optional sink_info() override { + return sinks; + } + }; +} // namespace + +/** @brief Context references retain shared control after its service is destroyed and restore once. */ +TEST(AudioOwnerTest, RetainedContextSurvivesOwnerAndRestoresOriginalSink) { + config::settings_t settings; + std::vector restored; + audio::audio_ctx_ref_t retained; + { + audio::service_t owner {settings, std::make_shared(), [&]() { + return std::make_unique(restored, platf::sink_t {"original", {}}); + }}; + retained = owner.context(); + auto second = owner.context(); + ASSERT_TRUE(retained); + EXPECT_EQ(retained.get(), second.get()); + EXPECT_TRUE(audio::is_audio_ctx_sink_available(*retained)); + retained->restore_sink = true; + } + EXPECT_TRUE(restored.empty()); + retained.reset(); + EXPECT_EQ(restored, std::vector {"original"}); +} + +/** @brief Failed lazy initialization can be retried after references release their failed attempt. */ +TEST(AudioOwnerTest, FailedInitializationAndSinkDiscoveryCanBeRetried) { + config::settings_t settings; + settings.audio.sink = "configured"; + std::vector restored; + int attempts {}; + audio::service_t owner {settings, std::make_shared(), [&]() -> std::unique_ptr { + ++attempts; + if (attempts == 1) { + return nullptr; + } + return std::make_unique(restored, attempts == 2 ? std::nullopt : std::optional {platf::sink_t {}}); + }}; + { + auto failed = owner.context(); + ASSERT_TRUE(failed); + EXPECT_FALSE(audio::is_audio_ctx_sink_available(*failed)); + } + { + auto failed = owner.context(); + ASSERT_TRUE(failed); + EXPECT_FALSE(failed->control); + } + auto succeeded = owner.context(); + ASSERT_TRUE(succeeded); + ASSERT_TRUE(succeeded->control); + EXPECT_EQ(attempts, 3); + EXPECT_TRUE(audio::is_audio_ctx_sink_available(*succeeded)); + succeeded->restore_sink = true; + succeeded.reset(); + EXPECT_EQ(restored, std::vector {"configured"}); +} + +/** @brief Independent audio owners preserve separate original sinks and capture contexts. */ +TEST(AudioOwnerTest, IndependentOwnersDoNotShareControlOrRestoration) { + config::settings_t first_settings; + config::settings_t second_settings; + std::vector first_restored; + std::vector second_restored; + audio::service_t first {first_settings, std::make_shared(), [&]() { + return std::make_unique(first_restored, platf::sink_t {"first", {}}); + }}; + audio::service_t second {second_settings, std::make_shared(), [&]() { + return std::make_unique(second_restored, platf::sink_t {"second", {}}); + }}; + auto first_context = first.context(); + auto second_context = second.context(); + ASSERT_TRUE(first_context); + ASSERT_TRUE(second_context); + EXPECT_NE(first_context.get(), second_context.get()); + first_context->restore_sink = true; + first_context.reset(); + EXPECT_EQ(first_restored, std::vector {"first"}); + EXPECT_TRUE(second_restored.empty()); +} + +/** @brief Empty and unavailable endpoints cannot be restored or reported as available. */ +TEST(AudioOwnerTest, EmptyAndUnavailableSinksKeepRoutingUnchanged) { + config::settings_t settings; + std::vector restored; + audio::service_t owner {settings, std::make_shared(), [&]() { + return std::make_unique(restored, platf::sink_t {}); + }}; + auto empty = owner.context(); + ASSERT_TRUE(empty); + EXPECT_FALSE(audio::is_audio_ctx_sink_available(*empty)); + empty->restore_sink = true; + empty.reset(); + EXPECT_TRUE(restored.empty()); + auto unavailable = owner.context(); + ASSERT_TRUE(unavailable); + unavailable->sink.host = "unavailable"; + EXPECT_FALSE(audio::is_audio_ctx_sink_available(*unavailable)); +} + +/** @brief Disabled host audio completes shutdown without initializing an audio backend. */ +TEST(AudioOwnerTest, DisabledCaptureDoesNotInitializeDevices) { + config::settings_t settings; + settings.audio.stream = false; + auto host_mail = std::make_shared(); + auto session_mail = std::make_shared(); + const auto shutdown_event = session_mail->event(mail::shutdown); + shutdown_event->raise(true); + int attempts {}; + audio::service_t owner {settings, host_mail, [&]() -> std::unique_ptr { + ++attempts; + return nullptr; + }}; + owner.capture(session_mail, {}, nullptr); + EXPECT_EQ(attempts, 0); +} diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp index 35b2ed71b..45489e019 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -7,10 +7,13 @@ #include "../tests_common.h" // standard includes +#include #include +#include #include #include #include +#include #include // local includes @@ -21,11 +24,13 @@ using namespace std::literals; TEST(ConfigDefaultsTest, UsesAutomaticGamepadSelection) { - EXPECT_EQ(config::input.gamepad, "auto"); + const config::store_t config; + EXPECT_EQ(config.values().input.gamepad, "auto"); } TEST(ConfigDefaultsTest, TreatsFp16SdrCapturesAsLinear) { - EXPECT_FALSE(config::video.fp16_sdr_gamma_encoded); + const config::store_t config; + EXPECT_FALSE(config.values().video.fp16_sdr_gamma_encoded); } using NvencPresetNameParam = std::pair; @@ -63,27 +68,19 @@ namespace { class ConfigPersistenceTest: public testing::Test { protected: /** - * @brief Preserve the active config path and prepare an empty temporary path. + * @brief Prepare this store's empty temporary configuration path. */ void SetUp() override { - original_config_file_ = config::sunshine.config_file; - original_gamepad_driver_ = config::input.gamepad_driver; - original_gamepad_ = config::input.gamepad; - original_apps_file_ = config::stream.file_apps; config_file_ = std::filesystem::temp_directory_path() / "sunshine_test_config_persistence.conf"; // NOSONAR(cpp:S5443): safe for tests std::filesystem::remove(config_file_); - config::sunshine.config_file = config_file_.string(); - config::input.gamepad_driver.clear(); + config_.edit_startup().sunshine.config_file = config_file_.string(); + config_.edit_startup().input.gamepad_driver.clear(); } /** - * @brief Remove the temporary file and restore the active config path. + * @brief Remove files created by this isolated configuration store. */ void TearDown() override { - config::sunshine.config_file = std::move(original_config_file_); - config::input.gamepad_driver = std::move(original_gamepad_driver_); - config::input.gamepad = std::move(original_gamepad_); - config::stream.file_apps = std::move(original_apps_file_); std::filesystem::remove(config_file_.parent_path() / "sunshine_test_config_apps.json"); std::filesystem::remove(config_file_); } @@ -97,12 +94,10 @@ namespace { return config_file_; } + config::store_t config_; ///< Configuration owner isolated to this test. + private: std::filesystem::path config_file_; ///< Temporary configuration file used by the test. - std::string original_config_file_; ///< Active configuration path restored after each test. - std::string original_gamepad_driver_; ///< Gamepad driver preference restored after each test. - std::string original_gamepad_; ///< Gamepad profile restored after each test. - std::string original_apps_file_; ///< Applications file path restored after each test. }; } // namespace @@ -110,13 +105,13 @@ namespace { TEST_F(ConfigPersistenceTest, AppendsMissingOptionWithoutReplacingExistingText) { ASSERT_EQ(file_handler::write_file(config_file().string().c_str(), "# retained comment"), 0); - EXPECT_TRUE(config::persist_config_option_if_missing("gamepad_driver", "all")); + EXPECT_TRUE(config_.persist_config_option_if_missing("gamepad_driver", "all")); EXPECT_EQ( file_handler::read_file(config_file().string().c_str()), "# retained comment\ngamepad_driver = all\n" ); - EXPECT_FALSE(config::persist_config_option_if_missing("gamepad_driver", "virtualhid")); + EXPECT_FALSE(config_.persist_config_option_if_missing("gamepad_driver", "virtualhid")); EXPECT_EQ( file_handler::read_file(config_file().string().c_str()), "# retained comment\ngamepad_driver = all\n" @@ -126,56 +121,52 @@ TEST_F(ConfigPersistenceTest, AppendsMissingOptionWithoutReplacingExistingText) TEST_F(ConfigPersistenceTest, DoesNotReplaceAnExistingOption) { ASSERT_EQ(file_handler::write_file(config_file().string().c_str(), "gamepad_driver = vigembus\n"), 0); - EXPECT_FALSE(config::persist_config_option_if_missing("gamepad_driver", "all")); + EXPECT_FALSE(config_.persist_config_option_if_missing("gamepad_driver", "all")); EXPECT_EQ(file_handler::read_file(config_file().string().c_str()), "gamepad_driver = vigembus\n"); } TEST_F(ConfigPersistenceTest, SelectsAllDriversOnlyForLicensedUsersWithoutAPreference) { - EXPECT_FALSE(config::select_all_gamepad_drivers_if_licensed(false)); - EXPECT_TRUE(config::input.gamepad_driver.empty()); + EXPECT_FALSE(config_.select_all_gamepad_drivers_if_licensed(false)); + EXPECT_TRUE(config_.edit_startup().input.gamepad_driver.empty()); EXPECT_TRUE(file_handler::read_file(config_file().string().c_str()).empty()); - EXPECT_TRUE(config::select_all_gamepad_drivers_if_licensed(true)); - EXPECT_EQ(config::input.gamepad_driver, config::GAMEPAD_DRIVER_ALL); + EXPECT_TRUE(config_.select_all_gamepad_drivers_if_licensed(true)); + EXPECT_EQ(config_.edit_startup().input.gamepad_driver, config::GAMEPAD_DRIVER_ALL); EXPECT_EQ(file_handler::read_file(config_file().string().c_str()), "gamepad_driver = all\n"); - EXPECT_FALSE(config::select_all_gamepad_drivers_if_licensed(true)); + EXPECT_FALSE(config_.select_all_gamepad_drivers_if_licensed(true)); EXPECT_EQ(file_handler::read_file(config_file().string().c_str()), "gamepad_driver = all\n"); } TEST_F(ConfigPersistenceTest, AcceptsAllGamepadProfilesAcrossRepeatedConfigurationChanges) { const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); - config::stream.file_apps = apps_file.string(); + config_.edit_startup().stream.file_apps = apps_file.string(); constexpr std::array profiles {"generic"sv, "x360"sv, "xone"sv, "xseries"sv, "ds4"sv, "ds5"sv, "switch"sv}; for (const auto profile : profiles) { - config::input.gamepad = "auto"; - config::apply_config_for_test(std::string {"gamepad = "} + std::string {profile} + "\n"); - EXPECT_EQ(config::input.gamepad, profile); + config_.edit_startup().input.gamepad = "auto"; + config_.apply_config_for_test(std::string {"gamepad = "} + std::string {profile} + "\n"); + EXPECT_EQ(config_.edit_startup().input.gamepad, profile); } } TEST_F(ConfigPersistenceTest, ParsesFp16SdrGammaEncodedOption) { const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); - config::stream.file_apps = apps_file.string(); + config_.edit_startup().stream.file_apps = apps_file.string(); - config::apply_config_for_test("fp16_sdr_gamma_encoded = enabled\n"); - EXPECT_TRUE(config::video.fp16_sdr_gamma_encoded); + config_.apply_config_for_test("fp16_sdr_gamma_encoded = enabled\n"); + EXPECT_TRUE(config_.edit_startup().video.fp16_sdr_gamma_encoded); - config::apply_config_for_test("fp16_sdr_gamma_encoded = disabled\n"); - EXPECT_FALSE(config::video.fp16_sdr_gamma_encoded); + config_.apply_config_for_test("fp16_sdr_gamma_encoded = disabled\n"); + EXPECT_FALSE(config_.edit_startup().video.fp16_sdr_gamma_encoded); } TEST_F(ConfigPersistenceTest, ParsesFecPercentagesAndRejectsOutOfRangeValues) { - const auto original_stream = config::stream; - const auto restore_stream = util::fail_guard([original_stream]() { - config::stream = original_stream; - }); const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); - config::stream.file_apps = apps_file.string(); + config_.edit_startup().stream.file_apps = apps_file.string(); constexpr std::array cases { std::pair {0, 0}, @@ -188,21 +179,17 @@ TEST_F(ConfigPersistenceTest, ParsesFecPercentagesAndRejectsOutOfRangeValues) { std::pair {255, 20}, }; for (const auto &[setting, expected] : cases) { - config::stream.fec_percentage = 20; - config::apply_config_for_test(std::format("fec_percentage = {}\n", setting)); - EXPECT_EQ(config::stream.fec_percentage, expected) << setting; + config_.edit_startup().stream.fec_percentage = 20; + config_.apply_config_for_test(std::format("fec_percentage = {}\n", setting)); + EXPECT_EQ(config_.edit_startup().stream.fec_percentage, expected) << setting; } } TEST_F(ConfigPersistenceTest, ParsesNvencTwoPassModesAndDefaultsUnknownValues) { using enum nvenc::nvenc_two_pass; - const auto original_video = config::video; - const auto restore_video = util::fail_guard([original_video]() { - config::video = original_video; - }); const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); - config::stream.file_apps = apps_file.string(); + config_.edit_startup().stream.file_apps = apps_file.string(); constexpr std::array cases { std::pair {"disabled"sv, disabled}, @@ -211,8 +198,113 @@ TEST_F(ConfigPersistenceTest, ParsesNvencTwoPassModesAndDefaultsUnknownValues) { std::pair {"unknown"sv, quarter_resolution}, }; for (const auto &[setting, expected] : cases) { - config::video.nv.two_pass = full_resolution; - config::apply_config_for_test(std::string {"nvenc_twopass = "} + std::string {setting} + "\n"); - EXPECT_EQ(config::video.nv.two_pass, expected) << setting; + config_.edit_startup().video.nv.two_pass = full_resolution; + config_.apply_config_for_test(std::string {"nvenc_twopass = "} + std::string {setting} + "\n"); + EXPECT_EQ(config_.edit_startup().video.nv.two_pass, expected) << setting; } } + +TEST(ConfigStoreTest, StartupSettingsAndRecordedChangesBelongToOneStore) { + config::store_t first; + config::store_t second; + first.edit_startup().input.gamepad = "ds5"; + first.edit_startup().video.qp = 42; + first.edit_startup().input.keybindings[0x41] = 0x42; + first.log_config_settings({{"qp", "42"}}, false); + EXPECT_TRUE(first.values().modified_config_settings.empty()); + first.log_config_settings({{"qp", "42"}}, true); + + EXPECT_EQ(first.values().input.gamepad, "ds5"); + EXPECT_EQ(first.values().video.qp, 42); + EXPECT_EQ(first.values().modified_config_settings.at("qp"), "42"); + EXPECT_EQ(second.values().input.gamepad, "auto"); + EXPECT_EQ(second.values().video.qp, 28); + EXPECT_FALSE(second.values().input.keybindings.contains(0x41)); + EXPECT_TRUE(second.values().modified_config_settings.empty()); +} + +TEST(ConfigStoreTest, CredentialsAreIndependentSnapshots) { + config::store_t first; + config::store_t second; + EXPECT_TRUE(first.credentials_snapshot().username.empty()); + first.update_credentials({"alice", "hash-a", "salt-a"}); + auto snapshot = first.credentials_snapshot(); + snapshot.username = "mutated"; + first.update_credentials({"bob", "hash-b", "salt-b"}); + + EXPECT_EQ(first.credentials_snapshot().username, "bob"); + EXPECT_EQ(first.credentials_snapshot().password, "hash-b"); + EXPECT_EQ(first.credentials_snapshot().salt, "salt-b"); + EXPECT_TRUE(second.credentials_snapshot().username.empty()); + EXPECT_EQ(snapshot.password, "hash-a"); +} + +TEST(ConfigStoreTest, ConcurrentCredentialReadersSeeCompleteUpdates) { + config::store_t config; + config.update_credentials({"alice", "alice", "alice"}); + std::atomic done {false}; + std::atomic consistent {true}; + std::thread writer {[&]() { + for (int index = 0; index < 1000; ++index) { + const auto value = index % 2 ? "alice" : "bob"; + config.update_credentials({value, value, value}); + } + done = true; + }}; + do { + const auto snapshot = config.credentials_snapshot(); + if (snapshot.username != snapshot.password || snapshot.password != snapshot.salt) { + consistent = false; + } + } while (!done); + writer.join(); + EXPECT_TRUE(consistent); +} + +TEST_F(ConfigPersistenceTest, CommandLineOverridesFileAndLastRepeatedValueWins) { + const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; + ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); + config_.edit_startup().stream.file_apps = apps_file.string(); + ASSERT_EQ(file_handler::write_file(config_file().string().c_str(), "qp = 31\nport = 47990\n"), 0); + std::array arguments {"sunshine", config_file().string(), "qp=37", "qp=39"}; + std::array argv; + std::ranges::transform(arguments, argv.begin(), [](auto &argument) { + return argument.data(); + }); + + ASSERT_EQ(config_.parse(argv.size(), argv.data()), 0); + EXPECT_EQ(config_.values().video.qp, 39); + EXPECT_EQ(config_.values().sunshine.port, 47990); + EXPECT_EQ(config_.values().modified_config_settings.at("qp"), "39"); +} + +TEST_F(ConfigPersistenceTest, CommandArgumentsAndFlagsStayWithTheirStore) { + const auto apps_file = config_file().parent_path() / "sunshine_test_config_apps.json"; + ASSERT_EQ(file_handler::write_file(apps_file.string().c_str(), "{}"), 0); + config_.edit_startup().stream.file_apps = apps_file.string(); + std::array arguments {"sunshine", "-01", "--version", "argument"}; + std::array argv; + std::ranges::transform(arguments, argv.begin(), [](auto &argument) { + return argument.data(); + }); + + ASSERT_EQ(config_.parse(argv.size(), argv.data()), 0); + EXPECT_TRUE(config_.values().sunshine.flags[config::flag::PIN_STDIN]); + EXPECT_TRUE(config_.values().sunshine.flags[config::flag::FRESH_STATE]); + EXPECT_EQ(config_.values().sunshine.cmd.name, "version"); + EXPECT_EQ(config_.values().sunshine.cmd.argc, 1); + EXPECT_EQ(config_.values().sunshine.cmd.argv[0], arguments.back()); + const config::store_t second; + EXPECT_FALSE(second.values().sunshine.flags.any()); + EXPECT_TRUE(second.values().sunshine.cmd.name.empty()); +} + +TEST(ConfigStoreTest, HelpAndUnknownFlagsRetainTheirReturnCodes) { + config::store_t config; + std::array arguments {"sunshine", "--help"}; + std::array argv {arguments[0].data(), arguments[1].data()}; + EXPECT_EQ(config.parse(argv.size(), argv.data()), 1); + arguments[1] = "-z"; + argv[1] = arguments[1].data(); + EXPECT_EQ(config.parse(argv.size(), argv.data()), -1); +} diff --git a/tests/unit/test_confighttp.cpp b/tests/unit/test_confighttp.cpp index ee4ebcd08..d342de8b7 100644 --- a/tests/unit/test_confighttp.cpp +++ b/tests/unit/test_confighttp.cpp @@ -100,6 +100,7 @@ X4wnh1bwdiidqpcgyuKossLOPxbS786WmsesaAWPnpoY6M8aija+ALwNNuWWmyMg */ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected members are intentional for test fixture subclassing protected: + config::credentials_t credentials; ///< Complete authentication values owned by this fixture. test_utils::server_context_t context; ///< Services owned by this HTTPS fixture. std::unique_ptr web; ///< Handlers bound to the fixture services. std::unique_ptr> server; @@ -108,11 +109,6 @@ protected: unsigned short port = 0; std::atomic_size_t permission_queries {0}; ///< Queries made by this fixture's permission handler. - std::string saved_username; - std::string saved_password; - std::string saved_salt; - std::string saved_locale; - std::vector saved_csrf_allowed_origins; std::filesystem::path test_web_dir; std::filesystem::path cert_file; std::filesystem::path key_file; @@ -120,7 +116,7 @@ protected: void SetUp() override { BaseTest::SetUp(); - web = std::make_unique(context.gamestream, context.http_state, context.processes, context.displays, context.inputs, context.rtsp, context.infrastructure.lifetime(), context.host_mail); + web = std::make_unique(context.configuration, context.gamestream, context.http_state, context.processes, context.displays, context.inputs, context.rtsp, context.infrastructure.lifetime(), context.host_mail); const auto handler = [this](auto method) { return [this, method](const auto &response, const auto &request) { (web.get()->*method)(response, request); @@ -137,23 +133,21 @@ protected: }); // Save current config - saved_username = config::sunshine.username; - saved_password = config::sunshine.password; - saved_salt = config::sunshine.salt; - saved_locale = config::sunshine.locale; - saved_csrf_allowed_origins = config::sunshine.csrf_allowed_origins; // Set up test credentials - config::sunshine.username = "testuser"; - config::sunshine.salt = "testsalt"; - config::sunshine.password = util::hex(crypto::hash("testpass" + config::sunshine.salt)).to_string(); + credentials.username = "testuser"; + context.configuration.update_credentials(credentials); + credentials.salt = "testsalt"; + context.configuration.update_credentials(credentials); + credentials.password = util::hex(crypto::hash("testpass" + credentials.salt)).to_string(); + context.configuration.update_credentials(credentials); // Set test locale - config::sunshine.locale = "en"; + context.configuration.edit_startup().sunshine.locale = "en"; // Set test web UI port (will be used in SetUp after server starts) // For now, just set the base defaults - we'll add the port-specific ones after server starts - config::sunshine.csrf_allowed_origins = { + context.configuration.edit_startup().sunshine.csrf_allowed_origins = { "https://localhost", "https://127.0.0.1", "https://[::1]" @@ -376,9 +370,9 @@ protected: ASSERT_NE(port, 0) << "Server failed to start"; // Now that we have the port, add it to CSRF allowed origins - config::sunshine.csrf_allowed_origins.push_back(std::format("https://localhost:{}", port)); - config::sunshine.csrf_allowed_origins.push_back(std::format("https://127.0.0.1:{}", port)); - config::sunshine.csrf_allowed_origins.push_back(std::format("https://[::1]:{}", port)); + context.configuration.edit_startup().sunshine.csrf_allowed_origins.push_back(std::format("https://localhost:{}", port)); + context.configuration.edit_startup().sunshine.csrf_allowed_origins.push_back(std::format("https://127.0.0.1:{}", port)); + context.configuration.edit_startup().sunshine.csrf_allowed_origins.push_back(std::format("https://[::1]:{}", port)); // Set up client client = std::make_unique>(std::format("localhost:{}", port), false); @@ -395,11 +389,6 @@ protected: web->reset_virtual_input_license_status_provider_for_testing(); web->reset_portal_token_path_provider_for_testing(); - config::sunshine.username = saved_username; - config::sunshine.password = saved_password; - config::sunshine.salt = saved_salt; - config::sunshine.locale = saved_locale; - config::sunshine.csrf_allowed_origins = saved_csrf_allowed_origins; context.gamestream.expire_pair_sessions(std::chrono::steady_clock::time_point::max()); // Clean up test HTML file from WEB_DIR @@ -1121,14 +1110,16 @@ TEST_F(ConfigHttpTest, GetPageRedirectsWhenUsernameSet) { // Test: web->getPage() doesn't redirect when username is empty TEST_F(ConfigHttpTest, GetPageNoRedirectWhenUsernameEmpty) { // Temporarily clear username - const std::string saved = config::sunshine.username; - config::sunshine.username = ""; + const std::string saved = credentials.username; + credentials.username = ""; + context.configuration.update_credentials(credentials); const auto response = client->request("GET", "/page-redirect-test"); ASSERT_EQ(response->status_code, "200 OK"); // Restore username - config::sunshine.username = saved; + credentials.username = saved; + context.configuration.update_credentials(credentials); } // Test: browser routes fall back to the SPA entry document diff --git a/tests/unit/test_entry_handler.cpp b/tests/unit/test_entry_handler.cpp index 787ed0436..733fae59e 100644 --- a/tests/unit/test_entry_handler.cpp +++ b/tests/unit/test_entry_handler.cpp @@ -11,54 +11,39 @@ #include /** - * @brief Test fixture that restores Web UI URL configuration after each test. + * @brief Test fixture that owns Web UI URL settings for each test. */ class LaunchUiUrlTest: public BaseTest { -private: - std::string original_bind_address; - std::uint16_t original_port; - protected: - void SetUp() override { - BaseTest::SetUp(); - original_bind_address = config::sunshine.bind_address; - original_port = config::sunshine.port; - config::sunshine.port = 47989; - } - - void TearDown() override { - config::sunshine.bind_address = original_bind_address; - config::sunshine.port = original_port; - BaseTest::TearDown(); - } + config::store_t configuration; ///< Configuration isolated to this fixture. }; /** * @brief Test that Web UI URLs use localhost when no bind address is configured. */ TEST_F(LaunchUiUrlTest, UsesLocalhostWithoutBindAddress) { - config::sunshine.bind_address = ""; + configuration.edit_startup().sunshine.bind_address = ""; - EXPECT_EQ(get_launch_ui_url(), "https://localhost:47990"); - EXPECT_EQ(get_launch_ui_url("/pin"), "https://localhost:47990/pin"); + EXPECT_EQ(get_launch_ui_url(configuration.values()), "https://localhost:47990"); + EXPECT_EQ(get_launch_ui_url(configuration.values(), "/pin"), "https://localhost:47990/pin"); } /** * @brief Test that Web UI URLs use the configured IPv4 bind address. */ TEST_F(LaunchUiUrlTest, UsesConfiguredIPv4Address) { - config::sunshine.bind_address = "198.51.100.56"; + configuration.edit_startup().sunshine.bind_address = "198.51.100.56"; - EXPECT_EQ(get_launch_ui_url(), "https://198.51.100.56:47990"); + EXPECT_EQ(get_launch_ui_url(configuration.values()), "https://198.51.100.56:47990"); } /** * @brief Test that Web UI URLs enclose configured IPv6 bind addresses in brackets. */ TEST_F(LaunchUiUrlTest, EscapesConfiguredIPv6Address) { - config::sunshine.bind_address = "2001:db8::1"; + configuration.edit_startup().sunshine.bind_address = "2001:db8::1"; - EXPECT_EQ(get_launch_ui_url("/config"), "https://[2001:db8::1]:47990/config"); + EXPECT_EQ(get_launch_ui_url(configuration.values(), "/config"), "https://[2001:db8::1]:47990/config"); } TEST(EntryHandlerTests, LogPublisherDataTest) { @@ -71,6 +56,11 @@ TEST(EntryHandlerTests, LogPublisherDataTest) { ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Get support: ")); } +TEST(EntryHandlerTests, CredentialsCommandShowsHelpWithoutReadingMissingArguments) { + const config::store_t configuration; + EXPECT_EQ(args::creds(configuration.values(), "sunshine", 0, nullptr), 0); +} + TEST(EntryHandlerTests, ControllersKeepArgumentsAndExitStatusIndependent) { char first_name[] = "first"; char second_name[] = "second"; @@ -85,6 +75,16 @@ TEST(EntryHandlerTests, ControllersKeepArgumentsAndExitStatusIndependent) { int signals = 0; lifetime::signal_guard_t guard {first}; + guard.on_signal(SIGINT, [&signals]() { + ++signals; + }); + first.exit_sunshine(7, true); + first.exit_sunshine(9, true); + EXPECT_EQ(first.exit_code(), 7); + EXPECT_EQ(second.exit_code(), 0); + EXPECT_EQ(signals, 2); +} + /** * @brief Termination signals remain registered before callbacks issue another signal. */ @@ -107,16 +107,6 @@ TEST(EntryHandlerTests, RearmsTerminationSignalsBeforeInvokingOwnedCallbacks) { } } - guard.on_signal(SIGINT, [&signals]() { - ++signals; - }); - first.exit_sunshine(7, true); - first.exit_sunshine(9, true); - EXPECT_EQ(first.exit_code(), 7); - EXPECT_EQ(second.exit_code(), 0); - EXPECT_EQ(signals, 2); -} - TEST(EntryHandlerTests, NativeCallbackBindingIsScopedAndRestoresPreviousHandler) { lifetime::controller_t controller; const auto expected = +[](int) { @@ -150,6 +140,16 @@ TEST(EntryHandlerTests, RequestedRestartRunsAfterDependentCleanup) { bool restarted = false; { lifetime::controller_t controller; + controller.restart_on_exit([&]() { + EXPECT_TRUE(cleaned); + restarted = true; + }); + auto dependent = util::fail_guard([&cleaned]() { + cleaned = true; + }); + } + EXPECT_TRUE(restarted); +} /** * @brief Infrastructure destruction waits for active work before releasing its dependencies. @@ -195,14 +195,4 @@ TEST(EntryHandlerTests, InfrastructureDestructionAcceptsPreviouslyJoinedSchedule infrastructure.scheduler().stop(); infrastructure.scheduler().join(); infrastructure.scheduler().join(); -} - controller.restart_on_exit([&]() { - EXPECT_TRUE(cleaned); - restarted = true; - }); - auto dependent = util::fail_guard([&cleaned]() { - cleaned = true; - }); - } - EXPECT_TRUE(restarted); } diff --git a/tests/unit/test_http_pairing.cpp b/tests/unit/test_http_pairing.cpp index d4e55f6c0..1eab055d9 100644 --- a/tests/unit/test_http_pairing.cpp +++ b/tests/unit/test_http_pairing.cpp @@ -101,8 +101,8 @@ struct PairingTest: BaseTest, test_utils::server_context_t, testing::WithParamIn */ void SetUp() override { BaseTest::SetUp(); - original_fresh_state = config::sunshine.flags[config::flag::FRESH_STATE]; - config::sunshine.flags[config::flag::FRESH_STATE] = true; + original_fresh_state = configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE]; + configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE] = true; gamestream.test_reset_client_state(); } @@ -111,7 +111,7 @@ struct PairingTest: BaseTest, test_utils::server_context_t, testing::WithParamIn */ void TearDown() override { gamestream.test_reset_client_state(); - config::sunshine.flags[config::flag::FRESH_STATE] = original_fresh_state; + configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE] = original_fresh_state; BaseTest::TearDown(); } @@ -420,9 +420,9 @@ namespace { void SetUp() override { BaseTest::SetUp(); gamestream.expire_pair_sessions(std::chrono::steady_clock::time_point::max()); - original_pin_stdin_ = config::sunshine.flags[config::flag::PIN_STDIN]; - original_ping_timeout_ = config::stream.ping_timeout; - config::sunshine.flags[config::flag::PIN_STDIN] = false; + original_pin_stdin_ = configuration.edit_startup().sunshine.flags[config::flag::PIN_STDIN]; + original_ping_timeout_ = configuration.edit_startup().stream.ping_timeout; + configuration.edit_startup().sunshine.flags[config::flag::PIN_STDIN] = false; server_ = std::make_unique>(); server_->config.port = 0; @@ -460,8 +460,8 @@ namespace { } client_.reset(); server_.reset(); - config::sunshine.flags[config::flag::PIN_STDIN] = original_pin_stdin_; - config::stream.ping_timeout = original_ping_timeout_; + configuration.edit_startup().sunshine.flags[config::flag::PIN_STDIN] = original_pin_stdin_; + configuration.edit_startup().stream.ping_timeout = original_ping_timeout_; BaseTest::TearDown(); } @@ -550,7 +550,7 @@ TEST_F(PairingHttpHandlerTest, PinReturnsCompletedHandshakeResult) { const auto pairing_id = wait_for_pending_pairing(); ASSERT_FALSE(pairing_id.empty()); - config::stream.ping_timeout = std::chrono::seconds {2}; + configuration.edit_startup().stream.ping_timeout = std::chrono::seconds {2}; std::packaged_task pin_task {[this, &pairing_id]() { return gamestream.pin(pairing_id, "5338", "Test client"); }}; @@ -572,7 +572,7 @@ TEST_F(PairingHttpHandlerTest, PinReturnsFalseWhenClientDoesNotCompleteHandshake const auto pairing_id = wait_for_pending_pairing(); ASSERT_FALSE(pairing_id.empty()); - config::stream.ping_timeout = std::chrono::milliseconds {50}; + configuration.edit_startup().stream.ping_timeout = std::chrono::milliseconds {50}; EXPECT_FALSE(gamestream.pin(pairing_id, "0000", "Test client")); EXPECT_NE(client_response.get().find("status_code=\"200\""), std::string::npos); EXPECT_TRUE(gamestream.get_pending_pairings().empty()); @@ -595,7 +595,7 @@ TEST_F(PairingHttpHandlerTest, DuplicateAndCapacityErrorsReturnImmediately) { TEST_F(PairingHttpHandlerTest, ConsolePinCompletesOrRejectsTheCertificatePhase) { gamestream.setup(PRIVATE_KEY, PUBLIC_CERT); - config::sunshine.flags[config::flag::PIN_STDIN] = true; + configuration.edit_startup().sunshine.flags[config::flag::PIN_STDIN] = true; std::istringstream input {"5338\n0000\n"}; const cin_buffer_guard input_guard {input.rdbuf()}; @@ -604,7 +604,7 @@ TEST_F(PairingHttpHandlerTest, ConsolePinCompletesOrRejectsTheCertificatePhase) } TEST_F(PairingHttpHandlerTest, ConsolePinReportsSessionExpiration) { - config::sunshine.flags[config::flag::PIN_STDIN] = true; + configuration.edit_startup().sunshine.flags[config::flag::PIN_STDIN] = true; gated_input_buffer input; const cin_buffer_guard input_guard {&input}; std::packaged_task request_task {[this]() { diff --git a/tests/unit/test_httpcommon.cpp b/tests/unit/test_httpcommon.cpp index e2b63f40d..77fb4fa3a 100644 --- a/tests/unit/test_httpcommon.cpp +++ b/tests/unit/test_httpcommon.cpp @@ -5,6 +5,10 @@ // test includes #include "../tests_common.h" +// standard includes +#include +#include + // lib includes #include @@ -71,3 +75,34 @@ INSTANTIATE_TEST_SUITE_P( std::make_tuple(URL_2, "hello-redirect.txt") ) ); + +/** + * @brief Credential reload publishes all fields together and preserves them after an incomplete file. + */ +TEST(HttpCredentialStoreTest, CompleteReloadAndFailuresPreserveIndependentStores) { + config::store_t first; + config::store_t second; + first.update_credentials({"previous", "previous hash", "previous salt"}); + second.update_credentials({"other", "other hash", "other salt"}); + const auto file = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "http_credentials_owner.json"; + { + std::ofstream output {file}; + output << R"({"username":"new","password":"new hash","salt":"new salt"})"; + } + ASSERT_EQ(http::reload_user_creds(file.string(), first), 0); + EXPECT_EQ(first.credentials_snapshot().username, "new"); + EXPECT_EQ(first.credentials_snapshot().password, "new hash"); + EXPECT_EQ(first.credentials_snapshot().salt, "new salt"); + EXPECT_EQ(second.credentials_snapshot().username, "other"); + { + std::ofstream output {file}; + output << R"({"username":"partial","password":"partial hash"})"; + } + EXPECT_NE(http::reload_user_creds(file.string(), first), 0); + EXPECT_EQ(first.credentials_snapshot().username, "new"); + EXPECT_EQ(first.credentials_snapshot().password, "new hash"); + EXPECT_EQ(first.credentials_snapshot().salt, "new salt"); + std::filesystem::remove(file); + EXPECT_NE(http::reload_user_creds(file.string(), first), 0); + EXPECT_EQ(first.credentials_snapshot().username, "new"); +} diff --git a/tests/unit/test_input.cpp b/tests/unit/test_input.cpp index d6a05c340..334210a0d 100644 --- a/tests/unit/test_input.cpp +++ b/tests/unit/test_input.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -26,6 +27,7 @@ extern "C" { // local includes #include "src/config.h" +#include "src/file_handler.h" #include "src/input.h" #include "src/platform/virtualhid_input.h" #include "src/utility.h" @@ -96,22 +98,22 @@ namespace { */ class InputGamepadSessionTest: public ::testing::Test { protected: + config::store_t config_; ///< Configuration owned by this fixture. runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this input fixture. - input::service_t inputs_ {infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. + input::service_t inputs_ {config_.values(), infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. /** * @brief Preserve configuration and install observable fake devices. */ void SetUp() override { - original_input_ = config::input; - config::input.controller = true; - config::input.mouse = true; - config::input.gamepad = "xseries"; + config_.edit_startup().input.controller = true; + config_.edit_startup().input.mouse = true; + config_.edit_startup().input.gamepad = "xseries"; - auto platform_input = platf::input(infrastructure_.scheduler()); + auto platform_input = platf::input(config_.values(), infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &context = platf::virtualhid::get_input_context(platform_input); - context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; + context = platf::virtualhid::input_context_t {config_.values(), lvh::BackendKind::fake}; context_ = &context; runtime_ = context.runtime.get(); ASSERT_NE(runtime_, nullptr); @@ -128,7 +130,6 @@ namespace { input::testing::set_platform_input(inputs_, {}); context_ = nullptr; runtime_ = nullptr; - config::input = std::move(original_input_); } /** @@ -152,7 +153,6 @@ namespace { private: platf::virtualhid::input_context_t *context_ = nullptr; ///< Fake input context installed in the global backend. lvh::Runtime *runtime_ = nullptr; ///< Fake runtime installed in the global input backend. - config::input_t original_input_; ///< Input configuration restored after each test. }; } // namespace @@ -293,7 +293,7 @@ TEST_F(InputGamepadSessionTest, RejectsMalformedBatchablePacketsAtQueueIngress) TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController) { ASSERT_FALSE(infrastructure_.scheduler().running()); - config::input.gamepad = "auto"; + config_.edit_startup().input.gamepad = "auto"; auto stream_input = inputs_.alloc(std::make_shared(), "simultaneous-controller-packets"); ASSERT_NE(stream_input, nullptr); @@ -399,9 +399,9 @@ TEST_F(InputGamepadSessionTest, YieldsAfterBoundedPacketBatch) { TEST_F(InputGamepadSessionTest, BatchesContinuousPacketsWithoutCrossingStateChanges) { ASSERT_FALSE(infrastructure_.scheduler().running()); - config::input.mouse = false; - config::input.controller = false; - config::input.native_pen_touch = false; + config_.edit_startup().input.mouse = false; + config_.edit_startup().input.controller = false; + config_.edit_startup().input.native_pen_touch = false; input::testing::set_input_task_sink(inputs_, [](std::shared_ptr) { }); @@ -522,11 +522,11 @@ TEST_F(InputGamepadSessionTest, RefreshesSharedVirtualInputAfterLicenseStateChan TEST_F(InputGamepadSessionTest, IndependentHostServicesDoNotShareRetainedSessionsOrGamepadSlots) { runtime::infrastructure_t other_infrastructure; - input::service_t other_inputs {other_infrastructure.scheduler(), other_infrastructure.mailbox(), other_infrastructure.cursor()}; - auto other_platform = platf::input(other_infrastructure.scheduler()); + input::service_t other_inputs {config_.values(), other_infrastructure.scheduler(), other_infrastructure.mailbox(), other_infrastructure.cursor()}; + auto other_platform = platf::input(config_.values(), other_infrastructure.scheduler()); ASSERT_TRUE(other_platform); auto &other_context = platf::virtualhid::get_input_context(other_platform); - other_context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; + other_context = platf::virtualhid::input_context_t {config_.values(), lvh::BackendKind::fake}; input::testing::set_platform_input(other_inputs, std::move(other_platform)); auto first = inputs_.alloc(std::make_shared(), "same-client"); @@ -592,3 +592,68 @@ TEST_F(InputGamepadSessionTest, RetargetsRelativeMouseFromLatestStreamGeometry) EXPECT_EQ(mouse_event.y, 9); EXPECT_EQ(context().mouse_viewport.offset_x, 0); } + +TEST_F(InputGamepadSessionTest, LicensedBackendChoiceIsSerializedWithoutChangingStartupSettings) { + const auto path = std::filesystem::temp_directory_path() / "sunshine_test_runtime_gamepad_policy.conf"; // NOSONAR(cpp:S5443): safe for tests + std::filesystem::remove(path); + const auto remove_file = util::fail_guard([&]() { + std::filesystem::remove(path); + }); + config_.edit_startup().sunshine.config_file = path.string(); + infrastructure_.scheduler().start(1); + const auto stop_worker = util::fail_guard([&]() { + infrastructure_.scheduler().stop(); + infrastructure_.scheduler().join(); + }); + + EXPECT_FALSE(inputs_.select_all_gamepad_drivers_if_licensed(config_, false)); + EXPECT_TRUE(inputs_.select_all_gamepad_drivers_if_licensed(config_, true)); + EXPECT_EQ(inputs_.configuration_snapshot().gamepad_driver, config::GAMEPAD_DRIVER_ALL); + EXPECT_EQ(context().gamepad_driver, config::GAMEPAD_DRIVER_ALL); + EXPECT_TRUE(config_.values().input.gamepad_driver.empty()); + EXPECT_EQ(file_handler::read_file(path.string().c_str()), "gamepad_driver = all\n"); + EXPECT_FALSE(inputs_.select_all_gamepad_drivers_if_licensed(config_, true)); + EXPECT_FALSE(inputs_.probe_gamepads()); + auto snapshot = inputs_.configuration_snapshot(); + snapshot.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + EXPECT_EQ(inputs_.configuration_snapshot().gamepad_driver, config::GAMEPAD_DRIVER_ALL); +} + +TEST_F(InputGamepadSessionTest, LicensedBackendChoiceHonorsSavedPreferencesAndPersistenceFailures) { + const auto path = std::filesystem::temp_directory_path() / "sunshine_test_existing_gamepad_policy.conf"; // NOSONAR(cpp:S5443): safe for tests + const auto remove_file = util::fail_guard([&]() { + std::filesystem::remove(path); + }); + config_.edit_startup().sunshine.config_file = path.string(); + ASSERT_EQ(file_handler::write_file(path.string().c_str(), "gamepad_driver = vigembus\n"), 0); + EXPECT_FALSE(inputs_.select_all_gamepad_drivers_if_licensed(config_, true)); + EXPECT_TRUE(inputs_.configuration_snapshot().gamepad_driver.empty()); + EXPECT_EQ(file_handler::read_file(path.string().c_str()), "gamepad_driver = vigembus\n"); + + config_.edit_startup().sunshine.config_file.clear(); + EXPECT_FALSE(inputs_.select_all_gamepad_drivers_if_licensed(config_, true)); + EXPECT_TRUE(inputs_.configuration_snapshot().gamepad_driver.empty()); +} + +TEST_F(InputGamepadSessionTest, LicensedBackendChoiceCanPrecedePlatformInitialization) { + const auto path = std::filesystem::temp_directory_path() / "sunshine_test_inactive_gamepad_policy.conf"; // NOSONAR(cpp:S5443): safe for tests + std::filesystem::remove(path); + const auto remove_file = util::fail_guard([&]() { + std::filesystem::remove(path); + }); + config_.edit_startup().sunshine.config_file = path.string(); + input::service_t inactive {config_.values(), infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; + + EXPECT_TRUE(inactive.select_all_gamepad_drivers_if_licensed(config_, true)); + EXPECT_EQ(inactive.configuration_snapshot().gamepad_driver, config::GAMEPAD_DRIVER_ALL); + EXPECT_TRUE(inputs_.configuration_snapshot().gamepad_driver.empty()); +} + +TEST_F(InputGamepadSessionTest, ExplicitStartupBackendChoiceRemainsSelectedAfterLicensing) { + config::store_t explicit_config; + explicit_config.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + input::service_t explicit_inputs {explicit_config.values(), infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; + + EXPECT_FALSE(explicit_inputs.select_all_gamepad_drivers_if_licensed(explicit_config, true)); + EXPECT_EQ(explicit_inputs.configuration_snapshot().gamepad_driver, config::GAMEPAD_DRIVER_NONE); +} diff --git a/tests/unit/test_keyboard.cpp b/tests/unit/test_keyboard.cpp index d7525ea70..bdbfeee43 100644 --- a/tests/unit/test_keyboard.cpp +++ b/tests/unit/test_keyboard.cpp @@ -319,24 +319,24 @@ namespace { */ class KeyboardPassthroughTest: public ::testing::Test { protected: + config::store_t config_; ///< Configuration owned by this fixture. runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this keyboard fixture. - input::service_t inputs_ {infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. + input::service_t inputs_ {config_.values(), infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. /** * @brief Install a fake platform backend, a keyboard recorder, and a stream. */ void SetUp() override { - original_input_ = config::input; - config::input.keyboard = true; - config::input.keybindings.clear(); - config::input.key_rightalt_to_key_win = false; + config_.edit_startup().input.keyboard = true; + config_.edit_startup().input.keybindings.clear(); + config_.edit_startup().input.key_rightalt_to_key_win = false; // Keep every emission on the calling thread so the recorded order is deterministic. - config::input.key_repeat_delay = 0ms; + config_.edit_startup().input.key_repeat_delay = 0ms; - auto platform_input = platf::input(infrastructure_.scheduler()); + auto platform_input = platf::input(config_.values(), infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &context = platf::virtualhid::get_input_context(platform_input); - context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; + context = platf::virtualhid::input_context_t {config_.values(), lvh::BackendKind::fake}; context_ = &context; ASSERT_NE(context_->keyboard, nullptr); input::testing::set_platform_input(inputs_, std::move(platform_input)); @@ -360,7 +360,6 @@ namespace { stream_.reset(); context_ = nullptr; input::testing::set_platform_input(inputs_, {}); - config::input = std::move(original_input_); } /** @@ -434,7 +433,6 @@ namespace { std::shared_ptr stream_; ///< Stream input state under test. std::vector events_; ///< Keyboard output recorded for the current test. platf::virtualhid::input_context_t *context_ = nullptr; ///< Fake input context installed in the global backend. - config::input_t original_input_; ///< Input configuration restored after each test. }; } // namespace @@ -647,7 +645,7 @@ TEST_F(KeyboardPassthroughTest, IgnoresRepeatedPressesAndUnmatchedReleases) { } TEST_F(KeyboardPassthroughTest, EmitsRemappedKeycodesFromKeybindings) { - config::input.keybindings = { + config_.edit_startup().input.keybindings = { {VKEY_LWIN, VKEY_LMENU}, {VKEY_RWIN, VKEY_RMENU}, {VKEY_LMENU, VKEY_LWIN}, @@ -679,7 +677,7 @@ TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltWhenAltIsRemappedToMeta // gets positional Option and Command. shortcutFlags is compared against the client's modifier // bitmask, so it has to track the client keycode. Tracking the remapped host keycode instead // left the ALT bit clear and wrapped every following key in a real VKEY_MENU press. - config::input.keybindings = { + config_.edit_startup().input.keybindings = { {VKEY_LWIN, VKEY_LMENU}, {VKEY_RWIN, VKEY_RMENU}, {VKEY_LMENU, VKEY_LWIN}, @@ -715,7 +713,7 @@ TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltWhenAltIsRemappedToMeta } TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltWhenRightAltIsRemappedToMeta) { - config::input.keybindings = {{VKEY_RMENU, VKEY_RWIN}}; + config_.edit_startup().input.keybindings = {{VKEY_RMENU, VKEY_RWIN}}; press(VKEY_RMENU, MODIFIER_ALT); press(VKEY_SPACE, MODIFIER_ALT); @@ -735,8 +733,8 @@ TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltWhenRightAltIsRemappedT TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltForKeyRightaltToKeyWin) { // config.cpp installs this keybinding when the option is enabled. - config::input.key_rightalt_to_key_win = true; - config::input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; + config_.edit_startup().input.key_rightalt_to_key_win = true; + config_.edit_startup().input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; press(VKEY_RMENU, MODIFIER_ALT); press(VKEY_SPACE, MODIFIER_ALT); @@ -755,8 +753,8 @@ TEST_F(KeyboardPassthroughTest, DoesNotInjectSyntheticAltForKeyRightaltToKeyWin) } TEST_F(KeyboardPassthroughTest, KeepsRealAltWhileRightAltMapsToKeyWin) { - config::input.key_rightalt_to_key_win = true; - config::input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; + config_.edit_startup().input.key_rightalt_to_key_win = true; + config_.edit_startup().input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; // Left Alt is a real Alt, so the ALT bit must not be masked away while it is held. press(VKEY_LMENU, MODIFIER_ALT); @@ -814,7 +812,7 @@ TEST_F(KeyboardPassthroughTest, KeepsShiftAndControlSetWhileTheirOtherSideRemain for (const auto &modifier : cases) { SCOPED_TRACE(modifier.name); - config::input.keybindings = {{modifier.right, VKEY_LWIN}}; + config_.edit_startup().input.keybindings = {{modifier.right, VKEY_LWIN}}; press(modifier.left, modifier.bit); press(modifier.right, modifier.bit); @@ -884,7 +882,7 @@ TEST_F(KeyboardPassthroughTest, DeliversKeysThroughTheVirtualKeyboard) { EXPECT_EQ(keyboard.last_submitted_event().key_code, VKEY_A); EXPECT_FALSE(keyboard.last_submitted_event().pressed); - config::input.keybindings = {{VKEY_LMENU, VKEY_LWIN}}; + config_.edit_startup().input.keybindings = {{VKEY_LMENU, VKEY_LWIN}}; press(VKEY_LMENU, MODIFIER_ALT); EXPECT_EQ(keyboard.submit_count(), submitted + 3); EXPECT_EQ(keyboard.last_submitted_event().key_code, VKEY_LWIN); @@ -923,7 +921,7 @@ TEST_F(KeyboardPassthroughTest, ReleasesHeldKeysAsThemselvesWithoutKeybindings) } TEST_F(KeyboardPassthroughTest, ReleasesTheRemappedHostKeyWhenTheClientDisconnects) { - config::input.keybindings = {{VKEY_LMENU, VKEY_LWIN}}; + config_.edit_startup().input.keybindings = {{VKEY_LMENU, VKEY_LWIN}}; // The press goes down as the remapped host key. press(VKEY_LMENU, MODIFIER_ALT); @@ -938,8 +936,8 @@ TEST_F(KeyboardPassthroughTest, ReleasesTheRemappedHostKeyWhenTheClientDisconnec TEST_F(KeyboardPassthroughTest, ReleasesTheRemappedRightAltForKeyRightaltToKeyWin) { // Mirrors what config parsing installs for the shipped key_rightalt_to_key_win option. - config::input.key_rightalt_to_key_win = true; - config::input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; + config_.edit_startup().input.key_rightalt_to_key_win = true; + config_.edit_startup().input.keybindings = {{VKEY_RMENU, VKEY_LWIN}}; press(VKEY_RMENU, MODIFIER_ALT); EXPECT_EQ(taken(), (std::vector {pressed(VKEY_LWIN)})); diff --git a/tests/unit/test_mouse.cpp b/tests/unit/test_mouse.cpp index e82c83e72..0dd09d698 100644 --- a/tests/unit/test_mouse.cpp +++ b/tests/unit/test_mouse.cpp @@ -104,6 +104,7 @@ namespace { } // namespace struct MouseHIDTest: PlatformTestSuite, testing::WithParamInterface { + config::store_t config_; ///< Configuration owned by this fixture. runtime::infrastructure_t infrastructure_; ///< Scheduler owned by this mouse fixture. void SetUp() override { @@ -131,7 +132,7 @@ TEST_P(MouseHIDTest, MoveInputTest) { util::point_t mouse_delta = GetParam(); BOOST_LOG(tests) << "MoveInputTest:: got param: " << mouse_delta; - platf::input_t input = platf::input(infrastructure_.scheduler()); + platf::input_t input = platf::input(config_.values(), infrastructure_.scheduler()); BOOST_LOG(tests) << "MoveInputTest:: init input"; BOOST_LOG(tests) << "MoveInputTest:: get current mouse loc"; @@ -174,7 +175,7 @@ TEST_P(MouseHIDTest, AbsMoveInputTest) { util::point_t mouse_pos = GetParam(); BOOST_LOG(tests) << "AbsMoveInputTest:: got param: " << mouse_pos; - platf::input_t input = platf::input(infrastructure_.scheduler()); + platf::input_t input = platf::input(config_.values(), infrastructure_.scheduler()); BOOST_LOG(tests) << "AbsMoveInputTest:: init input"; BOOST_LOG(tests) << "AbsMoveInputTest:: get current mouse loc"; diff --git a/tests/unit/test_network.cpp b/tests/unit/test_network.cpp index 3c07fd7e3..0a74c55a0 100644 --- a/tests/unit/test_network.cpp +++ b/tests/unit/test_network.cpp @@ -95,19 +95,7 @@ INSTANTIATE_TEST_SUITE_P( */ class BindAddressTest: public BaseTest { protected: - std::string original_bind_address; - - void SetUp() override { - BaseTest::SetUp(); - // Save the original bind_address config - original_bind_address = config::sunshine.bind_address; - } - - void TearDown() override { - // Restore the original bind_address config - config::sunshine.bind_address = original_bind_address; - BaseTest::TearDown(); - } + config::store_t configuration; ///< Configuration isolated to this fixture. }; /** @@ -115,9 +103,9 @@ protected: */ TEST_F(BindAddressTest, DefaultBehaviorIPv4) { // Clear bind_address to test the default behavior - config::sunshine.bind_address = ""; + configuration.edit_startup().sunshine.bind_address = ""; - const auto bind_addr = net::get_bind_address(net::af_e::IPV4); + const auto bind_addr = net::get_bind_address(configuration.values(), net::af_e::IPV4); ASSERT_EQ(bind_addr, "0.0.0.0"); } @@ -126,9 +114,9 @@ TEST_F(BindAddressTest, DefaultBehaviorIPv4) { */ TEST_F(BindAddressTest, DefaultBehaviorIPv6) { // Clear bind_address to test the default behavior - config::sunshine.bind_address = ""; + configuration.edit_startup().sunshine.bind_address = ""; - const auto bind_addr = net::get_bind_address(net::af_e::BOTH); + const auto bind_addr = net::get_bind_address(configuration.values(), net::af_e::BOTH); ASSERT_EQ(bind_addr, "::"); } @@ -136,57 +124,57 @@ TEST_F(BindAddressTest, DefaultBehaviorIPv6) { * @brief Test that an empty bind address preserves the configured address family. */ TEST_F(BindAddressTest, EmptyAddressPreservesConfiguredFamily) { - config::sunshine.bind_address = ""; + configuration.edit_startup().sunshine.bind_address = ""; - EXPECT_EQ(net::get_effective_address_family(net::af_e::IPV4), net::af_e::IPV4); - EXPECT_EQ(net::get_effective_address_family(net::af_e::BOTH), net::af_e::BOTH); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::IPV4), net::af_e::IPV4); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::BOTH), net::af_e::BOTH); } /** * @brief Test that an explicit IPv4 bind address selects an IPv4 socket. */ TEST_F(BindAddressTest, IPv4AddressSelectsIPv4Family) { - config::sunshine.bind_address = "192.0.2.101"; + configuration.edit_startup().sunshine.bind_address = "192.0.2.101"; - EXPECT_EQ(net::get_effective_address_family(net::af_e::IPV4), net::af_e::IPV4); - EXPECT_EQ(net::get_effective_address_family(net::af_e::BOTH), net::af_e::IPV4); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::IPV4), net::af_e::IPV4); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::BOTH), net::af_e::IPV4); } /** * @brief Test that an explicit IPv6 bind address does not override the configured family. */ TEST_F(BindAddressTest, IPv6AddressPreservesConfiguredFamily) { - config::sunshine.bind_address = "2001:db8::1"; + configuration.edit_startup().sunshine.bind_address = "2001:db8::1"; - EXPECT_EQ(net::get_effective_address_family(net::af_e::IPV4), net::af_e::IPV4); - EXPECT_EQ(net::get_effective_address_family(net::af_e::BOTH), net::af_e::BOTH); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::IPV4), net::af_e::IPV4); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::BOTH), net::af_e::BOTH); } /** * @brief Test that invalid bind addresses preserve the configured family for downstream error reporting. */ TEST_F(BindAddressTest, InvalidAddressPreservesConfiguredFamily) { - config::sunshine.bind_address = "not-an-address"; + configuration.edit_startup().sunshine.bind_address = "not-an-address"; - EXPECT_EQ(net::get_effective_address_family(net::af_e::IPV4), net::af_e::IPV4); - EXPECT_EQ(net::get_effective_address_family(net::af_e::BOTH), net::af_e::BOTH); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::IPV4), net::af_e::IPV4); + EXPECT_EQ(net::get_effective_address_family(configuration.values(), net::af_e::BOTH), net::af_e::BOTH); } /** * @brief Test that bind addresses are formatted for use as URL hosts. */ TEST_F(BindAddressTest, AddressFormatsAsUrlHost) { - config::sunshine.bind_address = ""; - EXPECT_EQ(net::get_bind_address_url_host(), "localhost"); + configuration.edit_startup().sunshine.bind_address = ""; + EXPECT_EQ(net::get_bind_address_url_host(configuration.values()), "localhost"); - config::sunshine.bind_address = "198.51.100.56"; - EXPECT_EQ(net::get_bind_address_url_host(), "198.51.100.56"); + configuration.edit_startup().sunshine.bind_address = "198.51.100.56"; + EXPECT_EQ(net::get_bind_address_url_host(configuration.values()), "198.51.100.56"); - config::sunshine.bind_address = "2001:db8::1"; - EXPECT_EQ(net::get_bind_address_url_host(), "[2001:db8::1]"); + configuration.edit_startup().sunshine.bind_address = "2001:db8::1"; + EXPECT_EQ(net::get_bind_address_url_host(configuration.values()), "[2001:db8::1]"); - config::sunshine.bind_address = "not-an-address"; - EXPECT_EQ(net::get_bind_address_url_host(), "not-an-address"); + configuration.edit_startup().sunshine.bind_address = "not-an-address"; + EXPECT_EQ(net::get_bind_address_url_host(configuration.values()), "not-an-address"); } /** @@ -194,9 +182,9 @@ TEST_F(BindAddressTest, AddressFormatsAsUrlHost) { */ TEST_F(BindAddressTest, ConfiguredIPv4Address) { // Set a specific IPv4 address - config::sunshine.bind_address = "192.168.1.100"; + configuration.edit_startup().sunshine.bind_address = "192.168.1.100"; - const auto bind_addr = net::get_bind_address(net::af_e::IPV4); + const auto bind_addr = net::get_bind_address(configuration.values(), net::af_e::IPV4); ASSERT_EQ(bind_addr, "192.168.1.100"); } @@ -205,9 +193,9 @@ TEST_F(BindAddressTest, ConfiguredIPv4Address) { */ TEST_F(BindAddressTest, ConfiguredIPv6Address) { // Set a specific IPv6 address - config::sunshine.bind_address = "::1"; + configuration.edit_startup().sunshine.bind_address = "::1"; - const auto bind_addr = net::get_bind_address(net::af_e::BOTH); + const auto bind_addr = net::get_bind_address(configuration.values(), net::af_e::BOTH); ASSERT_EQ(bind_addr, "::1"); } @@ -217,9 +205,9 @@ TEST_F(BindAddressTest, ConfiguredIPv6Address) { TEST_F(BindAddressTest, ConfiguredAddressOverridesFamily) { // Set a specific IPv6 address but request IPv4 family // The configured address should still be returned - config::sunshine.bind_address = "2001:db8::1"; + configuration.edit_startup().sunshine.bind_address = "2001:db8::1"; - const auto bind_addr = net::get_bind_address(net::af_e::IPV4); + const auto bind_addr = net::get_bind_address(configuration.values(), net::af_e::IPV4); ASSERT_EQ(bind_addr, "2001:db8::1"); } @@ -228,13 +216,13 @@ TEST_F(BindAddressTest, ConfiguredAddressOverridesFamily) { */ TEST_F(BindAddressTest, LoopbackAddresses) { // Test IPv4 loopback - config::sunshine.bind_address = "127.0.0.1"; - const auto bind_addr_v4 = net::get_bind_address(net::af_e::IPV4); + configuration.edit_startup().sunshine.bind_address = "127.0.0.1"; + const auto bind_addr_v4 = net::get_bind_address(configuration.values(), net::af_e::IPV4); ASSERT_EQ(bind_addr_v4, "127.0.0.1"); // Test IPv6 loopback - config::sunshine.bind_address = "::1"; - const auto bind_addr_v6 = net::get_bind_address(net::af_e::BOTH); + configuration.edit_startup().sunshine.bind_address = "::1"; + const auto bind_addr_v6 = net::get_bind_address(configuration.values(), net::af_e::BOTH); ASSERT_EQ(bind_addr_v6, "::1"); } @@ -243,13 +231,13 @@ TEST_F(BindAddressTest, LoopbackAddresses) { */ TEST_F(BindAddressTest, LinkLocalAddresses) { // Test IPv4 link-local - config::sunshine.bind_address = "169.254.1.1"; - const auto bind_addr_v4 = net::get_bind_address(net::af_e::IPV4); + configuration.edit_startup().sunshine.bind_address = "169.254.1.1"; + const auto bind_addr_v4 = net::get_bind_address(configuration.values(), net::af_e::IPV4); ASSERT_EQ(bind_addr_v4, "169.254.1.1"); // Test IPv6 link-local - config::sunshine.bind_address = "fe80::1"; - const auto bind_addr_v6 = net::get_bind_address(net::af_e::BOTH); + configuration.edit_startup().sunshine.bind_address = "fe80::1"; + const auto bind_addr_v6 = net::get_bind_address(configuration.values(), net::af_e::BOTH); ASSERT_EQ(bind_addr_v6, "fe80::1"); } diff --git a/tests/unit/test_nvhttp_client_auth.cpp b/tests/unit/test_nvhttp_client_auth.cpp index ec4ca5d37..7b731cf3e 100644 --- a/tests/unit/test_nvhttp_client_auth.cpp +++ b/tests/unit/test_nvhttp_client_auth.cpp @@ -29,12 +29,12 @@ protected: */ void SetUp() override { BaseTest::SetUp(); - original_state_file = config::nvhttp.file_state; - original_fresh_state = config::sunshine.flags[config::flag::FRESH_STATE]; + original_state_file = configuration.edit_startup().nvhttp.file_state; + original_fresh_state = configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE]; state_file = fs::path {SUNSHINE_TEST_BIN_DIR} / "client_authorization_state.json"; - config::nvhttp.file_state = state_file.string(); - config::sunshine.flags[config::flag::FRESH_STATE] = false; + configuration.edit_startup().nvhttp.file_state = state_file.string(); + configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE] = false; gamestream.test_reset_client_state(); std::error_code remove_error; @@ -49,8 +49,8 @@ protected: std::error_code remove_error; fs::remove(state_file, remove_error); - config::nvhttp.file_state = original_state_file; - config::sunshine.flags[config::flag::FRESH_STATE] = original_fresh_state; + configuration.edit_startup().nvhttp.file_state = original_state_file; + configuration.edit_startup().sunshine.flags[config::flag::FRESH_STATE] = original_fresh_state; BaseTest::TearDown(); } diff --git a/tests/unit/test_nvprefs_configuration.cpp b/tests/unit/test_nvprefs_configuration.cpp new file mode 100644 index 000000000..ed4794f16 --- /dev/null +++ b/tests/unit/test_nvprefs_configuration.cpp @@ -0,0 +1,24 @@ +/** + * @file tests/unit/test_nvprefs_configuration.cpp + * @brief Test per-host NVIDIA profile policy. + */ +#include "../tests_common.h" +#ifdef _WIN32 + #include + +TEST(NvPrefsConfigurationTest, IndependentHostsUseOnlyTheirOwnProfilePolicy) { + config::settings_t first; + first.video.nv_opengl_vulkan_on_dxgi = false; + first.video.nv_sunshine_high_power_mode = true; + config::settings_t second; + second.video.nv_opengl_vulkan_on_dxgi = true; + second.video.nv_sunshine_high_power_mode = false; + const auto first_policy = nvprefs::get_nvprefs_options(first); + const auto second_policy = nvprefs::get_nvprefs_options(second); + EXPECT_FALSE(first_policy.opengl_vulkan_on_dxgi); + EXPECT_TRUE(first_policy.sunshine_high_power_mode); + EXPECT_TRUE(second_policy.opengl_vulkan_on_dxgi); + EXPECT_FALSE(second_policy.sunshine_high_power_mode); + EXPECT_FALSE(nvprefs::get_nvprefs_options(first).opengl_vulkan_on_dxgi); +} +#endif diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 7bf6770d5..56e0d0039 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -61,7 +61,8 @@ protected: mutable int time_offset {}; ///< Timestamp offset local to this fixture. fs::path test_dir; - proc::proc_t process; ///< Process and configuration cache owned by each fixture. + config::settings_t settings; ///< Configuration owned by each process fixture. + proc::proc_t process {settings}; ///< Process and configuration cache owned by each fixture. }; // Tests for check_valid_png function @@ -344,7 +345,8 @@ protected: mutable int time_offset {}; ///< Timestamp offset local to this fixture. fs::path test_dir; - proc::proc_t process; ///< Process and configuration cache owned by each fixture. + config::settings_t settings; ///< Configuration owned by each process fixture. + proc::proc_t process {settings}; ///< Process and configuration cache owned by each fixture. }; /** @@ -352,7 +354,7 @@ protected: */ class ProcessUpdateTest: public ProcessRefreshTest { // NOSONAR(cpp:S3656): protected members are intentional for test fixture subclassing protected: - proc::proc_t saved_process; + proc::proc_t saved_process {settings}; void SetUp() override { ProcessRefreshTest::SetUp(); @@ -366,7 +368,7 @@ protected: ctx.id = "42"; apps_initial.push_back(std::move(ctx)); - proc::proc_t target(std::move(env), std::move(apps_initial)); + proc::proc_t target(settings, std::move(env), std::move(apps_initial)); process = std::move(target); auto launch_session = std::make_shared(); @@ -400,7 +402,7 @@ protected: ctx_new.name = "NewApp"; ctx_new.id = "99"; apps_new.push_back(std::move(ctx_new)); - return proc::proc_t(std::move(env2), std::move(apps_new)); + return proc::proc_t(settings, std::move(env2), std::move(apps_new)); } }; @@ -413,7 +415,7 @@ TEST_F(ProcessRefreshTest, UpdateAppsAndEnv_UpdatesAppsList) { ctx_a.id = "100"; apps_initial.push_back(std::move(ctx_a)); - proc::proc_t target(std::move(env), std::move(apps_initial)); + proc::proc_t target(settings, std::move(env), std::move(apps_initial)); ASSERT_EQ(target.get_apps().size(), 1u); EXPECT_EQ(target.get_apps()[0].name, "AppA"); @@ -429,7 +431,7 @@ TEST_F(ProcessRefreshTest, UpdateAppsAndEnv_UpdatesAppsList) { ctx_c.id = "300"; apps_new.push_back(std::move(ctx_c)); - proc::proc_t source(std::move(env2), std::move(apps_new)); + proc::proc_t source(settings, std::move(env2), std::move(apps_new)); // Act target.update_apps_and_env(std::move(source)); @@ -469,7 +471,7 @@ TEST_F(ProcessRefreshTest, Refresh_ParsesFileOnFirstCall) { // Save and clear the fixture-owned process manager auto saved = std::move(process); - process = proc::proc_t {}; + process = proc::proc_t {settings}; ASSERT_TRUE(process.get_apps().empty()); @@ -490,7 +492,7 @@ TEST_F(ProcessRefreshTest, Refresh_SkipsUnchangedFile) { writeAppsJson(apps_file, {"OriginalApp"}); auto saved = std::move(process); - process = proc::proc_t {}; + process = proc::proc_t {settings}; // First refresh — should parse process.refresh(apps_file.string()); @@ -513,7 +515,7 @@ TEST_F(ProcessRefreshTest, Refresh_ReparseAfterFileModified) { writeAppsJson(apps_file, {"BeforeEdit"}); auto saved = std::move(process); - process = proc::proc_t {}; + process = proc::proc_t {settings}; process.refresh(apps_file.string()); ASSERT_EQ(process.get_apps().size(), 1u); @@ -535,7 +537,7 @@ TEST_F(ProcessRefreshTest, Refresh_ReparseAfterFileMtimeDecreased) { writeAppsJson(apps_file, {"Initial"}); auto saved = std::move(process); - process = proc::proc_t {}; + process = proc::proc_t {settings}; process.refresh(apps_file.string()); ASSERT_EQ(process.get_apps().size(), 1u); @@ -562,7 +564,7 @@ TEST_F(ProcessRefreshTest, Refresh_PreservesRunningAppDuringReparse) { writeAppsJson(apps_file, {"Desktop"}); auto saved = std::move(process); - process = proc::proc_t {}; + process = proc::proc_t {settings}; // Initial parse process.refresh(apps_file.string()); @@ -632,8 +634,8 @@ TEST_F(ProcessRefreshTest, FileTimeType_DefaultValueComparison) { TEST_F(ProcessRefreshTest, IndependentOwnersParseAnUnchangedFile) { const auto apps_file = test_dir / "independent.json"; writeAppsJson(apps_file, {"Shared configuration"}); - proc::proc_t first; - proc::proc_t second; + proc::proc_t first {settings}; + proc::proc_t second {settings}; first.refresh(apps_file.string()); second.refresh(apps_file.string()); ASSERT_EQ(first.get_apps().size(), 1u); @@ -659,7 +661,7 @@ TEST_F(ProcessUpdateTest, MoveConstructionTransfersActiveApplication) { * @brief Move assignment preserves active state, including when assigning an owner to itself. */ TEST_F(ProcessUpdateTest, MoveAssignmentTransfersAndSelfAssignmentPreservesApplication) { - proc::proc_t destination; + proc::proc_t destination {settings}; destination = std::move(process); EXPECT_EQ(destination.running(), 42); EXPECT_EQ(process.running(), 0); @@ -669,3 +671,27 @@ TEST_F(ProcessUpdateTest, MoveAssignmentTransfersAndSelfAssignmentPreservesAppli destination.terminate(); EXPECT_EQ(destination.running(), 0); } + +/** + * @brief Application parsing reads preparation commands from the supplied configuration owner. + */ +TEST_F(ProcessRefreshTest, IndependentConfigurationOwnersSupplyTheirOwnPreparationCommands) { + const auto file = test_dir / "owned_configuration.json"; + writeAppsJson(file, {"Configured application"}); + config::settings_t first_settings; + config::settings_t second_settings; + first_settings.sunshine.prep_cmds.emplace_back(std::string {"first"}, false); + second_settings.sunshine.prep_cmds.emplace_back(std::string {"second"}, true); + proc::proc_t first {first_settings}; + proc::proc_t second {second_settings}; + first.refresh(file.string()); + second.refresh(file.string()); + ASSERT_EQ(first.get_apps().size(), 1u); + ASSERT_EQ(second.get_apps().size(), 1u); + ASSERT_EQ(first.get_apps().front().prep_cmds.size(), 1u); + ASSERT_EQ(second.get_apps().front().prep_cmds.size(), 1u); + EXPECT_EQ(first.get_apps().front().prep_cmds.front().do_cmd, "first"); + EXPECT_FALSE(first.get_apps().front().prep_cmds.front().elevated); + EXPECT_EQ(second.get_apps().front().prep_cmds.front().do_cmd, "second"); + EXPECT_TRUE(second.get_apps().front().prep_cmds.front().elevated); +} diff --git a/tests/unit/test_system_tray.cpp b/tests/unit/test_system_tray.cpp index 1c779613a..e2b8213ef 100644 --- a/tests/unit/test_system_tray.cpp +++ b/tests/unit/test_system_tray.cpp @@ -28,6 +28,8 @@ // local includes #include + #include + #include #include #include @@ -251,18 +253,17 @@ namespace { */ class SystemTrayTest: public testing::Test { protected: + config::store_t configuration; ///< Startup settings owned by this tray fixture. + /** * @brief Reset any tray state left by an earlier test. */ void SetUp() override { #ifdef _WIN32 - original_gamepad_driver_ = config::input.gamepad_driver; - config::input.gamepad_driver = config::GAMEPAD_DRIVER_ALL; + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_ALL; #elif defined(__APPLE__) - original_controller_ = config::input.controller; - original_gamepad_driver_ = config::input.gamepad_driver; - config::input.controller = true; - config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; + configuration.edit_startup().input.controller = true; + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; #endif EXPECT_EQ(system_tray::end_tray(), 0); #ifndef _WIN32 @@ -288,12 +289,6 @@ protected: std::ignore = tray_restore_mouse_position(); #endif system_tray::reset_tray_data_for_testing(); - #ifdef _WIN32 - config::input.gamepad_driver = std::move(original_gamepad_driver_); - #elif defined(__APPLE__) - config::input.controller = original_controller_; - config::input.gamepad_driver = std::move(original_gamepad_driver_); - #endif } /** @@ -310,16 +305,39 @@ protected: #endif return result; } - -private: - #ifdef _WIN32 - std::string original_gamepad_driver_; ///< Original gamepad driver preference restored after each test. - #elif defined(__APPLE__) - bool original_controller_ = false; ///< Original gamepad input setting restored after each test. - std::string original_gamepad_driver_; ///< Original gamepad backend setting restored after each test. - #endif }; +TEST_F(SystemTrayTest, BindsMenuCallbacksAndClearsDependenciesOnDestruction) { + lifetime::controller_t lifetime; + display_device::manager_t displays; + const auto &tray_data = system_tray::tray_data_for_testing(); + const auto verify_context = [&tray_data](void *expected) { + for (auto item = tray_data.menu; item->text; ++item) { + EXPECT_EQ(item->context, expected); + if (item->submenu) { + for (auto child = item->submenu; child->text; ++child) { + if (child->cb) { + EXPECT_EQ(child->context, expected); + } + } + } + } + }; + { + system_tray::application_binding_t binding {configuration.values(), lifetime, displays}; + EXPECT_EQ(&binding.settings, &configuration.values()); + EXPECT_EQ(&binding.lifetime, &lifetime); + EXPECT_EQ(&binding.displays, &displays); + verify_context(&binding); + #if defined(_WIN32) || defined(__APPLE__) + lvh::LicenseStatus license; + system_tray::update_tray_virtualhid_license(configuration.values(), license, false); + verify_context(&binding); + #endif + } + verify_context(nullptr); +} + TEST_F(SystemTrayTest, UpdatesAreIgnoredBeforeInitialization) { EXPECT_FALSE(system_tray::tray_initialized_for_testing()); EXPECT_EQ(system_tray::process_tray_events(), 1); @@ -370,7 +388,7 @@ TEST_F(SystemTrayTest, ResolvesDevelopmentTrayIconsFromExecutableDirectory) { } TEST_F(SystemTrayTest, PreparesVirtualHidMenuFromCurrentLicenseStatus) { - system_tray::prepare_tray_virtualhid_license(); + system_tray::prepare_tray_virtualhid_license(configuration.values()); const auto &tray_data = system_tray::tray_data_for_testing(); ASSERT_NE(tray_data.menu[2].submenu, nullptr); @@ -387,7 +405,7 @@ TEST_F(SystemTrayTest, PreparesLicensedVirtualHidMenuBeforeInitialization) { license.activation_usage = 1; license.activation_limit = 5; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); const auto *license_menu = tray_data.menu[2].submenu; @@ -408,7 +426,7 @@ TEST_F(SystemTrayTest, PreparesLicensedVirtualHidMenuBeforeInitialization) { license.customer_email.clear(); license.activation_usage = 0; license.activation_limit = 0; - system_tray::update_tray_virtualhid_license(license, false); + system_tray::update_tray_virtualhid_license(configuration.values(), license, false); EXPECT_STREQ(license_menu[1].text, "This machine is activated"); EXPECT_STREQ(license_menu[2].text, "Customer: Not reported"); @@ -419,9 +437,9 @@ TEST_F(SystemTrayTest, PromptsForUnsetGamepadDriverEvenWhenLicensed) { lvh::LicenseStatus license; license.service_available = true; license.state = lvh::LicenseState::licensed; - config::input.gamepad_driver.clear(); + configuration.edit_startup().input.gamepad_driver.clear(); - system_tray::update_tray_virtualhid_license(license, false); + system_tray::update_tray_virtualhid_license(configuration.values(), license, false); const auto &tray_data = system_tray::tray_data_for_testing(); EXPECT_STREQ(tray_data.notification_title, "Choose a Gamepad Backend"); @@ -435,7 +453,7 @@ TEST_F(SystemTrayTest, PromptsForUnsetGamepadDriverEvenWhenLicensed) { TEST_F(SystemTrayTest, NotifiesWhenVirtualHidDriverIsUnsupported) { const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MINIMUM_VERSION); - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address const auto &tray_data = system_tray::tray_data_for_testing(); const auto expected_notification = std::format( @@ -455,7 +473,7 @@ TEST_F(SystemTrayTest, PreservesExistingNotificationWhenVirtualHidDriverIsUsable lvh::LicenseStatus license; license.service_available = true; license.state = lvh::LicenseState::unlicensed; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); const auto *notification_title = tray_data.notification_title; @@ -463,12 +481,12 @@ TEST_F(SystemTrayTest, PreservesExistingNotificationWhenVirtualHidDriverIsUsable const auto notification_callback = tray_data.notification_cb; const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MINIMUM_VERSION); - system_tray::update_tray_virtualhid_driver(false, "", false, supported_versions); + system_tray::update_tray_virtualhid_driver(configuration.values(), false, "", false, supported_versions); EXPECT_EQ(tray_data.notification_title, notification_title); EXPECT_EQ(tray_data.notification_text, notification_text); EXPECT_EQ(tray_data.notification_cb, notification_callback); - system_tray::update_tray_virtualhid_driver(true, "0.0.1", true, supported_versions); + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "0.0.1", true, supported_versions); EXPECT_EQ(tray_data.notification_title, notification_title); EXPECT_EQ(tray_data.notification_text, notification_text); EXPECT_EQ(tray_data.notification_cb, notification_callback); @@ -478,9 +496,9 @@ TEST_F(SystemTrayTest, VigembusSelectionSuppressesVirtualHidNotifications) { lvh::LicenseStatus license; license.service_available = true; license.state = lvh::LicenseState::invalid; - config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIGEMBUS; + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_VIGEMBUS; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); EXPECT_EQ(tray_data.notification_title, nullptr); @@ -488,7 +506,7 @@ TEST_F(SystemTrayTest, VigembusSelectionSuppressesVirtualHidNotifications) { EXPECT_EQ(tray_data.notification_cb, nullptr); const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MINIMUM_VERSION); - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not IP addresses + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not IP addresses EXPECT_EQ(tray_data.notification_title, nullptr); EXPECT_EQ(tray_data.notification_text, nullptr); EXPECT_EQ(tray_data.notification_cb, nullptr); @@ -498,9 +516,9 @@ TEST_F(SystemTrayTest, NoneSelectionSuppressesWindowsVirtualHidNotifications) { lvh::LicenseStatus license; license.service_available = false; license.state = lvh::LicenseState::unavailable; - config::input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); EXPECT_EQ(tray_data.notification_title, nullptr); @@ -509,7 +527,7 @@ TEST_F(SystemTrayTest, NoneSelectionSuppressesWindowsVirtualHidNotifications) { EXPECT_STREQ(tray_data.menu[2].submenu[0].text, "Status: Unavailable"); const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MINIMUM_VERSION); - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not IP addresses + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338.54", false, supported_versions); // NOSONAR(cpp:S1313): not IP addresses EXPECT_EQ(tray_data.notification_title, nullptr); } @@ -526,7 +544,7 @@ TEST_P(UnlicensedVirtualHidTrayTest, PreparesMenuAndStartupNotification) { license.service_available = service_available; license.state = state; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); const auto *license_menu = tray_data.menu[2].submenu; @@ -547,7 +565,7 @@ TEST_P(UnlicensedVirtualHidTrayTest, PreparesMenuAndStartupNotification) { system_tray::resolve_tray_icon_paths_for_testing(); EXPECT_STREQ(tray_data.notification_icon, tray_data.allIconPaths[4]); - system_tray::update_tray_virtualhid_license(license, false); + system_tray::update_tray_virtualhid_license(configuration.values(), license, false); EXPECT_EQ(tray_data.notification_title, nullptr); EXPECT_EQ(tray_data.notification_text, nullptr); EXPECT_EQ(tray_data.notification_cb, nullptr); @@ -569,7 +587,7 @@ INSTANTIATE_TEST_SUITE_P( #ifdef __APPLE__ TEST_F(SystemTrayTest, NotifiesWhenMacBrokerVersionIsUnsupported) { const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MACOS_MINIMUM_VERSION); - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address const auto &tray_data = system_tray::tray_data_for_testing(); const auto expected_notification = std::format( @@ -584,15 +602,15 @@ TEST_F(SystemTrayTest, NotifiesWhenMacBrokerVersionIsUnsupported) { TEST_F(SystemTrayTest, MacBrokerVersionNotificationRespectsDisabledGamepads) { const auto supported_versions = std::format(">= {}", LIBVIRTUALHID_MACOS_MINIMUM_VERSION); - config::input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address const auto &tray_data = system_tray::tray_data_for_testing(); EXPECT_EQ(tray_data.notification_title, nullptr); EXPECT_EQ(tray_data.notification_text, nullptr); - config::input.gamepad_driver.clear(); - system_tray::update_tray_virtualhid_driver(true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address + configuration.edit_startup().input.gamepad_driver.clear(); + system_tray::update_tray_virtualhid_driver(configuration.values(), true, "2026.829.2338", false, supported_versions); // NOSONAR(cpp:S1313): not an IP address EXPECT_STREQ(tray_data.notification_title, "Update Virtual HID Broker"); } @@ -605,7 +623,7 @@ TEST_F(SystemTrayTest, ShowsLicensedMacBrokerDetailsBeforeInitialization) { license.activation_usage = 1; license.activation_limit = 5; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); ASSERT_EQ(tray_data.iconPathCount, 5); @@ -629,7 +647,7 @@ TEST_F(SystemTrayTest, ShowsMacBrokerLicenseAndAvailabilityWithOptionalStartupNo license.service_available = true; license.state = lvh::LicenseState::unlicensed; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); const auto &tray_data = system_tray::tray_data_for_testing(); const auto *menu = tray_data.menu[2].submenu; @@ -645,7 +663,7 @@ TEST_F(SystemTrayTest, ShowsMacBrokerLicenseAndAvailabilityWithOptionalStartupNo license.service_available = false; license.state = lvh::LicenseState::unavailable; - system_tray::update_tray_virtualhid_license(license, true); + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); EXPECT_STREQ(menu[0].text, "Status: Unavailable"); EXPECT_STREQ(menu[3].text, "License service: Unavailable"); EXPECT_STREQ(tray_data.notification_title, "Virtual HID Broker Is Unavailable"); @@ -653,19 +671,19 @@ TEST_F(SystemTrayTest, ShowsMacBrokerLicenseAndAvailabilityWithOptionalStartupNo EXPECT_STREQ(tray_data.notification_icon, tray_data.allIconPaths[4]); EXPECT_NE(tray_data.notification_cb, nullptr); - system_tray::update_tray_virtualhid_license(license, false); + system_tray::update_tray_virtualhid_license(configuration.values(), license, false); EXPECT_EQ(tray_data.notification_title, nullptr); EXPECT_EQ(tray_data.notification_cb, nullptr); - config::input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; - system_tray::update_tray_virtualhid_license(license, true); + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); EXPECT_EQ(tray_data.notification_title, nullptr); EXPECT_EQ(tray_data.notification_cb, nullptr); EXPECT_STREQ(menu[0].text, "Status: Unavailable"); - config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; - config::input.controller = false; - system_tray::update_tray_virtualhid_license(license, true); + configuration.edit_startup().input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; + configuration.edit_startup().input.controller = false; + system_tray::update_tray_virtualhid_license(configuration.values(), license, true); EXPECT_EQ(tray_data.notification_title, nullptr); } #endif diff --git a/tests/unit/test_video.cpp b/tests/unit/test_video.cpp index 5e4098488..9568ff378 100644 --- a/tests/unit/test_video.cpp +++ b/tests/unit/test_video.cpp @@ -69,9 +69,11 @@ TEST(VideoFormatMappingTest, MapsSupportedPixelFormatsAndRejectsUnsupportedOnes) } TEST(VideoServiceOwnershipTest, SnapshotChangesDoNotMutateServiceStateAndUnprobedCaptureStopsItsSession) { + const config::store_t config; runtime::infrastructure_t infrastructure; display_device::manager_t displays; platf::runtime_t platform { + config.values(), infrastructure.mailbox(), infrastructure.scheduler(), infrastructure.lifetime(), @@ -81,8 +83,8 @@ TEST(VideoServiceOwnershipTest, SnapshotChangesDoNotMutateServiceStateAndUnprobe infrastructure.preferences() #endif }; - video::service_t first {infrastructure.mailbox(), infrastructure.cursor(), displays, platform}; - video::service_t second {std::make_shared(), infrastructure.cursor(), displays, platform}; + video::service_t first {config.values(), infrastructure.mailbox(), infrastructure.cursor(), displays, platform}; + video::service_t second {config.values(), std::make_shared(), infrastructure.cursor(), displays, platform}; auto snapshot = first.capabilities(); snapshot.active_hevc_mode = 5; snapshot.yuv444.fill(true); @@ -97,24 +99,32 @@ TEST(VideoServiceOwnershipTest, SnapshotChangesDoNotMutateServiceStateAndUnprobe } TEST(VideoEncoderOwnershipTest, DescriptorCopiesKeepProbeCapabilitiesIndependent) { - auto first = video::software; - auto second = video::software; + const config::store_t config; + auto prototype = video::make_software(config.values()); + auto first = prototype; + auto second = prototype; first.h264[video::encoder_t::PASSED] = true; first.hevc[video::encoder_t::DYNAMIC_RANGE] = true; EXPECT_FALSE(second.h264[video::encoder_t::PASSED]); EXPECT_FALSE(second.hevc[video::encoder_t::DYNAMIC_RANGE]); - EXPECT_FALSE(video::software.h264[video::encoder_t::PASSED]); + EXPECT_FALSE(prototype.h264[video::encoder_t::PASSED]); EXPECT_EQ(first.platform_formats, second.platform_formats); } -struct EncoderTest: PlatformTestSuite, testing::WithParamInterface { +/** + * @brief Factory constructing an encoder descriptor for one immutable host configuration. + */ +using EncoderFactory = video::encoder_t (*)(const config::settings_t &); + +struct EncoderTest: PlatformTestSuite, testing::WithParamInterface { + config::store_t config_; ///< Immutable encoder fixture configuration. runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this encoder fixture. display_device::manager_t displays_; ///< Display configuration owner for encoder validation. - video::service_t videos_ {infrastructure_.mailbox(), infrastructure_.cursor(), displays_, platform()}; ///< Fixture-owned video service. + video::service_t videos_ {config_.values(), infrastructure_.mailbox(), infrastructure_.cursor(), displays_, platform()}; ///< Fixture-owned video service. void SetUp() override { BaseTest::SetUp(); - auto encoder = *GetParam(); + auto encoder = GetParam()(config_.values()); if (!videos_.validate_encoder(encoder, false)) { // Encoder failed validation, // if it's software - fail, otherwise skip @@ -132,43 +142,46 @@ INSTANTIATE_TEST_SUITE_P( EncoderTest, testing::Values( #if !defined(__APPLE__) - &video::nvenc, + &video::make_nvenc, #endif #ifdef _WIN32 - &video::amdvce, - &video::quicksync, + &video::make_amdvce, + &video::make_quicksync, #endif #if defined(__linux__) || defined(__FreeBSD__) - &video::vaapi, + &video::make_vaapi, #endif #ifdef __APPLE__ - &video::videotoolbox, + &video::make_videotoolbox, #endif - &video::software + &video::make_software ), [](const auto &info) { - return std::string(info.param->name); + const config::store_t config; + return std::string(info.param(config.values()).name); } ); #if !defined(_WIN32) && !defined(__APPLE__) TEST(NvencAvcodecOptionsTest, UsesVersionStablePresetAndSpatialAqNames) { + const config::store_t config; + const auto encoder = video::make_nvenc(config.values()); const std::array codecs { - &video::nvenc.av1, - &video::nvenc.hevc, - &video::nvenc.h264, + &encoder.av1, + &encoder.hevc, + &encoder.h264, }; for (const auto *codec : codecs) { const auto preset = std::ranges::find(codec->common_options, "preset"sv, &video::encoder_t::option_t::name); ASSERT_NE(codec->common_options.end(), preset); - ASSERT_TRUE(std::holds_alternative(preset->value)); - EXPECT_EQ(&config::video.nv_legacy.preset, std::get(preset->value)); + ASSERT_TRUE(std::holds_alternative(preset->value)); + EXPECT_EQ(&config.values().video.nv_legacy.preset, std::get(preset->value)); const auto spatial_aq = std::ranges::find(codec->common_options, "spatial-aq"sv, &video::encoder_t::option_t::name); ASSERT_NE(codec->common_options.end(), spatial_aq); - ASSERT_TRUE(std::holds_alternative(spatial_aq->value)); - EXPECT_EQ(&config::video.nv_legacy.spatial_aq, std::get(spatial_aq->value)); + ASSERT_TRUE(std::holds_alternative(spatial_aq->value)); + EXPECT_EQ(&config.values().video.nv_legacy.spatial_aq, std::get(spatial_aq->value)); EXPECT_EQ( codec->common_options.end(), @@ -264,20 +277,26 @@ INSTANTIATE_TEST_SUITE_P( #ifdef _WIN32 TEST(AmfH264OptionsTest, CoderUsesConfiguredValue) { - const auto coder_option = std::ranges::find(video::amdvce.h264.common_options, "coder"sv, &video::encoder_t::option_t::name); + const config::store_t config; + const auto encoder = video::make_amdvce(config.values()); + const auto coder_option = std::ranges::find(encoder.h264.common_options, "coder"sv, &video::encoder_t::option_t::name); - ASSERT_NE(video::amdvce.h264.common_options.end(), coder_option); - ASSERT_TRUE(std::holds_alternative(coder_option->value)); - EXPECT_EQ(&config::video.amd.amd_coder, std::get(coder_option->value)); + ASSERT_NE(encoder.h264.common_options.end(), coder_option); + ASSERT_TRUE(std::holds_alternative(coder_option->value)); + EXPECT_EQ(&config.values().video.amd.amd_coder, std::get(coder_option->value)); } /** * @brief Parameterized coverage for the AMF maximum access-unit-size option mappings. */ -struct AmfMaxAuSizeOptionsTest: testing::TestWithParam> {}; +struct AmfMaxAuSizeOptionsTest: testing::TestWithParam> {}; TEST_P(AmfMaxAuSizeOptionsTest, UsesConfiguredValueForSupportedCodecsOnly) { - const auto &[codec, supported] = GetParam(); + const auto &[index, supported] = GetParam(); + const config::store_t config; + const auto encoder = video::make_amdvce(config.values()); + const auto *codec = index == 0 ? &encoder.h264 : index == 1 ? &encoder.hevc : + &encoder.av1; const auto option = std::ranges::find(codec->common_options, "max_au_size"sv, &video::encoder_t::option_t::name); if (!supported) { @@ -286,17 +305,17 @@ TEST_P(AmfMaxAuSizeOptionsTest, UsesConfiguredValueForSupportedCodecsOnly) { } ASSERT_NE(codec->common_options.end(), option); - ASSERT_TRUE(std::holds_alternative *>(option->value)); - EXPECT_EQ(&config::video.amd.amd_max_au_size, std::get *>(option->value)); + ASSERT_TRUE(std::holds_alternative *>(option->value)); + EXPECT_EQ(&config.values().video.amd.amd_max_au_size, std::get *>(option->value)); } INSTANTIATE_TEST_SUITE_P( AmfCodecOptions, AmfMaxAuSizeOptionsTest, testing::Values( - std::make_tuple(&video::amdvce.h264, true), - std::make_tuple(&video::amdvce.hevc, true), - std::make_tuple(&video::amdvce.av1, false) + std::make_tuple(0, true), + std::make_tuple(1, true), + std::make_tuple(2, false) ) ); #endif @@ -309,35 +328,18 @@ using AmfMaxAuSizeConfigParam = std::tuple> struct AmfMaxAuSizeConfigTest: BaseTest, testing::WithParamInterface { void SetUp() override { BaseTest::SetUp(); - config::video.amd.amd_max_au_size.reset(); - config::stream.file_apps = SUNSHINE_SOURCE_DIR "/tests/unit/test_video.cpp"; + config_.edit_startup().video.amd.amd_max_au_size.reset(); + config_.edit_startup().stream.file_apps = SUNSHINE_SOURCE_DIR "/tests/unit/test_video.cpp"; } - void TearDown() override { - config::video = original_video; - config::audio = original_audio; - config::stream = original_stream; - config::nvhttp = original_nvhttp; - config::input = original_input; - config::sunshine = original_sunshine; - config::modified_config_settings = original_modified_config_settings; - BaseTest::TearDown(); - } - - config::video_t original_video {config::video}; ///< Video configuration restored after each parameterized test. - config::audio_t original_audio {config::audio}; ///< Audio configuration restored after each parameterized test. - config::stream_t original_stream {config::stream}; ///< Stream configuration restored after each parameterized test. - config::nvhttp_t original_nvhttp {config::nvhttp}; ///< HTTP configuration restored after each parameterized test. - config::input_t original_input {config::input}; ///< Input configuration restored after each parameterized test. - config::sunshine_t original_sunshine {config::sunshine}; ///< Core configuration restored after each parameterized test. - decltype(config::modified_config_settings) original_modified_config_settings {config::modified_config_settings}; ///< Modified settings restored after each parameterized test. + config::store_t config_; ///< Configuration isolated to this parser test. }; TEST_P(AmfMaxAuSizeConfigTest, AcceptsOnlyFfmpegSupportedRange) { const auto &[setting, expected] = GetParam(); - config::apply_config_for_test(setting); + config_.apply_config_for_test(setting); - EXPECT_EQ(expected, config::video.amd.amd_max_au_size); + EXPECT_EQ(expected, config_.edit_startup().video.amd.amd_max_au_size); } INSTANTIATE_TEST_SUITE_P( @@ -440,7 +442,7 @@ TEST(SoftwareEncoderConversion, Bgr0AndNv12) { frame->height = h; frame->format = AV_PIX_FMT_YUV420P; - video::avcodec_software_encode_device_t device; + video::avcodec_software_encode_device_t device {2}; ASSERT_EQ(device.init(w, h, frame, AV_PIX_FMT_YUV420P, false), 0); // set_frame() takes ownership of the frame; the device frees it on destruction. ASSERT_EQ(device.set_frame(frame, nullptr), 0);