Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
config.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <algorithm>
7#include <filesystem>
8#include <fstream>
9#include <functional>
10#include <iostream>
11#include <thread>
12#include <unordered_map>
13#include <utility>
14
15// lib includes
16#include <boost/asio.hpp>
17#include <boost/filesystem.hpp>
18#include <boost/property_tree/json_parser.hpp>
19#include <boost/property_tree/ptree.hpp>
20
21// local includes
22#include "config.h"
23#include "entry_handler.h"
24#include "file_handler.h"
25#include "logging.h"
26#include "nvhttp.h"
27#include "platform/common.h"
28#include "rtsp.h"
29#include "video.h"
30#include "utility.h"
31
32
33// For NVENC legacy constants
34#include <ffnvcodec/nvEncodeAPI.h>
35
36namespace fs = std::filesystem;
37using namespace std::literals;
38
39#define CA_DIR "credentials"
40#define PRIVATE_KEY_FILE CA_DIR "/cakey.pem"
41#define CERTIFICATE_FILE CA_DIR "/cacert.pem"
42
43#define APPS_JSON_PATH platf::appdata().string() + "/apps.json"
44
45namespace config {
46
47 namespace nv {
48
49 nvenc::nvenc_two_pass twopass_from_view(const ::std::string_view &preset) {
50 if (preset == "disabled") {
52 }
53 if (preset == "quarter_res") {
55 }
56 if (preset == "full_res") {
58 }
59 BOOST_LOG(warning) << "config: unknown nvenc_twopass value: " << preset;
61 }
62
63 } // namespace nv
64
65 namespace sw {
66 int svtav1_preset_from_view(const ::std::string_view &preset) {
67#define _CONVERT_(x, y) \
68 if (preset == #x##sv) \
69 return y
70 _CONVERT_(veryslow, 1);
71 _CONVERT_(slower, 2);
72 _CONVERT_(slow, 4);
73 _CONVERT_(medium, 5);
74 _CONVERT_(fast, 7);
75 _CONVERT_(faster, 9);
76 _CONVERT_(veryfast, 10);
77 _CONVERT_(superfast, 11);
78 _CONVERT_(ultrafast, 12);
79#undef _CONVERT_
80 return 11; // Default to superfast
81 }
82 } // namespace sw
83
84 namespace dd {
85 video_t::dd_t::config_option_e config_option_from_view(const ::std::string_view value) {
86#define _CONVERT_(x) \
87 if (value == #x##sv) \
88 return video_t::dd_t::config_option_e::x
89 _CONVERT_(disabled);
90 _CONVERT_(verify_only);
91 _CONVERT_(ensure_active);
92 _CONVERT_(ensure_primary);
93 _CONVERT_(ensure_only_display);
94#undef _CONVERT_
95 return video_t::dd_t::config_option_e::disabled; // Default to this if value is invalid
96 }
97
98 video_t::dd_t::resolution_option_e resolution_option_from_view(const ::std::string_view value) {
99#define _CONVERT_2_ARG_(str, val) \
100 if (value == #str##sv) \
101 return video_t::dd_t::resolution_option_e::val
102#define _CONVERT_(x) _CONVERT_2_ARG_(x, x)
103 _CONVERT_(disabled);
104 _CONVERT_2_ARG_(auto, automatic);
105 _CONVERT_(manual);
106#undef _CONVERT_
107#undef _CONVERT_2_ARG_
108 return video_t::dd_t::resolution_option_e::disabled; // Default to this if value is invalid
109 }
110
111 video_t::dd_t::refresh_rate_option_e refresh_rate_option_from_view(const ::std::string_view value) {
112#define _CONVERT_2_ARG_(str, val) \
113 if (value == #str##sv) \
114 return video_t::dd_t::refresh_rate_option_e::val
115#define _CONVERT_(x) _CONVERT_2_ARG_(x, x)
116 _CONVERT_(disabled);
117 _CONVERT_2_ARG_(auto, automatic);
118 _CONVERT_(manual);
119#undef _CONVERT_
120#undef _CONVERT_2_ARG_
121 return video_t::dd_t::refresh_rate_option_e::disabled; // Default to this if value is invalid
122 }
123
124 video_t::dd_t::hdr_option_e hdr_option_from_view(const ::std::string_view value) {
125#define _CONVERT_2_ARG_(str, val) \
126 if (value == #str##sv) \
127 return video_t::dd_t::hdr_option_e::val
128#define _CONVERT_(x) _CONVERT_2_ARG_(x, x)
129 _CONVERT_(disabled);
130 _CONVERT_2_ARG_(auto, automatic);
131#undef _CONVERT_
132#undef _CONVERT_2_ARG_
133 return video_t::dd_t::hdr_option_e::disabled; // Default to this if value is invalid
134 }
135
136 video_t::dd_t::mode_remapping_t mode_remapping_from_view(const ::std::string_view value) {
137 const auto parse_entry_list {[](const auto &entry_list, auto &output_field) {
138 for (auto &[_, entry] : entry_list) {
139 auto requested_resolution = entry.template get_optional<std::string>("requested_resolution"s);
140 auto requested_fps = entry.template get_optional<std::string>("requested_fps"s);
141 auto final_resolution = entry.template get_optional<std::string>("final_resolution"s);
142 auto final_refresh_rate = entry.template get_optional<std::string>("final_refresh_rate"s);
143
144 output_field.push_back(video_t::dd_t::mode_remapping_entry_t {requested_resolution.value_or(""), requested_fps.value_or(""), final_resolution.value_or(""), final_refresh_rate.value_or("")});
145 }
146 }};
147
148 // We need to add a wrapping object to make it valid JSON, otherwise ptree cannot parse it.
149 std::stringstream json_stream;
150 json_stream << "{\"dd_mode_remapping\":" << value << "}";
151
152 boost::property_tree::ptree json_tree;
153 boost::property_tree::read_json(json_stream, json_tree);
154
155 video_t::dd_t::mode_remapping_t output;
156 parse_entry_list(json_tree.get_child("dd_mode_remapping.mixed"), output.mixed);
157 parse_entry_list(json_tree.get_child("dd_mode_remapping.resolution_only"), output.resolution_only);
158 parse_entry_list(json_tree.get_child("dd_mode_remapping.refresh_rate_only"), output.refresh_rate_only);
159
160 return output;
161 }
162 } // namespace dd
163
164 video_t video {
165 false, // headless_mode
166 true, // limit_framerate
167 false, // double_refreshrate
168
169 28, // qp
170
171 0, // hevc_mode
172 0, // av1_mode
173
174 2, // min_threads
175 100, // default_scale_factor
176 {
177 "superfast"s, // preset
178 "zerolatency"s, // tune
179 11, // superfast
180 }, // software
181
182 {}, // nv
183 {}, // nv_legacy
184
185 {
186 false, // strict_rc_buffer
187 -1, // quality
188 true, // intra_refresh
189 }, // vaapi
190
191 {}, // capture
192 {}, // encoder
193 {}, // adapter_name
194 {}, // output_name
195 "evdi"s, // virtual_display_backend
196 false, // hermes_kms_multi_output
197 false, // hermes_kms_isolated_sessions
198 "auto"s, // gamescope_backend
199 "plasma"s, // hermes_kms_session_compositor
200 "gamescope"s, // isolation_method
201
202 {
203 video_t::dd_t::config_option_e::disabled, // configuration_option
205 {}, // manual_resolution
207 {}, // manual_refresh_rate
209 3s, // config_revert_delay
210 {}, // config_revert_on_disconnect
211 {}, // mode_remapping
212 {} // wa
213 }, // display_device
214
215 0, // max_bitrate
216 0, // minimum_fps_target (0 = framerate)
217
218 "1920x1080x60", // fallback_mode
219 false, // isolated Display
220 false, // ignore_encoder_probe_failure
221 false, // pyrowave (experimental, opt-in)
222 };
223
224 audio_t audio {
225 {}, // audio_sink
226 true, // stream audio
227 false, // stream_mic
228 true, // keep_sink_default
229 true, // auto_capture
230 };
231
232 stream_t stream {
233 10s, // ping_timeout
234
235 APPS_JSON_PATH,
236
237 20, // fecPercentage
238
239 true, // adaptive_fec
240 50, // adaptive_fec_max_percentage
241
242 ENCRYPTION_MODE_NEVER, // lan_encryption_mode
243 ENCRYPTION_MODE_OPPORTUNISTIC, // wan_encryption_mode
244 };
245
246 nvhttp_t nvhttp {
247 "lan", // origin web manager
248
249 PRIVATE_KEY_FILE,
250 CERTIFICATE_FILE,
251
252 platf::get_host_name(), // sunshine_name,
253 "hermes_state.json"s, // file_state
254 {}, // external_ip
255 };
256
257 input_t input {
258 {
259 {0x10, 0xA0},
260 {0x11, 0xA2},
261 {0x12, 0xA4},
262 },
263 -1ms, // back_button_timeout
264 500ms, // key_repeat_delay
265 std::chrono::duration<double> {1 / 24.9}, // key_repeat_period
266
267 {
268 platf::supported_gamepads(nullptr).front().name.data(),
269 platf::supported_gamepads(nullptr).front().name.size(),
270 }, // Default gamepad
271 "auto"s, // Linux: preserve evdev rumble for Xbox; native HID for PlayStation/Switch
272 true, // Back as PlayStation touchpad click (DS4/DS5)
273 true, // client gamepads with motion events are emulated as DS4
274 true, // client gamepads with touchpads are emulated as DS4
275 true, // virtualhid_randomize_mac
276
277 true, // keyboard enabled
278 true, // mouse enabled
279 true, // controller enabled
280 true, // high resolution scrolling
281 true, // native pen/touch support
282 true, // isolated_ignore_mouse_wiggle
283 false, // isolated_hide_hid_gamepads
284 true, // virtualhid_stable_mac
285 false, // enable input only mode
286 true, // forward_rumble
287 };
288
289 sunshine_t sunshine {
290 false, // hide_tray_controls
291 true, // enable_pairing
292 true, // enable_discovery
293 false, // envvar_compatibility_mode
294 false, // appliance_mode (dormant; parsed but no runtime effect yet)
295 "en", // locale
296 2, // min_log_level
297 0, // flags
298 {}, // User file
299 {}, // Username
300 {}, // Password
301 {}, // Password Salt
302 platf::appdata().string() + "/hermes.conf", // config file
303 {}, // cmd args
304 47989, // Base port number
305 // Default to dual-stack. On modern distros `localhost` often resolves to
306 // ::1 (IPv6) first, so an IPv4-only bind makes the web UI fail
307 // intermittently with "Failed to fetch" (the browser tries ::1, which
308 // nothing is listening on, before falling back to 127.0.0.1). "both" binds
309 // "::" dual-stack so localhost works regardless of how it resolves.
310 "both", // Address family
311 platf::appdata().string() + "/hermes.log", // log file
312 false, // notify_pre_releases
313 true, // announcements
314 false, // legacy_ordering
315 true, // system_tray
316 {}, // prep commands
317 {}, // state commands
318 {}, // server commands
319 false, // inhibit screen locking while a client is connected
320 };
321
322 bool endline(char ch) {
323 return ch == '\r' || ch == '\n';
324 }
325
326 bool space_tab(char ch) {
327 return ch == ' ' || ch == '\t';
328 }
329
330 bool whitespace(char ch) {
331 return space_tab(ch) || endline(ch);
332 }
333
334 std::string to_string(const char *begin, const char *end) {
335 std::string result;
336
337 KITTY_WHILE_LOOP(auto pos = begin, pos != end, {
338 auto comment = std::find(pos, end, '#');
339 auto endl = std::find_if(comment, end, endline);
340
341 result.append(pos, comment);
342
343 pos = endl;
344 })
345
346 return result;
347 }
348
349 template<class It>
350 It skip_list(It skipper, It end) {
351 int stack = 1;
352 while (skipper != end && stack) {
353 if (*skipper == '[') {
354 ++stack;
355 }
356 if (*skipper == ']') {
357 --stack;
358 }
359
360 ++skipper;
361 }
362
363 return skipper;
364 }
365
366 std::pair<
367 ::std::string_view::const_iterator,
368 ::std::optional<std::pair<std::string, std::string>>>
369 parse_option(::std::string_view::const_iterator begin, ::std::string_view::const_iterator end) {
370 begin = std::find_if_not(begin, end, whitespace);
371 auto endl = std::find_if(begin, end, endline);
372 auto endc = std::find(begin, endl, '#');
373 endc = std::find_if(std::make_reverse_iterator(endc), std::make_reverse_iterator(begin), std::not_fn(whitespace)).base();
374
375 auto eq = std::find(begin, endc, '=');
376 if (eq == endc || eq == begin) {
377 return std::make_pair(endl, std::nullopt);
378 }
379
380 auto end_name = std::find_if_not(std::make_reverse_iterator(eq), std::make_reverse_iterator(begin), space_tab).base();
381 auto begin_val = std::find_if_not(eq + 1, endc, space_tab);
382
383 if (begin_val == endl) {
384 return std::make_pair(endl, std::nullopt);
385 }
386
387 // Lists might contain newlines
388 if (*begin_val == '[') {
389 endl = skip_list(begin_val + 1, end);
390
391 // Check if we reached the end of the file without finding a closing bracket
392 // We know we have a valid closing bracket if:
393 // 1. We didn't reach the end, or
394 // 2. We reached the end but the last character was the matching closing bracket
395 if (endl == end && end == begin_val + 1) {
396 BOOST_LOG(warning) << "config: Missing ']' in config option: " << to_string(begin, end_name);
397 return std::make_pair(endl, std::nullopt);
398 }
399 }
400
401 return std::make_pair(
402 endl,
403 std::make_pair(to_string(begin, end_name), to_string(begin_val, endl))
404 );
405 }
406
407 const std::set<std::string> &server_computed_keys() {
408 static const std::set<std::string> keys {
409 "clipboardInfo",
410 "evdiDiagnostic",
411 "evdiInfo",
412 "evdiSetupRequired",
413 "hermesKmsDiagnostic",
414 "hermesKmsInfo",
415 "platform",
416 "preloginInfo",
417 "status",
418 "streamPorts",
419 "vdisplayStatus",
420 "version",
421 "version_commit",
422 };
423 return keys;
424 }
425
426 static void normalize_input_config_alias(std::unordered_map<std::string, std::string> &vars) {
427 for (const auto alias : {"ds5_virtualhid_randomize_mac", "ds5_inputtino_randomize_mac"}) {
428 auto legacy = vars.extract(alias);
429 if (!legacy.empty()) {
430 legacy.key() = "virtualhid_randomize_mac";
431 // Canonical wins; otherwise prefer the newer alias over Inputtino.
432 vars.insert(std::move(legacy));
433 }
434 }
435 }
436
437 std::unordered_map<std::string, std::string> parse_config(const ::std::string_view &file_content) {
438 std::unordered_map<std::string, std::string> vars;
439
440 auto pos = std::begin(file_content);
441 auto end = std::end(file_content);
442
443 while (pos < end) {
444 // auto newline = std::find_if(pos, end, [](auto ch) { return ch == '\n' || ch == '\r'; });
445 TUPLE_2D(endl, var, parse_option(pos, end));
446
447 pos = endl;
448 if (pos != end) {
449 pos += (*pos == '\r') ? 2 : 1;
450 }
451
452 if (!var) {
453 continue;
454 }
455
456 vars.emplace(std::move(*var));
457 }
458
459 // Canonicalize here as well as at apply time so the configuration UI sees
460 // an older saved value instead of silently showing the new key's default.
461 normalize_input_config_alias(vars);
462 return vars;
463 }
464
465 void string_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input) {
466 auto it = vars.find(name);
467 if (it == std::end(vars)) {
468 return;
469 }
470
471 input = std::move(it->second);
472
473 vars.erase(it);
474 }
475
476 template<typename T, typename F>
477 void generic_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, T &input, F &&f) {
478 std::string tmp;
479 string_f(vars, name, tmp);
480 if (!tmp.empty()) {
481 input = f(tmp);
482 }
483 }
484
485 void string_restricted_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input, const std::vector<::std::string_view> &allowed_vals) {
486 std::string temp;
487 string_f(vars, name, temp);
488
489 for (auto &allowed_val : allowed_vals) {
490 if (temp == allowed_val) {
491 input = std::move(temp);
492 return;
493 }
494 }
495
496 // A value that is set but not recognized used to be dropped without a word.
497 // The config file then said one thing and every consumer downstream behaved
498 // according to another, with nothing anywhere to connect the two - a typo,
499 // or a value written by a different version of Hermes, was indistinguishable
500 // from never having set the key at all.
501 if (!temp.empty()) {
502 std::string allowed;
503 for (const auto &allowed_val : allowed_vals) {
504 if (!allowed.empty()) {
505 allowed += ", ";
506 }
507 allowed += allowed_val;
508 }
509 BOOST_LOG(warning) << name << " = " << temp << " is not a recognized value; keeping "
510 << (input.empty() ? std::string {"the default"} : input)
511 << " instead. Valid values: " << allowed << '.';
512 }
513 }
514
515 void path_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, fs::path &input) {
516 // appdata needs to be retrieved once only
517 static auto appdata = platf::appdata();
518
519 std::string temp;
520 string_f(vars, name, temp);
521
522 if (!temp.empty()) {
523 input = temp;
524 }
525
526 if (input.is_relative()) {
527 input = appdata / input;
528 }
529
530 auto dir = input;
531 dir.remove_filename();
532
533 // Ensure the directories exists
534 if (!fs::exists(dir)) {
535 fs::create_directories(dir);
536 }
537 }
538
539 void path_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::string &input) {
540 fs::path temp = input;
541
542 path_f(vars, name, temp);
543
544 input = temp.string();
545 }
546
547 void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input) {
548 auto it = vars.find(name);
549
550 if (it == std::end(vars)) {
551 return;
552 }
553
554 ::std::string_view val = it->second;
555
556 // If value is something like: "756" instead of 756
557 if (val.size() >= 2 && val[0] == '"') {
558 val = val.substr(1, val.size() - 2);
559 }
560
561 // If that integer is in hexadecimal
562 if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) {
563 input = util::from_hex<int>(val.substr(2));
564 } else {
565 input = util::from_view(val);
566 }
567
568 vars.erase(it);
569 }
570
571 void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, ::std::optional<int> &input) {
572 auto it = vars.find(name);
573
574 if (it == std::end(vars)) {
575 return;
576 }
577
578 ::std::string_view val = it->second;
579
580 // If value is something like: "756" instead of 756
581 if (val.size() >= 2 && val[0] == '"') {
582 val = val.substr(1, val.size() - 2);
583 }
584
585 // If that integer is in hexadecimal
586 if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) {
587 input = util::from_hex<int>(val.substr(2));
588 } else {
589 input = util::from_view(val);
590 }
591
592 vars.erase(it);
593 }
594
595 template<class F>
596 void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input, F &&f) {
597 std::string tmp;
598 string_f(vars, name, tmp);
599 if (!tmp.empty()) {
600 input = f(tmp);
601 }
602 }
603
604 template<class F>
605 void int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, ::std::optional<int> &input, F &&f) {
606 std::string tmp;
607 string_f(vars, name, tmp);
608 if (!tmp.empty()) {
609 input = f(tmp);
610 }
611 }
612
613 void int_between_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, int &input, const std::pair<int, int> &range) {
614 int temp = input;
615
616 int_f(vars, name, temp);
617
618 TUPLE_2D_REF(lower, upper, range);
619 if (temp >= lower && temp <= upper) {
620 input = temp;
621 }
622 }
623
624 bool to_bool(std::string &boolean) {
625 std::for_each(std::begin(boolean), std::end(boolean), [](char ch) {
626 return (char) std::tolower(ch);
627 });
628
629 return boolean == "true"sv ||
630 boolean == "yes"sv ||
631 boolean == "enable"sv ||
632 boolean == "enabled"sv ||
633 boolean == "on"sv ||
634 (std::find(std::begin(boolean), std::end(boolean), '1') != std::end(boolean));
635 }
636
637 void bool_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, bool &input) {
638 std::string tmp;
639 string_f(vars, name, tmp);
640
641 if (tmp.empty()) {
642 return;
643 }
644
645 input = to_bool(tmp);
646 }
647
648 void double_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, double &input) {
649 std::string tmp;
650 string_f(vars, name, tmp);
651
652 if (tmp.empty()) {
653 return;
654 }
655
656 char *c_str_p;
657 auto val = std::strtod(tmp.c_str(), &c_str_p);
658
659 if (c_str_p == tmp.c_str()) {
660 return;
661 }
662
663 input = val;
664 }
665
666 void double_between_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, double &input, const std::pair<double, double> &range) {
667 double temp = input;
668
669 double_f(vars, name, temp);
670
671 TUPLE_2D_REF(lower, upper, range);
672 if (temp >= lower && temp <= upper) {
673 input = temp;
674 }
675 }
676
677 void list_string_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<std::string> &input) {
678 std::string string;
679 string_f(vars, name, string);
680
681 if (string.empty()) {
682 return;
683 }
684
685 input.clear();
686
687 auto begin = std::cbegin(string);
688 if (*begin == '[') {
689 ++begin;
690 }
691
692 begin = std::find_if_not(begin, std::cend(string), whitespace);
693 if (begin == std::cend(string)) {
694 return;
695 }
696
697 auto pos = begin;
698 while (pos < std::cend(string)) {
699 if (*pos == '[') {
700 pos = skip_list(pos + 1, std::cend(string)) + 1;
701 } else if (*pos == ']') {
702 break;
703 } else if (*pos == ',') {
704 input.emplace_back(begin, pos);
705 pos = begin = std::find_if_not(pos + 1, std::cend(string), whitespace);
706 } else {
707 ++pos;
708 }
709 }
710
711 if (pos != begin) {
712 input.emplace_back(begin, pos);
713 }
714 }
715
716 void list_prep_cmd_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<prep_cmd_t> &input) {
717 std::string string;
718 string_f(vars, name, string);
719
720 std::stringstream jsonStream;
721
722 // check if string is empty, i.e. when the value doesn't exist in the config file
723 if (string.empty()) {
724 return;
725 }
726
727 // We need to add a wrapping object to make it valid JSON, otherwise ptree cannot parse it.
728 jsonStream << "{\"prep_cmd\":" << string << "}";
729
730 boost::property_tree::ptree jsonTree;
731 boost::property_tree::read_json(jsonStream, jsonTree);
732
733 for (auto &[_, prep_cmd] : jsonTree.get_child("prep_cmd"s)) {
734 auto do_cmd = prep_cmd.get_optional<std::string>("do"s);
735 auto undo_cmd = prep_cmd.get_optional<std::string>("undo"s);
736 auto elevated = prep_cmd.get_optional<bool>("elevated"s);
737
738 input.emplace_back(do_cmd.value_or(""), undo_cmd.value_or(""), elevated.value_or(false));
739 }
740 }
741
742 void list_server_cmd_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<server_cmd_t> &input) {
743 std::string string;
744 string_f(vars, name, string);
745
746 std::stringstream jsonStream;
747
748 // check if string is empty, i.e. when the value doesn't exist in the config file
749 if (string.empty()) {
750 return;
751 }
752
753 // We need to add a wrapping object to make it valid JSON, otherwise ptree cannot parse it.
754 jsonStream << "{\"server_cmd\":" << string << "}";
755
756 boost::property_tree::ptree jsonTree;
757 boost::property_tree::read_json(jsonStream, jsonTree);
758
759 for (auto &[_, prep_cmd] : jsonTree.get_child("server_cmd"s)) {
760 auto cmd_name = prep_cmd.get_optional<std::string>("name"s);
761 auto cmd_val = prep_cmd.get_optional<std::string>("cmd"s);
762 auto elevated = prep_cmd.get_optional<bool>("elevated"s);
763
764 input.emplace_back(cmd_name.value_or(""), cmd_val.value_or(""), elevated.value_or(false));
765 }
766 }
767
768 void list_int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::vector<int> &input) {
769 std::vector<std::string> list;
770 list_string_f(vars, name, list);
771
772 // check if list is empty, i.e. when the value doesn't exist in the config file
773 if (list.empty()) {
774 return;
775 }
776
777 // The framerate list must be cleared before adding values from the file configuration.
778 // If the list is not cleared, then the specified parameters do not affect the behavior of the sunshine server.
779 // That is, if you set only 30 fps in the configuration file, it will not work because by default, during initialization the list includes 10, 30, 60, 90 and 120 fps.
780 input.clear();
781 for (auto &el : list) {
782 ::std::string_view val = el;
783
784 // If value is something like: "756" instead of 756
785 if (val.size() >= 2 && val[0] == '"') {
786 val = val.substr(1, val.size() - 2);
787 }
788
789 int tmp;
790
791 // If the integer is a hexadecimal
792 if (val.size() >= 2 && val.substr(0, 2) == "0x"sv) {
793 tmp = util::from_hex<int>(val.substr(2));
794 } else {
795 tmp = util::from_view(val);
796 }
797 input.emplace_back(tmp);
798 }
799 }
800
801 void map_int_int_f(std::unordered_map<std::string, std::string> &vars, const std::string &name, std::unordered_map<int, int> &input) {
802 std::vector<int> list;
803 list_int_f(vars, name, list);
804
805 // The list needs to be a multiple of 2
806 if (list.size() % 2) {
807 BOOST_LOG(warning) << "config: expected "sv << name << " to have a multiple of two elements --> not "sv << list.size();
808 return;
809 }
810
811 int x = 0;
812 while (x < list.size()) {
813 auto key = list[x++];
814 auto val = list[x++];
815
816 input.emplace(key, val);
817 }
818 }
819
820 int apply_flags(const char *line) {
821 int ret = 0;
822 while (*line != '\0') {
823 switch (*line) {
824 case '0':
825 config::sunshine.flags[config::flag::PIN_STDIN].flip();
826 break;
827 case '1':
828 config::sunshine.flags[config::flag::FRESH_STATE].flip();
829 break;
830 case '2':
831 config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE].flip();
832 break;
833 case 'p':
834 config::sunshine.flags[config::flag::UPNP].flip();
835 break;
836 default:
837 BOOST_LOG(warning) << "config: Unrecognized flag: ["sv << *line << ']' << std::endl;
838 ret = -1;
839 }
840
841 ++line;
842 }
843
844 return ret;
845 }
846
847 std::vector<::std::string_view> &get_supported_gamepad_options() {
848 const auto options = platf::supported_gamepads(nullptr);
849 static std::vector<::std::string_view> opts {};
850 opts.reserve(options.size());
851 for (auto &opt : options) {
852 opts.emplace_back(opt.name);
853 }
854 return opts;
855 }
856
857 void apply_config(std::unordered_map<std::string, std::string> &&vars) {
858 normalize_input_config_alias(vars);
859 if (!fs::exists(stream.file_apps.c_str())) {
860 fs::copy_file(HERMES_ASSETS_DIR "/apps.json", stream.file_apps);
861 }
862
863 for (auto &[name, val] : vars) {
864 BOOST_LOG(info) << "config: ["sv << name << "] -- ["sv << val << ']';
865 modified_config_settings[name] = val;
866 }
867
868 bool_f(vars, "headless_mode", video.headless_mode);
869 bool_f(vars, "limit_framerate", video.limit_framerate);
870 bool_f(vars, "double_refreshrate", video.double_refreshrate);
871 int_f(vars, "qp", video.qp);
872 int_between_f(vars, "hevc_mode", video.hevc_mode, {0, 3});
873 int_between_f(vars, "av1_mode", video.av1_mode, {0, 3});
874 int_f(vars, "min_threads", video.min_threads);
875 string_f(vars, "sw_preset", video.sw.sw_preset);
876 if (!video.sw.sw_preset.empty()) {
877 video.sw.svtav1_preset = sw::svtav1_preset_from_view(video.sw.sw_preset);
878 }
879 string_f(vars, "sw_tune", video.sw.sw_tune);
880
881 int_between_f(vars, "nvenc_preset", video.nv.quality_preset, {1, 7});
882 int_between_f(vars, "nvenc_vbv_increase", video.nv.vbv_percentage_increase, {0, 400});
883 bool_f(vars, "nvenc_spatial_aq", video.nv.adaptive_quantization);
884 generic_f(vars, "nvenc_twopass", video.nv.two_pass, nv::twopass_from_view);
885 bool_f(vars, "nvenc_h264_cavlc", video.nv.h264_cavlc);
886 bool_f(vars, "nvenc_intra_refresh", video.nv.intra_refresh);
887
888 video.nv_legacy.preset = video.nv.quality_preset + 11;
889 video.nv_legacy.multipass = video.nv.two_pass == nvenc::nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION :
890 video.nv.two_pass == nvenc::nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION :
891 NV_ENC_MULTI_PASS_DISABLED;
892 video.nv_legacy.h264_coder = video.nv.h264_cavlc ? NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC : NV_ENC_H264_ENTROPY_CODING_MODE_CABAC;
893 video.nv_legacy.aq = video.nv.adaptive_quantization;
894 video.nv_legacy.vbv_percentage_increase = video.nv.vbv_percentage_increase;
895
896 int_between_f(vars, "default_scale_factor", video.default_scale_factor, {20, 200});
897
898 bool_f(vars, "vaapi_strict_rc_buffer", video.vaapi.strict_rc_buffer);
899 int_between_f(vars, "vaapi_quality", video.vaapi.quality, {-1, 8});
900 bool_f(vars, "vaapi_intra_refresh", video.vaapi.intra_refresh);
901
902 string_f(vars, "capture", video.capture);
903 string_f(vars, "encoder", video.encoder);
904 string_f(vars, "adapter_name", video.adapter_name);
905 string_f(vars, "output_name", video.output_name);
906 string_restricted_f(vars, "virtual_display_backend", video.virtual_display_backend, {"evdi"sv, "hermes_kms"sv, "none"sv, "headless"sv});
907 // The container image wrote "headless" for the wlroots-headless fallback
908 // before there was a value for "this host has no virtual-display device".
909 // It was never accepted, so those installs silently ran as EVDI and were
910 // told to install a driver they had no use for. Keep reading it, under the
911 // one name the rest of Hermes has to know.
912 if (video.virtual_display_backend == "headless") {
913 video.virtual_display_backend = "none";
914 }
915 bool_f(vars, "hermes_kms_multi_output", video.hermes_kms_multi_output);
916 bool_f(vars, "hermes_kms_isolated_sessions", video.hermes_kms_isolated_sessions);
917 string_restricted_f(vars, "gamescope_backend", video.gamescope_backend, {"auto"sv, "wayland"sv, "sdl"sv, "drm"sv});
918 // Deliberately unrestricted: plasma is the user's own desktop, weston and
919 // labwc are the profiles Hermes ships as opt-in fallbacks, and any other
920 // name is a profile the administrator dropped in themselves.
921 string_f(vars, "hermes_kms_session_compositor", video.hermes_kms_session_compositor);
922 string_restricted_f(vars, "isolation_method", video.isolation_method, {"gamescope"sv, "kwin_virtual"sv});
923
924 generic_f(vars, "dd_configuration_option", video.dd.configuration_option, dd::config_option_from_view);
925 generic_f(vars, "dd_resolution_option", video.dd.resolution_option, dd::resolution_option_from_view);
926 string_f(vars, "dd_manual_resolution", video.dd.manual_resolution);
927 generic_f(vars, "dd_refresh_rate_option", video.dd.refresh_rate_option, dd::refresh_rate_option_from_view);
928 string_f(vars, "dd_manual_refresh_rate", video.dd.manual_refresh_rate);
929 generic_f(vars, "dd_hdr_option", video.dd.hdr_option, dd::hdr_option_from_view);
930 {
931 int value = -1;
932 int_between_f(vars, "dd_config_revert_delay", value, {0, std::numeric_limits<int>::max()});
933 if (value >= 0) {
934 video.dd.config_revert_delay = std::chrono::milliseconds {value};
935 }
936 }
937 bool_f(vars, "dd_config_revert_on_disconnect", video.dd.config_revert_on_disconnect);
938 generic_f(vars, "dd_mode_remapping", video.dd.mode_remapping, dd::mode_remapping_from_view);
939 {
940 int value = 0;
941 int_between_f(vars, "dd_wa_hdr_toggle_delay", value, {0, 3000});
942 video.dd.wa.hdr_toggle_delay = std::chrono::milliseconds {value};
943 }
944
945 int_f(vars, "max_bitrate", video.max_bitrate);
946 double_between_f(vars, "minimum_fps_target", video.minimum_fps_target, {0.0, 1000.0});
947
948 string_f(vars, "fallback_mode", video.fallback_mode);
949 bool_f(vars, "isolated_virtual_display_option", video.isolated_virtual_display_option);
950 bool_f(vars, "ignore_encoder_probe_failure", video.ignore_encoder_probe_failure);
951 bool_f(vars, "pyrowave", video.pyrowave);
952
953 path_f(vars, "pkey", nvhttp.pkey);
954 path_f(vars, "cert", nvhttp.cert);
955 string_f(vars, "sunshine_name", nvhttp.sunshine_name);
956 path_f(vars, "log_path", config::sunshine.log_file);
957 path_f(vars, "file_state", nvhttp.file_state);
958
959 // Must be run after "file_state"
960 config::sunshine.credentials_file = config::nvhttp.file_state;
961 path_f(vars, "credentials_file", config::sunshine.credentials_file);
962
963 string_f(vars, "external_ip", nvhttp.external_ip);
964 list_prep_cmd_f(vars, "global_prep_cmd", config::sunshine.prep_cmds);
965 list_prep_cmd_f(vars, "global_state_cmd", config::sunshine.state_cmds);
966 list_server_cmd_f(vars, "server_cmd", config::sunshine.server_cmds);
967
968 string_f(vars, "audio_sink", audio.sink);
969 bool_f(vars, "stream_audio", audio.stream);
970 bool_f(vars, "stream_mic", audio.stream_mic);
971 bool_f(vars, "keep_sink_default", audio.keep_default);
972 bool_f(vars, "auto_capture_sink", audio.auto_capture);
973
974 string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv});
975
976 int to = -1;
977 int_between_f(vars, "ping_timeout", to, {-1, std::numeric_limits<int>::max()});
978 if (to != -1) {
979 stream.ping_timeout = std::chrono::milliseconds(to);
980 }
981
982 int_between_f(vars, "lan_encryption_mode", stream.lan_encryption_mode, {0, 2});
983 int_between_f(vars, "wan_encryption_mode", stream.wan_encryption_mode, {0, 2});
984
985 path_f(vars, "file_apps", stream.file_apps);
986 int_between_f(vars, "fec_percentage", stream.fec_percentage, {1, 255});
987 bool_f(vars, "adaptive_fec", stream.adaptive_fec);
988 int_between_f(vars, "adaptive_fec_max_percentage", stream.adaptive_fec_max_percentage, {1, 50});
989
990 map_int_int_f(vars, "keybindings"s, input.keybindings);
991
992 // This config option will only be used by the UI
993 // When editing in the config file itself, use "keybindings"
994 bool map_rightalt_to_win = false;
995 bool_f(vars, "key_rightalt_to_key_win", map_rightalt_to_win);
996
997 if (map_rightalt_to_win) {
998 input.keybindings.emplace(0xA5, 0x5B);
999 }
1000
1001 to = std::numeric_limits<int>::min();
1002 int_f(vars, "back_button_timeout", to);
1003
1004 if (to > std::numeric_limits<int>::min()) {
1005 input.back_button_timeout = std::chrono::milliseconds {to};
1006 }
1007
1008 double repeat_frequency {0};
1009 double_between_f(vars, "key_repeat_frequency", repeat_frequency, {0, std::numeric_limits<double>::max()});
1010
1011 if (repeat_frequency > 0) {
1012 config::input.key_repeat_period = std::chrono::duration<double> {1 / repeat_frequency};
1013 }
1014
1015 to = -1;
1016 int_f(vars, "key_repeat_delay", to);
1017 if (to >= 0) {
1018 input.key_repeat_delay = std::chrono::milliseconds {to};
1019 }
1020
1021 string_restricted_f(vars, "gamepad"s, input.gamepad, get_supported_gamepad_options());
1022 string_restricted_f(vars, "linux_gamepad_backend"s, input.linux_gamepad_backend, {"auto"sv, "native"sv, "uinput"sv});
1023 bool_f(vars, "ds4_back_as_touchpad_click", input.ds4_back_as_touchpad_click);
1024 bool_f(vars, "motion_as_ds4", input.motion_as_ds4);
1025 bool_f(vars, "touchpad_as_ds4", input.touchpad_as_ds4);
1026 bool_f(vars, "virtualhid_randomize_mac", input.virtualhid_randomize_mac);
1027
1028 bool_f(vars, "mouse", input.mouse);
1029 bool_f(vars, "keyboard", input.keyboard);
1030 bool_f(vars, "controller", input.controller);
1031
1032
1033 bool_f(vars, "high_resolution_scrolling", input.high_resolution_scrolling);
1034 bool_f(vars, "native_pen_touch", input.native_pen_touch);
1035 bool_f(vars, "isolated_ignore_mouse_wiggle", input.isolated_ignore_mouse_wiggle);
1036 bool_f(vars, "isolated_hide_hid_gamepads", input.isolated_hide_hid_gamepads);
1037 bool_f(vars, "virtualhid_stable_mac", input.virtualhid_stable_mac);
1038 bool_f(vars, "enable_input_only_mode", input.enable_input_only_mode);
1039
1040 bool_f(vars, "system_tray", sunshine.system_tray);
1041 bool_f(vars, "hide_tray_controls", sunshine.hide_tray_controls);
1042 bool_f(vars, "inhibit_screen_lock", sunshine.inhibit_screen_lock);
1043 bool_f(vars, "enable_pairing", sunshine.enable_pairing);
1044 bool_f(vars, "enable_discovery", sunshine.enable_discovery);
1045 bool_f(vars, "envvar_compatibility_mode", sunshine.envvar_compatibility_mode);
1046 bool_f(vars, "appliance_mode", sunshine.appliance_mode);
1047 bool_f(vars, "notify_pre_releases", sunshine.notify_pre_releases);
1048 bool_f(vars, "announcements", sunshine.announcements);
1049 bool_f(vars, "legacy_ordering", sunshine.legacy_ordering);
1050 bool_f(vars, "forward_rumble", input.forward_rumble);
1051
1052 int port = sunshine.port;
1053 int_between_f(vars, "port"s, port, {1024 + nvhttp::PORT_HTTPS, 65535 - rtsp_stream::RTSP_SETUP_PORT});
1054 sunshine.port = (std::uint16_t) port;
1055
1056 string_restricted_f(vars, "address_family", sunshine.address_family, {"ipv4"sv, "both"sv});
1057
1058 bool upnp = false;
1059 bool_f(vars, "upnp"s, upnp);
1060
1061 if (upnp) {
1062 config::sunshine.flags[config::flag::UPNP].flip();
1063 }
1064
1065 string_restricted_f(vars, "locale", config::sunshine.locale, {
1066 "bg"sv, // Bulgarian
1067 "cs"sv, // Czech
1068 "de"sv, // German
1069 "en"sv, // English
1070 "en_GB"sv, // English (UK)
1071 "en_US"sv, // English (US)
1072 "es"sv, // Spanish
1073 "fr"sv, // French
1074 "hu"sv, // Hungarian
1075 "it"sv, // Italian
1076 "ja"sv, // Japanese
1077 "ko"sv, // Korean
1078 "pl"sv, // Polish
1079 "pt"sv, // Portuguese
1080 "pt_BR"sv, // Portuguese (Brazilian)
1081 "ru"sv, // Russian
1082 "sv"sv, // Swedish
1083 "tr"sv, // Turkish
1084 "uk"sv, // Ukrainian
1085 "vi"sv, // Vietnamese
1086 "zh"sv, // Chinese
1087 "zh_TW"sv, // Chinese (Traditional)
1088 });
1089
1090 std::string log_level_string;
1091 string_f(vars, "min_log_level", log_level_string);
1092
1093 if (!log_level_string.empty()) {
1094 if (log_level_string == "verbose"sv) {
1095 sunshine.min_log_level = 0;
1096 } else if (log_level_string == "debug"sv) {
1097 sunshine.min_log_level = 1;
1098 } else if (log_level_string == "info"sv) {
1099 sunshine.min_log_level = 2;
1100 } else if (log_level_string == "warning"sv) {
1101 sunshine.min_log_level = 3;
1102 } else if (log_level_string == "error"sv) {
1103 sunshine.min_log_level = 4;
1104 } else if (log_level_string == "fatal"sv) {
1105 sunshine.min_log_level = 5;
1106 } else if (log_level_string == "none"sv) {
1107 sunshine.min_log_level = 6;
1108 } else {
1109 // accept digit directly
1110 auto val = log_level_string[0];
1111 if (val >= '0' && val < '7') {
1112 sunshine.min_log_level = val - '0';
1113 }
1114 }
1115 }
1116
1117 auto it = vars.find("flags"s);
1118 if (it != std::end(vars)) {
1119 apply_flags(it->second.c_str());
1120
1121 vars.erase(it);
1122 }
1123
1124 for (const auto &key : server_computed_keys()) {
1125 vars.erase(key);
1126 }
1127
1128 if (sunshine.min_log_level <= 3) {
1129 for (auto &[var, _] : vars) {
1130 std::cout << "Warning: Unrecognized configurable option ["sv << var << ']' << std::endl;
1131 }
1132 }
1133
1134 ::video::active_hevc_mode = video.hevc_mode;
1135 ::video::active_av1_mode = video.av1_mode;
1136 }
1137
1138 int parse(int argc, char *argv[]) {
1139 std::unordered_map<std::string, std::string> cmd_vars;
1140
1141 for (auto x = 1; x < argc; ++x) {
1142 auto line = argv[x];
1143
1144 if (line == "--help"sv) {
1145 logging::print_help(*argv);
1146 return 1;
1147 }
1148 else if (*line == '-') {
1149 if (*(line + 1) == '-') {
1150 sunshine.cmd.name = line + 2;
1151 sunshine.cmd.argc = argc - x - 1;
1152 sunshine.cmd.argv = argv + x + 1;
1153
1154 break;
1155 }
1156 if (apply_flags(line + 1)) {
1157 logging::print_help(*argv);
1158 return -1;
1159 }
1160 } else {
1161 auto line_end = line + strlen(line);
1162
1163 auto pos = std::find(line, line_end, '=');
1164 if (pos == line_end) {
1165 sunshine.config_file = line;
1166 } else {
1167 TUPLE_EL(var, 1, parse_option(line, line_end));
1168 if (!var) {
1169 logging::print_help(*argv);
1170 return -1;
1171 }
1172
1173 TUPLE_EL_REF(name, 0, *var);
1174
1175 auto it = cmd_vars.find(name);
1176 if (it != std::end(cmd_vars)) {
1177 cmd_vars.erase(it);
1178 }
1179
1180 cmd_vars.emplace(std::move(*var));
1181 }
1182 }
1183 }
1184
1185 bool config_loaded = false;
1186 try {
1187 // Create appdata folder if it does not exist
1188 file_handler::make_directory(platf::appdata().string());
1189
1190 // Create empty config file if it does not exist
1191 if (!fs::exists(sunshine.config_file)) {
1192 auto cfg_file = std::ofstream {sunshine.config_file};
1193 }
1194
1195 // Read config file
1196 auto vars = parse_config(file_handler::read_file(sunshine.config_file.c_str()));
1197
1198 for (auto &[name, value] : cmd_vars) {
1199 vars.insert_or_assign(std::move(name), std::move(value));
1200 }
1201
1202 // Apply the config. Note: This will try to create any paths
1203 // referenced in the config, so we may receive exceptions if
1204 // the path is incorrect or inaccessible.
1205 apply_config(std::move(vars));
1206 config_loaded = true;
1207 } catch (const std::filesystem::filesystem_error &err) {
1208 BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what();
1209 } catch (const boost::filesystem::filesystem_error &err) {
1210 BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what();
1211 }
1212
1213 if (!config_loaded) {
1214 return -1;
1215 }
1216
1217
1218 return 0;
1219 }
1220} // namespace config
1221
Declarations for common platform specific utilities.
std::vector< supported_gamepad_t > & supported_gamepads(input_t *input)
Gets the supported gamepads for this platform backend.
std::string get_host_name()
Returns the current computer name in UTF-8.
Definition misc.cpp:1533
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:301
const std::set< std::string > & server_computed_keys()
Keys the Web UI's config response carries but that are never configuration: server-computed status,...
Definition config.cpp:407
Declarations for the configuration of Sunshine.
@ UPNP
Try Universal Plug 'n Play.
Definition config.h:211
@ FRESH_STATE
Do not load or save state.
Definition config.h:209
@ PIN_STDIN
Read PIN from stdin instead of http.
Definition config.h:208
@ FORCE_VIDEO_HEADER_REPLACE
force replacing headers inside video data
Definition config.h:210
Declarations for entry handling functions.
Declarations for file handling functions.
Declarations for logging related functions.
std::string read_file(const char *path)
Read a file to string.
bool make_directory(const std::string &path)
Make a directory.
void print_help(const char *name)
Print help to stdout.
Definition logging.cpp:211
nvenc_two_pass
Definition nvenc_config.h:9
@ disabled
Single pass, the fastest and no extra vram.
@ full_resolution
Better overall statistics, slower and uses more extra vram.
@ quarter_resolution
Larger motion vectors being caught, faster and uses less extra vram.
constexpr auto PORT_HTTPS
The HTTPS port, as a difference from the config port.
Definition nvhttp.h:54
Declarations for the nvhttp (GameStream) server.
Declarations for RTSP streaming.
@ disabled
Do not change refresh rate.
Definition config.h:89
@ automatic
Change refresh rate and use the one received from Moonlight.
Definition config.h:90
@ disabled
Do not change HDR settings.
Definition config.h:95
@ automatic
Change HDR settings and use the state requested by Moonlight.
Definition config.h:96
@ disabled
Disable the configuration for the device.
Definition config.h:75
@ disabled
Do not change resolution.
Definition config.h:83
@ automatic
Change resolution and use the one received from Moonlight.
Definition config.h:84
Declarations for utility functions.
Declarations for video.