From 29e4d6aa70bc7775d586d153f09d5cf84867697c Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:09:57 -0400 Subject: [PATCH] refactor(logging): centralize messages and extensible outputs Replace Boost logging calls with Sunshine text, format, and lazy builder functions to address cpp:S6996 at the shared source. Keep Boost private to the backend and provide independently owned synchronous or asynchronous sinks for future outputs. Add API, filtering, delivery, ownership, failure, periodic formatting, and external callback tests. Validate with the native build, 53 focused logging tests, Clang syntax checks, Linux syntax checks, and strict Doxygen. The broader native run has only the existing licensed HID broker failure. --- src/audio.cpp | 16 +- src/cbs.cpp | 20 +- src/config.cpp | 33 +- src/confighttp.cpp | 79 +- src/display_device.cpp | 126 +-- src/entry_handler.cpp | 18 +- src/file_handler.cpp | 2 +- src/httpcommon.cpp | 42 +- src/input.cpp | 257 +++--- src/logging.cpp | 310 ++++--- src/logging.h | 471 ++++++++--- src/main.cpp | 48 +- src/network.cpp | 2 +- src/nvenc/nvenc_base.cpp | 83 +- src/nvenc/nvenc_base.h | 2 +- src/nvenc/nvenc_d3d11.cpp | 4 +- src/nvenc/nvenc_d3d11_native.cpp | 6 +- src/nvenc/nvenc_d3d11_on_cuda.cpp | 36 +- src/nvenc/nvenc_dynamic_factory.cpp | 8 +- src/nvhttp.cpp | 45 +- src/platform/common.h | 4 +- src/platform/linux/audio.cpp | 47 +- src/platform/linux/cuda.cpp | 82 +- src/platform/linux/graphics.cpp | 126 +-- src/platform/linux/graphics.h | 2 +- src/platform/linux/kmsgrab.cpp | 252 +++--- src/platform/linux/kwingrab.cpp | 84 +- src/platform/linux/misc.cpp | 170 ++-- src/platform/linux/nvfbc_api.h | 4 +- src/platform/linux/pipewire.cpp | 126 +-- src/platform/linux/portalgrab.cpp | 94 +-- src/platform/linux/publish.cpp | 26 +- src/platform/linux/vaapi.cpp | 78 +- src/platform/linux/vulkan_encode.cpp | 47 +- src/platform/linux/wayland.cpp | 58 +- src/platform/linux/wlgrab.cpp | 42 +- src/platform/linux/x11grab.cpp | 37 +- src/platform/macos/av_audio.mm | 193 +++-- src/platform/macos/coreaudio_helpers.h | 2 +- src/platform/macos/display.mm | 31 +- src/platform/macos/microphone.mm | 26 +- src/platform/macos/misc.mm | 69 +- src/platform/macos/publish.cpp | 10 +- src/platform/virtualhid_input.cpp | 46 +- src/platform/windows/audio.cpp | 103 +-- src/platform/windows/display_base.cpp | 172 ++-- src/platform/windows/display_ram.cpp | 20 +- src/platform/windows/display_vram.cpp | 178 ++-- src/platform/windows/display_wgc.cpp | 34 +- src/platform/windows/input.cpp | 83 +- src/platform/windows/misc.cpp | 141 ++-- .../windows/nvprefs/nvprefs_common.cpp | 13 +- src/platform/windows/publish.cpp | 12 +- src/platform/windows/utf_utils.cpp | 8 +- src/process.cpp | 85 +- src/rtsp.cpp | 145 ++-- src/stream.cpp | 244 +++--- src/system_tray.cpp | 58 +- src/upnp.cpp | 61 +- src/video.cpp | 212 ++--- src/video.h | 2 +- src/video_colorspace.cpp | 6 +- tests/integration/test_external_commands.cpp | 8 +- tests/tests_common.h | 8 +- tests/tests_events.h | 87 +- tests/unit/test_logging.cpp | 38 +- tests/unit/test_logging_api.cpp | 772 ++++++++++++++++++ tests/unit/test_mouse.cpp | 62 +- tests/unit/test_process.cpp | 6 +- 69 files changed, 3720 insertions(+), 2102 deletions(-) create mode 100644 tests/unit/test_logging_api.cpp diff --git a/src/audio.cpp b/src/audio.cpp index b41595547..776e64c67 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -183,9 +183,7 @@ namespace audio { opus_multistream_encoder_ctl(opus.get(), OPUS_SET_BITRATE(stream.bitrate)); opus_multistream_encoder_ctl(opus.get(), OPUS_SET_VBR(0)); - BOOST_LOG(info) << "Opus initialized: "sv << stream.sampleRate / 1000 << " kHz, "sv - << stream.channelCount << " channels, "sv - << stream.bitrate / 1000 << " kbps (total), LOWDELAY"sv; + logging::info("Opus initialized: {} kHz, {} channels, {} kbps (total), LOWDELAY", stream.sampleRate / 1000, stream.channelCount, stream.bitrate / 1000); auto frame_size = config.packetDuration * stream.sampleRate / 1000; while (auto sample = samples->pop()) { @@ -193,7 +191,9 @@ namespace audio { int bytes = opus_multistream_encode_float(opus.get(), sample->data(), frame_size, std::begin(packet), (opus_int32) packet.size()); if (bytes < 0) { - BOOST_LOG(error) << "Couldn't encode audio: "sv << opus_strerror(bytes); + logging::error([&](std::ostream &out) { + out << "Couldn't encode audio: "sv << opus_strerror(bytes); + }); packets->stop(); return; @@ -226,7 +226,7 @@ namespace audio { } auto init_failure_fg = util::fail_guard([&shutdown_event]() { - BOOST_LOG(error) << "Unable to initialize audio capture. The stream will not have audio."sv; + logging::error("Unable to initialize audio capture. The stream will not have audio."sv); // Wait for shutdown to be signalled if we fail init. // This allows streaming to continue without audio. @@ -311,12 +311,12 @@ namespace audio { case platf::capture_e::timeout: continue; case platf::capture_e::reinit: - BOOST_LOG(info) << "Reinitializing audio capture"sv; + logging::info("Reinitializing audio capture"sv); mic.reset(); do { mic = control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size, continuous_audio, host_audio); if (!mic) { - BOOST_LOG(warning) << "Couldn't re-initialize audio input"sv; + logging::warning("Couldn't re-initialize audio input"sv); } } while (!mic && !shutdown_event->view(5s)); continue; @@ -376,7 +376,7 @@ namespace audio { int start_audio_control(audio_ctx_t &ctx, const config::settings_t &settings, const std::function()> &factory) { ctx.fallback_sink = settings.audio.sink; auto fg = util::fail_guard([]() { - BOOST_LOG(warning) << "There will be no audio"sv; + logging::warning("There will be no audio"sv); }); ctx.sink_flag = std::make_unique(false); diff --git a/src/cbs.cpp b/src/cbs.cpp index d933d870a..4204e3ea9 100644 --- a/src/cbs.cpp +++ b/src/cbs.cpp @@ -91,7 +91,9 @@ namespace cbs { auto err = ff_cbs_insert_unit_content(&frag, -1, nal, uh, nullptr); if (err < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Could not insert NAL unit SPS: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return {}; } @@ -99,7 +101,9 @@ namespace cbs { err = ff_cbs_write_fragment_data(cbs_ctx.get(), &frag); if (err < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Could not write fragment data: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Could not write fragment data: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return {}; } @@ -140,7 +144,9 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return {}; } @@ -199,7 +205,9 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return {}; } @@ -278,7 +286,9 @@ namespace cbs { int err = ff_cbs_read_packet(ctx.get(), &frag, packet); if (err < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Couldn't read packet: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return false; } diff --git a/src/config.cpp b/src/config.cpp index ce9fcef92..bfabb5f96 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -86,7 +87,7 @@ namespace config { if (preset == "full_res") { return full_resolution; } - BOOST_LOG(warning) << "config: unknown nvenc_twopass value: " << preset; + logging::warning("config: unknown nvenc_twopass value: {}", preset); return quarter_resolution; } @@ -107,7 +108,7 @@ namespace config { if (preset == "enabled") { return force_enabled; } - BOOST_LOG(warning) << "config: unknown nvenc_split_encode value: " << preset; + logging::warning("config: unknown nvenc_split_encode value: {}", preset); return driver_decides; } @@ -1001,7 +1002,9 @@ namespace config { // 1. We didn't reach the end, or // 2. We reached the end but the last character was the matching closing bracket if (endl == end && end == begin_val + 1) { - BOOST_LOG(warning) << "config: Missing ']' in config option: " << to_string(begin, end_name); + logging::warning([&](std::ostream &out) { + out << "config: Missing ']' in config option: " << to_string(begin, end_name); + }); return std::make_pair(endl, std::nullopt); } } @@ -1051,11 +1054,11 @@ namespace config { } file_content += std::format("{} = {}\n", name, value); if (file_handler::write_file(settings_.sunshine.config_file.c_str(), file_content) != 0) { - BOOST_LOG(warning) << "Failed to persist automatically selected config option '"sv << name << "'"sv; + logging::warning("Failed to persist automatically selected config option '{}'", name); return false; } - BOOST_LOG(info) << "Automatically selected config option '"sv << name << "' = "sv << value; + logging::info("Automatically selected config option '{}' = {}", name, value); return true; } @@ -1516,7 +1519,7 @@ namespace config { // The list needs to be a multiple of 2 if (list.size() % 2) { - BOOST_LOG(warning) << "config: expected "sv << name << " to have a multiple of two elements --> not "sv << list.size(); + logging::warning("config: expected {} to have a multiple of two elements --> not {}", name, list.size()); return; } @@ -1551,7 +1554,7 @@ namespace config { settings_.sunshine.flags[config::flag::UPNP].flip(); break; default: - BOOST_LOG(warning) << "config: Unrecognized flag: ["sv << *line << ']' << std::endl; + logging::warning("config: Unrecognized flag: [{}]\n", *line); ret = -1; } @@ -1586,7 +1589,7 @@ namespace config { for (auto &[name, val] : vars) { bool is_redacted = std::ranges::find(config::redacted_config, name) != config::redacted_config.end(); - BOOST_LOG(info) << "config: '"sv << name << "' = "sv << (is_redacted ? "[redacted]" : val); + logging::info("config: '{}' = {}", name, (is_redacted ? "[redacted]" : val)); if (save) { settings_.modified_config_settings[name] = val; @@ -1770,11 +1773,11 @@ namespace config { settings_.sunshine.csrf_allowed_origins.push_back(origin); } else { csrf_invalid_config = true; - BOOST_LOG(warning) << "Invalid 'csrf_allowed_origins' entry rejected: "sv << origin; + logging::warning("Invalid 'csrf_allowed_origins' entry rejected: {}", origin); } } if (csrf_invalid_config) { - BOOST_LOG(warning) << "Please refer to: https://docs.lizardbyte.dev/projects/sunshine/latest/md_docs_2configuration.html#csrf_allowed_origins"sv; + logging::warning("Please refer to: https://docs.lizardbyte.dev/projects/sunshine/latest/md_docs_2configuration.html#csrf_allowed_origins"sv); } int to = -1; @@ -1842,7 +1845,7 @@ namespace config { string_restricted_f(vars, "gamepad"s, settings_.input.gamepad, get_supported_gamepad_options()); #ifdef _WIN32 if (settings_.input.gamepad_driver == GAMEPAD_DRIVER_VIGEMBUS && settings_.input.gamepad != "auto"sv && settings_.input.gamepad != "x360"sv && settings_.input.gamepad != "ds4"sv) { - BOOST_LOG(warning) << "Gamepad type '"sv << settings_.input.gamepad << "' is not supported by ViGEmBus; using automatic selection"sv; + logging::warning("Gamepad type '{}' is not supported by ViGEmBus; using automatic selection", settings_.input.gamepad); settings_.input.gamepad = "auto"; } #endif @@ -2045,9 +2048,9 @@ namespace config { apply_config(std::move(vars)); config_loaded = true; } catch (const std::filesystem::filesystem_error &err) { - BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what(); + logging::fatal("Failed to apply config: {}", err.what()); } catch (const boost::filesystem::filesystem_error &err) { - BOOST_LOG(fatal) << "Failed to apply config: "sv << err.what(); + logging::fatal("Failed to apply config: {}", err.what()); } #ifdef _WIN32 @@ -2056,7 +2059,7 @@ namespace config { // so that service instance will do the work instead. if (!config_loaded && !shortcut_launch) { - BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; + logging::fatal("To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv); std::this_thread::sleep_for(10s); #else if (!config_loaded) { @@ -2091,7 +2094,7 @@ namespace config { shell_exec_info.nShow = SW_NORMAL; if (!ShellExecuteExW(&shell_exec_info)) { auto winerr = GetLastError(); - BOOST_LOG(error) << "Failed executing shell command: " << winerr << std::endl; + logging::error("Failed executing shell command: {}\n", winerr); return 1; } diff --git a/src/confighttp.cpp b/src/confighttp.cpp index 31b23fc35..df0d4c8a1 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -535,20 +536,20 @@ namespace confighttp { * @param request The HTTP request object. */ void print_req(const req_https_t &request) { - BOOST_LOG(debug) << "METHOD :: "sv << request->method; - BOOST_LOG(debug) << "DESTINATION :: "sv << request->path; + logging::debug("METHOD :: {}", request->method); + logging::debug("DESTINATION :: {}", request->path); for (auto &[name, val] : request->header) { - BOOST_LOG(debug) << name << " -- " << (name == "Authorization" ? "CREDENTIALS REDACTED" : val); + logging::debug("{} -- {}", name, (name == "Authorization" ? "CREDENTIALS REDACTED" : val)); } - BOOST_LOG(debug) << " [--] "sv; + logging::debug(" [--] "sv); for (auto &[name, val] : request->parse_query_string()) { - BOOST_LOG(debug) << name << " -- " << val; + logging::debug("{} -- {}", name, val); } - BOOST_LOG(debug) << " [--] "sv; + logging::debug(" [--] "sv); } /** @@ -571,7 +572,7 @@ namespace confighttp { */ void send_unauthorized(const resp_https_t &response, const req_https_t &request) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv; + logging::info("Web UI: [{}] -- not authorized", address); constexpr auto code = SimpleWeb::StatusCode::client_error_unauthorized; @@ -598,7 +599,7 @@ namespace confighttp { */ void send_redirect(const resp_https_t &response, const req_https_t &request, const char *path) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv; + logging::info("Web UI: [{}] -- not authorized", address); const SimpleWeb::CaseInsensitiveMultimap headers { {"Location", path}, {"X-Frame-Options", "DENY"}, @@ -618,7 +619,7 @@ namespace confighttp { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); if (const auto ip_type = net::from_address(address); ip_type > http_state.origin_web_ui_allowed()) { - BOOST_LOG(info) << "Web UI: ["sv << address << "] -- denied"sv; + logging::info("Web UI: [{}] -- denied", address); response->write(SimpleWeb::StatusCode::client_error_forbidden); return false; } @@ -790,7 +791,7 @@ namespace confighttp { if (token_it == csrf_tokens.end()) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: no token found for client"sv; + logging::error("Web UI: [{}] -- CSRF token validation failed: no token found for client", address); bad_request(response, request, "Invalid CSRF token"); return false; } @@ -798,14 +799,14 @@ namespace confighttp { if (const auto now = std::chrono::steady_clock::now(); token_it->second.expiration < now) { csrf_tokens.erase(token_it); auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token expired"sv; + logging::error("Web UI: [{}] -- CSRF token validation failed: token expired", address); bad_request(response, request, "CSRF token expired"); return false; } if (token_it->second.token != provided_token) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token mismatch"sv; + logging::error("Web UI: [{}] -- CSRF token validation failed: token mismatch", address); bad_request(response, request, "Invalid CSRF token"); return false; } @@ -862,8 +863,8 @@ namespace confighttp { const auto query_it = query_params.find("csrf_token"); if (query_it == query_params.end()) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF protection blocked request from origin: "sv << blocked_origin; - BOOST_LOG(error) << "Web UI: To allow this origin, add it to the 'csrf_allowed_origins' option in your Sunshine configuration"sv; + logging::error("Web UI: [{}] -- CSRF protection blocked request from origin: {}", address, blocked_origin); + logging::error("Web UI: To allow this origin, add it to the 'csrf_allowed_origins' option in your Sunshine configuration"sv); bad_request(response, request, "Missing CSRF token"); return false; } @@ -995,7 +996,9 @@ namespace confighttp { // Don't do anything if the file does not exist or is outside the assets directory if (!isChildPath(filePath, nodeModulesPath)) { - BOOST_LOG(warning) << "Someone requested a path " << filePath << " that is outside the assets folder"; + logging::warning([&](std::ostream &out) { + out << "Someone requested a path " << filePath << " that is outside the assets folder"; + }); bad_request(response, request); return; } @@ -1100,7 +1103,7 @@ namespace confighttp { send_response(response, file_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "GetApps: "sv << e.what(); + logging::warning("GetApps: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1159,7 +1162,7 @@ namespace confighttp { nlohmann::json output_tree; nlohmann::json input_tree = nlohmann::json::parse(ss); std::string file = file_handler::read_file(settings.stream.file_apps.c_str()); - BOOST_LOG(info) << file; + logging::info(file); nlohmann::json file_tree = nlohmann::json::parse(file); if (input_tree["prep-cmd"].empty()) { @@ -1200,7 +1203,7 @@ namespace confighttp { output_tree["status"] = true; send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "SaveApp: "sv << e.what(); + logging::warning("SaveApp: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1277,7 +1280,7 @@ namespace confighttp { output_tree["result"] = std::format("application {} deleted", index); send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "DeleteApp: "sv << e.what(); + logging::warning("DeleteApp: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1354,7 +1357,7 @@ namespace confighttp { send_response(response, output_tree); } catch (nlohmann::json::exception &e) { - BOOST_LOG(warning) << "Update Client: "sv << e.what(); + logging::warning("Update Client: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1404,7 +1407,7 @@ namespace confighttp { send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "Unpair: "sv << e.what(); + logging::warning("Unpair: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1532,7 +1535,7 @@ namespace confighttp { output_tree["status"] = true; send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "SaveConfig: "sv << e.what(); + logging::warning("SaveConfig: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1577,7 +1580,7 @@ namespace confighttp { // Check if we got the default image path (means validation failed or no image configured) if (validated_path == DEFAULT_APP_IMAGE_PATH) { - BOOST_LOG(debug) << "Application at index " << index << " does not have a valid cover image"; + logging::debug("Application at index {} does not have a valid cover image", index); not_found(response, request, "Cover image not found"); return; } @@ -1585,7 +1588,9 @@ namespace confighttp { // Open and stream the validated file std::ifstream in(validated_path, std::ios::binary); if (!in) { - BOOST_LOG(warning) << "Unable to read cover image file: " << validated_path; + logging::warning([&](std::ostream &out) { + out << "Unable to read cover image file: " << validated_path; + }); bad_request(response, request, "Unable to read cover image file"); return; } @@ -1597,7 +1602,7 @@ namespace confighttp { response->write(SimpleWeb::StatusCode::success_ok, in, headers); } catch (std::exception &e) { - BOOST_LOG(warning) << "GetCover: "sv << e.what(); + logging::warning("GetCover: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1660,7 +1665,7 @@ namespace confighttp { output_tree["path"] = path; send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "UploadCover: "sv << e.what(); + logging::warning("UploadCover: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1764,7 +1769,7 @@ namespace confighttp { send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "SavePassword: "sv << e.what(); + logging::warning("SavePassword: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1833,7 +1838,7 @@ namespace confighttp { output_tree["status"] = gamestream.cancel_pairing(pairing_id); send_response(response, output_tree); } catch (nlohmann::json::exception &e) { - BOOST_LOG(warning) << "CancelPairing: "sv << e.what(); + logging::warning("CancelPairing: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1894,7 +1899,7 @@ namespace confighttp { output_tree["status"] = gamestream.pin(pairing_id, pin, name); send_response(response, output_tree); } catch (std::exception &e) { - BOOST_LOG(warning) << "SavePin: "sv << e.what(); + logging::warning("SavePin: {}", e.what()); bad_request(response, request, e.what()); } } @@ -1949,7 +1954,9 @@ namespace confighttp { std::error_code ec; fs::remove(portal_token_path_provider()(), ec); if (ec) { - BOOST_LOG(error) << "Failed to delete XDG Portal restore token: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "Failed to delete XDG Portal restore token: "sv << ec.message(); + }); status = false; } #endif @@ -2304,12 +2311,14 @@ namespace confighttp { file_entry["type"] = is_dir ? "directory" : "file"; entries.push_back(file_entry); } catch (const fs::filesystem_error &e) { - BOOST_LOG(debug) << "BrowseDirectory: skipping entry due to error: "sv << e.what(); + logging::debug("BrowseDirectory: skipping entry due to error: {}", e.what()); } } if (iter_ec) { - BOOST_LOG(debug) << "BrowseDirectory: directory iteration error: "sv << iter_ec.message(); + logging::debug([&](std::ostream &out) { + out << "BrowseDirectory: directory iteration error: "sv << iter_ec.message(); + }); } // Sort: directories first, then files; both case-insensitively alphabetical @@ -2408,7 +2417,7 @@ namespace confighttp { output_tree["entries"] = build_browse_entries(dir_path, type_str); send_response(response, output_tree); } catch (const fs::filesystem_error &e) { - BOOST_LOG(warning) << "BrowseDirectory: "sv << e.what(); + logging::warning("BrowseDirectory: {}", e.what()); bad_request(response, request, e.what()); } } @@ -2516,7 +2525,7 @@ namespace confighttp { try { platf::set_thread_name("confighttp::tcp"); server->start([&display_addr](const unsigned short port) { - BOOST_LOG(info) << "Configuration UI available at [https://"sv << display_addr << ":" << port << "]"; + logging::info("Configuration UI available at [https://{}:{}]", display_addr, port); }); } catch (boost::system::system_error &err) { // It's possible the exception gets thrown after calling server->stop() from a different thread @@ -2524,7 +2533,7 @@ namespace confighttp { return; } - BOOST_LOG(fatal) << "Couldn't start Configuration HTTPS server on port ["sv << port_https << "]: "sv << err.what(); + logging::fatal("Couldn't start Configuration HTTPS server on port [{}]: {}", port_https, err.what()); shutdown_event->raise(true); return; } diff --git a/src/display_device.cpp b/src/display_device.cpp index 5b9648a35..f9097111c 100644 --- a/src/display_device.cpp +++ b/src/display_device.cpp @@ -264,10 +264,10 @@ namespace display_device { * std::optional resolution; * if (parse_resolution_string("1920x1080", resolution)) { * if (resolution) { - * BOOST_LOG(info) << "Value was specified"; + * logging::info("Value was specified"); * } * else { - * BOOST_LOG(info) << "Value was empty"; + * logging::info("Value was empty"); * } * } * @examples_end @@ -284,10 +284,9 @@ namespace display_device { }; return true; } catch (const std::out_of_range &) { - BOOST_LOG(error) << "Failed to parse resolution string " << trimmed_input << " (number out of range)."; + logging::error("Failed to parse resolution string {} (number out of range).", trimmed_input); } catch (const std::exception &err) { - BOOST_LOG(error) << "Failed to parse resolution string " << trimmed_input << ":\n" - << err.what(); + logging::error("Failed to parse resolution string {}:\n{}", trimmed_input, err.what()); } } else { if (trimmed_input.empty()) { @@ -295,7 +294,7 @@ namespace display_device { return true; } - BOOST_LOG(error) << "Failed to parse resolution string " << trimmed_input << R"(. It must match a "1920x1080" pattern!)"; + logging::error("Failed to parse resolution string {}. It must match a \"1920x1080\" pattern!", trimmed_input); } return false; @@ -312,10 +311,10 @@ namespace display_device { * std::optional refresh_rate; * if (parse_refresh_rate_string("59.95", refresh_rate)) { * if (refresh_rate) { - * BOOST_LOG(info) << "Value was specified"; + * logging::info("Value was specified"); * } * else { - * BOOST_LOG(info) << "Value was empty"; + * logging::info("Value was empty"); * } * } * @examples_end @@ -365,10 +364,9 @@ namespace display_device { } return true; } catch (const std::out_of_range &) { - BOOST_LOG(error) << "Failed to parse refresh rate string " << trimmed_input << " (number out of range)."; + logging::error("Failed to parse refresh rate string {} (number out of range).", trimmed_input); } catch (const std::exception &err) { - BOOST_LOG(error) << "Failed to parse refresh rate string " << trimmed_input << ":\n" - << err.what(); + logging::error("Failed to parse refresh rate string {}:\n{}", trimmed_input, err.what()); } } else { if (trimmed_input.empty()) { @@ -376,7 +374,9 @@ namespace display_device { return true; } - BOOST_LOG(error) << "Failed to parse refresh rate string " << trimmed_input << ". Must have a pattern of " << (allow_decimal_point ? R"("123" or "123.456")" : R"("123")") << "!"; + logging::error([&](std::ostream &out) { + out << "Failed to parse refresh rate string " << trimmed_input << ". Must have a pattern of " << (allow_decimal_point ? R"("123" or "123.456")" : R"("123")") << "!"; + }); } return false; @@ -435,14 +435,14 @@ namespace display_device { case resolution_option_e::automatic: { if (!session.enable_sops) { - BOOST_LOG(warning) << R"(Sunshine is configured to change resolution automatically, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)"; + logging::warning(R"(Sunshine is configured to change resolution automatically, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)"); } else if (session.width >= 0 && session.height >= 0) { config.m_resolution = Resolution { static_cast(session.width), static_cast(session.height) }; } else { - BOOST_LOG(error) << "Resolution provided by client session config is invalid: " << session.width << "x" << session.height; + logging::error("Resolution provided by client session config is invalid: {}x{}", session.width, session.height); return false; } break; @@ -450,15 +450,15 @@ namespace display_device { case resolution_option_e::manual: { if (!session.enable_sops) { - BOOST_LOG(warning) << R"(Sunshine is configured to change resolution manually, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)"; + logging::warning(R"(Sunshine is configured to change resolution manually, but the "Optimize game settings" is not set in the client! Resolution will not be changed.)"); } else { if (!parse_resolution_string(video_config.dd.manual_resolution, config.m_resolution)) { - BOOST_LOG(error) << "Failed to parse manual resolution string!"; + logging::error("Failed to parse manual resolution string!"); return false; } if (!config.m_resolution) { - BOOST_LOG(error) << "Manual resolution must be specified!"; + logging::error("Manual resolution must be specified!"); return false; } } @@ -495,7 +495,7 @@ namespace display_device { if (session.fps >= 0) { config.m_refresh_rate = Rational {static_cast(session.fps), 1}; } else { - BOOST_LOG(error) << "FPS value provided by client session config is invalid: " << session.fps; + logging::error("FPS value provided by client session config is invalid: {}", session.fps); return false; } break; @@ -503,12 +503,12 @@ namespace display_device { case refresh_rate_option_e::manual: { if (!parse_refresh_rate_string(video_config.dd.manual_refresh_rate, config.m_refresh_rate)) { - BOOST_LOG(error) << "Failed to parse manual refresh rate string!"; + logging::error("Failed to parse manual refresh rate string!"); return false; } if (!config.m_refresh_rate) { - BOOST_LOG(error) << "Manual refresh rate must be specified!"; + logging::error("Manual refresh rate must be specified!"); return false; } break; @@ -664,10 +664,10 @@ namespace display_device { }()}; if (remapping_list.empty()) { - BOOST_LOG(debug) << "No values are available for display mode remapping."; + logging::debug("No values are available for display mode remapping."); return true; } - BOOST_LOG(debug) << "Trying to remap display modes..."; + logging::debug("Trying to remap display modes..."); const auto entry_to_string {[type = *remapping_type](const config::video_t::dd_t::mode_remapping_entry_t &entry) { const bool mapping_resolution {is_resolution_mapped(type)}; @@ -684,39 +684,51 @@ namespace display_device { for (const auto &entry : remapping_list) { const auto parsed_entry {parse_remapping_entry(entry, *remapping_type)}; if (!parsed_entry) { - BOOST_LOG(error) << "Failed to parse remapping entry from:\n" - << entry_to_string(entry); + logging::error([&](std::ostream &out) { + out << "Failed to parse remapping entry from:\n" + << entry_to_string(entry); + }); return false; } if (!parsed_entry->final_resolution && !parsed_entry->final_refresh_rate) { - BOOST_LOG(error) << "At least one final value must be set for remapping display modes! Entry:\n" - << entry_to_string(entry); + logging::error([&](std::ostream &out) { + out << "At least one final value must be set for remapping display modes! Entry:\n" + << entry_to_string(entry); + }); return false; } if (!session.enable_sops && (parsed_entry->requested_resolution || parsed_entry->final_resolution)) { - BOOST_LOG(warning) << R"(Skipping remapping entry, because the "Optimize game settings" is not set in the client! Entry:\n)" - << entry_to_string(entry); + logging::warning([&](std::ostream &out) { + out << R"(Skipping remapping entry, because the "Optimize game settings" is not set in the client! Entry:\n)" + << entry_to_string(entry); + }); continue; } // Note: at this point config should already have parsed resolution set. if (parsed_entry->requested_resolution && parsed_entry->requested_resolution != config.m_resolution) { - BOOST_LOG(verbose) << "Skipping remapping because requested resolutions do not match! Entry:\n" - << entry_to_string(entry); + logging::verbose([&](std::ostream &out) { + out << "Skipping remapping because requested resolutions do not match! Entry:\n" + << entry_to_string(entry); + }); continue; } // Note: at this point config should already have parsed refresh rate set. if (parsed_entry->requested_fps && parsed_entry->requested_fps != config.m_refresh_rate) { - BOOST_LOG(verbose) << "Skipping remapping because requested FPS do not match! Entry:\n" - << entry_to_string(entry); + logging::verbose([&](std::ostream &out) { + out << "Skipping remapping because requested FPS do not match! Entry:\n" + << entry_to_string(entry); + }); continue; } - BOOST_LOG(info) << "Remapping requested display mode. Entry:\n" - << entry_to_string(entry); + logging::info([&](std::ostream &out) { + out << "Remapping requested display mode. Entry:\n" + << entry_to_string(entry); + }); if (parsed_entry->final_resolution) { config.m_resolution = parsed_entry->final_resolution; } @@ -821,8 +833,10 @@ namespace display_device { return parsed_devices; }()}; if (available_devices == tried_out_devices) { - BOOST_LOG(debug) << "Skipping reverting configuration, because no newly added/removed devices were detected since last check. Currently available devices:\n" - << toJson(available_devices); + logging::debug([&](std::ostream &out) { + out << "Skipping reverting configuration, because no newly added/removed devices were detected since last check. Currently available devices:\n" + << toJson(available_devices); + }); return; } @@ -841,11 +855,15 @@ namespace display_device { // Try again only after a device is added or removed. That includes redocking a display whose settings are still saved. if (result == Ok) { - BOOST_LOG(info) << "Recovered the available display layout, but settings for an unavailable display are still pending. Will retry once devices are added or removed. Currently available devices:\n" - << toJson(available_devices); + logging::info([&](std::ostream &out) { + out << "Recovered the available display layout, but settings for an unavailable display are still pending. Will retry once devices are added or removed. Currently available devices:\n" + << toJson(available_devices); + }); } else { - BOOST_LOG(warning) << "Failed to revert display device configuration (will retry once devices are added or removed). Enabling all of the available devices:\n" - << toJson(available_devices); + logging::warning([&](std::ostream &out) { + out << "Failed to revert display device configuration (will retry once devices are added or removed). Enabling all of the available devices:\n" + << toJson(available_devices); + }); } tried_out_devices.swap(available_devices); } @@ -889,7 +907,7 @@ namespace display_device { try { revert_configuration_unlocked(*impl, revert_option_e::try_once); } catch (const std::exception &error) { - BOOST_LOG(fatal) << error.what(); + logging::fatal(error.what()); } impl->sm_instance.reset(); } @@ -909,8 +927,10 @@ namespace display_device { const auto available_devices {impl->sm_instance->execute([](auto &settings_iface) { return settings_iface.enumAvailableDevices(); })}; - BOOST_LOG(info) << "Currently available display devices:\n" - << toJson(available_devices); + logging::info([&](std::ostream &out) { + out << "Currently available display devices:\n" + << toJson(available_devices); + }); // In case we have failed to revert configuration before shutting down, we should // do it now. @@ -964,12 +984,12 @@ namespace display_device { } if (const auto *disabled {std::get_if(&result)}; disabled) { - BOOST_LOG(info) << "Display device configuration is disabled. Reverting any active display device configuration."; + logging::info("Display device configuration is disabled. Reverting any active display device configuration."); revert_configuration(); return; } - BOOST_LOG(error) << "Failed to parse display device configuration. Display settings will not be changed."; + logging::error("Failed to parse display device configuration. Display settings will not be changed."); // Error details should already be logged for failed_to_parse_tag_t case, and we also don't // want to revert active configuration in case we have any } @@ -981,8 +1001,10 @@ namespace display_device { return; } - BOOST_LOG(info) << "Scheduling display device configuration:\n" - << toJson(config); + logging::info([&](std::ostream &out) { + out << "Scheduling display device configuration:\n" + << toJson(config); + }); impl->sm_instance->schedule([config](auto &settings_iface, auto &stop_token) { using enum SettingsManagerInterface::ApplyResult; @@ -991,11 +1013,11 @@ namespace display_device { // In other cases, when we either fail or succeed we just want to stop... const auto result {settings_iface.applySettings(config)}; if (result == Ok) { - BOOST_LOG(info) << "Display device configuration applied successfully."; + logging::info("Display device configuration applied successfully."); } else if (result == ApiTemporarilyUnavailable) { - BOOST_LOG(warning) << "Display device configuration API is temporarily unavailable. Will retry."; + logging::warning("Display device configuration API is temporarily unavailable. Will retry."); } else { - BOOST_LOG(error) << "Display device configuration failed with result: " << apply_result_name(result); + logging::error("Display device configuration failed with result: {}", apply_result_name(result)); } if (result != ApiTemporarilyUnavailable) { @@ -1050,7 +1072,7 @@ namespace display_device { const auto hdr_state {parse_hdr_option(video_config, session)}; #ifdef __APPLE__ if (hdr_state) { - BOOST_LOG(info) << "Ignoring HDR display device request on macOS because macOS HDR changes are not supported by libdisplaydevice."; + logging::info("Ignoring HDR display device request on macOS because macOS HDR changes are not supported by libdisplaydevice."); } #else config.m_hdr_state = hdr_state; @@ -1058,7 +1080,7 @@ namespace display_device { #ifdef __APPLE__ if (config.m_device_prep != SingleDisplayConfiguration::DevicePreparation::VerifyOnly) { - BOOST_LOG(warning) << "macOS libdisplaydevice currently supports only VerifyOnly display preparation. The requested preparation mode will fail."; + logging::warning("macOS libdisplaydevice currently supports only VerifyOnly display preparation. The requested preparation mode will fail."); } #endif diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp index 7947c1401..db8b41b85 100644 --- a/src/entry_handler.cpp +++ b/src/entry_handler.cpp @@ -171,9 +171,9 @@ namespace lifetime { } // namespace lifetime void log_publisher_data() { - BOOST_LOG(info) << "Package Publisher: "sv << SUNSHINE_PUBLISHER_NAME; - BOOST_LOG(info) << "Publisher Website: "sv << SUNSHINE_PUBLISHER_WEBSITE; - BOOST_LOG(info) << "Get support: "sv << SUNSHINE_PUBLISHER_ISSUE_URL; + logging::info("Package Publisher: {}", SUNSHINE_PUBLISHER_NAME); + logging::info("Publisher Website: {}", SUNSHINE_PUBLISHER_WEBSITE); + logging::info("Get support: {}", SUNSHINE_PUBLISHER_ISSUE_URL); } #ifdef _WIN32 @@ -207,14 +207,14 @@ namespace service_ctrl { scm_handle = OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm_handle) { auto winerr = GetLastError(); - BOOST_LOG(error) << "OpenSCManager() failed: "sv << winerr; + logging::error("OpenSCManager() failed: {}", winerr); return; } service_handle = OpenServiceA(scm_handle, "SunshineService", service_desired_access); if (!service_handle) { auto winerr = GetLastError(); - BOOST_LOG(error) << "OpenService() failed: "sv << winerr; + logging::error("OpenService() failed: {}", winerr); return; } } @@ -242,7 +242,7 @@ namespace service_ctrl { if (!StartServiceA(service_handle, 0, nullptr)) { auto winerr = GetLastError(); if (winerr != ERROR_SERVICE_ALREADY_RUNNING) { - BOOST_LOG(error) << "StartService() failed: "sv << winerr; + logging::error("StartService() failed: {}", winerr); return false; } } @@ -263,7 +263,7 @@ namespace service_ctrl { if (!QueryServiceStatus(service_handle, &status)) { auto winerr = GetLastError(); - BOOST_LOG(error) << "QueryServiceStatus() failed: "sv << winerr; + logging::error("QueryServiceStatus() failed: {}", winerr); return false; } @@ -303,7 +303,7 @@ namespace service_ctrl { } while (sc.query_service_status(status) && status.dwCurrentState == SERVICE_START_PENDING); if (status.dwCurrentState != SERVICE_RUNNING) { - BOOST_LOG(error) << std::format("{} failed to start: {}"sv, platf::SERVICE_NAME, status.dwWin32ExitCode); + logging::error("{} failed to start: {}", platf::SERVICE_NAME, status.dwWin32ExitCode); return false; } @@ -334,7 +334,7 @@ namespace service_ctrl { } while (err == ERROR_INSUFFICIENT_BUFFER); if (err != NO_ERROR) { - BOOST_LOG(error) << "Failed to query TCP table: "sv << err; + logging::error("Failed to query TCP table: {}", err); return false; } diff --git a/src/file_handler.cpp b/src/file_handler.cpp index f7b4ee725..cb09a464d 100644 --- a/src/file_handler.cpp +++ b/src/file_handler.cpp @@ -34,7 +34,7 @@ namespace file_handler { std::string read_file(const char *path) { if (!std::filesystem::exists(path)) { - BOOST_LOG(debug) << "Missing file: " << path; + logging::debug("Missing file: {}", path); return {}; } diff --git a/src/httpcommon.cpp b/src/httpcommon.cpp index 48375ec05..f0b016a6f 100644 --- a/src/httpcommon.cpp +++ b/src/httpcommon.cpp @@ -68,7 +68,7 @@ namespace http { return -1; } if (!user_creds_exist(settings.sunshine.credentials_file)) { - BOOST_LOG(info) << "Open the Web UI to set your new username and password and getting started"; + logging::info("Open the Web UI to set your new username and password and getting started"); } else if (reload_user_creds(settings.sunshine.credentials_file, store)) { return -1; } @@ -103,7 +103,7 @@ namespace http { try { pt::read_json(file, outputTree); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't read user credentials: "sv << e.what(); + logging::error("Couldn't read user credentials: {}", e.what()); return -1; } } @@ -115,11 +115,11 @@ namespace http { try { pt::write_json(file, outputTree); } catch (std::exception &e) { - BOOST_LOG(error) << "error writing to the credentials file, perhaps try this again as an administrator? Details: "sv << e.what(); + logging::error("error writing to the credentials file, perhaps try this again as an administrator? Details: {}", e.what()); return -1; } - BOOST_LOG(info) << "New credentials have been created"sv; + logging::info("New credentials have been created"sv); return 0; } @@ -138,7 +138,7 @@ namespace http { inputTree.find("password") != inputTree.not_found() && inputTree.find("salt") != inputTree.not_found(); } catch (std::exception &e) { - BOOST_LOG(error) << "validating user credentials: "sv << e.what(); + logging::error("validating user credentials: {}", e.what()); } return false; @@ -154,7 +154,7 @@ namespace http { config::credentials_t credentials {inputTree.get("username"), inputTree.get("password"), inputTree.get("salt")}; store.update_credentials(std::move(credentials)); } catch (std::exception &e) { - BOOST_LOG(error) << "loading user credentials: "sv << e.what(); + logging::error("loading user credentials: {}", e.what()); return -1; } return 0; @@ -177,37 +177,45 @@ namespace http { std::error_code err_code {}; fs::create_directories(pkey_dir, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't create directory ["sv << pkey_dir << "] :"sv << err_code.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't create directory ["sv << pkey_dir << "] :"sv << err_code.message(); + }); return -1; } fs::create_directories(cert_dir, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't create directory ["sv << cert_dir << "] :"sv << err_code.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't create directory ["sv << cert_dir << "] :"sv << err_code.message(); + }); return -1; } if (file_handler::write_file(pkey.c_str(), creds.pkey)) { - BOOST_LOG(error) << "Couldn't open ["sv << pkey << ']'; + logging::error("Couldn't open [{}]", pkey); return -1; } if (file_handler::write_file(cert.c_str(), creds.x509)) { - BOOST_LOG(error) << "Couldn't open ["sv << cert << ']'; + logging::error("Couldn't open [{}]", cert); return -1; } fs::permissions(pkey_path, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't change permissions of ["sv << pkey << "] :"sv << err_code.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't change permissions of ["sv << pkey << "] :"sv << err_code.message(); + }); return -1; } fs::permissions(cert_path, fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read | fs::perms::owner_write, fs::perm_options::replace, err_code); if (err_code) { - BOOST_LOG(error) << "Couldn't change permissions of ["sv << cert << "] :"sv << err_code.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't change permissions of ["sv << cert << "] :"sv << err_code.message(); + }); return -1; } @@ -220,19 +228,21 @@ namespace http { bool download_file(const std::string &url, const std::string &file, long ssl_version) { CURL *curl = curl_easy_init(); if (!curl) { - BOOST_LOG(error) << "Couldn't create CURL instance"; + logging::error("Couldn't create CURL instance"); return false; } if (std::string file_dir = file_handler::get_parent_directory(file); !file_handler::make_directory(file_dir)) { - BOOST_LOG(error) << "Couldn't create directory ["sv << file_dir << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't create directory ["sv << file_dir << ']'; + }); curl_easy_cleanup(curl); return false; } FILE *fp = fopen(file.c_str(), "wb"); if (!fp) { - BOOST_LOG(error) << "Couldn't open ["sv << file << ']'; + logging::error("Couldn't open [{}]", file); curl_easy_cleanup(curl); return false; } @@ -244,7 +254,7 @@ namespace http { CURLcode result = curl_easy_perform(curl); if (result != CURLE_OK) { - BOOST_LOG(error) << "Couldn't download ["sv << url << ", code:" << result << ']'; + logging::error("Couldn't download [{}, code:{}]", url, static_cast(result)); } curl_easy_cleanup(curl); diff --git a/src/input.cpp b/src/input.cpp index 5a289396e..98bccacdc 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -514,7 +514,9 @@ namespace input { constexpr auto VK_F1 = 0x70; constexpr auto VK_F13 = 0x7C; - BOOST_LOG(debug) << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view(); + logging::debug([&](std::ostream &out) { + out << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view(); + }); if (keyCode >= VK_F1 && keyCode <= VK_F13) { host.mail->event(mail::switch_display)->raise(keyCode - VK_F1); @@ -536,11 +538,12 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PNV_REL_MOUSE_MOVE_PACKET packet) { - BOOST_LOG(debug) - << "--begin relative mouse move packet--"sv << std::endl - << "deltaX ["sv << util::endian::big(packet->deltaX) << ']' << std::endl - << "deltaY ["sv << util::endian::big(packet->deltaY) << ']' << std::endl - << "--end relative mouse move packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin relative mouse move packet--"sv << std::endl + << "deltaX ["sv << util::endian::big(packet->deltaX) << ']' << std::endl + << "deltaY ["sv << util::endian::big(packet->deltaY) << ']' << std::endl + << "--end relative mouse move packet--"sv; + }); } /** @@ -549,13 +552,14 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PNV_ABS_MOUSE_MOVE_PACKET packet) { - BOOST_LOG(debug) - << "--begin absolute mouse move packet--"sv << std::endl - << "x ["sv << util::endian::big(packet->x) << ']' << std::endl - << "y ["sv << util::endian::big(packet->y) << ']' << std::endl - << "width ["sv << util::endian::big(packet->width) << ']' << std::endl - << "height ["sv << util::endian::big(packet->height) << ']' << std::endl - << "--end absolute mouse move packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin absolute mouse move packet--"sv << std::endl + << "x ["sv << util::endian::big(packet->x) << ']' << std::endl + << "y ["sv << util::endian::big(packet->y) << ']' << std::endl + << "width ["sv << util::endian::big(packet->width) << ']' << std::endl + << "height ["sv << util::endian::big(packet->height) << ']' << std::endl + << "--end absolute mouse move packet--"sv; + }); } /** @@ -564,11 +568,12 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PNV_MOUSE_BUTTON_PACKET packet) { - BOOST_LOG(debug) - << "--begin mouse button packet--"sv << std::endl - << "action ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl - << "button ["sv << util::hex(packet->button).to_string_view() << ']' << std::endl - << "--end mouse button packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin mouse button packet--"sv << std::endl + << "action ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl + << "button ["sv << util::hex(packet->button).to_string_view() << ']' << std::endl + << "--end mouse button packet--"sv; + }); } /** @@ -577,10 +582,11 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PNV_SCROLL_PACKET packet) { - BOOST_LOG(debug) - << "--begin mouse scroll packet--"sv << std::endl - << "scrollAmt1 ["sv << util::endian::big(packet->scrollAmt1) << ']' << std::endl - << "--end mouse scroll packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin mouse scroll packet--"sv << std::endl + << "scrollAmt1 ["sv << util::endian::big(packet->scrollAmt1) << ']' << std::endl + << "--end mouse scroll packet--"sv; + }); } /** @@ -589,10 +595,11 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PSS_HSCROLL_PACKET packet) { - BOOST_LOG(debug) - << "--begin mouse hscroll packet--"sv << std::endl - << "scrollAmount ["sv << util::endian::big(packet->scrollAmount) << ']' << std::endl - << "--end mouse hscroll packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin mouse hscroll packet--"sv << std::endl + << "scrollAmount ["sv << util::endian::big(packet->scrollAmount) << ']' << std::endl + << "--end mouse hscroll packet--"sv; + }); } /** @@ -601,13 +608,14 @@ namespace input { * @param packet Protocol packet being processed. */ void print(PNV_KEYBOARD_PACKET packet) { - BOOST_LOG(debug) - << "--begin keyboard packet--"sv << std::endl - << "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl - << "keyCode ["sv << util::hex(packet->keyCode).to_string_view() << ']' << std::endl - << "modifiers ["sv << util::hex(packet->modifiers).to_string_view() << ']' << std::endl - << "flags ["sv << util::hex(packet->flags).to_string_view() << ']' << std::endl - << "--end keyboard packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin keyboard packet--"sv << std::endl + << "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl + << "keyCode ["sv << util::hex(packet->keyCode).to_string_view() << ']' << std::endl + << "modifiers ["sv << util::hex(packet->modifiers).to_string_view() << ']' << std::endl + << "flags ["sv << util::hex(packet->flags).to_string_view() << ']' << std::endl + << "--end keyboard packet--"sv; + }); } /** @@ -617,10 +625,7 @@ namespace input { */ void print(PNV_UNICODE_PACKET packet) { std::string text(packet->text, util::endian::big(packet->header.size) - sizeof(packet->header.magic)); - BOOST_LOG(debug) - << "--begin unicode packet--"sv << std::endl - << "text ["sv << text << ']' << std::endl - << "--end unicode packet--"sv; + logging::debug("--begin unicode packet--\ntext [{}]\n--end unicode packet--", text); } /** @@ -630,18 +635,19 @@ namespace input { */ void print(PNV_MULTI_CONTROLLER_PACKET packet) { // Moonlight spams controller packet even when not necessary - BOOST_LOG(verbose) - << "--begin controller packet--"sv << std::endl - << "controllerNumber ["sv << packet->controllerNumber << ']' << std::endl - << "activeGamepadMask ["sv << util::hex(packet->activeGamepadMask).to_string_view() << ']' << std::endl - << "buttonFlags ["sv << util::hex((uint32_t) packet->buttonFlags | (packet->buttonFlags2 << 16)).to_string_view() << ']' << std::endl - << "leftTrigger ["sv << util::hex(packet->leftTrigger).to_string_view() << ']' << std::endl - << "rightTrigger ["sv << util::hex(packet->rightTrigger).to_string_view() << ']' << std::endl - << "leftStickX ["sv << packet->leftStickX << ']' << std::endl - << "leftStickY ["sv << packet->leftStickY << ']' << std::endl - << "rightStickX ["sv << packet->rightStickX << ']' << std::endl - << "rightStickY ["sv << packet->rightStickY << ']' << std::endl - << "--end controller packet--"sv; + logging::verbose([&](std::ostream &out) { + out << "--begin controller packet--"sv << std::endl + << "controllerNumber ["sv << packet->controllerNumber << ']' << std::endl + << "activeGamepadMask ["sv << util::hex(packet->activeGamepadMask).to_string_view() << ']' << std::endl + << "buttonFlags ["sv << util::hex((uint32_t) packet->buttonFlags | (packet->buttonFlags2 << 16)).to_string_view() << ']' << std::endl + << "leftTrigger ["sv << util::hex(packet->leftTrigger).to_string_view() << ']' << std::endl + << "rightTrigger ["sv << util::hex(packet->rightTrigger).to_string_view() << ']' << std::endl + << "leftStickX ["sv << packet->leftStickX << ']' << std::endl + << "leftStickY ["sv << packet->leftStickY << ']' << std::endl + << "rightStickX ["sv << packet->rightStickX << ']' << std::endl + << "rightStickY ["sv << packet->rightStickY << ']' << std::endl + << "--end controller packet--"sv; + }); } /** @@ -649,17 +655,18 @@ namespace input { * @param packet The touch packet. */ void print(PSS_TOUCH_PACKET packet) { - BOOST_LOG(debug) - << "--begin touch packet--"sv << std::endl - << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl - << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl - << "x ["sv << from_netfloat(packet->x) << ']' << std::endl - << "y ["sv << from_netfloat(packet->y) << ']' << std::endl - << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl - << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl - << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl - << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl - << "--end touch packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin touch packet--"sv << std::endl + << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl + << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl + << "x ["sv << from_netfloat(packet->x) << ']' << std::endl + << "y ["sv << from_netfloat(packet->y) << ']' << std::endl + << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl + << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl + << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl + << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl + << "--end touch packet--"sv; + }); } /** @@ -667,19 +674,20 @@ namespace input { * @param packet The pen packet. */ void print(PSS_PEN_PACKET packet) { - BOOST_LOG(debug) - << "--begin pen packet--"sv << std::endl - << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl - << "toolType ["sv << util::hex(packet->toolType).to_string_view() << ']' << std::endl - << "penButtons ["sv << util::hex(packet->penButtons).to_string_view() << ']' << std::endl - << "x ["sv << from_netfloat(packet->x) << ']' << std::endl - << "y ["sv << from_netfloat(packet->y) << ']' << std::endl - << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl - << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl - << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl - << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl - << "tilt ["sv << (uint32_t) packet->tilt << ']' << std::endl - << "--end pen packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin pen packet--"sv << std::endl + << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl + << "toolType ["sv << util::hex(packet->toolType).to_string_view() << ']' << std::endl + << "penButtons ["sv << util::hex(packet->penButtons).to_string_view() << ']' << std::endl + << "x ["sv << from_netfloat(packet->x) << ']' << std::endl + << "y ["sv << from_netfloat(packet->y) << ']' << std::endl + << "pressureOrDistance ["sv << from_netfloat(packet->pressureOrDistance) << ']' << std::endl + << "contactAreaMajor ["sv << from_netfloat(packet->contactAreaMajor) << ']' << std::endl + << "contactAreaMinor ["sv << from_netfloat(packet->contactAreaMinor) << ']' << std::endl + << "rotation ["sv << (uint32_t) packet->rotation << ']' << std::endl + << "tilt ["sv << (uint32_t) packet->tilt << ']' << std::endl + << "--end pen packet--"sv; + }); } /** @@ -687,13 +695,14 @@ namespace input { * @param packet The controller arrival packet. */ void print(PSS_CONTROLLER_ARRIVAL_PACKET packet) { - BOOST_LOG(debug) - << "--begin controller arrival packet--"sv << std::endl - << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl - << "type ["sv << util::hex(packet->type).to_string_view() << ']' << std::endl - << "capabilities ["sv << util::hex(packet->capabilities).to_string_view() << ']' << std::endl - << "supportedButtonFlags ["sv << util::hex(packet->supportedButtonFlags).to_string_view() << ']' << std::endl - << "--end controller arrival packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin controller arrival packet--"sv << std::endl + << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl + << "type ["sv << util::hex(packet->type).to_string_view() << ']' << std::endl + << "capabilities ["sv << util::hex(packet->capabilities).to_string_view() << ']' << std::endl + << "supportedButtonFlags ["sv << util::hex(packet->supportedButtonFlags).to_string_view() << ']' << std::endl + << "--end controller arrival packet--"sv; + }); } /** @@ -701,15 +710,16 @@ namespace input { * @param packet The controller touch packet. */ void print(PSS_CONTROLLER_TOUCH_PACKET packet) { - BOOST_LOG(debug) - << "--begin controller touch packet--"sv << std::endl - << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl - << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl - << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl - << "x ["sv << from_netfloat(packet->x) << ']' << std::endl - << "y ["sv << from_netfloat(packet->y) << ']' << std::endl - << "pressure ["sv << from_netfloat(packet->pressure) << ']' << std::endl - << "--end controller touch packet--"sv; + logging::debug([&](std::ostream &out) { + out << "--begin controller touch packet--"sv << std::endl + << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl + << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl + << "pointerId ["sv << util::hex(packet->pointerId).to_string_view() << ']' << std::endl + << "x ["sv << from_netfloat(packet->x) << ']' << std::endl + << "y ["sv << from_netfloat(packet->y) << ']' << std::endl + << "pressure ["sv << from_netfloat(packet->pressure) << ']' << std::endl + << "--end controller touch packet--"sv; + }); } /** @@ -717,14 +727,15 @@ namespace input { * @param packet The controller motion packet. */ void print(PSS_CONTROLLER_MOTION_PACKET packet) { - BOOST_LOG(verbose) - << "--begin controller motion packet--"sv << std::endl - << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl - << "motionType ["sv << util::hex(packet->motionType).to_string_view() << ']' << std::endl - << "x ["sv << from_netfloat(packet->x) << ']' << std::endl - << "y ["sv << from_netfloat(packet->y) << ']' << std::endl - << "z ["sv << from_netfloat(packet->z) << ']' << std::endl - << "--end controller motion packet--"sv; + logging::verbose([&](std::ostream &out) { + out << "--begin controller motion packet--"sv << std::endl + << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl + << "motionType ["sv << util::hex(packet->motionType).to_string_view() << ']' << std::endl + << "x ["sv << from_netfloat(packet->x) << ']' << std::endl + << "y ["sv << from_netfloat(packet->y) << ']' << std::endl + << "z ["sv << from_netfloat(packet->z) << ']' << std::endl + << "--end controller motion packet--"sv; + }); } /** @@ -732,12 +743,13 @@ namespace input { * @param packet The controller battery packet. */ void print(PSS_CONTROLLER_BATTERY_PACKET packet) { - BOOST_LOG(verbose) - << "--begin controller battery packet--"sv << std::endl - << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl - << "batteryState ["sv << util::hex(packet->batteryState).to_string_view() << ']' << std::endl - << "batteryPercentage ["sv << util::hex(packet->batteryPercentage).to_string_view() << ']' << std::endl - << "--end controller battery packet--"sv; + logging::verbose([&](std::ostream &out) { + out << "--begin controller battery packet--"sv << std::endl + << "controllerNumber ["sv << util::hex(packet->controllerNumber).to_string_view() << ']' << std::endl + << "batteryState ["sv << util::hex(packet->batteryState).to_string_view() << ']' << std::endl + << "batteryPercentage ["sv << util::hex(packet->batteryPercentage).to_string_view() << ']' << std::endl + << "--end controller battery packet--"sv; + }); } /** @@ -863,7 +875,7 @@ namespace input { refresh_touch_port(input); auto &touch_port = input->touch_port; if (!touch_port) { - BOOST_LOG(verbose) << "Ignoring early absolute input without a touch port"sv; + logging::verbose("Ignoring early absolute input without a touch port"sv); return std::nullopt; } @@ -959,7 +971,7 @@ namespace input { // Prevent divide by zero // Don't expect it to happen, but just in case if (!packet->width || !packet->height) { - BOOST_LOG(warning) << "Moonlight passed invalid dimensions"sv; + logging::warning("Moonlight passed invalid dimensions"sv); return; } @@ -1410,13 +1422,13 @@ namespace input { int alloc_gamepad(std::shared_ptr &input, int client_index, const platf::gamepad_arrival_t &arrival) { auto &host = input->host; if (client_index < 0 || client_index >= input->gamepads.size()) { - BOOST_LOG(warning) << "ControllerNumber out of range ["sv << client_index << ']'; + logging::warning("ControllerNumber out of range [{}]", client_index); return -1; } auto &gamepad = input->gamepads[client_index]; if (gamepad.id >= 0) { - BOOST_LOG(warning) << "ControllerNumber already allocated ["sv << client_index << ']'; + logging::warning("ControllerNumber already allocated [{}]", client_index); return gamepad.id; } @@ -1463,7 +1475,7 @@ namespace input { const float monitor_logical_w = (touch_port.width * touch_port.scalar_inv) / touch_port.scalar_tpcoords; const float monitor_logical_h = (touch_port.height * touch_port.scalar_inv) / touch_port.scalar_tpcoords; if (monitor_logical_w <= 0.0f || monitor_logical_h <= 0.0f) { - BOOST_LOG(warning) << "Ignoring touch/pen input due to invalid logical touch dimensions"sv; + logging::warning("Ignoring touch/pen input due to invalid logical touch dimensions"sv); return std::nullopt; } @@ -1598,13 +1610,13 @@ namespace input { } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { - BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; + logging::warning("ControllerNumber out of range [{}]", static_cast(packet->controllerNumber)); return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { - BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; + logging::warning("ControllerNumber [{}] not allocated", static_cast(packet->controllerNumber)); return; } @@ -1632,13 +1644,13 @@ namespace input { } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { - BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; + logging::warning("ControllerNumber out of range [{}]", static_cast(packet->controllerNumber)); return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { - BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; + logging::warning("ControllerNumber [{}] not allocated", static_cast(packet->controllerNumber)); return; } @@ -1665,13 +1677,13 @@ namespace input { } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { - BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; + logging::warning("ControllerNumber out of range [{}]", static_cast(packet->controllerNumber)); return; } auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { - BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; + logging::warning("ControllerNumber [{}] not allocated", static_cast(packet->controllerNumber)); return; } @@ -1697,7 +1709,7 @@ namespace input { } if (packet->controllerNumber < 0 || packet->controllerNumber >= input->gamepads.size()) { - BOOST_LOG(warning) << "ControllerNumber out of range ["sv << packet->controllerNumber << ']'; + logging::warning("ControllerNumber out of range [{}]", static_cast(packet->controllerNumber)); return; } @@ -1720,7 +1732,7 @@ namespace input { // If this gamepad has not been initialized, ignore it. // This could happen when platf::alloc_gamepad fails if (gamepad.id < 0) { - BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; + logging::warning("ControllerNumber [{}] not allocated", static_cast(packet->controllerNumber)); return; } @@ -2324,13 +2336,14 @@ namespace input { NV_INPUT_HEADER header {}; if (!validate_input_packet(input_data, &header)) { if (input_data.size() >= sizeof(header)) { - BOOST_LOG(warning) - << "Dropping malformed input packet type ["sv - << util::hex(util::endian::little(header.magic)).to_string_view() - << "] with declared payload size ["sv << util::endian::big(header.size) - << "] and actual size ["sv << input_data.size() << ']'; + logging::warning([&](std::ostream &out) { + out << "Dropping malformed input packet type ["sv + << util::hex(util::endian::little(header.magic)).to_string_view() + << "] with declared payload size ["sv << util::endian::big(header.size) + << "] and actual size ["sv << input_data.size() << ']'; + }); } else { - BOOST_LOG(warning) << "Dropping malformed input packet with actual size ["sv << input_data.size() << ']'; + logging::warning("Dropping malformed input packet with actual size [{}]", input_data.size()); } return; } diff --git a/src/logging.cpp b/src/logging.cpp index b14eaca66..cf120a71e 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -4,17 +4,22 @@ */ // standard includes #include +#include #include #include #include +#include +#include +#include // lib includes #include #include -#include +#include #include #include #include +#include #include #include @@ -37,94 +42,205 @@ using namespace std::literals; namespace bl = boost::log; BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", int) +BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "Timestamp", std::chrono::system_clock::time_point) namespace logging { - logger_t::logger_type &logger_t::get() const { - switch (severity_) { - case 0: - return verbose_source::get(); - case 1: - return debug_source::get(); - case 2: - return info_source::get(); - case 3: - return warning_source::get(); - case 4: - return error_source::get(); - case 5: - return fatal_source::get(); -#ifdef SUNSHINE_TESTS - case 10: - return tests_source::get(); -#endif - default: - throw std::invalid_argument {"Unsupported log severity"}; + namespace { + /** + * @brief Boost-managed source shared by all Sunshine logging functions. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(log_source, bl::sources::severity_logger_mt) { + logger_type source; + source.add_attribute("Timestamp", bl::attributes::make_function([]() { + return std::chrono::system_clock::now(); + })); + return source; } - } - deinit_t::deinit_t(boost::shared_ptr sink, boost::shared_ptr platform_sink): - sink_ {std::move(sink)}, - platform_sink_ {std::move(platform_sink)} { - } + /** + * @brief Validate a severity and select its displayed name. + * @param level Message severity. + * @return Name prefixed to formatted messages. + * @throws std::invalid_argument If this build does not support the severity. + */ + std::string_view level_name(level_e level) { +#ifdef SUNSHINE_TESTS + if (level == test_level) { + return "Tests"sv; + } +#endif + switch (level) { + case level_e::verbose: + return "Verbose"sv; + case level_e::debug: + return "Debug"sv; + case level_e::info: + return "Info"sv; + case level_e::warning: + return "Warning"sv; + case level_e::error: + return "Error"sv; + case level_e::fatal: + return "Fatal"sv; + default: + throw std::invalid_argument {"Unsupported log severity"}; + } + } + + /** + * @brief Convert a backend record into the public structured message. + * @param record Accepted backend record. + * @return Message shared with every registered output. + */ + message_t make_message(const bl::record_view &record) { + return { + static_cast(record[severity].get()), + record[timestamp].get(), + record[bl::expressions::smessage].get(), + }; + } + + /** + * @brief Format a backend record for the existing file and console outputs. + * @param record Backend record being formatted. + * @param output Stream receiving the formatted line. + */ + void formatter(const bl::record_view &record, bl::formatting_ostream &output) { + output << format_message(make_message(record)); + } + + /** + * @brief Adapt an application output to the Boost delivery machinery. + */ + class output_backend_t: public bl::sinks::basic_sink_backend { + public: + /** + * @brief Retain the application output while it is registered. + * @param output Application output receiving messages. + */ + explicit output_backend_t(std::shared_ptr output): + output_ {std::move(output)} {} + + /** + * @brief Deliver one structured message to the application output. + * @param record Accepted backend record. + */ + void consume(const bl::record_view &record) { + output_->consume(make_message(record)); + } + + private: + std::shared_ptr output_; ///< Application output retained by this backend. + }; + + /** + * @brief Asynchronous file and console output. + */ + using text_sink = bl::sinks::asynchronous_sink; + } // namespace + + /** + * @brief Own backend registrations and their optional worker shutdown functions. + */ + struct deinit_t::impl_t { + /** + * @brief One registered output and its worker shutdown operation. + */ + struct registration_t { + boost::shared_ptr sink; ///< Registered output. + std::function stop; ///< Stops a worker thread, when present. + }; + + std::vector registrations; ///< Outputs owned by this registration. + }; + + deinit_t::deinit_t(std::unique_ptr impl): + impl_ {std::move(impl)} {} deinit_t::~deinit_t() { auto core = bl::core::get(); - core->remove_sink(sink_); - if (platform_sink_) { - core->remove_sink(platform_sink_); - platform_sink_->flush(); + for (auto ®istration : impl_->registrations) { + core->remove_sink(registration.sink); + } + for (auto ®istration : impl_->registrations) { + if (registration.stop) { + registration.stop(); + } + registration.sink->flush(); } - sink_->stop(); - sink_->flush(); } - /** - * @brief Format a Boost.Log record for Sunshine log output. - */ - void formatter(const boost::log::record_view &view, boost::log::formatting_ostream &os) { - constexpr const char *message = "Message"; - constexpr const char *severity = "Severity"; - - auto log_level = view.attribute_values()[severity].extract().get(); - - std::string_view log_type; - switch (log_level) { - case 0: - log_type = "Verbose: "sv; - break; - case 1: - log_type = "Debug: "sv; - break; - case 2: - log_type = "Info: "sv; - break; - case 3: - log_type = "Warning: "sv; - break; - case 4: - log_type = "Error: "sv; - break; - case 5: - log_type = "Fatal: "sv; - break; -#ifdef SUNSHINE_TESTS - case 10: - log_type = "Tests: "sv; - break; + std::string format_message(const message_t &message) { + const auto seconds = std::chrono::floor(message.timestamp); + const auto milliseconds = std::chrono::duration_cast(message.timestamp - seconds).count(); + const auto time = std::chrono::system_clock::to_time_t(seconds); + std::tm local_time {}; +#ifdef _WIN32 + localtime_s(&local_time, &time); +#else + localtime_r(&time, &local_time); #endif - }; - - auto now = std::chrono::system_clock::now(); - auto ms = std::chrono::duration_cast( - now - std::chrono::time_point_cast(now) - ); - - auto t = std::chrono::system_clock::to_time_t(now); - auto lt = *std::localtime(&t); - - os << "["sv << std::put_time(<, "%Y-%m-%d %H:%M:%S.") << boost::format("%03u") % ms.count() << "]: "sv - << log_type << view.attribute_values()[message].extract(); + std::ostringstream output; + output << '[' << std::put_time(&local_time, "%Y-%m-%d %H:%M:%S.") + << std::setfill('0') << std::setw(3) << milliseconds + << "]: " << level_name(message.level) << ": " << message.text; + return output.str(); } + + bool is_enabled(level_e level) { + static_cast(level_name(level)); + return static_cast(log_source::get().open_record(bl::keywords::severity = static_cast(level))); + } + + void detail::write(level_e level, const void *context, writer_t writer) { + static_cast(level_name(level)); + auto &source = log_source::get(); + auto record = source.open_record(bl::keywords::severity = static_cast(level)); + if (!record) { + return; + } + std::ostringstream message; + writer(context, message); + bl::record_ostream output {record}; + output << message.view(); + output.flush(); + source.push_record(std::move(record)); + } + + std::unique_ptr add_sink(std::shared_ptr sink, int min_log_level, bool asynchronous) { + if (!sink) { + throw std::invalid_argument {"A logging output must not be null"}; + } + auto backend = boost::make_shared(std::move(sink)); + auto impl = std::make_unique(); + if (asynchronous) { + auto output = boost::make_shared>(backend); + output->set_filter(severity >= min_log_level); + output->set_exception_handler(bl::make_exception_suppressor()); + impl->registrations.push_back({output, [output]() { + output->stop(); + }}); + } else { + auto output = boost::make_shared>(backend); + output->set_filter(severity >= min_log_level); + output->set_exception_handler(bl::make_exception_suppressor()); + impl->registrations.push_back({output, {}}); + } + auto owner = std::unique_ptr {new deinit_t {std::move(impl)}}; + bl::core::get()->add_sink(owner->impl_->registrations.front().sink); + return owner; + } + +#ifdef SUNSHINE_TESTS + testing::scoped_disable_t::scoped_disable_t(): + previous_ {bl::core::get()->get_logging_enabled()} { + bl::core::get()->set_logging_enabled(false); + } + + testing::scoped_disable_t::~scoped_disable_t() { + bl::core::get()->set_logging_enabled(previous_); + } +#endif #ifdef __ANDROID__ namespace sinks = boost::log::sinks; namespace expr = boost::log::expressions; @@ -199,15 +315,21 @@ namespace logging { // This is particularly important when running from a Windows service. sink->locked_backend()->auto_flush(true); - boost::shared_ptr platform_sink; #ifdef __ANDROID__ - platform_sink = boost::make_shared>(); + auto platform_sink = boost::make_shared>(); #endif - auto owner = std::make_unique(sink, platform_sink); + auto impl = std::make_unique(); + impl->registrations.push_back({sink, [sink]() { + sink->stop(); + }}); +#ifdef __ANDROID__ + impl->registrations.push_back({platform_sink, {}}); +#endif + auto owner = std::unique_ptr {new deinit_t {std::move(impl)}}; bl::core::get()->add_sink(sink); - if (platform_sink) { - bl::core::get()->add_sink(platform_sink); - } +#ifdef __ANDROID__ + bl::core::get()->add_sink(platform_sink); +#endif return owner; } @@ -226,16 +348,16 @@ namespace logging { if (level <= AV_LOG_ERROR) { // We print AV_LOG_FATAL at the error level. FFmpeg prints things as fatal that // are expected in some cases, such as lack of codec support or similar things. - BOOST_LOG(error) << buffer.data(); + logging::error(buffer.data()); } else if (level <= AV_LOG_WARNING) { - BOOST_LOG(warning) << buffer.data(); + logging::warning(buffer.data()); } else if (level <= AV_LOG_INFO) { - BOOST_LOG(info) << buffer.data(); + logging::info(buffer.data()); } else if (level <= AV_LOG_VERBOSE) { // AV_LOG_VERBOSE is less verbose than AV_LOG_DEBUG - BOOST_LOG(debug) << buffer.data(); + logging::debug(buffer.data()); } else { - BOOST_LOG(verbose) << buffer.data(); + logging::verbose(buffer.data()); } }); } @@ -249,22 +371,22 @@ namespace logging { display_device::Logger::get().setCustomCallback([](const display_device::Logger::LogLevel level, const std::string &message) { switch (level) { case display_device::Logger::LogLevel::verbose: - BOOST_LOG(verbose) << message; + logging::verbose(message); break; case display_device::Logger::LogLevel::debug: - BOOST_LOG(debug) << message; + logging::debug(message); break; case display_device::Logger::LogLevel::info: - BOOST_LOG(info) << message; + logging::info(message); break; case display_device::Logger::LogLevel::warning: - BOOST_LOG(warning) << message; + logging::warning(message); break; case display_device::Logger::LogLevel::error: - BOOST_LOG(error) << message; + logging::error(message); break; case display_device::Logger::LogLevel::fatal: - BOOST_LOG(fatal) << message; + logging::fatal(message); break; } }); diff --git a/src/logging.h b/src/logging.h index 05fd678dd..9c0abeba3 100644 --- a/src/logging.h +++ b/src/logging.h @@ -5,132 +5,323 @@ #pragma once // standard includes +#include +#include #include #include #include +#include +#include +#include #include +#include #include - -// lib includes -#include -#include -#include -#include +#include +#include /** - * @brief Boost.Log asynchronous text sink used by Sunshine logging. + * @brief Application logging functions and independently registered outputs. + * + * Text and ordinary values can be logged directly. Formatting runs only when + * an output accepts the severity; use a builder to defer expensive arguments. + * @code + * logging::info("Server started"); + * logging::warning("Unknown preset: {}", preset); + * logging::debug([&](std::ostream &output) { + * output << collect_diagnostics(); + * }); + * @endcode */ -using text_sink = boost::log::sinks::asynchronous_sink; - namespace logging { /** - * @brief Boost-managed, thread-safe verbose logging source. + * @brief Severity levels shared by every logging output. */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(verbose_source, boost::log::sources::severity_logger_mt, (0)) - /** - * @brief Boost-managed, thread-safe debug logging source. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(debug_source, boost::log::sources::severity_logger_mt, (1)) - /** - * @brief Boost-managed, thread-safe informational logging source. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(info_source, boost::log::sources::severity_logger_mt, (2)) - /** - * @brief Boost-managed, thread-safe warning logging source. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(warning_source, boost::log::sources::severity_logger_mt, (3)) - /** - * @brief Boost-managed, thread-safe error logging source. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(error_source, boost::log::sources::severity_logger_mt, (4)) - /** - * @brief Boost-managed, thread-safe fatal logging source. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(fatal_source, boost::log::sources::severity_logger_mt, (5)) -#ifdef SUNSHINE_TESTS - /** - * @brief Boost-managed source available only for test output. - */ - BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(tests_source, boost::log::sources::severity_logger_mt, (10)) -#endif - - /** - * @brief Immutable severity handle preserving existing BOOST_LOG call sites. - * - * Boost.Log global storage initializes and synchronizes the mutable source. - */ - class logger_t { - public: - using logger_type = boost::log::sources::severity_logger_mt; ///< Managed source type. - using char_type = logger_type::char_type; ///< Character type required by Boost.Log. - - /** - * @brief Select the managed source for a severity. - * @param severity Default severity for this handle. - */ - constexpr explicit logger_t(int severity): - severity_ {severity} { - } - - /** - * @brief Access the Boost-managed source for this severity. - * - * Resolve the source in the linked logging implementation so shared encoder - * objects use the executable's production or test severity set. - * - * @return Thread-safe logging source. - * @throws std::invalid_argument If this build does not support the severity. - */ - logger_type &get() const; - - /** - * @brief Convert a severity handle for periodic logger construction. - * @return Managed logging source. - */ - operator logger_type &() const { - return get(); - } - - /** - * @brief Open a record using the managed source. - * @return Record accepted by the configured sinks. - */ - boost::log::record open_record() const { - return get().open_record(); - } - - /** - * @brief Open a record with Boost.Log named arguments. - * @param args Named attributes supplied by Boost.Log. - * @return Record accepted by the configured sinks. - */ - template - boost::log::record open_record(const Args &args) const { - return get().open_record(args); - } - - /** - * @brief Submit a completed record to the configured sinks. - * @param record Record to publish. - */ - void push_record(boost::log::record &&record) const { - get().push_record(std::move(record)); - } - - private: - int severity_; ///< Severity selected by the immutable handle. + enum class level_e { + verbose = 0, ///< Verbose diagnostics. + debug = 1, ///< Debug diagnostics. + info = 2, ///< Informational messages. + warning = 3, ///< Recoverable problems. + error = 4, ///< Errors. + fatal = 5, ///< Fatal errors. }; -} // namespace logging -inline constexpr logging::logger_t verbose {0}; ///< Verbose. -inline constexpr logging::logger_t debug {1}; ///< Debug. -inline constexpr logging::logger_t info {2}; ///< Info. -inline constexpr logging::logger_t warning {3}; ///< Warning. -inline constexpr logging::logger_t error {4}; ///< Error. -inline constexpr logging::logger_t fatal {5}; ///< Fatal. + /** + * @brief A structured message delivered to a registered logging sink. + */ + struct message_t { + level_e level; ///< Severity of the message. + std::chrono::system_clock::time_point timestamp; ///< Time the record was opened. + std::string text; ///< UTF-8 message text, without the timestamp or severity prefix. + }; + + /** + * @brief Interface for additional outputs such as a webhook or a test buffer. + */ + class sink_t { + public: + /** + * @brief Destroy a logging output. + */ + virtual ~sink_t() = default; + + /** + * @brief Consume an accepted message on this sink's delivery thread. + * @param message Structured logging message, valid for this call; copy it to retain it. + */ + virtual void consume(const message_t &message) = 0; + }; + + /** + * @brief Format a structured message using Sunshine's timestamp and severity prefix. + * @param message Structured logging message. + * @return A formatted line without an added trailing newline. + */ + std::string format_message(const message_t &message); + + /** + * @brief Check whether any registered output accepts a severity. + * @param level Severity to check. + * @return True when a record at this level is accepted. + * @throws std::invalid_argument If this build does not support the severity. + */ + bool is_enabled(level_e level); + + namespace detail { + /** + * @brief Type-erased, synchronous message writer. + */ + using writer_t = void (*)(const void *, std::ostream &); + + /** + * @brief Open a record and run its writer only when an output accepts it. + * @param level Message severity. + * @param context Writer object borrowed for the duration of the call. + * @param writer Function that writes the message. + */ + void write(level_e level, const void *context, writer_t writer); + } // namespace detail + + /** + * @brief Log a message without evaluating its builder when the severity is disabled. + * @tparam Builder A callable object accepting a standard output stream. + * @param level Message severity. + * @param builder Message builder invoked synchronously at most once. + * @throws std::invalid_argument If this build does not support the severity. + */ + template + requires std::is_object_v && std::invocable + void log(level_e level, const Builder &builder) { + detail::write(level, &builder, [](const void *context, std::ostream &output) { + (*static_cast(context))(output); + }); + } + + /** + * @brief Log an already available message. + * @param level Message severity. + * @param message UTF-8 message text. + */ + inline void log(level_e level, std::string_view message) { + log(level, [message](std::ostream &output) { + output << message; + }); + } + + /** + * @brief Format and log a message when an output accepts its severity. + * @tparam Args Types of the formatting arguments. + * @param level Message severity. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void log(level_e level, std::format_string format, Args &&...args) { + log(level, [&](std::ostream &output) { + output << std::format(format, std::forward(args)...); + }); + } + + /** + * @brief Write a verbose message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void verbose(Message &&message) { + log(level_e::verbose, std::forward(message)); + } + + /** + * @brief Format a verbose message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void verbose(std::format_string format, Args &&...args) { + log(level_e::verbose, format, std::forward(args)...); + } + + /** + * @brief Write a debug message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void debug(Message &&message) { + log(level_e::debug, std::forward(message)); + } + + /** + * @brief Format a debug message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void debug(std::format_string format, Args &&...args) { + log(level_e::debug, format, std::forward(args)...); + } + + /** + * @brief Write an informational message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void info(Message &&message) { + log(level_e::info, std::forward(message)); + } + + /** + * @brief Format an informational message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void info(std::format_string format, Args &&...args) { + log(level_e::info, format, std::forward(args)...); + } + + /** + * @brief Write a warning message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void warning(Message &&message) { + log(level_e::warning, std::forward(message)); + } + + /** + * @brief Format a warning message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void warning(std::format_string format, Args &&...args) { + log(level_e::warning, format, std::forward(args)...); + } + + /** + * @brief Write an error message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void error(Message &&message) { + log(level_e::error, std::forward(message)); + } + + /** + * @brief Format an error message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void error(std::format_string format, Args &&...args) { + log(level_e::error, format, std::forward(args)...); + } + + /** + * @brief Write a fatal message through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void fatal(Message &&message) { + log(level_e::fatal, std::forward(message)); + } + + /** + * @brief Format a fatal message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void fatal(std::format_string format, Args &&...args) { + log(level_e::fatal, format, std::forward(args)...); + } + #ifdef SUNSHINE_TESTS -inline constexpr logging::logger_t tests {10}; ///< Automatic test output. + inline constexpr level_e test_level {static_cast(10)}; ///< Severity reserved for test output. + + /** + * @brief Write a test event through the configured outputs. + * @tparam Message Type of the text or lazy stream builder. + * @param message Text or a lazy stream builder. + */ + template + void tests(Message &&message) { + log(test_level, std::forward(message)); + } + + /** + * @brief Format a test message when its severity is enabled. + * @tparam Args Types of the formatting arguments. + * @param format Compile-time checked format string. + * @param args Formatting arguments; use a builder to defer computing these values. + */ + template + requires(sizeof...(Args) > 0) + void tests(std::format_string format, Args &&...args) { + log(test_level, format, std::forward(args)...); + } + + namespace testing { + /** + * @brief Temporarily disable logging while testing lazy message construction. + */ + class scoped_disable_t { + public: + /** + * @brief Disable logging and remember its previous enabled state. + */ + scoped_disable_t(); + scoped_disable_t(const scoped_disable_t &) = delete; + scoped_disable_t &operator=(const scoped_disable_t &) = delete; + /** + * @brief Restore the logging state that preceded this scope. + */ + ~scoped_disable_t(); + + private: + bool previous_; ///< Enabled state restored when the scope ends. + }; + } // namespace testing #endif +} // namespace logging #include "stat_trackers.h" @@ -184,32 +375,42 @@ namespace logging { */ class deinit_t { public: - /** - * @brief Own the sinks registered by one logging initialization. - * @param sink Asynchronous text sink. - * @param platform_sink Additional platform sink, when present. - */ - deinit_t(boost::shared_ptr sink, boost::shared_ptr platform_sink = {}); - deinit_t(const deinit_t &) = delete; deinit_t &operator=(const deinit_t &) = delete; /** - * @brief Restores logging state when the logging subsystem shuts down. + * @brief Unregister and flush only the outputs owned by this registration. */ ~deinit_t(); private: - boost::shared_ptr sink_; ///< Sink whose registration this owner controls. - boost::shared_ptr platform_sink_; ///< Optional platform sink. + /** + * @brief Backend-specific output ownership. + */ + struct impl_t; + /** + * @brief Take ownership of the registered backend outputs. + * @param impl Backend-specific output ownership. + */ + explicit deinit_t(std::unique_ptr impl); + std::unique_ptr impl_; ///< Backend-specific output ownership. + + friend std::unique_ptr init(int min_log_level, const std::string &log_file); + friend std::unique_ptr add_sink(std::shared_ptr sink, int min_log_level, bool asynchronous); }; /** - * @brief Format a Boost.Log record for Sunshine log output. + * @brief Register an additional output without changing existing logging callers. * - * @param view Boost.Log record view being formatted. - * @param os Boost.Log output stream receiving formatted text. + * Keep the returned owner alive while the output is needed. Destroying it + * unregisters the output and drains any queued messages. + * + * @param sink Output receiving structured messages. + * @param min_log_level Minimum accepted severity. + * @param asynchronous Queue messages for a worker thread when true; flushing may deliver on the caller. + * @return Owner of this output registration. + * @throws std::invalid_argument If the output is null. */ - void formatter(const boost::log::record_view &view, boost::log::formatting_ostream &os); + [[nodiscard]] std::unique_ptr add_sink(std::shared_ptr sink, int min_log_level = 0, bool asynchronous = true); /** * @brief Rotate the current log file and initialize the logging system. @@ -254,7 +455,7 @@ namespace logging { /** * @brief A helper class for tracking and logging numerical values across a period of time * @examples - * min_max_avg_periodic_logger logger(debug, "Test time value", "ms", 5s); + * min_max_avg_periodic_logger logger(level_e::debug, "Test time value", "ms", 5s); * logger.collect_and_log(1); * // ... * logger.collect_and_log(2); @@ -275,12 +476,12 @@ namespace logging { * @param units Unit label appended to tracked numeric values. * @param interval_in_seconds Interval in seconds. */ - min_max_avg_periodic_logger(boost::log::sources::severity_logger_mt &severity, std::string_view message, std::string_view units, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): + min_max_avg_periodic_logger(level_e severity, std::string_view message, std::string_view units, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): severity(severity), message(message), units(units), interval(interval_in_seconds), - enabled(static_cast(severity.open_record())) { + enabled(logging::is_enabled(severity)) { } /** @@ -293,9 +494,13 @@ namespace logging { auto print_info = [&](const T &min_value, const T &max_value, double avg_value) { auto f = stat_trackers::two_digits_after_decimal(); if constexpr (std::is_floating_point_v) { - BOOST_LOG(severity.get()) << message << " (min/max/avg): " << f % min_value << units << "/" << f % max_value << units << "/" << f % avg_value << units; + log(severity, [&](std::ostream &output) { + output << message << " (min/max/avg): " << f % min_value << units << "/" << f % max_value << units << "/" << f % avg_value << units; + }); } else { - BOOST_LOG(severity.get()) << message << " (min/max/avg): " << min_value << units << "/" << max_value << units << "/" << f % avg_value << units; + log(severity, [&](std::ostream &output) { + output << message << " (min/max/avg): " << min_value << units << "/" << max_value << units << "/" << f % avg_value << units; + }); } }; tracker.collect_and_callback_on_interval(value, print_info, interval); @@ -332,7 +537,7 @@ namespace logging { } private: - std::reference_wrapper> severity; + level_e severity; ///< Severity used for periodic messages. std::string message; std::string units; std::chrono::seconds interval; @@ -343,7 +548,7 @@ namespace logging { /** * @brief A helper class for tracking and logging short time intervals across a period of time * @examples - * time_delta_periodic_logger logger(debug, "Test duration", 5s); + * time_delta_periodic_logger logger(level_e::debug, "Test duration", 5s); * logger.first_point_now(); * // ... * logger.second_point_now_and_log(); @@ -364,7 +569,7 @@ namespace logging { * @param message Message text to log or report. * @param interval_in_seconds Interval in seconds. */ - time_delta_periodic_logger(boost::log::sources::severity_logger_mt &severity, std::string_view message, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): + time_delta_periodic_logger(level_e severity, std::string_view message, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): logger(severity, message, "ms", interval_in_seconds) { } diff --git a/src/main.cpp b/src/main.cpp index 9cb9051f4..32c1506c7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -116,7 +116,7 @@ LRESULT CALLBACK SessionMonitorWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, L */ WINAPI BOOL ConsoleCtrlHandler(DWORD type) { if (type == CTRL_CLOSE_EVENT) { - BOOST_LOG(info) << "Console closed handler called"; + logging::info("Console closed handler called"); lifetime::signal_guard_t::native_exit(0, false); } return FALSE; @@ -144,18 +144,18 @@ void mainThreadLoop(const config::settings_t &settings, const std::shared_ptrview(); return; } // Main thread event loop - BOOST_LOG(info) << "Starting main loop"sv; + logging::info("Starting main loop"sv); #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 system_tray::run_tray_until_exit(shutdown_event); #endif - BOOST_LOG(info) << "Main loop has exited"sv; + logging::info("Main loop has exited"sv); } /** @@ -246,13 +246,13 @@ int main(int argc, char *argv[]) { auto log_deinit_guard = logging::init(settings.sunshine.min_log_level, settings.sunshine.log_file); if (!log_deinit_guard) { - BOOST_LOG(error) << "Logging failed to initialize"sv; + logging::error("Logging failed to initialize"sv); } // 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_VERSION << " commit: " << PROJECT_VERSION_COMMIT; + logging::info("{} version: {} commit: {}", PROJECT_NAME, PROJECT_VERSION, PROJECT_VERSION_COMMIT); // Log publisher metadata log_publisher_data(); @@ -264,11 +264,11 @@ int main(int argc, char *argv[]) { if (!settings.sunshine.cmd.name.empty()) { auto fn = cmd_to_func.find(settings.sunshine.cmd.name); if (fn == std::end(cmd_to_func)) { - BOOST_LOG(fatal) << "Unknown command: "sv << settings.sunshine.cmd.name; + logging::fatal("Unknown command: {}", settings.sunshine.cmd.name); - BOOST_LOG(info) << "Possible commands:"sv; + logging::info("Possible commands:"sv); for (auto &[key, _] : cmd_to_func) { - BOOST_LOG(info) << '\t' << key; + logging::info("\t{}", key); } return 7; @@ -290,10 +290,10 @@ int main(int argc, char *argv[]) { http::state_t http_state {configuration}; if (http_state.initialize()) { - BOOST_LOG(fatal) << "HTTP interface failed to initialize"sv; + logging::fatal("HTTP interface failed to initialize"sv); #ifdef _WIN32 - BOOST_LOG(fatal) << "To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv; + logging::fatal("To relaunch Sunshine successfully, use the shortcut in the Start Menu. Do not run Sunshine.exe manually."sv); std::this_thread::sleep_for(10s); #endif @@ -325,10 +325,10 @@ int main(int argc, char *argv[]) { auto shutdown_event = host_mail->event(mail::shutdown); lifetime::signal_guard_t signals {lifetime}; signals.on_signal(SIGINT, [&force_shutdown, &displays, &task_pool, &settings, shutdown_event]() { - BOOST_LOG(info) << "Interrupt handler called"sv; + logging::info("Interrupt handler called"sv); auto task = []() { - BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; + logging::fatal("10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv); logging::log_flush(); lifetime::debug_trap(); }; @@ -345,10 +345,10 @@ int main(int argc, char *argv[]) { }); signals.on_signal(SIGTERM, [&force_shutdown, &displays, &task_pool, &settings, shutdown_event]() { - BOOST_LOG(info) << "Terminate handler called"sv; + logging::info("Terminate handler called"sv); auto task = []() { - BOOST_LOG(fatal) << "10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv; + logging::fatal("10 seconds passed, yet Sunshine's still running: Forcing shutdown"sv); logging::log_flush(); lifetime::debug_trap(); }; @@ -385,7 +385,7 @@ int main(int argc, char *argv[]) { wnd_class.lpfnWndProc = SessionMonitorWindowProc; if (!RegisterClassA(&wnd_class)) { session_monitor_hwnd_promise.set_value(nullptr); - BOOST_LOG(error) << "Failed to register session monitor window class"sv << std::endl; + logging::error("Failed to register session monitor window class\n"); return; } @@ -407,7 +407,7 @@ int main(int argc, char *argv[]) { session_monitor_hwnd_promise.set_value(wnd); if (!wnd) { - BOOST_LOG(error) << "Failed to create session monitor window"sv << std::endl; + logging::error("Failed to create session monitor window\n"); return; } @@ -443,7 +443,7 @@ int main(int argc, char *argv[]) { #endif }; if (!platform.initialize()) { - BOOST_LOG(error) << "Platform failed to initialize"sv; + logging::error("Platform failed to initialize"sv); } // Capture the pre-request state so access granted during this launch causes @@ -457,12 +457,12 @@ int main(int argc, char *argv[]) { inputs.initialize(); if (settings.input.controller && inputs.probe_gamepads()) { - BOOST_LOG(warning) << "No gamepad input is available"sv; + logging::warning("No gamepad input is available"sv); } video::service_t videos {settings, host_mail, infrastructure.cursor(), displays, platform}; if (videos.probe_encoders()) { - BOOST_LOG(error) << "Video failed to find working encoder"sv; + logging::error("Video failed to find working encoder"sv); } std::unique_ptr mDNS; @@ -498,13 +498,13 @@ int main(int argc, char *argv[]) { #ifdef _WIN32 // If we're using the default port and GameStream is enabled, warn the user if (settings.sunshine.port == 47989 && is_gamestream_enabled()) { - BOOST_LOG(fatal) << "GameStream is still enabled in GeForce Experience! This *will* cause streaming problems with Sunshine!"sv; - BOOST_LOG(fatal) << "Disable GameStream on the SHIELD tab in GeForce Experience or change the Port setting on the Advanced tab in the Sunshine Web UI."sv; + logging::fatal("GameStream is still enabled in GeForce Experience! This *will* cause streaming problems with Sunshine!"sv); + logging::fatal("Disable GameStream on the SHIELD tab in GeForce Experience or change the Port setting on the Advanced tab in the Sunshine Web UI."sv); } #endif if (tray_is_enabled && settings.sunshine.system_tray) { - BOOST_LOG(info) << "Starting system tray"sv; + logging::info("Starting system tray"sv); #if defined(_WIN32) || defined(__APPLE__) system_tray::prepare_tray_virtualhid_license(settings); system_tray::prepare_tray_virtualhid_driver(settings); @@ -535,7 +535,7 @@ int main(int argc, char *argv[]) { permission_watcher = std::jthread([&lifetime, &settings](std::stop_token stop) { while (!stop.stop_requested()) { if (platf::required_permissions_granted(platf::get_permission_statuses(settings))) { - BOOST_LOG(info) << "Required permissions granted; restarting Sunshine"sv; + logging::info("Required permissions granted; restarting Sunshine"sv); platf::restart(lifetime); return; } diff --git a/src/network.cpp b/src/network.cpp index 190e226ea..2d764f333 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -248,7 +248,7 @@ namespace net { // Ensure port is in the range of 1024-65535 if (mapped_port < 1024 || mapped_port > 65535) { - BOOST_LOG(warning) << "Port out of range: "sv << mapped_port; + logging::warning("Port out of range: {}", mapped_port); } return mapped_port; diff --git a/src/nvenc/nvenc_base.cpp b/src/nvenc/nvenc_base.cpp index d20ca836c..159a6d437 100644 --- a/src/nvenc/nvenc_base.cpp +++ b/src/nvenc/nvenc_base.cpp @@ -206,20 +206,19 @@ namespace NVENC_NAMESPACE { const auto supported_width = get_encoder_cap(encode_guid, NV_ENC_CAPS_WIDTH_MAX); const auto supported_height = get_encoder_cap(encode_guid, NV_ENC_CAPS_HEIGHT_MAX); if (encoder_params.width > supported_width || encoder_params.height > supported_height) { - BOOST_LOG(error) << "NvEnc: gpu max encode resolution " << supported_width << "x" << supported_height - << ", requested " << encoder_params.width << "x" << encoder_params.height; + logging::error("NvEnc: gpu max encode resolution {}x{}, requested {}x{}", supported_width, supported_height, encoder_params.width, encoder_params.height); return false; } if (buffer_is_10bit(buffer_format) && !get_encoder_cap(encode_guid, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE)) { - BOOST_LOG(error) << "NvEnc: gpu doesn't support 10-bit encode"; + logging::error("NvEnc: gpu doesn't support 10-bit encode"); return false; } if (buffer_is_yuv444(buffer_format) && !get_encoder_cap(encode_guid, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE)) { - BOOST_LOG(error) << "NvEnc: gpu doesn't support YUV444 encode"; + logging::error("NvEnc: gpu doesn't support YUV444 encode"); return false; } if (async_event_handle && !get_encoder_cap(encode_guid, NV_ENC_CAPS_ASYNC_ENCODE_SUPPORT)) { - BOOST_LOG(warning) << "NvEnc: gpu doesn't support async encode"; + logging::warning("NvEnc: gpu doesn't support async encode"); async_event_handle = nullptr; } encoder_params.rfi = get_encoder_cap(encode_guid, NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION); @@ -246,7 +245,7 @@ namespace NVENC_NAMESPACE { } #else if (config.split_frame_encoding == ::nvenc::nvenc_split_frame_encoding::force_enabled) { - BOOST_LOG(warning) << "NvEnc: split-frame encoding requires NVENC API 13.0; ignoring forced mode"; + logging::warning("NvEnc: split-frame encoding requires NVENC API 13.0; ignoring forced mode"); } #endif } @@ -332,7 +331,7 @@ namespace NVENC_NAMESPACE { return; } if (!get_encoder_cap(encode_guid, NV_ENC_CAPS_SUPPORT_INTRA_REFRESH)) { - BOOST_LOG(error) << "NvEnc: Client asked for intra-refresh but the encoder does not support intra-refresh"; + logging::error("NvEnc: Client asked for intra-refresh but the encoder does not support intra-refresh"); return; } format_config.enableIntraRefresh = 1; @@ -345,7 +344,7 @@ namespace NVENC_NAMESPACE { if (get_encoder_cap(encode_guid, NV_ENC_CAPS_SINGLE_SLICE_INTRA_REFRESH)) { format_config.singleSliceIntraRefresh = 1; } else { - BOOST_LOG(warning) << "NvEnc: Single Slice Intra Refresh not supported"; + logging::warning("NvEnc: Single Slice Intra Refresh not supported"); } #endif } @@ -488,21 +487,21 @@ namespace NVENC_NAMESPACE { bool nvenc_base::initialize_encoder_resources(NV_ENC_INITIALIZE_PARAMS &init_params) { if (nvenc_failed(nvenc->nvEncInitializeEncoder(encoder, &init_params))) { - BOOST_LOG(error) << "NvEnc: NvEncInitializeEncoder() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncInitializeEncoder() failed: {}", last_nvenc_error_string); return false; } if (async_event_handle) { NV_ENC_EVENT_PARAMS event_params = {.version = NV_ENC_EVENT_PARAMS_VER}; event_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncRegisterAsyncEvent(encoder, &event_params))) { - BOOST_LOG(error) << "NvEnc: NvEncRegisterAsyncEvent() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncRegisterAsyncEvent() failed: {}", last_nvenc_error_string); return false; } } NV_ENC_CREATE_BITSTREAM_BUFFER create_bitstream_buffer = {.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER}; if (nvenc_failed(nvenc->nvEncCreateBitstreamBuffer(encoder, &create_bitstream_buffer))) { - BOOST_LOG(error) << "NvEnc: NvEncCreateBitstreamBuffer() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncCreateBitstreamBuffer() failed: {}", last_nvenc_error_string); return false; } output_bitstream = create_bitstream_buffer.bitstreamBuffer; @@ -557,9 +556,11 @@ namespace NVENC_NAMESPACE { } #endif - BOOST_LOG(info) << "NvEnc: created encoder v" << NVENC_SDK_VERSION << " " - << video_format_name(client_config.videoFormat) - << quality_preset_string_from_guid(init_params.presetGUID) << extra; + logging::info([&](std::ostream &out) { + out << "NvEnc: created encoder v" << NVENC_SDK_VERSION << " " + << video_format_name(client_config.videoFormat) + << quality_preset_string_from_guid(init_params.presetGUID) << extra; + }); } bool nvenc_base::create_encoder( @@ -581,7 +582,7 @@ namespace NVENC_NAMESPACE { const auto colorspace = nvenc_colorspace_from_sunshine_colorspace(sunshine_colorspace); const auto buffer_format = nvenc_format_from_sunshine_format(sunshine_buffer_format); if (buffer_format == NV_ENC_BUFFER_FORMAT_UNDEFINED) { - BOOST_LOG(error) << "NvEnc: unsupported input pixel format"; + logging::error("NvEnc: unsupported input pixel format"); return false; } encoder_params.width = client_config.width; @@ -594,18 +595,18 @@ namespace NVENC_NAMESPACE { session_params.deviceType = device_type; session_params.apiVersion = NVENCAPI_VERSION; if (nvenc_failed(nvenc->nvEncOpenEncodeSessionEx(&session_params, &encoder))) { - BOOST_LOG(error) << "NvEnc: NvEncOpenEncodeSessionEx() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncOpenEncodeSessionEx() failed: {}", last_nvenc_error_string); return false; } std::uint32_t encode_guid_count = 0; if (nvenc_failed(nvenc->nvEncGetEncodeGUIDCount(encoder, &encode_guid_count))) { - BOOST_LOG(error) << "NvEnc: NvEncGetEncodeGUIDCount() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncGetEncodeGUIDCount() failed: {}", last_nvenc_error_string); return false; } std::vector encode_guids(encode_guid_count); if (nvenc_failed(nvenc->nvEncGetEncodeGUIDs(encoder, encode_guids.data(), static_cast(encode_guids.size()), &encode_guid_count))) { - BOOST_LOG(error) << "NvEnc: NvEncGetEncodeGUIDs() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncGetEncodeGUIDs() failed: {}", last_nvenc_error_string); return false; } @@ -623,11 +624,11 @@ namespace NVENC_NAMESPACE { break; #endif default: - BOOST_LOG(error) << "NvEnc: unknown video format " << client_config.videoFormat; + logging::error("NvEnc: unknown video format {}", client_config.videoFormat); return false; } if (!contains_guid(encode_guids, init_params.encodeGUID)) { - BOOST_LOG(error) << "NvEnc: encoding format is not supported by the gpu"; + logging::error("NvEnc: encoding format is not supported by the gpu"); return false; } if (!validate_encoder_capabilities(init_params.encodeGUID, buffer_format)) { @@ -654,7 +655,7 @@ namespace NVENC_NAMESPACE { .presetCfg = {.version = NV_ENC_CONFIG_VER}, }; if (nvenc_failed(nvenc->nvEncGetEncodePresetConfigEx(encoder, init_params.encodeGUID, init_params.presetGUID, init_params.tuningInfo, &preset_config))) { - BOOST_LOG(error) << "NvEnc: NvEncGetEncodePresetConfigEx() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncGetEncodePresetConfigEx() failed: {}", last_nvenc_error_string); return false; } @@ -668,8 +669,10 @@ namespace NVENC_NAMESPACE { } auto frame_size_format = stat_trackers::two_digits_after_decimal(); - BOOST_LOG(debug) << "NvEnc: requested encoded frame size " - << frame_size_format % (client_config.bitrate / 8. / client_config.framerate) << " kB"; + logging::debug([&](std::ostream &out) { + out << "NvEnc: requested encoded frame size " + << frame_size_format % (client_config.bitrate / 8. / client_config.framerate) << " kB"; + }); log_created_encoder(init_params, enc_config, config, client_config, buffer_format); encoder_state = {}; @@ -680,7 +683,7 @@ namespace NVENC_NAMESPACE { void nvenc_base::destroy_encoder() { if (output_bitstream) { if (nvenc_failed(nvenc->nvEncDestroyBitstreamBuffer(encoder, output_bitstream))) { - BOOST_LOG(error) << "NvEnc: NvEncDestroyBitstreamBuffer() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncDestroyBitstreamBuffer() failed: {}", last_nvenc_error_string); } output_bitstream = nullptr; } @@ -688,18 +691,18 @@ namespace NVENC_NAMESPACE { NV_ENC_EVENT_PARAMS event_params = {.version = NV_ENC_EVENT_PARAMS_VER}; event_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncUnregisterAsyncEvent(encoder, &event_params))) { - BOOST_LOG(error) << "NvEnc: NvEncUnregisterAsyncEvent() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncUnregisterAsyncEvent() failed: {}", last_nvenc_error_string); } } if (registered_input_buffer) { if (nvenc_failed(nvenc->nvEncUnregisterResource(encoder, registered_input_buffer))) { - BOOST_LOG(error) << "NvEnc: NvEncUnregisterResource() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncUnregisterResource() failed: {}", last_nvenc_error_string); } registered_input_buffer = nullptr; } if (encoder) { if (nvenc_failed(nvenc->nvEncDestroyEncoder(encoder))) { - BOOST_LOG(error) << "NvEnc: NvEncDestroyEncoder() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncDestroyEncoder() failed: {}", last_nvenc_error_string); } encoder = nullptr; } @@ -717,7 +720,7 @@ namespace NVENC_NAMESPACE { assert(output_bitstream); if (!synchronize_input_buffer()) { - BOOST_LOG(error) << "NvEnc: failed to synchronize input buffer"; + logging::error("NvEnc: failed to synchronize input buffer"); return {}; } @@ -725,12 +728,12 @@ namespace NVENC_NAMESPACE { mapped_input_buffer.registeredResource = registered_input_buffer; if (nvenc_failed(nvenc->nvEncMapInputResource(encoder, &mapped_input_buffer))) { - BOOST_LOG(error) << "NvEnc: NvEncMapInputResource() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncMapInputResource() failed: {}", last_nvenc_error_string); return {}; } auto unmap_guard = util::fail_guard([&] { if (nvenc_failed(nvenc->nvEncUnmapInputResource(encoder, mapped_input_buffer.mappedResource))) { - BOOST_LOG(error) << "NvEnc: NvEncUnmapInputResource() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncUnmapInputResource() failed: {}", last_nvenc_error_string); } }); @@ -746,7 +749,7 @@ namespace NVENC_NAMESPACE { pic_params.completionEvent = async_event_handle; if (nvenc_failed(nvenc->nvEncEncodePicture(encoder, &pic_params))) { - BOOST_LOG(error) << "NvEnc: NvEncEncodePicture() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncEncodePicture() failed: {}", last_nvenc_error_string); return {}; } @@ -755,12 +758,12 @@ namespace NVENC_NAMESPACE { lock_bitstream.doNotWait = async_event_handle ? 1 : 0; if (async_event_handle && !wait_for_async_event(100)) { - BOOST_LOG(error) << "NvEnc: frame " << frame_index << " encode wait timeout"; + logging::error("NvEnc: frame {} encode wait timeout", frame_index); return {}; } if (nvenc_failed(nvenc->nvEncLockBitstream(encoder, &lock_bitstream))) { - BOOST_LOG(error) << "NvEnc: NvEncLockBitstream() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncLockBitstream() failed: {}", last_nvenc_error_string); return {}; } @@ -780,11 +783,11 @@ namespace NVENC_NAMESPACE { encoder_state.last_encoded_frame_index = frame_index; if (encoded_frame.idr) { - BOOST_LOG(debug) << "NvEnc: idr frame " << encoded_frame.frame_index; + logging::debug("NvEnc: idr frame {}", encoded_frame.frame_index); } if (nvenc_failed(nvenc->nvEncUnlockBitstream(encoder, lock_bitstream.outputBitstream))) { - BOOST_LOG(error) << "NvEnc: NvEncUnlockBitstream() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncUnlockBitstream() failed: {}", last_nvenc_error_string); } encoder_state.frame_size_logger.collect_and_log(encoded_frame.data.size() / 1000.); @@ -798,30 +801,30 @@ namespace NVENC_NAMESPACE { } if (first_frame >= encoder_state.last_rfi_range.first && last_frame <= encoder_state.last_rfi_range.second) { - BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " already done"; + logging::debug("NvEnc: rfi request {}-{} already done", first_frame, last_frame); return true; } encoder_state.rfi_needs_confirmation = true; if (last_frame < first_frame) { - BOOST_LOG(error) << "NvEnc: invaid rfi request " << first_frame << "-" << last_frame << ", generating IDR"; + logging::error("NvEnc: invaid rfi request {}-{}, generating IDR", first_frame, last_frame); return false; } - BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " expanding to last encoded frame " << encoder_state.last_encoded_frame_index; + logging::debug("NvEnc: rfi request {}-{} expanding to last encoded frame {}", first_frame, last_frame, encoder_state.last_encoded_frame_index); last_frame = encoder_state.last_encoded_frame_index; encoder_state.last_rfi_range = {first_frame, last_frame}; if (last_frame - first_frame + 1 >= encoder_params.ref_frames_in_dpb) { - BOOST_LOG(debug) << "NvEnc: rfi request too large, generating IDR"; + logging::debug("NvEnc: rfi request too large, generating IDR"); return false; } for (auto i = first_frame; i <= last_frame; i++) { if (nvenc_failed(nvenc->nvEncInvalidateRefFrames(encoder, i))) { - BOOST_LOG(error) << "NvEnc: NvEncInvalidateRefFrames() " << i << " failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncInvalidateRefFrames() {} failed: {}", i, last_nvenc_error_string); return false; } } diff --git a/src/nvenc/nvenc_base.h b/src/nvenc/nvenc_base.h index 8f9c8b01b..90818815b 100644 --- a/src/nvenc/nvenc_base.h +++ b/src/nvenc/nvenc_base.h @@ -334,7 +334,7 @@ namespace NVENC_NAMESPACE { uint64_t last_encoded_frame_index = 0; bool rfi_needs_confirmation = false; std::pair last_rfi_range; - logging::min_max_avg_periodic_logger frame_size_logger = {debug, "NvEnc: encoded frame sizes in kB", ""}; + logging::min_max_avg_periodic_logger frame_size_logger = {logging::level_e::debug, "NvEnc: encoded frame sizes in kB", ""}; } encoder_state; }; diff --git a/src/nvenc/nvenc_d3d11.cpp b/src/nvenc/nvenc_d3d11.cpp index 64829e25e..3f52295cf 100644 --- a/src/nvenc/nvenc_d3d11.cpp +++ b/src/nvenc/nvenc_d3d11.cpp @@ -31,14 +31,14 @@ namespace NVENC_NAMESPACE { GetProcAddress(dll.get(), "NvEncodeAPICreateInstance") ); if (!create_instance) { - BOOST_LOG(error) << "NvEnc: No NvEncodeAPICreateInstance() in NVENC driver library"; + logging::error("NvEnc: No NvEncodeAPICreateInstance() in NVENC driver library"); return false; } auto new_nvenc = std::make_unique(); new_nvenc->version = NV_ENCODE_API_FUNCTION_LIST_VER; if (nvenc_failed(create_instance(new_nvenc.get()))) { - BOOST_LOG(error) << "NvEnc: NvEncodeAPICreateInstance() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncodeAPICreateInstance() failed: {}", last_nvenc_error_string); return false; } diff --git a/src/nvenc/nvenc_d3d11_native.cpp b/src/nvenc/nvenc_d3d11_native.cpp index 32fe16053..0cf6b60b4 100644 --- a/src/nvenc/nvenc_d3d11_native.cpp +++ b/src/nvenc/nvenc_d3d11_native.cpp @@ -30,7 +30,7 @@ namespace NVENC_NAMESPACE { bool nvenc_d3d11_native::create_and_register_input_buffer() { if (encoder_params.buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT) { - BOOST_LOG(error) << "NvEnc: 10-bit 4:4:4 encoding is incompatible with D3D11 surface formats, use CUDA interop"; + logging::error("NvEnc: 10-bit 4:4:4 encoding is incompatible with D3D11 surface formats, use CUDA interop"); return false; } @@ -45,7 +45,7 @@ namespace NVENC_NAMESPACE { desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (d3d_device->CreateTexture2D(&desc, nullptr, &d3d_input_texture) != S_OK) { - BOOST_LOG(error) << "NvEnc: couldn't create input texture"; + logging::error("NvEnc: couldn't create input texture"); return false; } } @@ -60,7 +60,7 @@ namespace NVENC_NAMESPACE { register_resource.bufferUsage = NV_ENC_INPUT_IMAGE; if (nvenc_failed(nvenc->nvEncRegisterResource(encoder, ®ister_resource))) { - BOOST_LOG(error) << "NvEnc: NvEncRegisterResource() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncRegisterResource() failed: {}", last_nvenc_error_string); return false; } diff --git a/src/nvenc/nvenc_d3d11_on_cuda.cpp b/src/nvenc/nvenc_d3d11_on_cuda.cpp index 6738957da..af91793c2 100644 --- a/src/nvenc/nvenc_d3d11_on_cuda.cpp +++ b/src/nvenc/nvenc_d3d11_on_cuda.cpp @@ -27,21 +27,21 @@ namespace NVENC_NAMESPACE { if (cuda_d3d_input_texture) { if (cuda_failed(cuda_functions.cuGraphicsUnregisterResource(cuda_d3d_input_texture))) { - BOOST_LOG(error) << "NvEnc: cuGraphicsUnregisterResource() failed: error " << last_cuda_error; + logging::error("NvEnc: cuGraphicsUnregisterResource() failed: error {}", static_cast(last_cuda_error)); } cuda_d3d_input_texture = nullptr; } if (cuda_surface) { if (cuda_failed(cuda_functions.cuMemFree(cuda_surface))) { - BOOST_LOG(error) << "NvEnc: cuMemFree() failed: error " << last_cuda_error; + logging::error("NvEnc: cuMemFree() failed: error {}", static_cast(last_cuda_error)); } cuda_surface = 0; } } if (cuda_failed(cuda_functions.cuCtxDestroy(cuda_context))) { - BOOST_LOG(error) << "NvEnc: cuCtxDestroy() failed: error " << last_cuda_error; + logging::error("NvEnc: cuCtxDestroy() failed: error {}", static_cast(last_cuda_error)); } cuda_context = nullptr; } @@ -69,12 +69,12 @@ namespace NVENC_NAMESPACE { return location != nullptr; }; if (!load_function(cuda_functions.cuInit, "cuInit") || !load_function(cuda_functions.cuD3D11GetDevice, "cuD3D11GetDevice") || !load_function(cuda_functions.cuCtxCreate, "cuCtxCreate_v2") || !load_function(cuda_functions.cuCtxDestroy, "cuCtxDestroy_v2") || !load_function(cuda_functions.cuCtxPushCurrent, "cuCtxPushCurrent_v2") || !load_function(cuda_functions.cuCtxPopCurrent, "cuCtxPopCurrent_v2") || !load_function(cuda_functions.cuMemAllocPitch, "cuMemAllocPitch_v2") || !load_function(cuda_functions.cuMemFree, "cuMemFree_v2") || !load_function(cuda_functions.cuGraphicsD3D11RegisterResource, "cuGraphicsD3D11RegisterResource") || !load_function(cuda_functions.cuGraphicsUnregisterResource, "cuGraphicsUnregisterResource") || !load_function(cuda_functions.cuGraphicsMapResources, "cuGraphicsMapResources") || !load_function(cuda_functions.cuGraphicsUnmapResources, "cuGraphicsUnmapResources") || !load_function(cuda_functions.cuGraphicsSubResourceGetMappedArray, "cuGraphicsSubResourceGetMappedArray") || !load_function(cuda_functions.cuMemcpy2D, "cuMemcpy2D_v2")) { - BOOST_LOG(error) << "NvEnc: missing CUDA functions in " << dll_name; + logging::error("NvEnc: missing CUDA functions in {}", dll_name); FreeLibrary(cuda_functions.dll); cuda_functions = {}; } } else { - BOOST_LOG(debug) << "NvEnc: couldn't load CUDA dynamic library " << dll_name; + logging::debug("NvEnc: couldn't load CUDA dynamic library {}", dll_name); } if (cuda_functions.dll) { @@ -85,10 +85,10 @@ namespace NVENC_NAMESPACE { if (cuda_succeeded(cuda_functions.cuInit(0)) && cuda_succeeded(cuda_functions.cuD3D11GetDevice(&cuda_device, dxgi_adapter)) && cuda_succeeded(cuda_functions.cuCtxCreate(&cuda_context, CU_CTX_SCHED_BLOCKING_SYNC, cuda_device)) && cuda_succeeded(cuda_functions.cuCtxPopCurrent(&cuda_context))) { device = cuda_context; } else { - BOOST_LOG(error) << "NvEnc: couldn't create CUDA interop context: error " << last_cuda_error; + logging::error("NvEnc: couldn't create CUDA interop context: error {}", static_cast(last_cuda_error)); } } else { - BOOST_LOG(error) << "NvEnc: couldn't get DXGI adapter for CUDA interop"; + logging::error("NvEnc: couldn't get DXGI adapter for CUDA interop"); } } @@ -97,7 +97,7 @@ namespace NVENC_NAMESPACE { bool nvenc_d3d11_on_cuda::create_and_register_input_buffer() { if (encoder_params.buffer_format != NV_ENC_BUFFER_FORMAT_YUV444_10BIT) { - BOOST_LOG(error) << "NvEnc: CUDA interop is expected to be used only for 10-bit 4:4:4 encoding"; + logging::error("NvEnc: CUDA interop is expected to be used only for 10-bit 4:4:4 encoding"); return false; } @@ -113,7 +113,7 @@ namespace NVENC_NAMESPACE { desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (d3d_device->CreateTexture2D(&desc, nullptr, &d3d_input_texture) != S_OK) { - BOOST_LOG(error) << "NvEnc: couldn't create input texture"; + logging::error("NvEnc: couldn't create input texture"); return false; } } @@ -126,7 +126,7 @@ namespace NVENC_NAMESPACE { if (!cuda_d3d_input_texture) { if (cuda_failed(cuda_functions.cuGraphicsD3D11RegisterResource(&cuda_d3d_input_texture, d3d_input_texture, CU_GRAPHICS_REGISTER_FLAGS_NONE))) { - BOOST_LOG(error) << "NvEnc: cuGraphicsD3D11RegisterResource() failed: error " << last_cuda_error; + logging::error("NvEnc: cuGraphicsD3D11RegisterResource() failed: error {}", static_cast(last_cuda_error)); return false; } } @@ -137,7 +137,7 @@ namespace NVENC_NAMESPACE { encoder_params.width * 2, encoder_params.height * 3, 16))) { - BOOST_LOG(error) << "NvEnc: cuMemAllocPitch() failed: error " << last_cuda_error; + logging::error("NvEnc: cuMemAllocPitch() failed: error {}", static_cast(last_cuda_error)); return false; } } @@ -154,7 +154,7 @@ namespace NVENC_NAMESPACE { register_resource.bufferUsage = NV_ENC_INPUT_IMAGE; if (nvenc_failed(nvenc->nvEncRegisterResource(encoder, ®ister_resource))) { - BOOST_LOG(error) << "NvEnc: NvEncRegisterResource() failed: " << last_nvenc_error_string; + logging::error("NvEnc: NvEncRegisterResource() failed: {}", last_nvenc_error_string); return false; } @@ -171,13 +171,13 @@ namespace NVENC_NAMESPACE { } if (cuda_failed(cuda_functions.cuGraphicsMapResources(1, &cuda_d3d_input_texture, 0))) { - BOOST_LOG(error) << "NvEnc: cuGraphicsMapResources() failed: error " << last_cuda_error; + logging::error("NvEnc: cuGraphicsMapResources() failed: error {}", static_cast(last_cuda_error)); return false; } auto unmap = [&]() -> bool { if (cuda_failed(cuda_functions.cuGraphicsUnmapResources(1, &cuda_d3d_input_texture, 0))) { - BOOST_LOG(error) << "NvEnc: cuGraphicsUnmapResources() failed: error " << last_cuda_error; + logging::error("NvEnc: cuGraphicsUnmapResources() failed: error {}", static_cast(last_cuda_error)); return false; } return true; @@ -186,7 +186,7 @@ namespace NVENC_NAMESPACE { CUarray input_texture_array; if (cuda_failed(cuda_functions.cuGraphicsSubResourceGetMappedArray(&input_texture_array, cuda_d3d_input_texture, 0, 0))) { - BOOST_LOG(error) << "NvEnc: cuGraphicsSubResourceGetMappedArray() failed: error " << last_cuda_error; + logging::error("NvEnc: cuGraphicsSubResourceGetMappedArray() failed: error {}", static_cast(last_cuda_error)); return false; } @@ -202,7 +202,7 @@ namespace NVENC_NAMESPACE { copy_params.Height = encoder_params.height * 3; if (cuda_failed(cuda_functions.cuMemcpy2D(©_params))) { - BOOST_LOG(error) << "NvEnc: cuMemcpy2D() failed: error " << last_cuda_error; + logging::error("NvEnc: cuMemcpy2D() failed: error {}", static_cast(last_cuda_error)); return false; } } @@ -225,7 +225,7 @@ namespace NVENC_NAMESPACE { if (pushed_context) { CUcontext popped_context; if (parent.cuda_failed(parent.cuda_functions.cuCtxPopCurrent(&popped_context))) { - BOOST_LOG(error) << "NvEnc: cuCtxPopCurrent() failed: error " << parent.last_cuda_error; + logging::error("NvEnc: cuCtxPopCurrent() failed: error {}", static_cast(parent.last_cuda_error)); } } } @@ -234,7 +234,7 @@ namespace NVENC_NAMESPACE { if (cuda_context && cuda_succeeded(cuda_functions.cuCtxPushCurrent(cuda_context))) { return {*this, cuda_context}; } else { - BOOST_LOG(error) << "NvEnc: cuCtxPushCurrent() failed: error " << last_cuda_error; + logging::error("NvEnc: cuCtxPushCurrent() failed: error {}", static_cast(last_cuda_error)); return {*this, nullptr}; } } diff --git a/src/nvenc/nvenc_dynamic_factory.cpp b/src/nvenc/nvenc_dynamic_factory.cpp index 4e4a0c905..df77deef8 100644 --- a/src/nvenc/nvenc_dynamic_factory.cpp +++ b/src/nvenc/nvenc_dynamic_factory.cpp @@ -59,7 +59,7 @@ namespace nvenc { std::shared_ptr nvenc_dynamic_factory::get(const nvenc_runtime_api &runtime_api) { auto dll = runtime_api.load_driver(); if (!dll) { - BOOST_LOG(debug) << "NvEnc: Couldn't load NvEnc library " << nvenc_dll_name; + logging::debug("NvEnc: Couldn't load NvEnc library {}", nvenc_dll_name); return {}; } @@ -67,13 +67,13 @@ namespace nvenc { runtime_api.get_symbol(dll.get(), "NvEncodeAPIGetMaxSupportedVersion") ); if (!get_max_version) { - BOOST_LOG(error) << "NvEnc: No NvEncodeAPIGetMaxSupportedVersion() in " << nvenc_dll_name; + logging::error("NvEnc: No NvEncodeAPIGetMaxSupportedVersion() in {}", nvenc_dll_name); return {}; } std::uint32_t packed_max_version = 0; if (get_max_version(&packed_max_version) != 0U) { - BOOST_LOG(error) << "NvEnc: NvEncodeAPIGetMaxSupportedVersion() failed"; + logging::error("NvEnc: NvEncodeAPIGetMaxSupportedVersion() failed"); return {}; } @@ -114,7 +114,7 @@ namespace nvenc { case nvenc_sdk_version::unsupported: default: - BOOST_LOG(error) << "NvEnc: minimum required driver version is " << minimum_driver_version; + logging::error("NvEnc: minimum required driver version is {}", minimum_driver_version); return {}; } } diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 46f27c8f7..5dc8d9c1c 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -319,7 +320,7 @@ namespace nvhttp { try { pt::read_json(settings.nvhttp.file_state, root); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't read "sv << settings.nvhttp.file_state << ": "sv << e.what(); + logging::error("Couldn't read {}: {}", settings.nvhttp.file_state, e.what()); return; } } @@ -344,7 +345,7 @@ namespace nvhttp { try { pt::write_json(settings.nvhttp.file_state, root); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't write "sv << settings.nvhttp.file_state << ": "sv << e.what(); + logging::error("Couldn't write {}: {}", settings.nvhttp.file_state, e.what()); return; } } @@ -374,7 +375,7 @@ namespace nvhttp { auto certificate = crypto::x509(named_cert.cert); if (!certificate) { - BOOST_LOG(warning) << "Ignoring invalid paired-client certificate"sv; + logging::warning("Ignoring invalid paired-client certificate"sv); continue; } @@ -423,7 +424,7 @@ namespace nvhttp { */ void load_state() { if (!fs::exists(settings.nvhttp.file_state)) { - BOOST_LOG(info) << "File "sv << settings.nvhttp.file_state << " doesn't exist"sv; + logging::info("File {} doesn't exist", settings.nvhttp.file_state); http_state.set_unique_id(uuid_util::uuid_t::generate().string()); return; } @@ -432,7 +433,7 @@ namespace nvhttp { try { pt::read_json(settings.nvhttp.file_state, tree); } catch (std::exception &e) { - BOOST_LOG(error) << "Couldn't read "sv << settings.nvhttp.file_state << ": "sv << e.what(); + logging::error("Couldn't read {}: {}", settings.nvhttp.file_state, e.what()); return; } @@ -962,22 +963,22 @@ namespace nvhttp { */ template void print_req(std::shared_ptr::Request> request) { - BOOST_LOG(debug) << "TUNNEL :: "sv << (std::is_same_v ? "HTTPS"sv : "NONE"sv); + logging::debug("TUNNEL :: {}", (std::is_same_v ? "HTTPS"sv : "NONE"sv)); - BOOST_LOG(debug) << "METHOD :: "sv << request->method; - BOOST_LOG(debug) << "DESTINATION :: "sv << request->path; + logging::debug("METHOD :: {}", request->method); + logging::debug("DESTINATION :: {}", request->path); for (auto &[name, val] : request->header) { - BOOST_LOG(debug) << name << " -- " << val; + logging::debug("{} -- {}", name, val); } - BOOST_LOG(debug) << " [--] "sv; + logging::debug(" [--] "sv); for (auto &[name, val] : request->parse_query_string()) { - BOOST_LOG(debug) << name << " -- " << val; + logging::debug("{} -- {}", name, val); } - BOOST_LOG(debug) << " [--] "sv; + logging::debug(" [--] "sv); } /** @@ -1031,7 +1032,7 @@ namespace nvhttp { sess.async_insert_pin.device_name = get_arg(args, "devicename"); sess.async_insert_pin.address = net::addr_to_normalized_string(request->remote_endpoint().address()); - BOOST_LOG(debug) << sess.client.cert; + logging::debug("{}", sess.client.cert); const bool pin_stdin = settings.sunshine.flags[config::flag::PIN_STDIN]; if (!pin_stdin) { sess.async_insert_pin.response = response; @@ -1405,7 +1406,7 @@ namespace nvhttp { std::ostringstream data; if (tree.empty()) { - BOOST_LOG(error) << EMPTY_PROPERTY_TREE_ERROR_MSG; + logging::error(EMPTY_PROPERTY_TREE_ERROR_MSG); } pt::write_xml(data, tree); @@ -1469,7 +1470,7 @@ namespace nvhttp { auto encryption_mode = net::encryption_mode_for_address(settings, request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { - BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; + logging::error("Rejecting client that cannot comply with mandatory encryption requirement"sv); tree.put("root..status_code", 403); tree.put("root..status_message", "Encryption is mandatory for this host but unsupported by the client"); @@ -1522,7 +1523,7 @@ namespace nvhttp { std::ostringstream data; if (tree.empty()) { - BOOST_LOG(error) << EMPTY_PROPERTY_TREE_ERROR_MSG; + logging::error(EMPTY_PROPERTY_TREE_ERROR_MSG); } pt::write_xml(data, tree); @@ -1581,7 +1582,7 @@ namespace nvhttp { auto encryption_mode = net::encryption_mode_for_address(settings, request->remote_endpoint().address()); if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { - BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; + logging::error("Rejecting client that cannot comply with mandatory encryption requirement"sv); tree.put("root..status_code", 403); tree.put("root..status_message", "Encryption is mandatory for this host but unsupported by the client"); @@ -1703,7 +1704,7 @@ namespace nvhttp { #endif }; if (!x509) { - BOOST_LOG(info) << "unknown -- denied"sv; + logging::info("unknown -- denied"sv); return 0; } @@ -1714,13 +1715,13 @@ namespace nvhttp { X509_NAME_oneline(X509_get_subject_name(x509.get()), subject_name.data(), subject_name.size()); - BOOST_LOG(debug) << subject_name.data() << " -- "sv << (verified ? "verified"sv : "denied"sv); + logging::debug("{} -- {}", subject_name.data(), (verified ? "verified"sv : "denied"sv)); }); std::lock_guard lock {client_auth_mutex()}; auto err_str = verify_client_certificate(x509.get()); if (err_str) { - BOOST_LOG(warning) << "SSL Verification error :: "sv << err_str; + logging::warning("SSL Verification error :: {}", err_str); return verified; } @@ -1729,7 +1730,7 @@ namespace nvhttp { auto pem = crypto::pem(x509); auto [enabled, client_name] = get_client_status(pem); if (!enabled) { - BOOST_LOG(info) << "Client is disabled -- denied"sv; + logging::info("Client is disabled -- denied"sv); return verified; } @@ -1809,7 +1810,7 @@ namespace nvhttp { return; } - BOOST_LOG(fatal) << "Couldn't start http server on ports ["sv << port_https << ", "sv << port_https << "]: "sv << err.what(); + logging::fatal("Couldn't start http server on ports [{}, {}]: {}", port_https, port_https, err.what()); shutdown_event->raise(true); return; } diff --git a/src/platform/common.h b/src/platform/common.h index 40629f69b..e1bcd95c3 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -634,7 +634,7 @@ namespace platf { * @return Status from updating frame. */ virtual int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) { - BOOST_LOG(error) << "Illegal call to hwdevice_t::set_frame(). Did you forget to override it?"; + logging::error("Illegal call to hwdevice_t::set_frame(). Did you forget to override it?"); return -1; }; @@ -816,7 +816,7 @@ namespace platf { protected: // collect capture timing data (at loglevel debug) - logging::time_delta_periodic_logger sleep_overshoot_logger = {debug, "Frame capture sleep overshoot"}; ///< Periodic logger for capture sleep overshoot measurements. + logging::time_delta_periodic_logger sleep_overshoot_logger = {logging::level_e::debug, "Frame capture sleep overshoot"}; ///< Periodic logger for capture sleep overshoot measurements. }; /** diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index c6a1a999b..336a4b0de 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -59,7 +59,7 @@ namespace platf { ss << " sink_properties=device.description="sv << name; auto result = ss.str(); - BOOST_LOG(debug) << "null-sink args: "sv << result; + logging::debug("null-sink args: {}", result); return result; } @@ -81,7 +81,7 @@ namespace platf { auto buf = sample_buf.data(); int status; if (pa_simple_read(mic.get(), buf, sample_size * sizeof(float), &status)) { - BOOST_LOG(error) << "pa_simple_read() failed: "sv << pa_strerror(status); + logging::error("pa_simple_read() failed: {}", pa_strerror(status)); return capture_e::error; } @@ -142,7 +142,7 @@ namespace platf { // pa_channel_map pa_map; if (!fill_canonical_channel_map(channels, pa_map)) { - BOOST_LOG(error) << "Unsupported channel count for audio capture: "sv << channels; + logging::error("Unsupported channel count for audio capture: {}", channels); return nullptr; } @@ -166,7 +166,7 @@ namespace platf { if (!mic->mic) { auto err_str = pa_strerror(status); - BOOST_LOG(error) << "pa_simple_new() failed: "sv << err_str; + logging::error("pa_simple_new() failed: {}", err_str); return nullptr; } @@ -370,15 +370,15 @@ namespace platf { events->raise(ready); break; case PA_CONTEXT_TERMINATED: - BOOST_LOG(debug) << "PulseAudio context terminated"sv; + logging::debug("PulseAudio context terminated"sv); events->raise(terminated); break; case PA_CONTEXT_FAILED: - BOOST_LOG(debug) << "PulseAudio context failed"sv; + logging::debug("PulseAudio context failed"sv); events->raise(failed); break; case PA_CONTEXT_CONNECTING: - BOOST_LOG(debug) << "Connecting to pulseaudio"sv; + logging::debug("Connecting to pulseaudio"sv); case PA_CONTEXT_UNCONNECTED: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: @@ -390,7 +390,7 @@ namespace platf { auto status = pa_context_connect(ctx.get(), nullptr, PA_CONTEXT_NOFLAGS, nullptr); if (status) { - BOOST_LOG(error) << "Couldn't connect to pulseaudio: "sv << pa_strerror(status); + logging::error("Couldn't connect to pulseaudio: {}", pa_strerror(status)); return -1; } @@ -401,7 +401,7 @@ namespace platf { auto status = pa_mainloop_run(loop, &retval); if (status < 0) { - BOOST_LOG(error) << "Couldn't run pulseaudio main loop"sv; + logging::error("Couldn't run pulseaudio main loop"sv); return; } }, @@ -461,7 +461,7 @@ namespace platf { alarm->wait(); if (*alarm->status()) { - BOOST_LOG(error) << "Couldn't unload null-sink with index ["sv << i << "]: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::error("Couldn't unload null-sink with index [{}]: {}", i, pa_strerror(pa_context_errno(ctx.get()))); return -1; } @@ -488,7 +488,7 @@ namespace platf { cb_t f = [&](ctx_t::pointer ctx, const pa_sink_info *sink_info, int eol) { if (!sink_info) { if (!eol) { - BOOST_LOG(error) << "Couldn't get pulseaudio sink info: "sv << pa_strerror(pa_context_errno(ctx)); + logging::error("Couldn't get pulseaudio sink info: {}", pa_strerror(pa_context_errno(ctx))); alarm->ring(-1); } @@ -516,7 +516,7 @@ namespace platf { op_t op {pa_context_get_sink_info_list(ctx.get(), cb, &f)}; if (!op) { - BOOST_LOG(error) << "Couldn't create card info operation: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::error("Couldn't create card info operation: {}", pa_strerror(pa_context_errno(ctx.get()))); return std::nullopt; } @@ -533,7 +533,7 @@ namespace platf { if (index.stereo == PA_INVALID_INDEX) { index.stereo = load_null(stereo, speaker::map_stereo.data(), static_cast(speaker::map_stereo.size())); if (index.stereo == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for stereo: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::warning("Couldn't create virtual sink for stereo: {}", pa_strerror(pa_context_errno(ctx.get()))); } else { ++nullcount; } @@ -542,7 +542,7 @@ namespace platf { if (index.surround51 == PA_INVALID_INDEX) { index.surround51 = load_null(surround51, speaker::map_surround51.data(), static_cast(speaker::map_surround51.size())); if (index.surround51 == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-51: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::warning("Couldn't create virtual sink for surround-51: {}", pa_strerror(pa_context_errno(ctx.get()))); } else { ++nullcount; } @@ -551,14 +551,14 @@ namespace platf { if (index.surround71 == PA_INVALID_INDEX) { index.surround71 = load_null(surround71, speaker::map_surround71.data(), static_cast(speaker::map_surround71.size())); if (index.surround71 == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-71: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::warning("Couldn't create virtual sink for surround-71: {}", pa_strerror(pa_context_errno(ctx.get()))); } else { ++nullcount; } } if (sink_name.empty()) { - BOOST_LOG(warning) << "Couldn't find an active default sink. Continuing with virtual audio only."sv; + logging::warning("Couldn't find an active default sink. Continuing with virtual audio only."sv); } if (nullcount == 3) { @@ -579,7 +579,7 @@ namespace platf { cb_simple_t server_f = [&](ctx_t::pointer ctx, const pa_server_info *server_info) { if (!server_info) { - BOOST_LOG(error) << "Couldn't get pulseaudio server info: "sv << pa_strerror(pa_context_errno(ctx)); + logging::error("Couldn't get pulseaudio server info: {}", pa_strerror(pa_context_errno(ctx))); alarm->ring(-1); } @@ -612,8 +612,7 @@ namespace platf { cb_t sink_f = [&](ctx_t::pointer ctx, const pa_sink_info *sink_info, int eol) { if (!sink_info) { if (!eol) { - BOOST_LOG(error) << "Couldn't get pulseaudio sink info for ["sv << sink_name - << "]: "sv << pa_strerror(pa_context_errno(ctx)); + logging::error("Couldn't get pulseaudio sink info for [{}]: {}", sink_name, pa_strerror(pa_context_errno(ctx))); alarm->ring(-1); } @@ -628,7 +627,7 @@ namespace platf { alarm->wait(); // No need to check status. If it failed just return default name. - BOOST_LOG(info) << "Found default monitor by name: "sv << monitor_name; + logging::info("Found default monitor by name: {}", monitor_name); return monitor_name; } @@ -663,7 +662,7 @@ namespace platf { } bool is_sink_available(const std::string &sink) override { - BOOST_LOG(warning) << "audio_control_t::is_sink_available() unimplemented: "sv << sink; + logging::warning("audio_control_t::is_sink_available() unimplemented: {}", sink); return true; } @@ -676,7 +675,7 @@ namespace platf { int set_sink(const std::string &sink) override { auto alarm = safe::make_alarm(); - BOOST_LOG(info) << "Setting default sink to: ["sv << sink << "]"sv; + logging::info("Setting default sink to: [{}]", sink); op_t op { pa_context_set_default_sink( ctx.get(), @@ -687,13 +686,13 @@ namespace platf { }; if (!op) { - BOOST_LOG(error) << "Couldn't create set default-sink operation: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::error("Couldn't create set default-sink operation: {}", pa_strerror(pa_context_errno(ctx.get()))); return -1; } alarm->wait(); if (*alarm->status()) { - BOOST_LOG(error) << "Couldn't set default-sink ["sv << sink << "]: "sv << pa_strerror(pa_context_errno(ctx.get())); + logging::error("Couldn't set default-sink [{}]: {}", sink, pa_strerror(pa_context_errno(ctx.get()))); return -1; } diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 8063b4565..2d0a5684b 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -71,7 +71,7 @@ namespace cuda { * @param description Human-readable description used in log output. */ void pass_error(const std::string_view &sv, const char *name, const char *description) { - BOOST_LOG(error) << sv << name << ':' << description; + logging::error("{}{}:{}", sv, name, description); } /** @@ -98,7 +98,7 @@ namespace cuda { cdf->cuGetErrorName(result, &name); cdf->cuGetErrorString(result, &description); - BOOST_LOG(error) << sv << name << ':' << description; + logging::error("{}{}:{}", sv, name, description); return -1; } @@ -144,7 +144,7 @@ namespace cuda { int init() { auto status = cuda_load_functions(&cdf, nullptr); if (status) { - BOOST_LOG(error) << "Couldn't load cuda: "sv << status; + logging::error("Couldn't load cuda: {}", static_cast(status)); return -1; } @@ -168,7 +168,7 @@ namespace cuda { */ int init(int in_width, int in_height) { if (!cdf) { - BOOST_LOG(warning) << "cuda not initialized"sv; + logging::warning("cuda not initialized"sv); return -1; } @@ -194,13 +194,13 @@ namespace cuda { auto hwframe_ctx = (AVHWFramesContext *) hw_frames_ctx->data; if (hwframe_ctx->sw_format != AV_PIX_FMT_NV12 && hwframe_ctx->sw_format != AV_PIX_FMT_YUV444P) { - BOOST_LOG(error) << "cuda::cuda_t doesn't support any format other than AV_PIX_FMT_NV12 and AV_PIX_FMT_YUV444P"sv; + logging::error("cuda::cuda_t doesn't support any format other than AV_PIX_FMT_NV12 and AV_PIX_FMT_YUV444P"sv); return -1; } if (!frame->buf[0]) { if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) { - BOOST_LOG(error) << "Couldn't get hwframe for NVENC"sv; + logging::error("Couldn't get hwframe for NVENC"sv); return -1; } } @@ -362,7 +362,7 @@ namespace cuda { // use sysfs to look up the DRM device name from the PCI 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(); + logging::debug("Found CUDA device with PCI bus ID: {}", 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) { @@ -381,17 +381,17 @@ namespace cuda { continue; } - BOOST_LOG(debug) << "Found DRM primary node: "sv << filestring; + logging::debug("Found DRM primary node: {}", filestring); fs::path dri_path {"/dev/dri"sv}; auto device_path = dri_path / file; return platf::kms::privileged_open_drm_card_fd(device_path.c_str()); } } catch (const std::filesystem::filesystem_error &err) { - BOOST_LOG(error) << "Failed to read sysfs: "sv << err.what(); + logging::error("Failed to read sysfs: {}", err.what()); } - BOOST_LOG(error) << "Unable to find DRM device with PCI bus ID: "sv << pci_bus_id.data(); + logging::error("Unable to find DRM device with PCI bus ID: {}", pci_bus_id.data()); return -1; } @@ -426,13 +426,17 @@ namespace cuda { file = std::move(open_drm_fd_for_cuda_device(0)); if (file.el < 0) { std::array string; - BOOST_LOG(error) << "Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno, string.data(), string.size()); + logging::error([&](std::ostream &out) { + out << "Couldn't open DRM FD for CUDA device: "sv << strerror_r(errno, string.data(), string.size()); + }); return -1; } gbm = gbm::make_device(gbm::api_t::load(), file.el); if (!gbm) { - BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return -1; } @@ -472,13 +476,13 @@ namespace cuda { auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data; if (hw_frames_ctx->sw_format != AV_PIX_FMT_NV12 && hw_frames_ctx->sw_format != AV_PIX_FMT_YUV444P && hw_frames_ctx->sw_format != AV_PIX_FMT_P010LE && hw_frames_ctx->sw_format != AV_PIX_FMT_YUV444P16LE) { - BOOST_LOG(error) << "cuda::gl_cuda_vram_t doesn't support any format other than AV_PIX_FMT_NV12, AV_PIX_FMT_P010LE, AV_PIX_FMT_YUV444P and AV_PIX_FMT_YUV444P16LE"sv; + logging::error("cuda::gl_cuda_vram_t doesn't support any format other than AV_PIX_FMT_NV12, AV_PIX_FMT_P010LE, AV_PIX_FMT_YUV444P and AV_PIX_FMT_YUV444P16LE"sv); return -1; } if (!frame->buf[0]) { if (av_hwframe_get_buffer(hw_frames_ctx_buf, frame, 0)) { - BOOST_LOG(error) << "Couldn't get hwframe for NVENC_GL"sv; + logging::error("Couldn't get hwframe for NVENC_GL"sv); return -1; } } @@ -717,14 +721,14 @@ namespace cuda { NVFBC_BIND_CONTEXT_PARAMS params {NVFBC_BIND_CONTEXT_PARAMS_VER}; if (this->api->functions.nvFBCBindContext(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't bind NvFBC context to current thread: " << this->api->functions.nvFBCGetLastErrorStr(handle); + logging::error("Couldn't bind NvFBC context to current thread: {}", this->api->functions.nvFBCGetLastErrorStr(handle)); } } ~ctx_t() { NVFBC_RELEASE_CONTEXT_PARAMS params {NVFBC_RELEASE_CONTEXT_PARAMS_VER}; if (api->functions.nvFBCReleaseContext(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't release NvFBC context from current thread: " << api->functions.nvFBCGetLastErrorStr(handle); + logging::error("Couldn't release NvFBC context from current thread: {}", api->functions.nvFBCGetLastErrorStr(handle)); } } @@ -793,7 +797,7 @@ namespace cuda { handle.api = std::move(api); auto status = handle.api->functions.nvFBCCreateHandle(&handle.handle, ¶ms); if (status) { - BOOST_LOG(error) << "Failed to create session: "sv << handle.last_error(); + logging::error("Failed to create session: {}", handle.last_error()); return std::nullopt; } @@ -822,7 +826,7 @@ namespace cuda { auto status = api->functions.nvFBCGetStatus(handle, ¶ms); if (status) { - BOOST_LOG(error) << "Failed to get NvFBC status: "sv << last_error(); + logging::error("Failed to get NvFBC status: {}", last_error()); return std::nullopt; } @@ -838,7 +842,7 @@ namespace cuda { */ int capture(NVFBC_CREATE_CAPTURE_SESSION_PARAMS &capture_params) { if (api->functions.nvFBCCreateCaptureSession(handle, &capture_params)) { - BOOST_LOG(error) << "Failed to start capture session: "sv << last_error(); + logging::error("Failed to start capture session: {}", last_error()); return -1; } @@ -850,7 +854,7 @@ namespace cuda { }; if (api->functions.nvFBCToCudaSetUp(handle, &setup_params)) { - BOOST_LOG(error) << "Failed to setup cuda interop with nvFBC: "sv << last_error(); + logging::error("Failed to setup cuda interop with nvFBC: {}", last_error()); return -1; } return 0; @@ -869,7 +873,7 @@ namespace cuda { NVFBC_DESTROY_CAPTURE_SESSION_PARAMS params {NVFBC_DESTROY_CAPTURE_SESSION_PARAMS_VER}; if (api->functions.nvFBCDestroyCaptureSession(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't destroy capture session: "sv << last_error(); + logging::error("Couldn't destroy capture session: {}", last_error()); return -1; } @@ -895,7 +899,7 @@ namespace cuda { ctx_t ctx {api, handle}; if (api->functions.nvFBCDestroyHandle(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't destroy session handle: "sv << api->functions.nvFBCGetLastErrorStr(handle); + logging::error("Couldn't destroy session handle: {}", api->functions.nvFBCGetLastErrorStr(handle)); } handle_flags[SESSION_HANDLE] = false; @@ -944,12 +948,12 @@ namespace cuda { auto monitor_nr = util::from_view(display_name); if (monitor_nr < 0 || monitor_nr >= status_params->dwOutputNum) { - BOOST_LOG(warning) << "Can't stream monitor ["sv << monitor_nr << "], it needs to be between [0] and ["sv << status_params->dwOutputNum - 1 << "], defaulting to virtual desktop"sv; + logging::warning("Can't stream monitor [{}], it needs to be between [0] and [{}], defaulting to virtual desktop", monitor_nr, status_params->dwOutputNum - 1); } else { streamedMonitor = monitor_nr; } } else { - BOOST_LOG(warning) << "XrandR not available, streaming entire virtual desktop"sv; + logging::warning("XrandR not available, streaming entire virtual desktop"sv); } } @@ -1027,7 +1031,7 @@ namespace cuda { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } } @@ -1082,7 +1086,7 @@ namespace cuda { return platf::capture_e::reinit; } - BOOST_LOG(error) << "Couldn't capture nvFramebuffer: "sv << handle.last_error(); + logging::error("Couldn't capture nvFramebuffer: {}", handle.last_error()); return platf::capture_e::error; } @@ -1091,11 +1095,11 @@ namespace cuda { break; } - BOOST_LOG(debug) << "Direct capture failed attempt ["sv << x << ']'; + logging::debug("Direct capture failed attempt [{}]", x); } if (!info.bDirectCapture) { - BOOST_LOG(debug) << "Direct capture failed, trying the extra copy method"sv; + logging::debug("Direct capture failed, trying the extra copy method"sv); // Direct capture failed capture_params.bPushModel = nv_bool(false); capture_params.bWithCursor = nv_bool(false); @@ -1143,7 +1147,7 @@ namespace cuda { return platf::capture_e::reinit; } - BOOST_LOG(error) << "Couldn't capture nvFramebuffer: "sv << handle.last_error(); + logging::error("Couldn't capture nvFramebuffer: {}", handle.last_error()); return platf::capture_e::error; } @@ -1223,7 +1227,7 @@ namespace platf { */ std::shared_ptr nvfbc_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (hwdevice_type != mem_type_e::cuda) { - BOOST_LOG(error) << "Could not initialize nvfbc display with the given hw device type"sv; + logging::error("Could not initialize nvfbc display with the given hw device type"sv); return nullptr; } @@ -1259,20 +1263,20 @@ namespace platf { } if (!status_params->bIsCapturePossible) { - BOOST_LOG(error) << "NVidia driver doesn't support NvFBC screencasting"sv; + logging::error("NVidia driver doesn't support NvFBC screencasting"sv); } - BOOST_LOG(info) << "Found ["sv << status_params->dwOutputNum << "] outputs"sv; - BOOST_LOG(info) << "Virtual Desktop: "sv << status_params->screenSize.w << 'x' << status_params->screenSize.h; - BOOST_LOG(info) << "XrandR: "sv << (status_params->bXRandRAvailable ? "available"sv : "unavailable"sv); + logging::info("Found [{}] outputs", status_params->dwOutputNum); + logging::info("Virtual Desktop: {}x{}", status_params->screenSize.w, status_params->screenSize.h); + logging::info("XrandR: {}", (status_params->bXRandRAvailable ? "available"sv : "unavailable"sv)); for (auto x = 0; x < status_params->dwOutputNum; ++x) { auto &output = status_params->outputs[x]; - BOOST_LOG(info) << "-- Output --"sv; - BOOST_LOG(debug) << " ID: "sv << output.dwId; - BOOST_LOG(debug) << " Name: "sv << output.name; - BOOST_LOG(info) << " Resolution: "sv << output.trackedBox.w << 'x' << output.trackedBox.h; - BOOST_LOG(info) << " Offset: "sv << output.trackedBox.x << 'x' << output.trackedBox.y; + logging::info("-- Output --"sv); + logging::debug(" ID: {}", output.dwId); + logging::debug(" Name: {}", output.name); + logging::info(" Resolution: {}x{}", output.trackedBox.w, output.trackedBox.h); + logging::info(" Offset: {}x{}", output.trackedBox.x, output.trackedBox.y); display_names.emplace_back(std::to_string(x)); } diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index eff59b242..9c12a5f91 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -72,7 +72,9 @@ namespace gl { void drain_errors(const std::string_view &prefix) { GLenum err; while ((err = ctx.GetError()) != GL_NO_ERROR) { - BOOST_LOG(error) << "GL: "sv << prefix << ": ["sv << util::hex(err).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "GL: "sv << prefix << ": ["sv << util::hex(err).to_string_view() << ']'; + }); } } @@ -249,7 +251,7 @@ namespace gl { std::optional program_t::uniform(const char *block, std::pair *members, std::size_t count) { auto i = ctx.GetUniformBlockIndex(handle(), block); if (i == GL_INVALID_INDEX) { - BOOST_LOG(error) << "Couldn't find index of ["sv << block << ']'; + logging::error("Couldn't find index of [{}]", block); return std::nullopt; } @@ -274,7 +276,7 @@ namespace gl { if (indices[x] == GL_INVALID_INDEX) { error_flag = true; - BOOST_LOG(error) << "Couldn't find ["sv << block << '.' << members[x].first << ']'; + logging::error("Couldn't find [{}.{}]", block, members[x].first); } } @@ -362,7 +364,7 @@ namespace egl { cap_free(caps); if (value != CAP_SET) { - BOOST_LOG(debug) << "Failed to verify CAP_SYS_NICE effective capability"sv; + logging::debug("Failed to verify CAP_SYS_NICE effective capability"sv); return false; } @@ -374,14 +376,14 @@ namespace egl { cap_value_t sys_nice = CAP_SYS_NICE; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_nice, CAP_SET) || cap_set_proc(caps)) { - BOOST_LOG(debug) << "Failed to gain CAP_SYS_NICE"; + logging::debug("Failed to gain CAP_SYS_NICE"); } } ~cap_sys_nice() { cap_value_t sys_nice = CAP_SYS_NICE; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_nice, CAP_CLEAR) || cap_set_proc(caps)) { - BOOST_LOG(debug) << "Failed to drop CAP_SYS_NICE"; + logging::debug("Failed to drop CAP_SYS_NICE"); } cap_free(caps); } @@ -413,17 +415,21 @@ namespace egl { #endif if (!eglBindAPI(EGL_OPENGL_API)) { - BOOST_LOG(error) << "Couldn't bind API in privileged thread: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't bind API in privileged thread: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return EGL_NO_CONTEXT; } EGLContext privileged_ctx = eglCreateContext(display, config, share_context, attrib_list); if (privileged_ctx == EGL_NO_CONTEXT) { - BOOST_LOG(error) << "Couldn't create EGL context in privileged thread: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't create EGL context in privileged thread: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); } return privileged_ctx; }); } catch (const privileged_egl_worker_stopped &e) { - BOOST_LOG(error) << "Couldn't execute privileged EGL context creation: "sv << e.what(); + logging::error("Couldn't execute privileged EGL context creation: {}", e.what()); return EGL_NO_CONTEXT; } } @@ -439,7 +445,7 @@ namespace egl { sigset_t all; sigfillset(&all); if (pthread_sigmask(SIG_BLOCK, &all, nullptr) != 0) { - BOOST_LOG(error) << "Failed to block signals in egl_worker"sv; + logging::error("Failed to block signals in egl_worker"sv); queue_.stop(); return; } @@ -518,7 +524,7 @@ namespace egl { native_display_p = std::get<2>(native_display); break; default: - BOOST_LOG(error) << "egl::make_display(): Index ["sv << native_display.index() << "] not implemented"sv; + logging::error("egl::make_display(): Index [{}] not implemented", native_display.index()); return nullptr; } @@ -532,8 +538,10 @@ namespace egl { } if (raw_display == EGL_NO_DISPLAY) { - BOOST_LOG(error) << "Couldn't open EGL display: ["sv - << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't open EGL display: ["sv + << util::hex(eglGetError()).to_string_view() << ']'; + }); return nullptr; } display_t display {raw_display}; @@ -541,12 +549,14 @@ namespace egl { int major; int minor; if (!eglInitialize(display.get(), &major, &minor)) { - BOOST_LOG(error) << "Couldn't initialize EGL display: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't initialize EGL display: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return nullptr; } if (!gladLoaderLoadEGL(display.get())) { - BOOST_LOG(error) << "Failed to reload EGL for initialized display"sv; + logging::error("Failed to reload EGL for initialized display"sv); return nullptr; } @@ -555,8 +565,8 @@ namespace egl { const char *vendor = eglQueryString(display.get(), EGL_VENDOR); const char *apis = eglQueryString(display.get(), EGL_CLIENT_APIS); - BOOST_LOG(debug) << "EGL: ["sv << vendor << "]: version ["sv << version << ']'; - BOOST_LOG(debug) << "API's supported: ["sv << apis << ']'; + logging::debug("EGL: [{}]: version [{}]", vendor, version); + logging::debug("API's supported: [{}]", apis); std::array extensions { "EGL_KHR_create_context", @@ -567,7 +577,7 @@ namespace egl { for (auto ext : extensions) { if (!std::strstr(extension_st, ext)) { - BOOST_LOG(error) << "Missing extension: ["sv << ext << ']'; + logging::error("Missing extension: [{}]", ext); return nullptr; } } @@ -590,12 +600,16 @@ namespace egl { int count; EGLConfig conf; if (!eglChooseConfig(display, conf_attr.data(), &conf, 1, &count)) { - BOOST_LOG(error) << "Couldn't set config attributes: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't set config attributes: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return std::nullopt; } if (!eglBindAPI(EGL_OPENGL_API)) { - BOOST_LOG(error) << "Couldn't bind API: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't bind API: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return std::nullopt; } @@ -607,7 +621,7 @@ namespace egl { // Only add the high priority attribute if the driver explicitly supports it if (extension_st && std::string_view(extension_st).contains("EGL_IMG_context_priority"sv)) { - BOOST_LOG(debug) << "EGL: High priority context supported"sv; + logging::debug("EGL: High priority context supported"sv); attr.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG); attr.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG); } @@ -627,26 +641,26 @@ namespace egl { actual_priority_str = "HIGH"; } if (nice_warning) { - BOOST_LOG(warning) << "EGL: context priority set to "sv << actual_priority_str << " but CAP_SYS_NICE capability is missing"sv; + logging::warning("EGL: context priority set to {} but CAP_SYS_NICE capability is missing", actual_priority_str); } else { - BOOST_LOG(info) << "EGL: context priority set to "sv << actual_priority_str; + logging::info("EGL: context priority set to {}", actual_priority_str); } } if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, raw_ctx)) { - BOOST_LOG(error) << "Couldn't make current display"sv; + logging::error("Couldn't make current display"sv); return std::nullopt; } if (!gladLoadGLContext(&gl::ctx, eglGetProcAddress)) { - BOOST_LOG(error) << "Couldn't load OpenGL library"sv; + logging::error("Couldn't load OpenGL library"sv); return std::nullopt; } gl::egl_image_target_texture_2d_fn = (gl::PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLADapiproc) eglGetProcAddress("glEGLImageTargetTexture2DOES"); if (!gl::egl_image_target_texture_2d_fn) { - BOOST_LOG(warning) << "GL: glEGLImageTargetTexture2DOES not available; DMA-BUF import will fail"sv; + logging::warning("GL: glEGLImageTargetTexture2DOES not available; DMA-BUF import will fail"sv); } // GetString returns const GLubyte* (unsigned char*); convert to std::string safely (avoids sonar cpp:S6996). @@ -661,10 +675,10 @@ namespace egl { const auto gl_renderer = gl_string(gl::ctx.GetString(GL_RENDERER)); const auto gl_version = gl_string(gl::ctx.GetString(GL_VERSION)); const auto gl_shader = gl_string(gl::ctx.GetString(GL_SHADING_LANGUAGE_VERSION)); - BOOST_LOG(debug) << "GL: vendor: "sv << gl_vendor; - BOOST_LOG(debug) << "GL: renderer: "sv << gl_renderer; - BOOST_LOG(debug) << "GL: version: "sv << gl_version; - BOOST_LOG(debug) << "GL: shader: "sv << gl_shader; + logging::debug("GL: vendor: {}", gl_vendor); + logging::debug("GL: renderer: {}", gl_renderer); + logging::debug("GL: version: {}", gl_version); + logging::debug("GL: shader: {}", gl_shader); gl::ctx.PixelStorei(GL_UNPACK_ALIGNMENT, 1); @@ -787,14 +801,16 @@ namespace egl { }; if (!rgb->xrgb8) { - BOOST_LOG(error) << "Couldn't import RGB Image: "sv << util::hex(eglGetError()).to_string_view(); + logging::error([&](std::ostream &out) { + out << "Couldn't import RGB Image: "sv << util::hex(eglGetError()).to_string_view(); + }); return std::nullopt; } gl::ctx.BindTexture(GL_TEXTURE_2D, rgb->tex[0]); if (!gl::egl_image_target_texture_2d()) { - BOOST_LOG(error) << "glEGLImageTargetTexture2DOES is not available; cannot import RGB DMA-BUF"sv; + logging::error("glEGLImageTargetTexture2DOES is not available; cannot import RGB DMA-BUF"sv); return std::nullopt; } gl::egl_image_target_texture_2d()(GL_TEXTURE_2D, rgb->xrgb8); @@ -900,14 +916,16 @@ namespace egl { }; if (!nv12->r8 || !nv12->bg88) { - BOOST_LOG(error) << "Couldn't import YUV target: "sv << util::hex(eglGetError()).to_string_view(); + logging::error([&](std::ostream &out) { + out << "Couldn't import YUV target: "sv << util::hex(eglGetError()).to_string_view(); + }); return std::nullopt; } gl::ctx.BindTexture(GL_TEXTURE_2D, nv12->tex[0]); if (!gl::egl_image_target_texture_2d()) { - BOOST_LOG(error) << "glEGLImageTargetTexture2DOES is not available; cannot import YUV DMA-BUF"sv; + logging::error("glEGLImageTargetTexture2DOES is not available; cannot import YUV DMA-BUF"sv); return std::nullopt; } gl::egl_image_target_texture_2d()(GL_TEXTURE_2D, nv12->r8); @@ -954,14 +972,16 @@ namespace egl { }; if (!yuv444->r8 || !yuv444->g8 || !yuv444->b8) { - BOOST_LOG(error) << "Couldn't import YUV target: "sv << util::hex(eglGetError()).to_string_view(); + logging::error([&](std::ostream &out) { + out << "Couldn't import YUV target: "sv << util::hex(eglGetError()).to_string_view(); + }); return std::nullopt; } gl::ctx.BindTexture(GL_TEXTURE_2D, yuv444->tex[0]); if (!gl::egl_image_target_texture_2d()) { - BOOST_LOG(error) << "glEGLImageTargetTexture2DOES is not available; cannot import YUV DMA-BUF"sv; + logging::error("glEGLImageTargetTexture2DOES is not available; cannot import YUV DMA-BUF"sv); return std::nullopt; } gl::egl_image_target_texture_2d()(GL_TEXTURE_2D, yuv444->r8); @@ -1009,7 +1029,7 @@ namespace egl { y_format = GL_R16; uv_format = GL_RG16; } else { - BOOST_LOG(error) << "Unsupported target pixel format: "sv << format; + logging::error("Unsupported target pixel format: {}", static_cast(format)); return std::nullopt; } @@ -1056,7 +1076,7 @@ namespace egl { u_format = GL_R16; v_format = GL_R16; } else { - BOOST_LOG(error) << "Unsupported target pixel format: "sv << format; + logging::error("Unsupported target pixel format: {}", static_cast(format)); return std::nullopt; } @@ -1188,7 +1208,7 @@ namespace egl { gl_drain_errors; if (compiled_source.has_right()) { - BOOST_LOG(error) << sources[x] << ": "sv << compiled_source.right(); + logging::error("{}: {}", sources[x], compiled_source.right()); error_flag = true; } } @@ -1199,7 +1219,7 @@ namespace egl { auto program = gl::program_t::link(compiled_sources[3].left(), compiled_sources[4].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker: "sv << program.right(); + logging::error("GL linker: {}", program.right()); return std::nullopt; } @@ -1208,7 +1228,7 @@ namespace egl { program = gl::program_t::link(compiled_sources[1].left(), compiled_sources[0].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker: "sv << program.right(); + logging::error("GL linker: {}", program.right()); return std::nullopt; } @@ -1217,7 +1237,7 @@ namespace egl { program = gl::program_t::link(compiled_sources[3].left(), compiled_sources[2].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker: "sv << program.right(); + logging::error("GL linker: {}", program.right()); return std::nullopt; } @@ -1227,7 +1247,7 @@ namespace egl { auto loc_width_i = gl::ctx.GetUniformLocation(sws.program[1].handle(), "width_i"); if (loc_width_i < 0) { - BOOST_LOG(error) << "Couldn't find uniform [width_i]"sv; + logging::error("Couldn't find uniform [width_i]"sv); return std::nullopt; } @@ -1293,7 +1313,7 @@ namespace egl { gl_drain_errors; if (compiled_source.has_right()) { - BOOST_LOG(error) << sources[x] << ": "sv << compiled_source.right(); + logging::error("{}: {}", sources[x], compiled_source.right()); error_flag = true; } } @@ -1304,7 +1324,7 @@ namespace egl { auto program = gl::program_t::link(compiled_sources[0].left(), compiled_sources[4].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker (cursor shader): "sv << program.right(); + logging::error("GL linker (cursor shader): {}", program.right()); return std::nullopt; } @@ -1313,7 +1333,7 @@ namespace egl { program = gl::program_t::link(compiled_sources[0].left(), compiled_sources[1].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker (V - shader): "sv << program.right(); + logging::error("GL linker (V - shader): {}", program.right()); return std::nullopt; } @@ -1322,7 +1342,7 @@ namespace egl { program = gl::program_t::link(compiled_sources[0].left(), compiled_sources[2].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker (U - shader): "sv << program.right(); + logging::error("GL linker (U - shader): {}", program.right()); return std::nullopt; } @@ -1331,7 +1351,7 @@ namespace egl { program = gl::program_t::link(compiled_sources[0].left(), compiled_sources[3].left()); if (program.has_right()) { - BOOST_LOG(error) << "GL linker (Y - shader): "sv << program.right(); + logging::error("GL linker (Y - shader): {}", program.right()); return std::nullopt; } @@ -1388,7 +1408,7 @@ namespace egl { break; default: - BOOST_LOG(error) << "Unsupported pixel format for EGL frame: "sv << (int) format; + logging::error("Unsupported pixel format for EGL frame: {}", (int) format); return std::nullopt; } @@ -1456,7 +1476,9 @@ namespace egl { #ifndef NDEBUG auto status = gl::ctx.CheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { - BOOST_LOG(error) << "Pass Cursor: CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Pass Cursor: CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']'; + }); return; } #endif @@ -1479,7 +1501,9 @@ namespace egl { #ifndef NDEBUG auto status = gl::ctx.CheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { - BOOST_LOG(error) << "Pass "sv << x << ": CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Pass "sv << x << ": CheckFramebufferStatus() --> [0x"sv << util::hex(status).to_string_view() << ']'; + }); return -1; } #endif diff --git a/src/platform/linux/graphics.h b/src/platform/linux/graphics.h index 744791240..45d3e9895 100644 --- a/src/platform/linux/graphics.h +++ b/src/platform/linux/graphics.h @@ -171,7 +171,7 @@ namespace gl { void bind(It it_begin, It it_end) { using namespace std::literals; if (std::distance(it_begin, it_end) > size()) { - BOOST_LOG(warning) << "To many elements to bind"sv; + logging::warning("To many elements to bind"sv); return; } diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 19b5cb61c..bdb6167e4 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -56,18 +57,18 @@ namespace platf { cap_value_t sys_admin = CAP_SYS_ADMIN; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) { - BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN"sv; + logging::error("Failed to gain CAP_SYS_ADMIN"sv); } } ~cap_sys_admin() { cap_value_t sys_admin = CAP_SYS_ADMIN; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR)) { - BOOST_LOG(error) << "Failed to clear CAP_SYS_ADMIN capability flag"sv; + logging::error("Failed to clear CAP_SYS_ADMIN capability flag"sv); } else if (cap_set_proc(caps)) { // CAP_SYS_ADMIN may already have been dropped by privileged_drm_worker. if (errno != EPERM) { - BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN"sv; + logging::error("Failed to drop CAP_SYS_ADMIN"sv); } } cap_free(caps); @@ -146,7 +147,7 @@ namespace platf { sigset_t all; sigfillset(&all); if (pthread_sigmask(SIG_BLOCK, &all, nullptr) != 0) { - BOOST_LOG(error) << "Failed to block signals in drm_worker"sv; + logging::error("Failed to block signals in drm_worker"sv); queue_.stop(); return; } @@ -480,7 +481,7 @@ namespace platf { } } - BOOST_LOG(error) << "Unknown Monitor connector type ["sv << string << "]: Please report this to the GitHub issue tracker"sv; + logging::error("Unknown Monitor connector type [{}]: Please report this to the GitHub issue tracker", string); return DRM_MODE_CONNECTOR_Unknown; } @@ -524,7 +525,9 @@ namespace platf { for (; plane_p != end; ++plane_p) { plane_t plane = drmModeGetPlane(fd, *plane_p); if (!plane) { - BOOST_LOG(error) << "Couldn't get drm plane ["sv << (end - plane_p) << "]: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get drm plane ["sv << (end - plane_p) << "]: "sv << strerror(errno); + }); continue; } @@ -718,45 +721,47 @@ namespace platf { } version_t ver {drmGetVersion(fd.el)}; - BOOST_LOG(info) << path << " -> "sv << ((ver && ver->name) ? ver->name : "UNKNOWN"); + logging::info("{} -> {}", path, ((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); if (rendernode_path) { - BOOST_LOG(debug) << "Opening render node: "sv << rendernode_path; + logging::debug("Opening render node: {}", rendernode_path); render_fd.el = open(rendernode_path, O_RDWR); if (render_fd.el < 0) { - BOOST_LOG(warning) << "Couldn't open render node: "sv << rendernode_path << ": "sv << strerror(errno); + logging::warning([&](std::ostream &out) { + out << "Couldn't open render node: "sv << rendernode_path << ": "sv << strerror(errno); + }); render_fd.el = dup(fd.el); } free(rendernode_path); } else { - BOOST_LOG(warning) << "No render device name for: "sv << path; + logging::warning("No render device name for: {}", path); render_fd.el = dup(fd.el); } if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) { - BOOST_LOG(error) << "GPU driver doesn't support universal planes: "sv << path; + logging::error("GPU driver doesn't support universal planes: {}", path); return -1; } if (drmSetClientCap(fd.el, DRM_CLIENT_CAP_ATOMIC, 1)) { - BOOST_LOG(warning) << "GPU driver doesn't support atomic mode-setting: "sv << path; + logging::warning("GPU driver doesn't support atomic mode-setting: {}", 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 && settings.video.capture != "kms") { - BOOST_LOG(info) << "Avoiding KMS capture under X11 due to lack of atomic mode-setting"sv; + logging::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; + logging::warning("Cursor capture may fail without atomic mode-setting support!"sv); } plane_res.reset(drmModeGetPlaneResources(fd.el)); if (!plane_res) { - BOOST_LOG(error) << "Couldn't get drm plane resources"sv; + logging::error("Couldn't get drm plane resources"sv); return -1; } @@ -872,7 +877,7 @@ namespace platf { return *value; } - BOOST_LOG(error) << "Failed to determine panel orientation, defaulting to landscape."; + logging::error("Failed to determine panel orientation, defaulting to landscape."); return DRM_MODE_ROTATE_0; } @@ -911,7 +916,7 @@ namespace platf { std::vector monitors(conn_type_count_t &conn_type_count) { auto resources = res(); if (!resources) { - BOOST_LOG(error) << "Couldn't get connector resources"sv; + logging::error("Couldn't get connector resources"sv); return {}; } @@ -1092,23 +1097,14 @@ namespace platf { */ void print(plane_t::pointer plane, fb_t::pointer fb, crtc_t::pointer crtc) { if (crtc) { - BOOST_LOG(debug) << "crtc("sv << crtc->x << ", "sv << crtc->y << ')'; - BOOST_LOG(debug) << "crtc("sv << crtc->width << ", "sv << crtc->height << ')'; - BOOST_LOG(debug) << "plane->possible_crtcs == "sv << plane->possible_crtcs; + logging::debug("crtc({}, {})", crtc->x, crtc->y); + logging::debug("crtc({}, {})", crtc->width, crtc->height); + logging::debug("plane->possible_crtcs == {}", plane->possible_crtcs); } - BOOST_LOG(debug) - << "x("sv << plane->x - << ") y("sv << plane->y - << ") crtc_x("sv << plane->crtc_x - << ") crtc_y("sv << plane->crtc_y - << ") crtc_id("sv << plane->crtc_id - << ')'; + logging::debug("x({}) y({}) crtc_x({}) crtc_y({}) crtc_id({})", plane->x, plane->y, plane->crtc_x, plane->crtc_y, plane->crtc_id); - BOOST_LOG(debug) - << "Resolution: "sv << fb->width << 'x' << fb->height - << ": Pitch: "sv << fb->pitches[0] - << ": Offset: "sv << fb->offsets[0]; + logging::debug("Resolution: {}x{}: Pitch: {}: Offset: {}", fb->width, fb->height, fb->pitches[0], fb->offsets[0]); std::stringstream ss; @@ -1119,7 +1115,9 @@ namespace platf { ss << util::view(plane->formats[plane->count_formats - 1]) << ']'; - BOOST_LOG(debug) << ss.str(); + logging::debug([&](std::ostream &out) { + out << ss.str(); + }); } /** @@ -1138,12 +1136,12 @@ namespace platf { for (auto &card_descriptor : state.card_descriptors) { for (const auto &monitor_descriptor : card_descriptor.crtc_to_monitor | std::views::values) { if (display_name == std::format("{}-{}", drmModeGetConnectorTypeName(monitor_descriptor.type), monitor_descriptor.index)) { - BOOST_LOG(info) << "Mapped '"sv << display_name << "' to kmsgrab monitor index " << monitor_descriptor.monitor_index; + logging::info("Mapped '{}' to kmsgrab monitor index {}", display_name, monitor_descriptor.monitor_index); return monitor_descriptor.monitor_index; } } } - BOOST_LOG(warning) << "Couldn't map '"sv << display_name << "' to a monitor index. Falling back to first monitor in list (index=0)."; + logging::warning("Couldn't map '{}' to a monitor index. Falling back to first monitor in list (index=0).", display_name); return 0; // Fallback to first index if nothing can be matched } @@ -1205,7 +1203,9 @@ 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; + logging::debug([&](std::ostream &out) { + out << file << " is not a CUDA device"sv; + }); if (settings.video.encoder != "nvenc") { continue; } @@ -1215,7 +1215,9 @@ namespace platf { // This is important for hybrid GPU laptops where the display // may be connected through NVIDIA but rendering happens on Intel if (mem_type == mem_type_e::vaapi && card.is_nvidia()) { - BOOST_LOG(debug) << file << " is an NVIDIA card, skipping for VAAPI"sv; + logging::debug([&](std::ostream &out) { + out << file << " is an NVIDIA card, skipping for VAAPI"sv; + }); continue; } @@ -1237,12 +1239,14 @@ namespace platf { auto fb = card.fb(plane.get()); if (!fb) { - BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + }); return -1; } if (!fb->handles[0]) { - BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; + logging::error("Couldn't get handle for DRM Framebuffer [{}]: Probably not permitted", plane->fb_id); return -1; } @@ -1253,18 +1257,22 @@ namespace platf { auto fb_fd = card.handleFD(fb->handles[i]); if (fb_fd.el < 0) { - BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno); + }); continue; } } auto crtc = card.crtc(plane->crtc_id); if (!crtc) { - BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get CRTC info: "sv << strerror(errno); + }); continue; } - BOOST_LOG(info) << "Found monitor for DRM screencasting"sv; + logging::info("Found monitor for DRM screencasting"sv); // We need to find the correct /dev/dri/card{nr} to correlate the crtc_id with the monitor descriptor auto pos = std::find_if(std::begin(state.card_descriptors), std::end(state.card_descriptors), [&](card_descriptor_t &cd) { @@ -1274,7 +1282,9 @@ namespace platf { if (pos == std::end(state.card_descriptors)) { // This code path shouldn't happen, but it's there just in case. // card_descriptors is part of the guesswork after all. - BOOST_LOG(error) << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv; + logging::error([&](std::ostream &out) { + out << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv; + }); return -1; } @@ -1305,13 +1315,13 @@ namespace platf { switch (card.get_panel_orientation(plane->plane_id)) { case DRM_MODE_ROTATE_270: - BOOST_LOG(debug) << "Detected panel orientation at 90, swapping width and height."; + logging::debug("Detected panel orientation at 90, swapping width and height."); width = viewport.height; height = viewport.width; break; case DRM_MODE_ROTATE_90: case DRM_MODE_ROTATE_180: - BOOST_LOG(warning) << "Panel orientation is unsupported, screen capture may not work correctly."; + logging::warning("Panel orientation is unsupported, screen capture may not work correctly."); break; } @@ -1322,7 +1332,7 @@ namespace platf { // This code path shouldn't happen, but it's there just in case. // crtc_to_monitor is part of the guesswork after all. else { - BOOST_LOG(warning) << "Couldn't find crtc_id, this shouldn't have happened :\\"sv; + logging::warning("Couldn't find crtc_id, this shouldn't have happened :\\"sv); width = crtc->width; height = crtc->height; offset_x = crtc->x; @@ -1337,7 +1347,7 @@ namespace platf { kms::conn_type_count_t conn_type_count; for (auto &connector : card.monitors(conn_type_count)) { if (connector.crtc_id == crtc_id) { - BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']'; + logging::info("Found connector ID [{}]", connector.connector_id); connector_id = connector.connector_id; @@ -1351,7 +1361,7 @@ namespace platf { } } - BOOST_LOG(error) << "Couldn't find monitor ["sv << monitor_index << ']'; + logging::error("Couldn't find monitor [{}]", monitor_index); return -1; // Neatly break from nested for loop @@ -1375,16 +1385,16 @@ namespace platf { // We assume a 1:1 mapping between cursor planes and CRTCs, which seems to // match the behavior of drivers in the real world. If it's violated, we'll // proceed anyway but print a warning in the log. - BOOST_LOG(warning) << "Cursor plane spans multiple CRTCs!"sv; + logging::warning("Cursor plane spans multiple CRTCs!"sv); } - BOOST_LOG(info) << "Found cursor plane ["sv << plane->plane_id << ']'; + logging::info("Found cursor plane [{}]", plane->plane_id); cursor_plane_id = plane->plane_id; break; } if (cursor_plane_id < 0) { - BOOST_LOG(warning) << "No KMS cursor plane found. Cursor may not be displayed while streaming!"sv; + logging::warning("No KMS cursor plane found. Cursor may not be displayed while streaming!"sv); } return 0; @@ -1402,23 +1412,29 @@ namespace platf { prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id); if (hdr_metadata_blob == nullptr) { - BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Unable to get HDR metadata blob: "sv << strerror(errno); + }); return false; } if (hdr_metadata_blob->length < sizeof(uint32_t) + sizeof(hdr_metadata_infoframe)) { - BOOST_LOG(error) << "HDR metadata blob is too small: "sv << hdr_metadata_blob->length; + logging::error("HDR metadata blob is too small: {}", hdr_metadata_blob->length); return false; } auto raw_metadata = (hdr_output_metadata *) hdr_metadata_blob->data; if (raw_metadata->metadata_type != 0) { // HDMI_STATIC_METADATA_TYPE1 - BOOST_LOG(error) << "Unknown HDMI_STATIC_METADATA_TYPE value: "sv << raw_metadata->metadata_type; + logging::error([&](std::ostream &out) { + out << "Unknown HDMI_STATIC_METADATA_TYPE value: "sv << raw_metadata->metadata_type; + }); return false; } if (raw_metadata->hdmi_metadata_type1.metadata_type != 0) { // Static Metadata Type 1 - BOOST_LOG(error) << "Unknown secondary metadata type value: "sv << raw_metadata->hdmi_metadata_type1.metadata_type; + logging::error([&](std::ostream &out) { + out << "Unknown secondary metadata type value: "sv << raw_metadata->hdmi_metadata_type1.metadata_type; + }); return false; } @@ -1428,15 +1444,17 @@ namespace platf { case 0: // HDMI_EOTF_TRADITIONAL_GAMMA_SDR return false; case 1: // HDMI_EOTF_TRADITIONAL_GAMMA_HDR - BOOST_LOG(warning) << "Unsupported HDR EOTF: Traditional Gamma"sv; + logging::warning("Unsupported HDR EOTF: Traditional Gamma"sv); return true; case 2: // HDMI_EOTF_SMPTE_ST2084 return true; case 3: // HDMI_EOTF_BT_2100_HLG - BOOST_LOG(warning) << "Unsupported HDR EOTF: HLG"sv; + logging::warning("Unsupported HDR EOTF: HLG"sv); return true; default: - BOOST_LOG(warning) << "Unsupported HDR EOTF: "sv << raw_metadata->hdmi_metadata_type1.eotf; + logging::warning([&](std::ostream &out) { + out << "Unsupported HDR EOTF: "sv << raw_metadata->hdmi_metadata_type1.eotf; + }); return true; } } @@ -1455,7 +1473,9 @@ namespace platf { prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id); if (hdr_metadata_blob == nullptr) { - BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Unable to get HDR metadata blob: "sv << strerror(errno); + }); return false; } @@ -1518,15 +1538,15 @@ 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; + logging::error("Cursor plane is missing required plane CRTC properties!"sv); + logging::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; + logging::error("Cursor plane is missing required plane SRC properties!"sv); + logging::error("Atomic mode-setting must be enabled to capture the cursor!"sv); cursor_plane_id = -1; captured_cursor.visible = false; return; @@ -1547,10 +1567,10 @@ namespace platf { captured_cursor.visible = false; captured_cursor.fb_id = 0; } else if (plane->fb_id != captured_cursor.fb_id) { - BOOST_LOG(debug) << "Refreshing cursor image after FB changed"sv; + logging::debug("Refreshing cursor image after FB changed"sv); cursor_dirty = true; } else if (*prop_src_x != captured_cursor.prop_src_x || *prop_src_y != captured_cursor.prop_src_y || *prop_src_w != captured_cursor.prop_src_w || *prop_src_h != captured_cursor.prop_src_h) { - BOOST_LOG(debug) << "Refreshing cursor image after source dimensions changed"sv; + logging::debug("Refreshing cursor image after source dimensions changed"sv); cursor_dirty = true; } @@ -1565,7 +1585,7 @@ namespace platf { // All known cursor planes in the wild are 32 bpp if (!is_cursor_32bpp_format(fb->pixel_format)) { - BOOST_LOG(error) << "Unsupported cursor format: "sv << fb->pixel_format; + logging::error("Unsupported cursor format: {}", fb->pixel_format); captured_cursor.visible = false; cursor_plane_id = -1; return; @@ -1573,7 +1593,7 @@ namespace platf { // All known cursor planes in the wild require linear buffers if (fb->modifier != DRM_FORMAT_MOD_LINEAR && fb->modifier != DRM_FORMAT_MOD_INVALID) { - BOOST_LOG(error) << "Unsupported non-linear cursor modifier: "sv << fb->modifier; + logging::error("Unsupported non-linear cursor modifier: {}", fb->modifier); captured_cursor.visible = false; cursor_plane_id = -1; return; @@ -1587,7 +1607,7 @@ namespace platf { // Check for a legal source rectangle if (src_x + src_w > fb->width || src_y + src_h > fb->height) { - BOOST_LOG(error) << "Illegal source size: ["sv << src_x + src_w << ',' << src_y + src_h << "] > ["sv << fb->width << ',' << fb->height << ']'; + logging::error("Illegal source size: [{},{}] > [{},{}]", src_x + src_w, src_y + src_h, fb->width, fb->height); captured_cursor.visible = false; return; } @@ -1607,7 +1627,9 @@ namespace platf { drm_mode_map_dumb map = {}; map.handle = fb->handles[0]; if (drmIoctl(card.fd.el, DRM_IOCTL_MODE_MAP_DUMB, &map) < 0) { - BOOST_LOG(error) << "Failed to map cursor FB as dumb buffer: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Failed to map cursor FB as dumb buffer: "sv << strerror(errno); + }); captured_cursor.visible = false; return; } @@ -1616,7 +1638,9 @@ namespace platf { } if (mapped_data == MAP_FAILED) { - BOOST_LOG(error) << "Failed to mmap cursor FB: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Failed to mmap cursor FB: "sv << strerror(errno); + }); captured_cursor.visible = false; return; } @@ -1681,7 +1705,7 @@ namespace platf { if (connector_id) { auto connector_props = card.connector_props(*connector_id); if (hdr_metadata_blob_id != card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv)) { - BOOST_LOG(info) << "Reinitializing capture after HDR metadata change"sv; + logging::info("Reinitializing capture after HDR metadata change"sv); return capture_e::reinit; } } @@ -1692,20 +1716,21 @@ namespace platf { // A plane that stays without a framebuffer will not get the picture back by itself: // the compositor has moved it to another plane, or restarted. Pick a plane again. if (const auto now = std::chrono::steady_clock::now(); empty_plane_timer.update(plane->fb_id != 0, now)) { - BOOST_LOG(info) << "Reinitializing capture: plane ["sv << plane_id << "] has had no framebuffer for "sv - << std::chrono::duration_cast(empty_plane_timer.empty_for(now)).count() << "ms"sv; + logging::info("Reinitializing capture: plane [{}] has had no framebuffer for {}ms", plane_id, std::chrono::duration_cast(empty_plane_timer.empty_for(now)).count()); return capture_e::reinit; } auto fb = card.fb(plane.get()); if (!fb) { // This can happen if the display is being reconfigured while streaming - BOOST_LOG(warning) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + logging::warning([&](std::ostream &out) { + out << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + }); return capture_e::timeout; } if (!fb->handles[0]) { - BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; + logging::error("Couldn't get handle for DRM Framebuffer [{}]: Probably not permitted", plane->fb_id); return capture_e::error; } @@ -1722,7 +1747,9 @@ namespace platf { file[y] = card.handleFD(fb->handles[y]); if (file[y].el < 0) { - BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno); + }); return capture_e::error; } @@ -1800,7 +1827,7 @@ namespace platf { int init(const std::string &display_name, const ::video::config_t &config) { auto gbm_api = gbm::api_t::load(); if (!gbm_api) { - BOOST_LOG(warning) << "libgbm not initialized"sv; + logging::warning("libgbm not initialized"sv); return -1; } @@ -1810,7 +1837,9 @@ namespace platf { gbm = gbm::make_device(std::move(gbm_api), card.fd.el); if (!gbm) { - BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; + }); return -1; } @@ -1855,7 +1884,7 @@ namespace platf { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } } @@ -1973,7 +2002,7 @@ namespace platf { int w; gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); - BOOST_LOG(debug) << "width and height: w "sv << w << " h "sv << h; + logging::debug("width and height: w {} h {}", w, h); if (!pull_free_image_cb(img_out)) { return platf::capture_e::interrupted; @@ -2064,7 +2093,9 @@ namespace platf { } #endif - BOOST_LOG(error) << "Unsupported pixel format for egl::display_vram_t: "sv << platf::from_pix_fmt(pix_fmt); + logging::error([&](std::ostream &out) { + out << "Unsupported pixel format for egl::display_vram_t: "sv << platf::from_pix_fmt(pix_fmt); + }); return nullptr; } @@ -2125,7 +2156,7 @@ namespace platf { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } } @@ -2197,14 +2228,14 @@ namespace platf { #ifdef SUNSHINE_BUILD_VAAPI if (mem_type == mem_type_e::vaapi && !va::validate(card.render_fd.el, hevc_mode)) { - BOOST_LOG(warning) << "Monitor "sv << display_name << " doesn't support hardware encoding. Reverting back to GPU -> RAM -> GPU"sv; + logging::warning("Monitor {} doesn't support hardware encoding. Reverting back to GPU -> RAM -> GPU", display_name); return -1; } #endif #ifndef SUNSHINE_BUILD_CUDA if (mem_type == mem_type_e::cuda) { - BOOST_LOG(warning) << "Attempting to use NVENC without CUDA support. Reverting back to GPU -> RAM -> GPU"sv; + logging::warning("Attempting to use NVENC without CUDA support. Reverting back to GPU -> RAM -> GPU"sv); return -1; } #endif @@ -2263,7 +2294,7 @@ namespace platf { void correlate_to_wayland(std::vector &cds) { auto monitors = wl::monitors(); - BOOST_LOG(info) << "-------- Start of KMS monitor list --------"sv; + logging::info("-------- Start of KMS monitor list --------"sv); for (auto &monitor : monitors) { std::string_view name = monitor->name; @@ -2295,24 +2326,20 @@ namespace platf { monitor_descriptor.viewport.width != monitor->viewport.width || monitor_descriptor.viewport.height != monitor->viewport.height ) { - BOOST_LOG(warning) - << "Mismatch on expected Resolution compared to actual resolution: "sv - << monitor_descriptor.viewport.width << 'x' << monitor_descriptor.viewport.height - << " vs "sv - << monitor->viewport.width << 'x' << monitor->viewport.height; + logging::warning("Mismatch on expected Resolution compared to actual resolution: {}x{} vs {}x{}", monitor_descriptor.viewport.width, monitor_descriptor.viewport.height, monitor->viewport.width, monitor->viewport.height); } - BOOST_LOG(info) << "Monitor " << monitor_descriptor.monitor_index << " is "sv << name << ": "sv << monitor->description; + logging::info("Monitor {} is {}: {}", monitor_descriptor.monitor_index, name, monitor->description); goto break_for_loop; } } } break_for_loop: - BOOST_LOG(verbose) << "Reduced to name: "sv << name << ": "sv << index; + logging::verbose("Reduced to name: {}: {}", name, index); } - BOOST_LOG(info) << "--------- End of KMS monitor list ---------"sv; + logging::info("--------- End of KMS monitor list ---------"sv); } // A list of names of displays accepted as display_name @@ -2329,12 +2356,12 @@ namespace platf { int count = 0; if (!fs::exists("/dev/dri")) { - BOOST_LOG(warning) << "Couldn't find /dev/dri, kmsgrab won't be enabled"sv; + logging::warning("Couldn't find /dev/dri, kmsgrab won't be enabled"sv); return {}; } if (!gbm::api_t::load()) { - BOOST_LOG(warning) << "libgbm not initialized"sv; + logging::warning("libgbm not initialized"sv); return {}; } @@ -2360,9 +2387,11 @@ 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; + logging::debug([&](std::ostream &out) { + out << file << " is not a CUDA device"sv; + }); if (settings.video.encoder == "nvenc") { - BOOST_LOG(warning) << "Using NVENC with your display connected to a different GPU may not work properly!"sv; + logging::warning("Using NVENC with your display connected to a different GPU may not work properly!"sv); } else { continue; } @@ -2372,7 +2401,9 @@ namespace platf { // This is important for hybrid GPU laptops where the display // may be connected through NVIDIA but rendering happens on Intel if (hwdevice_type == mem_type_e::vaapi && card.is_nvidia()) { - BOOST_LOG(debug) << file << " is an NVIDIA card, skipping for VAAPI"sv; + logging::debug([&](std::ostream &out) { + out << file << " is an NVIDIA card, skipping for VAAPI"sv; + }); continue; } @@ -2391,15 +2422,18 @@ namespace platf { auto fb = card.fb(plane.get()); if (!fb) { - BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno); + }); continue; } if (!fb->handles[0]) { - BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv; + logging::error("Couldn't get handle for DRM Framebuffer [{}]: Probably not permitted", plane->fb_id); #if defined(SUNSHINE_BUILD_FLATPAK) || defined(SUNSHINE_BUILD_APPIMAGE) - BOOST_LOG((settings.video.capture == "kms") ? fatal : error) - << "AppImage and Flatpak do not support KMS capture. Use another capture method."sv; + logging::log((settings.video.capture == "kms") ? logging::level_e::fatal : logging::level_e::error, [&](std::ostream &out) { + out << "AppImage and Flatpak do not support KMS capture. Use another capture method."sv; + }); #endif break; } @@ -2407,7 +2441,9 @@ namespace platf { // This appears to return the offset of the monitor auto crtc = card.crtc(plane->crtc_id); if (!crtc) { - BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't get CRTC info: "sv << strerror(errno); + }); continue; } @@ -2444,9 +2480,9 @@ namespace platf { capture_geometry_t desktop; for (auto &card_descriptor : cds) { for (auto &[_, monitor_descriptor] : card_descriptor.crtc_to_monitor) { - BOOST_LOG(debug) << "Monitor description"sv; - BOOST_LOG(debug) << "Resolution: "sv << monitor_descriptor.viewport.width << 'x' << monitor_descriptor.viewport.height; - BOOST_LOG(debug) << "Offset: "sv << monitor_descriptor.viewport.offset_x << 'x' << monitor_descriptor.viewport.offset_y; + logging::debug("Monitor description"sv); + logging::debug("Resolution: {}x{}", monitor_descriptor.viewport.width, monitor_descriptor.viewport.height); + logging::debug("Offset: {}x{}", monitor_descriptor.viewport.offset_x, monitor_descriptor.viewport.offset_y); desktop.include(monitor_descriptor.viewport); } @@ -2457,11 +2493,13 @@ namespace platf { state.env_logical_width = desktop.logical_width; state.env_logical_height = desktop.logical_height; - BOOST_LOG(debug) << "Desktop resolution: "sv << state.env_width << 'x' << state.env_height; + logging::debug("Desktop resolution: {}x{}", state.env_width, state.env_height); state.card_descriptors = std::move(cds); - BOOST_LOG(debug) << "Final KMS display_names return list: " << (display_names | std::views::join_with(' ') | std::ranges::to()); + logging::debug([&](std::ostream &out) { + out << "Final KMS display_names return list: " << (display_names | std::views::join_with(' ') | std::ranges::to()); + }); return display_names; } diff --git a/src/platform/linux/kwingrab.cpp b/src/platform/linux/kwingrab.cpp index 5bb1f0e41..8e6aeec4a 100644 --- a/src/platform/linux/kwingrab.cpp +++ b/src/platform/linux/kwingrab.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -78,7 +79,7 @@ namespace kwin { // If we do not have a system permission, check if we need a temporary permission via user's application directory if (is_permission_system_deactivated()) { - BOOST_LOG(info) << "[kwingrab] No permission desktop file necessary. KWin permission system deactivated."; + logging::info("[kwingrab] No permission desktop file necessary. KWin permission system deactivated."); create_file = false; initialized = true; return; @@ -87,13 +88,13 @@ namespace kwin { // User: Check and (if necessary) update user's XDG applications for permission auto user_applications = get_xdg_user_applications_path(); if (user_applications.empty()) { - BOOST_LOG(error) << "[kwingrab] Failed to determine user application directory. Cannot continue with permission setup."; + logging::error("[kwingrab] Failed to determine user application directory. Cannot continue with permission setup."); return; } // Create non-existing application directory so we can write into it if (!std::filesystem::exists(user_applications) && !std::filesystem::create_directories(user_applications)) { // In case of failure log and return - BOOST_LOG(error) << "[kwingrab] Failed to create application directory. Cannot continue with permission setup."; + logging::error("[kwingrab] Failed to create application directory. Cannot continue with permission setup."); create_file = false; initialized = true; return; @@ -106,19 +107,19 @@ namespace kwin { auto entry_executablepath = get_executable_from_desktop_file(entry); if (!entry_executablepath.empty() && entry_executablepath == executablepath) { // This entry is exactly the one we need - BOOST_LOG(debug) << "[kwingrab] Ignoring current temporary KWin wayland permission file: "sv << entry; + logging::debug("[kwingrab] Ignoring current temporary KWin wayland permission file: {}", entry); create_file = false; continue; } if (!entry_executablepath.empty() && std::filesystem::exists(entry_executablepath)) { // This entry is for another sunshine executable that still exists - BOOST_LOG(debug) << "[kwingrab] Ignoring other valid temporary KWin wayland permission file: "sv << entry; + logging::debug("[kwingrab] Ignoring other valid temporary KWin wayland permission file: {}", entry); continue; } if (std::filesystem::remove(path)) { - BOOST_LOG(info) << "[kwingrab] Removed stale temporary KWin wayland permission file: "sv << entry << " executable: "sv << entry_executablepath; + logging::info("[kwingrab] Removed stale temporary KWin wayland permission file: {} executable: {}", entry, entry_executablepath); } else { - BOOST_LOG(warning) << "[kwingrab] Failed to remove stale temporary KWin wayland permission file: "sv << entry << " executable: "sv << entry_executablepath; + logging::warning("[kwingrab] Failed to remove stale temporary KWin wayland permission file: {} executable: {}", entry, entry_executablepath); } } } @@ -138,10 +139,10 @@ namespace kwin { << "NoDisplay=true" << std::endl; filestream.close(); // Give KWin time to catch up to the new desktop file - BOOST_LOG(info) << "[kwingrab] Created temporary KWin wayland permission file: "sv << user_filepath << " - Waiting 3 seconds for KDE to pick up new file."; + logging::info("[kwingrab] Created temporary KWin wayland permission file: {} - Waiting 3 seconds for KDE to pick up new file.", user_filepath); std::this_thread::sleep_for(std::chrono::milliseconds(3000)); } else { - BOOST_LOG(warning) << "[kwingrab] Failed to open temporary KWin wayland permission file: "sv << user_filepath; + logging::warning("[kwingrab] Failed to open temporary KWin wayland permission file: {}", user_filepath); } } @@ -234,7 +235,7 @@ namespace kwin { if (std::filesystem::exists(filename)) { auto file_executablepath = get_executable_from_desktop_file(filename); if (file_executablepath == executablepath) { - BOOST_LOG(info) << "[kwingrab] Found matching system KWin desktop permission file: "sv << filename; + logging::info("[kwingrab] Found matching system KWin desktop permission file: {}", filename); return true; } } @@ -325,13 +326,13 @@ namespace kwin { std::string wl_name; if (!lizardbyte::common::get_env("WAYLAND_DISPLAY", wl_name)) { - BOOST_LOG(error) << "[kwingrab] WAYLAND_DISPLAY not set"sv; + logging::error("[kwingrab] WAYLAND_DISPLAY not set"sv); return -1; } wl_display = wl_display_connect(wl_name.c_str()); if (!wl_display) { - BOOST_LOG(error) << "[kwingrab] cannot connect to Wayland display: "sv << wl_name; + logging::error("[kwingrab] cannot connect to Wayland display: {}", wl_name); return -1; } @@ -343,7 +344,7 @@ namespace kwin { wl_display_roundtrip(wl_display); if (!is_kwin_screencasting_available()) { - BOOST_LOG(debug) << "[kwingrab] zkde_screencast_unstable_v1 not found in registry."sv; + logging::debug("[kwingrab] zkde_screencast_unstable_v1 not found in registry."sv); return -1; } @@ -374,7 +375,7 @@ namespace kwin { }); std::vector output_names; for (const auto &output_parameter : sorted_outputs) { - BOOST_LOG(info) << "[kwingrab] Found output: "sv << output_parameter->name << " order: "sv << output_parameter->order << " position: "sv << output_parameter->pos_x << "x"sv << output_parameter->pos_y << " resolution: "sv << output_parameter->width << "x"sv << output_parameter->height; + logging::info("[kwingrab] Found output: {} order: {} position: {}x{} resolution: {}x{}", output_parameter->name, output_parameter->order, output_parameter->pos_x, output_parameter->pos_y, output_parameter->width, output_parameter->height); output_names.emplace_back(output_parameter->name); } return output_names; @@ -401,7 +402,7 @@ namespace kwin { int start(const std::string_view &output_name) { // Try find correct output by name if (outputs.empty()) { - BOOST_LOG(error) << "[kwingrab] no wl_output found"sv; + logging::error("[kwingrab] no wl_output found"sv); return -1; } struct wl_output *output = nullptr; @@ -427,12 +428,16 @@ namespace kwin { } else { // No screencast protocol found. Output an error based on newly initialized permission file. if (screencast_permission_helper_t::is_newly_initialized()) { - BOOST_LOG(error) << "[kwingrab] zkde_screencast_unstable_v1 not found in registry. "sv - "A new permission desktop file was automatically created but might now have been recognized yet. "sv - "Try restarting sunshine or set KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 to fully disable permission checks."sv; + logging::error( + "[kwingrab] zkde_screencast_unstable_v1 not found in registry. " + "A new permission desktop file was automatically created but might now have been recognized yet. " + "Try restarting sunshine or set KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 to fully disable permission checks." + ); } else { - BOOST_LOG(error) << "[kwingrab] zkde_screencast_unstable_v1 not found in registry. Check permission desktop file "sv - "for sunshine binary or set KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 to fully disable permission checks."sv; + logging::error( + "[kwingrab] zkde_screencast_unstable_v1 not found in registry. Check permission desktop file " + "for sunshine binary or set KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 to fully disable permission checks." + ); } return -1; } @@ -442,30 +447,27 @@ namespace kwin { } if (stream_failed) { - BOOST_LOG(error) << "[kwingrab] stream_output failed: "sv << stream_error_msg; + logging::error("[kwingrab] stream_output failed: {}", stream_error_msg); return -1; } // Check for valid node_id and/or object serial values here, stream_ready is just an internal flag if (out_node_id == PW_ID_ANY && (out_objectserial & SPA_ID_INVALID) == SPA_ID_INVALID) { - BOOST_LOG(error) << "[kwingrab] timeout waiting for created event"sv; + logging::error("[kwingrab] timeout waiting for created event"sv); return -1; } if ((out_objectserial & SPA_ID_INVALID) == SPA_ID_INVALID) { - BOOST_LOG(info) << "[kwingrab] Pipewire stream created: node="sv << out_node_id; + logging::info("[kwingrab] Pipewire stream created: node={}", out_node_id); } else { - BOOST_LOG(info) << "[kwingrab] Pipewire stream created: objectserial="sv << out_objectserial << " (node="sv << out_node_id << ")"sv; + logging::info("[kwingrab] Pipewire stream created: objectserial={} (node={})", out_objectserial, out_node_id); } if (out_params->width == 0 || out_params->height == 0) { - BOOST_LOG(error) << "[kwingrab] could not determine output dimensions"sv; + logging::error("[kwingrab] could not determine output dimensions"sv); return -1; } - BOOST_LOG(info) << "[kwingrab] Screencasting output"sv - << " name "sv << out_params->name - << " position "sv << out_params->pos_x << "x"sv << out_params->pos_y - << " resolution "sv << out_params->width << "x"sv << out_params->height; + logging::info("[kwingrab] Screencasting output name {} position {}x{} resolution {}x{}", out_params->name, out_params->pos_x, out_params->pos_y, out_params->width, out_params->height); return 0; } @@ -505,7 +507,7 @@ namespace kwin { } if (poll(&pfd, 1, remaining.count()) > 0 && (pfd.revents & POLLIN) && wl_display_dispatch(wl_display) < 0) { - BOOST_LOG(error) << "[kwingrab] wl_display_dispatch failed"sv; + logging::error("[kwingrab] wl_display_dispatch failed"sv); return -1; } } @@ -532,7 +534,7 @@ namespace kwin { wl_registry_bind(reg, name, &kde_output_order_v1_interface, bind_ver) ); kde_output_order_v1_add_listener(self->kde_output_order, &output_order_listener, self); - BOOST_LOG(debug) << "[kwingrab] bound kde_output_order_v1 version "sv << bind_ver; + logging::debug("[kwingrab] bound kde_output_order_v1 version {}", bind_ver); } else if (!std::strcmp(interface, zkde_screencast_unstable_v1_interface.name)) { // Bind version 1 to 6 — We use stream_output from v1 for node_id (deprecated but good as a fall-back) // but also try to get the newer (re-use safe) pipewire objectserial from v6 @@ -540,7 +542,7 @@ namespace kwin { self->kde_screencast_v1_ = static_cast( wl_registry_bind(reg, name, &zkde_screencast_unstable_v1_interface, bind_ver) ); - BOOST_LOG(debug) << "[kwingrab] bound zkde_screencast_unstable_v1 version "sv << bind_ver; + logging::debug("[kwingrab] bound zkde_screencast_unstable_v1 version {}", bind_ver); } else if (!std::strcmp(interface, wl_output_interface.name)) { // Bind version 4 - we need wl_output name for matching uint32_t bind_ver = std::min(version, static_cast(4)); @@ -551,10 +553,14 @@ namespace kwin { const auto [_, inserted] = self->outputs.try_emplace(output, std::make_shared()); if (inserted) { wl_output_add_listener(output, &output_listener, self); - BOOST_LOG(debug) << "[kwingrab] bound wl_output version "sv << bind_ver << " instance: "sv << output; + logging::debug([&](std::ostream &out) { + out << "[kwingrab] bound wl_output version "sv << bind_ver << " instance: "sv << output; + }); } else { // If we for some odd reason cannot add the output to the map clean it up and log a warning - BOOST_LOG(warning) << "[kwingrab] Ignoring output "sv << output << " because map emplace failed."sv; + logging::warning([&](std::ostream &out) { + out << "[kwingrab] Ignoring output "sv << output << " because map emplace failed."sv; + }); wl_output_destroy(output); } } @@ -631,7 +637,7 @@ namespace kwin { // ScreenCast v1 stream listener static void on_stream_closed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]]) { auto *self = static_cast(data); - BOOST_LOG(warning) << "[kwingrab] stream closed by server"sv; + logging::warning("[kwingrab] stream closed by server"sv); self->stream_failed = false; self->stream_ready = false; self->stream_error_msg = "stream closed by server"; @@ -642,7 +648,7 @@ namespace kwin { self->out_node_id = node; self->stream_failed = false; self->stream_ready = true; - BOOST_LOG(debug) << "[kwingrab] created event, node_id="sv << node; + logging::debug("[kwingrab] created event, node_id={}", node); } static void on_stream_failed(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], const char *err_msg) { @@ -650,14 +656,14 @@ namespace kwin { self->stream_failed = true; self->stream_ready = false; self->stream_error_msg = err_msg ? err_msg : "unknown error"; - BOOST_LOG(error) << "[kwingrab] failed event: "sv << self->stream_error_msg; + logging::error("[kwingrab] failed event: {}", self->stream_error_msg); } static void on_stream_serial(void *data, struct zkde_screencast_stream_unstable_v1 *stream [[maybe_unused]], uint32_t object_serial_hi, uint32_t object_serial_low) { auto *self = static_cast(data); self->out_objectserial = static_cast(object_serial_hi) << 32 | object_serial_low; // serial event always preceded the created event with the node id, so we only set stream_ready in created for v1 - BOOST_LOG(debug) << "[kwingrab] serial event, objectserial="sv << self->out_objectserial; + logging::debug("[kwingrab] serial event, objectserial={}", self->out_objectserial); } static constexpr struct zkde_screencast_stream_unstable_v1_listener stream_listener = { @@ -727,7 +733,7 @@ namespace platf { */ std::shared_ptr kwin_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (!pipewire::pipewire_display_t::init_pipewire_and_check_hwdevice_type(hwdevice_type)) { - BOOST_LOG(error) << "[kwingrab] Could not initialize pipewire-based display with the given hw device type."sv; + logging::error("[kwingrab] Could not initialize pipewire-based display with the given hw device type."sv); return nullptr; } diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index d00f794a5..76fa4dd1b 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -125,7 +125,9 @@ namespace dyn { ss << ']'; - BOOST_LOG(error) << ss.str(); + logging::error([&](std::ostream &out) { + out << ss.str(); + }); return nullptr; } @@ -141,7 +143,7 @@ namespace dyn { *fn = SUNSHINE_GNUC_EXTENSION(apiproc) dlsym(handle, name); if (!*fn && strict) { - BOOST_LOG(error) << "Couldn't find function: "sv << name; + logging::error("Couldn't find function: {}", name); err = -1; } @@ -210,7 +212,9 @@ namespace platf { #ifdef SUNSHINE_BUILD_DRM int fd = open(path.c_str(), flags | O_CLOEXEC); if (fd < 0) { - BOOST_LOG(error) << "Couldn't open: "sv << path.string() << ": "sv << strerror(errno); + logging::error([&](std::ostream &out) { + out << "Couldn't open: "sv << path.string() << ": "sv << strerror(errno); + }); return -1; } @@ -232,35 +236,47 @@ namespace platf { return 1; ///< Ioctl reached the master path but the magic (0) was invalid; we are master. } - BOOST_LOG(warning) << "Couldn't determine DRM master state for "sv << path.string() << ": "sv << strerror(err); + logging::warning([&](std::ostream &out) { + out << "Couldn't determine DRM master state for "sv << path.string() << ": "sv << strerror(err); + }); return -1; }; auto master = is_master(); if (master < 0) { - BOOST_LOG(warning) << "Proceeding without dropping DRM master for "sv << path.string() - << "; compositor VT switches may fail."sv; + logging::warning([&](std::ostream &out) { + out << "Proceeding without dropping DRM master for "sv << path.string() + << "; compositor VT switches may fail."sv; + }); return fd; } if (master) { if (drmDropMaster(fd)) { auto err = errno; - BOOST_LOG(warning) << "Couldn't drop DRM master for "sv << path.string() << ": "sv << strerror(err) - << ", Compositor VT switches may fail."sv; + logging::warning([&](std::ostream &out) { + out << "Couldn't drop DRM master for "sv << path.string() << ": "sv << strerror(err) + << ", Compositor VT switches may fail."sv; + }); return fd; } - BOOST_LOG(info) << "Dropped DRM master for "sv << path.string(); + logging::info([&](std::ostream &out) { + out << "Dropped DRM master for "sv << path.string(); + }); master = is_master(); if (master < 0) { - BOOST_LOG(warning) << "Could not re-verify DRM master state after drop for "sv << path.string() << "."sv; + logging::warning([&](std::ostream &out) { + out << "Could not re-verify DRM master state after drop for "sv << path.string() << "."sv; + }); return fd; } if (master) { - BOOST_LOG(warning) << "Still DRM master after drop for "sv << path.string() << "."sv; + logging::warning([&](std::ostream &out) { + out << "Still DRM master after drop for "sv << path.string() << "."sv; + }); return fd; } } @@ -268,7 +284,9 @@ namespace platf { return fd; #else #ifndef __FreeBSD__ - BOOST_LOG(info) << "Sunshine compiled without DRM support. Cannot control Linux DRM master state for "sv << path.string(); + logging::info([&](std::ostream &out) { + out << "Sunshine compiled without DRM support. Cannot control Linux DRM master state for "sv << path.string(); + }); #endif return open(path.c_str(), flags | O_CLOEXEC); #endif @@ -465,7 +483,7 @@ namespace platf { } #endif - BOOST_LOG(warning) << "Unable to find MAC address for "sv << address; + logging::warning("Unable to find MAC address for {}", address); return "00:00:00:00:00:00"s; } @@ -503,9 +521,11 @@ namespace platf { std::error_code ec; auto child = run_command(false, false, cmd, working_dir, _env, nullptr, ec, nullptr); if (ec) { - BOOST_LOG(warning) << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + }); } else { - BOOST_LOG(info) << "Opened url ["sv << url << "]"sv; + logging::info("Opened url [{}]", url); child.detach(); } } @@ -537,7 +557,7 @@ namespace platf { linux_nice = -15; break; default: - BOOST_LOG(debug) << "Unknown thread priority: "sv << std::to_underlying(priority); + logging::debug("Unknown thread priority: {}", std::to_underlying(priority)); return; } @@ -561,9 +581,9 @@ namespace platf { if (!err) { success = true; - BOOST_LOG(debug) << "RTKit: Successfully set priority to "sv << linux_nice; + logging::debug("RTKit: Successfully set priority to {}", linux_nice); } else { - BOOST_LOG(debug) << "RTKit: Could not set priority: "sv << err->message; + logging::debug("RTKit: Could not set priority: {}", err->message); g_clear_error(&err); } } @@ -571,9 +591,11 @@ namespace platf { if (!success) { // This will run on FreeBSD OR Linux if RTKit failed/was missing if (setpriority(PRIO_PROCESS, 0, linux_nice) == -1) { - BOOST_LOG(warning) << "setpriority failed for nice "sv << linux_nice << ": "sv << strerror(errno); + logging::warning([&](std::ostream &out) { + out << "setpriority failed for nice "sv << linux_nice << ": "sv << strerror(errno); + }); } else { - BOOST_LOG(debug) << "setpriority success for nice "sv << linux_nice; + logging::debug("setpriority success for nice {}", linux_nice); } } } @@ -612,7 +634,9 @@ namespace platf { std::array executable; ssize_t len = readlink("/proc/self/exe", executable.data(), executable.size() - 1); if (len == -1) { - BOOST_LOG(fatal) << "readlink() failed: "sv << errno; + logging::fatal([&](std::ostream &out) { + out << "readlink() failed: "sv << errno; + }); return; } executable[len] = '\0'; @@ -625,7 +649,9 @@ namespace platf { // Re-exec ourselves with the same arguments if (execv(executable.data(), argv) < 0) { - BOOST_LOG(fatal) << "execv() failed: "sv << errno; + logging::fatal([&](std::ostream &out) { + out << "execv() failed: "sv << errno; + }); return; } } @@ -644,10 +670,12 @@ namespace platf { bool request_process_group_exit(std::uintptr_t native_handle) { if (kill(-((pid_t) native_handle), SIGTERM) == 0 || errno == ESRCH) { - BOOST_LOG(debug) << "Successfully sent SIGTERM to process group: "sv << native_handle; + logging::debug("Successfully sent SIGTERM to process group: {}", native_handle); return true; } else { - BOOST_LOG(warning) << "Unable to send SIGTERM to process group ["sv << native_handle << "]: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "Unable to send SIGTERM to process group ["sv << native_handle << "]: "sv << errno; + }); return false; } } @@ -854,7 +882,9 @@ namespace platf { pfd.events = POLLOUT; if (poll(&pfd, 1, -1) != 1) { - BOOST_LOG(warning) << "poll() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "poll() failed: "sv << errno; + }); break; } @@ -862,7 +892,9 @@ namespace platf { continue; } - BOOST_LOG(verbose) << "sendmsg() failed: "sv << errno; + logging::verbose([&](std::ostream &out) { + out << "sendmsg() failed: "sv << errno; + }); break; } @@ -916,7 +948,9 @@ namespace platf { pfd.events = POLLOUT; if (poll(&pfd, 1, -1) != 1) { - BOOST_LOG(warning) << "poll() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "poll() failed: "sv << errno; + }); break; } @@ -924,7 +958,9 @@ namespace platf { continue; } - BOOST_LOG(warning) << "sendmmsg() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "sendmmsg() failed: "sv << errno; + }); return false; } @@ -998,7 +1034,9 @@ namespace platf { pfd.events = POLLOUT; if (poll(&pfd, 1, -1) != 1) { - BOOST_LOG(warning) << "poll() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "poll() failed: "sv << errno; + }); break; } @@ -1007,7 +1045,9 @@ namespace platf { } if (bytes_sent < 0) { - BOOST_LOG(warning) << "sendmsg() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "sendmsg() failed: "sv << errno; + }); return false; } @@ -1150,7 +1190,9 @@ namespace platf { for (const auto &tuple : options) { auto reset_val = std::get<2>(tuple); if (setsockopt(sockfd, std::get<0>(tuple), std::get<1>(tuple), &reset_val, sizeof(reset_val)) < 0) { - BOOST_LOG(warning) << "Failed to reset option: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "Failed to reset option: "sv << errno; + }); } } } @@ -1194,7 +1236,7 @@ namespace platf { dscp = 48; break; default: - BOOST_LOG(error) << "Unknown traffic type: "sv << (int) data_type; + logging::error("Unknown traffic type: {}", (int) data_type); break; } @@ -1206,7 +1248,9 @@ namespace platf { // Reset TOS to -1 when QoS is disabled reset_options.emplace_back(std::make_tuple(level, option, -1)); } else { - BOOST_LOG(error) << "Failed to set TOS/TCLASS: "sv << errno; + logging::error([&](std::ostream &out) { + out << "Failed to set TOS/TCLASS: "sv << errno; + }); } } } @@ -1219,14 +1263,16 @@ namespace platf { // 6 is the highest priority that can be used without SYS_CAP_ADMIN. #ifndef SO_PRIORITY // FreeBSD doesn't support SO_PRIORITY, so we skip this - BOOST_LOG(debug) << "SO_PRIORITY not supported on this platform, skipping traffic priority setting"; + logging::debug("SO_PRIORITY not supported on this platform, skipping traffic priority setting"); #else int priority = data_type == qos_data_type_e::audio ? 6 : 5; if (setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) == 0) { // Reset SO_PRIORITY to 0 when QoS is disabled reset_options.emplace_back(std::make_tuple(SOL_SOCKET, SO_PRIORITY, 0)); } else { - BOOST_LOG(error) << "Failed to set SO_PRIORITY: "sv << errno; + logging::error([&](std::ostream &out) { + out << "Failed to set SO_PRIORITY: "sv << errno; + }); } #endif @@ -1237,7 +1283,7 @@ namespace platf { try { return boost::asio::ip::host_name(); } catch (boost::system::system_error &err) { - BOOST_LOG(error) << "Failed to get hostname: "sv << err.what(); + logging::error("Failed to get hostname: {}", err.what()); return "Sunshine"s; } } @@ -1343,16 +1389,18 @@ namespace platf { case available: return true; case unreachable: - BOOST_LOG(debug) << "[portalgrab] xdg-desktop-portal not reachable; skipping Portal capture."sv; + logging::debug("[portalgrab] xdg-desktop-portal not reachable; skipping Portal capture."sv); return false; case stale_token: - BOOST_LOG(warning) << "[portalgrab] Saved portal token did not produce a session; discarding and restarting."sv; + logging::warning("[portalgrab] Saved portal token did not produce a session; discarding and restarting."sv); portal::clear_saved_token(); platf::restart(lifetime); return false; case no_token: - BOOST_LOG(fatal) << "Portal capture is awaiting user permission. "sv - << "The current session will attempt to use a fallback capture method."sv; + logging::fatal( + "Portal capture is awaiting user permission. " + "The current session will attempt to use a fallback capture method." + ); std::call_once(xdg_worker_flag, [this]() { xdg_worker = std::jthread([this]() { try { @@ -1360,12 +1408,12 @@ namespace platf { if (!portal_display_names(false, mail).empty()) { platf::restart(lifetime); } else { - BOOST_LOG(error) << "[portalgrab] Portal session token was not negotiated."sv; + logging::error("[portalgrab] Portal session token was not negotiated."sv); } } catch (const std::exception &e) { - BOOST_LOG(error) << "[portalgrab] Exception caught in xdg_worker: "sv << e.what(); + logging::error("[portalgrab] Exception caught in xdg_worker: {}", e.what()); } catch (...) { - BOOST_LOG(error) << "[portalgrab] Unknown exception caught in xdg_worker"sv; + logging::error("[portalgrab] Unknown exception caught in xdg_worker"sv); } }); }); @@ -1446,14 +1494,14 @@ namespace platf { #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { - BOOST_LOG(info) << "Screencasting with KMS"sv; + logging::info("Screencasting with KMS"sv); return kms_display(settings, hwdevice_type, display_name, config, *kms_state, window_system, hevc_mode); } #endif #ifdef SUNSHINE_BUILD_CUDA if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) { - BOOST_LOG(info) << "Screencasting with NvFBC"sv; + logging::info("Screencasting with NvFBC"sv); return nvfbc_display(hwdevice_type, display_name, config); } #endif @@ -1465,25 +1513,25 @@ namespace platf { #ifdef SUNSHINE_BUILD_WAYLAND if (sources[source::WAYLAND]) { - BOOST_LOG(info) << "Screencasting with Wayland's protocol"sv; + logging::info("Screencasting with Wayland's protocol"sv); return wl_display(settings, hwdevice_type, display_name, config); } #endif #ifdef SUNSHINE_BUILD_X11 if (sources[source::X11]) { - BOOST_LOG(info) << "Screencasting with X11"sv; + logging::info("Screencasting with X11"sv); return x11_display(settings, hwdevice_type, display_name, config, scheduler); } #endif #ifdef SUNSHINE_BUILD_PORTAL if (sources[source::PORTAL]) { - BOOST_LOG(info) << "Screencasting with XDG portal"sv; + logging::info("Screencasting with XDG portal"sv); return portal_display(settings, hwdevice_type, display_name, config, mail); } #endif #ifdef SUNSHINE_BUILD_KWIN if (sources[source::KWIN]) { - BOOST_LOG(info) << "Screencasting with KWin ScreenCast"sv; + logging::info("Screencasting with KWin ScreenCast"sv); return kwin_display(settings, hwdevice_type, display_name, config); } #endif @@ -1526,7 +1574,7 @@ namespace platf { #if defined(SUNSHINE_BUILD_X11) || defined(SUNSHINE_BUILD_CUDA) if (std::string v; lizardbyte::common::get_env("DISPLAY", v) && window_system != window_system_e::WAYLAND) { if (lizardbyte::common::get_env("WAYLAND_DISPLAY", v)) { - BOOST_LOG(warning) << "Wayland detected, yet sunshine will use X11 for screencasting, screencasting will only work on XWayland applications"sv; + logging::warning("Wayland detected, yet sunshine will use X11 for screencasting, screencasting will only work on XWayland applications"sv); } window_system = window_system_e::X11; @@ -1581,12 +1629,12 @@ namespace platf { #endif if (sources.none()) { - BOOST_LOG(error) << "Unable to initialize capture method"sv; + logging::error("Unable to initialize capture method"sv); return false; } if (!gladLoaderLoadEGL(NULL)) { - BOOST_LOG(error) << "Failed to load EGL library symbols"sv; + logging::error("Failed to load EGL library symbols"sv); return false; } @@ -1686,14 +1734,14 @@ namespace platf { const auto caps_to_check = all_caps ? ELEVATED_PRIVILEGES_FULL : ELEVATED_PRIVILEGES_ADMIN; const cap_t caps = cap_get_proc(); if (!caps) { - BOOST_LOG(error) << "[misc] has_elevated_privileges failed to get process capabilities."sv; + logging::error("[misc] has_elevated_privileges failed to get process capabilities."sv); return false; } for (const auto c : caps_to_check) { cap_flag_value_t cap_flags_value; cap_get_flag(caps, c, CAP_EFFECTIVE, &cap_flags_value); if (cap_flags_value == CAP_SET) { - BOOST_LOG(debug) << "[misc] has_elevated_privileges found effective cap:"sv << c; + logging::debug("[misc] has_elevated_privileges found effective cap:{}", c); return true; } } @@ -1701,7 +1749,7 @@ namespace platf { cap_flag_value_t cap_flags_value; cap_get_flag(caps, c, CAP_PERMITTED, &cap_flags_value); if (cap_flags_value == CAP_SET) { - BOOST_LOG(debug) << "[misc] has_elevated_privileges found permitted cap:"sv << c; + logging::debug("[misc] has_elevated_privileges found permitted cap:{}", c); return true; } } @@ -1716,7 +1764,7 @@ namespace platf { const auto caps_to_drop = all_caps ? ELEVATED_PRIVILEGES_FULL : ELEVATED_PRIVILEGES_ADMIN; const cap_t caps = cap_get_proc(); if (!caps) { - BOOST_LOG(error) << "[misc] drop_elevated_privileges failed to get process capabilities"sv; + logging::error("[misc] drop_elevated_privileges failed to get process capabilities"sv); return; } @@ -1724,18 +1772,22 @@ namespace platf { cap_set_flag(caps, CAP_PERMITTED, caps_to_drop.size(), caps_to_drop.data(), CAP_CLEAR); if (cap_set_proc(caps) != 0) { - BOOST_LOG(error) << "[misc] drop_elevated_privileges failed to prune capabilities: "sv << std::strerror(errno); + logging::error([&](std::ostream &out) { + out << "[misc] drop_elevated_privileges failed to prune capabilities: "sv << std::strerror(errno); + }); failed = true; } cap_free(caps); // Reset dumpable AFTER the caps have been pruned to ensure /proc/pid/root is accessible. if (prctl(PR_SET_DUMPABLE, 1) != 0) { - BOOST_LOG(error) << "[misc] drop_elevated_privileges failed to set PR_SET_DUMPABLE: "sv << std::strerror(errno); + logging::error([&](std::ostream &out) { + out << "[misc] drop_elevated_privileges failed to set PR_SET_DUMPABLE: "sv << std::strerror(errno); + }); failed = true; } if (!failed) { - BOOST_LOG(info) << "[misc] drop_elevated_privileges succeeded in dropping capabilities"sv; + logging::info("[misc] drop_elevated_privileges succeeded in dropping capabilities"sv); } #endif } diff --git a/src/platform/linux/nvfbc_api.h b/src/platform/linux/nvfbc_api.h index adf09cab8..35c6897c4 100644 --- a/src/platform/linux/nvfbc_api.h +++ b/src/platform/linux/nvfbc_api.h @@ -48,12 +48,12 @@ namespace cuda::nvfbc { NVFBC_API_FUNCTION_LIST functions {.dwVersion = NVFBC_VERSION}; if (create_instance(&functions)) { - BOOST_LOG(error) << "Unable to create NvFBC instance"; + logging::error("Unable to create NvFBC instance"); return {}; } if (!functions.nvFBCCreateHandle || !functions.nvFBCDestroyHandle || !functions.nvFBCGetStatus || !functions.nvFBCGetLastErrorStr || !functions.nvFBCBindContext || !functions.nvFBCReleaseContext || !functions.nvFBCCreateCaptureSession || !functions.nvFBCDestroyCaptureSession || !functions.nvFBCToCudaSetUp || !functions.nvFBCToCudaGrabFrame) { - BOOST_LOG(error) << "NvFBC function table is incomplete"; + logging::error("NvFBC function table is incomplete"); return {}; } return std::shared_ptr(new api_t(std::move(library), functions)); diff --git a/src/platform/linux/pipewire.cpp b/src/platform/linux/pipewire.cpp index 855daee65..e8bebf753 100644 --- a/src/platform/linux/pipewire.cpp +++ b/src/platform/linux/pipewire.cpp @@ -148,16 +148,16 @@ namespace pipewire { public: pipewire_t(): loop(pw_thread_loop_new("Pipewire thread", nullptr)) { - BOOST_LOG(debug) << "[pipewire] Start PW thread loop"sv; + logging::debug("[pipewire] Start PW thread loop"sv); pw_thread_loop_start(loop); } ~pipewire_t() { - BOOST_LOG(debug) << "[pipewire] Destroying pipewire_t"sv; + logging::debug("[pipewire] Destroying pipewire_t"sv); pw_thread_loop_lock(loop); // Lock the frame mutex to stop fill_img - BOOST_LOG(debug) << "[pipewire] Stop fill_img"sv; + logging::debug("[pipewire] Stop fill_img"sv); { std::scoped_lock lock(stream_data.frame_mutex); stream_data.frame_ready = false; @@ -166,34 +166,34 @@ namespace pipewire { // Release pipewire stream if (stream_data.stream) { - BOOST_LOG(debug) << "[pipewire] Disconnect stream"sv; + logging::debug("[pipewire] Disconnect stream"sv); pw_stream_disconnect(stream_data.stream); - BOOST_LOG(debug) << "[pipewire] Destroy stream"sv; + logging::debug("[pipewire] Destroy stream"sv); pw_stream_destroy(stream_data.stream); stream_data.stream = nullptr; } // Release pipewire core if (core) { - BOOST_LOG(debug) << "[pipewire] Disconnect PW core"sv; + logging::debug("[pipewire] Disconnect PW core"sv); pw_core_disconnect(core); core = nullptr; } // Release pipewire context if (context) { - BOOST_LOG(debug) << "[pipewire] Destroy PW context"sv; + logging::debug("[pipewire] Destroy PW context"sv); pw_context_destroy(context); context = nullptr; } // Release pipewire file descriptor if (fd >= 0) { - BOOST_LOG(debug) << "[pipewire] Close pipewire_fd"sv; + logging::debug("[pipewire] Close pipewire_fd"sv); close(fd); } // Release pipewire thread loop - BOOST_LOG(debug) << "[pipewire] Stop PW thread loop"sv; + logging::debug("[pipewire] Stop PW thread loop"sv); pw_thread_loop_unlock(loop); pw_thread_loop_stop(loop); - BOOST_LOG(debug) << "[pipewire] Destroy PW thread loop"sv; + logging::debug("[pipewire] Destroy PW thread loop"sv); pw_thread_loop_destroy(loop); } @@ -242,11 +242,12 @@ namespace pipewire { bool pacing_required = variable_rate || rate_comparison > 0; if (!variable_rate && rate_comparison < 0) { - BOOST_LOG(warning) - << "[pipewire] Sunshine frame pacing: disabled (negotiated rate lower than requested rate)"sv; + logging::warning("[pipewire] Sunshine frame pacing: disabled (negotiated rate lower than requested rate)"sv); } else { - BOOST_LOG(info) << "[pipewire] Sunshine frame pacing: "sv - << (pacing_required ? std::format("enabled ({}ms)", std::chrono::duration(requested_delay).count()) : "disabled (event-driven capture)"); + logging::info([&](std::ostream &out) { + out << "[pipewire] Sunshine frame pacing: "sv + << (pacing_required ? std::format("enabled ({}ms)", std::chrono::duration(requested_delay).count()) : "disabled (event-driven capture)"); + }); } return pacing_required; @@ -277,10 +278,10 @@ namespace pipewire { stream_data.shared = std::move(shared_state); pw_thread_loop_lock(loop); - BOOST_LOG(debug) << "[pipewire] Setup PW context"sv; + logging::debug("[pipewire] Setup PW context"sv); context = pw_context_new(pw_thread_loop_get_loop(loop), nullptr, 0); if (context) { - BOOST_LOG(debug) << "[pipewire] Connect PW context to fd"sv; + logging::debug("[pipewire] Connect PW context to fd"sv); if (fd >= 0) { core = pw_context_connect_fd(context, fd, nullptr, 0); } else { @@ -289,11 +290,15 @@ namespace pipewire { if (core) { pw_core_add_listener(core, &core_listener, &core_events, nullptr); } else { - BOOST_LOG(debug) << "[pipewire] Failed to connect to PW core. Error: "sv << errno << "(" << strerror(errno) << ")"sv; + logging::debug([&](std::ostream &out) { + out << "[pipewire] Failed to connect to PW core. Error: "sv << errno << "(" << strerror(errno) << ")"sv; + }); return -1; } } else { - BOOST_LOG(debug) << "[pipewire] Failed to setup PW context. Error: "sv << errno << "(" << strerror(errno) << ")"sv; + logging::debug([&](std::ostream &out) { + out << "[pipewire] Failed to setup PW context. Error: "sv << errno << "(" << strerror(errno) << ")"sv; + }); return -1; } @@ -318,14 +323,14 @@ namespace pipewire { int result = 0; if (!stream_data.stream) { if (!core) { - BOOST_LOG(debug) << "[pipewire] PW core not available. Cannot ensure stream."sv; + logging::debug("[pipewire] PW core not available. Cannot ensure stream."sv); pw_thread_loop_unlock(loop); return -1; } struct pw_properties *props = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", PW_KEY_MEDIA_ROLE, "Screen", nullptr); - BOOST_LOG(debug) << "[pipewire] Create PW stream"sv; + logging::debug("[pipewire] Create PW stream"sv); stream_data.stream = pw_stream_new(core, "Sunshine Video Capture", props); pw_stream_add_listener(stream_data.stream, &stream_data.stream_listener, &stream_events, &stream_data); @@ -360,7 +365,7 @@ namespace pipewire { // Connection via pipewire object serial if it is supported and the serial is valid (lower 32-bits != SPA_ID_INVALID, see also PW_KEY_OBJECT_SERIAL docs) if (SUNSHINE_USE_PIPEWIRE_OBJECT_SERIAL && (object_serial & SPA_ID_INVALID) != SPA_ID_INVALID) { pw_properties_setf(props, PW_KEY_TARGET_OBJECT, "%" PRIu64, object_serial); - BOOST_LOG(debug) << "[pipewire] Connect PW stream - fd: "sv << fd << " object serial: "sv << object_serial; + logging::debug("[pipewire] Connect PW stream - fd: {} object serial: {}", fd, object_serial); result = pw_stream_connect(stream_data.stream, PW_DIRECTION_INPUT, PW_ID_ANY, (enum pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS), params.data(), n_params); if (result < 0) { // Unset object serial for retry with node id @@ -371,7 +376,7 @@ namespace pipewire { } // Connection via legacy (and deprecated) pipewire node id if (result < 0) { - BOOST_LOG(debug) << "[pipewire] Connect PW stream - fd: "sv << fd << " node: "sv << node; + logging::debug("[pipewire] Connect PW stream - fd: {} node: {}", fd, node); result = pw_stream_connect(stream_data.stream, PW_DIRECTION_INPUT, node, (enum pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS), params.data(), n_params); } } @@ -565,8 +570,7 @@ namespace pipewire { break; } - BOOST_LOG(info) << "[pipewire] Using frame_timestamp (pts) metadata source: "sv - << (use_pts ? "Pipewire (via compositor)" : PROJECT_NAME); + logging::info("[pipewire] Using frame_timestamp (pts) metadata source: {}", (use_pts ? "Pipewire (via compositor)" : PROJECT_NAME)); return use_pts; } @@ -763,11 +767,11 @@ namespace pipewire { } static void on_core_info_cb([[maybe_unused]] void *user_data, const struct pw_core_info *pw_info) { - BOOST_LOG(info) << "[pipewire] Connected to pipewire version "sv << pw_info->version; + logging::info("[pipewire] Connected to pipewire version {}", pw_info->version); } static void on_core_error_cb([[maybe_unused]] void *user_data, const uint32_t id, const int seq, [[maybe_unused]] int res, const char *message) { - BOOST_LOG(info) << "[pipewire] Pipewire Error, id:"sv << id << " seq:"sv << seq << " message: "sv << message; + logging::info("[pipewire] Pipewire Error, id:{} seq:{} message: {}", id, seq, message); } constexpr static const struct pw_core_events core_events = { @@ -778,11 +782,9 @@ namespace pipewire { static void on_stream_state_changed(void *user_data, enum pw_stream_state old, enum pw_stream_state state, const char *err_msg) { if (err_msg != nullptr) { - BOOST_LOG(info) << "[pipewire] PipeWire stream error '" << err_msg << "' on state: " << pw_stream_state_as_string(old) - << " -> " << pw_stream_state_as_string(state); + logging::info("[pipewire] PipeWire stream error '{}' on state: {} -> {}", err_msg, pw_stream_state_as_string(old), pw_stream_state_as_string(state)); } else { - BOOST_LOG(info) << "[pipewire] PipeWire stream state: " << pw_stream_state_as_string(old) - << " -> " << pw_stream_state_as_string(state); + logging::info("[pipewire] PipeWire stream state: {} -> {}", pw_stream_state_as_string(old), pw_stream_state_as_string(state)); } auto *d = static_cast(user_data); @@ -891,16 +893,14 @@ namespace pipewire { return; } - BOOST_LOG(info) << "[pipewire] Video format: "sv << d->format.info.raw.format; - BOOST_LOG(info) << "[pipewire] Size: "sv << d->format.info.raw.size.width << "x"sv << d->format.info.raw.size.height; - BOOST_LOG(info) << "[pipewire] Color primaries: "sv << d->format.info.raw.color_primaries; - BOOST_LOG(info) << "[pipewire] Transfer function: "sv << d->format.info.raw.transfer_function; + logging::info("[pipewire] Video format: {}", static_cast(d->format.info.raw.format)); + logging::info("[pipewire] Size: {}x{}", d->format.info.raw.size.width, d->format.info.raw.size.height); + logging::info("[pipewire] Color primaries: {}", static_cast(d->format.info.raw.color_primaries)); + logging::info("[pipewire] Transfer function: {}", static_cast(d->format.info.raw.transfer_function)); if (d->format.info.raw.max_framerate.num == 0 && d->format.info.raw.max_framerate.denom == 1) { - BOOST_LOG(info) << "[pipewire] Compositor negotiated frame rate: 0/1 (variable rate capture)"sv; + logging::info("[pipewire] Compositor negotiated frame rate: 0/1 (variable rate capture)"sv); } else { - BOOST_LOG(info) << "[pipewire] Compositor negotiated frame rate: "sv - << d->format.info.raw.framerate.num << "/"sv << d->format.info.raw.framerate.denom - << ", max: "sv << d->format.info.raw.max_framerate.num << "/"sv << d->format.info.raw.max_framerate.denom; + logging::info("[pipewire] Compositor negotiated frame rate: {}/{}, max: {}/{}", d->format.info.raw.framerate.num, d->format.info.raw.framerate.denom, d->format.info.raw.max_framerate.num, d->format.info.raw.max_framerate.denom); } int physical_w = d->format.info.raw.size.width; @@ -933,10 +933,10 @@ namespace pipewire { uint32_t buffer_types = 0; if (spa_pod_find_prop(param, nullptr, SPA_FORMAT_VIDEO_modifier) != nullptr && d->drm_format) { - BOOST_LOG(info) << "[pipewire] using DMA-BUF buffers"sv; + logging::info("[pipewire] using DMA-BUF buffers"sv); buffer_types |= 1 << SPA_DATA_DmaBuf; } else { - BOOST_LOG(info) << "[pipewire] using memory buffers"sv; + logging::info("[pipewire] using memory buffers"sv); buffer_types |= 1 << SPA_DATA_MemPtr; } @@ -1025,13 +1025,13 @@ namespace pipewire { int desktop_logical_width = 0; int desktop_logical_height = 0; for (const auto &monitor : wl::monitors()) { - BOOST_LOG(debug) << "[pipewire] Found output: '"sv << monitor->name << "' offset: "sv << monitor->viewport.offset_x << 'x' << monitor->viewport.offset_y << " resolution: "sv << monitor->viewport.width << 'x' << monitor->viewport.height << " logical resolution: "sv << monitor->viewport.logical_width << 'x' << monitor->viewport.logical_height; + logging::debug("[pipewire] Found output: '{}' offset: {}x{} resolution: {}x{} logical resolution: {}x{}", monitor->name, monitor->viewport.offset_x, monitor->viewport.offset_y, monitor->viewport.width, monitor->viewport.height, monitor->viewport.logical_width, monitor->viewport.logical_height); // If logical_width and logical_height are not valid try to update them to correct values by matching to monitor // position/dimension or position/logical dimensions here since we're iterating for maximum environment size anyway if ((logical_width <= 0 || logical_height <= 0) && monitor->viewport.offset_x == offset_x && monitor->viewport.offset_y == offset_y && ((monitor->viewport.width == width && monitor->viewport.height == height) || (monitor->viewport.logical_width == width && monitor->viewport.logical_height == height))) { this->logical_width = monitor->viewport.logical_width; this->logical_height = monitor->viewport.logical_height; - BOOST_LOG(debug) << "[pipewire] Set logical resolution: "sv << logical_width << 'x' << logical_height; + logging::debug("[pipewire] Set logical resolution: {}x{}", logical_width, logical_height); } // Update desktop dimensions to setup maximum environment size over all screens desktop_width = std::max(desktop_width, monitor->viewport.offset_x + monitor->viewport.width); @@ -1043,12 +1043,12 @@ namespace pipewire { if (env_height <= 0 || env_width <= 0) { this->env_width = desktop_width; this->env_height = desktop_height; - BOOST_LOG(debug) << "[pipewire] Set desktop resolution: "sv << env_width << 'x' << env_height; + logging::debug("[pipewire] Set desktop resolution: {}x{}", env_width, env_height); } if (env_logical_height <= 0 || env_logical_width <= 0) { this->env_logical_width = desktop_logical_width; this->env_logical_height = desktop_logical_height; - BOOST_LOG(debug) << "[pipewire] Set desktop logical resolution: "sv << env_logical_width << 'x' << env_logical_height; + logging::debug("[pipewire] Set desktop logical resolution: {}x{}", env_logical_width, env_logical_height); } } } @@ -1072,11 +1072,11 @@ namespace pipewire { const AVRational fps = (pipewire.negotiate_variable_rate ? AVRational {0, 1} : ::video::framerate_to_rational(config)); if (fps.den != 1) { - BOOST_LOG(info) << "[pipewire] Requested frame rate: "sv << fps.num << "/"sv << fps.den << ", approx. "sv << av_q2d(fps) << " fps"sv; + logging::info("[pipewire] Requested frame rate: {}/{}, approx. {:.6g} fps", fps.num, fps.den, av_q2d(fps)); } else if (fps.num == 0 && fps.den == 1) { - BOOST_LOG(info) << "[pipewire] Requested variable frame rate (Sunshine pacing required: "sv << std::chrono::duration(delay).count() << "ms)"sv; + logging::info("[pipewire] Requested variable frame rate (Sunshine pacing required: {:.6g}ms)", std::chrono::duration(delay).count()); } else { - BOOST_LOG(info) << "[pipewire] Requested frame rate: "sv << fps.num << "fps"sv; + logging::info("[pipewire] Requested frame rate: {}fps", fps.num); } this->target_framerate = fps; mem_type = hwdevice_type; @@ -1090,10 +1090,10 @@ namespace pipewire { uint64_t pipewire_object_serial = SPA_ID_INVALID; // Default for invalid stream from pipewire docs for PW_KEY_OBJECT_SERIAL // Fetch stream info if (configure_stream(display_name, pipewire_fd, pipewire_node, pipewire_object_serial) < 0 || (pipewire_node == PW_ID_ANY && (pipewire_object_serial & SPA_ID_INVALID) == SPA_ID_INVALID)) { - BOOST_LOG(error) << "[pipewire] Could not find display with name: '"sv << display_name << "'"; + logging::error("[pipewire] Could not find display with name: '{}'", display_name); return -1; } - BOOST_LOG(info) << "[pipewire] Streaming display '"sv << display_name << "' offset: "sv << offset_x << "x"sv << offset_y << " resolution: "sv << width << "x"sv << height; + logging::info("[pipewire] Streaming display '{}' offset: {}x{} resolution: {}x{}", display_name, offset_x, offset_y, width, height); // Verify or update display parameters for streaming to ensure absolute touch inputs work as expected verify_and_update_display_parameters(); @@ -1112,13 +1112,13 @@ namespace pipewire { } if (pipewire.init(pipewire_fd, pipewire_node, pipewire_object_serial, shared_state) < 0) { - BOOST_LOG(error) << "[pipewire] Failed to init pipewire. pipewire_t::init() failed."; + logging::error("[pipewire] Failed to init pipewire. pipewire_t::init() failed."); return -1; } // Start PipeWire now so format negotiation can proceed before capture start if (pipewire.ensure_stream(mem_type, width, height, target_framerate, dmabuf_infos.data(), n_dmabuf_infos, display_is_nvidia) < 0) { - BOOST_LOG(error) << "[pipewire] Failed to ensure pipewire stream. pipewire_t::init() failed."; + logging::error("[pipewire] Failed to ensure pipewire stream. pipewire_t::init() failed."); return -1; } @@ -1139,7 +1139,7 @@ namespace pipewire { if (negotiated_w > 0 && negotiated_h > 0 && (negotiated_w != width || negotiated_h != height)) { width = negotiated_w; height = negotiated_h; - BOOST_LOG(info) << "[pipewire] Using negotiated Resolution: "sv << width << "x" << height; + logging::info("[pipewire] Using negotiated Resolution: {}x{}", width, height); // Reset and update display parameters for negotiated resolution env_width = 0; @@ -1230,7 +1230,7 @@ namespace pipewire { auto next_frame = std::chrono::steady_clock::now(); if (pipewire.ensure_stream(mem_type, width, height, target_framerate, dmabuf_infos.data(), n_dmabuf_infos, display_is_nvidia) < 0) { - BOOST_LOG(error) << "[pipewire] Failed to ensure pipewire stream. capture() failed with error."; + logging::error("[pipewire] Failed to ensure pipewire stream. capture() failed with error."); return platf::capture_e::error; } sleep_overshoot_logger.reset(); @@ -1246,7 +1246,7 @@ namespace pipewire { return status; } // Re-init the capture if the stream is dead for any other reason - BOOST_LOG(warning) << "[pipewire] PipeWire stream disconnected. Forcing session reset."sv; + logging::warning("[pipewire] PipeWire stream disconnected. Forcing session reset."sv); return platf::capture_e::reinit; } @@ -1265,23 +1265,23 @@ namespace pipewire { case platf::capture_e::timeout: if (!pull_free_image_cb(img_out)) { // Detect if shutdown is pending - BOOST_LOG(debug) << "[pipewire] PipeWire: timeout -> shutdown pending -> interrupt nudge"; + logging::debug("[pipewire] PipeWire: timeout -> shutdown pending -> interrupt nudge"); pipewire.frame_cv().notify_all(); return platf::capture_e::interrupted; } if (!push_captured_image_cb(std::move(img_out), false)) { - BOOST_LOG(debug) << "[pipewire] PipeWire: timeout -> !push_captured_image_cb -> ok"; + logging::debug("[pipewire] PipeWire: timeout -> !push_captured_image_cb -> ok"); return platf::capture_e::ok; } break; case platf::capture_e::ok: if (!push_captured_image_cb(std::move(img_out), true)) { - BOOST_LOG(debug) << "[pipewire] PipeWire: ok -> !push_captured_image_cb -> ok"; + logging::debug("[pipewire] PipeWire: ok -> !push_captured_image_cb -> ok"); return platf::capture_e::ok; } break; default: - BOOST_LOG(error) << "[pipewire] Unrecognized capture status ["sv << std::to_underlying(status) << ']'; + logging::error("[pipewire] Unrecognized capture status [{}]", std::to_underlying(status)); return status; } } @@ -1421,7 +1421,7 @@ namespace pipewire { img->sequence = ++sequence; if (retries > 0) { - BOOST_LOG(debug) << "[pipewire] Processed frame after " << retries << " redundant events."sv; + logging::debug("[pipewire] Processed frame after {} redundant events.", retries); } } @@ -1454,7 +1454,7 @@ namespace pipewire { eglQueryDmaBufFormatsEXT(egl_display, MAX_DMABUF_FORMATS, dmabuf_formats.data(), &num_dmabuf_formats); if (num_dmabuf_formats > MAX_DMABUF_FORMATS) { - BOOST_LOG(warning) << "[pipewire] Some DMA-BUF formats are being ignored"sv; + logging::warning("[pipewire] Some DMA-BUF formats are being ignored"sv); } for (const auto &fmt : format_map) { @@ -1471,7 +1471,7 @@ namespace pipewire { eglQueryDmaBufModifiersEXT(egl_display, fmt.fourcc, MAX_DMABUF_MODIFIERS, mods.data(), nullptr, &num_modifiers); if (num_modifiers > MAX_DMABUF_MODIFIERS) { - BOOST_LOG(warning) << "[pipewire] Some DMA-BUF modifiers are being ignored"sv; + logging::warning("[pipewire] Some DMA-BUF modifiers are being ignored"sv); } dmabuf_infos[n_dmabuf_infos].format = fmt.pw_format; @@ -1511,13 +1511,13 @@ namespace pipewire { bool intel_present = check_intel("/sys/class/drm/card0/device/vendor") || check_intel("/sys/class/drm/card1/device/vendor"); if (intel_present) { - BOOST_LOG(info) << "[pipewire] Hybrid GPU system detected (Intel + discrete) - CUDA will use memory buffers"sv; + logging::info("[pipewire] Hybrid GPU system detected (Intel + discrete) - CUDA will use memory buffers"sv); display_is_nvidia = false; } else { // No Intel GPU found, check if NVIDIA is present const char *vendor = eglQueryString(egl_display.get(), EGL_VENDOR); if (vendor && std::string_view(vendor).contains("NVIDIA")) { - BOOST_LOG(info) << "[pipewire] Pure NVIDIA system - DMA-BUF will be enabled for CUDA"sv; + logging::info("[pipewire] Pure NVIDIA system - DMA-BUF will be enabled for CUDA"sv); display_is_nvidia = true; } } diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index c81f3adc5..c3bfe51c1 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -84,7 +84,7 @@ namespace portal { if (file.is_open()) { std::getline(file, *token_); if (!token_->empty()) { - BOOST_LOG(info) << "[portalgrab] Loaded portal restore token from disk"sv; + logging::info("[portalgrab] Loaded portal restore token from disk"sv); } } } @@ -118,9 +118,9 @@ namespace portal { std::ofstream file(get_file_path()); if (file.is_open()) { file << *token_; - BOOST_LOG(info) << "[portalgrab] Saved portal restore token to disk"sv; + logging::info("[portalgrab] Saved portal restore token to disk"sv); } else { - BOOST_LOG(warning) << "[portalgrab] Failed to save portal restore token"sv; + logging::warning("[portalgrab] Failed to save portal restore token"sv); } } @@ -147,7 +147,7 @@ namespace portal { return std::isalnum(c) || c == '_' || c == '-'; }); !is_safe) { - BOOST_LOG(warning) << "[portalgrab] XDG session desktop type cannot be determined. Using .unknown suffix for Portal restore token."sv; + logging::warning("[portalgrab] XDG session desktop type cannot be determined. Using .unknown suffix for Portal restore token."sv); suffix = "unknown"; } @@ -163,9 +163,11 @@ namespace portal { // to this session type; if wrong, we're no worse off than not migrating. std::filesystem::rename(legacy_path, suffixed_path, ec); if (ec) { - BOOST_LOG(error) << "[portalgrab] Portal restore token migration failed: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "[portalgrab] Portal restore token migration failed: "sv << ec.message(); + }); } else { - BOOST_LOG(info) << "[portalgrab] Portal restore token migrated to portal_token."sv << suffix; + logging::info("[portalgrab] Portal restore token migrated to portal_token.{}", suffix); } } } @@ -332,15 +334,15 @@ namespace portal { ); if (err) { - BOOST_LOG(warning) << "[portalgrab] Failed to explicitly close portal session: "sv << err->message; + logging::warning("[portalgrab] Failed to explicitly close portal session: {}", err->message); } else { - BOOST_LOG(debug) << "[portalgrab] Explicitly closed portal session: "sv << session_handle; + logging::debug("[portalgrab] Explicitly closed portal session: {}", session_handle); } } } catch (const std::exception &e) { - BOOST_LOG(error) << "[portalgrab] Standard exception caught in ~dbus_t: "sv << e.what(); + logging::error("[portalgrab] Standard exception caught in ~dbus_t: {}", e.what()); } catch (...) { - BOOST_LOG(error) << "[portalgrab] Unknown exception caught in ~dbus_t"sv; + logging::error("[portalgrab] Unknown exception caught in ~dbus_t"sv); } if (pipewire_fd >= 0) { @@ -461,14 +463,14 @@ namespace portal { } if (select_remote_desktop_devices(loop, *session_path) < 0) { - BOOST_LOG(warning) << "[portalgrab] RemoteDesktop.SelectDevices failed, falling back to ScreenCast-only mode"sv; + logging::warning("[portalgrab] RemoteDesktop.SelectDevices failed, falling back to ScreenCast-only mode"sv); g_free(*session_path); *session_path = nullptr; return false; } if (select_screencast_sources(loop, *session_path, false) < 0) { - BOOST_LOG(warning) << "[portalgrab] ScreenCast.SelectSources failed with RemoteDesktop session, trying ScreenCast-only mode"sv; + logging::warning("[portalgrab] ScreenCast.SelectSources failed with RemoteDesktop session, trying ScreenCast-only mode"sv); g_free(*session_path); *session_path = nullptr; return false; @@ -523,7 +525,7 @@ namespace portal { ); // If we cannot get the property then the session portal was closed. if (err) { - BOOST_LOG(debug) << "[portalgrab] Session closed as check failed: "sv << err->message; + logging::debug("[portalgrab] Session closed as check failed: {}", err->message); return true; } } @@ -559,7 +561,7 @@ namespace portal { g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "CreateSession", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { - BOOST_LOG(error) << "[portalgrab] Could not create "sv << session_type << " session: "sv << err->message; + logging::error("[portalgrab] Could not create {} session: {}", session_type, err->message); return -1; } @@ -570,7 +572,7 @@ namespace portal { g_autoptr(GVariant) create_response = dbus_response_wait(&response, dbus_timeout); if (!create_response) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " CreateSession: no response received"sv; + logging::error("[portalgrab] {} CreateSession: no response received", session_type); return -1; } @@ -578,16 +580,16 @@ namespace portal { g_autoptr(GVariant) results = nullptr; g_variant_get(create_response, "(u@a{sv})", &response_code, &results); - BOOST_LOG(debug) << "[portalgrab] " << session_type << " CreateSession response_code: "sv << response_code; + logging::debug("[portalgrab] {} CreateSession response_code: {}", session_type, response_code); if (response_code != 0) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " CreateSession failed with response code: "sv << response_code; + logging::error("[portalgrab] {} CreateSession failed with response code: {}", session_type, response_code); return -1; } g_autoptr(GVariant) session_handle_v = g_variant_lookup_value(results, "session_handle", nullptr); if (!session_handle_v) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " CreateSession: session_handle not found in response"sv; + logging::error("[portalgrab] {} CreateSession: session_handle not found in response", session_type); return -1; } @@ -598,7 +600,7 @@ namespace portal { *session_path_out = g_strdup(g_variant_get_string(session_handle_v, nullptr)); } - BOOST_LOG(debug) << "[portalgrab] " << session_type << " CreateSession: got session handle: "sv << *session_path_out; + logging::debug("[portalgrab] {} CreateSession: got session handle: {}", session_type, *session_path_out); // Save it for the destructor to use during cleanup this->session_handle = *session_path_out; return 0; @@ -625,7 +627,7 @@ namespace portal { g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(remote_desktop_proxy, "SelectDevices", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { - BOOST_LOG(error) << "[portalgrab] Could not select devices: "sv << err->message; + logging::error("[portalgrab] Could not select devices: {}", err->message); return -1; } @@ -636,16 +638,16 @@ namespace portal { g_autoptr(GVariant) devices_response = dbus_response_wait(&response, dbus_timeout); if (!devices_response) { - BOOST_LOG(error) << "[portalgrab] SelectDevices: no response received"sv; + logging::error("[portalgrab] SelectDevices: no response received"sv); return -1; } guint32 response_code; g_variant_get(devices_response, "(u@a{sv})", &response_code, nullptr); - BOOST_LOG(debug) << "[portalgrab] SelectDevices response_code: "sv << response_code; + logging::debug("[portalgrab] SelectDevices response_code: {}", response_code); if (response_code != 0) { - BOOST_LOG(error) << "[portalgrab] SelectDevices failed with response code: "sv << response_code; + logging::error("[portalgrab] SelectDevices failed with response code: {}", response_code); return -1; } @@ -676,7 +678,7 @@ namespace portal { g_autoptr(GError) err = nullptr; g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(screencast_proxy, "SelectSources", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { - BOOST_LOG(error) << "[portalgrab] Could not select sources: "sv << err->message; + logging::error("[portalgrab] Could not select sources: {}", err->message); return -1; } @@ -687,16 +689,16 @@ namespace portal { g_autoptr(GVariant) sources_response = dbus_response_wait(&response, dbus_timeout); if (!sources_response) { - BOOST_LOG(error) << "[portalgrab] SelectSources: no response received"sv; + logging::error("[portalgrab] SelectSources: no response received"sv); return -1; } guint32 response_code; g_variant_get(sources_response, "(u@a{sv})", &response_code, nullptr); - BOOST_LOG(debug) << "[portalgrab] SelectSources response_code: "sv << response_code; + logging::debug("[portalgrab] SelectSources response_code: {}", response_code); if (response_code != 0) { - BOOST_LOG(error) << "[portalgrab] SelectSources failed with response code: "sv << response_code; + logging::error("[portalgrab] SelectSources failed with response code: {}", response_code); return -1; } @@ -722,7 +724,7 @@ namespace portal { g_autoptr(GError) err = nullptr; g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "Start", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { - BOOST_LOG(error) << "[portalgrab] Could not start "sv << session_type << " session: "sv << err->message; + logging::error("[portalgrab] Could not start {} session: {}", session_type, err->message); return -1; } @@ -733,7 +735,7 @@ namespace portal { g_autoptr(GVariant) start_response = dbus_response_wait(&response, (allow_start_timeout ? dbus_timeout : 0)); if (!start_response) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " Start: no response received"sv; + logging::error("[portalgrab] {} Start: no response received", session_type); return -1; } @@ -742,16 +744,16 @@ namespace portal { g_autoptr(GVariant) streams = nullptr; g_variant_get(start_response, "(u@a{sv})", &response_code, &dict); - BOOST_LOG(debug) << "[portalgrab] " << session_type << " Start response_code: "sv << response_code; + logging::debug("[portalgrab] {} Start response_code: {}", session_type, response_code); if (response_code != 0) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " Start failed with response code: "sv << response_code; + logging::error("[portalgrab] {} Start failed with response code: {}", session_type, response_code); return -1; } streams = g_variant_lookup_value(dict, "streams", G_VARIANT_TYPE("a(ua{sv})")); if (!streams) { - BOOST_LOG(error) << "[portalgrab] " << session_type << " Start: no streams in response"sv; + logging::error("[portalgrab] {} Start: no streams in response", session_type); return -1; } @@ -770,7 +772,7 @@ namespace portal { int out_height; bool result = g_variant_lookup(value, "size", "(ii)", &out_width, &out_height, nullptr); if (!result) { - BOOST_LOG(warning) << "[portalgrab] Ignoring stream without proper resolution on pipewire node "sv << out_pipewire_node; + logging::warning("[portalgrab] Ignoring stream without proper resolution on pipewire node {}", out_pipewire_node); continue; } @@ -778,7 +780,7 @@ namespace portal { int out_pos_y; result = g_variant_lookup(value, "position", "(ii)", &out_pos_x, &out_pos_y, nullptr); if (!result) { - BOOST_LOG(warning) << "[portalgrab] Falling back to position 0x0 for stream with resolution "sv << out_width << "x"sv << out_height << "on pipewire node "sv << out_pipewire_node; + logging::warning("[portalgrab] Falling back to position 0x0 for stream with resolution {}x{}on pipewire node {}", out_width, out_height, out_pipewire_node); out_pos_x = 0; out_pos_y = 0; } @@ -826,7 +828,7 @@ namespace portal { g_autoptr(GError) err = nullptr; g_autoptr(GVariant) reply = g_dbus_proxy_call_with_unix_fd_list_sync(screencast_proxy, "OpenPipeWireRemote", msg, G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &fd_list, nullptr, &err); if (err) { - BOOST_LOG(error) << "[portalgrab] Could not open pipewire remote: "sv << err->message; + logging::error("[portalgrab] Could not open pipewire remote: {}", err->message); return -1; } @@ -999,7 +1001,7 @@ namespace portal { return response->response; } - BOOST_LOG(info) << "[portalgrab] Portal request cancelled, timed out, or shutdown requested"sv; + logging::info("[portalgrab] Portal request cancelled, timed out, or shutdown requested"sv); close_request_async(response->conn, response->request_path); return nullptr; } @@ -1022,11 +1024,11 @@ namespace portal { int configure_stream(const std::string &display_name, int &out_pipewire_fd, uint32_t &out_pipewire_node, uint64_t &out_pipewire_object_serial [[maybe_unused]]) override { // Connect DBus portal session if (dbus.init() < 0) { - BOOST_LOG(error) << "[portalgrab] Failed to connect to dbus. portal_t setup failed."; + logging::error("[portalgrab] Failed to connect to dbus. portal_t setup failed."); return -1; } if (dbus.connect_to_portal(false) < 0) { - BOOST_LOG(error) << "[portalgrab] Failed to connect to portal. portal_t setup failed."; + logging::error("[portalgrab] Failed to connect to portal. portal_t setup failed."); return -1; } @@ -1035,7 +1037,7 @@ namespace portal { pipewire_streaminfo_t stream; auto streams = dbus.pipewire_streams; if (streams.empty()) { - BOOST_LOG(error) << "[portalgrab] No streams found on portal. portal_t setup failed."; + logging::error("[portalgrab] No streams found on portal. portal_t setup failed."); return -1; } for (auto &stream_ : streams) { @@ -1047,7 +1049,7 @@ namespace portal { } // Fall back to first stream if we cannot match the given display_name to a stream in currently available streams. if (use_fallback) { - BOOST_LOG(info) << "[portalgrab] Using first available stream as no matching stream was found for: '"sv << display_name << "'"; + logging::info("[portalgrab] Using first available stream as no matching stream was found for: '{}'", display_name); stream = dbus.pipewire_streams.at(0); } @@ -1078,14 +1080,14 @@ namespace portal { bool check_stream_dead(platf::capture_e &out_status) override { // If the pipewire stream stopped due to closed portal session stop the capture with an error if (dbus.is_session_closed()) { - BOOST_LOG(warning) << "[portalgrab] PipeWire stream stopped by closed portal session."sv; + logging::warning("[portalgrab] PipeWire stream stopped by closed portal session."sv); pipewire.frame_cv().notify_all(); out_status = platf::capture_e::error; return true; // Stop capture with error (due to out_status) } // Disable maxframerate negotiation if the stream died without having ever started (e.g. GNOME mutter does not support it) if (shared_state->previous_state != PW_STREAM_STATE_STREAMING && negotiate_maxframerate.load()) { - BOOST_LOG(warning) << "[portalgrab] Negotiation failed, will retry without maxFramerate"sv; + logging::warning("[portalgrab] Negotiation failed, will retry without maxFramerate"sv); negotiate_maxframerate.store(false); pipewire.set_negotiate_maxframerate(false); out_status = platf::capture_e::reinit; @@ -1116,7 +1118,7 @@ namespace platf { std::shared_ptr portal_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail) { using enum platf::mem_type_e; if (!pipewire::pipewire_display_t::init_pipewire_and_check_hwdevice_type(hwdevice_type)) { - BOOST_LOG(error) << "[portalgrab] Could not initialize pipewire-based display with the given hw device type."sv; + logging::error("[portalgrab] Could not initialize pipewire-based display with the given hw device type."sv); return nullptr; } @@ -1140,17 +1142,17 @@ namespace platf { auto dbus = std::make_shared(std::move(mail)); if (dbus->init() < 0) { - BOOST_LOG(warning) << "[portalgrab] Failed to connect to dbus. Cannot enumerate displays, returning empty list."; + logging::warning("[portalgrab] Failed to connect to dbus. Cannot enumerate displays, returning empty list."); return {}; } if (dbus->connect_to_portal(allow_start_timeout) < 0) { - BOOST_LOG(warning) << "[portalgrab] Failed to connect to portal. Cannot enumerate displays, returning empty list."; + logging::warning("[portalgrab] Failed to connect to portal. Cannot enumerate displays, returning empty list."); return {}; } for (auto stream_ : dbus->pipewire_streams) { - BOOST_LOG(info) << "[portalgrab] Found stream for display id/name: '"sv << stream_.monitor_name << "' position: "sv << stream_.pos_x << "x"sv << stream_.pos_y << " resolution: "sv << stream_.width << "x"sv << stream_.height; + logging::info("[portalgrab] Found stream for display id/name: '{}' position: {}x{} resolution: {}x{}", stream_.monitor_name, stream_.pos_x, stream_.pos_y, stream_.width, stream_.height); display_names.emplace_back(stream_.to_display_name()); } // Release the portal session as soon as possible to properly release related resources early. diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index 0b0511588..759f89a8c 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -77,19 +77,19 @@ namespace platf::publish { bool start(const std::string &instance_name) { poll.reset(api->simple_poll_new()); if (!poll) { - BOOST_LOG(error) << "Failed to create simple poll object."sv; + logging::error("Failed to create simple poll object."sv); return false; } name.reset(api->strdup(instance_name.c_str())); if (!name) { - BOOST_LOG(error) << "Failed to allocate Avahi service name."sv; + logging::error("Failed to allocate Avahi service name."sv); return false; } int avahi_error {}; // The callback can run synchronously, before client_new returns. client.reset(api->client_new(api->simple_poll_get(poll.get()), avahi::ClientFlags(0), client_callback, this, &avahi_error)); if (!client) { - BOOST_LOG(error) << "Failed to create client: "sv << api->strerror(avahi_error); + logging::error("Failed to create client: {}", api->strerror(avahi_error)); return false; } poll_thread = std::jthread {[this]() { @@ -131,7 +131,7 @@ namespace platf::publish { if (name) { return true; } - BOOST_LOG(error) << "Failed to allocate alternative Avahi service name."sv; + logging::error("Failed to allocate alternative Avahi service name."sv); api->simple_poll_quit(poll.get()); return false; } @@ -147,19 +147,19 @@ namespace platf::publish { switch (state) { case avahi::ENTRY_GROUP_ESTABLISHED: - BOOST_LOG(info) << "Avahi service " << name.get() << " successfully established."; + logging::info("Avahi service {} successfully established.", name.get()); break; case avahi::ENTRY_GROUP_COLLISION: if (!rename_service()) { break; } - BOOST_LOG(info) << "Avahi service name collision, renaming service to " << name.get(); + logging::info("Avahi service name collision, renaming service to {}", name.get()); create_services(api->entry_group_get_client(g)); break; case avahi::ENTRY_GROUP_FAILURE: - BOOST_LOG(error) << "Avahi entry group failure: " << api->strerror(api->client_errno(api->entry_group_get_client(g))); + logging::error("Avahi entry group failure: {}", api->strerror(api->client_errno(api->entry_group_get_client(g)))); api->simple_poll_quit(poll.get()); break; case avahi::ENTRY_GROUP_UNCOMMITED: @@ -179,7 +179,7 @@ namespace platf::publish { if (!group) { if (!(group = api->entry_group_new(c, entry_group_callback, this))) { - BOOST_LOG(error) << "api->entry_group_new() failed: "sv << api->strerror(api->client_errno(c)); + logging::error("api->entry_group_new() failed: {}", api->strerror(api->client_errno(c))); return; } } @@ -190,7 +190,7 @@ namespace platf::publish { } if (api->entry_group_is_empty(group)) { - BOOST_LOG(info) << "Adding avahi service "sv << name.get(); + logging::info("Adding avahi service {}", name.get()); ret = api->entry_group_add_service( group, @@ -211,7 +211,7 @@ namespace platf::publish { if (!rename_service()) { return; } - BOOST_LOG(info) << "Service name collision, renaming service to "sv << name.get(); + logging::info("Service name collision, renaming service to {}", name.get()); api->entry_group_reset(group); @@ -221,13 +221,13 @@ namespace platf::publish { return; } - BOOST_LOG(error) << "Failed to add "sv << platf::SERVICE_TYPE << " service: "sv << api->strerror(ret); + logging::error("Failed to add {} service: {}", platf::SERVICE_TYPE, api->strerror(ret)); return; } ret = api->entry_group_commit(group); if (ret < 0) { - BOOST_LOG(error) << "Failed to commit entry group: "sv << api->strerror(ret); + logging::error("Failed to commit entry group: {}", api->strerror(ret)); return; } } @@ -247,7 +247,7 @@ namespace platf::publish { create_services(c); break; case avahi::CLIENT_FAILURE: - BOOST_LOG(error) << "Client failure: "sv << api->strerror(api->client_errno(c)); + logging::error("Client failure: {}", api->strerror(api->client_errno(c))); api->simple_poll_quit(poll.get()); break; case avahi::CLIENT_S_COLLISION: diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index 2394e831f..2a2a8bcc1 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -192,7 +192,7 @@ namespace va { auto gbm_api = gbm::api_t::load(); if (!gbm_api) { - BOOST_LOG(warning) << "libgbm not initialized"sv; + logging::warning("libgbm not initialized"sv); return -1; } @@ -201,7 +201,9 @@ namespace va { gbm = gbm::make_device(std::move(gbm_api), file.el); if (!gbm) { std::array string; - BOOST_LOG(error) << "Couldn't create GBM device: ["sv << strerror_r(errno, string.data(), string.size()) << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't create GBM device: ["sv << strerror_r(errno, string.data(), string.size()) << ']'; + }); return -1; } @@ -233,7 +235,7 @@ namespace va { int num_eps; auto status = vaQueryConfigEntrypoints(va_display, profile, entrypoints.data(), &num_eps); if (status != VA_STATUS_SUCCESS) { - BOOST_LOG(error) << "Failed to query VA entrypoints: "sv << vaErrorStr(status); + logging::error("Failed to query VA entrypoints: {}", vaErrorStr(status)); return (VAEntrypoint) 0; } entrypoints.resize(num_eps); @@ -263,7 +265,7 @@ namespace va { int num_profs; auto status = vaQueryConfigProfiles(va_display, profiles.data(), &num_profs); if (status != VA_STATUS_SUCCESS) { - BOOST_LOG(error) << "Failed to query VA profiles: "sv << vaErrorStr(status); + logging::error("Failed to query VA profiles: {}", vaErrorStr(status)); return false; } profiles.resize(num_profs); @@ -304,7 +306,7 @@ namespace va { } } - BOOST_LOG(error) << "Unknown encoder profile: "sv << ctx->profile; + logging::error("Unknown encoder profile: {}", static_cast(ctx->profile)); return VAProfileNone; } @@ -330,10 +332,10 @@ namespace va { auto vendor = vaQueryVendorString(va_display); if (va_entrypoint == VAEntrypointEncSliceLP) { - BOOST_LOG(info) << "Using LP encoding mode"sv; + logging::info("Using LP encoding mode"sv); av_dict_set_int(options, "low_power", 1, 0); } else { - BOOST_LOG(info) << "Using normal encoding mode"sv; + logging::info("Using normal encoding mode"sv); } // When the compression_level AVOption is set, vaapi_encode.c assigns the value to VAEncMiscParameterBufferQualityLevel @@ -362,7 +364,7 @@ namespace va { } if (target_quality > 0) { ctx->compression_level = target_quality; - BOOST_LOG(info) << "[VAAPI] Quality level set to "sv << ctx->compression_level << " (fastest level: "sv << quality_attr.value << ")"sv; + logging::info("[VAAPI] Quality level set to {} (fastest level: {})", ctx->compression_level, quality_attr.value); } VAConfigAttrib rc_attr = {.type = VAConfigAttribRateControl}; @@ -379,7 +381,7 @@ namespace va { slice_attr.value = 1; } if (ctx->slices > slice_attr.value) { - BOOST_LOG(info) << "Limiting slice count to encoder maximum: "sv << slice_attr.value; + logging::info("Limiting slice count to encoder maximum: {}", slice_attr.value); ctx->slices = slice_attr.value; } @@ -436,10 +438,10 @@ namespace va { }); av_dict_set(options, "rc_mode", rc_mode.c_str(), 0); if (rc_val == VA_RC_CQP || rc_val == VA_RC_ICQ || rc_val == VA_RC_QVBR) { - BOOST_LOG(warning) << "[VAAPI] Applying QP for compatible rate control method (QP value: "sv << settings.video.qp << ")"sv; + logging::warning("[VAAPI] Applying QP for compatible rate control method (QP value: {})", settings.video.qp); av_dict_set_int(options, "qp", settings.video.qp, 0); } - BOOST_LOG(info) << "[VAAPI] Using "sv << rc_mode << " rate control "sv << rc_vbv << rc_whitelist; + logging::info("[VAAPI] Using {} rate control {}{}", rc_mode, rc_vbv, rc_whitelist); } /** @@ -455,7 +457,7 @@ namespace va { if (!frame->buf[0]) { if (av_hwframe_get_buffer(hw_frames_ctx_buf, frame, 0)) { - BOOST_LOG(error) << "Couldn't get hwframe for VAAPI"sv; + logging::error("Couldn't get hwframe for VAAPI"sv); return -1; } } @@ -472,7 +474,7 @@ namespace va { &prime ); if (status) { - BOOST_LOG(error) << "Couldn't export va surface handle: ["sv << (int) surface << "]: "sv << vaErrorStr(status); + logging::error("Couldn't export va surface handle: [{}]: {}", (int) surface, vaErrorStr(status)); return -1; } @@ -484,7 +486,7 @@ namespace va { } if (prime.num_layers != 2) { - BOOST_LOG(error) << "Invalid layer count for VA surface: expected 2, got "sv << prime.num_layers; + logging::error("Invalid layer count for VA surface: expected 2, got {}", prime.num_layers); return -1; } @@ -676,8 +678,24 @@ namespace va { unsigned int driver_quirks; } AVVAAPIDeviceContext; - static void __log(void *level, const char *msg) { - BOOST_LOG(*(logging::logger_t::logger_type *) level) << msg; + /** + * @brief Forward a VA-API error diagnostic to the application logger. + * @param context Unused native callback context. + * @param msg Diagnostic message supplied by VA-API. + */ + static void log_vaapi_error(void *context, const char *msg) { + static_cast(context); + logging::error(msg); + } + + /** + * @brief Forward a VA-API informational diagnostic to the application logger. + * @param context Unused native callback context. + * @param msg Diagnostic message supplied by VA-API. + */ + static void log_vaapi_info(void *context, const char *msg) { + static_cast(context); + logging::info(msg); } static void vaapi_hwdevice_ctx_free(AVHWDeviceContext *ctx) { @@ -706,24 +724,28 @@ namespace va { va::display_t display {vaGetDisplayDRM(fd)}; if (!display) { - BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << platf::resolve_render_device(va->settings); + logging::error([&](std::ostream &out) { + out << "Couldn't open a va display from DRM with device: "sv << platf::resolve_render_device(va->settings); + }); return -1; } va->va_display = display.get(); - vaSetErrorCallback(display.get(), __log, &error.get()); - vaSetErrorCallback(display.get(), __log, &info.get()); + vaSetErrorCallback(display.get(), log_vaapi_error, nullptr); + vaSetErrorCallback(display.get(), log_vaapi_info, nullptr); int major; int minor; auto status = vaInitialize(display.get(), &major, &minor); if (status) { - BOOST_LOG(error) << "Couldn't initialize va display: "sv << vaErrorStr(status); + logging::error("Couldn't initialize va display: {}", vaErrorStr(status)); return -1; } - BOOST_LOG(info) << "vaapi vendor: "sv << vaQueryVendorString(display.get()); + logging::info([&](std::ostream &out) { + out << "vaapi vendor: "sv << vaQueryVendorString(display.get()); + }); *hw_device_buf = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI); auto ctx = (AVHWDeviceContext *) (*hw_device_buf)->data; @@ -738,7 +760,9 @@ namespace va { auto err = av_hwdevice_ctx_init(*hw_device_buf); if (err) { std::array err_str {0}; - BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return err; } @@ -753,7 +777,7 @@ namespace va { int count; auto status = vaQueryConfigEntrypoints(display, profile, entrypoints.data(), &count); if (status) { - BOOST_LOG(error) << "Couldn't query entrypoints: "sv << vaErrorStr(status); + logging::error("Couldn't query entrypoints: {}", vaErrorStr(status)); return false; } entrypoints.resize(count); @@ -779,7 +803,7 @@ namespace va { std::string_view render_device {string.data(), (std::size_t) bytes}; - BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << render_device; + logging::error("Couldn't open a va display from DRM with device: {}", render_device); return false; } @@ -787,7 +811,7 @@ namespace va { int minor; auto status = vaInitialize(display.get(), &major, &minor); if (status) { - BOOST_LOG(error) << "Couldn't initialize va display: "sv << vaErrorStr(status); + logging::error("Couldn't initialize va display: {}", vaErrorStr(status)); return false; } @@ -838,7 +862,9 @@ namespace va { file_t file = ::open(render_device.c_str(), O_RDWR); // NOSONAR(cpp:S1874): `_sopen_s` not available if (file.el < 0) { std::array string; - BOOST_LOG(error) << "Couldn't open "sv << render_device << ": " << strerror_r(errno, string.data(), string.size()); + logging::error([&](std::ostream &out) { + out << "Couldn't open "sv << render_device << ": " << strerror_r(errno, string.data(), string.size()); + }); return nullptr; } diff --git a/src/platform/linux/vulkan_encode.cpp b/src/platform/linux/vulkan_encode.cpp index 704b4ce85..a4737744c 100644 --- a/src/platform/linux/vulkan_encode.cpp +++ b/src/platform/linux/vulkan_encode.cpp @@ -127,7 +127,7 @@ namespace vk { ci.pApplicationInfo = &app; VkInstance inst = VK_NULL_HANDLE; if (vkCreateInstance(&ci, nullptr, &inst) != VK_SUCCESS) { - BOOST_LOG(warning) << "[vulkan] Failed to create instance for modifier query"sv; + logging::warning("[vulkan] Failed to create instance for modifier query"sv); return result; } @@ -156,8 +156,10 @@ namespace vk { for (const auto &[drm_fmt, vk_fmt] : formats_to_query) { auto modifiers = query_format_modifiers(phys_dev, vk_fmt); if (!modifiers.empty()) { - BOOST_LOG(debug) << "[vulkan] Format 0x"sv << std::hex << drm_fmt << std::dec - << " has "sv << modifiers.size() << " supported modifiers"sv; + logging::debug([&](std::ostream &out) { + out << "[vulkan] Format 0x"sv << std::hex << drm_fmt << std::dec + << " has "sv << modifiers.size() << " supported modifiers"sv; + }); result[drm_fmt] = std::move(modifiers); } } @@ -267,12 +269,11 @@ namespace vk { } *max_level = enc_caps.maxQualityLevels; - BOOST_LOG(debug) << "[vulkan] Driver max quality level: "sv << *max_level; + logging::debug("[vulkan] Driver max quality level: {}", *max_level); // If requested level is 0 or within range, try to validate it if (requested_level > *max_level) { - BOOST_LOG(warning) << "[vulkan] Requested quality level "sv << requested_level - << " exceeds max "sv << *max_level << ", using max"sv; + logging::warning("[vulkan] Requested quality level {} exceeds max {}, using max", requested_level, *max_level); requested_level = *max_level; } @@ -410,7 +411,7 @@ namespace vk { do { \ VkResult _r = (expr); \ if (_r != VK_SUCCESS) { \ - BOOST_LOG(error) << #expr << " failed: " << _r; \ + logging::error("{} failed: {}", #expr, static_cast(_r)); \ return -1; \ } \ } while (0) @@ -422,7 +423,7 @@ namespace vk { do { \ VkResult _r = (expr); \ if (_r != VK_SUCCESS) { \ - BOOST_LOG(error) << #expr << " failed: " << _r; \ + logging::error("{} failed: {}", #expr, static_cast(_r)); \ return false; \ } \ } while (0) @@ -518,11 +519,9 @@ namespace vk { if (validated_quality == target_quality) { av_dict_set_int(options, "quality", validated_quality, 0); - BOOST_LOG(info) << "[vulkan] Encoder quality set to "sv << validated_quality - << " ("sv << preset_name << "), driver range: 0-"sv << max_quality; + logging::info("[vulkan] Encoder quality set to {} ({}), driver range: 0-{}", validated_quality, preset_name, max_quality); } else { - BOOST_LOG(warning) << "[vulkan] Quality level "sv << target_quality - << " is not supported by the driver; using default"sv; + logging::warning("[vulkan] Quality level {} is not supported by the driver; using default", target_quality); } } } @@ -550,7 +549,7 @@ namespace vk { { VkPhysicalDeviceProperties p; vkGetPhysicalDeviceProperties(vk_dev.phys_dev, &p); - BOOST_LOG(info) << "Vulkan encode using GPU: " << p.deviceName; + logging::info("Vulkan encode using GPU: {}", p.deviceName); } // Find a compute-capable queue family from FFmpeg's context @@ -562,7 +561,7 @@ namespace vk { } } if (vk_dev.compute_qf < 0) { - BOOST_LOG(error) << "No compute queue family in Vulkan device"sv; + logging::error("No compute queue family in Vulkan device"sv); return -1; } @@ -635,7 +634,7 @@ namespace vk { // Get encoder target frame if (!frame->buf[0]) { if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0) < 0) { - BOOST_LOG(error) << "Failed to get Vulkan frame"sv; + logging::error("Failed to get Vulkan frame"sv); return -1; } } @@ -649,7 +648,7 @@ namespace vk { if (descriptor.sequence > sequence) { sequence = descriptor.sequence; if (!import_dmabuf(descriptor.sd)) { - BOOST_LOG(error) << "Failed to import DMA-BUF"sv; + logging::error("Failed to import DMA-BUF"sv); return -1; } descriptors_dirty = true; @@ -852,7 +851,9 @@ namespace vk { case DRM_FORMAT_ARGB16161616F: return {VK_FORMAT_R16G16B16A16_SFLOAT, bgr_swap}; default: - BOOST_LOG(warning) << "Unknown DRM fourcc 0x" << std::hex << fourcc << std::dec << ", assuming B8G8R8A8"; + logging::warning([&](std::ostream &out) { + out << "Unknown DRM fourcc 0x" << std::hex << fourcc << std::dec << ", assuming B8G8R8A8"; + }); return {VK_FORMAT_B8G8R8A8_UNORM, identity}; } } @@ -942,9 +943,11 @@ namespace vk { auto res = vkCreateImage(vk_dev.dev, &img_ci, nullptr, &src.image); if (res != VK_SUCCESS) { close(fd); - BOOST_LOG(error) << "vkCreateImage for DMA-BUF failed: " << res - << " (modifier=0x" << std::hex << sd.modifier << std::dec - << ", pitch=" << sd.pitches[0] << ", offset=" << sd.offsets[0] << ")"; + logging::error([&](std::ostream &out) { + out << "vkCreateImage for DMA-BUF failed: " << res + << " (modifier=0x" << std::hex << sd.modifier << std::dec + << ", pitch=" << sd.pitches[0] << ", offset=" << sd.offsets[0] << ")"; + }); return false; } @@ -967,7 +970,7 @@ namespace vk { VkDeviceMemory src_mem = VK_NULL_HANDLE; res = vkAllocateMemory(vk_dev.dev, &alloc_info, nullptr, &src_mem); if (res != VK_SUCCESS) { - BOOST_LOG(error) << "vkAllocateMemory for DMA-BUF failed: " << res; + logging::error("vkAllocateMemory for DMA-BUF failed: {}", static_cast(res)); vkDestroyImage(vk_dev.dev, src.image, nullptr); src.image = VK_NULL_HANDLE; return false; @@ -1223,7 +1226,7 @@ namespace vk { auto res = vkQueueSubmit(vk_dev.compute_queue, 1, &submit, VK_NULL_HANDLE); if (res != VK_SUCCESS) { - BOOST_LOG(error) << "vkQueueSubmit failed: " << res; + logging::error("vkQueueSubmit failed: {}", static_cast(res)); return -1; } diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 01ec86f4d..3eb948e0a 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -64,13 +64,13 @@ namespace wl { drm_fd = accessors.open_render_node(render_path.c_str()); if (drm_fd < 0) { - BOOST_LOG(error) << "[wayland] Failed to open DRM render node: "sv << render_path; + logging::error("[wayland] Failed to open DRM render node: {}", render_path); return false; } device = accessors.create_device(drm_fd); if (!device) { - BOOST_LOG(error) << "[wayland] Failed to create GBM device"sv; + logging::error("[wayland] Failed to create GBM device"sv); reset(); return false; } @@ -118,17 +118,17 @@ namespace wl { } if (!display_name) { - BOOST_LOG(error) << "[wayland] Environment variable WAYLAND_DISPLAY has not been defined"sv; + logging::error("[wayland] Environment variable WAYLAND_DISPLAY has not been defined"sv); return -1; } display_internal.reset(wl_display_connect(display_name)); if (!display_internal) { - BOOST_LOG(error) << "[wayland] Couldn't connect to Wayland display: "sv << display_name; + logging::error("[wayland] Couldn't connect to Wayland display: {}", display_name); return -1; } - BOOST_LOG(info) << "[wayland] Found display ["sv << display_name << ']'; + logging::info("[wayland] Found display [{}]", display_name); return 0; } @@ -191,26 +191,26 @@ namespace wl { inline void monitor_t::xdg_name(zxdg_output_v1 *, const char *name) { this->name = name; - BOOST_LOG(info) << "[wayland] Name: "sv << this->name; + logging::info("[wayland] Name: {}", this->name); } void monitor_t::xdg_description(zxdg_output_v1 *, const char *description) { this->description = description; - BOOST_LOG(info) << "[wayland] Found monitor: "sv << this->description; + logging::info("[wayland] Found monitor: {}", this->description); } void monitor_t::xdg_position(zxdg_output_v1 *, std::int32_t x, std::int32_t y) { viewport.offset_x = x; viewport.offset_y = y; - BOOST_LOG(info) << "[wayland] Offset: "sv << x << 'x' << y; + logging::info("[wayland] Offset: {}x{}", x, y); } void monitor_t::xdg_size(zxdg_output_v1 *, std::int32_t width, std::int32_t height) { viewport.logical_width = width; viewport.logical_height = height; - BOOST_LOG(info) << "[wayland] Logical size: "sv << width << 'x' << height; + logging::info("[wayland] Logical size: {}x{}", width, height); } void monitor_t::wl_mode( @@ -220,7 +220,7 @@ namespace wl { std::int32_t height, std::int32_t refresh ) { - BOOST_LOG(info) << "[wayland] Resolution: "sv << width << 'x' << height; + logging::info("[wayland] Resolution: {}x{}", width, height); if (!(flags & WL_OUTPUT_MODE_CURRENT)) { return; @@ -272,28 +272,28 @@ namespace wl { const char *interface, std::uint32_t version ) { - BOOST_LOG(debug) << "[wayland] Available interface: "sv << interface << '(' << id << ") version "sv << version; + logging::debug("[wayland] Available interface: {}({}) version {}", interface, id, version); if (!std::strcmp(interface, wl_output_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + logging::info("[wayland] Found interface: {}({}) version {}", interface, id, version); monitors.emplace_back( std::make_unique( (wl_output *) wl_registry_bind(registry, id, &wl_output_interface, 2) ) ); } else if (!std::strcmp(interface, zxdg_output_manager_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + logging::info("[wayland] Found interface: {}({}) version {}", interface, id, version); output_manager = (zxdg_output_manager_v1 *) wl_registry_bind(registry, id, &zxdg_output_manager_v1_interface, version); this->interface[XDG_OUTPUT] = true; } else if (!std::strcmp(interface, zwlr_screencopy_manager_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + logging::info("[wayland] Found interface: {}({}) version {}", interface, id, version); screencopy_manager = (zwlr_screencopy_manager_v1 *) wl_registry_bind(registry, id, &zwlr_screencopy_manager_v1_interface, version); screencopy_version = version; this->interface[WLR_EXPORT_DMABUF] = true; } else if (!std::strcmp(interface, zwp_linux_dmabuf_v1_interface.name)) { - BOOST_LOG(info) << "[wayland] Found interface: "sv << interface << '(' << id << ") version "sv << version; + logging::info("[wayland] Found interface: {}({}) version {}", interface, id, version); dmabuf_interface = (zwp_linux_dmabuf_v1 *) wl_registry_bind(registry, id, &zwp_linux_dmabuf_v1_interface, std::min(version, 3u)); zwp_linux_dmabuf_v1_add_listener(dmabuf_interface, &dmabuf_listener, this); @@ -302,7 +302,7 @@ namespace wl { } void interface_t::del_interface(wl_registry *registry, uint32_t id) { - BOOST_LOG(info) << "[wayland] Delete: "sv << id; + logging::info("[wayland] Delete: {}", id); } // Initialize GBM @@ -349,8 +349,10 @@ namespace wl { } if (!common.empty()) { - BOOST_LOG(debug) << "[wayland] Format 0x"sv << std::hex << format << std::dec - << " has "sv << common.size() << " common modifiers"sv; + logging::debug([&](std::ostream &out) { + out << "[wayland] Format 0x"sv << std::hex << format << std::dec + << " has "sv << common.size() << " common modifiers"sv; + }); result[format] = std::move(common); } } @@ -447,7 +449,7 @@ namespace wl { // Flags callback void dmabuf_t::flags(zwlr_screencopy_frame_v1 *frame, std::uint32_t flags) { y_invert = flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT; - BOOST_LOG(verbose) << "Frame flags: "sv << flags << (y_invert ? " (y_invert)" : ""); + logging::verbose("Frame flags: {}{}", flags, (y_invert ? " (y_invert)" : "")); } std::optional export_gbm_bo_planes(gbm_bo *bo, frame_t &frame, const gbm_bo_accessors_t &accessors) { @@ -455,7 +457,7 @@ namespace wl { const auto plane_count = accessors.get_plane_count(bo); if (plane_count <= 0 || plane_count > static_cast(std::size(frame.sd.fds))) { - BOOST_LOG(error) << "[wayland] GBM buffer has unsupported plane count ["sv << plane_count << ']'; + logging::error("[wayland] GBM buffer has unsupported plane count [{}]", plane_count); return std::nullopt; } @@ -463,7 +465,7 @@ namespace wl { for (auto plane = 0; plane < plane_count; ++plane) { frame.sd.fds[plane] = accessors.get_fd_for_plane(bo, plane); if (frame.sd.fds[plane] < 0) { - BOOST_LOG(error) << "[wayland] Failed to export DMA-BUF plane ["sv << plane << ']'; + logging::error("[wayland] Failed to export DMA-BUF plane [{}]", plane); frame.destroy(); return std::nullopt; } @@ -478,7 +480,7 @@ namespace wl { // DMA-BUF creation helper void dmabuf_t::create_and_copy_dmabuf(zwlr_screencopy_frame_v1 *frame) { if (!init_gbm()) { - BOOST_LOG(error) << "Failed to initialize GBM"sv; + logging::error("Failed to initialize GBM"sv); zwlr_screencopy_frame_v1_destroy(frame); status = REINIT; return; @@ -498,7 +500,7 @@ namespace wl { } if (!current_bo) { - BOOST_LOG(error) << "Failed to create GBM buffer"sv; + logging::error("Failed to create GBM buffer"sv); zwlr_screencopy_frame_v1_destroy(frame); status = REINIT; return; @@ -551,11 +553,11 @@ namespace wl { create_and_copy_dmabuf(frame); } else if (shm_info.supported) { // SHM fallback would go here - BOOST_LOG(warning) << "[wayland] SHM capture not implemented"sv; + logging::warning("[wayland] SHM capture not implemented"sv); zwlr_screencopy_frame_v1_destroy(frame); status = REINIT; } else { - BOOST_LOG(error) << "[wayland] No supported buffer types"sv; + logging::error("[wayland] No supported buffer types"sv); zwlr_screencopy_frame_v1_destroy(frame); status = REINIT; } @@ -591,7 +593,7 @@ namespace wl { auto frame = static_cast(data); auto self = static_cast(zwlr_screencopy_frame_v1_get_user_data(frame)); - BOOST_LOG(error) << "[wayland] Failed to create buffer from params"sv; + logging::error("[wayland] Failed to create buffer from params"sv); self->cleanup_gbm(); self->get_next_frame()->destroy(); @@ -632,7 +634,7 @@ namespace wl { // Failed callback void dmabuf_t::failed(zwlr_screencopy_frame_v1 *frame) { - BOOST_LOG(error) << "[wayland] Frame capture failed"sv; + logging::error("[wayland] Frame capture failed"sv); // Clean up resources cleanup_gbm(); @@ -700,7 +702,7 @@ namespace wl { display.roundtrip(); if (!interface[interface_t::XDG_OUTPUT]) { - BOOST_LOG(error) << "[wayland] Missing Wayland wire XDG_OUTPUT"sv; + logging::error("[wayland] Missing Wayland wire XDG_OUTPUT"sv); return {}; } diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index 57aec2e08..fad4c75d1 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -123,9 +123,9 @@ namespace wl { delay = ::video::capture_frame_interval(config); const AVRational fps = ::video::framerate_to_rational(config); if (fps.den != 1) { - BOOST_LOG(info) << "[wlgrab] Requested frame rate [" << fps.num << "/" << fps.den << ", approx. " << av_q2d(fps) << " fps]"; + logging::info("[wlgrab] Requested frame rate [{}/{}, approx. {:.6g} fps]", fps.num, fps.den, av_q2d(fps)); } else { - BOOST_LOG(info) << "[wlgrab] Requested frame rate [" << fps.num << "fps]"; + logging::info("[wlgrab] Requested frame rate [{}fps]", fps.num); } mem_type = hwdevice_type; @@ -139,12 +139,12 @@ namespace wl { display.roundtrip(); if (!interface[wl::interface_t::XDG_OUTPUT]) { - BOOST_LOG(error) << "[wlgrab] Missing Wayland wire for xdg_output"sv; + logging::error("[wlgrab] Missing Wayland wire for xdg_output"sv); return -1; } if (!interface[wl::interface_t::WLR_EXPORT_DMABUF]) { - BOOST_LOG(error) << "[wlgrab] Missing Wayland wire for wlr-export-dmabuf"sv; + logging::error("[wlgrab] Missing Wayland wire for wlr-export-dmabuf"sv); return -1; } @@ -194,7 +194,7 @@ namespace wl { const double stream_fps = av_q2d(fps); const double output_fps = monitor->refresh_mhz / 1000.0; event_driven = use_damage_capture(interface.screencopy_version, stream_fps, monitor->refresh_mhz); - BOOST_LOG(info) << "[wlgrab] Frame capture: "sv << (event_driven ? "event-driven"sv : "paced"sv) << " (output "sv << output_fps << " Hz, stream "sv << stream_fps << " fps)"sv; + logging::info("[wlgrab] Frame capture: {} (output {:.6g} Hz, stream {:.6g} fps)", (event_driven ? "event-driven"sv : "paced"sv), output_fps, stream_fps); offset_x = monitor->viewport.offset_x; offset_y = monitor->viewport.offset_y; @@ -212,12 +212,12 @@ namespace wl { this->env_logical_width = desktop.logical_width; this->env_logical_height = desktop.logical_height; - BOOST_LOG(info) << "[wlgrab] Selected monitor ["sv << monitor->description << "] for streaming"sv; - BOOST_LOG(debug) << "[wlgrab] Offset: "sv << offset_x << 'x' << offset_y; - BOOST_LOG(debug) << "[wlgrab] Resolution: "sv << width << 'x' << height; - BOOST_LOG(debug) << "[wlgrab] Logical Resolution: "sv << logical_width << 'x' << logical_height; - BOOST_LOG(debug) << "[wlgrab] Desktop Resolution: "sv << env_width << 'x' << env_height; - BOOST_LOG(debug) << "[wlgrab] Logical Desktop Resolution: "sv << env_logical_width << 'x' << env_logical_height; + logging::info("[wlgrab] Selected monitor [{}] for streaming", monitor->description); + logging::debug("[wlgrab] Offset: {}x{}", offset_x, offset_y); + logging::debug("[wlgrab] Resolution: {}x{}", width, height); + logging::debug("[wlgrab] Logical Resolution: {}x{}", logical_width, logical_height); + logging::debug("[wlgrab] Desktop Resolution: {}x{}", env_width, env_height); + logging::debug("[wlgrab] Logical Desktop Resolution: {}x{}", env_logical_width, env_logical_height); return 0; } @@ -343,7 +343,7 @@ namespace wl { } break; default: - BOOST_LOG(error) << "[wlgrab] Unrecognized capture status ["sv << std::to_underlying(status) << ']'; + logging::error("[wlgrab] Unrecognized capture status [{}]", std::to_underlying(status)); return status; } } @@ -418,7 +418,7 @@ namespace wl { int w; gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); gl::ctx.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); - BOOST_LOG(debug) << "[wlgrab] width and height: w "sv << w << " h "sv << h; + logging::debug("[wlgrab] width and height: w {} h {}", w, h); gl::ctx.GetTextureSubImage((*rgb_opt)->tex[0], 0, 0, 0, 0, width, height, 1, GL_BGRA, GL_UNSIGNED_BYTE, img_out->height * img_out->row_pitch, img_out->data); gl::ctx.BindTexture(GL_TEXTURE_2D, 0); @@ -610,7 +610,7 @@ namespace wl { if (!encoder_modifiers.empty()) { intersected_modifiers = wl::intersect_modifiers(interface.supported_modifiers, encoder_modifiers); if (intersected_modifiers.empty()) { - BOOST_LOG(warning) << "[wlgrab] No common modifiers between compositor and vulkan encoder"sv; + logging::warning("[wlgrab] No common modifiers between compositor and vulkan encoder"sv); } } } @@ -629,7 +629,7 @@ namespace platf { */ std::shared_ptr wl_display(const config::settings_t &settings, mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda && hwdevice_type != platf::mem_type_e::vulkan) { - BOOST_LOG(error) << "[wlgrab] Could not initialize display with the given hw device type."sv; + logging::error("[wlgrab] Could not initialize display with the given hw device type."sv); return nullptr; } @@ -647,7 +647,7 @@ namespace platf { #ifndef SUNSHINE_BUILD_CUDA if (hwdevice_type == platf::mem_type_e::cuda) { - BOOST_LOG(warning) << "This build does not include CUDA support. Falling back to GPU -> RAM -> GPU for NVENC."sv; + logging::warning("This build does not include CUDA support. Falling back to GPU -> RAM -> GPU for NVENC."sv); } #endif @@ -676,12 +676,12 @@ namespace platf { display.roundtrip(); if (!interface[wl::interface_t::XDG_OUTPUT]) { - BOOST_LOG(warning) << "[wlgrab] Missing Wayland wire for xdg_output"sv; + logging::warning("[wlgrab] Missing Wayland wire for xdg_output"sv); return {}; } if (!interface[wl::interface_t::WLR_EXPORT_DMABUF]) { - BOOST_LOG(warning) << "[wlgrab] Missing Wayland wire for wlr-export-dmabuf"sv; + logging::warning("[wlgrab] Missing Wayland wire for wlr-export-dmabuf"sv); return {}; } @@ -691,17 +691,17 @@ namespace platf { display.roundtrip(); - BOOST_LOG(info) << "[wlgrab] -------- Start of Wayland monitor list --------"sv; + logging::info("[wlgrab] -------- Start of Wayland monitor list --------"sv); for (int x = 0; x < interface.monitors.size(); ++x) { auto monitor = interface.monitors[x].get(); - BOOST_LOG(info) << "[wlgrab] Monitor " << x << " is "sv << monitor->name << ": "sv << monitor->description; + logging::info("[wlgrab] Monitor {} is {}: {}", x, monitor->name, monitor->description); display_names.emplace_back(monitor->name.empty() ? std::to_string(x) : monitor->name); } - BOOST_LOG(info) << "[wlgrab] --------- End of Wayland monitor list ---------"sv; + logging::info("[wlgrab] --------- End of Wayland monitor list ---------"sv); return display_names; } diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 6328854c4..eba8def34 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -405,7 +405,7 @@ namespace platf { xcursor_t overlay {x11::fix::GetCursorImage(display)}; if (!overlay) { - BOOST_LOG(error) << "Couldn't get cursor from XFixesGetCursorImage"sv; + logging::error("Couldn't get cursor from XFixesGetCursorImage"sv); return; } @@ -493,7 +493,7 @@ namespace platf { */ int init(const std::string &display_name, const ::video::config_t &config) { if (!xdisplay) { - BOOST_LOG(error) << "Could not open X11 display"sv; + logging::error("Could not open X11 display"sv); return -1; } @@ -530,15 +530,14 @@ namespace platf { if (result_found && result->crtc) { crtc_info_t crt_info {x11::rr::GetCrtcInfo(xdisplay.get(), screenr.get(), result->crtc)}; - BOOST_LOG(info) - << "Streaming display: "sv << result->name << " with res "sv << crt_info->width << 'x' << crt_info->height << " offset by "sv << crt_info->x << 'x' << crt_info->y; + logging::info("Streaming display: {} with res {}x{} offset by {}x{}", result->name, crt_info->width, crt_info->height, crt_info->x, crt_info->y); width = crt_info->width; height = crt_info->height; offset_x = crt_info->x; offset_y = crt_info->y; } else { - BOOST_LOG(warning) << "Couldn't get info for requested display ["sv << display_name << "], defaulting to recording entire virtual desktop"sv; + logging::warning("Couldn't get info for requested display [{}], defaulting to recording entire virtual desktop", display_name); width = xattr.width; height = xattr.height; } @@ -582,7 +581,7 @@ namespace platf { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } } @@ -604,7 +603,7 @@ namespace platf { // The whole X server changed, so we must reinit everything if (xattr.width != env_width || xattr.height != env_height) { - BOOST_LOG(warning) << "X dimensions changed in non-SHM mode, request reinit"sv; + logging::warning("X dimensions changed in non-SHM mode, request reinit"sv); return capture_e::reinit; } @@ -754,7 +753,7 @@ namespace platf { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } } @@ -774,7 +773,7 @@ namespace platf { capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr &img_out, std::chrono::milliseconds timeout, bool cursor) { // The whole X server changed, so we must reinit everything if (xattr.width != env_width || xattr.height != env_height) { - BOOST_LOG(warning) << "X dimensions changed in SHM mode, request reinit"sv; + logging::warning("X dimensions changed in SHM mode, request reinit"sv); return capture_e::reinit; } else { auto img_cookie = shm_api->shm_get_image_unchecked(xcb.get(), display->root, offset_x, offset_y, width, height, ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, seg, 0); @@ -782,7 +781,7 @@ namespace platf { xcb_img_t img_reply {shm_api->shm_get_image_reply(xcb.get(), img_cookie, nullptr)}; if (!img_reply) { - BOOST_LOG(error) << "Could not get image reply"sv; + logging::error("Could not get image reply"sv); return capture_e::reinit; } @@ -846,7 +845,7 @@ namespace platf { } if (!xcb::get_extension_data(xcb.get(), shm_api->shm_id)->present) { - BOOST_LOG(error) << "Missing SHM extension"sv; + logging::error("Missing SHM extension"sv); return -1; } @@ -857,7 +856,7 @@ namespace platf { shm_id.id = shmget(IPC_PRIVATE, frame_size(), IPC_CREAT | 0777); if (shm_id.id == -1) { - BOOST_LOG(error) << "shmget failed"sv; + logging::error("shmget failed"sv); return -1; } @@ -865,7 +864,7 @@ namespace platf { data.data = shmat(shm_id.id, nullptr, 0); if ((uintptr_t) data.data == -1) { - BOOST_LOG(error) << "shmat failed"sv; + logging::error("shmat failed"sv); return -1; } @@ -895,13 +894,13 @@ namespace platf { */ std::shared_ptr x11_display(const config::settings_t &settings, platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, thread_pool_util::ThreadPool &scheduler) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda) { - BOOST_LOG(error) << "Could not initialize x11 display with the given hw device type"sv; + logging::error("Could not initialize x11 display with the given hw device type"sv); return nullptr; } auto shm_api = xcb::shm_api_t::load(); if (!shm_api || xcb::init() || x11::init() || x11::rr::init() || x11::fix::init()) { - BOOST_LOG(error) << "Couldn't init x11 libraries"sv; + logging::error("Couldn't init x11 libraries"sv); return nullptr; } @@ -935,12 +934,12 @@ namespace platf { */ std::vector x11_display_names() { if (load_x11() || load_xcb()) { - BOOST_LOG(error) << "Couldn't init x11 libraries"sv; + logging::error("Couldn't init x11 libraries"sv); return {}; } - BOOST_LOG(info) << "Detecting displays"sv; + logging::info("Detecting displays"sv); x11::xdisplay_t xdisplay {x11::OpenDisplay(nullptr)}; if (!xdisplay) { @@ -956,7 +955,9 @@ namespace platf { for (int x = 0; x < output; ++x) { output_info_t out_info {x11::rr::GetOutputInfo(xdisplay.get(), screenr.get(), screenr->outputs[x])}; if (out_info) { - BOOST_LOG(info) << "Detected display: "sv << out_info->name << " (id: "sv << monitor++ << ")"sv << out_info->name << " connected: "sv << (out_info->connection == RR_Connected); + logging::info([&](std::ostream &out) { + out << "Detected display: "sv << out_info->name << " (id: "sv << monitor++ << ")"sv << out_info->name << " connected: "sv << (out_info->connection == RR_Connected); + }); names.emplace_back(out_info->name); } } diff --git a/src/platform/macos/av_audio.mm b/src/platform/macos/av_audio.mm index af1927ed1..f2bd66577 100644 --- a/src/platform/macos/av_audio.mm +++ b/src/platform/macos/av_audio.mm @@ -29,7 +29,7 @@ namespace platf { bool request_microphone_permission(AVAuthorizationStatus authorization_status, const microphone_permission_request_t &request_access) { if (authorization_status == AVAuthorizationStatusNotDetermined) { - BOOST_LOG(info) << "Requesting microphone permission for the configured audio sink."sv; + logging::info("Requesting microphone permission for the configured audio sink."sv); } auto permission_granted = std::atomic {authorization_status == AVAuthorizationStatusAuthorized}; @@ -46,9 +46,9 @@ namespace platf { if (!permission_granted.load()) { if (authorization_status == AVAuthorizationStatusRestricted) { - BOOST_LOG(error) << "Microphone access is restricted by macOS."sv; + logging::error("Microphone access is restricted by macOS."sv); } else { - BOOST_LOG(error) << "Microphone access was denied. Enable Sunshine in System Settings -> Privacy & Security -> Microphone."sv; + logging::error("Microphone access was denied. Enable Sunshine in System Settings -> Privacy & Security -> Microphone."sv); } } @@ -224,10 +224,10 @@ namespace platf { + (NSArray *)microphones { using namespace std::literals; - BOOST_LOG(debug) << "Discovering microphones"sv; + logging::debug("Discovering microphones"sv); if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:((NSOperatingSystemVersion) {10, 15, 0})]) { - BOOST_LOG(debug) << "Using modern AVCaptureDeviceDiscoverySession API"sv; + logging::debug("Using modern AVCaptureDeviceDiscoverySession API"sv); // This will generate a warning about AVCaptureDeviceDiscoverySession being // unavailable before macOS 10.15, but we have a guard to prevent it from // being called on those earlier systems. @@ -240,18 +240,18 @@ namespace platf { mediaType:AVMediaTypeAudio position:AVCaptureDevicePositionUnspecified]; NSArray *devices = discoverySession.devices; - BOOST_LOG(debug) << "Found "sv << [devices count] << " devices using discovery session"sv; + logging::debug("Found {} devices using discovery session", [devices count]); return devices; #pragma clang diagnostic pop } else { - BOOST_LOG(debug) << "Using legacy AVCaptureDevice API"sv; + logging::debug("Using legacy AVCaptureDevice API"sv); // We're intentionally using a deprecated API here specifically for versions // of macOS where it's not deprecated, so we can ignore any deprecation // warnings: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio]; - BOOST_LOG(debug) << "Found "sv << [devices count] << " devices using legacy API"sv; + logging::debug("Found {} devices using legacy API", [devices count]); return devices; #pragma clang diagnostic pop } @@ -259,14 +259,14 @@ namespace platf { + (NSArray *)microphoneNames { using namespace std::literals; - BOOST_LOG(debug) << "Retrieving microphone names"sv; + logging::debug("Retrieving microphone names"sv); NSMutableArray *result = [NSMutableArray array]; for (AVCaptureDevice *device in [AVAudio microphones]) { [result addObject:[device localizedName]]; } - BOOST_LOG(info) << "Found "sv << [result count] << " microphones"sv; + logging::info("Found {} microphones", [result count]); return result; } @@ -274,20 +274,26 @@ namespace platf { using namespace std::literals; if (name == nil) { - BOOST_LOG(warning) << "Microphone not found: (nil)"sv; + logging::warning("Microphone not found: (nil)"sv); return nil; } - BOOST_LOG(debug) << "Searching for microphone: "sv << [name UTF8String]; + logging::debug([&](std::ostream &out) { + out << "Searching for microphone: "sv << [name UTF8String]; + }); for (AVCaptureDevice *device in [AVAudio microphones]) { if ([[device localizedName] isEqualToString:name]) { - BOOST_LOG(info) << "Found microphone: "sv << [name UTF8String]; + logging::info([&](std::ostream &out) { + out << "Found microphone: "sv << [name UTF8String]; + }); return device; } } - BOOST_LOG(warning) << "Microphone not found: "sv << [name UTF8String]; + logging::warning([&](std::ostream &out) { + out << "Microphone not found: "sv << [name UTF8String]; + }); return nil; } @@ -295,26 +301,30 @@ namespace platf { using namespace std::literals; if (device == nil) { - BOOST_LOG(error) << "Cannot setup microphone: device is nil"sv; + logging::error("Cannot setup microphone: device is nil"sv); return -1; } - BOOST_LOG(info) << "Setting up microphone: "sv << [[device localizedName] UTF8String] << " with "sv << sampleRate << "Hz, "sv << frameSize << " frames, "sv << (int) channels << " channels"sv; + logging::info([&](std::ostream &out) { + out << "Setting up microphone: "sv << [[device localizedName] UTF8String] << " with "sv << sampleRate << "Hz, "sv << frameSize << " frames, "sv << (int) channels << " channels"sv; + }); self.audioCaptureSession = [[AVCaptureSession alloc] init]; NSError *nsError; AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&nsError]; if (audioInput == nil) { - BOOST_LOG(error) << "Failed to create audio input from device: "sv << (nsError ? [[nsError localizedDescription] UTF8String] : "unknown error"sv); + logging::error([&](std::ostream &out) { + out << "Failed to create audio input from device: "sv << (nsError ? [[nsError localizedDescription] UTF8String] : "unknown error"sv); + }); return -1; } if ([self.audioCaptureSession canAddInput:audioInput]) { [self.audioCaptureSession addInput:audioInput]; - BOOST_LOG(debug) << "Successfully added audio input to capture session"sv; + logging::debug("Successfully added audio input to capture session"sv); } else { - BOOST_LOG(error) << "Cannot add audio input to capture session"sv; + logging::error("Cannot add audio input to capture session"sv); [audioInput dealloc]; return -1; } @@ -329,7 +339,7 @@ namespace platf { (NSString *) AVLinearPCMIsFloatKey: @YES, (NSString *) AVLinearPCMIsNonInterleaved: @NO }]; - BOOST_LOG(debug) << "Configured audio output with settings: "sv << sampleRate << "Hz, "sv << (int) channels << " channels, 32-bit float"sv; + logging::debug("Configured audio output with settings: {}Hz, {} channels, 32-bit float", sampleRate, (int) channels); dispatch_queue_attr_t qos = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, DISPATCH_QUEUE_PRIORITY_HIGH); dispatch_queue_t recordingQueue = dispatch_queue_create("audioSamplingQueue", qos); @@ -338,9 +348,9 @@ namespace platf { if ([self.audioCaptureSession canAddOutput:audioOutput]) { [self.audioCaptureSession addOutput:audioOutput]; - BOOST_LOG(debug) << "Successfully added audio output to capture session"sv; + logging::debug("Successfully added audio output to capture session"sv); } else { - BOOST_LOG(error) << "Cannot add audio output to capture session"sv; + logging::error("Cannot add audio output to capture session"sv); [audioInput release]; [audioOutput release]; return -1; @@ -350,10 +360,10 @@ namespace platf { // Initialize buffer and signal [self initializeAudioBuffer:channels]; - BOOST_LOG(debug) << "Audio buffer initialized for microphone capture"sv; + logging::debug("Audio buffer initialized for microphone capture"sv); [self.audioCaptureSession startRunning]; - BOOST_LOG(info) << "Audio capture session started successfully"sv; + logging::info("Audio capture session started successfully"sv); [audioInput release]; [audioOutput release]; @@ -391,7 +401,7 @@ namespace platf { - (int)setupSystemTap:(UInt32)sampleRate frameSize:(UInt32)frameSize channels:(UInt8)channels { using namespace std::literals; - BOOST_LOG(debug) << "setupSystemTap called with sampleRate:"sv << sampleRate << " frameSize:"sv << frameSize << " channels:"sv << (int) channels; + logging::debug("setupSystemTap called with sampleRate:{} frameSize:{} channels:{}", sampleRate, frameSize, (int) channels); // 1. Initialize system tap components if ([self initializeSystemTapContext:sampleRate frameSize:frameSize channels:channels] != 0) { @@ -431,7 +441,7 @@ namespace platf { [tapDescription release]; - BOOST_LOG(debug) << "System tap setup completed successfully!"sv; + logging::debug("System tap setup completed successfully!"sv); return 0; } @@ -463,7 +473,7 @@ namespace platf { OSStatus result = AudioObjectGetPropertyData(deviceID, &addr, 0, NULL, ioDataSize, outData); if (result != noErr) { - BOOST_LOG(warning) << "Failed to get device property (selector: "sv << selector << ", scope: "sv << scope << ", element: "sv << element << ") with status: "sv << result; + logging::warning("Failed to get device property (selector: {}, scope: {}, element: {}) with status: {}", selector, scope, element, result); } return result; @@ -476,50 +486,50 @@ namespace platf { */ - (void)cleanupSystemTapContext:(id)tapDescription { using namespace std::literals; - BOOST_LOG(debug) << "Starting system tap context cleanup"sv; + logging::debug("Starting system tap context cleanup"sv); // Clean up in reverse order of creation if (self->ioProcID && self->aggregateDeviceID != kAudioObjectUnknown) { AudioDeviceStop(self->aggregateDeviceID, self->ioProcID); AudioDeviceDestroyIOProcID(self->aggregateDeviceID, self->ioProcID); self->ioProcID = NULL; - BOOST_LOG(debug) << "IOProc stopped and destroyed"sv; + logging::debug("IOProc stopped and destroyed"sv); } if (self->aggregateDeviceID != kAudioObjectUnknown) { AudioHardwareDestroyAggregateDevice(self->aggregateDeviceID); self->aggregateDeviceID = kAudioObjectUnknown; - BOOST_LOG(debug) << "Aggregate device destroyed"sv; + logging::debug("Aggregate device destroyed"sv); } if (self->tapObjectID != kAudioObjectUnknown) { AudioHardwareDestroyProcessTap(self->tapObjectID); self->tapObjectID = kAudioObjectUnknown; - BOOST_LOG(debug) << "Process tap destroyed"sv; + logging::debug("Process tap destroyed"sv); } if (self->ioProcData) { if (self->ioProcData->conversionBuffer) { free(self->ioProcData->conversionBuffer); self->ioProcData->conversionBuffer = NULL; - BOOST_LOG(debug) << "Conversion buffer freed"sv; + logging::debug("Conversion buffer freed"sv); } if (self->ioProcData->audioConverter) { AudioConverterDispose(self->ioProcData->audioConverter); self->ioProcData->audioConverter = NULL; - BOOST_LOG(debug) << "AudioConverter disposed"sv; + logging::debug("AudioConverter disposed"sv); } free(self->ioProcData); self->ioProcData = NULL; - BOOST_LOG(debug) << "IOProc data freed"sv; + logging::debug("IOProc data freed"sv); } if (tapDescription) { [tapDescription release]; - BOOST_LOG(debug) << "Tap description released"sv; + logging::debug("Tap description released"sv); } - BOOST_LOG(debug) << "System tap context cleanup completed"sv; + logging::debug("System tap context cleanup completed"sv); } // MARK: - Buffer Management Methods @@ -527,7 +537,7 @@ namespace platf { - (void)initializeAudioBuffer:(UInt8)channels { using namespace std::literals; - BOOST_LOG(debug) << "Initializing audio buffer for "sv << (int) channels << " channels"sv; + logging::debug("Initializing audio buffer for {} channels", (int) channels); // Cleanup any existing circular buffer first TPCircularBufferCleanup(&self->audioSampleBuffer); @@ -544,12 +554,12 @@ namespace platf { } self->audioSemaphore = dispatch_semaphore_create(0); - BOOST_LOG(debug) << "Audio buffer initialized successfully with size: "sv << ringBufferSize << " bytes"sv; + logging::debug("Audio buffer initialized successfully with size: {} bytes", ringBufferSize); } - (void)cleanupAudioBuffer { using namespace std::literals; - BOOST_LOG(debug) << "Cleaning up audio buffer"sv; + logging::debug("Cleaning up audio buffer"sv); // Signal any waiting threads before cleanup and release semaphore if (self->audioSemaphore) { @@ -561,7 +571,7 @@ namespace platf { // Cleanup the circular buffer TPCircularBufferCleanup(&self->audioSampleBuffer); - BOOST_LOG(debug) << "Audio buffer cleanup completed"sv; + logging::debug("Audio buffer cleanup completed"sv); } /** @@ -570,7 +580,7 @@ namespace platf { */ - (void)dealloc { using namespace std::literals; - BOOST_LOG(debug) << "AVAudio dealloc started"sv; + logging::debug("AVAudio dealloc started"sv); // Cleanup system tap resources using the generalized method [self cleanupSystemTapContext:nil]; @@ -579,14 +589,14 @@ namespace platf { if (self.audioCaptureSession) { [self.audioCaptureSession stopRunning]; self.audioCaptureSession = nil; - BOOST_LOG(debug) << "Audio capture session stopped and released"sv; + logging::debug("Audio capture session stopped and released"sv); } self.audioConnection = nil; // Use our centralized buffer cleanup method (handles signal and buffer cleanup) [self cleanupAudioBuffer]; - BOOST_LOG(debug) << "AVAudio dealloc completed"sv; + logging::debug("AVAudio dealloc completed"sv); [super dealloc]; } @@ -598,12 +608,12 @@ namespace platf { // Check macOS version requirement if (![[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:((NSOperatingSystemVersion) {14, 0, 0})]) { - BOOST_LOG(error) << "macOS version requirement not met (need 14.0+)"sv; + logging::error("macOS version requirement not met (need 14.0+)"sv); return -1; } NSOperatingSystemVersion version = [[NSProcessInfo processInfo] operatingSystemVersion]; - BOOST_LOG(debug) << "macOS version check passed (running "sv << version.majorVersion << "."sv << version.minorVersion << "."sv << version.patchVersion << ")"sv; + logging::debug("macOS version check passed (running {}.{}.{})", version.majorVersion, version.minorVersion, version.patchVersion); // Initialize Core Audio objects self->tapObjectID = kAudioObjectUnknown; @@ -613,7 +623,7 @@ namespace platf { // Create IOProc data structure with client requirements self->ioProcData = (AVAudioIOProcData *) malloc(sizeof(AVAudioIOProcData)); if (!self->ioProcData) { - BOOST_LOG(error) << "Failed to allocate IOProc data structure"sv; + logging::error("Failed to allocate IOProc data structure"sv); return -1; } @@ -625,14 +635,14 @@ namespace platf { self->ioProcData->conversionBuffer = NULL; self->ioProcData->conversionBufferSize = 0; - BOOST_LOG(debug) << "System tap initialization completed"sv; + logging::debug("System tap initialization completed"sv); return 0; } - (CATapDescription *)createSystemTapDescriptionForChannels:(UInt8)channels { using namespace std::literals; - BOOST_LOG(debug) << "Creating tap description for "sv << (int) channels << " channels (using stereo tap)"sv; + logging::debug("Creating tap description for {} channels (using stereo tap)", (int) channels); NSArray *excludeProcesses = @[]; // Always use stereo tap - it handles mono by duplicating to left/right channels @@ -647,24 +657,26 @@ namespace platf { if (std::getenv("SUNSHINE_PUBLIC_AUDIO_TAP")) { // Shows the tap in Audio MIDI Setup and HALLab where it's easier to inspect - BOOST_LOG(debug) << "Setting tap as public (visible in Audio MIDI Setup and HALLab)"sv; + logging::debug("Setting tap as public (visible in Audio MIDI Setup and HALLab)"sv); [tapDescription setPrivate:NO]; } else { - BOOST_LOG(debug) << "Setting tap as private (hidden from Audio MIDI Setup and HALLab)"sv; + logging::debug("Setting tap as private (hidden from Audio MIDI Setup and HALLab)"sv); [tapDescription setPrivate:YES]; } // Set mute behavior based on the hostAudioEnabled property if (self.hostAudioEnabled) { tapDescription.muteBehavior = CATapUnmuted; // Audio to both tap and speakers - BOOST_LOG(debug) << "Core Audio tap: Host audio enabled (unmuted)"sv; + logging::debug("Core Audio tap: Host audio enabled (unmuted)"sv); } else { tapDescription.muteBehavior = CATapMuted; // Audio to tap only, speakers muted - BOOST_LOG(debug) << "Core Audio tap: Host audio disabled (muted)"sv; + logging::debug("Core Audio tap: Host audio disabled (muted)"sv); } // Create the tap - BOOST_LOG(debug) << "Creating process tap with name: "sv << [uniqueName UTF8String]; + logging::debug([&](std::ostream &out) { + out << "Creating process tap with name: "sv << [uniqueName UTF8String]; + }); // Use direct API call like the reference implementation OSStatus status = AudioHardwareCreateProcessTap(tapDescription, &self->tapObjectID); @@ -672,12 +684,14 @@ namespace platf { [uniqueUUID release]; if (status != noErr) { - BOOST_LOG(error) << "AudioHardwareCreateProcessTap failed: "sv << ca::Status(status); + logging::error([&](std::ostream &out) { + out << "AudioHardwareCreateProcessTap failed: "sv << ca::Status(status); + }); [tapDescription release]; return nil; } - BOOST_LOG(debug) << "Process tap created successfully with ID: "sv << self->tapObjectID; + logging::debug("Process tap created successfully with ID: {}", self->tapObjectID); return tapDescription; } @@ -690,7 +704,7 @@ namespace platf { tapUIDString = [[tapDescription UUID] UUIDString]; } if (!tapUIDString) { - BOOST_LOG(error) << "Failed to get tap UUID from description"sv; + logging::error("Failed to get tap UUID from description"sv); return kAudioHardwareUnspecifiedError; } @@ -709,14 +723,18 @@ namespace platf { @kAudioAggregateDeviceIsPrivateKey: std::getenv("SUNSHINE_PUBLIC_AUDIO_TAP") ? @NO : @YES, }; - BOOST_LOG(debug) << "Creating aggregate device with tap UID: "sv << [tapUIDString UTF8String]; + logging::debug([&](std::ostream &out) { + out << "Creating aggregate device with tap UID: "sv << [tapUIDString UTF8String]; + }); OSStatus status = AudioHardwareCreateAggregateDevice((CFDictionaryRef) aggregateProperties, &self->aggregateDeviceID); if (status != noErr && status != 'ExtA') { - BOOST_LOG(error) << "AudioHardwareCreateAggregateDevice failed: " << ca::Status(status); + logging::error([&](std::ostream &out) { + out << "AudioHardwareCreateAggregateDevice failed: " << ca::Status(status); + }); return status; } - BOOST_LOG(debug) << "Aggregate device created with ID: "sv << self->aggregateDeviceID; + logging::debug("Aggregate device created with ID: {}", self->aggregateDeviceID); // Configure the aggregate device if (self->aggregateDeviceID != kAudioObjectUnknown) { @@ -730,9 +748,9 @@ namespace platf { UInt32 sampleRateSize = sizeof(Float64); OSStatus sampleRateResult = AudioObjectSetPropertyData(self->aggregateDeviceID, &sampleRateAddr, 0, NULL, sampleRateSize, &deviceSampleRate); if (sampleRateResult != noErr) { - BOOST_LOG(warning) << "Failed to set aggregate device sample rate: "sv << sampleRateResult; + logging::warning("Failed to set aggregate device sample rate: {}", sampleRateResult); } else { - BOOST_LOG(debug) << "Set aggregate device sample rate to "sv << sampleRate << "Hz"sv; + logging::debug("Set aggregate device sample rate to {}Hz", sampleRate); } // Set buffer size on the aggregate device @@ -745,13 +763,13 @@ namespace platf { UInt32 frameSizeSize = sizeof(UInt32); OSStatus bufferSizeResult = AudioObjectSetPropertyData(self->aggregateDeviceID, &bufferSizeAddr, 0, NULL, frameSizeSize, &deviceFrameSize); if (bufferSizeResult != noErr) { - BOOST_LOG(warning) << "Failed to set aggregate device buffer size: "sv << bufferSizeResult; + logging::warning("Failed to set aggregate device buffer size: {}", bufferSizeResult); } else { - BOOST_LOG(debug) << "Set aggregate device buffer size to "sv << frameSize << " frames"sv; + logging::debug("Set aggregate device buffer size to {} frames", frameSize); } } - BOOST_LOG(debug) << "Aggregate device created and configured successfully"sv; + logging::debug("Aggregate device created and configured successfully"sv); return noErr; } @@ -775,13 +793,14 @@ namespace platf { data:&aggregateDeviceSampleRate]; if (sampleRateStatus != noErr) { - BOOST_LOG(error) << "Failed to get device sample rate, falling back to client rate (" << clientSampleRate << "Hz): " << ca::Status(sampleRateStatus); + logging::error([&](std::ostream &out) { + out << "Failed to get device sample rate, falling back to client rate (" << clientSampleRate << "Hz): " << ca::Status(sampleRateStatus); + }); aggregateDeviceSampleRate = (Float64) clientSampleRate; } else if (aggregateDeviceSampleRate <= 0.0) { // API returned noErr but the value is invalid (e.g. 0 from a UInt32→Float64 casting issue). // Treat it as a failure rather than silently proceeding with an invalid rate. - BOOST_LOG(error) << "getDeviceProperty returned noErr but got invalid sample rate: "sv - << aggregateDeviceSampleRate << "Hz - falling back to client rate (" << clientSampleRate << "Hz)"sv; + logging::error("getDeviceProperty returned noErr but got invalid sample rate: {:.6g}Hz - falling back to client rate ({}Hz)", aggregateDeviceSampleRate, clientSampleRate); aggregateDeviceSampleRate = (Float64) clientSampleRate; } @@ -801,23 +820,21 @@ namespace platf { OSStatus streamConfigStatus = AudioObjectGetPropertyData(self->aggregateDeviceID, &streamConfigAddr, 0, NULL, &streamConfigSize, streamConfig); if (streamConfigStatus == noErr && streamConfig->mNumberBuffers > 0) { aggregateDeviceChannels = streamConfig->mBuffers[0].mNumberChannels; - BOOST_LOG(debug) << "Device reports "sv << aggregateDeviceChannels << " input channels"sv; + logging::debug("Device reports {} input channels", aggregateDeviceChannels); } else { - BOOST_LOG(error) << "Failed to get stream configuration, falling back to client channels (" << (int) clientChannels << "): "sv << streamConfigStatus; + logging::error("Failed to get stream configuration, falling back to client channels ({}): {}", (int) clientChannels, streamConfigStatus); } free(streamConfig); } } else { - BOOST_LOG(error) << "Failed to get stream configuration size, falling back to client channels (" << (int) clientChannels << "): "sv << streamConfigSizeStatus; + logging::error("Failed to get stream configuration size, falling back to client channels ({}): {}", (int) clientChannels, streamConfigSizeStatus); } - BOOST_LOG(debug) << "Device properties - Sample Rate: "sv << aggregateDeviceSampleRate << "Hz, Channels: "sv << aggregateDeviceChannels; + logging::debug("Device properties - Sample Rate: {:.6g}Hz, Channels: {}", aggregateDeviceSampleRate, aggregateDeviceChannels); // Create AudioConverter based on actual device properties vs client requirements BOOL needsConversion = (aggregateDeviceSampleRate != clientSampleRate) || (aggregateDeviceChannels != clientChannels); - BOOST_LOG(debug) << "needsConversion: "sv << (needsConversion ? "YES" : "NO") - << " (device: "sv << aggregateDeviceSampleRate << "Hz/" << aggregateDeviceChannels << "ch" - << " -> client: "sv << clientSampleRate << "Hz/" << (int) clientChannels << "ch)"sv; + logging::debug("needsConversion: {} (device: {:.6g}Hz/{}ch -> client: {}Hz/{}ch)", (needsConversion ? "YES" : "NO"), aggregateDeviceSampleRate, aggregateDeviceChannels, clientSampleRate, (int) clientChannels); if (needsConversion) { AudioStreamBasicDescription sourceFormat {}; @@ -842,12 +859,14 @@ namespace platf { OSStatus converterStatus = AudioConverterNew(&sourceFormat, &targetFormat, &self->ioProcData->audioConverter); if (converterStatus != noErr) { - BOOST_LOG(error) << "AudioConverterNew failed: " << ca::Status(converterStatus); + logging::error([&](std::ostream &out) { + out << "AudioConverterNew failed: " << ca::Status(converterStatus); + }); return converterStatus; } - BOOST_LOG(debug) << "AudioConverter created successfully for "sv << aggregateDeviceSampleRate << "Hz/" << aggregateDeviceChannels << "ch -> " << clientSampleRate << "Hz/" << (int) clientChannels << "ch"sv; + logging::debug("AudioConverter created successfully for {:.6g}Hz/{}ch -> {}Hz/{}ch", aggregateDeviceSampleRate, aggregateDeviceChannels, clientSampleRate, (int) clientChannels); } else { - BOOST_LOG(debug) << "No conversion needed - formats match (device: "sv << aggregateDeviceSampleRate << "Hz/" << aggregateDeviceChannels << "ch)"sv; + logging::debug("No conversion needed - formats match (device: {:.6g}Hz/{}ch)", aggregateDeviceSampleRate, aggregateDeviceChannels); } // Pre-allocate conversion buffer for real-time use (eliminates malloc in audio callback) @@ -856,7 +875,7 @@ namespace platf { self->ioProcData->conversionBuffer = (float *) malloc(self->ioProcData->conversionBufferSize); if (!self->ioProcData->conversionBuffer) { - BOOST_LOG(error) << "Failed to allocate conversion buffer"sv; + logging::error("Failed to allocate conversion buffer"sv); if (self->ioProcData->audioConverter) { AudioConverterDispose(self->ioProcData->audioConverter); self->ioProcData->audioConverter = NULL; @@ -864,13 +883,13 @@ namespace platf { return kAudioHardwareUnspecifiedError; } - BOOST_LOG(debug) << "Pre-allocated conversion buffer: "sv << self->ioProcData->conversionBufferSize << " bytes ("sv << maxFrames << " frames)"sv; + logging::debug("Pre-allocated conversion buffer: {} bytes ({} frames)", self->ioProcData->conversionBufferSize, maxFrames); // Store the actual device format for use in the IOProc self->ioProcData->aggregateDeviceSampleRate = aggregateDeviceSampleRate; self->ioProcData->aggregateDeviceChannels = aggregateDeviceChannels; - BOOST_LOG(debug) << "Device properties and converter configuration completed"sv; + logging::debug("Device properties and converter configuration completed"sv); return noErr; } @@ -878,23 +897,27 @@ namespace platf { using namespace std::literals; // Create IOProc - BOOST_LOG(debug) << "Creating IOProc for aggregate device ID: "sv << self->aggregateDeviceID; + logging::debug("Creating IOProc for aggregate device ID: {}", self->aggregateDeviceID); OSStatus status = AudioDeviceCreateIOProcID(self->aggregateDeviceID, platf::systemAudioIOProc, self->ioProcData, &self->ioProcID); if (status != kAudioHardwareNoError) { - BOOST_LOG(error) << "AudioDeviceCreateIOProcID failed: " << ca::Status(status); + logging::error([&](std::ostream &out) { + out << "AudioDeviceCreateIOProcID failed: " << ca::Status(status); + }); return status; } // Start the IOProc - BOOST_LOG(debug) << "Starting IOProc for aggregate device"; + logging::debug("Starting IOProc for aggregate device"); status = AudioDeviceStart(self->aggregateDeviceID, self->ioProcID); if (status != kAudioHardwareNoError) { - BOOST_LOG(error) << "AudioDeviceStart failed: " << ca::Status(status); + logging::error([&](std::ostream &out) { + out << "AudioDeviceStart failed: " << ca::Status(status); + }); AudioDeviceDestroyIOProcID(self->aggregateDeviceID, self->ioProcID); return status; } - BOOST_LOG(debug) << "System tap IO proc created and started successfully"sv; + logging::debug("System tap IO proc created and started successfully"sv); return noErr; } diff --git a/src/platform/macos/coreaudio_helpers.h b/src/platform/macos/coreaudio_helpers.h index 5330b716e..73b37717b 100644 --- a/src/platform/macos/coreaudio_helpers.h +++ b/src/platform/macos/coreaudio_helpers.h @@ -8,7 +8,7 @@ namespace ca { // Display FourCC error codes, with fallback to integer. - // Usage: BOOST_LOG(error) << ca::Status(err); + // Usage: logging::error([&](std::ostream &out) { out << ca::Status(err); }); // Some CoreAudio error examples: // kAudioHardwareNoError = 0, diff --git a/src/platform/macos/display.mm b/src/platform/macos/display.mm index b9a8eac66..1306be5b4 100644 --- a/src/platform/macos/display.mm +++ b/src/platform/macos/display.mm @@ -164,7 +164,7 @@ namespace platf { return device; } else { - BOOST_LOG(error) << "Unsupported Pixel Format."sv; + logging::error("Unsupported Pixel Format."sv); return nullptr; } } @@ -250,22 +250,22 @@ namespace platf { */ std::shared_ptr mac_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, display_device::manager_t &displays) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::videotoolbox) { - BOOST_LOG(error) << "Could not initialize display with the given hw device type."sv; + logging::error("Could not initialize display with the given hw device type."sv); return nullptr; } auto display = std::make_shared(); - BOOST_LOG(debug) << "Waking display for capture selector ["sv << display_name << ']'; + logging::debug("Waking display for capture selector [{}]", display_name); if (!display_device::wake_display(display_name, 1s)) { - BOOST_LOG(debug) << "Display wake attempt did not expose the requested display ["sv << display_name << ']'; + logging::debug("Display wake attempt did not expose the requested display [{}]", display_name); } display->display_power_guard = display_device::keep_display_awake("Sunshine display capture"); if (display->display_power_guard) { - BOOST_LOG(debug) << "Keeping display awake for capture"sv; + logging::debug("Keeping display awake for capture"sv); } else { - BOOST_LOG(debug) << "Unable to create display sleep prevention assertion"sv; + logging::debug("Unable to create display sleep prevention assertion"sv); } // Default to main display @@ -274,23 +274,20 @@ namespace platf { if (const auto configured_display_id {parse_display_id(display_name)}) { display->display_id = *configured_display_id; } else if (!display_name.empty()) { - BOOST_LOG(warning) << "Configured display ["sv << display_name - << "] is not a valid macOS capture display id. Falling back to main display ["sv - << display->display_id << "]."sv; + logging::warning("Configured display [{}] is not a valid macOS capture display id. Falling back to main display [{}].", display_name, display->display_id); } // Print all displays available with their names and ids - BOOST_LOG(debug) << "Detecting displays"sv; + logging::debug("Detecting displays"sv); for (const auto &device : displays.enumerate_devices()) { if (device.m_display_name.empty()) { continue; } - BOOST_LOG(debug) << "Detected display: "sv << device.m_friendly_name - << " (id: "sv << device.m_display_name << ") connected: true"sv; + logging::debug("Detected display: {} (id: {}) connected: true", device.m_friendly_name, device.m_display_name); } - BOOST_LOG(info) << "Configuring selected display ("sv << display->display_id << ") to stream"sv; + logging::info("Configuring selected display ({}) to stream", display->display_id); const auto selected_display_bounds = CGDisplayBounds(display->display_id); const auto desktop_bounds = active_desktop_bounds(display->display_id); @@ -305,15 +302,13 @@ namespace platf { display->env_width = display->env_logical_width; display->env_height = display->env_logical_height; - BOOST_LOG(debug) << "Selected display bounds: "sv << display->offset_x << 'x' << display->offset_y << ' ' - << display->logical_width << 'x' << display->logical_height; - BOOST_LOG(debug) << "Active desktop bounds: "sv << display->env_offset_x << 'x' << display->env_offset_y << ' ' - << display->env_logical_width << 'x' << display->env_logical_height; + logging::debug("Selected display bounds: {}x{} {}x{}", display->offset_x, display->offset_y, display->logical_width, display->logical_height); + logging::debug("Active desktop bounds: {}x{} {}x{}", display->env_offset_x, display->env_offset_y, display->env_logical_width, display->env_logical_height); display->av_capture = [[AVVideo alloc] initWithDisplay:display->display_id frameRate:config.framerate]; if (!display->av_capture) { - BOOST_LOG(error) << "Video setup failed."sv; + logging::error("Video setup failed."sv); return nullptr; } diff --git a/src/platform/macos/microphone.mm b/src/platform/macos/microphone.mm index 9e66c58d2..453d5b7ad 100644 --- a/src/platform/macos/microphone.mm +++ b/src/platform/macos/microphone.mm @@ -41,7 +41,7 @@ namespace platf { // Using 5 second timeout to prevent indefinite hanging dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, 5LL * NSEC_PER_SEC); if (dispatch_semaphore_wait(av_audio_capture->audioSemaphore, timeout) != 0) { - BOOST_LOG(warning) << "Audio sample timeout - no audio data received within 5 seconds"sv; + logging::warning("Audio sample timeout - no audio data received within 5 seconds"sv); // Fill with silence and return to prevent hanging std::fill(sample_in.begin(), sample_in.end(), 0.0f); @@ -86,7 +86,7 @@ namespace platf { * @return Status from updating sink. */ int set_sink(const std::string &sink) override { - BOOST_LOG(warning) << "audio_control_t::set_sink() unimplemented: "sv << sink; + logging::warning("audio_control_t::set_sink() unimplemented: {}", sink); return 0; } @@ -107,39 +107,41 @@ namespace platf { // Set the host audio enabled flag from the stream configuration mic->av_audio_capture.hostAudioEnabled = host_audio_enabled ? YES : NO; - BOOST_LOG(debug) << "Set hostAudioEnabled to: "sv << (host_audio_enabled ? "YES" : "NO"); + logging::debug("Set hostAudioEnabled to: {}", (host_audio_enabled ? "YES" : "NO")); if (settings.audio.sink.empty()) { // Use macOS system-wide audio tap - BOOST_LOG(info) << "Using macOS system audio tap for capture."sv; - BOOST_LOG(info) << "Sample rate: "sv << sample_rate << ", Frame size: "sv << frame_size << ", Channels: "sv << channels; + logging::info("Using macOS system audio tap for capture."sv); + logging::info("Sample rate: {}, Frame size: {}, Channels: {}", sample_rate, frame_size, channels); if ([mic->av_audio_capture setupSystemTap:sample_rate frameSize:frame_size channels:channels]) { - BOOST_LOG(error) << "Failed to setup system audio tap."sv; + logging::error("Failed to setup system audio tap."sv); return nullptr; } } else { // Use specified macOS audio sink const char *audio_sink = settings.audio.sink.c_str(); - BOOST_LOG(info) << "Using configured audio sink "sv << audio_sink << " for capture."sv; + logging::info("Using configured audio sink {} for capture.", audio_sink); if (!request_microphone_permission()) { return nullptr; } if ((audio_capture_device = [AVAudio findMicrophone:[NSString stringWithUTF8String:audio_sink]]) == nullptr) { - BOOST_LOG(error) << "opening microphone '"sv << audio_sink << "' failed. Please set a valid input source in the Sunshine config."sv; - BOOST_LOG(error) << "Available inputs:"sv; + logging::error("opening microphone '{}' failed. Please set a valid input source in the Sunshine config.", audio_sink); + logging::error("Available inputs:"sv); for (NSString *name in [AVAudio microphoneNames]) { - BOOST_LOG(error) << "\t"sv << [name UTF8String]; + logging::error([&](std::ostream &out) { + out << "\t"sv << [name UTF8String]; + }); } return nullptr; } if ([mic->av_audio_capture setupMicrophone:audio_capture_device sampleRate:sample_rate frameSize:frame_size channels:channels]) { - BOOST_LOG(error) << "Failed to setup microphone."sv; + logging::error("Failed to setup microphone."sv); return nullptr; } } @@ -148,7 +150,7 @@ namespace platf { } bool is_sink_available(const std::string &sink) override { - BOOST_LOG(warning) << "audio_control_t::is_sink_available() unimplemented: "sv << sink; + logging::warning("audio_control_t::is_sink_available() unimplemented: {}", sink); return true; } diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 759cc7aaf..4b8724b7f 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -16,6 +16,7 @@ #include #include #include +#include // platform includes #include @@ -289,7 +290,7 @@ namespace platf { if (id == "system_audio") { const bool settings_opened = open_privacy_settings(@"Privacy_ScreenCapture"); if (!request_system_audio_permission()) { - BOOST_LOG(warning) << "System audio recording permission or tap setup is unavailable"sv; + logging::warning("System audio recording permission or tap setup is unavailable"sv); } return settings_opened; } @@ -323,7 +324,7 @@ namespace platf { } [defaults setBool:YES forKey:system_audio_requested_key]; if (!request_system_audio_permission()) { - BOOST_LOG(warning) << "System audio recording permission or tap setup is unavailable"sv; + logging::warning("System audio recording permission or tap setup is unavailable"sv); } } @@ -337,8 +338,8 @@ namespace platf { std::unique_ptr init(const config::settings_t &settings) { if (!screen_recording_granted()) { - BOOST_LOG(error) << "No screen capture permission!"sv; - BOOST_LOG(error) << "Please activate Sunshine in System Settings -> Privacy & Security -> Screen & System Audio Recording"sv; + logging::error("No screen capture permission!"sv); + logging::error("Please activate Sunshine in System Settings -> Privacy & Security -> Screen & System Audio Recording"sv); return nullptr; } // Record that we determined that we have the screen capture permission. @@ -408,7 +409,7 @@ namespace platf { for (auto pos = ifaddrs.get(); pos != nullptr; pos = pos->ifa_next) { if (pos->ifa_addr && address == from_sockaddr(pos->ifa_addr)) { - BOOST_LOG(verbose) << "Looking for MAC of "sv << pos->ifa_name; + logging::verbose("Looking for MAC of {}", pos->ifa_name); struct ifaddrs *ifap, *ifaptr; unsigned char *ptr; @@ -429,14 +430,14 @@ namespace platf { freeifaddrs(ifap); if (ifaptr != nullptr) { - BOOST_LOG(verbose) << "Found MAC of "sv << pos->ifa_name << ": "sv << mac_address; + logging::verbose("Found MAC of {}: {}", pos->ifa_name, mac_address); return mac_address; } } } } - BOOST_LOG(warning) << "Unable to find MAC address for "sv << address; + logging::warning("Unable to find MAC address for {}", address); return "00:00:00:00:00:00"s; } @@ -473,9 +474,11 @@ namespace platf { std::error_code ec; auto child = run_command(false, false, cmd, working_dir, _env, nullptr, ec, nullptr); if (ec) { - BOOST_LOG(warning) << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + }); } else { - BOOST_LOG(info) << "Opened url ["sv << url << "]"sv; + logging::info("Opened url [{}]", url); child.detach(); } } @@ -497,7 +500,7 @@ namespace platf { mac_priority = QOS_CLASS_USER_INTERACTIVE; break; default: - BOOST_LOG(error) << "Unknown thread priority: "sv << (int) priority; + logging::error("Unknown thread priority: {}", (int) priority); return; } @@ -556,7 +559,9 @@ namespace platf { char executable[2048]; uint32_t size = sizeof(executable); if (_NSGetExecutablePath(executable, &size) < 0) { - BOOST_LOG(fatal) << "NSGetExecutablePath() failed: "sv << errno; + logging::fatal([&](std::ostream &out) { + out << "NSGetExecutablePath() failed: "sv << errno; + }); return; } @@ -572,7 +577,9 @@ namespace platf { // WindowServer retains stale state and silently refuses to show new tray icons. pid_t child = fork(); if (child < 0) { - BOOST_LOG(fatal) << "fork() failed: "sv << errno; + logging::fatal([&](std::ostream &out) { + out << "fork() failed: "sv << errno; + }); return; } @@ -620,10 +627,12 @@ namespace platf { bool request_process_group_exit(std::uintptr_t native_handle) { if (killpg((pid_t) native_handle, SIGTERM) == 0 || errno == ESRCH) { - BOOST_LOG(debug) << "Successfully sent SIGTERM to process group: "sv << native_handle; + logging::debug("Successfully sent SIGTERM to process group: {}", native_handle); return true; } else { - BOOST_LOG(warning) << "Unable to send SIGTERM to process group ["sv << native_handle << "]: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "Unable to send SIGTERM to process group ["sv << native_handle << "]: "sv << errno; + }); return false; } } @@ -746,7 +755,9 @@ namespace platf { pfd.events = POLLOUT; if (poll(&pfd, 1, -1) != 1) { - BOOST_LOG(warning) << "poll() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "poll() failed: "sv << errno; + }); break; } @@ -755,7 +766,9 @@ namespace platf { } if (bytes_sent < 0) { - BOOST_LOG(warning) << "sendmsg() failed: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "sendmsg() failed: "sv << errno; + }); return false; } @@ -789,7 +802,9 @@ namespace platf { for (const auto &tuple : options) { auto reset_val = std::get<2>(tuple); if (setsockopt(sockfd, std::get<0>(tuple), std::get<1>(tuple), &reset_val, sizeof(reset_val)) < 0) { - BOOST_LOG(warning) << "Failed to reset option: "sv << errno; + logging::warning([&](std::ostream &out) { + out << "Failed to reset option: "sv << errno; + }); } } } @@ -817,7 +832,7 @@ namespace platf { service_type = NET_SERVICE_TYPE_VO; break; default: - BOOST_LOG(error) << "Unknown traffic type: "sv << (int) data_type; + logging::error("Unknown traffic type: {}", (int) data_type); break; } @@ -826,7 +841,9 @@ namespace platf { // Reset SO_NET_SERVICE_TYPE to best-effort when QoS is disabled reset_options.emplace_back(std::make_tuple(SOL_SOCKET, SO_NET_SERVICE_TYPE, NET_SERVICE_TYPE_BE)); } else { - BOOST_LOG(error) << "Failed to set SO_NET_SERVICE_TYPE: "sv << errno; + logging::error([&](std::ostream &out) { + out << "Failed to set SO_NET_SERVICE_TYPE: "sv << errno; + }); } } @@ -852,7 +869,7 @@ namespace platf { dscp = 48; break; default: - BOOST_LOG(error) << "Unknown traffic type: "sv << (int) data_type; + logging::error("Unknown traffic type: {}", (int) data_type); break; } @@ -864,7 +881,9 @@ namespace platf { // Reset TOS to -1 when QoS is disabled reset_options.emplace_back(std::make_tuple(level, option, -1)); } else { - BOOST_LOG(error) << "Failed to set TOS/TCLASS: "sv << errno; + logging::error([&](std::ostream &out) { + out << "Failed to set TOS/TCLASS: "sv << errno; + }); } } } @@ -876,7 +895,7 @@ namespace platf { try { return boost::asio::ip::host_name(); } catch (boost::system::system_error &err) { - BOOST_LOG(error) << "Failed to get hostname: "sv << err.what(); + logging::error("Failed to get hostname: {}", err.what()); return "Sunshine"s; } } @@ -923,7 +942,9 @@ namespace dyn { ss << ']'; - BOOST_LOG(error) << ss.str(); + logging::error([&](std::ostream &out) { + out << ss.str(); + }); return nullptr; } @@ -936,7 +957,7 @@ namespace dyn { *fn = (void (*)()) dlsym(handle, name); if (!*fn && strict) { - BOOST_LOG(error) << "Couldn't find function: "sv << name; + logging::error("Couldn't find function: {}", name); err = -1; } diff --git a/src/platform/macos/publish.cpp b/src/platform/macos/publish.cpp index edd09eda7..c35e310ba 100644 --- a/src/platform/macos/publish.cpp +++ b/src/platform/macos/publish.cpp @@ -24,7 +24,7 @@ namespace platf::publish { void operator()(pointer serviceRef) { DNSServiceRefDeallocate(serviceRef); - BOOST_LOG(info) << "Deregistered DNS service."sv; + logging::info("Deregistered DNS service."sv); } }; @@ -52,7 +52,7 @@ namespace platf::publish { auto timeout = timeval {.tv_sec = 3, .tv_usec = 0}; // 3 second timeout const auto ready = select(socket + 1, &fdset, nullptr, nullptr, &timeout); if (ready == -1) { - BOOST_LOG(error) << "Failed to obtain response from DNS service."sv; + logging::error("Failed to obtain response from DNS service."sv); break; } else if (ready != 0) { DNSServiceProcessResult(serviceRef); @@ -83,10 +83,10 @@ namespace platf::publish { */ void registrationCallback(DNSServiceRef /*serviceRef*/, DNSServiceFlags /*flags*/, DNSServiceErrorType errorCode, const char * /*name*/, const char * /*regtype*/, const char * /*domain*/, void * /*context*/) { if (errorCode != kDNSServiceErr_NoError) { - BOOST_LOG(error) << "Failed to register DNS service: Error "sv << errorCode; + logging::error("Failed to register DNS service: Error {}", errorCode); return; } - BOOST_LOG(info) << "Successfully registered DNS service."sv; + logging::info("Successfully registered DNS service."sv); } } // anonymous namespace @@ -118,7 +118,7 @@ namespace platf::publish { nullptr // context ); if (status != kDNSServiceErr_NoError) { - BOOST_LOG(error) << "Failed immediately to register DNS service: Error "sv << status; + logging::error("Failed immediately to register DNS service: Error {}", status); return nullptr; } return std::make_unique(serviceRef); diff --git a/src/platform/virtualhid_input.cpp b/src/platform/virtualhid_input.cpp index 6df6ac09f..8ed31779d 100644 --- a/src/platform/virtualhid_input.cpp +++ b/src/platform/virtualhid_input.cpp @@ -76,7 +76,7 @@ namespace platf::virtualhid { void log_failure(std::string_view operation, const lvh::OperationStatus &status) { if (!status.ok()) { - BOOST_LOG(warning) << operation << ": "sv << status.message(); + logging::warning("{}: {}", operation, status.message()); } } @@ -89,16 +89,16 @@ namespace platf::virtualhid { void log_virtualhid_message(lvh::LogLevel level, const std::string &message) { switch (level) { case lvh::LogLevel::debug: - BOOST_LOG(debug) << "[libvirtualhid] "sv << message; + logging::debug("[libvirtualhid] {}", message); break; case lvh::LogLevel::info: - BOOST_LOG(info) << "[libvirtualhid] "sv << message; + logging::info("[libvirtualhid] {}", message); break; case lvh::LogLevel::warning: - BOOST_LOG(warning) << "[libvirtualhid] "sv << message; + logging::warning("[libvirtualhid] {}", message); break; case lvh::LogLevel::error: - BOOST_LOG(error) << "[libvirtualhid] "sv << message; + logging::error("[libvirtualhid] {}", message); break; } } @@ -194,27 +194,27 @@ namespace platf::virtualhid { } if (metadata.type == LI_CTYPE_PS) { - BOOST_LOG(info) << "Gamepad will be DualSense controller (auto-selected by client-reported type)"sv; + logging::info("Gamepad will be DualSense controller (auto-selected by client-reported type)"sv); return profile_for_name("ds5"sv); } if (metadata.type == LI_CTYPE_NINTENDO) { - BOOST_LOG(info) << "Gamepad will be Nintendo Switch Pro controller (auto-selected by client-reported type)"sv; + logging::info("Gamepad will be Nintendo Switch Pro controller (auto-selected by client-reported type)"sv); return profile_for_name("switch"sv); } if (metadata.type == LI_CTYPE_XBOX) { - BOOST_LOG(info) << "Gamepad will be Xbox Series controller (auto-selected by client-reported type)"sv; + logging::info("Gamepad will be Xbox Series controller (auto-selected by client-reported type)"sv); return profile_for_name("xseries"sv); } if (settings.input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { - BOOST_LOG(info) << "Gamepad will be DualSense controller (auto-selected by motion sensor presence)"sv; + logging::info("Gamepad will be DualSense controller (auto-selected by motion sensor presence)"sv); return profile_for_name("ds5"sv); } if (settings.input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { - BOOST_LOG(info) << "Gamepad will be DualSense controller (auto-selected by touchpad presence)"sv; + logging::info("Gamepad will be DualSense controller (auto-selected by touchpad presence)"sv); return profile_for_name("ds5"sv); } - BOOST_LOG(info) << "Gamepad will be Xbox Series controller (default)"sv; + logging::info("Gamepad will be Xbox Series controller (default)"sv); return profile_for_name("xseries"sv); } @@ -271,22 +271,22 @@ namespace platf::virtualhid { void warn_unsupported_client_features(int global_index, const gamepad_arrival_t &metadata, const lvh::GamepadProfileSupport &support) { if ((metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO)) && !support.supports_motion) { - BOOST_LOG(warning) << "Gamepad "sv << global_index << " has motion sensors, but the selected virtual profile cannot expose them"sv; + logging::warning("Gamepad {} has motion sensors, but the selected virtual profile cannot expose them", global_index); } if ((metadata.capabilities & LI_CCAP_TOUCHPAD) && !support.supports_touchpad) { - BOOST_LOG(warning) << "Gamepad "sv << global_index << " has a touchpad, but the selected virtual profile cannot expose it"sv; + logging::warning("Gamepad {} has a touchpad, but the selected virtual profile cannot expose it", global_index); } if ((metadata.capabilities & LI_CCAP_RGB_LED) && !support.supports_rgb_led) { - BOOST_LOG(warning) << "Gamepad "sv << global_index << " has an RGB LED, but the selected virtual profile cannot expose it"sv; + logging::warning("Gamepad {} has an RGB LED, but the selected virtual profile cannot expose it", global_index); } } void warn_missing_client_features(int global_index, const gamepad_arrival_t &metadata, const lvh::GamepadProfileSupport &support) { if (support.supports_motion && !(metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { - BOOST_LOG(warning) << "Gamepad "sv << global_index << " is emulating a motion-capable controller, but the client gamepad does not have motion sensors active"sv; + logging::warning("Gamepad {} is emulating a motion-capable controller, but the client gamepad does not have motion sensors active", global_index); } if (support.supports_touchpad && !(metadata.capabilities & LI_CCAP_TOUCHPAD)) { - BOOST_LOG(warning) << "Gamepad "sv << global_index << " is emulating a touchpad-capable controller, but the client gamepad does not have a touchpad"sv; + logging::warning("Gamepad {} is emulating a touchpad-capable controller, but the client gamepad does not have a touchpad", global_index); } } @@ -347,7 +347,7 @@ namespace platf::virtualhid { case BUTTON_X2: return extra; default: - BOOST_LOG(warning) << "Unknown mouse button: "sv << button; + logging::warning("Unknown mouse button: {}", button); return std::nullopt; } } @@ -553,7 +553,7 @@ namespace platf::virtualhid { gamepad_driver {settings.input.gamepad_driver}, runtime {create_runtime(backend)} { if (!runtime) { - BOOST_LOG(warning) << "Unable to create libvirtualhid runtime"sv; + logging::warning("Unable to create libvirtualhid runtime"sv); return; } @@ -693,7 +693,7 @@ namespace platf::virtualhid { for (auto &[name, is_enabled, reason_disabled] : gamepads) { if (!is_enabled) { - BOOST_LOG(warning) << "Gamepad "sv << name << " is disabled due to "sv << reason_disabled; + logging::warning("Gamepad {} is disabled due to {}", name, reason_disabled); } } @@ -730,7 +730,7 @@ namespace platf::virtualhid { return -1; } if (id.globalIndex < 0 || id.globalIndex >= static_cast(context.gamepads.size())) { - BOOST_LOG(warning) << "Invalid libvirtualhid gamepad index: "sv << id.globalIndex; + logging::warning("Invalid libvirtualhid gamepad index: {}", id.globalIndex); return -1; } @@ -739,9 +739,9 @@ namespace platf::virtualhid { auto profile = selection.profile(); profile.name = std::format("Sunshine {}", profile.name); if (settings.input.gamepad != "auto"sv) { - BOOST_LOG(info) << "Gamepad "sv << id.globalIndex << " will be "sv << profile.name << " (manual selection)"sv; + logging::info("Gamepad {} will be {} (manual selection)", id.globalIndex, profile.name); } else { - BOOST_LOG(info) << "Gamepad "sv << id.globalIndex << " will be "sv << profile.name; + logging::info("Gamepad {} will be {}", id.globalIndex, profile.name); } lvh::CreateGamepadOptions options; @@ -854,7 +854,7 @@ namespace platf::virtualhid { return !id.has_value(); }); if (slot == gamepad->touch_ids.end()) { - BOOST_LOG(warning) << "No free libvirtualhid gamepad touch slots"sv; + logging::warning("No free libvirtualhid gamepad touch slots"sv); return; } *slot = touch.pointerId; diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index 12748863f..67f99344d 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -365,7 +365,7 @@ namespace platf::audio { ); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't activate Device: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't activate Device: [0x{}]", util::hex(status).to_string_view()); return nullptr; } @@ -377,7 +377,7 @@ namespace platf::audio { wave_format_t mixer_waveformat; status = audio_client->GetMixFormat(&mixer_waveformat); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't get mix format for audio device: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't get mix format for audio device: [0x{}]", util::hex(status).to_string_view()); return nullptr; } @@ -387,9 +387,7 @@ namespace platf::audio { capture_waveformat.dwChannelMask = waveformatext_pointer->dwChannelMask; } - BOOST_LOG(info) << "Audio mixer format is "sv << mixer_waveformat->wBitsPerSample << "-bit, "sv - << mixer_waveformat->nSamplesPerSec << " Hz, "sv - << ((mixer_waveformat->nSamplesPerSec != 48000) ? "will be resampled to 48000 by Windows"sv : "no resampling needed"sv); + logging::info("Audio mixer format is {}-bit, {} Hz, {}", mixer_waveformat->wBitsPerSample, mixer_waveformat->nSamplesPerSec, (mixer_waveformat->nSamplesPerSec != 48000) ? "will be resampled to 48000 by Windows"sv : "no resampling needed"sv); } status = audio_client->Initialize( @@ -403,11 +401,13 @@ namespace platf::audio { ); if (status) { - BOOST_LOG(error) << "Couldn't initialize audio client for ["sv << format.name << "]: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't initialize audio client for [{}]: [0x{}]", format.name, util::hex(status).to_string_view()); return nullptr; } - BOOST_LOG(info) << "Audio capture format is "sv << logging::bracket(waveformat_to_pretty_string(capture_waveformat)); + logging::info([&](std::ostream &out) { + out << "Audio capture format is "sv << logging::bracket(waveformat_to_pretty_string(capture_waveformat)); + }); return audio_client; } @@ -428,7 +428,7 @@ namespace platf::audio { ); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't get default audio endpoint [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't get default audio endpoint [0x{}]", util::hex(status).to_string_view()); return nullptr; } @@ -610,7 +610,7 @@ namespace platf::audio { int init(std::uint32_t sample_rate, std::uint32_t frame_size, std::uint32_t channels_out, bool continuous, device_t capture_device) { audio_event.reset(CreateEventA(nullptr, FALSE, FALSE, nullptr)); if (!audio_event) { - BOOST_LOG(error) << "Couldn't create Event handle"sv; + logging::error("Couldn't create Event handle"sv); return -1; } @@ -626,14 +626,14 @@ namespace platf::audio { ); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't create Device Enumerator [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't create Device Enumerator [0x{}]", util::hex(status).to_string_view()); return -1; } status = device_enum->RegisterEndpointNotificationCallback(&endpt_notification); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't register endpoint notification [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't register endpoint notification [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -646,23 +646,22 @@ namespace platf::audio { for (const auto &format : formats) { if (format.channel_count != channels_out) { - BOOST_LOG(debug) << "Skipping audio format ["sv << format.name << "] with channel count ["sv - << format.channel_count << " != "sv << channels_out << ']'; + logging::debug("Skipping audio format [{}] with channel count [{} != {}]", format.name, format.channel_count, channels_out); continue; } - BOOST_LOG(debug) << "Trying audio format ["sv << format.name << ']'; + logging::debug("Trying audio format [{}]", format.name); audio_client = make_audio_client(device, format); if (audio_client) { - BOOST_LOG(debug) << "Found audio format ["sv << format.name << ']'; + logging::debug("Found audio format [{}]", format.name); channels = channels_out; break; } } if (!audio_client) { - BOOST_LOG(error) << "Couldn't find supported format for audio"sv; + logging::error("Couldn't find supported format for audio"sv); return -1; } @@ -674,7 +673,7 @@ namespace platf::audio { std::uint32_t frames; status = audio_client->GetBufferSize(&frames); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't acquire the number of audio frames [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't acquire the number of audio frames [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -685,14 +684,14 @@ namespace platf::audio { status = audio_client->GetService(IID_IAudioCaptureClient, (void **) &audio_capture); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't initialize audio capture client [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't initialize audio capture client [0x{}]", util::hex(status).to_string_view()); return -1; } status = audio_client->SetEventHandle(audio_event.get()); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't set event handle [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't set event handle [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -701,13 +700,15 @@ namespace platf::audio { DWORD task_index = 0; mmcss_task_handle = AvSetMmThreadCharacteristics("Pro Audio", &task_index); if (!mmcss_task_handle) { - BOOST_LOG(error) << "Couldn't associate audio capture thread with Pro Audio MMCSS task [0x" << util::hex(GetLastError()).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't associate audio capture thread with Pro Audio MMCSS task [0x" << util::hex(GetLastError()).to_string_view() << ']'; + }); } } status = audio_client->Start(); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't start recording [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't start recording [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -779,7 +780,7 @@ namespace platf::audio { case WAIT_TIMEOUT: return capture_e::timeout; default: - BOOST_LOG(error) << "Couldn't wait for audio event: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't wait for audio event: [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -803,19 +804,19 @@ namespace platf::audio { case AUDCLNT_E_DEVICE_INVALIDATED: return capture_e::reinit; default: - BOOST_LOG(error) << "Couldn't capture audio [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't capture audio [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } if (buffer_flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) { - BOOST_LOG(debug) << "Audio capture signaled buffer discontinuity"; + logging::debug("Audio capture signaled buffer discontinuity"); } sample_aligned.uninitialized = std::end(sample_buf) - sample_buf_pos; auto n = std::min(sample_aligned.uninitialized, block_aligned.audio_sample_size * channels); if (n < block_aligned.audio_sample_size * channels) { - BOOST_LOG(warning) << "Audio capture buffer overflow"; + logging::warning("Audio capture buffer overflow"); } if (buffer_flags & AUDCLNT_BUFFERFLAGS_SILENT) { @@ -886,7 +887,7 @@ namespace platf::audio { if (settings.audio.external_audio) { if (settings.audio.sink.empty()) { - BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; + logging::error("external_audio requires an explicit audio_sink"); return std::nullopt; } sink.host = settings.audio.sink; @@ -929,7 +930,7 @@ namespace platf::audio { "virtual-"s + formats[2].name + device_id, }); } else if (!settings.audio.virtual_sink.empty()) { - BOOST_LOG(warning) << "Couldn't find the specified virtual audio sink " << settings.audio.virtual_sink; + logging::warning("Couldn't find the specified virtual audio sink {}", settings.audio.virtual_sink); } return sink; @@ -1013,7 +1014,7 @@ namespace platf::audio { const auto &requested_sink = settings.audio.external_audio || assigned_sink.empty() ? settings.audio.sink : assigned_sink; if (settings.audio.external_audio && requested_sink.empty()) { - BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; + logging::error("external_audio requires an explicit audio_sink"); return nullptr; } @@ -1024,11 +1025,11 @@ namespace platf::audio { if (!requested_sink.empty()) { capture_device = get_sink_device(requested_sink); if (!capture_device) { - BOOST_LOG(error) << "Couldn't resolve audio sink ["sv << requested_sink << "] to a capture device"sv; + logging::error("Couldn't resolve audio sink [{}] to a capture device", requested_sink); return nullptr; } - BOOST_LOG(info) << "Capturing audio from sink ["sv << requested_sink << ']'; + logging::info("Capturing audio from sink [{}]", requested_sink); } if (mic->init(sample_rate, frame_size, channels, continuous_audio, std::move(capture_device))) { @@ -1039,7 +1040,7 @@ namespace platf::audio { auto virtual_sink_info = extract_virtual_sink_info(assigned_sink); if (virtual_sink_info && !settings.audio.external_audio) { mic->default_endpt_changed_cb = [this] { - BOOST_LOG(info) << "Resetting sink to ["sv << assigned_sink << "] after default changed"; + logging::info("Resetting sink to [{}] after default changed", assigned_sink); set_sink(assigned_sink); }; } @@ -1072,7 +1073,7 @@ namespace platf::audio { if (matched) { return matched->second; } else { - BOOST_LOG(error) << "Couldn't find audio sink " << sink; + logging::error("Couldn't find audio sink {}", sink); return std::nullopt; } } @@ -1089,7 +1090,7 @@ namespace platf::audio { if (SUCCEEDED(current_default_dev->OpenPropertyStore(STGM_READ, &prop)) && SUCCEEDED(prop->GetValue(PKEY_AudioEngine_DeviceFormat, ¤t_device_format.prop))) { auto *format = (WAVEFORMATEXTENSIBLE *) current_device_format.prop.blob.pBlobData; wanted_bits_per_sample = format->Samples.wValidBitsPerSample; - BOOST_LOG(info) << "Virtual audio device will use "sv << wanted_bits_per_sample << "-bit to match default device"sv; + logging::info("Virtual audio device will use {}-bit to match default device", wanted_bits_per_sample); } } @@ -1108,12 +1109,14 @@ namespace platf::audio { WAVEFORMATEXTENSIBLE p {}; if (SUCCEEDED(policy->SetDeviceFormat(device_id_copy.c_str(), waveformat_copy_pointer, (WAVEFORMATEX *) &p))) { - BOOST_LOG(info) << "Changed virtual audio sink format to " << logging::bracket(waveformat_to_pretty_string(waveformat)); + logging::info([&](std::ostream &out) { + out << "Changed virtual audio sink format to " << logging::bracket(waveformat_to_pretty_string(waveformat)); + }); return device_id; } } - BOOST_LOG(error) << "Couldn't set virtual audio sink waveformat"; + logging::error("Couldn't set virtual audio sink waveformat"); return std::nullopt; } @@ -1139,9 +1142,9 @@ namespace platf::audio { if (status) { // Depending on the format of the string, we could get either of these errors if (status == HRESULT_FROM_WIN32(ERROR_NOT_FOUND) || status == E_INVALIDARG) { - BOOST_LOG(warning) << "Audio sink not found: "sv << sink; + logging::warning("Audio sink not found: {}", sink); } else { - BOOST_LOG(warning) << "Couldn't set ["sv << sink << "] to role ["sv << x << "]: 0x"sv << util::hex(status).to_string_view(); + logging::warning("Couldn't set [{}] to role [{}]: 0x{}", sink, x, util::hex(status).to_string_view()); } ++failure; @@ -1216,7 +1219,7 @@ namespace platf::audio { collection_t collection; auto status = device_enum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't enumerate: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't enumerate: [0x{}]", util::hex(status).to_string_view()); return std::nullopt; } @@ -1312,7 +1315,7 @@ namespace platf::audio { // Disable the Steam Streaming Speakers temporarily to allow the OS to pick a new default. auto hr = policy->SetEndpointVisibility(steam_device_id.c_str(), FALSE); if (FAILED(hr)) { - BOOST_LOG(warning) << "Failed to disable Steam audio device: "sv << util::hex(hr).to_string_view(); + logging::warning("Failed to disable Steam audio device: {}", util::hex(hr).to_string_view()); return; } @@ -1322,7 +1325,7 @@ namespace platf::audio { // Enable the Steam Streaming Speakers again hr = policy->SetEndpointVisibility(steam_device_id.c_str(), TRUE); if (FAILED(hr)) { - BOOST_LOG(warning) << "Failed to enable Steam audio device: "sv << util::hex(hr).to_string_view(); + logging::warning("Failed to enable Steam audio device: {}", util::hex(hr).to_string_view()); return; } @@ -1340,7 +1343,7 @@ namespace platf::audio { policy->SetDefaultEndpoint(new_default_id.get(), (ERole) x); } - BOOST_LOG(info) << "Successfully reset default audio device"sv; + logging::info("Successfully reset default audio device"sv); } /** @@ -1353,7 +1356,7 @@ namespace platf::audio { // so we have to load it at runtime. It's Vista or later, so it will always be available. auto newdev = LoadLibraryExW(L"newdev.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (!newdev) { - BOOST_LOG(error) << "newdev.dll failed to load"sv; + logging::error("newdev.dll failed to load"sv); return false; } auto fg = util::fail_guard([newdev]() { @@ -1362,7 +1365,7 @@ namespace platf::audio { auto fn_DiInstallDriverW = (decltype(DiInstallDriverW) *) GetProcAddress(newdev, "DiInstallDriverW"); if (!fn_DiInstallDriverW) { - BOOST_LOG(error) << "DiInstallDriverW() is missing"sv; + logging::error("DiInstallDriverW() is missing"sv); return false; } @@ -1373,7 +1376,7 @@ namespace platf::audio { std::array driver_path = {}; ExpandEnvironmentStringsW(STEAM_AUDIO_DRIVER_PATH, driver_path.data(), driver_path.size()); if (fn_DiInstallDriverW(nullptr, driver_path.data(), 0, nullptr)) { - BOOST_LOG(info) << "Successfully installed Steam Streaming Speakers"sv; + logging::info("Successfully installed Steam Streaming Speakers"sv); // Wait for 5 seconds to allow the audio subsystem to reconfigure things before // modifying the default audio device or enumerating devices again. @@ -1395,21 +1398,21 @@ namespace platf::audio { auto err = GetLastError(); switch (err) { case ERROR_ACCESS_DENIED: - BOOST_LOG(warning) << "Administrator privileges are required to install Steam Streaming Speakers"sv; + logging::warning("Administrator privileges are required to install Steam Streaming Speakers"sv); break; case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: - BOOST_LOG(info) << "Steam audio drivers not found. This is expected if you don't have Steam installed."sv; + logging::info("Steam audio drivers not found. This is expected if you don't have Steam installed."sv); break; default: - BOOST_LOG(warning) << "Failed to install Steam audio drivers: "sv << err; + logging::warning("Failed to install Steam audio drivers: {}", err); break; } return false; } #else - BOOST_LOG(warning) << "Unable to install Steam Streaming Speakers on unknown architecture"sv; + logging::warning("Unable to install Steam Streaming Speakers on unknown architecture"sv); return false; #endif } @@ -1433,7 +1436,7 @@ namespace platf::audio { ); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't create audio policy config: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't create audio policy config: [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -1448,7 +1451,7 @@ namespace platf::audio { ); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't create Device Enumerator: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't create Device Enumerator: [0x{}]", util::hex(status).to_string_view()); return -1; } diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 1f8701d55..77b959837 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -73,7 +73,7 @@ namespace platf::dxgi { // Ask the display implementation which formats it supports auto supported_formats = display->get_supported_capture_formats(); if (supported_formats.empty()) { - BOOST_LOG(warning) << "No compatible capture formats for this encoder"sv; + logging::warning("No compatible capture formats for this encoder"sv); return -1; } @@ -93,16 +93,16 @@ namespace platf::dxgi { // with mode changes and we don't want to accidentally fall back to suboptimal capture if // we get unlucky and succeed below. if (FAILED(status)) { - BOOST_LOG(warning) << "DuplicateOutput1 Failed [0x"sv << util::hex(status).to_string_view() << ']'; + logging::warning("DuplicateOutput1 Failed [0x{}]", util::hex(status).to_string_view()); return -1; } } else { - BOOST_LOG(warning) << "IDXGIOutput5 is not supported by your OS. Capture performance may be reduced."sv; + logging::warning("IDXGIOutput5 is not supported by your OS. Capture performance may be reduced."sv); dxgi::output1_t output1 {}; status = display->output->QueryInterface(IID_IDXGIOutput1, (void **) &output1); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIOutput1 from the output"sv; + logging::error("Failed to query IDXGIOutput1 from the output"sv); return -1; } @@ -118,7 +118,7 @@ namespace platf::dxgi { } if (FAILED(status)) { - BOOST_LOG(error) << "DuplicateOutput Failed [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("DuplicateOutput Failed [0x{}]", util::hex(status).to_string_view()); return -1; } } @@ -127,18 +127,20 @@ namespace platf::dxgi { DXGI_OUTDUPL_DESC dup_desc; dup->GetDesc(&dup_desc); - BOOST_LOG(info) << "Desktop resolution ["sv << dup_desc.ModeDesc.Width << 'x' << dup_desc.ModeDesc.Height << ']'; - BOOST_LOG(info) << "Desktop format ["sv << display->dxgi_format_to_string(dup_desc.ModeDesc.Format) << ']'; + logging::info("Desktop resolution [{}x{}]", dup_desc.ModeDesc.Width, dup_desc.ModeDesc.Height); + logging::info("Desktop format [{}]", display->dxgi_format_to_string(dup_desc.ModeDesc.Format)); display->display_refresh_rate = dup_desc.ModeDesc.RefreshRate; double display_refresh_rate_decimal = (double) display->display_refresh_rate.Numerator / display->display_refresh_rate.Denominator; - BOOST_LOG(info) << "Display refresh rate [" << display_refresh_rate_decimal << "Hz]"; + logging::info("Display refresh rate [{:.6g}Hz]", display_refresh_rate_decimal); if (display->client_frame_rate_strict.Numerator > 0) { int num = display->client_frame_rate_strict.Numerator; int den = display->client_frame_rate_strict.Denominator; - BOOST_LOG(info) << "Requested frame rate [" << num << "/" << den << " exactly " << av_q2d(AVRational {num, den}) << " fps]"; + logging::info([&](std::ostream &out) { + out << "Requested frame rate [" << num << "/" << den << " exactly " << av_q2d(AVRational {num, den}) << " fps]"; + }); } else { - BOOST_LOG(info) << "Requested frame rate [" << display->client_frame_rate << "fps]"; + logging::info("Requested frame rate [{}fps]", display->client_frame_rate); } display->display_refresh_rate_rounded = lround(display_refresh_rate_decimal); return 0; @@ -158,7 +160,7 @@ namespace platf::dxgi { // is on screen the whole time, so we can't just print when it changes. Instead we'll keep track // of the last time we printed the warning and print another if we haven't printed one recently. if (frame_info.ProtectedContentMaskedOut && std::chrono::steady_clock::now() > last_protected_content_warning_time + 10s) { - BOOST_LOG(warning) << "Windows is currently blocking DRM-protected content from capture. You may see black regions where this content would be."sv; + logging::warning("Windows is currently blocking DRM-protected content from capture. You may see black regions where this content would be."sv); last_protected_content_warning_time = std::chrono::steady_clock::now(); } @@ -171,7 +173,7 @@ namespace platf::dxgi { case DXGI_ERROR_ACCESS_DENIED: return capture_e::reinit; default: - BOOST_LOG(error) << "Couldn't acquire next frame [0x"sv << util::hex(status).to_string_view(); + logging::error("Couldn't acquire next frame [0x{}", util::hex(status).to_string_view()); return capture_e::error; } } @@ -196,14 +198,14 @@ namespace platf::dxgi { return capture_e::ok; case DXGI_ERROR_INVALID_CALL: - BOOST_LOG(warning) << "Duplication frame already released"; + logging::warning("Duplication frame already released"); return capture_e::ok; case DXGI_ERROR_ACCESS_LOST: return capture_e::reinit; default: - BOOST_LOG(error) << "Error while releasing duplication frame [0x"sv << util::hex(status).to_string_view(); + logging::error("Error while releasing duplication frame [0x{}", util::hex(status).to_string_view()); return capture_e::error; } } @@ -229,7 +231,7 @@ namespace platf::dxgi { double candidate_rate = (double) candidate.Numerator / candidate.Denominator; // Can only decrease requested fps, otherwise client may start accumulating frames and suffer increased latency. if (client_frame_rate > candidate_rate && candidate_rate / client_frame_rate > 0.99) { - BOOST_LOG(info) << "Adjusted capture rate to " << candidate_rate << "fps to better match display"; + logging::info("Adjusted capture rate to {:.6g}fps to better match display", candidate_rate); return candidate; } } @@ -301,7 +303,7 @@ namespace platf::dxgi { frame_pacing_group_start = img_out->frame_timestamp; if (!frame_pacing_group_start) { - BOOST_LOG(warning) << "snapshot() provided image without timestamp"; + logging::warning("snapshot() provided image without timestamp"); frame_pacing_group_start = std::chrono::steady_clock::now(); } @@ -344,7 +346,7 @@ namespace platf::dxgi { } break; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']'; + logging::error("Unrecognized capture status [{}]", (int) status); return status; } @@ -391,14 +393,14 @@ namespace platf::dxgi { nullptr ); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create D3D11 device for DD test [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create D3D11 device for DD test [0x{}]", util::hex(status).to_string_view()); return false; } output1_t output1; status = output->QueryInterface(IID_IDXGIOutput1, (void **) &output1); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIOutput1 from the output"sv; + logging::error("Failed to query IDXGIOutput1 from the output"sv); return false; } @@ -427,7 +429,7 @@ namespace platf::dxgi { } } - BOOST_LOG(error) << "DuplicateOutput() test failed [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("DuplicateOutput() test failed [0x{}]", util::hex(status).to_string_view()); return false; } @@ -484,7 +486,7 @@ namespace platf::dxgi { status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create DXGIFactory1 [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create DXGIFactory1 [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -558,7 +560,7 @@ namespace platf::dxgi { } if (!output) { - BOOST_LOG(error) << "Failed to locate an output device"sv; + logging::error("Failed to locate an output device"sv); return -1; } @@ -574,7 +576,7 @@ namespace platf::dxgi { status = adapter->QueryInterface(IID_IDXGIAdapter, (void **) &adapter_p); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIAdapter interface"sv; + logging::error("Failed to query IDXGIAdapter interface"sv); return -1; } @@ -594,7 +596,7 @@ namespace platf::dxgi { adapter_p->Release(); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create D3D11 device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create D3D11 device [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -603,18 +605,19 @@ namespace platf::dxgi { adapter->GetDesc(&adapter_desc); auto description = utf_utils::to_utf8(adapter_desc.Description); - BOOST_LOG(info) - << std::endl - << "Device Description : " << 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 - << "Device Sys Mem : "sv << adapter_desc.DedicatedSystemMemory / 1048576 << " MiB"sv << std::endl - << "Share Sys Mem : "sv << adapter_desc.SharedSystemMemory / 1048576 << " MiB"sv << std::endl - << "Feature Level : 0x"sv << util::hex(feature_level).to_string_view() << std::endl - << "Capture size : "sv << width << 'x' << height << std::endl - << "Offset : "sv << offset_x << 'x' << offset_y << std::endl - << "Virtual Desktop : "sv << env_width << 'x' << env_height; + logging::info([&](std::ostream &out) { + out << std::endl + << "Device Description : " << 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 + << "Device Sys Mem : "sv << adapter_desc.DedicatedSystemMemory / 1048576 << " MiB"sv << std::endl + << "Share Sys Mem : "sv << adapter_desc.SharedSystemMemory / 1048576 << " MiB"sv << std::endl + << "Feature Level : 0x"sv << util::hex(feature_level).to_string_view() << std::endl + << "Capture size : "sv << width << 'x' << height << std::endl + << "Offset : "sv << offset_x << 'x' << offset_y << std::endl + << "Virtual Desktop : "sv << env_width << 'x' << env_height; + }); // Bump up thread priority { @@ -629,7 +632,7 @@ namespace platf::dxgi { tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), nullptr, nullptr)) { - BOOST_LOG(warning) << "Could not set privilege to increase GPU priority"; + logging::warning("Could not set privilege to increase GPU priority"); } } @@ -642,13 +645,13 @@ namespace platf::dxgi { auto d3dkmt_query_adapter_info = (PD3DKMTQueryAdapterInfo) GetProcAddress(gdi32, "D3DKMTQueryAdapterInfo"); auto d3dkmt_close_adapter = (PD3DKMTCloseAdapter) GetProcAddress(gdi32, "D3DKMTCloseAdapter"); if (!d3dkmt_open_adapter || !d3dkmt_query_adapter_info || !d3dkmt_close_adapter) { - BOOST_LOG(error) << "Couldn't load d3dkmt functions from gdi32.dll to determine GPU HAGS status"; + logging::error("Couldn't load d3dkmt functions from gdi32.dll to determine GPU HAGS status"); return false; } D3DKMT_OPENADAPTERFROMLUID d3dkmt_adapter = {.AdapterLuid = adapter}; if (FAILED(d3dkmt_open_adapter(&d3dkmt_adapter))) { - BOOST_LOG(error) << "D3DKMTOpenAdapterFromLuid() failed while trying to determine GPU HAGS status"; + logging::error("D3DKMTOpenAdapterFromLuid() failed while trying to determine GPU HAGS status"); return false; } @@ -664,13 +667,13 @@ namespace platf::dxgi { if (SUCCEEDED(d3dkmt_query_adapter_info(&d3dkmt_adapter_info))) { result = d3dkmt_adapter_caps.HwSchEnabled; } else { - BOOST_LOG(warning) << "D3DKMTQueryAdapterInfo() failed while trying to determine GPU HAGS status"; + logging::warning("D3DKMTQueryAdapterInfo() failed while trying to determine GPU HAGS status"); result = false; } D3DKMT_CLOSEADAPTER d3dkmt_close_adapter_wrap = {d3dkmt_adapter.hAdapter}; if (FAILED(d3dkmt_close_adapter(&d3dkmt_close_adapter_wrap))) { - BOOST_LOG(error) << "D3DKMTCloseAdapter() failed while trying to determine GPU HAGS status"; + logging::error("D3DKMTCloseAdapter() failed while trying to determine GPU HAGS status"); } return result; @@ -688,26 +691,26 @@ namespace platf::dxgi { priority = D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH; } } - BOOST_LOG(info) << "Active GPU has HAGS " << (hags_enabled ? "enabled" : "disabled"); - BOOST_LOG(info) << "Using " << (priority == D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH ? "high" : "realtime") << " GPU priority"; + logging::info("Active GPU has HAGS {}", (hags_enabled ? "enabled" : "disabled")); + logging::info("Using {} GPU priority", (priority == D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH ? "high" : "realtime")); if (FAILED(d3dkmt_set_process_priority(GetCurrentProcess(), priority))) { - BOOST_LOG(warning) << "Failed to adjust GPU priority. Please run application as administrator for optimal performance."; + logging::warning("Failed to adjust GPU priority. Please run application as administrator for optimal performance."); } } else { - BOOST_LOG(error) << "Couldn't load D3DKMTSetProcessSchedulingPriorityClass function from gdi32.dll to adjust GPU priority"; + logging::error("Couldn't load D3DKMTSetProcessSchedulingPriorityClass function from gdi32.dll to adjust GPU priority"); } } dxgi::dxgi_t dxgi; status = device->QueryInterface(IID_IDXGIDevice, (void **) &dxgi); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to query DXGI interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::warning("Failed to query DXGI interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } status = dxgi->SetGPUThreadPriority(7); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to increase capture GPU thread priority. Please run application as administrator for optimal performance."; + logging::warning("Failed to increase capture GPU thread priority. Please run application as administrator for optimal performance."); } } @@ -716,13 +719,13 @@ namespace platf::dxgi { dxgi::dxgi1_t dxgi {}; status = device->QueryInterface(IID_IDXGIDevice, (void **) &dxgi); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query DXGI interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query DXGI interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } status = dxgi->SetMaximumFrameLatency(1); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to set maximum frame latency [0x"sv << util::hex(status).to_string_view() << ']'; + logging::warning("Failed to set maximum frame latency [0x{}]", util::hex(status).to_string_view()); } } @@ -739,21 +742,22 @@ namespace platf::dxgi { DXGI_OUTPUT_DESC1 desc1; output6->GetDesc1(&desc1); - BOOST_LOG(info) - << std::endl - << "Colorspace : "sv << colorspace_to_string(desc1.ColorSpace) << std::endl - << "Bits Per Color : "sv << desc1.BitsPerColor << std::endl - << "Red Primary : ["sv << desc1.RedPrimary[0] << ',' << desc1.RedPrimary[1] << ']' << std::endl - << "Green Primary : ["sv << desc1.GreenPrimary[0] << ',' << desc1.GreenPrimary[1] << ']' << std::endl - << "Blue Primary : ["sv << desc1.BluePrimary[0] << ',' << desc1.BluePrimary[1] << ']' << std::endl - << "White Point : ["sv << desc1.WhitePoint[0] << ',' << desc1.WhitePoint[1] << ']' << std::endl - << "Min Luminance : "sv << desc1.MinLuminance << " nits"sv << std::endl - << "Max Luminance : "sv << desc1.MaxLuminance << " nits"sv << std::endl - << "Max Full Luminance : "sv << desc1.MaxFullFrameLuminance << " nits"sv; + logging::info([&](std::ostream &out) { + out << std::endl + << "Colorspace : "sv << colorspace_to_string(desc1.ColorSpace) << std::endl + << "Bits Per Color : "sv << desc1.BitsPerColor << std::endl + << "Red Primary : ["sv << desc1.RedPrimary[0] << ',' << desc1.RedPrimary[1] << ']' << std::endl + << "Green Primary : ["sv << desc1.GreenPrimary[0] << ',' << desc1.GreenPrimary[1] << ']' << std::endl + << "Blue Primary : ["sv << desc1.BluePrimary[0] << ',' << desc1.BluePrimary[1] << ']' << std::endl + << "White Point : ["sv << desc1.WhitePoint[0] << ',' << desc1.WhitePoint[1] << ']' << std::endl + << "Min Luminance : "sv << desc1.MinLuminance << " nits"sv << std::endl + << "Max Luminance : "sv << desc1.MaxLuminance << " nits"sv << std::endl + << "Max Full Luminance : "sv << desc1.MaxFullFrameLuminance << " nits"sv; + }); } if (!timer || !*timer) { - BOOST_LOG(error) << "Uninitialized high precision timer"; + logging::error("Uninitialized high precision timer"); return -1; } @@ -765,7 +769,7 @@ namespace platf::dxgi { auto status = output->QueryInterface(IID_IDXGIOutput6, (void **) &output6); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to query IDXGIOutput6 from the output"sv; + logging::warning("Failed to query IDXGIOutput6 from the output"sv); return false; } @@ -782,7 +786,7 @@ namespace platf::dxgi { auto status = output->QueryInterface(IID_IDXGIOutput6, (void **) &output6); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to query IDXGIOutput6 from the output"sv; + logging::warning("Failed to query IDXGIOutput6 from the output"sv); return false; } @@ -1060,7 +1064,7 @@ namespace platf { HRESULT status; - BOOST_LOG(debug) << "Detecting monitors..."sv; + logging::debug("Detecting monitors..."sv); // We sync the thread desktop once before we start the enumeration process // to ensure test_dxgi_duplication() returns consistent results for all GPUs @@ -1072,7 +1076,7 @@ namespace platf { dxgi::factory1_t factory; status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create DXGIFactory1 [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create DXGIFactory1 [0x{}]", util::hex(status).to_string_view()); return {}; } @@ -1082,17 +1086,18 @@ namespace platf { DXGI_ADAPTER_DESC1 adapter_desc; adapter->GetDesc1(&adapter_desc); - BOOST_LOG(debug) - << std::endl - << "====== ADAPTER ====="sv << std::endl - << "Device Name : "sv << utf_utils::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 - << "Device Sys Mem : "sv << adapter_desc.DedicatedSystemMemory / 1048576 << " MiB"sv << std::endl - << "Share Sys Mem : "sv << adapter_desc.SharedSystemMemory / 1048576 << " MiB"sv << std::endl - << std::endl - << " ====== OUTPUT ======"sv << std::endl; + logging::debug([&](std::ostream &out) { + out << std::endl + << "====== ADAPTER ====="sv << std::endl + << "Device Name : "sv << utf_utils::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 + << "Device Sys Mem : "sv << adapter_desc.DedicatedSystemMemory / 1048576 << " MiB"sv << std::endl + << "Share Sys Mem : "sv << adapter_desc.SharedSystemMemory / 1048576 << " MiB"sv << std::endl + << std::endl + << " ====== OUTPUT ======"sv << std::endl; + }); dxgi::output_t::pointer output_p {}; for (int y = 0; adapter->EnumOutputs(y, &output_p) != DXGI_ERROR_NOT_FOUND; ++y) { @@ -1106,11 +1111,12 @@ namespace platf { auto width = desc.DesktopCoordinates.right - desc.DesktopCoordinates.left; auto height = desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top; - BOOST_LOG(debug) - << " Output Name : "sv << device_name << std::endl - << " AttachedToDesktop : "sv << (desc.AttachedToDesktop ? "yes"sv : "no"sv) << std::endl - << " Resolution : "sv << width << 'x' << height << std::endl - << std::endl; + logging::debug([&](std::ostream &out) { + out << " Output Name : "sv << device_name << std::endl + << " AttachedToDesktop : "sv << (desc.AttachedToDesktop ? "yes"sv : "no"sv) << std::endl + << " Resolution : "sv << width << 'x' << height << std::endl + << 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, true)) { @@ -1139,13 +1145,13 @@ namespace platf { auto status = CreateDXGIFactory1(IID_IDXGIFactory1, (void **) &factory); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create DXGIFactory1 [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create DXGIFactory1 [0x{}]", util::hex(status).to_string_view()); factory.release(); } // Always request reenumeration on the first streaming session just to ensure we // can deal with any initialization races that may occur when the system is booting. - BOOST_LOG(info) << "Encoder reenumeration is required"sv; + logging::info("Encoder reenumeration is required"sv); return true; } else { // The DXGI factory from last time is still current, so no encoder changes have occurred. diff --git a/src/platform/windows/display_ram.cpp b/src/platform/windows/display_ram.cpp index 9a4553bff..fde5a9e40 100644 --- a/src/platform/windows/display_ram.cpp +++ b/src/platform/windows/display_ram.cpp @@ -201,7 +201,7 @@ namespace platf::dxgi { blend_cursor_color(cursor, img, true); break; default: - BOOST_LOG(warning) << "Unsupported cursor format ["sv << cursor.shape_info.Type << ']'; + logging::warning("Unsupported cursor format [{}]", cursor.shape_info.Type); } } @@ -239,7 +239,7 @@ namespace platf::dxgi { UINT dummy; status = dup.dup->GetFramePointerShape(img_data.size(), img_data.data(), &dummy, &cursor.shape_info); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to get new pointer shape [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to get new pointer shape [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -257,7 +257,7 @@ namespace platf::dxgi { status = res->QueryInterface(IID_ID3D11Texture2D, (void **) &src); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't query interface [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't query interface [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -267,7 +267,7 @@ namespace platf::dxgi { // If we don't know the capture format yet, grab it from this texture and create the staging texture if (capture_format == DXGI_FORMAT_UNKNOWN) { capture_format = desc.Format; - BOOST_LOG(info) << "Capture format ["sv << dxgi_format_to_string(capture_format) << ']'; + logging::info("Capture format [{}]", dxgi_format_to_string(capture_format)); D3D11_TEXTURE2D_DESC t {}; t.Width = width; @@ -282,7 +282,7 @@ namespace platf::dxgi { auto status = device->CreateTexture2D(&t, nullptr, &texture); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create staging texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create staging texture [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } } @@ -290,14 +290,14 @@ namespace platf::dxgi { // It's possible for our display enumeration to race with mode changes and result in // mismatched image pool and desktop texture sizes. If this happens, just reinit again. if (desc.Width != width || desc.Height != height) { - BOOST_LOG(info) << "Capture size changed ["sv << width << 'x' << height << " -> "sv << desc.Width << 'x' << desc.Height << ']'; + logging::info("Capture size changed [{}x{} -> {}x{}]", width, height, desc.Width, desc.Height); return capture_e::reinit; } // It's also possible for the capture format to change on the fly. If that happens, // reinitialize capture to try format detection again and create new images. if (capture_format != desc.Format) { - BOOST_LOG(info) << "Capture format changed ["sv << dxgi_format_to_string(capture_format) << " -> "sv << dxgi_format_to_string(desc.Format) << ']'; + logging::info("Capture format changed [{} -> {}]", dxgi_format_to_string(capture_format), dxgi_format_to_string(desc.Format)); return capture_e::reinit; } @@ -313,7 +313,7 @@ namespace platf::dxgi { // If we don't know the final capture format yet, encode a dummy image if (capture_format == DXGI_FORMAT_UNKNOWN) { - BOOST_LOG(debug) << "Capture format is still unknown. Encoding a blank image"sv; + logging::debug("Capture format is still unknown. Encoding a blank image"sv); if (dummy_img(img)) { return capture_e::error; @@ -322,7 +322,7 @@ namespace platf::dxgi { // Map the staging texture for CPU access (making it inaccessible for the GPU) status = device_ctx->Map(texture.get(), 0, D3D11_MAP_READ, 0, &img_info); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to map texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to map texture [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -369,7 +369,7 @@ namespace platf::dxgi { int display_ram_t::complete_img(platf::img_t *img, bool dummy) { // If this is not a dummy image, we must know the format by now if (!dummy && capture_format == DXGI_FORMAT_UNKNOWN) { - BOOST_LOG(error) << "display_ram_t::complete_img() called with unknown capture format!"; + logging::error("display_ram_t::complete_img() called with unknown capture format!"); return -1; } diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 482046dc2..7ae6f97a7 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -75,7 +75,7 @@ namespace platf::dxgi { buf_t::pointer buf_p; auto status = device->CreateBuffer(&buffer_desc, &init_data, &buf_p); if (status) { - BOOST_LOG(error) << "Failed to create buffer: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create buffer: [0x{}]", util::hex(status).to_string_view()); return nullptr; } @@ -117,7 +117,7 @@ namespace platf::dxgi { blend_t blend; auto status = device->CreateBlendState(&bdesc, &blend); if (status) { - BOOST_LOG(error) << "Failed to create blend state: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create blend state: [0x{}]", util::hex(status).to_string_view()); return nullptr; } @@ -236,7 +236,7 @@ namespace platf::dxgi { if (status == S_OK) { _locked = true; } else { - BOOST_LOG(error) << "Failed to acquire texture mutex [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to acquire texture mutex [0x{}]", util::hex(status).to_string_view()); } return _locked; } @@ -270,7 +270,7 @@ namespace platf::dxgi { pixel = transparent; } else { // Other alpha values are illegal in masked color cursors - BOOST_LOG(warning) << "Illegal alpha value in masked color cursor: " << alpha; + logging::warning("Illegal alpha value in masked color cursor: {}", static_cast(alpha)); } }); return cursor_img; @@ -279,7 +279,7 @@ namespace platf::dxgi { // Monochrome is handled below break; default: - BOOST_LOG(error) << "Invalid cursor shape type: " << shape_info.Type; + logging::error("Invalid cursor shape type: {}", shape_info.Type); return {}; } @@ -345,7 +345,7 @@ namespace platf::dxgi { pixel |= 0xFF000000; } else { // Other alpha values are illegal in masked color cursors - BOOST_LOG(warning) << "Illegal alpha value in masked color cursor: " << alpha; + logging::warning("Illegal alpha value in masked color cursor: {}", static_cast(alpha)); } }); return cursor_img; @@ -357,7 +357,7 @@ namespace platf::dxgi { // Monochrome cursors are handled below. break; default: - BOOST_LOG(error) << "Invalid cursor shape type: " << shape_info.Type; + logging::error("Invalid cursor shape type: {}", shape_info.Type); return {}; } @@ -420,12 +420,16 @@ namespace platf::dxgi { auto status = D3DCompileFromFile(wFile.c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entrypoint, shader_model, flags, 0, &compiled_p, &msg_p); if (msg_p) { - BOOST_LOG(warning) << std::string_view {(const char *) msg_p->GetBufferPointer(), msg_p->GetBufferSize() - 1}; + logging::warning([&](std::ostream &out) { + out << std::string_view {(const char *) msg_p->GetBufferPointer(), msg_p->GetBufferSize() - 1}; + }); msg_p->Release(); } if (status) { - BOOST_LOG(error) << "Couldn't compile ["sv << file << "] [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error([&](std::ostream &out) { + out << "Couldn't compile ["sv << file << "] [0x"sv << util::hex(status).to_string_view() << ']'; + }); return nullptr; } @@ -465,7 +469,7 @@ namespace platf::dxgi { // 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() << ']'; + logging::error("Failed to acquire encoder mutex [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -527,13 +531,13 @@ namespace platf::dxgi { } if (!color_vectors) { - BOOST_LOG(error) << "No vector data for colorspace"sv; + logging::error("No vector data for colorspace"sv); return; } auto color_matrix = make_buffer(device.get(), *color_vectors); if (!color_matrix) { - BOOST_LOG(warning) << "Failed to create color matrix"sv; + logging::warning("Failed to create color matrix"sv); return; } @@ -560,14 +564,18 @@ namespace platf::dxgi { #ifndef DOXYGEN #define create_vertex_shader_helper(x, y) \ if (FAILED(status = device->CreateVertexShader(x->GetBufferPointer(), x->GetBufferSize(), nullptr, &y))) { \ - BOOST_LOG(error) << "Failed to create vertex shader " << #x << ": " << util::log_hex(status); \ + logging::error([&](std::ostream &out) { \ + out << "Failed to create vertex shader " << #x << ": " << util::log_hex(status); \ + }); \ return -1; \ } #endif #ifndef DOXYGEN #define create_pixel_shader_helper(x, y) \ if (FAILED(status = device->CreatePixelShader(x->GetBufferPointer(), x->GetBufferSize(), nullptr, &y))) { \ - BOOST_LOG(error) << "Failed to create pixel shader " << #x << ": " << util::log_hex(status); \ + logging::error([&](std::ostream &out) { \ + out << "Failed to create pixel shader " << #x << ": " << util::log_hex(status); \ + }); \ return -1; \ } #endif @@ -576,7 +584,7 @@ namespace platf::dxgi { const auto fp16_transfer = select_fp16_transfer(format, display->is_hdr(), display->settings.video.fp16_sdr_gamma_encoded); if (fp16_transfer == fp16_transfer_e::gamma_encoded) { - BOOST_LOG(info) << "Treating FP16 SDR capture as gamma-encoded (fp16_sdr_gamma_encoded)"sv; + logging::info("Treating FP16 SDR capture as gamma-encoded (fp16_sdr_gamma_encoded)"sv); } // Formats without PQ shaders pass their linear shader as perceptual_quantizer, which is never selected for them @@ -646,7 +654,7 @@ namespace platf::dxgi { break; default: - BOOST_LOG(error) << "Unable to create shaders because of the unrecognized surface format"; + logging::error("Unable to create shaders because of the unrecognized surface format"); return -1; } @@ -687,7 +695,7 @@ namespace platf::dxgi { subsample_offset = make_buffer(device.get(), subsample_offset_in); if (!subsample_offset) { - BOOST_LOG(error) << "Failed to create subsample offset vertex constant buffer"; + logging::error("Failed to create subsample offset vertex constant buffer"); return -1; } device_ctx->VSSetConstantBuffers(0, 1, &subsample_offset); @@ -697,7 +705,7 @@ namespace platf::dxgi { std::array rotation_data {-rotation_modifier}; // aligned to 16-byte auto rotation = make_buffer(device.get(), rotation_data); if (!rotation) { - BOOST_LOG(error) << "Failed to create display rotation vertex constant buffer"; + logging::error("Failed to create display rotation vertex constant buffer"); return -1; } device_ctx->VSSetConstantBuffers(1, 1, &rotation); @@ -733,7 +741,7 @@ namespace platf::dxgi { break; default: - BOOST_LOG(error) << "Unable to create render target views because of the unrecognized surface format"; + logging::error("Unable to create render target views because of the unrecognized surface format"); return -1; } @@ -744,7 +752,9 @@ namespace platf::dxgi { auto status = device->CreateRenderTargetView(output_texture.get(), &rtv_desc, &rt); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create render target view: " << util::log_hex(status); + logging::error([&](std::ostream &out) { + out << "Failed to create render target view: " << util::log_hex(status); + }); return false; } @@ -815,7 +825,9 @@ namespace platf::dxgi { break; default: - BOOST_LOG(error) << "D3D11 backend doesn't support pixel format: " << from_pix_fmt(pix_fmt); + logging::error([&](std::ostream &out) { + out << "D3D11 backend doesn't support pixel format: " << from_pix_fmt(pix_fmt); + }); return -1; } @@ -843,31 +855,31 @@ namespace platf::dxgi { ); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create encoder D3D11 device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create encoder D3D11 device [0x{}]", util::hex(status).to_string_view()); return -1; } dxgi::dxgi_t dxgi; status = device->QueryInterface(IID_IDXGIDevice, (void **) &dxgi); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to query DXGI interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::warning("Failed to query DXGI interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } status = dxgi->SetGPUThreadPriority(7); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to increase encoding GPU thread priority. Please run application as administrator for optimal performance."; + logging::warning("Failed to increase encoding GPU thread priority. Please run application as administrator for optimal performance."); } auto default_color_vectors = ::video::color_vectors_from_colorspace({::video::colorspace_e::rec601, false, 8}, true); if (!default_color_vectors) { - BOOST_LOG(error) << "Missing color vectors for Rec. 601"sv; + logging::error("Missing color vectors for Rec. 601"sv); return -1; } color_matrix = make_buffer(device.get(), *default_color_vectors); if (!color_matrix) { - BOOST_LOG(error) << "Failed to create color matrix buffer"sv; + logging::error("Failed to create color matrix buffer"sv); return -1; } device_ctx->VSSetConstantBuffers(3, 1, &color_matrix); @@ -895,7 +907,7 @@ namespace platf::dxgi { status = device->CreateSamplerState(&sampler_desc, &sampler_linear); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create point sampler state [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create point sampler state [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -952,28 +964,28 @@ namespace platf::dxgi { device1_t device1; auto status = device->QueryInterface(__uuidof(ID3D11Device1), (void **) &device1); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query ID3D11Device1 [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query ID3D11Device1 [0x{}]", util::hex(status).to_string_view()); return -1; } // Open a handle to the shared texture status = device1->OpenSharedResource1(img.encoder_texture_handle, __uuidof(ID3D11Texture2D), (void **) &img_ctx.encoder_texture); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to open shared image texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to open shared image texture [0x{}]", util::hex(status).to_string_view()); return -1; } // Get the keyed mutex to synchronize with the capture code status = img_ctx.encoder_texture->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **) &img_ctx.encoder_mutex); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIKeyedMutex [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query IDXGIKeyedMutex [0x{}]", util::hex(status).to_string_view()); return -1; } // Create the SRV for the encoder texture status = device->CreateShaderResourceView(img_ctx.encoder_texture.get(), nullptr, &img_ctx.encoder_input_res); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create shader resource view for encoding [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create shader resource view for encoding [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -1009,14 +1021,18 @@ namespace platf::dxgi { texture2d_t texture; auto status = device->CreateTexture2D(&texture_desc, &texture_data, &texture); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create black texture: " << util::log_hex(status); + logging::error([&](std::ostream &out) { + out << "Failed to create black texture: " << util::log_hex(status); + }); return {}; } shader_res_t resource_view; status = device->CreateShaderResourceView(texture.get(), nullptr, &resource_view); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create black texture resource view: " << util::log_hex(status); + logging::error([&](std::ostream &out) { + out << "Failed to create black texture resource view: " << util::log_hex(status); + }); return {}; } @@ -1134,7 +1150,7 @@ namespace platf::dxgi { auto status = base.device->QueryInterface(IID_ID3D11Multithread, (void **) &mt); if (FAILED(status)) { - BOOST_LOG(warning) << "Failed to query ID3D11Multithread interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::warning("Failed to query ID3D11Multithread interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -1160,7 +1176,9 @@ namespace platf::dxgi { auto err = av_hwframe_get_buffer(hw_frames_ctx, frame, 0); if (err) { std::array err_str {0}; - BOOST_LOG(error) << "Failed to get hwframe buffer: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Failed to get hwframe buffer: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return -1; } } @@ -1175,7 +1193,9 @@ namespace platf::dxgi { auto err = av_hwframe_map(d3d11_frame.get(), frame, AV_HWFRAME_MAP_WRITE | AV_HWFRAME_MAP_OVERWRITE); if (err) { std::array err_str {0}; - BOOST_LOG(error) << "Failed to map D3D11 frame: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Failed to map D3D11 frame: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return -1; } @@ -1305,7 +1325,7 @@ namespace platf::dxgi { texture2d_t texture; auto status = device->CreateTexture2D(&t, &data, &texture); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create mouse texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create mouse texture [0x{}]", util::hex(status).to_string_view()); return false; } @@ -1313,7 +1333,7 @@ namespace platf::dxgi { cursor.input_res.reset(); status = device->CreateShaderResourceView(texture.get(), nullptr, &cursor.input_res); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create cursor shader resource view [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create cursor shader resource view [0x{}]", util::hex(status).to_string_view()); return false; } @@ -1355,7 +1375,7 @@ namespace platf::dxgi { UINT dummy; status = dup.dup->GetFramePointerShape(img_data.size(), std::begin(img_data), &dummy, &shape_info); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to get new pointer shape [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to get new pointer shape [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -1381,7 +1401,7 @@ namespace platf::dxgi { // Get the texture object from this frame status = res->QueryInterface(IID_ID3D11Texture2D, (void **) &src); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't query interface [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't query interface [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } @@ -1391,20 +1411,20 @@ namespace platf::dxgi { // It's possible for our display enumeration to race with mode changes and result in // mismatched image pool and desktop texture sizes. If this happens, just reinit again. if (desc.Width != width_before_rotation || desc.Height != height_before_rotation) { - BOOST_LOG(info) << "Capture size changed ["sv << width << 'x' << height << " -> "sv << desc.Width << 'x' << desc.Height << ']'; + logging::info("Capture size changed [{}x{} -> {}x{}]", width, height, desc.Width, desc.Height); return capture_e::reinit; } // If we don't know the capture format yet, grab it from this texture if (capture_format == DXGI_FORMAT_UNKNOWN) { capture_format = desc.Format; - BOOST_LOG(info) << "Capture format ["sv << dxgi_format_to_string(capture_format) << ']'; + logging::info("Capture format [{}]", dxgi_format_to_string(capture_format)); } // It's also possible for the capture format to change on the fly. If that happens, // reinitialize capture to try format detection again and create new images. if (capture_format != desc.Format) { - BOOST_LOG(info) << "Capture format changed ["sv << dxgi_format_to_string(capture_format) << " -> "sv << dxgi_format_to_string(desc.Format) << ']'; + logging::info("Capture format changed [{} -> {}]", dxgi_format_to_string(capture_format), dxgi_format_to_string(desc.Format)); return capture_e::reinit; } } @@ -1497,7 +1517,7 @@ namespace platf::dxgi { t.BindFlags = 0; status = device->CreateTexture2D(&t, nullptr, &surface); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create frame copy texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create frame copy texture [0x{}]", util::hex(status).to_string_view()); return false; } @@ -1517,7 +1537,7 @@ namespace platf::dxgi { // we must acquire lock before doing anything to it. texture_lock_helper lock_helper(d3d_img->capture_mutex.get()); if (!lock_helper.lock()) { - BOOST_LOG(error) << "Failed to lock capture texture"; + logging::error("Failed to lock capture texture"); return {nullptr, nullptr}; } @@ -1537,7 +1557,7 @@ namespace platf::dxgi { { auto p_surface = std::get_if(&last_frame_variant); if (!p_surface) { - BOOST_LOG(error) << "Logical error at " << __FILE__ << ":" << __LINE__; + logging::error("Logical error at {}:{}", __FILE__, __LINE__); return capture_e::error; } @@ -1565,7 +1585,7 @@ namespace platf::dxgi { { auto p_img = std::get_if>(&last_frame_variant); if (!p_img) { - BOOST_LOG(error) << "Logical error at " << __FILE__ << ":" << __LINE__; + logging::error("Logical error at {}:{}", __FILE__, __LINE__); return capture_e::error; } auto [d3d_img, lock] = get_locked_d3d_img(*p_img); @@ -1655,7 +1675,7 @@ namespace platf::dxgi { { auto p_img = std::get_if>(&last_frame_variant); if (!p_img) { - BOOST_LOG(error) << "Logical error at " << __FILE__ << ":" << __LINE__; + logging::error("Logical error at {}:{}", __FILE__, __LINE__); return capture_e::error; } img_out = *p_img; @@ -1666,11 +1686,11 @@ namespace platf::dxgi { { auto p_surface = std::get_if(&last_frame_variant); if (!p_surface) { - BOOST_LOG(error) << "Logical error at " << __FILE__ << ":" << __LINE__; + logging::error("Logical error at {}:{}", __FILE__, __LINE__); return capture_e::error; } if (!blend_mouse_cursor_flag) { - BOOST_LOG(error) << "Logical error at " << __FILE__ << ":" << __LINE__; + logging::error("Logical error at {}:{}", __FILE__, __LINE__); return capture_e::error; } @@ -1749,13 +1769,13 @@ namespace platf::dxgi { auto status = device->CreateSamplerState(&sampler_desc, &sampler_linear); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create point sampler state [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create point sampler state [0x{}]", util::hex(status).to_string_view()); return -1; } status = device->CreateVertexShader(shaders->cursor_vs_hlsl->GetBufferPointer(), shaders->cursor_vs_hlsl->GetBufferSize(), nullptr, &cursor_vs); if (status) { - BOOST_LOG(error) << "Failed to create scene vertex shader [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create scene vertex shader [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -1764,7 +1784,7 @@ namespace platf::dxgi { std::array rotation_data {rotation_modifier}; // aligned to 16-byte auto rotation = make_buffer(device.get(), rotation_data); if (!rotation) { - BOOST_LOG(error) << "Failed to create display rotation vertex constant buffer"; + logging::error("Failed to create display rotation vertex constant buffer"); return -1; } device_ctx->VSSetConstantBuffers(2, 1, &rotation); @@ -1774,7 +1794,7 @@ namespace platf::dxgi { // This shader will normalize scRGB white levels to a user-defined white level status = device->CreatePixelShader(shaders->cursor_ps_normalize_white_hlsl->GetBufferPointer(), shaders->cursor_ps_normalize_white_hlsl->GetBufferSize(), nullptr, &cursor_ps); if (status) { - BOOST_LOG(error) << "Failed to create cursor blending (normalized white) pixel shader [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create cursor blending (normalized white) pixel shader [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -1784,7 +1804,7 @@ namespace platf::dxgi { std::array white_multiplier_data {300.0f / 80.f}; // aligned to 16-byte auto white_multiplier = make_buffer(device.get(), white_multiplier_data); if (!white_multiplier) { - BOOST_LOG(warning) << "Failed to create cursor blending (normalized white) white multiplier constant buffer"; + logging::warning("Failed to create cursor blending (normalized white) white multiplier constant buffer"); return -1; } @@ -1792,7 +1812,7 @@ namespace platf::dxgi { } else { status = device->CreatePixelShader(shaders->cursor_ps_hlsl->GetBufferPointer(), shaders->cursor_ps_hlsl->GetBufferSize(), nullptr, &cursor_ps); if (status) { - BOOST_LOG(error) << "Failed to create cursor blending pixel shader [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create cursor blending pixel shader [0x{}]", util::hex(status).to_string_view()); return -1; } } @@ -1831,14 +1851,14 @@ namespace platf::dxgi { // It's possible for our display enumeration to race with mode changes and result in // mismatched image pool and desktop texture sizes. If this happens, just reinit again. if (desc.Width != width_before_rotation || desc.Height != height_before_rotation) { - BOOST_LOG(info) << "Capture size changed ["sv << width << 'x' << height << " -> "sv << desc.Width << 'x' << desc.Height << ']'; + logging::info("Capture size changed [{}x{} -> {}x{}]", width, height, desc.Width, desc.Height); return capture_e::reinit; } // It's also possible for the capture format to change on the fly. If that happens, // reinitialize capture to try format detection again and create new images. if (capture_format != desc.Format) { - BOOST_LOG(info) << "Capture format changed ["sv << dxgi_format_to_string(capture_format) << " -> "sv << dxgi_format_to_string(desc.Format) << ']'; + logging::info("Capture format changed [{} -> {}]", dxgi_format_to_string(capture_format), dxgi_format_to_string(desc.Format)); return capture_e::reinit; } @@ -1854,7 +1874,7 @@ namespace platf::dxgi { if (lock_helper.lock()) { device_ctx->CopyResource(d3d_img->capture_texture.get(), src.get()); } else { - BOOST_LOG(error) << "Failed to lock capture texture"; + logging::error("Failed to lock capture texture"); return capture_e::error; } } else { @@ -1903,7 +1923,7 @@ namespace platf::dxgi { // If this is not a dummy image, we must know the format by now if (!dummy && capture_format == DXGI_FORMAT_UNKNOWN) { - BOOST_LOG(error) << "display_vram_t::complete_img() called with unknown capture format!"; + logging::error("display_vram_t::complete_img() called with unknown capture format!"); return -1; } @@ -1936,34 +1956,34 @@ namespace platf::dxgi { 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() << ']'; + logging::error("Failed to create img buf texture [0x{}]", util::hex(status).to_string_view()); return -1; } status = device->CreateRenderTargetView(img->capture_texture.get(), nullptr, &img->capture_rt); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create render target view [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create render target view [0x{}]", util::hex(status).to_string_view()); return -1; } // Get the keyed mutex to synchronize with the encoding code status = img->capture_texture->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **) &img->capture_mutex); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIKeyedMutex [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query IDXGIKeyedMutex [0x{}]", util::hex(status).to_string_view()); return -1; } resource1_t resource; status = img->capture_texture->QueryInterface(__uuidof(IDXGIResource1), (void **) &resource); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to query IDXGIResource1 [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query IDXGIResource1 [0x{}]", util::hex(status).to_string_view()); return -1; } // Create a handle for the encoder device to use to open this texture status = resource->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ, nullptr, &img->encoder_texture_handle); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create shared texture handle [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create shared texture handle [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -2036,33 +2056,25 @@ namespace platf::dxgi { if (config.videoFormat == 2 && version < AMF_MAKE_FULL_VERSION(1, 4, 30, 0)) { // AMF 1.4.30 adds ultra low latency mode for AV1. Don't use AV1 on earlier versions. // This corresponds to driver version 23.5.2 (23.10.01.45) or newer. - BOOST_LOG(warning) << "AV1 encoding is disabled on AMF version "sv - << AMF_GET_MAJOR_VERSION(version) << '.' - << AMF_GET_MINOR_VERSION(version) << '.' - << AMF_GET_SUBMINOR_VERSION(version) << '.' - << AMF_GET_BUILD_VERSION(version); - BOOST_LOG(warning) << "If your AMD GPU supports AV1 encoding, update your graphics drivers!"sv; + logging::warning("AV1 encoding is disabled on AMF version {}.{}.{}.{}", AMF_GET_MAJOR_VERSION(version), AMF_GET_MINOR_VERSION(version), AMF_GET_SUBMINOR_VERSION(version), AMF_GET_BUILD_VERSION(version)); + logging::warning("If your AMD GPU supports AV1 encoding, update your graphics drivers!"sv); return false; } else if (config.dynamicRange && version < AMF_MAKE_FULL_VERSION(1, 4, 23, 0)) { // Older versions of the AMD AMF runtime can crash when fed P010 surfaces. // Fail if AMF version is below 1.4.23 where HEVC Main10 encoding was introduced. // AMF 1.4.23 corresponds to driver version 21.12.1 (21.40.11.03) or newer. - BOOST_LOG(warning) << "HDR encoding is disabled on AMF version "sv - << AMF_GET_MAJOR_VERSION(version) << '.' - << AMF_GET_MINOR_VERSION(version) << '.' - << AMF_GET_SUBMINOR_VERSION(version) << '.' - << AMF_GET_BUILD_VERSION(version); - BOOST_LOG(warning) << "If your AMD GPU supports HEVC Main10 encoding, update your graphics drivers!"sv; + logging::warning("HDR encoding is disabled on AMF version {}.{}.{}.{}", AMF_GET_MAJOR_VERSION(version), AMF_GET_MINOR_VERSION(version), AMF_GET_SUBMINOR_VERSION(version), AMF_GET_BUILD_VERSION(version)); + logging::warning("If your AMD GPU supports HEVC Main10 encoding, update your graphics drivers!"sv); return false; } } else { - BOOST_LOG(warning) << "AMFQueryVersion() failed: "sv << result; + logging::warning("AMFQueryVersion() failed: {}", static_cast(result)); } } else { - BOOST_LOG(warning) << "AMF DLL missing export: "sv << AMF_QUERY_VERSION_FUNCTION_NAME; + logging::warning("AMF DLL missing export: {}", AMF_QUERY_VERSION_FUNCTION_NAME); } } else { - BOOST_LOG(warning) << "Detected AMD GPU but AMF failed to load"sv; + logging::warning("Detected AMD GPU but AMF failed to load"sv); } } else if (adapter_desc.VendorId == 0x8086) { // Intel // If it's not a QSV encoder, it's not compatible with an Intel GPU @@ -2088,7 +2100,7 @@ namespace platf::dxgi { return false; } } else { - BOOST_LOG(warning) << "Unknown GPU vendor ID: " << util::hex(adapter_desc.VendorId).to_string_view(); + logging::warning("Unknown GPU vendor ID: {}", util::hex(adapter_desc.VendorId).to_string_view()); } return true; @@ -2117,7 +2129,7 @@ namespace platf::dxgi { }; } auto shaders = std::make_shared(); - BOOST_LOG(info) << "Compiling shaders..."sv; + logging::info("Compiling shaders..."sv); if (!(shaders->convert_yuv420_packed_uv_type0_ps_hlsl = shader_bytecode_t {compiler(SUNSHINE_SHADERS_DIR "/convert_yuv420_packed_uv_type0_ps.hlsl", "ps_5_0").release()})) { return nullptr; } @@ -2193,7 +2205,7 @@ namespace platf::dxgi { if (!(shaders->cursor_vs_hlsl = shader_bytecode_t {compiler(SUNSHINE_SHADERS_DIR "/cursor_vs.hlsl", "vs_5_0").release()})) { return nullptr; } - BOOST_LOG(info) << "Compiled shaders"sv; + logging::info("Compiled shaders"sv); return shaders; } } // namespace platf::dxgi diff --git a/src/platform/windows/display_wgc.cpp b/src/platform/windows/display_wgc.cpp index b85dbd232..d46597362 100644 --- a/src/platform/windows/display_wgc.cpp +++ b/src/platform/windows/display_wgc.cpp @@ -106,19 +106,19 @@ namespace platf::dxgi { winrt::com_ptr<::IInspectable> d3d_comhandle; try { if (!winrt::GraphicsCaptureSession::IsSupported()) { - BOOST_LOG(error) << "Screen capture is not supported on this device for this release of Windows!"sv; + logging::error("Screen capture is not supported on this device for this release of Windows!"sv); return -1; } if (FAILED(status = display->device->QueryInterface(IID_IDXGIDevice, (void **) &dxgi))) { - BOOST_LOG(error) << "Failed to query DXGI interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query DXGI interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } if (FAILED(status = winrt::CreateDirect3D11DeviceFromDXGIDevice(*&dxgi, d3d_comhandle.put()))) { - BOOST_LOG(error) << "Failed to query WinRT DirectX interface from device [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to query WinRT DirectX interface from device [0x{}]", util::hex(status).to_string_view()); return -1; } } catch (winrt::hresult_error &e) { - BOOST_LOG(error) << "Screen capture is not supported on this device for this release of Windows: failed to acquire device: [0x"sv << util::hex(e.code()).to_string_view() << ']'; + logging::error("Screen capture is not supported on this device for this release of Windows: failed to acquire device: [0x{}]", util::hex(e.code()).to_string_view()); return -1; } @@ -128,7 +128,7 @@ namespace platf::dxgi { auto monitor_factory = winrt::get_activation_factory(); if (monitor_factory == nullptr || FAILED(status = monitor_factory->CreateForMonitor(output_desc.Monitor, winrt::guid_of(), winrt::put_abi(item)))) { - BOOST_LOG(error) << "Screen capture is not supported on this device for this release of Windows: failed to acquire display: [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Screen capture is not supported on this device for this release of Windows: failed to acquire display: [0x{}]", util::hex(status).to_string_view()); return -1; } @@ -143,31 +143,31 @@ namespace platf::dxgi { capture_session = frame_pool.CreateCaptureSession(item); frame_pool.FrameArrived({this, &wgc_capture_t::on_frame_arrived}); } catch (winrt::hresult_error &e) { - BOOST_LOG(error) << "Screen capture is not supported on this device for this release of Windows: failed to create capture session: [0x"sv << util::hex(e.code()).to_string_view() << ']'; + logging::error("Screen capture is not supported on this device for this release of Windows: failed to create capture session: [0x{}]", util::hex(e.code()).to_string_view()); return -1; } try { if (winrt::ApiInformation::IsPropertyPresent(L"Windows.Graphics.Capture.GraphicsCaptureSession", L"IsBorderRequired")) { capture_session.IsBorderRequired(false); } else { - BOOST_LOG(warning) << "Can't disable colored border around capture area on this version of Windows"; + logging::warning("Can't disable colored border around capture area on this version of Windows"); } } catch (winrt::hresult_error &e) { - BOOST_LOG(warning) << "Screen capture may not be fully supported on this device for this release of Windows: failed to disable border around capture area: [0x"sv << util::hex(e.code()).to_string_view() << ']'; + logging::warning("Screen capture may not be fully supported on this device for this release of Windows: failed to disable border around capture area: [0x{}]", util::hex(e.code()).to_string_view()); } try { if (winrt::ApiInformation::IsPropertyPresent(L"Windows.Graphics.Capture.GraphicsCaptureSession", L"MinUpdateInterval")) { capture_session.MinUpdateInterval(4ms); // 250Hz } else { - BOOST_LOG(warning) << "Can't set MinUpdateInterval on this version of Windows"; + logging::warning("Can't set MinUpdateInterval on this version of Windows"); } } catch (winrt::hresult_error &e) { - BOOST_LOG(warning) << "Screen capture may be capped to 60fps on this device for this release of Windows: failed to set MinUpdateInterval: [0x"sv << util::hex(e.code()).to_string_view() << ']'; + logging::warning("Screen capture may be capped to 60fps on this device for this release of Windows: failed to set MinUpdateInterval: [0x{}]", util::hex(e.code()).to_string_view()); } try { capture_session.StartCapture(); } catch (winrt::hresult_error &e) { - BOOST_LOG(error) << "Screen capture is not supported on this device for this release of Windows: failed to start capture: [0x"sv << util::hex(e.code()).to_string_view() << ']'; + logging::error("Screen capture is not supported on this device for this release of Windows: failed to start capture: [0x{}]", util::hex(e.code()).to_string_view()); return -1; } return 0; @@ -183,7 +183,7 @@ namespace platf::dxgi { try { frame = sender.TryGetNextFrame(); } catch (winrt::hresult_error &e) { - BOOST_LOG(warning) << "Failed to capture frame: "sv << e.code(); + logging::warning("Failed to capture frame: {}", static_cast(e.code())); return; } if (frame != nullptr) { @@ -281,7 +281,7 @@ namespace platf::dxgi { // Create the staging texture if it doesn't exist. It should match the source in size and format. if (texture == nullptr) { capture_format = desc.Format; - BOOST_LOG(info) << "Capture format ["sv << dxgi_format_to_string(capture_format) << ']'; + logging::info("Capture format [{}]", dxgi_format_to_string(capture_format)); D3D11_TEXTURE2D_DESC t {}; t.Width = width; @@ -296,7 +296,7 @@ namespace platf::dxgi { auto status = device->CreateTexture2D(&t, nullptr, &texture); if (FAILED(status)) { - BOOST_LOG(error) << "Failed to create staging texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to create staging texture [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } } @@ -304,13 +304,13 @@ namespace platf::dxgi { // It's possible for our display enumeration to race with mode changes and result in // mismatched image pool and desktop texture sizes. If this happens, just reinit again. if (desc.Width != width || desc.Height != height) { - BOOST_LOG(info) << "Capture size changed ["sv << width << 'x' << height << " -> "sv << desc.Width << 'x' << desc.Height << ']'; + logging::info("Capture size changed [{}x{} -> {}x{}]", width, height, desc.Width, desc.Height); return capture_e::reinit; } // It's also possible for the capture format to change on the fly. If that happens, // reinitialize capture to try format detection again and create new images. if (capture_format != desc.Format) { - BOOST_LOG(info) << "Capture format changed ["sv << dxgi_format_to_string(capture_format) << " -> "sv << dxgi_format_to_string(desc.Format) << ']'; + logging::info("Capture format changed [{} -> {}]", dxgi_format_to_string(capture_format), dxgi_format_to_string(desc.Format)); return capture_e::reinit; } @@ -324,7 +324,7 @@ namespace platf::dxgi { // Map the staging texture for CPU access (making it inaccessible for the GPU) if (FAILED(status = device_ctx->Map(texture.get(), 0, D3D11_MAP_READ, 0, &img_info))) { - BOOST_LOG(error) << "Failed to map texture [0x"sv << util::hex(status).to_string_view() << ']'; + logging::error("Failed to map texture [0x{}]", util::hex(status).to_string_view()); return capture_e::error; } diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 9fc99476b..17bd9811c 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -279,7 +279,7 @@ namespace platf { client_t client {vigem_alloc()}; VIGEM_ERROR status = vigem_connect(client.get()); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "ViGEmBus is not installed or running, so its limited Xbox 360 and DualShock 4 gamepad support is unavailable"sv; + logging::warning("ViGEmBus is not installed or running, so its limited Xbox 360 and DualShock 4 gamepad support is unavailable"sv); return -1; } else { vigem_disconnect(client.get()); @@ -306,12 +306,12 @@ namespace platf { // Establish a connect to the ViGEm driver if we don't have one yet if (!client) { - BOOST_LOG(debug) << "Connecting to ViGEmBus driver"sv; + logging::debug("Connecting to ViGEmBus driver"sv); client.reset(vigem_alloc()); auto status = vigem_connect(client.get()); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't setup connection to ViGEm for gamepad support ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't setup connection to ViGEm for gamepad support [{}]", util::hex(status).to_string_view()); client.reset(); return -1; } @@ -340,7 +340,7 @@ namespace platf { auto status = vigem_target_add(client.get(), gamepad.gp.get()); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(error) << "Couldn't add Gamepad to ViGEm connection ["sv << util::hex(status).to_string_view() << ']'; + logging::error("Couldn't add Gamepad to ViGEm connection [{}]", util::hex(status).to_string_view()); return -1; } @@ -354,7 +354,7 @@ namespace platf { } if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't register notifications for rumble support ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't register notifications for rumble support [{}]", util::hex(status).to_string_view()); } return 0; @@ -408,7 +408,7 @@ namespace platf { if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { auto status = vigem_target_remove(client.get(), gamepad.gp.get()); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't detach gamepad from ViGEm ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't detach gamepad from ViGEm [{}]", util::hex(status).to_string_view()); } } @@ -423,7 +423,7 @@ namespace platf { } } if (disconnect) { - BOOST_LOG(debug) << "Disconnecting from ViGEmBus driver"sv; + logging::debug("Disconnecting from ViGEmBus driver"sv); vigem_disconnect(client.get()); client.reset(); } @@ -496,7 +496,7 @@ namespace platf { if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { auto status = vigem_target_remove(client.get(), gamepad.gp.get()); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't detach gamepad from ViGEm ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't detach gamepad from ViGEm [{}]", util::hex(status).to_string_view()); } } } @@ -518,9 +518,10 @@ namespace platf { std::uint8_t /* led_number */, void *userdata ) { - BOOST_LOG(debug) - << "largeMotor: "sv << (int) largeMotor << std::endl - << "smallMotor: "sv << (int) smallMotor; + logging::debug([&](std::ostream &out) { + out << "largeMotor: "sv << (int) largeMotor << std::endl + << "smallMotor: "sv << (int) smallMotor; + }); auto *context = static_cast(userdata); context->defer_feedback([target, largeMotor, smallMotor](vigem_t &context) { @@ -536,12 +537,13 @@ namespace platf { DS4_LIGHTBAR_COLOR led_color, void *userdata ) { - BOOST_LOG(debug) - << "largeMotor: "sv << (int) largeMotor << std::endl - << "smallMotor: "sv << (int) smallMotor << std::endl - << "LED: "sv << util::hex(led_color.Red).to_string_view() << ' ' - << util::hex(led_color.Green).to_string_view() << ' ' - << util::hex(led_color.Blue).to_string_view() << std::endl; + logging::debug([&](std::ostream &out) { + out << "largeMotor: "sv << (int) largeMotor << std::endl + << "smallMotor: "sv << (int) smallMotor << std::endl + << "LED: "sv << util::hex(led_color.Red).to_string_view() << ' ' + << util::hex(led_color.Green).to_string_view() << ' ' + << util::hex(led_color.Blue).to_string_view() << std::endl; + }); auto *context = static_cast(userdata); context->defer_feedback([target, largeMotor, smallMotor, led_color](vigem_t &context) { @@ -607,9 +609,9 @@ namespace platf { if (auto &raw = *result; settings.input.controller && !should_use_virtualhid_gamepads(raw) && virtualhid::should_try_vigembus_fallback(settings.input.gamepad, false, settings.input.gamepad_driver)) { if (settings.input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { - BOOST_LOG(info) << "ViGEmBus is selected as the only virtual gamepad driver"sv; + logging::info("ViGEmBus is selected as the only virtual gamepad driver"sv); } else if (raw.virtualhid.runtime && raw.virtualhid.runtime->capabilities().supports_gamepad) { - BOOST_LOG(info) << "Virtual HID Driver license is not valid; using the ViGEmBus gamepad fallback"sv; + logging::info("Virtual HID Driver license is not valid; using the ViGEmBus gamepad fallback"sv); } auto vigem = std::make_shared(scheduler); if (!vigem->init()) { @@ -651,16 +653,15 @@ namespace platf { bool should_allocate_vigembus_gamepad(const config::settings_t &settings, std::string_view driver, const bool virtualhid_selected) { if (!virtualhid::should_try_vigembus_fallback(settings.input.gamepad, virtualhid_selected, driver)) { if (driver == config::GAMEPAD_DRIVER_VIRTUALHID && !virtualhid_selected) { - BOOST_LOG(warning) << "Virtual HID Driver is selected but is unavailable or unlicensed; ViGEmBus fallback is disabled by configuration"sv; + logging::warning("Virtual HID Driver is selected but is unavailable or unlicensed; ViGEmBus fallback is disabled by configuration"sv); } else { - BOOST_LOG(warning) << "libvirtualhid could not create the requested gamepad profile, and ViGEm fallback cannot emulate "sv << settings.input.gamepad; + logging::warning("libvirtualhid could not create the requested gamepad profile, and ViGEm fallback cannot emulate {}", settings.input.gamepad); } return false; } if (!virtualhid_selected && !virtualhid::should_try_vigembus_fallback(settings.input.gamepad, true, driver)) { - BOOST_LOG(warning) << "Configured gamepad profile '"sv << settings.input.gamepad - << "' is unavailable; using ViGEmBus automatic selection because Virtual HID Driver is not usable"sv; + logging::warning("Configured gamepad profile '{}' is unavailable; using ViGEmBus automatic selection because Virtual HID Driver is not usable", settings.input.gamepad); } return true; } @@ -739,44 +740,44 @@ namespace platf { VIGEM_TARGET_TYPE selectedGamepadType; if (settings.input.gamepad == "x360"sv) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox 360 controller (manual selection)"sv; + logging::info("Gamepad {} will be Xbox 360 controller (manual selection)", id.globalIndex); selectedGamepadType = Xbox360Wired; } else if (settings.input.gamepad == "ds4"sv) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (manual selection)"sv; + logging::info("Gamepad {} will be DualShock 4 controller (manual selection)", id.globalIndex); selectedGamepadType = DualShock4Wired; } else if (metadata.type == LI_CTYPE_PS) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (auto-selected by client-reported type)"sv; + logging::info("Gamepad {} will be DualShock 4 controller (auto-selected by client-reported type)", id.globalIndex); selectedGamepadType = DualShock4Wired; } else if (metadata.type == LI_CTYPE_XBOX) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox 360 controller (auto-selected by client-reported type)"sv; + logging::info("Gamepad {} will be Xbox 360 controller (auto-selected by client-reported type)", id.globalIndex); selectedGamepadType = Xbox360Wired; } else if (settings.input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (auto-selected by motion sensor presence)"sv; + logging::info("Gamepad {} will be DualShock 4 controller (auto-selected by motion sensor presence)", id.globalIndex); selectedGamepadType = DualShock4Wired; } else if (settings.input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualShock 4 controller (auto-selected by touchpad presence)"sv; + logging::info("Gamepad {} will be DualShock 4 controller (auto-selected by touchpad presence)", id.globalIndex); selectedGamepadType = DualShock4Wired; } else { - BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox 360 controller (default)"sv; + logging::info("Gamepad {} will be Xbox 360 controller (default)", id.globalIndex); selectedGamepadType = Xbox360Wired; } if (selectedGamepadType == Xbox360Wired) { if (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO)) { - BOOST_LOG(warning) << "Gamepad " << id.globalIndex << " has motion sensors, but they are not usable when emulating an Xbox 360 controller"sv; + logging::warning("Gamepad {} has motion sensors, but they are not usable when emulating an Xbox 360 controller", id.globalIndex); } if (metadata.capabilities & LI_CCAP_TOUCHPAD) { - BOOST_LOG(warning) << "Gamepad " << id.globalIndex << " has a touchpad, but it is not usable when emulating an Xbox 360 controller"sv; + logging::warning("Gamepad {} has a touchpad, but it is not usable when emulating an Xbox 360 controller", id.globalIndex); } if (metadata.capabilities & LI_CCAP_RGB_LED) { - BOOST_LOG(warning) << "Gamepad " << id.globalIndex << " has an RGB LED, but it is not usable when emulating an Xbox 360 controller"sv; + logging::warning("Gamepad {} has an RGB LED, but it is not usable when emulating an Xbox 360 controller", id.globalIndex); } } else if (selectedGamepadType == DualShock4Wired) { if (!(metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) { - BOOST_LOG(warning) << "Gamepad " << id.globalIndex << " is emulating a DualShock 4 controller, but the client gamepad doesn't have motion sensors active"sv; + logging::warning("Gamepad {} is emulating a DualShock 4 controller, but the client gamepad doesn't have motion sensors active", id.globalIndex); } if (!(metadata.capabilities & LI_CCAP_TOUCHPAD)) { - BOOST_LOG(warning) << "Gamepad " << id.globalIndex << " is emulating a DualShock 4 controller, but the client gamepad doesn't have a touchpad"sv; + logging::warning("Gamepad {} is emulating a DualShock 4 controller, but the client gamepad doesn't have a touchpad", id.globalIndex); } } @@ -1053,7 +1054,7 @@ namespace platf { // Send the report to the virtual device auto status = vigem_target_ds4_update_ex(vigem->client.get(), gamepad.gp.get(), gamepad.report.ds4); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't send gamepad input to ViGEm ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't send gamepad input to ViGEm [{}]", util::hex(status).to_string_view()); return; } @@ -1100,7 +1101,7 @@ namespace platf { x360_update_state(gamepad, gamepad_state); status = vigem_target_x360_update(vigem->client.get(), gamepad.gp.get(), gamepad.report.x360); if (!VIGEM_SUCCESS(status)) { - BOOST_LOG(warning) << "Couldn't send gamepad input to ViGEm ["sv << util::hex(status).to_string_view() << ']'; + logging::warning("Couldn't send gamepad input to ViGEm [{}]", util::hex(status).to_string_view()); } } else { ds4_update_state(raw->virtualhid.settings.get(), gamepad, gamepad_state); @@ -1158,7 +1159,7 @@ namespace platf { report.sCurrentTouch.bIsUpTrackingNum2 &= ~0x80; report.sCurrentTouch.bIsUpTrackingNum2++; } else { - BOOST_LOG(warning) << "No more free pointer indices! Did the client miss an touch up event?"sv; + logging::warning("No more free pointer indices! Did the client miss an touch up event?"sv); return; } } else if (touch.eventType == LI_TOUCH_EVENT_CANCEL_ALL) { @@ -1174,7 +1175,7 @@ namespace platf { } else { auto i = gamepad.pointer_id_map.find(touch.pointerId); if (i == gamepad.pointer_id_map.end()) { - BOOST_LOG(warning) << "Pointer ID not found! Did the client miss a touch down event?"sv; + logging::warning("Pointer ID not found! Did the client miss a touch down event?"sv); return; } @@ -1194,7 +1195,7 @@ namespace platf { // Free the pointer index gamepad.available_pointers |= (1 << pointerIndex); } else if (touch.eventType != LI_TOUCH_EVENT_MOVE) { - BOOST_LOG(warning) << "Unsupported touch event for gamepad: "sv << (uint32_t) touch.eventType; + logging::warning("Unsupported touch event for gamepad: {}", (uint32_t) touch.eventType); return; } } @@ -1398,7 +1399,7 @@ namespace platf { caps |= platform_caps::pen_touch; } } else { - BOOST_LOG(warning) << "Unable to create libvirtualhid runtime for touch/pen capability detection"sv; + logging::warning("Unable to create libvirtualhid runtime for touch/pen capability detection"sv); } } diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index c08dc4913..4e8e7cea4 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -259,7 +259,7 @@ namespace platf { } } } - BOOST_LOG(warning) << "Unable to find MAC address for "sv << address; + logging::warning("Unable to find MAC address for {}", address); return "00:00:00:00:00:00"s; } @@ -271,14 +271,14 @@ namespace platf { auto hDesk = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, GENERIC_ALL); if (!hDesk) { auto err = GetLastError(); - BOOST_LOG(error) << "Failed to Open Input Desktop [0x"sv << util::hex(err).to_string_view() << ']'; + logging::error("Failed to Open Input Desktop [0x{}]", util::hex(err).to_string_view()); return nullptr; } if (!SetThreadDesktop(hDesk)) { auto err = GetLastError(); - BOOST_LOG(error) << "Failed to sync desktop to thread [0x"sv << util::hex(err).to_string_view() << ']'; + logging::error("Failed to sync desktop to thread [0x{}]", util::hex(err).to_string_view()); } CloseDesktop(hDesk); @@ -294,7 +294,7 @@ namespace platf { DWORD bytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, status, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_string.data(), err_string.size(), nullptr); - BOOST_LOG(error) << prefix << ": "sv << std::string_view {err_string.data(), bytes}; + logging::error("{}: {}", prefix, std::string_view {err_string.data(), bytes}); } /** @@ -323,11 +323,15 @@ namespace platf { if (ret) { if (!CheckTokenMembership(user_token, AdministratorsGroup, &ret)) { ret = false; - BOOST_LOG(error) << "Failed to verify token membership for administrative access: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Failed to verify token membership for administrative access: " << GetLastError(); + }); } FreeSid(AdministratorsGroup); } else { - BOOST_LOG(error) << "Unable to allocate SID to check administrative access: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Unable to allocate SID to check administrative access: " << GetLastError(); + }); } return ret; @@ -349,13 +353,13 @@ namespace platf { consoleSessionId = WTSGetActiveConsoleSessionId(); if (0xFFFFFFFF == consoleSessionId) { // If there is no active console session, log a warning and return null - BOOST_LOG(warning) << "There isn't an active user session, therefore it is not possible to execute commands under the users profile."; + logging::warning("There isn't an active user session, therefore it is not possible to execute commands under the users profile."); return nullptr; } // Get the user token for the active console session if (!WTSQueryUserToken(consoleSessionId, &userToken)) { - BOOST_LOG(debug) << "QueryUserToken failed, this would prevent commands from launching under the users profile."; + logging::debug("QueryUserToken failed, this would prevent commands from launching under the users profile."); return nullptr; } @@ -365,7 +369,9 @@ namespace platf { // Elevation - Limited: User is an admin, has UAC enabled. // Elevation - Full: User is an admin, has UAC disabled. if (!GetTokenInformation(userToken, TokenElevationType, &elevationType, sizeof(TOKEN_ELEVATION_TYPE), &dwSize)) { - BOOST_LOG(debug) << "Retrieving token information failed: " << GetLastError(); + logging::debug([&](std::ostream &out) { + out << "Retrieving token information failed: " << GetLastError(); + }); CloseHandle(userToken); return nullptr; } @@ -374,8 +380,7 @@ namespace platf { // The documentation for this scenario is conflicting, so we'll double check to see if user is actually an admin. if (elevated && (elevationType == TokenElevationTypeDefault && !IsUserAdmin(userToken))) { // We don't have to strip the token or do anything here, but let's give the user a warning so they're aware what is happening. - BOOST_LOG(warning) << "This command requires elevation and the current user account logged in does not have administrator rights. " - << "For security reasons Sunshine will retain the same access level as the current user and will not elevate it."; + logging::warning("This command requires elevation and the current user account logged in does not have administrator rights. For security reasons Sunshine will retain the same access level as the current user and will not elevate it."); } // User has a limited token, this means they have UAC enabled and is an Administrator @@ -384,7 +389,9 @@ namespace platf { // Retrieve the administrator token that is linked to the limited token if (!GetTokenInformation(userToken, TokenLinkedToken, reinterpret_cast(&linkedToken), sizeof(TOKEN_LINKED_TOKEN), &dwSize)) { // If the retrieval failed, log an error message and return null - BOOST_LOG(error) << "Retrieving linked token information failed: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Retrieving linked token information failed: " << GetLastError(); + }); CloseHandle(userToken); // There is no scenario where this should be hit, except for an actual error. @@ -455,7 +462,9 @@ namespace platf { // Allocate memory for the SID structure SystemSid = LocalAlloc(LMEM_FIXED, dwSize); if (SystemSid == nullptr) { - BOOST_LOG(error) << "Failed to allocate memory for the SID structure: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Failed to allocate memory for the SID structure: " << GetLastError(); + }); return false; } @@ -464,11 +473,15 @@ namespace platf { if (ret) { // Check if the current process token contains this SID if (!CheckTokenMembership(nullptr, SystemSid, &ret)) { - BOOST_LOG(error) << "Failed to check token membership: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Failed to check token membership: " << GetLastError(); + }); ret = false; } } else { - BOOST_LOG(error) << "Failed to create a SID for the local system account. This may happen if the system is out of memory or if the SID buffer is too small: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Failed to create a SID for the local system account. This may happen if the system is out of memory or if the SID buffer is too small: " << GetLastError(); + }); } // Free the memory allocated for the SID structure @@ -585,11 +598,11 @@ namespace platf { if (process_launched) { // If the launch was successful, create a new bp::child object representing the new process auto child = bp::child((bp::pid_t) process_info.dwProcessId); - BOOST_LOG(info) << cmd << " running with PID "sv << child.id(); + logging::info("{} running with PID {}", cmd, child.id()); return child; } else { auto winerror = GetLastError(); - BOOST_LOG(error) << "Failed to launch process: "sv << winerror; + logging::error("Failed to launch process: {}", winerror); ec = std::make_error_code(std::errc::invalid_argument); // We must NOT attach the failed process here, since this case can potentially be induced by ACL // manipulation (denying yourself execute permission) to cause an escalation of privilege. @@ -613,7 +626,7 @@ namespace platf { if (!ImpersonateLoggedOnUser(user_token)) { auto winerror = GetLastError(); // Log the failure of impersonating the user and its error code - BOOST_LOG(error) << "Failed to impersonate user: "sv << winerror; + logging::error("Failed to impersonate user: {}", winerror); ec = std::make_error_code(std::errc::permission_denied); return ec; } @@ -627,7 +640,7 @@ namespace platf { if (!RevertToSelf()) { 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; + logging::fatal("Failed to revert to self after impersonation: {}", winerror); DebugBreak(); } @@ -693,7 +706,7 @@ namespace platf { if (token) { auto err = RegOpenUserClassesRoot(token, 0, GENERIC_ALL, &user_classes_root); if (err != ERROR_SUCCESS) { - BOOST_LOG(error) << "Failed to open classes root for target user: "sv << err; + logging::error("Failed to open classes root for target user: {}", err); return false; } } @@ -709,7 +722,7 @@ namespace platf { // RegOpenCurrentUser() doesn't take a token. It assumes we're impersonating the desired user. auto err = RegOpenCurrentUser(GENERIC_ALL, &user_key); if (err != ERROR_SUCCESS) { - BOOST_LOG(error) << "Failed to open user key for target user: "sv << err; + logging::error("Failed to open user key for target user: {}", err); user_key = nullptr; } }); @@ -725,13 +738,13 @@ namespace platf { auto err = RegOverridePredefKey(HKEY_CLASSES_ROOT, user_classes_root); if (err != ERROR_SUCCESS) { - BOOST_LOG(error) << "Failed to override HKEY_CLASSES_ROOT: "sv << err; + logging::error("Failed to override HKEY_CLASSES_ROOT: {}", err); return false; } err = RegOverridePredefKey(HKEY_CURRENT_USER, user_key); if (err != ERROR_SUCCESS) { - BOOST_LOG(error) << "Failed to override HKEY_CURRENT_USER: "sv << err; + logging::error("Failed to override HKEY_CURRENT_USER: {}", err); RegOverridePredefKey(HKEY_CLASSES_ROOT, nullptr); return false; } @@ -812,7 +825,7 @@ namespace platf { 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; + logging::warning("Failed to split command string: {}", raw_cmd); return utf_utils::from_utf8(raw_cmd); } @@ -826,7 +839,9 @@ namespace platf { DWORD out_len = scheme.size(); 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() << ']'; + logging::warning([&](std::ostream &out) { + out << "Failed to extract URL scheme from URL: "sv << utf_utils::to_utf8(raw_target) << " ["sv << util::hex(res).to_string_view() << ']'; + }); return utf_utils::from_utf8(raw_cmd); } @@ -875,7 +890,7 @@ 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; + logging::warning("Using trampoline to handle target: {}", raw_cmd); std::wcscpy(shell_command_string.data(), L"cmd.exe /c start \"\" /wait \"%1\" %*"); needs_cmd_escaping = true; @@ -891,7 +906,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() << ']'; + logging::warning("Failed to query command string for raw command: {} [{}]", raw_cmd, util::hex(res).to_string_view()); return utf_utils::from_utf8(raw_cmd); } @@ -995,7 +1010,7 @@ namespace platf { break; default: - BOOST_LOG(warning) << "Unsupported argument replacement: %%" << next_char; + logging::warning("Unsupported argument replacement: %%{}", next_char); break; } @@ -1006,7 +1021,9 @@ namespace platf { match_pos += match_replacement.size(); } - BOOST_LOG(info) << "Resolved user-provided command '"sv << raw_cmd << "' to '"sv << cmd_string << '\''; + logging::info([&](std::ostream &out) { + out << "Resolved user-provided command '"sv << raw_cmd << "' to '"sv << utf_utils::to_utf8(cmd_string) << '\''; + }); return cmd_string; } @@ -1144,9 +1161,11 @@ namespace platf { auto child = run_command(false, false, url, working_dir, _env, nullptr, ec, nullptr); if (ec) { - BOOST_LOG(warning) << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); + }); } else { - BOOST_LOG(info) << "Opened url ["sv << url << "]"sv; + logging::info("Opened url [{}]", url); child.detach(); } } @@ -1172,13 +1191,13 @@ namespace platf { win32_priority = THREAD_PRIORITY_HIGHEST; break; default: - BOOST_LOG(error) << "Unknown thread priority: "sv << (int) priority; + logging::error("Unknown thread priority: {}", (int) priority); return; } if (!SetThreadPriority(GetCurrentThread(), win32_priority)) { auto winerr = GetLastError(); - BOOST_LOG(warning) << "Unable to set thread priority to "sv << win32_priority << ": "sv << winerr; + logging::warning("Unable to set thread priority to {}: {}", win32_priority, winerr); } } @@ -1186,7 +1205,7 @@ namespace platf { std::wstring wname = utf_utils::from_utf8(std::string {name}); HRESULT hr = SetThreadDescription(GetCurrentThread(), wname.c_str()); if (FAILED(hr)) { - BOOST_LOG(error) << "SetThreadDescription failed: " << hr; + logging::error("SetThreadDescription failed: {}", hr); } } @@ -1206,7 +1225,7 @@ namespace platf { if (nt_set_timer_resolution_max()) { used_nt_set_timer_resolution = true; } else { - BOOST_LOG(error) << "NtSetTimerResolution() failed, falling back to timeBeginPeriod()"; + logging::error("NtSetTimerResolution() failed, falling back to timeBeginPeriod()"); timeBeginPeriod(1); used_nt_set_timer_resolution = false; } @@ -1242,7 +1261,7 @@ namespace platf { BOOL value = TRUE; auto error = wlan->set(wlan_handle, &wlan_interface_list->InterfaceInfo[i].InterfaceGuid, wlan_intf_opcode_media_streaming_mode, sizeof(value), &value, nullptr); if (error == ERROR_SUCCESS) { - BOOST_LOG(info) << "WLAN interface "sv << i << " is now in low latency mode"sv; + logging::info("WLAN interface {} is now in low latency mode", i); } } } @@ -1263,7 +1282,7 @@ namespace platf { } // If there is no mouse connected, enable Mouse Keys to force the cursor to appear if (!GetSystemMetrics(SM_MOUSEPRESENT)) { - BOOST_LOG(info) << "A mouse was not detected. Sunshine will enable Mouse Keys while streaming to force the mouse cursor to appear."; + logging::info("A mouse was not detected. Sunshine will enable Mouse Keys while streaming to force the mouse cursor to appear."); // Get the current state of Mouse Keys so we can restore it when streaming is over previous_mouse_keys_state.cbSize = sizeof(previous_mouse_keys_state); @@ -1280,11 +1299,11 @@ namespace platf { enabled_mouse_keys = true; } else { auto winerr = GetLastError(); - BOOST_LOG(warning) << "Unable to enable Mouse Keys: "sv << winerr; + logging::warning("Unable to enable Mouse Keys: {}", winerr); } } else { auto winerr = GetLastError(); - BOOST_LOG(warning) << "Unable to get current state of Mouse Keys: "sv << winerr; + logging::warning("Unable to get current state of Mouse Keys: {}", winerr); } } } @@ -1301,7 +1320,7 @@ namespace platf { if (used_nt_set_timer_resolution) { used_nt_set_timer_resolution = false; if (!nt_set_timer_resolution_min()) { - BOOST_LOG(error) << "nt_set_timer_resolution_min() failed even though nt_set_timer_resolution_max() succeeded"; + logging::error("nt_set_timer_resolution_min() failed even though nt_set_timer_resolution_max() succeeded"); } } else { timeEndPeriod(1); @@ -1321,7 +1340,7 @@ namespace platf { enabled_mouse_keys = false; if (!SystemParametersInfoW(SPI_SETMOUSEKEYS, 0, &previous_mouse_keys_state, 0)) { auto winerr = GetLastError(); - BOOST_LOG(warning) << "Unable to restore original state of Mouse Keys: "sv << winerr; + logging::warning("Unable to restore original state of Mouse Keys: {}", winerr); } } } @@ -1336,14 +1355,14 @@ namespace platf { std::array executable; if (GetModuleFileNameW(nullptr, executable.data(), executable.size()) == 0) { auto winerr = GetLastError(); - BOOST_LOG(fatal) << "Failed to get Sunshine path: "sv << winerr; + logging::fatal("Failed to get Sunshine path: {}", winerr); return; } PROCESS_INFORMATION process_info; if (!CreateProcessW(executable.data(), GetCommandLineW(), nullptr, nullptr, false, CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, (LPSTARTUPINFOW) &startup_info, &process_info)) { auto winerr = GetLastError(); - BOOST_LOG(fatal) << "Unable to restart Sunshine: "sv << winerr; + logging::fatal("Unable to restart Sunshine: {}", winerr); return; } @@ -1385,11 +1404,11 @@ namespace platf { if (enum_ctx->process_ids.find(wnd_process_id) != enum_ctx->process_ids.end()) { // Send an async WM_CLOSE message to this window if (SendNotifyMessageW(hwnd, WM_CLOSE, 0, 0)) { - BOOST_LOG(debug) << "Sent WM_CLOSE to PID: "sv << wnd_process_id; + logging::debug("Sent WM_CLOSE to PID: {}", wnd_process_id); enum_ctx->requested_exit = true; } else { auto error = GetLastError(); - BOOST_LOG(warning) << "Failed to send WM_CLOSE to PID ["sv << wnd_process_id << "]: " << error; + logging::warning("Failed to send WM_CLOSE to PID [{}]: {}", wnd_process_id, error); } } @@ -1418,7 +1437,7 @@ namespace platf { if (!success) { auto err = GetLastError(); - BOOST_LOG(warning) << "Failed to enumerate processes in group: "sv << err; + logging::warning("Failed to enumerate processes in group: {}", err); return false; } else if (process_id_list->NumberOfProcessIdsInList == 0) { // If all processes are already dead, treat it as a success @@ -1443,7 +1462,7 @@ namespace platf { if (!QueryInformationJobObject((HANDLE) native_handle, JobObjectBasicAccountingInformation, &accounting_info, sizeof(accounting_info), nullptr)) { auto err = GetLastError(); - BOOST_LOG(error) << "Failed to get job accounting info: "sv << err; + logging::error("Failed to get job accounting info: {}", err); return false; } @@ -1636,7 +1655,7 @@ namespace platf { DWORD bytes_sent; if (WSASendMsg((SOCKET) send_info.native_socket, &msg, 0, &bytes_sent, nullptr, nullptr) == SOCKET_ERROR) { auto winerr = WSAGetLastError(); - BOOST_LOG(warning) << "WSASendMsg() failed: "sv << winerr; + logging::warning("WSASendMsg() failed: {}", winerr); return false; } @@ -1662,7 +1681,7 @@ namespace platf { virtual ~qos_t() { if (!api->remove(api->handle, (SOCKET) nullptr, flow_id, 0)) { auto winerr = GetLastError(); - BOOST_LOG(warning) << "QOSRemoveSocketFromFlow() failed: "sv << winerr; + logging::warning("QOSRemoveSocketFromFlow() failed: {}", winerr); } } @@ -1703,7 +1722,7 @@ namespace platf { empty.sin6_family = AF_INET6; if (connect((SOCKET) native_socket, (PSOCKADDR) &empty, sizeof(empty)) < 0) { auto wsaerr = WSAGetLastError(); - BOOST_LOG(error) << "qWAVE dual-stack workaround failed: "sv << wsaerr; + logging::error("qWAVE dual-stack workaround failed: {}", wsaerr); } } }); @@ -1723,9 +1742,9 @@ namespace platf { if (address_v6.is_v4_mapped()) { if (connect((SOCKET) native_socket, (PSOCKADDR) &saddr_v6, sizeof(saddr_v6)) < 0) { auto wsaerr = WSAGetLastError(); - BOOST_LOG(error) << "qWAVE dual-stack workaround failed: "sv << wsaerr; + logging::error("qWAVE dual-stack workaround failed: {}", wsaerr); } else { - BOOST_LOG(debug) << "Using qWAVE connect() workaround for QoS tagging"sv; + logging::debug("Using qWAVE connect() workaround for QoS tagging"sv); using_connect_hack = true; dest_addr = nullptr; } @@ -1744,14 +1763,14 @@ namespace platf { traffic_type = QOSTrafficTypeAudioVideo; break; default: - BOOST_LOG(error) << "Unknown traffic type: "sv << (int) data_type; + logging::error("Unknown traffic type: {}", (int) data_type); return nullptr; } QOS_FLOWID flow_id = 0; if (!api->add(api->handle, (SOCKET) native_socket, dest_addr, traffic_type, QOS_NON_ADAPTIVE_FLOW, &flow_id)) { auto winerr = GetLastError(); - BOOST_LOG(warning) << "QOSAddSocketToFlow() failed: "sv << winerr; + logging::warning("QOSAddSocketToFlow() failed: {}", winerr); return nullptr; } @@ -1791,7 +1810,9 @@ namespace platf { std::string get_host_name() { std::array hostname; if (GetHostNameW(hostname.data(), hostname.size()) == SOCKET_ERROR) { - BOOST_LOG(error) << "GetHostNameW() failed: "sv << WSAGetLastError(); + logging::error([&](std::ostream &out) { + out << "GetHostNameW() failed: "sv << WSAGetLastError(); + }); return "Sunshine"s; } return utf_utils::to_utf8(hostname.data()); @@ -1808,7 +1829,9 @@ namespace platf { if (!timer) { timer = CreateWaitableTimerEx(nullptr, nullptr, 0, TIMER_ALL_ACCESS); if (!timer) { - BOOST_LOG(error) << "Unable to create high_precision_timer, CreateWaitableTimerEx() failed: " << GetLastError(); + logging::error([&](std::ostream &out) { + out << "Unable to create high_precision_timer, CreateWaitableTimerEx() failed: " << GetLastError(); + }); } } } @@ -1821,15 +1844,15 @@ namespace platf { void sleep_for(const std::chrono::nanoseconds &duration) override { if (!timer) { - BOOST_LOG(error) << "Attempting high_precision_timer::sleep_for() with uninitialized timer"; + logging::error("Attempting high_precision_timer::sleep_for() with uninitialized timer"); return; } if (duration < 0s) { - BOOST_LOG(error) << "Attempting high_precision_timer::sleep_for() with negative duration"; + logging::error("Attempting high_precision_timer::sleep_for() with negative duration"); return; } if (duration > 5s) { - BOOST_LOG(error) << "Attempting high_precision_timer::sleep_for() with unexpectedly large duration (>5s)"; + logging::error("Attempting high_precision_timer::sleep_for() with unexpectedly large duration (>5s)"); return; } diff --git a/src/platform/windows/nvprefs/nvprefs_common.cpp b/src/platform/windows/nvprefs/nvprefs_common.cpp index 8b73b50d6..51e238bd6 100644 --- a/src/platform/windows/nvprefs/nvprefs_common.cpp +++ b/src/platform/windows/nvprefs/nvprefs_common.cpp @@ -8,6 +8,7 @@ // local includes #include "src/config.h" #include "src/logging.h" +#include "src/platform/windows/utf_utils.h" namespace nvprefs { @@ -15,28 +16,32 @@ namespace nvprefs { * @brief Forward an informational NVPrefs message to the logger. */ void info_message(const std::wstring &message) { - BOOST_LOG(info) << "nvprefs: " << message; + logging::info([&](std::ostream &out) { + out << "nvprefs: " << utf_utils::to_utf8(message); + }); } /** * @brief Forward an informational NVPrefs message to the logger. */ void info_message(const std::string &message) { - BOOST_LOG(info) << "nvprefs: " << message; + logging::info("nvprefs: {}", message); } /** * @brief Forward an NVPrefs error message to the logger. */ void error_message(const std::wstring &message) { - BOOST_LOG(error) << "nvprefs: " << message; + logging::error([&](std::ostream &out) { + out << "nvprefs: " << utf_utils::to_utf8(message); + }); } /** * @brief Forward an NVPrefs error message to the logger. */ void error_message(const std::string &message) { - BOOST_LOG(error) << "nvprefs: " << message; + logging::error("nvprefs: {}", message); } /** diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index bccbe7ca4..eb9000edc 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -235,21 +235,21 @@ namespace platf::publish { port(net::map_port(settings, nvhttp::PORT_HTTP)), existing_instance(nullptr) { if (service(port, true, existing_instance)) { - BOOST_LOG(error) << "Unable to register Sunshine mDNS service"sv; + logging::error("Unable to register Sunshine mDNS service"sv); return; } - BOOST_LOG(info) << "Registered Sunshine mDNS service"sv; + logging::info("Registered Sunshine mDNS service"sv); } ~mdns_registration_t() override { if (existing_instance) { if (service(port, false, existing_instance)) { - BOOST_LOG(error) << "Unable to unregister Sunshine mDNS service"sv; + logging::error("Unable to unregister Sunshine mDNS service"sv); return; } - BOOST_LOG(info) << "Unregistered Sunshine mDNS service"sv; + logging::info("Unregistered Sunshine mDNS service"sv); } } @@ -274,7 +274,7 @@ namespace platf::publish { _DnsServiceRegister = (_DnsServiceRegister_fn) GetProcAddress(handle, "DnsServiceRegister"); if (!(_DnsServiceFreeInstance && _DnsServiceDeRegister && _DnsServiceRegister)) { - BOOST_LOG(error) << "mDNS service not available in dnsapi.dll"sv; + logging::error("mDNS service not available in dnsapi.dll"sv); return -1; } @@ -290,7 +290,7 @@ namespace platf::publish { HMODULE handle = LoadLibrary("dnsapi.dll"); if (!handle || load_funcs(handle)) { - BOOST_LOG(error) << "Couldn't load dnsapi.dll, You'll need to add PC manually from Moonlight"sv; + logging::error("Couldn't load dnsapi.dll, You'll need to add PC manually from Moonlight"sv); return nullptr; } diff --git a/src/platform/windows/utf_utils.cpp b/src/platform/windows/utf_utils.cpp index 45635ad07..99be89c22 100644 --- a/src/platform/windows/utf_utils.cpp +++ b/src/platform/windows/utf_utils.cpp @@ -22,7 +22,7 @@ namespace utf_utils { 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; + logging::error("Failed to get UTF-16 buffer size: {}", winerr); return {}; } @@ -31,7 +31,7 @@ namespace utf_utils { 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; + logging::error("Failed to convert string to UTF-16: {}", winerr); return {}; } @@ -48,7 +48,7 @@ namespace utf_utils { 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; + logging::error("Failed to get UTF-8 buffer size: {}", winerr); return {}; } @@ -57,7 +57,7 @@ namespace utf_utils { 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; + logging::error("Failed to convert string to UTF-8: {}", winerr); return {}; } diff --git a/src/process.cpp b/src/process.cpp index e7a6a1882..e7e7433be 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -7,6 +7,7 @@ // standard includes #include #include +#include #include #include #include @@ -91,7 +92,7 @@ namespace proc { // Request processes in the group to exit gracefully if (platf::request_process_group_exit((std::uintptr_t) group.native_handle())) { // If the request was successful, wait for a little while for them to exit. - BOOST_LOG(info) << "Successfully requested the app to exit. Waiting up to "sv << exit_timeout.count() << " seconds for it to close."sv; + logging::info("Successfully requested the app to exit. Waiting up to {} seconds for it to close.", exit_timeout.count()); // group::wait_for() and similar functions are broken and deprecated, so we use a simple polling loop while (platf::process_group_running((std::uintptr_t) group.native_handle()) && (--exit_timeout).count() >= 0) { @@ -99,15 +100,15 @@ namespace proc { } if (exit_timeout.count() < 0) { - BOOST_LOG(warning) << "App did not fully exit within the timeout. Terminating the app's remaining processes."sv; + logging::warning("App did not fully exit within the timeout. Terminating the app's remaining processes."sv); } else { - BOOST_LOG(info) << "All app processes have successfully exited."sv; + logging::info("All app processes have successfully exited."sv); } } else { - BOOST_LOG(info) << "App did not respond to a graceful termination request. Forcefully terminating the app's processes."sv; + logging::info("App did not respond to a graceful termination request. Forcefully terminating the app's processes."sv); } } else { - BOOST_LOG(info) << "No graceful exit timeout was specified for this app. Forcefully terminating the app's processes."sv; + logging::info("No graceful exit timeout was specified for this app. Forcefully terminating the app's processes."sv); } // We always call terminate() even if we waited successfully for all processes above. @@ -140,15 +141,15 @@ namespace proc { parts = boost::program_options::split_unix(cmd); #endif } catch (boost::escaped_list_error &err) { - BOOST_LOG(error) << "Boost failed to parse command ["sv << cmd << "] because " << err.what(); + logging::error("Boost failed to parse command [{}] because {}", cmd, err.what()); return boost::filesystem::path(); } if (parts.empty()) { - BOOST_LOG(error) << "Unable to parse command: "sv << cmd; + logging::error("Unable to parse command: {}", cmd); return boost::filesystem::path(); } - BOOST_LOG(debug) << "Parsed target ["sv << parts.at(0) << "] from command ["sv << cmd << ']'; + logging::debug("Parsed target [{}] from command [{}]", parts.at(0), cmd); // If the target is a URL, don't parse any further here if (parts.at(0).find("://") != std::string::npos) { @@ -160,12 +161,14 @@ namespace proc { if (!cmd_path.is_absolute()) { cmd_path = boost::process::v1::search_path(parts.at(0)); if (cmd_path.empty()) { - BOOST_LOG(error) << "Unable to find executable ["sv << parts.at(0) << "]. Is it in your PATH?"sv; + logging::error("Unable to find executable [{}]. Is it in your PATH?", parts.at(0)); return boost::filesystem::path(); } } - BOOST_LOG(debug) << "Resolved target ["sv << parts.at(0) << "] to path ["sv << cmd_path << ']'; + logging::debug([&](std::ostream &out) { + out << "Resolved target ["sv << parts.at(0) << "] to path ["sv << cmd_path << ']'; + }); // Now that we have a complete path, we can just use parent_path() return cmd_path.parent_path(); @@ -177,7 +180,7 @@ namespace proc { const auto stripped_command = boost::trim_copy(command); if (stripped_command.empty() || stripped_command.starts_with(host_command_prefix)) { if (!stripped_command.empty()) { - BOOST_LOG(warning) << "Command ["sv << stripped_command << "] already includes [flatpak-spawn --host], which is no longer required for Flatpak builds."sv; + logging::warning("Command [{}] already includes [flatpak-spawn --host], which is no longer required for Flatpak builds.", stripped_command); } return stripped_command; } @@ -197,7 +200,7 @@ namespace proc { }); if (iter == _apps.end()) { - BOOST_LOG(error) << "Couldn't find app with ID ["sv << app_id << ']'; + logging::error("Couldn't find app with ID [{}]", app_id); return 404; } @@ -264,11 +267,13 @@ namespace proc { boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(command, _env) : boost::filesystem::path(_app.working_dir); - BOOST_LOG(info) << "Executing Do Cmd: ["sv << command << ']'; + logging::info("Executing Do Cmd: [{}]", command); auto child = platf::run_command(cmd.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { - BOOST_LOG(error) << "Couldn't run ["sv << command << "]: System: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't run ["sv << command << "]: System: "sv << ec.message(); + }); // We don't want any prep commands failing launch of the desktop. // This is to prevent the issue where users reboot their PC and need to log in with Sunshine. // permission_denied is typically returned when the user impersonation fails, which can happen when user is not signed in yet. @@ -279,12 +284,14 @@ namespace proc { child.wait(ec); if (ec) { - BOOST_LOG(error) << '[' << command << "] wait failed with error code ["sv << ec << ']'; + logging::error([&](std::ostream &out) { + out << '[' << command << "] wait failed with error code ["sv << ec << ']'; + }); return -1; } auto ret = child.exit_code(); if (ret != 0) { - BOOST_LOG(error) << '[' << command << "] exited with code ["sv << ret << ']'; + logging::error("[{}] exited with code [{}]", command, ret); return -1; } } @@ -294,27 +301,35 @@ namespace proc { boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(command, _env) : boost::filesystem::path(_app.working_dir); - BOOST_LOG(info) << "Spawning ["sv << command << "] in ["sv << working_dir << ']'; + logging::info([&](std::ostream &out) { + out << "Spawning ["sv << command << "] in ["sv << working_dir << ']'; + }); auto child = platf::run_command(_app.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { - BOOST_LOG(warning) << "Couldn't spawn ["sv << command << "]: System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "Couldn't spawn ["sv << command << "]: System: "sv << ec.message(); + }); } else { child.detach(); } } if (_app.cmd.empty()) { - BOOST_LOG(info) << "Executing [Desktop]"sv; + logging::info("Executing [Desktop]"sv); placebo = true; } else { const auto command = prepare_command(_app.cmd); boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(command, _env) : boost::filesystem::path(_app.working_dir); - BOOST_LOG(info) << "Executing: ["sv << command << "] in ["sv << working_dir << ']'; + logging::info([&](std::ostream &out) { + out << "Executing: ["sv << command << "] in ["sv << working_dir << ']'; + }); _process = platf::run_command(_app.elevated, true, command, working_dir, _env, _pipe.get(), ec, &_process_group); if (ec) { - BOOST_LOG(warning) << "Couldn't run ["sv << command << "]: System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "Couldn't run ["sv << command << "]: System: "sv << ec.message(); + }); return -1; } } @@ -346,15 +361,15 @@ namespace proc { // The app is still running only if the initial process launched is still running return _app_id; } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { - BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; - BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; + logging::info("App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv); + logging::info("Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv); placebo = true; return _app_id; } // Perform cleanup actions now if needed if (_process) { - BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; + logging::info("App exited with code [{}]", _process.native_exit_code()); terminate(); } @@ -382,18 +397,20 @@ namespace proc { boost::filesystem::path working_dir = _app.working_dir.empty() ? find_working_directory(command, _env) : boost::filesystem::path(_app.working_dir); - BOOST_LOG(info) << "Executing Undo Cmd: ["sv << command << ']'; + logging::info("Executing Undo Cmd: [{}]", command); auto child = platf::run_command(cmd.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); if (ec) { - BOOST_LOG(warning) << "System: "sv << ec.message(); + logging::warning([&](std::ostream &out) { + out << "System: "sv << ec.message(); + }); } child.wait(); auto ret = child.exit_code(); if (ret != 0) { - BOOST_LOG(warning) << "Return code ["sv << ret << ']'; + logging::warning("Return code [{}]", ret); } } @@ -606,7 +623,9 @@ namespace proc { if (auto full_image_path = std::filesystem::path(SUNSHINE_ASSETS_DIR) / app_image_path; std::filesystem::exists(full_image_path)) { // Validate PNG signature if (!check_valid_png(full_image_path)) { - BOOST_LOG(warning) << "Invalid PNG file at path ["sv << full_image_path << ']'; + logging::warning([&](std::ostream &out) { + out << "Invalid PNG file at path ["sv << full_image_path << ']'; + }); return DEFAULT_APP_IMAGE_PATH; } return full_image_path.string(); @@ -620,13 +639,17 @@ namespace proc { // check if specified image exists if (std::error_code code; !std::filesystem::exists(app_image_path, code)) { // return default box image if image does not exist - BOOST_LOG(warning) << "Couldn't find app image at path ["sv << app_image_path << ']'; + logging::warning([&](std::ostream &out) { + out << "Couldn't find app image at path ["sv << app_image_path << ']'; + }); return DEFAULT_APP_IMAGE_PATH; } // Validate PNG signature if (!check_valid_png(app_image_path)) { - BOOST_LOG(warning) << "Invalid PNG file at path ["sv << app_image_path << ']'; + logging::warning([&](std::ostream &out) { + out << "Invalid PNG file at path ["sv << app_image_path << ']'; + }); return DEFAULT_APP_IMAGE_PATH; } @@ -848,7 +871,7 @@ namespace proc { std::move(apps) }; } catch (std::exception &e) { - BOOST_LOG(error) << e.what(); + logging::error(e.what()); } return std::nullopt; diff --git a/src/rtsp.cpp b/src/rtsp.cpp index 06f972b9c..869b06351 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -14,6 +14,7 @@ extern "C" { #include #include #include +#include #include #include @@ -162,7 +163,7 @@ namespace rtsp_stream { */ void read() { if (begin == std::end(msg_buf) || (session->rtsp_cipher && begin + sizeof(encrypted_rtsp_header_t) >= std::end(msg_buf))) { - BOOST_LOG(error) << "RTSP: read(): Exceeded maximum rtsp packet size: "sv << msg_buf.size(); + logging::error("RTSP: read(): Exceeded maximum rtsp packet size: {}", msg_buf.size()); respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {}); @@ -195,19 +196,23 @@ namespace rtsp_stream { * @param bytes The number of bytes read. */ static void handle_read_encrypted_header(std::shared_ptr &socket, const boost::system::error_code &ec, std::size_t bytes) { - BOOST_LOG(debug) << "handle_read_encrypted_header(): Handle read of size: "sv << bytes << " bytes"sv; + logging::debug("handle_read_encrypted_header(): Handle read of size: {} bytes", bytes); auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't close tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_encrypted_header(): Couldn't close tcp socket: "sv << ec.message(); + }); } }); if (ec || bytes < sizeof(encrypted_rtsp_header_t)) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't read from tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_encrypted_header(): Couldn't read from tcp socket: "sv << ec.message(); + }); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -215,7 +220,7 @@ namespace rtsp_stream { auto header = (encrypted_rtsp_header_t *) socket->begin; if (!header->is_encrypted()) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Rejecting unencrypted RTSP message"sv; + logging::error("RTSP: handle_read_encrypted_header(): Rejecting unencrypted RTSP message"sv); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -225,7 +230,7 @@ namespace rtsp_stream { // Check if we have enough space to read this message if (socket->begin + sizeof(*header) + payload_length >= std::end(socket->msg_buf)) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Exceeded maximum rtsp packet size: "sv << socket->msg_buf.size(); + logging::error("RTSP: handle_read_encrypted_header(): Exceeded maximum rtsp packet size: {}", socket->msg_buf.size()); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -244,14 +249,16 @@ namespace rtsp_stream { * @param bytes The number of bytes read. */ static void handle_read_encrypted_message(std::shared_ptr &socket, const boost::system::error_code &ec, std::size_t bytes) { - BOOST_LOG(debug) << "handle_read_encrypted(): Handle read of size: "sv << bytes << " bytes"sv; + logging::debug("handle_read_encrypted(): Handle read of size: {} bytes", bytes); auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted_message(): Couldn't close tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_encrypted_message(): Couldn't close tcp socket: "sv << ec.message(); + }); } }); @@ -260,7 +267,9 @@ namespace rtsp_stream { auto seq = util::endian::big(header->sequenceNumber); if (ec || bytes < payload_length) { - BOOST_LOG(error) << "RTSP: handle_read_encrypted(): Couldn't read from tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_encrypted(): Couldn't read from tcp socket: "sv << ec.message(); + }); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -281,7 +290,7 @@ namespace rtsp_stream { std::vector plaintext; if (socket->session->rtsp_cipher->decrypt(std::string_view {(const char *) header->tag.data(), sizeof(header->tag) + bytes}, plaintext, &iv)) { - BOOST_LOG(error) << "Failed to verify RTSP message tag"sv; + logging::error("Failed to verify RTSP message tag"sv); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -289,7 +298,7 @@ namespace rtsp_stream { msg_t req {new msg_t::element_type {}}; if (auto status = parseRtspMessage(req.get(), (char *) plaintext.data(), (int) plaintext.size())) { - BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']'; + logging::error("Malformed RTSP message: [{}]", status); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -307,7 +316,7 @@ namespace rtsp_stream { */ void read_plaintext_payload() { if (begin == std::end(msg_buf)) { - BOOST_LOG(error) << "RTSP: read_plaintext_payload(): Exceeded maximum rtsp packet size: "sv << msg_buf.size(); + logging::error("RTSP: read_plaintext_payload(): Exceeded maximum rtsp packet size: {}", msg_buf.size()); respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {}); @@ -335,19 +344,23 @@ namespace rtsp_stream { * @param bytes The number of bytes read. */ static void handle_plaintext_payload(std::shared_ptr &socket, const boost::system::error_code &ec, std::size_t bytes) { - BOOST_LOG(debug) << "handle_plaintext_payload(): Handle read of size: "sv << bytes << " bytes"sv; + logging::debug("handle_plaintext_payload(): Handle read of size: {} bytes", bytes); auto sock_close = util::fail_guard([&socket]() { boost::system::error_code ec; socket->sock.close(ec); if (ec) { - BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't close tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_plaintext_payload(): Couldn't close tcp socket: "sv << ec.message(); + }); } }); if (ec) { - BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't read from tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_plaintext_payload(): Couldn't read from tcp socket: "sv << ec.message(); + }); return; } @@ -355,7 +368,7 @@ namespace rtsp_stream { auto end = socket->begin + bytes; msg_t req {new msg_t::element_type {}}; if (auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (int) (end - socket->msg_buf.data()))) { - BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']'; + logging::error("Malformed RTSP message: [{}]", status); respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); return; @@ -370,7 +383,7 @@ namespace rtsp_stream { auto content_length = 0; for (auto option = req->options; option != nullptr; option = option->next) { if ("Content-length"sv == option->option) { - BOOST_LOG(debug) << "Found Content-Length: "sv << option->content << " bytes"sv; + logging::debug("Found Content-Length: {} bytes", option->content); // If content_length > bytes read, then we need to store current data read, // to be appended by the next read. @@ -386,7 +399,9 @@ namespace rtsp_stream { if (end - socket->crlf >= content_length) { if (end - socket->crlf > content_length) { - BOOST_LOG(warning) << "(end - socket->crlf) > content_length -- "sv << (std::size_t) (end - socket->crlf) << " > "sv << content_length; + logging::warning([&](std::ostream &out) { + out << "(end - socket->crlf) > content_length -- "sv << (std::size_t) (end - socket->crlf) << " > "sv << content_length; + }); } fg.disable(); @@ -405,16 +420,20 @@ namespace rtsp_stream { * @param bytes The number of bytes read. */ static void handle_read_plaintext(std::shared_ptr &socket, const boost::system::error_code &ec, std::size_t bytes) { - BOOST_LOG(debug) << "handle_read_plaintext(): Handle read of size: "sv << bytes << " bytes"sv; + logging::debug("handle_read_plaintext(): Handle read of size: {} bytes", bytes); if (ec) { - BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't read from tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_plaintext(): Couldn't read from tcp socket: "sv << ec.message(); + }); boost::system::error_code ec; socket->sock.close(ec); if (ec) { - BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't close tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: handle_read_plaintext(): Couldn't close tcp socket: "sv << ec.message(); + }); } return; @@ -512,7 +531,9 @@ namespace rtsp_stream { auto bind_addr_str = net::get_bind_address(settings, af); const auto bind_addr = boost::asio::ip::make_address(bind_addr_str, ec); if (ec) { - BOOST_LOG(error) << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); + logging::error([&](std::ostream &out) { + out << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); + }); return -1; } @@ -563,7 +584,9 @@ namespace rtsp_stream { */ void handle_accept(const boost::system::error_code &ec) { if (ec) { - BOOST_LOG(error) << "Couldn't accept incoming connections: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't accept incoming connections: "sv << ec.message(); + }); // Stop server clear(); @@ -579,7 +602,7 @@ namespace rtsp_stream { socket->read(); } else { // This can happen due to normal things like port scanning, so let's not make these visible by default - BOOST_LOG(debug) << "No pending session for incoming RTSP connection"sv; + logging::debug("No pending session for incoming RTSP connection"sv); // If there is no session pending, close the connection immediately boost::system::error_code ec; @@ -626,7 +649,7 @@ namespace rtsp_stream { if (!ec) { auto discarded = launch_event.pop(0s); if (discarded) { - BOOST_LOG(debug) << "Event timeout: "sv << discarded->unique_id; + logging::debug("Event timeout: {}", discarded->unique_id); } } }); @@ -642,7 +665,7 @@ namespace rtsp_stream { auto launch_session = launch_event.view(0s); if (launch_session) { if (launch_session->id != launch_session_id) { - BOOST_LOG(error) << "Attempted to clear unexpected session: "sv << launch_session_id << " vs "sv << launch_session->id; + logging::error("Attempted to clear unexpected session: {} vs {}", launch_session_id, launch_session->id); } else { raised_timer.cancel(); launch_event.pop(); @@ -719,7 +742,9 @@ namespace rtsp_stream { void insert(const std::shared_ptr &session) { auto lg = _session_slots.lock(); _session_slots->emplace(session); - BOOST_LOG(info) << "New streaming session started [active sessions: "sv << _session_slots->size() << ']'; + logging::info([&](std::ostream &out) { + out << "New streaming session started [active sessions: "sv << _session_slots->size() << ']'; + }); } /** @@ -838,7 +863,9 @@ namespace rtsp_stream { bytes_send += sock.send(boost::asio::buffer(sv.substr(bytes_send)), 0, ec); if (ec) { - BOOST_LOG(error) << "RTSP: Couldn't send data over tcp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "RTSP: Couldn't send data over tcp socket: "sv << ec.message(); + }); return -1; } } @@ -867,11 +894,12 @@ namespace rtsp_stream { int serialized_len; util::c_ptr raw_resp {serializeRtspMessage(resp.get(), &serialized_len)}; - BOOST_LOG(debug) - << "---Begin Response---"sv << std::endl - << std::string_view {raw_resp.get(), (std::size_t) serialized_len} << std::endl - << std::string_view {payload.first, (std::size_t) payload.second} << std::endl - << "---End Response---"sv << std::endl; + logging::debug([&](std::ostream &out) { + out << "---Begin Response---"sv << std::endl + << std::string_view {raw_resp.get(), (std::size_t) serialized_len} << std::endl + << std::string_view {payload.first, (std::size_t) payload.second} << std::endl + << "---End Response---"sv << std::endl; + }); // Encrypt the RTSP message if encryption is enabled if (session.rtsp_cipher) { @@ -1223,16 +1251,15 @@ namespace rtsp_stream { // Limit the packetsize to avoid fragmentation with clients that cannot configure this value if (server->settings.stream.packetsize && server->settings.stream.packetsize < config.packetsize) { if (server->settings.stream.packetsize < config::PACKETSIZE_MIN || server->settings.stream.packetsize > config::PACKETSIZE_MAX) { - BOOST_LOG(warning) << "packetsize range: ["sv << config::PACKETSIZE_MIN << "-"sv << config::PACKETSIZE_MAX - << "] invalid value: "sv << server->settings.stream.packetsize; + logging::warning("packetsize range: [{}-{}] invalid value: {}", config::PACKETSIZE_MIN, config::PACKETSIZE_MAX, server->settings.stream.packetsize); } else { if (server->settings.stream.packetsize < config::PACKETSIZE_SMALL) { - BOOST_LOG(info) << "packetsize is small < "sv << config::PACKETSIZE_SMALL << " bytes, reduce bitrate if the stream breaks"sv; + logging::info("packetsize is small < {} bytes, reduce bitrate if the stream breaks", config::PACKETSIZE_SMALL); } else if (server->settings.stream.packetsize > config::PACKETSIZE_LARGE) { - BOOST_LOG(info) << "packetsize is large > "sv << config::PACKETSIZE_LARGE << " bytes, jumbo frames may be used"sv; + logging::info("packetsize is large > {} bytes, jumbo frames may be used", config::PACKETSIZE_LARGE); } - BOOST_LOG(info) << "packetsize limit: "sv << config.packetsize << " -> "sv << server->settings.stream.packetsize << " bytes"sv; + logging::info("packetsize limit: {} -> {} bytes", config.packetsize, server->settings.stream.packetsize); config.packetsize = server->settings.stream.packetsize; } } @@ -1273,7 +1300,7 @@ namespace rtsp_stream { for (auto option = req->options; option != nullptr; option = option->next) { if ("Host"sv == option->option) { std::string_view content {option->content}; - BOOST_LOG(debug) << "Found Host: "sv << content; + logging::debug("Found Host: {}", content); config.audio.flags[audio::config_t::HIGH_QUALITY] = (content.find("0.0.0.0"sv) == std::string::npos); } } @@ -1301,7 +1328,7 @@ namespace rtsp_stream { config.audio.flags[audio::config_t::CUSTOM_SURROUND_PARAMS] = valid; } if (session.continuous_audio) { - BOOST_LOG(info) << "Client requested continuous audio"sv; + logging::info("Client requested continuous audio"sv); config.audio.flags[audio::config_t::CONTINUOUS_AUDIO] = true; } @@ -1310,7 +1337,7 @@ namespace rtsp_stream { // too low, we'll allow it to exceed the limits rather than reducing the encoding bitrate // down to nearly nothing. if (configuredBitrateKbps) { - BOOST_LOG(debug) << "Client configured bitrate is "sv << configuredBitrateKbps << " Kbps"sv; + logging::debug("Client configured bitrate is {} Kbps", configuredBitrateKbps); // If the FEC percentage isn't too high, adjust the configured bitrate to ensure video // traffic doesn't exceed the user's selected bitrate when the FEC shards are included. @@ -1327,19 +1354,19 @@ namespace rtsp_stream { // traffic (capped at 10% reduction). configuredBitrateKbps -= std::min((std::int64_t) 500, configuredBitrateKbps / 10); - BOOST_LOG(debug) << "Final adjusted video encoding bitrate is "sv << configuredBitrateKbps << " Kbps"sv; + logging::debug("Final adjusted video encoding bitrate is {} Kbps", configuredBitrateKbps); config.monitor.bitrate = (int) configuredBitrateKbps; } if (config.monitor.videoFormat == 1 && capabilities.active_hevc_mode == 1) { - BOOST_LOG(warning) << "HEVC is disabled, yet the client requested HEVC"sv; + logging::warning("HEVC is disabled, yet the client requested HEVC"sv); respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {}); return; } if (config.monitor.videoFormat == 2 && capabilities.active_av1_mode == 1) { - BOOST_LOG(warning) << "AV1 is disabled, yet the client requested AV1"sv; + logging::warning("AV1 is disabled, yet the client requested AV1"sv); respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {}); return; @@ -1348,7 +1375,7 @@ namespace rtsp_stream { // Check that any required encryption is enabled auto encryption_mode = net::encryption_mode_for_address(server->settings, sock.remote_endpoint().address()); if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY && (config.encryptionFlagsEnabled & (SS_ENC_VIDEO | SS_ENC_AUDIO)) != (SS_ENC_VIDEO | SS_ENC_AUDIO)) { - BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; + logging::error("Rejecting client that cannot comply with mandatory encryption requirement"sv); respond(sock, session, &option, 403, "Forbidden", req->sequenceNumber, {}); return; @@ -1358,7 +1385,7 @@ namespace rtsp_stream { server->insert(stream_session); if (stream::session::start(*stream_session, sock.remote_endpoint().address().to_string())) { - BOOST_LOG(error) << "Failed to start a streaming session"sv; + logging::error("Failed to start a streaming session"sv); server->remove(stream_session); respond(sock, session, &option, 500, "Internal Server Error", req->sequenceNumber, {}); @@ -1402,7 +1429,9 @@ namespace rtsp_stream { boost::system::error_code ec; if (server.bind(net::af_from_enum_string(server.settings.sunshine.address_family), net::map_port(server.settings, rtsp_stream::RTSP_SETUP_PORT), ec)) { - BOOST_LOG(fatal) << "Couldn't bind RTSP server to port ["sv << net::map_port(server.settings, rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Couldn't bind RTSP server to port ["sv << net::map_port(server.settings, rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message(); + }); shutdown_event->raise(true); return; @@ -1445,10 +1474,10 @@ namespace rtsp_stream { auto seqnm = msg->sequenceNumber; std::string_view messageBuffer {msg->messageBuffer}; - BOOST_LOG(debug) << "type ["sv << type << ']'; - BOOST_LOG(debug) << "sequence number ["sv << seqnm << ']'; - BOOST_LOG(debug) << "protocol :: "sv << protocol; - BOOST_LOG(debug) << "payload :: "sv << payload; + logging::debug("type [{}]", type); + logging::debug("sequence number [{}]", seqnm); + logging::debug("protocol :: {}", protocol); + logging::debug("payload :: {}", payload); if (msg->type == TYPE_RESPONSE) { auto &resp = msg->message.response; @@ -1456,27 +1485,25 @@ namespace rtsp_stream { auto statuscode = resp.statusCode; std::string_view status {resp.statusString}; - BOOST_LOG(debug) << "statuscode :: "sv << statuscode; - BOOST_LOG(debug) << "status :: "sv << status; + logging::debug("statuscode :: {}", statuscode); + logging::debug("status :: {}", status); } else { auto &req = msg->message.request; std::string_view command {req.command}; std::string_view target {req.target}; - BOOST_LOG(debug) << "command :: "sv << command; - BOOST_LOG(debug) << "target :: "sv << target; + logging::debug("command :: {}", command); + logging::debug("target :: {}", target); } for (auto option = msg->options; option != nullptr; option = option->next) { std::string_view content {option->content}; std::string_view name {option->option}; - BOOST_LOG(debug) << name << " :: "sv << content; + logging::debug("{} :: {}", name, content); } - BOOST_LOG(debug) << "---Begin MessageBuffer---"sv << std::endl - << messageBuffer << std::endl - << "---End MessageBuffer---"sv << std::endl; + logging::debug("---Begin MessageBuffer---\n{}\n---End MessageBuffer---\n", messageBuffer); } } // namespace rtsp_stream diff --git a/src/stream.cpp b/src/stream.cpp index 9eb8c96af..f13c7aac3 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -623,7 +623,7 @@ namespace stream { auto bytes = session->control.cipher.encrypt(plaintext, packet->payload(), &iv); if (bytes <= 0) { - BOOST_LOG(error) << "Couldn't encrypt control data"sv; + logging::error("Couldn't encrypt control data"sv); return {}; } @@ -759,13 +759,13 @@ namespace stream { if (session_p->control.connect_data != connect_data) { continue; } else { - BOOST_LOG(debug) << "Initialized new control stream session by connect data match [v2]"sv; + logging::debug("Initialized new control stream session by connect data match [v2]"sv); } } else { if (session_p->control.expected_peer_address != peer_addr) { continue; } else { - BOOST_LOG(debug) << "Initialized new control stream session by IP address match [v1]"sv; + logging::debug("Initialized new control stream session by IP address match [v1]"sv); } } @@ -783,12 +783,14 @@ namespace stream { try { session_p->localAddress = boost::asio::ip::make_address(local_address); } catch (const boost::system::system_error &e) { - BOOST_LOG(error) << "boost::system::system_error in address parsing: " << e.what() << " (code: " << e.code() << ")"sv; + logging::error([&](std::ostream &out) { + out << "boost::system::system_error in address parsing: " << e.what() << " (code: " << e.code() << ")"sv; + }); throw; } - BOOST_LOG(debug) << "Control local address ["sv << local_address << ']'; - BOOST_LOG(debug) << "Control peer address ["sv << peer_addr << ':' << peer_port << ']'; + logging::debug("Control local address [{}]", local_address); + logging::debug("Control peer address [{}:{}]", peer_addr, peer_port); // Insert this into the map for O(1) lookups in the future auto ptslg = _peer_to_session.lock(); @@ -809,17 +811,20 @@ namespace stream { void control_server_t::call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected) { // If we are using the encrypted control stream protocol, drop any messages that come off the wire unencrypted if (session->config.controlProtocolType == 13 && !reinjected && type != packetTypes[IDX_ENCRYPTED]) { - BOOST_LOG(error) << "Dropping unencrypted message on encrypted control stream: "sv << util::hex(type).to_string_view(); + logging::error([&](std::ostream &out) { + out << "Dropping unencrypted message on encrypted control stream: "sv << util::hex(type).to_string_view(); + }); return; } auto cb = _map_type_cb.find(type); if (cb == std::end(_map_type_cb)) { - BOOST_LOG(debug) - << "type [Unknown] { "sv << util::hex(type).to_string_view() << " }"sv << std::endl - << "---data---"sv << std::endl - << util::hex_vec(payload) << std::endl - << "---end data---"sv; + logging::debug([&](std::ostream &out) { + out << "type [Unknown] { "sv << util::hex(type).to_string_view() << " }"sv << std::endl + << "---data---"sv << std::endl + << util::hex_vec(payload) << std::endl + << "---end data---"sv; + }); } else { cb->second(session, payload); } @@ -832,7 +837,9 @@ namespace stream { if (res > 0) { auto session = get_session(event.peer, event.data); if (!session) { - BOOST_LOG(warning) << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv; + logging::warning([&](std::ostream &out) { + out << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv; + }); enet_peer_disconnect_now(event.peer, 0); return; @@ -851,10 +858,10 @@ namespace stream { } break; case ENET_EVENT_TYPE_CONNECT: - BOOST_LOG(info) << "CLIENT CONNECTED"sv; + logging::info("CLIENT CONNECTED"sv); break; case ENET_EVENT_TYPE_DISCONNECT: - BOOST_LOG(info) << "CLIENT DISCONNECTED"sv; + logging::info("CLIENT DISCONNECTED"sv); // No more clients to send video data to ^_^ if (session->state == session::state_e::RUNNING) { session::stop(*session); @@ -934,7 +941,7 @@ namespace stream { parity_shards = minparityshards; fecpercentage = (100 * parity_shards) / data_shards; - BOOST_LOG(verbose) << "Increasing FEC percentage to "sv << fecpercentage << " to meet parity shard minimum"sv << std::endl; + logging::verbose("Increasing FEC percentage to {} to meet parity shard minimum\n", fecpercentage); } auto nr_shards = data_shards + parity_shards; @@ -1079,7 +1086,7 @@ namespace stream { */ int send_feedback_msg(session_t *session, platf::gamepad_feedback_msg_t &msg) { if (!session->control.peer) { - BOOST_LOG(warning) << "Couldn't send gamepad feedback data, still waiting for PING from Moonlight"sv; + logging::warning("Couldn't send gamepad feedback data, still waiting for PING from Moonlight"sv); // Still waiting for PING from Moonlight return -1; } @@ -1097,7 +1104,9 @@ namespace stream { plaintext.lowfreq = util::endian::little(data.lowfreq); plaintext.highfreq = util::endian::little(data.highfreq); - BOOST_LOG(verbose) << "Rumble: "sv << msg.id << " :: "sv << util::hex(data.lowfreq).to_string_view() << " :: "sv << util::hex(data.highfreq).to_string_view(); + logging::verbose([&](std::ostream &out) { + out << "Rumble: "sv << msg.id << " :: "sv << util::hex(data.lowfreq).to_string_view() << " :: "sv << util::hex(data.highfreq).to_string_view(); + }); std::array encrypted_payload; @@ -1113,7 +1122,9 @@ namespace stream { plaintext.left = util::endian::little(data.left_trigger); plaintext.right = util::endian::little(data.right_trigger); - BOOST_LOG(verbose) << "Rumble triggers: "sv << msg.id << " :: "sv << util::hex(data.left_trigger).to_string_view() << " :: "sv << util::hex(data.right_trigger).to_string_view(); + logging::verbose([&](std::ostream &out) { + out << "Rumble triggers: "sv << msg.id << " :: "sv << util::hex(data.left_trigger).to_string_view() << " :: "sv << util::hex(data.right_trigger).to_string_view(); + }); std::array encrypted_payload; @@ -1129,7 +1140,9 @@ namespace stream { plaintext.reportrate = util::endian::little(data.report_rate); plaintext.type = data.motion_type; - BOOST_LOG(verbose) << "Motion event state: "sv << msg.id << " :: "sv << util::hex(data.report_rate).to_string_view() << " :: "sv << util::hex(data.motion_type).to_string_view(); + logging::verbose([&](std::ostream &out) { + out << "Motion event state: "sv << msg.id << " :: "sv << util::hex(data.report_rate).to_string_view() << " :: "sv << util::hex(data.motion_type).to_string_view(); + }); std::array encrypted_payload; @@ -1146,7 +1159,9 @@ namespace stream { plaintext.g = data.g; plaintext.b = data.b; - BOOST_LOG(verbose) << "RGB: "sv << msg.id << " :: "sv << util::hex(data.r).to_string_view() << util::hex(data.g).to_string_view() << util::hex(data.b).to_string_view(); + logging::verbose([&](std::ostream &out) { + out << "RGB: "sv << msg.id << " :: "sv << util::hex(data.r).to_string_view() << util::hex(data.g).to_string_view() << util::hex(data.b).to_string_view(); + }); std::array encrypted_payload; @@ -1162,7 +1177,9 @@ namespace stream { plaintext.solid = data.solid; plaintext.flashing = data.flashing; - BOOST_LOG(verbose) << "Player LEDs: "sv << msg.id << " :: solid "sv << util::hex(data.solid).to_string_view() << " :: flashing "sv << util::hex(data.flashing).to_string_view(); + logging::verbose([&](std::ostream &out) { + out << "Player LEDs: "sv << msg.id << " :: solid "sv << util::hex(data.solid).to_string_view() << " :: flashing "sv << util::hex(data.flashing).to_string_view(); + }); std::array encrypted_payload; @@ -1184,13 +1201,15 @@ namespace stream { payload = encode_control(session, util::view(plaintext), encrypted_payload); } else { - BOOST_LOG(error) << "Unknown gamepad feedback message type"sv; + logging::error("Unknown gamepad feedback message type"sv); return -1; } if (session->broadcast_ref->control_server.send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); - BOOST_LOG(warning) << "Couldn't send gamepad feedback to ["sv << addr << ':' << port << ']'; + logging::warning([&](std::ostream &out) { + out << "Couldn't send gamepad feedback to ["sv << addr << ':' << port << ']'; + }); return -1; } @@ -1207,7 +1226,7 @@ namespace stream { */ int send_hdr_mode(session_t *session, video::hdr_info_t hdr_info) { if (!session->control.peer) { - BOOST_LOG(warning) << "Couldn't send HDR mode, still waiting for PING from Moonlight"sv; + logging::warning("Couldn't send HDR mode, still waiting for PING from Moonlight"sv); // Still waiting for PING from Moonlight return -1; } @@ -1225,12 +1244,14 @@ namespace stream { auto payload = encode_control(session, util::view(plaintext), encrypted_payload); if (session->broadcast_ref->control_server.send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); - BOOST_LOG(warning) << "Couldn't send HDR mode to ["sv << addr << ':' << port << ']'; + logging::warning([&](std::ostream &out) { + out << "Couldn't send HDR mode to ["sv << addr << ':' << port << ']'; + }); return -1; } - BOOST_LOG(debug) << "Sent HDR mode: " << hdr_info->enabled; + logging::debug("Sent HDR mode: {}", static_cast(hdr_info->enabled)); return 0; } @@ -1242,15 +1263,15 @@ namespace stream { void controlBroadcastThread(control_server_t *server) { const auto &host_mail = server->owner->host_mail; server->map(packetTypes[IDX_PERIODIC_PING], [](session_t *session, const std::string_view &payload) { - BOOST_LOG(verbose) << "type [IDX_PERIODIC_PING]"sv; + logging::verbose("type [IDX_PERIODIC_PING]"sv); }); server->map(packetTypes[IDX_START_A], [&](session_t *session, const std::string_view &payload) { - BOOST_LOG(debug) << "type [IDX_START_A]"sv; + logging::debug("type [IDX_START_A]"sv); }); server->map(packetTypes[IDX_START_B], [&](session_t *session, const std::string_view &payload) { - BOOST_LOG(debug) << "type [IDX_START_B]"sv; + logging::debug("type [IDX_START_B]"sv); }); server->map(packetTypes[IDX_LOSS_STATS], [&](session_t *session, const std::string_view &payload) { @@ -1260,17 +1281,11 @@ namespace stream { auto lastGoodFrame = stats[3]; - BOOST_LOG(verbose) - << "type [IDX_LOSS_STATS]"sv << std::endl - << "---begin stats---" << std::endl - << "loss count since last report [" << count << ']' << std::endl - << "time in milli since last report [" << t.count() << ']' << std::endl - << "last good frame [" << lastGoodFrame << ']' << std::endl - << "---end stats---"; + logging::verbose("type [IDX_LOSS_STATS]\n---begin stats---\nloss count since last report [{}]\ntime in milli since last report [{}]\nlast good frame [{}]\n---end stats---", count, t.count(), lastGoodFrame); }); server->map(packetTypes[IDX_REQUEST_IDR_FRAME], [&](session_t *session, const std::string_view &payload) { - BOOST_LOG(debug) << "type [IDX_REQUEST_IDR_FRAME]"sv; + logging::debug("type [IDX_REQUEST_IDR_FRAME]"sv); session->video.idr_events->raise(true); }); @@ -1280,16 +1295,13 @@ namespace stream { auto firstFrame = frames[0]; auto lastFrame = frames[1]; - BOOST_LOG(debug) - << "type [IDX_INVALIDATE_REF_FRAMES]"sv << std::endl - << "firstFrame [" << firstFrame << ']' << std::endl - << "lastFrame [" << lastFrame << ']'; + logging::debug("type [IDX_INVALIDATE_REF_FRAMES]\nfirstFrame [{}]\nlastFrame [{}]", firstFrame, lastFrame); session->video.invalidate_ref_frames_events->raise(std::make_pair(firstFrame, lastFrame)); }); server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) { - BOOST_LOG(debug) << "type [IDX_INPUT_DATA]"sv; + logging::debug("type [IDX_INPUT_DATA]"sv); auto tagged_cipher_length = util::endian::big(*(int32_t *) payload.data()); std::string_view tagged_cipher {payload.data() + sizeof(tagged_cipher_length), (size_t) tagged_cipher_length}; @@ -1301,7 +1313,7 @@ namespace stream { if (cipher.decrypt(tagged_cipher, plaintext, &iv)) { // something went wrong :( - BOOST_LOG(error) << "Failed to verify tag"sv; + logging::error("Failed to verify tag"sv); session::stop(*session); return; @@ -1315,7 +1327,7 @@ namespace stream { }); server->map(packetTypes[IDX_ENCRYPTED], [server](session_t *session, const std::string_view &payload) { - BOOST_LOG(verbose) << "type [IDX_ENCRYPTED]"sv; + logging::verbose("type [IDX_ENCRYPTED]"sv); auto header = (control_encrypted_p) (payload.data() - 2); @@ -1323,7 +1335,7 @@ namespace stream { auto seq = util::endian::little(header->seq); if (length < (16 + 4 + 4)) { - BOOST_LOG(warning) << "Control: Runt packet"sv; + logging::warning("Control: Runt packet"sv); return; } @@ -1356,7 +1368,7 @@ namespace stream { if (cipher.decrypt(tagged_cipher, plaintext, &iv)) { // something went wrong :( - BOOST_LOG(error) << "Failed to verify tag"sv; + logging::error("Failed to verify tag"sv); session::stop(*session); return; @@ -1366,7 +1378,7 @@ namespace stream { std::string_view next_payload {(char *) plaintext.data() + 4, plaintext.size() - 4}; if (type == packetTypes[IDX_ENCRYPTED]) { - BOOST_LOG(error) << "Bad packet type [IDX_ENCRYPTED] found"sv; + logging::error("Bad packet type [IDX_ENCRYPTED] found"sv); session::stop(*session); return; } @@ -1407,7 +1419,7 @@ namespace stream { if (now > session->pingTimeout) { auto address = session->control.peer ? platf::from_sockaddr((sockaddr *) &session->control.peer->address.address) : session->control.expected_peer_address; - BOOST_LOG(info) << address << ": Ping Timeout"sv; + logging::info("{}: Ping Timeout", address); session::stop(*session); } @@ -1454,7 +1466,7 @@ namespace stream { // Don't break until any pending sessions either expire or connect if (server->owner->processes.running() == 0 && !has_session_awaiting_peer) { - BOOST_LOG(info) << "Process terminated"sv; + logging::info("Process terminated"sv); break; } @@ -1483,7 +1495,9 @@ namespace stream { if (server->send(payload, session->control.peer)) { TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address)); - BOOST_LOG(warning) << "Couldn't send termination code to ["sv << addr << ':' << port << ']'; + logging::warning([&](std::ostream &out) { + out << "Couldn't send termination code to ["sv << addr << ':' << port << ']'; + }); } } @@ -1550,7 +1564,9 @@ namespace stream { }); auto type_str = buf_elem ? "AUDIO"sv : "VIDEO"sv; - BOOST_LOG(verbose) << "Recv: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + logging::verbose([&](std::ostream &out) { + out << "Recv: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + }); populate_peer_to_session(); @@ -1560,7 +1576,9 @@ namespace stream { } if (ec || !bytes) { - BOOST_LOG(error) << "Couldn't receive data from udp socket: "sv << ec.message(); + logging::error([&](std::ostream &out) { + out << "Couldn't receive data from udp socket: "sv << ec.message(); + }); return; } @@ -1568,7 +1586,9 @@ namespace stream { // For legacy PING packets, find the matching session by address. auto it = peer_to_session.find(peer.address()); if (it != std::end(peer_to_session)) { - BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + logging::debug([&](std::ostream &out) { + out << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + }); it->second->raise(peer, std::string {buf[buf_elem].data(), bytes}); } } else if (bytes >= sizeof(SS_PING)) { @@ -1577,7 +1597,9 @@ namespace stream { // For new PING packets that include a client identifier, search by payload. auto it = peer_to_session.find(std::string {ping->payload, sizeof(ping->payload)}); if (it != std::end(peer_to_session)) { - BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + logging::debug([&](std::ostream &out) { + out << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; + }); it->second->raise(peer, std::string {buf[buf_elem].data(), bytes}); } } @@ -1611,17 +1633,17 @@ namespace stream { platf::set_thread_name("stream::videoBroadcast"); platf::adjust_thread_priority(platf::thread_priority_e::high); - logging::min_max_avg_periodic_logger frame_processing_latency_logger(debug, "Frame processing latency", "ms"); + logging::min_max_avg_periodic_logger frame_processing_latency_logger(logging::level_e::debug, "Frame processing latency", "ms"); - logging::time_delta_periodic_logger frame_send_batch_latency_logger(debug, "Network: each send_batch() latency"); - logging::time_delta_periodic_logger frame_fec_latency_logger(debug, "Network: each FEC block latency"); - logging::time_delta_periodic_logger frame_network_latency_logger(debug, "Network: frame's overall network latency"); + logging::time_delta_periodic_logger frame_send_batch_latency_logger(logging::level_e::debug, "Network: each send_batch() latency"); + logging::time_delta_periodic_logger frame_fec_latency_logger(logging::level_e::debug, "Network: each FEC block latency"); + logging::time_delta_periodic_logger frame_network_latency_logger(logging::level_e::debug, "Network: frame's overall network latency"); crypto::aes_t iv(12); auto timer = platf::create_high_precision_timer(); if (!timer || !*timer) { - BOOST_LOG(error) << "Failed to create timer, aborting video broadcast thread"; + logging::error("Failed to create timer, aborting video broadcast thread"); return; } @@ -1705,7 +1727,7 @@ namespace stream { // If the number of FEC blocks needed exceeds the protocol limit, turn off FEC for this frame. // For normal FEC percentages, this should only happen for enormous frames (over 800 packets at 20%). if (fec_blocks_needed > MAX_FEC_BLOCKS) { - BOOST_LOG(warning) << "Skipping FEC for abnormally large encoded frame (needed "sv << fec_blocks_needed << " FEC blocks)"sv; + logging::warning("Skipping FEC for abnormally large encoded frame (needed {} FEC blocks)", fec_blocks_needed); fecPercentage = 0; fec_blocks_needed = MAX_FEC_BLOCKS; } @@ -1714,7 +1736,7 @@ namespace stream { auto fec_blocks_begin = std::begin(fec_blocks); auto fec_blocks_end = std::begin(fec_blocks) + fec_blocks_needed; - BOOST_LOG(verbose) << "Generating "sv << fec_blocks_needed << " FEC blocks"sv; + logging::verbose("Generating {} FEC blocks", fec_blocks_needed); // Align individual FEC blocks to blocksize auto unaligned_size = payload.size() / fec_blocks_needed; @@ -1723,7 +1745,9 @@ namespace stream { // If we exceed the 10-bit FEC packet index (which means our frame exceeded 4096 packets), // the frame will be unrecoverable. Log an error for this case. if (aligned_size / blocksize >= 1024) { - BOOST_LOG(error) << "Encoder produced a frame too large to send! Is the encoder broken? (needed "sv << (aligned_size / blocksize) << " packets)"sv; + logging::error([&](std::ostream &out) { + out << "Encoder produced a frame too large to send! Is the encoder broken? (needed "sv << (aligned_size / blocksize) << " packets)"sv; + }); } // Split the data into aligned FEC blocks @@ -1873,7 +1897,7 @@ namespace stream { // Use a batched send if it's supported on this platform if (!platf::send_batch(batch_info)) { // Batched send is not available, so send each packet individually - BOOST_LOG(verbose) << "Falling back to unbatched send"sv; + logging::verbose("Falling back to unbatched send"sv); for (auto y = 0; y < current_batch_size; y++) { auto send_info = platf::send_info_t { shards.prefix(next_shard_to_send + y), @@ -1904,11 +1928,13 @@ namespace stream { frame_network_latency_logger.second_point_now_and_log(); - BOOST_LOG(verbose) << "Sent Frame seq ["sv << packet->frame_index() << "] pts ["sv << timestamp - << "] shards ["sv << shards.size() << "/"sv << shards.percentage << "%]"sv - << (frame_is_dupe ? " Dupe" : "") - << (packet->is_idr() ? " Key" : "") - << (packet->after_ref_frame_invalidation ? " RFI" : ""); + logging::verbose([&](std::ostream &out) { + out << "Sent Frame seq ["sv << packet->frame_index() << "] pts ["sv << timestamp + << "] shards ["sv << shards.size() << "/"sv << shards.percentage << "%]"sv + << (frame_is_dupe ? " Dupe" : "") + << (packet->is_idr() ? " Key" : "") + << (packet->after_ref_frame_invalidation ? " RFI" : ""); + }); ++blockIndex; lowseq += shards.size(); @@ -1916,7 +1942,7 @@ namespace stream { session->video.lowseq = lowseq; } catch (const std::exception &e) { - BOOST_LOG(error) << "Broadcast video failed "sv << e.what(); + logging::error("Broadcast video failed {}", e.what()); std::this_thread::sleep_for(100ms); } } @@ -1971,11 +1997,11 @@ namespace stream { auto bytes = encode_audio(session->config.encryptionFlagsEnabled & SS_ENC_AUDIO, packet_data, shards_p[sequenceNumber % RTPA_DATA_SHARDS], iv, session->audio.cipher); if (bytes < 0) { - BOOST_LOG(error) << "Couldn't encode audio packet"sv; + logging::error("Couldn't encode audio packet"sv); break; } - BOOST_LOG(verbose) << "Audio [seq "sv << sequenceNumber << ", pts "sv << timestamp << "] :: send..."sv; + logging::verbose("Audio [seq {}, pts {}] :: send...", sequenceNumber, timestamp); audio_packet.rtp.sequenceNumber = util::endian::big(sequenceNumber); audio_packet.rtp.timestamp = util::endian::big(timestamp); @@ -2023,11 +2049,13 @@ namespace stream { session->localAddress, }; platf::send(send_info); - BOOST_LOG(verbose) << "Audio FEC ["sv << (sequenceNumber & ~(RTPA_DATA_SHARDS - 1)) << ' ' << x << "] :: send..."sv; + logging::verbose([&](std::ostream &out) { + out << "Audio FEC ["sv << (sequenceNumber & ~(RTPA_DATA_SHARDS - 1)) << ' ' << x << "] :: send..."sv; + }); } } } catch (const std::exception &e) { - BOOST_LOG(error) << "Broadcast audio failed "sv << e.what(); + logging::error("Broadcast audio failed {}", e.what()); std::this_thread::sleep_for(100ms); } } @@ -2046,7 +2074,7 @@ namespace stream { auto audio_port = net::map_port(ctx.owner->settings, AUDIO_STREAM_PORT); if (ctx.control_server.bind(ctx.owner->settings, address_family, control_port)) { - BOOST_LOG(error) << "Couldn't bind Control server to port ["sv << control_port << "], likely another process already bound to the port"sv; + logging::error("Couldn't bind Control server to port [{}], likely another process already bound to the port", control_port); return -1; } @@ -2054,7 +2082,9 @@ namespace stream { boost::system::error_code ec; ctx.video_sock.open(protocol, ec); if (ec) { - BOOST_LOG(fatal) << "Couldn't open socket for Video server: "sv << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Couldn't open socket for Video server: "sv << ec.message(); + }); return -1; } @@ -2063,33 +2093,41 @@ namespace stream { try { ctx.video_sock.set_option(boost::asio::socket_base::send_buffer_size(1024 * 1024)); } catch (...) { - BOOST_LOG(error) << "Failed to set video socket send buffer size (SO_SENDBUF)"; + logging::error("Failed to set video socket send buffer size (SO_SENDBUF)"); } auto bind_addr_str = net::get_bind_address(ctx.owner->settings, address_family); const auto bind_addr = boost::asio::ip::make_address(bind_addr_str, ec); if (ec) { - BOOST_LOG(fatal) << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message(); + }); return -1; } ctx.video_sock.bind(udp::endpoint(bind_addr, video_port), ec); if (ec) { - BOOST_LOG(fatal) << "Couldn't bind Video server to port ["sv << video_port << "]: "sv << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Couldn't bind Video server to port ["sv << video_port << "]: "sv << ec.message(); + }); return -1; } ctx.audio_sock.open(protocol, ec); if (ec) { - BOOST_LOG(fatal) << "Couldn't open socket for Audio server: "sv << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Couldn't open socket for Audio server: "sv << ec.message(); + }); return -1; } ctx.audio_sock.bind(udp::endpoint(bind_addr, audio_port), ec); if (ec) { - BOOST_LOG(fatal) << "Couldn't bind Audio server to port ["sv << audio_port << "]: "sv << ec.message(); + logging::fatal([&](std::ostream &out) { + out << "Couldn't bind Audio server to port ["sv << audio_port << "]: "sv << ec.message(); + }); return -1; } @@ -2130,15 +2168,15 @@ namespace stream { video_packets.reset(); audio_packets.reset(); - BOOST_LOG(debug) << "Waiting for main listening thread to end..."sv; + logging::debug("Waiting for main listening thread to end..."sv); ctx.recv_thread.join(); - BOOST_LOG(debug) << "Waiting for main video thread to end..."sv; + logging::debug("Waiting for main video thread to end..."sv); ctx.video_thread.join(); - BOOST_LOG(debug) << "Waiting for main audio thread to end..."sv; + logging::debug("Waiting for main audio thread to end..."sv); ctx.audio_thread.join(); - BOOST_LOG(debug) << "Waiting for main control thread to end..."sv; + logging::debug("Waiting for main control thread to end..."sv); ctx.control_thread.join(); - BOOST_LOG(debug) << "All broadcasting threads ended"sv; + logging::debug("All broadcasting threads ended"sv); broadcast_shutdown_event->reset(); } @@ -2188,12 +2226,18 @@ namespace stream { TUPLE_2D_REF(recv_peer, msg, *msg_opt); if (msg.find(expected_payload) != std::string::npos) { // Match the new PING payload format - BOOST_LOG(debug) << "Received ping [v2] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + logging::debug([&](std::ostream &out) { + out << "Received ping [v2] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + }); } else if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) && msg == "PING"sv) { // Match the legacy fixed PING payload only if the new type is not supported - BOOST_LOG(debug) << "Received ping [v1] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + logging::debug([&](std::ostream &out) { + out << "Received ping [v1] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + }); } else { - BOOST_LOG(debug) << "Received non-ping from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + logging::debug([&](std::ostream &out) { + out << "Received non-ping from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']'; + }); current_time = std::chrono::steady_clock::now(); continue; } @@ -2203,7 +2247,7 @@ namespace stream { return 0; } - BOOST_LOG(error) << "Initial Ping Timeout"sv; + logging::error("Initial Ping Timeout"sv); return -1; } @@ -2230,7 +2274,7 @@ namespace stream { auto address = session->video.peer.address(); session->video.qos = session->owner->platform.enable_socket_qos(ref->video_sock.native_handle(), address, session->video.peer.port(), platf::qos_data_type_e::video, session->config.videoQosType != 0); - BOOST_LOG(debug) << "Start capturing Video"sv; + logging::debug("Start capturing Video"sv); session->owner->videos.capture(session->mail, session->config.monitor, session); } @@ -2257,7 +2301,7 @@ namespace stream { auto address = session->audio.peer.address(); session->audio.qos = session->owner->platform.enable_socket_qos(ref->audio_sock.native_handle(), address, session->audio.peer.port(), platf::qos_data_type_e::audio, session->config.audioQosType != 0); - BOOST_LOG(debug) << "Start capturing Audio"sv; + logging::debug("Start capturing Audio"sv); session->owner->audios.capture(session->mail, session->config.audio, session); } @@ -2299,7 +2343,7 @@ namespace stream { // GPU scheduling enabled. If this happens, we will terminate ourselves and the service can restart. // The alternative is that Sunshine can never start another session until it's manually restarted. auto task = []() { - BOOST_LOG(fatal) << "Hang detected! Session failed to terminate in 10 seconds."sv; + logging::fatal("Hang detected! Session failed to terminate in 10 seconds."sv); logging::log_flush(); lifetime::debug_trap(); }; @@ -2309,14 +2353,14 @@ namespace stream { session.owner->scheduler.cancel(force_kill); }); - BOOST_LOG(debug) << "Waiting for video to end..."sv; + logging::debug("Waiting for video to end..."sv); session.videoThread.join(); - BOOST_LOG(debug) << "Waiting for audio to end..."sv; + logging::debug("Waiting for audio to end..."sv); session.audioThread.join(); - BOOST_LOG(debug) << "Waiting for control to end..."sv; + logging::debug("Waiting for control to end..."sv); session.controlEnd.view(); // Reset input on session stop to avoid stuck repeated keys - BOOST_LOG(debug) << "Resetting Input..."sv; + logging::debug("Resetting Input..."sv); input::reset(session.input); // If this is the last session, invoke the platform callbacks @@ -2339,7 +2383,7 @@ namespace stream { session.owner->platform.streaming_will_stop(); } - BOOST_LOG(debug) << "Session ended"sv; + logging::debug("Session ended"sv); } /** @@ -2354,7 +2398,7 @@ namespace stream { } session.control.expected_peer_address = addr_string; - BOOST_LOG(debug) << "Expecting incoming session connections from "sv << addr_string; + logging::debug("Expecting incoming session connections from {}", addr_string); // Insert this session into the session list { @@ -2422,7 +2466,7 @@ namespace stream { session->video.lowseq = 0; session->video.ping_payload = launch_session.av_ping_payload; if (config.encryptionFlagsEnabled & SS_ENC_VIDEO) { - BOOST_LOG(info) << "Video encryption enabled"sv; + logging::info("Video encryption enabled"sv); session->video.cipher = crypto::cipher::gcm_t { launch_session.gcm_key, false diff --git a/src/system_tray.cpp b/src/system_tray.cpp index c18a82caf..5fc85ef60 100644 --- a/src/system_tray.cpp +++ b/src/system_tray.cpp @@ -184,7 +184,7 @@ namespace system_tray { #endif void tray_open_ui_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Opening UI from system tray"sv; + logging::info("Opening UI from system tray"sv); if (item && item->context) { launch_ui(static_cast(item->context)->settings); } @@ -204,7 +204,7 @@ namespace system_tray { #if defined(_WIN32) || defined(__APPLE__) void tray_virtualhid_license_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Opening Virtual HID Broker license settings from system tray"sv; + logging::info("Opening Virtual HID Broker license settings from system tray"sv); if (!item || !item->context) { return; } @@ -217,13 +217,13 @@ namespace system_tray { } void tray_virtualhid_download_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Opening Virtual HID Broker download from system tray"sv; + logging::info("Opening Virtual HID Broker download from system tray"sv); platf::open_url(std::string {LIBVIRTUALHID_RELEASES_URL}); } #endif /** - * @brief Forwards Qt log messages to Sunshine's BOOST_LOG logger. + * @brief Forward Qt messages through Sunshine logging functions. * @param level Log level: 0=debug, 1=info, 2=warning, 3=error. * @param msg The message string from Qt. */ @@ -233,22 +233,22 @@ namespace system_tray { } switch (level) { case 0: - BOOST_LOG(debug) << "Qt: " << msg; + logging::debug("Qt: {}", msg); break; case 1: - BOOST_LOG(info) << "Qt: " << msg; + logging::info("Qt: {}", msg); break; case 2: - BOOST_LOG(warning) << "Qt: " << msg; + logging::warning("Qt: {}", msg); break; default: - BOOST_LOG(error) << "Qt: " << msg; + logging::error("Qt: {}", msg); break; } } void tray_reset_display_device_config_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Resetting display device config from system tray"sv; + logging::info("Resetting display device config from system tray"sv); if (item && item->context) { std::ignore = static_cast(item->context)->displays.reset_persistence(); @@ -256,7 +256,7 @@ namespace system_tray { } void tray_restart_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Restarting from system tray"sv; + logging::info("Restarting from system tray"sv); if (item && item->context) { platf::restart(static_cast(item->context)->lifetime); @@ -264,7 +264,7 @@ namespace system_tray { } void tray_quit_cb([[maybe_unused]] struct tray_menu *item) { - BOOST_LOG(info) << "Quitting from system tray"sv; + logging::info("Quitting from system tray"sv); if (!item || !item->context) { return; } @@ -645,7 +645,7 @@ namespace system_tray { open_bound_ui("/troubleshooting#virtualhid"); }; - BOOST_LOG(warning) << notification_text; + logging::warning(notification_text); if (tray_initialized_state().load()) { tray_update(&tray); } @@ -692,7 +692,9 @@ namespace system_tray { (std::filesystem::path {executable.data()}.parent_path() / utf_utils::from_utf8(relativePath)).lexically_normal(); auto full = utf_utils::to_utf8(full_path.wstring()); - BOOST_LOG(debug) << "System Tray: using " << full << " for icon path"; + logging::debug([&](std::ostream &out) { + out << "System Tray: using " << full << " for icon path"; + }); const auto it = g_cache.try_emplace(relativePath, std::move(full)).first; return it->second.c_str(); @@ -727,7 +729,9 @@ namespace system_tray { full = std::string(resourcesPath) + "/" + relativePath; } - BOOST_LOG(debug) << "System Tray: using " << full << " for icon path"; + logging::debug([&](std::ostream &out) { + out << "System Tray: using " << full << " for icon path"; + }); const auto it = g_cache.try_emplace(relativePath, std::move(full)).first; return it->second.c_str(); @@ -788,7 +792,7 @@ namespace system_tray { PSECURITY_DESCRIPTOR sd; auto security_error = GetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, &old_dacl, nullptr, &sd); if (security_error != ERROR_SUCCESS) { - BOOST_LOG(warning) << "GetSecurityInfo() failed: "sv << security_error; + logging::warning("GetSecurityInfo() failed: {}", security_error); return 1; } @@ -800,7 +804,7 @@ namespace system_tray { PSID world_sid; if (!AllocateAndInitializeSid(&sid_authority, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &world_sid)) { security_error = GetLastError(); - BOOST_LOG(warning) << "AllocateAndInitializeSid() failed: "sv << security_error; + logging::warning("AllocateAndInitializeSid() failed: {}", security_error); return 1; } @@ -818,7 +822,7 @@ namespace system_tray { PACL new_dacl; security_error = SetEntriesInAcl(1, &ea, old_dacl, &new_dacl); if (security_error != ERROR_SUCCESS) { - BOOST_LOG(warning) << "SetEntriesInAcl() failed: "sv << security_error; + logging::warning("SetEntriesInAcl() failed: {}", security_error); return 1; } @@ -828,7 +832,7 @@ namespace system_tray { security_error = SetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, new_dacl, nullptr); if (security_error != ERROR_SUCCESS) { - BOOST_LOG(warning) << "SetSecurityInfo() failed: "sv << security_error; + logging::warning("SetSecurityInfo() failed: {}", security_error); return 1; } } @@ -855,14 +859,14 @@ namespace system_tray { return 1; } if (tray_init(&tray) < 0) { - BOOST_LOG(warning) << "Failed to create system tray"sv; + logging::warning("Failed to create system tray"sv); return 1; } tray_initialized_state().store(true); } - BOOST_LOG(info) << "System tray created"sv; + logging::info("System tray created"sv); return 0; } @@ -872,7 +876,7 @@ namespace system_tray { int process_tray_events() { if (!tray_initialized_state().load()) { - BOOST_LOG(error) << "System tray is not initialized"sv; + logging::error("System tray is not initialized"sv); return 1; } @@ -999,12 +1003,12 @@ namespace system_tray { */ static void tray_thread_worker(const std::stop_token stop_token) { platf::set_thread_name("system_tray"); - BOOST_LOG(info) << "System tray thread started"sv; + logging::info("System tray thread started"sv); // Initialize the tray in this thread if (init_tray_with_stop_token(stop_token) != 0) { if (!stop_token.stop_requested()) { - BOOST_LOG(error) << "Failed to initialize tray in thread"sv; + logging::error("Failed to initialize tray in thread"sv); } return; } @@ -1019,22 +1023,22 @@ namespace system_tray { tray_initialized_state().store(false); } - BOOST_LOG(info) << "System tray thread ended"sv; + logging::info("System tray thread ended"sv); } int init_tray_threaded() { try { auto &worker = tray_worker_thread(); if (worker.joinable()) { - BOOST_LOG(error) << "System tray thread is already running"sv; + logging::error("System tray thread is already running"sv); return 1; } worker = std::jthread(tray_thread_worker); - BOOST_LOG(info) << "System tray thread initialized successfully"sv; + logging::info("System tray thread initialized successfully"sv); return 0; } catch (const std::system_error &e) { - BOOST_LOG(error) << "Failed to create tray thread: " << e.what(); + logging::error("Failed to create tray thread: {}", e.what()); return 1; } } diff --git a/src/upnp.cpp b/src/upnp.cpp index b023aa646..f59249ed9 100644 --- a/src/upnp.cpp +++ b/src/upnp.cpp @@ -121,7 +121,7 @@ namespace upnp { int err; device_t device {upnpDiscover(2000, nullptr, nullptr, 0, IPv6, 2, &err)}; if (!device || err) { - BOOST_LOG(debug) << "Couldn't discover any IPv6 UPNP devices"sv; + logging::debug("Couldn't discover any IPv6 UPNP devices"sv); return false; } @@ -130,7 +130,9 @@ namespace upnp { std::array lan_addr; auto status = upnp::UPNP_GetValidIGDStatus(device, &urls, &data, lan_addr); if (status != 1 && status != 2) { - BOOST_LOG(debug) << "No valid IPv6 IGD: "sv << status_string(status); + logging::debug([&](std::ostream &out) { + out << "No valid IPv6 IGD: "sv << status_string(status); + }); return false; } @@ -141,10 +143,7 @@ namespace upnp { // Check if this firewall supports IPv6 pinholes err = UPNP_GetFirewallStatus(urls->controlURL_6FC, data.IPv6FC.servicetype, &firewallEnabled, &pinholeAllowed); if (err == UPNPCOMMAND_SUCCESS) { - BOOST_LOG(debug) << "UPnP IPv6 firewall control available. Firewall is "sv - << (firewallEnabled ? "enabled"sv : "disabled"sv) - << ", pinhole is "sv - << (pinholeAllowed ? "allowed"sv : "disallowed"sv); + logging::debug("UPnP IPv6 firewall control available. Firewall is {}, pinhole is {}", (firewallEnabled ? "enabled"sv : "disabled"sv), (pinholeAllowed ? "allowed"sv : "disallowed"sv)); if (pinholeAllowed) { // Create pinholes for each port @@ -158,23 +157,23 @@ namespace upnp { // Open a pinhole for the LAN port, since there will be no WAN->LAN port mapping on IPv6 err = UPNP_AddPinhole(urls->controlURL_6FC, data.IPv6FC.servicetype, "", "0", lan_addr.data(), mapping.port.lan.c_str(), mapping.port.proto.c_str(), mapping_period.c_str(), uniqueId.data()); if (err == UPNPCOMMAND_SUCCESS) { - BOOST_LOG(debug) << "Successfully created pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan; + logging::debug("Successfully created pinhole for {} {}", mapping.port.proto, mapping.port.lan); } else { - BOOST_LOG(debug) << "Failed to create pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan << ": "sv << err; + logging::debug("Failed to create pinhole for {} {}: {}", mapping.port.proto, mapping.port.lan, err); } } return err == 0; } else { - BOOST_LOG(debug) << "IPv6 pinholes are not allowed by the IGD"sv; + logging::debug("IPv6 pinholes are not allowed by the IGD"sv); return false; } } else { - BOOST_LOG(debug) << "Failed to get IPv6 firewall status: "sv << err; + logging::debug("Failed to get IPv6 firewall status: {}", err); return false; } } else { - BOOST_LOG(debug) << "IPv6 Firewall Control is not supported by the IGD"sv; + logging::debug("IPv6 Firewall Control is not supported by the IGD"sv); return false; } } @@ -196,7 +195,7 @@ namespace upnp { bool indefinite = false; // First check if this port is already mapped successfully - BOOST_LOG(debug) << "Checking for existing UPnP port mapping for "sv << mapping.port.wan; + logging::debug("Checking for existing UPnP port mapping for {}", mapping.port.wan); auto err = UPNP_GetSpecificPortMappingEntry( urls->controlURL, data.first.servicetype, @@ -212,20 +211,20 @@ namespace upnp { leaseDuration.data() ); if (err == 714) { // NoSuchEntryInArray - BOOST_LOG(debug) << "Mapping entry not found for "sv << mapping.port.wan; + logging::debug("Mapping entry not found for {}", mapping.port.wan); } else if (err == UPNPCOMMAND_SUCCESS) { // Some routers change the description, so we can't check that here if (std::string_view {intClient.data()} == lan_addr) { if (std::atoi(leaseDuration.data()) == 0) { - BOOST_LOG(debug) << "Static mapping entry found for "sv << mapping.port.wan; + logging::debug("Static mapping entry found for {}", mapping.port.wan); // It's a static mapping, so we're done here return true; } else { - BOOST_LOG(debug) << "Mapping entry found for "sv << mapping.port.wan << " ("sv << leaseDuration.data() << " seconds remaining)"sv; + logging::debug("Mapping entry found for {} ({} seconds remaining)", mapping.port.wan, leaseDuration.data()); } } else { - BOOST_LOG(warning) << "UPnP conflict detected with: "sv << intClient.data(); + logging::warning("UPnP conflict detected with: {}", intClient.data()); // Some UPnP IGDs won't let unauthenticated clients delete other conflicting port mappings // for security reasons, but we will give it a try anyway. @@ -237,12 +236,12 @@ namespace upnp { nullptr ); if (err) { - BOOST_LOG(error) << "Unable to delete conflicting UPnP port mapping: "sv << err; + logging::error("Unable to delete conflicting UPnP port mapping: {}", err); return false; } } } else { - BOOST_LOG(error) << "UPNP_GetSpecificPortMappingEntry() failed: "sv << err; + logging::error("UPNP_GetSpecificPortMappingEntry() failed: {}", err); // If we get a strange error from the router, we'll assume it's some old broken IGDv1 // device and only use indefinite lease durations to hopefully avoid confusing it. @@ -267,7 +266,7 @@ namespace upnp { if (err != UPNPCOMMAND_SUCCESS && !indefinite) { // This may be an old/broken IGD that doesn't like non-static mappings. - BOOST_LOG(debug) << "Trying static mapping after failure: "sv << err; + logging::debug("Trying static mapping after failure: {}", err); err = UPNP_AddPortMapping( urls->controlURL, data.first.servicetype, @@ -282,11 +281,11 @@ namespace upnp { } if (err) { - BOOST_LOG(error) << "Failed to map "sv << mapping.port.proto << ' ' << mapping.port.lan << ": "sv << err; + logging::error("Failed to map {} {}: {}", mapping.port.proto, mapping.port.lan, err); return false; } - BOOST_LOG(debug) << "Successfully mapped "sv << mapping.port.proto << ' ' << mapping.port.lan; + logging::debug("Successfully mapped {} {}", mapping.port.proto, mapping.port.lan); return true; } @@ -306,9 +305,9 @@ namespace upnp { ); if (status && status != 714) { // NoSuchEntryInArray - BOOST_LOG(warning) << "Failed to unmap "sv << it->port.proto << ' ' << it->port.lan << ": "sv << status; + logging::warning("Failed to unmap {} {}: {}", it->port.proto, it->port.lan, status); } else { - BOOST_LOG(debug) << "Successfully unmapped "sv << it->port.proto << ' ' << it->port.lan; + logging::debug("Successfully unmapped {} {}", it->port.proto, it->port.lan); } } } @@ -330,13 +329,13 @@ namespace upnp { int err = 0; device_t device {upnpDiscover(2000, nullptr, nullptr, 0, IPv4, 2, &err)}; if (!device || err) { - BOOST_LOG(warning) << "Couldn't discover any IPv4 UPNP devices"sv; + logging::warning("Couldn't discover any IPv4 UPNP devices"sv); mapped = false; continue; } for (auto dev = device.get(); dev != nullptr; dev = dev->pNext) { - BOOST_LOG(debug) << "Found device: "sv << dev->descURL; + logging::debug("Found device: {}", dev->descURL); } std::array lan_addr; @@ -344,28 +343,30 @@ namespace upnp { urls_t urls; auto status = upnp::UPNP_GetValidIGDStatus(device, &urls, &data, lan_addr); if (status != 1 && status != 2) { - BOOST_LOG(error) << status_string(status); + logging::error([&](std::ostream &out) { + out << status_string(status); + }); mapped = false; continue; } std::string lan_addr_str {lan_addr.data()}; - BOOST_LOG(debug) << "Found valid IGD device: "sv << urls->rootdescURL; + logging::debug("Found valid IGD device: {}", urls->rootdescURL); for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) { map_upnp_port(data, urls, lan_addr_str, *it); } if (!mapped) { - BOOST_LOG(info) << "Completed UPnP port mappings to "sv << lan_addr_str << " via "sv << urls->rootdescURL; + logging::info("Completed UPnP port mappings to {} via {}", lan_addr_str, urls->rootdescURL); } // If we are listening on IPv6 and the IGD has an IPv6 firewall enabled, try to create IPv6 firewall pinholes if (address_family == net::af_e::BOTH) { if (create_ipv6_pinholes() && !mapped) { // Only log the first time through - BOOST_LOG(info) << "Successfully opened IPv6 pinholes on the IGD"sv; + logging::info("Successfully opened IPv6 pinholes on the IGD"sv); } } @@ -375,7 +376,7 @@ namespace upnp { if (mapped) { // Unmap ports upon termination - BOOST_LOG(info) << "Unmapping UPNP ports..."sv; + logging::info("Unmapping UPNP ports..."sv); unmap_all_upnp_ports(mapped_urls, data); } } diff --git a/src/video.cpp b/src/video.cpp index ea807a274..d3a0629db 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -73,7 +73,7 @@ namespace video { return true; } - BOOST_LOG(error) << "No display devices are active at the moment! Cannot probe the encoders."; + logging::error("No display devices are active at the moment! Cannot probe the encoders."); return false; } } // namespace @@ -182,7 +182,7 @@ namespace video { } const auto mode = config.chromaSamplingType == 1 ? "YUV 4:4:4 dynamic range"sv : "dynamic range"sv; - BOOST_LOG(warning) << video_format.name << ": "sv << mode << " not supported, falling back to SDR"sv; + logging::warning("{}: {} not supported, falling back to SDR", video_format.name, mode); config.dynamicRange = 0; return config; } @@ -267,7 +267,9 @@ namespace video { auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get()); if (status < 0) { std::array string; - BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Couldn't scale frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } @@ -293,7 +295,9 @@ namespace video { auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } } @@ -395,14 +399,18 @@ namespace video { av_dict_free(&options); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to set SWS options: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to set SWS options: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } status = sws_init_context(sws.get(), nullptr, nullptr); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to initialize SWS: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to initialize SWS: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } @@ -528,7 +536,7 @@ namespace video { * @param last_frame Last frame. */ void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override { - BOOST_LOG(error) << "Encoder doesn't support reference frame invalidation"; + logging::error("Encoder doesn't support reference frame invalidation"); request_idr_frame(); } @@ -1606,7 +1614,7 @@ namespace video { // If we now have no displays, let's put the old display array back and fail if (display_names.empty() && !old_display_names.empty()) { - BOOST_LOG(error) << "No displays were found after reenumeration!"sv; + logging::error("No displays were found after reenumeration!"sv); display_names = std::move(old_display_names); return; } else if (display_names.empty()) { @@ -1626,7 +1634,7 @@ namespace video { } // The old display was removed, so we'll start back at the first display again - BOOST_LOG(warning) << "Previous active display ["sv << current_display_name << "] is no longer present"sv; + logging::warning("Previous active display [{}] is no longer present", current_display_name); } else { for (int x = 0; x < display_names.size(); ++x) { if (display_names[x] == output_name) { @@ -1891,7 +1899,7 @@ namespace video { case platf::capture_e::interrupted: return; default: - BOOST_LOG(error) << "Unrecognized capture status ["sv << std::to_underlying(status) << ']'; + logging::error("Unrecognized capture status [{}]", std::to_underlying(status)); return; } } @@ -1920,7 +1928,9 @@ namespace video { auto ret = avcodec_send_frame(ctx.get(), frame); if (ret < 0) { std::array err_str {0}; - BOOST_LOG(error) << "Could not send a frame for encoding: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, ret); + logging::error([&](std::ostream &out) { + out << "Could not send a frame for encoding: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, ret); + }); return -1; } @@ -1937,11 +1947,11 @@ namespace video { } if (av_packet->flags & AV_PKT_FLAG_KEY) { - BOOST_LOG(debug) << "Frame "sv << frame_nr << ": IDR Keyframe (AV_FRAME_FLAG_KEY)"sv; + logging::debug("Frame {}: IDR Keyframe (AV_FRAME_FLAG_KEY)", frame_nr); } if ((frame->flags & AV_FRAME_FLAG_KEY) && !(av_packet->flags & AV_PKT_FLAG_KEY)) { - BOOST_LOG(error) << "Encoder did not produce IDR frame when requested!"sv; + logging::error("Encoder did not produce IDR frame when requested!"sv); } if (session.inject) { @@ -1994,12 +2004,12 @@ namespace video { int encode_nvenc(int64_t frame_nr, nvenc_encode_session_t &session, safe::mail_raw_t::queue_t &packets, void *channel_data, std::optional frame_timestamp) { auto encoded_frame = session.encode_frame(frame_nr); if (encoded_frame.data.empty()) { - BOOST_LOG(error) << "NvENC returned empty packet"; + logging::error("NvENC returned empty packet"); return -1; } if (frame_nr != encoded_frame.frame_index) { - BOOST_LOG(error) << "NvENC frame index mismatch " << frame_nr << " " << encoded_frame.frame_index; + logging::error("NvENC frame index mismatch {} {}", frame_nr, encoded_frame.frame_index); } auto packet = std::make_unique(std::move(encoded_frame.data), encoded_frame.frame_index, encoded_frame.idr); @@ -2061,31 +2071,31 @@ namespace video { auto &video_format = encoder.codec_from_config(config); if (!video_format[encoder_t::PASSED] || !disp->is_codec_supported(video_format.name, config)) { - BOOST_LOG(error) << encoder.name << ": "sv << video_format.name << " mode not supported"sv; + logging::error("{}: {} mode not supported", encoder.name, video_format.name); return nullptr; } if (config.chromaSamplingType == 1) { if (!video_format[encoder_t::YUV444]) { - BOOST_LOG(error) << video_format.name << ": YUV 4:4:4 not supported"sv; + logging::error("{}: YUV 4:4:4 not supported", video_format.name); return nullptr; } if (config.dynamicRange && !video_format[encoder_t::DYNAMIC_RANGE_YUV444]) { - BOOST_LOG(error) << video_format.name << ": YUV 4:4:4 dynamic range not supported"sv; + logging::error("{}: YUV 4:4:4 dynamic range not supported", video_format.name); return nullptr; } } else { if (config.dynamicRange && !video_format[encoder_t::DYNAMIC_RANGE]) { - BOOST_LOG(error) << video_format.name << ": dynamic range not supported"sv; + logging::error("{}: dynamic range not supported", video_format.name); return nullptr; } } auto codec = avcodec_find_encoder_by_name(video_format.name.c_str()); if (!codec) { - BOOST_LOG(error) << "Couldn't open ["sv << video_format.name << ']'; + logging::error("Couldn't open [{}]", video_format.name); return nullptr; } @@ -2155,7 +2165,7 @@ namespace video { if (video_format[encoder_t::REF_FRAMES_RESTRICT]) { ctx->refs = config.numRefFrames; } else { - BOOST_LOG(warning) << "Client requested reference frame limit, but encoder doesn't support it!"sv; + logging::warning("Client requested reference frame limit, but encoder doesn't support it!"sv); } } @@ -2199,7 +2209,9 @@ namespace video { auto err = av_hwdevice_ctx_create_derived(&derived_context, platform_formats->avcodec_derived_dev_type, encoding_stream_context.get(), 0); if (err) { std::array err_str {0}; - BOOST_LOG(error) << "Failed to derive device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Failed to derive device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return nullptr; } @@ -2298,7 +2310,7 @@ namespace video { } auto bitrate = ((settings.video.max_bitrate > 0) ? std::min(config.bitrate, settings.video.max_bitrate) : config.bitrate) * 1000; - BOOST_LOG(info) << "Streaming bitrate is " << bitrate; + logging::info("Streaming bitrate is {}", bitrate); ctx->rc_max_rate = bitrate; ctx->bit_rate = bitrate; @@ -2338,16 +2350,18 @@ namespace video { std::array err_str {0}; if (!video_format.fallback_options.empty() && retries == 0) { - BOOST_LOG(info) - << "Retrying with fallback configuration options for ["sv << video_format.name << "] after error: "sv - << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::info([&](std::ostream &out) { + out << "Retrying with fallback configuration options for ["sv << video_format.name << "] after error: "sv + << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); continue; } else { - BOOST_LOG(error) - << "Could not open codec ["sv - << video_format.name << "]: "sv - << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Could not open codec ["sv + << video_format.name << "]: "sv + << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return nullptr; } @@ -2396,7 +2410,7 @@ namespace video { clm->MaxFALL = hdr_metadata.maxFrameAverageLightLevel; } } else { - BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; + logging::error("Couldn't get display hdr metadata when colorspace selection indicates it should have one"); } } @@ -2509,9 +2523,9 @@ namespace video { auto fail_guard = util::fail_guard([&encoder, &session] { if (encoder.flags & ASYNC_TEARDOWN) { std::jthread encoder_teardown_thread {[session = std::move(session)]() mutable { - BOOST_LOG(info) << "Starting async encoder teardown"; + logging::info("Starting async encoder teardown"); session.reset(); - BOOST_LOG(info) << "Async encoder teardown complete"; + logging::info("Async encoder teardown complete"); }}; encoder_teardown_thread.detach(); } @@ -2520,7 +2534,9 @@ namespace video { // set max frame time based on client-requested target framerate. double minimum_fps_target = (host.settings.video.minimum_fps_target > 0.0) ? host.settings.video.minimum_fps_target : (config.framerate / 2); std::chrono::duration max_frametime {1000.0 / minimum_fps_target}; - BOOST_LOG(info) << "Minimum FPS target set to ~"sv << minimum_fps_target << "fps ("sv << max_frametime.count() << "ms)"sv; + logging::info([&](std::ostream &out) { + out << "Minimum FPS target set to ~"sv << minimum_fps_target << "fps ("sv << max_frametime.count() << "ms)"sv; + }); auto shutdown_event = mail->event(mail::shutdown); auto packets = host.mail->queue(mail::video_packets); @@ -2563,7 +2579,7 @@ namespace video { if (auto img = images->pop(max_frametime)) { frame_timestamp = img->frame_timestamp; if (session->convert(*img)) { - BOOST_LOG(error) << "Could not convert image"sv; + logging::error("Could not convert image"sv); return; } } else if (!images->running()) { @@ -2586,7 +2602,7 @@ namespace video { } if (encode(frame_nr++, *session, packets, channel_data, frame_timestamp)) { - BOOST_LOG(error) << "Could not encode video packet"sv; + logging::error("Could not encode video packet"sv); return; } @@ -2687,11 +2703,11 @@ namespace video { { auto encoder_name = encoder.codec_from_config(config).name; - BOOST_LOG(info) << "Creating encoder " << logging::bracket(encoder_name); + logging::info("Creating encoder [{}]", encoder_name); - BOOST_LOG(info) << "Color coding: " << colorspace_to_string(colorspace.colorspace); - BOOST_LOG(info) << "Color depth: " << colorspace.bit_depth << "-bit"; - BOOST_LOG(info) << "Color range: " << (colorspace.full_range ? "JPEG" : "MPEG"); + logging::info("Color coding: {}", colorspace_to_string(colorspace.colorspace)); + logging::info("Color depth: {}-bit", colorspace.bit_depth); + logging::info("Color range: {}", (colorspace.full_range ? "JPEG" : "MPEG")); } if (dynamic_cast(encoder.platform_formats.get())) { @@ -2736,7 +2752,7 @@ namespace video { if (disp->get_hdr_metadata(hdr_info->metadata)) { hdr_info->enabled = true; } else { - BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; + logging::error("Couldn't get display hdr metadata when colorspace selection indicates it should have one"); } } ctx.hdr_events->raise(std::move(hdr_info)); @@ -2748,7 +2764,7 @@ namespace video { // Load the initial image to prepare for encoding if (session->convert(img)) { - BOOST_LOG(error) << "Could not convert initial image"sv; + logging::error("Could not convert initial image"sv); return std::nullopt; } @@ -2862,7 +2878,7 @@ namespace video { } if (frame_captured && pos->session->convert(*img)) { - BOOST_LOG(error) << "Could not convert image"sv; + logging::error("Could not convert image"sv); ctx->shutdown_event->raise(true); continue; @@ -2874,7 +2890,7 @@ namespace video { } if (encode(ctx->frame_nr++, *pos->session, ctx->packets, ctx->channel_data, frame_timestamp)) { - BOOST_LOG(error) << "Could not encode video packet"sv; + logging::error("Could not encode video packet"sv); ctx->shutdown_event->raise(true); continue; @@ -3015,7 +3031,7 @@ namespace video { if (display->get_hdr_metadata(hdr_info->metadata)) { hdr_info->enabled = true; } else { - BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one"; + logging::error("Couldn't get display hdr metadata when colorspace selection indicates it should have one"); } } hdr_event->raise(std::move(hdr_info)); @@ -3106,7 +3122,7 @@ namespace video { auto packet = packets->pop(); if (!packet->is_idr()) { - BOOST_LOG(error) << "First packet type is not an IDR frame"sv; + logging::error("First packet type is not an IDR frame"sv); return -1; } @@ -3139,9 +3155,9 @@ namespace video { const auto output_name {host.displays.map_output_name(host.settings.video.output_name)}; std::shared_ptr disp; - BOOST_LOG(info) << "Trying encoder ["sv << encoder.name << ']'; + logging::info("Trying encoder [{}]", encoder.name); auto fg = util::fail_guard([&]() { - BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] failed"sv; + logging::info("Encoder [{}] failed", encoder.name); }); auto test_hevc = host.probed.active_hevc_mode >= 2 || (host.probed.active_hevc_mode == 0 && !(encoder.flags & H264_ONLY)); @@ -3162,7 +3178,7 @@ namespace video { } if (!disp->is_codec_supported(encoder.h264.name, config_autoselect)) { fg.disable(); - BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] is not supported on this GPU"sv; + logging::info("Encoder [{}] is not supported on this GPU", encoder.name); return false; } @@ -3208,7 +3224,7 @@ namespace video { encoder.hevc[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_hevc >= 0; encoder.hevc[encoder_t::PASSED] = max_ref_frames_hevc >= 0 || autoselect_hevc >= 0; } else { - BOOST_LOG(info) << "Encoder ["sv << encoder.hevc.name << "] is not supported on this GPU"sv; + logging::info("Encoder [{}] is not supported on this GPU", encoder.hevc.name); encoder.hevc.capabilities.reset(); } } else { @@ -3236,7 +3252,7 @@ namespace video { encoder.av1[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_av1 >= 0; encoder.av1[encoder_t::PASSED] = max_ref_frames_av1 >= 0 || autoselect_av1 >= 0; } else { - BOOST_LOG(info) << "Encoder ["sv << encoder.av1.name << "] is not supported on this GPU"sv; + logging::info("Encoder [{}] is not supported on this GPU", encoder.av1.name); encoder.av1.capabilities.reset(); } } else { @@ -3323,10 +3339,10 @@ namespace video { encoder.hevc[encoder_t::VUI_PARAMETERS] = encoder.hevc[encoder_t::VUI_PARAMETERS] && !host.settings.sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE]; if (!encoder.h264[encoder_t::VUI_PARAMETERS]) { - BOOST_LOG(warning) << encoder.name << ": h264 missing sps->vui parameters"sv; + logging::warning("{}: h264 missing sps->vui parameters", encoder.name); } if (encoder.hevc[encoder_t::PASSED] && !encoder.hevc[encoder_t::VUI_PARAMETERS]) { - BOOST_LOG(warning) << encoder.name << ": hevc missing sps->vui parameters"sv; + logging::warning("{}: hevc missing sps->vui parameters", encoder.name); } fg.disable(); @@ -3366,16 +3382,16 @@ namespace video { auto adjust_encoder_constraints_hevc = [&](encoder_t *encoder) { // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support if (host.probed.active_hevc_mode == 5 && !encoder->hevc[encoder_t::DYNAMIC_RANGE] && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 Rext10_444 on this system"sv; + logging::warning("Encoder [{}] does not support HEVC Main10 Rext10_444 on this system", encoder->name); host.probed.active_hevc_mode = 0; } else if (host.probed.active_hevc_mode == 4 && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Rext10_444 on this system"sv; + logging::warning("Encoder [{}] does not support HEVC Rext10_444 on this system", encoder->name); host.probed.active_hevc_mode = 0; } else if (host.probed.active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 on this system"sv; + logging::warning("Encoder [{}] does not support HEVC Main10 on this system", encoder->name); host.probed.active_hevc_mode = 0; } else if (host.probed.active_hevc_mode == 2 && !encoder->hevc[encoder_t::PASSED]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC on this system"sv; + logging::warning("Encoder [{}] does not support HEVC on this system", encoder->name); host.probed.active_hevc_mode = 0; } }; @@ -3383,16 +3399,16 @@ namespace video { auto adjust_encoder_constraints_av1 = [&](encoder_t *encoder) { // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support if (host.probed.active_av1_mode == 5 && !encoder->av1[encoder_t::DYNAMIC_RANGE] && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 Rext10_444 on this system"sv; + logging::warning("Encoder [{}] does not support AV1 Main10 Rext10_444 on this system", encoder->name); host.probed.active_av1_mode = 0; } else if (host.probed.active_av1_mode == 4 && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Rext10_444 on this system"sv; + logging::warning("Encoder [{}] does not support AV1 Rext10_444 on this system", encoder->name); host.probed.active_av1_mode = 0; } else if (host.probed.active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 on this system"sv; + logging::warning("Encoder [{}] does not support AV1 Main10 on this system", encoder->name); host.probed.active_av1_mode = 0; } else if (host.probed.active_av1_mode == 2 && !encoder->av1[encoder_t::PASSED]) { - BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 on this system"sv; + logging::warning("Encoder [{}] does not support AV1 on this system", encoder->name); host.probed.active_av1_mode = 0; } }; @@ -3421,11 +3437,11 @@ namespace video { }); if (host.chosen_encoder == nullptr) { - BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << host.settings.video.encoder << ']'; + logging::error("Couldn't find any working encoder matching [{}]", host.settings.video.encoder); } } - BOOST_LOG(info) << "// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv; + logging::info("// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv); // If we haven't found an encoder yet, but we want one with specific codec support, search for that now. if (host.chosen_encoder == nullptr && (host.probed.active_hevc_mode >= 2 || host.probed.active_av1_mode >= 2)) { @@ -3467,7 +3483,7 @@ namespace video { }); if (host.chosen_encoder == nullptr) { - BOOST_LOG(error) << "Couldn't find any working encoder that meets HEVC/AV1 requirements"sv; + logging::error("Couldn't find any working encoder that meets HEVC/AV1 requirements"sv); } } @@ -3496,18 +3512,18 @@ namespace video { if (host.chosen_encoder == nullptr) { const auto output_name {host.displays.map_output_name(host.settings.video.output_name)}; - BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv; + logging::fatal("Unable to find display or encoder during startup."sv); if (!host.settings.video.adapter_name.empty() || !output_name.empty()) { - BOOST_LOG(fatal) << "Please ensure your manually chosen GPU and monitor are connected and powered on."sv; + logging::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; + logging::fatal("Please check that a display is connected and powered on."sv); } return -1; } - BOOST_LOG(info); - BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant. //"sv; - BOOST_LOG(info); + logging::info(""sv); + logging::info("// Ignore any errors mentioned above, they are not relevant. //"sv); + logging::info(""sv); auto &encoder = *host.chosen_encoder; @@ -3519,34 +3535,40 @@ namespace video { host.probed.yuv444[2] = encoder.av1[encoder_t::PASSED] && encoder.av1[encoder_t::YUV444]; - BOOST_LOG(debug) << "------ h264 ------"sv; + logging::debug("------ h264 ------"sv); for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = static_cast(x); - BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv); + logging::debug([&](std::ostream &out) { + out << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv); + }); } - BOOST_LOG(debug) << "-------------------"sv; - BOOST_LOG(info) << "Found H.264 encoder: "sv << encoder.h264.name << " ["sv << encoder.name << ']'; + logging::debug("-------------------"sv); + logging::info("Found H.264 encoder: {} [{}]", encoder.h264.name, encoder.name); if (encoder.hevc[encoder_t::PASSED]) { - BOOST_LOG(debug) << "------ hevc ------"sv; + logging::debug("------ hevc ------"sv); for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = static_cast(x); - BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv); + logging::debug([&](std::ostream &out) { + out << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv); + }); } - BOOST_LOG(debug) << "-------------------"sv; + logging::debug("-------------------"sv); - BOOST_LOG(info) << "Found HEVC encoder: "sv << encoder.hevc.name << " ["sv << encoder.name << ']'; + logging::info("Found HEVC encoder: {} [{}]", encoder.hevc.name, encoder.name); } if (encoder.av1[encoder_t::PASSED]) { - BOOST_LOG(debug) << "------ av1 ------"sv; + logging::debug("------ av1 ------"sv); for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { auto flag = static_cast(x); - BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv); + logging::debug([&](std::ostream &out) { + out << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv); + }); } - BOOST_LOG(debug) << "-------------------"sv; + logging::debug("-------------------"sv); - BOOST_LOG(info) << "Found AV1 encoder: "sv << encoder.av1.name << " ["sv << encoder.name << ']'; + logging::info("Found AV1 encoder: {} [{}]", encoder.av1.name, encoder.name); } // 2 - passed @@ -3565,7 +3587,7 @@ namespace video { host.probed.active_hevc_mode += 2; } } - BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_HEVC_MODE: "sv << host.probed.active_hevc_mode; + logging::debug("ENCODER STATUS ACTIVE_HEVC_MODE: {}", host.probed.active_hevc_mode); } if (host.probed.active_av1_mode == 0) { @@ -3579,7 +3601,7 @@ namespace video { host.probed.active_av1_mode += 2; } } - BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_AV1_MODE: "sv << host.probed.active_av1_mode; + logging::debug("ENCODER STATUS ACTIVE_AV1_MODE: {}", host.probed.active_av1_mode); } return 0; @@ -3608,7 +3630,9 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device.empty() ? nullptr : render_device.c_str(), nullptr, 0); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to create a VAAPI device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to create a VAAPI device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } @@ -3636,7 +3660,7 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VULKAN, render_device.c_str(), nullptr, 0); if (status >= 0) { - BOOST_LOG(info) << "Using Vulkan device: "sv << render_device; + logging::info("Using Vulkan device: {}", render_device); return hw_device_buf; } @@ -3645,12 +3669,12 @@ namespace video { for (auto device : devices) { status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VULKAN, device, nullptr, 0); if (status >= 0) { - BOOST_LOG(info) << "Using Vulkan device index: "sv << device; + logging::info("Using Vulkan device index: {}", device); return hw_device_buf; } } - BOOST_LOG(error) << "Failed to create a Vulkan device"sv; + logging::error("Failed to create a Vulkan device"sv); return -1; } #endif @@ -3664,7 +3688,9 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to create a CUDA device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to create a CUDA device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } @@ -3680,7 +3706,9 @@ namespace video { auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, nullptr, nullptr, 0); if (status < 0) { std::array string; - BOOST_LOG(error) << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + logging::error([&](std::ostream &out) { + out << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string.data(), AV_ERROR_MAX_STRING_SIZE, status); + }); return -1; } @@ -3718,7 +3746,9 @@ namespace video { auto err = av_hwdevice_ctx_init(ctx_buf.get()); if (err) { std::array err_str {0}; - BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + logging::error([&](std::ostream &out) { + out << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str.data(), AV_ERROR_MAX_STRING_SIZE, err); + }); return err; } diff --git a/src/video.h b/src/video.h index 2a368298f..ea82fbd08 100644 --- a/src/video.h +++ b/src/video.h @@ -420,7 +420,7 @@ namespace video { const codec_t &codec_from_config(const config_t &config) const { switch (config.videoFormat) { default: - BOOST_LOG(error) << "Unknown video format " << config.videoFormat << ", falling back to H.264"; + logging::error("Unknown video format {}, falling back to H.264", config.videoFormat); // fallthrough case 0: return h264; diff --git a/src/video_colorspace.cpp b/src/video_colorspace.cpp index a8f23f482..dcc511948 100644 --- a/src/video_colorspace.cpp +++ b/src/video_colorspace.cpp @@ -73,7 +73,7 @@ namespace video { break; default: - BOOST_LOG(error) << "Unknown video colorspace in csc, falling back to Rec. 709"; + logging::error("Unknown video colorspace in csc, falling back to Rec. 709"); colorspace.colorspace = rec709; break; } @@ -91,13 +91,13 @@ namespace video { break; default: - BOOST_LOG(error) << "Unknown dynamicRange value, falling back to 10-bit color depth"; + logging::error("Unknown dynamicRange value, falling back to 10-bit color depth"); colorspace.bit_depth = 10; break; } if (colorspace.colorspace == bt2020sdr && colorspace.bit_depth != 10) { - BOOST_LOG(error) << "BT.2020 SDR colorspace expects 10-bit color depth, falling back to Rec. 709"; + logging::error("BT.2020 SDR colorspace expects 10-bit color depth, falling back to Rec. 709"); colorspace.colorspace = rec709; } diff --git a/tests/integration/test_external_commands.cpp b/tests/integration/test_external_commands.cpp index adf730a90..f925fa0e1 100644 --- a/tests/integration/test_external_commands.cpp +++ b/tests/integration/test_external_commands.cpp @@ -126,14 +126,14 @@ TEST_P(ExternalCommandTest, RunExternalCommand) { // Use the xfail condition and reason from test data XFAIL_IF(xfail_condition, xfail_reason); - BOOST_LOG(info) << "Running external command test: " << description; - BOOST_LOG(debug) << "Command: " << command; + logging::info("Running external command test: {}", description); + logging::debug("Command: {}", command); auto [exit_code, output] = runCommand(command, working_directory); - BOOST_LOG(debug) << "Command exit code: " << exit_code; + logging::debug("Command exit code: {}", exit_code); if (!output.empty()) { - BOOST_LOG(debug) << "Command output: " << output; + logging::debug("Command output: {}", output); } if (should_succeed) { diff --git a/tests/tests_common.h b/tests/tests_common.h index 3dcb39e09..de499630d 100644 --- a/tests/tests_common.h +++ b/tests/tests_common.h @@ -57,12 +57,12 @@ namespace test_utils { if (test_passed) { // XPass: Test was expected to fail but passed const std::string message = "XPASS: Test unexpectedly passed (expected to fail: " + marker.reason + ")"; - BOOST_LOG(warning) << message; + logging::warning(message); GTEST_SKIP() << "XPASS: Test unexpectedly passed (expected to fail: " << marker.reason << ")"; } else { // XFail: Test failed as expected const std::string message = "XFAIL: Test failed as expected (" + marker.reason + ")"; - BOOST_LOG(info) << message; + logging::info(message); GTEST_SKIP() << "XFAIL: " << marker.reason; } } @@ -80,7 +80,7 @@ namespace test_utils { inline bool checkEqual(const T1 &actual, const T2 &expected, const std::string &message = "") { bool result = (actual == expected); if (!message.empty()) { - BOOST_LOG(debug) << "Assertion check: " << message << " - " << (result ? "PASSED" : "FAILED"); + logging::debug("Assertion check: {} - {}", message, (result ? "PASSED" : "FAILED")); } return result; } @@ -96,7 +96,7 @@ namespace test_utils { inline bool checkNotEqual(const T1 &actual, const T2 &expected, const std::string &message = "") { const bool result = (actual != expected); if (!message.empty()) { - BOOST_LOG(debug) << "Assertion check: " << message << " - " << (result ? "PASSED" : "FAILED"); + logging::debug("Assertion check: {} - {}", message, (result ? "PASSED" : "FAILED")); } return result; } diff --git a/tests/tests_events.h b/tests/tests_events.h index 432fb336e..04f33561b 100644 --- a/tests/tests_events.h +++ b/tests/tests_events.h @@ -7,40 +7,95 @@ // test includes #include "tests_common.h" -struct SunshineEventListener: BufferedTestEventListener { - SunshineEventListener() { - sink = boost::make_shared(); - sink_buffer = boost::make_shared(); - sink->locked_backend()->add_stream(sink_buffer); - sink->set_formatter(&logging::formatter); - } +// standard includes +#include +#include +#include +/** + * @brief Buffer Sunshine logs and test events while the test program runs. + */ +struct SunshineEventListener: BufferedTestEventListener { + /** + * @brief Register the synchronous sink for the test program. + * @param unit_test Test program whose events are being buffered. + */ void OnTestProgramStart(const testing::UnitTest &unit_test) override { static_cast(unit_test); - boost::log::core::get()->add_sink(sink); + sink_owner = logging::add_sink(sink, 0, false); } + /** + * @brief Remove the sink when the test program finishes. + * @param unit_test Test program whose logging registration is ending. + */ void OnTestProgramEnd(const testing::UnitTest &unit_test) override { static_cast(unit_test); - boost::log::core::get()->remove_sink(sink); + sink_owner.reset(); } protected: + /** + * @brief Emit a test event through the application logging API. + * @param message Test event text to buffer. + */ void logTestEvent(const std::string &message) override { - BOOST_LOG(tests) << message; + logging::tests(message); } + /** + * @brief Read the buffered output for the current test. + * @return Formatted log output collected by the listener. + */ [[nodiscard]] std::string bufferedTestOutput() const override { - return sink_buffer->str(); + return sink->output(); } + /** + * @brief Clear output collected for the preceding test. + */ void clearBufferedTestOutput() override { - sink_buffer->str(""); - sink_buffer->clear(); + sink->clear(); } private: - using sink_t = boost::log::sinks::synchronous_sink; - boost::shared_ptr sink; - boost::shared_ptr sink_buffer; + /** + * @brief Collect formatted records independently of the logging backend. + */ + class buffering_sink_t final: public logging::sink_t { + public: + /** + * @brief Append a log record to the synchronized output buffer. + * @param message Completed record to format and retain. + */ + void consume(const logging::message_t &message) override { + std::lock_guard lock {mutex}; + buffer += logging::format_message(message); + buffer += '\n'; + } + + /** + * @brief Obtain a consistent copy of buffered records. + * @return Formatted log lines retained by the sink. + */ + [[nodiscard]] std::string output() const { + std::lock_guard lock {mutex}; + return buffer; + } + + /** + * @brief Discard previously buffered records. + */ + void clear() { + std::lock_guard lock {mutex}; + buffer.clear(); + } + + private: + mutable std::mutex mutex; ///< Protects output against concurrent application logging. + std::string buffer; ///< Formatted records for the current test. + }; + + std::shared_ptr sink {std::make_shared()}; ///< Sink receiving test and application records. + std::unique_ptr sink_owner; ///< Registration removed before the sink is destroyed. }; diff --git a/tests/unit/test_logging.cpp b/tests/unit/test_logging.cpp index 834ac9202..f9e12e22c 100644 --- a/tests/unit/test_logging.cpp +++ b/tests/unit/test_logging.cpp @@ -8,26 +8,30 @@ #include "../tests_log_checker.h" // standard includes +#include #include #include #include #include #include +#include #include #include #include +#include +#include // local includes #include namespace { std::array log_levels = { - std::tuple("verbose", &verbose), - std::tuple("debug", &debug), - std::tuple("info", &info), - std::tuple("warning", &warning), - std::tuple("error", &error), - std::tuple("fatal", &fatal), + std::tuple("verbose", logging::level_e::verbose), + std::tuple("debug", logging::level_e::debug), + std::tuple("info", logging::level_e::info), + std::tuple("warning", logging::level_e::warning), + std::tuple("error", logging::level_e::error), + std::tuple("fatal", logging::level_e::fatal), }; constexpr auto log_file = "test_sunshine.log"; @@ -140,14 +144,12 @@ INSTANTIATE_TEST_SUITE_P( ); TEST_P(LogLevelsTest, PutMessage) { - auto [label, plogger] = GetParam(); - ASSERT_TRUE(plogger); - auto &logger = *plogger; + auto [label, level] = GetParam(); std::random_device rand_dev; std::mt19937_64 rand_gen(rand_dev()); auto test_message = std::format("{}{}", rand_gen(), rand_gen()); - BOOST_LOG(logger) << test_message; + logging::log(level, test_message); ASSERT_TRUE(log_checker::line_contains(log_file, test_message)); } @@ -157,13 +159,13 @@ TEST_F(LogRotationTest, LoggingOwnerRemovesOnlyItsOwnSink) { auto first = logging::init(0, log_path.string()); auto second = logging::init(0, second_path.string()); - BOOST_LOG(info) << "both sinks receive this record"; + logging::info("both sinks receive this record"); logging::log_flush(); EXPECT_NE(read_log_file(log_path).find("both sinks receive this record"), std::string::npos); EXPECT_NE(read_log_file(second_path).find("both sinks receive this record"), std::string::npos); first.reset(); - BOOST_LOG(info) << "remaining sink receives this record"; + logging::info("remaining sink receives this record"); logging::log_flush(); EXPECT_EQ(read_log_file(log_path).find("remaining sink receives this record"), std::string::npos); EXPECT_NE(read_log_file(second_path).find("remaining sink receives this record"), std::string::npos); @@ -175,7 +177,7 @@ TEST_F(LogRotationTest, ManagedLoggerAcceptsConcurrentWriters) { for (int writer = 0; writer < 4; ++writer) { writers.emplace_back([writer]() { for (int record = 0; record < 20; ++record) { - BOOST_LOG(info) << std::format("writer {} record {}", writer, record); + logging::info("writer {} record {}", writer, record); } }); } @@ -191,19 +193,15 @@ TEST_F(LogRotationTest, ManagedLoggerAcceptsConcurrentWriters) { } TEST_F(BaseTest, RejectsUnsupportedLoggerSeverity) { - EXPECT_THROW(logging::logger_t {99}.get(), std::invalid_argument); + EXPECT_THROW(logging::log(static_cast(99), "invalid severity"), std::invalid_argument); } /** - * @brief Runtime severity handles preserve test logging across shared production objects. + * @brief Runtime test severity preserves logging across shared production objects. */ TEST_F(LogRotationTest, ManagedLoggerPreservesRuntimeTestSeverity) { auto owner = logging::init(0, log_path.string()); - const auto severity = tests.get().default_severity(); - const logging::logger_t logger {severity}; - - EXPECT_EQ(&logger.get(), &logging::tests_source::get()); - BOOST_LOG(logger) << "runtime test severity is accepted"; + logging::log(logging::test_level, "runtime test severity is accepted"); EXPECT_TRUE(log_checker::line_equals(log_path.string(), "Tests: runtime test severity is accepted")); } diff --git a/tests/unit/test_logging_api.cpp b/tests/unit/test_logging_api.cpp new file mode 100644 index 000000000..ecf8a6a99 --- /dev/null +++ b/tests/unit/test_logging_api.cpp @@ -0,0 +1,772 @@ +/** + * @file tests/unit/test_logging_api.cpp + * @brief Tests for Sunshine logging functions and independently owned sinks. + */ + +// test includes +#include + +// standard includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// lib includes +#include + +// local includes +#include "src/logging.h" + +// conditional includes +#ifndef __ANDROID__ + #include + +extern "C" { + #include +} +#endif + +namespace { + /** + * @brief A delivered message and the thread that consumed it. + */ + struct delivery_t { + logging::message_t message; ///< Immutable message supplied to the sink. + std::thread::id thread; ///< Thread executing the sink callback. + }; + + /** + * @brief Record sink deliveries without depending on the logging backend. + */ + class recording_sink_t final: public logging::sink_t { + public: + /** + * @brief Copy an accepted message for later assertions. + * + * @param message Message accepted by this sink. + */ + void consume(const logging::message_t &message) override { + std::lock_guard lock {mutex_}; + deliveries_.push_back({message, std::this_thread::get_id()}); + delivered_.notify_all(); + } + + /** + * @brief Wait for normal asynchronous delivery before explicitly flushing. + * @param count Minimum number of recorded messages. + * @return True when the expected messages arrived before the timeout. + */ + bool wait_for_messages(std::size_t count) { + std::unique_lock lock {mutex_}; + return delivered_.wait_for(lock, std::chrono::seconds {5}, [this, count]() { + return deliveries_.size() >= count; + }); + } + + /** + * @brief Read a coherent snapshot after synchronous delivery or flushing. + * + * @return Recorded messages and callback threads. + */ + std::vector snapshot() const { + std::lock_guard lock {mutex_}; + return deliveries_; + } + + private: + mutable std::mutex mutex_; ///< Protects deliveries from asynchronous callbacks. + std::condition_variable delivered_; ///< Signals completed asynchronous deliveries. + std::vector deliveries_; ///< Copies of accepted records. + }; + + /** + * @brief Fail the first delivery and record subsequent deliveries. + */ + class failing_sink_t final: public logging::sink_t { + public: + /** + * @brief Simulate a transient backend failure before accepting later messages. + * + * @param message Message accepted by this sink. + */ + void consume(const logging::message_t &message) override { + if (attempts_.fetch_add(1) == 0) { + throw std::runtime_error {"transient sink failure"}; + } + accepted_.consume(message); + } + + /** + * @brief Count attempted deliveries including the failed delivery. + * + * @return Number of callbacks executed. + */ + int attempts() const { + return attempts_.load(); + } + + /** + * @brief Read messages delivered after the transient failure. + * + * @return Successfully accepted records. + */ + std::vector snapshot() const { + return accepted_.snapshot(); + } + + private: + std::atomic attempts_ {0}; ///< Counts callbacks safely on either delivery thread. + recording_sink_t accepted_; ///< Records callbacks after the first failure. + }; + + /** + * @brief Hold the first asynchronous delivery while more records are queued. + */ + class gated_sink_t final: public logging::sink_t { + public: + /** + * @brief Bind a release signal used to unblock the consumer. + * + * @param release Signal that allows delivery to continue. + */ + explicit gated_sink_t(std::shared_future release): + release_ {std::move(release)}, + started_ {started_signal_.get_future().share()} { + } + + /** + * @brief Wait on the first callback and record every accepted message. + * + * @param message Message accepted by this sink. + */ + void consume(const logging::message_t &message) override { + if (!first_started_.exchange(true)) { + started_signal_.set_value(); + release_.wait(); + } + accepted_.consume(message); + } + + /** + * @brief Obtain the signal indicating that the consumer is blocked. + * + * @return Signal set by the first delivery callback. + */ + std::shared_future started() const { + return started_; + } + + /** + * @brief Read delivered records after the consumer has been released. + * + * @return Successfully delivered records. + */ + std::vector snapshot() const { + return accepted_.snapshot(); + } + + private: + std::shared_future release_; ///< Signal unblocking the first callback. + std::promise started_signal_; ///< Signals entry into the first callback. + std::shared_future started_; ///< Allows the producer to await that callback. + std::atomic first_started_ {false}; ///< Ensures only the first callback waits. + recording_sink_t accepted_; ///< Stores all delivered messages in order. + }; + + /** + * @brief A custom value supported by both streaming and standard formatting. + */ + struct custom_value_t { + std::string_view text; ///< Text emitted by the custom formatters. + int *formats = nullptr; ///< Optional counter for standard formatter invocations. + }; + + /** + * @brief Stream a custom value through a lazy logging callback. + * + * @param out Stream receiving the value. + * @param value Custom value to print. + * @return The output stream. + */ + std::ostream &operator<<(std::ostream &out, const custom_value_t &value) { + return out << value.text; + } +} // namespace + +/** + * @brief Format a custom test value with the standard string formatting options. + */ +template<> +struct std::formatter: std::formatter { + /** + * @brief Delegate formatting of the custom value to its text. + * + * @tparam FormatContext Type of the destination formatting context. + * @param value Custom value to print. + * @param context Destination and formatting state. + * @return Iterator after the formatted value. + */ + template + auto format(const custom_value_t &value, FormatContext &context) const { + if (value.formats) { + ++*value.formats; + } + return std::formatter::format(value.text, context); + } +}; + +namespace { + /** + * @brief Named severity functions and the metadata expected from their overloads. + */ + struct severity_case_t { + logging::level_e level; ///< Expected message severity. + std::string_view label; ///< Severity label used by the text formatter. + void (*emit)(); ///< Emits text, lazy-stream, and standard-format messages. + }; + + const std::array severity_cases { + severity_case_t {logging::level_e::verbose, "Verbose", []() { + logging::verbose("literal {braces}"); + logging::verbose([](std::ostream &out) { + out << "stream"; + }); + logging::verbose("formatted {}", 17); + }}, + severity_case_t {logging::level_e::debug, "Debug", []() { + logging::debug("literal {braces}"); + logging::debug([](std::ostream &out) { + out << "stream"; + }); + logging::debug("formatted {}", 17); + }}, + severity_case_t {logging::level_e::info, "Info", []() { + logging::info("literal {braces}"); + logging::info([](std::ostream &out) { + out << "stream"; + }); + logging::info("formatted {}", 17); + }}, + severity_case_t {logging::level_e::warning, "Warning", []() { + logging::warning("literal {braces}"); + logging::warning([](std::ostream &out) { + out << "stream"; + }); + logging::warning("formatted {}", 17); + }}, + severity_case_t {logging::level_e::error, "Error", []() { + logging::error("literal {braces}"); + logging::error([](std::ostream &out) { + out << "stream"; + }); + logging::error("formatted {}", 17); + }}, + severity_case_t {logging::level_e::fatal, "Fatal", []() { + logging::fatal("literal {braces}"); + logging::fatal([](std::ostream &out) { + out << "stream"; + }); + logging::fatal("formatted {}", 17); + }}, + severity_case_t {logging::test_level, "Tests", []() { + logging::tests("literal {braces}"); + logging::tests([](std::ostream &out) { + out << "stream"; + }); + logging::tests("formatted {}", 17); + }}, + }; ///< All production severities and the linked test severity. + + /** + * @brief Check named logging overloads and text formatting at each severity. + */ + class LoggingSeverityTest: public testing::TestWithParam {}; + + /** + * @brief Check sink behavior with both synchronous and asynchronous delivery. + */ + class LoggingSinkTest: public testing::TestWithParam {}; +} // namespace + +/** + * @brief Every named severity function forwards all three supported message forms. + */ +TEST_P(LoggingSeverityTest, NamedFunctionsPreserveSeverityAndMessageForms) { + const auto test_case = GetParam(); + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + + EXPECT_TRUE(logging::is_enabled(test_case.level)); + test_case.emit(); + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 3U); + EXPECT_EQ(messages[0].message.text, "literal {braces}"); + EXPECT_EQ(messages[1].message.text, "stream"); + EXPECT_EQ(messages[2].message.text, "formatted 17"); + for (const auto &delivery : messages) { + EXPECT_EQ(delivery.message.level, test_case.level); + EXPECT_EQ(delivery.thread, std::this_thread::get_id()); + } +} + +/** + * @brief Formatting uses the supplied timestamp and severity without adding a newline. + */ +TEST_P(LoggingSeverityTest, FormatsSuppliedMetadataAndPreservesMessageText) { + std::tm local_time {}; + local_time.tm_year = 124; + local_time.tm_mon = 0; + local_time.tm_mday = 2; + local_time.tm_hour = 3; + local_time.tm_min = 4; + local_time.tm_sec = 5; + local_time.tm_isdst = -1; + const auto timestamp = std::chrono::system_clock::from_time_t(std::mktime(&local_time)) + std::chrono::milliseconds {123}; + const logging::message_t message {GetParam().level, timestamp, "first line\nsecond line"}; + + EXPECT_EQ(logging::format_message(message), std::format("[2024-01-02 03:04:05.123]: {}: first line\nsecond line", GetParam().label)); +} + +INSTANTIATE_TEST_SUITE_P(AllSeverities, LoggingSeverityTest, testing::ValuesIn(severity_cases)); + +/** + * @brief Rejected records do not invoke builders, and the scoped setting is restored. + */ +TEST(LoggingApiTest, RejectedRecordsDoNotEvaluateLazyBuilders) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + int calls = 0; + int formats = 0; + { + logging::testing::scoped_disable_t disabled; + EXPECT_FALSE(logging::is_enabled(logging::level_e::info)); + logging::log(logging::level_e::info, [&](std::ostream &out) { + ++calls; + out << "filtered generic message"; + }); + logging::info([&](std::ostream &out) { + ++calls; + out << "filtered named message"; + }); + logging::log(logging::level_e::info, "filtered text"); + logging::log(logging::level_e::info, "{}", custom_value_t {"filtered generic format", &formats}); + logging::info("{}", custom_value_t {"filtered named format", &formats}); + { + logging::testing::scoped_disable_t nested; + EXPECT_FALSE(logging::is_enabled(logging::level_e::info)); + } + EXPECT_FALSE(logging::is_enabled(logging::level_e::info)); + EXPECT_EQ(calls, 0); + EXPECT_EQ(formats, 0); + EXPECT_TRUE(sink->snapshot().empty()); + } + + EXPECT_TRUE(logging::is_enabled(logging::level_e::info)); + logging::info([&](std::ostream &out) { + ++calls; + out << "accepted after restoration"; + }); + EXPECT_EQ(calls, 1); + ASSERT_EQ(sink->snapshot().size(), 1U); + EXPECT_EQ(sink->snapshot().front().message.text, "accepted after restoration"); +} + +/** + * @brief Accepted builders execute once and preserve existing stream formatting. + */ +TEST(LoggingApiTest, LazyBuilderPreservesManipulatorsBoostFormatAndCustomValues) { + auto first = std::make_shared(); + auto second = std::make_shared(); + auto first_owner = logging::add_sink(first, 0, false); + auto second_owner = logging::add_sink(second, 0, false); + int calls = 0; + + logging::log(logging::level_e::info, [&](std::ostream &out) { + ++calls; + out << std::hex << std::setfill('0') << std::setw(4) << 42 << ' ' + << std::boolalpha << true << std::endl + << boost::format("%1%: %2%") % "Boost" % 7 << ' ' + << custom_value_t {"custom"}; + }); + + EXPECT_EQ(calls, 1); + ASSERT_EQ(first->snapshot().size(), 1U); + ASSERT_EQ(second->snapshot().size(), 1U); + EXPECT_EQ(first->snapshot().front().message.text, "002a true\nBoost: 7 custom"); + EXPECT_EQ(second->snapshot().front().message.text, first->snapshot().front().message.text); +} + +/** + * @brief Standard format arguments retain width, numeric, and user-defined formatting. + */ +TEST(LoggingApiTest, StandardFormatOverloadUsesTypedFormatting) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + + logging::log(logging::level_e::warning, "{:04x} {:.2f} {:>8}", 42, 1.25, custom_value_t {"custom"}); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 1U); + EXPECT_EQ(messages.front().message.level, logging::level_e::warning); + EXPECT_EQ(messages.front().message.text, "002a 1.25 custom"); +} + +/** + * @brief A throwing builder discards partial text without disabling subsequent records. + */ +TEST(LoggingApiTest, BuilderExceptionDoesNotPublishPartialMessage) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + + EXPECT_THROW(logging::info([](std::ostream &out) { + out << "partial text that must be discarded"; + throw std::runtime_error {"builder failure"}; + }), + std::runtime_error); + EXPECT_TRUE(sink->snapshot().empty()); + + logging::info("record after builder failure"); + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 1U); + EXPECT_EQ(messages.front().message.text, "record after builder failure"); +} + +/** + * @brief All sinks receive one message timestamp while keeping their delivery policy. + */ +TEST(LoggingApiTest, SynchronousAndAsynchronousSinksReceiveIdenticalMetadata) { + auto synchronous = std::make_shared(); + auto asynchronous = std::make_shared(); + auto synchronous_owner = logging::add_sink(synchronous, 0, false); + auto asynchronous_owner = logging::add_sink(asynchronous); + const auto before = std::chrono::system_clock::now(); + + logging::error("shared message metadata"); + const auto after = std::chrono::system_clock::now(); + ASSERT_TRUE(asynchronous->wait_for_messages(1)); + logging::log_flush(); + + const auto immediate = synchronous->snapshot(); + const auto deferred = asynchronous->snapshot(); + ASSERT_EQ(immediate.size(), 1U); + ASSERT_EQ(deferred.size(), 1U); + EXPECT_EQ(immediate.front().message.level, logging::level_e::error); + EXPECT_EQ(deferred.front().message.level, immediate.front().message.level); + EXPECT_EQ(deferred.front().message.text, immediate.front().message.text); + EXPECT_EQ(deferred.front().message.timestamp, immediate.front().message.timestamp); + EXPECT_GE(immediate.front().message.timestamp, before); + EXPECT_LE(immediate.front().message.timestamp, after); + EXPECT_EQ(immediate.front().thread, std::this_thread::get_id()); + EXPECT_NE(deferred.front().thread, std::this_thread::get_id()); +} + +/** + * @brief Each sink filters independently without preventing other sinks from receiving. + */ +TEST(LoggingApiTest, SinkMinimumSeverityOnlyFiltersThatSink) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, static_cast(logging::level_e::warning), false); + + logging::verbose("filtered verbose"); + logging::info("filtered info"); + logging::warning("accepted warning"); + logging::fatal("accepted fatal"); + logging::tests("accepted test severity"); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 3U); + EXPECT_EQ(messages[0].message.level, logging::level_e::warning); + EXPECT_EQ(messages[1].message.level, logging::level_e::fatal); + EXPECT_EQ(messages[2].message.level, logging::test_level); +} + +/** + * @brief Destroying one sink registration preserves independent sink registrations. + */ +TEST(LoggingApiTest, RemovingOneOwnerLeavesOtherSinksRegistered) { + auto first = std::make_shared(); + auto second = std::make_shared(); + auto first_owner = logging::add_sink(first, 0, false); + auto second_owner = logging::add_sink(second, 0, false); + + logging::info("both owners active"); + first_owner.reset(); + logging::info("second owner active"); + + ASSERT_EQ(first->snapshot().size(), 1U); + const auto remaining = second->snapshot(); + ASSERT_EQ(remaining.size(), 2U); + EXPECT_EQ(remaining[1].message.text, "second owner active"); +} + +/** + * @brief An asynchronous owner waits for its consumer and drains queued owned messages. + */ +TEST(LoggingApiTest, AsynchronousRemovalDrainsPendingMessages) { + std::promise release; + auto sink = std::make_shared(release.get_future().share()); + auto owner = logging::add_sink(sink); + logging::debug("queued {}", 0); + const auto started = sink->started().wait_for(std::chrono::seconds {5}); + EXPECT_EQ(started, std::future_status::ready); + if (started != std::future_status::ready) { + release.set_value(); + owner.reset(); + return; + } + + for (int index = 1; index < 32; ++index) { + auto text = std::format("queued {}", index); + logging::log(logging::level_e::debug, std::string_view {text}); + text.assign("producer buffer overwritten"); + } + + std::promise removed; + auto completion = removed.get_future(); + std::jthread remover {[owner = std::move(owner), &removed]() mutable { + owner.reset(); + removed.set_value(); + }}; + EXPECT_EQ(completion.wait_for(std::chrono::milliseconds {50}), std::future_status::timeout); + release.set_value(); + remover.join(); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 32U); + for (std::size_t index = 0; index < messages.size(); ++index) { + EXPECT_EQ(messages[index].message.text, std::format("queued {}", index)); + } +} + +/** + * @brief A registration retains its sink until queued work and ownership are released. + */ +TEST_P(LoggingSinkTest, OwnerRetainsSinkUntilRemoval) { + auto sink = std::make_shared(); + const std::weak_ptr retained = sink; + auto owner = logging::add_sink(sink, 0, GetParam()); + logging::info("sink is retained"); + logging::log_flush(); + ASSERT_EQ(sink->snapshot().size(), 1U); + + sink.reset(); + EXPECT_FALSE(retained.expired()); + owner.reset(); + EXPECT_TRUE(retained.expired()); +} + +/** + * @brief Suppressed backend exceptions do not stop future messages or other sinks. + */ +TEST_P(LoggingSinkTest, BackendExceptionDoesNotPreventLaterRecords) { + auto failing = std::make_shared(); + auto healthy = std::make_shared(); + auto failing_owner = logging::add_sink(failing, 0, GetParam()); + auto healthy_owner = logging::add_sink(healthy, 0, false); + + EXPECT_NO_THROW(logging::warning("first backend attempt fails")); + EXPECT_NO_THROW(logging::warning("later backend attempt succeeds")); + logging::log_flush(); + + EXPECT_EQ(failing->attempts(), 2); + const auto delivered = failing->snapshot(); + ASSERT_EQ(delivered.size(), 1U); + EXPECT_EQ(delivered.front().message.text, "later backend attempt succeeds"); + EXPECT_EQ(healthy->snapshot().size(), 2U); +} + +INSTANTIATE_TEST_SUITE_P(DeliveryPolicies, LoggingSinkTest, testing::Bool()); + +/** + * @brief Periodic integer samples retain integer extrema and a fractional average. + */ +TEST(LoggingApiTest, PeriodicIntegerLoggerPreservesFormattingAndReset) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + logging::min_max_avg_periodic_logger logger {logging::level_e::debug, "integer samples", "ms", std::chrono::seconds {0}}; + ASSERT_TRUE(logger.is_enabled()); + + logger.collect_and_log(7); + std::this_thread::sleep_for(std::chrono::milliseconds {5}); + logger.collect_and_log(std::function {[]() { + return 9; + }}); + logger.reset(); + logger.collect_and_log(10); + std::this_thread::sleep_for(std::chrono::milliseconds {5}); + logger.collect_and_log(12); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 2U); + EXPECT_EQ(messages[0].message.level, logging::level_e::debug); + EXPECT_EQ(messages[0].message.text, "integer samples (min/max/avg): 7ms/7ms/7.00ms"); + EXPECT_EQ(messages[1].message.text, "integer samples (min/max/avg): 10ms/10ms/10.00ms"); +} + +/** + * @brief Floating periodic samples preserve two fractional digits for every aggregate. + */ +TEST(LoggingApiTest, PeriodicFloatingLoggerPreservesTwoDecimalPlaces) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + logging::min_max_avg_periodic_logger logger {logging::level_e::debug, "floating samples", "ms", std::chrono::seconds {0}}; + + logger.collect_and_log(1.234); + std::this_thread::sleep_for(std::chrono::milliseconds {5}); + logger.collect_and_log(5.0); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 1U); + EXPECT_EQ(messages.front().message.text, "floating samples (min/max/avg): 1.23ms/1.23ms/1.23ms"); +} + +/** + * @brief Elapsed-time logging retains the millisecond units and caller-supplied points. + */ +TEST(LoggingApiTest, TimeDeltaLoggerPreservesElapsedMilliseconds) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + logging::time_delta_periodic_logger logger {logging::level_e::debug, "elapsed", std::chrono::seconds {0}}; + ASSERT_TRUE(logger.is_enabled()); + const auto start = std::chrono::steady_clock::now(); + + logger.first_point(start); + logger.second_point_and_log(start + std::chrono::microseconds {1250}); + std::this_thread::sleep_for(std::chrono::milliseconds {5}); + logger.second_point_and_log(start + std::chrono::microseconds {2500}); + logger.reset(); + logger.first_point_now(); + logger.second_point_now_and_log(); + + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), 1U); + EXPECT_EQ(messages.front().message.text, "elapsed (min/max/avg): 1.25ms/1.25ms/1.25ms"); +} + +/** + * @brief Disabled periodic loggers do not evaluate sample functions or emit records. + */ +TEST(LoggingApiTest, DisabledPeriodicLoggersDoNotEvaluateSamples) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + logging::testing::scoped_disable_t disabled; + logging::min_max_avg_periodic_logger samples {logging::level_e::debug, "disabled samples", "ms", std::chrono::seconds {0}}; + logging::time_delta_periodic_logger elapsed {logging::level_e::debug, "disabled elapsed", std::chrono::seconds {0}}; + int calls = 0; + + EXPECT_FALSE(samples.is_enabled()); + samples.collect_and_log(std::function {[&calls]() { + return ++calls; + }}); + samples.collect_and_log(1); + samples.reset(); + EXPECT_FALSE(elapsed.is_enabled()); + const auto point = std::chrono::steady_clock::now(); + elapsed.first_point(point); + elapsed.second_point_and_log(point + std::chrono::milliseconds {1}); + elapsed.first_point_now(); + elapsed.second_point_now_and_log(); + elapsed.reset(); + + EXPECT_EQ(calls, 0); + EXPECT_TRUE(sink->snapshot().empty()); +} + +#ifndef __ANDROID__ +/** + * @brief FFmpeg messages retain their mapped severity and text through the shared source. + */ +TEST(LoggingApiTest, FfmpegCallbackPreservesSeverityMapping) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + const auto previous_level = av_log_get_level(); + logging::setup_av_logging(0); + const std::array levels { + std::pair {AV_LOG_FATAL, logging::level_e::error}, + std::pair {AV_LOG_ERROR, logging::level_e::error}, + std::pair {AV_LOG_WARNING, logging::level_e::warning}, + std::pair {AV_LOG_INFO, logging::level_e::info}, + std::pair {AV_LOG_VERBOSE, logging::level_e::debug}, + std::pair {AV_LOG_DEBUG, logging::level_e::verbose}, + }; + for (std::size_t index = 0; index < levels.size(); ++index) { + av_log(nullptr, levels[index].first, "FFmpeg bridge %zu\n", index); + } + av_log_set_level(previous_level); + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), levels.size()); + for (std::size_t index = 0; index < levels.size(); ++index) { + EXPECT_EQ(messages[index].message.level, levels[index].second); + EXPECT_EQ(messages[index].message.text, std::format("FFmpeg bridge {}\n", index)); + } +} + +/** + * @brief libdisplaydevice messages preserve every severity while unknown levels are ignored. + */ +TEST(LoggingApiTest, DisplayDeviceCallbackPreservesSeverityMapping) { + auto sink = std::make_shared(); + auto owner = logging::add_sink(sink, 0, false); + using display_level_e = display_device::Logger::LogLevel; + auto &logger = display_device::Logger::get(); + const std::array levels { + std::pair {display_level_e::verbose, logging::level_e::verbose}, + std::pair {display_level_e::debug, logging::level_e::debug}, + std::pair {display_level_e::info, logging::level_e::info}, + std::pair {display_level_e::warning, logging::level_e::warning}, + std::pair {display_level_e::error, logging::level_e::error}, + std::pair {display_level_e::fatal, logging::level_e::fatal}, + }; + auto previous_level = display_level_e::fatal; + for (const auto &entry : levels) { + if (logger.isLogLevelEnabled(entry.first)) { + previous_level = entry.first; + break; + } + } + logging::setup_libdisplaydevice_logging(0); + for (std::size_t index = 0; index < levels.size(); ++index) { + logger.write(levels[index].first, std::format("Display device bridge {}", index)); + } + logger.write(static_cast(99), "unsupported display device severity"); + logger.setLogLevel(previous_level); + const auto messages = sink->snapshot(); + ASSERT_EQ(messages.size(), levels.size()); + for (std::size_t index = 0; index < levels.size(); ++index) { + EXPECT_EQ(messages[index].message.level, levels[index].second); + EXPECT_EQ(messages[index].message.text, std::format("Display device bridge {}", index)); + } +} +#endif + +/** + * @brief Null sinks and unsupported severity values fail before accepting records. + */ +TEST(LoggingApiTest, RejectsNullSinksAndInvalidSeverities) { + EXPECT_THROW(static_cast(logging::add_sink(std::shared_ptr {})), std::invalid_argument); + const auto invalid = static_cast(99); + EXPECT_THROW(logging::is_enabled(invalid), std::invalid_argument); + EXPECT_THROW(logging::log(invalid, "invalid text message"), std::invalid_argument); + EXPECT_THROW(logging::log(invalid, "invalid formatted {}", 1), std::invalid_argument); + int calls = 0; + EXPECT_THROW(logging::log(invalid, [&](std::ostream &) { + ++calls; + }), + std::invalid_argument); + EXPECT_EQ(calls, 0); + EXPECT_THROW(logging::format_message({invalid, std::chrono::system_clock::now(), "invalid format severity"}), std::invalid_argument); +} diff --git a/tests/unit/test_mouse.cpp b/tests/unit/test_mouse.cpp index 0dd09d698..5fa8b138b 100644 --- a/tests/unit/test_mouse.cpp +++ b/tests/unit/test_mouse.cpp @@ -131,22 +131,30 @@ INSTANTIATE_TEST_SUITE_P( TEST_P(MouseHIDTest, MoveInputTest) { util::point_t mouse_delta = GetParam(); - BOOST_LOG(tests) << "MoveInputTest:: got param: " << mouse_delta; + logging::tests([&](std::ostream &out) { + out << "MoveInputTest:: got param: " << mouse_delta; + }); platf::input_t input = platf::input(config_.values(), infrastructure_.scheduler()); - BOOST_LOG(tests) << "MoveInputTest:: init input"; + logging::tests("MoveInputTest:: init input"); - BOOST_LOG(tests) << "MoveInputTest:: get current mouse loc"; + logging::tests("MoveInputTest:: get current mouse loc"); auto old_loc = platf::get_mouse_loc(input); if (!old_loc) { GTEST_SKIP() << "Mouse location is not observable in this environment"; } - BOOST_LOG(tests) << "MoveInputTest:: got current mouse loc: " << *old_loc; + logging::tests([&](std::ostream &out) { + out << "MoveInputTest:: got current mouse loc: " << *old_loc; + }); - BOOST_LOG(tests) << "MoveInputTest:: move: " << mouse_delta; + logging::tests([&](std::ostream &out) { + out << "MoveInputTest:: move: " << mouse_delta; + }); platf::move_mouse(input, mouse_delta.x, mouse_delta.y); - BOOST_LOG(tests) << "MoveInputTest:: moved: " << mouse_delta; + logging::tests([&](std::ostream &out) { + out << "MoveInputTest:: moved: " << mouse_delta; + }); - BOOST_LOG(tests) << "MoveInputTest:: get updated mouse loc"; + logging::tests("MoveInputTest:: get updated mouse loc"); auto new_loc = wait_for_mouse_location(input, [old_loc = *old_loc, &mouse_delta](const auto &location) { return is_relative_axis_moved(location.x - old_loc.x, mouse_delta.x) && is_relative_axis_moved(location.y - old_loc.y, mouse_delta.y); @@ -154,14 +162,16 @@ TEST_P(MouseHIDTest, MoveInputTest) { if (!new_loc) { GTEST_SKIP() << "Virtual mouse movement is not observable in this environment"; } - BOOST_LOG(tests) << "MoveInputTest:: got updated mouse loc: " << *new_loc; + logging::tests([&](std::ostream &out) { + out << "MoveInputTest:: got updated mouse loc: " << *new_loc; + }); bool has_input_moved = old_loc->x != new_loc->x && old_loc->y != new_loc->y; if (!has_input_moved) { - BOOST_LOG(tests) << "MoveInputTest:: haven't moved"; + logging::tests("MoveInputTest:: haven't moved"); } else { - BOOST_LOG(tests) << "MoveInputTest:: moved"; + logging::tests("MoveInputTest:: moved"); } EXPECT_TRUE(has_input_moved); @@ -173,40 +183,50 @@ TEST_P(MouseHIDTest, MoveInputTest) { TEST_P(MouseHIDTest, AbsMoveInputTest) { util::point_t mouse_pos = GetParam(); - BOOST_LOG(tests) << "AbsMoveInputTest:: got param: " << mouse_pos; + logging::tests([&](std::ostream &out) { + out << "AbsMoveInputTest:: got param: " << mouse_pos; + }); platf::input_t input = platf::input(config_.values(), infrastructure_.scheduler()); - BOOST_LOG(tests) << "AbsMoveInputTest:: init input"; + logging::tests("AbsMoveInputTest:: init input"); - BOOST_LOG(tests) << "AbsMoveInputTest:: get current mouse loc"; + logging::tests("AbsMoveInputTest:: get current mouse loc"); auto old_loc = platf::get_mouse_loc(input); if (!old_loc) { GTEST_SKIP() << "Mouse location is not observable in this environment"; } - BOOST_LOG(tests) << "AbsMoveInputTest:: got current mouse loc: " << *old_loc; + logging::tests([&](std::ostream &out) { + out << "AbsMoveInputTest:: got current mouse loc: " << *old_loc; + }); const auto abs_port = absolute_mouse_test_port(); const auto expected_pos = expected_absolute_mouse_location(mouse_pos, abs_port); - BOOST_LOG(tests) << "AbsMoveInputTest:: touch port: " << abs_port.offset_x << 'x' << abs_port.offset_y << ' ' << abs_port.width << 'x' << abs_port.height; - BOOST_LOG(tests) << "AbsMoveInputTest:: move: " << mouse_pos; + logging::tests("AbsMoveInputTest:: touch port: {}x{} {}x{}", abs_port.offset_x, abs_port.offset_y, abs_port.width, abs_port.height); + logging::tests([&](std::ostream &out) { + out << "AbsMoveInputTest:: move: " << mouse_pos; + }); platf::abs_mouse(input, abs_port, mouse_pos.x, mouse_pos.y); - BOOST_LOG(tests) << "AbsMoveInputTest:: moved: " << mouse_pos; + logging::tests([&](std::ostream &out) { + out << "AbsMoveInputTest:: moved: " << mouse_pos; + }); - BOOST_LOG(tests) << "AbsMoveInputTest:: get updated mouse loc"; + logging::tests("AbsMoveInputTest:: get updated mouse loc"); auto new_loc = wait_for_mouse_location(input, [&expected_pos](const auto &location) { return is_near(location.x, expected_pos.x) && is_near(location.y, expected_pos.y); }); if (!new_loc) { GTEST_SKIP() << "Absolute virtual mouse movement is not observable in this environment"; } - BOOST_LOG(tests) << "AbsMoveInputTest:: got updated mouse loc: " << *new_loc; + logging::tests([&](std::ostream &out) { + out << "AbsMoveInputTest:: got updated mouse loc: " << *new_loc; + }); bool has_input_moved = old_loc->x != new_loc->x || old_loc->y != new_loc->y; if (!has_input_moved) { - BOOST_LOG(tests) << "AbsMoveInputTest:: haven't moved"; + logging::tests("AbsMoveInputTest:: haven't moved"); } else { - BOOST_LOG(tests) << "AbsMoveInputTest:: moved"; + logging::tests("AbsMoveInputTest:: moved"); } // Verify we moved to the absolute coordinate diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 56e0d0039..822d302fb 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -616,11 +616,9 @@ TEST_F(ProcessRefreshTest, FileTimeType_DefaultValueComparison) { // We cannot assert the comparison direction since it is platform-dependent. // Instead, just log and document both cases. if (now_time <= default_time) { - BOOST_LOG(info) << "file_time_type::clock::now() <= file_time_type{} is TRUE on this platform " - << "(this is the UCRT64 case that requires the optional sentinel)"; + logging::info("file_time_type::clock::now() <= file_time_type{} is TRUE on this platform (this is the UCRT64 case that requires the optional sentinel)"); } else { - BOOST_LOG(info) << "file_time_type::clock::now() > file_time_type{} on this platform " - << "(default-init guard would have worked, but optional is still safer)"; + logging::info("file_time_type::clock::now() > file_time_type{} on this platform (default-init guard would have worked, but optional is still safer)"); } // The actual correctness is verified by Refresh_ParsesFileOnFirstCall above —