-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
310 lines (267 loc) · 12.1 KB
/
Copy pathmain.cpp
File metadata and controls
310 lines (267 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
* @file src/main.cpp
* @brief Runs the Moonlight Xbox startup sequence and main loop.
*/
// nxdk includes
#include <hal/debug.h>
#include <SDL.h>
#include <windows.h> // NOSONAR(cpp:S3806) nxdk requires lowercase header names
// standard includes
#include <algorithm>
#include <array>
#include <atomic>
#include <cstdio>
#include <string>
#include <vector>
// local includes
#include "src/app/client_state.h"
#include "src/app/settings_storage.h"
#include "src/logging/log_file.h"
#include "src/logging/logger.h"
#include "src/network/runtime_network.h"
#include "src/splash/splash_screen.h"
#include "src/startup/host_storage.h"
#include "src/startup/memory_stats.h"
#include "src/startup/video_mode.h"
#include "src/ui/shell_screen.h"
namespace {
struct StartupTaskState {
SDL_Thread *thread = nullptr;
std::atomic<bool> completed = false;
startup::LoadSavedHostsResult loadedHosts;
network::RuntimeNetworkStatus runtimeNetworkStatus;
};
void apply_persisted_settings(app::ClientState &state, const app::AppSettings &settings) {
state.settings.loggingLevel = settings.loggingLevel;
state.settings.xemuConsoleLoggingLevel = settings.xemuConsoleLoggingLevel;
state.settings.logViewerPlacement = settings.logViewerPlacement;
state.settings.preferredVideoMode = settings.preferredVideoMode;
state.settings.preferredVideoModeSet = settings.preferredVideoModeSet;
state.settings.streamFramerate = settings.streamFramerate;
state.settings.streamBitrateKbps = settings.streamBitrateKbps;
state.settings.videoDecoder = settings.videoDecoder;
state.settings.playAudioOnPc = settings.playAudioOnPc;
state.settings.showPerformanceStats = settings.showPerformanceStats;
state.settings.playAudioOnXbox = settings.playAudioOnXbox;
state.settings.dirty = false;
}
/**
* @brief Return whether two stream-resolution entries target the same width and height.
*
* @param left First stream-resolution entry to compare.
* @param right Second stream-resolution entry to compare.
* @return True when both entries describe the same stream resolution.
*/
bool stream_resolutions_match(const VIDEO_MODE &left, const VIDEO_MODE &right) {
return left.width == right.width && left.height == right.height;
}
/**
* @brief Finalize the preferred stream resolution after startup detection.
*
* @param state Mutable client state receiving detected Xbox video modes.
* @param selection Detected Xbox output modes and preferred startup mode.
* @param encoderSettings Active Xbox video encoder settings.
*/
void initialize_stream_video_mode_settings(app::ClientState &state, const startup::VideoModeSelection &selection, DWORD encoderSettings) {
state.settings.availableVideoModes = startup::filter_stream_video_modes_for_encoder_settings(selection.availableVideoModes, encoderSettings);
if (state.settings.availableVideoModes.empty()) {
state.settings.preferredVideoMode = {};
state.settings.preferredVideoModeSet = false;
return;
}
if (const auto preferredMode = std::find_if(state.settings.availableVideoModes.begin(), state.settings.availableVideoModes.end(), [&state](const VIDEO_MODE &candidate) {
return stream_resolutions_match(candidate, state.settings.preferredVideoMode);
});
state.settings.preferredVideoModeSet && preferredMode != state.settings.availableVideoModes.end()) {
state.settings.preferredVideoMode = *preferredMode;
return;
}
state.settings.preferredVideoMode = startup::choose_default_stream_video_mode(state.settings.availableVideoModes, selection.bestVideoMode);
state.settings.preferredVideoModeSet = state.settings.preferredVideoMode.width > 0 && state.settings.preferredVideoMode.height > 0;
}
void load_persisted_settings(app::ClientState &state) {
const app::LoadAppSettingsResult loadResult = app::load_app_settings();
apply_persisted_settings(state, loadResult.settings);
for (const std::string &warning : loadResult.warnings) {
logging::warn("settings", warning);
}
if (!loadResult.fileFound) {
logging::info("settings", "No persisted settings file found. Using defaults.");
return;
}
logging::info("settings", "Loaded persisted Moonlight settings");
if (!loadResult.cleanupRequired) {
return;
}
const app::SaveAppSettingsResult saveResult = app::save_app_settings(loadResult.settings);
if (saveResult.success) {
logging::info("settings", "Removed obsolete settings keys from the persisted configuration");
return;
}
logging::warn("settings", saveResult.errorMessage.empty() ? "Failed to rewrite the settings file after cleaning obsolete keys" : saveResult.errorMessage);
}
int report_startup_failure(const char *category, const std::string &message) {
logging::error(category, message);
logging::print_startup_console_line(logging::LogLevel::warning, category, "Holding failure screen for 5 seconds before exit.");
Sleep(5000);
return 1;
}
void debug_print_startup_checkpoint(const char *message) {
if (message == nullptr) {
return;
}
logging::print_startup_console_line(logging::LogLevel::info, "startup", message);
}
void debug_print_video_mode_selection(const startup::VideoModeSelection &selection) {
logging::print_startup_console_line(
logging::LogLevel::info,
"video",
"Detected " + std::to_string(selection.availableVideoModes.size()) + " video mode(s)"
);
for (const std::string &line : startup::format_video_mode_lines(selection)) {
logging::print_startup_console_line(logging::LogLevel::info, "video", line);
}
}
void debug_print_encoder_settings(DWORD encoderSettings) {
std::array<char, 160> messageBuffer {};
std::snprintf(
messageBuffer.data(),
messageBuffer.size(),
"Encoder settings: 0x%08lX (widescreen=%s, 480p=%s, 720p=%s, 1080i=%s)",
encoderSettings,
(encoderSettings & VIDEO_WIDESCREEN) != 0 ? "on" : "off",
(encoderSettings & VIDEO_MODE_480P) != 0 ? "on" : "off",
(encoderSettings & VIDEO_MODE_720P) != 0 ? "on" : "off",
(encoderSettings & VIDEO_MODE_1080I) != 0 ? "on" : "off"
);
logging::print_startup_console_line(logging::LogLevel::info, "video", messageBuffer.data());
}
int run_startup_task(void *context) {
auto *task = static_cast<StartupTaskState *>(context);
if (task == nullptr) {
return -1;
}
task->loadedHosts = startup::load_saved_hosts();
task->runtimeNetworkStatus = network::initialize_runtime_networking();
task->completed.store(true);
return 0;
}
void finish_startup_task(app::ClientState &clientState, StartupTaskState *task) {
if (task == nullptr) {
return;
}
if (task->thread != nullptr) {
int threadResult = 0;
SDL_WaitThread(task->thread, &threadResult);
(void) threadResult;
task->thread = nullptr;
}
for (const std::string &warning : task->loadedHosts.warnings) {
logging::warn("hosts", warning);
}
if (task->loadedHosts.fileFound) {
app::replace_hosts(clientState, task->loadedHosts.hosts, "Loaded " + std::to_string(task->loadedHosts.hosts.size()) + " saved host(s)");
logging::info("hosts", "Loaded " + std::to_string(task->loadedHosts.hosts.size()) + " saved host record(s)");
}
for (const std::string &line : network::format_runtime_network_status_lines(task->runtimeNetworkStatus)) {
logging::log(task->runtimeNetworkStatus.ready ? logging::LogLevel::info : logging::LogLevel::warning, "network", line);
}
if (!task->runtimeNetworkStatus.ready) {
clientState.shell.statusMessage = task->runtimeNetworkStatus.summary;
}
}
} // namespace
/**
* @brief Initialize the client runtime and enter the main shell loop.
*
* @return Process exit code.
*/
int main() {
logging::Logger logger;
logging::set_global_logger(&logger);
logging::set_minimum_level(logging::LogLevel::trace);
app::ClientState clientState = app::create_initial_state();
load_persisted_settings(clientState);
logging::set_file_minimum_level(clientState.settings.loggingLevel);
logging::set_debugger_console_minimum_level(clientState.settings.xemuConsoleLoggingLevel);
const std::string logFilePath = logging::default_log_file_path();
logging::RuntimeLogFileSink runtimeLogFile(logFilePath);
app::set_log_file_path(clientState, logFilePath);
if (std::string logFileResetError; !runtimeLogFile.reset(&logFileResetError)) {
logging::print_startup_console_line(
logging::LogLevel::warning,
"logging",
logFileResetError.empty() ? "Failed to reset the runtime log file." : logFileResetError
);
}
logging::set_file_sink([&runtimeLogFile](const logging::LogEntry &entry) {
std::string ignoredError;
runtimeLogFile.consume(entry, &ignoredError);
});
logging::info("app", std::string("Initial screen: ") + app::to_string(clientState.shell.activeScreen));
debug_print_startup_checkpoint("Runtime logging initialized");
const DWORD encoderSettings = XVideoGetEncoderSettings();
debug_print_encoder_settings(encoderSettings);
const startup::VideoModeSelection videoModeSelection = startup::select_best_video_mode();
initialize_stream_video_mode_settings(clientState, videoModeSelection, encoderSettings);
const VIDEO_MODE &bestVideoMode = videoModeSelection.bestVideoMode;
debug_print_video_mode_selection(videoModeSelection);
startup::log_memory_statistics();
debug_print_startup_checkpoint(
(std::string("About to call XVideoSetMode with ") + std::to_string(bestVideoMode.width) + "x" + std::to_string(bestVideoMode.height) + ", bpp=" + std::to_string(bestVideoMode.bpp) + ", refresh=" + std::to_string(bestVideoMode.refresh)).c_str()
);
const BOOL setVideoModeResult = XVideoSetMode(bestVideoMode.width, bestVideoMode.height, bestVideoMode.bpp, bestVideoMode.refresh);
debug_print_startup_checkpoint(setVideoModeResult ? "Returned from XVideoSetMode successfully" : "XVideoSetMode returned failure");
debug_print_startup_checkpoint("About to call SDL_Init");
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) != 0) {
return report_startup_failure("sdl", std::string("SDL_Init failed: ") + SDL_GetError());
}
debug_print_startup_checkpoint("SDL_Init succeeded");
debug_print_startup_checkpoint("About to create SDL window");
SDL_Window *window = SDL_CreateWindow(
"Moonlight Xbox",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
bestVideoMode.width,
bestVideoMode.height,
SDL_WINDOW_SHOWN
);
if (window == nullptr) {
const int exitCode = report_startup_failure("sdl", std::string("SDL_CreateWindow failed: ") + SDL_GetError());
SDL_Quit();
return exitCode;
}
debug_print_startup_checkpoint("SDL window creation succeeded");
StartupTaskState startupTask {};
debug_print_startup_checkpoint("Starting background startup task");
startupTask.thread = SDL_CreateThread(run_startup_task, "startup-init", &startupTask);
if (startupTask.thread == nullptr) {
debug_print_startup_checkpoint("SDL_CreateThread failed; running startup task synchronously");
run_startup_task(&startupTask);
} else {
debug_print_startup_checkpoint("Background startup task created");
}
logging::info("app", "Showing splash screen");
debug_print_startup_checkpoint("About to show splash screen");
logging::set_startup_debug_enabled(false);
logging::set_startup_console_enabled(false);
splash::show_splash_screen(window, bestVideoMode, [&startupTask]() {
return !startupTask.completed.load();
});
finish_startup_task(clientState, &startupTask);
startup::log_video_modes(videoModeSelection);
logging::info("app", "Starting interactive shell");
const int exitCode = ui::run_shell(window, bestVideoMode, clientState);
if (clientState.hosts.dirty) {
const startup::SaveSavedHostsResult saveResult = startup::save_saved_hosts(clientState.hosts.items);
if (saveResult.success) {
logging::info("hosts", "Saved host records before exit");
clientState.hosts.dirty = false;
} else {
logging::error("hosts", saveResult.errorMessage);
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return exitCode;
}