Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <algorithm>
7#include <codecvt>
8#include <csignal>
9#include <fstream>
10#include <iostream>
11
12// local includes
13#include "confighttp.h"
14#include "display_device.h"
15#include "entry_handler.h"
16#include "globals.h"
17#include "httpcommon.h"
18#include "logging.h"
19#include "main.h"
20#include "nvhttp.h"
21#include "process.h"
22#include "system_tray.h"
23#include "upnp.h"
24#include "uuid.h"
25#include "video.h"
26
30
31 #include <boost/log/core.hpp>
32
33#define PROBE_DISPLAY_UUID "38F72B96-B00C-4F21-8B6C-E1BFF1602B0E"
34
35extern "C" {
36#include "rswrapper.h"
37}
38
39using namespace std::literals;
40
41std::map<int, std::function<void()>> signal_handlers;
42
43void on_signal_forwarder(int sig) {
44 signal_handlers.at(sig)();
45}
46
47template<class FN>
48void on_signal(int sig, FN &&fn) {
49 signal_handlers.emplace(sig, std::forward<FN>(fn));
50
51 std::signal(sig, on_signal_forwarder);
52}
53
54std::map<std::string_view, std::function<int(const char *name, int argc, char **argv)>> cmd_to_func {
55 {"creds"sv, [](const char *name, int argc, char **argv) {
56 return args::creds(name, argc, argv);
57 }},
58 {"help"sv, [](const char *name, int argc, char **argv) {
59 return args::help(name);
60 }},
61 {"version"sv, [](const char *name, int argc, char **argv) {
62 return args::version();
63 }},
64};
65
66
67#if defined HERMES_TRAY && HERMES_TRAY >= 1
68constexpr bool tray_is_enabled = true;
69#else
70constexpr bool tray_is_enabled = false;
71#endif
72
73void mainThreadLoop(const std::shared_ptr<safe::event_t<bool>> &shutdown_event) {
74 bool run_loop = false;
75
76 // Conditions that would require the main thread event loop
77 run_loop = tray_is_enabled;
78
79 if (!run_loop) {
80 BOOST_LOG(info) << "No main thread features enabled, skipping event loop"sv;
81 return;
82 }
83
84 // Main thread event loop
85 BOOST_LOG(info) << "Starting main loop"sv;
86 while (true) {
87 if (shutdown_event->peek()) {
88 BOOST_LOG(info) << "Shutdown event detected, breaking main loop"sv;
89 if (tray_is_enabled && config::sunshine.system_tray) {
91 }
92 break;
93 }
94
95 if (tray_is_enabled) {
97 }
98
99 // Sleep to avoid busy waiting
100 std::this_thread::sleep_for(std::chrono::milliseconds(50));
101 }
102}
103
104int main(int argc, char *argv[]) {
105 lifetime::argv = argv;
106
107 task_pool_util::TaskPool::task_id_t force_shutdown = nullptr;
108
109
110#pragma GCC diagnostic push
111#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
112 // Use UTF-8 conversion for the default C++ locale (used by boost::log)
113 std::locale utf8_locale(std::locale(), new std::codecvt_utf8<wchar_t>);
114 std::locale::global(utf8_locale);
115 boost::filesystem::path::imbue(utf8_locale);
116#pragma GCC diagnostic pop
117
118 mail::man = std::make_shared<safe::mail_raw_t>();
119
120 // `--prelogin` answers on the terminal and nowhere else. Reading the
121 // configuration logs every setting, and starting the log rotates the log
122 // file - of a Hermes that is very likely running while this is asked.
123 const bool prelogin_command = std::any_of(argv + 1, argv + argc, [](const char *argument) {
124 return argument == "--prelogin"sv;
125 });
126 if (prelogin_command) {
127 boost::log::core::get()->set_logging_enabled(false);
128 }
129
130 // parse config file
131 if (config::parse(argc, argv)) {
132 return 0;
133 }
134
135 if (prelogin_command && config::sunshine.cmd.name == "prelogin"sv) {
136 return platf::prelogin::command(argv[0], config::sunshine.cmd.argc, config::sunshine.cmd.argv);
137 }
138
139 auto log_deinit_guard = logging::init(config::sunshine.min_log_level, config::sunshine.log_file);
140 if (!log_deinit_guard) {
141 BOOST_LOG(error) << "Logging failed to initialize"sv;
142 }
143
144 // logging can begin at this point
145 // if anything is logged prior to this point, it will appear in stdout, but not in the log viewer in the UI
146 // the version should be printed to the log before anything else
147 BOOST_LOG(info) << PROJECT_NAME << " version: " << PROJECT_VERSION << " commit: " << PROJECT_VERSION_COMMIT;
148
149 // Log publisher metadata
151
152 // Log modified_config_settings
153 for (auto &[name, val] : config::modified_config_settings) {
154 BOOST_LOG(info) << "config: '"sv << name << "' = "sv << val;
155 }
156 config::modified_config_settings.clear();
157
158 if (!config::sunshine.cmd.name.empty()) {
159 auto fn = cmd_to_func.find(config::sunshine.cmd.name);
160 if (fn == std::end(cmd_to_func)) {
161 BOOST_LOG(fatal) << "Unknown command: "sv << config::sunshine.cmd.name;
162
163 BOOST_LOG(info) << "Possible commands:"sv;
164 for (auto &[key, _] : cmd_to_func) {
165 BOOST_LOG(info) << '\t' << key;
166 }
167
168 return 7;
169 }
170
171 return fn->second(argv[0], config::sunshine.cmd.argc, config::sunshine.cmd.argv);
172 }
173
174 // Adding guard here first as it also performs recovery after crash,
175 // otherwise people could theoretically end up without display output.
176 // It also should be destroyed before forced shutdown to expedite the cleanup.
177 auto display_device_deinit_guard = display_device::init(platf::appdata() / "display_device.state", config::video);
178 if (!display_device_deinit_guard) {
179 BOOST_LOG(error) << "Display device session failed to initialize"sv;
180 }
181
182
183 task_pool.start(1);
184
185 // Create signal handler after logging has been initialized
186 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
187 on_signal(SIGINT, [&force_shutdown, &display_device_deinit_guard, shutdown_event]() {
188 BOOST_LOG(info) << "Interrupt handler called"sv;
189
190 auto task = []() {
191 BOOST_LOG(fatal) << "10 seconds passed, yet Hermes is still running: Forcing shutdown"sv;
194 };
195
196 proc::proc.terminate();
197
198 force_shutdown = task_pool.pushDelayed(task, 10s).task_id;
199
200 shutdown_event->raise(true);
201 display_device_deinit_guard = nullptr;
202 });
203
204 on_signal(SIGTERM, [&force_shutdown, &display_device_deinit_guard, shutdown_event]() {
205 BOOST_LOG(info) << "Terminate handler called"sv;
206
207 auto task = []() {
208 BOOST_LOG(fatal) << "10 seconds passed, yet Hermes is still running: Forcing shutdown"sv;
211 };
212 force_shutdown = task_pool.pushDelayed(task, 10s).task_id;
213
214 shutdown_event->raise(true);
215 display_device_deinit_guard = nullptr;
216 });
217
218
219 proc::refresh(config::stream.file_apps);
220
221 // If any of the following fail, we log an error and continue event though sunshine will not function correctly.
222 // This allows access to the UI to fix configuration problems or view the logs.
223
225
226 auto platf_deinit_guard = platf::init();
227 if (!platf_deinit_guard) {
228 BOOST_LOG(error) << "Platform failed to initialize"sv;
229 }
230
231 auto proc_deinit_guard = proc::init();
232 if (!proc_deinit_guard) {
233 BOOST_LOG(error) << "Proc failed to initialize"sv;
234 }
235
236 // Initialize virtual display driver early so clients know it's supported
238
239 // Say what this session can and cannot do before anything depends on it. A
240 // virtual-display feature that is unavailable here is almost always a
241 // configuration a user can fix, and the alternative to saying so at startup
242 // is that they find out from a black stream.
245
247 auto input_deinit_guard = input::init();
248
249 if (input::probe_gamepads()) {
250 BOOST_LOG(warning) << "No gamepad input is available"sv;
251 }
252
253 // A host with no monitor has nothing to probe until a virtual display stands
254 // in, so go straight to one. Probing first would fail and log the fatal "no
255 // display" error - which the Web UI shows as a startup failure - before the
256 // fallback below had even run.
257 const bool display_present = video::display_present();
258 // Started before anyone logged in, with no monitor, the only thing on screen
259 // is the login greeter. SDDM's greeter quits for good when its last output
260 // goes away, so the probe display's removal would leave nothing for the
261 // first client to log in on. Leave the greeter alone: the first session
262 // probes on the display it brings up.
263 const bool defer_probe = !display_present && !VDISPLAY::windowSystemAttached();
264 if (defer_probe) {
265 BOOST_LOG(info) << "No monitor is lit and no graphical session is attached; "
266 "probing encoders when the first session brings up its virtual display."sv;
267 }
268 if (!defer_probe && (!display_present || video::probe_encoders())) {
269 // No screen could be opened - typically because every monitor is asleep.
270 // A temporary virtual output would be a monitor plugged in and unplugged,
271 // which wakes every display the compositor drives, at every start of
272 // Hermes. An encoder does not depend on a screen, so validate it on a
273 // display with nothing behind it instead.
274 BOOST_LOG(info) << "No screen to probe encoders on; probing them without one."sv;
276 BOOST_LOG(error) << "Video failed to find working encoder: allow probing but failed"sv;
277 }
278 }
279
280 if (http::init()) {
281 BOOST_LOG(fatal) << "HTTP interface failed to initialize"sv;
282
283
284 return -1;
285 }
286
287 std::unique_ptr<platf::deinit_t> mDNS;
288 auto sync_mDNS = std::async(std::launch::async, [&mDNS]() {
289 if (config::sunshine.enable_discovery) {
290 mDNS = platf::publish::start();
291 }
292 });
293
294 std::unique_ptr<platf::deinit_t> upnp_unmap;
295 auto sync_upnp = std::async(std::launch::async, [&upnp_unmap]() {
296 upnp_unmap = upnp::start();
297 });
298
299 // FIXME: Temporary workaround: Simple-Web_server needs to be updated or replaced
300 if (shutdown_event->peek()) {
301 return lifetime::desired_exit_code;
302 }
303
304 std::thread httpThread {nvhttp::start};
305 std::thread configThread {confighttp::start};
306 std::thread rtspThread {rtsp_stream::start};
307
308 // Started at boot, before anyone logged in, Hermes joins the graphical
309 // session once there is one and no client is in the way.
310 auto session_attach_guard = platf::session_attach::start();
311
312
313 if (tray_is_enabled && config::sunshine.system_tray) {
314 BOOST_LOG(info) << "Starting system tray"sv;
316 }
317
318 mainThreadLoop(shutdown_event);
319
320 // Wait for shutdown, this is not necessary when we're using the main event loop
321 shutdown_event->view();
322
323 httpThread.join();
324 configThread.join();
325 rtspThread.join();
326
327 task_pool.stop();
328 task_pool.join();
329
330
331 return lifetime::desired_exit_code;
332}
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:301
void start()
Start the HTTPS server.
Declarations for the Web UI Config HTTP server.
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).
Declarations for display device handling.
void log_publisher_data()
Log the publisher metadata provided from CMake.
Declarations for entry handling functions.
thread_pool_util::ThreadPool task_pool
A thread pool for processing tasks.
Definition globals.cpp:9
Declarations for globally accessible variables and functions.
Declarations for common HTTP.
Declarations for logging related functions.
int main(int argc, char *argv[])
Main application entry point.
Definition main.cpp:104
Declarations for the main entry point for Sunshine.
int creds(const char *name, int argc, char *argv[])
Reset the user credentials.
int version()
Print the version to stdout, then exit.
int help(const char *name)
Print help to stdout, then exit.
void debug_trap()
Breaks into the debugger or terminates Sunshine if no debugger is attached.
std::unique_ptr< deinit_t > init(int min_log_level, const std::string &log_file)
Initialize the logging system.
Definition logging.cpp:104
void log_flush()
Flush the log.
Definition logging.cpp:205
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
void start()
Start the nvhttp server.
Definition nvhttp.cpp:2241
Handles the system tray icon and notification system.
int init_tray()
Initializes the system tray without starting a loop.
int process_tray_events()
Processes a single tray event iteration.
int end_tray()
Exit the system tray.
std::unique_ptr< platf::deinit_t > start()
Start UPnP port mapping and return its shutdown guard.
Definition upnp.cpp:743
Declarations for the nvhttp (GameStream) server.
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Definition prelogin.cpp:632
void log_report()
Say at startup what stands between this host and being reachable before login. Silent unless Hermes i...
Definition prelogin.cpp:613
Set up and check what it takes for Hermes to be reachable before login.
std::unique_ptr< platf::deinit_t > init()
Initialize proc functions.
Definition process.cpp:1601
void initVDisplayDriver()
Initialize the virtual display driver. This should be called early in startup to enable virtual displ...
Definition process.cpp:1580
Declarations for the startup and shutdown of the apps started by a streaming Session.
#define reed_solomon_init
This initializes the RS function pointers to the best vectorized version available.
Definition rswrapper.c:118
Wrappers for nanors vectorization.
void start()
Runs the RTSP server loop.
Definition rtsp.cpp:1413
void drop_stale_display_environment()
Forget display variables that point at a display server that is gone.
std::unique_ptr< platf::deinit_t > start()
Start watching for a session to attach to.
Let a Hermes that started before the graphical session catch up with it.
Declarations for the system tray icon and notification system.
Declarations for UPnP port mapping.
Declarations for UUID generation.
bool display_present()
Whether the host has a display to capture without creating one.
Definition video.cpp:52
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
Definition video.cpp:3232
int probe_encoders_without_display()
Probe encoders without opening any screen.
Definition video.cpp:3224
Declarations for video.
bool windowSystemAttached()
Whether Hermes runs inside a graphical session (Wayland or X11).
void logSessionAssessment()
Probe, assess and log what this session can and cannot do.
Virtual display declarations for Linux.