From a420760d36b5406d8c49a8ad435bfdbe8f8f80d6 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Feb 2024 09:01:14 -0500 Subject: [PATCH 001/129] ci(linux): increase root reserve for AppImage build (#2130) --- .github/workflows/CI.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index fb74710eda1..4b53e3204e9 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -286,7 +286,7 @@ jobs: - name: Maximize build space uses: easimon/maximize-build-space@v8 with: - root-reserve-mb: 20480 + root-reserve-mb: 30720 remove-dotnet: 'true' remove-android: 'true' remove-haskell: 'true' From 8689469ea8387bff6a7483c7c8bb565551bd8f41 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Feb 2024 14:15:45 -0500 Subject: [PATCH 002/129] refactor(main): move remaining entry related code (#2127) --- cmake/compile_definitions/common.cmake | 4 + docs/source/source_code/src/entry_handler.rst | 5 + docs/source/source_code/src/globals.rst | 5 + src/audio.cpp | 2 +- src/config.cpp | 3 +- src/confighttp.cpp | 2 +- src/entry_handler.cpp | 384 ++++++++++++++++++ src/entry_handler.h | 60 +++ src/globals.cpp | 27 ++ src/globals.h | 42 ++ src/input.cpp | 2 +- src/main.cpp | 353 +--------------- src/main.h | 67 --- src/nvhttp.cpp | 2 +- src/platform/linux/audio.cpp | 2 +- src/platform/linux/cuda.cpp | 4 +- src/platform/linux/input.cpp | 2 +- src/platform/linux/kmsgrab.cpp | 2 +- src/platform/linux/misc.cpp | 2 +- src/platform/linux/wlgrab.cpp | 3 +- src/platform/linux/x11grab.cpp | 3 +- src/platform/macos/misc.mm | 2 +- src/platform/windows/display_base.cpp | 2 +- src/platform/windows/input.cpp | 3 +- src/platform/windows/misc.cpp | 3 +- src/platform/windows/publish.cpp | 1 - src/process.cpp | 2 +- src/rtsp.cpp | 2 +- src/stream.cpp | 2 +- src/system_tray.cpp | 2 +- src/upnp.cpp | 2 +- src/video.cpp | 2 +- 32 files changed, 560 insertions(+), 439 deletions(-) create mode 100644 docs/source/source_code/src/entry_handler.rst create mode 100644 docs/source/source_code/src/globals.rst create mode 100644 src/entry_handler.cpp create mode 100644 src/entry_handler.h create mode 100644 src/globals.cpp create mode 100644 src/globals.h diff --git a/cmake/compile_definitions/common.cmake b/cmake/compile_definitions/common.cmake index e51dbf56526..94f1ac598cc 100644 --- a/cmake/compile_definitions/common.cmake +++ b/cmake/compile_definitions/common.cmake @@ -45,8 +45,12 @@ set(SUNSHINE_TARGET_FILES "${CMAKE_SOURCE_DIR}/src/uuid.h" "${CMAKE_SOURCE_DIR}/src/config.h" "${CMAKE_SOURCE_DIR}/src/config.cpp" + "${CMAKE_SOURCE_DIR}/src/entry_handler.cpp" + "${CMAKE_SOURCE_DIR}/src/entry_handler.h" "${CMAKE_SOURCE_DIR}/src/file_handler.cpp" "${CMAKE_SOURCE_DIR}/src/file_handler.h" + "${CMAKE_SOURCE_DIR}/src/globals.cpp" + "${CMAKE_SOURCE_DIR}/src/globals.h" "${CMAKE_SOURCE_DIR}/src/logging.cpp" "${CMAKE_SOURCE_DIR}/src/logging.h" "${CMAKE_SOURCE_DIR}/src/main.cpp" diff --git a/docs/source/source_code/src/entry_handler.rst b/docs/source/source_code/src/entry_handler.rst new file mode 100644 index 00000000000..c522b065652 --- /dev/null +++ b/docs/source/source_code/src/entry_handler.rst @@ -0,0 +1,5 @@ +entry_handler +============= + +.. doxygenfile:: entry_handler.h + :allow-dot-graphs: diff --git a/docs/source/source_code/src/globals.rst b/docs/source/source_code/src/globals.rst new file mode 100644 index 00000000000..ed70cecf692 --- /dev/null +++ b/docs/source/source_code/src/globals.rst @@ -0,0 +1,5 @@ +globals +======= + +.. doxygenfile:: globals.h + :allow-dot-graphs: diff --git a/src/audio.cpp b/src/audio.cpp index a3555eaa080..1995e380ea7 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -10,8 +10,8 @@ #include "audio.h" #include "config.h" +#include "globals.h" #include "logging.h" -#include "main.h" #include "thread_safe.h" #include "utility.h" diff --git a/src/config.cpp b/src/config.cpp index 5cd08cee94e..d9aaab3e31c 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -15,9 +16,9 @@ #include #include "config.h" +#include "entry_handler.h" #include "file_handler.h" #include "logging.h" -#include "main.h" #include "nvhttp.h" #include "rtsp.h" #include "utility.h" diff --git a/src/confighttp.cpp b/src/confighttp.cpp index e3a5f898e39..0657902dd16 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -30,9 +30,9 @@ #include "confighttp.h" #include "crypto.h" #include "file_handler.h" +#include "globals.h" #include "httpcommon.h" #include "logging.h" -#include "main.h" #include "network.h" #include "nvhttp.h" #include "platform/common.h" diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp new file mode 100644 index 00000000000..c7719eb0ed1 --- /dev/null +++ b/src/entry_handler.cpp @@ -0,0 +1,384 @@ +/** + * @file entry_handler.cpp + * @brief Entry point related functions. + */ + +// standard includes +#include +#include +#include + +// local includes +#include "config.h" +#include "confighttp.h" +#include "entry_handler.h" +#include "globals.h" +#include "httpcommon.h" +#include "logging.h" +#include "network.h" +#include "platform/common.h" +#include "version.h" + +extern "C" { +#ifdef _WIN32 + #include +#endif +} + +using namespace std::literals; + +/** + * @brief Launch the Web UI. + * + * EXAMPLES: + * ```cpp + * launch_ui(); + * ``` + */ +void +launch_ui() { + std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)); + platf::open_url(url); +} + +/** + * @brief Launch the Web UI at a specific endpoint. + * + * EXAMPLES: + * ```cpp + * launch_ui_with_path("/pin"); + * ``` + */ +void +launch_ui_with_path(std::string path) { + std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)) + path; + platf::open_url(url); +} + +namespace args { + /** + * @brief Reset the user credentials. + * + * @param name The name of the program. + * @param argc The number of arguments. + * @param argv The arguments. + * + * EXAMPLES: + * ```cpp + * creds("sunshine", 2, {"new_username", "new_password"}); + * ``` + */ + int + creds(const char *name, int argc, char *argv[]) { + if (argc < 2 || argv[0] == "help"sv || argv[1] == "help"sv) { + help(name, argc, argv); + } + + http::save_user_creds(config::sunshine.credentials_file, argv[0], argv[1]); + + return 0; + } + + /** + * @brief Print help to stdout, then exit. + * @param name The name of the program. + * @param argc The number of arguments. (Unused) + * @param argv The arguments. (Unused) + * + * EXAMPLES: + * ```cpp + * print_help("sunshine", 0, nullptr); + * ``` + */ + int + help(const char *name, int argc, char *argv[]) { + print_help(name); + return 0; + } + + /** + * @brief Print the version to stdout, then exit. + * @param name The name of the program. (Unused) + * @param argc The number of arguments. (Unused) + * @param argv The arguments. (Unused) + * + * EXAMPLES: + * ```cpp + * version("sunshine", 0, nullptr); + * ``` + */ + int + version(const char *name, int argc, char *argv[]) { + std::cout << PROJECT_NAME << " version: v" << PROJECT_VER << std::endl; + return 0; + } + +#ifdef _WIN32 + /** + * @brief Restore global NVIDIA control panel settings. + * + * If Sunshine was improperly terminated, this function restores + * the global NVIDIA control panel settings to the undo file left + * by Sunshine. This function is typically called by the uninstaller. + * + * @param name The name of the program. (Unused) + * @param argc The number of arguments. (Unused) + * @param argv The arguments. (Unused) + * + * EXAMPLES: + * ```cpp + * restore_nvprefs_undo("sunshine", 0, nullptr); + * ``` + */ + int + restore_nvprefs_undo(const char *name, int argc, char *argv[]) { + if (nvprefs_instance.load()) { + nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); + nvprefs_instance.unload(); + } + return 0; + } +#endif +} // namespace args + +namespace lifetime { + char **argv; + std::atomic_int desired_exit_code; + + /** + * @brief Terminates Sunshine gracefully with the provided exit code. + * @param exit_code The exit code to return from main(). + * @param async Specifies whether our termination will be non-blocking. + */ + void + exit_sunshine(int exit_code, bool async) { + // Store the exit code of the first exit_sunshine() call + int zero = 0; + desired_exit_code.compare_exchange_strong(zero, exit_code); + + // Raise SIGINT to start termination + std::raise(SIGINT); + + // Termination will happen asynchronously, but the caller may + // have wanted synchronous behavior. + while (!async) { + std::this_thread::sleep_for(1s); + } + } + + /** + * @brief Gets the argv array passed to main(). + */ + char ** + get_argv() { + return argv; + } +} // namespace lifetime + +#ifdef _WIN32 +/** + * @brief Check if NVIDIA's GameStream software is running. + * @return `true` if GameStream is enabled, `false` otherwise. + */ +bool +is_gamestream_enabled() { + DWORD enabled; + DWORD size = sizeof(enabled); + return RegGetValueW( + HKEY_LOCAL_MACHINE, + L"SOFTWARE\\NVIDIA Corporation\\NvStream", + L"EnableStreaming", + RRF_RT_REG_DWORD, + nullptr, + &enabled, + &size) == ERROR_SUCCESS && + enabled != 0; +} + +namespace service_ctrl { + class service_controller { + public: + /** + * @brief Constructor for service_controller class. + * @param service_desired_access SERVICE_* desired access flags. + */ + service_controller(DWORD service_desired_access) { + scm_handle = OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CONNECT); + if (!scm_handle) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "OpenSCManager() failed: "sv << winerr; + return; + } + + service_handle = OpenServiceA(scm_handle, "SunshineService", service_desired_access); + if (!service_handle) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "OpenService() failed: "sv << winerr; + return; + } + } + + ~service_controller() { + if (service_handle) { + CloseServiceHandle(service_handle); + } + + if (scm_handle) { + CloseServiceHandle(scm_handle); + } + } + + /** + * @brief Asynchronously starts the Sunshine service. + */ + bool + start_service() { + if (!service_handle) { + return false; + } + + if (!StartServiceA(service_handle, 0, nullptr)) { + auto winerr = GetLastError(); + if (winerr != ERROR_SERVICE_ALREADY_RUNNING) { + BOOST_LOG(error) << "StartService() failed: "sv << winerr; + return false; + } + } + + return true; + } + + /** + * @brief Query the service status. + * @param status The SERVICE_STATUS struct to populate. + */ + bool + query_service_status(SERVICE_STATUS &status) { + if (!service_handle) { + return false; + } + + if (!QueryServiceStatus(service_handle, &status)) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "QueryServiceStatus() failed: "sv << winerr; + return false; + } + + return true; + } + + private: + SC_HANDLE scm_handle = NULL; + SC_HANDLE service_handle = NULL; + }; + + /** + * @brief Check if the service is running. + * + * EXAMPLES: + * ```cpp + * is_service_running(); + * ``` + */ + bool + is_service_running() { + service_controller sc { SERVICE_QUERY_STATUS }; + + SERVICE_STATUS status; + if (!sc.query_service_status(status)) { + return false; + } + + return status.dwCurrentState == SERVICE_RUNNING; + } + + /** + * @brief Start the service and wait for startup to complete. + * + * EXAMPLES: + * ```cpp + * start_service(); + * ``` + */ + bool + start_service() { + service_controller sc { SERVICE_QUERY_STATUS | SERVICE_START }; + + std::cout << "Starting Sunshine..."sv; + + // This operation is asynchronous, so we must wait for it to complete + if (!sc.start_service()) { + return false; + } + + SERVICE_STATUS status; + do { + Sleep(1000); + std::cout << '.'; + } while (sc.query_service_status(status) && status.dwCurrentState == SERVICE_START_PENDING); + + if (status.dwCurrentState != SERVICE_RUNNING) { + BOOST_LOG(error) << SERVICE_NAME " failed to start: "sv << status.dwWin32ExitCode; + return false; + } + + std::cout << std::endl; + return true; + } + + /** + * @brief Wait for the UI to be ready after Sunshine startup. + * + * EXAMPLES: + * ```cpp + * wait_for_ui_ready(); + * ``` + */ + bool + wait_for_ui_ready() { + std::cout << "Waiting for Web UI to be ready..."; + + // Wait up to 30 seconds for the web UI to start + for (int i = 0; i < 30; i++) { + PMIB_TCPTABLE tcp_table = nullptr; + ULONG table_size = 0; + ULONG err; + + auto fg = util::fail_guard([&tcp_table]() { + free(tcp_table); + }); + + do { + // Query all open TCP sockets to look for our web UI port + err = GetTcpTable(tcp_table, &table_size, false); + if (err == ERROR_INSUFFICIENT_BUFFER) { + free(tcp_table); + tcp_table = (PMIB_TCPTABLE) malloc(table_size); + } + } while (err == ERROR_INSUFFICIENT_BUFFER); + + if (err != NO_ERROR) { + BOOST_LOG(error) << "Failed to query TCP table: "sv << err; + return false; + } + + uint16_t port_nbo = htons(net::map_port(confighttp::PORT_HTTPS)); + for (DWORD i = 0; i < tcp_table->dwNumEntries; i++) { + auto &entry = tcp_table->table[i]; + + // Look for our port in the listening state + if (entry.dwLocalPort == port_nbo && entry.dwState == MIB_TCP_STATE_LISTEN) { + std::cout << std::endl; + return true; + } + } + + Sleep(1000); + std::cout << '.'; + } + + std::cout << "timed out"sv << std::endl; + return false; + } +} // namespace service_ctrl +#endif diff --git a/src/entry_handler.h b/src/entry_handler.h new file mode 100644 index 00000000000..c58d0325d70 --- /dev/null +++ b/src/entry_handler.h @@ -0,0 +1,60 @@ +/** + * @file entry_handler.h + * @brief Header file for entry point functions. + */ +#pragma once + +// standard includes +#include +#include + +// local includes +#include "thread_pool.h" +#include "thread_safe.h" + +// functions +void +launch_ui(); +void +launch_ui_with_path(std::string path); + +#ifdef _WIN32 +// windows only functions +bool +is_gamestream_enabled(); +#endif + +namespace args { + int + creds(const char *name, int argc, char *argv[]); + int + help(const char *name, int argc, char *argv[]); + int + version(const char *name, int argc, char *argv[]); +#ifdef _WIN32 + int + restore_nvprefs_undo(const char *name, int argc, char *argv[]); +#endif +} // namespace args + +namespace lifetime { + extern char **argv; + extern std::atomic_int desired_exit_code; + void + exit_sunshine(int exit_code, bool async); + char ** + get_argv(); +} // namespace lifetime + +#ifdef _WIN32 +namespace service_ctrl { + bool + is_service_running(); + + bool + start_service(); + + bool + wait_for_ui_ready(); +} // namespace service_ctrl +#endif diff --git a/src/globals.cpp b/src/globals.cpp new file mode 100644 index 00000000000..ae6c7544360 --- /dev/null +++ b/src/globals.cpp @@ -0,0 +1,27 @@ +/** + * @file globals.cpp + * @brief Implementation for globally accessible variables and functions. + */ +#include "globals.h" + +/** + * @brief A process-wide communication mechanism. + */ +safe::mail_t mail::man; + +/** + * @brief A thread pool for processing tasks. + */ +thread_pool_util::ThreadPool task_pool; + +/** + * @brief A boolean flag to indicate whether the cursor should be displayed. + */ +bool display_cursor = true; + +#ifdef _WIN32 +/** + * @brief A global singleton used for NVIDIA control panel modifications. + */ +nvprefs::nvprefs_interface nvprefs_instance; +#endif diff --git a/src/globals.h b/src/globals.h new file mode 100644 index 00000000000..a137bc9c4d5 --- /dev/null +++ b/src/globals.h @@ -0,0 +1,42 @@ +/** + * @file globals.h + * @brief Header for globally accessible variables and functions. + */ +#pragma once + +#include "entry_handler.h" +#include "thread_pool.h" + +extern thread_pool_util::ThreadPool task_pool; +extern bool display_cursor; + +#ifdef _WIN32 + // Declare global singleton used for NVIDIA control panel modifications + #include "platform/windows/nvprefs/nvprefs_interface.h" +extern nvprefs::nvprefs_interface nvprefs_instance; +#endif + +namespace mail { +#define MAIL(x) \ + constexpr auto x = std::string_view { \ + #x \ + } + + extern safe::mail_t man; + + // Global mail + MAIL(shutdown); + MAIL(broadcast_shutdown); + MAIL(video_packets); + MAIL(audio_packets); + MAIL(switch_display); + + // Local mail + MAIL(touch_port); + MAIL(idr); + MAIL(invalidate_ref_frames); + MAIL(gamepad_feedback); + MAIL(hdr); +#undef MAIL + +} // namespace mail diff --git a/src/input.cpp b/src/input.cpp index b7416fffac2..89f7291f11a 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -17,9 +17,9 @@ extern "C" { #include #include "config.h" +#include "globals.h" #include "input.h" #include "logging.h" -#include "main.h" #include "platform/common.h" #include "thread_pool.h" #include "utility.h" diff --git a/src/main.cpp b/src/main.cpp index 1d1bb305398..cbe481ee2e9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,31 +5,22 @@ // standard includes #include -#include #include #include -#include // lib includes -#include -#include #include -#include -#include // local includes -#include "config.h" #include "confighttp.h" +#include "entry_handler.h" +#include "globals.h" #include "httpcommon.h" #include "logging.h" #include "main.h" -#include "network.h" #include "nvhttp.h" -#include "platform/common.h" #include "process.h" -#include "rtsp.h" #include "system_tray.h" -#include "thread_pool.h" #include "upnp.h" #include "version.h" #include "video.h" @@ -37,26 +28,11 @@ extern "C" { #include #include - -#ifdef _WIN32 - #include -#endif } -safe::mail_t mail::man; - using namespace std::literals; namespace bl = boost::log; -#ifdef _WIN32 -// Define global singleton used for NVIDIA control panel modifications -nvprefs::nvprefs_interface nvprefs_instance; -#endif - -thread_pool_util::ThreadPool task_pool; - -bool display_cursor = true; - struct NoDelete { void operator()(void *) {} @@ -64,309 +40,6 @@ struct NoDelete { BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", int) -namespace help { - int - entry(const char *name, int argc, char *argv[]) { - print_help(name); - return 0; - } -} // namespace help - -namespace version { - int - entry(const char *name, int argc, char *argv[]) { - std::cout << PROJECT_NAME << " version: v" << PROJECT_VER << std::endl; - return 0; - } -} // namespace version - -#ifdef _WIN32 -namespace restore_nvprefs_undo { - int - entry(const char *name, int argc, char *argv[]) { - // Restore global NVIDIA control panel settings to the undo file - // left by improper termination of sunshine.exe, if it exists. - // This entry point is typically called by the uninstaller. - if (nvprefs_instance.load()) { - nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); - nvprefs_instance.unload(); - } - return 0; - } -} // namespace restore_nvprefs_undo -#endif - -namespace lifetime { - static char **argv; - static std::atomic_int desired_exit_code; - - /** - * @brief Terminates Sunshine gracefully with the provided exit code. - * @param exit_code The exit code to return from main(). - * @param async Specifies whether our termination will be non-blocking. - */ - void - exit_sunshine(int exit_code, bool async) { - // Store the exit code of the first exit_sunshine() call - int zero = 0; - desired_exit_code.compare_exchange_strong(zero, exit_code); - - // Raise SIGINT to start termination - std::raise(SIGINT); - - // Termination will happen asynchronously, but the caller may - // have wanted synchronous behavior. - while (!async) { - std::this_thread::sleep_for(1s); - } - } - - /** - * @brief Gets the argv array passed to main(). - */ - char ** - get_argv() { - return argv; - } -} // namespace lifetime - -#ifdef _WIN32 -namespace service_ctrl { - class service_controller { - public: - /** - * @brief Constructor for service_controller class. - * @param service_desired_access SERVICE_* desired access flags. - */ - service_controller(DWORD service_desired_access) { - scm_handle = OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CONNECT); - if (!scm_handle) { - auto winerr = GetLastError(); - BOOST_LOG(error) << "OpenSCManager() failed: "sv << winerr; - return; - } - - service_handle = OpenServiceA(scm_handle, "SunshineService", service_desired_access); - if (!service_handle) { - auto winerr = GetLastError(); - BOOST_LOG(error) << "OpenService() failed: "sv << winerr; - return; - } - } - - ~service_controller() { - if (service_handle) { - CloseServiceHandle(service_handle); - } - - if (scm_handle) { - CloseServiceHandle(scm_handle); - } - } - - /** - * @brief Asynchronously starts the Sunshine service. - */ - bool - start_service() { - if (!service_handle) { - return false; - } - - if (!StartServiceA(service_handle, 0, nullptr)) { - auto winerr = GetLastError(); - if (winerr != ERROR_SERVICE_ALREADY_RUNNING) { - BOOST_LOG(error) << "StartService() failed: "sv << winerr; - return false; - } - } - - return true; - } - - /** - * @brief Query the service status. - * @param status The SERVICE_STATUS struct to populate. - */ - bool - query_service_status(SERVICE_STATUS &status) { - if (!service_handle) { - return false; - } - - if (!QueryServiceStatus(service_handle, &status)) { - auto winerr = GetLastError(); - BOOST_LOG(error) << "QueryServiceStatus() failed: "sv << winerr; - return false; - } - - return true; - } - - private: - SC_HANDLE scm_handle = NULL; - SC_HANDLE service_handle = NULL; - }; - - /** - * @brief Check if the service is running. - * - * EXAMPLES: - * ```cpp - * is_service_running(); - * ``` - */ - bool - is_service_running() { - service_controller sc { SERVICE_QUERY_STATUS }; - - SERVICE_STATUS status; - if (!sc.query_service_status(status)) { - return false; - } - - return status.dwCurrentState == SERVICE_RUNNING; - } - - /** - * @brief Start the service and wait for startup to complete. - * - * EXAMPLES: - * ```cpp - * start_service(); - * ``` - */ - bool - start_service() { - service_controller sc { SERVICE_QUERY_STATUS | SERVICE_START }; - - std::cout << "Starting Sunshine..."sv; - - // This operation is asynchronous, so we must wait for it to complete - if (!sc.start_service()) { - return false; - } - - SERVICE_STATUS status; - do { - Sleep(1000); - std::cout << '.'; - } while (sc.query_service_status(status) && status.dwCurrentState == SERVICE_START_PENDING); - - if (status.dwCurrentState != SERVICE_RUNNING) { - BOOST_LOG(error) << SERVICE_NAME " failed to start: "sv << status.dwWin32ExitCode; - return false; - } - - std::cout << std::endl; - return true; - } - - /** - * @brief Wait for the UI to be ready after Sunshine startup. - * - * EXAMPLES: - * ```cpp - * wait_for_ui_ready(); - * ``` - */ - bool - wait_for_ui_ready() { - std::cout << "Waiting for Web UI to be ready..."; - - // Wait up to 30 seconds for the web UI to start - for (int i = 0; i < 30; i++) { - PMIB_TCPTABLE tcp_table = nullptr; - ULONG table_size = 0; - ULONG err; - - auto fg = util::fail_guard([&tcp_table]() { - free(tcp_table); - }); - - do { - // Query all open TCP sockets to look for our web UI port - err = GetTcpTable(tcp_table, &table_size, false); - if (err == ERROR_INSUFFICIENT_BUFFER) { - free(tcp_table); - tcp_table = (PMIB_TCPTABLE) malloc(table_size); - } - } while (err == ERROR_INSUFFICIENT_BUFFER); - - if (err != NO_ERROR) { - BOOST_LOG(error) << "Failed to query TCP table: "sv << err; - return false; - } - - uint16_t port_nbo = htons(net::map_port(confighttp::PORT_HTTPS)); - for (DWORD i = 0; i < tcp_table->dwNumEntries; i++) { - auto &entry = tcp_table->table[i]; - - // Look for our port in the listening state - if (entry.dwLocalPort == port_nbo && entry.dwState == MIB_TCP_STATE_LISTEN) { - std::cout << std::endl; - return true; - } - } - - Sleep(1000); - std::cout << '.'; - } - - std::cout << "timed out"sv << std::endl; - return false; - } -} // namespace service_ctrl - -/** - * @brief Checks if NVIDIA's GameStream software is running. - * @return `true` if GameStream is enabled. - */ -bool -is_gamestream_enabled() { - DWORD enabled; - DWORD size = sizeof(enabled); - return RegGetValueW( - HKEY_LOCAL_MACHINE, - L"SOFTWARE\\NVIDIA Corporation\\NvStream", - L"EnableStreaming", - RRF_RT_REG_DWORD, - nullptr, - &enabled, - &size) == ERROR_SUCCESS && - enabled != 0; -} - -#endif - -/** - * @brief Launch the Web UI. - * - * EXAMPLES: - * ```cpp - * launch_ui(); - * ``` - */ -void -launch_ui() { - std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)); - platf::open_url(url); -} - -/** - * @brief Launch the Web UI at a specific endpoint. - * - * EXAMPLES: - * ```cpp - * launch_ui_with_path("/pin"); - * ``` - */ -void -launch_ui_with_path(std::string path) { - std::string url = "https://localhost:" + std::to_string(net::map_port(confighttp::PORT_HTTPS)) + path; - platf::open_url(url); -} - std::map> signal_handlers; void on_signal_forwarder(int sig) { @@ -381,26 +54,12 @@ on_signal(int sig, FN &&fn) { std::signal(sig, on_signal_forwarder); } -namespace gen_creds { - int - entry(const char *name, int argc, char *argv[]) { - if (argc < 2 || argv[0] == "help"sv || argv[1] == "help"sv) { - print_help(name); - return 0; - } - - http::save_user_creds(config::sunshine.credentials_file, argv[0], argv[1]); - - return 0; - } -} // namespace gen_creds - std::map> cmd_to_func { - { "creds"sv, gen_creds::entry }, - { "help"sv, help::entry }, - { "version"sv, version::entry }, + { "creds"sv, args::creds }, + { "help"sv, args::help }, + { "version"sv, args::version }, #ifdef _WIN32 - { "restore-nvprefs-undo"sv, restore_nvprefs_undo::entry }, + { "restore-nvprefs-undo"sv, args::restore_nvprefs_undo }, #endif }; diff --git a/src/main.h b/src/main.h index 02a21fd321e..f34ca6cda66 100644 --- a/src/main.h +++ b/src/main.h @@ -6,73 +6,6 @@ // macros #pragma once -// standard includes -#include -#include - -// local includes -#include "thread_pool.h" -#include "thread_safe.h" - -#ifdef _WIN32 - // Declare global singleton used for NVIDIA control panel modifications - #include "platform/windows/nvprefs/nvprefs_interface.h" -extern nvprefs::nvprefs_interface nvprefs_instance; -#endif - -extern thread_pool_util::ThreadPool task_pool; -extern bool display_cursor; - // functions int main(int argc, char *argv[]); -void -launch_ui(); -void -launch_ui_with_path(std::string path); - -// namespaces -namespace mail { -#define MAIL(x) \ - constexpr auto x = std::string_view { \ - #x \ - } - - extern safe::mail_t man; - - // Global mail - MAIL(shutdown); - MAIL(broadcast_shutdown); - MAIL(video_packets); - MAIL(audio_packets); - MAIL(switch_display); - - // Local mail - MAIL(touch_port); - MAIL(idr); - MAIL(invalidate_ref_frames); - MAIL(gamepad_feedback); - MAIL(hdr); -#undef MAIL - -} // namespace mail - -namespace lifetime { - void - exit_sunshine(int exit_code, bool async); - char ** - get_argv(); -} // namespace lifetime - -#ifdef _WIN32 -namespace service_ctrl { - bool - is_service_running(); - - bool - start_service(); - - bool - wait_for_ui_ready(); -} // namespace service_ctrl -#endif diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index af211c579b7..b8bddb44bb7 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -23,9 +23,9 @@ #include "config.h" #include "crypto.h" #include "file_handler.h" +#include "globals.h" #include "httpcommon.h" #include "logging.h" -#include "main.h" #include "network.h" #include "nvhttp.h" #include "platform/common.h" diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 577287b77ef..e663c811ba2 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -4,6 +4,7 @@ */ #include #include +#include #include @@ -15,7 +16,6 @@ #include "src/config.h" #include "src/logging.h" -#include "src/main.h" #include "src/thread_safe.h" namespace platf { diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 856fecc657a..5b121c70691 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -3,10 +3,9 @@ * @brief todo */ #include - #include - #include +#include #include #include @@ -20,7 +19,6 @@ extern "C" { #include "cuda.h" #include "graphics.h" #include "src/logging.h" -#include "src/main.h" #include "src/utility.h" #include "src/video.h" #include "wayland.h" diff --git a/src/platform/linux/input.cpp b/src/platform/linux/input.cpp index 43433e58a92..85818110730 100644 --- a/src/platform/linux/input.cpp +++ b/src/platform/linux/input.cpp @@ -20,11 +20,11 @@ #include #include #include +#include #include "src/config.h" #include "src/input.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include "src/utility.h" diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index a18fc31a823..192482deaa1 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -13,9 +13,9 @@ #include #include +#include #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include "src/round_robin.h" #include "src/utility.h" diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 8ead76b0715..ecc5887e0f1 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -26,8 +26,8 @@ #include "graphics.h" #include "misc.h" #include "src/config.h" +#include "src/entry_handler.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include "vaapi.h" diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index 6acde691479..84b69bd0be0 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -2,10 +2,11 @@ * @file src/platform/linux/wlgrab.cpp * @brief todo */ +#include + #include "src/platform/common.h" #include "src/logging.h" -#include "src/main.h" #include "src/video.h" #include "cuda.h" diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 0c1583002b9..1167d3f5809 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -5,6 +5,7 @@ #include "src/platform/common.h" #include +#include #include #include @@ -17,8 +18,8 @@ #include #include "src/config.h" +#include "src/globals.h" #include "src/logging.h" -#include "src/main.h" #include "src/task_pool.h" #include "src/video.h" diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 0a8bf1b78ae..20c2247e049 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -18,8 +18,8 @@ #include #include "misc.h" +#include "src/entry_handler.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 3ae6e337d26..78c927e7782 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -16,7 +17,6 @@ typedef long NTSTATUS; #include "misc.h" #include "src/config.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include "src/stat_trackers.h" #include "src/video.h" diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 144dac1999a..5056c2c7246 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -6,14 +6,15 @@ #include #include +#include #include #include "keylayout.h" #include "misc.h" #include "src/config.h" +#include "src/globals.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #ifdef __MINGW32__ diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 1bbfe113a38..708fd267484 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -35,8 +35,9 @@ #define NTDDI_VERSION NTDDI_WIN10 #include +#include "src/entry_handler.h" +#include "src/globals.h" #include "src/logging.h" -#include "src/main.h" #include "src/platform/common.h" #include "src/utility.h" #include diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index 47c16721e20..6eb4d8948e1 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -14,7 +14,6 @@ #include "misc.h" #include "src/config.h" #include "src/logging.h" -#include "src/main.h" #include "src/network.h" #include "src/nvhttp.h" #include "src/platform/common.h" diff --git a/src/process.cpp b/src/process.cpp index fef585cdae6..e660e8162a1 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -23,7 +24,6 @@ #include "config.h" #include "crypto.h" #include "logging.h" -#include "main.h" #include "platform/common.h" #include "system_tray.h" #include "utility.h" diff --git a/src/rtsp.cpp b/src/rtsp.cpp index 73f224b8ef1..0180fbee37a 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -16,9 +16,9 @@ extern "C" { #include #include "config.h" +#include "globals.h" #include "input.h" #include "logging.h" -#include "main.h" #include "network.h" #include "rtsp.h" #include "stream.h" diff --git a/src/stream.cpp b/src/stream.cpp index 12fb8663fc8..b9238057b1c 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -18,9 +18,9 @@ extern "C" { } #include "config.h" +#include "globals.h" #include "input.h" #include "logging.h" -#include "main.h" #include "network.h" #include "stat_trackers.h" #include "stream.h" diff --git a/src/system_tray.cpp b/src/system_tray.cpp index 621ace0cfb9..39131ba30fe 100644 --- a/src/system_tray.cpp +++ b/src/system_tray.cpp @@ -38,9 +38,9 @@ // local includes #include "confighttp.h" #include "logging.h" - #include "main.h" #include "platform/common.h" #include "process.h" + #include "src/entry_handler.h" #include "version.h" using namespace std::literals; diff --git a/src/upnp.cpp b/src/upnp.cpp index 55c49aaf67c..f65bcb87cc4 100644 --- a/src/upnp.cpp +++ b/src/upnp.cpp @@ -7,8 +7,8 @@ #include "config.h" #include "confighttp.h" +#include "globals.h" #include "logging.h" -#include "main.h" #include "network.h" #include "nvhttp.h" #include "rtsp.h" diff --git a/src/video.cpp b/src/video.cpp index e013249880b..636bcf60138 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -19,9 +19,9 @@ extern "C" { #include "cbs.h" #include "config.h" +#include "globals.h" #include "input.h" #include "logging.h" -#include "main.h" #include "nvenc/nvenc_base.h" #include "platform/common.h" #include "sync.h" From 69a3edd9b01c76aa44fd5c2a29de1c3b3722cb41 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 11 Feb 2024 15:16:41 -0600 Subject: [PATCH 003/129] Use Win32 APIs for UTF-16<->UTF-8 conversion std::codecvt is deprecated since C++17 and broken for some characters/locales --- src/platform/windows/audio.cpp | 15 ++--- src/platform/windows/display_base.cpp | 15 ++--- src/platform/windows/display_vram.cpp | 5 +- src/platform/windows/misc.cpp | 93 +++++++++++++++++++++++---- src/platform/windows/misc.h | 16 +++++ src/platform/windows/publish.cpp | 4 +- src/process.cpp | 6 +- 7 files changed, 113 insertions(+), 41 deletions(-) diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index 296112e1ad3..3e9267b32aa 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -7,8 +7,6 @@ #include #include -#include - #include #include @@ -19,6 +17,8 @@ #include "src/logging.h" #include "src/platform/common.h" +#include "misc.h" + // Must be the last included file // clang-format off #include "PolicyConfig.h" @@ -89,7 +89,6 @@ namespace platf::audio { PROPVARIANT prop; }; - static std::wstring_convert, wchar_t> converter; struct format_t { enum type_e : int { none, @@ -613,7 +612,7 @@ namespace platf::audio { audio::wstring_t wstring; device->GetId(&wstring); - sink.host = converter.to_bytes(wstring.get()); + sink.host = to_utf8(wstring.get()); collection_t collection; auto status = device_enum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection); @@ -627,7 +626,7 @@ namespace platf::audio { collection->GetCount(&count); // If the sink isn't a device name, we'll assume it's a device ID - auto virtual_device_id = find_device_id_by_name(config::audio.virtual_sink).value_or(converter.from_bytes(config::audio.virtual_sink)); + auto virtual_device_id = find_device_id_by_name(config::audio.virtual_sink).value_or(from_utf8(config::audio.virtual_sink)); auto virtual_device_found = false; for (auto x = 0; x < count; ++x) { @@ -674,7 +673,7 @@ namespace platf::audio { } if (virtual_device_found) { - auto name_suffix = converter.to_bytes(virtual_device_id); + auto name_suffix = to_utf8(virtual_device_id); sink.null = std::make_optional(sink_t::null_t { "virtual-"s.append(formats[format_t::stereo - 1].name) + name_suffix, "virtual-"s.append(formats[format_t::surr51 - 1].name) + name_suffix, @@ -749,7 +748,7 @@ namespace platf::audio { auto sink_info = get_sink_info(sink); // If the sink isn't a device name, we'll assume it's a device ID - auto wstring_device_id = find_device_id_by_name(sink).value_or(converter.from_bytes(sink_info.second.data())); + auto wstring_device_id = find_device_id_by_name(sink).value_or(from_utf8(sink_info.second.data())); if (sink_info.first == format_t::none) { // wstring_device_id does not contain virtual-(format name) @@ -839,7 +838,7 @@ namespace platf::audio { UINT count; collection->GetCount(&count); - auto wstring_name = converter.from_bytes(name.data()); + auto wstring_name = from_utf8(name.data()); for (auto x = 0; x < count; ++x) { audio::device_t device; diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 78c927e7782..a5f8cc5d31a 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -3,7 +3,6 @@ * @brief todo */ #include -#include #include #include @@ -447,10 +446,8 @@ namespace platf::dxgi { return -1; } - std::wstring_convert, wchar_t> converter; - - auto adapter_name = converter.from_bytes(config::video.adapter_name); - auto output_name = converter.from_bytes(display_name); + auto adapter_name = from_utf8(config::video.adapter_name); + auto output_name = from_utf8(display_name); adapter_t::pointer adapter_p; for (int tries = 0; tries < 2; ++tries) { @@ -561,7 +558,7 @@ namespace platf::dxgi { DXGI_ADAPTER_DESC adapter_desc; adapter->GetDesc(&adapter_desc); - auto description = converter.to_bytes(adapter_desc.Description); + auto description = to_utf8(adapter_desc.Description); BOOST_LOG(info) << std::endl << "Device Description : " << description << std::endl @@ -1066,8 +1063,6 @@ namespace platf { BOOST_LOG(debug) << "Detecting monitors..."sv; - std::wstring_convert, wchar_t> converter; - // We must set the GPU preference before calling any DXGI APIs! if (!dxgi::probe_for_gpu_preference(config::video.output_name)) { BOOST_LOG(warning) << "Failed to set GPU preference. Capture may not work!"sv; @@ -1088,7 +1083,7 @@ namespace platf { BOOST_LOG(debug) << std::endl << "====== ADAPTER ====="sv << std::endl - << "Device Name : "sv << converter.to_bytes(adapter_desc.Description) << std::endl + << "Device Name : "sv << to_utf8(adapter_desc.Description) << std::endl << "Device Vendor ID : 0x"sv << util::hex(adapter_desc.VendorId).to_string_view() << std::endl << "Device Device ID : 0x"sv << util::hex(adapter_desc.DeviceId).to_string_view() << std::endl << "Device Video Mem : "sv << adapter_desc.DedicatedVideoMemory / 1048576 << " MiB"sv << std::endl @@ -1104,7 +1099,7 @@ namespace platf { DXGI_OUTPUT_DESC desc; output->GetDesc(&desc); - auto device_name = converter.to_bytes(desc.DeviceName); + auto device_name = to_utf8(desc.DeviceName); auto width = desc.DesktopCoordinates.right - desc.DesktopCoordinates.left; auto height = desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top; diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 74b0bab7fbf..e9f8140d525 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -4,8 +4,6 @@ */ #include -#include - #include #include @@ -342,9 +340,8 @@ namespace platf::dxgi { #ifndef NDEBUG flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #endif - std::wstring_convert, wchar_t> converter; - auto wFile = converter.from_bytes(file); + auto wFile = from_utf8(file); auto status = D3DCompileFromFile(wFile.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entrypoint, shader_model, flags, 0, &compiled_p, &msg_p); if (msg_p) { diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 708fd267484..2014d9435b8 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -2,7 +2,6 @@ * @file src/platform/windows/misc.cpp * @brief todo */ -#include #include #include #include @@ -35,6 +34,8 @@ #define NTDDI_VERSION NTDDI_WIN10 #include +#include "misc.h" + #include "src/entry_handler.h" #include "src/globals.h" #include "src/logging.h" @@ -66,8 +67,6 @@ using namespace std::literals; namespace platf { using adapteraddrs_t = util::c_ptr; - static std::wstring_convert, wchar_t> converter; - bool enabled_mouse_keys = false; MOUSEKEYS previous_mouse_keys_state; @@ -297,7 +296,7 @@ namespace platf { // Parse the environment block and populate env for (auto c = (PWCHAR) env_block; *c != UNICODE_NULL; c += wcslen(c) + 1) { // Environment variable entries end with a null-terminator, so std::wstring() will get an entire entry. - std::string env_tuple = converter.to_bytes(std::wstring { c }); + std::string env_tuple = to_utf8(std::wstring { c }); std::string env_name = env_tuple.substr(0, env_tuple.find('=')); std::string env_val = env_tuple.substr(env_tuple.find('=') + 1); @@ -371,7 +370,7 @@ namespace platf { for (const auto &entry : env) { auto name = entry.get_name(); auto value = entry.to_string(); - size += converter.from_bytes(name).length() + 1 /* L'=' */ + converter.from_bytes(value).length() + 1 /* L'\0' */; + size += from_utf8(name).length() + 1 /* L'=' */ + from_utf8(value).length() + 1 /* L'\0' */; } size += 1 /* L'\0' */; @@ -383,9 +382,9 @@ namespace platf { auto value = entry.to_string(); // Construct the NAME=VAL\0 string - append_string_to_environment_block(env_block, offset, converter.from_bytes(name)); + append_string_to_environment_block(env_block, offset, from_utf8(name)); env_block[offset++] = L'='; - append_string_to_environment_block(env_block, offset, converter.from_bytes(value)); + append_string_to_environment_block(env_block, offset, from_utf8(value)); env_block[offset++] = L'\0'; } @@ -625,14 +624,14 @@ namespace platf { */ std::wstring resolve_command_string(const std::string &raw_cmd, const std::wstring &working_dir, HANDLE token) { - std::wstring raw_cmd_w = converter.from_bytes(raw_cmd); + std::wstring raw_cmd_w = from_utf8(raw_cmd); // First, convert the given command into parts so we can get the executable/file/URL without parameters auto raw_cmd_parts = boost::program_options::split_winmain(raw_cmd_w); if (raw_cmd_parts.empty()) { // This is highly unexpected, but we'll just return the raw string and hope for the best. BOOST_LOG(warning) << "Failed to split command string: "sv << raw_cmd; - return converter.from_bytes(raw_cmd); + return from_utf8(raw_cmd); } auto raw_target = raw_cmd_parts.at(0); @@ -646,7 +645,7 @@ namespace platf { res = UrlGetPartW(raw_target.c_str(), scheme.data(), &out_len, URL_PART_SCHEME, 0); if (res != S_OK) { BOOST_LOG(warning) << "Failed to extract URL scheme from URL: "sv << raw_target << " ["sv << util::hex(res).to_string_view() << ']'; - return converter.from_bytes(raw_cmd); + return from_utf8(raw_cmd); } // If the target is a URL, the class is found using the URL scheme (prior to and not including the ':') @@ -658,7 +657,7 @@ namespace platf { if (extension == nullptr || *extension == 0) { // If the file has no extension, assume it's a command and allow CreateProcess() // to try to find it via PATH - return converter.from_bytes(raw_cmd); + return from_utf8(raw_cmd); } // For regular files, the class is found using the file extension (including the dot) @@ -674,7 +673,7 @@ namespace platf { // Override HKEY_CLASSES_ROOT and HKEY_CURRENT_USER to ensure we query the correct class info if (!override_per_user_predefined_keys(token)) { - return converter.from_bytes(raw_cmd); + return from_utf8(raw_cmd); } // Find the command string for the specified class @@ -699,7 +698,7 @@ namespace platf { if (res != S_OK) { BOOST_LOG(warning) << "Failed to query command string for raw command: "sv << raw_cmd << " ["sv << util::hex(res).to_string_view() << ']'; - return converter.from_bytes(raw_cmd); + return from_utf8(raw_cmd); } // Finally, construct the real command string that will be passed into CreateProcess(). @@ -825,7 +824,7 @@ namespace platf { */ bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { - std::wstring start_dir = converter.from_bytes(working_dir.string()); + std::wstring start_dir = from_utf8(working_dir.string()); HANDLE job = group ? group->native_handle() : nullptr; STARTUPINFOEXW startup_info = create_startup_info(file, job ? &job : nullptr, ec); PROCESS_INFORMATION process_info; @@ -1602,4 +1601,70 @@ namespace platf { } return {}; } + + /** + * @brief Converts a UTF-8 string into a UTF-16 wide string. + * @param string The UTF-8 string. + * @return The converted UTF-16 wide string. + */ + std::wstring + from_utf8(const std::string &string) { + // No conversion needed if the string is empty + if (string.empty()) { + return {}; + } + + // Get the output size required to store the string + auto output_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string.data(), string.size(), nullptr, 0); + if (output_size == 0) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "Failed to get UTF-16 buffer size: "sv << winerr; + return {}; + } + + // Perform the conversion + std::wstring output(output_size, L'\0'); + output_size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string.data(), string.size(), output.data(), output.size()); + if (output_size == 0) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "Failed to convert string to UTF-16: "sv << winerr; + return {}; + } + + return output; + } + + /** + * @brief Converts a UTF-16 wide string into a UTF-8 string. + * @param string The UTF-16 wide string. + * @return The converted UTF-8 string. + */ + std::string + to_utf8(const std::wstring &string) { + // No conversion needed if the string is empty + if (string.empty()) { + return {}; + } + + // Get the output size required to store the string + auto output_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string.data(), string.size(), + nullptr, 0, nullptr, nullptr); + if (output_size == 0) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "Failed to get UTF-8 buffer size: "sv << winerr; + return {}; + } + + // Perform the conversion + std::string output(output_size, '\0'); + output_size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string.data(), string.size(), + output.data(), output.size(), nullptr, nullptr); + if (output_size == 0) { + auto winerr = GetLastError(); + BOOST_LOG(error) << "Failed to convert string to UTF-8: "sv << winerr; + return {}; + } + + return output; + } } // namespace platf diff --git a/src/platform/windows/misc.h b/src/platform/windows/misc.h index 9228ce59fe7..5a3e29b0257 100644 --- a/src/platform/windows/misc.h +++ b/src/platform/windows/misc.h @@ -20,4 +20,20 @@ namespace platf { std::chrono::nanoseconds qpc_time_difference(int64_t performance_counter1, int64_t performance_counter2); + + /** + * @brief Converts a UTF-8 string into a UTF-16 wide string. + * @param string The UTF-8 string. + * @return The converted UTF-16 wide string. + */ + std::wstring + from_utf8(const std::string &string); + + /** + * @brief Converts a UTF-16 wide string into a UTF-8 string. + * @param string The UTF-16 wide string. + * @return The converted UTF-8 string. + */ + std::string + to_utf8(const std::wstring &string); } // namespace platf diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index 6eb4d8948e1..131bb5ac11f 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -107,12 +107,10 @@ namespace platf::publish { service(bool enable, PDNS_SERVICE_INSTANCE &existing_instance) { auto alarm = safe::make_alarm(); - std::wstring_convert, wchar_t> converter; - std::wstring name { SERVICE_INSTANCE_NAME.data(), SERVICE_INSTANCE_NAME.size() }; std::wstring domain { SERVICE_TYPE_DOMAIN.data(), SERVICE_TYPE_DOMAIN.size() }; - auto host = converter.from_bytes(boost::asio::ip::host_name() + ".local"); + auto host = from_utf8(boost::asio::ip::host_name() + ".local"); DNS_SERVICE_INSTANCE instance {}; instance.pszInstanceName = name.data(); diff --git a/src/process.cpp b/src/process.cpp index e660e8162a1..804291577c2 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -29,6 +29,9 @@ #include "utility.h" #ifdef _WIN32 + // from_utf8() string conversion function + #include "platform/windows/misc.h" + // _SH constants for _wfsopen() #include #endif @@ -187,8 +190,7 @@ namespace proc { #ifdef _WIN32 // fopen() interprets the filename as an ANSI string on Windows, so we must convert it // to UTF-16 and use the wchar_t variants for proper Unicode log file path support. - std::wstring_convert, wchar_t> converter; - auto woutput = converter.from_bytes(_app.output); + auto woutput = platf::from_utf8(_app.output); // Use _SH_DENYNO to allow us to open this log file again for writing even if it is // still open from a previous execution. This is required to handle the case of a From 6ddc4b7ba31af4fc34e5c766ccee4edb81194f1b Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sat, 10 Feb 2024 15:33:56 -0600 Subject: [PATCH 004/129] Properly re-escape arguments when processing %* --- src/platform/windows/misc.cpp | 73 ++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 2014d9435b8..d3e98950abb 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -614,6 +614,67 @@ namespace platf { return true; } + /** + * @brief This function quotes/escapes an argument according to the Windows parsing convention. + * @param argument The raw argument to process. + * @return An argument string suitable for use by CreateProcess(). + */ + std::wstring + escape_argument(const std::wstring &argument) { + // If there are no characters requiring quoting/escaping, we're done + if (argument.find_first_of(L" \t\n\v\"") == argument.npos) { + return argument; + } + + // The algorithm implemented here comes from a MSDN blog post: + // https://web.archive.org/web/20120201194949/http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx + std::wstring escaped_arg; + escaped_arg.push_back(L'"'); + for (auto it = argument.begin();; it++) { + auto backslash_count = 0U; + while (it != argument.end() && *it == L'\\') { + it++; + backslash_count++; + } + + if (it == argument.end()) { + escaped_arg.append(backslash_count * 2, L'\\'); + break; + } + else if (*it == L'"') { + escaped_arg.append(backslash_count * 2 + 1, L'\\'); + } + else { + escaped_arg.append(backslash_count, L'\\'); + } + + escaped_arg.push_back(*it); + } + escaped_arg.push_back(L'"'); + return escaped_arg; + } + + /** + * @brief This function escapes an argument according to cmd's parsing convention. + * @param argument An argument already escaped by `escape_argument()`. + * @return An argument string suitable for use by cmd.exe. + */ + std::wstring + escape_argument_for_cmd(const std::wstring &argument) { + // Start with the original string and modify from there + std::wstring escaped_arg = argument; + + // Look for the next cmd metacharacter + size_t match_pos = 0; + while ((match_pos = escaped_arg.find_first_of(L"()%!^\"<>&|", match_pos)) != std::wstring::npos) { + // Insert an escape character and skip past the match + escaped_arg.insert(match_pos, 1, L'^'); + match_pos += 2; + } + + return escaped_arg; + } + /** * @brief This function resolves the given raw command into a proper command string for CreateProcess(). * @details This converts URLs and non-executable file paths into a runnable command like ShellExecute(). @@ -665,6 +726,7 @@ namespace platf { } std::array shell_command_string; + bool needs_cmd_escaping = false; { // Overriding these predefined keys affects process-wide state, so serialize all calls // to ensure the handle state is consistent while we perform the command query. @@ -689,6 +751,7 @@ namespace platf { if (res == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) { BOOST_LOG(warning) << "Using trampoline to handle target: "sv << raw_cmd; std::wcscpy(shell_command_string.data(), L"cmd.exe /c start \"\" \"%1\" %*"); + needs_cmd_escaping = true; res = S_OK; } @@ -752,10 +815,18 @@ namespace platf { // All arguments following the target case L'*': for (int i = 1; i < raw_cmd_parts.size(); i++) { + // Insert a space before arguments after the first one if (i > 1) { match_replacement += L' '; } - match_replacement += raw_cmd_parts.at(i); + + // Argument escaping applies only to %*, not the single substitutions like %2 + auto escaped_argument = escape_argument(raw_cmd_parts.at(i)); + if (needs_cmd_escaping) { + // If we're using the cmd.exe trampoline, we'll need to add additional escaping + escaped_argument = escape_argument_for_cmd(escaped_argument); + } + match_replacement += escaped_argument; } break; From 56da68c8632c3395c49fdecd5731ccd4421e760b Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 14 Feb 2024 21:39:14 -0600 Subject: [PATCH 005/129] Preserve backwards-compatible argument escaping behavior for executables --- src/platform/windows/misc.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index d3e98950abb..b53bfea5a6e 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -720,6 +720,13 @@ namespace platf { // to try to find it via PATH return from_utf8(raw_cmd); } + else if (boost::iequals(extension, L".exe")) { + // If the file has an .exe extension, we will bypass the resolution here and + // directly pass the unmodified command string to CreateProcess(). The argument + // escaping rules are subtly different between CreateProcess() and ShellExecute(), + // and we want to preserve backwards compatibility with older configs. + return from_utf8(raw_cmd); + } // For regular files, the class is found using the file extension (including the dot) lookup_string = extension; From d1a635809ac8cf7b16913479648d067159119e97 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 14 Feb 2024 23:28:32 -0600 Subject: [PATCH 006/129] Implement backwards compatibility for NVENC APIs back to Video Codec SDK v11.0 This allows NVENC on drivers 456.71 (October 2020) and later. --- src/nvenc/nvenc_base.cpp | 63 +++++++++++++++++++++++++++++++-------- src/nvenc/nvenc_base.h | 12 ++++++++ src/nvenc/nvenc_d3d11.cpp | 4 +-- 3 files changed, 65 insertions(+), 14 deletions(-) diff --git a/src/nvenc/nvenc_base.cpp b/src/nvenc/nvenc_base.cpp index 63107324f37..b9eba5a04df 100644 --- a/src/nvenc/nvenc_base.cpp +++ b/src/nvenc/nvenc_base.cpp @@ -4,6 +4,17 @@ #include "src/logging.h" #include "src/utility.h" +#define MAKE_NVENC_VER(major, minor) ((major) | ((minor) << 24)) + +// Make sure we check backwards compatibility when bumping the Video Codec SDK version +// Things to look out for: +// - NV_ENC_*_VER definitions where the value inside NVENCAPI_STRUCT_VERSION() was increased +// - Incompatible struct changes in nvEncodeAPI.h (fields removed, semantics changed, etc.) +// - Test both old and new drivers with all supported codecs +#if NVENCAPI_VERSION != MAKE_NVENC_VER(12U, 0U) + #error Check and update NVENC code for backwards compatibility! +#endif + namespace { GUID @@ -81,6 +92,10 @@ namespace nvenc { bool nvenc_base::create_encoder(const nvenc_config &config, const video::config_t &client_config, const nvenc_colorspace_t &colorspace, NV_ENC_BUFFER_FORMAT buffer_format) { + // Pick the minimum NvEncode API version required to support the specified codec + // to maximize driver compatibility. AV1 was introduced in SDK v12.0. + minimum_api_version = (client_config.videoFormat <= 1) ? MAKE_NVENC_VER(11U, 0U) : MAKE_NVENC_VER(12U, 0U); + if (!nvenc && !init_library()) return false; if (encoder) destroy_encoder(); @@ -91,12 +106,12 @@ namespace nvenc { encoder_params.buffer_format = buffer_format; encoder_params.rfi = true; - NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = { NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER }; + NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = { min_struct_version(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER) }; session_params.device = device; session_params.deviceType = device_type; - session_params.apiVersion = NVENCAPI_VERSION; + session_params.apiVersion = minimum_api_version; if (nvenc_failed(nvenc->nvEncOpenEncodeSessionEx(&session_params, &encoder))) { - BOOST_LOG(error) << "NvEncOpenEncodeSessionEx failed"; + BOOST_LOG(error) << "NvEncOpenEncodeSessionEx failed: " << last_error_string; return false; } @@ -112,7 +127,7 @@ namespace nvenc { return false; } - NV_ENC_INITIALIZE_PARAMS init_params = { NV_ENC_INITIALIZE_PARAMS_VER }; + NV_ENC_INITIALIZE_PARAMS init_params = { min_struct_version(NV_ENC_INITIALIZE_PARAMS_VER) }; switch (client_config.videoFormat) { case 0: @@ -146,7 +161,7 @@ namespace nvenc { } auto get_encoder_cap = [&](NV_ENC_CAPS cap) { - NV_ENC_CAPS_PARAM param = { NV_ENC_CAPS_PARAM_VER, cap }; + NV_ENC_CAPS_PARAM param = { min_struct_version(NV_ENC_CAPS_PARAM_VER), cap }; int value = 0; nvenc->nvEncGetEncodeCaps(encoder, init_params.encodeGUID, ¶m, &value); return value; @@ -199,7 +214,7 @@ namespace nvenc { init_params.frameRateNum = client_config.framerate; init_params.frameRateDen = 1; - NV_ENC_PRESET_CONFIG preset_config = { NV_ENC_PRESET_CONFIG_VER, { NV_ENC_CONFIG_VER } }; + NV_ENC_PRESET_CONFIG preset_config = { min_struct_version(NV_ENC_PRESET_CONFIG_VER), { min_struct_version(NV_ENC_CONFIG_VER, 7, 8) } }; if (nvenc_failed(nvenc->nvEncGetEncodePresetConfigEx(encoder, init_params.encodeGUID, init_params.presetGUID, init_params.tuningInfo, &preset_config))) { BOOST_LOG(error) << "NvEncGetEncodePresetConfigEx failed: " << last_error_string; return false; @@ -344,7 +359,7 @@ namespace nvenc { } if (async_event_handle) { - NV_ENC_EVENT_PARAMS event_params = { NV_ENC_EVENT_PARAMS_VER }; + NV_ENC_EVENT_PARAMS event_params = { min_struct_version(NV_ENC_EVENT_PARAMS_VER) }; event_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncRegisterAsyncEvent(encoder, &event_params))) { BOOST_LOG(error) << "NvEncRegisterAsyncEvent failed: " << last_error_string; @@ -352,7 +367,7 @@ namespace nvenc { } } - NV_ENC_CREATE_BITSTREAM_BUFFER create_bitstream_buffer = { NV_ENC_CREATE_BITSTREAM_BUFFER_VER }; + NV_ENC_CREATE_BITSTREAM_BUFFER create_bitstream_buffer = { min_struct_version(NV_ENC_CREATE_BITSTREAM_BUFFER_VER) }; if (nvenc_failed(nvenc->nvEncCreateBitstreamBuffer(encoder, &create_bitstream_buffer))) { BOOST_LOG(error) << "NvEncCreateBitstreamBuffer failed: " << last_error_string; return false; @@ -394,7 +409,7 @@ namespace nvenc { output_bitstream = nullptr; } if (encoder && async_event_handle) { - NV_ENC_EVENT_PARAMS event_params = { NV_ENC_EVENT_PARAMS_VER }; + NV_ENC_EVENT_PARAMS event_params = { min_struct_version(NV_ENC_EVENT_PARAMS_VER) }; event_params.completionEvent = async_event_handle; nvenc->nvEncUnregisterAsyncEvent(encoder, &event_params); } @@ -420,7 +435,7 @@ namespace nvenc { assert(registered_input_buffer); assert(output_bitstream); - NV_ENC_MAP_INPUT_RESOURCE mapped_input_buffer = { NV_ENC_MAP_INPUT_RESOURCE_VER }; + NV_ENC_MAP_INPUT_RESOURCE mapped_input_buffer = { min_struct_version(NV_ENC_MAP_INPUT_RESOURCE_VER) }; mapped_input_buffer.registeredResource = registered_input_buffer; if (nvenc_failed(nvenc->nvEncMapInputResource(encoder, &mapped_input_buffer))) { @@ -429,7 +444,7 @@ namespace nvenc { } auto unmap_guard = util::fail_guard([&] { nvenc->nvEncUnmapInputResource(encoder, &mapped_input_buffer); }); - NV_ENC_PIC_PARAMS pic_params = { NV_ENC_PIC_PARAMS_VER }; + NV_ENC_PIC_PARAMS pic_params = { min_struct_version(NV_ENC_PIC_PARAMS_VER, 4, 6) }; pic_params.inputWidth = encoder_params.width; pic_params.inputHeight = encoder_params.height; pic_params.encodePicFlags = force_idr ? NV_ENC_PIC_FLAG_FORCEIDR : 0; @@ -445,7 +460,7 @@ namespace nvenc { return {}; } - NV_ENC_LOCK_BITSTREAM lock_bitstream = { NV_ENC_LOCK_BITSTREAM_VER }; + NV_ENC_LOCK_BITSTREAM lock_bitstream = { min_struct_version(NV_ENC_LOCK_BITSTREAM_VER, 1, 2) }; lock_bitstream.outputBitstream = output_bitstream; lock_bitstream.doNotWait = 0; @@ -585,4 +600,28 @@ namespace nvenc { return false; } + /** + * @brief This function returns the corresponding struct version for the minimum API required by the codec. + * @details Reducing the struct versions maximizes driver compatibility by avoiding needless API breaks. + * @param version The raw structure version from `NVENCAPI_STRUCT_VERSION()`. + * @param v11_struct_version Optionally specifies the struct version to use with v11 SDK major versions. + * @param v12_struct_version Optionally specifies the struct version to use with v12 SDK major versions. + * @return A suitable struct version for the active codec. + */ + uint32_t + nvenc_base::min_struct_version(uint32_t version, uint32_t v11_struct_version, uint32_t v12_struct_version) { + assert(minimum_api_version); + + // Mask off and replace the original NVENCAPI_VERSION + version &= ~NVENCAPI_VERSION; + version |= minimum_api_version; + + // If there's a struct version override, apply that too + if (v11_struct_version || v12_struct_version) { + version &= ~(0xFFu << 16); + version |= (((minimum_api_version & 0xFF) >= 12) ? v12_struct_version : v11_struct_version) << 16; + } + + return version; + } } // namespace nvenc diff --git a/src/nvenc/nvenc_base.h b/src/nvenc/nvenc_base.h index aa02fbef620..2d012ef8da8 100644 --- a/src/nvenc/nvenc_base.h +++ b/src/nvenc/nvenc_base.h @@ -45,6 +45,17 @@ namespace nvenc { bool nvenc_failed(NVENCSTATUS status); + /** + * @brief This function returns the corresponding struct version for the minimum API required by the codec. + * @details Reducing the struct versions maximizes driver compatibility by avoiding needless API breaks. + * @param version The raw structure version from `NVENCAPI_STRUCT_VERSION()`. + * @param v11_struct_version Optionally specifies the struct version to use with v11 SDK major versions. + * @param v12_struct_version Optionally specifies the struct version to use with v12 SDK major versions. + * @return A suitable struct version for the active codec. + */ + uint32_t + min_struct_version(uint32_t version, uint32_t v11_struct_version = 0, uint32_t v12_struct_version = 0); + const NV_ENC_DEVICE_TYPE device_type; void *const device; @@ -68,6 +79,7 @@ namespace nvenc { private: NV_ENC_OUTPUT_PTR output_bitstream = nullptr; + uint32_t minimum_api_version = 0; struct { uint64_t last_encoded_frame_index = 0; diff --git a/src/nvenc/nvenc_d3d11.cpp b/src/nvenc/nvenc_d3d11.cpp index 7db6fdd2fa4..cb33a1801af 100644 --- a/src/nvenc/nvenc_d3d11.cpp +++ b/src/nvenc/nvenc_d3d11.cpp @@ -39,7 +39,7 @@ namespace nvenc { if ((dll = LoadLibraryEx(dll_name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32))) { if (auto create_instance = (decltype(NvEncodeAPICreateInstance) *) GetProcAddress(dll, "NvEncodeAPICreateInstance")) { auto new_nvenc = std::make_unique(); - new_nvenc->version = NV_ENCODE_API_FUNCTION_LIST_VER; + new_nvenc->version = min_struct_version(NV_ENCODE_API_FUNCTION_LIST_VER); if (nvenc_failed(create_instance(new_nvenc.get()))) { BOOST_LOG(error) << "NvEncodeAPICreateInstance failed: " << last_error_string; } @@ -83,7 +83,7 @@ namespace nvenc { } if (!registered_input_buffer) { - NV_ENC_REGISTER_RESOURCE register_resource = { NV_ENC_REGISTER_RESOURCE_VER }; + NV_ENC_REGISTER_RESOURCE register_resource = { min_struct_version(NV_ENC_REGISTER_RESOURCE_VER, 3, 4) }; register_resource.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX; register_resource.width = encoder_params.width; register_resource.height = encoder_params.height; From 8074bf8c8d0914bed80682f18be01826b18f794c Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Fri, 23 Feb 2024 20:00:53 -0500 Subject: [PATCH 007/129] fix(main): fix version printing (#2167) --- src/main.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index cbe481ee2e9..b8983e3d221 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -97,9 +97,6 @@ SessionMonitorWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { */ int main(int argc, char *argv[]) { - // the version should be printed to the log before anything else - BOOST_LOG(info) << PROJECT_NAME << " version: " << PROJECT_VER; - lifetime::argv = argv; task_pool_util::TaskPool::task_id_t force_shutdown = nullptr; @@ -197,6 +194,11 @@ main(int argc, char *argv[]) { bl::core::get()->add_sink(sink); auto fg = util::fail_guard(log_flush); + // logging can begin at this point + // if anything is logged prior to this point, it will appear in stdout, but not in the log viewer in the UI + // the version should be printed to the log before anything else + BOOST_LOG(info) << PROJECT_NAME << " version: " << PROJECT_VER; + if (!config::sunshine.cmd.name.empty()) { auto fn = cmd_to_func.find(config::sunshine.cmd.name); if (fn == std::end(cmd_to_func)) { From 341fdaad77d65f0c4ca18db5c489520032f4effd Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Fri, 23 Feb 2024 20:54:10 -0500 Subject: [PATCH 008/129] build(cmake): add option to skip cuda inheriting compile options (#2164) --- cmake/prep/options.cmake | 4 ++++ cmake/targets/common.cmake | 9 ++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cmake/prep/options.cmake b/cmake/prep/options.cmake index 7a8d728ba47..90f748eb8a8 100644 --- a/cmake/prep/options.cmake +++ b/cmake/prep/options.cmake @@ -6,6 +6,10 @@ option(SUNSHINE_REQUIRE_TRAY "Require system tray icon. Fail the build if tray r option(SUNSHINE_SYSTEM_WAYLAND_PROTOCOLS "Use system installation of wayland-protocols rather than the submodule." OFF) +option(CUDA_INHERIT_COMPILE_OPTIONS + "When building CUDA code, inherit compile options from the the main project. You may want to disable this if + your IDE throws errors about unknown flags after running cmake." ON) + if(APPLE) option(SUNSHINE_CONFIGURE_PORTFILE "Configure macOS Portfile. Recommended to use with SUNSHINE_CONFIGURE_ONLY" OFF) diff --git a/cmake/targets/common.cmake b/cmake/targets/common.cmake index cb5fe4e67d4..3dd629e0cab 100644 --- a/cmake/targets/common.cmake +++ b/cmake/targets/common.cmake @@ -28,9 +28,12 @@ set_target_properties(sunshine PROPERTIES CXX_STANDARD 17 VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR}) -foreach(flag IN LISTS SUNSHINE_COMPILE_OPTIONS) - list(APPEND SUNSHINE_COMPILE_OPTIONS_CUDA "$<$:--compiler-options=${flag}>") -endforeach() +# CLion complains about unknown flags after running cmake, and cannot add symbols to the index for cuda files +if(CUDA_INHERIT_COMPILE_OPTIONS) + foreach(flag IN LISTS SUNSHINE_COMPILE_OPTIONS) + list(APPEND SUNSHINE_COMPILE_OPTIONS_CUDA "$<$:--compiler-options=${flag}>") + endforeach() +endif() target_compile_options(sunshine PRIVATE $<$:${SUNSHINE_COMPILE_OPTIONS}>;$<$:${SUNSHINE_COMPILE_OPTIONS_CUDA};-std=c++17>) # cmake-lint: disable=C0301 From dde804f14b1e5acf8e07182ff9e3833521d33b83 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 23 Feb 2024 21:48:41 -0500 Subject: [PATCH 009/129] build(deps): bump third-party/ViGEmClient from `1920260` to `8d71f67` (#2168) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third-party/ViGEmClient | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third-party/ViGEmClient b/third-party/ViGEmClient index 19202603d40..8d71f6740ff 160000 --- a/third-party/ViGEmClient +++ b/third-party/ViGEmClient @@ -1 +1 @@ -Subproject commit 19202603d40202e34e06bf3a1a42c1eec0b1ec02 +Subproject commit 8d71f6740ffff4671cdadbca255ce528e3cd3fef From c6f94e93e0a8bb02c2f617843ce1ce55ce7352a9 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sat, 24 Feb 2024 22:34:53 -0500 Subject: [PATCH 010/129] build(cmake): error build on warning (#2165) --- .github/workflows/CI.yml | 12 ++++++++--- cmake/compile_definitions/common.cmake | 20 ++++++++++++++++++- cmake/compile_definitions/windows.cmake | 11 +++++++++- cmake/prep/options.cmake | 2 ++ docker/debian-bookworm.dockerfile | 1 + docker/debian-bullseye.dockerfile | 1 + docker/fedora-38.dockerfile | 1 + docker/fedora-39.dockerfile | 1 + docker/ubuntu-20.04.dockerfile | 1 + docker/ubuntu-22.04.dockerfile | 1 + packaging/linux/Arch/PKGBUILD | 1 + .../linux/flatpak/dev.lizardbyte.sunshine.yml | 1 + packaging/macos/Portfile | 3 ++- 13 files changed, 50 insertions(+), 6 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 4b53e3204e9..f1005458c93 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -400,7 +400,9 @@ jobs: mkdir -p artifacts cd build - cmake -DCMAKE_BUILD_TYPE=Release \ + cmake \ + -DBUILD_WERROR=ON \ + -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DSUNSHINE_ASSETS_DIR=share/sunshine \ -DSUNSHINE_EXECUTABLE_PATH=/usr/bin/sunshine \ @@ -576,7 +578,9 @@ jobs: run: | mkdir build cd build - cmake -DCMAKE_BUILD_TYPE=Release \ + cmake \ + -DBUILD_WERROR=ON \ + -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DSUNSHINE_ASSETS_DIR=local/sunshine/assets \ -DSUNSHINE_EXECUTABLE_PATH=/usr/bin/sunshine \ @@ -784,7 +788,9 @@ jobs: run: | mkdir build cd build - cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + cmake \ + -DBUILD_WERROR=ON \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DSUNSHINE_ASSETS_DIR=assets \ -G "MinGW Makefiles" \ .. diff --git a/cmake/compile_definitions/common.cmake b/cmake/compile_definitions/common.cmake index 94f1ac598cc..ca6ddcbb0f3 100644 --- a/cmake/compile_definitions/common.cmake +++ b/cmake/compile_definitions/common.cmake @@ -3,7 +3,25 @@ list(APPEND SUNSHINE_COMPILE_OPTIONS -Wall -Wno-sign-compare) # Wall - enable all warnings +# Werror - treat warnings as errors +# Wno-maybe-uninitialized/Wno-uninitialized - disable warnings for maybe uninitialized variables # Wno-sign-compare - disable warnings for signed/unsigned comparisons +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + # GCC specific compile options + + # GCC 12 and higher will complain about maybe-uninitialized + if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 12) + list(APPEND SUNSHINE_COMPILE_OPTIONS -Wno-maybe-uninitialized) + endif() +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # Clang specific compile options + + # Clang doesn't actually complain about this this, so disabling for now + # list(APPEND SUNSHINE_COMPILE_OPTIONS -Wno-uninitialized) +endif() +if(BUILD_WERROR) + list(APPEND SUNSHINE_COMPILE_OPTIONS -Werror) +endif() # setup assets directory if(NOT SUNSHINE_ASSETS_DIR) @@ -28,7 +46,7 @@ file(GLOB NVENC_SOURCES CONFIGURE_DEPENDS "src/nvenc/*.cpp" "src/nvenc/*.h") list(APPEND PLATFORM_TARGET_FILES ${NVENC_SOURCES}) configure_file("${CMAKE_SOURCE_DIR}/src/version.h.in" version.h @ONLY) -include_directories("${CMAKE_CURRENT_BINARY_DIR}") +include_directories("${CMAKE_CURRENT_BINARY_DIR}") # required for importing version.h set(SUNSHINE_TARGET_FILES "${CMAKE_SOURCE_DIR}/third-party/nanors/rs.c" diff --git a/cmake/compile_definitions/windows.cmake b/cmake/compile_definitions/windows.cmake index e3729927fc1..2095cc5baa4 100644 --- a/cmake/compile_definitions/windows.cmake +++ b/cmake/compile_definitions/windows.cmake @@ -6,6 +6,9 @@ enable_language(RC) set(CMAKE_RC_COMPILER windres) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") +# gcc complains about misleading indentation in some mingw includes +list(APPEND SUNSHINE_COMPILE_OPTIONS -Wno-misleading-indentation) + # curl add_definitions(-DCURL_STATICLIB) include_directories(SYSTEM ${CURL_STATIC_INCLUDE_DIRS}) @@ -28,8 +31,14 @@ file(GLOB NVPREFS_FILES CONFIGURE_DEPENDS include_directories(SYSTEM "${CMAKE_SOURCE_DIR}/third-party/ViGEmClient/include") set_source_files_properties("${CMAKE_SOURCE_DIR}/third-party/ViGEmClient/src/ViGEmClient.cpp" PROPERTIES COMPILE_DEFINITIONS "UNICODE=1;ERROR_INVALID_DEVICE_OBJECT_PARAMETER=650") +set(VIGEM_COMPILE_FLAGS "") +string(APPEND VIGEM_COMPILE_FLAGS "-Wno-unknown-pragmas ") +string(APPEND VIGEM_COMPILE_FLAGS "-Wno-misleading-indentation ") +string(APPEND VIGEM_COMPILE_FLAGS "-Wno-class-memaccess ") +string(APPEND VIGEM_COMPILE_FLAGS "-Wno-unused-function ") +string(APPEND VIGEM_COMPILE_FLAGS "-Wno-unused-variable ") set_source_files_properties("${CMAKE_SOURCE_DIR}/third-party/ViGEmClient/src/ViGEmClient.cpp" - PROPERTIES COMPILE_FLAGS "-Wno-unknown-pragmas -Wno-misleading-indentation -Wno-class-memaccess") + PROPERTIES COMPILE_FLAGS ${VIGEM_COMPILE_FLAGS}) # sunshine icon if(NOT DEFINED SUNSHINE_ICON_PATH) diff --git a/cmake/prep/options.cmake b/cmake/prep/options.cmake index 90f748eb8a8..9104320d31d 100644 --- a/cmake/prep/options.cmake +++ b/cmake/prep/options.cmake @@ -1,3 +1,5 @@ +option(BUILD_WERROR "Enable -Werror flag." OFF) + # if this option is set, the build will exit after configuring special package configuration files option(SUNSHINE_CONFIGURE_ONLY "Configure special files only, then exit." OFF) diff --git a/docker/debian-bookworm.dockerfile b/docker/debian-bookworm.dockerfile index a62e092eab4..d664ff8c8ee 100644 --- a/docker/debian-bookworm.dockerfile +++ b/docker/debian-bookworm.dockerfile @@ -105,6 +105,7 @@ RUN <<_MAKE #!/bin/bash set -e cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ diff --git a/docker/debian-bullseye.dockerfile b/docker/debian-bullseye.dockerfile index f355307631d..5f607c2481d 100644 --- a/docker/debian-bullseye.dockerfile +++ b/docker/debian-bullseye.dockerfile @@ -119,6 +119,7 @@ set -e source "$HOME/.nvm/nvm.sh" nvm use 20.9.0 cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ diff --git a/docker/fedora-38.dockerfile b/docker/fedora-38.dockerfile index 5408782d074..9ba496c5b97 100644 --- a/docker/fedora-38.dockerfile +++ b/docker/fedora-38.dockerfile @@ -105,6 +105,7 @@ RUN <<_MAKE #!/bin/bash set -e cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DSUNSHINE_ASSETS_DIR=share/sunshine \ diff --git a/docker/fedora-39.dockerfile b/docker/fedora-39.dockerfile index cc781a6730f..e942a8aa916 100644 --- a/docker/fedora-39.dockerfile +++ b/docker/fedora-39.dockerfile @@ -105,6 +105,7 @@ RUN <<_MAKE #!/bin/bash set -e cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DSUNSHINE_ASSETS_DIR=share/sunshine \ diff --git a/docker/ubuntu-20.04.dockerfile b/docker/ubuntu-20.04.dockerfile index d677830db5c..4a1dcf4867c 100644 --- a/docker/ubuntu-20.04.dockerfile +++ b/docker/ubuntu-20.04.dockerfile @@ -155,6 +155,7 @@ set -e source "$HOME/.nvm/nvm.sh" nvm use 20.9.0 cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ diff --git a/docker/ubuntu-22.04.dockerfile b/docker/ubuntu-22.04.dockerfile index ab6ec096a3b..fa2d5e19d85 100644 --- a/docker/ubuntu-22.04.dockerfile +++ b/docker/ubuntu-22.04.dockerfile @@ -120,6 +120,7 @@ source "$HOME/.nvm/nvm.sh" nvm use 20.9.0 #Actually build cmake \ + -DBUILD_WERROR=ON \ -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ diff --git a/packaging/linux/Arch/PKGBUILD b/packaging/linux/Arch/PKGBUILD index a0ceb6b5684..4422698263e 100644 --- a/packaging/linux/Arch/PKGBUILD +++ b/packaging/linux/Arch/PKGBUILD @@ -61,6 +61,7 @@ build() { -S "$pkgname" \ -B build \ -Wno-dev \ + -D BUILD_WERROR=ON \ -D CMAKE_INSTALL_PREFIX=/usr \ -D SUNSHINE_EXECUTABLE_PATH=/usr/bin/sunshine \ -D SUNSHINE_ASSETS_DIR="share/sunshine" diff --git a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml index b62f0e1d667..d9fe390045a 100644 --- a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml +++ b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml @@ -330,6 +330,7 @@ modules: npm_config_nodedir: /usr/lib/sdk/node18 NPM_CONFIG_LOGLEVEL: info config-opts: + - -DBUILD_WERROR=ON - -DCMAKE_BUILD_TYPE=Release - -DCMAKE_INSTALL_PREFIX=/app - -DCMAKE_CUDA_COMPILER=/app/cuda/bin/nvcc diff --git a/packaging/macos/Portfile b/packaging/macos/Portfile index 19aeccf2dbd..2ef8098f155 100644 --- a/packaging/macos/Portfile +++ b/packaging/macos/Portfile @@ -40,7 +40,8 @@ depends_lib port:avahi \ boost.version 1.81 -configure.args -DCMAKE_INSTALL_PREFIX=${prefix} \ +configure.args -DBUILD_WERROR=ON \ + -DCMAKE_INSTALL_PREFIX=${prefix} \ -DSUNSHINE_ASSETS_DIR=etc/sunshine/assets startupitem.create yes From 8a7a6c48f8048e701571ba88727345c9f6f9df48 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Mon, 26 Feb 2024 12:55:34 -0500 Subject: [PATCH 011/129] build(cmake) properly find evdev (#2176) --- cmake/compile_definitions/linux.cmake | 13 +++++++++++-- packaging/linux/flatpak/dev.lizardbyte.sunshine.yml | 1 - src/platform/linux/input.cpp | 2 ++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cmake/compile_definitions/linux.cmake b/cmake/compile_definitions/linux.cmake index 613a090947d..b6d1990a24e 100644 --- a/cmake/compile_definitions/linux.cmake +++ b/cmake/compile_definitions/linux.cmake @@ -120,6 +120,17 @@ elseif(NOT LIBDRM_FOUND) message(WARNING "Missing libcap") endif() +# evdev +pkg_check_modules(PC_EVDEV libevdev REQUIRED) +find_path(EVDEV_INCLUDE_DIR libevdev/libevdev.h + HINTS ${PC_EVDEV_INCLUDE_DIRS} ${PC_EVDEV_INCLUDEDIR}) +find_library(EVDEV_LIBRARY + NAMES evdev libevdev) +if(EVDEV_INCLUDE_DIR AND EVDEV_LIBRARY) + include_directories(SYSTEM ${EVDEV_INCLUDE_DIR}) + list(APPEND PLATFORM_LIBRARIES ${EVDEV_LIBRARY}) +endif() + # vaapi if(${SUNSHINE_ENABLE_VAAPI}) find_package(Libva) @@ -241,13 +252,11 @@ list(APPEND PLATFORM_TARGET_FILES list(APPEND PLATFORM_LIBRARIES Boost::dynamic_linking dl - evdev numa pulse pulse-simple) include_directories( SYSTEM - /usr/include/libevdev-1.0 "${CMAKE_SOURCE_DIR}/third-party/nv-codec-headers/include" "${CMAKE_SOURCE_DIR}/third-party/glad/include") diff --git a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml index d9fe390045a..a4176d4ea15 100644 --- a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml +++ b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml @@ -325,7 +325,6 @@ modules: append-path: /usr/lib/sdk/node18/bin build-args: - --share=network - cxxflags: -I${C_INCLUDE_PATH}/libevdev-1.0 env: npm_config_nodedir: /usr/lib/sdk/node18 NPM_CONFIG_LOGLEVEL: info diff --git a/src/platform/linux/input.cpp b/src/platform/linux/input.cpp index 85818110730..42e239980d8 100644 --- a/src/platform/linux/input.cpp +++ b/src/platform/linux/input.cpp @@ -6,8 +6,10 @@ #include #include +extern "C" { #include #include +} #ifdef SUNSHINE_BUILD_X11 #include From 11c5b64d397cb51d6de755320e7134f7b01ec304 Mon Sep 17 00:00:00 2001 From: James Le Cuirot Date: Mon, 26 Feb 2024 23:53:56 +0000 Subject: [PATCH 012/129] Use nlohmann_json package instead of submodule (#2161) --- .github/workflows/CI.yml | 1 + .gitmodules | 4 ---- cmake/compile_definitions/common.cmake | 3 +-- cmake/compile_definitions/windows.cmake | 1 + cmake/dependencies/common.cmake | 3 --- cmake/dependencies/windows.cmake | 3 +++ docs/source/building/windows.rst | 1 + packaging/macos/Portfile | 7 ++++--- third-party/nlohmann_json | 1 - 9 files changed, 11 insertions(+), 13 deletions(-) delete mode 160000 third-party/nlohmann_json diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index f1005458c93..60f555c2166 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -769,6 +769,7 @@ jobs: mingw-w64-x86_64-cmake mingw-w64-x86_64-curl mingw-w64-x86_64-miniupnpc + mingw-w64-x86_64-nlohmann-json mingw-w64-x86_64-nodejs mingw-w64-x86_64-nsis mingw-w64-x86_64-onevpl diff --git a/.gitmodules b/.gitmodules index 67522f450ed..a4231d16f72 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,10 +10,6 @@ path = third-party/nanors url = https://github.com/sleepybishop/nanors.git branch = master -[submodule "third-party/nlohmann_json"] - path = third-party/nlohmann_json - url = https://github.com/nlohmann/json - branch = master [submodule "third-party/nv-codec-headers"] path = third-party/nv-codec-headers url = https://github.com/FFmpeg/nv-codec-headers diff --git a/cmake/compile_definitions/common.cmake b/cmake/compile_definitions/common.cmake index ca6ddcbb0f3..646e1298e43 100644 --- a/cmake/compile_definitions/common.cmake +++ b/cmake/compile_definitions/common.cmake @@ -152,5 +152,4 @@ list(APPEND SUNSHINE_EXTERNAL_LIBRARIES ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${CURL_LIBRARIES} - ${PLATFORM_LIBRARIES} - nlohmann_json::nlohmann_json) + ${PLATFORM_LIBRARIES}) diff --git a/cmake/compile_definitions/windows.cmake b/cmake/compile_definitions/windows.cmake index 2095cc5baa4..699a84c184d 100644 --- a/cmake/compile_definitions/windows.cmake +++ b/cmake/compile_definitions/windows.cmake @@ -84,6 +84,7 @@ list(PREPEND PLATFORM_LIBRARIES avrt iphlpapi shlwapi + PkgConfig::NLOHMANN_JSON ${CURL_STATIC_LIBRARIES}) if(SUNSHINE_ENABLE_TRAY) diff --git a/cmake/dependencies/common.cmake b/cmake/dependencies/common.cmake index a1f35128005..29bed10e5cd 100644 --- a/cmake/dependencies/common.cmake +++ b/cmake/dependencies/common.cmake @@ -19,9 +19,6 @@ pkg_check_modules(CURL REQUIRED libcurl) pkg_check_modules(MINIUPNP miniupnpc REQUIRED) include_directories(SYSTEM ${MINIUPNP_INCLUDE_DIRS}) -# nlohmann_json -add_subdirectory("${CMAKE_SOURCE_DIR}/third-party/nlohmann_json") - # ffmpeg pre-compiled binaries if(WIN32) if(NOT CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64") diff --git a/cmake/dependencies/windows.cmake b/cmake/dependencies/windows.cmake index 376c44da65a..a7ecce3963d 100644 --- a/cmake/dependencies/windows.cmake +++ b/cmake/dependencies/windows.cmake @@ -2,3 +2,6 @@ set(Boost_USE_STATIC_LIBS ON) # cmake-lint: disable=C0103 find_package(Boost 1.71.0 COMPONENTS locale log filesystem program_options REQUIRED) + +# nlohmann_json +pkg_check_modules(NLOHMANN_JSON nlohmann_json REQUIRED IMPORTED_TARGET) diff --git a/docs/source/building/windows.rst b/docs/source/building/windows.rst index 8e83c58e99d..f73346ffebf 100644 --- a/docs/source/building/windows.rst +++ b/docs/source/building/windows.rst @@ -26,6 +26,7 @@ Install dependencies: mingw-w64-x86_64-cmake \ mingw-w64-x86_64-curl \ mingw-w64-x86_64-miniupnpc \ + mingw-w64-x86_64-nlohmann-json \ mingw-w64-x86_64-nodejs \ mingw-w64-x86_64-onevpl \ mingw-w64-x86_64-openssl \ diff --git a/packaging/macos/Portfile b/packaging/macos/Portfile index 2ef8098f155..ba4815e25dc 100644 --- a/packaging/macos/Portfile +++ b/packaging/macos/Portfile @@ -31,12 +31,13 @@ post-fetch { system -W ${worksrcpath} "${git.cmd} submodule update --init --recursive" } +depends_build-append port:npm9 \ + port:pkgconfig + depends_lib port:avahi \ port:curl \ port:libopus \ - port:miniupnpc \ - port:npm9 \ - port:pkgconfig + port:miniupnpc boost.version 1.81 diff --git a/third-party/nlohmann_json b/third-party/nlohmann_json deleted file mode 160000 index 9cca280a4d0..00000000000 --- a/third-party/nlohmann_json +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9cca280a4d0ccf0c08f47a99aa71d1b0e52f8d03 From c605a4da2b8d19c079ce047abb22981a2fac5b05 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Feb 2024 21:36:59 -0500 Subject: [PATCH 013/129] build(deps): bump peter-evans/create-pull-request from 5 to 6 (#2083) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/localize.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/localize.yml b/.github/workflows/localize.yml index f9cd64859bb..815b67585ce 100644 --- a/.github/workflows/localize.yml +++ b/.github/workflows/localize.yml @@ -77,7 +77,7 @@ jobs: run: echo "date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT - name: Create/Update Pull Request - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v6 with: add-paths: | locale/*.po From 53b2217a34ef04a25554651a3270962cdfcf8dee Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Feb 2024 22:33:13 -0500 Subject: [PATCH 014/129] build(deps): bump bootstrap from 5.3.2 to 5.3.3 (#2154) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4a709402bb3..b685e0966a4 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "@fortawesome/fontawesome-free": "6.5.1", "@popperjs/core": "2.11.8", "@vitejs/plugin-vue": "4.6.2", - "bootstrap": "5.3.2", + "bootstrap": "5.3.3", "vite": "4.5.2", "vite-plugin-ejs": "1.6.4", "vue": "3.4.5" From 83e3ea5aa7cc87b17653838b8da04528d3763bf6 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 25 Feb 2024 19:23:58 -0600 Subject: [PATCH 015/129] Use a common function to abort for debugging purposes --- src/entry_handler.cpp | 12 ++++++++++++ src/entry_handler.h | 2 ++ src/main.cpp | 4 ++-- src/platform/windows/misc.cpp | 2 +- src/stream.cpp | 2 +- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp index c7719eb0ed1..146a4dfb07b 100644 --- a/src/entry_handler.cpp +++ b/src/entry_handler.cpp @@ -166,6 +166,18 @@ namespace lifetime { } } + /** + * @brief Breaks into the debugger or terminates Sunshine if no debugger is attached. + */ + void + debug_trap() { +#ifdef _WIN32 + DebugBreak(); +#else + std::raise(SIGTRAP); +#endif + } + /** * @brief Gets the argv array passed to main(). */ diff --git a/src/entry_handler.h b/src/entry_handler.h index c58d0325d70..bdab361cf0c 100644 --- a/src/entry_handler.h +++ b/src/entry_handler.h @@ -42,6 +42,8 @@ namespace lifetime { extern std::atomic_int desired_exit_code; void exit_sunshine(int exit_code, bool async); + void + debug_trap(); char ** get_argv(); } // namespace lifetime diff --git a/src/main.cpp b/src/main.cpp index b8983e3d221..5cc28f9f2a2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -318,7 +318,7 @@ main(int argc, char *argv[]) { auto task = []() { BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; log_flush(); - std::abort(); + lifetime::debug_trap(); }; force_shutdown = task_pool.pushDelayed(task, 10s).task_id; @@ -331,7 +331,7 @@ main(int argc, char *argv[]) { auto task = []() { BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; log_flush(); - std::abort(); + lifetime::debug_trap(); }; force_shutdown = task_pool.pushDelayed(task, 10s).task_id; diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index b53bfea5a6e..77de69f4cd3 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -489,7 +489,7 @@ namespace platf { auto winerror = GetLastError(); // Log the failure of reverting to self and its error code BOOST_LOG(fatal) << "Failed to revert to self after impersonation: "sv << winerror; - std::abort(); + DebugBreak(); } return ec; diff --git a/src/stream.cpp b/src/stream.cpp index b9238057b1c..9c146804523 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -1815,7 +1815,7 @@ namespace stream { auto task = []() { BOOST_LOG(fatal) << "Hang detected! Session failed to terminate in 10 seconds."sv; log_flush(); - std::abort(); + lifetime::debug_trap(); }; auto force_kill = task_pool.pushDelayed(task, 10s).task_id; auto fg = util::fail_guard([&force_kill]() { From 1020d0c133c027eb542161dc620b83d88f6f87ad Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 27 Feb 2024 00:25:22 -0600 Subject: [PATCH 016/129] Install ViGEmBus before starting Sunshine --- cmake/packaging/windows.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/packaging/windows.cmake b/cmake/packaging/windows.cmake index 1ea1afe191d..2b512ed6999 100644 --- a/cmake/packaging/windows.cmake +++ b/cmake/packaging/windows.cmake @@ -57,8 +57,8 @@ SET(CPACK_NSIS_EXTRA_INSTALL_COMMANDS nsExec::ExecToLog 'icacls \\\"$INSTDIR\\\" /reset' nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\migrate-config.bat\\\"' nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\add-firewall-rule.bat\\\"' - nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\install-service.bat\\\"' nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\install-gamepad.bat\\\"' + nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\install-service.bat\\\"' nsExec::ExecToLog '\\\"$INSTDIR\\\\scripts\\\\autostart-service.bat\\\"' NoController: ") From a0d5973799b455203770c876f0ec0469abab84ee Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 27 Feb 2024 00:27:09 -0600 Subject: [PATCH 017/129] Avoid display switching unexpectedly when the UAC secure desktop appears --- src/platform/windows/display_base.cpp | 38 ++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index a5f8cc5d31a..b258690e10e 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -358,8 +358,15 @@ namespace platf::dxgi { return false; } + /** + * @brief Tests to determine if the Desktop Duplication API can capture the given output. + * @details When testing for enumeration only, we avoid resyncing the thread desktop. + * @param adapter The DXGI adapter to use for capture. + * @param output The DXGI output to capture. + * @param enumeration_only Specifies whether this test is occurring for display enumeration. + */ bool - test_dxgi_duplication(adapter_t &adapter, output_t &output) { + test_dxgi_duplication(adapter_t &adapter, output_t &output, bool enumeration_only) { D3D_FEATURE_LEVEL featureLevels[] { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, @@ -397,14 +404,26 @@ namespace platf::dxgi { for (int x = 0; x < 2; ++x) { dup_t dup; - // Ensure we can duplicate the current display - syncThreadDesktop(); + // Only resynchronize the thread desktop when not enumerating displays. + // During enumeration, the caller will do this only once to ensure + // a consistent view of available outputs. + if (!enumeration_only) { + syncThreadDesktop(); + } status = output1->DuplicateOutput((IUnknown *) device.get(), &dup); if (SUCCEEDED(status)) { return true; } - std::this_thread::sleep_for(200ms); + + // If we're not resyncing the thread desktop and we don't have permission to + // capture the current desktop, just bail immediately. Retrying won't help. + if (enumeration_only && status == E_ACCESSDENIED) { + break; + } + else { + std::this_thread::sleep_for(200ms); + } } BOOST_LOG(error) << "DuplicateOutput() test failed [0x"sv << util::hex(status).to_string_view() << ']'; @@ -472,7 +491,7 @@ namespace platf::dxgi { continue; } - if (desc.AttachedToDesktop && test_dxgi_duplication(adapter_tmp, output_tmp)) { + if (desc.AttachedToDesktop && test_dxgi_duplication(adapter_tmp, output_tmp, false)) { output = std::move(output_tmp); offset_x = desc.DesktopCoordinates.left; @@ -1068,6 +1087,13 @@ namespace platf { BOOST_LOG(warning) << "Failed to set GPU preference. Capture may not work!"sv; } + // We sync the thread desktop once before we start the enumeration process + // to ensure test_dxgi_duplication() returns consistent results for all GPUs + // even if the current desktop changes during our enumeration process. + // It is critical that we either fully succeed in enumeration or fully fail, + // otherwise it can lead to the capture code switching monitors unexpectedly. + syncThreadDesktop(); + dxgi::factory1_t factory; status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory); if (FAILED(status)) { @@ -1111,7 +1137,7 @@ namespace platf { << std::endl; // Don't include the display in the list if we can't actually capture it - if (desc.AttachedToDesktop && dxgi::test_dxgi_duplication(adapter, output)) { + if (desc.AttachedToDesktop && dxgi::test_dxgi_duplication(adapter, output, true)) { display_names.emplace_back(std::move(device_name)); } } From 15272fb47ebb594d2d089e5f04fc24cf0d5f4af7 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Thu, 29 Feb 2024 10:33:19 -0500 Subject: [PATCH 018/129] fix(config): properly save global_prep_cmd and fps (#2192) --- src_assets/common/assets/web/config.html | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index e9d866dde51..b90ab7ed1ac 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -1408,12 +1408,20 @@

this.tabs.forEach(tab => { Object.keys(tab.options).forEach(optionKey => { let delete_value = false - if (optionKey === "global_prep_cmd" || optionKey === "resolutions" || optionKey === "fps") { - let regex = /([\d]+x[\d]+)/g // this regex is only needed for resolutions - // Use a regular expression to find each value and replace it with a quoted version - let config_value = JSON.parse(config[optionKey].replace(regex, '"$1"')).toString() - let default_value = JSON.parse(tab.options[optionKey].replace(regex, '"$1"')).toString() + if (["resolutions", "fps", "global_prep_cmd"].includes(optionKey)) { + let config_value, default_value + + if (optionKey === "resolutions") { + let regex = /([\d]+x[\d]+)/g + + // Use a regular expression to find each value and replace it with a quoted version + config_value = JSON.parse(config[optionKey].replace(regex, '"$1"')).toString() + default_value = JSON.parse(tab.options[optionKey].replace(regex, '"$1"')).toString() + } else { + config_value = JSON.parse(config[optionKey]) + default_value = JSON.parse(tab.options[optionKey]) + } if (config_value === default_value) { delete_value = true From 4252f5df7c95e492adee29976e6581bb4597ad16 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 21:42:52 -0600 Subject: [PATCH 019/129] Add option to allow HEVC usage on older Intel GPUs without low-power encoding --- docs/source/about/advanced_usage.rst | 16 ++++++++++++++++ src/config.cpp | 2 ++ src/config.h | 1 + src/video.cpp | 4 +++- src_assets/common/assets/web/config.html | 13 +++++++++++++ 5 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/source/about/advanced_usage.rst b/docs/source/about/advanced_usage.rst index fe603e38174..aae82ae7bd1 100644 --- a/docs/source/about/advanced_usage.rst +++ b/docs/source/about/advanced_usage.rst @@ -1424,6 +1424,22 @@ keybindings qsv_coder = auto +`qsv_slow_hevc `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + This options enables use of HEVC on older Intel GPUs that only support low power encoding for H.264. + + .. Caution:: Streaming performance may be significantly reduced when this option is enabled. + +**Default** + ``disabled`` + +**Example** + .. code-block:: text + + qsv_slow_hevc = disabled + `AMD AMF Encoder `__ --------------------------------------------------------------------- diff --git a/src/config.cpp b/src/config.cpp index d9aaab3e31c..ba2718aca7f 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -339,6 +339,7 @@ namespace config { { qsv::medium, // preset qsv::_auto, // cavlc + false, // slow_hevc }, // qsv { @@ -962,6 +963,7 @@ namespace config { 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); std::string quality; string_f(vars, "amd_quality", quality); diff --git a/src/config.h b/src/config.h index e08a87f3c4d..6c48f466b8e 100644 --- a/src/config.h +++ b/src/config.h @@ -44,6 +44,7 @@ namespace config { struct { std::optional qsv_preset; std::optional qsv_cavlc; + bool qsv_slow_hevc; } qsv; struct { diff --git a/src/video.cpp b/src/video.cpp index 636bcf60138..b73c0a4dd4b 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -763,7 +763,9 @@ namespace video { { "profile"s, (int) qsv::profile_hevc_e::main_10 }, }, // Fallback options - {}, + { + { "low_power"s, []() { return config::video.qsv.qsv_slow_hevc ? 0 : 1; } }, + }, std::nullopt, // QP rate control fallback "hevc_qsv"s, }, diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index b90ab7ed1ac..85fecacd0d9 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -1021,6 +1021,18 @@

+ +
+ + +
+ This can enable HEVC encoding on older Intel GPUs, at the cost of higher GPU usage and worse performance. +
+
+ @@ -1293,6 +1305,7 @@

options: { "qsv_preset": "medium", "qsv_coder": "auto", + "qsv_slow_hevc": "disabled", }, }, { From e9bb5697b05e8fc834ae15c78bc715819574e817 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 21:44:14 -0600 Subject: [PATCH 020/129] Move UPnP option to the top of the Network tab --- docs/source/about/advanced_usage.rst | 52 ++++++++++++------------ src_assets/common/assets/web/config.html | 22 +++++----- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/docs/source/about/advanced_usage.rst b/docs/source/about/advanced_usage.rst index aae82ae7bd1..6d87eb0c028 100644 --- a/docs/source/about/advanced_usage.rst +++ b/docs/source/about/advanced_usage.rst @@ -712,6 +712,32 @@ keybindings `Network `__ ----------------------------------------------------- +`upnp `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + Sunshine will attempt to open ports for streaming over the internet. + +**Choices** + +.. table:: + :widths: auto + + ===== =========== + Value Description + ===== =========== + on enable UPnP + off disable UPnP + ===== =========== + +**Default** + ``disabled`` + +**Example** + .. code-block:: text + + upnp = on + `address_family `__ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -798,32 +824,6 @@ keybindings origin_web_ui_allowed = lan -`upnp `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - Sunshine will attempt to open ports for streaming over the internet. - -**Choices** - -.. table:: - :widths: auto - - ===== =========== - Value Description - ===== =========== - on enable UPnP - off disable UPnP - ===== =========== - -**Default** - ``disabled`` - -**Example** - .. code-block:: text - - upnp = on - `external_ip `__ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index 85fecacd0d9..315ad75f370 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -553,6 +553,16 @@

+ +
+ + +
Automatically configure port forwarding for streaming over the Internet
+
+
@@ -649,16 +659,6 @@

- -
- - -
Automatically configure port forwarding
-
-
@@ -1261,10 +1261,10 @@

id: "network", name: "Network", options: { + "upnp": "disabled", "address_family": "ipv4", "port": 47989, "origin_web_ui_allowed": "lan", - "upnp": "disabled", "external_ip": "", "lan_encryption_mode": 0, "wan_encryption_mode": 1, From dfb212cc3ce885580ff09c0d9a667fb3963c47d6 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 21:45:01 -0600 Subject: [PATCH 021/129] Don't display automatic gamepad options on unsupported platforms --- src_assets/common/assets/web/config.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index 315ad75f370..c1305adddd7 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -221,7 +221,7 @@

-
+

- +
- +
- Adaptive P-State algorithm which NVIDIA drivers employ doesn't work well with low latency streaming, so - sunshine requests high power mode explicitly.
+ Sunshine requests maximum GPU clock speed while streaming to reduce encoding latency.
Disabling it is not recommended since this can lead to significantly increased encoding latency.
From 2e97c55005d09e1fea6636bc071919d481988fca Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 22:00:46 -0600 Subject: [PATCH 023/129] Move and rename Channels option to feature more prominently in the UI --- docs/source/about/advanced_usage.rst | 41 +++++++++++------------- src_assets/common/assets/web/config.html | 25 ++++++--------- 2 files changed, 28 insertions(+), 38 deletions(-) diff --git a/docs/source/about/advanced_usage.rst b/docs/source/about/advanced_usage.rst index 6d87eb0c028..f376f65887d 100644 --- a/docs/source/about/advanced_usage.rst +++ b/docs/source/about/advanced_usage.rst @@ -92,6 +92,24 @@ editing the `conf` file in a text editor. Use the examples as reference. min_log_level = info +`channels `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + Sunshine can support multiple clients streaming simultaneously, at the cost of higher CPU and GPU usage. + + .. note:: All connected clients share control of the same streaming session. + + .. warning:: Some hardware encoders may have limitations that reduce performance with multiple streams. + +**Default** + ``1`` + +**Example** + .. code-block:: text + + channels = 1 + `global_prep_cmd `__ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -913,29 +931,6 @@ keybindings `Advanced `__ ------------------------------------------------------- -`channels `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - This will generate distinct video streams, unlike simply broadcasting to multiple Clients. - - When multicasting, it could be useful to have different configurations for each connected Client. - - For instance: - - - Clients connected through WAN and LAN have different bitrate constraints. - - Decoders may require different settings for color. - - .. warning:: CPU usage increases for each distinct video stream generated. - -**Default** - ``1`` - -**Example** - .. code-block:: text - - channels = 1 - `fec_percentage `__ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index 17aea3d1e7e..3921f966811 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -64,6 +64,16 @@

Configuration

+ +
+ + +
+ Sunshine can allow a single streaming session to be shared with multiple clients simultaneously.
+ Note: Some hardware encoders may have limitations that reduce performance with multiple streams. +
+
+
@@ -721,21 +731,6 @@

- -
- - -
- When multicasting, it could be useful to have different configurations for each connected Client. For example: -
    -
  • Clients connected through WAN and LAN have different bitrate constraints.
  • -
  • Decoders may require different settings for color
  • -
- Unlike simply broadcasting to multiple Client, this will generate distinct video streams.
- Note, CPU usage increases for each distinct video stream generated -
-
-
From 8081f4167e379d2a93c6161ba9ca7bb1ece4d4bc Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 22:09:04 -0600 Subject: [PATCH 024/129] Add note to enclose paths with spaces in quotes --- src_assets/common/assets/web/apps.html | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src_assets/common/assets/web/apps.html b/src_assets/common/assets/web/apps.html index 36ddc5a9e6d..8156d0a6f48 100644 --- a/src_assets/common/assets/web/apps.html +++ b/src_assets/common/assets/web/apps.html @@ -197,7 +197,8 @@

Applications

- A list of commands to be run and forgotten about + A list of commands to be run in the background.
+ Note: If the path to the command executable contains spaces, you must enclose it in quotes.
@@ -206,8 +207,8 @@

Applications

- The main application, if it is not specified, a process is started - that sleeps indefinitely + The main application to start. If blank, no application will be started.
+ Note: If the path to the command executable contains spaces, you must enclose it in quotes.
From cb57322190fad8ac3f98e9d8346b5504669f4d1e Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 22:13:32 -0600 Subject: [PATCH 025/129] Move and rename Files tab to be less prominent --- docs/source/about/advanced_usage.rst | 185 +++++++++++------------ src_assets/common/assets/web/config.html | 142 ++++++++--------- 2 files changed, 163 insertions(+), 164 deletions(-) diff --git a/docs/source/about/advanced_usage.rst b/docs/source/about/advanced_usage.rst index f376f65887d..f29e6d05f8d 100644 --- a/docs/source/about/advanced_usage.rst +++ b/docs/source/about/advanced_usage.rst @@ -124,99 +124,6 @@ editing the `conf` file in a text editor. Use the examples as reference. global_prep_cmd = [{"do":"nircmd.exe setdisplay 1280 720 32 144","undo":"nircmd.exe setdisplay 2560 1440 32 144"}] -`Files `__ -------------------------------------------------- - -`file_apps `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The application configuration file path. The file contains a json formatted list of applications that can be started - by Moonlight. - -**Default** - OS and package dependent - -**Example** - .. code-block:: text - - file_apps = apps.json - -`credentials_file `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The file where user credentials for the UI are stored. - -**Default** - ``sunshine_state.json`` - -**Example** - .. code-block:: text - - credentials_file = sunshine_state.json - -`log_path `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The path where the sunshine log is stored. - -**Default** - ``sunshine.log`` - -**Example** - .. code-block:: text - - log_path = sunshine.log - -`pkey `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The private key used for the web UI and Moonlight client pairing. For best compatibility, this should be an RSA-2048 private key. - - .. warning:: Not all Moonlight clients support ECDSA keys or RSA key lengths other than 2048 bits. - -**Default** - ``credentials/cakey.pem`` - -**Example** - .. code-block:: text - - pkey = /dir/pkey.pem - -`cert `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The certificate used for the web UI and Moonlight client pairing. For best compatibility, this should have an RSA-2048 public key. - - .. warning:: Not all Moonlight clients support ECDSA keys or RSA key lengths other than 2048 bits. - -**Default** - ``credentials/cacert.pem`` - -**Example** - .. code-block:: text - - cert = /dir/cert.pem - -`file_state `__ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Description** - The file where current state of Sunshine is stored. - -**Default** - ``sunshine_state.json`` - -**Example** - .. code-block:: text - - file_state = sunshine_state.json - - `Input `__ ------------------------------------------------- @@ -928,6 +835,98 @@ keybindings ping_timeout = 10000 +`Config Files `__ +-------------------------------------------------------- + +`file_apps `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The application configuration file path. The file contains a json formatted list of applications that can be started + by Moonlight. + +**Default** + OS and package dependent + +**Example** + .. code-block:: text + + file_apps = apps.json + +`credentials_file `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The file where user credentials for the UI are stored. + +**Default** + ``sunshine_state.json`` + +**Example** + .. code-block:: text + + credentials_file = sunshine_state.json + +`log_path `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The path where the sunshine log is stored. + +**Default** + ``sunshine.log`` + +**Example** + .. code-block:: text + + log_path = sunshine.log + +`pkey `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The private key used for the web UI and Moonlight client pairing. For best compatibility, this should be an RSA-2048 private key. + + .. warning:: Not all Moonlight clients support ECDSA keys or RSA key lengths other than 2048 bits. + +**Default** + ``credentials/cakey.pem`` + +**Example** + .. code-block:: text + + pkey = /dir/pkey.pem + +`cert `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The certificate used for the web UI and Moonlight client pairing. For best compatibility, this should have an RSA-2048 public key. + + .. warning:: Not all Moonlight clients support ECDSA keys or RSA key lengths other than 2048 bits. + +**Default** + ``credentials/cacert.pem`` + +**Example** + .. code-block:: text + + cert = /dir/cert.pem + +`file_state `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The file where current state of Sunshine is stored. + +**Default** + ``sunshine_state.json`` + +**Example** + .. code-block:: text + + file_state = sunshine_state.json + `Advanced `__ ------------------------------------------------------- diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index 3921f966811..a072e101ba0 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -124,65 +124,6 @@

Configuration

- -
- -
- - -
- The file where current apps of Sunshine are stored -
-
- - -
- - -
- Store Username/Password separately from Sunshine's state file. -
-
- - -
- - -
- The file where the current logs of Sunshine are stored. -
-
- - -
- - -
The private key used for the web UI and Moonlight client pairing. For best - compatibility, this should be an RSA-2048 private key.
-
- - -
- - -
- The certificate used for the web UI and Moonlight client pairing. For best compatibility, this should have - an RSA-2048 public key. -
-
- - -
- - -
- The file where current state of Sunshine is stored -
-
- -
-
@@ -729,6 +670,65 @@

+ +
+ +
+ + +
+ The file where current apps of Sunshine are stored +
+
+ + +
+ + +
+ Store Username/Password separately from Sunshine's state file. +
+
+ + +
+ + +
+ The file where the current logs of Sunshine are stored. +
+
+ + +
+ + +
The private key used for the web UI and Moonlight client pairing. For best + compatibility, this should be an RSA-2048 private key.
+
+ + +
+ + +
+ The certificate used for the web UI and Moonlight client pairing. For best compatibility, this should have + an RSA-2048 public key. +
+
+ + +
+ + +
+ The file where current state of Sunshine is stored +
+
+ +
+
@@ -1204,18 +1204,6 @@

"global_prep_cmd": "[]", }, }, - { - id: "files", - name: "Files", - options: { - "file_apps": "", - "credentials_file": "", - "log_path": "", - "pkey": "", - "cert": "", - "file_state": "", - }, - }, { id: "input", name: "Input", @@ -1264,6 +1252,18 @@

"ping_timeout": 10000, }, }, + { + id: "files", + name: "Config Files", + options: { + "file_apps": "", + "credentials_file": "", + "log_path": "", + "pkey": "", + "cert": "", + "file_state": "", + }, + }, { id: "advanced", name: "Advanced", From e430f51e2fd981ed91aed79adbbacfcaa427c2a6 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 26 Feb 2024 22:43:34 -0600 Subject: [PATCH 026/129] Add friendly message when encoder detection fails --- src/video.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/video.cpp b/src/video.cpp index b73c0a4dd4b..f786aeb59f0 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -2721,7 +2721,13 @@ namespace video { } if (chosen_encoder == nullptr) { - BOOST_LOG(fatal) << "Couldn't find any working encoder"sv; + BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv; + if (!config::video.adapter_name.empty() || !config::video.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; + } return -1; } From 75a97883e71d1c17eb2784c110469042f520f81f Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sat, 24 Feb 2024 14:18:15 -0600 Subject: [PATCH 027/129] Rework dummy image handling to avoid RTX HDR driver bug As a side effect, it avoids useless allocations and uploads of a zeroed memory buffer to clear the dummy image textures. --- src/platform/windows/display_vram.cpp | 83 +++++++++++++-------------- 1 file changed, 39 insertions(+), 44 deletions(-) diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index e9f8140d525..a56869eab40 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -125,6 +125,9 @@ namespace platf::dxgi { // the first successful capture of a desktop frame bool dummy = false; + // Set to true if the image is blank (contains no content at all, including a cursor) + bool blank = true; + // Unique identifier for this image uint32_t id = 0; @@ -382,38 +385,40 @@ namespace platf::dxgi { } auto &img = (img_d3d_t &) img_base; - auto &img_ctx = img_ctx_map[img.id]; + if (!img.blank) { + auto &img_ctx = img_ctx_map[img.id]; - // Open the shared capture texture with our ID3D11Device - if (initialize_image_context(img, img_ctx)) { - return -1; - } + // Open the shared capture texture with our ID3D11Device + if (initialize_image_context(img, img_ctx)) { + return -1; + } - // Acquire encoder mutex to synchronize with capture code - auto status = img_ctx.encoder_mutex->AcquireSync(0, INFINITE); - if (status != S_OK) { - BOOST_LOG(error) << "Failed to acquire encoder mutex [0x"sv << util::hex(status).to_string_view() << ']'; - return -1; - } + // Acquire encoder mutex to synchronize with capture code + auto status = img_ctx.encoder_mutex->AcquireSync(0, INFINITE); + if (status != S_OK) { + BOOST_LOG(error) << "Failed to acquire encoder mutex [0x"sv << util::hex(status).to_string_view() << ']'; + return -1; + } - device_ctx->OMSetRenderTargets(1, &nv12_Y_rt, nullptr); - device_ctx->VSSetShader(scene_vs.get(), nullptr, 0); - device_ctx->PSSetShader(img.format == DXGI_FORMAT_R16G16B16A16_FLOAT ? convert_Y_fp16_ps.get() : convert_Y_ps.get(), nullptr, 0); - device_ctx->RSSetViewports(1, &outY_view); - device_ctx->PSSetShaderResources(0, 1, &img_ctx.encoder_input_res); - device_ctx->Draw(3, 0); + device_ctx->OMSetRenderTargets(1, &nv12_Y_rt, nullptr); + device_ctx->VSSetShader(scene_vs.get(), nullptr, 0); + device_ctx->PSSetShader(img.format == DXGI_FORMAT_R16G16B16A16_FLOAT ? convert_Y_fp16_ps.get() : convert_Y_ps.get(), nullptr, 0); + device_ctx->RSSetViewports(1, &outY_view); + device_ctx->PSSetShaderResources(0, 1, &img_ctx.encoder_input_res); + device_ctx->Draw(3, 0); - device_ctx->OMSetRenderTargets(1, &nv12_UV_rt, nullptr); - device_ctx->VSSetShader(convert_UV_vs.get(), nullptr, 0); - device_ctx->PSSetShader(img.format == DXGI_FORMAT_R16G16B16A16_FLOAT ? convert_UV_fp16_ps.get() : convert_UV_ps.get(), nullptr, 0); - device_ctx->RSSetViewports(1, &outUV_view); - device_ctx->Draw(3, 0); + device_ctx->OMSetRenderTargets(1, &nv12_UV_rt, nullptr); + device_ctx->VSSetShader(convert_UV_vs.get(), nullptr, 0); + device_ctx->PSSetShader(img.format == DXGI_FORMAT_R16G16B16A16_FLOAT ? convert_UV_fp16_ps.get() : convert_UV_ps.get(), nullptr, 0); + device_ctx->RSSetViewports(1, &outUV_view); + device_ctx->Draw(3, 0); - // Release encoder mutex to allow capture code to reuse this image - img_ctx.encoder_mutex->ReleaseSync(0); + // Release encoder mutex to allow capture code to reuse this image + img_ctx.encoder_mutex->ReleaseSync(0); - ID3D11ShaderResourceView *emptyShaderResourceView = nullptr; - device_ctx->PSSetShaderResources(0, 1, &emptyShaderResourceView); + ID3D11ShaderResourceView *emptyShaderResourceView = nullptr; + device_ctx->PSSetShaderResources(0, 1, &emptyShaderResourceView); + } return 0; } @@ -1144,6 +1149,9 @@ namespace platf::dxgi { return { nullptr, nullptr }; } + // Clear the blank flag now that we're ready to capture into the image + d3d_img->blank = false; + return { std::move(d3d_img), std::move(lock_helper) }; }; @@ -1289,15 +1297,14 @@ namespace platf::dxgi { // Clear the image if it has been used as a dummy. // It can have the mouse cursor blended onto it. auto old_d3d_img = (img_d3d_t *) img_out.get(); - bool reclear_dummy = old_d3d_img->dummy && old_d3d_img->capture_texture; + bool reclear_dummy = !old_d3d_img->blank && old_d3d_img->capture_texture; auto [d3d_img, lock] = get_locked_d3d_img(img_out, true); if (!d3d_img) return capture_e::error; if (reclear_dummy) { - auto dummy_data = std::make_unique(d3d_img->row_pitch * d3d_img->height); - std::fill_n(dummy_data.get(), d3d_img->row_pitch * d3d_img->height, 0); - device_ctx->UpdateSubresource(d3d_img->capture_texture.get(), 0, nullptr, dummy_data.get(), d3d_img->row_pitch, 0); + const float rgb_black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + device_ctx->ClearRenderTargetView(d3d_img->capture_rt.get(), rgb_black); } if (blend_mouse_cursor_flag) { @@ -1409,6 +1416,7 @@ namespace platf::dxgi { img->width = width_before_rotation; img->height = height_before_rotation; img->id = next_image_id++; + img->blank = true; return img; } @@ -1456,20 +1464,7 @@ namespace platf::dxgi { t.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; t.MiscFlags = D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; - HRESULT status; - if (dummy) { - auto dummy_data = std::make_unique(img->row_pitch * img->height); - std::fill_n(dummy_data.get(), img->row_pitch * img->height, 0); - D3D11_SUBRESOURCE_DATA initial_data { - dummy_data.get(), - (UINT) img->row_pitch, - 0 - }; - status = device->CreateTexture2D(&t, &initial_data, &img->capture_texture); - } - else { - status = device->CreateTexture2D(&t, nullptr, &img->capture_texture); - } + auto status = device->CreateTexture2D(&t, nullptr, &img->capture_texture); if (FAILED(status)) { BOOST_LOG(error) << "Failed to create img buf texture [0x"sv << util::hex(status).to_string_view() << ']'; return -1; From 1ab30aa70bc017ec3aa53a42f559f603d47db97c Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 1 Mar 2024 20:51:50 -0600 Subject: [PATCH 028/129] Add log messages to indicate display numbers for KMS and Wlgrab --- src/platform/linux/kmsgrab.cpp | 13 ++++++++++--- src/platform/linux/wlgrab.cpp | 6 ++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 192482deaa1..cd622fa775c 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -145,10 +145,13 @@ namespace platf { }; struct monitor_t { + // Connector attributes std::uint32_t type; - std::uint32_t index; + // Monitor index in the global list + std::uint32_t monitor_index; + platf::touch_port_t viewport; }; @@ -1516,11 +1519,11 @@ namespace platf { correlate_to_wayland(std::vector &cds) { auto monitors = wl::monitors(); + BOOST_LOG(info) << "-------- Start of KMS monitor list --------"sv; + for (auto &monitor : monitors) { std::string_view name = monitor->name; - BOOST_LOG(info) << name << ": "sv << monitor->description; - // Try to convert names in the format: // {type}-{index} // {index} is n'th occurrence of {type} @@ -1553,6 +1556,7 @@ namespace platf { << monitor->viewport.width << 'x' << monitor->viewport.height; } + BOOST_LOG(info) << "Monitor " << monitor_descriptor.monitor_index << " is "sv << name << ": "sv << monitor->description; goto break_for_loop; } } @@ -1561,6 +1565,8 @@ namespace platf { BOOST_LOG(verbose) << "Reduced to name: "sv << name << ": "sv << index; } + + BOOST_LOG(info) << "--------- End of KMS monitor list ---------"sv; } // A list of names of displays accepted as display_name @@ -1637,6 +1643,7 @@ namespace platf { (int) crtc->width, (int) crtc->height, }; + it->second.monitor_index = count; } kms::env_width = std::max(kms::env_width, (int) (crtc->x + crtc->width)); diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index 84b69bd0be0..2ea15359fc3 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -424,15 +424,21 @@ namespace platf { display.roundtrip(); + BOOST_LOG(info) << "-------- Start of Wayland monitor list --------"sv; + for (int x = 0; x < interface.monitors.size(); ++x) { auto monitor = interface.monitors[x].get(); wl::env_width = std::max(wl::env_width, (int) (monitor->viewport.offset_x + monitor->viewport.width)); wl::env_height = std::max(wl::env_height, (int) (monitor->viewport.offset_y + monitor->viewport.height)); + BOOST_LOG(info) << "Monitor " << x << " is "sv << monitor->name << ": "sv << monitor->description; + display_names.emplace_back(std::to_string(x)); } + BOOST_LOG(info) << "--------- End of Wayland monitor list ---------"sv; + return display_names; } From 5606840c8983b714a0e442c42d887a49807715e1 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 1 Mar 2024 20:52:17 -0600 Subject: [PATCH 029/129] Stop enumeration after finding a working capture backend --- src/platform/linux/misc.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index ecc5887e0f1..0075d4502f8 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -836,27 +836,29 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_CUDA - if (config::video.capture.empty() || config::video.capture == "nvfbc") { + if ((config::video.capture.empty() && sources.none()) || config::video.capture == "nvfbc") { if (verify_nvfbc()) { sources[source::NVFBC] = true; } } #endif #ifdef SUNSHINE_BUILD_WAYLAND - if (config::video.capture.empty() || config::video.capture == "wlr") { + if ((config::video.capture.empty() && sources.none()) || config::video.capture == "wlr") { if (verify_wl()) { sources[source::WAYLAND] = true; } } #endif #ifdef SUNSHINE_BUILD_DRM - if (config::video.capture.empty() || config::video.capture == "kms") { + if ((config::video.capture.empty() && sources.none()) || config::video.capture == "kms") { if (verify_kms()) { sources[source::KMS] = true; } } #endif #ifdef SUNSHINE_BUILD_X11 + // We enumerate this capture backend regardless of other suitable sources, + // since it may be needed as a NvFBC fallback for software encoding on X11. if (config::video.capture.empty() || config::video.capture == "x11") { if (verify_x11()) { sources[source::X11] = true; From 8d5a9054ec3b60349162033db28ec34c5c40a809 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 3 Mar 2024 16:50:20 -0500 Subject: [PATCH 030/129] chore: bump version to v0.22.0 (#2201) Co-authored-by: Cameron Gutman --- CHANGELOG.md | 127 +++++++++++++++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 2 +- 2 files changed, 128 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbeb4028382..037395640fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,131 @@ # Changelog +## [0.22.0] - 2024-03-03 +**Breaking** +- (Network) Clients must now be paired with the host before they can use Wake-on-LAN +- (Build/Linux) Drop Fedora 37 support + +**Added** +- (Input/Linux) Add native/pen touch support for Linux +- (Capture/Linux) Add HDR streaming support for Linux using KMS capture backend +- (Capture/Linux) Add KMS capture support for Nvidia GPUs running Wayland +- (Network) Add support for full E2E stream encryption, configurable for LAN and WAN independently +- (Process) Add process group tracking to automatically handle launchers that spawn other child processes +- (Capture/Windows) Add setting for controlling GPU power saving and encoding latency tradeoff for NVENC +- (Capture/Windows) Add additional encoding settings for NVENC +- (Process/Windows) Add experimental support for launching URLs and other non-exe files +- (Capture/Windows) Add setting to allow use of slower HEVC encoding on older Intel GPUs +- (Input/Windows) Add settings to control automatic gamepad type selection heuristics +- (Input/Windows) Add setting to allow DS4 back/select button to trigger touchpad click +- (Input) Add setting to disable high resolution scrolling and native pen/touch support +- (Network) Add support for certificates types other than RSA-2048 +- (Build/Linux) Add Fedora 39 docker image and rpm package +- (Capture/Linux) Display monitor indexes in logs for wlroots and KMS capture backends +- (UI) Add link to logs inside fatal error container +- (UI) Add hash handler and ids for all configuration categories and settings + +**Changed** +- (UI) Several configuration options have been moved to more suitable locations +- (Network) Client-selected bitrate is now adjusted for FEC percentage and other stream overhead +- (Capture/Linux) Improve VAAPI encoding performance on Intel GPUs +- (Capture) Connection establishment delay is reduced by eliminating many encoder probing operations +- (Process) Graceful termination of running processes is attempted first when stopping apps +- (Capture) Improve software encoding performance by enabling multi-threaded color conversion +- (Capture) Adjust default CPU thread count for software encoding from 1 to 2 for improved performance +- (Steam/Windows) Modernized the default Steam app shortcut to avoid depending on Steam's install location and support app termination +- (Linux) Updated desktop files +- (Config) Add 2560x1440 to default resolutions +- (Network) Use the configured ping timeout for the initial launch event timeout +- (UI) Migrate UI to Vite and Vue3, and various UX improvements +- (Logging) Adjust wording and severity of some log messages +- (Build) Use a single submodule for ffmpeg +- (Install/Windows) Skip ViGEmBus installation if a supported version is already installed +- (Build/Linux) Optionally, allow using the system installation of wayland-protocols +- (Build/Linux) Make vaapi optional +- (Windows) Replace boost::json with nlohmann/json + +**Fixed** +- (Network/Windows) Fix auto-discovery of hosts by iOS/tvOS clients +- (Network) Fix immediate connection termination when streaming over some Internet connections +- (Capture/Linux) Fix missing mouse cursor when using KMS capture on a GPU with hardware cursor support +- (Capture/Windows) Add workaround for Nvidia driver bug causing Sunshine to crash when RTX HDR is globally enabled +- (Capture/Windows) Add workaround for AMD driver bug on pre-RDNA GPUs causing hardware encoding failure +- (Capture/Windows) Reintroduce support for encoding on older Nvidia GPU drivers (v456.71-v522.25) +- (Capture/Windows) Fix encoding on old Intel GPUs that don't support low-power H.264 encoding +- (Capture/Linux) Fix GL errors or corrupt video output on GPUs that use aux planes such as Intel Arc +- (Capture/Linux) Fix GL errors or corrupt video output on GPUs that use DRM modifiers on YUV buffers +- (Input/Windows) Fix non-functional duplicate controllers appearing in rare cases +- (Input/Windows) Avoid triggering crash in ViGEmBus when the system goes to sleep +- (Input/Linux) Fix scrolling in applications that don't support high-resolution scrolling +- (Input/Linux) Fix absolute mouse input being interpreted as touch input +- (Capture/Linux) Fix wlroots capture causing GL errors and crashes +- (Capture/Linux) Fix wlroots capture failing when the display scale factor was not 1 +- (Capture/Linux) Fix excessive CPU usage when using wlroots capture backend +- (Capture/Linux) Fix capture of virtual displays created by the amdgpu kernel driver +- (Audio/Windows) Fix audio capture failures on Insider Preview versions of Windows 11 +- (Capture/Windows) Fix incorrect portrait mode rotation +- (Capture/Windows) Fix capture recovery when a driver update/crash occurs while streaming +- (Capture/Windows) Fix delay displaying UAC dialogs when the mouse cursor is not moving +- (Capture/Linux) Fix corrupt video output or stream disconnections if the display resolution changes while streaming +- (Capture/Linux) Fix color of aspect ratio padding in the capture image with VAAPI +- (Tray/Linux) Fix random crash when the tray icon is updating +- (Network) Fix QoS tagging when running in IPv4+IPv6 mode +- (Process) Fix termination of child processes upon app quit when the parent has already terminated +- (Process) Fix notification of graceful termination to connected clients when Sunshine quits +- (Capture) Fix corrupt output or green aspect-ratio padding when using software encoding with some video resolutions +- (Windows) Fix crashes when processing file paths or other strings with certain non-ASCII characters +- (Capture) Ensure user supplied framerates are used exclusively in place of pre-defined framerates +- (CMake/Linux) Skip including unnecessary headers +- (Capture/Linux) Replace vaTerminate method with dl handle +- (Capture/Linux) Fix capture when DRM is enabled and x11 is disabled +- (Tray) Use PROJECT_NAME definition for tooltip +- (CMake) Use GNUInstallDirs to install data and lib directories +- (macOS) Replace deprecated code +- (API) Allow trailing slashes in on API endpoints +- (API) Add additional pin validation +- (Linux) Use XDG spec for fetching config directory +- (CMake) Properly find evdev +- (Config) Properly save global_prep_cmd and fps settings + +**Dependencies** +- Bump third-party/wayland-protocols from 681c33c to 46f201b +- Bump third-party/nv-codec-headers from 9402b5a to 22441b5 +- Bump third-party/nanors from 395e5ad to e9e242e +- Bump third-party/Simple-Web-Server from 2f29926 to 27b41f5 +- Bump ffmpeg +- Bump third-party/tray from 2664388 to 2bf1c61 +- Bump actions/setup-python from 4 to 5 +- Bump actions/upload-artifact from 3 to 4 +- Bump @fortawesome/fontawesome-free from 6.4.2 to 6.5.1 +- Bump babel from 2.13.0 to 2.14.0 +- Move miniupnpc from submodule to system installed package +- Bump furo from 2023.9.10 to 2024.1.29 +- Bump third-party/moonlight-common-c from f78f213 to cbd0ec1 +- Bump third-party/ViGEmClient from 1920260 to 8d71f67 +- Bump peter-evans/create-pull-request from 5 to 6 +- Bump bootstrap from 5.3.2 to 5.3.3 + +**Misc** +- (Build) Update global workflows +- (Docs/Linux) Add example for setting custom resolution with NVIDIA +- (Docs) Fix broken links +- (Docs/Windows) Add information about disk permissions +- (Docs) Fix failing images +- (Docs) Use glob pattern to match source code docs +- (CI/macOS) Install boost from source +- (Docs) Add reset credentials examples for unique packages +- (Docs) Refactor and general cleanup +- (Docs) Cross-reference config settings to the UI +- (Docs/Docker) Add podman notes +- (Build) Use CMAKE_SOURCE_DIR property everywhere +- (Build/Docker) Add docker toolchain file for CLion +- (macOS) Various code style fixes +- (Deps) Alphabetize git submodules +- (Docs/Examples) Update URI examples +- (Refactor) Refactored some code in preparation for unit testing implementation +- (CMake) Add option to skip cuda inheriting compile options +- (CMake) Add option to error build on warnings + ## [0.21.0] - 2023-10-15 **Added** - (Input) Add support for automatically selecting the emulated controller type based on the physical controller connected to the client @@ -592,3 +718,4 @@ settings. In v0.17.0, games now run under your user account without elevated pri [0.19.1]: https://github.com/LizardByte/Sunshine/releases/tag/v0.19.1 [0.20.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.20.0 [0.21.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.21.0 +[0.22.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index 53d8bde2881..d672c9b8ae8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.18) # todo - set this conditionally # todo - set version to 0.0.0 once confident in automated versioning -project(Sunshine VERSION 0.21.0 +project(Sunshine VERSION 0.22.0 DESCRIPTION "Sunshine is a self-hosted game stream host for Moonlight." HOMEPAGE_URL "https://app.lizardbyte.dev/Sunshine") From 529f1b84f8a2c665a4442f72ec16aa86fbd8cc77 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 3 Mar 2024 18:37:06 -0600 Subject: [PATCH 031/129] Fix CUDA context leak causing encoder init failures using X11 capture with NVENC --- CHANGELOG.md | 3 ++- src/platform/linux/cuda.cu | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 037395640fa..5f8290545da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,7 +50,7 @@ - (Capture/Linux) Fix missing mouse cursor when using KMS capture on a GPU with hardware cursor support - (Capture/Windows) Add workaround for Nvidia driver bug causing Sunshine to crash when RTX HDR is globally enabled - (Capture/Windows) Add workaround for AMD driver bug on pre-RDNA GPUs causing hardware encoding failure -- (Capture/Windows) Reintroduce support for encoding on older Nvidia GPU drivers (v456.71-v522.25) +- (Capture/Windows) Reintroduce support for NVENC on older Nvidia GPU drivers (v456.71-v522.25) - (Capture/Windows) Fix encoding on old Intel GPUs that don't support low-power H.264 encoding - (Capture/Linux) Fix GL errors or corrupt video output on GPUs that use aux planes such as Intel Arc - (Capture/Linux) Fix GL errors or corrupt video output on GPUs that use DRM modifiers on YUV buffers @@ -68,6 +68,7 @@ - (Capture/Windows) Fix delay displaying UAC dialogs when the mouse cursor is not moving - (Capture/Linux) Fix corrupt video output or stream disconnections if the display resolution changes while streaming - (Capture/Linux) Fix color of aspect ratio padding in the capture image with VAAPI +- (Capture/Linux) Fix NVENC initialization error when using X11 capture with some GPUs - (Tray/Linux) Fix random crash when the tray icon is updating - (Network) Fix QoS tagging when running in IPv4+IPv6 mode - (Process) Fix termination of child processes upon app quit when the parent has already terminated diff --git a/src/platform/linux/cuda.cu b/src/platform/linux/cuda.cu index 863e3f944fe..8fb1a5ee2d6 100644 --- a/src/platform/linux/cuda.cu +++ b/src/platform/linux/cuda.cu @@ -222,7 +222,7 @@ std::optional tex_t::make(int height, int pitch) { return tex; } -tex_t::tex_t() : array {}, texture { INVALID_TEXTURE } {} +tex_t::tex_t() : array {}, texture { INVALID_TEXTURE, INVALID_TEXTURE } {} tex_t::tex_t(tex_t &&other) : array { other.array }, texture { other.texture } { other.array = 0; other.texture.point = INVALID_TEXTURE; From cacadc4df426e42273bcf4ad37758220faf2201f Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Mon, 4 Mar 2024 22:15:37 -0500 Subject: [PATCH 032/129] build(linux): ensure pre-compiled arch pkg is not debug build (#2214) --- docker/archlinux.dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/docker/archlinux.dockerfile b/docker/archlinux.dockerfile index 15cb5d23685..bd853ad395d 100644 --- a/docker/archlinux.dockerfile +++ b/docker/archlinux.dockerfile @@ -87,6 +87,7 @@ RUN <<_PKGBUILD set -e namcap -i PKGBUILD makepkg -si --noconfirm +rm -f /build/sunshine/pkg/sunshine-debug*.pkg.tar.zst ls -a _PKGBUILD From 9f94eebd32f148120389ebd3246829ee7e7bd66e Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 4 Mar 2024 18:43:16 -0600 Subject: [PATCH 033/129] Fix mismatched case and unhandled exception in open_drm_fd_for_cuda_device() --- src/platform/linux/cuda.cpp | 43 ++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 5b121c70691..33c939243f2 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -247,29 +247,38 @@ namespace cuda { // There's no way to directly go from CUDA to a DRM device, so we'll // use sysfs to look up the DRM device name from the PCI ID. - char pci_bus_id[13]; - CU_CHECK(cdf->cuDeviceGetPCIBusId(pci_bus_id, sizeof(pci_bus_id), device), "Couldn't get CUDA device PCI bus ID"); - BOOST_LOG(debug) << "Found CUDA device with PCI bus ID: "sv << pci_bus_id; + std::array pci_bus_id; + CU_CHECK(cdf->cuDeviceGetPCIBusId(pci_bus_id.data(), pci_bus_id.size(), device), "Couldn't get CUDA device PCI bus ID"); + BOOST_LOG(debug) << "Found CUDA device with PCI bus ID: "sv << pci_bus_id.data(); + + // Linux uses lowercase hexadecimal while CUDA uses uppercase + std::transform(pci_bus_id.begin(), pci_bus_id.end(), pci_bus_id.begin(), + [](char c) { return std::tolower(c); }); // Look for the name of the primary node in sysfs - char sysfs_path[PATH_MAX]; - std::snprintf(sysfs_path, sizeof(sysfs_path), "/sys/bus/pci/devices/%s/drm", pci_bus_id); - fs::path sysfs_dir { sysfs_path }; - for (auto &entry : fs::directory_iterator { sysfs_dir }) { - auto file = entry.path().filename(); - auto filestring = file.generic_u8string(); - if (std::string_view { filestring }.substr(0, 4) != "card"sv) { - continue; - } + try { + char sysfs_path[PATH_MAX]; + std::snprintf(sysfs_path, sizeof(sysfs_path), "/sys/bus/pci/devices/%s/drm", pci_bus_id.data()); + fs::path sysfs_dir { sysfs_path }; + for (auto &entry : fs::directory_iterator { sysfs_dir }) { + auto file = entry.path().filename(); + auto filestring = file.generic_u8string(); + if (std::string_view { filestring }.substr(0, 4) != "card"sv) { + continue; + } - BOOST_LOG(debug) << "Found DRM primary node: "sv << filestring; + BOOST_LOG(debug) << "Found DRM primary node: "sv << filestring; - fs::path dri_path { "/dev/dri"sv }; - auto device_path = dri_path / file; - return open(device_path.c_str(), O_RDWR); + fs::path dri_path { "/dev/dri"sv }; + auto device_path = dri_path / file; + return open(device_path.c_str(), O_RDWR); + } + } + catch (const std::filesystem::filesystem_error &err) { + BOOST_LOG(error) << "Failed to read sysfs: "sv << err.what(); } - BOOST_LOG(error) << "Unable to find DRM device with PCI bus ID: "sv << pci_bus_id; + BOOST_LOG(error) << "Unable to find DRM device with PCI bus ID: "sv << pci_bus_id.data(); return -1; } From 4ebc7b5cef0884cae5076a8f79d96a3859bea9e8 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Tue, 5 Mar 2024 08:56:09 -0500 Subject: [PATCH 034/129] build(macos): add build strategy matrix (#2211) --- .github/workflows/CI.yml | 69 ++++++++++++++++++++++++---------- README.rst | 4 +- docs/source/about/setup.rst | 4 +- docs/source/building/macos.rst | 20 ++++++++-- src/main.cpp | 3 ++ 5 files changed, 73 insertions(+), 27 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 60f555c2166..06d5a5e5d02 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -506,11 +506,23 @@ jobs: prerelease: ${{ needs.setup_release.outputs.pre_release }} build_mac: - name: MacOS - runs-on: macos-11 needs: [check_changelog, setup_release] env: BOOST_VERSION: 1.83.0 + strategy: + fail-fast: false # false to test all, true to fail entire job if any fail + matrix: + include: + # https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories + # while GitHub has larger macOS runners, they are not available for our repos :( + - os_version: "12" + arch: "x86_64" + - os_version: "13" + arch: "x86_64" + - os_version: "14" + arch: "arm64" + name: macOS-${{ matrix.os_version }} ${{ matrix.arch }} + runs-on: macos-${{ matrix.os_version }} steps: - name: Checkout @@ -520,24 +532,32 @@ jobs: - name: Setup Dependencies MacOS run: | + if [[ ${{ matrix.arch }} == "arm64" ]]; then + brew_prefix="/opt/homebrew" + else + brew_prefix="/usr/local" + fi + # install dependencies using homebrew brew install cmake curl miniupnpc node openssl opus pkg-config # fix openssl header not found - # ln -sf /usr/local/opt/openssl/include/openssl /usr/local/include/openssl - - # by installing boost from source, several headers cannot be found... - # the above commented out link only works if boost is installed from homebrew... does not make sense - ln -sf $(find /usr/local/Cellar -type d -name "openssl" -path "*/openssl@3/*/include" | head -n 1) \ - /usr/local/include/openssl + openssl_path=$(find ${brew_prefix}/Cellar -type d -name "openssl" -path "*/openssl@3/*/include" | head -n 1) + echo "OpenSSL path: $openssl_path" + ln -sf $openssl_path ${brew_prefix}/include/openssl + ls -l ${brew_prefix}/include/openssl # fix opus header not found - ln -sf $(find /usr/local/Cellar -type d -name "opus" -path "*/opus/*/include" | head -n 1) \ - /usr/local/include/opus + opus_path=$(find ${brew_prefix}/Cellar -type d -name "opus" -path "*/opus/*/include" | head -n 1) + echo "Opus path: $opus_path" + ln -sf $opus_path ${brew_prefix}/include/opus + ls -l ${brew_prefix}/include/opus # fix miniupnpc header not found - ln -sf $(find /usr/local/Cellar -type d -name "miniupnpc" -path "*/miniupnpc/*/include" | head -n 1) \ - /usr/local/include/miniupnpc + upnp_path=$(find ${brew_prefix}/Cellar -type d -name "miniupnpc" -path "*/miniupnpc/*/include" | head -n 1) + echo "Miniupnpc path: $upnp_path" + ln -sf $upnp_path ${brew_prefix}/include/miniupnpc + ls -l ${brew_prefix}/include/miniupnpc - name: Install Boost # installing boost from homebrew takes 30 minutes in a GitHub runner @@ -594,15 +614,13 @@ jobs: # package cpack -G DragNDrop - mv ./cpack_artifacts/Sunshine.dmg ../artifacts/sunshine.dmg - - # cpack -G Bundle - # mv ./cpack_artifacts/Sunshine.dmg ../artifacts/sunshine-bundle.dmg + mv ./cpack_artifacts/Sunshine.dmg \ + ../artifacts/sunshine-macos-${{ matrix.os_version }}-${{ matrix.arch }}.dmg - name: Upload Artifacts uses: actions/upload-artifact@v4 with: - name: sunshine-macos + name: sunshine-macos-${{ matrix.os_version }}-${{ matrix.arch }} path: artifacts/ - name: Create/Update GitHub Release @@ -620,9 +638,19 @@ jobs: prerelease: ${{ needs.setup_release.outputs.pre_release }} build_mac_port: - name: Macports needs: [check_changelog, setup_release] - runs-on: macos-11 + strategy: + fail-fast: false # false to test all, true to fail entire job if any fail + matrix: + include: + # https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories + # while GitHub has larger macOS runners, they are not available for our repos :( + - os_version: "12" + release: true + - os_version: "13" + - os_version: "14" + name: Macports (macOS-${{ matrix.os_version }}) + runs-on: macos-${{ matrix.os_version }} steps: - name: Checkout @@ -725,13 +753,14 @@ jobs: echo "::endgroup::" - name: Upload Artifacts + if: ${{ matrix.release == 'true' }} uses: actions/upload-artifact@v4 with: name: sunshine-macports path: artifacts/ - name: Create/Update GitHub Release - if: ${{ needs.setup_release.outputs.create_release == 'true' }} + if: ${{ needs.setup_release.outputs.create_release == 'true' && matrix.release == 'true' }} uses: ncipollo/release-action@v1 with: name: ${{ needs.setup_release.outputs.release_name }} diff --git a/README.rst b/README.rst index fbc78658668..11508d976e3 100644 --- a/README.rst +++ b/README.rst @@ -32,11 +32,11 @@ System Requirements +------------+------------------------------------------------------------+ | OS | Windows: 10+ (Windows Server not supported) | | +------------------------------------------------------------+ -| | macOS: 11.7+ | +| | macOS: 12+ | | +------------------------------------------------------------+ | | Linux/Debian: 11 (bullseye) | | +------------------------------------------------------------+ -| | Linux/Fedora: 37+ | +| | Linux/Fedora: 38+ | | +------------------------------------------------------------+ | | Linux/Ubuntu: 20.04+ (focal) | +------------+------------------------------------------------------------+ diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 8a280fcf644..2457ccc59e9 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -281,14 +281,14 @@ Install .. tab:: macOS - .. important:: Sunshine on macOS is experimental. Gamepads do not work. Other features may not work as expected. + .. important:: Sunshine on macOS is experimental. Gamepads do not work. .. tab:: dmg .. warning:: The `dmg` does not include runtime dependencies. This package is not recommended for most users. No support will be provided! - #. Download the ``sunshine.dmg`` file and install it. + #. Download the ``sunshine--.dmg`` file and install it. Uninstall: .. code-block:: bash diff --git a/docs/source/building/macos.rst b/docs/source/building/macos.rst index c14751c28f8..bf96fb394f9 100644 --- a/docs/source/building/macos.rst +++ b/docs/source/building/macos.rst @@ -20,9 +20,23 @@ Install Requirements .. code-block:: bash brew install boost cmake miniupnpc node opus pkg-config - # if there are issues with an SSL header that is not found: - cd /usr/local/include - ln -s ../opt/openssl/include/openssl . + +If there are issues with an SSL header that is not found: + .. tab:: Intel + + .. code-block:: bash + + pushd /usr/local/include + ln -s ../opt/openssl/include/openssl . + popd + + .. tab:: Apple Silicon + + .. code-block:: bash + + pushd /opt/homebrew/include + ln -s ../opt/openssl/include/openssl . + popd Build ----- diff --git a/src/main.cpp b/src/main.cpp index 5cc28f9f2a2..a3901448680 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -106,8 +106,11 @@ main(int argc, char *argv[]) { setlocale(LC_ALL, ".UTF-8"); #endif +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Use UTF-8 conversion for the default C++ locale (used by boost::log) std::locale::global(std::locale(std::locale(), new std::codecvt_utf8)); +#pragma GCC diagnostic pop mail::man = std::make_shared(); From b99a9e92becb5e2b56e0555093d81b8aa8712f6e Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Tue, 5 Mar 2024 18:18:17 -0500 Subject: [PATCH 035/129] build(macos): fix publishing of portfile (#2220) --- .github/workflows/CI.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 06d5a5e5d02..c2d97440e22 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -753,14 +753,14 @@ jobs: echo "::endgroup::" - name: Upload Artifacts - if: ${{ matrix.release == 'true' }} + if: ${{ matrix.release }} uses: actions/upload-artifact@v4 with: name: sunshine-macports path: artifacts/ - name: Create/Update GitHub Release - if: ${{ needs.setup_release.outputs.create_release == 'true' && matrix.release == 'true' }} + if: ${{ needs.setup_release.outputs.create_release == 'true' && matrix.release }} uses: ncipollo/release-action@v1 with: name: ${{ needs.setup_release.outputs.release_name }} From 3f215968ad61864063b1a84025e7ce74f6c1e553 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Tue, 5 Mar 2024 23:00:51 -0500 Subject: [PATCH 036/129] fix(config): add missing resolution to default config ui (#2224) --- src_assets/common/assets/web/config.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src_assets/common/assets/web/config.html b/src_assets/common/assets/web/config.html index a072e101ba0..e7d47e4d852 100644 --- a/src_assets/common/assets/web/config.html +++ b/src_assets/common/assets/web/config.html @@ -1234,7 +1234,7 @@

"install_steam_audio_drivers": "enabled", "adapter_name": "", "output_name": "", - "resolutions": "[352x240,480x360,858x480,1280x720,1920x1080,2560x1080,3440x1440,1920x1200,3840x2160,3840x1600]", + "resolutions": "[352x240,480x360,858x480,1280x720,1920x1080,2560x1080,2560x1440,3440x1440,1920x1200,3840x2160,3840x1600]", "fps": "[10,30,60,90,120]", }, }, From 9e299c295dc94ca6f1d813f1b974e40de901f369 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 5 Mar 2024 22:32:06 -0600 Subject: [PATCH 037/129] Fix predefined FPS values not taking effect --- src/config.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/config.cpp b/src/config.cpp index ba2718aca7f..21562f83487 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -849,6 +849,11 @@ namespace config { std::vector list; list_string_f(vars, name, list); + // check if list is empty, i.e. when the value doesn't exist in the config file + if (list.empty()) { + return; + } + // The framerate list must be cleared before adding values from the file configuration. // If the list is not cleared, then the specified parameters do not affect the behavior of the sunshine server. // 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. From c86a4e112be4d1a396e561619ea78f1d01a407b0 Mon Sep 17 00:00:00 2001 From: detiam <44510779+detiam@users.noreply.github.com> Date: Wed, 6 Mar 2024 23:23:32 +0800 Subject: [PATCH 038/129] Fix wrong path in desktop file (#2223) Co-authored-by: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> --- cmake/packaging/unix.cmake | 2 -- cmake/prep/special_package_configuration.cmake | 2 ++ packaging/linux/flatpak/sunshine.desktop | 4 ++-- packaging/linux/sunshine.desktop | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/packaging/unix.cmake b/cmake/packaging/unix.cmake index d6a4ae93575..bacbfc910de 100644 --- a/cmake/packaging/unix.cmake +++ b/cmake/packaging/unix.cmake @@ -1,8 +1,6 @@ # unix specific packaging # put anything here that applies to both linux and macos -include(GNUInstallDirs) - # return here if building a macos package if(SUNSHINE_PACKAGE_MACOS) return() diff --git a/cmake/prep/special_package_configuration.cmake b/cmake/prep/special_package_configuration.cmake index 3094c2399a5..a5a780f5563 100644 --- a/cmake/prep/special_package_configuration.cmake +++ b/cmake/prep/special_package_configuration.cmake @@ -3,6 +3,8 @@ if (APPLE) configure_file(packaging/macos/Portfile Portfile @ONLY) endif() elseif (UNIX) + include(GNUInstallDirs) # this needs to be included prior to configuring the desktop files + # configure the .desktop file if(${SUNSHINE_BUILD_APPIMAGE}) configure_file(packaging/linux/AppImage/sunshine.desktop sunshine.desktop @ONLY) diff --git a/packaging/linux/flatpak/sunshine.desktop b/packaging/linux/flatpak/sunshine.desktop index be702701e08..1c5fe13a409 100644 --- a/packaging/linux/flatpak/sunshine.desktop +++ b/packaging/linux/flatpak/sunshine.desktop @@ -12,9 +12,9 @@ Actions=RunInTerminal;KMS; [Desktop Action RunInTerminal] Name=Run in Terminal Icon=application-x-executable -Exec=gio launch @CMAKE_INSTALL_DATAROOTDIR@/applications/sunshine_terminal.desktop +Exec=gio launch @CMAKE_INSTALL_FULL_DATAROOTDIR@/applications/sunshine_terminal.desktop [Desktop Action KMS] Name=Run in Terminal (KMS) Icon=application-x-executable -Exec=gio launch @CMAKE_INSTALL_DATAROOTDIR@/applications/sunshine_kms.desktop +Exec=gio launch @CMAKE_INSTALL_FULL_DATAROOTDIR@/applications/sunshine_kms.desktop diff --git a/packaging/linux/sunshine.desktop b/packaging/linux/sunshine.desktop index b0f2ce327ec..719555301d5 100644 --- a/packaging/linux/sunshine.desktop +++ b/packaging/linux/sunshine.desktop @@ -12,4 +12,4 @@ Actions=RunInTerminal; [Desktop Action RunInTerminal] Name=Run in Terminal Icon=application-x-executable -Exec=gio launch @CMAKE_INSTALL_DATAROOTDIR@/applications/sunshine_terminal.desktop +Exec=gio launch @CMAKE_INSTALL_FULL_DATAROOTDIR@/applications/sunshine_terminal.desktop From 3b3e6818f31858eaa6413c8e832dc803eeb48157 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 5 Mar 2024 22:57:28 -0600 Subject: [PATCH 039/129] Make debuginfo artifacts harder to confuse with the Windows portable build --- .github/workflows/CI.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index c2d97440e22..6b1eb296b47 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -843,11 +843,15 @@ jobs: - name: Package Windows Debug Info working-directory: build run: | - # save the original binaries with debug info + # use .dbg file extension for binaries to avoid confusion with real packages + Get-ChildItem -File -Recurse | ` + % { Rename-Item -Path $_.PSPath -NewName $_.Name.Replace(".exe",".dbg") } + + # save the binaries with debug info 7z -r ` "-xr!CMakeFiles" ` "-xr!cpack_artifacts" ` - a "../artifacts/sunshine-debuginfo-win32.zip" "*.exe" + a "../artifacts/sunshine-win32-debuginfo.7z" "*.dbg" - name: Upload Artifacts uses: actions/upload-artifact@v4 From 6aeaaf5ec9df4c278c1a8126a2dfbc748d000d76 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 6 Mar 2024 19:18:12 -0600 Subject: [PATCH 040/129] Fix process tree tracking when the cmd.exe trampoline is used --- src/platform/windows/misc.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 77de69f4cd3..98065e3201a 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -681,10 +681,11 @@ namespace platf { * @param raw_cmd The raw command provided by the user. * @param working_dir The working directory for the new process. * @param token The user token currently being impersonated or `NULL` if running as ourselves. + * @param creation_flags The creation flags for CreateProcess(), which may be modified by this function. * @return A command string suitable for use by CreateProcess(). */ std::wstring - resolve_command_string(const std::string &raw_cmd, const std::wstring &working_dir, HANDLE token) { + resolve_command_string(const std::string &raw_cmd, const std::wstring &working_dir, HANDLE token, DWORD &creation_flags) { std::wstring raw_cmd_w = from_utf8(raw_cmd); // First, convert the given command into parts so we can get the executable/file/URL without parameters @@ -757,8 +758,13 @@ namespace platf { // FIXME: Maybe we can improve this in the future. if (res == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) { BOOST_LOG(warning) << "Using trampoline to handle target: "sv << raw_cmd; - std::wcscpy(shell_command_string.data(), L"cmd.exe /c start \"\" \"%1\" %*"); + std::wcscpy(shell_command_string.data(), L"cmd.exe /c start \"\" /wait \"%1\" %*"); needs_cmd_escaping = true; + + // We must suppress the console window that would otherwise appear when starting cmd.exe. + creation_flags &= ~CREATE_NEW_CONSOLE; + creation_flags |= CREATE_NO_WINDOW; + res = S_OK; } @@ -951,7 +957,7 @@ namespace platf { // Open the process as the current user account, elevation is handled in the token itself. ec = impersonate_current_user(user_token, [&]() { std::wstring env_block = create_environment_block(cloned_env); - std::wstring wcmd = resolve_command_string(cmd, start_dir, user_token); + std::wstring wcmd = resolve_command_string(cmd, start_dir, user_token, creation_flags); ret = CreateProcessAsUserW(user_token, NULL, (LPWSTR) wcmd.c_str(), @@ -985,7 +991,7 @@ namespace platf { } std::wstring env_block = create_environment_block(cloned_env); - std::wstring wcmd = resolve_command_string(cmd, start_dir, NULL); + std::wstring wcmd = resolve_command_string(cmd, start_dir, NULL, creation_flags); ret = CreateProcessW(NULL, (LPWSTR) wcmd.c_str(), NULL, From 972e5d2b145d2e927f4f94c3dc36b777f9d1b650 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 6 Mar 2024 19:45:49 -0600 Subject: [PATCH 041/129] Strip quotes out of the working directory path --- src/process.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/process.cpp b/src/process.cpp index 804291577c2..89dc4dc5ae5 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -664,6 +664,12 @@ namespace proc { if (working_dir) { ctx.working_dir = parse_env_val(this_env, *working_dir); +#ifdef _WIN32 + // The working directory, unlike the command itself, should not be quoted + // when it contains spaces. Unlike POSIX, Windows forbids quotes in paths, + // so we can safely strip them all out here to avoid confusing the user. + boost::erase_all(ctx.working_dir, "\""); +#endif } if (image_path) { From 06c0ed1d1cb5a80c6f0a6fe8d7a3fd8a77580adc Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 6 Mar 2024 20:54:27 -0600 Subject: [PATCH 042/129] Temporarily add the working directory to our path when starting an app CreateProcess() doesn't search in the child's specified working directory by default. --- src/platform/windows/misc.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 98065e3201a..e7bb64e52b8 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -933,6 +933,31 @@ namespace platf { // Create a new console for interactive processes and use no console for non-interactive processes creation_flags |= interactive ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW; + // Find the PATH variable in our environment block using a case-insensitive search + auto sunshine_wenv = boost::this_process::wenvironment(); + std::wstring path_var_name { L"PATH" }; + std::wstring old_path_val; + auto itr = std::find_if(sunshine_wenv.cbegin(), sunshine_wenv.cend(), [&](const auto &e) { return boost::iequals(e.get_name(), path_var_name); }); + if (itr != sunshine_wenv.cend()) { + // Use the existing variable if it exists, since Boost treats these as case-sensitive. + path_var_name = itr->get_name(); + old_path_val = sunshine_wenv[path_var_name].to_string(); + } + + // Temporarily prepend the specified working directory to PATH to ensure CreateProcess() + // will (preferentially) find binaries that reside in the working directory. + sunshine_wenv[path_var_name].assign(start_dir + L";" + old_path_val); + + // Restore the old PATH value for our process when we're done here + auto restore_path = util::fail_guard([&]() { + if (old_path_val.empty()) { + sunshine_wenv[path_var_name].clear(); + } + else { + sunshine_wenv[path_var_name].assign(old_path_val); + } + }); + BOOL ret; if (is_running_as_system()) { // Duplicate the current user's token From f5dd0d4eafbd34a540c77c73c9cab1d05b99b0f8 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 6 Mar 2024 20:55:00 -0600 Subject: [PATCH 043/129] Update app examples to clarify new command syntax for Windows --- docs/source/about/guides/app_examples.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/source/about/guides/app_examples.rst b/docs/source/about/guides/app_examples.rst index ca834e4a4f2..8bca2bd89f0 100644 --- a/docs/source/about/guides/app_examples.rst +++ b/docs/source/about/guides/app_examples.rst @@ -6,6 +6,8 @@ and applications to Sunshine. .. attention:: Throughout these examples, any fields not shown are left blank. You can enhance your experience by adding an image or a log file (via the ``Output`` field). +.. note:: When a working directory is not specified, it defaults to the folder where the target application resides. + Common Examples --------------- @@ -24,7 +26,7 @@ Steam Big Picture ^^^^^^^^^^^^^^^^^ .. note:: Steam is launched as a detached command because Steam starts with a process that self updates itself and the original - process is killed. Since the original process ends it will not work as a regular command. + process is killed. .. tab:: Linux @@ -51,7 +53,7 @@ Steam Big Picture +----------------------+-----------------------------+ | Application Name | ``Steam Big Picture`` | +----------------------+-----------------------------+ - | Detached Commands | ``steam://open/bigpicture`` | + | Command | ``steam://open/bigpicture`` | +----------------------+-----------------------------+ | Image | ``steam.png`` | +----------------------+-----------------------------+ @@ -59,8 +61,7 @@ Steam Big Picture Epic Game Store game ^^^^^^^^^^^^^^^^^^^^ -.. note:: Using URI method will be the most consistent between various games, but does not allow a game to be launched - using the "Command" and therefore the stream will not end when the game ends. +.. note:: Using URI method will be the most consistent between various games. URI (Epic) """""""""" @@ -70,7 +71,7 @@ URI (Epic) +----------------------+--------------------------------------------------------------------------------------------------------------------------------------------+ | Application Name | ``Surviving Mars`` | +----------------------+--------------------------------------------------------------------------------------------------------------------------------------------+ - | Detached Commands | ``com.epicgames.launcher://apps/d759128018124dcabb1fbee9bb28e178%3A20729b9176c241f0b617c5723e70ec2d%3AOvenbird?action=launch&silent=true`` | + | Command | ``com.epicgames.launcher://apps/d759128018124dcabb1fbee9bb28e178%3A20729b9176c241f0b617c5723e70ec2d%3AOvenbird?action=launch&silent=true`` | +----------------------+--------------------------------------------------------------------------------------------------------------------------------------------+ Binary (Epic w/ working directory) @@ -81,7 +82,7 @@ Binary (Epic w/ working directory) +----------------------+-----------------------------------------------+ | Application Name | ``Surviving Mars`` | +----------------------+-----------------------------------------------+ - | Command | ``cmd /c "MarsEpic.exe"`` | + | Command | ``MarsEpic.exe`` | +----------------------+-----------------------------------------------+ | Working Directory | ``C:\Program Files\Epic Games\SurvivingMars`` | +----------------------+-----------------------------------------------+ @@ -100,8 +101,7 @@ Binary (Epic w/o working directory) Steam game ^^^^^^^^^^ -.. note:: Using URI method will be the most consistent between various games, but does not allow a game to be launched - using the "Command" and therefore the stream will not end when the game ends. +.. note:: Using URI method will be the most consistent between various games. URI (Steam) """"""""""" @@ -127,7 +127,7 @@ URI (Steam) +----------------------+------------------------------+ | Application Name | ``Surviving Mars`` | +----------------------+------------------------------+ - | Detached Commands | ``steam://rungameid/464920`` | + | Command | ``steam://rungameid/464920`` | +----------------------+------------------------------+ Binary (Steam w/ working directory) From 7cdd156bcecda18d83237b7b8ff537ac10a8c0ba Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Thu, 7 Mar 2024 00:59:40 -0600 Subject: [PATCH 044/129] Fix heap corruption with cursor pixel counts that aren't divisible by 8 --- src/platform/windows/display_vram.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index a56869eab40..1baa1282bb9 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -234,7 +234,7 @@ namespace platf::dxgi { auto xor_mask = std::begin(img_data) + bytes; for (auto x = 0; x < bytes; ++x) { - for (auto c = 7; c >= 0; --c) { + for (auto c = 7; c >= 0 && ((std::uint8_t *) pixel_data) != std::end(cursor_img); --c) { auto bit = 1 << c; auto color_type = ((*and_mask & bit) ? 1 : 0) + ((*xor_mask & bit) ? 2 : 0); @@ -307,7 +307,7 @@ namespace platf::dxgi { auto xor_mask = std::begin(img_data) + bytes; for (auto x = 0; x < bytes; ++x) { - for (auto c = 7; c >= 0; --c) { + for (auto c = 7; c >= 0 && ((std::uint8_t *) pixel_data) != std::end(cursor_img); --c) { auto bit = 1 << c; auto color_type = ((*and_mask & bit) ? 1 : 0) + ((*xor_mask & bit) ? 2 : 0); From ce3b62598317caf605385e1a9061b95edf889196 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 8 Mar 2024 17:26:43 -0600 Subject: [PATCH 045/129] Fix undefined behavior when computing cursor end pointer --- src/platform/linux/kmsgrab.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index cd622fa775c..a7a3256d433 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -1240,8 +1240,13 @@ namespace platf { auto delta_width = std::min(captured_cursor.src_w, std::max(0, screen_width - cursor_x)) - cursor_delta_x; for (auto y = 0; y < delta_height; ++y) { // Offset into the cursor image to skip drawing the parts of the cursor image that are off screen - auto cursor_begin = (uint32_t *) &captured_cursor.pixels[((y + cursor_delta_y) * captured_cursor.src_w + cursor_delta_x) * 4]; - auto cursor_end = (uint32_t *) &captured_cursor.pixels[((y + cursor_delta_y) * captured_cursor.src_w + delta_width + cursor_delta_x) * 4]; + // + // NB: We must access the elements via the data() function because cursor_end may point to the + // the first element beyond the valid range of the vector. Using vector's [] operator in that + // manner is undefined behavior (and triggers errors when using debug libc++), while doing the + // same with an array is fine. + auto cursor_begin = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + cursor_delta_x) * 4]; + auto cursor_end = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + delta_width + cursor_delta_x) * 4]; auto pixels_begin = &pixels[(y + cursor_y) * (img.row_pitch / img.pixel_pitch) + cursor_x]; From 33e99e1feb02299ac907c12fedf9d8d36cae775c Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sat, 9 Mar 2024 10:47:55 -0500 Subject: [PATCH 046/129] build(macos)!: add homebrew formula and drop dmg (#2222) --- .github/workflows/CI.yml | 155 +++++++----------- CMakeLists.txt | 2 +- cmake/prep/options.cmake | 8 + .../prep/special_package_configuration.cmake | 3 + cmake/targets/common.cmake | 13 +- docs/source/about/setup.rst | 13 +- packaging/macos/sunshine.rb | 62 +++++++ src_assets/macos/misc/uninstall_pkg.sh | 3 + vite.config.js | 17 +- 9 files changed, 162 insertions(+), 114 deletions(-) create mode 100644 packaging/macos/sunshine.rb diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 6b1eb296b47..f2529e7390e 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -505,10 +505,8 @@ jobs: discussionCategory: announcements prerelease: ${{ needs.setup_release.outputs.pre_release }} - build_mac: + build_mac_brew: needs: [check_changelog, setup_release] - env: - BOOST_VERSION: 1.83.0 strategy: fail-fast: false # false to test all, true to fail entire job if any fail matrix: @@ -516,126 +514,87 @@ jobs: # https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories # while GitHub has larger macOS runners, they are not available for our repos :( - os_version: "12" - arch: "x86_64" + release: true - os_version: "13" - arch: "x86_64" - os_version: "14" - arch: "arm64" - name: macOS-${{ matrix.os_version }} ${{ matrix.arch }} + name: Homebrew (macOS-${{ matrix.os_version }}) runs-on: macos-${{ matrix.os_version }} steps: - name: Checkout uses: actions/checkout@v4 - with: - submodules: recursive - - name: Setup Dependencies MacOS + - name: Setup Dependencies Homebrew + run: | + # install dependencies using homebrew + brew install cmake + + - name: Configure formula run: | - if [[ ${{ matrix.arch }} == "arm64" ]]; then - brew_prefix="/opt/homebrew" + # variables for formula + branch=${GITHUB_HEAD_REF} + + # check the branch variable + if [ -z "$branch" ] + then + echo "This is a PUSH event" + clone_url=${{ github.event.repository.clone_url }} + branch="${{ github.ref_name }}" else - brew_prefix="/usr/local" + echo "This is a PR event" + clone_url=${{ github.event.pull_request.head.repo.clone_url }} + branch="${{ github.event.pull_request.head.ref }}" fi + echo "Branch: ${branch}" + echo "Clone URL: ${clone_url}" - # install dependencies using homebrew - brew install cmake curl miniupnpc node openssl opus pkg-config - - # fix openssl header not found - openssl_path=$(find ${brew_prefix}/Cellar -type d -name "openssl" -path "*/openssl@3/*/include" | head -n 1) - echo "OpenSSL path: $openssl_path" - ln -sf $openssl_path ${brew_prefix}/include/openssl - ls -l ${brew_prefix}/include/openssl - - # fix opus header not found - opus_path=$(find ${brew_prefix}/Cellar -type d -name "opus" -path "*/opus/*/include" | head -n 1) - echo "Opus path: $opus_path" - ln -sf $opus_path ${brew_prefix}/include/opus - ls -l ${brew_prefix}/include/opus - - # fix miniupnpc header not found - upnp_path=$(find ${brew_prefix}/Cellar -type d -name "miniupnpc" -path "*/miniupnpc/*/include" | head -n 1) - echo "Miniupnpc path: $upnp_path" - ln -sf $upnp_path ${brew_prefix}/include/miniupnpc - ls -l ${brew_prefix}/include/miniupnpc - - - name: Install Boost - # installing boost from homebrew takes 30 minutes in a GitHub runner - run: | - export BOOST_ROOT=${HOME}/boost-${BOOST_VERSION} - - # install boost - wget \ - https://github.com/boostorg/boost/releases/download/boost-${BOOST_VERSION}/boost-${BOOST_VERSION}.tar.gz \ - --progress=bar:force:noscroll -q --show-progress - tar xf boost-${BOOST_VERSION}.tar.gz - cd boost-${BOOST_VERSION} - - # libdir should be set by --prefix but isn't - ./bootstrap.sh \ - --prefix=${BOOST_ROOT} \ - --libdir=${BOOST_ROOT}/lib \ - --with-libraries=locale,log,program_options,system,thread - ./b2 headers - ./b2 install \ - --prefix=${BOOST_ROOT} \ - --libdir=${BOOST_ROOT}/lib \ - -j$(sysctl -n hw.ncpu) \ - link=shared,static \ - variant=release \ - cxxflags=-std=c++14 \ - cxxflags=-stdlib=libc++ \ - linkflags=-stdlib=libc++ - - # put boost in cmake prefix path - echo "BOOST_ROOT=${BOOST_ROOT}" >> ${GITHUB_ENV} - - - name: Build MacOS - env: - BRANCH: ${{ github.head_ref || github.ref_name }} - BUILD_VERSION: ${{ needs.check_changelog.outputs.next_version_bare }} - COMMIT: ${{ github.event.pull_request.head.sha || github.sha }} - run: | mkdir build cd build cmake \ - -DBUILD_WERROR=ON \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX=/usr \ - -DSUNSHINE_ASSETS_DIR=local/sunshine/assets \ - -DSUNSHINE_EXECUTABLE_PATH=/usr/bin/sunshine \ + -DGITHUB_BRANCH="${branch}" \ + -DGITHUB_CLONE_URL="${clone_url}" \ + -DSUNSHINE_CONFIGURE_HOMEBREW=ON \ + -DSUNSHINE_CONFIGURE_ONLY=ON \ .. - make -j $(sysctl -n hw.ncpu) + cd .. - - name: Package MacOS - run: | - mkdir -p artifacts - cd build + # copy formula to artifacts + mkdir -p homebrew + cp -f ./build/sunshine.rb ./homebrew/sunshine.rb - # package - cpack -G DragNDrop - mv ./cpack_artifacts/Sunshine.dmg \ - ../artifacts/sunshine-macos-${{ matrix.os_version }}-${{ matrix.arch }}.dmg + # testing + cat ./homebrew/sunshine.rb - name: Upload Artifacts + if: ${{ matrix.release }} uses: actions/upload-artifact@v4 with: - name: sunshine-macos-${{ matrix.os_version }}-${{ matrix.arch }} - path: artifacts/ + name: sunshine-homebrew + path: homebrew/ - - name: Create/Update GitHub Release - if: ${{ needs.setup_release.outputs.create_release == 'true' }} - uses: ncipollo/release-action@v1 + - name: Should Publish Homebrew Formula + id: homebrew_publish + run: | + PUBLISH=false + if [[ \ + "${{ matrix.release }}" == "true" && \ + "${{ github.repository_owner }}" == "LizardByte" && \ + "${{ needs.setup_release.outputs.create_release }}" == "true" && \ + "${{ github.ref }}" == "refs/heads/master" \ + ]]; then + PUBLISH=true + fi + + echo "publish=${PUBLISH}" >> $GITHUB_OUTPUT + + - name: Validate and Publish Homebrew Formula + uses: LizardByte/homebrew-release-action@v2024.309.150158 with: - name: ${{ needs.setup_release.outputs.release_name }} - tag: ${{ needs.setup_release.outputs.release_tag }} - commit: ${{ needs.setup_release.outputs.release_commit }} - artifacts: "*artifacts/*" + formula_file: ${{ github.workspace }}/homebrew/sunshine.rb + git_email: ${{ secrets.GH_BOT_EMAIL }} + git_username: ${{ secrets.GH_BOT_NAME }} + publish: ${{ steps.homebrew_publish.outputs.publish }} token: ${{ secrets.GH_BOT_TOKEN }} - allowUpdates: true - body: ${{ needs.setup_release.outputs.release_body }} - discussionCategory: announcements - prerelease: ${{ needs.setup_release.outputs.pre_release }} build_mac_port: needs: [check_changelog, setup_release] diff --git a/CMakeLists.txt b/CMakeLists.txt index d672c9b8ae8..593d86b82dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,7 +4,7 @@ cmake_minimum_required(VERSION 3.18) # todo - set version to 0.0.0 once confident in automated versioning project(Sunshine VERSION 0.22.0 - DESCRIPTION "Sunshine is a self-hosted game stream host for Moonlight." + DESCRIPTION "Self-hosted game stream host for Moonlight" HOMEPAGE_URL "https://app.lizardbyte.dev/Sunshine") set(PROJECT_LICENSE "GPL-3.0") diff --git a/cmake/prep/options.cmake b/cmake/prep/options.cmake index 9104320d31d..9a7fca8e5e5 100644 --- a/cmake/prep/options.cmake +++ b/cmake/prep/options.cmake @@ -12,7 +12,15 @@ option(CUDA_INHERIT_COMPILE_OPTIONS "When building CUDA code, inherit compile options from the the main project. You may want to disable this if your IDE throws errors about unknown flags after running cmake." ON) +if(UNIX) + # technically, the homebrew build could be on linux as well... no idea if it would actually work + option(SUNSHINE_BUILD_HOMEBREW + "Enable a Homebrew build." OFF) +endif () + if(APPLE) + option(SUNSHINE_CONFIGURE_HOMEBREW + "Configure macOS Homebrew formula. Recommended to use with SUNSHINE_CONFIGURE_ONLY" OFF) option(SUNSHINE_CONFIGURE_PORTFILE "Configure macOS Portfile. Recommended to use with SUNSHINE_CONFIGURE_ONLY" OFF) option(SUNSHINE_PACKAGE_MACOS diff --git a/cmake/prep/special_package_configuration.cmake b/cmake/prep/special_package_configuration.cmake index a5a780f5563..695b6e443c2 100644 --- a/cmake/prep/special_package_configuration.cmake +++ b/cmake/prep/special_package_configuration.cmake @@ -2,6 +2,9 @@ if (APPLE) if(${SUNSHINE_CONFIGURE_PORTFILE}) configure_file(packaging/macos/Portfile Portfile @ONLY) endif() + if(${SUNSHINE_CONFIGURE_HOMEBREW}) + configure_file(packaging/macos/sunshine.rb sunshine.rb @ONLY) + endif() elseif (UNIX) include(GNUInstallDirs) # this needs to be included prior to configuring the desktop files diff --git a/cmake/targets/common.cmake b/cmake/targets/common.cmake index 3dd629e0cab..9f2ce08240e 100644 --- a/cmake/targets/common.cmake +++ b/cmake/targets/common.cmake @@ -37,8 +37,19 @@ endif() target_compile_options(sunshine PRIVATE $<$:${SUNSHINE_COMPILE_OPTIONS}>;$<$:${SUNSHINE_COMPILE_OPTIONS_CUDA};-std=c++17>) # cmake-lint: disable=C0301 +# Homebrew build fails the vite build if we set these environment variables +if(${SUNSHINE_BUILD_HOMEBREW}) + set(NPM_SOURCE_ASSETS_DIR "") + set(NPM_ASSETS_DIR "") + set(NPM_BUILD_HOMEBREW "true") +else() + set(NPM_SOURCE_ASSETS_DIR ${SUNSHINE_SOURCE_ASSETS_DIR}) + set(NPM_ASSETS_DIR ${CMAKE_BINARY_DIR}) + set(NPM_BUILD_HOMEBREW "") +endif() + #WebUI build add_custom_target(web-ui ALL WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" COMMENT "Installing NPM Dependencies and Building the Web UI" - COMMAND bash -c \"npm install && SUNSHINE_SOURCE_ASSETS_DIR=${SUNSHINE_SOURCE_ASSETS_DIR} SUNSHINE_ASSETS_DIR=${CMAKE_BINARY_DIR} npm run build\") # cmake-lint: disable=C0301 + COMMAND bash -c \"npm install && SUNSHINE_BUILD_HOMEBREW=${NPM_BUILD_HOMEBREW} SUNSHINE_SOURCE_ASSETS_DIR=${NPM_SOURCE_ASSETS_DIR} SUNSHINE_ASSETS_DIR=${NPM_ASSETS_DIR} npm run build\") # cmake-lint: disable=C0301 diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 2457ccc59e9..53da139875b 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -283,18 +283,15 @@ Install .. important:: Sunshine on macOS is experimental. Gamepads do not work. - .. tab:: dmg + .. tab:: Homebrew - .. warning:: The `dmg` does not include runtime dependencies. This package is not recommended for most users. - No support will be provided! + #. Install `Homebrew `__ + #. Update the Homebrew sources and install Sunshine. - #. Download the ``sunshine--.dmg`` file and install it. - - Uninstall: .. code-block:: bash - cd /etc/sunshine/assets - uninstall_pkg.sh + brew tap LizardByte/homebrew + brew install sunshine .. tab:: Portfile diff --git a/packaging/macos/sunshine.rb b/packaging/macos/sunshine.rb new file mode 100644 index 00000000000..e312c99d4d6 --- /dev/null +++ b/packaging/macos/sunshine.rb @@ -0,0 +1,62 @@ +require "language/node" + +class @PROJECT_NAME@ < Formula + desc "@PROJECT_DESCRIPTION@" + homepage "@PROJECT_HOMEPAGE_URL@" + url "@GITHUB_CLONE_URL@", + tag: "@GITHUB_BRANCH@" + version "@PROJECT_VERSION@" + license all_of: ["GPL-3.0-only"] + head "@GITHUB_CLONE_URL@", branch: "nightly" + + depends_on "boost" => :build + depends_on "cmake" => :build + depends_on "pkg-config" => :build + depends_on "curl" + depends_on "miniupnpc" + depends_on "node" + depends_on "openssl" + depends_on "opus" + + def install + args = %W[ + -DBUIld_WERROR=ON + -DCMAKE_INSTALL_PREFIX=#{prefix} + -DOPENSSL_ROOT_DIR=#{Formula["openssl"].opt_prefix} + -DSUNSHINE_ASSETS_DIR=sunshine/assets + -DSUNSHINE_BUILD_HOMEBREW=ON + ] + system "cmake", "-S", ".", "-B", "build", *std_cmake_args, *args + + cd "build" do + system "make", "-j" + system "make", "install" + end + end + + service do + run [opt_bin/"sunshine", "~/.config/sunshine/sunshine.conf"] + end + + def caveats + <<~EOS + Thanks for installing @PROJECT_NAME@! + + To get started, review the documentation at: + https://docs.lizardbyte.dev/projects/sunshine/en/latest/ + + Sunshine can only access microphones on macOS due to system limitations. + To stream system audio use "Soundflower" or "BlackHole". + + Gamepads are not currently supported on macOS. + EOS + end + + test do + # test that the binary runs at all + output = shell_output("#{bin}/sunshine --version").strip + puts output + + # TODO: add unit tests + end +end diff --git a/src_assets/macos/misc/uninstall_pkg.sh b/src_assets/macos/misc/uninstall_pkg.sh index 869f33d2fe6..89e7bbfb278 100644 --- a/src_assets/macos/misc/uninstall_pkg.sh +++ b/src_assets/macos/misc/uninstall_pkg.sh @@ -1,4 +1,7 @@ #!/bin/bash -e + +# note: this file was used to remove files when using the pkg/dmg, it is no longer used, but left for reference + set -e package_name=org.macports.Sunshine diff --git a/vite.config.js b/vite.config.js index a41470e4bf5..8732f1a08c7 100644 --- a/vite.config.js +++ b/vite.config.js @@ -16,13 +16,18 @@ import process from 'process' let assetsSrcPath = 'src_assets/common/assets/web'; let assetsDstPath = 'build/assets/web'; -if (process.env.SUNSHINE_SOURCE_ASSETS_DIR) { - console.log("Using srcdir from Cmake: " + resolve(process.env.SUNSHINE_SOURCE_ASSETS_DIR,"common/assets/web")); - assetsSrcPath = resolve(process.env.SUNSHINE_SOURCE_ASSETS_DIR,"common/assets/web") +if (process.env.SUNSHINE_BUILD_HOMEBREW) { + console.log("Building for homebrew, using default paths") } -if (process.env.SUNSHINE_ASSETS_DIR) { - console.log("Using destdir from Cmake: " + resolve(process.env.SUNSHINE_ASSETS_DIR,"assets/web")); - assetsDstPath = resolve(process.env.SUNSHINE_ASSETS_DIR,"assets/web") +else { + if (process.env.SUNSHINE_SOURCE_ASSETS_DIR) { + console.log("Using srcdir from Cmake: " + resolve(process.env.SUNSHINE_SOURCE_ASSETS_DIR,"common/assets/web")); + assetsSrcPath = resolve(process.env.SUNSHINE_SOURCE_ASSETS_DIR,"common/assets/web") + } + if (process.env.SUNSHINE_ASSETS_DIR) { + console.log("Using destdir from Cmake: " + resolve(process.env.SUNSHINE_ASSETS_DIR,"assets/web")); + assetsDstPath = resolve(process.env.SUNSHINE_ASSETS_DIR,"assets/web") + } } let header = fs.readFileSync(resolve(assetsSrcPath, "template_header.html")) From 9d5b01727efdc03a80f31c46a4c6ca529db5eee7 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 8 Mar 2024 23:13:27 -0600 Subject: [PATCH 047/129] Replace WMIC-based check for ViGEmBus with a Powershell check This version is simpler and much faster on machines with many installed apps. --- .../windows/misc/gamepad/install-gamepad.bat | 25 ++++++------------- 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src_assets/windows/misc/gamepad/install-gamepad.bat b/src_assets/windows/misc/gamepad/install-gamepad.bat index cf164cb5109..a31babb93f6 100644 --- a/src_assets/windows/misc/gamepad/install-gamepad.bat +++ b/src_assets/windows/misc/gamepad/install-gamepad.bat @@ -2,28 +2,17 @@ setlocal enabledelayedexpansion rem Check if a compatible version of ViGEmBus is already installed (1.17 or later) -set Version= -for /f "usebackq delims=" %%a in (`wmic product where "name='ViGEm Bus Driver' or name='Nefarius Virtual Gamepad Emulation Bus Driver'" get Version /format:Textvaluelist`) do ( - for /f "delims=" %%# in ("%%a") do set "%%#" -) - -rem Extract Major and Minor versions -for /f "tokens=1,2 delims=." %%a in ("%Version%") do ( - set "MajorVersion=%%a" - set "MinorVersion=%%b" -) - -rem Compare the version to 1.17 -if /i !MajorVersion! gtr 1 goto skip -if /i !MajorVersion! equ 1 ( - if /i !MinorVersion! geq 17 ( - goto skip - ) +rem +rem Note: We use exit code 2 to indicate success because either 0 or 1 may be returned +rem based on the PowerShell version if an exception occurs. +powershell -c Exit $(if ((Get-Item "$env:SystemRoot\System32\drivers\ViGEmBus.sys").VersionInfo.FileVersion -ge [System.Version]"1.17") { 2 } Else { 1 }) +if %ERRORLEVEL% EQU 2 ( + goto skip ) goto continue :skip -echo "The installed version is %Version%, no update needed. Exiting." +echo "The installed version is 1.17 or later, no update needed. Exiting." exit /b 0 :continue From 278567f72d02b528c45c749e8cecfa54d310d55e Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sat, 9 Mar 2024 11:18:39 -0600 Subject: [PATCH 048/129] Move kmsgrab dependencies from optdepends to depends kmsgrab is the most fully featured capture backend for current versions of Sunshine, so it should be built by default. In addition to zero-copy capture and HDR support, it is the *only* capture backend that can handle non-wlroots Wayland capture. --- docker/archlinux.dockerfile | 4 +--- packaging/linux/Arch/PKGBUILD | 6 +++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/docker/archlinux.dockerfile b/docker/archlinux.dockerfile index bd853ad395d..ddb3c28bafb 100644 --- a/docker/archlinux.dockerfile +++ b/docker/archlinux.dockerfile @@ -34,7 +34,7 @@ ENV COMMIT=${COMMIT} SHELL ["/bin/bash", "-o", "pipefail", "-c"] # install dependencies -# cuda, libcap, and libdrm are optional dependencies for PKGBUILD +# cuda is an optional build-time dependency for PKGBUILD RUN <<_DEPS #!/bin/bash set -e @@ -43,8 +43,6 @@ pacman -Syu --disable-download-timeout --needed --noconfirm \ cmake \ cuda \ git \ - libcap \ - libdrm \ namcap _DEPS diff --git a/packaging/linux/Arch/PKGBUILD b/packaging/linux/Arch/PKGBUILD index 4422698263e..dd478080049 100644 --- a/packaging/linux/Arch/PKGBUILD +++ b/packaging/linux/Arch/PKGBUILD @@ -13,6 +13,8 @@ depends=('avahi' 'boost-libs' 'curl' 'libayatana-appindicator' + 'libcap' + 'libdrm' 'libevdev' 'libmfx' 'libnotify' @@ -35,9 +37,7 @@ makedepends=('boost' 'make' 'nodejs' 'npm') -optdepends=('cuda: NvFBC capture support' - 'libcap' - 'libdrm') +optdepends=('cuda: NvFBC capture support') provides=('sunshine') From 74ce047a4b372cd7aa39abdae2f8b12629c3f57d Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sat, 9 Mar 2024 11:24:55 -0600 Subject: [PATCH 049/129] Add optdepends for Intel and AMD hardware encoding --- packaging/linux/Arch/PKGBUILD | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packaging/linux/Arch/PKGBUILD b/packaging/linux/Arch/PKGBUILD index dd478080049..4bdef18d99f 100644 --- a/packaging/linux/Arch/PKGBUILD +++ b/packaging/linux/Arch/PKGBUILD @@ -37,7 +37,9 @@ makedepends=('boost' 'make' 'nodejs' 'npm') -optdepends=('cuda: NvFBC capture support') +optdepends=('cuda: Nvidia GPU encoding support' + 'libva-mesa-driver: AMD GPU encoding support' + 'intel-media-driver: Intel GPU encoding support') provides=('sunshine') From cb4bfaa2f407ac3bdd6a08d4b47bbaf40d8f2f0e Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sat, 9 Mar 2024 11:55:22 -0600 Subject: [PATCH 050/129] Add the .INSTALL script needed for kmsgrab to work This also removes the standalone PKGBUILD artifact because our PKGBUILD has external dependencies now. --- .../prep/special_package_configuration.cmake | 1 + docker/archlinux.dockerfile | 2 +- docs/source/about/setup.rst | 19 ++----------------- packaging/linux/Arch/PKGBUILD | 1 + packaging/linux/Arch/sunshine.install | 12 ++++++++++++ 5 files changed, 17 insertions(+), 18 deletions(-) create mode 100644 packaging/linux/Arch/sunshine.install diff --git a/cmake/prep/special_package_configuration.cmake b/cmake/prep/special_package_configuration.cmake index 695b6e443c2..d04066cdc8a 100644 --- a/cmake/prep/special_package_configuration.cmake +++ b/cmake/prep/special_package_configuration.cmake @@ -29,6 +29,7 @@ elseif (UNIX) # configure the arch linux pkgbuild if(${SUNSHINE_CONFIGURE_PKGBUILD}) configure_file(packaging/linux/Arch/PKGBUILD PKGBUILD @ONLY) + configure_file(packaging/linux/Arch/sunshine.install sunshine.install @ONLY) endif() # configure the flatpak manifest diff --git a/docker/archlinux.dockerfile b/docker/archlinux.dockerfile index ddb3c28bafb..e8cfd93998e 100644 --- a/docker/archlinux.dockerfile +++ b/docker/archlinux.dockerfile @@ -78,6 +78,7 @@ _MAKE WORKDIR /build/sunshine/pkg RUN mv /build/sunshine/build/PKGBUILD . +RUN mv /build/sunshine/build/sunshine.install . # namcap and build PKGBUILD file RUN <<_PKGBUILD @@ -91,7 +92,6 @@ _PKGBUILD FROM scratch as artifacts -COPY --link --from=sunshine-build /build/sunshine/pkg/PKGBUILD /PKGBUILD COPY --link --from=sunshine-build /build/sunshine/pkg/sunshine*.pkg.tar.zst /sunshine.pkg.tar.zst FROM sunshine-base as sunshine diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 53da139875b..0a68bad8f14 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -38,7 +38,6 @@ Install =========================================== ============== ============== ================================ Package CUDA Version Min Driver CUDA Compute Capabilities =========================================== ============== ============== ================================ - PKGBUILD User dependent User dependent User dependent sunshine.AppImage 11.8.0 450.80.02 35;50;52;60;61;62;70;75;80;86;90 sunshine.pkg.tar.zst 11.8.0 450.80.02 35;50;52;60;61;62;70;75;80;86;90 sunshine_{arch}.flatpak 12.0.0 525.60.13 50;52;60;61;62;70;75;80;86;90 @@ -90,21 +89,7 @@ Install ./sunshine.AppImage --remove - .. tab:: Archlinux PKGBUILD - - #. Open terminal and run the following code. - - .. code-block:: bash - - wget https://github.com/LizardByte/Sunshine/releases/latest/download/PKGBUILD - makepkg -fi - - Uninstall: - .. code-block:: bash - - pacman -R sunshine - - .. tab:: Archlinux pkg + .. tab:: Arch Linux Package #. Open terminal and run the following code. @@ -205,7 +190,7 @@ Install sudo dnf remove sunshine - The `deb`, `rpm`, `Flatpak` and `AppImage` packages should handle these steps automatically. + The `deb`, `rpm`, `zst`, `Flatpak` and `AppImage` packages should handle these steps automatically. Third party packages may not. Sunshine needs access to `uinput` to create mouse and gamepad events. diff --git a/packaging/linux/Arch/PKGBUILD b/packaging/linux/Arch/PKGBUILD index 4bdef18d99f..44a6beb2b2f 100644 --- a/packaging/linux/Arch/PKGBUILD +++ b/packaging/linux/Arch/PKGBUILD @@ -8,6 +8,7 @@ pkgdesc="@PROJECT_DESCRIPTION@" arch=('x86_64' 'aarch64') url=@PROJECT_HOMEPAGE_URL@ license=('GPL3') +install=sunshine.install depends=('avahi' 'boost-libs' diff --git a/packaging/linux/Arch/sunshine.install b/packaging/linux/Arch/sunshine.install new file mode 100644 index 00000000000..4d4a4a45493 --- /dev/null +++ b/packaging/linux/Arch/sunshine.install @@ -0,0 +1,12 @@ +do_setcap() { + setcap cap_sys_admin+p $(readlink -f $(which sunshine)) +} + +post_install() { + do_setcap +} + +post_upgrade() { + do_setcap +} + From bc0a4786f4c403a696482933f9bd9a760cf4f344 Mon Sep 17 00:00:00 2001 From: brycerocky <56776312+brycerocky@users.noreply.github.com> Date: Sun, 10 Mar 2024 15:35:48 -0700 Subject: [PATCH 051/129] Use icon caching for system tray. (#2238) --- src/system_tray.cpp | 2 ++ third-party/tray | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/system_tray.cpp b/src/system_tray.cpp index 39131ba30fe..eb5948a41c1 100644 --- a/src/system_tray.cpp +++ b/src/system_tray.cpp @@ -145,6 +145,8 @@ namespace system_tray { { .text = "Restart", .cb = tray_restart_cb }, { .text = "Quit", .cb = tray_quit_cb }, { .text = nullptr } }, + .iconPathCount = 4, + .allIconPaths = { TRAY_ICON, TRAY_ICON_LOCKED, TRAY_ICON_PLAYING, TRAY_ICON_PAUSING }, }; /** diff --git a/third-party/tray b/third-party/tray index 2bf1c610300..a08c1025c3f 160000 --- a/third-party/tray +++ b/third-party/tray @@ -1 +1 @@ -Subproject commit 2bf1c610300b27f8d8ce87e2f13223fc83efeb42 +Subproject commit a08c1025c3f158d6b6c4b9bcf0ab770291d26896 From a2785baf0aa7202bceecd975b1aa2d8798d2378a Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 10 Mar 2024 22:03:20 -0400 Subject: [PATCH 052/129] fix(linux): automatically migrate config directory (#2240) --- .../linux/flatpak/dev.lizardbyte.sunshine.yml | 1 + src/platform/linux/misc.cpp | 48 +++++++++++++++---- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml index a4176d4ea15..1da03310f7a 100644 --- a/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml +++ b/packaging/linux/flatpak/dev.lizardbyte.sunshine.yml @@ -11,6 +11,7 @@ separate-locales: false finish-args: - --device=all # access all devices - --env=PULSE_PROP_media.category=Manager # allow sunshine to manage audio sinks + - --env=SUNSHINE_MIGRATE_CONFIG=1 # migrate config files to the new location - --filesystem=home # need to save files in user's home directory - --share=ipc # required for X11 shared memory extension - --share=network # access network diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 0075d4502f8..27b281ac3e0 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -100,22 +100,54 @@ namespace platf { fs::path appdata() { + bool found = false; + bool migrate_config = true; const char *dir; + const char *homedir; + fs::path config_path; + + // Get the home directory + if ((homedir = getenv("HOME")) == nullptr || strlen(homedir) == 0) { + // If HOME is empty or not set, use the current user's home directory + homedir = getpwuid(geteuid())->pw_dir; + } // May be set if running under a systemd service with the ConfigurationDirectory= option set. - if ((dir = getenv("CONFIGURATION_DIRECTORY")) != nullptr) { - return fs::path { dir } / "sunshine"sv; + if ((dir = getenv("CONFIGURATION_DIRECTORY")) != nullptr && strlen(dir) > 0) { + found = true; + config_path = fs::path(dir) / "sunshine"sv; } // Otherwise, follow the XDG base directory specification: // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html - if ((dir = getenv("XDG_CONFIG_HOME")) != nullptr) { - return fs::path { dir } / "sunshine"sv; - } - if ((dir = getenv("HOME")) == nullptr) { - dir = getpwuid(geteuid())->pw_dir; + if (!found && (dir = getenv("XDG_CONFIG_HOME")) != nullptr && strlen(dir) > 0) { + found = true; + config_path = fs::path(dir) / "sunshine"sv; + } + // As a last resort, use the home directory + if (!found) { + migrate_config = false; + config_path = fs::path(homedir) / ".config/sunshine"sv; + } + + // migrate from the old config location if necessary + if (migrate_config && found && getenv("SUNSHINE_MIGRATE_CONFIG") == "1"sv) { + fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; + if (old_config_path != config_path && fs::exists(old_config_path)) { + if (!fs::exists(config_path)) { + BOOST_LOG(info) << "Migrating config from "sv << old_config_path << " to "sv << config_path; + std::error_code ec; + fs::rename(old_config_path, config_path, ec); + if (ec) { + return old_config_path; + } + } + else { + BOOST_LOG(warning) << "Config exists in both "sv << old_config_path << " and "sv << config_path << ", using "sv << config_path << "... it is recommended to remove "sv << old_config_path; + } + } } - return fs::path { dir } / ".config/sunshine"sv; + return config_path; } std::string From 91744960c138772928b602eb0091a082d7f7a508 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Mon, 11 Mar 2024 02:42:25 -0500 Subject: [PATCH 053/129] Avoid broken fallback to cross-adapter NVENC encoding with KMS --- src/platform/linux/kmsgrab.cpp | 21 ++++++++++++++++++++- src/platform/linux/misc.cpp | 6 +++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index a7a3256d433..a567d70314a 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -108,6 +108,7 @@ namespace platf { using obj_prop_t = util::safe_ptr; using prop_t = util::safe_ptr; using prop_blob_t = util::safe_ptr; + using version_t = util::safe_ptr; using conn_type_count_t = std::map; @@ -364,6 +365,12 @@ namespace platf { return drmModeGetResources(fd.el); } + bool + is_nvidia() { + version_t ver { drmGetVersion(fd.el) }; + return ver && ver->name && strncmp(ver->name, "nvidia-drm", 10) == 0; + } + bool is_cursor(std::uint32_t plane_id) { auto props = plane_props(plane_id); @@ -604,6 +611,12 @@ namespace platf { continue; } + // Skip non-Nvidia cards if we're looking for CUDA devices + if (mem_type == mem_type_e::cuda && !card.is_nvidia()) { + BOOST_LOG(debug) << file << " is not a CUDA device"sv; + continue; + } + auto end = std::end(card); for (auto plane = std::begin(card); plane != end; ++plane) { // Skip unused planes @@ -1576,7 +1589,7 @@ namespace platf { // A list of names of displays accepted as display_name std::vector - kms_display_names() { + kms_display_names(mem_type_e hwdevice_type) { int count = 0; if (!fs::exists("/dev/dri")) { @@ -1608,6 +1621,12 @@ namespace platf { continue; } + // Skip non-Nvidia cards if we're looking for CUDA devices + if (hwdevice_type == mem_type_e::cuda && !card.is_nvidia()) { + BOOST_LOG(debug) << file << " is not a CUDA device"sv; + continue; + } + auto crtc_to_monitor = kms::map_crtc_to_monitor(card.monitors(conn_type_count)); auto end = std::end(card); diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 27b281ac3e0..884c0e9047a 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -766,13 +766,13 @@ namespace platf { #ifdef SUNSHINE_BUILD_DRM std::vector - kms_display_names(); + kms_display_names(mem_type_e hwdevice_type); std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); bool verify_kms() { - return !kms_display_names().empty(); + return !kms_display_names(mem_type_e::unknown).empty(); } #endif @@ -798,7 +798,7 @@ namespace platf { if (sources[source::WAYLAND]) return wl_display_names(); #endif #ifdef SUNSHINE_BUILD_DRM - if (sources[source::KMS]) return kms_display_names(); + if (sources[source::KMS]) return kms_display_names(hwdevice_type); #endif #ifdef SUNSHINE_BUILD_X11 if (sources[source::X11]) return x11_display_names(); From 3117fa57ec53709c665833eabb316441e02207fc Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 10 Mar 2024 19:35:51 -0500 Subject: [PATCH 054/129] Rename 85-sunshine.rules to 60-sunshine.rules This ensures the rules are evaluated before 73-seat-late.rules which enables uaccess tag application for existing logged on users. --- cmake/packaging/linux.cmake | 4 ++-- docs/source/about/setup.rst | 2 +- packaging/linux/AppImage/AppRun | 4 ++-- packaging/linux/flatpak/scripts/additional-install.sh | 4 ++-- packaging/linux/flatpak/scripts/remove-additional-install.sh | 2 +- .../linux/misc/{85-sunshine.rules => 60-sunshine.rules} | 0 6 files changed, 8 insertions(+), 8 deletions(-) rename src_assets/linux/misc/{85-sunshine.rules => 60-sunshine.rules} (100%) diff --git a/cmake/packaging/linux.cmake b/cmake/packaging/linux.cmake index 8563414a40e..499f058c8bd 100644 --- a/cmake/packaging/linux.cmake +++ b/cmake/packaging/linux.cmake @@ -3,7 +3,7 @@ install(DIRECTORY "${SUNSHINE_SOURCE_ASSETS_DIR}/linux/assets/" DESTINATION "${SUNSHINE_ASSETS_DIR}") if(${SUNSHINE_BUILD_APPIMAGE} OR ${SUNSHINE_BUILD_FLATPAK}) - install(FILES "${SUNSHINE_SOURCE_ASSETS_DIR}/linux/misc/85-sunshine.rules" + install(FILES "${SUNSHINE_SOURCE_ASSETS_DIR}/linux/misc/60-sunshine.rules" DESTINATION "${SUNSHINE_ASSETS_DIR}/udev/rules.d") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/sunshine.service" DESTINATION "${SUNSHINE_ASSETS_DIR}/systemd/user") @@ -11,7 +11,7 @@ else() find_package(Systemd) find_package(Udev) - install(FILES "${SUNSHINE_SOURCE_ASSETS_DIR}/linux/misc/85-sunshine.rules" + install(FILES "${SUNSHINE_SOURCE_ASSETS_DIR}/linux/misc/60-sunshine.rules" DESTINATION "${UDEV_RULES_INSTALL_DIR}") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/sunshine.service" DESTINATION "${SYSTEMD_USER_UNIT_INSTALL_DIR}") diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 0a68bad8f14..89b5830247f 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -199,7 +199,7 @@ Install .. code-block:: bash echo 'KERNEL=="uinput", SUBSYSTEM=="misc", OPTIONS+="static_node=uinput", TAG+="uaccess"' | \ - sudo tee /etc/udev/rules.d/85-sunshine.rules + sudo tee /etc/udev/rules.d/60-sunshine.rules #. Optionally, configure autostart service diff --git a/packaging/linux/AppImage/AppRun b/packaging/linux/AppImage/AppRun index ddc5fd38455..4eeaeada97f 100644 --- a/packaging/linux/AppImage/AppRun +++ b/packaging/linux/AppImage/AppRun @@ -46,7 +46,7 @@ echo " function install() { # user input rules # shellcheck disable=SC2002 - cat "$SUNSHINE_SHARE_HERE/udev/rules.d/85-sunshine.rules" | sudo tee /etc/udev/rules.d/85-sunshine.rules + cat "$SUNSHINE_SHARE_HERE/udev/rules.d/60-sunshine.rules" | sudo tee /etc/udev/rules.d/60-sunshine.rules # sunshine service mkdir -p ~/.config/systemd/user @@ -79,7 +79,7 @@ function install() { function remove() { # remove input rules - sudo rm -f /etc/udev/rules.d/85-sunshine.rules + sudo rm -f /etc/udev/rules.d/60-sunshine.rules # remove service sudo rm -f ~/.config/systemd/user/sunshine.service diff --git a/packaging/linux/flatpak/scripts/additional-install.sh b/packaging/linux/flatpak/scripts/additional-install.sh index 8a905b53810..a27db4e09ba 100644 --- a/packaging/linux/flatpak/scripts/additional-install.sh +++ b/packaging/linux/flatpak/scripts/additional-install.sh @@ -7,7 +7,7 @@ echo Sunshine User Service has been installed. echo Use [systemctl --user enable sunshine] once to autostart Sunshine on login. # Udev rule -UDEV=$(cat /app/share/sunshine/udev/rules.d/85-sunshine.rules) +UDEV=$(cat /app/share/sunshine/udev/rules.d/60-sunshine.rules) echo Configuring mouse permission. -flatpak-spawn --host pkexec sh -c "echo '$UDEV' > /etc/udev/rules.d/85-sunshine.rules" +flatpak-spawn --host pkexec sh -c "echo '$UDEV' > /etc/udev/rules.d/60-sunshine.rules" echo Restart computer for mouse permission to take effect. diff --git a/packaging/linux/flatpak/scripts/remove-additional-install.sh b/packaging/linux/flatpak/scripts/remove-additional-install.sh index 6148f62ea1e..0d13baeb62c 100644 --- a/packaging/linux/flatpak/scripts/remove-additional-install.sh +++ b/packaging/linux/flatpak/scripts/remove-additional-install.sh @@ -7,5 +7,5 @@ systemctl --user daemon-reload echo Sunshine User Service has been removed. # Udev rule -flatpak-spawn --host pkexec sh -c "rm /etc/udev/rules.d/85-sunshine.rules" +flatpak-spawn --host pkexec sh -c "rm /etc/udev/rules.d/60-sunshine.rules" echo Mouse permission removed. Restart computer to take effect. diff --git a/src_assets/linux/misc/85-sunshine.rules b/src_assets/linux/misc/60-sunshine.rules similarity index 100% rename from src_assets/linux/misc/85-sunshine.rules rename to src_assets/linux/misc/60-sunshine.rules From 3181d91edf6e1ad958f19626381b5980fc2afabb Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 10 Mar 2024 20:06:59 -0500 Subject: [PATCH 055/129] Apply udev rules to /dev/uinput immediately after installation --- docs/source/about/setup.rst | 5 ++++- packaging/linux/AppImage/AppRun | 21 ++------------------- packaging/linux/Arch/sunshine.install | 8 ++++++++ src_assets/linux/misc/postinst | 7 +++++++ 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 89b5830247f..8b803a78215 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -195,11 +195,14 @@ Install Sunshine needs access to `uinput` to create mouse and gamepad events. - #. Create `udev` rules. + #. Create and reload `udev` rules for uinput. .. code-block:: bash echo 'KERNEL=="uinput", SUBSYSTEM=="misc", OPTIONS+="static_node=uinput", TAG+="uaccess"' | \ sudo tee /etc/udev/rules.d/60-sunshine.rules + sudo udevadm control --reload-rules + sudo udevadm trigger + sudo modprobe uinput #. Optionally, configure autostart service diff --git a/packaging/linux/AppImage/AppRun b/packaging/linux/AppImage/AppRun index 4eeaeada97f..404704c34d3 100644 --- a/packaging/linux/AppImage/AppRun +++ b/packaging/linux/AppImage/AppRun @@ -47,6 +47,8 @@ function install() { # user input rules # shellcheck disable=SC2002 cat "$SUNSHINE_SHARE_HERE/udev/rules.d/60-sunshine.rules" | sudo tee /etc/udev/rules.d/60-sunshine.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --property-match=DEVNAME=/dev/uinput # sunshine service mkdir -p ~/.config/systemd/user @@ -56,25 +58,6 @@ function install() { # setcap sudo setcap cap_sys_admin+p "$(readlink -f "$SUNSHINE_BIN_HERE")" - - while true - do - read -r -p "This installation requires a reboot. Do you want to reboot NOW? [y/n] " input - - case $input in - [yY][eE][sS]|[yY]) - echo "Yes" - sudo reboot now - ;; - [nN][oO]|[nN]) - echo "No" - break - ;; - *) - echo "Invalid input..." - ;; - esac - done } function remove() { diff --git a/packaging/linux/Arch/sunshine.install b/packaging/linux/Arch/sunshine.install index 4d4a4a45493..a8a700f1f1c 100644 --- a/packaging/linux/Arch/sunshine.install +++ b/packaging/linux/Arch/sunshine.install @@ -2,11 +2,19 @@ do_setcap() { setcap cap_sys_admin+p $(readlink -f $(which sunshine)) } +do_udev_reload() { + udevadm control --reload-rules + udevadm trigger --property-match=DEVNAME=/dev/uinput + modprobe uinput || true +} + post_install() { do_setcap + do_udev_reload } post_upgrade() { do_setcap + do_udev_reload } diff --git a/src_assets/linux/misc/postinst b/src_assets/linux/misc/postinst index 63f0523d867..aab899f94ec 100644 --- a/src_assets/linux/misc/postinst +++ b/src_assets/linux/misc/postinst @@ -6,3 +6,10 @@ if [ -x "$path_to_setcap" ] ; then echo "$path_to_setcap cap_sys_admin+p /usr/bin/sunshine" $path_to_setcap cap_sys_admin+p $(readlink -f /usr/bin/sunshine) fi + +# Trigger udev rule reload for /dev/uinput +path_to_udevadm=$(which udevadm) +if [ -x "$path_to_udevadm" ] ; then + $path_to_udevadm control --reload-rules + $path_to_udevadm trigger --property-match=DEVNAME=/dev/uinput +fi From 97467ea355ea3f39ad1ea568847d85757aa1052b Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 10 Mar 2024 22:06:11 -0500 Subject: [PATCH 056/129] Reorder and reword the KMS setup step --- docs/source/about/setup.rst | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 8b803a78215..5b1f32937b9 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -204,6 +204,22 @@ Install sudo udevadm trigger sudo modprobe uinput + #. Enable permissions for KMS capture. + .. warning:: Capture of most Wayland-based desktop environments will fail unless this step is performed. + + .. note:: ``cap_sys_admin`` may as well be root, except you don't need to be root to run it. It is necessary to + allow Sunshine to use KMS capture. + + **Enable** + .. code-block:: bash + + sudo setcap cap_sys_admin+p $(readlink -f $(which sunshine)) + + **Disable (for Xorg/X11 only)** + .. code-block:: bash + + sudo setcap -r $(readlink -f $(which sunshine)) + #. Optionally, configure autostart service - filename: ``~/.config/systemd/user/sunshine.service`` @@ -248,20 +264,6 @@ Install systemctl --user enable sunshine - #. Additional Setup for KMS - .. note:: ``cap_sys_admin`` may as well be root, except you don't need to be root to run it. It is necessary to - allow Sunshine to use KMS. - - **Enable** - .. code-block:: bash - - sudo setcap cap_sys_admin+p $(readlink -f $(which sunshine)) - - **Disable (for Xorg/X11)** - .. code-block:: bash - - sudo setcap -r $(readlink -f $(which sunshine)) - #. Reboot .. code-block:: bash From e383ab99563e82e54a15e2d4b394e7bc3f0c8bb9 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 10 Mar 2024 22:20:52 -0500 Subject: [PATCH 057/129] Add note to prefer distro packages over Flatpak/AppImage --- docs/source/about/setup.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 5b1f32937b9..70ed96f57f7 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -51,6 +51,8 @@ Install .. tab:: AppImage + .. caution:: Use distro-specific packages instead of the AppImage if they are available. + According to AppImageLint the supported distro matrix of the AppImage is below. - ✔ Debian bullseye @@ -103,7 +105,7 @@ Install pacman -R sunshine - .. tab:: Debian Package + .. tab:: Debian/Ubuntu Package #. Download ``sunshine-{distro}-{distro-version}-{arch}.deb`` and run the following code. @@ -123,6 +125,8 @@ Install .. tab:: Flatpak Package + .. caution:: Use distro-specific packages instead of the Flatpak if they are available. + .. important:: The instructions provided here are for the version supplied in the `latest release`_, which does not necessarily match the version in the Flathub repository! From d8877982ffe4a4fc22dbae3e2776145d6651d92a Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 12 Mar 2024 18:08:14 -0500 Subject: [PATCH 058/129] Improve KMS debuggability and avoid known broken cases --- src/platform/linux/kmsgrab.cpp | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index a567d70314a..748fc93a967 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -15,6 +15,7 @@ #include #include +#include "src/config.h" #include "src/logging.h" #include "src/platform/common.h" #include "src/round_robin.h" @@ -298,6 +299,9 @@ namespace platf { return -1; } + version_t ver { drmGetVersion(fd.el) }; + BOOST_LOG(info) << path << " -> "sv << ((ver && ver->name) ? ver->name : "UNKNOWN"); + // Open the render node for this card to share with libva. // If it fails, we'll just share the primary node instead. char *rendernode_path = drmGetRenderDeviceNameFromFd(fd.el); @@ -316,12 +320,21 @@ namespace platf { } if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) { - BOOST_LOG(error) << "Couldn't expose some/all drm planes for card: "sv << path; + BOOST_LOG(error) << "GPU driver doesn't support universal planes: "sv << path; return -1; } if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_ATOMIC, 1)) { - BOOST_LOG(warning) << "Couldn't expose some properties for card: "sv << path; + BOOST_LOG(warning) << "GPU driver doesn't support atomic mode-setting: "sv << path; +#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") { + BOOST_LOG(info) << "Avoiding KMS capture under X11 due to lack of atomic mode-setting"sv; + return -1; + } +#endif + BOOST_LOG(warning) << "Cursor capture may fail without atomic mode-setting support!"sv; } plane_res.reset(drmModeGetPlaneResources(fd.el)); @@ -640,8 +653,7 @@ namespace platf { } if (!fb->handles[0]) { - BOOST_LOG(error) - << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Possibly not permitted: do [sudo setcap cap_sys_admin+p sunshine]"sv; + BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; return -1; } @@ -909,12 +921,14 @@ namespace platf { if (!prop_crtc_w || !prop_crtc_h || !prop_crtc_x || !prop_crtc_y) { BOOST_LOG(error) << "Cursor plane is missing required plane CRTC properties!"sv; + BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv; cursor_plane_id = -1; captured_cursor.visible = false; return; } if (!prop_src_x || !prop_src_y || !prop_src_w || !prop_src_h) { BOOST_LOG(error) << "Cursor plane is missing required plane SRC properties!"sv; + BOOST_LOG(error) << "Atomic mode-setting must be enabled to capture the cursor!"sv; cursor_plane_id = -1; captured_cursor.visible = false; return; @@ -1072,8 +1086,7 @@ namespace platf { } if (!fb->handles[0]) { - BOOST_LOG(error) - << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Possibly not permitted: do [sudo setcap cap_sys_admin+p sunshine]"sv; + BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; return capture_e::error; } @@ -1647,8 +1660,9 @@ namespace platf { } if (!fb->handles[0]) { - BOOST_LOG(error) - << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Possibly not permitted: do [sudo setcap cap_sys_admin+p sunshine]"sv; + BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; + BOOST_LOG((window_system != window_system_e::X11 || config::video.capture == "kms") ? fatal : error) + << "You must run [sudo setcap cap_sys_admin+p $(readlink -f sunshine)] for KMS display capture to work!"sv; break; } From c13a30db7876ad18fecd222f4433ccd11f24d6c5 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Tue, 12 Mar 2024 21:01:49 -0500 Subject: [PATCH 059/129] Allow NVENC to be forced to try capturing non-Nvidia GPUs --- src/platform/linux/kmsgrab.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 748fc93a967..d4feb3557d8 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -625,9 +625,12 @@ namespace platf { } // Skip non-Nvidia cards if we're looking for CUDA devices + // 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; - continue; + if (config::video.encoder != "nvenc") { + continue; + } } auto end = std::end(card); @@ -1635,9 +1638,15 @@ namespace platf { } // Skip non-Nvidia cards if we're looking for CUDA devices + // 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; - continue; + if (config::video.encoder == "nvenc") { + BOOST_LOG(warning) << "Using NVENC with your display connected to a different GPU may not work properly!"sv; + } + else { + continue; + } } auto crtc_to_monitor = kms::map_crtc_to_monitor(card.monitors(conn_type_count)); From 1859e23cd5be366a38a106b5e9e42149b68f8961 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Mar 2024 09:04:41 -0400 Subject: [PATCH 060/129] build(deps): bump LizardByte/homebrew-release-action from 2024.309.150158 to 2024.311.172824 (#2245) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/CI.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index f2529e7390e..80c309ca052 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -588,7 +588,7 @@ jobs: echo "publish=${PUBLISH}" >> $GITHUB_OUTPUT - name: Validate and Publish Homebrew Formula - uses: LizardByte/homebrew-release-action@v2024.309.150158 + uses: LizardByte/homebrew-release-action@v2024.311.172824 with: formula_file: ${{ github.workspace }}/homebrew/sunshine.rb git_email: ${{ secrets.GH_BOT_EMAIL }} From 0bfad20d4c3d7ffe27b25a9617e601998911e5c4 Mon Sep 17 00:00:00 2001 From: Crashdummy Date: Wed, 13 Mar 2024 14:48:13 +0100 Subject: [PATCH 061/129] fix(Linux/Fedora): re-enable CUDA and bump to 12.4.0 (#2247) --- docker/fedora-38.dockerfile | 42 ++++++++++++++++---------------- docker/fedora-39.dockerfile | 48 ++++++++++++++++++------------------- docs/source/about/setup.rst | 4 ++-- 3 files changed, 45 insertions(+), 49 deletions(-) diff --git a/docker/fedora-38.dockerfile b/docker/fedora-38.dockerfile index 9ba496c5b97..55622ab7070 100644 --- a/docker/fedora-38.dockerfile +++ b/docker/fedora-38.dockerfile @@ -68,28 +68,27 @@ dnf clean all rm -rf /var/cache/yum _DEPS -# todo - enable cuda once it's supported for gcc 13 and fedora 38 ## install cuda -#WORKDIR /build/cuda +WORKDIR /build/cuda ## versions: https://developer.nvidia.com/cuda-toolkit-archive -#ENV CUDA_VERSION="12.0.0" -#ENV CUDA_BUILD="525.60.13" +ENV CUDA_VERSION="12.4.0" +ENV CUDA_BUILD="550.54.14" ## hadolint ignore=SC3010 -#RUN <<_INSTALL_CUDA -##!/bin/bash -#set -e -#cuda_prefix="https://developer.download.nvidia.com/compute/cuda/" -#cuda_suffix="" -#if [[ "${TARGETPLATFORM}" == 'linux/arm64' ]]; then -# cuda_suffix="_sbsa" -#fi -#url="${cuda_prefix}${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux${cuda_suffix}.run" -#echo "cuda url: ${url}" -#wget "$url" --progress=bar:force:noscroll -q --show-progress -O ./cuda.run -#chmod a+x ./cuda.run -#./cuda.run --silent --toolkit --toolkitpath=/build/cuda --no-opengl-libs --no-man-page --no-drm -#rm ./cuda.run -#_INSTALL_CUDA +RUN <<_INSTALL_CUDA +#!/bin/bash +set -e +cuda_prefix="https://developer.download.nvidia.com/compute/cuda/" +cuda_suffix="" +if [[ "${TARGETPLATFORM}" == 'linux/arm64' ]]; then + cuda_suffix="_sbsa" +fi +url="${cuda_prefix}${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux${cuda_suffix}.run" +echo "cuda url: ${url}" +wget "$url" --progress=bar:force:noscroll -q --show-progress -O ./cuda.run +chmod a+x ./cuda.run +./cuda.run --silent --toolkit --toolkitpath=/build/cuda --no-opengl-libs --no-man-page --no-drm +rm ./cuda.run +_INSTALL_CUDA # copy repository WORKDIR /build/sunshine/ @@ -99,12 +98,11 @@ COPY --link .. . WORKDIR /build/sunshine/build # cmake and cpack -# todo - add cmake argument back in for cuda support "-DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \" -# todo - re-enable "DSUNSHINE_ENABLE_CUDA" RUN <<_MAKE #!/bin/bash set -e cmake \ + -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DBUILD_WERROR=ON \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ @@ -113,7 +111,7 @@ cmake \ -DSUNSHINE_ENABLE_WAYLAND=ON \ -DSUNSHINE_ENABLE_X11=ON \ -DSUNSHINE_ENABLE_DRM=ON \ - -DSUNSHINE_ENABLE_CUDA=OFF \ + -DSUNSHINE_ENABLE_CUDA=ON \ /build/sunshine make -j "$(nproc)" cpack -G RPM diff --git a/docker/fedora-39.dockerfile b/docker/fedora-39.dockerfile index e942a8aa916..7bdb4adc216 100644 --- a/docker/fedora-39.dockerfile +++ b/docker/fedora-39.dockerfile @@ -68,28 +68,27 @@ dnf clean all rm -rf /var/cache/yum _DEPS -# todo - enable cuda once it's supported for gcc 13 and fedora 39 -## install cuda -#WORKDIR /build/cuda -## versions: https://developer.nvidia.com/cuda-toolkit-archive -#ENV CUDA_VERSION="12.0.0" -#ENV CUDA_BUILD="525.60.13" -## hadolint ignore=SC3010 -#RUN <<_INSTALL_CUDA -##!/bin/bash -#set -e -#cuda_prefix="https://developer.download.nvidia.com/compute/cuda/" -#cuda_suffix="" -#if [[ "${TARGETPLATFORM}" == 'linux/arm64' ]]; then -# cuda_suffix="_sbsa" -#fi -#url="${cuda_prefix}${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux${cuda_suffix}.run" -#echo "cuda url: ${url}" -#wget "$url" --progress=bar:force:noscroll -q --show-progress -O ./cuda.run -#chmod a+x ./cuda.run -#./cuda.run --silent --toolkit --toolkitpath=/build/cuda --no-opengl-libs --no-man-page --no-drm -#rm ./cuda.run -#_INSTALL_CUDA +# install cuda +WORKDIR /build/cuda +# versions: https://developer.nvidia.com/cuda-toolkit-archive +ENV CUDA_VERSION="12.4.0" +ENV CUDA_BUILD="550.54.14" +# hadolint ignore=SC3010 +RUN <<_INSTALL_CUDA +#!/bin/bash +set -e +cuda_prefix="https://developer.download.nvidia.com/compute/cuda/" +cuda_suffix="" +if [[ "${TARGETPLATFORM}" == 'linux/arm64' ]]; then + cuda_suffix="_sbsa" +fi +url="${cuda_prefix}${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux${cuda_suffix}.run" +echo "cuda url: ${url}" +wget "$url" --progress=bar:force:noscroll -q --show-progress -O ./cuda.run +chmod a+x ./cuda.run +./cuda.run --silent --toolkit --toolkitpath=/build/cuda --no-opengl-libs --no-man-page --no-drm +rm ./cuda.run +_INSTALL_CUDA # copy repository WORKDIR /build/sunshine/ @@ -99,12 +98,11 @@ COPY --link .. . WORKDIR /build/sunshine/build # cmake and cpack -# todo - add cmake argument back in for cuda support "-DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \" -# todo - re-enable "DSUNSHINE_ENABLE_CUDA" RUN <<_MAKE #!/bin/bash set -e cmake \ + -DCMAKE_CUDA_COMPILER:PATH=/build/cuda/bin/nvcc \ -DBUILD_WERROR=ON \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ @@ -113,7 +111,7 @@ cmake \ -DSUNSHINE_ENABLE_WAYLAND=ON \ -DSUNSHINE_ENABLE_X11=ON \ -DSUNSHINE_ENABLE_DRM=ON \ - -DSUNSHINE_ENABLE_CUDA=OFF \ + -DSUNSHINE_ENABLE_CUDA=ON \ /build/sunshine make -j "$(nproc)" cpack -G RPM diff --git a/docs/source/about/setup.rst b/docs/source/about/setup.rst index 70ed96f57f7..2a2b015ce9c 100644 --- a/docs/source/about/setup.rst +++ b/docs/source/about/setup.rst @@ -43,8 +43,8 @@ Install sunshine_{arch}.flatpak 12.0.0 525.60.13 50;52;60;61;62;70;75;80;86;90 sunshine-debian-bookworm-{arch}.deb 12.0.0 525.60.13 50;52;60;61;62;70;75;80;86;90 sunshine-debian-bullseye-{arch}.deb 11.8.0 450.80.02 35;50;52;60;61;62;70;75;80;86;90 - sunshine-fedora-38-{arch}.rpm unavailable unavailable none - sunshine-fedora-39-{arch}.rpm unavailable unavailable none + sunshine-fedora-38-{arch}.rpm 12.4.0 525.60.13 50;52;60;61;62;70;75;80;86;90 + sunshine-fedora-39-{arch}.rpm 12.4.0 525.60.13 50;52;60;61;62;70;75;80;86;90 sunshine-ubuntu-20.04-{arch}.deb 11.8.0 450.80.02 35;50;52;60;61;62;70;75;80;86;90 sunshine-ubuntu-22.04-{arch}.deb 11.8.0 450.80.02 35;50;52;60;61;62;70;75;80;86;90 =========================================== ============== ============== ================================ From 3e49e25c63eed5cbc3d9596515ce359603060bdd Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Wed, 13 Mar 2024 10:44:31 -0400 Subject: [PATCH 062/129] chore: bump version to v0.22.1 (#2221) Co-authored-by: Cameron Gutman --- CHANGELOG.md | 38 ++++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f8290545da..6ab14e01b8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,42 @@ # Changelog +## [0.22.1] - 2024-03-13 +**Breaking** +- (ArchLinux) Drop support for standalone PKGBUILD files. Use the binary Arch package or install via AUR instead. +- (macOS) Drop support for experimental dmg package. Use Homebrew or MacPorts instead. + +**Added** +- (macOS) Added Homebrew support + +**Changed** +- (Process/Windows) The working directory is now searched first when the command contains a relative path +- (ArchLinux) The kmsgrab capture backend is now compiled by default to support Wayland capture on non-wlroots-based compositors +- (Capture/Linux) X11 capture is now preferred over kmsgrab for cards that lack atomic modesetting support to ensure cursor capture works +- (Capture/Linux) Kmsgrab will only choose NVENC by default if the display is connected to the Nvidia GPU to avoid possible EGL import failures + +**Fixed** +- (Config) Fix unsupported resolution error with some Moonlight clients +- (Capture/Windows) Fix crash when streaming Ryujinx, Red Alert 2, and other apps that use unusually sized monochrome cursors +- (Capture/Linux) Fix crash in KMS cursor capture when running on Arch-based distros +- (Capture/Linux) Fix crash if CUDA GPU has a PCI ID with hexadecimal digits greater than 9 +- (Process/Windows) Fix starting apps when the working directory is enclosed in quotes +- (Process/Windows) Fix process tree tracking when the app is launched via a cmd.exe trampoline +- (Installer/Windows) Fix slow operation during ViGEmBus installation that may cause the installer to appear stuck +- (Build/macOS) Fix issues building on macOS 13 and 14 +- (Build/Linux) Fix missing install script in the Arch binary package +- (Build/Linux) Fix missing optional dependencies in the Arch binary package +- (Build/Linux) Ensure correct Arch pkg is published to GitHub releases +- (Capture/Linux) Fix mismatched case and unhandled exception in CUDA device lookup +- (Config) Add missing resolution to default config ui +- (Linux) Fix udev rules for uinput access not working until after reboot +- (Linux) Fix wrong path in desktop files +- (Tray) Cache icons to avoid possible DRM issues +- (Linux) Migrate old config files to new location if env SUNSHINE_MIGRATE_CONFIG=1 is set (automatically set for Flatpak) +- (Linux/Fedora) Re-enable CUDA support and bump to 12.4.0 + +**Misc** +- (Build/Windows) Adjust Windows debuginfo artifact to reduce confusion with real release binaries + ## [0.22.0] - 2024-03-03 **Breaking** - (Network) Clients must now be paired with the host before they can use Wake-on-LAN @@ -720,3 +757,4 @@ settings. In v0.17.0, games now run under your user account without elevated pri [0.20.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.20.0 [0.21.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.21.0 [0.22.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.0 +[0.22.1]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.1 diff --git a/CMakeLists.txt b/CMakeLists.txt index 593d86b82dd..fce20cd2bb7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.18) # todo - set this conditionally # todo - set version to 0.0.0 once confident in automated versioning -project(Sunshine VERSION 0.22.0 +project(Sunshine VERSION 0.22.1 DESCRIPTION "Self-hosted game stream host for Moonlight" HOMEPAGE_URL "https://app.lizardbyte.dev/Sunshine") From 22736c4ce92d3a359a96db1cd9107adea5db484f Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Wed, 13 Mar 2024 18:05:45 -0400 Subject: [PATCH 063/129] Fix(linux/fedora39) patch system headers so build succeeds with cuda (#2253) Co-authored-by: Cameron Gutman <2695644+cgutman@users.noreply.github.com> --- .gitattributes | 3 +++ docker/fedora-39.dockerfile | 7 +++++++ 2 files changed, 10 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..1ccee08a107 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# ensure dockerfiles are checked out with LF line endings +Dockerfile text eol=lf +*.dockerfile text eol=lf diff --git a/docker/fedora-39.dockerfile b/docker/fedora-39.dockerfile index 7bdb4adc216..20dae39a797 100644 --- a/docker/fedora-39.dockerfile +++ b/docker/fedora-39.dockerfile @@ -81,6 +81,13 @@ cuda_prefix="https://developer.download.nvidia.com/compute/cuda/" cuda_suffix="" if [[ "${TARGETPLATFORM}" == 'linux/arm64' ]]; then cuda_suffix="_sbsa" + + # patch headers https://bugs.launchpad.net/ubuntu/+source/mumax3/+bug/2032624 + sed -i 's/__Float32x4_t/int/g' /usr/include/bits/math-vector.h + sed -i 's/__Float64x2_t/int/g' /usr/include/bits/math-vector.h + sed -i 's/__SVFloat32_t/float/g' /usr/include/bits/math-vector.h + sed -i 's/__SVFloat64_t/float/g' /usr/include/bits/math-vector.h + sed -i 's/__SVBool_t/int/g' /usr/include/bits/math-vector.h fi url="${cuda_prefix}${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux${cuda_suffix}.run" echo "cuda url: ${url}" From c43dd2489f217e7ab04a16fc1bf7534cf6266e5f Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Wed, 13 Mar 2024 17:32:04 -0500 Subject: [PATCH 064/129] Don't update tray icon after tray_exit() was called --- CHANGELOG.md | 1 + src/system_tray.cpp | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ab14e01b8e..d1c67c68c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ - (Linux) Fix udev rules for uinput access not working until after reboot - (Linux) Fix wrong path in desktop files - (Tray) Cache icons to avoid possible DRM issues +- (Tray) Fix attempt to update tray icon after it was destroyed - (Linux) Migrate old config files to new location if env SUNSHINE_MIGRATE_CONFIG=1 is set (automatically set for Flatpak) - (Linux/Fedora) Re-enable CUDA support and bump to 12.4.0 diff --git a/src/system_tray.cpp b/src/system_tray.cpp index eb5948a41c1..c34c3d75a98 100644 --- a/src/system_tray.cpp +++ b/src/system_tray.cpp @@ -47,6 +47,8 @@ using namespace std::literals; // system_tray namespace namespace system_tray { + static std::atomic tray_initialized = false; + /** * @brief Callback for opening the UI from the system tray. * @param item The tray menu item. @@ -239,6 +241,7 @@ namespace system_tray { BOOST_LOG(info) << "System tray created"sv; } + tray_initialized = true; while (tray_loop(1) == 0) { BOOST_LOG(debug) << "System tray loop"sv; } @@ -275,6 +278,7 @@ namespace system_tray { */ int end_tray() { + tray_initialized = false; tray_exit(); return 0; } @@ -285,6 +289,10 @@ namespace system_tray { */ void update_tray_playing(std::string app_name) { + if (!tray_initialized) { + return; + } + tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; @@ -307,6 +315,10 @@ namespace system_tray { */ void update_tray_pausing(std::string app_name) { + if (!tray_initialized) { + return; + } + tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; @@ -329,6 +341,10 @@ namespace system_tray { */ void update_tray_stopped(std::string app_name) { + if (!tray_initialized) { + return; + } + tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; @@ -350,6 +366,10 @@ namespace system_tray { */ void update_tray_require_pin() { + if (!tray_initialized) { + return; + } + tray.notification_title = NULL; tray.notification_text = NULL; tray.notification_cb = NULL; From 476141d740bc5ae622967db6c57ccf156b2a6483 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 14 Mar 2024 21:13:55 -0400 Subject: [PATCH 065/129] build(deps): bump LizardByte/homebrew-release-action from 2024.311.172824 to 2024.314.134529 (#2264) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/CI.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 80c309ca052..09a0aaeae66 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -588,7 +588,7 @@ jobs: echo "publish=${PUBLISH}" >> $GITHUB_OUTPUT - name: Validate and Publish Homebrew Formula - uses: LizardByte/homebrew-release-action@v2024.311.172824 + uses: LizardByte/homebrew-release-action@v2024.314.134529 with: formula_file: ${{ github.workspace }}/homebrew/sunshine.rb git_email: ${{ secrets.GH_BOT_EMAIL }} From b523945f48ba5542dc5a3fd1d3897ba726092723 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Thu, 14 Mar 2024 18:11:27 -0500 Subject: [PATCH 066/129] Update tray submodule to fix broken tray icon on some systems --- third-party/tray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third-party/tray b/third-party/tray index a08c1025c3f..4d8b798cafd 160000 --- a/third-party/tray +++ b/third-party/tray @@ -1 +1 @@ -Subproject commit a08c1025c3f158d6b6c4b9bcf0ab770291d26896 +Subproject commit 4d8b798cafdd11285af9409c16b5f792968e0045 From f66a7d5da65a00d5b8cb8aed79169b67be9c1076 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Thu, 14 Mar 2024 18:37:00 -0500 Subject: [PATCH 067/129] Fix dereferencing a null pointer if SUNSHINE_MIGRATE_CONFIG doesn't exist --- src/platform/linux/misc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 884c0e9047a..b4de6005d13 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -104,6 +104,7 @@ namespace platf { bool migrate_config = true; const char *dir; const char *homedir; + const char *migrate_envvar; fs::path config_path; // Get the home directory @@ -130,7 +131,8 @@ namespace platf { } // migrate from the old config location if necessary - if (migrate_config && found && getenv("SUNSHINE_MIGRATE_CONFIG") == "1"sv) { + migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); + if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; if (old_config_path != config_path && fs::exists(old_config_path)) { if (!fs::exists(config_path)) { From aa1985dec84fcf26b941a2bde4998351bbb2f2a9 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 15 Mar 2024 00:11:02 -0500 Subject: [PATCH 068/129] Avoid calling Boost logging functions in appdata() The app data directory is needed prior to logging initialization. --- src/platform/linux/misc.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index b4de6005d13..b4e3d1aec9b 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -10,6 +10,7 @@ // standard includes #include +#include // lib includes #include @@ -98,6 +99,11 @@ namespace platf { return ifaddr_t { p }; } + /** + * @brief Performs migration if necessary, then returns the appdata directory. + * @details This is used for the log directory, so it cannot invoke Boost logging! + * @return The path of the appdata directory that should be used. + */ fs::path appdata() { bool found = false; @@ -136,15 +142,18 @@ namespace platf { fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; if (old_config_path != config_path && fs::exists(old_config_path)) { if (!fs::exists(config_path)) { - BOOST_LOG(info) << "Migrating config from "sv << old_config_path << " to "sv << config_path; + std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl; std::error_code ec; fs::rename(old_config_path, config_path, ec); if (ec) { + std::cerr << "Migration failed: " << ec.message() << std::endl; return old_config_path; } } else { - BOOST_LOG(warning) << "Config exists in both "sv << old_config_path << " and "sv << config_path << ", using "sv << config_path << "... it is recommended to remove "sv << old_config_path; + // We cannot use Boost logging because it hasn't been initialized yet! + std::cerr << "Config exists in both "sv << old_config_path << " and "sv << config_path << ". Using "sv << config_path << " for config" << std::endl; + std::cerr << "It is recommended to remove "sv << old_config_path << std::endl; } } } From 8c9e14e3356ee05b1f48f777e44cbfde9e74a083 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 15 Mar 2024 00:15:55 -0500 Subject: [PATCH 069/129] Only attempt a config migration once per launch --- src/platform/linux/misc.cpp | 101 +++++++++++++++++++----------------- 1 file changed, 53 insertions(+), 48 deletions(-) diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index b4e3d1aec9b..092c5607983 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -106,57 +106,62 @@ namespace platf { */ fs::path appdata() { - bool found = false; - bool migrate_config = true; - const char *dir; - const char *homedir; - const char *migrate_envvar; - fs::path config_path; - - // Get the home directory - if ((homedir = getenv("HOME")) == nullptr || strlen(homedir) == 0) { - // If HOME is empty or not set, use the current user's home directory - homedir = getpwuid(geteuid())->pw_dir; - } - - // May be set if running under a systemd service with the ConfigurationDirectory= option set. - if ((dir = getenv("CONFIGURATION_DIRECTORY")) != nullptr && strlen(dir) > 0) { - found = true; - config_path = fs::path(dir) / "sunshine"sv; - } - // Otherwise, follow the XDG base directory specification: - // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html - if (!found && (dir = getenv("XDG_CONFIG_HOME")) != nullptr && strlen(dir) > 0) { - found = true; - config_path = fs::path(dir) / "sunshine"sv; - } - // As a last resort, use the home directory - if (!found) { - migrate_config = false; - config_path = fs::path(homedir) / ".config/sunshine"sv; - } - - // migrate from the old config location if necessary - migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); - if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { - fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; - if (old_config_path != config_path && fs::exists(old_config_path)) { - if (!fs::exists(config_path)) { - std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl; - std::error_code ec; - fs::rename(old_config_path, config_path, ec); - if (ec) { - std::cerr << "Migration failed: " << ec.message() << std::endl; - return old_config_path; + static std::once_flag migration_flag; + static fs::path config_path; + + // Ensure migration is only attempted once + std::call_once(migration_flag, []() { + bool found = false; + bool migrate_config = true; + const char *dir; + const char *homedir; + const char *migrate_envvar; + + // Get the home directory + if ((homedir = getenv("HOME")) == nullptr || strlen(homedir) == 0) { + // If HOME is empty or not set, use the current user's home directory + homedir = getpwuid(geteuid())->pw_dir; + } + + // May be set if running under a systemd service with the ConfigurationDirectory= option set. + if ((dir = getenv("CONFIGURATION_DIRECTORY")) != nullptr && strlen(dir) > 0) { + found = true; + config_path = fs::path(dir) / "sunshine"sv; + } + // Otherwise, follow the XDG base directory specification: + // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html + if (!found && (dir = getenv("XDG_CONFIG_HOME")) != nullptr && strlen(dir) > 0) { + found = true; + config_path = fs::path(dir) / "sunshine"sv; + } + // As a last resort, use the home directory + if (!found) { + migrate_config = false; + config_path = fs::path(homedir) / ".config/sunshine"sv; + } + + // migrate from the old config location if necessary + migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); + if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { + fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; + if (old_config_path != config_path && fs::exists(old_config_path)) { + if (!fs::exists(config_path)) { + std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl; + std::error_code ec; + fs::rename(old_config_path, config_path, ec); + if (ec) { + std::cerr << "Migration failed: " << ec.message() << std::endl; + config_path = old_config_path; + } + } + else { + // We cannot use Boost logging because it hasn't been initialized yet! + std::cerr << "Config exists in both "sv << old_config_path << " and "sv << config_path << ". Using "sv << config_path << " for config" << std::endl; + std::cerr << "It is recommended to remove "sv << old_config_path << std::endl; } - } - else { - // We cannot use Boost logging because it hasn't been initialized yet! - std::cerr << "Config exists in both "sv << old_config_path << " and "sv << config_path << ". Using "sv << config_path << " for config" << std::endl; - std::cerr << "It is recommended to remove "sv << old_config_path << std::endl; } } - } + }); return config_path; } From 15c5e76ed4d994439322812df36e25f7b26c1814 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Fri, 15 Mar 2024 00:44:53 -0500 Subject: [PATCH 070/129] Use a copy+delete instead of a move operation for config migration This can handle migration across filesystems. --- src/platform/linux/misc.cpp | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 092c5607983..980c0804858 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -143,12 +143,30 @@ namespace platf { // migrate from the old config location if necessary migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { + std::error_code ec; fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; - if (old_config_path != config_path && fs::exists(old_config_path)) { - if (!fs::exists(config_path)) { + if (old_config_path != config_path && fs::exists(old_config_path, ec)) { + if (!fs::exists(config_path, ec)) { std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl; - std::error_code ec; - fs::rename(old_config_path, config_path, ec); + if (!ec) { + // Create the new directory tree if it doesn't already exist + fs::create_directories(config_path, ec); + } + if (!ec) { + // Copy the old directory into the new location + // NB: We use a copy instead of a move so that cross-volume migrations work + fs::copy(old_config_path, config_path, fs::copy_options::recursive | fs::copy_options::copy_symlinks, ec); + } + if (!ec) { + // If the copy was successful, delete the original directory + fs::remove_all(old_config_path, ec); + if (ec) { + std::cerr << "Failed to clean up old config directory: " << ec.message() << std::endl; + + // This is not fatal. Next time we start, we'll warn the user to delete the old one. + ec.clear(); + } + } if (ec) { std::cerr << "Migration failed: " << ec.message() << std::endl; config_path = old_config_path; From bd5c50041cc020f648a45f8130ed421f2c8fc901 Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Thu, 14 Mar 2024 18:37:27 -0500 Subject: [PATCH 071/129] Update changelog and bump version to v0.22.2 --- CHANGELOG.md | 7 +++++++ CMakeLists.txt | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1c67c68c3f..d4fbff3a4ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [0.22.2] - 2024-03-15 +**Fixed** +- (Tray/Windows) Fix broken system tray icon on some systems +- (Linux) Fix crash when XDG_CONFIG_HOME or CONFIGURATION_DIRECTORY are set +- (Linux) Fix config migration across filesystems and with non-existent parent directories + ## [0.22.1] - 2024-03-13 **Breaking** - (ArchLinux) Drop support for standalone PKGBUILD files. Use the binary Arch package or install via AUR instead. @@ -759,3 +765,4 @@ settings. In v0.17.0, games now run under your user account without elevated pri [0.21.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.21.0 [0.22.0]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.0 [0.22.1]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.1 +[0.22.2]: https://github.com/LizardByte/Sunshine/releases/tag/v0.22.2 diff --git a/CMakeLists.txt b/CMakeLists.txt index fce20cd2bb7..ebff395abbc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.18) # todo - set this conditionally # todo - set version to 0.0.0 once confident in automated versioning -project(Sunshine VERSION 0.22.1 +project(Sunshine VERSION 0.22.2 DESCRIPTION "Self-hosted game stream host for Moonlight" HOMEPAGE_URL "https://app.lizardbyte.dev/Sunshine") From 7534fa10230483ae47e94c4e0a89e85f13d19dc5 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sat, 16 Mar 2024 09:04:29 -0400 Subject: [PATCH 072/129] refactor(video): move encoder declarations to header (#2185) --- src/video.cpp | 157 ++------------------------------------------- src/video.h | 172 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 150 deletions(-) diff --git a/src/video.cpp b/src/video.cpp index f786aeb59f0..920ce1a4857 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -14,7 +14,6 @@ extern "C" { #include #include #include -#include } #include "cbs.h" @@ -51,12 +50,6 @@ namespace video { av_buffer_unref(&ref); } - using avcodec_ctx_t = util::safe_ptr; - using avcodec_frame_t = util::safe_ptr; - using avcodec_buffer_t = util::safe_ptr; - using sws_t = util::safe_ptr; - using img_event_t = std::shared_ptr>>; - namespace nv { enum class profile_h264_e : int { @@ -87,11 +80,6 @@ namespace video { }; } // namespace qsv - platf::mem_type_e - map_base_dev_type(AVHWDeviceType type); - platf::pix_fmt_e - map_pix_fmt(AVPixelFormat fmt); - util::Either dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); util::Either @@ -288,137 +276,6 @@ namespace video { ALWAYS_REPROBE = 1 << 9, // This is an encoder of last resort and we want to aggressively probe for a better one }; - struct encoder_platform_formats_t { - virtual ~encoder_platform_formats_t() = default; - platf::mem_type_e dev_type; - platf::pix_fmt_e pix_fmt_8bit, pix_fmt_10bit; - }; - - struct encoder_platform_formats_avcodec: encoder_platform_formats_t { - using init_buffer_function_t = std::function(platf::avcodec_encode_device_t *)>; - - encoder_platform_formats_avcodec( - const AVHWDeviceType &avcodec_base_dev_type, - const AVHWDeviceType &avcodec_derived_dev_type, - const AVPixelFormat &avcodec_dev_pix_fmt, - const AVPixelFormat &avcodec_pix_fmt_8bit, - const AVPixelFormat &avcodec_pix_fmt_10bit, - const init_buffer_function_t &init_avcodec_hardware_input_buffer_function): - avcodec_base_dev_type { avcodec_base_dev_type }, - avcodec_derived_dev_type { avcodec_derived_dev_type }, - avcodec_dev_pix_fmt { avcodec_dev_pix_fmt }, - avcodec_pix_fmt_8bit { avcodec_pix_fmt_8bit }, - avcodec_pix_fmt_10bit { avcodec_pix_fmt_10bit }, - init_avcodec_hardware_input_buffer { init_avcodec_hardware_input_buffer_function } { - dev_type = map_base_dev_type(avcodec_base_dev_type); - pix_fmt_8bit = map_pix_fmt(avcodec_pix_fmt_8bit); - pix_fmt_10bit = map_pix_fmt(avcodec_pix_fmt_10bit); - } - - AVHWDeviceType avcodec_base_dev_type, avcodec_derived_dev_type; - AVPixelFormat avcodec_dev_pix_fmt; - AVPixelFormat avcodec_pix_fmt_8bit, avcodec_pix_fmt_10bit; - - init_buffer_function_t init_avcodec_hardware_input_buffer; - }; - - struct encoder_platform_formats_nvenc: encoder_platform_formats_t { - encoder_platform_formats_nvenc( - const platf::mem_type_e &dev_type, - const platf::pix_fmt_e &pix_fmt_8bit, - const platf::pix_fmt_e &pix_fmt_10bit) { - encoder_platform_formats_t::dev_type = dev_type; - encoder_platform_formats_t::pix_fmt_8bit = pix_fmt_8bit; - encoder_platform_formats_t::pix_fmt_10bit = pix_fmt_10bit; - } - }; - - struct encoder_t { - std::string_view name; - enum flag_e { - PASSED, // Is supported - REF_FRAMES_RESTRICT, // Set maximum reference frames - CBR, // Some encoders don't support CBR, if not supported --> attempt constant quantatication parameter instead - DYNAMIC_RANGE, // hdr - VUI_PARAMETERS, // AMD encoder with VAAPI doesn't add VUI parameters to SPS - MAX_FLAGS - }; - - static std::string_view - from_flag(flag_e flag) { -#define _CONVERT(x) \ - case flag_e::x: \ - return #x##sv - switch (flag) { - _CONVERT(PASSED); - _CONVERT(REF_FRAMES_RESTRICT); - _CONVERT(CBR); - _CONVERT(DYNAMIC_RANGE); - _CONVERT(VUI_PARAMETERS); - _CONVERT(MAX_FLAGS); - } -#undef _CONVERT - - return "unknown"sv; - } - - struct option_t { - KITTY_DEFAULT_CONSTR_MOVE(option_t) - option_t(const option_t &) = default; - - std::string name; - std::variant *, std::function, std::string, std::string *> value; - - option_t(std::string &&name, decltype(value) &&value): - name { std::move(name) }, value { std::move(value) } {} - }; - - const std::unique_ptr platform_formats; - - struct { - std::vector common_options; - std::vector sdr_options; - std::vector hdr_options; - std::vector fallback_options; - - // QP option to set in the case that CBR/VBR is not supported - // by the encoder. If CBR/VBR is guaranteed to be supported, - // don't specify this option to avoid wasteful encoder probing. - std::optional qp; - - std::string name; - std::bitset capabilities; - - bool - operator[](flag_e flag) const { - return capabilities[(std::size_t) flag]; - } - - std::bitset::reference - operator[](flag_e flag) { - return capabilities[(std::size_t) flag]; - } - } av1, hevc, h264; - - uint32_t flags; - }; - - struct encode_session_t { - virtual ~encode_session_t() = default; - - virtual int - convert(platf::img_t &img) = 0; - - virtual void - request_idr_frame() = 0; - - virtual void - request_normal_frame() = 0; - - virtual void - invalidate_ref_frames(int64_t first_frame, int64_t last_frame) = 0; - }; - class avcodec_encode_session_t: public encode_session_t { public: avcodec_encode_session_t() = default; @@ -586,7 +443,7 @@ namespace video { auto capture_thread_sync = safe::make_shared(start_capture_sync, end_capture_sync); #ifdef _WIN32 - static encoder_t nvenc { + encoder_t nvenc { "nvenc"sv, std::make_unique( platf::mem_type_e::dxgi, @@ -630,7 +487,7 @@ namespace video { PARALLEL_ENCODING | REF_FRAMES_INVALIDATION // flags }; #elif !defined(__APPLE__) - static encoder_t nvenc { + encoder_t nvenc { "nvenc"sv, std::make_unique( #ifdef _WIN32 @@ -718,7 +575,7 @@ namespace video { #endif #ifdef _WIN32 - static encoder_t quicksync { + encoder_t quicksync { "quicksync"sv, std::make_unique( AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_QSV, @@ -799,7 +656,7 @@ namespace video { PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT }; - static encoder_t amdvce { + encoder_t amdvce { "amdvce"sv, std::make_unique( AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_NONE, @@ -871,7 +728,7 @@ namespace video { }; #endif - static encoder_t software { + encoder_t software { "software"sv, std::make_unique( AV_HWDEVICE_TYPE_NONE, AV_HWDEVICE_TYPE_NONE, @@ -936,7 +793,7 @@ namespace video { }; #ifdef __linux__ - static encoder_t vaapi { + encoder_t vaapi { "vaapi"sv, std::make_unique( AV_HWDEVICE_TYPE_VAAPI, AV_HWDEVICE_TYPE_NONE, @@ -1004,7 +861,7 @@ namespace video { #endif #ifdef __APPLE__ - static encoder_t videotoolbox { + encoder_t videotoolbox { "videotoolbox"sv, std::make_unique( AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_HWDEVICE_TYPE_NONE, diff --git a/src/video.h b/src/video.h index fec5c38b343..eb8eabc358d 100644 --- a/src/video.h +++ b/src/video.h @@ -11,11 +11,181 @@ extern "C" { #include +#include } struct AVPacket; namespace video { + platf::mem_type_e + map_base_dev_type(AVHWDeviceType type); + platf::pix_fmt_e + map_pix_fmt(AVPixelFormat fmt); + + void + free_ctx(AVCodecContext *ctx); + void + free_frame(AVFrame *frame); + void + free_buffer(AVBufferRef *ref); + + using avcodec_ctx_t = util::safe_ptr; + using avcodec_frame_t = util::safe_ptr; + using avcodec_buffer_t = util::safe_ptr; + using sws_t = util::safe_ptr; + using img_event_t = std::shared_ptr>>; + + struct encoder_platform_formats_t { + virtual ~encoder_platform_formats_t() = default; + platf::mem_type_e dev_type; + platf::pix_fmt_e pix_fmt_8bit, pix_fmt_10bit; + }; + + struct encoder_platform_formats_avcodec: encoder_platform_formats_t { + using init_buffer_function_t = std::function(platf::avcodec_encode_device_t *)>; + + encoder_platform_formats_avcodec( + const AVHWDeviceType &avcodec_base_dev_type, + const AVHWDeviceType &avcodec_derived_dev_type, + const AVPixelFormat &avcodec_dev_pix_fmt, + const AVPixelFormat &avcodec_pix_fmt_8bit, + const AVPixelFormat &avcodec_pix_fmt_10bit, + const init_buffer_function_t &init_avcodec_hardware_input_buffer_function): + avcodec_base_dev_type { avcodec_base_dev_type }, + avcodec_derived_dev_type { avcodec_derived_dev_type }, + avcodec_dev_pix_fmt { avcodec_dev_pix_fmt }, + avcodec_pix_fmt_8bit { avcodec_pix_fmt_8bit }, + avcodec_pix_fmt_10bit { avcodec_pix_fmt_10bit }, + init_avcodec_hardware_input_buffer { init_avcodec_hardware_input_buffer_function } { + dev_type = map_base_dev_type(avcodec_base_dev_type); + pix_fmt_8bit = map_pix_fmt(avcodec_pix_fmt_8bit); + pix_fmt_10bit = map_pix_fmt(avcodec_pix_fmt_10bit); + } + + AVHWDeviceType avcodec_base_dev_type, avcodec_derived_dev_type; + AVPixelFormat avcodec_dev_pix_fmt; + AVPixelFormat avcodec_pix_fmt_8bit, avcodec_pix_fmt_10bit; + + init_buffer_function_t init_avcodec_hardware_input_buffer; + }; + + struct encoder_platform_formats_nvenc: encoder_platform_formats_t { + encoder_platform_formats_nvenc( + const platf::mem_type_e &dev_type, + const platf::pix_fmt_e &pix_fmt_8bit, + const platf::pix_fmt_e &pix_fmt_10bit) { + encoder_platform_formats_t::dev_type = dev_type; + encoder_platform_formats_t::pix_fmt_8bit = pix_fmt_8bit; + encoder_platform_formats_t::pix_fmt_10bit = pix_fmt_10bit; + } + }; + + struct encoder_t { + std::string_view name; + enum flag_e { + PASSED, // Is supported + REF_FRAMES_RESTRICT, // Set maximum reference frames + CBR, // Some encoders don't support CBR, if not supported --> attempt constant quantatication parameter instead + DYNAMIC_RANGE, // hdr + VUI_PARAMETERS, // AMD encoder with VAAPI doesn't add VUI parameters to SPS + MAX_FLAGS + }; + + static std::string_view + from_flag(flag_e flag) { +#define _CONVERT(x) \ + case flag_e::x: \ + std::string_view(#x) + switch (flag) { + _CONVERT(PASSED); + _CONVERT(REF_FRAMES_RESTRICT); + _CONVERT(CBR); + _CONVERT(DYNAMIC_RANGE); + _CONVERT(VUI_PARAMETERS); + _CONVERT(MAX_FLAGS); + } +#undef _CONVERT + + return { "unknown" }; + } + + struct option_t { + KITTY_DEFAULT_CONSTR_MOVE(option_t) + option_t(const option_t &) = default; + + std::string name; + std::variant *, std::function, std::string, std::string *> value; + + option_t(std::string &&name, decltype(value) &&value): + name { std::move(name) }, value { std::move(value) } {} + }; + + const std::unique_ptr platform_formats; + + struct codec_t { + std::vector common_options; + std::vector sdr_options; + std::vector hdr_options; + std::vector fallback_options; + + // QP option to set in the case that CBR/VBR is not supported + // by the encoder. If CBR/VBR is guaranteed to be supported, + // don't specify this option to avoid wasteful encoder probing. + std::optional qp; + + std::string name; + std::bitset capabilities; + + bool + operator[](flag_e flag) const { + return capabilities[(std::size_t) flag]; + } + + std::bitset::reference + operator[](flag_e flag) { + return capabilities[(std::size_t) flag]; + } + } av1, hevc, h264; + + uint32_t flags; + }; + + struct encode_session_t { + virtual ~encode_session_t() = default; + + virtual int + convert(platf::img_t &img) = 0; + + virtual void + request_idr_frame() = 0; + + virtual void + request_normal_frame() = 0; + + virtual void + invalidate_ref_frames(int64_t first_frame, int64_t last_frame) = 0; + }; + + // encoders + extern encoder_t software; + +#if !defined(__APPLE__) + extern encoder_t nvenc; // available for windows and linux +#endif + +#ifdef _WIN32 + extern encoder_t amdvce; + extern encoder_t quicksync; +#endif + +#ifdef __linux__ + extern encoder_t vaapi; +#endif + +#ifdef __APPLE__ + extern encoder_t videotoolbox; +#endif + struct packet_raw_t { virtual ~packet_raw_t() = default; @@ -154,6 +324,8 @@ namespace video { config_t config, void *channel_data); + bool + validate_encoder(encoder_t &encoder, bool expect_failure); int probe_encoders(); } // namespace video From 8316f44e10f3f6ef27fc27b3ef6e69f359b1b667 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 17 Mar 2024 00:07:18 -0400 Subject: [PATCH 073/129] ci(linux): refactor linux build (#2275) --- .github/workflows/CI.yml | 108 +++++++++++++++------------------------ 1 file changed, 40 insertions(+), 68 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 09a0aaeae66..a35f2affbcc 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -165,7 +165,7 @@ jobs: remove-android: 'true' remove-haskell: 'true' remove-codeql: 'true' - remove-docker-images: 'false' + remove-docker-images: 'true' - name: Checkout uses: actions/checkout@v4 @@ -291,61 +291,48 @@ jobs: remove-android: 'true' remove-haskell: 'true' remove-codeql: 'true' - remove-docker-images: 'false' + remove-docker-images: 'true' - name: Checkout uses: actions/checkout@v4 with: submodules: recursive + - name: Install wget + run: | + sudo apt-get update -y + sudo apt-get install -y \ + wget + + - name: Install CUDA + env: + CUDA_VERSION: 11.8.0 + CUDA_BUILD: 520.61.05 + timeout-minutes: 4 + run: | + url_base="https://developer.download.nvidia.com/compute/cuda/${CUDA_VERSION}/local_installers" + url="${url_base}/cuda_${CUDA_VERSION}_${CUDA_BUILD}_linux.run" + sudo wget -q -O /root/cuda.run ${url} + sudo chmod a+x /root/cuda.run + sudo /root/cuda.run --silent --toolkit --toolkitpath=/usr/local/cuda --no-opengl-libs --no-man-page --no-drm + sudo rm /root/cuda.run + - name: Setup Dependencies Linux run: | + # allow newer gcc sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - if [[ ${{ matrix.dist }} == "18.04" ]]; then - # Ubuntu 18.04 packages - sudo add-apt-repository ppa:savoury1/boost-defaults-1.71 -y - - sudo apt-get update -y - sudo apt-get install -y \ - libboost-filesystem1.71-dev \ - libboost-locale1.71-dev \ - libboost-log1.71-dev \ - libboost-regex1.71-dev \ - libboost-program-options1.71-dev - - # Install cmake - wget https://cmake.org/files/v3.22/cmake-3.22.2-linux-x86_64.sh - chmod +x cmake-3.22.2-linux-x86_64.sh - mkdir /opt/cmake - ./cmake-3.22.2-linux-x86_64.sh --prefix=/opt/cmake --skip-license - ln --force --symbolic /opt/cmake/bin/cmake /usr/local/bin/cmake - cmake --version - - # install newer tar from focal... appimagelint fails on 18.04 without this - echo "original tar version" - tar --version - wget -O tar.deb http://security.ubuntu.com/ubuntu/pool/main/t/tar/tar_1.30+dfsg-7ubuntu0.20.04.3_amd64.deb - sudo apt-get -y install -f ./tar.deb - echo "new tar version" - tar --version - else - # Ubuntu 20.04+ packages - sudo apt-get update -y - sudo apt-get install -y \ - cmake \ - libboost-filesystem-dev \ - libboost-locale-dev \ - libboost-log-dev \ - libboost-program-options-dev - fi - sudo apt-get install -y \ build-essential \ + cmake \ gcc-10 \ g++-10 \ libayatana-appindicator3-dev \ libavdevice-dev \ + libboost-filesystem-dev \ + libboost-locale-dev \ + libboost-log-dev \ + libboost-program-options-dev \ libcap-dev \ libcurl4-openssl-dev \ libdrm-dev \ @@ -366,8 +353,7 @@ jobs: libxcb1-dev \ libxfixes-dev \ libxrandr-dev \ - libxtst-dev \ - wget + libxtst-dev # clean apt cache sudo apt-get clean @@ -382,20 +368,15 @@ jobs: --slave /usr/bin/gcc-ar gcc-ar /usr/bin/gcc-ar-10 \ --slave /usr/bin/gcc-ranlib gcc-ranlib /usr/bin/gcc-ranlib-10 - # Install CUDA - sudo wget \ - https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.run \ - --progress=bar:force:noscroll -q --show-progress -O /root/cuda.run - sudo chmod a+x /root/cuda.run - sudo /root/cuda.run --silent --toolkit --toolkitpath=/usr --no-opengl-libs --no-man-page --no-drm - sudo rm /root/cuda.run - - name: Build Linux env: BRANCH: ${{ github.head_ref || github.ref_name }} BUILD_VERSION: ${{ needs.check_changelog.outputs.next_version_bare }} COMMIT: ${{ github.event.pull_request.head.sha || github.sha }} + timeout-minutes: 5 run: | + echo "nproc: $(nproc)" + mkdir -p build mkdir -p artifacts @@ -403,6 +384,7 @@ jobs: cmake \ -DBUILD_WERROR=ON \ -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_COMPILER:PATH=/usr/local/cuda/bin/nvcc \ -DCMAKE_INSTALL_PREFIX=/usr \ -DSUNSHINE_ASSETS_DIR=share/sunshine \ -DSUNSHINE_EXECUTABLE_PATH=/usr/bin/sunshine \ @@ -412,20 +394,7 @@ jobs: -DSUNSHINE_ENABLE_CUDA=ON \ ${{ matrix.EXTRA_ARGS }} \ .. - make -j ${nproc} - - - name: Package Linux - CPACK - # todo - this is no longer used - if: ${{ matrix.type == 'cpack' }} - working-directory: build - run: | - cpack -G DEB - mv ./cpack_artifacts/Sunshine.deb ../artifacts/sunshine-${{ matrix.dist }}.deb - - if [[ ${{ matrix.dist }} == "20.04" ]]; then - cpack -G RPM - mv ./cpack_artifacts/Sunshine.rpm ../artifacts/sunshine.rpm - fi + make -j $(expr $(nproc) - 1) # use all but one core - name: Set AppImage Version if: | @@ -452,12 +421,12 @@ jobs: # AppImage # https://docs.appimage.org/packaging-guide/index.html - wget https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage + wget -q https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage chmod +x linuxdeploy-x86_64.AppImage # https://github.com/linuxdeploy/linuxdeploy-plugin-gtk sudo apt-get install libgtk-3-dev librsvg2-dev -y - wget https://raw.githubusercontent.com/linuxdeploy/linuxdeploy-plugin-gtk/master/linuxdeploy-plugin-gtk.sh + wget -q https://raw.githubusercontent.com/linuxdeploy/linuxdeploy-plugin-gtk/master/linuxdeploy-plugin-gtk.sh chmod +x linuxdeploy-plugin-gtk.sh export DEPLOY_GTK_VERSION=3 @@ -475,14 +444,17 @@ jobs: # permissions chmod +x ../artifacts/sunshine.AppImage + - name: Delete cuda + # free up space on the runner + run: | + sudo rm -rf /usr/local/cuda + - name: Verify AppImage if: ${{ matrix.type == 'AppImage' }} run: | wget https://github.com/TheAssassin/appimagelint/releases/download/continuous/appimagelint-x86_64.AppImage chmod +x appimagelint-x86_64.AppImage - # rm -rf ~/.cache/appimagelint/ - ./appimagelint-x86_64.AppImage ./artifacts/sunshine.AppImage - name: Upload Artifacts From 87774333f38a354a03aa9dceeba74593beec2e2f Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Fri, 22 Mar 2024 19:54:12 -0400 Subject: [PATCH 074/129] feat(i18n): add ui localization (#2279) Co-authored-by: TheElixZammuto <6505622+TheElixZammuto@users.noreply.github.com> --- crowdin.yml | 12 +- docs/source/about/advanced_usage.rst | 34 + docs/source/contributing/localization.rst | 84 +- package.json | 3 +- src/config.cpp | 14 + src/config.h | 1 + src/confighttp.cpp | 19 + src_assets/common/assets/web/Navbar.vue | 12 +- src_assets/common/assets/web/ResourceCard.vue | 21 +- src_assets/common/assets/web/apps.html | 178 ++-- src_assets/common/assets/web/config.html | 818 +++++++----------- src_assets/common/assets/web/index.html | 35 +- src_assets/common/assets/web/locale.js | 27 + src_assets/common/assets/web/password.html | 34 +- src_assets/common/assets/web/pin.html | 23 +- .../assets/web/public/assets/css/sunshine.css | 4 + .../assets/web/public/assets/locale/de.json | 376 ++++++++ .../web/public/assets/locale/en-GB.json | 376 ++++++++ .../web/public/assets/locale/en-US.json | 376 ++++++++ .../assets/web/public/assets/locale/en.json | 376 ++++++++ .../assets/web/public/assets/locale/es.json | 376 ++++++++ .../assets/web/public/assets/locale/fr.json | 376 ++++++++ .../assets/web/public/assets/locale/it.json | 376 ++++++++ .../assets/web/public/assets/locale/ru.json | 376 ++++++++ .../assets/web/public/assets/locale/sv.json | 376 ++++++++ .../assets/web/public/assets/locale/zh.json | 376 ++++++++ .../common/assets/web/template_header.html | 1 + .../common/assets/web/troubleshooting.html | 52 +- src_assets/common/assets/web/welcome.html | 33 +- 29 files changed, 4446 insertions(+), 719 deletions(-) create mode 100644 src_assets/common/assets/web/locale.js create mode 100644 src_assets/common/assets/web/public/assets/css/sunshine.css create mode 100644 src_assets/common/assets/web/public/assets/locale/de.json create mode 100644 src_assets/common/assets/web/public/assets/locale/en-GB.json create mode 100644 src_assets/common/assets/web/public/assets/locale/en-US.json create mode 100644 src_assets/common/assets/web/public/assets/locale/en.json create mode 100644 src_assets/common/assets/web/public/assets/locale/es.json create mode 100644 src_assets/common/assets/web/public/assets/locale/fr.json create mode 100644 src_assets/common/assets/web/public/assets/locale/it.json create mode 100644 src_assets/common/assets/web/public/assets/locale/ru.json create mode 100644 src_assets/common/assets/web/public/assets/locale/sv.json create mode 100644 src_assets/common/assets/web/public/assets/locale/zh.json diff --git a/crowdin.yml b/crowdin.yml index 0be504ba7d8..3dd19366ef0 100644 --- a/crowdin.yml +++ b/crowdin.yml @@ -1,7 +1,7 @@ --- "base_path": "." "base_url": "https://api.crowdin.com" # optional (for Crowdin Enterprise only) -"preserve_hierarchy": false # flatten tree on crowdin +"preserve_hierarchy": true # false will flatten tree on crowdin, but doesn't work with dest option "pull_request_labels": [ "crowdin", "l10n" @@ -10,6 +10,7 @@ "files": [ { "source": "/locale/*.po", + "dest": "/%original_file_name%", "translation": "/locale/%two_letters_code%/LC_MESSAGES/%original_file_name%", "languages_mapping": { "two_letters_code": { @@ -17,6 +18,13 @@ "en-GB": "en_GB", "en-US": "en_US" } - } + }, + "update_option": "update_as_unapproved" + }, + { + "source": "/src_assets/common/assets/web/public/assets/locale/en.json", + "dest": "/sunshine.json", + "translation": "/src_assets/common/assets/web/public/assets/locale/%two_letters_code%.%file_extension%", + "update_option": "update_as_unapproved" } ] diff --git a/docs/source/about/advanced_usage.rst b/docs/source/about/advanced_usage.rst index f29e6d05f8d..d23b96cc582 100644 --- a/docs/source/about/advanced_usage.rst +++ b/docs/source/about/advanced_usage.rst @@ -47,6 +47,40 @@ editing the `conf` file in a text editor. Use the examples as reference. `General `__ ----------------------------------------------------- +`locale `__ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Description** + The locale used for Sunshine's user interface. + +**Choices** + +.. table:: + :widths: auto + + ======= =========== + Value Description + ======= =========== + de German + en English + en-GB English (UK) + en-US English (United States) + es Spanish + fr French + it Italian + ru Russian + sv Swedish + zh Chinese (Simplified) + ======= =========== + +**Default** + ``en`` + +**Example** + .. code-block:: text + + locale = en + `sunshine_name `__ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/source/contributing/localization.rst b/docs/source/contributing/localization.rst index 2ca912805e1..0148b8170e4 100644 --- a/docs/source/contributing/localization.rst +++ b/docs/source/contributing/localization.rst @@ -30,42 +30,74 @@ localization there. Extraction ---------- -There should be minimal cases where strings need to be extracted from source code; however it may be necessary in some -situations. For example if a system tray icon is added it should be localized as it is user interfacing. -- Wrap the string to be extracted in a function as shown. - .. code-block:: cpp +.. tab:: UI - #include - #include + Sunshine uses `Vue I18n `__ for localizing the UI. + The following is a simple example of how to use it. - std::string msg = boost::locale::translate("Hello world!"); + - Add the string to `src_assets/common/assets/web/public/assets/locale/en.json`, in English. + .. code-block:: json -.. tip:: More examples can be found in the documentation for - `boost locale `__. + { + "index": { + "welcome": "Hello, Sunshine!" + } + } -.. warning:: This is for information only. Contributors should never include manually updated template files, or - manually compiled language files in Pull Requests. + .. note:: The json keys should be sorted alphabetically. You can use `jsonabc `__ + to sort the keys. -Strings are automatically extracted from the code to the `locale/sunshine.po` template file. The generated file is -used by CrowdIn to generate language specific template files. The file is generated using the -`.github/workflows/localize.yml` workflow and is run on any push event into the `nightly` branch. Jobs are only run if -any of the following paths are modified. + - Use the string in a Vue component. + .. code-block:: html -.. code-block:: yaml + - - 'src/**' + .. tip:: More formatting examples can be found in the + `Vue I18n guide `__. -When testing locally it may be desirable to manually extract, initialize, update, and compile strings. Python is -required for this, along with the python dependencies in the `./scripts/requirements.txt` file. Additionally, -`xgettext `__ must be installed. +.. tab:: C++ -**Extract, initialize, and update** - .. code-block:: bash + There should be minimal cases where strings need to be extracted from C++ source code; however it may be necessary in + some situations. For example the system tray icon could be localized as it is user interfacing. - python ./scripts/_locale.py --extract --init --update + - Wrap the string to be extracted in a function as shown. + .. code-block:: cpp -**Compile** - .. code-block:: bash + #include + #include - python ./scripts/_locale.py --compile + std::string msg = boost::locale::translate("Hello world!"); + + .. tip:: More examples can be found in the documentation for + `boost locale `__. + + .. warning:: This is for information only. Contributors should never include manually updated template files, or + manually compiled language files in Pull Requests. + + Strings are automatically extracted from the code to the `locale/sunshine.po` template file. The generated file is + used by CrowdIn to generate language specific template files. The file is generated using the + `.github/workflows/localize.yml` workflow and is run on any push event into the `nightly` branch. Jobs are only run if + any of the following paths are modified. + + .. code-block:: yaml + + - 'src/**' + + When testing locally it may be desirable to manually extract, initialize, update, and compile strings. Python is + required for this, along with the python dependencies in the `./scripts/requirements.txt` file. Additionally, + `xgettext `__ must be installed. + + **Extract, initialize, and update** + .. code-block:: bash + + python ./scripts/_locale.py --extract --init --update + + **Compile** + .. code-block:: bash + + python ./scripts/_locale.py --compile diff --git a/package.json b/package.json index b685e0966a4..706c23384ce 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "bootstrap": "5.3.3", "vite": "4.5.2", "vite-plugin-ejs": "1.6.4", - "vue": "3.4.5" + "vue": "3.4.5", + "vue-i18n": "9.10.2" } } diff --git a/src/config.cpp b/src/config.cpp index 21562f83487..b2660f7d2c1 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -441,6 +441,7 @@ namespace config { }; sunshine_t sunshine { + "en", // locale 2, // min_log_level 0, // flags {}, // User file @@ -1101,6 +1102,19 @@ namespace config { config::sunshine.flags[config::flag::UPNP].flip(); } + string_restricted_f(vars, "locale", config::sunshine.locale, { + "de"sv, // German + "en"sv, // English + "en-GB"sv, // English (UK) + "en-US"sv, // English (US) + "es"sv, // Spanish + "fr"sv, // French + "it"sv, // Italian + "ru"sv, // Russian + "sv"sv, // Swedish + "zh"sv, // Chinese + }); + std::string log_level_string; string_f(vars, "min_log_level", log_level_string); diff --git a/src/config.h b/src/config.h index 6c48f466b8e..f30e7e6a05a 100644 --- a/src/config.h +++ b/src/config.h @@ -160,6 +160,7 @@ namespace config { bool elevated; }; struct sunshine_t { + std::string locale; int min_log_level; std::bitset flags; std::string credentials_file; diff --git a/src/confighttp.cpp b/src/confighttp.cpp index 0657902dd16..de25bf0e7cf 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -550,6 +550,24 @@ namespace confighttp { } } + void + getLocale(resp_https_t response, req_https_t request) { + // we need to return the locale whether authenticated or not + + print_req(request); + + pt::ptree outputTree; + auto g = util::fail_guard([&]() { + std::ostringstream data; + + pt::write_json(data, outputTree); + response->write(data.str()); + }); + + outputTree.put("status", "true"); + outputTree.put("locale", config::sunshine.locale); + } + void saveConfig(resp_https_t response, req_https_t request) { if (!authenticate(response, request)) return; @@ -743,6 +761,7 @@ namespace confighttp { server.resource["^/api/apps$"]["POST"] = saveApp; server.resource["^/api/config$"]["GET"] = getConfig; server.resource["^/api/config$"]["POST"] = saveConfig; + server.resource["^/api/configLocale$"]["GET"] = getLocale; server.resource["^/api/restart$"]["POST"] = restart; server.resource["^/api/password$"]["POST"] = savePassword; server.resource["^/api/apps/([0-9]+)$"]["DELETE"] = deleteApp; diff --git a/src_assets/common/assets/web/Navbar.vue b/src_assets/common/assets/web/Navbar.vue index 948fb4d7244..9e4e1be64f5 100644 --- a/src_assets/common/assets/web/Navbar.vue +++ b/src_assets/common/assets/web/Navbar.vue @@ -11,22 +11,22 @@ diff --git a/src_assets/common/assets/web/ResourceCard.vue b/src_assets/common/assets/web/ResourceCard.vue index e2481ca475a..aee837689cf 100644 --- a/src_assets/common/assets/web/ResourceCard.vue +++ b/src_assets/common/assets/web/ResourceCard.vue @@ -1,35 +1,32 @@