9#include <boost/algorithm/string.hpp>
10#include <display_device/audio_context_interface.h>
11#include <display_device/file_settings_persistence.h>
12#include <display_device/json.h>
13#include <display_device/retry_scheduler.h>
14#include <display_device/settings_manager_interface.h>
25namespace display_device {
27 constexpr std::chrono::milliseconds DEFAULT_RETRY_INTERVAL {5000};
34 std::chrono::milliseconds config_revert_delay {0};
35 std::unique_ptr<RetryScheduler<SettingsManagerInterface>> sm_instance {
nullptr};
45 class sunshine_audio_context_t:
public AudioContextInterface {
47 [[nodiscard]]
bool capture()
override {
48 return context_scheduler.execute([](
auto &audio_context) {
50 audio_context = boost::none;
51 audio_context = audio_context_t {};
58 [[nodiscard]]
bool isCaptured()
const override {
59 return context_scheduler.execute([](
const auto &audio_context) {
63 return !audio_context->released;
71 context_scheduler.schedule([](
auto &audio_context,
auto &stop_token) {
73 audio_context->released =
true;
75 const auto *audio_ctx_ptr = audio_context->audio_ctx_ref.get();
76 if (audio_ctx_ptr && !audio::is_audio_ctx_sink_available(*audio_ctx_ptr) && audio_context->retry_counter > 0) {
80 --audio_context->retry_counter;
85 audio_context = boost::none;
86 stop_token.requestStop();
88 SchedulerOptions {.m_sleep_durations = {2s}});
92 struct audio_context_t {
102 bool released {
false};
107 int retry_counter {15};
110 RetryScheduler<boost::optional<audio_context_t>> context_scheduler {std::make_unique<boost::optional<audio_context_t>>(boost::none)};
119 unsigned int stou(
const std::string &value) {
120 unsigned long result {std::stoul(value)};
121 if (result > std::numeric_limits<unsigned int>::max()) {
122 throw std::out_of_range(
"stou");
145 bool parse_resolution_string(
const std::string &input, std::optional<Resolution> &output) {
146 const std::string trimmed_input {boost::algorithm::trim_copy(input)};
147 const std::regex resolution_regex {R
"(^(\d+)x(\d+)$)"};
149 if (std::smatch match; std::regex_match(trimmed_input, match, resolution_regex)) {
151 output = Resolution {
152 stou(match[1].str()),
156 }
catch (
const std::out_of_range &) {
157 BOOST_LOG(error) <<
"Failed to parse resolution string " << trimmed_input <<
" (number out of range).";
158 }
catch (
const std::exception &err) {
159 BOOST_LOG(error) <<
"Failed to parse resolution string " << trimmed_input <<
":\n"
163 if (trimmed_input.empty()) {
164 output = std::nullopt;
168 BOOST_LOG(error) <<
"Failed to parse resolution string " << trimmed_input << R
"(. It must match a "1920x1080" pattern!)";
193 bool parse_refresh_rate_string(
const std::string &input, std::optional<FloatingPoint> &output,
const bool allow_decimal_point =
true) {
194 static const auto is_zero {[](
const auto &character) {
195 return character ==
'0';
197 const std::string trimmed_input {boost::algorithm::trim_copy(input)};
198 const std::regex refresh_rate_regex {allow_decimal_point ? R
"(^(\d+)(?:\.(\d+))?$)" : R"(^(\d+)$)"};
200 if (std::smatch match; std::regex_match(trimmed_input, match, refresh_rate_regex)) {
203 std::string trimmed_match_1 {boost::algorithm::trim_left_copy_if(match[1].str(), is_zero)};
204 if (trimmed_match_1.empty()) {
205 trimmed_match_1 =
"0"s;
208 std::string trimmed_match_2;
209 if (allow_decimal_point && match[2].matched) {
210 trimmed_match_2 = boost::algorithm::trim_right_copy_if(match[2].str(), is_zero);
213 if (!trimmed_match_2.empty()) {
221 const std::string numerator_str {trimmed_match_1 + trimmed_match_2};
222 const auto numerator {stou(numerator_str)};
225 const auto denominator {
static_cast<unsigned int>(std::pow(10, trimmed_match_2.size()))};
227 output = Rational {numerator, denominator};
234 output = Rational {stou(trimmed_match_1), 1};
237 }
catch (
const std::out_of_range &) {
238 BOOST_LOG(error) <<
"Failed to parse refresh rate string " << trimmed_input <<
" (number out of range).";
239 }
catch (
const std::exception &err) {
240 BOOST_LOG(error) <<
"Failed to parse refresh rate string " << trimmed_input <<
":\n"
244 if (trimmed_input.empty()) {
245 output = std::nullopt;
249 BOOST_LOG(error) <<
"Failed to parse refresh rate string " << trimmed_input <<
". Must have a pattern of " << (allow_decimal_point ? R
"("123" or "123.456")" : R"("123")") << "!";
266 std::optional<SingleDisplayConfiguration::DevicePreparation> parse_device_prep_option(
const config::video_t &video_config) {
268 using enum SingleDisplayConfiguration::DevicePreparation;
270 switch (video_config.dd.configuration_option) {
276 return EnsurePrimary;
277 case ensure_only_display:
278 return EnsureOnlyDisplay;
301 bool parse_resolution_option(
const config::video_t &video_config,
const rtsp_stream::launch_session_t &session, SingleDisplayConfiguration &config) {
304 switch (video_config.dd.resolution_option) {
305 case resolution_option_e::automatic:
307 if (!session.enable_sops) {
308 BOOST_LOG(warning) << R
"(Hermes is configured to change resolution automatically, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)";
309 } else if (session.width >= 0 && session.height >= 0) {
310 config.m_resolution = Resolution {
311 static_cast<unsigned int>(session.width),
312 static_cast<unsigned int>(session.height)
315 BOOST_LOG(error) <<
"Resolution provided by client session config is invalid: " << session.width <<
"x" << session.height;
320 case resolution_option_e::manual:
322 if (!session.enable_sops) {
323 BOOST_LOG(warning) << R
"(Hermes is configured to change resolution manually, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)";
325 if (!parse_resolution_string(video_config.dd.
manual_resolution, config.m_resolution)) {
326 BOOST_LOG(error) <<
"Failed to parse manual resolution string!";
330 if (!config.m_resolution) {
331 BOOST_LOG(error) <<
"Manual resolution must be specified!";
337 case resolution_option_e::disabled:
359 bool parse_refresh_rate_option(
const config::video_t &video_config,
const rtsp_stream::launch_session_t &session, SingleDisplayConfiguration &config) {
362 switch (video_config.dd.refresh_rate_option) {
363 case refresh_rate_option_e::automatic:
365 if (session.fps >= 0) {
366 config.m_refresh_rate = Rational {
static_cast<unsigned int>(session.fps), 1000};
368 BOOST_LOG(error) <<
"FPS value provided by client session config is invalid: " << session.fps;
373 case refresh_rate_option_e::manual:
375 if (!parse_refresh_rate_string(video_config.dd.
manual_refresh_rate, config.m_refresh_rate)) {
376 BOOST_LOG(error) <<
"Failed to parse manual refresh rate string!";
380 if (!config.m_refresh_rate) {
381 BOOST_LOG(error) <<
"Manual refresh rate must be specified!";
386 case refresh_rate_option_e::disabled:
406 std::optional<HdrState> parse_hdr_option(
const config::video_t &video_config,
const rtsp_stream::launch_session_t &session) {
409 switch (video_config.dd.hdr_option) {
410 case hdr_option_e::automatic:
411 return session.enable_hdr ? HdrState::Enabled : HdrState::Disabled;
412 case hdr_option_e::disabled:
422 enum class remapping_type_e {
433 std::optional<remapping_type_e> determine_remapping_type(
const config::video_t &video_config) {
434 using dd_t = config::video_t::dd_t;
435 const bool auto_resolution {video_config.dd.resolution_option == dd_t::resolution_option_e::automatic};
436 const bool auto_refresh_rate {video_config.dd.refresh_rate_option == dd_t::refresh_rate_option_e::automatic};
438 if (auto_resolution && auto_refresh_rate) {
439 return remapping_type_e::mixed;
442 if (auto_resolution) {
443 return remapping_type_e::resolution_only;
446 if (auto_refresh_rate) {
447 return remapping_type_e::refresh_rate_only;
456 struct parsed_remapping_entry_t {
457 std::optional<Resolution> requested_resolution;
458 std::optional<FloatingPoint> requested_fps;
459 std::optional<Resolution> final_resolution;
460 std::optional<FloatingPoint> final_refresh_rate;
468 bool is_resolution_mapped(
const remapping_type_e type) {
469 return type == remapping_type_e::resolution_only || type == remapping_type_e::mixed;
477 bool is_fps_mapped(
const remapping_type_e type) {
478 return type == remapping_type_e::refresh_rate_only || type == remapping_type_e::mixed;
487 std::optional<parsed_remapping_entry_t> parse_remapping_entry(
const config::video_t::dd_t::mode_remapping_entry_t &entry,
const remapping_type_e type) {
488 parsed_remapping_entry_t result {};
490 if (is_resolution_mapped(type) && (!parse_resolution_string(entry.requested_resolution, result.requested_resolution) ||
491 !parse_resolution_string(entry.final_resolution, result.final_resolution))) {
495 if (is_fps_mapped(type) && (!parse_refresh_rate_string(entry.requested_fps, result.requested_fps,
false) ||
496 !parse_refresh_rate_string(entry.final_refresh_rate, result.final_refresh_rate))) {
518 bool remap_display_mode_if_needed(
const config::video_t &video_config,
const rtsp_stream::launch_session_t &session, SingleDisplayConfiguration &config) {
519 const auto remapping_type {determine_remapping_type(video_config)};
520 if (!remapping_type) {
524 const auto &remapping_list {[&]() {
525 using enum remapping_type_e;
527 switch (*remapping_type) {
528 case resolution_only:
530 case refresh_rate_only:
534 return video_config.dd.mode_remapping.
mixed;
538 if (remapping_list.empty()) {
539 BOOST_LOG(debug) <<
"No values are available for display mode remapping.";
542 BOOST_LOG(debug) <<
"Trying to remap display modes...";
544 const auto entry_to_string {[type = *remapping_type](
const config::video_t::dd_t::mode_remapping_entry_t &entry) {
545 const bool mapping_resolution {is_resolution_mapped(type)};
546 const bool mapping_fps {is_fps_mapped(type)};
549 return (mapping_resolution ?
" - requested resolution: "s + entry.requested_resolution +
"\n" :
"") +
550 (mapping_fps ?
" - requested FPS: "s + entry.requested_fps +
"\n" :
"") +
551 (mapping_resolution ?
" - final resolution: "s + entry.final_resolution +
"\n" :
"") +
552 (mapping_fps ?
" - final refresh rate: "s + entry.final_refresh_rate :
"");
556 for (
const auto &entry : remapping_list) {
557 const auto parsed_entry {parse_remapping_entry(entry, *remapping_type)};
559 BOOST_LOG(error) <<
"Failed to parse remapping entry from:\n"
560 << entry_to_string(entry);
564 if (!parsed_entry->final_resolution && !parsed_entry->final_refresh_rate) {
565 BOOST_LOG(error) <<
"At least one final value must be set for remapping display modes! Entry:\n"
566 << entry_to_string(entry);
570 if (!session.enable_sops && (parsed_entry->requested_resolution || parsed_entry->final_resolution)) {
571 BOOST_LOG(warning) << R
"(Skipping remapping entry, because the "Optimize game settings" is not set in the client! Entry:\n)"
572 << entry_to_string(entry);
577 if (parsed_entry->requested_resolution && parsed_entry->requested_resolution != config.m_resolution) {
578 BOOST_LOG(verbose) <<
"Skipping remapping because requested resolutions do not match! Entry:\n"
579 << entry_to_string(entry);
584 if (parsed_entry->requested_fps && parsed_entry->requested_fps != config.m_refresh_rate) {
585 BOOST_LOG(verbose) <<
"Skipping remapping because requested FPS do not match! Entry:\n"
586 << entry_to_string(entry);
590 BOOST_LOG(info) <<
"Remapping requested display mode. Entry:\n"
591 << entry_to_string(entry);
592 if (parsed_entry->final_resolution) {
593 config.m_resolution = parsed_entry->final_resolution;
595 if (parsed_entry->final_refresh_rate) {
596 config.m_refresh_rate = parsed_entry->final_refresh_rate;
610 std::unique_ptr<SettingsManagerInterface> make_settings_manager([[maybe_unused]]
const std::filesystem::path &persistence_filepath, [[maybe_unused]]
const config::video_t &video_config) {
617 enum class revert_option_e {
620 try_indefinitely_with_delay
627 void revert_configuration_unlocked(
const revert_option_e option) {
628 if (!DD_DATA.sm_instance) {
634 SchedulerOptions scheduler_option {.m_sleep_durations = {DEFAULT_RETRY_INTERVAL}};
635 if (option == revert_option_e::try_indefinitely_with_delay && DD_DATA.config_revert_delay > std::chrono::milliseconds::zero()) {
636 scheduler_option.m_sleep_durations = {DD_DATA.config_revert_delay, DEFAULT_RETRY_INTERVAL};
637 scheduler_option.m_execution = SchedulerOptions::Execution::ScheduledOnly;
640 DD_DATA.sm_instance->schedule([try_once = (option == revert_option_e::try_once), tried_out_devices = std::set<std::string> {}](
auto &settings_iface,
auto &stop_token)
mutable {
642 std::ignore = settings_iface.revertSettings();
643 stop_token.requestStop();
647 auto available_devices {[&settings_iface]() {
648 const auto devices {settings_iface.enumAvailableDevices()};
649 std::set<std::string> parsed_devices;
654 std::inserter(parsed_devices, std::end(parsed_devices)),
655 [](
const auto &device) {
656 return device.m_device_id +
" - " + device.m_friendly_name;
660 return parsed_devices;
662 if (available_devices == tried_out_devices) {
663 BOOST_LOG(debug) <<
"Skipping reverting configuration, because no newly added/removed devices were detected since last check. Currently available devices:\n"
664 << toJson(available_devices);
668 using enum SettingsManagerInterface::RevertResult;
669 if (
const auto result {settings_iface.revertSettings()}; result == Ok) {
670 stop_token.requestStop();
672 }
else if (result == ApiTemporarilyUnavailable) {
678 BOOST_LOG(warning) <<
"Failed to revert display device configuration (will retry once devices are added or removed). Enabling all of the available devices:\n"
679 << toJson(available_devices);
680 tried_out_devices.swap(available_devices);
686 std::unique_ptr<platf::deinit_t>
init(
const std::filesystem::path &persistence_filepath,
const config::video_t &video_config) {
687 std::lock_guard lock {DD_DATA.mutex};
690 if (!persistence_filepath.empty() && std::filesystem::exists(persistence_filepath)) {
691 std::filesystem::remove(persistence_filepath);
694 revert_configuration_unlocked(revert_option_e::try_once);
697 DD_DATA.sm_instance =
nullptr;
701 if (
auto settings_manager {make_settings_manager(persistence_filepath, video_config)}) {
702 DD_DATA.sm_instance = std::make_unique<RetryScheduler<SettingsManagerInterface>>(std::move(settings_manager));
704 const auto available_devices {DD_DATA.sm_instance->execute([](
auto &settings_iface) {
705 return settings_iface.enumAvailableDevices();
707 BOOST_LOG(info) <<
"Currently available display devices:\n"
708 << toJson(available_devices);
712 revert_configuration_unlocked(revert_option_e::try_indefinitely);
717 ~deinit_t()
override {
718 std::lock_guard lock {DD_DATA.mutex};
724 revert_configuration_unlocked(revert_option_e::try_once);
725 }
catch (std::exception &err) {
726 BOOST_LOG(fatal) << err.what();
729 DD_DATA.sm_instance =
nullptr;
733 return std::make_unique<deinit_t>();
737 std::lock_guard lock {DD_DATA.mutex};
738 if (!DD_DATA.sm_instance) {
743 return DD_DATA.sm_instance->execute([&output_name](
auto &settings_iface) {
744 return settings_iface.getDisplayName(output_name);
748 std::string map_display_name(
const std::string &display_name) {
749 std::lock_guard lock { DD_DATA.mutex };
750 if (!DD_DATA.sm_instance) {
754 const auto available_devices { DD_DATA.sm_instance->execute([](
auto &settings_iface) {
return settings_iface.enumAvailableDevices(); }) };
756 for (
auto &i : available_devices) {
757 if (i.m_display_name == display_name) {
758 return i.m_device_id;
767 if (
const auto *parsed_config { std::get_if<SingleDisplayConfiguration>(&result) }; parsed_config) {
772 if (
const auto *disabled {std::get_if<configuration_disabled_tag_t>(&result)}; disabled) {
782 std::lock_guard lock {DD_DATA.mutex};
783 if (!DD_DATA.sm_instance) {
788 DD_DATA.sm_instance->schedule([config](
auto &settings_iface,
auto &stop_token) {
791 if (settings_iface.applySettings(config) != SettingsManagerInterface::ApplyResult::ApiTemporarilyUnavailable) {
792 stop_token.requestStop();
795 {.m_sleep_durations = {DEFAULT_RETRY_INTERVAL}});
799 std::lock_guard lock {DD_DATA.mutex};
800 revert_configuration_unlocked(revert_option_e::try_indefinitely_with_delay);
804 std::lock_guard lock {DD_DATA.mutex};
805 if (!DD_DATA.sm_instance) {
810 return DD_DATA.sm_instance->execute([](
auto &settings_iface,
auto &stop_token) {
813 stop_token.requestStop();
814 return settings_iface.resetPersistence();
819 std::lock_guard lock {DD_DATA.mutex};
820 if (!DD_DATA.sm_instance) {
825 return DD_DATA.sm_instance->execute([](
auto &settings_iface) {
826 return settings_iface.enumAvailableDevices();
831 const auto device_prep {parse_device_prep_option(video_config)};
836 SingleDisplayConfiguration config;
837 config.m_device_id = video_config.output_name;
838 config.m_device_prep = *device_prep;
839 config.m_hdr_state = parse_hdr_option(video_config, session);
841 if (!parse_resolution_option(video_config, session, config)) {
846 if (!parse_refresh_rate_option(video_config, session, config)) {
851 if (!remap_display_mode_if_needed(video_config, session, config)) {
audio_ctx_ref_t get_audio_ctx_ref()
Get the reference to the audio context.
Declarations for audio capture and encoding.
Declarations for common platform specific utilities.
std::variant< failed_to_parse_tag_t, configuration_disabled_tag_t, SingleDisplayConfiguration > parse_configuration(const config::video_t &video_config, const rtsp_stream::launch_session_t &session)
Parse the user configuration and the session information.
void revert_configuration()
Revert the display configuration and restore the previous state.
std::unique_ptr< platf::deinit_t > init(const std::filesystem::path &persistence_filepath, const config::video_t &video_config)
Initialize the implementation and perform the initial state recovery (if needed).
void configure_display(const config::video_t &video_config, const rtsp_stream::launch_session_t &session)
Configure the display device based on the user configuration and the session information.
EnumeratedDeviceList enumerate_devices()
Enumerate the available devices.
bool reset_persistence()
Reset the persistence and currently held initial display state.
std::string map_output_name(const std::string &output_name)
Map the output name to a specific display.
Declarations for display device handling.
@ disabled
Single pass, the fastest and no extra vram.
Declarations for RTSP streaming.
std::vector< mode_remapping_entry_t > refresh_rate_only
To be use when only refresh_rate_option is set to automatic.
std::vector< mode_remapping_entry_t > mixed
To be used when resolution_option and refresh_rate_option is set to automatic.
std::vector< mode_remapping_entry_t > resolution_only
To be use when only resolution_option is set to automatic.
std::string manual_resolution
Manual resolution in case resolution_option == resolution_option_e::manual.
std::chrono::milliseconds config_revert_delay
Time to wait until settings are reverted (after stream ends/app exists).
std::string manual_refresh_rate
Manual refresh rate in case refresh_rate_option == refresh_rate_option_e::manual.
@ disabled
Disable the configuration for the device.
A tag structure indicating that configuration is disabled.
A tag structure indicating that configuration parsing has failed.
void release(input_raw_t *raw, int index)
Free a gamepad whose stream ended; a detached desktop keeps it.