From 404b8ab881c213b3fbc0cfac10b7dcceac1c6cca Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:27:35 -0400 Subject: [PATCH] refactor(capture): own input video and Linux runtime state --- src/input.cpp | 528 +++++++++++------- src/input.h | 126 +++-- src/platform/common.h | 111 +++- src/platform/linux/capture_geometry.h | 31 + src/platform/linux/kmsgrab.cpp | 103 ++-- src/platform/linux/misc.cpp | 281 ++++++---- src/platform/linux/misc.h | 14 +- src/platform/linux/portalgrab.cpp | 27 +- src/platform/linux/vaapi.cpp | 12 +- src/platform/linux/vaapi.h | 3 +- src/platform/linux/wlgrab.cpp | 29 +- src/platform/linux/x11grab.cpp | 27 +- src/platform/macos/display.mm | 8 +- src/platform/macos/misc.mm | 74 ++- src/platform/virtualhid_input.cpp | 3 +- src/platform/windows/input.cpp | 39 +- src/video.cpp | 434 ++++++++------ src/video.h | 123 ++-- tests/tests_common.h | 43 +- tests/unit/platform/test_virtualhid_input.cpp | 12 +- tests/unit/test_capture_geometry.cpp | 45 ++ tests/unit/test_input.cpp | 127 +++-- tests/unit/test_keyboard.cpp | 29 +- tests/unit/test_mouse.cpp | 6 +- tests/unit/test_video.cpp | 50 +- 25 files changed, 1498 insertions(+), 787 deletions(-) create mode 100644 src/platform/linux/capture_geometry.h create mode 100644 tests/unit/test_capture_geometry.cpp diff --git a/src/input.cpp b/src/input.cpp index 79b5e30a6..3a36678a3 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -162,8 +162,6 @@ namespace input { return std::clamp(from_netfloat(f), min, max); } - static task_pool_util::TaskPool::task_id_t key_press_repeat_id {}; - /** * @brief Press state retained so releases and repeats use the key's original identity. */ @@ -172,54 +170,128 @@ namespace input { bool extended = false; ///< Whether its press identified an extended key. }; - static std::unordered_map key_press {}; - static std::array mouse_press {}; + /** + * @brief Hash string-like session identifiers without allocating temporary strings. + */ + struct transparent_string_hash_t { + using is_transparent = void; ///< Enable heterogeneous unordered-map lookup. - static platf::input_t platf_input; + /** + * @brief Hash a string view. + * + * @param value Session identifier to hash. + * @return Hash value for the supplied identifier. + */ + std::size_t operator()(const std::string_view value) const noexcept { + return std::hash {}(value); + } + }; + + using retained_input_map_t = std::unordered_map< + std::string, + std::shared_ptr, + transparent_string_hash_t, + std::equal_to<>>; ///< Retained inputs keyed by paired-client identity. + + /** + * @brief Synchronized storage for retained input sessions. + */ + struct retained_input_state_t { + std::mutex mutex; ///< Synchronizes retained session access across transport threads. + retained_input_map_t inputs; ///< Paused input sessions keyed by paired-client identity. + }; + + /** + * @brief Host input resources and shared state owned by one input service. + */ + struct service_t::impl_t: std::enable_shared_from_this { + /** + * @brief Bind the host dependencies without opening platform devices. + * @param scheduler Scheduler serializing host input work. + * @param mail Host mailbox carrying display selection. + * @param cursor Host cursor visibility preference. + */ + impl_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): + scheduler {scheduler}, + mail {std::move(mail)}, + cursor {cursor} { + } + + thread_pool_util::ThreadPool &scheduler; ///< Host input task scheduler. + safe::mail_t mail; ///< Host communication mailbox. + bool &cursor; ///< Host cursor visibility preference. + std::atomic_bool stopping {false}; ///< Prevents new delayed work during service destruction. + task_pool_util::TaskPool::task_id_t key_press_repeat_id {}; ///< Scheduled keyboard repeat. + std::unordered_map key_press; ///< Host pressed-key state. + std::array mouse_press {}; ///< Host mouse-button state. + platf::input_t platf_input; ///< Platform input backend. + std::bitset gamepadMask {}; ///< Host gamepad allocation bitmap. + retained_input_state_t retained; ///< Sessions retained across paused transport connections. +#ifdef SUNSHINE_TESTS + std::function test_keyboard_sink; ///< Keyboard recorder. + std::function test_packet_hook; ///< Packet-dispatch recorder. + std::function)> test_task_sink; ///< Task scheduling recorder. +#endif + }; + +#ifdef SUNSHINE_TESTS + /** + * @brief Access service-owned dependencies from the test adapters. + */ + struct service_access_t { + /** + * @brief Obtain a test fixture's host input state. + * @param service Fixture-owned input service. + * @return Service implementation used by the adapters. + */ + static service_t::impl_t &state(service_t &service) { + return *service.impl_; + } + }; +#endif #ifdef SUNSHINE_TESTS /** * @brief Recorder that unit tests install in place of the platform keyboard. * * @return Mutable reference to the recorder, empty when no test installed one. + * @param host Host input or video service and its capture dependencies. */ - std::function &keyboard_sink() { - static std::function sink; - return sink; + std::function &keyboard_sink(service_t::impl_t &host) { + return host.test_keyboard_sink; } /** * @brief Return the optional callback for observing queued packet dispatch in tests. * * @return Mutable test callback. + * @param host Host input or video service and its capture dependencies. */ - std::function &input_packet_hook() { - static std::function hook; - return hook; + std::function &input_packet_hook(service_t::impl_t &host) { + return host.test_packet_hook; } /** * @brief Return the optional callback for observing input task scheduling in tests. * * @return Mutable test callback. + * @param host Host input or video service and its capture dependencies. */ - std::function)> &input_task_sink() { - static std::function)> sink; - return sink; + std::function)> &input_task_sink(service_t::impl_t &host) { + return host.test_task_sink; } #endif - static std::bitset gamepadMask {}; /** * @brief Release all platform resources associated with a virtual gamepad. * - * @param platf_input Platf input. + * @param host Host input owner. * @param id Identifier for the controller, session, display, or resource. */ - void free_gamepad(platf::input_t &platf_input, int id) { - platf::gamepad_update(platf_input, id, platf::gamepad_state_t {}); - platf::free_gamepad(platf_input, id); + void free_gamepad(service_t::impl_t &host, int id) { + platf::gamepad_update(host.platf_input, id, platf::gamepad_state_t {}); + platf::free_gamepad(host.platf_input, id); - free_id(gamepadMask, id); + free_id(host.gamepadMask, id); } /** @@ -234,17 +306,23 @@ namespace input { } ~gamepad_t() { + if (!owner) { + return; + } + auto &host = *owner; if (id >= 0) { - if (task_pool.running()) { - task_pool.push([id = this->id]() { - ::input::free_gamepad(platf_input, id); + if (host.scheduler.running()) { + host.scheduler.push([id = this->id, owner = owner]() { + ::input::free_gamepad(*owner, id); }); } else { - ::input::free_gamepad(platf_input, id); + ::input::free_gamepad(host, id); } } } + std::shared_ptr owner; ///< Host input service owning this controller slot. + platf::gamepad_state_t gamepad_state; ///< Gamepad state. thread_pool_util::ThreadPool::task_id_t back_timeout_id; ///< Back timeout ID. @@ -296,22 +374,32 @@ namespace input { * * @param touch_port_event Event carrying the active touch port. * @param feedback_queue Queue used for controller feedback. + * @param owner Host input or video service and its capture dependencies. */ input_t( + std::shared_ptr owner, safe::mail_raw_t::event_t touch_port_event, platf::feedback_queue_t feedback_queue ): + owner {std::move(owner)}, + host {*this->owner}, shortcutFlags {}, gamepads(MAX_GAMEPADS), - client_context {platf::allocate_client_input_context(platf_input)}, + client_context {platf::allocate_client_input_context(host.platf_input)}, touch_port_event {std::move(touch_port_event)}, feedback_queue {std::move(feedback_queue)}, mouse_left_button_timeout {}, touch_port {{0, 0, 0, 0, 0, 0}, 0, 0, 0.0f, 0.0f, 1.0f, 1.0f, 0, 0}, accumulated_vscroll_delta {}, accumulated_hscroll_delta {} { + for (auto &gamepad : gamepads) { + gamepad.owner = this->owner; + } } + std::shared_ptr owner; ///< Keeps host resources alive for the retained session. + service_t::impl_t &host; ///< Host service shared by retained client input sessions. + // Keep track of alt+ctrl+shift key combo int shortcutFlags; ///< Shortcut flags. @@ -337,57 +425,17 @@ namespace input { int32_t accumulated_hscroll_delta; ///< Accumulated hscroll delta. }; - /** - * @brief Hash string-like session identifiers without allocating temporary strings. - */ - struct transparent_string_hash_t { - using is_transparent = void; ///< Enable heterogeneous unordered-map lookup. - - /** - * @brief Hash a string view. - * - * @param value Session identifier to hash. - * @return Hash value for the supplied identifier. - */ - std::size_t operator()(const std::string_view value) const noexcept { - return std::hash {}(value); - } - }; - - using retained_input_map_t = std::unordered_map< - std::string, - std::shared_ptr, - transparent_string_hash_t, - std::equal_to<>>; ///< Retained inputs keyed by paired-client identity. - - /** - * @brief Synchronized storage for retained input sessions. - */ - struct retained_input_state_t { - std::mutex mutex; ///< Synchronizes retained session access across transport threads. - retained_input_map_t inputs; ///< Paused input sessions keyed by paired-client identity. - }; - - /** - * @brief Access process-wide retained input session storage. - * - * @return Mutable retained input session state. - */ - retained_input_state_t &retained_input_state() { - static retained_input_state_t state; - return state; - } - /** * @brief Execute lifecycle work on the input task thread when it is running. * * @tparam Function Callable type. * @param function Lifecycle operation to execute. + * @param host Host input or video service and its capture dependencies. */ template - void dispatch_input_task(Function &&function) { - if (task_pool.running()) { - task_pool.push(std::forward(function)); + void dispatch_input_task(service_t::impl_t &host, Function &&function) { + if (host.scheduler.running()) { + host.scheduler.push(std::forward(function)); } else { std::forward(function)(); } @@ -399,13 +447,14 @@ namespace input { * @param input Retained input session whose gamepads should be destroyed. */ void destroy_gamepads(const std::shared_ptr &input) { + auto &host = input->host; for (auto &gamepad : input->gamepads) { if (gamepad.back_timeout_id) { - task_pool.cancel(gamepad.back_timeout_id); + host.scheduler.cancel(gamepad.back_timeout_id); gamepad.back_timeout_id = nullptr; } if (gamepad.id >= 0) { - ::input::free_gamepad(platf_input, gamepad.id); + ::input::free_gamepad(host, gamepad.id); gamepad.id = -1; } gamepad.gamepad_state = {}; @@ -432,6 +481,7 @@ namespace input { * @param mail Mailbox for the resumed stream connection. */ void rebind_input(const std::shared_ptr &input, const safe::mail_t &mail) { + auto &host = input->host; input->touch_port_event = mail->event(mail::touch_port); input->feedback_queue = mail->queue(mail::gamepad_feedback); @@ -441,8 +491,8 @@ namespace input { continue; } - if (platf::rebind_gamepad(platf_input, {gamepad.id, static_cast(client_index)}, input->feedback_queue) != 0) { - free_id(gamepadMask, gamepad.id); + if (platf::rebind_gamepad(host.platf_input, {gamepad.id, static_cast(client_index)}, input->feedback_queue) != 0) { + free_id(host.gamepadMask, gamepad.id); gamepad.id = -1; } } @@ -452,21 +502,22 @@ namespace input { * @brief Apply shortcut based on VKEY * @param keyCode The VKEY code * @return 0 if no shortcut applied, > 0 if shortcut applied. + * @param host Host input or video service and its capture dependencies. */ - inline int apply_shortcut(short keyCode) { + inline int apply_shortcut(service_t::impl_t &host, short keyCode) { constexpr auto VK_F1 = 0x70; constexpr auto VK_F13 = 0x7C; BOOST_LOG(debug) << "Apply Shortcut: 0x"sv << util::hex((std::uint8_t) keyCode).to_string_view(); if (keyCode >= VK_F1 && keyCode <= VK_F13) { - mail::man->event(mail::switch_display)->raise(keyCode - VK_F1); + host.mail->event(mail::switch_display)->raise(keyCode - VK_F1); return 1; } switch (keyCode) { case 0x4E /* VKEY_N */: - display_cursor = !display_cursor; + host.cursor = !host.cursor; return 1; } @@ -776,6 +827,7 @@ namespace input { * @param packet Protocol packet being processed. */ void passthrough(std::shared_ptr &input, PNV_REL_MOUSE_MOVE_PACKET packet) { + auto &host = input->host; if (!config::input.mouse) { return; } @@ -784,13 +836,13 @@ namespace input { refresh_touch_port(input); if (input->touch_port) { platf::move_mouse( - platf_input, + host.platf_input, platform_touch_port(input->touch_port), util::endian::big(packet->deltaX), util::endian::big(packet->deltaY) ); } else { - platf::move_mouse(platf_input, util::endian::big(packet->deltaX), util::endian::big(packet->deltaY)); + platf::move_mouse(host.platf_input, util::endian::big(packet->deltaX), util::endian::big(packet->deltaY)); } } @@ -886,6 +938,7 @@ namespace input { * @param packet Protocol packet being processed. */ void passthrough(std::shared_ptr &input, PNV_ABS_MOUSE_MOVE_PACKET packet) { + auto &host = input->host; if (!config::input.mouse) { return; } @@ -915,7 +968,7 @@ namespace input { auto &touch_port = input->touch_port; - platf::abs_mouse(platf_input, platform_touch_port(touch_port), tpcoords->first, tpcoords->second); + platf::abs_mouse(host.platf_input, platform_touch_port(touch_port), tpcoords->first, tpcoords->second); } /** @@ -925,19 +978,20 @@ namespace input { * @param packet The mouse button packet. */ void passthrough(std::shared_ptr &input, PNV_MOUSE_BUTTON_PACKET packet) { + auto &host = input->host; 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); - if (button > 0 && button < mouse_press.size()) { - if (mouse_press[button] != release) { + if (button > 0 && button < host.mouse_press.size()) { + if (host.mouse_press[button] != release) { // button state is already what we want return; } - mouse_press[button] = !release; + host.mouse_press[button] = !release; } /** * When Moonlight sends mouse input through absolute coordinates, @@ -954,19 +1008,19 @@ namespace input { * when the last mouse coordinates were absolute */ if (button == BUTTON_LEFT && release && !input->mouse_left_button_timeout) { - auto f = [=]() { - auto left_released = mouse_press[BUTTON_LEFT]; + auto f = [=, &host]() { + auto left_released = host.mouse_press[BUTTON_LEFT]; if (left_released) { // Already released left button return; } - platf::button_mouse(platf_input, BUTTON_LEFT, release); + platf::button_mouse(host.platf_input, BUTTON_LEFT, release); - mouse_press[BUTTON_LEFT] = false; + host.mouse_press[BUTTON_LEFT] = false; input->mouse_left_button_timeout = nullptr; }; - input->mouse_left_button_timeout = task_pool.pushDelayed(std::move(f), 10ms).task_id; + input->mouse_left_button_timeout = host.scheduler.pushDelayed(std::move(f), 10ms).task_id; return; } @@ -974,15 +1028,15 @@ namespace input { button == BUTTON_RIGHT && !release && input->mouse_left_button_timeout > DISABLE_LEFT_BUTTON_DELAY ) { - platf::button_mouse(platf_input, BUTTON_RIGHT, false); - platf::button_mouse(platf_input, BUTTON_RIGHT, true); + platf::button_mouse(host.platf_input, BUTTON_RIGHT, false); + platf::button_mouse(host.platf_input, BUTTON_RIGHT, true); - mouse_press[BUTTON_RIGHT] = false; + host.mouse_press[BUTTON_RIGHT] = false; return; } - platf::button_mouse(platf_input, button, release); + platf::button_mouse(host.platf_input, button, release); } /** @@ -1123,15 +1177,16 @@ namespace input { * @param release Whether the key event is a release. * @param flags Bit flags that modify the requested operation. * @param extended Whether the client identified an extended key. + * @param host Host input or video service and its capture dependencies. */ - void emit_keyboard_update(uint16_t key_code, bool release, uint8_t flags, bool extended = false) { + void emit_keyboard_update(service_t::impl_t &host, uint16_t key_code, bool release, uint8_t flags, bool extended = false) { #ifdef SUNSHINE_TESTS - if (keyboard_sink()) { - keyboard_sink()(testing::keyboard_event_t {key_code, release, flags, extended}); + if (keyboard_sink(host)) { + keyboard_sink(host)(testing::keyboard_event_t {key_code, release, flags, extended}); return; } #endif - platf::keyboard_update(platf_input, key_code, release, flags, extended); + platf::keyboard_update(host.platf_input, key_code, release, flags, extended); } /** @@ -1142,33 +1197,34 @@ namespace input { * @param flags Bit flags that modify the requested operation. * @param synthetic_modifiers Synthetic modifiers. * @param extended Whether the client identified an extended key. + * @param host Host input or video service and its capture dependencies. */ - void send_key_and_modifiers(uint16_t key_code, bool release, uint8_t flags, uint8_t synthetic_modifiers, bool extended) { + void send_key_and_modifiers(service_t::impl_t &host, uint16_t key_code, bool release, uint8_t flags, uint8_t synthetic_modifiers, bool extended) { if (!release) { // Press any synthetic modifiers required for this key if (synthetic_modifiers & MODIFIER_SHIFT) { - emit_keyboard_update(VKEY_SHIFT, false, flags); + emit_keyboard_update(host, VKEY_SHIFT, false, flags); } if (synthetic_modifiers & MODIFIER_CTRL) { - emit_keyboard_update(VKEY_CONTROL, false, flags); + emit_keyboard_update(host, VKEY_CONTROL, false, flags); } if (synthetic_modifiers & MODIFIER_ALT) { - emit_keyboard_update(VKEY_MENU, false, flags); + emit_keyboard_update(host, VKEY_MENU, false, flags); } } - emit_keyboard_update(map_keycode(key_code), release, flags, extended); + emit_keyboard_update(host, map_keycode(key_code), release, flags, extended); if (!release) { // Raise any synthetic modifier keys we pressed if (synthetic_modifiers & MODIFIER_SHIFT) { - emit_keyboard_update(VKEY_SHIFT, true, flags); + emit_keyboard_update(host, VKEY_SHIFT, true, flags); } if (synthetic_modifiers & MODIFIER_CTRL) { - emit_keyboard_update(VKEY_CONTROL, true, flags); + emit_keyboard_update(host, VKEY_CONTROL, true, flags); } if (synthetic_modifiers & MODIFIER_ALT) { - emit_keyboard_update(VKEY_MENU, true, flags); + emit_keyboard_update(host, VKEY_MENU, true, flags); } } } @@ -1179,18 +1235,23 @@ namespace input { * @param key_code Moonlight keyboard packet key code. * @param flags Bit flags that modify the requested operation. * @param synthetic_modifiers Synthetic modifiers. + * @param owner Host input or video service and its capture dependencies. */ - void repeat_key(uint16_t key_code, uint8_t flags, uint8_t synthetic_modifiers) { + void repeat_key(std::shared_ptr owner, uint16_t key_code, uint8_t flags, uint8_t synthetic_modifiers) { + auto &host = *owner; + if (host.stopping.load()) { + return; + } // If key no longer pressed, stop repeating - const auto state = key_press[make_kpid(key_code, flags)]; + const auto state = host.key_press[make_kpid(key_code, flags)]; if (!state.pressed) { - key_press_repeat_id = nullptr; + host.key_press_repeat_id = nullptr; return; } - send_key_and_modifiers(key_code, false, flags, synthetic_modifiers, state.extended); + send_key_and_modifiers(host, key_code, false, flags, synthetic_modifiers, state.extended); - key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_period, key_code, flags, synthetic_modifiers).task_id; + host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, config::input.key_repeat_period, std::move(owner), key_code, flags, synthetic_modifiers).task_id; } /** @@ -1200,6 +1261,7 @@ namespace input { * @param packet Protocol packet being processed. */ void passthrough(std::shared_ptr &input, PNV_KEYBOARD_PACKET packet) { + auto &host = input->host; if (!config::input.keyboard) { return; } @@ -1230,23 +1292,23 @@ namespace input { } } - auto &state = key_press[make_kpid(keyCode, packet->flags)]; + auto &state = host.key_press[make_kpid(keyCode, packet->flags)]; if (!state.pressed) { if (!release) { // A new key has been pressed down, we need to check for key combo's // If a key-combo has been pressed down, don't pass it through - if (input->shortcutFlags == input_t::SHORTCUT && apply_shortcut(keyCode) > 0) { + if (input->shortcutFlags == input_t::SHORTCUT && apply_shortcut(host, keyCode) > 0) { return; } state.extended = (modifiers & MODIFIER_EXTENDED) != 0; - if (key_press_repeat_id) { - task_pool.cancel(key_press_repeat_id); + if (host.key_press_repeat_id) { + host.scheduler.cancel(host.key_press_repeat_id); } if (config::input.key_repeat_delay.count() > 0) { - key_press_repeat_id = task_pool.pushDelayed(repeat_key, config::input.key_repeat_delay, keyCode, packet->flags, synthetic_modifiers).task_id; + host.key_press_repeat_id = host.scheduler.pushDelayed(repeat_key, config::input.key_repeat_delay, input->owner, keyCode, packet->flags, synthetic_modifiers).task_id; } } else { // Already released @@ -1259,7 +1321,7 @@ namespace input { state.pressed = !release; - send_key_and_modifiers(keyCode, release, packet->flags, synthetic_modifiers, state.extended); + send_key_and_modifiers(host, keyCode, release, packet->flags, synthetic_modifiers, state.extended); // Track the modifier state the client is holding, not the remapped host key. // This is compared against packet->modifiers above, which is client-side, so a @@ -1273,18 +1335,19 @@ namespace input { * @param packet The scroll packet. */ void passthrough(std::shared_ptr &input, PNV_SCROLL_PACKET packet) { + auto &host = input->host; if (!config::input.mouse) { return; } if (config::input.high_resolution_scrolling) { - platf::scroll(platf_input, util::endian::big(packet->scrollAmt1)); + platf::scroll(host.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) { // Send any full ticks that have accumulated and store the rest - platf::scroll(platf_input, full_ticks * WHEEL_DELTA); + platf::scroll(host.platf_input, full_ticks * WHEEL_DELTA); input->accumulated_vscroll_delta -= full_ticks * WHEEL_DELTA; } } @@ -1296,18 +1359,19 @@ namespace input { * @param packet The scroll packet. */ void passthrough(std::shared_ptr &input, PSS_HSCROLL_PACKET packet) { + auto &host = input->host; if (!config::input.mouse) { return; } if (config::input.high_resolution_scrolling) { - platf::hscroll(platf_input, util::endian::big(packet->scrollAmount)); + platf::hscroll(host.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) { // Send any full ticks that have accumulated and store the rest - platf::hscroll(platf_input, full_ticks * WHEEL_DELTA); + platf::hscroll(host.platf_input, full_ticks * WHEEL_DELTA); input->accumulated_hscroll_delta -= full_ticks * WHEEL_DELTA; } } @@ -1317,14 +1381,15 @@ namespace input { * @brief Forward a client input packet directly to the platform backend. * * @param packet Protocol packet being processed. + * @param host Host input or video service and its capture dependencies. */ - void passthrough(const NV_UNICODE_PACKET *packet) { + void passthrough(service_t::impl_t &host, const NV_UNICODE_PACKET *packet) { if (!config::input.keyboard) { return; } int size = util::endian::big(packet->header.size) - sizeof(packet->header.magic); - platf::unicode(platf_input, packet->text, size); + platf::unicode(host.platf_input, packet->text, size); } /** @@ -1336,6 +1401,7 @@ namespace input { * @return Assigned global gamepad slot, or -1 when allocation fails. */ int alloc_gamepad(std::shared_ptr &input, int client_index, const platf::gamepad_arrival_t &arrival) { + auto &host = input->host; if (client_index < 0 || client_index >= input->gamepads.size()) { BOOST_LOG(warning) << "ControllerNumber out of range ["sv << client_index << ']'; return -1; @@ -1347,13 +1413,13 @@ namespace input { return gamepad.id; } - const auto id = alloc_id(gamepadMask); + const auto id = alloc_id(host.gamepadMask); if (id < 0) { return -1; } - if (platf::alloc_gamepad(platf_input, {id, static_cast(client_index)}, arrival, input->feedback_queue)) { - free_id(gamepadMask, id); + if (platf::alloc_gamepad(host.platf_input, {id, static_cast(client_index)}, arrival, input->feedback_queue)) { + free_id(host.gamepadMask, id); return -1; } @@ -1517,6 +1583,7 @@ namespace input { * @param packet The controller touch packet. */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_TOUCH_PACKET packet) { + auto &host = input->host; if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1541,7 +1608,7 @@ namespace input { from_clamped_netfloat(packet->pressure, 0.0f, 1.0f), }; - platf::gamepad_touch(platf_input, touch); + platf::gamepad_touch(host.platf_input, touch); } /** @@ -1550,6 +1617,7 @@ namespace input { * @param packet The controller motion packet. */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_MOTION_PACKET packet) { + auto &host = input->host; if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1573,7 +1641,7 @@ namespace input { from_netfloat(packet->z), }; - platf::gamepad_motion(platf_input, motion); + platf::gamepad_motion(host.platf_input, motion); } /** @@ -1582,6 +1650,7 @@ namespace input { * @param packet The controller battery packet. */ void passthrough(std::shared_ptr &input, PSS_CONTROLLER_BATTERY_PACKET packet) { + auto &host = input->host; if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1603,7 +1672,7 @@ namespace input { packet->batteryPercentage }; - platf::gamepad_battery(platf_input, battery); + platf::gamepad_battery(host.platf_input, battery); } /** @@ -1613,6 +1682,7 @@ namespace input { * @param packet Protocol packet being processed. */ void passthrough(std::shared_ptr &input, PNV_MULTI_CONTROLLER_PACKET packet) { + auto &host = input->host; if (!config::input.controller || config::input.gamepad_driver == config::GAMEPAD_DRIVER_NONE) { return; } @@ -1633,7 +1703,7 @@ namespace input { } } else if (!(packet->activeGamepadMask & (1 << packet->controllerNumber)) && gamepad.id >= 0) { // If this is the final event for a gamepad being removed, free the gamepad and return. - ::input::free_gamepad(platf_input, gamepad.id); + ::input::free_gamepad(host, gamepad.id); gamepad.id = -1; return; } @@ -1683,7 +1753,7 @@ namespace input { if (platf::BACK & bf_new) { // Don't emulate home button if timeout < 0 if (config::input.back_button_timeout >= 0ms) { - auto f = [input, controller = packet->controllerNumber]() { + auto f = [input, controller = packet->controllerNumber, &host]() { auto &gamepad = input->gamepads[controller]; auto &state = gamepad.gamepad_state; @@ -1691,31 +1761,31 @@ namespace input { // Force the back button up gamepad.back_button_state = button_state_e::UP; state.buttonFlags &= ~platf::BACK; - platf::gamepad_update(platf_input, gamepad.id, state); + platf::gamepad_update(host.platf_input, gamepad.id, state); // Press Home button state.buttonFlags |= platf::HOME; - platf::gamepad_update(platf_input, gamepad.id, state); + platf::gamepad_update(host.platf_input, gamepad.id, state); // Sleep for a short time to allow the input to be detected std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Release Home button state.buttonFlags &= ~platf::HOME; - platf::gamepad_update(platf_input, gamepad.id, state); + platf::gamepad_update(host.platf_input, gamepad.id, state); gamepad.back_timeout_id = nullptr; }; - gamepad.back_timeout_id = task_pool.pushDelayed(std::move(f), config::input.back_button_timeout).task_id; + gamepad.back_timeout_id = host.scheduler.pushDelayed(std::move(f), config::input.back_button_timeout).task_id; } } else if (gamepad.back_timeout_id) { - task_pool.cancel(gamepad.back_timeout_id); + host.scheduler.cancel(gamepad.back_timeout_id); gamepad.back_timeout_id = nullptr; } } - platf::gamepad_update(platf_input, gamepad.id, gamepad_state); + platf::gamepad_update(host.platf_input, gamepad.id, gamepad_state); gamepad.gamepad_state = gamepad_state; } @@ -2094,13 +2164,14 @@ namespace input { * @param input Retained stream input state. */ void schedule_input_packet_task(const std::shared_ptr &input) { + auto &host = input->host; #ifdef SUNSHINE_TESTS - if (const auto &sink = input_task_sink(); sink) { + if (const auto &sink = input_task_sink(host); sink) { sink(input); return; } #endif - task_pool.push(passthrough_queued_messages, input); + host.scheduler.push(passthrough_queued_messages, input); } /** @@ -2110,6 +2181,7 @@ namespace input { * @return True if a packet was processed, or false when the stream queue is empty. */ bool passthrough_next_message(std::shared_ptr &input) { + auto &host = input->host; // 'entry' backs the 'payload' pointer, so they must remain in scope together std::vector entry; PNV_INPUT_HEADER payload; @@ -2155,7 +2227,7 @@ namespace input { input::print((void *) payload); #ifdef SUNSHINE_TESTS - if (const auto &hook = input_packet_hook(); hook) { + if (const auto &hook = input_packet_hook(host); hook) { hook(util::endian::little(payload->magic)); } #endif @@ -2183,7 +2255,7 @@ namespace input { passthrough(input, (PNV_KEYBOARD_PACKET) payload); break; case UTF8_TEXT_EVENT_MAGIC: - passthrough(static_cast(static_cast(payload))); + passthrough(host, static_cast(static_cast(payload))); break; case MULTI_CONTROLLER_MAGIC_GEN5: passthrough(input, (PNV_MULTI_CONTROLLER_PACKET) payload); @@ -2270,26 +2342,28 @@ namespace input { /** * @brief Release every pressed mouse button tracked by Sunshine. + * @param host Host input or video service and its capture dependencies. */ - void reset_mouse_buttons() { - for (int button = 0; button < mouse_press.size(); ++button) { - if (mouse_press[button]) { - platf::button_mouse(platf_input, button, true); - mouse_press[button] = false; + void reset_mouse_buttons(service_t::impl_t &host) { + for (int button = 0; button < host.mouse_press.size(); ++button) { + if (host.mouse_press[button]) { + platf::button_mouse(host.platf_input, button, true); + host.mouse_press[button] = false; } } } /** * @brief Release every pressed keyboard key tracked by Sunshine. + * @param host Host input or video service and its capture dependencies. */ - void reset_keyboard_keys() { - for (auto &[key, state] : key_press) { + void reset_keyboard_keys(service_t::impl_t &host) { + for (auto &[key, state] : host.key_press) { if (state.pressed) { - // key_press is keyed on the client's unmapped virtual-key code, but the press was + // host.key_press is keyed on the client's unmapped virtual-key code, but the press was // emitted through map_keycode(). Release the host key that actually went down, // otherwise a remapped modifier stays latched after the client disconnects. - emit_keyboard_update(map_keycode(vk_from_kpid(key) & 0x00FF), true, flags_from_kpid(key), state.extended); + emit_keyboard_update(host, map_keycode(vk_from_kpid(key) & 0x00FF), true, flags_from_kpid(key), state.extended); state.pressed = false; } } @@ -2301,16 +2375,17 @@ namespace input { * @param input Retained stream input state to neutralize. */ void reset_gamepads(const std::shared_ptr &input) { + auto &host = input->host; for (int client_index = 0; client_index < input->gamepads.size(); ++client_index) { auto &gamepad = input->gamepads[client_index]; if (gamepad.back_timeout_id) { - task_pool.cancel(gamepad.back_timeout_id); + host.scheduler.cancel(gamepad.back_timeout_id); gamepad.back_timeout_id = nullptr; } if (gamepad.id >= 0) { - platf::gamepad_update(platf_input, gamepad.id, {}); + platf::gamepad_update(host.platf_input, gamepad.id, {}); platf::gamepad_touch( - platf_input, + host.platf_input, {{gamepad.id, static_cast(client_index)}, LI_TOUCH_EVENT_CANCEL_ALL, 0, 0.0F, 0.0F, 0.0F} ); } @@ -2325,8 +2400,9 @@ namespace input { * @param input Retained stream input state to reset. */ void reset_input_state(const std::shared_ptr &input) { - reset_mouse_buttons(); - reset_keyboard_keys(); + auto &host = input->host; + reset_mouse_buttons(host); + reset_keyboard_keys(host); reset_gamepads(input); } @@ -2334,32 +2410,35 @@ namespace input { * @brief Reset the object to its initial empty state. */ void reset(std::shared_ptr &input) { - task_pool.cancel(key_press_repeat_id); - task_pool.cancel(input->mouse_left_button_timeout); + auto &host = input->host; + host.scheduler.cancel(host.key_press_repeat_id); + host.scheduler.cancel(input->mouse_left_button_timeout); - // Ensure input is synchronous, by using the task_pool - task_pool.push(reset_input_state, input); + // Ensure input is synchronous, by using the host.scheduler + host.scheduler.push(reset_input_state, input); } - void terminate_gamepads() { + void service_t::terminate_gamepads() { + auto &host = *impl_; retained_input_map_t inputs; { - auto &state = retained_input_state(); + auto &state = host.retained; std::lock_guard lock {state.mutex}; state.inputs.swap(inputs); } if (!inputs.empty()) { - dispatch_input_task([inputs = std::move(inputs)]() { + dispatch_input_task(host, [inputs = std::move(inputs), &host]() { destroy_gamepads(inputs); }); } } - void terminate_gamepads(const std::string_view session_id) { + void service_t::terminate_gamepads(const std::string_view session_id) { + auto &host = *impl_; std::shared_ptr input; { - auto &state = retained_input_state(); + auto &state = host.retained; std::lock_guard lock {state.mutex}; const auto iter = state.inputs.find(session_id); if (iter == state.inputs.end()) { @@ -2370,58 +2449,65 @@ namespace input { state.inputs.erase(iter); } - dispatch_input_task([input = std::move(input)]() { + dispatch_input_task(host, [input = std::move(input), &host]() { destroy_gamepads(input); }); } - /** - * @brief RAII helper that runs shutdown cleanup when destroyed. - */ - class deinit_t: public platf::deinit_t { - public: - /** - * @brief Destroy the input subsystem deinitializer. - */ - ~deinit_t() override { + service_t::service_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor): + impl_ {std::make_shared(scheduler, std::move(mail), cursor)} { + } + + service_t::~service_t() { + auto &host = *impl_; + host.stopping.store(true); + auto cleanup = [owner = impl_]() { + auto &host = *owner; retained_input_map_t inputs; { - auto &state = retained_input_state(); - std::lock_guard lock {state.mutex}; - state.inputs.swap(inputs); + std::lock_guard lock {host.retained.mutex}; + host.retained.inputs.swap(inputs); } + for (const auto &[id, input] : inputs) { + host.scheduler.cancel(input->mouse_left_button_timeout); + } + host.scheduler.cancel(host.key_press_repeat_id); destroy_gamepads(inputs); - platf_input.reset(); + host.platf_input.reset(); + }; + if (host.scheduler.running()) { + host.scheduler.push(std::move(cleanup)).get(); + } else { + cleanup(); } - }; + } - /** - * @brief Initialize the platform input backend. - */ - [[nodiscard]] std::unique_ptr init() { - platf_input = platf::input(); - - return std::make_unique(); + bool service_t::initialize() { + impl_->platf_input = platf::input(impl_->scheduler); + return static_cast(impl_->platf_input); } /** * @brief Probe connected gamepads and update input capability state. */ - bool probe_gamepads() { - const auto &gamepads = platf::supported_gamepads(std::addressof(platf_input)); + bool service_t::probe_gamepads() { + auto &host = *impl_; + const auto &gamepads = platf::supported_gamepads(std::addressof(host.platf_input)); return std::ranges::none_of(gamepads, [](const auto &gamepad) { return gamepad.is_enabled && gamepad.name != "auto"; }); } - void refresh_virtual_input() { - dispatch_input_task([]() { - if (platf_input) { - task_pool.cancel(key_press_repeat_id); - key_press_repeat_id = nullptr; - reset_mouse_buttons(); - reset_keyboard_keys(); - auto &context = platf::virtualhid::get_input_context(platf_input); + void service_t::refresh_virtual_input() { + auto &host = *impl_; + dispatch_input_task(host, [owner = impl_]() { + auto &host = *owner; + if (host.platf_input) { + host.scheduler.cancel(host.key_press_repeat_id); + host.key_press_repeat_id = nullptr; + reset_mouse_buttons(host); + reset_keyboard_keys(host); + auto &context = platf::virtualhid::get_input_context(host.platf_input); context.refresh_keyboard(); context.refresh_mouse(); } @@ -2431,11 +2517,12 @@ namespace input { /** * @brief Allocate and initialize platform input state for a stream. */ - std::shared_ptr alloc(safe::mail_t mail, std::string session_id) { + std::shared_ptr service_t::alloc(safe::mail_t mail, std::string session_id) { + auto &host = *impl_; std::shared_ptr input; bool resumed = false; { - auto &state = retained_input_state(); + auto &state = host.retained; std::lock_guard lock {state.mutex}; const auto iter = state.inputs.find(session_id); if (iter != state.inputs.end()) { @@ -2443,6 +2530,7 @@ namespace input { resumed = true; } else { input = std::make_shared( + impl_, mail->event(mail::touch_port), mail->queue(mail::gamepad_feedback) ); @@ -2451,27 +2539,30 @@ namespace input { } if (resumed) { - dispatch_input_task([input, mail = std::move(mail)]() { + dispatch_input_task(host, [input, mail = std::move(mail), &host]() { rebind_input(input, mail); }); } // Workaround to ensure new frames will be captured when a client connects - task_pool.pushDelayed([]() { - platf::move_mouse(platf_input, 1, 1); - platf::move_mouse(platf_input, -1, -1); + host.scheduler.pushDelayed([owner = impl_]() { + if (!owner->stopping.load()) { + platf::move_mouse(owner->platf_input, 1, 1); + platf::move_mouse(owner->platf_input, -1, -1); + } }, - 100ms); + 100ms); return input; } #ifdef SUNSHINE_TESTS namespace testing { - void set_platform_input(platf::input_t input) { - terminate_gamepads(); - platf_input = std::move(input); - gamepadMask.reset(); + void set_platform_input(service_t &service, platf::input_t input) { + auto &host = service_access_t::state(service); + service.terminate_gamepads(); + host.platf_input = std::move(input); + host.gamepadMask.reset(); } int alloc_gamepad(std::shared_ptr &input, std::uint8_t client_index, const platf::gamepad_arrival_t &metadata) { @@ -2485,20 +2576,23 @@ namespace input { return input->gamepads[client_index].id; } - void set_input_packet_hook(std::function hook) { - input_packet_hook() = std::move(hook); + void set_input_packet_hook(service_t &service, std::function hook) { + auto &host = service_access_t::state(service); + input_packet_hook(host) = std::move(hook); } - void set_input_task_sink(std::function)> sink) { - input_task_sink() = std::move(sink); + void set_input_task_sink(service_t &service, std::function)> sink) { + auto &host = service_access_t::state(service); + input_task_sink(host) = std::move(sink); } void process_queued_messages(std::shared_ptr input) { ::input::passthrough_queued_messages(std::move(input)); } - void set_keyboard_sink(std::function sink) { - keyboard_sink() = std::move(sink); + void set_keyboard_sink(service_t &service, std::function sink) { + auto &host = service_access_t::state(service); + keyboard_sink(host) = std::move(sink); } void send_keyboard_packet(std::shared_ptr &input, std::uint16_t key_code, std::uint8_t modifiers, std::uint8_t flags, bool release) { @@ -2525,14 +2619,16 @@ namespace input { ::input::passthrough(input, &packet); } - void reset_keyboard_state() { - task_pool.cancel(key_press_repeat_id); - key_press_repeat_id = nullptr; - key_press.clear(); + void reset_keyboard_state(service_t &service) { + auto &host = service_access_t::state(service); + host.scheduler.cancel(host.key_press_repeat_id); + host.key_press_repeat_id = nullptr; + host.key_press.clear(); } - void release_held_keys() { - reset_keyboard_keys(); + void release_held_keys(service_t &service) { + auto &host = service_access_t::state(service); + reset_keyboard_keys(host); } bool is_valid_input_packet(std::span packet) { diff --git a/src/input.h b/src/input.h index f181f6336..a0876c2b3 100644 --- a/src/input.h +++ b/src/input.h @@ -17,9 +17,74 @@ #include "platform/common.h" #include "thread_safe.h" +namespace thread_pool_util { + class ThreadPool; +} + namespace input { struct input_t; + /** + * @brief Owns host input state shared by all clients of one application. + */ + class service_t { + public: + struct impl_t; ///< Private implementation retained by client input sessions. + + /** + * @brief Bind the host scheduler, mailbox, and cursor preference. + * @param scheduler Scheduler serializing input work. + * @param mail Host mailbox carrying display selection. + * @param cursor Host cursor visibility preference. + */ + service_t(thread_pool_util::ThreadPool &scheduler, safe::mail_t mail, bool &cursor); + service_t(const service_t &) = delete; + service_t &operator=(const service_t &) = delete; + /** + * @brief Release retained virtual devices and the platform input backend. + */ + ~service_t(); + + /** + * @brief Initialize the platform input backend at the application startup stage. + * @return Whether a platform input context was created. + */ + bool initialize(); + + /** + * @brief Destroy all retained virtual gamepad sessions. + */ + void terminate_gamepads(); + /** + * @brief Destroy the retained virtual gamepads for one paired client. + * @param session_id Stable paired-client identity. + */ + void terminate_gamepads(std::string_view session_id); + + /** + * @brief Check whether any configured gamepad backend is available. + * @return True when no enabled backend was found. + */ + bool probe_gamepads(); + + /** + * @brief Serialize keyboard and mouse backend refresh with streamed input. + */ + void refresh_virtual_input(); + + /** + * @brief Allocate or resume input state for a paired client. + * @param mail Mailbox for the active transport session. + * @param session_id Stable paired-client identity. + * @return Retained client input state bound to the transport mailbox. + */ + std::shared_ptr alloc(safe::mail_t mail, std::string session_id); + + private: + friend struct service_access_t; + std::shared_ptr impl_; ///< Host input state retained by queued tasks and client sessions. + }; + /** * @brief Write a debug log representation of the input packet. * @@ -33,65 +98,20 @@ namespace input { */ void reset(std::shared_ptr &input); - /** - * @brief Destroy every retained virtual gamepad session. - * - * Retained gamepads survive a paused transport connection so they can be reused on resume. Call this when the - * streamed application or all streaming sessions are explicitly terminated. - */ - void terminate_gamepads(); - - /** - * @brief Destroy virtual gamepads retained for one paired client. - * - * @param session_id Stable paired-client identity used by alloc(). - */ - void terminate_gamepads(std::string_view session_id); - /** * @brief Queue a raw input message for platform passthrough. */ void passthrough(std::shared_ptr &input, std::vector &&input_data); - /** - * @brief Initialize global input resources and platform backends. - * - * @return Cleanup handle for initialized input resources, or null if none are required. - */ - [[nodiscard]] std::unique_ptr init(); - - /** - * @brief Probe whether the platform can create virtual gamepads. - * - * @return True when at least one configured gamepad backend is available. - */ - bool probe_gamepads(); - - /** - * @brief Recreate shared libvirtualhid keyboard and mouse devices after a license-state change. - * - * The work is serialized with streamed input so both backends can switch - * safely between the Windows HID and SendInput paths. - */ - void refresh_virtual_input(); - - /** - * @brief Allocate and initialize platform input state for a stream. - * - * @param mail Mailbox used to exchange messages with worker threads. - * @param session_id Stable paired-client identity shared by launch and resume connections. - * @return Shared input state bound to the stream mailbox. - */ - std::shared_ptr alloc(safe::mail_t mail, std::string session_id); - #ifdef SUNSHINE_TESTS namespace testing { /** * @brief Replace the global platform input backend for a unit test. * * @param input Test-owned platform input backend. + * @param service Fixture-owned host input service. */ - void set_platform_input(platf::input_t input); + void set_platform_input(service_t &service, platf::input_t input); /** * @brief Allocate a gamepad directly in retained input state for a unit test. @@ -115,15 +135,17 @@ namespace input { /** * @brief Install a callback called just before dispatching a queued input packet in a test. * @param hook Callback receiving the packet magic, or empty to remove it. + * @param service Fixture-owned host input service. */ - void set_input_packet_hook(std::function hook); + void set_input_packet_hook(service_t &service, std::function hook); /** * @brief Redirect input task scheduling to a test callback. * * @param sink Callback receiving the stream whose packet task was queued, or empty to restore the worker pool. + * @param service Fixture-owned host input service. */ - void set_input_task_sink(std::function)> sink); + void set_input_task_sink(service_t &service, std::function)> sink); /** * @brief Process queued input packets on the calling thread in a test. @@ -151,7 +173,7 @@ namespace input { * @param sink Recorder invoked in place of platf::keyboard_update, or empty to restore * delivery to the platform backend. */ - void set_keyboard_sink(std::function sink); + void set_keyboard_sink(service_t &service, std::function sink); /** * @brief Process one client keyboard packet on the calling thread. @@ -176,12 +198,12 @@ namespace input { /** * @brief Forget every key Sunshine tracks as pressed and cancel any pending key repeat. */ - void reset_keyboard_state(); + void reset_keyboard_state(service_t &service); /** * @brief Release every key Sunshine tracks as pressed, as a disconnect does. */ - void release_held_keys(); + void release_held_keys(service_t &service); /** * @brief Validate raw protocol input bytes for a unit test. diff --git a/src/platform/common.h b/src/platform/common.h index adb97f352..78d7add3d 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -41,6 +41,22 @@ struct AVHWFramesContext; struct AVCodecContext; struct AVDictionary; +namespace thread_pool_util { + class ThreadPool; +} + +namespace lifetime { + class controller_t; +} + +namespace display_device { + class manager_t; +} + +namespace nvprefs { + class nvprefs_interface; +} + #ifdef _WIN32 // Forward declarations of boost classes to avoid having to include boost headers // here, which results in issues with Windows.h and WinSock2.h include order. @@ -986,7 +1002,7 @@ namespace platf { void streaming_will_start(); void streaming_will_stop(); - void restart(); + void restart(lifetime::controller_t &lifetime); /** * @brief Platform buffer pointer and size for batched socket sends. @@ -1110,6 +1126,97 @@ namespace platf { */ 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); + /** + * @brief Own platform resources for one application lifetime. + */ + class runtime_t { + public: + /** + * @brief Bind the application services used by platform resources. + * @param mail Application mailbox. + * @param scheduler Scheduler for deferred native input and capture work. + * @param lifetime Application exit and restart controller. + * @param displays Display configuration manager. + * @param preferences NVIDIA preference manager on Windows. + */ + runtime_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &displays +#ifdef _WIN32 + , + nvprefs::nvprefs_interface &preferences +#endif + ); + /** + * @brief Release platform resources after their consumers stop. + */ + ~runtime_t(); + /** + * @brief Platform owners cannot be copied. + */ + runtime_t(const runtime_t &) = delete; + /** + * @brief Platform owners cannot be assigned. + */ + runtime_t &operator=(const runtime_t &) = delete; + /** + * @brief Initialize native capture and application resources. + * @return Whether initialization succeeded. + */ + bool initialize(); + /** + * @brief Enumerate names accepted by the selected capture backend. + * @param type Requested memory type. + * @return Display names. + */ + std::vector display_names(mem_type_e type); + /** + * @brief Create a capture resource. + * @param type Requested memory type. + * @param name Display name. + * @param config Capture configuration. + * @return Capture resource, or nullptr. + */ + std::shared_ptr display(mem_type_e type, const std::string &name, const video::config_t &config); + /** + * @brief Check whether a GPU change requires another encoder probe. + * @return Whether to repeat probing. + */ + bool needs_encoder_reenumeration(); + /** + * @brief Set codec requirements for subsequently created capture resources. + * @param hevc_mode Active HEVC mode. + */ + void set_capture_requirements(int hevc_mode); + /** + * @brief Apply native settings when streaming begins. + */ + void streaming_will_start(); + /** + * @brief Restore native settings when streaming ends. + */ + void streaming_will_stop(); + /** + * @brief Enable native mouse support when required by the current devices. + */ + void enable_mouse_keys(); + /** + * @brief Create scoped socket priority settings. + * @param socket Native socket. + * @param address Destination address. + * @param port Destination port. + * @param type Traffic class. + * @param dscp_tagging Enable DSCP tagging. + * @return Settings lifetime owner. + */ + std::unique_ptr enable_socket_qos(uintptr_t socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e type, bool dscp_tagging); + + private: + /** + * @brief Native implementation retained by dependent resources. + */ + struct impl_t; + std::shared_ptr impl; + }; + /** * @brief Open a url in the default web browser. * @param url The url to open. @@ -1135,7 +1242,7 @@ namespace platf { * * @return Platform-specific input backend for the active stream. */ - input_t input(); + input_t input(thread_pool_util::ThreadPool &scheduler); /** * @brief Get the current mouse position for platform input tests. * diff --git a/src/platform/linux/capture_geometry.h b/src/platform/linux/capture_geometry.h new file mode 100644 index 000000000..ab135b045 --- /dev/null +++ b/src/platform/linux/capture_geometry.h @@ -0,0 +1,31 @@ +/** + * @file src/platform/linux/capture_geometry.h + * @brief Desktop bounds computed from a capture resource's discovered outputs. + */ +#pragma once +#include "src/platform/common.h" + +#include + +namespace platf { + /** + * @brief Physical and logical desktop extents relative to the desktop origin. + */ + struct capture_geometry_t { + int width {}; ///< Physical right edge. + int height {}; ///< Physical bottom edge. + int logical_width {}; ///< Logical right edge. + int logical_height {}; ///< Logical bottom edge. + + /** + * @brief Extend this snapshot with one discovered output. + * @param viewport Output position and physical/logical sizes. + */ + void include(const touch_port_t &viewport) { + width = std::max(width, viewport.offset_x + viewport.width); + height = std::max(height, viewport.offset_y + viewport.height); + logical_width = std::max(logical_width, viewport.offset_x + viewport.logical_width); + logical_height = std::max(logical_height, viewport.offset_y + viewport.logical_height); + } + }; +} // namespace platf diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 9f00fd88d..18166ee8a 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -22,6 +22,7 @@ #include // local includes +#include "capture_geometry.h" #include "cuda.h" #include "graphics.h" #include "kms_plane.h" @@ -343,12 +344,6 @@ namespace platf { */ using conn_type_count_t = std::map; - static int env_width; - static int env_height; - - static int env_logical_width; - static int env_logical_height; - /** * @brief Convert a DRM plane type value to a diagnostic string. * @@ -410,7 +405,20 @@ namespace platf { std::map crtc_to_monitor; ///< Crtc to monitor. }; - static std::vector card_descriptors; + /** + * @brief Discovery metadata owned by one platform runtime. + */ + struct capture_state_t { + int env_width {}; ///< Physical desktop width. + int env_height {}; ///< Physical desktop height. + int env_logical_width {}; ///< Logical desktop width. + int env_logical_height {}; ///< Logical desktop height. + std::vector card_descriptors; ///< Discovered card metadata. + }; + + std::shared_ptr make_capture_state() { + return std::make_shared(); + } static std::uint32_t from_view(const std::string_view &string) { #ifndef DOXYGEN @@ -697,7 +705,7 @@ namespace platf { * @param path Filesystem path for the DRM device or resource. * @return 0 on success; nonzero or negative platform status on failure. */ - int init(const char *path) { + int init(const char *path, window_system_e window_system) { fd.el = platf::kms::privileged_drm_worker::open_drm_card_fd_privileged(path); if (fd.el < 0) { return -1; @@ -1114,13 +1122,13 @@ namespace platf { * @param display_name Name of the display to determine monitor index for (or monitor index string value) * @return monitor's display index */ - static int64_t map_display_name_to_monitor_index(const std::string_view &display_name) { + static int64_t map_display_name_to_monitor_index(const std::string_view &display_name, const capture_state_t &state) { // Handle (legacy) monitor index strings by converting them to integer if (display_name.empty() || std::ranges::all_of(display_name, ::isdigit)) { return util::from_view(display_name); } // display_name is a connector name (not empty and containing non-digits) - for (auto &card_descriptor : kms::card_descriptors) { + for (auto &card_descriptor : state.card_descriptors) { for (const auto &monitor_descriptor : card_descriptor.crtc_to_monitor | std::views::values) { if (display_name == std::format("{}-{}", drmModeGetConnectorTypeName(monitor_descriptor.type), monitor_descriptor.index)) { BOOST_LOG(info) << "Mapped '"sv << display_name << "' to kmsgrab monitor index " << monitor_descriptor.monitor_index; @@ -1142,9 +1150,12 @@ namespace platf { * * @param mem_type Mem type. */ - display_t(mem_type_e mem_type): + display_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): platf::display_t(), - mem_type {mem_type} { + mem_type {mem_type}, + state(state), + window_system(window_system), + hevc_mode(hevc_mode) { } /** @@ -1154,10 +1165,14 @@ namespace platf { * @param config Configuration values to apply. * @return 0 on success; nonzero or negative platform status on failure. */ + capture_state_t state; ///< Immutable discovery snapshot for this capture resource. + window_system_e window_system; ///< Session type when this resource was created. + int hevc_mode; ///< Codec validation requirement for this resource. + int init(const std::string &display_name, const ::video::config_t &config) { delay = ::video::capture_frame_interval(config); - int monitor_index = map_display_name_to_monitor_index(display_name); + int monitor_index = map_display_name_to_monitor_index(display_name, state); int monitor = 0; fs::path card_dir {"/dev/dri"sv}; @@ -1170,7 +1185,7 @@ namespace platf { } kms::card_t card; - if (card.init(entry.path().c_str())) { + if (card.init(entry.path().c_str(), window_system)) { continue; } @@ -1239,11 +1254,11 @@ 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(state.card_descriptors), std::end(state.card_descriptors), [&](card_descriptor_t &cd) { return cd.path == filestring; }); - if (pos == std::end(card_descriptors)) { + if (pos == std::end(state.card_descriptors)) { // This code path shouldn't happen, but it's there just in case. // card_descriptors is part of the guesswork after all. BOOST_LOG(error) << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv; @@ -1259,11 +1274,11 @@ namespace platf { img_offset_x = crtc->x; img_offset_y = crtc->y; - this->env_width = ::platf::kms::env_width; - this->env_height = ::platf::kms::env_height; + this->env_width = state.env_width; + this->env_height = state.env_height; - this->env_logical_width = ::platf::kms::env_logical_width; - this->env_logical_height = ::platf::kms::env_logical_height; + this->env_logical_width = state.env_logical_width; + this->env_logical_height = state.env_logical_height; auto monitor = pos->crtc_to_monitor.find(plane->crtc_id); if (monitor != std::end(pos->crtc_to_monitor)) { @@ -1754,8 +1769,8 @@ namespace platf { * * @param mem_type Mem type. */ - display_ram_t(mem_type_e mem_type): - display_t(mem_type) { + display_ram_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): + display_t(mem_type, state, window_system, hevc_mode) { } /** @@ -1999,8 +2014,8 @@ namespace platf { * * @param mem_type Mem type. */ - display_vram_t(mem_type_e mem_type): - display_t(mem_type) { + display_vram_t(mem_type_e mem_type, const capture_state_t &state, window_system_e window_system, int hevc_mode): + display_t(mem_type, state, window_system, hevc_mode) { } /** @@ -2160,7 +2175,7 @@ namespace platf { } #ifdef SUNSHINE_BUILD_VAAPI - if (mem_type == mem_type_e::vaapi && !va::validate(card.render_fd.el)) { + if (mem_type == mem_type_e::vaapi && !va::validate(card.render_fd.el, hevc_mode)) { BOOST_LOG(warning) << "Monitor "sv << display_name << " doesn't support hardware encoding. Reverting back to GPU -> RAM -> GPU"sv; return -1; } @@ -2189,9 +2204,9 @@ namespace platf { * @param config Configuration values to apply. * @return KMS display backend, or nullptr when initialization fails. */ - std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) { + std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode) { if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda || hwdevice_type == mem_type_e::vulkan) { - auto disp = std::make_shared(hwdevice_type); + auto disp = std::make_shared(hwdevice_type, state, window_system, hevc_mode); if (!disp->init(display_name, config)) { return disp; @@ -2200,7 +2215,7 @@ namespace platf { // In the case of failure, attempt the old method for VAAPI } - auto disp = std::make_shared(hwdevice_type); + auto disp = std::make_shared(hwdevice_type, state, window_system, hevc_mode); if (disp->init(display_name, config)) { return nullptr; @@ -2282,7 +2297,7 @@ namespace platf { * @param hwdevice_type Hardware device type requested for capture or encode. * @return KMS display names, or an empty list when KMS capture is unavailable. */ - std::vector kms_display_names(mem_type_e hwdevice_type) { + std::vector kms_display_names(mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system) { int count = 0; if (!fs::exists("/dev/dri")) { @@ -2310,7 +2325,7 @@ namespace platf { } kms::card_t card; - if (card.init(entry.path().c_str())) { + if (card.init(entry.path().c_str(), window_system)) { continue; } @@ -2379,8 +2394,8 @@ namespace platf { it->second.monitor_index = count; } - kms::env_width = std::max(kms::env_width, (int) (crtc->x + crtc->width)); - kms::env_height = std::max(kms::env_height, (int) (crtc->y + crtc->height)); + state.env_width = std::max(state.env_width, (int) (crtc->x + crtc->width)); + state.env_height = std::max(state.env_height, (int) (crtc->y + crtc->height)); kms::print(plane.get(), fb.get(), crtc.get()); display_names.emplace_back(std::format("{}-{}", drmModeGetConnectorTypeName(it->second.type), it->second.index)); @@ -2397,30 +2412,26 @@ namespace platf { correlate_to_wayland(cds); } - // Deduce the full virtual desktop size - kms::env_width = 0; - kms::env_height = 0; - - kms::env_logical_width = 0; - kms::env_logical_height = 0; - + // Deduce desktop extents from this discovery snapshot. + capture_geometry_t desktop; for (auto &card_descriptor : cds) { for (auto &[_, monitor_descriptor] : card_descriptor.crtc_to_monitor) { BOOST_LOG(debug) << "Monitor description"sv; BOOST_LOG(debug) << "Resolution: "sv << monitor_descriptor.viewport.width << 'x' << monitor_descriptor.viewport.height; BOOST_LOG(debug) << "Offset: "sv << monitor_descriptor.viewport.offset_x << 'x' << monitor_descriptor.viewport.offset_y; - kms::env_width = std::max(kms::env_width, (int) (monitor_descriptor.viewport.offset_x + monitor_descriptor.viewport.width)); - kms::env_height = std::max(kms::env_height, (int) (monitor_descriptor.viewport.offset_y + monitor_descriptor.viewport.height)); - - kms::env_logical_height = std::max(kms::env_logical_height, (int) (monitor_descriptor.viewport.offset_y + monitor_descriptor.viewport.logical_height)); - kms::env_logical_width = std::max(kms::env_logical_width, (int) (monitor_descriptor.viewport.offset_x + monitor_descriptor.viewport.logical_width)); + desktop.include(monitor_descriptor.viewport); } } - BOOST_LOG(debug) << "Desktop resolution: "sv << kms::env_width << 'x' << kms::env_height; + state.env_width = desktop.width; + state.env_height = desktop.height; + state.env_logical_width = desktop.logical_width; + state.env_logical_height = desktop.logical_height; - kms::card_descriptors = std::move(cds); + BOOST_LOG(debug) << "Desktop resolution: "sv << state.env_width << 'x' << state.env_height; + + state.card_descriptors = std::move(cds); BOOST_LOG(debug) << "Final KMS display_names return list: " << (display_names | std::views::join_with(' ') | std::ranges::to()); return display_names; diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index babf0a488..c4686e3d2 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -103,8 +103,6 @@ using namespace std::literals; namespace fs = std::filesystem; namespace bp = boost::process::v1; -window_system_e window_system; ///< Window system. - namespace dyn { /** * @brief Return the native handle owned by the wrapper. @@ -610,7 +608,7 @@ namespace platf { /** * @brief Request a Sunshine process restart on exit. */ - void restart_on_exit() { + void restart_on_exit(char **argv) { std::array executable; ssize_t len = readlink("/proc/self/exe", executable.data(), executable.size() - 1); if (len == -1) { @@ -626,7 +624,7 @@ namespace platf { } // Re-exec ourselves with the same arguments - if (execv(executable.data(), lifetime::get_argv()) < 0) { + if (execv(executable.data(), argv) < 0) { BOOST_LOG(fatal) << "execv() failed: "sv << errno; return; } @@ -635,10 +633,12 @@ namespace platf { /** * @brief Restart the Sunshine process through the platform launcher. */ - void restart() { + void restart(lifetime::controller_t &lifetime) { // Gracefully clean up and restart ourselves instead of exiting - atexit(restart_on_exit); - lifetime::exit_sunshine(0, true); + lifetime.restart_on_exit([argv = lifetime.get_argv()]() { + restart_on_exit(argv); + }); + lifetime.exit_sunshine(0, true); } bool request_process_group_exit(std::uintptr_t native_handle) { @@ -1013,10 +1013,113 @@ namespace platf { return true; } + namespace source { + /** + * @brief Enumerates supported source options. + */ + enum source_e : std::size_t { +#ifdef SUNSHINE_BUILD_CUDA + NVFBC, ///< NvFBC +#endif +#ifdef SUNSHINE_BUILD_WAYLAND + WAYLAND, ///< Wayland +#endif +#ifdef SUNSHINE_BUILD_DRM + KMS, ///< KMS +#endif +#ifdef SUNSHINE_BUILD_X11 + X11, ///< X11 +#endif +#ifdef SUNSHINE_BUILD_KWIN + KWIN, ///< KWin ScreenCast +#endif +#ifdef SUNSHINE_BUILD_PORTAL + PORTAL, ///< XDG PORTAL +#endif + MAX_FLAGS ///< The maximum number of flags + }; + } // namespace source + + /** + * @brief Own capture discovery and deferred portal work for one host. + */ + struct runtime_t::impl_t { + /** + * @brief Bind narrow host dependencies. + * @param mail Host mailbox. + * @param scheduler Host scheduler. + * @param lifetime Exit controller. + */ + impl_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime): + mail(std::move(mail)), + scheduler(scheduler), + lifetime(lifetime) {} + + safe::mail_t mail; ///< Host mailbox retained by portal response loops. + thread_pool_util::ThreadPool &scheduler; ///< Scheduler outliving all captures. + lifetime::controller_t &lifetime; ///< Host restart controller. + window_system_e window_system {window_system_e::NONE}; ///< Detected desktop protocol. + std::bitset sources; ///< Capture backend selection. + std::shared_ptr> qos_ref_count {std::make_shared>(0)}; ///< Active socket-priority scopes. + std::string last_render_device; ///< Last successfully probed GPU render node. + int hevc_mode {}; ///< Codec requirements for newly created captures. + bool initialized {}; ///< Whether platform initialization succeeded. +#ifdef SUNSHINE_BUILD_DRM + std::shared_ptr kms_state {kms::make_capture_state()}; ///< KMS discovery cache. + bool verify_kms(); +#endif +#ifdef SUNSHINE_BUILD_WAYLAND + bool verify_wl(); +#endif +#ifdef SUNSHINE_BUILD_X11 + bool verify_x11(); +#endif +#ifdef SUNSHINE_BUILD_PORTAL + std::jthread xdg_worker; ///< Portal token negotiation worker. + std::once_flag xdg_worker_flag; ///< One negotiation attempt per host. + bool verify_portal(); +#endif + /** + * @brief Stop response loops before joining portal negotiation. + */ + ~impl_t() { +#ifdef SUNSHINE_BUILD_PORTAL + if (xdg_worker.joinable()) { + mail->event(mail::shutdown)->raise(true); + xdg_worker.join(); + } +#endif + } + + /** + * @brief Discover the available capture backends. + * @return Whether capture initialization succeeded. + */ + bool initialize(); + /** + * @brief Enumerate the selected capture backend. + * @param type Memory type. + * @return Display names. + */ + std::vector display_names(mem_type_e type); + /** + * @brief Create a selected capture backend. + * @param type Memory type. + * @param name Display selector. + * @param config Capture options. + * @return Capture resource. + */ + std::shared_ptr display(mem_type_e type, const std::string &name, const video::config_t &config); + /** + * @brief Detect render-node changes. + * @return Whether to repeat encoder probing. + */ + bool needs_encoder_reenumeration(); + }; + // We can't track QoS state separately for each destination on this OS, // so we keep a ref count to only disable QoS options when all clients // are disconnected. - static std::atomic qos_ref_count = 0; /** * @brief Linux QoS state used to tune socket priority while streaming. @@ -1029,14 +1132,15 @@ namespace platf { * @param sockfd Native socket descriptor whose options are updated. * @param options Request options or socket options to apply. */ - qos_t(int sockfd, std::vector> options): + qos_t(std::shared_ptr> count, int sockfd, std::vector> options): + qos_ref_count(std::move(count)), sockfd(sockfd), options(options) { - qos_ref_count++; + (*qos_ref_count)++; } virtual ~qos_t() { - if (--qos_ref_count == 0) { + if (--(*qos_ref_count) == 0) { for (const auto &tuple : options) { auto reset_val = std::get<2>(tuple); if (setsockopt(sockfd, std::get<0>(tuple), std::get<1>(tuple), &reset_val, sizeof(reset_val)) < 0) { @@ -1047,6 +1151,7 @@ namespace platf { } private: + std::shared_ptr> qos_ref_count; ///< Retained priority scope count. int sockfd; std::vector> options; }; @@ -1054,7 +1159,7 @@ namespace platf { /** * @brief Enables QoS on the given socket for traffic to the specified destination. */ - 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 runtime_t::enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging) { int sockfd = (int) native_socket; std::vector> reset_options; @@ -1119,7 +1224,7 @@ namespace platf { } #endif - return std::make_unique(sockfd, reset_options); + return std::make_unique(impl->qos_ref_count, sockfd, reset_options); } std::string get_host_name() { @@ -1131,35 +1236,6 @@ namespace platf { } } - namespace source { - /** - * @brief Enumerates supported source options. - */ - enum source_e : std::size_t { -#ifdef SUNSHINE_BUILD_CUDA - NVFBC, ///< NvFBC -#endif -#ifdef SUNSHINE_BUILD_WAYLAND - WAYLAND, ///< Wayland -#endif -#ifdef SUNSHINE_BUILD_DRM - KMS, ///< KMS -#endif -#ifdef SUNSHINE_BUILD_X11 - X11, ///< X11 -#endif -#ifdef SUNSHINE_BUILD_KWIN - KWIN, ///< KWin ScreenCast -#endif -#ifdef SUNSHINE_BUILD_PORTAL - PORTAL, ///< XDG PORTAL -#endif - MAX_FLAGS ///< The maximum number of flags - }; - } // namespace source - - static std::bitset sources; - #ifdef SUNSHINE_BUILD_CUDA std::vector nvfbc_display_names(); std::shared_ptr nvfbc_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); @@ -1191,32 +1267,32 @@ namespace platf { * * @return True when the active window system is Wayland and at least one output is discoverable. */ - bool verify_wl() { + bool runtime_t::impl_t::verify_wl() { return window_system == window_system_e::WAYLAND && !wl_display_names().empty(); } #endif #ifdef SUNSHINE_BUILD_DRM - std::vector kms_display_names(mem_type_e hwdevice_type); - std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + std::vector kms_display_names(mem_type_e hwdevice_type, kms::capture_state_t &state, window_system_e window_system); + std::shared_ptr kms_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, const kms::capture_state_t &state, window_system_e window_system, int hevc_mode); - bool verify_kms() { - return !kms_display_names(mem_type_e::unknown).empty(); + bool runtime_t::impl_t::verify_kms() { + return !kms_display_names(mem_type_e::unknown, *kms_state, window_system).empty(); } #endif #ifdef SUNSHINE_BUILD_X11 std::vector x11_display_names(); - std::shared_ptr x11_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + std::shared_ptr x11_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, thread_pool_util::ThreadPool &scheduler); - bool verify_x11() { + bool runtime_t::impl_t::verify_x11() { return window_system == window_system_e::X11 && !x11_display_names().empty(); } #endif #ifdef SUNSHINE_BUILD_PORTAL - std::vector portal_display_names(bool allow_start_timeout); - std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + std::vector portal_display_names(bool allow_start_timeout, safe::mail_t mail); + std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail); /** * @brief Enumerates possible Portal probe responses. @@ -1233,7 +1309,7 @@ namespace platf { * * @return Can return no_token, unreachable, stale_token or available for processing via verify_portal(). */ - portal_probe_e probe_portal() { + portal_probe_e probe_portal(safe::mail_t mail) { using enum portal_probe_e; if (!portal::is_portal_service_reachable()) { @@ -1242,7 +1318,7 @@ namespace platf { if (!portal::has_saved_token()) { return no_token; } - return portal_display_names(true).empty() ? stale_token : available; + return portal_display_names(true, mail).empty() ? stale_token : available; } /** @@ -1252,10 +1328,10 @@ namespace platf { * * @return True if Portal is available. */ - bool verify_portal() { + bool runtime_t::impl_t::verify_portal() { using enum portal_probe_e; - auto result = probe_portal(); + auto result = probe_portal(mail); switch (result) { case available: return true; @@ -1265,17 +1341,17 @@ namespace platf { case stale_token: BOOST_LOG(warning) << "[portalgrab] Saved portal token did not produce a session; discarding and restarting."sv; portal::clear_saved_token(); - platf::restart(); + platf::restart(lifetime); return false; case no_token: BOOST_LOG(fatal) << "Portal capture is awaiting user permission. "sv << "The current session will attempt to use a fallback capture method."sv; - std::call_once(portal::xdg_worker_flag, []() { - portal::xdg_worker = std::jthread([]() { + std::call_once(xdg_worker_flag, [this]() { + xdg_worker = std::jthread([this]() { try { platf::set_thread_name("xdg_worker"); - if (!portal_display_names(false).empty()) { - platf::restart(); + if (!portal_display_names(false, mail).empty()) { + platf::restart(lifetime); } else { BOOST_LOG(error) << "[portalgrab] Portal session token was not negotiated."sv; } @@ -1305,7 +1381,7 @@ namespace platf { /** * @brief List display names accepted by the selected capture backend. */ - std::vector display_names(mem_type_e hwdevice_type) { + std::vector runtime_t::impl_t::display_names(mem_type_e hwdevice_type) { #ifdef SUNSHINE_BUILD_CUDA // display using NvFBC only supports mem_type_e::cuda if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) { @@ -1319,7 +1395,7 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { - return kms_display_names(hwdevice_type); + return kms_display_names(hwdevice_type, *kms_state, window_system); } #endif #ifdef SUNSHINE_BUILD_X11 @@ -1329,7 +1405,7 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_PORTAL if (sources[source::PORTAL]) { - return portal_display_names(true); + return portal_display_names(true, mail); } #endif #ifdef SUNSHINE_BUILD_KWIN @@ -1345,11 +1421,10 @@ namespace platf { * * @return Always `true` because Linux GPU changes are not tracked by this backend. */ - bool needs_encoder_reenumeration() { + bool runtime_t::impl_t::needs_encoder_reenumeration() { // Only re-probe if the GPU render device changed (hotplug, driver reload). // Full re-probing on every reconnect leaks ~20 MB due to FFmpeg CBS // allocations during HEVC/AV1 codec validation. - static std::string last_render_device; auto current = platf::resolve_render_device(); if (current == last_render_device) { return false; @@ -1358,14 +1433,14 @@ namespace platf { return true; } - std::shared_ptr display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { + std::shared_ptr runtime_t::impl_t::display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { // Please ensure that KMS followed by CUDA remains at the top so that we can // drop DRM worker privileges once neither backend requires it. #ifdef SUNSHINE_BUILD_DRM if (sources[source::KMS]) { BOOST_LOG(info) << "Screencasting with KMS"sv; - return kms_display(hwdevice_type, display_name, config); + return kms_display(hwdevice_type, display_name, config, *kms_state, window_system, hevc_mode); } #endif @@ -1390,13 +1465,13 @@ namespace platf { #ifdef SUNSHINE_BUILD_X11 if (sources[source::X11]) { BOOST_LOG(info) << "Screencasting with X11"sv; - return x11_display(hwdevice_type, display_name, config); + return x11_display(hwdevice_type, display_name, config, scheduler); } #endif #ifdef SUNSHINE_BUILD_PORTAL if (sources[source::PORTAL]) { BOOST_LOG(info) << "Screencasting with XDG portal"sv; - return portal_display(hwdevice_type, display_name, config); + return portal_display(hwdevice_type, display_name, config, mail); } #endif #ifdef SUNSHINE_BUILD_KWIN @@ -1412,7 +1487,11 @@ namespace platf { /** * @brief Initialize the Linux high-precision timer file descriptor. */ - std::unique_ptr init() { + bool runtime_t::impl_t::initialize() { + if (initialized) { + return true; + } + sources.reset(); // enable low latency mode for AMD // https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/30039 lizardbyte::common::set_env("AMD_DEBUG", "lowlatencyenc"); @@ -1496,37 +1575,16 @@ namespace platf { if (sources.none()) { BOOST_LOG(error) << "Unable to initialize capture method"sv; - return nullptr; + return false; } if (!gladLoaderLoadEGL(NULL)) { BOOST_LOG(error) << "Failed to load EGL library symbols"sv; - return nullptr; + return false; } -#ifdef SUNSHINE_BUILD_PORTAL - class deinit_t: public platf::deinit_t { - public: - /** - * @brief Handle xdg_worker thread cleanup in destructor. - */ - ~deinit_t() override { - try { - if (portal::xdg_worker.joinable()) { - // Make sure the worker's response loop sees shutdown before we block on join(). - if (mail::man) { - mail::man->event(mail::shutdown)->raise(true); - } - portal::xdg_worker.join(); - } - } catch (const std::exception &err) { - BOOST_LOG(error) << "[portalgrab] Exception while joining xdg_worker: "sv << err.what(); - } - } - }; -#endif - - return std::make_unique(); + initialized = true; + return true; } /** @@ -1675,3 +1733,36 @@ namespace platf { #endif } } // namespace platf + +namespace platf { + runtime_t::runtime_t(safe::mail_t mail, thread_pool_util::ThreadPool &scheduler, lifetime::controller_t &lifetime, display_device::manager_t &): + impl(std::make_shared(std::move(mail), scheduler, lifetime)) {} + + runtime_t::~runtime_t() = default; + + bool runtime_t::initialize() { + return impl->initialize(); + } + + std::vector runtime_t::display_names(mem_type_e type) { + return impl->display_names(type); + } + + std::shared_ptr runtime_t::display(mem_type_e type, const std::string &name, const video::config_t &config) { + return impl->display(type, name, config); + } + + bool runtime_t::needs_encoder_reenumeration() { + return impl->needs_encoder_reenumeration(); + } + + void runtime_t::set_capture_requirements(int mode) { + impl->hevc_mode = mode; + } + + void runtime_t::streaming_will_start() {} + + void runtime_t::streaming_will_stop() {} + + void runtime_t::enable_mouse_keys() {} +} // namespace platf diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index 5d88fbb04..edcc6b8df 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -37,8 +38,6 @@ enum class window_system_e { WAYLAND, ///< Wayland }; -extern window_system_e window_system; ///< Window system. - namespace dyn { /** * @brief Generic GLX procedure pointer returned by the loader. @@ -89,8 +88,6 @@ namespace portal { */ bool is_portal_service_reachable(); - inline std::jthread xdg_worker; ///< XDG worker thread to negotiate restore token. - inline std::once_flag xdg_worker_flag; ///< Flag to ensure xdg_worker spawns only once. } // namespace portal #endif @@ -150,6 +147,15 @@ namespace platf { #if defined(__linux__) && defined(SUNSHINE_BUILD_DRM) namespace kms { + /** + * @brief Runtime-owned KMS discovery cache, snapshotted by capture resources. + */ + struct capture_state_t; + /** + * @brief Create an empty KMS discovery owner. + * @return Independent discovery state. + */ + std::shared_ptr make_capture_state(); /** * @brief Force-construct the DRM privileged worker thread while the calling * thread still holds CAP_SYS_ADMIN in CAP_PERMITTED. diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index b530ae6d4..b74a6135d 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -300,6 +300,14 @@ namespace portal { */ class dbus_t { public: + /** + * @brief Retain the host shutdown mailbox. + * @param mail Host mailbox. + */ + explicit dbus_t(safe::mail_t mail): + mail(std::move(mail)) {} + + safe::mail_t mail; ///< Shutdown mailbox for response loops. guint dbus_timeout = 10; ///< Timeout in seconds for DBus calls. dbus_t &operator=(dbus_t &&) = delete; // Do not allow to copying @@ -944,7 +952,7 @@ namespace portal { * @param timeout_seconds Timeout in seconds before quitting loop. * @return Variant containing the requested data. */ - static GVariant *dbus_response_wait(dbus_response_t *response, guint timeout_seconds = 0) { + GVariant *dbus_response_wait(dbus_response_t *response, guint timeout_seconds = 0) { GSource *timeout_source = nullptr; if (timeout_seconds > 0) { @@ -962,7 +970,7 @@ namespace portal { } constexpr guint shutdown_poll_interval_ms = 1000; - auto shutdown_event = mail::man ? mail::man->event(mail::shutdown) : nullptr; + auto shutdown_event = mail ? mail->event(mail::shutdown) : nullptr; loop_context_t ctx {response->loop, shutdown_event}; GSource *shutdown_source = g_timeout_source_new(shutdown_poll_interval_ms); @@ -1002,6 +1010,13 @@ namespace portal { */ class portal_t: public pipewire::pipewire_display_t { public: + /** + * @brief Bind portal response loops to their host. + * @param mail Host mailbox. + */ + explicit portal_t(safe::mail_t mail): + dbus(std::move(mail)) {} + int configure_stream(const std::string &display_name, int &out_pipewire_fd, uint32_t &out_pipewire_node, uint64_t &out_pipewire_object_serial [[maybe_unused]]) override { // Connect DBus portal session if (dbus.init() < 0) { @@ -1094,14 +1109,14 @@ namespace platf { * @param config Configuration values to apply. * @return Display backend backed by xdg-desktop-portal and PipeWire, or nullptr. */ - std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { + std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, safe::mail_t mail) { using enum platf::mem_type_e; if (!pipewire::pipewire_display_t::init_pipewire_and_check_hwdevice_type(hwdevice_type)) { BOOST_LOG(error) << "[portalgrab] Could not initialize pipewire-based display with the given hw device type."sv; return nullptr; } - auto portal = std::make_shared(); + auto portal = std::make_shared(std::move(mail)); if (portal->init(hwdevice_type, display_name, config)) { return nullptr; } @@ -1115,9 +1130,9 @@ namespace platf { * @param allow_start_timeout True if "Start" DBus call is allowed to time out. * @return Portal display names, or an empty list when portal discovery fails. */ - std::vector portal_display_names(bool allow_start_timeout) { + std::vector portal_display_names(bool allow_start_timeout, safe::mail_t mail) { std::vector display_names; - auto dbus = std::make_shared(); + auto dbus = std::make_shared(std::move(mail)); if (dbus->init() < 0) { BOOST_LOG(warning) << "[portalgrab] Failed to connect to dbus. Cannot enumerate displays, returning empty list."; diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index e2e0de21d..3b5d65528 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -664,7 +664,7 @@ namespace va { } AVVAAPIDeviceContext; static void __log(void *level, const char *msg) { - BOOST_LOG(*(boost::log::sources::severity_logger *) level) << msg; + BOOST_LOG(*(logging::logger_t::logger_type *) level) << msg; } static void vaapi_hwdevice_ctx_free(AVHWDeviceContext *ctx) { @@ -699,8 +699,8 @@ namespace va { va->va_display = display.get(); - vaSetErrorCallback(display.get(), __log, &error); - vaSetErrorCallback(display.get(), __log, &info); + vaSetErrorCallback(display.get(), __log, &error.get()); + vaSetErrorCallback(display.get(), __log, &info.get()); int major; int minor; @@ -757,7 +757,7 @@ namespace va { /** * @brief Validate that the configured VAAPI device can be used. */ - bool validate(int fd) { + bool validate(int fd, int hevc_mode) { va::display_t display {vaGetDisplayDRM(fd)}; if (!display) { std::array string; @@ -782,11 +782,11 @@ namespace va { return false; } - if (video::active_hevc_mode > 1 && !query(display.get(), VAProfileHEVCMain)) { + if (hevc_mode > 1 && !query(display.get(), VAProfileHEVCMain)) { return false; } - if (video::active_hevc_mode > 2 && !query(display.get(), VAProfileHEVCMain10)) { + if (hevc_mode > 2 && !query(display.get(), VAProfileHEVCMain10)) { return false; } diff --git a/src/platform/linux/vaapi.h b/src/platform/linux/vaapi.h index c56cf2868..5fafe9869 100644 --- a/src/platform/linux/vaapi.h +++ b/src/platform/linux/vaapi.h @@ -55,7 +55,8 @@ namespace va { * @brief Validate that the configured VAAPI device can be used. * * @param fd Native file descriptor to wrap or inspect. + * @param hevc_mode Required HEVC capability; automatic mode permits H.264-only devices. * @return True when the VAAPI device is usable for capture or encode. */ - bool validate(int fd); + bool validate(int fd, int hevc_mode); } // namespace va diff --git a/src/platform/linux/wlgrab.cpp b/src/platform/linux/wlgrab.cpp index c5cd887c7..26aa14b8f 100644 --- a/src/platform/linux/wlgrab.cpp +++ b/src/platform/linux/wlgrab.cpp @@ -6,6 +6,7 @@ #include // local includes +#include "capture_geometry.h" #include "cuda.h" #include "src/logging.h" #include "src/platform/common.h" @@ -17,8 +18,6 @@ using namespace std::literals; namespace wl { - static int env_width; - static int env_height; bool use_vram_capture(platf::mem_type_e hwdevice_type) { if (hwdevice_type == platf::mem_type_e::vaapi) { @@ -192,22 +191,16 @@ namespace wl { width = monitor->viewport.width; height = monitor->viewport.height; - this->env_width = ::wl::env_width; - this->env_height = ::wl::env_height; - this->logical_width = monitor->viewport.logical_width; this->logical_height = monitor->viewport.logical_height; - - int desktop_logical_width = 0; - int desktop_logical_height = 0; - for (auto &monitor_entry : interface.monitors) { - auto output_monitor = monitor_entry.get(); - desktop_logical_width = std::max(desktop_logical_width, output_monitor->viewport.offset_x + output_monitor->viewport.logical_width); - desktop_logical_height = std::max(desktop_logical_height, output_monitor->viewport.offset_y + output_monitor->viewport.logical_height); + platf::capture_geometry_t desktop; + for (auto &output : interface.monitors) { + desktop.include(output->viewport); } - - this->env_logical_width = desktop_logical_width; - this->env_logical_height = desktop_logical_height; + this->env_width = desktop.width; + this->env_height = desktop.height; + this->env_logical_width = desktop.logical_width; + this->env_logical_height = desktop.logical_height; BOOST_LOG(info) << "[wlgrab] Selected monitor ["sv << monitor->description << "] for streaming"sv; BOOST_LOG(debug) << "[wlgrab] Offset: "sv << offset_x << 'x' << offset_y; @@ -678,9 +671,6 @@ namespace platf { return {}; } - wl::env_width = 0; - wl::env_height = 0; - for (auto &monitor : interface.monitors) { monitor->listen(interface.output_manager); } @@ -692,9 +682,6 @@ namespace platf { for (int x = 0; x < interface.monitors.size(); ++x) { auto monitor = interface.monitors[x].get(); - wl::env_width = std::max(wl::env_width, monitor->viewport.offset_x + monitor->viewport.width); - wl::env_height = std::max(wl::env_height, monitor->viewport.offset_y + monitor->viewport.height); - BOOST_LOG(info) << "[wlgrab] Monitor " << x << " is "sv << monitor->name << ": "sv << monitor->description; display_names.emplace_back(monitor->name.empty() ? std::to_string(x) : monitor->name); diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 6ffbfa252..7aa0c57de 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -24,14 +24,16 @@ #include "graphics.h" #include "misc.h" #include "src/config.h" -#include "src/globals.h" #include "src/logging.h" #include "src/platform/common.h" -#include "src/task_pool.h" +#include "src/scheduler.h" +#include "src/thread_pool.h" #include "src/video.h" #include "vaapi.h" #include "x11grab.h" +#include + using namespace std::literals; namespace platf { @@ -683,6 +685,7 @@ namespace platf { */ struct shm_attr_t: public x11_attr_t { const std::shared_ptr shm_api; ///< API retained until SHM resources are released. + thread_pool_util::ThreadPool &scheduler; ///< Host scheduler retained for delayed refresh. x11::xdisplay_t shm_xdisplay; ///< X11 display held separately to prevent races with x11_attr_t::xdisplay. xcb_connect_t xcb; ///< XCB connection used by the shared-memory capture path. xcb_screen_t *display; ///< XCB screen containing the captured root window. @@ -700,7 +703,7 @@ namespace platf { void delayed_refresh() { refresh(); - refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; + refresh_task_id = scheduler.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; } /** @@ -709,15 +712,16 @@ namespace platf { * @param mem_type Requested memory path for the capture backend. * @param shm_api Validated API retained for the lifetime of shared-memory capture. */ - shm_attr_t(mem_type_e mem_type, std::shared_ptr shm_api): + shm_attr_t(mem_type_e mem_type, std::shared_ptr shm_api, thread_pool_util::ThreadPool &scheduler): + scheduler(scheduler), x11_attr_t(mem_type), shm_api {std::move(shm_api)}, shm_xdisplay {x11::OpenDisplay(nullptr)} { - refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; + refresh_task_id = scheduler.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; } ~shm_attr_t() override { - while (!task_pool.cancel(refresh_task_id)); + while (!scheduler.cancel(refresh_task_id)); } capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) override { @@ -883,7 +887,7 @@ namespace platf { * @param config Configuration values to apply. * @return X11 display backend, or nullptr when initialization fails. */ - std::shared_ptr x11_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) { + std::shared_ptr x11_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config, thread_pool_util::ThreadPool &scheduler) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::vaapi && hwdevice_type != platf::mem_type_e::cuda) { BOOST_LOG(error) << "Could not initialize x11 display with the given hw device type"sv; return nullptr; @@ -897,7 +901,7 @@ namespace platf { } // Attempt to use shared memory X11 to avoid copying the frame - auto shm_disp = std::make_shared(hwdevice_type, std::move(shm_api)); + auto shm_disp = std::make_shared(hwdevice_type, std::move(shm_api), scheduler); auto status = shm_disp->init(display_name, config); if (status > 0) { @@ -983,9 +987,10 @@ namespace platf { */ int load_x11() { // This will be called once only - static int x11_status = - window_system == window_system_e::NONE || - x11::init() || x11::rr::init() || x11::fix::init(); + static const int x11_status = []() { + std::string display; + return !lizardbyte::common::get_env("DISPLAY", display) || x11::init() || x11::rr::init() || x11::fix::init(); + }(); return x11_status; } diff --git a/src/platform/macos/display.mm b/src/platform/macos/display.mm index 903a139fe..18ad67445 100644 --- a/src/platform/macos/display.mm +++ b/src/platform/macos/display.mm @@ -240,7 +240,7 @@ namespace platf { } }; - std::shared_ptr display(platf::mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) { + std::shared_ptr mac_display(platf::mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config, display_device::manager_t &displays) { if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::videotoolbox) { BOOST_LOG(error) << "Could not initialize display with the given hw device type."sv; return nullptr; @@ -273,7 +273,7 @@ namespace platf { // Print all displays available with their names and ids BOOST_LOG(debug) << "Detecting displays"sv; - for (const auto &device : display_device::enumerate_devices()) { + for (const auto &device : displays.enumerate_devices()) { if (device.m_display_name.empty()) { continue; } @@ -321,13 +321,13 @@ namespace platf { return display; } - std::vector display_names(mem_type_e hwdevice_type) { + std::vector mac_display_names(mem_type_e hwdevice_type, display_device::manager_t &displays) { std::vector display_names; if (hwdevice_type != platf::mem_type_e::system && hwdevice_type != platf::mem_type_e::videotoolbox) { return display_names; } - const auto devices {display_device::enumerate_devices()}; + const auto devices {displays.enumerate_devices()}; display_names.reserve(devices.size()); for (const auto &device : devices) { if (!device.m_display_name.empty()) { diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 703ace5e2..8640b9881 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -551,7 +551,7 @@ namespace platf { * This keeps the shell tracking the original PID as its foreground job, * preserving Ctrl+C and terminal log output. */ - void restart_on_exit() { + void restart_on_exit(char **argv) { char executable[2048]; uint32_t size = sizeof(executable); if (_NSGetExecutablePath(executable, &size) < 0) { @@ -581,7 +581,7 @@ namespace platf { setpgid(0, 0); // Replace this child with the new Sunshine instance - execv(executable, lifetime::get_argv()); + execv(executable, argv); // If execv fails, exit the child immediately without running atexit handlers _exit(1); @@ -609,10 +609,12 @@ namespace platf { _exit(WIFEXITED(status) ? WEXITSTATUS(status) : 1); } - void restart() { + void restart(lifetime::controller_t &lifetime) { // Gracefully clean up and restart ourselves instead of exiting - atexit(restart_on_exit); - lifetime::exit_sunshine(0, true); + lifetime.restart_on_exit([argv = lifetime.get_argv()]() { + restart_on_exit(argv); + }); + lifetime.exit_sunshine(0, true); } bool request_process_group_exit(std::uintptr_t native_handle) { @@ -942,3 +944,65 @@ namespace dyn { return err; } } // namespace dyn + +namespace platf { + /** + * @brief Own the macOS platform initialization and explicit display manager. + */ + struct runtime_t::impl_t { + display_device::manager_t &displays; ///< Display manager for discovery. + std::unique_ptr initialization; ///< Native initialization lifetime. + + /** + * @brief Bind display discovery. + * @param displays Display manager. + */ + explicit impl_t(display_device::manager_t &displays): + displays(displays) {} + }; + + std::shared_ptr mac_display(mem_type_e type, const std::string &name, const video::config_t &config, display_device::manager_t &displays); + std::vector mac_display_names(mem_type_e type, display_device::manager_t &displays); + + runtime_t::runtime_t(safe::mail_t, thread_pool_util::ThreadPool &, lifetime::controller_t &, display_device::manager_t &displays): + impl(std::make_shared(displays)) {} + + runtime_t::~runtime_t() = default; + + bool runtime_t::initialize() { + if (!impl->initialization) { + impl->initialization = platf::init(); + } + return static_cast(impl->initialization); + } + + std::vector runtime_t::display_names(mem_type_e type) { + return mac_display_names(type, impl->displays); + } + + std::shared_ptr runtime_t::display(mem_type_e type, const std::string &name, const video::config_t &config) { + return mac_display(type, name, config, impl->displays); + } + + bool runtime_t::needs_encoder_reenumeration() { + return platf::needs_encoder_reenumeration(); + } + + void runtime_t::set_capture_requirements(int) {} + + void runtime_t::streaming_will_start() { + platf::streaming_will_start(); + } + + void runtime_t::streaming_will_stop() { + platf::streaming_will_stop(); + } + + void runtime_t::enable_mouse_keys() { + platf::enable_mouse_keys(); + } + + std::unique_ptr runtime_t::enable_socket_qos(uintptr_t socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e type, bool dscp_tagging) { + return platf::enable_socket_qos(socket, address, port, type, dscp_tagging); + } +} // namespace platf diff --git a/src/platform/virtualhid_input.cpp b/src/platform/virtualhid_input.cpp index 30ab2c4f9..419e2efed 100644 --- a/src/platform/virtualhid_input.cpp +++ b/src/platform/virtualhid_input.cpp @@ -1125,7 +1125,8 @@ namespace platf { } // namespace - input_t input() { + input_t input(thread_pool_util::ThreadPool &scheduler) { + (void) scheduler; return {new input_raw_t {}}; } diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 2a2176d5e..df65b5b1a 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -29,10 +29,10 @@ // local includes #include "misc.h" #include "src/config.h" -#include "src/globals.h" #include "src/logging.h" #include "src/platform/common.h" #include "src/platform/virtualhid_input.h" +#include "src/thread_pool.h" namespace platf { using namespace std::literals; @@ -247,6 +247,15 @@ namespace platf { */ class vigem_t { public: + /** + * @brief Bind deferred gamepad work to the application scheduler. + * @param scheduler Application scheduler. + */ + explicit vigem_t(thread_pool_util::ThreadPool &scheduler): + scheduler(scheduler) {} + + thread_pool_util::ThreadPool &scheduler; ///< Scheduler that outlives this input context. + /** * @brief Connect to ViGEm and prepare virtual gamepad slots. * @@ -377,7 +386,7 @@ namespace platf { auto &gamepad = gamepads[nr]; if (gamepad.repeat_task) { - task_pool.cancel(gamepad.repeat_task); + scheduler.cancel(gamepad.repeat_task); gamepad.repeat_task = nullptr; } @@ -495,7 +504,7 @@ namespace platf { << "largeMotor: "sv << (int) largeMotor << std::endl << "smallMotor: "sv << (int) smallMotor; - task_pool.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); + static_cast(userdata)->scheduler.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); } void CALLBACK ds4_notify( @@ -513,14 +522,22 @@ namespace platf { << util::hex(led_color.Green).to_string_view() << ' ' << util::hex(led_color.Blue).to_string_view() << std::endl; - task_pool.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); - task_pool.push(&vigem_t::set_rgb_led, (vigem_t *) userdata, target, led_color.Red, led_color.Green, led_color.Blue); + static_cast(userdata)->scheduler.push(&vigem_t::rumble, (vigem_t *) userdata, target, largeMotor, smallMotor); + static_cast(userdata)->scheduler.push(&vigem_t::set_rgb_led, (vigem_t *) userdata, target, led_color.Red, led_color.Green, led_color.Blue); } /** * @brief Global virtual input device handles shared by clients. */ struct input_raw_t { + /** + * @brief Bind input fallback resources to their scheduler. + * @param scheduler Application scheduler. + */ + explicit input_raw_t(thread_pool_util::ThreadPool &scheduler): + scheduler(scheduler) {} + + thread_pool_util::ThreadPool &scheduler; ///< Application scheduler. virtualhid::input_context_t virtualhid; ///< libvirtualhid input context. std::unique_ptr vigem; ///< ViGEm fallback context. }; @@ -559,8 +576,8 @@ namespace platf { }; } - input_t input() { - input_t result {new input_raw_t {}}; + input_t input(thread_pool_util::ThreadPool &scheduler) { + input_t result {new input_raw_t {scheduler}}; if (auto &raw = *result; config::input.controller && !should_use_virtualhid_gamepads(raw) && virtualhid::should_try_vigembus_fallback(config::input.gamepad, false, config::input.gamepad_driver)) { if (config::input.gamepad_driver == config::GAMEPAD_DRIVER_VIGEMBUS) { @@ -568,7 +585,7 @@ namespace platf { } else if (raw.virtualhid.runtime && raw.virtualhid.runtime->capabilities().supports_gamepad) { BOOST_LOG(info) << "Virtual HID Driver license is not valid; using the ViGEmBus gamepad fallback"sv; } - auto vigem = std::make_unique(); + auto vigem = std::make_unique(scheduler); if (!vigem->init()) { raw.vigem = std::move(vigem); } @@ -588,7 +605,7 @@ namespace platf { return true; } - auto vigem = std::make_unique(); + auto vigem = std::make_unique(raw->scheduler); if (vigem->init()) { return false; } @@ -976,7 +993,7 @@ namespace platf { // Cancel any pending updates. We will requeue one here when we're finished. if (gamepad.repeat_task) { - task_pool.cancel(gamepad.repeat_task); + vigem->scheduler.cancel(gamepad.repeat_task); gamepad.repeat_task = nullptr; } @@ -996,7 +1013,7 @@ namespace platf { // Repeat at least every 100ms to keep the 16-bit timestamp field from overflowing gamepad.last_report_ts = now; - gamepad.repeat_task = task_pool.pushDelayed(ds4_update_ts_and_send, 100ms, vigem, nr).task_id; + gamepad.repeat_task = vigem->scheduler.pushDelayed(ds4_update_ts_and_send, 100ms, vigem, nr).task_id; } } diff --git a/src/video.cpp b/src/video.cpp index c90847ecb..2eb1ad1e3 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -50,9 +50,10 @@ namespace video { /** * @brief Check if we can allow probing for the encoders. * @return True if there should be no issues with the probing, false if we should prevent it. + * @param displays Display configuration manager. */ - bool allow_encoder_probing() { - const auto devices {display_device::enumerate_devices()}; + bool allow_encoder_probing(display_device::manager_t &displays) { + const auto devices {displays.enumerate_devices()}; // If there are no devices, then either the API is not working correctly or OS does not support the lib. // Either way we should not block the probing in this case as we can't tell what's wrong. @@ -684,7 +685,7 @@ namespace video { * @param ctx Native context object used by the operation or callback. * @return 0 when the capture thread is started. */ - int start_capture_sync(capture_thread_sync_ctx_t &ctx); + int start_capture_sync(service_t::impl_t &host, capture_thread_sync_ctx_t &ctx); /** * @brief Stop capture sync processing. * @@ -697,7 +698,7 @@ namespace video { * @param ctx Native context object used by the operation or callback. * @return 0 when the capture thread is started; nonzero on setup failure. */ - int start_capture_async(capture_thread_async_ctx_t &ctx); + int start_capture_async(service_t::impl_t &host, capture_thread_async_ctx_t &ctx); /** * @brief Stop capture async processing. * @@ -705,15 +706,64 @@ namespace video { */ void end_capture_async(capture_thread_async_ctx_t &ctx); - // Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread - auto capture_thread_async = safe::make_shared(start_capture_async, end_capture_async); ///< Capture thread async. - auto capture_thread_sync = safe::make_shared(start_capture_sync, end_capture_sync); ///< Capture thread sync. + /** + * @brief Copy immutable encoder descriptors for one service's probe state. + * @return Independent encoder descriptors with shared immutable format metadata. + */ + std::vector make_encoders(); + + /** + * @brief Capture coordinators and encoder state owned by one video service. + */ + struct service_t::impl_t { + /** + * @brief Bind capture dependencies and construct inactive coordinators. + * @param mail Host mailbox for encoded packets and display selection. + * @param cursor Host cursor visibility preference. + * @param displays Display configuration manager. + */ + impl_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): + mail {std::move(mail)}, + cursor {cursor}, + displays {displays}, + platform {platform}, + encoders {make_encoders()}, + capture_thread_async { + [this](capture_thread_async_ctx_t &ctx) { + return start_capture_async(*this, ctx); + }, + [](capture_thread_async_ctx_t &ctx) { + end_capture_async(ctx); + } + }, + capture_thread_sync { + [this](capture_thread_sync_ctx_t &ctx) { + return start_capture_sync(*this, ctx); + }, + [](capture_thread_sync_ctx_t &ctx) { + end_capture_sync(ctx); + } + } { + } + + safe::mail_t mail; ///< Host packet and lifecycle mailbox. + bool &cursor; ///< Host cursor visibility preference. + display_device::manager_t &displays; ///< Display configuration dependency. + platf::runtime_t &platform; ///< Host capture backend owner. + mutable std::mutex probe_mutex; ///< Protects complete capability snapshots and probes. + capabilities_t probed; ///< Latest complete encoder probe result. + std::vector encoders; ///< Encoder descriptors and capability flags owned by this host. + encoder_t *chosen_encoder = nullptr; ///< Encoder selected for the host. + safe::shared_t capture_thread_async; ///< Shared asynchronous capture coordinator. + safe::shared_t capture_thread_sync; ///< Shared synchronous capture coordinator. + std::jthread sync_thread; ///< Synchronous capture worker joined before service destruction. + }; #ifdef _WIN32 /** * @brief NVENC. */ - encoder_t nvenc { + const encoder_t nvenc { "nvenc"sv, std::make_unique( platf::mem_type_e::dxgi, @@ -755,7 +805,7 @@ namespace video { PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT | ASYNC_TEARDOWN // flags }; #elif !defined(__APPLE__) - encoder_t nvenc { + const encoder_t nvenc { "nvenc"sv, std::make_unique( #ifdef _WIN32 @@ -862,7 +912,7 @@ namespace video { /** * @brief Quicksync. */ - encoder_t quicksync { + const encoder_t quicksync { "quicksync"sv, std::make_unique( AV_HWDEVICE_TYPE_D3D11VA, @@ -976,7 +1026,7 @@ namespace video { /** * @brief Amdvce. */ - encoder_t amdvce { + const encoder_t amdvce { "amdvce"sv, std::make_unique( AV_HWDEVICE_TYPE_D3D11VA, @@ -1091,7 +1141,7 @@ namespace video { /** * @brief Mediafoundation. */ - encoder_t mediafoundation { + const encoder_t mediafoundation { "mediafoundation"sv, std::make_unique( AV_HWDEVICE_TYPE_D3D11VA, @@ -1155,7 +1205,7 @@ namespace video { /** * @brief Software. */ - encoder_t software { + const encoder_t software { "software"sv, std::make_unique( AV_HWDEVICE_TYPE_NONE, @@ -1232,7 +1282,7 @@ namespace video { /** * @brief VA-API. */ - encoder_t vaapi { + const encoder_t vaapi { "vaapi"sv, std::make_unique( AV_HWDEVICE_TYPE_VAAPI, @@ -1296,7 +1346,7 @@ namespace video { }; #ifdef SUNSHINE_BUILD_VULKAN - encoder_t vulkan { + const encoder_t vulkan { "vulkan"sv, std::make_unique( AV_HWDEVICE_TYPE_VULKAN, @@ -1374,7 +1424,7 @@ namespace video { /** * @brief Videotoolbox. */ - encoder_t videotoolbox { + const encoder_t videotoolbox { "videotoolbox"sv, std::make_unique( AV_HWDEVICE_TYPE_VIDEOTOOLBOX, @@ -1448,7 +1498,7 @@ namespace video { }; #endif - static const std::vector encoders { + static const std::vector encoder_prototypes { #ifndef __APPLE__ &nvenc, #endif @@ -1469,11 +1519,14 @@ namespace video { &software }; - static encoder_t *chosen_encoder; - int active_hevc_mode; ///< HEVC mode selected by the most recent encoder probe. - int active_av1_mode; ///< AV1 mode selected by the most recent encoder probe. - bool last_encoder_probe_supported_ref_frames_invalidation = false; ///< Whether the last probe found reference-frame invalidation support. - std::array last_encoder_probe_supported_yuv444_for_codec = {}; ///< YUV444 support discovered for each probed codec. + std::vector make_encoders() { + std::vector result; + result.reserve(encoder_prototypes.size()); + for (const auto *encoder : encoder_prototypes) { + result.push_back(*encoder); + } + return result; + } /** * @brief Recreate a display capture object after a capture failure. @@ -1482,12 +1535,13 @@ namespace video { * @param type Protocol, message, or resource type selector. * @param display_name Display name. * @param config Configuration values to apply. + * @param host Host input or video service and its capture dependencies. */ - void reset_display(std::shared_ptr &disp, const platf::mem_type_e &type, const std::string &display_name, const config_t &config) { + void reset_display(service_t::impl_t &host, std::shared_ptr &disp, const platf::mem_type_e &type, const std::string &display_name, const config_t &config) { // We try this twice, in case we still get an error on reinitialization for (int x = 0; x < 2; ++x) { disp.reset(); - disp = platf::display(type, display_name, config); + disp = host.platform.display(type, display_name, config); if (disp) { break; } @@ -1503,10 +1557,11 @@ namespace video { * @param dev_type The encoder device type used for display lookup. * @param display_names The list of display names to repopulate. * @param current_display_index The current display index or -1 if not yet known. + * @param host Host input or video service and its capture dependencies. */ - void refresh_displays(platf::mem_type_e dev_type, std::vector &display_names, int ¤t_display_index) { + void refresh_displays(service_t::impl_t &host, platf::mem_type_e dev_type, std::vector &display_names, int ¤t_display_index) { // It is possible that the output name may be empty even if it wasn't before (device disconnected) or vice-versa - const auto output_name {display_device::map_output_name(config::video.output_name)}; + const auto output_name {host.displays.map_output_name(config::video.output_name)}; std::string current_display_name; // If we have a current display index, let's start with that @@ -1516,7 +1571,7 @@ namespace video { // Refresh the display names auto old_display_names = std::move(display_names); - display_names = platf::display_names(dev_type); + display_names = host.platform.display_names(dev_type); // If we now have no displays, let's put the old display array back and fail if (display_names.empty() && !old_display_names.empty()) { @@ -1558,13 +1613,9 @@ namespace video { * @param display_wp Weak pointer holder for the active display. * @param reinit_event Signal raised while the display is being reinitialized. * @param encoder Selected encoder. + * @param host Host input or video service and its capture dependencies. */ - void captureThread( - std::shared_ptr> capture_ctx_queue, - sync_util::sync_t> &display_wp, - safe::signal_t &reinit_event, - const encoder_t &encoder - ) { + void captureThread(service_t::impl_t &host, std::shared_ptr> capture_ctx_queue, sync_util::sync_t> &display_wp, safe::signal_t &reinit_event, const encoder_t &encoder) { std::vector capture_ctxs; auto fg = util::fail_guard([&]() { @@ -1579,7 +1630,7 @@ namespace video { } }); - auto switch_display_event = mail::man->event(mail::switch_display); + auto switch_display_event = host.mail->event(mail::switch_display); // Wait for the initial capture context or a request to stop the queue auto initial_capture_ctx = capture_ctx_queue->pop(); @@ -1592,8 +1643,8 @@ namespace video { // get the most up-to-date list available monitors std::vector display_names; int display_p = -1; - refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); - auto disp = platf::display(encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); + refresh_displays(host, encoder.platform_formats->dev_type, display_names, display_p); + auto disp = host.platform.display(encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); if (!disp) { return; } @@ -1734,7 +1785,7 @@ namespace video { return true; }; - auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor); + auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &host.cursor); if (artificial_reinit && status != platf::capture_e::error) { status = platf::capture_e::reinit; @@ -1781,7 +1832,7 @@ namespace video { disp.reset(); // Refresh display names since a display removal might have caused the reinitialization - refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); + refresh_displays(host, encoder.platform_formats->dev_type, display_names, display_p); // Process any pending display switch with the new list of displays if (switch_display_event->peek()) { @@ -1789,7 +1840,7 @@ namespace video { } // reset_display() will sleep between retries - reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); + reset_display(host, disp, encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config); if (disp) { break; } @@ -2398,18 +2449,18 @@ namespace video { * @param reinit_event Signal raised while the encoder/display is reinitializing. * @param encoder Selected encoder. * @param channel_data Opaque channel data passed to packets. + * @param host Host input or video service and its capture dependencies. */ - void encode_run( - int &frame_nr, // Store progress of the frame number - safe::mail_t mail, - img_event_t images, - config_t config, - std::shared_ptr disp, - std::unique_ptr encode_device, - safe::signal_t &reinit_event, - const encoder_t &encoder, - void *channel_data - ) { + void encode_run(service_t::impl_t &host, + int &frame_nr, // Store progress of the frame number + safe::mail_t mail, + img_event_t images, + config_t config, + std::shared_ptr disp, + std::unique_ptr encode_device, + safe::signal_t &reinit_event, + const encoder_t &encoder, + void *channel_data) { auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device)); if (!session) { return; @@ -2438,7 +2489,7 @@ namespace video { BOOST_LOG(info) << "Minimum FPS target set to ~"sv << minimum_fps_target << "fps ("sv << max_frametime.count() << "ms)"sv; auto shutdown_event = mail->event(mail::shutdown); - auto packets = mail::man->queue(mail::video_packets); + auto packets = host.mail->queue(mail::video_packets); auto idr_events = mail->event(mail::idr); auto invalidate_ref_frames_events = mail->event>(mail::invalidate_ref_frames); @@ -2509,7 +2560,7 @@ namespace video { // While streaming check to see if the mouse is present and enable Mouse Keys to force the cursor to appear // This is useful for KVM switch scenarios where mouse may disappear during streaming - platf::enable_mouse_keys(); + host.platform.enable_mouse_keys(); } } @@ -2679,18 +2730,14 @@ namespace video { * @param display_names Cached display names. * @param display_p Active display index. * @return Encoder loop result. + * @param host Host input or video service and its capture dependencies. */ - encode_e encode_run_sync( - std::vector> &synced_session_ctxs, - encode_session_ctx_queue_t &encode_session_ctx_queue, - std::vector &display_names, - int &display_p - ) { - const auto &encoder = *chosen_encoder; + encode_e encode_run_sync(service_t::impl_t &host, std::vector> &synced_session_ctxs, encode_session_ctx_queue_t &encode_session_ctx_queue, std::vector &display_names, int &display_p) { + const auto &encoder = *host.chosen_encoder; std::shared_ptr disp; - auto switch_display_event = mail::man->event(mail::switch_display); + auto switch_display_event = host.mail->event(mail::switch_display); if (synced_session_ctxs.empty()) { auto ctx = encode_session_ctx_queue.pop(); @@ -2703,7 +2750,7 @@ namespace video { while (encode_session_ctx_queue.running()) { // Refresh display names since a display removal might have caused the reinitialization - refresh_displays(encoder.platform_formats->dev_type, display_names, display_p); + refresh_displays(host, encoder.platform_formats->dev_type, display_names, display_p); // Process any pending display switch with the new list of displays if (switch_display_event->peek()) { @@ -2711,7 +2758,7 @@ namespace video { } // reset_display() will sleep between retries - reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config); + reset_display(host, disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config); if (disp) { break; } @@ -2817,7 +2864,7 @@ namespace video { return true; }; - auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor); + auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &host.cursor); switch (status) { case platf::capture_e::reinit: case platf::capture_e::error: @@ -2833,9 +2880,10 @@ namespace video { /** * @brief Run synchronous capture and encode work on the capture thread. + * @param host Host input or video service and its capture dependencies. */ - void captureThreadSync() { - auto ref = capture_thread_sync.ref(); + void captureThreadSync(service_t::impl_t &host) { + auto ref = host.capture_thread_sync.ref(); std::vector> synced_session_ctxs; @@ -2860,7 +2908,7 @@ namespace video { std::vector display_names; int display_p = -1; - while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {} + while (encode_run_sync(host, synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {} } /** @@ -2869,12 +2917,9 @@ namespace video { * @param mail Session mail bus. * @param config Video configuration. * @param channel_data Opaque channel data passed to packets. + * @param host Host input or video service and its capture dependencies. */ - void capture_async( - safe::mail_t mail, - config_t &config, - void *channel_data - ) { + void capture_async(service_t::impl_t &host, safe::mail_t mail, config_t &config, void *channel_data) { auto shutdown_event = mail->event(mail::shutdown); auto images = std::make_shared(); @@ -2883,7 +2928,7 @@ namespace video { shutdown_event->raise(true); }); - auto ref = capture_thread_async.ref(); + auto ref = host.capture_thread_async.ref(); if (!ref) { return; } @@ -2919,7 +2964,7 @@ namespace video { display = ref->display_wp->lock(); } - auto &encoder = *chosen_encoder; + auto &encoder = *host.chosen_encoder; auto encode_device = make_encode_device(*display, encoder, config); if (!encode_device) { @@ -2940,17 +2985,7 @@ namespace video { } hdr_event->raise(std::move(hdr_info)); - encode_run( - frame_nr, - mail, - images, - config, - display, - std::move(encode_device), - ref->reinit_event, - *ref->encoder_p, - channel_data - ); + encode_run(host, frame_nr, mail, images, config, display, std::move(encode_device), ref->reinit_event, *ref->encoder_p, channel_data); } } @@ -2960,26 +2995,23 @@ namespace video { * @param mail Session mail bus. * @param config Client-requested video configuration, normalized before capture begins. * @param channel_data Opaque channel data passed to packets. + * @param host Host input or video service and its capture dependencies. */ - void capture( - safe::mail_t mail, - config_t config, - void *channel_data - ) { - config = resolve_dynamic_range(*chosen_encoder, config); + void capture(service_t::impl_t &host, safe::mail_t mail, config_t config, void *channel_data) { + config = resolve_dynamic_range(*host.chosen_encoder, config); auto idr_events = mail->event(mail::idr); idr_events->raise(true); - if (chosen_encoder->flags & PARALLEL_ENCODING) { - capture_async(std::move(mail), config, channel_data); + if (host.chosen_encoder->flags & PARALLEL_ENCODING) { + capture_async(host, std::move(mail), config, channel_data); } else { safe::signal_t join_event; - auto ref = capture_thread_sync.ref(); + auto ref = host.capture_thread_sync.ref(); ref->encode_session_ctx_queue.raise(sync_session_ctx_t { &join_event, mail->event(mail::shutdown), - mail::man->queue(mail::video_packets), + host.mail->queue(mail::video_packets), std::move(idr_events), mail->event(mail::hdr), mail->event(mail::touch_port), @@ -3007,8 +3039,9 @@ namespace video { * @param encoder Encoder configuration or encoder instance. * @param config Configuration values to apply. * @return 0 when the selected encoder/device accepts the configuration; nonzero otherwise. + * @param host Host input or video service and its capture dependencies. */ - int validate_config(std::shared_ptr disp, const encoder_t &encoder, const config_t &config) { + int validate_config(service_t::impl_t &host, std::shared_ptr disp, const encoder_t &encoder, const config_t &config) { auto encode_device = make_encode_device(*disp, encoder, config); if (!encode_device) { return -1; @@ -3029,7 +3062,7 @@ namespace video { session->request_idr_frame(); - auto packets = mail::man->queue(mail::video_packets); + auto packets = host.mail->queue(mail::video_packets); while (!packets->peek()) { if (encode(1, *session, packets, nullptr, {})) { return -1; @@ -3062,9 +3095,10 @@ namespace video { /** * @brief Validate encoder before it is used. + * @param host Host input or video service and its capture dependencies. */ - bool validate_encoder(encoder_t &encoder, bool expect_failure) { - const auto output_name {display_device::map_output_name(config::video.output_name)}; + bool validate_encoder(service_t::impl_t &host, encoder_t &encoder, bool expect_failure) { + const auto output_name {host.displays.map_output_name(config::video.output_name)}; std::shared_ptr disp; BOOST_LOG(info) << "Trying encoder ["sv << encoder.name << ']'; @@ -3072,8 +3106,8 @@ namespace video { BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] failed"sv; }); - auto test_hevc = active_hevc_mode >= 2 || (active_hevc_mode == 0 && !(encoder.flags & H264_ONLY)); - auto test_av1 = active_av1_mode >= 2 || (active_av1_mode == 0 && !(encoder.flags & H264_ONLY)); + auto test_hevc = host.probed.active_hevc_mode >= 2 || (host.probed.active_hevc_mode == 0 && !(encoder.flags & H264_ONLY)); + auto test_av1 = host.probed.active_av1_mode >= 2 || (host.probed.active_av1_mode == 0 && !(encoder.flags & H264_ONLY)); encoder.h264.capabilities.set(); encoder.hevc.capabilities.set(); @@ -3084,7 +3118,7 @@ namespace video { config_t config_autoselect {1920, 1080, 60, 6000, 1000, 1, 0, 1, 0, 0, 0, 0}; // If the encoder isn't supported at all (not even H.264), bail early - reset_display(disp, encoder.platform_formats->dev_type, output_name, config_autoselect); + reset_display(host, disp, encoder.platform_formats->dev_type, output_name, config_autoselect); if (!disp) { return false; } @@ -3096,13 +3130,13 @@ namespace video { // If we're expecting failure, use the autoselect ref config first since that will always succeed // if the encoder is available. - auto max_ref_frames_h264 = expect_failure ? -1 : validate_config(disp, encoder, config_max_ref_frames); - auto autoselect_h264 = max_ref_frames_h264 >= 0 ? max_ref_frames_h264 : validate_config(disp, encoder, config_autoselect); + auto max_ref_frames_h264 = expect_failure ? -1 : validate_config(host, disp, encoder, config_max_ref_frames); + auto autoselect_h264 = max_ref_frames_h264 >= 0 ? max_ref_frames_h264 : validate_config(host, disp, encoder, config_autoselect); if (autoselect_h264 < 0) { return false; } else if (expect_failure) { // We expected failure, but actually succeeded. Do the max_ref_frames probe we skipped. - max_ref_frames_h264 = validate_config(disp, encoder, config_max_ref_frames); + max_ref_frames_h264 = validate_config(host, disp, encoder, config_max_ref_frames); } std::vector> packet_deficiencies { @@ -3121,13 +3155,13 @@ namespace video { config_autoselect.videoFormat = 1; if (disp->is_codec_supported(encoder.hevc.name, config_autoselect)) { - auto max_ref_frames_hevc = validate_config(disp, encoder, config_max_ref_frames); + auto max_ref_frames_hevc = validate_config(host, disp, encoder, config_max_ref_frames); // If H.264 succeeded with max ref frames specified, assume that we can count on // HEVC to also succeed with max ref frames specified if HEVC is supported. auto autoselect_hevc = (max_ref_frames_hevc >= 0 || max_ref_frames_h264 >= 0) ? max_ref_frames_hevc : - validate_config(disp, encoder, config_autoselect); + validate_config(host, disp, encoder, config_autoselect); for (auto [validate_flag, encoder_flag] : packet_deficiencies) { encoder.hevc[encoder_flag] = (max_ref_frames_hevc & validate_flag && autoselect_hevc & validate_flag); @@ -3149,13 +3183,13 @@ namespace video { config_autoselect.videoFormat = 2; if (disp->is_codec_supported(encoder.av1.name, config_autoselect)) { - auto max_ref_frames_av1 = validate_config(disp, encoder, config_max_ref_frames); + auto max_ref_frames_av1 = validate_config(host, disp, encoder, config_max_ref_frames); // If H.264 succeeded with max ref frames specified, assume that we can count on // AV1 to also succeed with max ref frames specified if AV1 is supported. auto autoselect_av1 = (max_ref_frames_av1 >= 0 || max_ref_frames_h264 >= 0) ? max_ref_frames_av1 : - validate_config(disp, encoder, config_autoselect); + validate_config(host, disp, encoder, config_autoselect); for (auto [validate_flag, encoder_flag] : packet_deficiencies) { encoder.av1[encoder_flag] = (max_ref_frames_av1 & validate_flag && autoselect_av1 & validate_flag); @@ -3177,7 +3211,7 @@ namespace video { auto test_yuv444 = [&](auto &flag_map, auto video_format) { const config_t config = {1920, 1080, 60, 6000, 1000, 1, 0, 1, video_format, 0, 1, 0}; - reset_display(disp, encoder.platform_formats->dev_type, output_name, config); + reset_display(host, disp, encoder.platform_formats->dev_type, output_name, config); if (!disp) { return; } @@ -3187,7 +3221,7 @@ namespace video { auto encoder_codec_name = encoder.codec_from_config(config).name; - if ((encoder.flags & YUV444_SUPPORT) && disp->is_codec_supported(encoder_codec_name, config) && validate_config(disp, encoder, config) >= 0) { + if ((encoder.flags & YUV444_SUPPORT) && disp->is_codec_supported(encoder_codec_name, config) && validate_config(host, disp, encoder, config) >= 0) { flag_map[encoder_t::YUV444] = true; } else { flag_map[encoder_t::YUV444] = false; @@ -3197,7 +3231,7 @@ namespace video { auto test_yuv420_hdr = [&](auto &flag_map, auto video_format) { const config_t config = {1920, 1080, 60, 6000, 1000, 1, 0, 3, video_format, 1, 0, 0}; - reset_display(disp, encoder.platform_formats->dev_type, output_name, config); + reset_display(host, disp, encoder.platform_formats->dev_type, output_name, config); if (!disp) { return; } @@ -3207,7 +3241,7 @@ namespace video { auto encoder_codec_name = encoder.codec_from_config(config).name; - if (disp->is_codec_supported(encoder_codec_name, config) && validate_config(disp, encoder, config) >= 0) { + if (disp->is_codec_supported(encoder_codec_name, config) && validate_config(host, disp, encoder, config) >= 0) { flag_map[encoder_t::DYNAMIC_RANGE] = true; } else { flag_map[encoder_t::DYNAMIC_RANGE] = false; @@ -3217,7 +3251,7 @@ namespace video { auto test_yuv444_hdr = [&](auto &flag_map, auto video_format) { const config_t config = {1920, 1080, 60, 6000, 1000, 1, 0, 3, video_format, 1, 1, 0}; - reset_display(disp, encoder.platform_formats->dev_type, output_name, config); + reset_display(host, disp, encoder.platform_formats->dev_type, output_name, config); if (!disp) { return; } @@ -3227,7 +3261,7 @@ namespace video { auto encoder_codec_name = encoder.codec_from_config(config).name; - if ((encoder.flags & YUV444_SUPPORT) && disp->is_codec_supported(encoder_codec_name, config) && validate_config(disp, encoder, config) >= 0) { + if ((encoder.flags & YUV444_SUPPORT) && disp->is_codec_supported(encoder_codec_name, config) && validate_config(host, disp, encoder, config) >= 0) { flag_map[encoder_t::DYNAMIC_RANGE_YUV444] = true; } else { flag_map[encoder_t::DYNAMIC_RANGE_YUV444] = false; @@ -3261,57 +3295,62 @@ namespace video { return true; } - int probe_encoders() { - if (!allow_encoder_probing()) { + int probe_encoders(service_t::impl_t &host) { + if (!allow_encoder_probing(host.displays)) { // Error already logged return -1; } - auto encoder_list = encoders; + std::vector encoder_list; + encoder_list.reserve(host.encoders.size()); + for (auto &encoder : host.encoders) { + encoder_list.push_back(&encoder); + } // If we already have a good encoder, check to see if another probe is required - if (chosen_encoder && !(chosen_encoder->flags & ALWAYS_REPROBE) && !platf::needs_encoder_reenumeration()) { + if (host.chosen_encoder && !(host.chosen_encoder->flags & ALWAYS_REPROBE) && !host.platform.needs_encoder_reenumeration()) { return 0; } // Restart encoder selection - auto previous_encoder = chosen_encoder; - chosen_encoder = nullptr; - active_hevc_mode = config::video.hevc_mode; - active_av1_mode = config::video.av1_mode; - last_encoder_probe_supported_ref_frames_invalidation = false; + auto previous_encoder = host.chosen_encoder; + host.chosen_encoder = nullptr; + host.probed.active_hevc_mode = config::video.hevc_mode; + host.probed.active_av1_mode = config::video.av1_mode; + host.probed.ref_frames_invalidation = false; + host.platform.set_capture_requirements(host.probed.active_hevc_mode); auto adjust_encoder_constraints_hevc = [&](encoder_t *encoder) { // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support - if (active_hevc_mode == 5 && !encoder->hevc[encoder_t::DYNAMIC_RANGE] && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { + if (host.probed.active_hevc_mode == 5 && !encoder->hevc[encoder_t::DYNAMIC_RANGE] && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 Rext10_444 on this system"sv; - active_hevc_mode = 0; - } else if (active_hevc_mode == 4 && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { + host.probed.active_hevc_mode = 0; + } else if (host.probed.active_hevc_mode == 4 && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Rext10_444 on this system"sv; - active_hevc_mode = 0; - } else if (active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) { + host.probed.active_hevc_mode = 0; + } else if (host.probed.active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 on this system"sv; - active_hevc_mode = 0; - } else if (active_hevc_mode == 2 && !encoder->hevc[encoder_t::PASSED]) { + host.probed.active_hevc_mode = 0; + } else if (host.probed.active_hevc_mode == 2 && !encoder->hevc[encoder_t::PASSED]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC on this system"sv; - active_hevc_mode = 0; + host.probed.active_hevc_mode = 0; } }; auto adjust_encoder_constraints_av1 = [&](encoder_t *encoder) { // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support - if (active_av1_mode == 5 && !encoder->av1[encoder_t::DYNAMIC_RANGE] && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { + if (host.probed.active_av1_mode == 5 && !encoder->av1[encoder_t::DYNAMIC_RANGE] && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 Rext10_444 on this system"sv; - active_av1_mode = 0; - } else if (active_av1_mode == 4 && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { + host.probed.active_av1_mode = 0; + } else if (host.probed.active_av1_mode == 4 && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Rext10_444 on this system"sv; - active_av1_mode = 0; - } else if (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE]) { + host.probed.active_av1_mode = 0; + } else if (host.probed.active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 on this system"sv; - active_av1_mode = 0; - } else if (active_av1_mode == 2 && !encoder->av1[encoder_t::PASSED]) { + host.probed.active_av1_mode = 0; + } else if (host.probed.active_av1_mode == 2 && !encoder->av1[encoder_t::PASSED]) { BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 on this system"sv; - active_av1_mode = 0; + host.probed.active_av1_mode = 0; } }; @@ -3322,7 +3361,7 @@ namespace video { if (encoder->name == config::video.encoder) { // Remove the encoder from the list entirely if it fails validation - if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { + if (!validate_encoder(host, *encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); break; } @@ -3331,14 +3370,14 @@ namespace video { adjust_encoder_constraints_hevc(encoder); adjust_encoder_constraints_av1(encoder); - chosen_encoder = encoder; + host.chosen_encoder = encoder; break; } pos++; }); - if (chosen_encoder == nullptr) { + if (host.chosen_encoder == nullptr) { BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << config::video.encoder << ']'; } } @@ -3346,59 +3385,59 @@ namespace video { BOOST_LOG(info) << "// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv; // If we haven't found an encoder yet, but we want one with specific codec support, search for that now. - if (chosen_encoder == nullptr && (active_hevc_mode >= 2 || active_av1_mode >= 2)) { + if (host.chosen_encoder == nullptr && (host.probed.active_hevc_mode >= 2 || host.probed.active_av1_mode >= 2)) { KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; // Remove the encoder from the list entirely if it fails validation - if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { + if (!validate_encoder(host, *encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); continue; } // Skip it if it doesn't support the specified codec at all - if ((active_hevc_mode >= 2 && !encoder->hevc[encoder_t::PASSED]) || (active_av1_mode >= 2 && !encoder->av1[encoder_t::PASSED])) { + if ((host.probed.active_hevc_mode >= 2 && !encoder->hevc[encoder_t::PASSED]) || (host.probed.active_av1_mode >= 2 && !encoder->av1[encoder_t::PASSED])) { pos++; continue; } // Skip it if it doesn't support HDR on the specified codec - if ((active_hevc_mode == 5 && !encoder->hevc[encoder_t::DYNAMIC_RANGE] && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) || (active_av1_mode == 5 && !encoder->av1[encoder_t::DYNAMIC_RANGE] && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444])) { + if ((host.probed.active_hevc_mode == 5 && !encoder->hevc[encoder_t::DYNAMIC_RANGE] && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) || (host.probed.active_av1_mode == 5 && !encoder->av1[encoder_t::DYNAMIC_RANGE] && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444])) { pos++; continue; } // Skip it if it doesn't support HDR on the specified codec - if ((active_hevc_mode == 4 && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) || (active_av1_mode == 4 && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444])) { + if ((host.probed.active_hevc_mode == 4 && !encoder->hevc[encoder_t::DYNAMIC_RANGE_YUV444]) || (host.probed.active_av1_mode == 4 && !encoder->av1[encoder_t::DYNAMIC_RANGE_YUV444])) { pos++; continue; } // Skip it if it doesn't support HDR on the specified codec - if ((active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) || (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE])) { + if ((host.probed.active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) || (host.probed.active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE])) { pos++; continue; } - chosen_encoder = encoder; + host.chosen_encoder = encoder; break; }); - if (chosen_encoder == nullptr) { + if (host.chosen_encoder == nullptr) { BOOST_LOG(error) << "Couldn't find any working encoder that meets HEVC/AV1 requirements"sv; } } // If no encoder was specified or the specified encoder was unusable, keep trying // the remaining encoders until we find one that passes validation. - if (chosen_encoder == nullptr) { + if (host.chosen_encoder == nullptr) { KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), { auto encoder = *pos; // If we've used a previous encoder and it's not this one, we expect this encoder to // fail to validate. It will use a slightly different order of checks to more quickly // eliminate failing encoders. - if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) { + if (!validate_encoder(host, *encoder, previous_encoder && previous_encoder != encoder)) { pos = encoder_list.erase(pos); continue; } @@ -3407,13 +3446,13 @@ namespace video { adjust_encoder_constraints_hevc(encoder); adjust_encoder_constraints_av1(encoder); - chosen_encoder = encoder; + host.chosen_encoder = encoder; break; }); } - if (chosen_encoder == nullptr) { - const auto output_name {display_device::map_output_name(config::video.output_name)}; + if (host.chosen_encoder == nullptr) { + const auto output_name {host.displays.map_output_name(config::video.output_name)}; BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv; if (!config::video.adapter_name.empty() || !output_name.empty()) { BOOST_LOG(fatal) << "Please ensure your manually chosen GPU and monitor are connected and powered on."sv; @@ -3427,15 +3466,15 @@ namespace video { BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant. //"sv; BOOST_LOG(info); - auto &encoder = *chosen_encoder; + auto &encoder = *host.chosen_encoder; - last_encoder_probe_supported_ref_frames_invalidation = (encoder.flags & REF_FRAMES_INVALIDATION); - last_encoder_probe_supported_yuv444_for_codec[0] = encoder.h264[encoder_t::PASSED] && - encoder.h264[encoder_t::YUV444]; - last_encoder_probe_supported_yuv444_for_codec[1] = encoder.hevc[encoder_t::PASSED] && - encoder.hevc[encoder_t::YUV444]; - last_encoder_probe_supported_yuv444_for_codec[2] = encoder.av1[encoder_t::PASSED] && - encoder.av1[encoder_t::YUV444]; + host.probed.ref_frames_invalidation = (encoder.flags & REF_FRAMES_INVALIDATION); + host.probed.yuv444[0] = encoder.h264[encoder_t::PASSED] && + encoder.h264[encoder_t::YUV444]; + host.probed.yuv444[1] = encoder.hevc[encoder_t::PASSED] && + encoder.hevc[encoder_t::YUV444]; + host.probed.yuv444[2] = encoder.av1[encoder_t::PASSED] && + encoder.av1[encoder_t::YUV444]; BOOST_LOG(debug) << "------ h264 ------"sv; for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) { @@ -3472,32 +3511,32 @@ namespace video { // 4 - HDR yuv444 // 5 - HDR yuv420 & HDR yuv444 - if (active_hevc_mode == 0) { - active_hevc_mode = 1; + if (host.probed.active_hevc_mode == 0) { + host.probed.active_hevc_mode = 1; if (encoder.hevc[encoder_t::PASSED]) { - active_hevc_mode = 2; + host.probed.active_hevc_mode = 2; if (encoder.hevc[encoder_t::DYNAMIC_RANGE]) { - active_hevc_mode += 1; + host.probed.active_hevc_mode += 1; } if (encoder.hevc[encoder_t::DYNAMIC_RANGE_YUV444]) { - active_hevc_mode += 2; + host.probed.active_hevc_mode += 2; } } - BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_HEVC_MODE: "sv << active_hevc_mode; + BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_HEVC_MODE: "sv << host.probed.active_hevc_mode; } - if (active_av1_mode == 0) { - active_av1_mode = 1; + if (host.probed.active_av1_mode == 0) { + host.probed.active_av1_mode = 1; if (encoder.av1[encoder_t::PASSED]) { - active_av1_mode = 2; + host.probed.active_av1_mode = 2; if (encoder.av1[encoder_t::DYNAMIC_RANGE]) { - active_av1_mode += 1; + host.probed.active_av1_mode += 1; } if (encoder.av1[encoder_t::DYNAMIC_RANGE_YUV444]) { - active_av1_mode += 2; + host.probed.active_av1_mode += 2; } } - BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_AV1_MODE: "sv << active_av1_mode; + BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_AV1_MODE: "sv << host.probed.active_av1_mode; } return 0; @@ -3647,15 +3686,17 @@ namespace video { /** * @brief Start capture async. + * @param host Host input or video service and its capture dependencies. */ - int start_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) { - capture_thread_ctx.encoder_p = chosen_encoder; + int start_capture_async(service_t::impl_t &host, capture_thread_async_ctx_t &capture_thread_ctx) { + capture_thread_ctx.encoder_p = host.chosen_encoder; capture_thread_ctx.reinit_event.reset(); capture_thread_ctx.capture_ctx_queue = std::make_shared>(30); capture_thread_ctx.capture_thread = std::jthread { captureThread, + std::ref(host), capture_thread_ctx.capture_ctx_queue, std::ref(capture_thread_ctx.display_wp), std::ref(capture_thread_ctx.reinit_event), @@ -3676,9 +3717,13 @@ namespace video { /** * @brief Start capture sync. + * @param host Host input or video service and its capture dependencies. */ - int start_capture_sync(capture_thread_sync_ctx_t &ctx) { - std::jthread {&captureThreadSync}.detach(); + int start_capture_sync(service_t::impl_t &host, capture_thread_sync_ctx_t &ctx) { + if (host.sync_thread.joinable()) { + host.sync_thread.join(); + } + host.sync_thread = std::jthread {&captureThreadSync, std::ref(host)}; return 0; } @@ -3744,4 +3789,35 @@ namespace video { return unknown; } + service_t::service_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform): + impl_ {std::make_unique(std::move(mail), cursor, displays, platform)} { + } + + service_t::~service_t() = default; + + capabilities_t service_t::capabilities() const { + std::lock_guard lock {impl_->probe_mutex}; + return impl_->probed; + } + + int service_t::probe_encoders() { + std::lock_guard lock {impl_->probe_mutex}; + const auto result = ::video::probe_encoders(*impl_); + impl_->platform.set_capture_requirements(impl_->probed.active_hevc_mode); + return result; + } + + bool service_t::validate_encoder(encoder_t &encoder, bool expect_failure) { + std::lock_guard lock {impl_->probe_mutex}; + return ::video::validate_encoder(*impl_, encoder, expect_failure); + } + + void service_t::capture(safe::mail_t mail, config_t config, void *channel_data) { + if (!impl_->chosen_encoder) { + mail->event(mail::shutdown)->raise(true); + return; + } + ::video::capture(*impl_, std::move(mail), config, channel_data); + } + } // namespace video diff --git a/src/video.h b/src/video.h index 63f3cf55c..8f611a7d7 100644 --- a/src/video.h +++ b/src/video.h @@ -4,6 +4,14 @@ */ #pragma once +namespace display_device { + class manager_t; +} + +namespace platf { + class runtime_t; +} + // standard includes #include #include @@ -354,7 +362,7 @@ namespace video { } }; - const std::unique_ptr platform_formats; ///< Platform-specific memory and pixel formats accepted by the encoder. + const std::shared_ptr platform_formats; ///< Shared immutable platform memory and pixel formats accepted by the encoder. /** * @brief Codec capabilities for AV1, HEVC, or H.264. @@ -452,24 +460,24 @@ namespace video { }; // encoders - extern encoder_t software; + extern const encoder_t software; #if !defined(__APPLE__) - extern encoder_t nvenc; // available for windows and linux + extern const encoder_t nvenc; // available for windows and linux #endif #ifdef _WIN32 - extern encoder_t amdvce; - extern encoder_t quicksync; - extern encoder_t mediafoundation; + extern const encoder_t amdvce; + extern const encoder_t quicksync; + extern const encoder_t mediafoundation; #endif #if defined(__linux__) || defined(linux) || defined(__linux) || defined(__FreeBSD__) - extern encoder_t vaapi; + extern const encoder_t vaapi; #endif #ifdef __APPLE__ - extern encoder_t videotoolbox; + extern const encoder_t videotoolbox; #endif /** @@ -678,10 +686,68 @@ namespace video { */ using hdr_info_t = std::unique_ptr; - extern int active_hevc_mode; - extern int active_av1_mode; - extern bool last_encoder_probe_supported_ref_frames_invalidation; - extern std::array last_encoder_probe_supported_yuv444_for_codec; // 0 - H.264, 1 - HEVC, 2 - AV1 + /** + * @brief Coherent result of one encoder capability probe. + */ + struct capabilities_t { + int active_hevc_mode = 0; ///< Selected HEVC operating mode. + int active_av1_mode = 0; ///< Selected AV1 operating mode. + bool ref_frames_invalidation = false; ///< Reference-frame invalidation support. + std::array yuv444 {}; ///< H.264, HEVC, and AV1 YUV444 support. + }; + + /** + * @brief Owns encoder selection, capability probes, and shared capture coordinators. + */ + class service_t { + public: + struct impl_t; ///< Private capture and encoder state. + + /** + * @brief Bind host capture dependencies without probing hardware. + * @param mail Host packet and display-switch mailbox. + * @param cursor Host cursor visibility preference. + * @param displays Display configuration manager. + */ + service_t(safe::mail_t mail, bool &cursor, display_device::manager_t &displays, platf::runtime_t &platform); + service_t(const service_t &) = delete; + service_t &operator=(const service_t &) = delete; + /** + * @brief Join capture workers before their host dependencies are released. + */ + ~service_t(); + + /** + * @brief Read the latest complete encoder capability snapshot. + * @return Capabilities published by the latest probe. + */ + capabilities_t capabilities() const; + + /** + * @brief Probe encoders when no client is actively streaming. + * @return Zero when a usable encoder is selected, nonzero otherwise. + */ + int probe_encoders(); + + /** + * @brief Validate one encoder using this service's configured capture requirements. + * @param encoder Encoder to probe and update. + * @param expect_failure Whether an unavailable encoder is expected. + * @return Whether the encoder can produce the requested formats. + */ + bool validate_encoder(encoder_t &encoder, bool expect_failure); + + /** + * @brief Capture and encode video for a transport session. + * @param mail Transport session mailbox. + * @param config Negotiated stream configuration. + * @param channel_data Packet channel metadata. + */ + void capture(safe::mail_t mail, config_t config, void *channel_data); + + private: + std::unique_ptr impl_; ///< Encoder state and capture worker ownership. + }; /** * @brief Resolve a client-requested dynamic range against probed encoder capabilities. @@ -692,39 +758,6 @@ namespace video { */ config_t resolve_dynamic_range(const encoder_t &encoder, config_t config); - /** - * @brief Capture and encode video for a streaming session. - * - * @param mail Session mail bus. - * @param config Client-requested video configuration, normalized before capture begins. - * @param channel_data Opaque channel data passed to packets. - */ - void capture( - safe::mail_t mail, - config_t config, - void *channel_data - ); - - /** - * @brief Validate encoder before it is used. - * - * @param encoder Encoder configuration or encoder instance. - * @param expect_failure Expect failure. - * @return True when encoder validation matches `expect_failure`. - */ - bool validate_encoder(encoder_t &encoder, bool expect_failure); - - /** - * @brief Probe encoders and select the preferred encoder. - * This is called once at startup and each time a stream is launched to - * ensure the best encoder is selected. Encoder availability can change - * at runtime due to all sorts of things from driver updates to eGPUs. - * - * @warning This is only safe to call when there is no client actively streaming. - * @return 0 when a usable encoder is selected; nonzero when probing fails. - */ - int probe_encoders(); - // Several NTSC standard refresh rates are hardcoded here, because their // true rate requires a denominator of 1001. ffmpeg's av_d2q() would assume it could // reduce 29.97 to 2997/100 but this would be slightly wrong. We also include diff --git a/tests/tests_common.h b/tests/tests_common.h index 4544a381b..b93a55ea0 100644 --- a/tests/tests_common.h +++ b/tests/tests_common.h @@ -21,6 +21,7 @@ #include // local includes +#include #include #include #include @@ -154,20 +155,46 @@ namespace test_utils { #define IS_FREEBSD false #endif +/** + * @brief Own initialized platform resources for one test suite. + */ struct PlatformTestSuite: BaseTest { + /** + * @brief Initialize the suite's independent native runtime. + */ static void SetUpTestSuite() { - ASSERT_FALSE(platf_deinit); - BOOST_LOG(tests) << "Setting up platform test suite"; - platf_deinit = platf::init(); - ASSERT_TRUE(platf_deinit); + ASSERT_FALSE(platform_); + infrastructure_ = std::make_unique(); + displays_ = std::make_unique(); + platform_ = std::make_unique(infrastructure_->mailbox(), infrastructure_->scheduler(), infrastructure_->lifetime(), *displays_ +#ifdef _WIN32 + , + infrastructure_->preferences() +#endif + ); + ASSERT_TRUE(platform_->initialize()); } + /** + * @brief Release capture resources before their dependencies. + */ static void TearDownTestSuite() { - ASSERT_TRUE(platf_deinit); - platf_deinit = {}; - BOOST_LOG(tests) << "Tore down platform test suite"; + platform_.reset(); + displays_.reset(); + infrastructure_.reset(); + } + +protected: + /** + * @brief Access the initialized platform runtime. + * @return Suite platform owner. + */ + static platf::runtime_t &platform() { + return *platform_; } private: - inline static std::unique_ptr platf_deinit; + inline static std::unique_ptr infrastructure_; ///< Suite scheduler and mailbox. + inline static std::unique_ptr displays_; ///< Suite display manager. + inline static std::unique_ptr platform_; ///< Suite platform resources. }; diff --git a/tests/unit/platform/test_virtualhid_input.cpp b/tests/unit/platform/test_virtualhid_input.cpp index d143a7e92..5f2d0a0f1 100644 --- a/tests/unit/platform/test_virtualhid_input.cpp +++ b/tests/unit/platform/test_virtualhid_input.cpp @@ -106,6 +106,8 @@ namespace { */ class VirtualHidDeviceTest: public ::testing::Test { protected: + runtime::infrastructure_t infrastructure_; ///< Host resources owned by this input fixture. + /** * @brief Preserve input configuration and create fake virtual devices. */ @@ -115,7 +117,7 @@ namespace { client_ = std::make_unique(*context_); const auto *test_info = ::testing::UnitTest::GetInstance()->current_test_info(); const std::string queue_name = std::string {"virtualhid-input-test-"} + test_info->test_suite_name() + '-' + test_info->name(); - feedback_queue_ = mail::man->queue(queue_name); + feedback_queue_ = infrastructure_.mailbox()->queue(queue_name); ASSERT_NE(context_->runtime, nullptr); ASSERT_NE(context_->keyboard, nullptr); @@ -297,7 +299,7 @@ TEST_F(VirtualHidDeviceTest, ReportsStaticAndRuntimeGamepadChoices) { #if defined(_WIN32) || defined(__APPLE__) TEST_F(VirtualHidDeviceTest, NoneSelectionHidesAvailableGamepads) { config::input.gamepad_driver = config::GAMEPAD_DRIVER_NONE; - auto platform_input = platf::input(); + auto platform_input = platf::input(infrastructure_.scheduler()); ASSERT_TRUE(platform_input); EXPECT_TRUE(platf::supported_gamepads(std::addressof(platform_input)).empty()); @@ -310,7 +312,7 @@ TEST_F(VirtualHidDeviceTest, BrokerCreatesAndUpdatesEveryGamepadProfileWhenLicen } config::input.gamepad_driver = config::GAMEPAD_DRIVER_VIRTUALHID; - auto platform_input = platf::input(); + auto platform_input = platf::input(infrastructure_.scheduler()); ASSERT_TRUE(platform_input); const auto &context = platf::virtualhid::get_input_context(platform_input); if (!context.runtime || !context.runtime->capabilities().supports_gamepad) { @@ -560,7 +562,7 @@ TEST_F(VirtualHidDeviceTest, RoutesAndDeduplicatesGamepadFeedback) { EXPECT_EQ(feedback->data.adaptive_triggers.left, output.left_trigger_effect); EXPECT_EQ(feedback->data.adaptive_triggers.right, output.right_trigger_effect); - auto resumed_feedback = mail::man->queue("virtualhid-input-test-resumed-feedback"); + auto resumed_feedback = infrastructure_.mailbox()->queue("virtualhid-input-test-resumed-feedback"); ASSERT_EQ(platf::virtualhid::rebind_gamepad(*context(), {0, 7}, resumed_feedback), 0); output.kind = lvh::GamepadOutputKind::rumble; output.low_frequency_rumble = 100; @@ -1032,7 +1034,7 @@ TEST_F(VirtualHidDeviceTest, TranslatesPenButtonsToolsAndTransitions) { } TEST_F(VirtualHidDeviceTest, PlatformWrappersForwardToVirtualHidContext) { - auto platform_input = platf::input(); + auto platform_input = platf::input(infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &platform_context = platf::virtualhid::get_input_context(platform_input); platform_context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; diff --git a/tests/unit/test_capture_geometry.cpp b/tests/unit/test_capture_geometry.cpp new file mode 100644 index 000000000..ee2a7e9e1 --- /dev/null +++ b/tests/unit/test_capture_geometry.cpp @@ -0,0 +1,45 @@ +/** + * @file tests/unit/test_capture_geometry.cpp + * @brief Test discovery snapshots used by Linux capture resources. + */ +#include "../tests_common.h" + +#include + +TEST(CaptureGeometryTest, EmptyDiscoveryKeepsAllExtentsAtOrigin) { + const platf::capture_geometry_t empty; + EXPECT_EQ(empty.width, 0); + EXPECT_EQ(empty.height, 0); + EXPECT_EQ(empty.logical_width, 0); + EXPECT_EQ(empty.logical_height, 0); +} + +TEST(CaptureGeometryTest, IndependentSnapshotsKeepMixedScaleOutputBounds) { + platf::capture_geometry_t first; + first.include({.offset_x = 0, .offset_y = 0, .width = 3840, .height = 2160, .logical_width = 1920, .logical_height = 1080}); + first.include({.offset_x = 1920, .offset_y = 100, .width = 2560, .height = 1440, .logical_width = 2560, .logical_height = 1440}); + EXPECT_EQ(first.width, 4480); + EXPECT_EQ(first.height, 2160); + EXPECT_EQ(first.logical_width, 4480); + EXPECT_EQ(first.logical_height, 1540); + const auto capture_snapshot = first; + platf::capture_geometry_t replacement; + replacement.include({.width = 1280, .height = 720, .logical_width = 1280, .logical_height = 720}); + first = replacement; + EXPECT_EQ(first.width, 1280); + EXPECT_EQ(capture_snapshot.width, 4480); + EXPECT_EQ(capture_snapshot.logical_height, 1540); +} + +TEST(CaptureGeometryTest, OutputsLeftOfOriginDoNotShrinkExistingBounds) { + platf::capture_geometry_t desktop; + desktop.include({.offset_x = -1920, .offset_y = -1080, .width = 1920, .height = 1080, .logical_width = 1920, .logical_height = 1080}); + EXPECT_EQ(desktop.width, 0); + EXPECT_EQ(desktop.height, 0); + desktop.include({.width = 1920, .height = 1080, .logical_width = 1920, .logical_height = 1080}); + desktop.include({.offset_x = -500, .offset_y = -500, .width = 600, .height = 600, .logical_width = 600, .logical_height = 600}); + EXPECT_EQ(desktop.width, 1920); + EXPECT_EQ(desktop.height, 1080); + EXPECT_EQ(desktop.logical_width, 1920); + EXPECT_EQ(desktop.logical_height, 1080); +} diff --git a/tests/unit/test_input.cpp b/tests/unit/test_input.cpp index 5c3634a91..d6a05c340 100644 --- a/tests/unit/test_input.cpp +++ b/tests/unit/test_input.cpp @@ -69,12 +69,12 @@ namespace { * @param expected Expected number of dispatched packets. */ template - void expect_packet_dispatches(Packet original, Packet different, std::uint32_t magic, std::size_t expected) { + void expect_packet_dispatches(input::service_t &inputs_, Packet original, Packet different, std::uint32_t magic, std::size_t expected) { SCOPED_TRACE(magic); - auto stream_input = input::alloc(std::make_shared(), "packet-batching"); + auto stream_input = inputs_.alloc(std::make_shared(), "packet-batching"); ASSERT_NE(stream_input, nullptr); std::size_t dispatch_count = 0; - input::testing::set_input_packet_hook([magic, &dispatch_count](std::uint32_t dispatched_magic) { + input::testing::set_input_packet_hook(inputs_, [magic, &dispatch_count](std::uint32_t dispatched_magic) { EXPECT_EQ(dispatched_magic, magic); ++dispatch_count; }); @@ -86,7 +86,7 @@ namespace { input::passthrough(stream_input, std::move(bytes)); } input::testing::process_queued_messages(stream_input); - input::testing::set_input_packet_hook({}); + input::testing::set_input_packet_hook(inputs_, {}); EXPECT_EQ(dispatch_count, expected); EXPECT_EQ(input::testing::queued_input_packet_count(stream_input), 0); } @@ -96,6 +96,9 @@ namespace { */ class InputGamepadSessionTest: public ::testing::Test { protected: + runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this input fixture. + input::service_t inputs_ {infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. + /** * @brief Preserve configuration and install observable fake devices. */ @@ -105,24 +108,24 @@ namespace { config::input.mouse = true; config::input.gamepad = "xseries"; - auto platform_input = platf::input(); + auto platform_input = platf::input(infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &context = platf::virtualhid::get_input_context(platform_input); context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; context_ = &context; runtime_ = context.runtime.get(); ASSERT_NE(runtime_, nullptr); - input::testing::set_platform_input(std::move(platform_input)); + input::testing::set_platform_input(inputs_, std::move(platform_input)); } /** * @brief Destroy retained test sessions and restore configuration. */ void TearDown() override { - input::testing::set_input_packet_hook({}); - input::testing::set_input_task_sink({}); - input::terminate_gamepads(); - input::testing::set_platform_input({}); + input::testing::set_input_packet_hook(inputs_, {}); + input::testing::set_input_task_sink(inputs_, {}); + inputs_.terminate_gamepads(); + input::testing::set_platform_input(inputs_, {}); context_ = nullptr; runtime_ = nullptr; config::input = std::move(original_input_); @@ -246,11 +249,11 @@ TEST(InputPacketValidationTest, PreservesUnknownPacketHandlingWithinDeclaredBoun } TEST_F(InputGamepadSessionTest, RejectsMalformedBatchablePacketsAtQueueIngress) { - ASSERT_FALSE(task_pool.running()); + ASSERT_FALSE(infrastructure_.scheduler().running()); const std::shared_ptr empty_input; EXPECT_EQ(input::testing::queued_input_packet_count(empty_input), 0); - auto stream_input = input::alloc(std::make_shared(), "packet-validation-client"); + auto stream_input = inputs_.alloc(std::make_shared(), "packet-validation-client"); ASSERT_NE(stream_input, nullptr); auto short_header = make_input_packet(SS_PEN_MAGIC, sizeof(std::uint32_t), sizeof(NV_INPUT_HEADER) - 1); @@ -289,13 +292,13 @@ TEST_F(InputGamepadSessionTest, RejectsMalformedBatchablePacketsAtQueueIngress) } TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController) { - ASSERT_FALSE(task_pool.running()); + ASSERT_FALSE(infrastructure_.scheduler().running()); config::input.gamepad = "auto"; - auto stream_input = input::alloc(std::make_shared(), "simultaneous-controller-packets"); + auto stream_input = inputs_.alloc(std::make_shared(), "simultaneous-controller-packets"); ASSERT_NE(stream_input, nullptr); std::vector> scheduled; - input::testing::set_input_task_sink([&](std::shared_ptr input) { + input::testing::set_input_task_sink(inputs_, [&](std::shared_ptr input) { scheduled.push_back(std::move(input)); }); @@ -320,7 +323,7 @@ TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController std::promise arrival_started; std::promise release_arrival; const auto release_signal = release_arrival.get_future().share(); - input::testing::set_input_packet_hook([&](std::uint32_t magic) { + input::testing::set_input_packet_hook(inputs_, [&](std::uint32_t magic) { if (magic == SS_CONTROLLER_ARRIVAL_MAGIC) { arrival_started.set_value(); release_signal.wait(); @@ -341,7 +344,7 @@ TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController EXPECT_EQ(scheduled.size(), 1); EXPECT_EQ(input::testing::queued_input_packet_count(stream_input), 1); - auto other_input = input::alloc(std::make_shared(), "independent-input-stream"); + auto other_input = inputs_.alloc(std::make_shared(), "independent-input-stream"); if (!other_input) { release_arrival.set_value(); worker.join(); @@ -355,7 +358,7 @@ TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController const auto active_before_gamepad = runtime().active_device_count(); release_arrival.set_value(); worker.join(); - input::testing::set_input_packet_hook({}); + input::testing::set_input_packet_hook(inputs_, {}); input::testing::process_queued_messages(other_input); EXPECT_EQ(input::testing::queued_input_packet_count(stream_input), 0); @@ -370,12 +373,12 @@ TEST_F(InputGamepadSessionTest, SerializesArrivalAndStatePacketsForOneController } TEST_F(InputGamepadSessionTest, YieldsAfterBoundedPacketBatch) { - ASSERT_FALSE(task_pool.running()); - auto stream_input = input::alloc(std::make_shared(), "bounded-input-batch"); + ASSERT_FALSE(infrastructure_.scheduler().running()); + auto stream_input = inputs_.alloc(std::make_shared(), "bounded-input-batch"); ASSERT_NE(stream_input, nullptr); std::vector> scheduled; - input::testing::set_input_task_sink([&](std::shared_ptr input) { + input::testing::set_input_task_sink(inputs_, [&](std::shared_ptr input) { scheduled.push_back(std::move(input)); }); @@ -395,84 +398,84 @@ TEST_F(InputGamepadSessionTest, YieldsAfterBoundedPacketBatch) { } TEST_F(InputGamepadSessionTest, BatchesContinuousPacketsWithoutCrossingStateChanges) { - ASSERT_FALSE(task_pool.running()); + ASSERT_FALSE(infrastructure_.scheduler().running()); config::input.mouse = false; config::input.controller = false; config::input.native_pen_touch = false; - input::testing::set_input_task_sink([](std::shared_ptr) { + input::testing::set_input_task_sink(inputs_, [](std::shared_ptr) { }); NV_MULTI_CONTROLLER_PACKET controller {}; - expect_packet_dispatches(controller, controller, MULTI_CONTROLLER_MAGIC_GEN5, 1); + expect_packet_dispatches(inputs_, controller, controller, MULTI_CONTROLLER_MAGIC_GEN5, 1); auto changed_controller = controller; changed_controller.controllerNumber = 1; - expect_packet_dispatches(controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 2); + expect_packet_dispatches(inputs_, controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 2); changed_controller = controller; changed_controller.activeGamepadMask = 1; - expect_packet_dispatches(controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); + expect_packet_dispatches(inputs_, controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); changed_controller = controller; changed_controller.buttonFlags = 1; - expect_packet_dispatches(controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); + expect_packet_dispatches(inputs_, controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); changed_controller = controller; changed_controller.buttonFlags2 = 1; - expect_packet_dispatches(controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); + expect_packet_dispatches(inputs_, controller, changed_controller, MULTI_CONTROLLER_MAGIC_GEN5, 3); SS_TOUCH_PACKET touch {}; touch.eventType = LI_TOUCH_EVENT_MOVE; - expect_packet_dispatches(touch, touch, SS_TOUCH_MAGIC, 1); + expect_packet_dispatches(inputs_, touch, touch, SS_TOUCH_MAGIC, 1); auto changed_touch = touch; changed_touch.pointerId = 1; - expect_packet_dispatches(touch, changed_touch, SS_TOUCH_MAGIC, 2); + expect_packet_dispatches(inputs_, touch, changed_touch, SS_TOUCH_MAGIC, 2); changed_touch = touch; changed_touch.eventType = LI_TOUCH_EVENT_DOWN; - expect_packet_dispatches(touch, changed_touch, SS_TOUCH_MAGIC, 3); + expect_packet_dispatches(inputs_, touch, changed_touch, SS_TOUCH_MAGIC, 3); changed_touch.eventType = LI_TOUCH_EVENT_HOVER; - expect_packet_dispatches(touch, changed_touch, SS_TOUCH_MAGIC, 3); + expect_packet_dispatches(inputs_, touch, changed_touch, SS_TOUCH_MAGIC, 3); SS_PEN_PACKET pen {}; pen.eventType = LI_TOUCH_EVENT_MOVE; - expect_packet_dispatches(pen, pen, SS_PEN_MAGIC, 1); + expect_packet_dispatches(inputs_, pen, pen, SS_PEN_MAGIC, 1); auto changed_pen = pen; changed_pen.eventType = LI_TOUCH_EVENT_DOWN; - expect_packet_dispatches(pen, changed_pen, SS_PEN_MAGIC, 3); + expect_packet_dispatches(inputs_, pen, changed_pen, SS_PEN_MAGIC, 3); changed_pen.eventType = LI_TOUCH_EVENT_HOVER; - expect_packet_dispatches(pen, changed_pen, SS_PEN_MAGIC, 3); + expect_packet_dispatches(inputs_, pen, changed_pen, SS_PEN_MAGIC, 3); changed_pen = pen; changed_pen.penButtons = 1; - expect_packet_dispatches(pen, changed_pen, SS_PEN_MAGIC, 3); + expect_packet_dispatches(inputs_, pen, changed_pen, SS_PEN_MAGIC, 3); changed_pen = pen; changed_pen.toolType = 1; - expect_packet_dispatches(pen, changed_pen, SS_PEN_MAGIC, 3); + expect_packet_dispatches(inputs_, pen, changed_pen, SS_PEN_MAGIC, 3); SS_CONTROLLER_TOUCH_PACKET controller_touch {}; controller_touch.eventType = LI_TOUCH_EVENT_MOVE; - expect_packet_dispatches(controller_touch, controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 1); + expect_packet_dispatches(inputs_, controller_touch, controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 1); auto changed_controller_touch = controller_touch; changed_controller_touch.controllerNumber = 1; - expect_packet_dispatches(controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 2); + expect_packet_dispatches(inputs_, controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 2); changed_controller_touch = controller_touch; changed_controller_touch.pointerId = 1; - expect_packet_dispatches(controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 2); + expect_packet_dispatches(inputs_, controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 2); changed_controller_touch = controller_touch; changed_controller_touch.eventType = LI_TOUCH_EVENT_DOWN; - expect_packet_dispatches(controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 3); + expect_packet_dispatches(inputs_, controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 3); changed_controller_touch.eventType = LI_TOUCH_EVENT_HOVER; - expect_packet_dispatches(controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 3); + expect_packet_dispatches(inputs_, controller_touch, changed_controller_touch, SS_CONTROLLER_TOUCH_MAGIC, 3); SS_CONTROLLER_MOTION_PACKET motion {}; - expect_packet_dispatches(motion, motion, SS_CONTROLLER_MOTION_MAGIC, 1); + expect_packet_dispatches(inputs_, motion, motion, SS_CONTROLLER_MOTION_MAGIC, 1); auto changed_motion = motion; changed_motion.controllerNumber = 1; - expect_packet_dispatches(motion, changed_motion, SS_CONTROLLER_MOTION_MAGIC, 2); + expect_packet_dispatches(inputs_, motion, changed_motion, SS_CONTROLLER_MOTION_MAGIC, 2); changed_motion = motion; changed_motion.motionType = 1; - expect_packet_dispatches(motion, changed_motion, SS_CONTROLLER_MOTION_MAGIC, 2); + expect_packet_dispatches(inputs_, motion, changed_motion, SS_CONTROLLER_MOTION_MAGIC, 2); } TEST_F(InputGamepadSessionTest, ReusesGamepadsAcrossPauseAndDestroysThemOnTermination) { const std::string session_id = "paired-client-certificate"; auto first_mail = std::make_shared(); - auto first = input::alloc(first_mail, session_id); + auto first = inputs_.alloc(first_mail, session_id); ASSERT_NE(first, nullptr); const auto active_devices_before_gamepad = runtime().active_device_count(); @@ -487,17 +490,17 @@ TEST_F(InputGamepadSessionTest, ReusesGamepadsAcrossPauseAndDestroysThemOnTermin EXPECT_EQ(runtime().active_device_count(), active_devices_before_gamepad + 1); auto resumed_mail = std::make_shared(); - auto resumed = input::alloc(resumed_mail, session_id); + auto resumed = inputs_.alloc(resumed_mail, session_id); ASSERT_NE(resumed, nullptr); EXPECT_EQ(paused.lock(), resumed); EXPECT_EQ(input::testing::gamepad_id(resumed, 0), original_id); EXPECT_EQ(runtime().active_device_count(), active_devices_before_gamepad + 1); - input::terminate_gamepads(session_id); + inputs_.terminate_gamepads(session_id); EXPECT_EQ(input::testing::gamepad_id(resumed, 0), -1); EXPECT_EQ(runtime().active_device_count(), active_devices_before_gamepad); - auto replacement = input::alloc(std::make_shared(), session_id); + auto replacement = inputs_.alloc(std::make_shared(), session_id); EXPECT_NE(replacement, resumed); } @@ -508,7 +511,7 @@ TEST_F(InputGamepadSessionTest, RefreshesSharedVirtualInputAfterLicenseStateChan const auto original_mouse_id = context().mouse->device_id(); const auto active_devices = runtime().active_device_count(); - input::refresh_virtual_input(); + inputs_.refresh_virtual_input(); ASSERT_NE(context().keyboard, nullptr); ASSERT_NE(context().mouse, nullptr); @@ -517,9 +520,31 @@ TEST_F(InputGamepadSessionTest, RefreshesSharedVirtualInputAfterLicenseStateChan EXPECT_EQ(runtime().active_device_count(), active_devices); } +TEST_F(InputGamepadSessionTest, IndependentHostServicesDoNotShareRetainedSessionsOrGamepadSlots) { + runtime::infrastructure_t other_infrastructure; + input::service_t other_inputs {other_infrastructure.scheduler(), other_infrastructure.mailbox(), other_infrastructure.cursor()}; + auto other_platform = platf::input(other_infrastructure.scheduler()); + ASSERT_TRUE(other_platform); + auto &other_context = platf::virtualhid::get_input_context(other_platform); + other_context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; + input::testing::set_platform_input(other_inputs, std::move(other_platform)); + + auto first = inputs_.alloc(std::make_shared(), "same-client"); + auto second = other_inputs.alloc(std::make_shared(), "same-client"); + ASSERT_NE(first, second); + const platf::gamepad_arrival_t metadata {LI_CTYPE_XBOX, 0, 0}; + EXPECT_EQ(input::testing::alloc_gamepad(first, 0, metadata), 0); + EXPECT_EQ(input::testing::alloc_gamepad(second, 0, metadata), 0); + + inputs_.terminate_gamepads("same-client"); + EXPECT_EQ(input::testing::gamepad_id(first, 0), -1); + EXPECT_EQ(input::testing::gamepad_id(second, 0), 0); + EXPECT_EQ(other_inputs.alloc(std::make_shared(), "same-client"), second); +} + TEST_F(InputGamepadSessionTest, RetargetsRelativeMouseFromLatestStreamGeometry) { auto session_mail = std::make_shared(); - auto stream_input = input::alloc(session_mail, "relative-mouse-client"); + auto stream_input = inputs_.alloc(session_mail, "relative-mouse-client"); ASSERT_NE(stream_input, nullptr); input::touch_port_t left_viewport { diff --git a/tests/unit/test_keyboard.cpp b/tests/unit/test_keyboard.cpp index dd52fad55..d7525ea70 100644 --- a/tests/unit/test_keyboard.cpp +++ b/tests/unit/test_keyboard.cpp @@ -319,6 +319,9 @@ namespace { */ class KeyboardPassthroughTest: public ::testing::Test { protected: + runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this keyboard fixture. + input::service_t inputs_ {infrastructure_.scheduler(), infrastructure_.mailbox(), infrastructure_.cursor()}; ///< Fixture-owned host input service. + /** * @brief Install a fake platform backend, a keyboard recorder, and a stream. */ @@ -330,21 +333,21 @@ namespace { // Keep every emission on the calling thread so the recorded order is deterministic. config::input.key_repeat_delay = 0ms; - auto platform_input = platf::input(); + auto platform_input = platf::input(infrastructure_.scheduler()); ASSERT_TRUE(platform_input); auto &context = platf::virtualhid::get_input_context(platform_input); context = platf::virtualhid::input_context_t {lvh::BackendKind::fake}; context_ = &context; ASSERT_NE(context_->keyboard, nullptr); - input::testing::set_platform_input(std::move(platform_input)); - input::testing::reset_keyboard_state(); + input::testing::set_platform_input(inputs_, std::move(platform_input)); + input::testing::reset_keyboard_state(inputs_); - input::testing::set_keyboard_sink([this](const input::testing::keyboard_event_t &event) { + input::testing::set_keyboard_sink(inputs_, [this](const input::testing::keyboard_event_t &event) { events_.push_back(event); }); static int session = 0; - stream_ = input::alloc(std::make_shared(), std::format("keyboard-test-{}", ++session)); + stream_ = inputs_.alloc(std::make_shared(), std::format("keyboard-test-{}", ++session)); ASSERT_NE(stream_, nullptr); } @@ -352,11 +355,11 @@ namespace { * @brief Stop recording, drop tracked key state, and restore configuration. */ void TearDown() override { - input::testing::set_keyboard_sink({}); - input::testing::reset_keyboard_state(); + input::testing::set_keyboard_sink(inputs_, {}); + input::testing::reset_keyboard_state(inputs_); stream_.reset(); context_ = nullptr; - input::testing::set_platform_input({}); + input::testing::set_platform_input(inputs_, {}); config::input = std::move(original_input_); } @@ -474,7 +477,7 @@ TEST_F(KeyboardPassthroughTest, PreservesExtendedEnterOnReleaseAndDisconnect) { press(VKEY_RETURN, MODIFIER_EXTENDED); taken_events(); - input::testing::release_held_keys(); + input::testing::release_held_keys(inputs_); events = taken_events(); ASSERT_EQ(events.size(), 1U); EXPECT_TRUE(events[0].extended); @@ -866,7 +869,7 @@ TEST_F(KeyboardPassthroughTest, DeliversKeysThroughTheVirtualKeyboard) { // Drop the recorder so the events travel the real path into libvirtualhid's fake backend. // This keeps the recorder honest: if platf::keyboard_update stopped being reached, every // other test here would still pass. - input::testing::set_keyboard_sink({}); + input::testing::set_keyboard_sink(inputs_, {}); auto &keyboard = fake_keyboard(); const auto submitted = keyboard.submit_count(); @@ -909,7 +912,7 @@ TEST_F(KeyboardPassthroughTest, ReleasesHeldKeysAsThemselvesWithoutKeybindings) press(VKEY_A, MODIFIER_ALT); EXPECT_EQ(taken(), (std::vector {pressed(VKEY_LMENU), pressed(VKEY_A)})); - input::testing::release_held_keys(); + input::testing::release_held_keys(inputs_); // key_press is an unordered_map, so the release order is unspecified. auto released_keys = taken(); @@ -926,7 +929,7 @@ TEST_F(KeyboardPassthroughTest, ReleasesTheRemappedHostKeyWhenTheClientDisconnec press(VKEY_LMENU, MODIFIER_ALT); EXPECT_EQ(taken(), (std::vector {pressed(VKEY_LWIN)})); - input::testing::release_held_keys(); + input::testing::release_held_keys(inputs_); // key_press is keyed on the unmapped 0xA4, so releasing that would leave the host holding // the remapped key down forever. @@ -941,7 +944,7 @@ TEST_F(KeyboardPassthroughTest, ReleasesTheRemappedRightAltForKeyRightaltToKeyWi press(VKEY_RMENU, MODIFIER_ALT); EXPECT_EQ(taken(), (std::vector {pressed(VKEY_LWIN)})); - input::testing::release_held_keys(); + input::testing::release_held_keys(inputs_); EXPECT_EQ(taken(), (std::vector {released(VKEY_LWIN)})); } diff --git a/tests/unit/test_mouse.cpp b/tests/unit/test_mouse.cpp index eb0148f7d..e82c83e72 100644 --- a/tests/unit/test_mouse.cpp +++ b/tests/unit/test_mouse.cpp @@ -104,6 +104,8 @@ namespace { } // namespace struct MouseHIDTest: PlatformTestSuite, testing::WithParamInterface { + runtime::infrastructure_t infrastructure_; ///< Scheduler owned by this mouse fixture. + void SetUp() override { BaseTest::SetUp(); } @@ -129,7 +131,7 @@ TEST_P(MouseHIDTest, MoveInputTest) { util::point_t mouse_delta = GetParam(); BOOST_LOG(tests) << "MoveInputTest:: got param: " << mouse_delta; - platf::input_t input = platf::input(); + platf::input_t input = platf::input(infrastructure_.scheduler()); BOOST_LOG(tests) << "MoveInputTest:: init input"; BOOST_LOG(tests) << "MoveInputTest:: get current mouse loc"; @@ -172,7 +174,7 @@ TEST_P(MouseHIDTest, AbsMoveInputTest) { util::point_t mouse_pos = GetParam(); BOOST_LOG(tests) << "AbsMoveInputTest:: got param: " << mouse_pos; - platf::input_t input = platf::input(); + platf::input_t input = platf::input(infrastructure_.scheduler()); BOOST_LOG(tests) << "AbsMoveInputTest:: init input"; BOOST_LOG(tests) << "AbsMoveInputTest:: get current mouse loc"; diff --git a/tests/unit/test_video.cpp b/tests/unit/test_video.cpp index 73297ca97..5e4098488 100644 --- a/tests/unit/test_video.cpp +++ b/tests/unit/test_video.cpp @@ -22,6 +22,7 @@ extern "C" { // local includes #include +#include #include using namespace std::literals; @@ -67,11 +68,54 @@ TEST(VideoFormatMappingTest, MapsSupportedPixelFormatsAndRejectsUnsupportedOnes) } } -struct EncoderTest: PlatformTestSuite, testing::WithParamInterface { +TEST(VideoServiceOwnershipTest, SnapshotChangesDoNotMutateServiceStateAndUnprobedCaptureStopsItsSession) { + runtime::infrastructure_t infrastructure; + display_device::manager_t displays; + platf::runtime_t platform { + infrastructure.mailbox(), + infrastructure.scheduler(), + infrastructure.lifetime(), + displays +#ifdef _WIN32 + , + infrastructure.preferences() +#endif + }; + video::service_t first {infrastructure.mailbox(), infrastructure.cursor(), displays, platform}; + video::service_t second {std::make_shared(), infrastructure.cursor(), displays, platform}; + auto snapshot = first.capabilities(); + snapshot.active_hevc_mode = 5; + snapshot.yuv444.fill(true); + EXPECT_EQ(first.capabilities().active_hevc_mode, 0); + EXPECT_EQ(second.capabilities().active_hevc_mode, 0); + EXPECT_FALSE(first.capabilities().yuv444[0]); + + auto session_mail = std::make_shared(); + auto shutdown = session_mail->event(mail::shutdown); + first.capture(session_mail, {}, nullptr); + EXPECT_TRUE(shutdown->peek()); +} + +TEST(VideoEncoderOwnershipTest, DescriptorCopiesKeepProbeCapabilitiesIndependent) { + auto first = video::software; + auto second = video::software; + first.h264[video::encoder_t::PASSED] = true; + first.hevc[video::encoder_t::DYNAMIC_RANGE] = true; + EXPECT_FALSE(second.h264[video::encoder_t::PASSED]); + EXPECT_FALSE(second.hevc[video::encoder_t::DYNAMIC_RANGE]); + EXPECT_FALSE(video::software.h264[video::encoder_t::PASSED]); + EXPECT_EQ(first.platform_formats, second.platform_formats); +} + +struct EncoderTest: PlatformTestSuite, testing::WithParamInterface { + runtime::infrastructure_t infrastructure_; ///< Infrastructure owned by this encoder fixture. + display_device::manager_t displays_; ///< Display configuration owner for encoder validation. + video::service_t videos_ {infrastructure_.mailbox(), infrastructure_.cursor(), displays_, platform()}; ///< Fixture-owned video service. + void SetUp() override { BaseTest::SetUp(); - auto &encoder = *GetParam(); - if (!video::validate_encoder(encoder, false)) { + auto encoder = *GetParam(); + if (!videos_.validate_encoder(encoder, false)) { // Encoder failed validation, // if it's software - fail, otherwise skip if (encoder.name == "software") {