From e5bfa5067c1146adb88af85103e945c29c926da9 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:23:45 +0100 Subject: [PATCH 1/2] feat(windows): mosaic waiting image for parts whose session is restarting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A line of osms-mosaic.txt may end with the path of a waiting image ("OSWP", width, height, BGRA pixels) and may use session 0 while the session of that part restarts. The part keeps its place and shows the image (OpenStreamMS draws its logo and "Reconnecting…") until the session publishes frames again, instead of the layout dropping to fewer parts. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/display.h | 40 +++++++++- src/platform/windows/display_remoteidd.cpp | 73 ++++++++++++++++++- src/platform/windows/display_vram.cpp | 8 +- .../unit/platform/windows/test_remoteidd.cpp | 40 ++++++++++ 4 files changed, 155 insertions(+), 6 deletions(-) diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index 293b8dda372..814d5f82889 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -7,6 +7,7 @@ // standard includes #include #include +#include #include #include #include @@ -874,10 +875,29 @@ namespace platf::dxgi { * @brief A session of a mosaic stream, as listed in osms-mosaic.txt. */ struct mosaic_entry_t { - uint32_t session; ///< Terminal Services session id. + uint32_t session; ///< Terminal Services session id; 0 while the session is (re)starting. int cells; ///< Cells of the 2x2 grid it covers: 1 top-left, 2 top-right, 4 bottom-left, 8 bottom-right. + std::string waiting; ///< Image shown while the session publishes no frames (see read_waiting_image); empty = black. }; + /** + * @brief Image that OpenStreamMS draws for a part whose session is (re)starting. + */ + struct waiting_image_t { + int width = 0; ///< Width in pixels. + int height = 0; ///< Height in pixels. + std::vector bgra; ///< Pixels, BGRA, top to bottom, width * 4 bytes per row. + }; + + /** + * @brief Read a waiting image: "OSWP", width and height as little-endian int32, then the + * BGRA pixels. + * + * @param bytes File content. + * @return The image, or nullopt when the content is not a valid image. + */ + std::optional parse_waiting_image(const std::string &bytes); + /** * @brief Content of osms-mosaic.txt. */ @@ -909,8 +929,9 @@ namespace platf::dxgi { /** * @brief Parse osms-mosaic.txt. * - * Lines are "canvas " or " "; lines starting with # - * are comments. Lines that do not parse, and parts that overlap an earlier one, are skipped. + * Lines are "canvas " or " []"; + * lines starting with # are comments. Session 0 keeps the part while its session is + * (re)starting. Lines that do not parse, and parts that overlap an earlier one, are skipped. * * @param text File content. * @return Parsed layout. @@ -995,6 +1016,8 @@ namespace platf::dxgi { uint32_t frame_width = 0; ///< Size of the last frame copied, to notice a shrink. uint32_t frame_height = 0; ///< Size of the last frame copied, to notice a shrink. std::chrono::steady_clock::time_point next_open; ///< When to retry opening the slot. + texture2d_t waiting; ///< Image shown until the session publishes a frame; null = black. + bool showing_waiting = false; ///< The waiting image is on the canvas. }; /** @@ -1012,6 +1035,17 @@ namespace platf::dxgi { * @brief Clear the canvas to black and copy every tile again on the next snapshot. */ void clear_canvas(); + /** + * @brief Load the waiting image of a tile into a texture; on failure the tile stays black. + * @param tile Tile. + * @param path Image file written by OpenStreamMS. + */ + void load_waiting(mosaic_tile_t &tile, const std::string &path); + /** + * @brief Copy the waiting image of a tile onto its part of the canvas. + * @param tile Tile with a waiting image. + */ + void draw_waiting(mosaic_tile_t &tile); /** * @brief Snapshot in mosaic mode: copy the tiles that changed and then the canvas. */ diff --git a/src/platform/windows/display_remoteidd.cpp b/src/platform/windows/display_remoteidd.cpp index 8607cfba619..e57ec0e3c35 100644 --- a/src/platform/windows/display_remoteidd.cpp +++ b/src/platform/windows/display_remoteidd.cpp @@ -134,6 +134,10 @@ namespace platf::dxgi { } continue; } + // Rest of the line: the waiting image path (it may contain spaces). + std::string waiting; + std::getline(fields, waiting); + waiting.erase(0, waiting.find_first_not_of(" \t")); uint32_t session = 0; auto [end, ec] = std::from_chars(first.data(), first.data() + first.size(), session); int cells = mosaic_area_cells(second); @@ -142,11 +146,28 @@ namespace platf::dxgi { continue; } used |= cells; - layout.entries.push_back({session, cells}); + layout.entries.push_back({session, cells, std::move(waiting)}); } return layout; } + std::optional parse_waiting_image(const std::string &bytes) { + if (bytes.size() < 12 || bytes.compare(0, 4, "OSWP") != 0) { + return std::nullopt; + } + auto read_int = [&](size_t at) { + return static_cast(static_cast(bytes[at]) | (static_cast(bytes[at + 1]) << 8) | (static_cast(bytes[at + 2]) << 16) | (static_cast(static_cast(bytes[at + 3])) << 24)); + }; + waiting_image_t image; + image.width = read_int(4); + image.height = read_int(8); + if (image.width <= 0 || image.height <= 0 || image.width > 16384 || image.height > 16384 || bytes.size() != 12 + static_cast(image.width) * image.height * 4) { + return std::nullopt; + } + image.bgra.assign(bytes.begin() + 12, bytes.end()); + return image; + } + mosaic_rect_t mosaic_rect(int cells, int canvas_width, int canvas_height) { const bool left = cells & 0b0101; const bool right = cells & 0b1010; @@ -218,6 +239,9 @@ namespace platf::dxgi { tile.y = rect.y; tile.width = rect.width; tile.height = rect.height; + if (!e.waiting.empty()) { + load_waiting(tile, e.waiting); + } if (e.session == session) { // Absolute mouse: the client points at the canvas, the desktop is this tile. @@ -255,7 +279,9 @@ namespace platf::dxgi { clear_canvas(); for (auto &tile : tiles) { - open_tile(tile); + if (tile.session) { + open_tile(tile); + } } BOOST_LOG(info) << "RemoteIdd mosaic: "sv << tiles.size() << " sessions on a "sv << canvas_w << 'x' << canvas_h << " canvas"sv; return 0; @@ -294,7 +320,50 @@ namespace platf::dxgi { device_ctx->ClearRenderTargetView(canvas_rt.get(), black); for (auto &tile : tiles) { tile.last_frame = 0; + tile.showing_waiting = false; } compose_now = true; } + + void display_ridd_vram_t::load_waiting(mosaic_tile_t &tile, const std::string &path) { + std::ifstream file(std::filesystem::path(reinterpret_cast(path.c_str())), std::ios::binary); + std::ostringstream content; + if (file) { + content << file.rdbuf(); + } + auto image = parse_waiting_image(content.str()); + if (!image) { + BOOST_LOG(warning) << "RemoteIdd mosaic: no valid waiting image at "sv << path; + return; + } + D3D11_TEXTURE2D_DESC desc {}; + desc.Width = image->width; + desc.Height = image->height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_IMMUTABLE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + D3D11_SUBRESOURCE_DATA data {image->bgra.data(), static_cast(image->width * 4), 0}; + ID3D11Texture2D *raw = nullptr; + if (FAILED(device->CreateTexture2D(&desc, &data, &raw))) { + BOOST_LOG(warning) << "RemoteIdd mosaic: failed to create the waiting image texture"sv; + return; + } + tile.waiting.reset(raw); + } + + void display_ridd_vram_t::draw_waiting(mosaic_tile_t &tile) { + D3D11_TEXTURE2D_DESC desc; + tile.waiting->GetDesc(&desc); + // Same size as the part (OpenStreamMS draws it so); otherwise centred and cropped. + const auto w = std::min(desc.Width, tile.width); + const auto h = std::min(desc.Height, tile.height); + const auto sx = (desc.Width - w) / 2; + const auto sy = (desc.Height - h) / 2; + D3D11_BOX box {sx, sy, 0, sx + w, sy + h, 1}; + device_ctx->CopySubresourceRegion(canvas.get(), 0, tile.x + (tile.width - static_cast(w)) / 2, tile.y + (tile.height - static_cast(h)) / 2, 0, tile.waiting.get(), 0, &box); + tile.showing_waiting = true; + } } // namespace platf::dxgi diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 2677dc7bf92..585c9d00f6b 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -1999,7 +1999,7 @@ namespace platf::dxgi { std::vector events; events.reserve(tiles.size()); for (auto &tile : tiles) { - if (!tile.consumer && now >= tile.next_open) { + if (!tile.consumer && tile.session && now >= tile.next_open) { open_tile(tile); } if (tile.consumer) { @@ -2035,6 +2035,11 @@ namespace platf::dxgi { uint64_t newest_qpc = 0; for (auto &tile : tiles) { if (!tile.consumer) { + // Session (re)starting: its waiting image until it publishes again. + if (tile.waiting && !tile.showing_waiting) { + draw_waiting(tile); + updated = true; + } continue; } auto id = tile.consumer->LatestFrameId(); @@ -2072,6 +2077,7 @@ namespace platf::dxgi { // is cropped to its part rather than scaled. D3D11_BOX box {0, 0, 0, std::min(frame.Width, tile.width), std::min(frame.Height, tile.height), 1}; device_ctx->CopySubresourceRegion(canvas.get(), 0, tile.x, tile.y, 0, src.get(), 0, &box); + tile.showing_waiting = false; tile.last_frame = frame.FrameId; newest_qpc = std::max(newest_qpc, frame.QpcPresent); updated = true; diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index f5956e7b6b9..4afc41cc96f 100644 --- a/tests/unit/platform/windows/test_remoteidd.cpp +++ b/tests/unit/platform/windows/test_remoteidd.cpp @@ -375,6 +375,46 @@ TEST(RemoteIddMosaicLayoutTest, ParsesCanvasSessionsAndSkipsBadLines) { EXPECT_EQ(layout.entries[2].cells, 0b1000); } +/** + * @brief A part keeps its place with session 0 while its session restarts, with the waiting + * image path (spaces included) after the part name. + */ +TEST(RemoteIddMosaicLayoutTest, ParsesWaitingImageAndSessionZero) { + auto layout = platf::dxgi::parse_mosaic_layout( + "canvas 3840 2160\n" + "7 Top C:\\Program Files\\OpenStreamMS\\sessions\\x\\osms-wait-0.bgra\n" + "0 Bottom C:\\wait 1.bgra\r\n" + "9 TopLeft\n" // overlaps 7 + ); + ASSERT_EQ(layout.entries.size(), 2u); + EXPECT_EQ(layout.entries[0].session, 7u); + EXPECT_EQ(layout.entries[0].waiting, "C:\\Program Files\\OpenStreamMS\\sessions\\x\\osms-wait-0.bgra"); + EXPECT_EQ(layout.entries[1].session, 0u); + EXPECT_EQ(layout.entries[1].cells, 0b1100); + EXPECT_EQ(layout.entries[1].waiting, "C:\\wait 1.bgra"); + EXPECT_TRUE(platf::dxgi::parse_mosaic_layout("7 Top\n").entries[0].waiting.empty()); +} + +/** + * @brief A waiting image is "OSWP", width, height and exactly width * height BGRA pixels. + */ +TEST(RemoteIddMosaicLayoutTest, ParsesWaitingImage) { + std::string ok = "OSWP"; + ok += std::string("\x02\x00\x00\x00\x01\x00\x00\x00", 8); + ok += std::string("\x01\x02\x03\x04\x05\x06\x07\x08", 8); + auto image = platf::dxgi::parse_waiting_image(ok); + ASSERT_TRUE(image.has_value()); + EXPECT_EQ(image->width, 2); + EXPECT_EQ(image->height, 1); + ASSERT_EQ(image->bgra.size(), 8u); + EXPECT_EQ(image->bgra[7], 8); + + EXPECT_FALSE(platf::dxgi::parse_waiting_image(ok.substr(0, ok.size() - 1)).has_value()); // short + EXPECT_FALSE(platf::dxgi::parse_waiting_image("OSWX" + ok.substr(4)).has_value()); // magic + EXPECT_FALSE(platf::dxgi::parse_waiting_image("OSWP" + std::string(8, '\0')).has_value()); // 0x0 + EXPECT_FALSE(platf::dxgi::parse_waiting_image("").has_value()); +} + /** * @brief Without a valid canvas line the canvas is left to the stream size. */ From ed4a3c8a2e5d080c8fd4a9232d6d0c707fc6d16d Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:41:21 +0100 Subject: [PATCH 2/2] feat(windows): send a mosaic's mouse and keyboard to another of its sessions OpenStreamMS writes osms-input.txt (session, its part of the canvas and the canvas size) when the user moves the mouse and keyboard of a composite stream to another member. Events go to the OpenStreamMS relay in that session through the pipe osms-input-, only if its server is a SYSTEM process of that session; absolute positions are mapped from its part of the canvas to its desktop. Keys and buttons held in the old session are released on the switch, and input stays in this session while the relay is missing. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/session_input.cpp | 278 +++++++++++++++++- src/platform/windows/session_input.h | 39 +++ .../platform/windows/test_session_input.cpp | 64 ++++ 3 files changed, 372 insertions(+), 9 deletions(-) create mode 100644 tests/unit/platform/windows/test_session_input.cpp diff --git a/src/platform/windows/session_input.cpp b/src/platform/windows/session_input.cpp index 1ea2e432ca7..c79d5b24482 100644 --- a/src/platform/windows/session_input.cpp +++ b/src/platform/windows/session_input.cpp @@ -6,9 +6,15 @@ #include #include #include +#include #include +#include +#include +#include #include +#include #include +#include #include // platform includes @@ -35,7 +41,7 @@ namespace platf::session_input { * * @param inputs Events to inject. */ - void send(std::span inputs) { + void send_local(std::span inputs) { const auto count = static_cast(inputs.size()); if (SendInput(count, inputs.data(), sizeof(INPUT)) == count) { return; @@ -51,6 +57,217 @@ namespace platf::session_input { BOOST_LOG(error) << "Couldn't send session-local input: "sv << GetLastError(); } + DWORD own_session() { + static const DWORD session = [] { + DWORD s = 0; + ProcessIdToSessionId(GetCurrentProcessId(), &s); + return s; + }(); + return session; + } + + // ── Mosaic: mouse and keyboard to another session (osms-input.txt) ───────── + + /** + * @brief Header of each batch sent to the OpenStreamMS input relay: "OSIN" and the event count, + * followed by that many INPUT structures. + */ + constexpr std::uint32_t relay_magic = 0x4E49534F; + + std::mutex redirect_mutex; + std::optional target; ///< nullopt = this session. + std::chrono::steady_clock::time_point next_target_check; + HANDLE relay_pipe = INVALID_HANDLE_VALUE; + DWORD relay_session = 0; + std::chrono::steady_clock::time_point next_relay_connect; + std::vector held; ///< Keys and mouse buttons down, released when the target changes. + + std::filesystem::path target_path() { + return std::filesystem::path(config::sunshine.config_file).parent_path() / "osms-input.txt"; + } + + void close_relay() { + if (relay_pipe != INVALID_HANDLE_VALUE) { + CloseHandle(relay_pipe); + relay_pipe = INVALID_HANDLE_VALUE; + } + } + + /** + * @brief Whether the pipe server is a SYSTEM process of that session (the OpenStreamMS relay): + * any process can create a pipe with that name first and would get the keystrokes. + */ + bool trusted_relay(HANDLE pipe, DWORD session) { + ULONG pid = 0; + DWORD pid_session = 0; + if (!GetNamedPipeServerProcessId(pipe, &pid) || !ProcessIdToSessionId(pid, &pid_session) || pid_session != session) { + return false; + } + HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!process) { + return false; + } + bool system = false; + HANDLE token = nullptr; + if (OpenProcessToken(process, TOKEN_QUERY, &token)) { + alignas(TOKEN_USER) std::array buffer {}; + DWORD length = 0; + if (GetTokenInformation(token, TokenUser, buffer.data(), static_cast(buffer.size()), &length)) { + system = IsWellKnownSid(reinterpret_cast(buffer.data())->User.Sid, WinLocalSystemSid); + } + CloseHandle(token); + } + CloseHandle(process); + return system; + } + + bool connect_relay(DWORD session) { + if (relay_pipe != INVALID_HANDLE_VALUE && relay_session == session) { + return true; + } + close_relay(); + const auto now = std::chrono::steady_clock::now(); + if (now < next_relay_connect) { + return false; + } + next_relay_connect = now + 1s; + + const auto name = L"\\\\.\\pipe\\osms-input-" + std::to_wstring(session); + // Identification only: the relay must not be able to impersonate Sunshine. + HANDLE pipe = CreateFileW(name.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr); + if (pipe == INVALID_HANDLE_VALUE) { + BOOST_LOG(warning) << "No input relay in session "sv << session << " ("sv << GetLastError() << "); mouse and keyboard stay in this session"sv; + return false; + } + if (!trusted_relay(pipe, session)) { + BOOST_LOG(error) << "Input relay of session "sv << session << " is not a SYSTEM process; ignored"sv; + CloseHandle(pipe); + return false; + } + relay_pipe = pipe; + relay_session = session; + BOOST_LOG(info) << "Mouse and keyboard go to session "sv << session; + return true; + } + + /** + * @brief Inject in the target session, or here when there is none (or its relay is not + * running: better here than lost). + */ + void deliver(const std::optional &to, std::span inputs) { + if (inputs.empty()) { + return; + } + if (!to || !connect_relay(to->session)) { + send_local(inputs); + return; + } + std::vector buffer(8 + inputs.size_bytes()); + const std::uint32_t header[] {relay_magic, static_cast(inputs.size())}; + std::memcpy(buffer.data(), header, sizeof(header)); + std::memcpy(buffer.data() + 8, inputs.data(), inputs.size_bytes()); + DWORD written = 0; + if (!WriteFile(relay_pipe, buffer.data(), static_cast(buffer.size()), &written, nullptr) || written != buffer.size()) { + BOOST_LOG(warning) << "Input relay of session "sv << relay_session << " went away ("sv << GetLastError() << ')'; + close_relay(); + send_local(inputs); + } + } + + void track_held(const INPUT &input) { + if (input.type == INPUT_KEYBOARD) { + if (input.ki.dwFlags & KEYEVENTF_UNICODE) { + return; + } + std::erase_if(held, [&](const INPUT &h) { + return h.type == INPUT_KEYBOARD && h.ki.wVk == input.ki.wVk && h.ki.wScan == input.ki.wScan; + }); + if (!(input.ki.dwFlags & KEYEVENTF_KEYUP)) { + held.push_back(input); + } + return; + } + if (input.type != INPUT_MOUSE) { + return; + } + constexpr DWORD downs = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_XDOWN; + constexpr DWORD ups = downs << 1; // every *UP flag is its *DOWN flag shifted once + const DWORD flags = input.mi.dwFlags; + if (flags & (downs | ups)) { + const DWORD down = (flags & downs) | ((flags & ups) >> 1); + std::erase_if(held, [&](const INPUT &h) { + return h.type == INPUT_MOUSE && h.mi.dwFlags == down && h.mi.mouseData == input.mi.mouseData; + }); + if (flags & downs) { + INPUT h {}; + h.type = INPUT_MOUSE; + h.mi.dwFlags = flags & downs; + h.mi.mouseData = input.mi.mouseData; + held.push_back(h); + } + } + } + + /** + * @brief Release what is held in the session that stops receiving input: a Ctrl or a mouse + * button would stay down there. + */ + void release_held(const std::optional &from) { + std::vector releases; + for (auto h : held) { + if (h.type == INPUT_KEYBOARD) { + h.ki.dwFlags |= KEYEVENTF_KEYUP; + } else { + h.mi.dwFlags <<= 1; + } + releases.push_back(h); + } + held.clear(); + deliver(from, releases); + } + + /** + * @brief Target from osms-input.txt, re-read at most every 250 ms. Call with redirect_mutex held. + */ + const std::optional ¤t_target() { + const auto now = std::chrono::steady_clock::now(); + if (now < next_target_check) { + return target; + } + next_target_check = now + 250ms; + + std::optional next; + if (std::ifstream file(target_path(), std::ios::binary); file) { + std::ostringstream content; + content << file.rdbuf(); + next = parse_input_target(content.str()); + } + if (next && next->session == own_session()) { + next.reset(); + } + + const DWORD before = target ? target->session : 0; + const DWORD after = next ? next->session : 0; + if (before != after) { + release_held(target); + if (!next) { + close_relay(); + BOOST_LOG(info) << "Mouse and keyboard back to this session"sv; + } + } + target = next; + return target; + } + + void send(std::span inputs) { + std::scoped_lock lock {redirect_mutex}; + const auto &to = current_target(); + for (const auto &input : inputs) { + track_held(input); + } + deliver(to, inputs); + } + void send(INPUT input) { std::array inputs {input}; send(std::span {inputs}); @@ -117,22 +334,50 @@ namespace platf::session_input { } } // namespace - bool should_use() { - static const DWORD own_session = [] { - DWORD session = 0; - ProcessIdToSessionId(GetCurrentProcessId(), &session); - return session; - }(); + std::optional parse_input_target(const std::string &text) { + std::istringstream lines(text); + std::string line; + while (std::getline(lines, line)) { + if (line.empty() || line[0] == '#' || line.find_first_not_of(" \t\r") == std::string::npos) { + continue; + } + std::istringstream fields(line); + long long session = 0; + input_target_t t; + if (!(fields >> session >> t.x >> t.y >> t.width >> t.height >> t.canvas_width >> t.canvas_height) || + session <= 0 || session > std::numeric_limits::max() || + t.x < 0 || t.y < 0 || t.width <= 0 || t.height <= 0 || + t.x + t.width > t.canvas_width || t.y + t.height > t.canvas_height) { + return std::nullopt; + } + t.session = static_cast(session); + return t; + } + return std::nullopt; + } + + std::pair map_to_target(const input_target_t &target, float canvas_fx, float canvas_fy) { + const auto axis = [](float fraction, int canvas, int start, int length) { + const float pixel = std::clamp(fraction, 0.0F, 1.0F) * static_cast(canvas); + const float inside = std::clamp((pixel - static_cast(start)) / static_cast(length), 0.0F, 1.0F); + return static_cast(std::lround(inside * static_cast(std::numeric_limits::max()))); + }; + return { + axis(canvas_fx, target.canvas_width, target.x, target.width), + axis(canvas_fy, target.canvas_height, target.y, target.height), + }; + } + bool should_use() { // The console can move between sessions while streaming (e.g. someone logs // in locally), so compare on every event. 0xFFFFFFFF means "no console // session right now": SendInput is still the right choice then. - const bool bypass = WTSGetActiveConsoleSessionId() != own_session; + const bool bypass = WTSGetActiveConsoleSessionId() != own_session(); static std::atomic logged {-1}; if (const int state = bypass ? 1 : 0; logged.exchange(state) != state) { if (bypass) { - BOOST_LOG(info) << "Sunshine runs outside the console session ("sv << own_session + BOOST_LOG(info) << "Sunshine runs outside the console session ("sv << own_session() << "): mouse and keyboard use SendInput instead of Virtual HID devices"sv; } else { BOOST_LOG(info) << "Sunshine runs in the console session: mouse and keyboard use libvirtualhid"sv; @@ -154,6 +399,21 @@ namespace platf::session_input { const int viewport_w = has_logical ? touch_port.logical_width : touch_port.width; const int viewport_h = has_logical ? touch_port.logical_height : touch_port.height; + // Mouse and keyboard moved to another session of the mosaic: the client points at the + // canvas and that session's desktop is its part of it. + std::optional to; + { + std::scoped_lock lock {redirect_mutex}; + to = current_target(); + } + if (to && viewport_w > 0 && viewport_h > 0) { + const auto fx = (x - static_cast(viewport_x)) / static_cast(viewport_w); + const auto fy = (y - static_cast(viewport_y)) / static_cast(viewport_h); + const auto [tx, ty] = map_to_target(*to, fx, fy); + send(mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK, tx, ty)); + return; + } + const auto dx = scale_to_desktop(x - static_cast(viewport_x), viewport_x, viewport_w, touch_port.env_offset_x, touch_port.width); const auto dy = scale_to_desktop(y - static_cast(viewport_y), viewport_y, viewport_h, touch_port.env_offset_y, touch_port.height); send(mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK, dx, dy)); diff --git a/src/platform/windows/session_input.h b/src/platform/windows/session_input.h index c3444153fbb..3cf2813445b 100644 --- a/src/platform/windows/session_input.h +++ b/src/platform/windows/session_input.h @@ -14,11 +14,50 @@ // standard includes #include +#include +#include // local includes #include "src/platform/common.h" namespace platf::session_input { + /** + * @brief Session that receives the mouse and keyboard of a mosaic stream. + * + * OpenStreamMS writes osms-input.txt next to sunshine.conf when the user moves the mouse + * and keyboard of a composite stream to another of its sessions (from the HUD). Events + * then go to an OpenStreamMS relay in that session (named pipe osms-input-, owned + * by SYSTEM) instead of this one; absolute mouse positions are mapped from the session's + * part of the canvas to its desktop. + */ + struct input_target_t { + std::uint32_t session = 0; ///< Terminal Services session id. + int x = 0; ///< Left edge of its part of the canvas. + int y = 0; ///< Top edge of its part of the canvas. + int width = 0; ///< Width of its part. + int height = 0; ///< Height of its part. + int canvas_width = 0; ///< Canvas width. + int canvas_height = 0; ///< Canvas height. + }; + + /** + * @brief Parse osms-input.txt: " ". + * + * @param text File content; lines starting with # are comments. + * @return The target, or nullopt when the content is not valid. + */ + std::optional parse_input_target(const std::string &text); + + /** + * @brief Map a position on the canvas (0..1) to the 0..65535 range of the target's desktop. + * + * @param target Target session and its part of the canvas. + * @param canvas_fx Horizontal position on the whole canvas, 0..1. + * @param canvas_fy Vertical position on the whole canvas, 0..1. + * @return Absolute coordinates for MOUSEEVENTF_ABSOLUTE, clamped to the target's part. + */ + std::pair map_to_target(const input_target_t &target, float canvas_fx, float canvas_fy); + /** * @brief Whether mouse and keyboard must bypass driver-backed HID devices. * diff --git a/tests/unit/platform/windows/test_session_input.cpp b/tests/unit/platform/windows/test_session_input.cpp new file mode 100644 index 00000000000..cf9015dd310 --- /dev/null +++ b/tests/unit/platform/windows/test_session_input.cpp @@ -0,0 +1,64 @@ +/** + * @file tests/unit/platform/windows/test_session_input.cpp + * @brief Tests for moving the mouse and keyboard of a mosaic stream to another session. + */ + +// test includes +#include "../../../tests_common.h" + +#ifdef _WIN32 + // standard includes + #include + + // local includes + #include + +using platf::session_input::input_target_t; +using platf::session_input::map_to_target; +using platf::session_input::parse_input_target; + +TEST(SessionInputTargetTest, ParsesSessionAndPart) { + const auto t = parse_input_target("# written by OpenStreamMS\r\n3 960 0 960 1080 1920 1080\r\n"); + ASSERT_TRUE(t.has_value()); + EXPECT_EQ(t->session, 3u); + EXPECT_EQ(t->x, 960); + EXPECT_EQ(t->y, 0); + EXPECT_EQ(t->width, 960); + EXPECT_EQ(t->height, 1080); + EXPECT_EQ(t->canvas_width, 1920); + EXPECT_EQ(t->canvas_height, 1080); +} + +TEST(SessionInputTargetTest, RejectsInvalidContent) { + EXPECT_FALSE(parse_input_target("").has_value()); + EXPECT_FALSE(parse_input_target("3 960 0 960").has_value()); + EXPECT_FALSE(parse_input_target("0 0 0 960 1080 1920 1080").has_value()); + EXPECT_FALSE(parse_input_target("-2 0 0 960 1080 1920 1080").has_value()); + EXPECT_FALSE(parse_input_target("3 0 0 0 1080 1920 1080").has_value()); + EXPECT_FALSE(parse_input_target("3 1000 0 960 1080 1920 1080").has_value()); // outside the canvas +} + +TEST(SessionInputTargetTest, MapsThePartToTheWholeDesktop) { + const input_target_t right {3, 960, 0, 960, 1080, 1920, 1080}; + + auto [x, y] = map_to_target(right, 0.75F, 0.5F); // centre of the right half + EXPECT_NEAR(x, 32768, 40); + EXPECT_NEAR(y, 32768, 40); + + std::tie(x, y) = map_to_target(right, 1.0F, 1.0F); + EXPECT_EQ(x, 65535); + EXPECT_EQ(y, 65535); + + // The left half belongs to another session: the pointer stays on the target's edge. + std::tie(x, y) = map_to_target(right, 0.25F, 0.0F); + EXPECT_EQ(x, 0); + EXPECT_EQ(y, 0); +} + +TEST(SessionInputTargetTest, MapsAQuarter) { + const input_target_t bottom_left {5, 0, 540, 960, 540, 1920, 1080}; + const auto [x, y] = map_to_target(bottom_left, 0.25F, 0.75F); + EXPECT_NEAR(x, 32768, 40); + EXPECT_NEAR(y, 32768, 70); +} +#endif