diff --git a/src/crypto.cpp b/src/crypto.cpp index a6f326e70..cdc89dd27 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -28,10 +28,8 @@ namespace crypto { _certs.clear(); } - static int openssl_verify_cb(int ok, X509_STORE_CTX *ctx) { - int err_code = X509_STORE_CTX_get_error(ctx); - - switch (err_code) { + static int openssl_verify_cb(const int ok, X509_STORE_CTX *ctx) { + switch (X509_STORE_CTX_get_error(ctx)) { // Expired or not-yet-valid certificates are fine. Sometimes Moonlight is running on embedded devices // that don't have accurate clocks (or haven't yet synchronized by the time Moonlight first runs). // This behavior also matches what GeForce Experience does. diff --git a/src/input.cpp b/src/input.cpp index 768ddece2..9c7197013 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -93,7 +93,7 @@ namespace input { * @param f Netfloat value. * @return The native endianness float value. */ - float from_netfloat(netfloat f) { + float from_netfloat(const netfloat f) { return boost::endian::endian_load(f); } @@ -104,7 +104,7 @@ namespace input { * @param max The maximum value for clamping. * @return Clamped native endianess float value. */ - float from_clamped_netfloat(netfloat f, float min, float max) { + float from_clamped_netfloat(const netfloat f, const float min, const float max) { return std::clamp(from_netfloat(f), min, max); } @@ -220,7 +220,7 @@ namespace input { return 0; } - void print(PNV_REL_MOUSE_MOVE_PACKET packet) { + void print(const _NV_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 @@ -228,7 +228,7 @@ namespace input { << "--end relative mouse move packet--"sv; } - void print(PNV_ABS_MOUSE_MOVE_PACKET packet) { + void print(const _NV_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 @@ -238,7 +238,7 @@ namespace input { << "--end absolute mouse move packet--"sv; } - void print(PNV_MOUSE_BUTTON_PACKET packet) { + void print(const _NV_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 @@ -246,21 +246,21 @@ namespace input { << "--end mouse button packet--"sv; } - void print(PNV_SCROLL_PACKET packet) { + void print(const _NV_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; } - void print(PSS_HSCROLL_PACKET packet) { + void print(const _SS_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; } - void print(PNV_KEYBOARD_PACKET packet) { + void print(const _NV_KEYBOARD_PACKET *packet) { BOOST_LOG(debug) << "--begin keyboard packet--"sv << std::endl << "keyAction ["sv << util::hex(packet->header.magic).to_string_view() << ']' << std::endl @@ -270,7 +270,7 @@ namespace input { << "--end keyboard packet--"sv; } - void print(PNV_UNICODE_PACKET packet) { + void print(const _NV_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 @@ -278,7 +278,7 @@ namespace input { << "--end unicode packet--"sv; } - void print(PNV_MULTI_CONTROLLER_PACKET packet) { + void print(const _NV_MULTI_CONTROLLER_PACKET *packet) { // Moonlight spams controller packet even when not necessary BOOST_LOG(verbose) << "--begin controller packet--"sv << std::endl @@ -298,7 +298,7 @@ namespace input { * @brief Prints a touch packet. * @param packet The touch packet. */ - void print(PSS_TOUCH_PACKET packet) { + void print(const _SS_TOUCH_PACKET *packet) { BOOST_LOG(debug) << "--begin touch packet--"sv << std::endl << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl @@ -316,7 +316,7 @@ namespace input { * @brief Prints a pen packet. * @param packet The pen packet. */ - void print(PSS_PEN_PACKET packet) { + void print(const _SS_PEN_PACKET *packet) { BOOST_LOG(debug) << "--begin pen packet--"sv << std::endl << "eventType ["sv << util::hex(packet->eventType).to_string_view() << ']' << std::endl @@ -336,7 +336,7 @@ namespace input { * @brief Prints a controller arrival packet. * @param packet The controller arrival packet. */ - void print(PSS_CONTROLLER_ARRIVAL_PACKET packet) { + void print(const _SS_CONTROLLER_ARRIVAL_PACKET *packet) { BOOST_LOG(debug) << "--begin controller arrival packet--"sv << std::endl << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl @@ -350,7 +350,7 @@ namespace input { * @brief Prints a controller touch packet. * @param packet The controller touch packet. */ - void print(PSS_CONTROLLER_TOUCH_PACKET packet) { + void print(const _SS_CONTROLLER_TOUCH_PACKET *packet) { BOOST_LOG(debug) << "--begin controller touch packet--"sv << std::endl << "controllerNumber ["sv << (uint32_t) packet->controllerNumber << ']' << std::endl @@ -366,7 +366,7 @@ namespace input { * @brief Prints a controller motion packet. * @param packet The controller motion packet. */ - void print(PSS_CONTROLLER_MOTION_PACKET packet) { + void print(const _SS_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 @@ -381,7 +381,7 @@ namespace input { * @brief Prints a controller battery packet. * @param packet The controller battery packet. */ - void print(PSS_CONTROLLER_BATTERY_PACKET packet) { + void print(const _SS_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 @@ -441,7 +441,7 @@ namespace input { } } - void passthrough(std::shared_ptr &input, PNV_REL_MOUSE_MOVE_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_REL_MOUSE_MOVE_PACKET *packet) { if (!config::input.mouse) { return; } @@ -457,7 +457,7 @@ namespace input { * @param size The size of the client's surface containing the value. * @return The host-relative coordinate pair if a touchport is available. */ - std::optional> client_to_touchport(std::shared_ptr &input, const std::pair &val, const std::pair &size) { + std::optional> client_to_touchport(const std::shared_ptr &input, const std::pair &val, const std::pair &size) { auto &touch_port_event = input->touch_port_event; auto &touch_port = input->touch_port; if (touch_port_event->peek()) { @@ -490,7 +490,7 @@ namespace input { * @param scalar The scalar cartesian coordinate pair. * @return The scaled radial coordinate. */ - float multiply_polar_by_cartesian_scalar(float r, float angle, const std::pair &scalar) { + float multiply_polar_by_cartesian_scalar(const float r, const float angle, const std::pair &scalar) { // Convert polar to cartesian coordinates float x = r * std::cos(angle); float y = r * std::sin(angle); @@ -503,7 +503,7 @@ namespace input { return std::sqrt(std::pow(x, 2) + std::pow(y, 2)); } - std::pair scale_client_contact_area(const std::pair &val, uint16_t rotation, const std::pair &scalar) { + std::pair scale_client_contact_area(const std::pair &val, const uint16_t rotation, const std::pair &scalar) { // If the rotation is unknown, we'll just scale both axes equally by using // a 45-degree angle for our scaling calculations float angle = rotation == LI_ROT_UNKNOWN ? (M_PI / 4) : (rotation * (M_PI / 180)); @@ -516,7 +516,7 @@ namespace input { return {multiply_polar_by_cartesian_scalar(major, angle, scalar), multiply_polar_by_cartesian_scalar(minor, angle + (M_PI / 2), scalar)}; } - void passthrough(std::shared_ptr &input, PNV_ABS_MOUSE_MOVE_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_ABS_MOUSE_MOVE_PACKET *packet) { if (!config::input.mouse) { return; } @@ -555,13 +555,13 @@ namespace input { platf::abs_mouse(platf_input, abs_port, tpcoords->first, tpcoords->second); } - void passthrough(std::shared_ptr &input, PNV_MOUSE_BUTTON_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_MOUSE_BUTTON_PACKET *packet) { if (!config::input.mouse) { return; } - auto release = util::endian::little(packet->header.magic) == MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5; - auto button = util::endian::big(packet->button); + const auto release = util::endian::little(packet->header.magic) == MOUSE_BUTTON_UP_EVENT_MAGIC_GEN5; + const auto button = util::endian::big(packet->button); if (button > 0 && button < mouse_press.size()) { if (mouse_press[button] != release) { // button state is already what we want @@ -616,9 +616,8 @@ namespace input { platf::button_mouse(platf_input, button, release); } - short map_keycode(short keycode) { - auto it = config::input.keybindings.find(keycode); - if (it != std::end(config::input.keybindings)) { + short map_keycode(const short keycode) { + if (const auto it = config::input.keybindings.find(keycode); it != std::end(config::input.keybindings)) { return it->second; } @@ -626,9 +625,9 @@ namespace input { } /** - * @brief Update flags for keyboard shortcut combo's + * @brief Update flags for keyboard-shortcut combo's */ - inline void update_shortcutFlags(int *flags, short keyCode, bool release) { + inline void update_shortcutFlags(int *flags, const short keyCode, const bool release) { switch (keyCode) { case VKEY_SHIFT: case VKEY_LSHIFT: @@ -677,7 +676,7 @@ namespace input { } } - void send_key_and_modifiers(uint16_t key_code, bool release, uint8_t flags, uint8_t synthetic_modifiers) { + void send_key_and_modifiers(const uint16_t key_code, const bool release, const uint8_t flags, const uint8_t synthetic_modifiers) { if (!release) { // Press any synthetic modifiers required for this key if (synthetic_modifiers & MODIFIER_SHIFT) { @@ -719,16 +718,16 @@ namespace input { key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_period, key_code, flags, synthetic_modifiers).task_id; } - void passthrough(std::shared_ptr &input, PNV_KEYBOARD_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_KEYBOARD_PACKET *packet) { if (!config::input.keyboard) { return; } - auto release = util::endian::little(packet->header.magic) == KEY_UP_EVENT_MAGIC; + const auto release = util::endian::little(packet->header.magic) == KEY_UP_EVENT_MAGIC; auto keyCode = packet->keyCode & 0x00FF; // Set synthetic modifier flags if the keyboard packet is requesting modifier - // keys that are not current pressed. + // keys that are not currently pressed. uint8_t synthetic_modifiers = 0; if (!release && !is_modifier(keyCode)) { if (!(input->shortcutFlags & input_t::SHIFT) && (packet->modifiers & MODIFIER_SHIFT)) { @@ -763,7 +762,7 @@ namespace input { return; } } else if (!release) { - // Already pressed down key + // Already pressed down the key return; } @@ -779,7 +778,7 @@ namespace input { * @param input The input context pointer. * @param packet The scroll packet. */ - void passthrough(std::shared_ptr &input, PNV_SCROLL_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_SCROLL_PACKET *packet) { if (!config::input.mouse) { return; } @@ -788,8 +787,7 @@ namespace input { platf::scroll(platf_input, util::endian::big(packet->scrollAmt1)); } else { input->accumulated_vscroll_delta += util::endian::big(packet->scrollAmt1); - auto full_ticks = input->accumulated_vscroll_delta / WHEEL_DELTA; - if (full_ticks) { + if (const auto full_ticks = input->accumulated_vscroll_delta / WHEEL_DELTA) { // Send any full ticks that have accumulated and store the rest platf::scroll(platf_input, full_ticks * WHEEL_DELTA); input->accumulated_vscroll_delta -= full_ticks * WHEEL_DELTA; @@ -802,7 +800,7 @@ namespace input { * @param input The input context pointer. * @param packet The scroll packet. */ - void passthrough(std::shared_ptr &input, PSS_HSCROLL_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_HSCROLL_PACKET *packet) { if (!config::input.mouse) { return; } @@ -811,8 +809,7 @@ namespace input { platf::hscroll(platf_input, util::endian::big(packet->scrollAmount)); } else { input->accumulated_hscroll_delta += util::endian::big(packet->scrollAmount); - auto full_ticks = input->accumulated_hscroll_delta / WHEEL_DELTA; - if (full_ticks) { + if (const auto full_ticks = input->accumulated_hscroll_delta / WHEEL_DELTA) { // Send any full ticks that have accumulated and store the rest platf::hscroll(platf_input, full_ticks * WHEEL_DELTA); input->accumulated_hscroll_delta -= full_ticks * WHEEL_DELTA; @@ -825,7 +822,7 @@ namespace input { return; } - auto size = util::endian::big(packet->header.size) - sizeof(packet->header.magic); + const auto size = util::endian::big(packet->header.size) - sizeof(packet->header.magic); platf::unicode(platf_input, packet->text, size); } @@ -834,7 +831,7 @@ namespace input { * @param input The input context pointer. * @param packet The controller arrival packet. */ - void passthrough(std::shared_ptr &input, PSS_CONTROLLER_ARRIVAL_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_CONTROLLER_ARRIVAL_PACKET *packet) { if (!config::input.controller) { return; } @@ -855,7 +852,7 @@ namespace input { util::endian::little(packet->supportedButtonFlags), }; - auto id = alloc_id(gamepadMask); + const auto id = alloc_id(gamepadMask); if (id < 0) { return; } @@ -874,7 +871,7 @@ namespace input { * @param input The input context pointer. * @param packet The touch packet. */ - void passthrough(std::shared_ptr &input, PSS_TOUCH_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_TOUCH_PACKET *packet) { if (!config::input.mouse) { return; } @@ -885,8 +882,8 @@ namespace input { return; } - auto &touch_port = input->touch_port; - platf::touch_port_t abs_port { + const auto &touch_port = input->touch_port; + const platf::touch_port_t abs_port { touch_port.offset_x, touch_port.offset_y, touch_port.env_width, @@ -904,14 +901,14 @@ namespace input { } // Normalize the contact area based on the touchport - auto contact_area = scale_client_contact_area( + const auto contact_area = scale_client_contact_area( {from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f}, rotation, {abs_port.width / 65535.f, abs_port.height / 65535.f} ); - platf::touch_input_t touch { + const platf::touch_input_t touch { packet->eventType, rotation, util::endian::little(packet->pointerId), @@ -930,7 +927,7 @@ namespace input { * @param input The input context pointer. * @param packet The pen packet. */ - void passthrough(std::shared_ptr &input, PSS_PEN_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_PEN_PACKET *packet) { if (!config::input.mouse) { return; } @@ -941,8 +938,8 @@ namespace input { return; } - auto &touch_port = input->touch_port; - platf::touch_port_t abs_port { + const auto &touch_port = input->touch_port; + const platf::touch_port_t abs_port { touch_port.offset_x, touch_port.offset_y, touch_port.env_width, @@ -960,14 +957,14 @@ namespace input { } // Normalize the contact area based on the touchport - auto contact_area = scale_client_contact_area( + const auto contact_area = scale_client_contact_area( {from_clamped_netfloat(packet->contactAreaMajor, 0.0f, 1.0f) * 65535.f, from_clamped_netfloat(packet->contactAreaMinor, 0.0f, 1.0f) * 65535.f}, rotation, {abs_port.width / 65535.f, abs_port.height / 65535.f} ); - platf::pen_input_t pen { + const platf::pen_input_t pen { packet->eventType, packet->toolType, packet->penButtons, @@ -988,7 +985,7 @@ namespace input { * @param input The input context pointer. * @param packet The controller touch packet. */ - void passthrough(std::shared_ptr &input, PSS_CONTROLLER_TOUCH_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_CONTROLLER_TOUCH_PACKET *packet) { if (!config::input.controller) { return; } @@ -998,13 +995,13 @@ namespace input { return; } - auto &gamepad = input->gamepads[packet->controllerNumber]; + const auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } - platf::gamepad_touch_t touch { + const platf::gamepad_touch_t touch { {gamepad.id, packet->controllerNumber}, packet->eventType, util::endian::little(packet->pointerId), @@ -1021,7 +1018,7 @@ namespace input { * @param input The input context pointer. * @param packet The controller motion packet. */ - void passthrough(std::shared_ptr &input, PSS_CONTROLLER_MOTION_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_CONTROLLER_MOTION_PACKET *packet) { if (!config::input.controller) { return; } @@ -1031,13 +1028,13 @@ namespace input { return; } - auto &gamepad = input->gamepads[packet->controllerNumber]; + const auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } - platf::gamepad_motion_t motion { + const platf::gamepad_motion_t motion { {gamepad.id, packet->controllerNumber}, packet->motionType, from_netfloat(packet->x), @@ -1053,7 +1050,7 @@ namespace input { * @param input The input context pointer. * @param packet The controller battery packet. */ - void passthrough(std::shared_ptr &input, PSS_CONTROLLER_BATTERY_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _SS_CONTROLLER_BATTERY_PACKET *packet) { if (!config::input.controller) { return; } @@ -1063,13 +1060,13 @@ namespace input { return; } - auto &gamepad = input->gamepads[packet->controllerNumber]; + const auto &gamepad = input->gamepads[packet->controllerNumber]; if (gamepad.id < 0) { BOOST_LOG(warning) << "ControllerNumber ["sv << packet->controllerNumber << "] not allocated"sv; return; } - platf::gamepad_battery_t battery { + const platf::gamepad_battery_t battery { {gamepad.id, packet->controllerNumber}, packet->batteryState, packet->batteryPercentage @@ -1078,7 +1075,7 @@ namespace input { platf::gamepad_battery(platf_input, battery); } - void passthrough(std::shared_ptr &input, PNV_MULTI_CONTROLLER_PACKET packet) { + void passthrough(const std::shared_ptr &input, const _NV_MULTI_CONTROLLER_PACKET *packet) { if (!config::input.controller) { return; } @@ -1094,7 +1091,7 @@ namespace input { // If this is an event for a new gamepad, create the gamepad now. Ideally, the client would // send a controller arrival instead of this but it's still supported for legacy clients. if ((packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id < 0) { - auto id = alloc_id(gamepadMask); + const auto id = alloc_id(gamepadMask); if (id < 0) { return; } @@ -1120,7 +1117,7 @@ namespace input { } std::uint16_t bf = packet->buttonFlags; - std::uint32_t bf2 = packet->buttonFlags2; + const std::uint32_t bf2 = packet->buttonFlags2; platf::gamepad_state_t gamepad_state { bf | (bf2 << 16), packet->leftTrigger, @@ -1154,7 +1151,7 @@ namespace input { if (platf::BACK & bf) { if (platf::BACK & bf_new) { - // Don't emulate home button if timeout < 0 + // Don't emulate the home button if timeout < 0 if (config::input.back_button_timeout >= 0ms) { auto f = [input, controller = packet->controllerNumber]() { auto &gamepad = input->gamepads[controller]; @@ -1166,7 +1163,7 @@ namespace input { state.buttonFlags &= ~platf::BACK; platf::gamepad_update(platf_input, gamepad.id, state); - // Press Home button + // Press the Home button state.buttonFlags |= platf::HOME; platf::gamepad_update(platf_input, gamepad.id, state); @@ -1205,7 +1202,7 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PNV_REL_MOUSE_MOVE_PACKET dest, PNV_REL_MOUSE_MOVE_PACKET src) { + batch_result_e batch(PNV_REL_MOUSE_MOVE_PACKET dest, const _NV_REL_MOUSE_MOVE_PACKET *src) { short deltaX, deltaY; // Batching is safe as long as the result doesn't overflow a 16-bit integer @@ -1228,7 +1225,7 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PNV_ABS_MOUSE_MOVE_PACKET dest, PNV_ABS_MOUSE_MOVE_PACKET src) { + batch_result_e batch(PNV_ABS_MOUSE_MOVE_PACKET dest, const _NV_ABS_MOUSE_MOVE_PACKET *src) { // Batching must only happen if the reference width and height don't change if (dest->width != src->width || dest->height != src->height) { return batch_result_e::terminate_batch; @@ -1245,7 +1242,7 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PNV_SCROLL_PACKET dest, PNV_SCROLL_PACKET src) { + batch_result_e batch(PNV_SCROLL_PACKET dest, const _NV_SCROLL_PACKET *src) { short scrollAmt; // Batching is safe as long as the result doesn't overflow a 16-bit integer @@ -1265,7 +1262,7 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PSS_HSCROLL_PACKET dest, PSS_HSCROLL_PACKET src) { + batch_result_e batch(PSS_HSCROLL_PACKET dest, const _SS_HSCROLL_PACKET *src) { short scrollAmt; // Batching is safe as long as the result doesn't overflow a 16-bit integer @@ -1284,13 +1281,13 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PNV_MULTI_CONTROLLER_PACKET dest, PNV_MULTI_CONTROLLER_PACKET src) { + batch_result_e batch(PNV_MULTI_CONTROLLER_PACKET dest, const _NV_MULTI_CONTROLLER_PACKET *src) { // Do not allow batching if the active controllers change if (dest->activeGamepadMask != src->activeGamepadMask) { return batch_result_e::terminate_batch; } - // We can only batch entries for the same controller, but allow batching attempts to continue + // We can only batch entries for the same controller but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; @@ -1312,14 +1309,14 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PSS_TOUCH_PACKET dest, PSS_TOUCH_PACKET src) { + batch_result_e batch(PSS_TOUCH_PACKET dest, const _SS_TOUCH_PACKET *src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } - // Don't batch beyond state changing events + // Don't batch beyond state-changing events if (src->eventType != LI_TOUCH_EVENT_MOVE && src->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; @@ -1346,7 +1343,7 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PSS_PEN_PACKET dest, PSS_PEN_PACKET src) { + batch_result_e batch(PSS_PEN_PACKET dest, const _SS_PEN_PACKET *src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { @@ -1379,20 +1376,20 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PSS_CONTROLLER_TOUCH_PACKET dest, PSS_CONTROLLER_TOUCH_PACKET src) { + batch_result_e batch(PSS_CONTROLLER_TOUCH_PACKET dest, const _SS_CONTROLLER_TOUCH_PACKET *src) { // Only batch hover or move events if (dest->eventType != LI_TOUCH_EVENT_MOVE && dest->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; } - // We can only batch entries for the same controller, but allow batching attempts to continue + // We can only batch entries for the same controller but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; } - // Don't batch beyond state changing events + // Don't batch beyond state-changing events if (src->eventType != LI_TOUCH_EVENT_MOVE && src->eventType != LI_TOUCH_EVENT_HOVER) { return batch_result_e::terminate_batch; @@ -1419,8 +1416,8 @@ namespace input { * @param src A later packet to attempt to batch. * @return The status of the batching operation. */ - batch_result_e batch(PSS_CONTROLLER_MOTION_PACKET dest, PSS_CONTROLLER_MOTION_PACKET src) { - // We can only batch entries for the same controller, but allow batching attempts to continue + batch_result_e batch(PSS_CONTROLLER_MOTION_PACKET dest, const _SS_CONTROLLER_MOTION_PACKET *src) { + // We can only batch entries for the same controller but allow batching attempts to continue // in case we have more packets for this controller later in the queue. if (dest->controllerNumber != src->controllerNumber) { return batch_result_e::not_batchable; @@ -1478,7 +1475,7 @@ namespace input { * @brief Called on a thread pool thread to process an input message. * @param input The input context pointer. */ - void passthrough_next_message(std::shared_ptr input) { + void passthrough_next_message(const std::shared_ptr &input) { // 'entry' backs the 'payload' pointer, so they must remain in scope together std::vector entry; PNV_INPUT_HEADER payload; @@ -1584,11 +1581,11 @@ namespace input { task_pool.push(passthrough_next_message, input); } - void reset(std::shared_ptr &input) { + void reset(const std::shared_ptr &input) { task_pool.cancel(key_press_repeat_id); task_pool.cancel(input->mouse_left_button_timeout); - // Ensure input is synchronous, by using the task_pool + // Ensure input is synchronous by using the task_pool task_pool.push([]() { for (int x = 0; x < mouse_press.size(); ++x) { if (mouse_press[x]) { @@ -1622,9 +1619,8 @@ namespace input { } bool probe_gamepads() { - auto input = static_cast(platf_input.get()); - const auto gamepads = platf::supported_gamepads(input); - for (auto &gamepad : gamepads) { + const auto input = static_cast(platf_input.get()); + for (const auto gamepads = platf::supported_gamepads(input); auto &gamepad : gamepads) { if (gamepad.is_enabled && gamepad.name != "auto") { return false; } @@ -1632,7 +1628,7 @@ namespace input { return true; } - std::shared_ptr alloc(safe::mail_t mail) { + std::shared_ptr alloc(const safe::mail_t &mail) { auto input = std::make_shared( mail->event(mail::touch_port), mail->queue(mail::gamepad_feedback) diff --git a/src/input.h b/src/input.h index 96b2f457f..5fc0105a9 100644 --- a/src/input.h +++ b/src/input.h @@ -15,14 +15,14 @@ namespace input { struct input_t; void print(void *input); - void reset(std::shared_ptr &input); + void reset(const std::shared_ptr &input); void passthrough(std::shared_ptr &input, std::vector &&input_data); [[nodiscard]] std::unique_ptr init(); bool probe_gamepads(); - std::shared_ptr alloc(safe::mail_t mail); + std::shared_ptr alloc(const safe::mail_t &mail); struct touch_port_t: public platf::touch_port_t { int env_width, env_height; diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index c1d9401c2..acbc1dc99 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -66,7 +66,7 @@ namespace nvhttp { void after_bind() override { if (verify) { context.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_client_once); - context.set_verify_callback([](int verified, boost::asio::ssl::verify_context &ctx) { + context.set_verify_callback([](int verified, const boost::asio::ssl::verify_context &ctx) { // To respond with an error message, a connection must be established return 1; }); @@ -338,7 +338,7 @@ namespace nvhttp { map_id_sess.erase(sess.client.uniqueID); } - void fail_pair(pair_session_t &sess, pt::ptree &tree, const std::string status_msg) { + void fail_pair(const pair_session_t &sess, pt::ptree &tree, const std::string status_msg) { tree.put("root.paired", 0); tree.put("root..status_code", 400); tree.put("root..status_message", status_msg); @@ -359,7 +359,7 @@ namespace nvhttp { std::string_view salt_view {sess.async_insert_pin.salt.data(), 32}; - auto salt = util::from_hex>(salt_view, true); + const auto salt = util::from_hex>(salt_view, true); auto key = crypto::gen_aes_key(salt, pin); sess.cipher_key = std::make_unique(key); @@ -385,8 +385,8 @@ namespace nvhttp { std::vector decrypted; cipher.decrypt(challenge, decrypted); - auto x509 = crypto::x509(conf_intern.servercert); - auto sign = crypto::signature(x509); + const auto x509 = crypto::x509(conf_intern.servercert); + const auto sign = crypto::signature(x509); auto serversecret = crypto::rand(16); decrypted.insert(std::end(decrypted), std::begin(sign), std::end(sign)); @@ -441,7 +441,7 @@ namespace nvhttp { tree.put("root..status_code", 200); } - void clientpairingsecret(pair_session_t &sess, std::shared_ptr> &add_cert, pt::ptree &tree, const std::string &client_pairing_secret) { + void clientpairingsecret(pair_session_t &sess, const std::shared_ptr> &add_cert, pt::ptree &tree, const std::string &client_pairing_secret) { if (sess.last_phase != PAIR_PHASE::SERVERCHALLENGERESP) { fail_pair(sess, tree, "Out of order call to clientpairingsecret"); return; @@ -455,15 +455,15 @@ namespace nvhttp { return; } - std::string_view secret {client_pairing_secret.data(), 16}; - std::string_view sign {client_pairing_secret.data() + secret.size(), client_pairing_secret.size() - secret.size()}; + const std::string_view secret {client_pairing_secret.data(), 16}; + const std::string_view sign {client_pairing_secret.data() + secret.size(), client_pairing_secret.size() - secret.size()}; - auto x509 = crypto::x509(client.cert); + const auto x509 = crypto::x509(client.cert); if (!x509) { fail_pair(sess, tree, "Invalid client certificate"); return; } - auto x509_sign = crypto::signature(x509); + const auto x509_sign = crypto::signature(x509); std::string data; data.reserve(sess.serverchallenge.size() + x509_sign.size() + secret.size()); @@ -475,9 +475,8 @@ namespace nvhttp { auto hash = crypto::hash(data); // if hash not correct, probably MITM - bool same_hash = hash.size() == sess.clienthash.size() && std::equal(hash.begin(), hash.end(), sess.clienthash.begin()); - auto verify = crypto::verify256(crypto::x509(client.cert), secret, sign); - if (same_hash && verify) { + const bool same_hash = hash.size() == sess.clienthash.size() && std::equal(hash.begin(), hash.end(), sess.clienthash.begin()); + if (const auto verify = crypto::verify256(crypto::x509(client.cert), secret, sign); same_hash && verify) { tree.put("root.paired", 1); add_cert->raise(crypto::x509(client.cert)); @@ -576,7 +575,7 @@ namespace nvhttp { sess.client.cert = util::from_hex_vec(get_arg(args, "clientcert"), true); BOOST_LOG(debug) << sess.client.cert; - auto ptr = map_id_sess.emplace(sess.client.uniqueID, std::move(sess)).first; + const auto ptr = map_id_sess.emplace(sess.client.uniqueID, std::move(sess)).first; ptr->second.async_insert_pin.salt = std::move(get_arg(args, "salt")); if (config::sunshine.flags[config::flag::PIN_STDIN]) { @@ -611,13 +610,13 @@ namespace nvhttp { } if (it = args.find("clientchallenge"); it != std::end(args)) { - auto challenge = util::from_hex_vec(it->second, true); + const auto challenge = util::from_hex_vec(it->second, true); clientchallenge(sess_it->second, tree, challenge); } else if (it = args.find("serverchallengeresp"); it != std::end(args)) { - auto encrypted_response = util::from_hex_vec(it->second, true); + const auto encrypted_response = util::from_hex_vec(it->second, true); serverchallengeresp(sess_it->second, tree, encrypted_response); } else if (it = args.find("clientpairingsecret"); it != std::end(args)) { - auto pairingsecret = util::from_hex_vec(it->second, true); + const auto pairingsecret = util::from_hex_vec(it->second, true); clientpairingsecret(sess_it->second, add_cert, tree, pairingsecret); } else { tree.put("root..status_code", 404); @@ -625,7 +624,7 @@ namespace nvhttp { } } - bool pin(std::string pin, std::string name) { + bool pin(std::string pin, const std::string &name) { pt::ptree tree; if (map_id_sess.empty()) { return false; @@ -779,7 +778,7 @@ namespace nvhttp { return named_cert_nodes; } - void applist(resp_https_t response, req_https_t request) { + void applist(const resp_https_t &response, const req_https_t &request) { print_req(request); pt::ptree tree; @@ -807,7 +806,7 @@ namespace nvhttp { } } - void launch(bool &host_audio, resp_https_t response, req_https_t request) { + void launch(bool &host_audio, const resp_https_t &response, const req_https_t &request) { print_req(request); pt::ptree tree; @@ -838,10 +837,9 @@ namespace nvhttp { return; } - auto appid = util::from_view(get_arg(args, "appid")); + const auto appid = util::from_view(get_arg(args, "appid")); - auto current_appid = proc::proc.running(); - if (current_appid > 0) { + if (const auto current_appid = proc::proc.running(); current_appid > 0) { tree.put("root.resume", 0); tree.put("root..status_code", 400); tree.put("root..status_message", "An app is already running on this host"); @@ -850,7 +848,7 @@ namespace nvhttp { } host_audio = util::from_view(get_arg(args, "localAudioPlayMode")); - auto launch_session = make_launch_session(host_audio, args); + const auto launch_session = make_launch_session(host_audio, args); if (rtsp_stream::session_count() == 0) { // The display should be restored in case something fails as there are no other sessions. @@ -874,8 +872,7 @@ namespace nvhttp { } } - auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); - if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { + if (const auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address()); !launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) { BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv; tree.put("root..status_code", 403); @@ -886,8 +883,7 @@ namespace nvhttp { } if (appid > 0) { - auto err = proc::proc.execute(appid, launch_session); - if (err) { + if (const auto err = proc::proc.execute(appid, launch_session)) { tree.put("root..status_code", err); tree.put("root..status_message", "Failed to start the specified application"); tree.put("root.gamesession", 0); @@ -914,7 +910,7 @@ namespace nvhttp { revert_display_configuration = false; } - void resume(bool &host_audio, resp_https_t response, req_https_t request) { + void resume(bool &host_audio, const resp_https_t &response, const req_https_t &request) { print_req(request); pt::ptree tree; @@ -926,8 +922,7 @@ namespace nvhttp { response->close_connection_after_response = true; }); - auto current_appid = proc::proc.running(); - if (current_appid == 0) { + if (const auto current_appid = proc::proc.running(); current_appid == 0) { tree.put("root.resume", 0); tree.put("root..status_code", 503); tree.put("root..status_message", "No running app to resume"); @@ -1001,7 +996,7 @@ namespace nvhttp { rtsp_stream::launch_session_raise(launch_session); } - void cancel(resp_https_t response, req_https_t request) { + void cancel(const resp_https_t &response, const req_https_t &request) { print_req(request); pt::ptree tree; @@ -1026,7 +1021,7 @@ namespace nvhttp { display_device::revert_configuration(); } - void appasset(resp_https_t response, req_https_t request) { + void appasset(const resp_https_t &response, const req_https_t &request) { print_req(request); auto args = request->parse_query_string(); @@ -1045,15 +1040,13 @@ namespace nvhttp { } void start() { - auto shutdown_event = mail::man->event(mail::shutdown); + const auto shutdown_event = mail::man->event(mail::shutdown); - auto port_http = net::map_port(PORT_HTTP); - auto port_https = net::map_port(PORT_HTTPS); - auto address_family = net::af_from_enum_string(config::sunshine.address_family); + const auto port_http = net::map_port(PORT_HTTP); + const auto port_https = net::map_port(PORT_HTTPS); + const auto address_family = net::af_from_enum_string(config::sunshine.address_family); - bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; - - if (!clean_slate) { + if (const bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE]; !clean_slate) { load_state(); } @@ -1071,7 +1064,7 @@ namespace nvhttp { http_server_t http_server; // Verify certificates after establishing connection - https_server.verify = [add_cert](SSL *ssl) { + https_server.verify = [add_cert](const SSL *ssl) { crypto::x509_t x509 { #if OPENSSL_VERSION_MAJOR >= 3 SSL_get1_peer_certificate(ssl) diff --git a/src/nvhttp.h b/src/nvhttp.h index 636337071..0f7d40b7b 100644 --- a/src/nvhttp.h +++ b/src/nvhttp.h @@ -162,7 +162,7 @@ namespace nvhttp { * Then using the client certificate public key we should be able to verify that * the client secret has been signed by Moonlight */ - void clientpairingsecret(pair_session_t &sess, std::shared_ptr> &add_cert, boost::property_tree::ptree &tree, const std::string &client_pairing_secret); + void clientpairingsecret(pair_session_t &sess, const std::shared_ptr> &add_cert, boost::property_tree::ptree &tree, const std::string &client_pairing_secret); /** * @brief Compare the user supplied pin to the Moonlight pin. @@ -173,7 +173,7 @@ namespace nvhttp { * bool pin_status = nvhttp::pin("1234", "laptop"); * @examples_end */ - bool pin(std::string pin, std::string name); + bool pin(std::string pin, const std::string &name); /** * @brief Remove single client. diff --git a/src/platform/common.h b/src/platform/common.h index 28704bb12..30549252e 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -600,7 +600,7 @@ namespace platf { */ bool needs_encoder_reenumeration(); - boost::process::v1::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const boost::process::v1::environment &env, FILE *file, std::error_code &ec, boost::process::v1::group *group); + boost::process::v1::child run_command(bool elevated, bool interactive, const std::string &cmd, const boost::filesystem::path &working_dir, const boost::process::v1::environment &env, FILE *file, std::error_code &ec, boost::process::v1::group *group); enum class thread_priority_e : int { low, ///< Low priority @@ -704,7 +704,7 @@ namespace platf { boost::asio::ip::address &source_address; }; - bool send(send_info_t &send_info); + bool send(const send_info_t &send_info); enum class qos_data_type_e : int { audio, ///< Audio @@ -719,7 +719,7 @@ namespace platf { * @param data_type The type of traffic sent on this socket. * @param dscp_tagging Specifies whether to enable DSCP tagging on outgoing traffic. */ - std::unique_ptr enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging); + std::unique_ptr enable_socket_qos(uintptr_t native_socket, const boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging); /** * @brief Open a url in the default web browser. diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 0e53e939b..4321758a0 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -156,22 +156,22 @@ namespace platf { f(ctx, i, eol); } - void cb_i(ctx_t::pointer ctx, std::uint32_t i, void *userdata) { - auto alarm = (safe::alarm_raw_t *) userdata; + void cb_i(const pa_context *ctx, std::uint32_t i, void *userdata) { + const auto alarm = (safe::alarm_raw_t *) userdata; alarm->ring(i); } - void ctx_state_cb(ctx_t::pointer ctx, void *userdata) { - auto &f = *(std::function *) userdata; + void ctx_state_cb(const ctx_t::pointer ctx, void *userdata) { + const auto &f = *(std::function *) userdata; f(ctx); } - void success_cb(ctx_t::pointer ctx, int status, void *userdata) { + void success_cb(const pa_context *ctx, const int status, void *userdata) { assert(userdata != nullptr); - auto alarm = (safe::alarm_raw_t *) userdata; + const auto alarm = (safe::alarm_raw_t *) userdata; alarm->ring(status ? 0 : 1); } @@ -203,7 +203,7 @@ namespace platf { loop.reset(pa_mainloop_new()); ctx.reset(pa_context_new(pa_mainloop_get_api(loop.get()), "sunshine")); - events_cb = std::make_unique>([this](ctx_t::pointer ctx) { + events_cb = std::make_unique>([this](const pa_context *ctx) { switch (pa_context_get_state(ctx)) { case PA_CONTEXT_READY: events->raise(ready); @@ -227,18 +227,16 @@ namespace platf { pa_context_set_state_callback(ctx.get(), ctx_state_cb, events_cb.get()); - auto status = pa_context_connect(ctx.get(), nullptr, PA_CONTEXT_NOFLAGS, nullptr); - if (status) { + if (const auto status = pa_context_connect(ctx.get(), nullptr, PA_CONTEXT_NOFLAGS, nullptr)) { BOOST_LOG(error) << "Couldn't connect to pulseaudio: "sv << pa_strerror(status); return -1; } worker = std::thread { - [](loop_t::pointer loop) { + [](const loop_t::pointer loop) { int retval; - auto status = pa_mainloop_run(loop, &retval); - if (status < 0) { + if (const auto status = pa_mainloop_run(loop, &retval); status < 0) { BOOST_LOG(error) << "Couldn't run pulseaudio main loop"sv; return; } @@ -246,23 +244,22 @@ namespace platf { loop.get() }; - auto event = events->pop(); - if (event == failed) { + if (const auto event = events->pop(); event == failed) { return -1; } return 0; } - int load_null(const char *name, const std::uint8_t *channel_mapping, int channels) { - auto alarm = safe::make_alarm(); + int load_null(const char *name, const std::uint8_t *channel_mapping, const int channels) { + const auto alarm = safe::make_alarm(); op_t op { pa_context_load_module( ctx.get(), "module-null-sink", to_string(name, channel_mapping, channels).c_str(), - cb_i, + reinterpret_cast(cb_i), alarm.get() ), }; @@ -279,7 +276,7 @@ namespace platf { auto alarm = safe::make_alarm(); op_t op { - pa_context_unload_module(ctx.get(), i, success_cb, alarm.get()) + pa_context_unload_module(ctx.get(), i, reinterpret_cast(success_cb), alarm.get()) }; alarm->wait(); @@ -297,14 +294,14 @@ namespace platf { constexpr auto surround51 = "sink-sunshine-surround51"; constexpr auto surround71 = "sink-sunshine-surround71"; - auto alarm = safe::make_alarm(); + const auto alarm = safe::make_alarm(); sink_t sink; // Count of all virtual sinks that are created by us int nullcount = 0; - cb_t f = [&](ctx_t::pointer ctx, const pa_sink_info *sink_info, int eol) { + cb_t f = [&](const pa_context *ctx, const pa_sink_info *sink_info, const int eol) { if (!sink_info) { if (!eol) { BOOST_LOG(error) << "Couldn't get pulseaudio sink info: "sv << pa_strerror(pa_context_errno(ctx)); @@ -332,9 +329,7 @@ namespace platf { } }; - op_t op {pa_context_get_sink_info_list(ctx.get(), cb, &f)}; - - if (!op) { + if (const op_t op {pa_context_get_sink_info_list(ctx.get(), cb, &f)}; !op) { BOOST_LOG(error) << "Couldn't create card info operation: "sv << pa_strerror(pa_context_errno(ctx.get())); return std::nullopt; @@ -346,7 +341,7 @@ namespace platf { return std::nullopt; } - auto sink_name = get_default_sink_name(); + const auto sink_name = get_default_sink_name(); sink.host = sink_name; if (index.stereo == PA_INVALID_INDEX) { @@ -389,9 +384,9 @@ namespace platf { std::string get_default_sink_name() { std::string sink_name; - auto alarm = safe::make_alarm(); + const auto alarm = safe::make_alarm(); - cb_simple_t server_f = [&](ctx_t::pointer ctx, const pa_server_info *server_info) { + cb_simple_t server_f = [&](const pa_context *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)); alarm->ring(-1); @@ -405,19 +400,19 @@ namespace platf { op_t server_op {pa_context_get_server_info(ctx.get(), cb, &server_f)}; alarm->wait(); - // No need to check status. If it failed just return default name. + // No need to check status. If it fails, just return the default name. return sink_name; } std::string get_monitor_name(const std::string &sink_name) { std::string monitor_name; - auto alarm = safe::make_alarm(); + const auto alarm = safe::make_alarm(); if (sink_name.empty()) { return monitor_name; } - cb_t sink_f = [&](ctx_t::pointer ctx, const pa_sink_info *sink_info, int eol) { + cb_t sink_f = [&](const pa_context *ctx, const pa_sink_info *sink_info, const int eol) { if (!sink_info) { if (!eol) { BOOST_LOG(error) << "Couldn't get pulseaudio sink info for ["sv << sink_name @@ -468,11 +463,11 @@ namespace platf { auto alarm = safe::make_alarm(); BOOST_LOG(info) << "Setting default sink to: ["sv << sink << "]"sv; - op_t op { + const op_t op { pa_context_set_default_sink( ctx.get(), sink.c_str(), - success_cb, + reinterpret_cast(success_cb), alarm.get() ), }; diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index 245addb6a..5f905f1ab 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -45,14 +45,14 @@ namespace gl { } } - tex_t tex_t::make(std::size_t count) { + tex_t tex_t::make(const std::size_t count) { tex_t textures {count}; ctx.GenTextures(textures.size(), textures.begin()); - float color[] = {0.0f, 0.0f, 0.0f, 1.0f}; + constexpr float color[] = {0.0f, 0.0f, 0.0f, 1.0f}; - for (auto tex : textures) { + for (const auto tex : textures) { gl::ctx.BindTexture(GL_TEXTURE_2D, tex); gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // x gl::ctx.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // y @@ -70,7 +70,7 @@ namespace gl { } } - frame_buf_t frame_buf_t::make(std::size_t count) { + frame_buf_t frame_buf_t::make(const std::size_t count) { frame_buf_t frame_buf {count}; ctx.GenFramebuffers(frame_buf.size(), frame_buf.begin()); @@ -102,8 +102,8 @@ namespace gl { util::Either shader_t::compile(const std::string_view &source, GLenum type) { shader_t shader; - auto data = source.data(); - GLint length = source.length(); + const auto data = source.data(); + const GLint length = source.length(); shader._shader.el = ctx.CreateShader(type); ctx.ShaderSource(shader.handle(), 1, &data, &length); @@ -149,7 +149,7 @@ namespace gl { ctx.BufferSubData(GL_UNIFORM_BUFFER, offset, view.size(), (const void *) view.data()); } - void buffer_t::update(std::string_view *members, std::size_t count, std::size_t offset) { + void buffer_t::update(const std::string_view *members, std::size_t count, std::size_t offset) { util::buffer_t buffer {_size}; for (int x = 0; x < count; ++x) { @@ -210,7 +210,7 @@ namespace gl { } std::optional program_t::uniform(const char *block, std::pair *members, std::size_t count) { - auto i = ctx.GetUniformBlockIndex(handle(), block); + const auto i = ctx.GetUniformBlockIndex(handle(), block); if (i == GL_INVALID_INDEX) { BOOST_LOG(error) << "Couldn't find index of ["sv << block << ']'; return std::nullopt; @@ -222,8 +222,8 @@ namespace gl { bool error_flag = false; util::buffer_t offsets {count}; - auto indices = (std::uint32_t *) alloca(count * sizeof(std::uint32_t)); - auto names = (const char **) alloca(count * sizeof(const char *)); + const auto indices = (std::uint32_t *) alloca(count * sizeof(std::uint32_t)); + const auto names = (const char **) alloca(count * sizeof(const char *)); auto names_p = names; std::for_each_n(members, count, [names_p](auto &member) mutable { @@ -282,7 +282,7 @@ namespace gbm { } } - std::vector> funcs { + const std::vector> funcs { {(GLADapiproc *) &device_destroy, "gbm_device_destroy"}, {(GLADapiproc *) &create_device, "gbm_create_device"}, }; @@ -535,7 +535,7 @@ namespace egl { } std::optional import_source(display_t::pointer egl_display, const surface_descriptor_t &xrgb) { - auto attribs = surface_descriptor_to_egl_attribs(xrgb); + const auto attribs = surface_descriptor_to_egl_attribs(xrgb); rgb_t rgb { egl_display, @@ -564,7 +564,7 @@ namespace egl { * @param img The image to use for texture sizing. * @return The new RGB texture. */ - rgb_t create_blank(platf::img_t &img) { + rgb_t create_blank(const platf::img_t &img) { rgb_t rgb { EGL_NO_DISPLAY, EGL_NO_IMAGE, @@ -578,9 +578,9 @@ namespace egl { auto framebuf = gl::frame_buf_t::make(1); framebuf.bind(&rgb->tex[0], &rgb->tex[0] + 1); - GLenum attachment = GL_COLOR_ATTACHMENT0; + constexpr GLenum attachment = GL_COLOR_ATTACHMENT0; gl::ctx.DrawBuffers(1, &attachment); - const GLuint rgb_black[] = {0, 0, 0, 0}; + constexpr GLuint rgb_black[] = {0, 0, 0, 0}; gl::ctx.ClearBufferuiv(GL_COLOR, 0, rgb_black); gl_drain_errors; @@ -589,8 +589,8 @@ namespace egl { } std::optional import_target(display_t::pointer egl_display, std::array &&fds, const surface_descriptor_t &y, const surface_descriptor_t &uv) { - auto y_attribs = surface_descriptor_to_egl_attribs(y); - auto uv_attribs = surface_descriptor_to_egl_attribs(uv); + const auto y_attribs = surface_descriptor_to_egl_attribs(y); + const auto uv_attribs = surface_descriptor_to_egl_attribs(uv); nv12_t nv12 { egl_display, @@ -624,8 +624,8 @@ namespace egl { gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, nv12->buf[x]); gl::ctx.DrawBuffers(1, &attachments[x]); - const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; - const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; + constexpr float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; + constexpr float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black); } @@ -643,7 +643,7 @@ namespace egl { * @param format Format of the target frame. * @return The new RGB texture. */ - std::optional create_target(int width, int height, AVPixelFormat format) { + std::optional create_target(const int width, const int height, const AVPixelFormat format) { nv12_t nv12 { EGL_NO_DISPLAY, EGL_NO_IMAGE, @@ -656,7 +656,7 @@ namespace egl { GLint uv_format; // Determine the size of each plane element - auto fmt_desc = av_pix_fmt_desc_get(format); + const auto fmt_desc = av_pix_fmt_desc_get(format); if (fmt_desc->comp[0].depth <= 8) { y_format = GL_R8; uv_format = GL_RG8; @@ -685,8 +685,8 @@ namespace egl { gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, nv12->buf[x]); gl::ctx.DrawBuffers(1, &attachments[x]); - const float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; - const float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; + constexpr float y_black[] = {0.0f, 0.0f, 0.0f, 0.0f}; + constexpr float uv_black[] = {0.5f, 0.5f, 0.5f, 0.5f}; gl::ctx.ClearBufferfv(GL_COLOR, 0, x == 0 ? y_black : uv_black); } @@ -698,7 +698,7 @@ namespace egl { } void sws_t::apply_colorspace(const video::sunshine_colorspace_t &colorspace) { - auto color_p = video::color_vectors_from_colorspace(colorspace); + const auto color_p = video::color_vectors_from_colorspace(colorspace); std::string_view members[] { util::view(color_p->color_vec_y), @@ -719,12 +719,12 @@ namespace egl { sws.serial = std::numeric_limits::max(); - // Ensure aspect ratio is maintained + // Ensure the aspect ratio is maintained auto scalar = std::fminf(out_width / (float) in_width, out_height / (float) in_height); auto out_width_f = in_width * scalar; auto out_height_f = in_height * scalar; - // result is always positive + // the result is always positive auto offsetX_f = (out_width - out_width_f) / 2; auto offsetY_f = (out_height - out_height_f) / 2; @@ -856,12 +856,11 @@ namespace egl { return convert(fb); } - std::optional sws_t::make(int in_width, int in_height, int out_width, int out_height, AVPixelFormat format) { + std::optional sws_t::make(const int in_width, const int in_height, const int out_width, const int out_height, const AVPixelFormat format) { GLint gl_format; - // Decide the bit depth format of the backing texture based the target frame format - auto fmt_desc = av_pix_fmt_desc_get(format); - switch (fmt_desc->comp[0].depth) { + // Decide the bit depth format of the backing texture based on the target frame format + switch (const auto fmt_desc = av_pix_fmt_desc_get(format); fmt_desc->comp[0].depth) { case 8: gl_format = GL_RGBA8; break; @@ -890,14 +889,14 @@ namespace egl { return make(in_width, in_height, out_width, out_height, std::move(tex)); } - void sws_t::load_ram(platf::img_t &img) { + void sws_t::load_ram(const platf::img_t &img) { loaded_texture = tex[0]; gl::ctx.BindTexture(GL_TEXTURE_2D, loaded_texture); gl::ctx.TexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.width, img.height, GL_BGRA, GL_UNSIGNED_BYTE, img.data); } - void sws_t::load_vram(img_descriptor_t &img, int offset_x, int offset_y, int texture) { + void sws_t::load_vram(const img_descriptor_t &img, const int offset_x, const int offset_y, int texture) { // When only a sub-part of the image must be encoded... const bool copy = offset_x || offset_y || img.sd.width != in_width || img.sd.height != in_height; if (copy) { @@ -911,7 +910,7 @@ namespace egl { } if (img.data) { - GLenum attachment = GL_COLOR_ATTACHMENT0; + constexpr GLenum attachment = GL_COLOR_ATTACHMENT0; gl::ctx.BindFramebuffer(GL_FRAMEBUFFER, cursor_framebuffer[0]); gl::ctx.UseProgram(program[2].handle()); diff --git a/src/platform/linux/graphics.h b/src/platform/linux/graphics.h index 00e38943c..f233c3e7d 100644 --- a/src/platform/linux/graphics.h +++ b/src/platform/linux/graphics.h @@ -130,7 +130,7 @@ namespace gl { const char *block() const; void update(const std::string_view &view, std::size_t offset = 0); - void update(std::string_view *members, std::size_t count, std::size_t offset = 0); + void update(const std::string_view *members, std::size_t count, std::size_t offset = 0); private: const char *_block; @@ -246,7 +246,7 @@ namespace egl { const surface_descriptor_t &xrgb ); - rgb_t create_blank(platf::img_t &img); + rgb_t create_blank(const platf::img_t &img); std::optional import_target( display_t::pointer egl_display, @@ -308,8 +308,8 @@ namespace egl { // Make an area of the image black int blank(gl::frame_buf_t &fb, int offsetX, int offsetY, int width, int height); - void load_ram(platf::img_t &img); - void load_vram(img_descriptor_t &img, int offset_x, int offset_y, int texture); + void load_ram(const platf::img_t &img); + void load_vram(const img_descriptor_t &img, int offset_x, int offset_y, int texture); void apply_colorspace(const video::sunshine_colorspace_t &colorspace); diff --git a/src/platform/linux/input/inputtino_gamepad.cpp b/src/platform/linux/input/inputtino_gamepad.cpp index 7e782b59b..ee9c8d022 100644 --- a/src/platform/linux/input/inputtino_gamepad.cpp +++ b/src/platform/linux/input/inputtino_gamepad.cpp @@ -119,8 +119,7 @@ namespace platf::gamepad { switch (selectedGamepadType) { case XboxOneWired: { - auto xOne = create_xbox_one(); - if (xOne) { + if (auto xOne = create_xbox_one()) { (*xOne).set_on_rumble(on_rumble_fn); gamepad->joypad = std::make_unique(std::move(*xOne)); raw->gamepads[id.globalIndex] = std::move(gamepad); @@ -132,8 +131,7 @@ namespace platf::gamepad { } case SwitchProWired: { - auto switchPro = create_switch(); - if (switchPro) { + if (auto switchPro = create_switch()) { (*switchPro).set_on_rumble(on_rumble_fn); gamepad->joypad = std::make_unique(std::move(*switchPro)); raw->gamepads[id.globalIndex] = std::move(gamepad); @@ -145,8 +143,7 @@ namespace platf::gamepad { } case DualSenseWired: { - auto ds5 = create_ds5(id.globalIndex); - if (ds5) { + if (auto ds5 = create_ds5(id.globalIndex)) { (*ds5).set_on_rumble(on_rumble_fn); (*ds5).set_on_led([feedback_queue, idx = id.clientRelativeIndex, gamepad](int r, int g, int b) { // Don't resend duplicate LED data @@ -179,14 +176,14 @@ namespace platf::gamepad { return -1; } - void free(input_raw_t *raw, int nr) { + void free(input_raw_t *raw, const int nr) { // This will call the destructor which in turn will stop the background threads for rumble and LED (and ultimately remove the joypad device) raw->gamepads[nr]->joypad.reset(); raw->gamepads[nr].reset(); } - void update(input_raw_t *raw, int nr, const gamepad_state_t &gamepad_state) { - auto gamepad = raw->gamepads[nr]; + void update(const input_raw_t *raw, const int nr, const gamepad_state_t &gamepad_state) { + const auto gamepad = raw->gamepads[nr]; if (!gamepad) { return; } @@ -200,8 +197,8 @@ namespace platf::gamepad { *gamepad->joypad); } - void touch(input_raw_t *raw, const gamepad_touch_t &touch) { - auto gamepad = raw->gamepads[touch.id.globalIndex]; + void touch(const input_raw_t *raw, const gamepad_touch_t &touch) { + const auto gamepad = raw->gamepads[touch.id.globalIndex]; if (!gamepad) { return; } @@ -215,8 +212,8 @@ namespace platf::gamepad { } } - void motion(input_raw_t *raw, const gamepad_motion_t &motion) { - auto gamepad = raw->gamepads[motion.id.globalIndex]; + void motion(const input_raw_t *raw, const gamepad_motion_t &motion) { + const auto gamepad = raw->gamepads[motion.id.globalIndex]; if (!gamepad) { return; } @@ -233,8 +230,8 @@ namespace platf::gamepad { } } - void battery(input_raw_t *raw, const gamepad_battery_t &battery) { - auto gamepad = raw->gamepads[battery.id.globalIndex]; + void battery(const input_raw_t *raw, const gamepad_battery_t &battery) { + const auto gamepad = raw->gamepads[battery.id.globalIndex]; if (!gamepad) { return; } @@ -262,7 +259,7 @@ namespace platf::gamepad { } } - std::vector &supported_gamepads(input_t *input) { + std::vector &supported_gamepads(const input_t *input) { if (!input) { static std::vector gps { supported_gamepad_t {"auto", true, ""}, diff --git a/src/platform/linux/input/inputtino_gamepad.h b/src/platform/linux/input/inputtino_gamepad.h index 8d26c9e1f..e08f82524 100644 --- a/src/platform/linux/input/inputtino_gamepad.h +++ b/src/platform/linux/input/inputtino_gamepad.h @@ -27,13 +27,13 @@ namespace platf::gamepad { void free(input_raw_t *raw, int nr); - void update(input_raw_t *raw, int nr, const gamepad_state_t &gamepad_state); + void update(const input_raw_t *raw, int nr, const gamepad_state_t &gamepad_state); - void touch(input_raw_t *raw, const gamepad_touch_t &touch); + void touch(const input_raw_t *raw, const gamepad_touch_t &touch); - void motion(input_raw_t *raw, const gamepad_motion_t &motion); + void motion(const input_raw_t *raw, const gamepad_motion_t &motion); - void battery(input_raw_t *raw, const gamepad_battery_t &battery); + void battery(const input_raw_t *raw, const gamepad_battery_t &battery); - std::vector &supported_gamepads(input_t *input); + std::vector &supported_gamepads(const input_t *input); } // namespace platf::gamepad diff --git a/src/platform/linux/input/inputtino_mouse.cpp b/src/platform/linux/input/inputtino_mouse.cpp index f8d822de2..765178cfd 100644 --- a/src/platform/linux/input/inputtino_mouse.cpp +++ b/src/platform/linux/input/inputtino_mouse.cpp @@ -31,7 +31,7 @@ namespace platf::mouse { } } - void button(input_raw_t *raw, int button, bool release) { + void button(input_raw_t *raw, const int button, const bool release) { if (raw->mouse) { inputtino::Mouse::MOUSE_BUTTON btn_type; switch (button) { @@ -62,19 +62,19 @@ namespace platf::mouse { } } - void scroll(input_raw_t *raw, int high_res_distance) { + void scroll(input_raw_t *raw, const int high_res_distance) { if (raw->mouse) { (*raw->mouse).vertical_scroll(high_res_distance); } } - void hscroll(input_raw_t *raw, int high_res_distance) { + void hscroll(input_raw_t *raw, const int high_res_distance) { if (raw->mouse) { (*raw->mouse).horizontal_scroll(high_res_distance); } } - util::point_t get_location(input_raw_t *raw) { + util::point_t get_location(const input_raw_t *raw) { if (raw->mouse) { // TODO: decide what to do after https://github.com/games-on-whales/inputtino/issues/6 is resolved. // TODO: auto x = (*raw->mouse).get_absolute_x(); diff --git a/src/platform/linux/input/inputtino_mouse.h b/src/platform/linux/input/inputtino_mouse.h index 67eaf97af..495987ef4 100644 --- a/src/platform/linux/input/inputtino_mouse.h +++ b/src/platform/linux/input/inputtino_mouse.h @@ -25,5 +25,5 @@ namespace platf::mouse { void hscroll(input_raw_t *raw, int high_res_distance); - util::point_t get_location(input_raw_t *raw); + util::point_t get_location(const input_raw_t *raw); } // namespace platf::mouse diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 3db748999..984cc9ab3 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -123,7 +123,7 @@ namespace platf { static int env_width; static int env_height; - std::string_view plane_type(std::uint64_t val) { + std::string_view plane_type(const std::uint64_t val) { switch (val) { case DRM_PLANE_TYPE_OVERLAY: return "DRM_PLANE_TYPE_OVERLAY"sv; @@ -137,13 +137,13 @@ namespace platf { } struct connector_t { - // For example: HDMI-A or HDMI + // For example, HDMI-A or HDMI std::uint32_t type; // Equals zero if not applicable std::uint32_t crtc_id; - // For example HDMI-A-{index} or HDMI-{index} + // For example, HDMI-A-{index} or HDMI-{index} std::uint32_t index; // ID of the connector @@ -230,14 +230,14 @@ namespace platf { class plane_it_t: public round_robin_util::it_wrap_t { public: - plane_it_t(int fd, std::uint32_t *plane_p, std::uint32_t *end): + plane_it_t(const int fd, std::uint32_t *plane_p, std::uint32_t *end): fd {fd}, plane_p {plane_p}, end {end} { load_next_valid_plane(); } - plane_it_t(int fd, std::uint32_t *end): + plane_it_t(const int fd, std::uint32_t *end): fd {fd}, plane_p {end}, end {end} { @@ -310,8 +310,7 @@ namespace platf { // 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) { + if (char *rendernode_path = drmGetRenderDeviceNameFromFd(fd.el)) { BOOST_LOG(debug) << "Opening render node: "sv << rendernode_path; render_fd.el = open(rendernode_path, O_RDWR); if (render_fd.el < 0) { @@ -351,27 +350,25 @@ namespace platf { return 0; } - fb_t fb(plane_t::pointer plane) { + fb_t fb(const plane_t::pointer plane) { cap_sys_admin admin; - auto fb2 = drmModeGetFB2(fd.el, plane->fb_id); - if (fb2) { + if (auto fb2 = drmModeGetFB2(fd.el, plane->fb_id)) { return std::make_unique(fb2); } - auto fb = drmModeGetFB(fd.el, plane->fb_id); - if (fb) { + if (auto fb = drmModeGetFB(fd.el, plane->fb_id)) { return std::make_unique(fb); } return nullptr; } - crtc_t crtc(std::uint32_t id) { + crtc_t crtc(const std::uint32_t id) { return drmModeGetCrtc(fd.el, id); } - encoder_t encoder(std::uint32_t id) { + encoder_t encoder(const std::uint32_t id) { return drmModeGetEncoder(fd.el, id); } @@ -384,9 +381,8 @@ namespace platf { return ver && ver->name && strncmp(ver->name, "nvidia-drm", 10) == 0; } - bool is_cursor(std::uint32_t plane_id) { - auto props = plane_props(plane_id); - for (auto &[prop, val] : props) { + bool is_cursor(const std::uint32_t plane_id) { + for (auto props = plane_props(plane_id); auto &[prop, val] : props) { if (prop->name == "type"sv) { if (val == DRM_PLANE_TYPE_CURSOR) { return true; @@ -399,7 +395,7 @@ namespace platf { return false; } - std::optional prop_value_by_name(const std::vector> &props, std::string_view name) { + std::optional prop_value_by_name(const std::vector> &props, const std::string_view name) { for (auto &[prop, val] : props) { if (prop->name == name) { return val; @@ -409,9 +405,8 @@ namespace platf { } std::uint32_t get_panel_orientation(std::uint32_t plane_id) { - auto props = plane_props(plane_id); - auto value = prop_value_by_name(props, "rotation"sv); - if (value) { + const auto props = plane_props(plane_id); + if (const auto value = prop_value_by_name(props, "rotation"sv)) { return *value; } @@ -419,7 +414,7 @@ namespace platf { return DRM_MODE_ROTATE_0; } - int get_crtc_index_by_id(std::uint32_t crtc_id) { + int get_crtc_index_by_id(const std::uint32_t crtc_id) { auto resources = res(); for (int i = 0; i < resources->count_crtcs; i++) { if (resources->crtcs[i] == crtc_id) { @@ -429,7 +424,7 @@ namespace platf { return -1; } - connector_interal_t connector(std::uint32_t id) { + connector_interal_t connector(const std::uint32_t id) { return drmModeGetConnector(fd.el, id); } @@ -441,19 +436,18 @@ namespace platf { } std::vector monitors; - std::for_each_n(resources->connectors, resources->count_connectors, [this, &conn_type_count, &monitors](std::uint32_t id) { + std::for_each_n(resources->connectors, resources->count_connectors, [this, &conn_type_count, &monitors](const std::uint32_t id) { auto conn = connector(id); std::uint32_t crtc_id = 0; if (conn->encoder_id) { - auto enc = encoder(conn->encoder_id); - if (enc) { + if (auto enc = encoder(conn->encoder_id)) { crtc_id = enc->crtc_id; } } - auto index = ++conn_type_count[conn->connector_type]; + const auto index = ++conn_type_count[conn->connector_type]; monitors.emplace_back(connector_t { conn->connector_type, @@ -467,18 +461,17 @@ namespace platf { return monitors; } - file_t handleFD(std::uint32_t handle) { + file_t handleFD(const std::uint32_t handle) { file_t fb_fd; - auto status = drmPrimeHandleToFD(fd.el, handle, 0 /* flags */, &fb_fd.el); - if (status) { + if (drmPrimeHandleToFD(fd.el, handle, 0 /* flags */, &fb_fd.el)) { return {}; } return fb_fd; } - std::vector> props(std::uint32_t id, std::uint32_t type) { + std::vector> props(const std::uint32_t id, const std::uint32_t type) { obj_prop_t obj_prop = drmModeObjectGetProperties(fd.el, id, type); if (!obj_prop) { return {}; @@ -547,7 +540,7 @@ namespace platf { } }; - void print(plane_t::pointer plane, fb_t::pointer fb, crtc_t::pointer crtc) { + void print(const plane_t::pointer plane, const fb_t::pointer fb, const 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 << ')'; @@ -592,8 +585,7 @@ namespace platf { int monitor_index = util::from_view(display_name); int monitor = 0; - fs::path card_dir {"/dev/dri"sv}; - for (auto &entry : fs::directory_iterator {card_dir}) { + for (fs::path card_dir {"/dev/dri"sv}; auto &entry : fs::directory_iterator {card_dir}) { auto file = entry.path().filename(); auto filestring = file.generic_string(); @@ -647,8 +639,7 @@ namespace platf { break; } - auto fb_fd = card.handleFD(fb->handles[i]); - if (fb_fd.el < 0) { + if (auto fb_fd = card.handleFD(fb->handles[i]); fb_fd.el < 0) { BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno); continue; } @@ -663,7 +654,7 @@ namespace platf { BOOST_LOG(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(card_descriptors), std::end(card_descriptors), [&](card_descriptor_t &cd) { + auto pos = std::find_if(std::begin(card_descriptors), std::end(card_descriptors), [&](const card_descriptor_t &cd) { return cd.path == filestring; }); @@ -724,8 +715,7 @@ namespace platf { crtc_index = card.get_crtc_index_by_id(plane->crtc_id); // Find the connector for this CRTC - kms::conn_type_count_t conn_type_count; - for (auto &connector : card.monitors(conn_type_count)) { + for (kms::conn_type_count_t conn_type_count; auto &connector : card.monitors(conn_type_count)) { if (connector.crtc_id == crtc_id) { BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']'; @@ -1049,7 +1039,7 @@ namespace platf { plane_t plane = drmModeGetPlane(card.fd.el, plane_id); frame_timestamp = std::chrono::steady_clock::now(); - auto fb = card.fb(plane.get()); + const 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); @@ -1177,8 +1167,7 @@ namespace platf { } std::shared_ptr img_out; - auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor); - switch (status) { + switch (auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor)) { case platf::capture_e::reinit: case platf::capture_e::error: case platf::capture_e::interrupted: @@ -1221,42 +1210,41 @@ namespace platf { void blend_cursor(img_t &img) { // TODO: Cursor scaling is not supported in this codepath. // We always draw the cursor at the source size. - auto pixels = (int *) img.data; + const auto pixels = (int *) img.data; - int32_t screen_height = img.height; - int32_t screen_width = img.width; + const int32_t screen_height = img.height; + const int32_t screen_width = img.width; // This is the position in the target that we will start drawing the cursor - auto cursor_x = std::max(0, captured_cursor.x - img_offset_x); - auto cursor_y = std::max(0, captured_cursor.y - img_offset_y); + const auto cursor_x = std::max(0, captured_cursor.x - img_offset_x); + const auto cursor_y = std::max(0, captured_cursor.y - img_offset_y); - // If the cursor is partially off screen, the coordinates may be negative + // If the cursor is partially off-screen, the coordinates may be negative // which means we will draw the top-right visible portion of the cursor only. - auto cursor_delta_x = cursor_x - std::max(-captured_cursor.src_w, captured_cursor.x - img_offset_x); - auto cursor_delta_y = cursor_y - std::max(-captured_cursor.src_h, captured_cursor.y - img_offset_y); + const auto cursor_delta_x = cursor_x - std::max(-captured_cursor.src_w, captured_cursor.x - img_offset_x); + const auto cursor_delta_y = cursor_y - std::max(-captured_cursor.src_h, captured_cursor.y - img_offset_y); - auto delta_height = std::min(captured_cursor.src_h, std::max(0, screen_height - cursor_y)) - cursor_delta_y; - auto delta_width = std::min(captured_cursor.src_w, std::max(0, screen_width - cursor_x)) - cursor_delta_x; + const auto delta_height = std::min(captured_cursor.src_h, std::max(0, screen_height - cursor_y)) - cursor_delta_y; + const auto delta_width = std::min(captured_cursor.src_w, std::max(0, screen_width - cursor_x)) - cursor_delta_x; for (auto y = 0; y < delta_height; ++y) { // Offset into the cursor image to skip drawing the parts of the cursor image that are off screen // // NB: We must access the elements via the data() function because cursor_end may point to the - // the first element beyond the valid range of the vector. Using vector's [] operator in that + // first element beyond the valid range of the vector. Using vector's [] operator in that // manner is undefined behavior (and triggers errors when using debug libc++), while doing the // same with an array is fine. - auto cursor_begin = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + cursor_delta_x) * 4]; - auto cursor_end = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + delta_width + cursor_delta_x) * 4]; + const auto cursor_begin = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + cursor_delta_x) * 4]; + const auto cursor_end = (uint32_t *) &captured_cursor.pixels.data()[((y + cursor_delta_y) * captured_cursor.src_w + delta_width + cursor_delta_x) * 4]; auto pixels_begin = &pixels[(y + cursor_y) * (img.row_pitch / img.pixel_pitch) + cursor_x]; std::for_each(cursor_begin, cursor_end, [&](uint32_t cursor_pixel) { - auto colors_in = (uint8_t *) pixels_begin; + const auto colors_in = (uint8_t *) pixels_begin; - auto alpha = (*(uint *) &cursor_pixel) >> 24u; - if (alpha == 255) { + if (const auto alpha = (*(uint *) &cursor_pixel) >> 24u; alpha == 255) { *pixels_begin = cursor_pixel; } else { - auto colors_out = (uint8_t *) &cursor_pixel; + const auto colors_out = (uint8_t *) &cursor_pixel; colors_in[0] = colors_out[0] + (colors_in[0] * (255 - alpha) + 255 / 2) / 255; colors_in[1] = colors_out[1] + (colors_in[1] * (255 - alpha) + 255 / 2) / 255; colors_in[2] = colors_out[2] + (colors_in[2] * (255 - alpha) + 255 / 2) / 255; @@ -1391,8 +1379,7 @@ namespace platf { } std::shared_ptr img_out; - auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor); - switch (status) { + switch (auto status = snapshot(pull_free_image_cb, img_out, 1000ms, *cursor)) { case platf::capture_e::reinit: case platf::capture_e::error: case platf::capture_e::interrupted: @@ -1422,11 +1409,10 @@ namespace platf { if (!pull_free_image_cb(img_out)) { return platf::capture_e::interrupted; } - auto img = (egl::img_descriptor_t *) img_out.get(); + const auto img = (egl::img_descriptor_t *) img_out.get(); img->reset(); - auto status = refresh(fb_fd, &img->sd, img->frame_timestamp); - if (status != capture_e::ok) { + if (const auto status = refresh(fb_fd, &img->sd, img->frame_timestamp); status != capture_e::ok) { return status; } @@ -1487,9 +1473,7 @@ namespace platf { std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) { if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda) { - auto disp = std::make_shared(hwdevice_type); - - if (!disp->init(display_name, config)) { + if (auto disp = std::make_shared(hwdevice_type); !disp->init(display_name, config)) { return disp; } @@ -1516,7 +1500,7 @@ namespace platf { * This is an ugly hack :( */ void correlate_to_wayland(std::vector &cds) { - auto monitors = wl::monitors(); + const auto monitors = wl::monitors(); BOOST_LOG(info) << "-------- Start of KMS monitor list --------"sv; @@ -1526,7 +1510,7 @@ namespace platf { // Try to convert names in the format: // {type}-{index} // {index} is n'th occurrence of {type} - auto index_begin = name.find_last_of('-'); + const auto index_begin = name.find_last_of('-'); std::uint32_t index; if (index_begin == std::string_view::npos) { @@ -1647,8 +1631,7 @@ namespace platf { continue; } - auto it = crtc_to_monitor.find(plane->crtc_id); - if (it != std::end(crtc_to_monitor)) { + if (auto it = crtc_to_monitor.find(plane->crtc_id); it != std::end(crtc_to_monitor)) { it->second.viewport = platf::touch_port_t { (int) crtc->x, (int) crtc->y, diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 9da873372..924ebc3d0 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -49,11 +49,8 @@ window_system_e window_system; namespace dyn { void *handle(const std::vector &libs) { - void *handle; - - for (auto lib : libs) { - handle = dlopen(lib, RTLD_LAZY | RTLD_LOCAL); - if (handle) { + for (const auto lib : libs) { + if (void *handle = dlopen(lib, RTLD_LAZY | RTLD_LOCAL)) { return handle; } } @@ -115,7 +112,6 @@ namespace platf { bool migrate_config = true; const char *dir; const char *homedir; - const char *migrate_envvar; // Get the home directory if ((homedir = getenv("HOME")) == nullptr || strlen(homedir) == 0) { @@ -141,11 +137,9 @@ namespace platf { } // migrate from the old config location if necessary - migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); - if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { - std::error_code ec; - fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; - if (old_config_path != config_path && fs::exists(old_config_path, ec)) { + if (const char *migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG"); migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) { + const fs::path old_config_path = fs::path(homedir) / ".config/sunshine"sv; + if (std::error_code ec; old_config_path != config_path && fs::exists(old_config_path, ec)) { if (!fs::exists(config_path, ec)) { std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl; if (!ec) { @@ -186,8 +180,7 @@ namespace platf { std::string from_sockaddr(const sockaddr *const ip_addr) { char data[INET6_ADDRSTRLEN] = {}; - auto family = ip_addr->sa_family; - if (family == AF_INET6) { + if (const auto family = ip_addr->sa_family; family == AF_INET6) { inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN); } else if (family == AF_INET) { inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN); @@ -199,7 +192,7 @@ namespace platf { std::pair from_sockaddr_ex(const sockaddr *const ip_addr) { char data[INET6_ADDRSTRLEN] = {}; - auto family = ip_addr->sa_family; + const auto family = ip_addr->sa_family; std::uint16_t port = 0; if (family == AF_INET6) { inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN); @@ -216,8 +209,7 @@ namespace platf { auto ifaddrs = get_ifaddrs(); for (auto pos = ifaddrs.get(); pos != nullptr; pos = pos->ifa_next) { if (pos->ifa_addr && address == from_sockaddr(pos->ifa_addr)) { - std::ifstream mac_file("/sys/class/net/"s + pos->ifa_name + "/address"); - if (mac_file.good()) { + if (std::ifstream mac_file("/sys/class/net/"s + pos->ifa_name + "/address"); mac_file.good()) { std::string mac_address; std::getline(mac_file, mac_address); return mac_address; @@ -229,7 +221,7 @@ namespace platf { return "00:00:00:00:00:00"s; } - bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { + bp::child run_command(bool elevated, bool interactive, const std::string &cmd, const boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { // clang-format off if (!group) { if (!file) { @@ -256,10 +248,10 @@ namespace platf { */ void open_url(const std::string &url) { // set working dir to user home directory - auto working_dir = boost::filesystem::path(std::getenv("HOME")); - std::string cmd = R"(xdg-open ")" + url + R"(")"; + const auto working_dir = boost::filesystem::path(std::getenv("HOME")); + const std::string cmd = R"(xdg-open ")" + url + R"(")"; - boost::process::v1::environment _env = boost::this_process::environment(); + const boost::process::v1::environment _env = boost::this_process::environment(); std::error_code ec; auto child = run_command(false, false, cmd, working_dir, _env, nullptr, ec, nullptr); if (ec) { @@ -284,7 +276,7 @@ namespace platf { void restart_on_exit() { char executable[PATH_MAX]; - ssize_t len = readlink("/proc/self/exe", executable, PATH_MAX - 1); + const ssize_t len = readlink("/proc/self/exe", executable, PATH_MAX - 1); if (len == -1) { BOOST_LOG(fatal) << "readlink() failed: "sv << errno; return; @@ -292,7 +284,7 @@ namespace platf { executable[len] = '\0'; // ASIO doesn't use O_CLOEXEC, so we have to close all fds ourselves - int openmax = (int) sysconf(_SC_OPEN_MAX); + const int openmax = (int) sysconf(_SC_OPEN_MAX); for (int fd = STDERR_FILENO + 1; fd < openmax; fd++) { close(fd); } @@ -318,7 +310,7 @@ namespace platf { return unsetenv(name.c_str()); } - bool request_process_group_exit(std::uintptr_t native_handle) { + bool request_process_group_exit(const 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; return true; @@ -328,30 +320,30 @@ namespace platf { } } - bool process_group_running(std::uintptr_t native_handle) { + bool process_group_running(const std::uintptr_t native_handle) { return waitpid(-((pid_t) native_handle), nullptr, WNOHANG) >= 0; } - struct sockaddr_in to_sockaddr(boost::asio::ip::address_v4 address, uint16_t port) { + struct sockaddr_in to_sockaddr(const boost::asio::ip::address_v4 &address, const uint16_t port) { struct sockaddr_in saddr_v4 = {}; saddr_v4.sin_family = AF_INET; saddr_v4.sin_port = htons(port); - auto addr_bytes = address.to_bytes(); + const auto addr_bytes = address.to_bytes(); memcpy(&saddr_v4.sin_addr, addr_bytes.data(), sizeof(saddr_v4.sin_addr)); return saddr_v4; } - struct sockaddr_in6 to_sockaddr(boost::asio::ip::address_v6 address, uint16_t port) { + struct sockaddr_in6 to_sockaddr(const boost::asio::ip::address_v6 &address, const uint16_t port) { struct sockaddr_in6 saddr_v6 = {}; saddr_v6.sin6_family = AF_INET6; saddr_v6.sin6_port = htons(port); saddr_v6.sin6_scope_id = address.scope_id(); - auto addr_bytes = address.to_bytes(); + const auto addr_bytes = address.to_bytes(); memcpy(&saddr_v6.sin6_addr, addr_bytes.data(), sizeof(saddr_v6.sin6_addr)); return saddr_v6; @@ -423,7 +415,7 @@ namespace platf { { // UDP GSO on Linux currently only supports sending 64K or 64 segments at a time size_t seg_index = 0; - const size_t seg_max = 65536 / 1500; + constexpr size_t seg_max = 65536 / 1500; struct iovec iovs[(send_info.headers ? std::min(seg_max, send_info.block_count) : 1) * max_iovs_per_msg]; auto msg_size = send_info.header_size + send_info.payload_size; while (seg_index < send_info.block_count) { @@ -564,8 +556,8 @@ namespace platf { } } - bool send(send_info_t &send_info) { - auto sockfd = (int) send_info.native_socket; + bool send(const send_info_t &send_info) { + const auto sockfd = (int) send_info.native_socket; struct msghdr msg = {}; // Convert the target address into a sockaddr @@ -593,11 +585,11 @@ namespace platf { msg.msg_control = cmbuf.buf; msg.msg_controllen = sizeof(cmbuf.buf); - auto pktinfo_cm = CMSG_FIRSTHDR(&msg); + const auto pktinfo_cm = CMSG_FIRSTHDR(&msg); if (send_info.source_address.is_v6()) { struct in6_pktinfo pktInfo; - struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); + const struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0); pktInfo.ipi6_addr = saddr_v6.sin6_addr; pktInfo.ipi6_ifindex = 0; @@ -610,7 +602,7 @@ namespace platf { } else { struct in_pktinfo pktInfo; - struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); + const struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0); pktInfo.ipi_spec_dst = saddr_v4.sin_addr; pktInfo.ipi_ifindex = 0; @@ -671,7 +663,7 @@ namespace platf { class qos_t: public deinit_t { public: - qos_t(int sockfd, std::vector> options): + qos_t(const int sockfd, const std::vector> &options): sockfd(sockfd), options(options) { qos_ref_count++; @@ -701,7 +693,7 @@ namespace platf { * @param data_type The type of traffic sent on this socket. * @param dscp_tagging Specifies whether to enable DSCP tagging on outgoing traffic. */ - std::unique_ptr enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging) { + std::unique_ptr enable_socket_qos(const uintptr_t native_socket, const boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, const bool dscp_tagging) { int sockfd = (int) native_socket; std::vector> reset_options; @@ -753,7 +745,7 @@ namespace platf { // reset SO_PRIORITY back to 0. // // 6 is the highest priority that can be used without SYS_CAP_ADMIN. - int priority = data_type == qos_data_type_e::audio ? 6 : 5; + const 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)); diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index a2bac72f8..ecd0bf2df 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -218,7 +218,7 @@ namespace avahi { } } - std::vector> funcs { + const std::vector> funcs { {(dyn::apiproc *) &alternative_service_name, "avahi_alternative_service_name"}, {(dyn::apiproc *) &free, "avahi_free"}, {(dyn::apiproc *) &strdup, "avahi_strdup"}, @@ -257,7 +257,7 @@ namespace avahi { } } - std::vector> funcs { + const std::vector> funcs { {(dyn::apiproc *) &client_new, "avahi_client_new"}, {(dyn::apiproc *) &client_free, "avahi_client_free"}, {(dyn::apiproc *) &entry_group_get_client, "avahi_entry_group_get_client"}, @@ -299,7 +299,7 @@ namespace platf::publish { void create_services(avahi::Client *c); - void entry_group_callback(avahi::EntryGroup *g, avahi::EntryGroupState state, void *) { + void entry_group_callback(avahi::EntryGroup *g, const avahi::EntryGroupState state, const void *) { group = g; switch (state) { @@ -323,14 +323,12 @@ namespace platf::publish { } void create_services(avahi::Client *c) { - int ret; - auto fg = util::fail_guard([]() { avahi::simple_poll_quit(poll.get()); }); if (!group) { - if (!(group = avahi::entry_group_new(c, entry_group_callback, nullptr))) { + if (!(group = avahi::entry_group_new(c, reinterpret_cast(entry_group_callback), nullptr))) { BOOST_LOG(error) << "avahi::entry_group_new() failed: "sv << avahi::strerror(avahi::client_errno(c)); return; } @@ -339,7 +337,7 @@ namespace platf::publish { if (avahi::entry_group_is_empty(group)) { BOOST_LOG(info) << "Adding avahi service "sv << name.get(); - ret = avahi::entry_group_add_service( + int ret = avahi::entry_group_add_service( group, avahi::IF_UNSPEC, avahi::PROTO_UNSPEC, @@ -380,7 +378,7 @@ namespace platf::publish { fg.disable(); } - void client_callback(avahi::Client *c, avahi::ClientState state, void *) { + void client_callback(avahi::Client *c, const avahi::ClientState state, const void *) { switch (state) { case avahi::CLIENT_S_RUNNING: create_services(c); @@ -431,11 +429,11 @@ namespace platf::publish { return nullptr; } - auto instance_name = net::mdns_instance_name(platf::get_host_name()); + const auto instance_name = net::mdns_instance_name(platf::get_host_name()); name.reset(avahi::strdup(instance_name.c_str())); client.reset( - avahi::client_new(avahi::simple_poll_get(poll.get()), avahi::ClientFlags(0), client_callback, nullptr, &avhi_error) + avahi::client_new(avahi::simple_poll_get(poll.get()), static_cast(0), reinterpret_cast(client_callback), nullptr, &avhi_error) ); if (!client) { diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index e0cc7930d..b0fcac256 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -97,7 +97,7 @@ namespace va { class va_t: public platf::avcodec_encode_device_t { public: - int init(int in_width, int in_height, file_t &&render_device) { + int init(const int in_width, const int in_height, file_t &&render_device) { file = std::move(render_device); if (!gbm::create_device) { @@ -137,11 +137,10 @@ namespace va { * @param profile The profile to match. * @return A valid encoding entrypoint or 0 on failure. */ - VAEntrypoint select_va_entrypoint(VAProfile profile) { + VAEntrypoint select_va_entrypoint(const VAProfile profile) { std::vector entrypoints(vaMaxNumEntrypoints(va_display)); int num_eps; - auto status = vaQueryConfigEntrypoints(va_display, profile, entrypoints.data(), &num_eps); - if (status != VA_STATUS_SUCCESS) { + if (const auto status = vaQueryConfigEntrypoints(va_display, profile, entrypoints.data(), &num_eps); status != VA_STATUS_SUCCESS) { BOOST_LOG(error) << "Failed to query VA entrypoints: "sv << vaErrorStr(status); return (VAEntrypoint) 0; } @@ -167,7 +166,7 @@ namespace va { * @param profile The profile to match. * @return Boolean value indicating if the profile is supported. */ - bool is_va_profile_supported(VAProfile profile) { + bool is_va_profile_supported(const VAProfile profile) { std::vector profiles(vaMaxNumProfiles(va_display)); int num_profs; auto status = vaQueryConfigProfiles(va_display, profiles.data(), &num_profs); @@ -185,7 +184,7 @@ namespace va { * @param ctx The FFmpeg codec context. * @return The matching VA profile or `VAProfileNone` on failure. */ - VAProfile get_va_profile(AVCodecContext *ctx) { + VAProfile get_va_profile(const AVCodecContext *ctx) { if (ctx->codec_id == AV_CODEC_ID_H264) { // There's no VAAPI profile for H.264 4:4:4 return VAProfileH264High; @@ -218,19 +217,19 @@ namespace va { } void init_codec_options(AVCodecContext *ctx, AVDictionary **options) override { - auto va_profile = get_va_profile(ctx); + const auto va_profile = get_va_profile(ctx); if (va_profile == VAProfileNone || !is_va_profile_supported(va_profile)) { // Don't bother doing anything if the profile isn't supported return; } - auto va_entrypoint = select_va_entrypoint(va_profile); + const auto va_entrypoint = select_va_entrypoint(va_profile); if (va_entrypoint == 0) { // It's possible that only decoding is supported for this profile return; } - auto vendor = vaQueryVendorString(va_display); + const auto vendor = vaQueryVendorString(va_display); if (va_entrypoint == VAEntrypointEncSliceLP) { BOOST_LOG(info) << "Using LP encoding mode"sv; @@ -303,10 +302,10 @@ namespace va { } va::DRMPRIMESurfaceDescriptor prime; - va::VASurfaceID surface = (std::uintptr_t) frame->data[3]; - auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data; + const va::VASurfaceID surface = (std::uintptr_t) frame->data[3]; + const auto hw_frames_ctx = (AVHWFramesContext *) hw_frames_ctx_buf->data; - auto status = vaExportSurfaceHandle( + const auto status = vaExportSurfaceHandle( this->va_display, surface, va::SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, @@ -402,7 +401,7 @@ namespace va { class va_vram_t: public va_t { public: int convert(platf::img_t &img) override { - auto &descriptor = (egl::img_descriptor_t &) img; + const auto &descriptor = (egl::img_descriptor_t &) img; if (descriptor.sequence == 0) { // For dummy images, use a blank RGB texture instead of importing a DMA-BUF @@ -427,7 +426,7 @@ namespace va { return 0; } - int init(int in_width, int in_height, file_t &&render_device, int offset_x, int offset_y) { + int init(const int in_width, const int in_height, file_t &&render_device, const int offset_x, const int offset_y) { if (va_t::init(in_width, in_height, std::move(render_device))) { return -1; } @@ -495,7 +494,7 @@ namespace va { } int vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *base, AVBufferRef **hw_device_buf) { - auto va = (va::va_t *) base; + const auto va = (va::va_t *) base; auto fd = dup(va->file.el); auto *priv = (VAAPIDevicePriv *) av_mallocz(sizeof(VAAPIDevicePriv)); @@ -508,7 +507,7 @@ namespace va { va::display_t display {vaGetDisplayDRM(fd)}; if (!display) { - auto render_device = config::video.adapter_name.empty() ? "/dev/dri/renderD128" : config::video.adapter_name.c_str(); + const auto render_device = config::video.adapter_name.empty() ? "/dev/dri/renderD128" : config::video.adapter_name.c_str(); BOOST_LOG(error) << "Couldn't open a va display from DRM with device: "sv << render_device; return -1; @@ -520,8 +519,7 @@ namespace va { vaSetErrorCallback(display.get(), __log, &info); int major, minor; - auto status = vaInitialize(display.get(), &major, &minor); - if (status) { + if (const auto status = vaInitialize(display.get(), &major, &minor)) { BOOST_LOG(error) << "Couldn't initialize va display: "sv << vaErrorStr(status); return -1; } @@ -529,8 +527,8 @@ namespace va { BOOST_LOG(info) << "vaapi vendor: "sv << vaQueryVendorString(display.get()); *hw_device_buf = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI); - auto ctx = (AVHWDeviceContext *) (*hw_device_buf)->data; - auto hwctx = (AVVAAPIDeviceContext *) ctx->hwctx; + const auto ctx = (AVHWDeviceContext *) (*hw_device_buf)->data; + const auto hwctx = (AVVAAPIDeviceContext *) ctx->hwctx; // Ownership of the VADisplay and DRM fd is now ours to manage via the free() function hwctx->display = display.release(); @@ -538,8 +536,7 @@ namespace va { ctx->free = vaapi_hwdevice_ctx_free; fg.disable(); - auto err = av_hwdevice_ctx_init(*hw_device_buf); - if (err) { + if (const auto err = av_hwdevice_ctx_init(*hw_device_buf)) { char err_str[AV_ERROR_MAX_STRING_SIZE] {0}; BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err); @@ -554,14 +551,13 @@ namespace va { entrypoints.resize(vaMaxNumEntrypoints(display)); int count; - auto status = vaQueryConfigEntrypoints(display, profile, entrypoints.data(), &count); - if (status) { + if (const auto status = vaQueryConfigEntrypoints(display, profile, entrypoints.data(), &count)) { BOOST_LOG(error) << "Couldn't query entrypoints: "sv << vaErrorStr(status); return false; } entrypoints.resize(count); - for (auto entrypoint : entrypoints) { + for (const auto entrypoint : entrypoints) { if (entrypoint == VAEntrypointEncSlice || entrypoint == VAEntrypointEncSliceLP) { return true; } @@ -575,7 +571,7 @@ namespace va { if (!display) { char string[1024]; - auto bytes = readlink(std::format("/proc/self/fd/{}", fd).c_str(), string, sizeof(string)); + const auto bytes = readlink(std::format("/proc/self/fd/{}", fd).c_str(), string, sizeof(string)); std::string_view render_device {string, (std::size_t) bytes}; @@ -584,8 +580,7 @@ namespace va { } int major, minor; - auto status = vaInitialize(display.get(), &major, &minor); - if (status) { + if (const auto status = vaInitialize(display.get(), &major, &minor)) { BOOST_LOG(error) << "Couldn't initialize va display: "sv << vaErrorStr(status); return false; } @@ -626,7 +621,7 @@ namespace va { } std::unique_ptr make_avcodec_encode_device(int width, int height, int offset_x, int offset_y, bool vram) { - auto render_device = config::video.adapter_name.empty() ? "/dev/dri/renderD128" : config::video.adapter_name.c_str(); + const auto render_device = config::video.adapter_name.empty() ? "/dev/dri/renderD128" : config::video.adapter_name.c_str(); file_t file = open(render_device, O_RDWR); if (file.el < 0) { diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 4fa05a277..68e5b6397 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -78,7 +78,7 @@ namespace wl { * @param timeout The timeout in milliseconds. * @return `true` if new events were dispatched or `false` if the timeout expired. */ - bool display_t::dispatch(std::chrono::milliseconds timeout) { + bool display_t::dispatch(const std::chrono::milliseconds timeout) { // Check if any events are queued already. If not, flush // outgoing events, and prepare to wait for readability. if (wl_display_prepare_read(display_internal.get()) == 0) { @@ -136,22 +136,22 @@ namespace wl { BOOST_LOG(info) << "Found monitor: "sv << this->description; } - void monitor_t::xdg_position(zxdg_output_v1 *, std::int32_t x, std::int32_t y) { + void monitor_t::xdg_position(zxdg_output_v1 *, const std::int32_t x, const std::int32_t y) { viewport.offset_x = x; viewport.offset_y = y; BOOST_LOG(info) << "Offset: "sv << x << 'x' << y; } - void monitor_t::xdg_size(zxdg_output_v1 *, std::int32_t width, std::int32_t height) { + void monitor_t::xdg_size(zxdg_output_v1 *, const std::int32_t width, const std::int32_t height) { BOOST_LOG(info) << "Logical size: "sv << width << 'x' << height; } void monitor_t::wl_mode( - wl_output *wl_output, + const wl_output *wl_output, std::uint32_t flags, - std::int32_t width, - std::int32_t height, + const std::int32_t width, + const std::int32_t height, std::int32_t refresh ) { viewport.width = width; @@ -161,7 +161,7 @@ namespace wl { } void monitor_t::listen(zxdg_output_manager_v1 *output_manager) { - auto xdg_output = zxdg_output_manager_v1_get_xdg_output(output_manager, output); + const auto xdg_output = zxdg_output_manager_v1_get_xdg_output(output_manager, output); zxdg_output_v1_add_listener(xdg_output, &xdg_listener, this); wl_output_add_listener(output, &wl_listener, this); } @@ -183,9 +183,9 @@ namespace wl { void interface_t::add_interface( wl_registry *registry, - std::uint32_t id, + const std::uint32_t id, const char *interface, - std::uint32_t version + const std::uint32_t version ) { BOOST_LOG(debug) << "Available interface: "sv << interface << '(' << id << ") version "sv << version; @@ -214,7 +214,7 @@ namespace wl { } } - void interface_t::del_interface(wl_registry *registry, uint32_t id) { + void interface_t::del_interface(const wl_registry *registry, const uint32_t id) { BOOST_LOG(info) << "Delete: "sv << id; } @@ -291,7 +291,7 @@ namespace wl { zwlr_screencopy_manager_v1 *screencopy_manager, zwp_linux_dmabuf_v1 *dmabuf_interface, wl_output *output, - bool blend_cursor + const bool blend_cursor ) { this->dmabuf_interface = dmabuf_interface; // Reset state @@ -299,7 +299,7 @@ namespace wl { dmabuf_info.supported = false; // Create new frame - auto frame = zwlr_screencopy_manager_v1_capture_output( + const auto frame = zwlr_screencopy_manager_v1_capture_output( screencopy_manager, blend_cursor ? 1 : 0, output @@ -331,10 +331,10 @@ namespace wl { // Buffer format callback void dmabuf_t::buffer( zwlr_screencopy_frame_v1 *frame, - uint32_t format, - uint32_t width, - uint32_t height, - uint32_t stride + const uint32_t format, + const uint32_t width, + const uint32_t height, + const uint32_t stride ) { shm_info.supported = true; shm_info.format = format; @@ -348,9 +348,9 @@ namespace wl { // DMA-BUF format callback void dmabuf_t::linux_dmabuf( zwlr_screencopy_frame_v1 *frame, - std::uint32_t format, - std::uint32_t width, - std::uint32_t height + const std::uint32_t format, + const std::uint32_t width, + const std::uint32_t height ) { dmabuf_info.supported = true; dmabuf_info.format = format; @@ -385,7 +385,7 @@ namespace wl { } // Get buffer info - int fd = gbm_bo_get_fd(current_bo); + const int fd = gbm_bo_get_fd(current_bo); if (fd < 0) { BOOST_LOG(error) << "Failed to get buffer FD"sv; gbm_bo_destroy(current_bo); @@ -395,18 +395,18 @@ namespace wl { return; } - uint32_t stride = gbm_bo_get_stride(current_bo); - uint64_t modifier = gbm_bo_get_modifier(current_bo); + const uint32_t stride = gbm_bo_get_stride(current_bo); + const uint64_t modifier = gbm_bo_get_modifier(current_bo); // Store in surface descriptor for later use - auto next_frame = get_next_frame(); + const auto next_frame = get_next_frame(); next_frame->sd.fds[0] = fd; next_frame->sd.pitches[0] = stride; next_frame->sd.offsets[0] = 0; next_frame->sd.modifier = modifier; // Create linux-dmabuf buffer - auto params = zwp_linux_dmabuf_v1_create_params(dmabuf_interface); + const auto params = zwp_linux_dmabuf_v1_create_params(dmabuf_interface); zwp_linux_buffer_params_v1_add(params, fd, 0, 0, stride, modifier >> 32, modifier & 0xffffffff); // Add listener for buffer creation @@ -418,7 +418,7 @@ namespace wl { // Buffer done callback - time to create buffer void dmabuf_t::buffer_done(zwlr_screencopy_frame_v1 *frame) { - auto next_frame = get_next_frame(); + const auto next_frame = get_next_frame(); // Prefer DMA-BUF if supported if (dmabuf_info.supported && dmabuf_interface) { @@ -447,8 +447,8 @@ namespace wl { struct zwp_linux_buffer_params_v1 *params, struct wl_buffer *buffer ) { - auto frame = static_cast(data); - auto self = static_cast(zwlr_screencopy_frame_v1_get_user_data(frame)); + const auto frame = static_cast(data); + const auto self = static_cast(zwlr_screencopy_frame_v1_get_user_data(frame)); // Store for cleanup self->current_wl_buffer = buffer; @@ -462,8 +462,8 @@ namespace wl { void *data, struct zwp_linux_buffer_params_v1 *params ) { - auto frame = static_cast(data); - auto self = static_cast(zwlr_screencopy_frame_v1_get_user_data(frame)); + const auto frame = static_cast(data); + const auto self = static_cast(zwlr_screencopy_frame_v1_get_user_data(frame)); BOOST_LOG(error) << "Failed to create buffer from params"sv; self->cleanup_gbm(); @@ -503,7 +503,7 @@ namespace wl { // Clean up resources cleanup_gbm(); - auto next_frame = get_next_frame(); + const auto next_frame = get_next_frame(); next_frame->destroy(); zwlr_screencopy_frame_v1_destroy(frame); @@ -550,7 +550,7 @@ namespace wl { return {}; } - for (auto &monitor : interface.monitors) { + for (const auto &monitor : interface.monitors) { monitor->listen(interface.output_manager); } diff --git a/src/platform/linux/wayland.h b/src/platform/linux/wayland.h index 08d5acbd5..a0740ee99 100644 --- a/src/platform/linux/wayland.h +++ b/src/platform/linux/wayland.h @@ -114,13 +114,13 @@ namespace wl { void xdg_done(zxdg_output_v1 *) {} - void wl_geometry(wl_output *wl_output, std::int32_t x, std::int32_t y, std::int32_t physical_width, std::int32_t physical_height, std::int32_t subpixel, const char *make, const char *model, std::int32_t transform) {} + void wl_geometry(const wl_output *wl_output, std::int32_t x, std::int32_t y, std::int32_t physical_width, std::int32_t physical_height, std::int32_t subpixel, const char *make, const char *model, std::int32_t transform) {} - void wl_mode(wl_output *wl_output, std::uint32_t flags, std::int32_t width, std::int32_t height, std::int32_t refresh); + void wl_mode(const ::wl_output *wl_output, std::uint32_t flags, std::int32_t width, std::int32_t height, std::int32_t refresh); - void wl_done(wl_output *wl_output) {} + void wl_done(const wl_output *wl_output) {} - void wl_scale(wl_output *wl_output, std::int32_t factor) {} + void wl_scale(const wl_output *wl_output, std::int32_t factor) {} wl_output *output; std::string name; @@ -164,7 +164,7 @@ namespace wl { private: void add_interface(wl_registry *registry, std::uint32_t id, const char *interface, std::uint32_t version); - void del_interface(wl_registry *registry, uint32_t id); + void del_interface(const wl_registry *registry, uint32_t id); std::bitset interface; wl_registry_listener listener; diff --git a/src/platform/macos/input.cpp b/src/platform/macos/input.cpp index 7e61ab4be..2b3e3d75e 100644 --- a/src/platform/macos/input.cpp +++ b/src/platform/macos/input.cpp @@ -294,11 +294,11 @@ const KeyCodeMap kKeyCodesMap[] = { CGEventPost(kCGHIDEventTap, event); } - void unicode(input_t &input, char *utf8, int size) { + void unicode(const input_t &input, const char *utf8, int size) { BOOST_LOG(info) << "unicode: Unicode input not yet implemented for MacOS."sv; } - int alloc_gamepad(input_t &input, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue) { + int alloc_gamepad(const input_t &input, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue) { BOOST_LOG(info) << "alloc_gamepad: Gamepad not yet implemented for MacOS."sv; return -1; } @@ -307,7 +307,7 @@ const KeyCodeMap kKeyCodesMap[] = { BOOST_LOG(info) << "free_gamepad: Gamepad not yet implemented for MacOS."sv; } - void gamepad_update(input_t &input, int nr, const gamepad_state_t &gamepad_state) { + void gamepad_update(const input_t &input, int nr, const gamepad_state_t &gamepad_state) { BOOST_LOG(info) << "gamepad: Gamepad not yet implemented for MacOS."sv; } @@ -460,7 +460,7 @@ const KeyCodeMap kKeyCodesMap[] = { CFRelease(upEvent); } - void hscroll(input_t &input, int high_res_distance) { + void hscroll(const input_t &input, int high_res_distance) { // Unimplemented } @@ -469,7 +469,7 @@ const KeyCodeMap kKeyCodesMap[] = { * @param input The global input context. * @return A unique pointer to a per-client input data context. */ - std::unique_ptr allocate_client_input_context(input_t &input) { + std::unique_ptr allocate_client_input_context(const input_t &input) { // Unused return nullptr; } @@ -480,7 +480,7 @@ const KeyCodeMap kKeyCodesMap[] = { * @param touch_port The current viewport for translating to screen coordinates. * @param touch The touch event. */ - void touch_update(client_input_t *input, const touch_port_t &touch_port, const touch_input_t &touch) { + void touch_update(const client_input_t *input, const touch_port_t &touch_port, const touch_input_t &touch) { // Unimplemented feature - platform_caps::pen_touch } @@ -499,7 +499,7 @@ const KeyCodeMap kKeyCodesMap[] = { * @param input The global input context. * @param touch The touch event. */ - void gamepad_touch(input_t &input, const gamepad_touch_t &touch) { + void gamepad_touch(const input_t &input, const gamepad_touch_t &touch) { // Unimplemented feature - platform_caps::controller_touch } @@ -508,7 +508,7 @@ const KeyCodeMap kKeyCodesMap[] = { * @param input The global input context. * @param motion The motion event. */ - void gamepad_motion(input_t &input, const gamepad_motion_t &motion) { + void gamepad_motion(const input_t &input, const gamepad_motion_t &motion) { // Unimplemented } @@ -517,7 +517,7 @@ const KeyCodeMap kKeyCodesMap[] = { * @param input The global input context. * @param battery The battery event. */ - void gamepad_battery(input_t &input, const gamepad_battery_t &battery) { + void gamepad_battery(const input_t &input, const gamepad_battery_t &battery) { // Unimplemented } @@ -577,7 +577,7 @@ const KeyCodeMap kKeyCodesMap[] = { delete input; } - std::vector &supported_gamepads(input_t *input) { + std::vector &supported_gamepads(const input_t *input) { static std::vector gamepads { supported_gamepad_t {"", false, "gamepads.macos_not_implemented"} }; diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 540dd74ff..d2e195ef8 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -170,7 +170,7 @@ namespace platf { return "00:00:00:00:00:00"s; } - bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { + bp::child run_command(bool elevated, bool interactive, const std::string &cmd, const boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { // clang-format off if (!group) { if (!file) { diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 02310ec33..e2047a46d 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -326,18 +326,14 @@ namespace platf { * @param largeMotor The large motor. * @param smallMotor The small motor. */ - void rumble(target_t::pointer target, std::uint8_t largeMotor, std::uint8_t smallMotor) { + void rumble(const _VIGEM_TARGET_T *target, const std::uint8_t largeMotor, const std::uint8_t smallMotor) { for (int x = 0; x < gamepads.size(); ++x) { - auto &gamepad = gamepads[x]; - - if (gamepad.gp.get() == target) { + if (auto &gamepad = gamepads[x]; gamepad.gp.get() == target) { // Convert from 8-bit to 16-bit values - uint16_t normalizedLargeMotor = largeMotor << 8; - uint16_t normalizedSmallMotor = smallMotor << 8; + const uint16_t normalizedLargeMotor = largeMotor << 8; // Don't resend duplicate rumble data - if (normalizedSmallMotor != gamepad.last_rumble.data.rumble.highfreq || - normalizedLargeMotor != gamepad.last_rumble.data.rumble.lowfreq) { + if (const uint16_t normalizedSmallMotor = smallMotor << 8; normalizedSmallMotor != gamepad.last_rumble.data.rumble.highfreq || normalizedLargeMotor != gamepad.last_rumble.data.rumble.lowfreq) { // We have to use the client-relative index when communicating back to the client gamepad_feedback_msg_t msg = gamepad_feedback_msg_t::make_rumble( gamepad.client_relative_index, @@ -359,11 +355,9 @@ namespace platf { * @param g The red channel. * @param b The red channel. */ - void set_rgb_led(target_t::pointer target, std::uint8_t r, std::uint8_t g, std::uint8_t b) { + void set_rgb_led(const _VIGEM_TARGET_T *target, const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { for (int x = 0; x < gamepads.size(); ++x) { - auto &gamepad = gamepads[x]; - - if (gamepad.gp.get() == target) { + if (auto &gamepad = gamepads[x]; gamepad.gp.get() == target) { // Don't resend duplicate RGB data if (r != gamepad.last_rgb_led.data.rgb_led.r || g != gamepad.last_rgb_led.data.rgb_led.g || @@ -385,8 +379,7 @@ namespace platf { if (client) { for (auto &gamepad : gamepads) { if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { - auto status = vigem_target_remove(client.get(), gamepad.gp.get()); - if (!VIGEM_SUCCESS(status)) { + if (auto status = vigem_target_remove(client.get(), gamepad.gp.get()); !VIGEM_SUCCESS(status)) { BOOST_LOG(warning) << "Couldn't detach gamepad from ViGEm ["sv << util::hex(status).to_string_view() << ']'; } } @@ -471,10 +464,9 @@ namespace platf { */ void send_input(INPUT &i) { retry: - auto send = SendInput(1, &i, sizeof(INPUT)); + const auto send = SendInput(1, &i, sizeof(INPUT)); if (send != 1) { - auto hDesk = syncThreadDesktop(); - if (_lastKnownInputDesktop != hDesk) { + if (const auto hDesk = syncThreadDesktop(); _lastKnownInputDesktop != hDesk) { _lastKnownInputDesktop = hDesk; goto retry; } @@ -491,11 +483,10 @@ namespace platf { * @param count The number of elements in `pointerInfo`. * @return true if input was successfully injected. */ - bool inject_synthetic_pointer_input(input_raw_t *input, HSYNTHETICPOINTERDEVICE device, const POINTER_TYPE_INFO *pointerInfo, UINT32 count) { + bool inject_synthetic_pointer_input(const input_raw_t *input, HSYNTHETICPOINTERDEVICE device, const POINTER_TYPE_INFO *pointerInfo, UINT32 count) { retry: if (!input->fnInjectSyntheticPointerInput(device, pointerInfo, count)) { - auto hDesk = syncThreadDesktop(); - if (_lastKnownInputDesktop != hDesk) { + if (const auto hDesk = syncThreadDesktop(); _lastKnownInputDesktop != hDesk) { _lastKnownInputDesktop = hDesk; goto retry; } @@ -504,7 +495,7 @@ namespace platf { return true; } - void abs_mouse(input_t &input, const touch_port_t &touch_port, float x, float y) { + void abs_mouse(input_t &input, const touch_port_t &touch_port, const float x, const float y) { INPUT i {}; i.type = INPUT_MOUSE; @@ -517,8 +508,8 @@ namespace platf { // MOUSEEVENTF_VIRTUALDESK maps to the entirety of the desktop rather than the primary desktop MOUSEEVENTF_VIRTUALDESK; - auto scaled_x = std::lround((x + touch_port.offset_x) * ((float) target_touch_port.width / (float) touch_port.width)); - auto scaled_y = std::lround((y + touch_port.offset_y) * ((float) target_touch_port.height / (float) touch_port.height)); + const auto scaled_x = std::lround((x + touch_port.offset_x) * ((float) target_touch_port.width / (float) touch_port.width)); + const auto scaled_y = std::lround((y + touch_port.offset_y) * ((float) target_touch_port.height / (float) touch_port.height)); mi.dx = scaled_x; mi.dy = scaled_y; @@ -526,7 +517,7 @@ namespace platf { send_input(i); } - void move_mouse(input_t &input, int deltaX, int deltaY) { + void move_mouse(input_t &input, const int deltaX, const int deltaY) { INPUT i {}; i.type = INPUT_MOUSE; @@ -553,7 +544,7 @@ namespace platf { }; } - void button_mouse(input_t &input, int button, bool release) { + void button_mouse(input_t &input, const int button, const bool release) { INPUT i {}; i.type = INPUT_MOUSE; @@ -576,7 +567,7 @@ namespace platf { send_input(i); } - void scroll(input_t &input, int distance) { + void scroll(input_t &input, const int distance) { INPUT i {}; i.type = INPUT_MOUSE; @@ -588,7 +579,7 @@ namespace platf { send_input(i); } - void hscroll(input_t &input, int distance) { + void hscroll(input_t &input, const int distance) { INPUT i {}; i.type = INPUT_MOUSE; @@ -600,7 +591,7 @@ namespace platf { send_input(i); } - void keyboard_update(input_t &input, uint16_t modcode, bool release, uint8_t flags) { + void keyboard_update(input_t &input, const uint16_t modcode, const bool release, const uint8_t flags) { INPUT i {}; i.type = INPUT_KEYBOARD; auto &ki = i.ki; @@ -620,7 +611,7 @@ namespace platf { if (ki.wScan) { ki.dwFlags = KEYEVENTF_SCANCODE; } else { - // If there is no scancode mapping or it's non-normalized, send it as a regular VK event. + // If there is no scancode mapping, or it's non-normalized, send it as a regular VK event. ki.wVk = modcode; } @@ -840,7 +831,7 @@ namespace platf { */ void repeat_touch(client_input_raw_t *raw) { if (!inject_synthetic_pointer_input(raw->global, raw->touch, raw->touchInfo, raw->activeTouchSlots)) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to refresh virtual touch input: "sv << err; } @@ -853,7 +844,7 @@ namespace platf { */ void repeat_pen(client_input_raw_t *raw) { if (!inject_synthetic_pointer_input(raw->global, raw->pen, &raw->penInfo, 1)) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to refresh virtual pen input: "sv << err; } @@ -917,7 +908,7 @@ namespace platf { BOOST_LOG(info) << "Creating virtual touch input device"sv; raw->touch = raw->global->fnCreateSyntheticPointerDevice(PT_TOUCH, ARRAYSIZE(raw->touchInfo), POINTER_FEEDBACK_DEFAULT); if (!raw->touch) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to create virtual touch device: "sv << err; return; } @@ -1006,7 +997,7 @@ namespace platf { } if (!inject_synthetic_pointer_input(raw->global, raw->touch, raw->touchInfo, raw->activeTouchSlots)) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to inject virtual touch input: "sv << err; return; } @@ -1043,7 +1034,7 @@ namespace platf { BOOST_LOG(info) << "Creating virtual pen input device"sv; raw->pen = raw->global->fnCreateSyntheticPointerDevice(PT_PEN, 1, POINTER_FEEDBACK_DEFAULT); if (!raw->pen) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to create virtual pen device: "sv << err; return; } @@ -1110,10 +1101,10 @@ namespace platf { // We require rotation and tilt to perform the conversion to X and Y tilt angles if (pen.tilt != LI_TILT_UNKNOWN && pen.rotation != LI_ROT_UNKNOWN) { - auto rotationRads = pen.rotation * (M_PI / 180.f); - auto tiltRads = pen.tilt * (M_PI / 180.f); - auto r = std::sin(tiltRads); - auto z = std::cos(tiltRads); + const auto rotationRads = pen.rotation * (M_PI / 180.f); + const auto tiltRads = pen.tilt * (M_PI / 180.f); + const auto r = std::sin(tiltRads); + const auto z = std::cos(tiltRads); // Convert polar coordinates into X and Y tilt angles penInfo.penMask |= PEN_MASK_TILT_X | PEN_MASK_TILT_Y; @@ -1125,7 +1116,7 @@ namespace platf { } if (!inject_synthetic_pointer_input(raw->global, raw->pen, &raw->penInfo, 1)) { - auto err = GetLastError(); + const auto err = GetLastError(); BOOST_LOG(warning) << "Failed to inject virtual pen input: "sv << err; return; } @@ -1143,7 +1134,7 @@ namespace platf { // We can do no worse than one UTF-16 character per byte of UTF-8 WCHAR wide[size]; - int chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, size, wide, size); + const int chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, size, wide, size); if (chars <= 0) { return; } @@ -1222,7 +1213,7 @@ namespace platf { } void free_gamepad(input_t &input, int nr) { - auto raw = (input_raw_t *) input.get(); + const auto raw = (input_raw_t *) input.get(); if (!raw->vigem) { return; @@ -1239,7 +1230,7 @@ namespace platf { static XUSB_BUTTON x360_buttons(const gamepad_state_t &gamepad_state) { int buttons {}; - auto flags = gamepad_state.buttonFlags; + const auto flags = gamepad_state.buttonFlags; if (flags & DPAD_UP) { buttons |= XUSB_GAMEPAD_DPAD_UP; } @@ -1307,8 +1298,7 @@ namespace platf { } static DS4_DPAD_DIRECTIONS ds4_dpad(const gamepad_state_t &gamepad_state) { - auto flags = gamepad_state.buttonFlags; - if (flags & DPAD_UP) { + if (const auto flags = gamepad_state.buttonFlags; flags & DPAD_UP) { if (flags & DPAD_RIGHT) { return DS4_BUTTON_DPAD_NORTHEAST; } else if (flags & DPAD_LEFT) { @@ -1347,7 +1337,7 @@ namespace platf { static DS4_BUTTONS ds4_buttons(const gamepad_state_t &gamepad_state) { int buttons {}; - auto flags = gamepad_state.buttonFlags; + const auto flags = gamepad_state.buttonFlags; if (flags & LEFT_STICK) { buttons |= DS4_BUTTON_THUMB_LEFT; } @@ -1409,12 +1399,12 @@ namespace platf { return (DS4_SPECIAL_BUTTONS) buttons; } - static std::uint8_t to_ds4_triggerX(std::int16_t v) { + static std::uint8_t to_ds4_triggerX(const std::int16_t v) { return (v + std::numeric_limits::max() / 2 + 1) / 257; } - static std::uint8_t to_ds4_triggerY(std::int16_t v) { - auto new_v = -((std::numeric_limits::max() / 2 + v - 1)) / 257; + static std::uint8_t to_ds4_triggerY(const std::int16_t v) { + const auto new_v = -((std::numeric_limits::max() / 2 + v - 1)) / 257; return new_v == 0 ? 0xFF : (std::uint8_t) new_v; } @@ -1456,15 +1446,14 @@ namespace platf { } if (gamepad.gp && vigem_target_is_attached(gamepad.gp.get())) { - auto now = std::chrono::steady_clock::now(); - auto delta_ns = std::chrono::duration_cast(now - gamepad.last_report_ts); + const auto now = std::chrono::steady_clock::now(); + const auto delta_ns = std::chrono::duration_cast(now - gamepad.last_report_ts); // Timestamp is reported in 5.333us units gamepad.report.ds4.Report.wTimestamp += (uint16_t) (delta_ns.count() / 5333); // 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)) { + if (const auto status = vigem_target_ds4_update_ex(vigem->client.get(), gamepad.gp.get(), gamepad.report.ds4); !VIGEM_SUCCESS(status)) { BOOST_LOG(warning) << "Couldn't send gamepad input to ViGEm ["sv << util::hex(status).to_string_view() << ']'; return; } @@ -1482,7 +1471,7 @@ namespace platf { * @param gamepad_state The gamepad button/axis state sent from the client. */ void gamepad_update(input_t &input, int nr, const gamepad_state_t &gamepad_state) { - auto vigem = ((input_raw_t *) input.get())->vigem; + const auto vigem = ((input_raw_t *) input.get())->vigem; // If there is no gamepad support if (!vigem) { @@ -1494,12 +1483,9 @@ namespace platf { return; } - VIGEM_ERROR status; - if (vigem_target_get_type(gamepad.gp.get()) == Xbox360Wired) { x360_update_state(gamepad, gamepad_state); - status = vigem_target_x360_update(vigem->client.get(), gamepad.gp.get(), gamepad.report.x360); - if (!VIGEM_SUCCESS(status)) { + if (const VIGEM_ERROR status = vigem_target_x360_update(vigem->client.get(), gamepad.gp.get(), gamepad.report.x360); !VIGEM_SUCCESS(status)) { BOOST_LOG(warning) << "Couldn't send gamepad input to ViGEm ["sv << util::hex(status).to_string_view() << ']'; } } else { @@ -1514,7 +1500,7 @@ namespace platf { * @param touch The touch event. */ void gamepad_touch(input_t &input, const gamepad_touch_t &touch) { - auto vigem = ((input_raw_t *) input.get())->vigem; + const auto vigem = ((input_raw_t *) input.get())->vigem; // If there is no gamepad support if (!vigem) { @@ -1566,7 +1552,7 @@ namespace platf { // All pointers are now available gamepad.available_pointers = 0x3; } else { - auto i = gamepad.pointer_id_map.find(touch.pointerId); + const 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; return; @@ -1594,9 +1580,9 @@ namespace platf { } // Touchpad is 1920x943 according to ViGEm - uint16_t x = touch.x * 1920; - uint16_t y = touch.y * 943; - uint8_t touchData[] = { + const uint16_t x = touch.x * 1920; + const uint16_t y = touch.y * 943; + const uint8_t touchData[] = { (uint8_t) (x & 0xFF), // Low 8 bits of X (uint8_t) ((x >> 8 & 0x0F) | (y & 0x0F) << 4), // High 4 bits of X and low 4 bits of Y (uint8_t) (y >> 4 & 0xFF) // High 8 bits of Y @@ -1620,7 +1606,7 @@ namespace platf { * @param motion The motion event. */ void gamepad_motion(input_t &input, const gamepad_motion_t &motion) { - auto vigem = ((input_raw_t *) input.get())->vigem; + const auto vigem = ((input_raw_t *) input.get())->vigem; // If there is no gamepad support if (!vigem) { @@ -1647,7 +1633,7 @@ namespace platf { * @param battery The battery event. */ void gamepad_battery(input_t &input, const gamepad_battery_t &battery) { - auto vigem = ((input_raw_t *) input.get())->vigem; + const auto vigem = ((input_raw_t *) input.get())->vigem; // If there is no gamepad support if (!vigem) { @@ -1715,7 +1701,7 @@ namespace platf { } void freeInput(void *p) { - auto input = (input_raw_t *) p; + const auto input = (input_raw_t *) p; delete input; } @@ -1731,9 +1717,9 @@ namespace platf { return gps; } - auto vigem = ((input_raw_t *) input)->vigem; - auto enabled = vigem != nullptr; - auto reason = enabled ? "" : "gamepads.vigem-not-available"; + const auto vigem = ((input_raw_t *) input)->vigem; + const auto enabled = vigem != nullptr; + const auto reason = enabled ? "" : "gamepads.vigem-not-available"; // ds4 == ps4 static std::vector gps { diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index a921c3cc1..c6b1a3a90 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -895,7 +895,7 @@ namespace platf { * @param group A pointer to a `bp::group` object to which the new process should belong (may be `nullptr`). * @return A `bp::child` object representing the new process, or an empty `bp::child` object if the launch fails. */ - bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { + bp::child run_command(bool elevated, bool interactive, const std::string &cmd, const boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) { std::wstring start_dir = from_utf8(working_dir.string()); HANDLE job = group ? group->native_handle() : nullptr; STARTUPINFOEXW startup_info = create_startup_info(file, job ? &job : nullptr, ec); @@ -1321,7 +1321,7 @@ namespace platf { return accounting_info.ActiveProcesses != 0; } - SOCKADDR_IN to_sockaddr(boost::asio::ip::address_v4 address, uint16_t port) { + SOCKADDR_IN to_sockaddr(const boost::asio::ip::address_v4 &address, uint16_t port) { SOCKADDR_IN saddr_v4 = {}; saddr_v4.sin_family = AF_INET; @@ -1333,7 +1333,7 @@ namespace platf { return saddr_v4; } - SOCKADDR_IN6 to_sockaddr(boost::asio::ip::address_v6 address, uint16_t port) { + SOCKADDR_IN6 to_sockaddr(const boost::asio::ip::address_v6 &address, uint16_t port) { SOCKADDR_IN6 saddr_v6 = {}; saddr_v6.sin6_family = AF_INET6; @@ -1451,7 +1451,7 @@ namespace platf { return WSASendMsg((SOCKET) send_info.native_socket, &msg, 0, &bytes_sent, nullptr, nullptr) != SOCKET_ERROR; } - bool send(send_info_t &send_info) { + bool send(const send_info_t &send_info) { WSAMSG msg; // Convert the target address into a SOCKADDR @@ -1556,7 +1556,7 @@ namespace platf { * @param data_type The type of traffic sent on this socket. * @param dscp_tagging Specifies whether to enable DSCP tagging on outgoing traffic. */ - std::unique_ptr enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging) { + std::unique_ptr enable_socket_qos(uintptr_t native_socket, const boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging) { SOCKADDR_IN saddr_v4; SOCKADDR_IN6 saddr_v6; PSOCKADDR dest_addr; diff --git a/src/process.cpp b/src/process.cpp index fb123470a..e29ab810d 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -95,7 +95,7 @@ namespace proc { } } - boost::filesystem::path find_working_directory(const std::string &cmd, boost::process::v1::environment &env) { + boost::filesystem::path find_working_directory(const std::string &cmd, const boost::process::v1::environment &env) { // Parse the raw command string into parts to get the actual command portion #ifdef _WIN32 auto parts = boost::program_options::split_winmain(cmd); diff --git a/src/rtsp.cpp b/src/rtsp.cpp index 25647e2e3..a55df0b98 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -130,7 +130,7 @@ namespace rtsp_stream { * @param ec The error code of the read operation. * @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) { + static void handle_read_encrypted_header(const std::shared_ptr &socket, const boost::system::error_code &ec, const std::size_t bytes) { BOOST_LOG(debug) << "handle_read_encrypted_header(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { @@ -149,7 +149,7 @@ namespace rtsp_stream { return; } - auto header = (encrypted_rtsp_header_t *) socket->begin; + const 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; @@ -179,7 +179,7 @@ namespace rtsp_stream { * @param ec The error code of the read operation. * @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) { + static void handle_read_encrypted_message(const std::shared_ptr &socket, const boost::system::error_code &ec, const std::size_t bytes) { BOOST_LOG(debug) << "handle_read_encrypted(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { @@ -191,8 +191,8 @@ namespace rtsp_stream { } }); - auto header = (encrypted_rtsp_header_t *) socket->begin; - auto payload_length = header->payload_length(); + const auto header = (encrypted_rtsp_header_t *) socket->begin; + const auto payload_length = header->payload_length(); auto seq = util::endian::big(header->sequenceNumber); if (ec || bytes < payload_length) { @@ -270,7 +270,7 @@ namespace rtsp_stream { * @param ec The error code of the read operation. * @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) { + static void handle_plaintext_payload(const std::shared_ptr &socket, const boost::system::error_code &ec, const std::size_t bytes) { BOOST_LOG(debug) << "handle_plaintext_payload(): Handle read of size: "sv << bytes << " bytes"sv; auto sock_close = util::fail_guard([&socket]() { @@ -288,9 +288,9 @@ namespace rtsp_stream { return; } - auto end = socket->begin + bytes; + const auto end = socket->begin + bytes; msg_t req {new msg_t::element_type {}}; - if (auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (std::size_t) (end - socket->msg_buf.data()))) { + if (const auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (std::size_t) (end - socket->msg_buf.data()))) { BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']'; respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {}); @@ -310,8 +310,8 @@ namespace rtsp_stream { // If content_length > bytes read, then we need to store current data read, // to be appended by the next read. - std::string_view content {option->content}; - auto begin = std::find_if(std::begin(content), std::end(content), [](auto ch) { + const std::string_view content {option->content}; + const auto begin = std::find_if(std::begin(content), std::end(content), [](auto ch) { return (bool) std::isdigit(ch); }); @@ -360,13 +360,13 @@ namespace rtsp_stream { socket->read(); }); - auto begin = std::max(socket->begin - 4, socket->begin); + const auto begin = std::max(socket->begin - 4, socket->begin); auto buf_size = bytes + (begin - socket->begin); - auto end = begin + buf_size; + const auto end = begin + buf_size; constexpr auto needle = "\r\n\r\n"sv; - auto it = std::search(begin, begin + buf_size, std::begin(needle), std::end(needle)); + const auto it = std::search(begin, begin + buf_size, std::begin(needle), std::end(needle)); if (it == end) { socket->begin = end; @@ -404,7 +404,7 @@ namespace rtsp_stream { clear(); } - int bind(net::af_e af, std::uint16_t port, boost::system::error_code &ec) { + int bind(const net::af_e af, const std::uint16_t port, boost::system::error_code &ec) { acceptor.open(af == net::IPV4 ? tcp::v4() : tcp::v6(), ec); if (ec) { return -1; @@ -454,10 +454,9 @@ namespace rtsp_stream { return; } - auto socket = std::move(next_socket); + const auto socket = std::move(next_socket); - auto launch_session {launch_event.view(0s)}; - if (launch_session) { + if (const auto launch_session {launch_event.view(0s)}) { // Associate the current RTSP session with this socket and start reading socket->session = launch_session; socket->read(); @@ -502,8 +501,7 @@ namespace rtsp_stream { raised_timer.expires_after(config::stream.ping_timeout); raised_timer.async_wait([this](const boost::system::error_code &ec) { if (!ec) { - auto discarded = launch_event.pop(0s); - if (discarded) { + if (const auto discarded = launch_event.pop(0s)) { BOOST_LOG(debug) << "Event timeout: "sv << discarded->unique_id; } } @@ -514,11 +512,10 @@ namespace rtsp_stream { * @brief Clear state for the oldest launch session. * @param launch_session_id The ID of the session to clear. */ - void session_clear(uint32_t launch_session_id) { + void session_clear(const uint32_t launch_session_id) { // We currently only support a single pending RTSP session, // so the ID should always match the one for that session. - auto launch_session = launch_event.view(0s); - if (launch_session) { + if (const auto launch_session = launch_event.view(0s)) { if (launch_session->id != launch_session_id) { BOOST_LOG(error) << "Attempted to clear unexpected session: "sv << launch_session_id << " vs "sv << launch_session->id; } else { @@ -546,12 +543,11 @@ namespace rtsp_stream { * clear(false); * @examples_end */ - void clear(bool all = true) { + void clear(const bool all = true) { auto lg = _session_slots.lock(); for (auto i = _session_slots->begin(); i != _session_slots->end();) { - auto &slot = *(*i); - if (all || stream::session::state(slot) == stream::session::state_e::STOPPING) { + if (auto &slot = *(*i); all || stream::session::state(slot) == stream::session::state_e::STOPPING) { stream::session::stop(slot); stream::session::join(slot); @@ -626,7 +622,7 @@ namespace rtsp_stream { } int session_count() { - // Ensure session_count is up-to-date + // Ensure session_count is up to date server.clear(false); return server.session_count(); @@ -653,7 +649,7 @@ namespace rtsp_stream { } void respond(tcp::socket &sock, launch_session_t &session, msg_t &resp) { - auto payload = std::make_pair(resp->payload, resp->payloadLength); + const auto payload = std::make_pair(resp->payload, resp->payloadLength); // Restore response message for proper destruction auto lg = util::fail_guard([&]() { @@ -689,7 +685,7 @@ namespace rtsp_stream { iv[11] = 'R'; // RTSP // Allocate the message with an empty header and reserved space for the payload - auto payload_length = serialized_len + payload.second; + const auto payload_length = serialized_len + payload.second; std::vector message(sizeof(encrypted_rtsp_header_t)); message.reserve(message.size() + payload_length); @@ -698,7 +694,7 @@ namespace rtsp_stream { std::copy_n(payload.first, payload.second, std::back_inserter(message)); // Initialize the message header - auto header = (encrypted_rtsp_header_t *) message.data(); + const auto header = (encrypted_rtsp_header_t *) message.data(); header->typeAndLength = util::endian::big(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + payload_length); header->sequenceNumber = util::endian::big(session.rtsp_iv_counter); @@ -708,10 +704,8 @@ namespace rtsp_stream { // Send the full encrypted message send(sock, std::string_view {(char *) message.data(), message.size()}); } else { - std::string_view tmp_resp {raw_resp.get(), (size_t) serialized_len}; - // Send the plaintext RTSP message header - if (send(sock, tmp_resp)) { + if (const std::string_view tmp_resp {raw_resp.get(), (size_t) serialized_len}; send(sock, tmp_resp)) { return; } @@ -731,25 +725,25 @@ namespace rtsp_stream { respond(sock, session, nullptr, 404, "NOT FOUND", req->sequenceNumber, {}); } - void cmd_option(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { + void cmd_option([[maybe_unused]] const rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast("CSeq"); - auto seqn_str = std::to_string(req->sequenceNumber); + const auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast(seqn_str.c_str()); respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); } - void cmd_describe(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { + void cmd_describe([[maybe_unused]] const rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast("CSeq"); - auto seqn_str = std::to_string(req->sequenceNumber); + const auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast(seqn_str.c_str()); std::stringstream ss; @@ -762,8 +756,7 @@ namespace rtsp_stream { uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2; // Determine the encryption desired for this remote endpoint - auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); - if (encryption_mode != config::ENCRYPTION_MODE_NEVER) { + if (const auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); encryption_mode != config::ENCRYPTION_MODE_NEVER) { // Advertise support for video encryption if it's not disabled encryption_flags_supported |= SS_ENC_VIDEO; @@ -797,7 +790,7 @@ namespace rtsp_stream { } for (int x = 0; x < audio::MAX_STREAM_CONFIG; ++x) { - auto &stream_config = audio::stream_configs[x]; + const auto &stream_config = audio::stream_configs[x]; std::uint8_t mapping[platf::speaker::MAX_SPEAKERS]; auto mapping_p = stream_config.mapping; @@ -826,7 +819,7 @@ namespace rtsp_stream { respond(sock, session, &option, 200, "OK", req->sequenceNumber, ss.str()); } - void cmd_setup(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { + void cmd_setup([[maybe_unused]] const rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM options[4] {}; auto &seqn = options[0]; @@ -836,12 +829,12 @@ namespace rtsp_stream { seqn.option = const_cast("CSeq"); - auto seqn_str = std::to_string(req->sequenceNumber); + const auto seqn_str = std::to_string(req->sequenceNumber); seqn.content = const_cast(seqn_str.c_str()); std::string_view target {req->message.request.target}; - auto begin = std::find(std::begin(target), std::end(target), '=') + 1; - auto end = std::find(begin, std::end(target), '/'); + const auto begin = std::find(std::begin(target), std::end(target), '=') + 1; + const auto end = std::find(begin, std::end(target), '/'); std::string_view type {begin, (size_t) std::distance(begin, end)}; std::uint16_t port; @@ -898,7 +891,7 @@ namespace rtsp_stream { std::vector lines; - auto whitespace = [](char ch) { + auto whitespace = [](const char ch) { return ch == '\n' || ch == '\r'; }; @@ -917,14 +910,10 @@ namespace rtsp_stream { } } - std::string_view client; std::unordered_map args; for (auto line : lines) { - auto type = line.substr(0, 2); - if (type == "s="sv) { - client = line.substr(2); - } else if (type == "a=") { + if (auto type = line.substr(0, 2); type == "a=") { auto pos = line.find(':'); auto name = line.substr(2, pos - 2); @@ -1072,9 +1061,7 @@ namespace rtsp_stream { } // Check that any required encryption is enabled - auto encryption_mode = net::encryption_mode_for_address(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)) { + if (auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); 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; respond(sock, session, &option, 403, "Forbidden", req->sequenceNumber, {}); @@ -1095,13 +1082,13 @@ namespace rtsp_stream { respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); } - void cmd_play(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { + void cmd_play([[maybe_unused]] const rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) { OPTION_ITEM option {}; // I know these string literals will not be modified option.option = const_cast("CSeq"); - auto seqn_str = std::to_string(req->sequenceNumber); + const auto seqn_str = std::to_string(req->sequenceNumber); option.content = const_cast(seqn_str.c_str()); respond(sock, session, &option, 200, "OK", req->sequenceNumber, {}); @@ -1125,7 +1112,7 @@ namespace rtsp_stream { } std::thread rtsp_thread {[&shutdown_event] { - auto broadcast_shutdown_event = mail::man->event(mail::broadcast_shutdown); + const auto broadcast_shutdown_event = mail::man->event(mail::broadcast_shutdown); while (!shutdown_event->peek()) { server.iterate(); @@ -1133,7 +1120,7 @@ namespace rtsp_stream { if (broadcast_shutdown_event->peek()) { server.clear(); } else { - // cleanup all stopped sessions + // clean up all stopped sessions server.clear(false); } } @@ -1154,7 +1141,7 @@ namespace rtsp_stream { std::string_view payload {msg->payload, (size_t) msg->payloadLength}; std::string_view protocol {msg->protocol}; - auto seqnm = msg->sequenceNumber; + const auto seqnm = msg->sequenceNumber; std::string_view messageBuffer {msg->messageBuffer}; BOOST_LOG(debug) << "type ["sv << type << ']'; @@ -1163,15 +1150,15 @@ namespace rtsp_stream { BOOST_LOG(debug) << "payload :: "sv << payload; if (msg->type == TYPE_RESPONSE) { - auto &resp = msg->message.response; + const auto &resp = msg->message.response; - auto statuscode = resp.statusCode; + const auto statuscode = resp.statusCode; std::string_view status {resp.statusString}; BOOST_LOG(debug) << "statuscode :: "sv << statuscode; BOOST_LOG(debug) << "status :: "sv << status; } else { - auto &req = msg->message.request; + const auto &req = msg->message.request; std::string_view command {req.command}; std::string_view target {req.target}; diff --git a/src/stream.cpp b/src/stream.cpp index e6bb5ebfd..9b0fc76ee 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -257,7 +257,7 @@ namespace stream { return cbc.encrypt(std::string_view {(char *) std::begin(plaintext), plaintext.size()}, destination, &iv); } - static inline void while_starting_do_nothing(std::atomic &state) { + static inline void while_starting_do_nothing(const std::atomic &state) { while (state.load(std::memory_order_acquire) == session::state_e::STARTING) { std::this_thread::sleep_for(1ms); } @@ -915,24 +915,24 @@ namespace stream { } void controlBroadcastThread(control_server_t *server) { - server->map(packetTypes[IDX_PERIODIC_PING], [](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_PERIODIC_PING], [](const session_t *session, const std::string_view &payload) { BOOST_LOG(verbose) << "type [IDX_PERIODIC_PING]"sv; }); - server->map(packetTypes[IDX_START_A], [&](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_START_A], [&](const session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_START_A]"sv; }); - server->map(packetTypes[IDX_START_B], [&](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_START_B], [&](const session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_START_B]"sv; }); - server->map(packetTypes[IDX_LOSS_STATS], [&](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_LOSS_STATS], [&](const session_t *session, const std::string_view &payload) { int32_t *stats = (int32_t *) payload.data(); - auto count = stats[0]; + const auto count = stats[0]; std::chrono::milliseconds t {stats[1]}; - auto lastGoodFrame = stats[3]; + const auto lastGoodFrame = stats[3]; BOOST_LOG(verbose) << "type [IDX_LOSS_STATS]"sv << std::endl @@ -943,14 +943,14 @@ namespace stream { << "---end stats---"; }); - server->map(packetTypes[IDX_REQUEST_IDR_FRAME], [&](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_REQUEST_IDR_FRAME], [&](const session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_REQUEST_IDR_FRAME]"sv; session->video.idr_events->raise(true); }); - server->map(packetTypes[IDX_INVALIDATE_REF_FRAMES], [&](session_t *session, const std::string_view &payload) { - auto frames = (std::int64_t *) payload.data(); + server->map(packetTypes[IDX_INVALIDATE_REF_FRAMES], [&](const session_t *session, const std::string_view &payload) { + const auto frames = (std::int64_t *) payload.data(); auto firstFrame = frames[0]; auto lastFrame = frames[1]; @@ -965,8 +965,8 @@ namespace stream { server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(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}; + const auto tagged_cipher_length = util::endian::big(*(int32_t *) payload.data()); + const std::string_view tagged_cipher {payload.data() + sizeof(tagged_cipher_length), (size_t) tagged_cipher_length}; std::vector plaintext; @@ -993,7 +993,7 @@ namespace stream { auto header = (control_encrypted_p) (payload.data() - 2); - auto length = util::endian::little(header->length); + const auto length = util::endian::little(header->length); auto seq = util::endian::little(header->seq); if (length < (16 + 4 + 4)) { @@ -1001,7 +1001,7 @@ namespace stream { return; } - auto tagged_cipher_length = length - 4; + const auto tagged_cipher_length = length - 4; std::string_view tagged_cipher {(char *) header->payload(), (size_t) tagged_cipher_length}; auto &cipher = session->control.cipher; @@ -1036,8 +1036,8 @@ namespace stream { return; } - auto type = *(std::uint16_t *) plaintext.data(); - std::string_view next_payload {(char *) plaintext.data() + 4, plaintext.size() - 4}; + const auto type = *(std::uint16_t *) plaintext.data(); + const 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; @@ -1174,8 +1174,8 @@ namespace stream { auto &video_sock = ctx.video_sock; auto &audio_sock = ctx.audio_sock; - auto &message_queue_queue = ctx.message_queue_queue; - auto broadcast_shutdown_event = mail::man->event(mail::broadcast_shutdown); + const auto &message_queue_queue = ctx.message_queue_queue; + const auto broadcast_shutdown_event = mail::man->event(mail::broadcast_shutdown); auto &io = ctx.io_context; @@ -1237,11 +1237,10 @@ namespace stream { it->second->raise(peer, std::string {buf[buf_elem].data(), bytes}); } } else if (bytes >= sizeof(SS_PING)) { - auto ping = (PSS_PING) buf[buf_elem].data(); + const auto ping = (PSS_PING) buf[buf_elem].data(); // 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)) { + if (const auto it = peer_to_session.find(std::string {ping->payload, sizeof(ping->payload)}); it != std::end(peer_to_session)) { BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str; it->second->raise(peer, std::string {buf[buf_elem].data(), bytes}); } @@ -1402,10 +1401,10 @@ namespace stream { // Send less than 64K in a single batch. // On Windows, batches above 64K seem to bypass SO_SNDBUF regardless of its size, // appear in "Other I/O" and begin waiting for interrupts. - // This gives inconsistent performance so we'd rather avoid it. + // This gives inconsistent performance, so we'd rather avoid it. size_t send_batch_size = 64 * 1024 / blocksize; // Also don't exceed 64 packets, which can happen when Moonlight requests - // unusually small packet size. + // an unusually small packet size. // Generic Segmentation Offload on Linux can't do more than 64. send_batch_size = std::min(64, send_batch_size); @@ -1416,7 +1415,7 @@ namespace stream { size_t ratecontrol_group_packets_sent = 0; auto blockIndex = 0; - std::for_each(fec_blocks_begin, fec_blocks_end, [&](std::string_view ¤t_payload) { + std::for_each(fec_blocks_begin, fec_blocks_end, [&](const std::string_view ¤t_payload) { auto packets = (current_payload.size() + (blocksize - 1)) / blocksize; for (int x = 0; x < packets; ++x) { @@ -1509,7 +1508,7 @@ namespace stream { if (x - next_shard_to_send + 1 >= send_batch_size || x + 1 == shards.size()) { // Do pacing within the frame. - // Also trigger pacing before the first send_batch() of the frame + // Also, trigger pacing before the first send_batch() of the frame // to account for the last send_batch() of the previous frame. if (ratecontrol_group_packets_sent >= ratecontrol_packets_in_1ms || ratecontrol_frame_packets_sent == 0) { @@ -1525,7 +1524,7 @@ namespace stream { ratecontrol_group_packets_sent = 0; } - size_t current_batch_size = x - next_shard_to_send + 1; + const size_t current_batch_size = x - next_shard_to_send + 1; batch_info.block_offset = next_shard_to_send; batch_info.block_count = current_batch_size; @@ -1585,8 +1584,8 @@ namespace stream { } void audioBroadcastThread(udp::socket &sock) { - auto shutdown_event = mail::man->event(mail::broadcast_shutdown); - auto packets = mail::man->queue(mail::audio_packets); + const auto shutdown_event = mail::man->event(mail::broadcast_shutdown); + const auto packets = mail::man->queue(mail::audio_packets); audio_packet_t audio_packet; fec::rs_t rs {reed_solomon_new(RTPA_DATA_SHARDS, RTPA_FEC_SHARDS)}; @@ -1613,16 +1612,16 @@ namespace stream { } TUPLE_2D_REF(channel_data, packet_data, *packet); - auto session = (session_t *) channel_data; + const auto session = (session_t *) channel_data; - auto sequenceNumber = session->audio.sequenceNumber; - auto timestamp = session->audio.timestamp; + const auto sequenceNumber = session->audio.sequenceNumber; + const auto timestamp = session->audio.timestamp; *(std::uint32_t *) iv.data() = util::endian::big(session->audio.avRiKeyId + sequenceNumber); auto &shards_p = session->audio.shards_p; - auto bytes = encode_audio(session->config.encryptionFlagsEnabled & SS_ENC_AUDIO, packet_data, shards_p[sequenceNumber % RTPA_DATA_SHARDS], iv, session->audio.cipher); + const 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; break; @@ -1689,11 +1688,11 @@ namespace stream { } int start_broadcast(broadcast_ctx_t &ctx) { - auto address_family = net::af_from_enum_string(config::sunshine.address_family); - auto protocol = address_family == net::IPV4 ? udp::v4() : udp::v6(); - auto control_port = net::map_port(CONTROL_PORT); - auto video_port = net::map_port(VIDEO_STREAM_PORT); - auto audio_port = net::map_port(AUDIO_STREAM_PORT); + const auto address_family = net::af_from_enum_string(config::sunshine.address_family); + const auto protocol = address_family == net::IPV4 ? udp::v4() : udp::v6(); + const auto control_port = net::map_port(CONTROL_PORT); + const auto video_port = net::map_port(VIDEO_STREAM_PORT); + const auto audio_port = net::map_port(AUDIO_STREAM_PORT); if (ctx.control_server.bind(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; @@ -1782,7 +1781,7 @@ namespace stream { broadcast_shutdown_event->reset(); } - int recv_ping(session_t *session, decltype(broadcast)::ptr_t ref, socket_e type, std::string_view expected_payload, udp::endpoint &peer, std::chrono::milliseconds timeout) { + int recv_ping(const session_t *session, decltype(broadcast)::ptr_t ref, socket_e type, std::string_view expected_payload, udp::endpoint &peer, std::chrono::milliseconds timeout) { auto messages = std::make_shared(30); av_session_id_t session_id = std::string {expected_payload}; @@ -1864,8 +1863,7 @@ namespace stream { while_starting_do_nothing(session->state); auto ref = broadcast.ref(); - auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, config::stream.ping_timeout); - if (error < 0) { + if (const auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, config::stream.ping_timeout); error < 0) { return; } @@ -1880,15 +1878,13 @@ namespace stream { namespace session { std::atomic_uint running_sessions; - state_e state(session_t &session) { + state_e state(const session_t &session) { return session.state.load(std::memory_order_relaxed); } void stop(session_t &session) { while_starting_do_nothing(session.state); - auto expected = state_e::RUNNING; - auto already_stopping = !session.state.compare_exchange_strong(expected, state_e::STOPPING); - if (already_stopping) { + if (auto expected = state_e::RUNNING; !session.state.compare_exchange_strong(expected, state_e::STOPPING)) { return; } @@ -1959,7 +1955,7 @@ namespace stream { session.broadcast_ref->control_server._sessions->push_back(&session); } - auto addr = boost::asio::ip::make_address(addr_string); + const auto addr = boost::asio::ip::make_address(addr_string); session.video.peer.address(addr); session.video.peer.port(0); @@ -1984,7 +1980,7 @@ namespace stream { return 0; } - std::shared_ptr alloc(config_t &config, rtsp_stream::launch_session_t &launch_session) { + std::shared_ptr alloc(const config_t &config, rtsp_stream::launch_session_t &launch_session) { auto session = std::make_shared(); auto mail = std::make_shared(); @@ -2026,7 +2022,7 @@ namespace stream { } // Audio FEC spans multiple audio packets, - // therefore its session specific + // therefore it's session specific session->audio.shards = std::move(shards); session->audio.shards_p = std::move(shards_p); diff --git a/src/stream.h b/src/stream.h index 53afff4fa..7cb2a58c5 100644 --- a/src/stream.h +++ b/src/stream.h @@ -46,10 +46,10 @@ namespace stream { RUNNING, ///< The session is running }; - std::shared_ptr alloc(config_t &config, rtsp_stream::launch_session_t &launch_session); + std::shared_ptr alloc(const config_t &config, rtsp_stream::launch_session_t &launch_session); int start(session_t &session, const std::string &addr_string); void stop(session_t &session); void join(session_t &session); - state_e state(session_t &session); + state_e state(const session_t &session); } // namespace session } // namespace stream diff --git a/src/task_pool.h b/src/task_pool.h index 081be24d0..9022314d7 100644 --- a/src/task_pool.h +++ b/src/task_pool.h @@ -155,14 +155,12 @@ namespace task_pool_util { * @param duration The delay before executing the task. */ template - void delay(task_id_t task_id, std::chrono::duration duration) { + void delay(const _ImplBase *task_id, std::chrono::duration duration) { std::lock_guard lg(_task_mutex); auto it = _timer_tasks.begin(); for (; it < _timer_tasks.cend(); ++it) { - const __task &task = std::get<1>(*it); - - if (&*task == task_id) { + if (const __task &task = std::get<1>(*it); &*task == task_id) { std::get<0>(*it) = std::chrono::steady_clock::now() + duration; break; @@ -185,14 +183,11 @@ namespace task_pool_util { } } - bool cancel(task_id_t task_id) { + bool cancel(const _ImplBase *task_id) { std::lock_guard lg(_task_mutex); - auto it = _timer_tasks.begin(); - for (; it < _timer_tasks.cend(); ++it) { - const __task &task = std::get<1>(*it); - - if (&*task == task_id) { + for (auto it = _timer_tasks.begin(); it < _timer_tasks.cend(); ++it) { + if (const __task &task = std::get<1>(*it); &*task == task_id) { _timer_tasks.erase(it); return true; @@ -202,10 +197,10 @@ namespace task_pool_util { return false; } - std::optional> pop(task_id_t task_id) { + std::optional> pop(const _ImplBase *task_id) { std::lock_guard lg(_task_mutex); - auto pos = std::find_if(std::begin(_timer_tasks), std::end(_timer_tasks), [&task_id](const auto &t) { + const auto pos = std::find_if(std::begin(_timer_tasks), std::end(_timer_tasks), [&task_id](const auto &t) { return t.second.get() == task_id; }); diff --git a/src/video.cpp b/src/video.cpp index 8f6b69c44..bb9424a28 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -120,22 +120,21 @@ namespace video { util::Either dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); util::Either vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); - util::Either cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); - util::Either vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *); + util::Either cuda_init_avcodec_hardware_input_buffer(const platf::avcodec_encode_device_t *); + util::Either vt_init_avcodec_hardware_input_buffer(const platf::avcodec_encode_device_t *); class avcodec_software_encode_device_t: public platf::avcodec_encode_device_t { public: int convert(platf::img_t &img) override { // If we need to add aspect ratio padding, we need to scale into an intermediate output buffer - bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height); + const bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height); // Setup the input frame using the caller's img_t sws_input_frame->data[0] = img.data; sws_input_frame->linesize[0] = img.row_pitch; // Perform color conversion and scaling to the final size - auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get()); - if (status < 0) { + if (const auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get()); status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; @@ -464,8 +463,8 @@ namespace video { encode_session_ctx_queue_t encode_session_ctx_queue {30}; }; - int start_capture_sync(capture_thread_sync_ctx_t &ctx); - void end_capture_sync(capture_thread_sync_ctx_t &ctx); + int start_capture_sync(const capture_thread_sync_ctx_t &ctx); + void end_capture_sync(const capture_thread_sync_ctx_t &ctx); int start_capture_async(capture_thread_async_ctx_t &ctx); void end_capture_async(capture_thread_async_ctx_t &ctx); @@ -1371,8 +1370,8 @@ namespace video { } } - int encode_avcodec(int64_t frame_nr, avcodec_encode_session_t &session, safe::mail_raw_t::queue_t &packets, void *channel_data, std::optional frame_timestamp) { - auto &frame = session.device->frame; + int encode_avcodec(const int64_t frame_nr, avcodec_encode_session_t &session, const safe::mail_raw_t::queue_t &packets, void *channel_data, const std::optional frame_timestamp) { + const auto &frame = session.device->frame; frame->pts = frame_nr; auto &ctx = session.avcodec_ctx; @@ -1391,7 +1390,7 @@ namespace video { while (ret >= 0) { auto packet = std::make_unique(); - auto av_packet = packet.get()->av_packet; + const auto av_packet = packet.get()->av_packet; ret = avcodec_receive_packet(ctx.get(), av_packet); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { @@ -1445,7 +1444,7 @@ namespace video { return 0; } - 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) { + int encode_nvenc(const int64_t frame_nr, nvenc_encode_session_t &session, const safe::mail_raw_t::queue_t &packets, void *channel_data, const std::optional frame_timestamp) { auto encoded_frame = session.encode_frame(frame_nr); if (encoded_frame.data.empty()) { BOOST_LOG(error) << "NvENC returned empty packet"; @@ -1668,7 +1667,7 @@ namespace video { [&](int v) { av_dict_set_int(&options, option.name.c_str(), v, 0); }, - [&](int *v) { + [&](const int *v) { av_dict_set_int(&options, option.name.c_str(), *v, 0); }, [&](std::optional *v) { @@ -1682,7 +1681,7 @@ namespace video { [&](const std::string &v) { av_dict_set(&options, option.name.c_str(), v.c_str(), 0); }, - [&](std::string *v) { + [&](const std::string *v) { if (!v->empty()) { av_dict_set(&options, option.name.c_str(), v->c_str(), 0); } @@ -1975,20 +1974,20 @@ namespace video { } } - input::touch_port_t make_port(platf::display_t *display, const config_t &config) { - float wd = display->width; - float hd = display->height; + input::touch_port_t make_port(const platf::display_t *display, const config_t &config) { + const float wd = display->width; + const float hd = display->height; - float wt = config.width; - float ht = config.height; + const float wt = config.width; + const float ht = config.height; - auto scalar = std::fminf(wt / wd, ht / hd); + const auto scalar = std::fminf(wt / wd, ht / hd); - auto w2 = scalar * wd; - auto h2 = scalar * hd; + const auto w2 = scalar * wd; + const auto h2 = scalar * hd; - auto offsetX = (config.width - w2) * 0.5f; - auto offsetY = (config.height - h2) * 0.5f; + const auto offsetX = (config.width - w2) * 0.5f; + const auto offsetY = (config.height - h2) * 0.5f; return input::touch_port_t { { @@ -2008,7 +2007,7 @@ namespace video { std::unique_ptr make_encode_device(platf::display_t &disp, const encoder_t &encoder, const config_t &config) { std::unique_ptr result; - auto colorspace = colorspace_from_client_config(config, disp.is_hdr()); + const auto colorspace = colorspace_from_client_config(config, disp.is_hdr()); platf::pix_fmt_e pix_fmt; if (config.chromaSamplingType == 1) { @@ -2028,7 +2027,7 @@ namespace video { } { - auto encoder_name = encoder.codec_from_config(config).name; + const auto encoder_name = encoder.codec_from_config(config).name; BOOST_LOG(info) << "Creating encoder " << logging::bracket(encoder_name); @@ -2276,13 +2275,13 @@ namespace video { } void capture_async( - safe::mail_t mail, - config_t &config, + const safe::mail_t &mail, + const config_t &config, void *channel_data ) { - auto shutdown_event = mail->event(mail::shutdown); + const auto shutdown_event = mail->event(mail::shutdown); - auto images = std::make_shared(); + const auto images = std::make_shared(); auto lg = util::fail_guard([&]() { images->stop(); shutdown_event->raise(true); @@ -2301,8 +2300,8 @@ namespace video { int frame_nr = 1; - auto touch_port_event = mail->event(mail::touch_port); - auto hdr_event = mail->event(mail::hdr); + const auto touch_port_event = mail->event(mail::touch_port); + const auto hdr_event = mail->event(mail::hdr); // Encoding takes place on this thread platf::adjust_thread_priority(platf::thread_priority_e::high); @@ -2361,7 +2360,7 @@ namespace video { void capture( safe::mail_t mail, - config_t config, + const config_t &config, void *channel_data ) { auto idr_events = mail->event(mail::idr); @@ -2843,11 +2842,10 @@ namespace video { return hw_device_buf; } - util::Either cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { + util::Either cuda_init_avcodec_hardware_input_buffer(const platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; - auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */); - if (status < 0) { + if (const auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */); status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to create a CUDA device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; @@ -2856,11 +2854,10 @@ namespace video { return hw_device_buf; } - util::Either vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) { + util::Either vt_init_avcodec_hardware_input_buffer(const platf::avcodec_encode_device_t *encode_device) { avcodec_buffer_t hw_device_buf; - auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, nullptr, nullptr, 0); - if (status < 0) { + if (const auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, nullptr, nullptr, 0); status < 0) { char string[AV_ERROR_MAX_STRING_SIZE]; BOOST_LOG(error) << "Failed to create a VideoToolbox device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status); return -1; @@ -2926,12 +2923,12 @@ namespace video { capture_thread_ctx.capture_thread.join(); } - int start_capture_sync(capture_thread_sync_ctx_t &ctx) { + int start_capture_sync(const capture_thread_sync_ctx_t &ctx) { std::thread {&captureThreadSync}.detach(); return 0; } - void end_capture_sync(capture_thread_sync_ctx_t &ctx) { + void end_capture_sync(const capture_thread_sync_ctx_t &ctx) { } platf::mem_type_e map_base_dev_type(AVHWDeviceType type) { diff --git a/src/video.h b/src/video.h index a966c53e6..f1379ceab 100644 --- a/src/video.h +++ b/src/video.h @@ -337,7 +337,7 @@ namespace video { void capture( safe::mail_t mail, - config_t config, + const config_t &config, void *channel_data ); diff --git a/tools/sunshinesvc.cpp b/tools/sunshinesvc.cpp index 4f3b1a2f4..fb412fc95 100644 --- a/tools/sunshinesvc.cpp +++ b/tools/sunshinesvc.cpp @@ -20,7 +20,7 @@ HANDLE session_change_event; #define SERVICE_NAME "SunshineService" -DWORD WINAPI HandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) { +DWORD WINAPI HandlerEx(DWORD dwControl, DWORD dwEventType, const LPVOID lpEventData, const LPVOID lpContext) { switch (dwControl) { case SERVICE_CONTROL_INTERROGATE: return NO_ERROR;