Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

feat(xbox): sign-in, session API and native WebRTC session (X1)

Veyra Goal Agentb734407818bc
diff --git a/CMakeLists.txt b/CMakeLists.txt
index eb443d40..f2a09337 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -49,6 +49,7 @@ option(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR
"Enable local-only experimental Feature 18 adapter" OFF)
option(VEYRA_ENABLE_REMOTEPLAY "Build PS5 Remote Play with pinned Chiaki source" OFF)
option(VEYRA_ENABLE_MOONLIGHT "Build the Moonlight / Sunshine streaming core (pinned moonlight-common-c)" OFF)
+option(VEYRA_ENABLE_XBOX "Build Xbox home streaming (unofficial; libdatachannel from the vcpkg tree)" OFF)
option(VEYRA_ENABLE_DLSS_SR "Enable public DLSS SR backend" OFF)
option(VEYRA_ENABLE_DLSS_FG "Enable public DLSSG backend" OFF)
option(VEYRA_ENABLE_NVOF "Enable NVIDIA Optical Flow guidance" OFF)
@@ -562,6 +563,13 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_sources PUBLIC veyra_moonlight_protocol veyra_moonlight_common_c PRIVATE Opus::opus)
endif()
+ if(VEYRA_ENABLE_XBOX)
+ set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
+ include(VeyraXbox)
+ target_compile_definitions(veyra_sources PUBLIC VEYRA_ENABLE_XBOX=1)
+ target_link_libraries(veyra_sources PUBLIC veyra_xbox_protocol)
+ endif()
+
add_executable(veyra_source_tests
tests/integration/MediaFileSourceTests.cpp
)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 60f046fe..244273e4 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -595,3 +595,22 @@ License texts: `licenses/moonlight/ENET_MIT.txt`, `licenses/moonlight/NANORS_MIT
The streamed machine runs **Sunshine** (GPL-3.0, https://github.com/LizardByte/Sunshine), which users install
themselves; Veyra neither ships nor downloads it.
+
+## Xbox home streaming (unofficial, 2026-10-01)
+
+The optional `VEYRA_ENABLE_XBOX` build streams from the user's own Xbox console. It is **not affiliated with or
+endorsed by Microsoft**; it signs in with the client identity of xbox.com's web player, as the open-source clients do.
+
+The sign-in sequence (`src/xbox/Account.cpp`), the session API (`src/xbox/StreamApi.cpp`) and the data-channel
+protocol (`src/xbox/WebRtcSession.cpp`, `include/veyra/xbox/Protocol.h`) are ports of **Greenlight**
+(MIT, https://github.com/unknownskl/greenlight, commit `58e832a1b1e4bf6b5119a2c84df06ae5e5534993`,
+`packages/player` and `packages/desktop/main/helpers`) and of **xal-node** (MIT, https://github.com/unknownskl/xal-node,
+commit `a17a526b1d00e8456251908324ad51c9b24faa1a`, `src/msal.ts`). Nothing from either tree is compiled.
+
+Linked from the vcpkg tree (pins in `scripts/xbox/dependency-lock.json`):
+**libdatachannel** 0.24.5 (MPL-2.0, https://github.com/paullouisageneau/libdatachannel),
+**libjuice** 1.7.2 (MPL-2.0, https://github.com/paullouisageneau/libjuice; built with the one-line patch
+`scripts/xbox/vcpkg-overlay/libjuice/ipv4-interrupt.diff`, whose source is published there),
+**usrsctp** 0.9.5.0 (BSD-3-Clause), **libsrtp** 2.8.0 (BSD-3-Clause), **plog** 1.1.11 (MIT) and
+**nlohmann/json** 3.12.0 (MIT). MPL-2.0 is file-level copyleft and compatible with GPL-3.0; the MPL sources used are
+the published upstream releases plus the patch above. License texts: `licenses/xbox/`.
diff --git a/cmake/VeyraXbox.cmake b/cmake/VeyraXbox.cmake
new file mode 100644
index 00000000..54bee66b
--- /dev/null
+++ b/cmake/VeyraXbox.cmake
@@ -0,0 +1,29 @@
+include_guard(GLOBAL)
+# Xbox home streaming (unofficial): sign-in, the streaming session API and a native WebRTC session.
+#
+# veyra_xbox_protocol WinHTTP + nlohmann-json for the services, libdatachannel (MPL-2.0) for WebRTC.
+#
+# libdatachannel, libjuice, usrsctp, libsrtp and plog come from the vcpkg tree on CMAKE_PREFIX_PATH
+# (x64-windows-static, the same OpenSSL as the rest of the build). Nothing is downloaded here.
+find_package(LibDataChannel CONFIG REQUIRED)
+find_package(nlohmann_json CONFIG REQUIRED)
+
+add_library(veyra_xbox_protocol STATIC
+ "${VEYRA_ROOT}/src/xbox/Https.cpp"
+ "${VEYRA_ROOT}/src/xbox/Account.cpp"
+ "${VEYRA_ROOT}/src/xbox/StreamApi.cpp"
+ "${VEYRA_ROOT}/src/xbox/WebRtcSession.cpp")
+target_compile_features(veyra_xbox_protocol PUBLIC cxx_std_20)
+set_target_properties(veyra_xbox_protocol PROPERTIES CXX_EXTENSIONS OFF)
+target_compile_definitions(veyra_xbox_protocol PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+target_include_directories(veyra_xbox_protocol PUBLIC "${VEYRA_ROOT}/include")
+target_link_libraries(veyra_xbox_protocol
+ PUBLIC LibDataChannel::LibDataChannel nlohmann_json::nlohmann_json veyra_base
+ PRIVATE winhttp crypt32 shell32 ole32 ws2_32)
+veyra_apply_warnings(veyra_xbox_protocol)
+
+add_executable(veyra_xbox_tests "${VEYRA_ROOT}/tests/xbox/XboxTests.cpp")
+target_compile_features(veyra_xbox_tests PRIVATE cxx_std_20)
+target_compile_definitions(veyra_xbox_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+target_link_libraries(veyra_xbox_tests PRIVATE veyra_xbox_protocol)
+veyra_apply_warnings(veyra_xbox_tests)
diff --git a/include/veyra/xbox/Account.h b/include/veyra/xbox/Account.h
new file mode 100644
index 00000000..3952dad0
--- /dev/null
+++ b/include/veyra/xbox/Account.h
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Signing in to Xbox for home streaming, the way Greenlight does it (unknownskl/greenlight, MIT, via
+// xal-node's MSAL flow): a Microsoft device-code sign-in with the xbox.com web client id, then Xbox Live
+// user and XSTS tokens, then a streaming token for the "xhome" offering. The user signs in on Microsoft's
+// own page (microsoft.com/link); this program never sees the password. Only the refresh token is kept,
+// DPAPI-protected, under %LOCALAPPDATA%\Veyra\xbox.
+//
+// Unofficial: the client id is Microsoft's, borrowed as every open-source client does; Microsoft can
+// change or block this at any time.
+#pragma once
+#include <atomic>
+#include <cstdint>
+#include <filesystem>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "veyra/xbox/Https.h"
+
+namespace veyra::xbox {
+
+inline constexpr const char* kMsalClientId = "1f907974-e22b-4810-a9de-d9647380c97e";
+
+struct DeviceCode {
+ std::string userCode; // shown to the user
+ std::string deviceCode; // secret, polled with
+ std::string verificationUri; // https://www.microsoft.com/link
+ int expiresInSeconds = 900;
+ int intervalSeconds = 5;
+};
+
+enum class SignInPoll { Pending, SlowDown, Done, Expired, Declined, Failed };
+
+struct StreamingAccess {
+ std::string host; // region host of the xhome offering, without scheme
+ std::string gsToken; // bearer token for the streaming API
+ std::string regionName;
+ int64_t expiresAt = 0; // unix seconds
+};
+
+// The persisted part of a sign-in.
+struct SavedTokens {
+ std::string refreshToken;
+ std::string accessToken;
+ int64_t accessExpiresAt = 0;
+ std::string userHash; // uhs, for display / diagnostics only
+};
+
+std::filesystem::path dataDirectory(); // %LOCALAPPDATA%\Veyra\xbox (VEYRA_XBOX_DATA overrides, for tests)
+std::optional<SavedTokens> loadTokens(const std::filesystem::path& file);
+bool saveTokens(const std::filesystem::path& file, const SavedTokens& tokens);
+
+// The XErr codes Xbox Live answers sign-in problems with, as a sentence for the user (empty if unknown).
+std::wstring describeXboxError(const std::string& responseBody);
+
+class Account {
+public:
+ Account(std::shared_ptr<HttpsTransport> transport, std::filesystem::path tokenFile);
+
+ bool signedIn() const;
+ void signOut();
+
+ // Device-code sign-in: show userCode and verificationUri, then poll every intervalSeconds.
+ DeviceCode beginSignIn();
+ SignInPoll pollSignIn(const DeviceCode& code, std::string* detail = nullptr);
+
+ // A streaming token for the home (console) offering. Refreshes everything that has expired.
+ // Throws ServiceError / NetworkError / std::runtime_error.
+ StreamingAccess streamingAccess();
+ // The token the session's /connect step wants (MSAL "console transfer" token).
+ std::string transferToken();
+
+ // Clock injection for tests (unix seconds).
+ void setClock(std::function<int64_t()> clock) { clock_ = std::move(clock); }
+
+private:
+ std::string userAccessToken();
+ std::string xstsUserToken();
+ void store();
+
+ std::shared_ptr<HttpsTransport> http_;
+ std::filesystem::path file_;
+ mutable std::mutex mutex_;
+ std::optional<SavedTokens> tokens_;
+ std::string userToken_; // user.auth.xboxlive.com
+ int64_t userTokenExpiresAt_ = 0;
+ std::optional<StreamingAccess> streaming_;
+ std::function<int64_t()> clock_;
+};
+
+} // namespace veyra::xbox
diff --git a/include/veyra/xbox/Https.h b/include/veyra/xbox/Https.h
new file mode 100644
index 00000000..dded9517
--- /dev/null
+++ b/include/veyra/xbox/Https.h
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// HTTPS for the Xbox streaming services: Microsoft sign-in, Xbox Live token services and the
+// game-streaming (gssv) endpoints. All of them are ordinary public HTTPS, so the Windows HTTP stack
+// (WinHTTP) does the TLS and certificate checks with the system's roots and proxy settings.
+// The transport is an interface so the sign-in and session logic can be tested with scripted replies.
+#pragma once
+#include <atomic>
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+namespace veyra::xbox {
+
+struct HttpsRequest {
+ std::string method = "GET";
+ std::string host; // "login.microsoftonline.com"
+ std::string path; // "/consumers/oauth2/v2.0/devicecode"
+ std::map<std::string, std::string> headers;
+ std::string body;
+ int timeoutMs = 15000;
+};
+
+struct HttpsResponse {
+ int status = 0;
+ std::string body;
+};
+
+struct NetworkError : std::runtime_error {
+ explicit NetworkError(const std::string& message) : std::runtime_error(message) {}
+};
+
+// A non-2xx answer from a service; `body` is kept for the error details the services send.
+struct ServiceError : std::runtime_error {
+ int status;
+ std::string body;
+ ServiceError(int code, std::string text, const std::string& what)
+ : std::runtime_error(what), status(code), body(std::move(text)) {}
+};
+
+class HttpsTransport {
+public:
+ virtual ~HttpsTransport() = default;
+ // Throws NetworkError for connection/TLS/timeout failures; any HTTP status is returned.
+ virtual HttpsResponse send(const HttpsRequest& request) = 0;
+};
+
+// WinHTTP implementation. `cancel`, when set, aborts between steps of a request.
+std::shared_ptr<HttpsTransport> makeWinHttpTransport(const std::atomic<bool>* cancel = nullptr);
+
+// Form-urlencodes one value.
+std::string urlEncode(const std::string& text);
+
+} // namespace veyra::xbox
diff --git a/include/veyra/xbox/Protocol.h b/include/veyra/xbox/Protocol.h
new file mode 100644
index 00000000..57380363
--- /dev/null
+++ b/include/veyra/xbox/Protocol.h
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// The data-channel protocol of Xbox home streaming, as Greenlight's player speaks it
+// (unknownskl/greenlight packages/player, MIT): the JSON handshake and messages on "message" and
+// "control", and the little-endian binary reports on "input". Pure functions only, tested offline.
+#pragma once
+#include <cstdint>
+#include <cstring>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "veyra/remoteplay/Types.h"
+
+namespace veyra::xbox {
+
+enum ReportType : uint16_t {
+ ReportMetadata = 1, ReportGamepad = 2, ReportPointer = 4, ReportClientMetadata = 8, ReportServerMetadata = 16,
+ ReportMouse = 32, ReportKeyboard = 64, ReportVibration = 128,
+};
+
+// Gamepad buttons as the input report carries them.
+enum GamepadButton : uint16_t {
+ BtnNexus = 2, BtnMenu = 4, BtnView = 8, BtnA = 16, BtnB = 32, BtnX = 64, BtnY = 128,
+ BtnUp = 256, BtnDown = 512, BtnLeft = 1024, BtnRight = 2048,
+ BtnLeftShoulder = 4096, BtnRightShoulder = 8192, BtnLeftThumb = 16384, BtnRightThumb = 32768,
+};
+
+struct GamepadFrame {
+ uint8_t index = 0;
+ uint16_t buttons = 0;
+ int16_t leftX = 0, leftY = 0, rightX = 0, rightY = 0; // up is positive (the report's convention)
+ uint16_t leftTrigger = 0, rightTrigger = 0; // 0..65535
+ bool operator==(const GamepadFrame&) const = default;
+};
+
+struct Vibration {
+ uint8_t gamepad = 0;
+ uint8_t leftMotor = 0, rightMotor = 0, leftTrigger = 0, rightTrigger = 0; // percent 0..100
+ uint16_t durationMs = 0, delayMs = 0;
+ uint8_t repeat = 0;
+};
+
+namespace detail {
+inline void put16(std::vector<uint8_t>& b, size_t at, uint16_t v) { b[at] = uint8_t(v); b[at + 1] = uint8_t(v >> 8); }
+inline void put32(std::vector<uint8_t>& b, size_t at, uint32_t v) { for (int i = 0; i < 4; ++i) b[at + size_t(i)] = uint8_t(v >> (8 * i)); }
+inline void putDouble(std::vector<uint8_t>& b, size_t at, double v) { uint64_t u; std::memcpy(&u, &v, 8); for (int i = 0; i < 8; ++i) b[at + size_t(i)] = uint8_t(u >> (8 * i)); }
+inline uint16_t get16(const uint8_t* p) { return uint16_t(p[0] | (p[1] << 8)); }
+inline uint32_t get32(const uint8_t* p) { return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); }
+}
+
+// Header: report type (u16), sequence (u32), timestamp in ms (f64) = 14 bytes.
+inline std::vector<uint8_t> clientMetadataReport(uint32_t sequence, double timeMs, uint8_t maxTouchPoints = 1) {
+ std::vector<uint8_t> b(15, 0);
+ detail::put16(b, 0, ReportClientMetadata);
+ detail::put32(b, 2, sequence);
+ detail::putDouble(b, 6, timeMs);
+ b[14] = maxTouchPoints;
+ return b;
+}
+
+// One report with up to a few gamepads: count (u8), then per pad 23 bytes: index, buttons, 4 axes,
+// 2 triggers, physicality (u32 LE 1) and virtual physicality (u32 written big-endian 1, as the
+// reference client does).
+inline std::vector<uint8_t> gamepadReport(uint32_t sequence, double timeMs, const std::vector<GamepadFrame>& pads) {
+ std::vector<uint8_t> b(14 + 1 + 23 * pads.size(), 0);
+ detail::put16(b, 0, ReportGamepad);
+ detail::put32(b, 2, sequence);
+ detail::putDouble(b, 6, timeMs);
+ size_t at = 14;
+ b[at++] = uint8_t(pads.size());
+ for (const auto& p : pads) {
+ b[at++] = p.index;
+ detail::put16(b, at, p.buttons);
+ detail::put16(b, at + 2, uint16_t(p.leftX));
+ detail::put16(b, at + 4, uint16_t(p.leftY));
+ detail::put16(b, at + 6, uint16_t(p.rightX));
+ detail::put16(b, at + 8, uint16_t(p.rightY));
+ detail::put16(b, at + 10, p.leftTrigger);
+ detail::put16(b, at + 12, p.rightTrigger);
+ detail::put32(b, at + 14, 1);
+ b[at + 18] = 0; b[at + 19] = 0; b[at + 20] = 0; b[at + 21] = 1; // big-endian 1
+ at += 22;
+ }
+ return b;
+}
+
+// SDL state (down-positive sticks, 0..255 triggers) to the report's frame.
+inline GamepadFrame gamepadFromController(const remoteplay::ControllerState& s, uint8_t index = 0) {
+ GamepadFrame f;
+ f.index = index;
+ if (!s.inputActive) return f;
+ using B = remoteplay::ControllerState;
+ struct Pair { uint32_t from; uint16_t to; };
+ static constexpr Pair map[] = {
+ {B::Cross, BtnA}, {B::Circle, BtnB}, {B::Square, BtnX}, {B::Triangle, BtnY},
+ {B::Up, BtnUp}, {B::Down, BtnDown}, {B::Left, BtnLeft}, {B::Right, BtnRight},
+ {B::L1, BtnLeftShoulder}, {B::R1, BtnRightShoulder}, {B::L3, BtnLeftThumb}, {B::R3, BtnRightThumb},
+ {B::Options, BtnMenu}, {B::Share, BtnView}, {B::PS, BtnNexus},
+ };
+ for (const auto& m : map) if (s.buttons & m.from) f.buttons = uint16_t(f.buttons | m.to);
+ const auto flip = [](int16_t v) { return v == INT16_MIN ? int16_t(INT16_MAX) : int16_t(-v); };
+ const auto clamp = [](int16_t v) { return v < -32767 ? int16_t(-32767) : v; };
+ f.leftX = clamp(s.leftX);
+ f.leftY = flip(s.leftY);
+ f.rightX = clamp(s.rightX);
+ f.rightY = flip(s.rightY);
+ f.leftTrigger = uint16_t(s.l2 * 257u);
+ f.rightTrigger = uint16_t(s.r2 * 257u);
+ return f;
+}
+
+inline std::optional<Vibration> parseVibration(const uint8_t* p, size_t n) {
+ if (n < 13 || p[0] != ReportVibration) return std::nullopt;
+ Vibration v;
+ v.gamepad = p[3];
+ v.leftMotor = p[4]; v.rightMotor = p[5]; v.leftTrigger = p[6]; v.rightTrigger = p[7];
+ v.durationMs = detail::get16(p + 8);
+ v.delayMs = detail::get16(p + 10);
+ v.repeat = p[12];
+ return v;
+}
+
+// Server metadata: height then width (u32 LE each) after the 2-byte header.
+inline bool parseServerMetadata(const uint8_t* p, size_t n, uint32_t* width, uint32_t* height) {
+ if (n < 10 || p[0] != ReportServerMetadata) return false;
+ *height = detail::get32(p + 2);
+ *width = detail::get32(p + 6);
+ return true;
+}
+
+} // namespace veyra::xbox
diff --git a/include/veyra/xbox/StreamApi.h b/include/veyra/xbox/StreamApi.h
new file mode 100644
index 00000000..cfebac43
--- /dev/null
+++ b/include/veyra/xbox/StreamApi.h
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// The Xbox home-streaming (xHome) session API on the region host the streaming sign-in returned.
+// Ported from Greenlight (unknownskl/greenlight, MIT): xcloudapi.ts and streammanager.ts. The signalling
+// goes through Microsoft's servers even when the console is on the same network; the media then flows
+// over WebRTC (see XboxSessionSource).
+#pragma once
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "veyra/xbox/Https.h"
+
+namespace veyra::xbox {
+
+struct Console {
+ std::string serverId; // "F4001234ABCD5678"
+ std::string name;
+ std::string powerState; // "On", "ConnectedStandby", "Off" ...
+ std::string consoleType; // "XboxSeriesX", "XboxOne" ...
+ bool outOfHomeWarning = false;
+};
+
+struct SessionState {
+ std::string state; // Provisioning, ReadyToConnect, Provisioned, WaitingForResources, Failed
+ std::string errorCode, errorMessage;
+};
+
+struct IceCandidate {
+ std::string candidate; // "a=candidate:..." as the service sends it
+ std::string sdpMid;
+ int sdpMLineIndex = 0;
+};
+
+class StreamApi {
+public:
+ StreamApi(std::shared_ptr<HttpsTransport> transport, std::string host, std::string gsToken);
+
+ std::vector<Console> consoles();
+ // Starts a session on a console; returns the session id.
+ std::string play(const std::string& serverId, const std::string& locale = "zh-CN");
+ SessionState state(const std::string& sessionId);
+ void connect(const std::string& sessionId, const std::string& transferToken);
+ // Sends the local offer, returns the console's answer SDP.
+ std::string exchangeSdp(const std::string& sessionId, const std::string& offerSdp);
+ // Sends local candidates, returns the console's (plus the IPv4 ones hidden in Teredo addresses).
+ std::vector<IceCandidate> exchangeIce(const std::string& sessionId, const std::vector<IceCandidate>& local);
+ void keepalive(const std::string& sessionId);
+ void stop(const std::string& sessionId);
+
+ // Exposed for tests.
+ static std::vector<Console> parseConsoles(const std::string& body);
+ static std::vector<IceCandidate> parseIce(const std::string& exchangeResponse);
+ // A Teredo address (2001:0:...) carries the client's public IPv4 and port, obfuscated.
+ static bool teredoIpv4(const std::string& ipv6, std::string* ipv4, int* port);
+
+ void setRetryDelayMs(int ms) { retryDelayMs_ = ms; }
+
+private:
+ HttpsResponse call(const std::string& method, const std::string& path, const std::string& body,
+ const std::map<std::string, std::string>& extraHeaders = {});
+ std::string getExchange(const std::string& path);
+
+ std::shared_ptr<HttpsTransport> http_;
+ std::string host_, token_;
+ int retryDelayMs_ = 750;
+};
+
+} // namespace veyra::xbox
diff --git a/include/veyra/xbox/WebRtcSession.h b/include/veyra/xbox/WebRtcSession.h
new file mode 100644
index 00000000..652886ee
--- /dev/null
+++ b/include/veyra/xbox/WebRtcSession.h
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// The media side of an Xbox home stream, natively with libdatachannel (no browser): one Opus audio
+// track, one H.264 video track (received as Annex-B access units for the shared hardware decoder) and the
+// four data channels the console expects (chat, control, input, message). The signalling is an interface,
+// so a test can connect two local peers; the real one goes through StreamApi.
+#pragma once
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+#include "veyra/xbox/Protocol.h"
+#include "veyra/xbox/StreamApi.h"
+
+namespace rtc {
+class PeerConnection;
+class DataChannel;
+class Track;
+}
+
+namespace veyra::xbox {
+
+class Signaling {
+public:
+ virtual ~Signaling() = default;
+ virtual std::string exchangeSdp(const std::string& offerSdp) = 0;
+ virtual std::vector<IceCandidate> exchangeIce(const std::vector<IceCandidate>& local) = 0;
+};
+
+struct WebRtcCallbacks {
+ // One access unit, Annex-B, with the RTP timestamp (90 kHz) and the local arrival time (100 ns ticks).
+ std::function<void(std::vector<uint8_t>&& unit, uint32_t rtpTimestamp, int64_t arrival100ns)> video;
+ // One Opus packet, 48 kHz timestamp.
+ std::function<void(const uint8_t* data, size_t size, uint32_t rtpTimestamp)> audio;
+ std::function<void(const Vibration&)> vibration;
+ std::function<void(uint32_t width, uint32_t height)> serverVideoSize;
+ // The console ended the stream (serverInitiatedDisconnect) or the connection dropped.
+ std::function<void(const std::string& reason)> ended;
+};
+
+struct WebRtcStats {
+ uint64_t bytesReceived = 0; // data channels (libdatachannel's count)
+ uint64_t videoBytes = 0; // access units handed to the decoder
+ uint64_t videoUnits = 0, audioPackets = 0, keyframeRequests = 0;
+ double rttMs = 0;
+ bool handshakeDone = false;
+};
+
+class WebRtcSession {
+public:
+ WebRtcSession();
+ ~WebRtcSession();
+ WebRtcSession(const WebRtcSession&) = delete;
+ WebRtcSession& operator=(const WebRtcSession&) = delete;
+
+ void setCallbacks(WebRtcCallbacks callbacks) { callbacks_ = std::move(callbacks); }
+ // Tests: gather candidates on this address only (e.g. "127.0.0.1"). Empty: every interface.
+ void setBindAddress(std::string address) { bindAddress_ = std::move(address); }
+
+ // Offer, signalling, ICE; returns once connected, false (with `error`) on failure or timeout.
+ bool start(Signaling& signaling, std::string* error, std::chrono::milliseconds timeout = std::chrono::seconds(20));
+ // True once the console acknowledged the message-channel handshake (input is accepted from then on).
+ bool ready() const { return handshakeDone_.load(); }
+ bool waitReady(std::chrono::milliseconds timeout);
+
+ void sendGamepad(const GamepadFrame& frame); // sent when it changes, and at least every 33 ms by the caller
+ void requestKeyframe();
+ void close();
+
+ WebRtcStats stats() const;
+
+ // The SDP offer this session would send (built without connecting), for tests and diagnostics.
+ static std::string describeCodecs(const std::string& sdp);
+
+private:
+ void onMessageChannel(const std::string& text);
+ void onInputChannel(const uint8_t* data, size_t size);
+ void sendMessageJson(const std::string& text);
+ void sendClientConfig();
+ double nowMs() const;
+
+ WebRtcCallbacks callbacks_;
+ std::shared_ptr<rtc::PeerConnection> pc_;
+ std::shared_ptr<rtc::Track> audio_, video_;
+ std::shared_ptr<rtc::DataChannel> chat_, control_, input_, message_;
+ std::mutex mutex_;
+ std::condition_variable changed_;
+ std::atomic<bool> connected_{false}, failed_{false}, closed_{false}, handshakeDone_{false}, handshakeSent_{false};
+ std::atomic<uint32_t> inputSequence_{0};
+ std::atomic<uint64_t> videoUnits_{0}, audioPackets_{0}, keyframeRequests_{0}, videoBytes_{0};
+ std::chrono::steady_clock::time_point origin_ = std::chrono::steady_clock::now();
+ std::string failure_;
+ std::string bindAddress_;
+};
+
+} // namespace veyra::xbox
diff --git a/licenses/xbox/greenlight-MIT.txt b/licenses/xbox/greenlight-MIT.txt
new file mode 100644
index 00000000..92583d29
--- /dev/null
+++ b/licenses/xbox/greenlight-MIT.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2019 UnknownSKL (Jim Kroon)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/licenses/xbox/libdatachannel.txt b/licenses/xbox/libdatachannel.txt
new file mode 100644
index 00000000..14e2f777
--- /dev/null
+++ b/licenses/xbox/libdatachannel.txt
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/licenses/xbox/libjuice.txt b/licenses/xbox/libjuice.txt
new file mode 100644
index 00000000..14e2f777
--- /dev/null
+++ b/licenses/xbox/libjuice.txt
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/licenses/xbox/libsrtp.txt b/licenses/xbox/libsrtp.txt
new file mode 100644
index 00000000..af0a2ac3
--- /dev/null
+++ b/licenses/xbox/libsrtp.txt
@@ -0,0 +1,35 @@
+/*
+ *
+ * Copyright (c) 2001-2017 Cisco Systems, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ *
+ * Neither the name of the Cisco Systems, Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
diff --git a/licenses/xbox/nlohmann-json.txt b/licenses/xbox/nlohmann-json.txt
new file mode 100644
index 00000000..a1dacc8d
--- /dev/null
+++ b/licenses/xbox/nlohmann-json.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2013-2025 Niels Lohmann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/licenses/xbox/plog.txt b/licenses/xbox/plog.txt
new file mode 100644
index 00000000..8a91a0ae
--- /dev/null
+++ b/licenses/xbox/plog.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 Sergey Podobry
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/licenses/xbox/usrsctp.txt b/licenses/xbox/usrsctp.txt
new file mode 100644
index 00000000..a2d1f989
--- /dev/null
+++ b/licenses/xbox/usrsctp.txt
@@ -0,0 +1,27 @@
+Copyright (c) 2015, Randall Stewart and Michael Tuexen
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of usrsctp nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/xbox/xal-node-MIT.txt b/licenses/xbox/xal-node-MIT.txt
new file mode 100644
index 00000000..9c4323cd
--- /dev/null
+++ b/licenses/xbox/xal-node-MIT.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2023 UnknownSKL (Jim Kroon)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/scripts/xbox/dependency-lock.json b/scripts/xbox/dependency-lock.json
new file mode 100644
index 00000000..1c11a3d6
--- /dev/null
+++ b/scripts/xbox/dependency-lock.json
@@ -0,0 +1,25 @@
+{
+ "purpose": "Xbox home streaming (unofficial). Protocol ported from Greenlight; WebRTC through libdatachannel built by vcpkg.",
+ "reference_sources": {
+ "greenlight": { "repo": "https://github.com/unknownskl/greenlight", "commit": "58e832a1b1e4bf6b5119a2c84df06ae5e5534993", "license": "MIT", "use": "protocol reference (packages/player, packages/desktop/main/helpers); no code linked" },
+ "xal-node": { "repo": "https://github.com/unknownskl/xal-node", "commit": "a17a526b1d00e8456251908324ad51c9b24faa1a", "license": "MIT", "use": "MSAL device-code sign-in sequence (src/msal.ts); ported, not linked" }
+ },
+ "vcpkg": {
+ "checkout": "C:/veyra-deps/vcpkg",
+ "commit": "30ef65cad98f08e7197c9a1656fbd871bcb72f2d",
+ "triplet": "x64-windows-static",
+ "install_root": "C:/veyra-deps/xbox-installed (a copy of remoteplay-installed plus the packages below; same OpenSSL 3.6.4)",
+ "command": "vcpkg install \"libdatachannel[srtp]:x64-windows-static\" --overlay-ports=scripts/xbox/vcpkg-overlay --x-install-root=C:/veyra-deps/xbox-installed --classic",
+ "packages": {
+ "libdatachannel": { "version": "0.24.5", "license": "MPL-2.0", "features": ["srtp", "ws"] },
+ "libjuice": { "version": "1.7.2", "license": "MPL-2.0", "patched": "scripts/xbox/vcpkg-overlay/libjuice/ipv4-interrupt.diff" },
+ "usrsctp": { "version": "0.9.5.0", "license": "BSD-3-Clause" },
+ "libsrtp": { "version": "2.8.0", "license": "BSD-3-Clause" },
+ "plog": { "version": "1.1.11", "license": "MIT" },
+ "nlohmann-json": { "version": "3.12.0", "license": "MIT" }
+ }
+ },
+ "patches": {
+ "libjuice/ipv4-interrupt.diff": "The poll thread's wake-up socket binds 127.0.0.1 instead of \"localhost\". Where IPv6 loopback drops UDP (seen on the development machine with a VPN/TUN adapter) the wake-up packet to ::1 is lost without an error, and ICE checks wait for the 60 s poll timeout."
+ }
+}
diff --git a/scripts/xbox/vcpkg-overlay/libjuice/dependencies.diff b/scripts/xbox/vcpkg-overlay/libjuice/dependencies.diff
new file mode 100644
index 00000000..f6f7b950
--- /dev/null
+++ b/scripts/xbox/vcpkg-overlay/libjuice/dependencies.diff
@@ -0,0 +1,44 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 5712462..dd6c669 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -120,11 +120,14 @@ if(WIN32)
+ endif()
+
+ if (USE_NETTLE)
+- find_package(Nettle REQUIRED)
++ find_path(NETTLE_INCLUDE_PATH "nettle/hmac.h" REQUIRED)
++ find_library(NETTLE_LIBRARY_PATH NAMES nettle libnettle NAMES_PER_DIR REQUIRED)
++ target_include_directories(juice PRIVATE ${NETTLE_INCLUDE_PATH})
++ target_include_directories(juice-static PRIVATE ${NETTLE_INCLUDE_PATH})
+ target_compile_definitions(juice PRIVATE USE_NETTLE=1)
+- target_link_libraries(juice PRIVATE Nettle::Nettle)
++ target_link_libraries(juice PRIVATE ${NETTLE_LIBRARY_PATH})
+ target_compile_definitions(juice-static PRIVATE USE_NETTLE=1)
+- target_link_libraries(juice-static PRIVATE Nettle::Nettle)
++ target_link_libraries(juice-static PRIVATE ${NETTLE_LIBRARY_PATH})
+ else()
+ target_compile_definitions(juice PRIVATE USE_NETTLE=0)
+ target_compile_definitions(juice-static PRIVATE USE_NETTLE=0)
+@@ -137,8 +140,6 @@ endif()
+
+ if(APPLE)
+ # This seems to be necessary on MacOS
+- target_include_directories(juice PRIVATE /usr/local/include)
+- target_include_directories(juice-static PRIVATE /usr/local/include)
+ endif()
+
+ set_target_properties(juice PROPERTIES EXPORT_NAME LibJuice)
+diff --git a/cmake/LibJuiceConfig.cmake.in b/cmake/LibJuiceConfig.cmake.in
+index 247e53f..f049d9a 100644
+--- a/cmake/LibJuiceConfig.cmake.in
++++ b/cmake/LibJuiceConfig.cmake.in
+@@ -1,4 +1,8 @@
+ @PACKAGE_INIT@
+
++include(CMakeFindDependencyMacro)
++set(THREADS_PREFER_PTHREAD_FLAG ON)
++find_dependency(Threads)
++
+ include("${CMAKE_CURRENT_LIST_DIR}/LibJuiceTargets.cmake")
+
diff --git a/scripts/xbox/vcpkg-overlay/libjuice/ipv4-interrupt.diff b/scripts/xbox/vcpkg-overlay/libjuice/ipv4-interrupt.diff
new file mode 100644
index 00000000..964944df
--- /dev/null
+++ b/scripts/xbox/vcpkg-overlay/libjuice/ipv4-interrupt.diff
@@ -0,0 +1,13 @@
+--- a/src/conn_poll.c
++++ b/src/conn_poll.c
+@@ -77,7 +77,9 @@
+ #ifdef _WIN32
+ udp_socket_config_t interrupt_config;
+ memset(&interrupt_config, 0, sizeof(interrupt_config));
+- interrupt_config.bind_address = "localhost";
++ // Veyra: IPv4 loopback. "localhost" resolves to ::1 first, and where IPv6 loopback drops UDP
++ // (some VPN/TUN set-ups) the wake-up packet vanishes and ICE checks stall for a minute.
++ interrupt_config.bind_address = "127.0.0.1";
+ registry_impl->interrupt_sock = udp_create_socket(&interrupt_config);
+ if (registry_impl->interrupt_sock == INVALID_SOCKET) {
+ JLOG_FATAL("Dummy socket creation failed");
diff --git a/scripts/xbox/vcpkg-overlay/libjuice/portfile.cmake b/scripts/xbox/vcpkg-overlay/libjuice/portfile.cmake
new file mode 100644
index 00000000..794a87ea
--- /dev/null
+++ b/scripts/xbox/vcpkg-overlay/libjuice/portfile.cmake
@@ -0,0 +1,35 @@
+vcpkg_from_github(
+ OUT_SOURCE_PATH SOURCE_PATH
+ REPO paullouisageneau/libjuice
+ REF "v${VERSION}"
+ SHA512 770b7123949a644ab8df01020abb2c8744496e1e486c91292252bb309a8c38239ae2a6c369b4eb0c028f6ac0ea78e5da09922d0ddf8446e50b4eb299cf1dabca
+ HEAD_REF master
+ PATCHES
+ dependencies.diff
+ soversion.diff
+ ipv4-interrupt.diff
+)
+
+vcpkg_check_features(OUT_FEATURE_OPTIONS FEATURE_OPTIONS
+ FEATURES
+ nettle USE_NETTLE
+)
+
+vcpkg_cmake_configure(
+ SOURCE_PATH "${SOURCE_PATH}"
+ OPTIONS
+ ${FEATURE_OPTIONS}
+ -DNO_TESTS=ON
+)
+
+vcpkg_cmake_install()
+vcpkg_cmake_config_fixup(CONFIG_PATH lib/cmake/LibJuice)
+vcpkg_fixup_pkgconfig()
+
+if(VCPKG_LIBRARY_LINKAGE STREQUAL "static")
+ vcpkg_replace_string("${CURRENT_PACKAGES_DIR}/include/juice/juice.h" "#ifndef JUICE_STATIC" "#if 0")
+endif()
+
+file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include")
+
+vcpkg_install_copyright(FILE_LIST "${SOURCE_PATH}/LICENSE")
diff --git a/scripts/xbox/vcpkg-overlay/libjuice/soversion.diff b/scripts/xbox/vcpkg-overlay/libjuice/soversion.diff
new file mode 100644
index 00000000..7d94bdc4
--- /dev/null
+++ b/scripts/xbox/vcpkg-overlay/libjuice/soversion.diff
@@ -0,0 +1,13 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 3b020a9..1f1dd5c 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -97,7 +97,7 @@ set(THREADS_PREFER_PTHREAD_FLAG ON)
+ find_package(Threads REQUIRED)
+
+ add_library(juice ${LIBJUICE_SOURCES})
+-set_target_properties(juice PROPERTIES VERSION ${PROJECT_VERSION})
++set_target_properties(juice PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR})
+ target_include_directories(juice PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:include>)
diff --git a/scripts/xbox/vcpkg-overlay/libjuice/vcpkg.json b/scripts/xbox/vcpkg-overlay/libjuice/vcpkg.json
new file mode 100644
index 00000000..7d0a36ae
--- /dev/null
+++ b/scripts/xbox/vcpkg-overlay/libjuice/vcpkg.json
@@ -0,0 +1,26 @@
+{
+ "name": "libjuice",
+ "version": "1.7.2",
+ "port-version": 1,
+ "description": "The library is a simplified implementation of the Interactive Connectivity Establishment (ICE) protocol in C for POSIX platforms (including Linux and Apple macOS) and Microsoft Windows.",
+ "homepage": "https://github.com/paullouisageneau/libjuice",
+ "license": "MPL-2.0",
+ "dependencies": [
+ {
+ "name": "vcpkg-cmake",
+ "host": true
+ },
+ {
+ "name": "vcpkg-cmake-config",
+ "host": true
+ }
+ ],
+ "features": {
+ "nettle": {
+ "description": "Use nettle for HMAC computation instead of the Builtin",
+ "dependencies": [
+ "nettle"
+ ]
+ }
+ }
+}
diff --git a/src/xbox/Account.cpp b/src/xbox/Account.cpp
new file mode 100644
index 00000000..83466209
--- /dev/null
+++ b/src/xbox/Account.cpp
@@ -0,0 +1,322 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Sign-in sequence ported from xal-node's Msal class (unknownskl/xal-node, MIT) as used by Greenlight.
+#include "veyra/xbox/Account.h"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <wincrypt.h>
+
+#include <chrono>
+#include <cstdio>
+#include <ctime>
+#include <fstream>
+#include <iterator>
+#include <nlohmann/json.hpp>
+
+namespace veyra::xbox {
+namespace {
+
+using json = nlohmann::json;
+
+constexpr const char* kScope = "xboxlive.signin openid profile offline_access";
+
+int64_t systemNow() {
+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+}
+
+// "2026-10-01T12:34:56.1234567Z" -> unix seconds (0 when it does not parse).
+int64_t parseTime(const std::string& text) {
+ std::tm t{};
+ if (sscanf_s(text.c_str(), "%d-%d-%dT%d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return 0;
+ t.tm_year -= 1900;
+ t.tm_mon -= 1;
+ return int64_t(_mkgmtime(&t));
+}
+
+json parse(const HttpsResponse& response, const char* what) {
+ if (response.status < 200 || response.status > 299)
+ throw ServiceError(response.status, response.body, std::string(what) + " returned HTTP " + std::to_string(response.status));
+ try {
+ return json::parse(response.body);
+ } catch (const json::exception&) {
+ throw std::runtime_error(std::string(what) + " returned something that is not JSON");
+ }
+}
+
+std::string form(std::initializer_list<std::pair<const char*, std::string>> fields) {
+ std::string out;
+ for (const auto& [k, v] : fields) {
+ if (!out.empty()) out += '&';
+ out += k;
+ out += '=';
+ out += urlEncode(v);
+ }
+ return out;
+}
+
+HttpsRequest formPost(const char* host, const char* path, std::string body) {
+ HttpsRequest r;
+ r.method = "POST";
+ r.host = host;
+ r.path = path;
+ r.headers["Content-Type"] = "application/x-www-form-urlencoded";
+ r.headers["Cache-Control"] = "no-store, must-revalidate, no-cache";
+ r.body = std::move(body);
+ return r;
+}
+
+HttpsRequest xblPost(const char* host, const char* path, const json& body) {
+ HttpsRequest r;
+ r.method = "POST";
+ r.host = host;
+ r.path = path;
+ r.headers["x-xbl-contract-version"] = "1";
+ r.headers["Cache-Control"] = "no-cache";
+ r.headers["Content-Type"] = "application/json";
+ r.headers["Accept"] = "*/*";
+ r.headers["Origin"] = "https://www.xbox.com";
+ r.headers["Referer"] = "https://www.xbox.com/";
+ r.headers["ms-cv"] = "0";
+ r.body = body.dump();
+ return r;
+}
+
+std::vector<uint8_t> protect(const std::string& plain) {
+ DATA_BLOB in{DWORD(plain.size()), reinterpret_cast<BYTE*>(const_cast<char*>(plain.data()))};
+ DATA_BLOB out{};
+ if (!CryptProtectData(&in, L"Veyra Xbox sign-in", nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &out)) return {};
+ std::vector<uint8_t> bytes(out.pbData, out.pbData + out.cbData);
+ LocalFree(out.pbData);
+ return bytes;
+}
+
+std::optional<std::string> unprotect(std::vector<uint8_t> bytes) {
+ DATA_BLOB in{DWORD(bytes.size()), bytes.data()};
+ DATA_BLOB out{};
+ if (!CryptUnprotectData(&in, nullptr, nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &out)) return std::nullopt;
+ std::string plain(reinterpret_cast<char*>(out.pbData), out.cbData);
+ SecureZeroMemory(out.pbData, out.cbData);
+ LocalFree(out.pbData);
+ return plain;
+}
+
+} // namespace
+
+std::filesystem::path dataDirectory() {
+ wchar_t override[MAX_PATH] = {};
+ if (GetEnvironmentVariableW(L"VEYRA_XBOX_DATA", override, MAX_PATH) > 0) return std::filesystem::path(override);
+ PWSTR raw = nullptr;
+ if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &raw))) throw std::runtime_error("Cannot resolve the user data directory");
+ std::filesystem::path result(raw);
+ CoTaskMemFree(raw);
+ return result / L"Veyra" / L"xbox";
+}
+
+std::optional<SavedTokens> loadTokens(const std::filesystem::path& file) {
+ std::ifstream in(file, std::ios::binary);
+ if (!in) return std::nullopt;
+ std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
+ if (bytes.empty() || bytes.size() > (1u << 20)) return std::nullopt;
+ const auto plain = unprotect(std::move(bytes));
+ if (!plain) return std::nullopt;
+ try {
+ const json j = json::parse(*plain);
+ SavedTokens t;
+ t.refreshToken = j.value("refresh", "");
+ t.accessToken = j.value("access", "");
+ t.accessExpiresAt = j.value("accessExpires", int64_t(0));
+ t.userHash = j.value("uhs", "");
+ if (t.refreshToken.empty()) return std::nullopt;
+ return t;
+ } catch (const json::exception&) {
+ return std::nullopt;
+ }
+}
+
+bool saveTokens(const std::filesystem::path& file, const SavedTokens& tokens) {
+ std::error_code ec;
+ std::filesystem::create_directories(file.parent_path(), ec);
+ std::string plain = json{{"refresh", tokens.refreshToken}, {"access", tokens.accessToken},
+ {"accessExpires", tokens.accessExpiresAt}, {"uhs", tokens.userHash}}.dump();
+ const auto bytes = protect(plain);
+ SecureZeroMemory(plain.data(), plain.size());
+ if (bytes.empty()) return false;
+ const auto temp = std::filesystem::path(file).concat(L".tmp");
+ {
+ std::ofstream out(temp, std::ios::binary | std::ios::trunc);
+ if (!out) return false;
+ out.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()));
+ if (!out) return false;
+ }
+ std::filesystem::rename(temp, file, ec);
+ return !ec;
+}
+
+std::wstring describeXboxError(const std::string& responseBody) {
+ try {
+ const json j = json::parse(responseBody);
+ const uint64_t code = j.value("XErr", uint64_t(0));
+ switch (code) {
+ case 2148916233: return L"这个微软账号还没有 Xbox 档案。请先在 xbox.com 用它登录一次,创建档案后再试。";
+ case 2148916235: return L"这个账号所在的国家或地区不提供 Xbox Live。";
+ case 2148916236: case 2148916237: return L"这个账号需要先在 xbox.com 完成成人验证。";
+ case 2148916238: return L"这是儿童账号,需要家长在家庭组里允许后才能使用。";
+ default: return {};
+ }
+ } catch (const json::exception&) {
+ return {};
+ }
+}
+
+Account::Account(std::shared_ptr<HttpsTransport> transport, std::filesystem::path tokenFile)
+ : http_(std::move(transport)), file_(std::move(tokenFile)), clock_(systemNow) {
+ tokens_ = loadTokens(file_);
+}
+
+bool Account::signedIn() const {
+ std::lock_guard lock(mutex_);
+ return tokens_.has_value();
+}
+
+void Account::signOut() {
+ std::lock_guard lock(mutex_);
+ tokens_.reset();
+ userToken_.clear();
+ streaming_.reset();
+ std::error_code ec;
+ std::filesystem::remove(file_, ec);
+}
+
+void Account::store() {
+ if (tokens_) saveTokens(file_, *tokens_);
+}
+
+DeviceCode Account::beginSignIn() {
+ const json j = parse(http_->send(formPost("login.microsoftonline.com", "/consumers/oauth2/v2.0/devicecode",
+ form({{"client_id", kMsalClientId}, {"scope", kScope}}))), "device code request");
+ DeviceCode code;
+ code.userCode = j.value("user_code", "");
+ code.deviceCode = j.value("device_code", "");
+ code.verificationUri = j.value("verification_uri", "https://www.microsoft.com/link");
+ code.expiresInSeconds = j.value("expires_in", 900);
+ code.intervalSeconds = std::max(1, j.value("interval", 5));
+ if (code.userCode.empty() || code.deviceCode.empty()) throw std::runtime_error("device code request returned no code");
+ return code;
+}
+
+SignInPoll Account::pollSignIn(const DeviceCode& code, std::string* detail) {
+ const HttpsResponse response = http_->send(formPost("login.microsoftonline.com", "/consumers/oauth2/v2.0/token",
+ form({{"grant_type", "urn:ietf:params:oauth:grant-type:device_code"}, {"client_id", kMsalClientId}, {"device_code", code.deviceCode}})));
+ json j;
+ try { j = json::parse(response.body); } catch (const json::exception&) { return SignInPoll::Failed; }
+ if (response.status >= 200 && response.status <= 299) {
+ SavedTokens t;
+ t.refreshToken = j.value("refresh_token", "");
+ t.accessToken = j.value("access_token", "");
+ t.accessExpiresAt = clock_() + j.value("expires_in", 3600);
+ if (t.refreshToken.empty() || t.accessToken.empty()) return SignInPoll::Failed;
+ std::lock_guard lock(mutex_);
+ tokens_ = std::move(t);
+ userToken_.clear();
+ streaming_.reset();
+ store();
+ return SignInPoll::Done;
+ }
+ const std::string error = j.value("error", "");
+ if (detail) *detail = error;
+ if (error == "authorization_pending") return SignInPoll::Pending;
+ if (error == "slow_down") return SignInPoll::SlowDown;
+ if (error == "expired_token" || error == "code_expired") return SignInPoll::Expired;
+ if (error == "authorization_declined" || error == "access_denied") return SignInPoll::Declined;
+ return SignInPoll::Failed;
+}
+
+// Caller holds mutex_.
+std::string Account::userAccessToken() {
+ if (!tokens_) throw std::runtime_error("not signed in");
+ if (!tokens_->accessToken.empty() && tokens_->accessExpiresAt - 60 > clock_()) return tokens_->accessToken;
+ const HttpsResponse response = http_->send(formPost("login.microsoftonline.com", "/consumers/oauth2/v2.0/token",
+ form({{"client_id", kMsalClientId}, {"grant_type", "refresh_token"}, {"refresh_token", tokens_->refreshToken}, {"scope", kScope}})));
+ if (response.status == 400 || response.status == 401) {
+ // The refresh token is no longer accepted (password changed, signed out elsewhere, 90 days unused).
+ tokens_.reset();
+ std::error_code ec;
+ std::filesystem::remove(file_, ec);
+ throw ServiceError(response.status, response.body, "sign-in expired");
+ }
+ const json j = parse(response, "token refresh");
+ tokens_->accessToken = j.value("access_token", "");
+ tokens_->accessExpiresAt = clock_() + j.value("expires_in", 3600);
+ const std::string rotated = j.value("refresh_token", "");
+ if (!rotated.empty()) tokens_->refreshToken = rotated;
+ store();
+ return tokens_->accessToken;
+}
+
+// Caller holds mutex_.
+std::string Account::xstsUserToken() {
+ if (!userToken_.empty() && userTokenExpiresAt_ - 60 > clock_()) return userToken_;
+ const std::string access = userAccessToken();
+ const json body = {{"Properties", {{"AuthMethod", "RPS"}, {"RpsTicket", "d=" + access}, {"SiteName", "user.auth.xboxlive.com"}}},
+ {"RelyingParty", "http://auth.xboxlive.com"}, {"TokenType", "JWT"}};
+ const json j = parse(http_->send(xblPost("user.auth.xboxlive.com", "/user/authenticate", body)), "Xbox Live user authentication");
+ userToken_ = j.value("Token", "");
+ userTokenExpiresAt_ = parseTime(j.value("NotAfter", ""));
+ if (userTokenExpiresAt_ == 0) userTokenExpiresAt_ = clock_() + 3600;
+ try { tokens_->userHash = j.at("DisplayClaims").at("xui").at(0).value("uhs", ""); } catch (const json::exception&) {}
+ if (userToken_.empty()) throw std::runtime_error("Xbox Live user authentication returned no token");
+ return userToken_;
+}
+
+StreamingAccess Account::streamingAccess() {
+ std::lock_guard lock(mutex_);
+ if (streaming_ && streaming_->expiresAt - 120 > clock_()) return *streaming_;
+ const std::string user = xstsUserToken();
+ const json authorize = {{"Properties", {{"SandboxId", "RETAIL"}, {"UserTokens", json::array({user})}}},
+ {"RelyingParty", "http://gssv.xboxlive.com/"}, {"TokenType", "JWT"}};
+ const json xsts = parse(http_->send(xblPost("xsts.auth.xboxlive.com", "/xsts/authorize", authorize)), "Xbox Live authorization");
+ const std::string gssv = xsts.value("Token", "");
+ if (gssv.empty()) throw std::runtime_error("Xbox Live authorization returned no token");
+
+ HttpsRequest request;
+ request.method = "POST";
+ request.host = "xhome.gssv-play-prod.xboxlive.com";
+ request.path = "/v2/login/user";
+ request.headers["Content-Type"] = "application/json";
+ request.headers["Cache-Control"] = "no-store, must-revalidate, no-cache";
+ request.headers["x-gssv-client"] = "XboxComBrowser";
+ request.body = json{{"token", gssv}, {"offeringId", "xhome"}}.dump();
+ const json j = parse(http_->send(request), "streaming sign-in");
+
+ StreamingAccess access;
+ access.gsToken = j.value("gsToken", "");
+ access.expiresAt = clock_() + j.value("durationInSeconds", 3600);
+ try {
+ for (const auto& region : j.at("offeringSettings").at("regions")) {
+ if (!region.value("isDefault", false) && !access.host.empty()) continue;
+ std::string uri = region.value("baseUri", "");
+ if (uri.rfind("https://", 0) == 0) uri = uri.substr(8);
+ while (!uri.empty() && uri.back() == '/') uri.pop_back();
+ access.host = uri;
+ access.regionName = region.value("name", "");
+ if (region.value("isDefault", false)) break;
+ }
+ } catch (const json::exception&) {}
+ if (access.gsToken.empty() || access.host.empty()) throw std::runtime_error("streaming sign-in returned no region or token");
+ streaming_ = access;
+ return access;
+}
+
+std::string Account::transferToken() {
+ std::lock_guard lock(mutex_);
+ if (!tokens_) throw std::runtime_error("not signed in");
+ userAccessToken(); // keeps the refresh token current
+ const json j = parse(http_->send(formPost("login.live.com", "/oauth20_token.srf",
+ form({{"client_id", kMsalClientId}, {"scope", "service::http://Passport.NET/purpose::PURPOSE_XBOX_CLOUD_CONSOLE_TRANSFER_TOKEN"},
+ {"grant_type", "refresh_token"}, {"refresh_token", tokens_->refreshToken}}))), "console transfer token");
+ const std::string token = j.value("access_token", "");
+ if (token.empty()) throw std::runtime_error("console transfer token missing");
+ return token;
+}
+
+} // namespace veyra::xbox
diff --git a/src/xbox/Https.cpp b/src/xbox/Https.cpp
new file mode 100644
index 00000000..ba4638c8
--- /dev/null
+++ b/src/xbox/Https.cpp
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/xbox/Https.h"
+
+#include <windows.h>
+#include <winhttp.h>
+
+#include <vector>
+
+namespace veyra::xbox {
+namespace {
+
+std::wstring widen(const std::string& text) {
+ if (text.empty()) return {};
+ const int length = MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0);
+ std::wstring out(size_t(length), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), out.data(), length);
+ return out;
+}
+
+struct Handle {
+ HINTERNET h = nullptr;
+ Handle() = default;
+ explicit Handle(HINTERNET value) : h(value) {}
+ Handle(const Handle&) = delete;
+ Handle& operator=(const Handle&) = delete;
+ ~Handle() { if (h) WinHttpCloseHandle(h); }
+ explicit operator bool() const { return h != nullptr; }
+};
+
+std::string lastError(const char* step) {
+ return std::string(step) + " failed (WinHTTP error " + std::to_string(GetLastError()) + ")";
+}
+
+class WinHttpTransport final : public HttpsTransport {
+public:
+ explicit WinHttpTransport(const std::atomic<bool>* cancel) : cancel_(cancel) {
+ session_.h = WinHttpOpen(L"Veyra/2.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ if (!session_) session_.h = WinHttpOpen(L"Veyra/2.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ if (session_) {
+ DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3;
+ if (!WinHttpSetOption(session_.h, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols))) {
+ protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; // older Windows without TLS 1.3 in WinHTTP
+ WinHttpSetOption(session_.h, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols));
+ }
+ }
+ }
+
+ HttpsResponse send(const HttpsRequest& request) override {
+ if (!session_) throw NetworkError(lastError("WinHttpOpen"));
+ checkCancel();
+ Handle connection(WinHttpConnect(session_.h, widen(request.host).c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0));
+ if (!connection) throw NetworkError(lastError("WinHttpConnect"));
+ Handle handle(WinHttpOpenRequest(connection.h, widen(request.method).c_str(), widen(request.path).c_str(), nullptr,
+ WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE));
+ if (!handle) throw NetworkError(lastError("WinHttpOpenRequest"));
+ const int t = request.timeoutMs;
+ WinHttpSetTimeouts(handle.h, t, t, t, t);
+ std::wstring headers;
+ for (const auto& [name, value] : request.headers) headers += widen(name) + L": " + widen(value) + L"\r\n";
+ const BOOL sent = WinHttpSendRequest(handle.h, headers.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : headers.c_str(),
+ headers.empty() ? 0 : DWORD(-1),
+ request.body.empty() ? WINHTTP_NO_REQUEST_DATA : const_cast<char*>(request.body.data()),
+ DWORD(request.body.size()), DWORD(request.body.size()), 0);
+ if (!sent) throw NetworkError(lastError("WinHttpSendRequest"));
+ checkCancel();
+ if (!WinHttpReceiveResponse(handle.h, nullptr)) throw NetworkError(lastError("WinHttpReceiveResponse"));
+ HttpsResponse response;
+ DWORD status = 0, size = sizeof(status);
+ WinHttpQueryHeaders(handle.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX);
+ response.status = int(status);
+ for (;;) {
+ checkCancel();
+ DWORD available = 0;
+ if (!WinHttpQueryDataAvailable(handle.h, &available)) throw NetworkError(lastError("WinHttpQueryDataAvailable"));
+ if (available == 0) break;
+ if (response.body.size() + available > (16u << 20)) throw NetworkError("response larger than 16 MB");
+ std::vector<char> chunk(available);
+ DWORD read = 0;
+ if (!WinHttpReadData(handle.h, chunk.data(), available, &read)) throw NetworkError(lastError("WinHttpReadData"));
+ response.body.append(chunk.data(), read);
+ }
+ return response;
+ }
+
+private:
+ void checkCancel() const {
+ if (cancel_ && cancel_->load()) throw NetworkError("cancelled");
+ }
+ Handle session_;
+ const std::atomic<bool>* cancel_;
+};
+
+} // namespace
+
+std::shared_ptr<HttpsTransport> makeWinHttpTransport(const std::atomic<bool>* cancel) {
+ return std::make_shared<WinHttpTransport>(cancel);
+}
+
+std::string urlEncode(const std::string& text) {
+ static const char* hex = "0123456789ABCDEF";
+ std::string out;
+ for (const unsigned char c : text) {
+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') out += char(c);
+ else { out += '%'; out += hex[c >> 4]; out += hex[c & 15]; }
+ }
+ return out;
+}
+
+} // namespace veyra::xbox
diff --git a/src/xbox/StreamApi.cpp b/src/xbox/StreamApi.cpp
new file mode 100644
index 00000000..b8b101ee
--- /dev/null
+++ b/src/xbox/StreamApi.cpp
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/xbox/StreamApi.h"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+#include <chrono>
+#include <nlohmann/json.hpp>
+#include <sstream>
+#include <thread>
+
+namespace veyra::xbox {
+namespace {
+
+using json = nlohmann::json;
+
+// What the session API expects to hear about the client (Greenlight sends the same).
+const char* kDeviceInfo = R"({"appInfo":{"env":{"clientAppId":"Microsoft.GamingApp","clientAppType":"native","clientAppVersion":"2203.1001.4.0","clientSdkVersion":"8.5.2","httpEnvironment":"prod","sdkInstallId":""}},"dev":{"hw":{"make":"Microsoft","model":"Surface Pro","sdktype":"native"},"os":{"name":"Windows 11","ver":"22631.2715","platform":"desktop"},"displayInfo":{"dimensions":{"widthInPixels":1920,"heightInPixels":1080},"pixelDensity":{"dpiX":1,"dpiY":1}}}})";
+
+json parse(const HttpsResponse& response, const std::string& what) {
+ try {
+ return json::parse(response.body);
+ } catch (const json::exception&) {
+ throw std::runtime_error(what + " returned something that is not JSON");
+ }
+}
+
+} // namespace
+
+StreamApi::StreamApi(std::shared_ptr<HttpsTransport> transport, std::string host, std::string gsToken)
+ : http_(std::move(transport)), host_(std::move(host)), token_(std::move(gsToken)) {}
+
+HttpsResponse StreamApi::call(const std::string& method, const std::string& path, const std::string& body,
+ const std::map<std::string, std::string>& extraHeaders) {
+ HttpsRequest r;
+ r.method = method;
+ r.host = host_;
+ r.path = path;
+ r.headers["Content-Type"] = "application/json";
+ r.headers["Authorization"] = "Bearer " + token_;
+ for (const auto& [k, v] : extraHeaders) r.headers[k] = v;
+ if (method == "POST") r.body = body.empty() ? "{}" : body;
+ const HttpsResponse response = http_->send(r);
+ if (response.status < 200 || response.status > 299)
+ throw ServiceError(response.status, response.body, method + " " + path + " returned HTTP " + std::to_string(response.status));
+ return response;
+}
+
+std::vector<Console> StreamApi::parseConsoles(const std::string& body) {
+ std::vector<Console> out;
+ const json j = json::parse(body);
+ for (const auto& c : j.value("results", json::array())) {
+ Console console;
+ console.serverId = c.value("serverId", "");
+ console.name = c.value("deviceName", "");
+ console.powerState = c.value("powerState", "");
+ console.consoleType = c.value("consoleType", "");
+ console.outOfHomeWarning = c.value("outOfHomeWarning", false);
+ if (!console.serverId.empty()) out.push_back(std::move(console));
+ }
+ return out;
+}
+
+std::vector<Console> StreamApi::consoles() {
+ const HttpsResponse response = call("GET", "/v6/servers/home", "");
+ try {
+ return parseConsoles(response.body);
+ } catch (const json::exception&) {
+ throw std::runtime_error("console list is not JSON");
+ }
+}
+
+std::string StreamApi::play(const std::string& serverId, const std::string& locale) {
+ const json body = {
+ {"titleId", ""}, {"systemUpdateGroup", ""}, {"clientSessionId", ""},
+ {"settings", {{"nanoVersion", "V3;WebrtcTransport.dll"}, {"enableTextToSpeech", false}, {"highContrast", 0},
+ {"locale", locale}, {"useIceConnection", false}, {"timezoneOffsetMinutes", 480},
+ {"sdkType", "web"}, {"osName", "windows"}}},
+ {"serverId", serverId}, {"fallbackRegionNames", json::array()},
+ };
+ const json j = parse(call("POST", "/v5/sessions/home/play", body.dump(), {{"X-MS-Device-Info", kDeviceInfo}}), "play");
+ const std::string path = j.value("sessionPath", "");
+ // "v5/sessions/home/<id>"
+ const auto slash = path.find_last_of('/');
+ const std::string id = slash == std::string::npos ? path : path.substr(slash + 1);
+ if (id.empty()) throw std::runtime_error("play returned no session");
+ return id;
+}
+
+SessionState StreamApi::state(const std::string& sessionId) {
+ const json j = parse(call("GET", "/v5/sessions/home/" + sessionId + "/state", ""), "session state");
+ SessionState s;
+ s.state = j.value("state", "");
+ if (j.contains("errorDetails") && j["errorDetails"].is_object()) {
+ const json& e = j["errorDetails"];
+ s.errorCode = e.contains("code") && e["code"].is_string() ? e["code"].get<std::string>() : std::string();
+ s.errorMessage = e.contains("message") && e["message"].is_string() ? e["message"].get<std::string>() : std::string();
+ }
+ return s;
+}
+
+void StreamApi::connect(const std::string& sessionId, const std::string& transferToken) {
+ call("POST", "/v5/sessions/home/" + sessionId + "/connect", json{{"userToken", transferToken}}.dump());
+}
+
+// The service answers 204 until the console has replied; poll a bounded number of times.
+std::string StreamApi::getExchange(const std::string& path) {
+ for (int attempt = 0; attempt < 40; ++attempt) {
+ const HttpsResponse response = call("GET", path, "");
+ if (response.status != 204 && !response.body.empty()) {
+ const json j = parse(response, path);
+ if (j.contains("errorDetails") && j["errorDetails"].is_object() && j["errorDetails"].value("code", "") != "")
+ throw std::runtime_error(path + ": " + j["errorDetails"].value("message", j["errorDetails"].value("code", "")));
+ return j.value("exchangeResponse", "");
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(retryDelayMs_));
+ }
+ throw std::runtime_error(path + ": the console did not answer");
+}
+
+std::string StreamApi::exchangeSdp(const std::string& sessionId, const std::string& offerSdp) {
+ const json body = {
+ {"messageType", "offer"}, {"sdp", offerSdp},
+ {"configuration", {
+ {"chatConfiguration", {{"bytesPerSample", 2}, {"expectedClipDurationMs", 20},
+ {"format", {{"codec", "opus"}, {"container", "webm"}}},
+ {"numChannels", 1}, {"sampleFrequencyHz", 24000}}},
+ {"chat", {{"minVersion", 1}, {"maxVersion", 1}}},
+ {"control", {{"minVersion", 1}, {"maxVersion", 3}}},
+ {"input", {{"minVersion", 1}, {"maxVersion", 8}}},
+ {"message", {{"minVersion", 1}, {"maxVersion", 1}}},
+ }},
+ };
+ const std::string path = "/v5/sessions/home/" + sessionId + "/sdp";
+ call("POST", path, body.dump());
+ const std::string exchange = getExchange(path);
+ try {
+ const json answer = json::parse(exchange);
+ const std::string sdp = answer.value("sdp", "");
+ if (sdp.empty()) throw std::runtime_error("the console's answer has no SDP (status: " + answer.value("status", std::string("?")) + ")");
+ return sdp;
+ } catch (const json::exception&) {
+ throw std::runtime_error("the console's answer is not JSON");
+ }
+}
+
+bool StreamApi::teredoIpv4(const std::string& ipv6, std::string* ipv4, int* port) {
+ in6_addr address{};
+ if (InetPtonA(AF_INET6, ipv6.c_str(), &address) != 1) return false;
+ const uint8_t* b = address.s6_addr;
+ if (!(b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00)) return false;
+ const int p = ((b[10] << 8) | b[11]) ^ 0xFFFF;
+ char text[INET_ADDRSTRLEN] = {};
+ std::snprintf(text, sizeof(text), "%u.%u.%u.%u", b[12] ^ 0xFFu, b[13] ^ 0xFFu, b[14] ^ 0xFFu, b[15] ^ 0xFFu);
+ if (ipv4) *ipv4 = text;
+ if (port) *port = p;
+ return true;
+}
+
+std::vector<IceCandidate> StreamApi::parseIce(const std::string& exchangeResponse) {
+ std::vector<IceCandidate> out;
+ const json list = json::parse(exchangeResponse);
+ for (const auto& c : list) {
+ IceCandidate candidate;
+ candidate.candidate = c.value("candidate", "");
+ candidate.sdpMid = c.contains("sdpMid") ? (c["sdpMid"].is_string() ? c["sdpMid"].get<std::string>() : std::to_string(c["sdpMid"].get<int>())) : "0";
+ candidate.sdpMLineIndex = c.contains("sdpMLineIndex") ? (c["sdpMLineIndex"].is_string() ? std::atoi(c["sdpMLineIndex"].get<std::string>().c_str()) : c["sdpMLineIndex"].get<int>()) : 0;
+ if (candidate.candidate.empty() || candidate.candidate == "a=end-of-candidates") continue;
+ // Greenlight: a Teredo candidate also reaches the console on the IPv4 address and port it hides,
+ // and on port 9002 of that address.
+ std::istringstream fields(candidate.candidate);
+ std::vector<std::string> parts;
+ for (std::string part; fields >> part;) parts.push_back(part);
+ std::string ipv4;
+ int port = 0;
+ if (parts.size() > 4 && parts[4].rfind("2001", 0) == 0 && teredoIpv4(parts[4], &ipv4, &port)) {
+ out.push_back({"a=candidate:10 1 UDP 1 " + ipv4 + " 9002 typ host ", candidate.sdpMid, candidate.sdpMLineIndex});
+ out.push_back({"a=candidate:11 1 UDP 1 " + ipv4 + " " + std::to_string(port) + " typ host ", candidate.sdpMid, candidate.sdpMLineIndex});
+ }
+ out.push_back(std::move(candidate));
+ }
+ return out;
+}
+
+std::vector<IceCandidate> StreamApi::exchangeIce(const std::string& sessionId, const std::vector<IceCandidate>& local) {
+ json candidates = json::array();
+ for (const auto& c : local) candidates.push_back({{"candidate", c.candidate}, {"sdpMid", c.sdpMid}, {"sdpMLineIndex", c.sdpMLineIndex}});
+ const std::string path = "/v5/sessions/home/" + sessionId + "/ice";
+ call("POST", path, json{{"messageType", "iceCandidate"}, {"candidate", candidates}}.dump());
+ try {
+ return parseIce(getExchange(path));
+ } catch (const json::exception&) {
+ throw std::runtime_error("the console's ICE candidates are not JSON");
+ }
+}
+
+void StreamApi::keepalive(const std::string& sessionId) {
+ call("POST", "/v5/sessions/home/" + sessionId + "/keepalive", "{}");
+}
+
+void StreamApi::stop(const std::string& sessionId) {
+ call("DELETE", "/v5/sessions/home/" + sessionId, "");
+}
+
+} // namespace veyra::xbox
diff --git a/src/xbox/WebRtcSession.cpp b/src/xbox/WebRtcSession.cpp
new file mode 100644
index 00000000..52034945
--- /dev/null
+++ b/src/xbox/WebRtcSession.cpp
@@ -0,0 +1,355 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Channel set-up, handshake and messages follow Greenlight's player (unknownskl/greenlight
+// packages/player/src/client/lib, MIT): channel.ts, control.ts, message.ts, input.ts, sdp.ts.
+#include "veyra/xbox/WebRtcSession.h"
+
+#include <windows.h>
+
+#include <rtc/rtc.hpp>
+
+#include <nlohmann/json.hpp>
+#include <random>
+#include <sstream>
+
+#include "veyra/Log.h"
+
+namespace veyra::xbox {
+namespace {
+
+using json = nlohmann::json;
+using Clock = std::chrono::steady_clock;
+
+int64_t host100ns() {
+ return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count() / 100;
+}
+
+std::string uuid4() {
+ static thread_local std::mt19937_64 rng{std::random_device{}()};
+ uint8_t b[16];
+ for (int i = 0; i < 16; i += 8) {
+ const uint64_t r = rng();
+ std::memcpy(b + i, &r, 8);
+ }
+ b[6] = uint8_t((b[6] & 0x0F) | 0x40);
+ b[8] = uint8_t((b[8] & 0x3F) | 0x80);
+ static const char* hex = "0123456789abcdef";
+ std::string s;
+ for (int i = 0; i < 16; ++i) {
+ if (i == 4 || i == 6 || i == 8 || i == 10) s += '-';
+ s += hex[b[i] >> 4];
+ s += hex[b[i] & 15];
+ }
+ return s;
+}
+
+std::string message(const std::string& target, const json& content) {
+ return json{{"type", "Message"}, {"content", content.dump()}, {"id", uuid4()}, {"target", target}, {"cv", ""}}.dump();
+}
+
+void logOnce() {
+ static std::once_flag once;
+ std::call_once(once, [] {
+ // VEYRA_XBOX_RTC_DEBUG=1 logs libdatachannel's ICE/DTLS/SCTP details (for field diagnosis).
+ const bool debug = GetEnvironmentVariableA("VEYRA_XBOX_RTC_DEBUG", nullptr, 0) > 0;
+ rtc::InitLogger(debug ? rtc::LogLevel::Verbose : rtc::LogLevel::Warning, [](rtc::LogLevel level, std::string text) {
+ if (level <= rtc::LogLevel::Error) log::warn("xbox-rtc", text);
+ else log::info("xbox-rtc", text);
+ });
+ });
+}
+
+// Removes a=candidate / a=end-of-candidates lines: candidates go through the ICE exchange.
+std::string withoutCandidates(const std::string& sdp) {
+ std::istringstream in(sdp);
+ std::string out, line;
+ while (std::getline(in, line)) {
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (line.rfind("a=candidate:", 0) == 0 || line == "a=end-of-candidates") continue;
+ out += line;
+ out += "\r\n";
+ }
+ return out;
+}
+
+} // namespace
+
+WebRtcSession::WebRtcSession() { logOnce(); }
+
+WebRtcSession::~WebRtcSession() { close(); }
+
+double WebRtcSession::nowMs() const {
+ return std::chrono::duration<double, std::milli>(Clock::now() - origin_).count();
+}
+
+std::string WebRtcSession::describeCodecs(const std::string& sdp) {
+ std::istringstream in(sdp);
+ std::string out, line;
+ while (std::getline(in, line)) {
+ if (line.rfind("a=rtpmap:", 0) == 0 || line.rfind("a=fmtp:", 0) == 0 || line.rfind("m=", 0) == 0) {
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ out += line + "\n";
+ }
+ }
+ return out;
+}
+
+bool WebRtcSession::start(Signaling& signaling, std::string* error, std::chrono::milliseconds timeout) {
+ const auto fail = [&](const std::string& why) {
+ if (error) *error = why;
+ log::warn("xbox", "webrtc start failed: " + why);
+ return false;
+ };
+ rtc::Configuration config;
+ config.disableAutoNegotiation = true;
+ config.maxMessageSize = 256 * 1024;
+ if (!bindAddress_.empty()) config.bindAddress = bindAddress_;
+ pc_ = std::make_shared<rtc::PeerConnection>(config);
+
+ pc_->onStateChange([this](rtc::PeerConnection::State state) {
+ log::info("xbox", std::string("peer connection state ") + std::to_string(int(state)));
+ if (state == rtc::PeerConnection::State::Connected) connected_ = true;
+ if (state == rtc::PeerConnection::State::Failed || state == rtc::PeerConnection::State::Closed ||
+ state == rtc::PeerConnection::State::Disconnected) {
+ const bool wasConnected = connected_.exchange(false);
+ failed_ = true;
+ if (wasConnected && !closed_ && callbacks_.ended) callbacks_.ended("connection lost");
+ }
+ changed_.notify_all();
+ });
+ pc_->onGatheringStateChange([this](rtc::PeerConnection::GatheringState) { changed_.notify_all(); });
+
+ // Audio (send-receive, as the reference client; nothing is sent) and video (receive only, H.264
+ // in the reference client's order: Main, Constrained Baseline, Baseline).
+ rtc::Description::Audio audio("0", rtc::Description::Direction::SendRecv);
+ audio.addOpusCodec(111, std::string("minptime=10;useinbandfec=1;stereo=1"));
+ audio_ = pc_->addTrack(audio);
+ rtc::Description::Video video("1", rtc::Description::Direction::RecvOnly);
+ video.addH264Codec(102, std::string("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f"));
+ video.addH264Codec(104, std::string("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"));
+ video.addH264Codec(106, std::string("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"));
+ video_ = pc_->addTrack(video);
+
+ auto depacketizer = std::make_shared<rtc::H264RtpDepacketizer>(rtc::NalUnit::Separator::LongStartSequence);
+ video_->setMediaHandler(depacketizer);
+ video_->chainMediaHandler(std::make_shared<rtc::RtcpReceivingSession>());
+ video_->onFrame([this](rtc::binary data, rtc::FrameInfo info) {
+ ++videoUnits_;
+ videoBytes_ += data.size();
+ if (!callbacks_.video) return;
+ std::vector<uint8_t> unit(data.size());
+ std::memcpy(unit.data(), data.data(), data.size());
+ callbacks_.video(std::move(unit), info.timestamp, host100ns());
+ });
+ audio_->setMediaHandler(std::make_shared<rtc::OpusRtpDepacketizer>());
+ audio_->chainMediaHandler(std::make_shared<rtc::RtcpReceivingSession>());
+ audio_->onFrame([this](rtc::binary data, rtc::FrameInfo info) {
+ ++audioPackets_;
+ if (callbacks_.audio) callbacks_.audio(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp);
+ });
+
+ // The channels, in the reference client's creation order.
+ const auto channel = [&](const char* label, const char* protocol) {
+ rtc::DataChannelInit init;
+ init.protocol = protocol;
+ return pc_->createDataChannel(label, init);
+ };
+ chat_ = channel("chat", "chatV1");
+ control_ = channel("control", "controlV1");
+ input_ = channel("input", "1.0");
+ message_ = channel("message", "messageV1");
+
+ // The handshake starts once every channel is open: its acknowledgement triggers sends on control and
+ // input, which would be dropped by a channel still opening.
+ const auto maybeHandshake = [this] {
+ if (!message_ || !control_ || !input_ || !chat_) return;
+ if (!message_->isOpen() || !control_->isOpen() || !input_->isOpen() || !chat_->isOpen()) return;
+ if (handshakeSent_.exchange(true)) return;
+ log::info("xbox", "data channels open; sending handshake");
+ sendMessageJson(json{{"type", "Handshake"}, {"version", "messageV1"}, {"id", "be0bfc6d-1e83-4c8a-90ed-fa8601c5a179"}, {"cv", "0"}}.dump());
+ };
+ for (const auto& dc : {chat_, control_, input_, message_}) dc->onOpen(maybeHandshake);
+ message_->onMessage([this](rtc::message_variant data) {
+ if (const auto* text = std::get_if<std::string>(&data)) onMessageChannel(*text);
+ else if (const auto* bin = std::get_if<rtc::binary>(&data))
+ onMessageChannel(std::string(reinterpret_cast<const char*>(bin->data()), bin->size()));
+ });
+ input_->onMessage([this](rtc::message_variant data) {
+ if (const auto* bin = std::get_if<rtc::binary>(&data)) onInputChannel(reinterpret_cast<const uint8_t*>(bin->data()), bin->size());
+ });
+ control_->onMessage([](rtc::message_variant data) {
+ if (const auto* text = std::get_if<std::string>(&data)) log::info("xbox-control", *text);
+ });
+
+ // Offer: gather every local candidate first (no trickle on this service).
+ pc_->setLocalDescription(rtc::Description::Type::Offer);
+ {
+ std::unique_lock lock(mutex_);
+ changed_.wait_for(lock, std::chrono::seconds(5), [&] { return pc_->gatheringState() == rtc::PeerConnection::GatheringState::Complete; });
+ }
+ const auto local = pc_->localDescription();
+ if (!local) return fail("no local description");
+ const std::string offer = withoutCandidates(std::string(*local));
+ std::vector<IceCandidate> candidates;
+ for (const auto& c : local->candidates()) {
+ std::string text = c.candidate();
+ if (text.rfind("a=", 0) == 0) text = text.substr(2);
+ candidates.push_back({text, c.mid(), c.mid() == "0" ? 0 : (c.mid() == "1" ? 1 : 2)});
+ if (GetEnvironmentVariableA("VEYRA_XBOX_RTC_DEBUG", nullptr, 0) > 0) log::info("xbox", "local candidate [" + text + "] mid " + c.mid());
+ }
+ log::info("xbox", "offer codecs:\n" + describeCodecs(offer));
+
+ std::string answer;
+ try {
+ answer = signaling.exchangeSdp(offer);
+ } catch (const std::exception& e) {
+ return fail(std::string("SDP exchange: ") + e.what());
+ }
+ log::info("xbox", "answer codecs:\n" + describeCodecs(answer));
+ try {
+ pc_->setRemoteDescription(rtc::Description(answer, rtc::Description::Type::Answer));
+ } catch (const std::exception& e) {
+ return fail(std::string("the console's answer was not accepted: ") + e.what());
+ }
+ std::vector<IceCandidate> remote;
+ try {
+ remote = signaling.exchangeIce(candidates);
+ } catch (const std::exception& e) {
+ return fail(std::string("ICE exchange: ") + e.what());
+ }
+ int added = 0;
+ for (const auto& c : remote) {
+ std::string text = c.candidate;
+ if (text.rfind("a=", 0) == 0) text = text.substr(2);
+ while (!text.empty() && text.back() == ' ') text.pop_back();
+ if (GetEnvironmentVariableA("VEYRA_XBOX_RTC_DEBUG", nullptr, 0) > 0) log::info("xbox", "remote candidate [" + text + "] mid " + c.sdpMid);
+ try {
+ pc_->addRemoteCandidate(rtc::Candidate(text, c.sdpMid.empty() ? "0" : c.sdpMid));
+ ++added;
+ } catch (const std::exception& e) {
+ log::warn("xbox", std::string("remote candidate ignored: ") + e.what() + " [" + text + "]");
+ }
+ }
+ log::info("xbox", "local candidates " + std::to_string(candidates.size()) + ", remote " + std::to_string(added));
+ if (added == 0) return fail("the console sent no usable network candidates");
+
+ std::unique_lock lock(mutex_);
+ if (!changed_.wait_for(lock, timeout, [&] { return connected_.load() || failed_.load(); }) || !connected_)
+ return fail(failed_ ? "the connection to the console failed (network or firewall)" : "timed out connecting to the console");
+ return true;
+}
+
+bool WebRtcSession::waitReady(std::chrono::milliseconds timeout) {
+ std::unique_lock lock(mutex_);
+ return changed_.wait_for(lock, timeout, [&] { return handshakeDone_.load() || failed_.load(); }) && handshakeDone_;
+}
+
+void WebRtcSession::sendMessageJson(const std::string& text) {
+ if (message_ && message_->isOpen()) message_->send(rtc::binary(reinterpret_cast<const std::byte*>(text.data()), reinterpret_cast<const std::byte*>(text.data()) + text.size()));
+}
+
+void WebRtcSession::sendClientConfig() {
+ sendMessageJson(message("/streaming/systemUi/configuration", {{"version", {0, 2, 0}}, {"systemUis", json::array()}}));
+ sendMessageJson(message("/streaming/properties/clientappinstallidchanged", {{"clientAppInstallId", "c97d7ee0-73b2-4239-bf1d-9d805a338429"}}));
+ sendMessageJson(message("/streaming/characteristics/orientationchanged", {{"orientation", 0}}));
+ sendMessageJson(message("/streaming/characteristics/touchinputenabledchanged", {{"touchInputEnabled", false}}));
+ sendMessageJson(message("/streaming/characteristics/clientdevicecapabilities", json::object()));
+ sendMessageJson(message("/streaming/characteristics/dimensionschanged", {
+ {"horizontal", 1920}, {"vertical", 1080}, {"preferredWidth", 1920}, {"preferredHeight", 1080},
+ {"safeAreaLeft", 0}, {"safeAreaTop", 0}, {"safeAreaRight", 1920}, {"safeAreaBottom", 1080}, {"supportsCustomResolution", true}}));
+}
+
+void WebRtcSession::onMessageChannel(const std::string& text) {
+ json j;
+ try { j = json::parse(text); } catch (const json::exception&) { log::warn("xbox", "message channel: not JSON"); return; }
+ const std::string type = j.value("type", "");
+ if (type == "HandshakeAck") {
+ log::info("xbox", "handshake acknowledged");
+ // Control: authorise, then announce pad 0 (the reference client adds, removes and re-adds it).
+ const auto sendControl = [this](const std::string& s) {
+ if (control_ && control_->isOpen()) control_->send(rtc::binary(reinterpret_cast<const std::byte*>(s.data()), reinterpret_cast<const std::byte*>(s.data()) + s.size()));
+ };
+ sendControl(json{{"message", "authorizationRequest"}, {"accessKey", "4BDB3609-C1F1-4195-9B37-FEFF45DA8B8E"}}.dump());
+ sendControl(json{{"message", "gamepadChanged"}, {"gamepadIndex", 0}, {"wasAdded", true}}.dump());
+ sendControl(json{{"message", "gamepadChanged"}, {"gamepadIndex", 0}, {"wasAdded", false}}.dump());
+ sendControl(json{{"message", "gamepadChanged"}, {"gamepadIndex", 0}, {"wasAdded", true}}.dump());
+ if (input_ && input_->isOpen()) {
+ const auto report = clientMetadataReport(0, nowMs(), 1);
+ input_->send(reinterpret_cast<const std::byte*>(report.data()), report.size());
+ }
+ sendClientConfig();
+ handshakeDone_ = true;
+ changed_.notify_all();
+ return;
+ }
+ if (type == "TransactionStart" || type == "Message") {
+ const std::string target = j.value("target", "");
+ const std::string id = j.value("id", "");
+ log::info("xbox-message", target + " " + j.value("content", std::string()).substr(0, 300));
+ if (target == "/streaming/sessionLifetimeManagement/serverInitiatedDisconnect") {
+ sendMessageJson(json{{"type", "TransactionComplete"}, {"content", "\"\""}, {"id", id}, {"cv", ""}}.dump());
+ if (callbacks_.ended) callbacks_.ended("the console ended the stream");
+ } else if (target == "/streaming/systemUi/messages/ShowMessageDialog") {
+ // A system dialog meant for the player; acknowledge it so the console does not wait.
+ sendMessageJson(json{{"type", "TransactionComplete"}, {"content", json{{"Result", 0}}.dump()}, {"id", id}, {"cv", ""}}.dump());
+ } else if (type == "TransactionStart") {
+ sendMessageJson(json{{"type", "TransactionComplete"}, {"content", "\"\""}, {"id", id}, {"cv", ""}}.dump());
+ }
+ return;
+ }
+ log::info("xbox-message", "unhandled " + type);
+}
+
+void WebRtcSession::onInputChannel(const uint8_t* data, size_t size) {
+ if (size < 2) return;
+ if (auto v = parseVibration(data, size)) {
+ if (callbacks_.vibration) callbacks_.vibration(*v);
+ return;
+ }
+ uint32_t w = 0, h = 0;
+ if (parseServerMetadata(data, size, &w, &h)) {
+ log::info("xbox", "server video " + std::to_string(w) + "x" + std::to_string(h));
+ if (callbacks_.serverVideoSize) callbacks_.serverVideoSize(w, h);
+ }
+}
+
+void WebRtcSession::sendGamepad(const GamepadFrame& frame) {
+ if (!handshakeDone_ || !input_ || !input_->isOpen()) return;
+ const auto report = gamepadReport(++inputSequence_, nowMs(), {frame});
+ input_->send(reinterpret_cast<const std::byte*>(report.data()), report.size());
+}
+
+void WebRtcSession::requestKeyframe() {
+ ++keyframeRequests_;
+ if (video_) video_->requestKeyframe();
+ if (control_ && control_->isOpen() && handshakeDone_) {
+ const std::string s = json{{"message", "videoKeyframeRequested"}, {"ifrRequested", true}}.dump();
+ control_->send(rtc::binary(reinterpret_cast<const std::byte*>(s.data()), reinterpret_cast<const std::byte*>(s.data()) + s.size()));
+ }
+}
+
+void WebRtcSession::close() {
+ if (closed_.exchange(true)) return;
+ if (pc_) {
+ try { pc_->close(); } catch (...) {}
+ }
+ changed_.notify_all();
+ chat_.reset(); control_.reset(); input_.reset(); message_.reset();
+ audio_.reset(); video_.reset();
+ pc_.reset();
+}
+
+WebRtcStats WebRtcSession::stats() const {
+ WebRtcStats s;
+ s.videoUnits = videoUnits_.load();
+ s.audioPackets = audioPackets_.load();
+ s.keyframeRequests = keyframeRequests_.load();
+ s.videoBytes = videoBytes_.load();
+ s.handshakeDone = handshakeDone_.load();
+ if (const auto pc = pc_) {
+ s.bytesReceived = pc->bytesReceived();
+ if (const auto rtt = pc->rtt()) s.rttMs = double(rtt->count());
+ }
+ return s;
+}
+
+} // namespace veyra::xbox
diff --git a/tests/xbox/XboxTests.cpp b/tests/xbox/XboxTests.cpp
new file mode 100644
index 00000000..e2400b28
--- /dev/null
+++ b/tests/xbox/XboxTests.cpp
@@ -0,0 +1,474 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Offline tests for the Xbox streaming core: the input/report formats, the session API and the sign-in
+// chain against scripted service replies, and the WebRTC session against a second local libdatachannel
+// peer that plays the console (real ICE, DTLS, SCTP and RTP on loopback). None of this proves that
+// Microsoft's services or a real console accept the client; it proves the client does what the reference
+// client does and survives the replies it can get.
+#include <windows.h>
+
+#include <rtc/rtc.hpp>
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <algorithm>
+#include <deque>
+#include <fstream>
+#include <iterator>
+#include <optional>
+#include <sstream>
+#include <filesystem>
+#include <functional>
+#include <map>
+#include <mutex>
+#include <nlohmann/json.hpp>
+#include <thread>
+
+#include "veyra/xbox/Account.h"
+#include "veyra/xbox/Protocol.h"
+#include "veyra/xbox/StreamApi.h"
+#include "veyra/xbox/WebRtcSession.h"
+
+using namespace veyra::xbox;
+using json = nlohmann::json;
+
+namespace {
+
+int g_checks = 0, g_failures = 0;
+void check(bool ok, const char* what) {
+ ++g_checks;
+ if (!ok) { ++g_failures; std::printf("FAIL %s\n", what); }
+ else if (GetEnvironmentVariableA("VEYRA_TEST_VERBOSE", nullptr, 0) > 0) std::printf("ok %s\n", what);
+ std::fflush(stdout);
+}
+
+// ---------------------------------------------------------------- scripted HTTPS
+
+struct FakeTransport final : HttpsTransport {
+ struct Reply { std::string host, path; int status; std::string body; };
+ std::deque<Reply> script;
+ std::vector<HttpsRequest> seen;
+ std::mutex mutex;
+ HttpsResponse send(const HttpsRequest& r) override {
+ std::lock_guard lock(mutex);
+ seen.push_back(r);
+ if (script.empty()) return {599, "no scripted reply for " + r.host + r.path};
+ Reply reply = script.front();
+ if (reply.host != r.host || reply.path != r.path) return {598, "unexpected request " + r.method + " " + r.host + r.path + " (wanted " + reply.host + reply.path + ")"};
+ script.pop_front();
+ return {reply.status, reply.body};
+ }
+ void add(std::string host, std::string path, int status, std::string body) { script.push_back({std::move(host), std::move(path), status, std::move(body)}); }
+};
+
+// ---------------------------------------------------------------- protocol
+
+void protocolTests() {
+ const auto meta = clientMetadataReport(0, 12.5, 1);
+ check(meta.size() == 15 && meta[0] == 8 && meta[1] == 0 && meta[14] == 1, "client metadata report: type 8, 15 bytes, touch points last");
+ double t = 0;
+ std::memcpy(&t, meta.data() + 6, 8);
+ check(t == 12.5, "report timestamp is a little-endian double at offset 6");
+
+ GamepadFrame pad;
+ pad.index = 0;
+ pad.buttons = BtnA | BtnMenu | BtnNexus;
+ pad.leftX = 1000; pad.leftY = -2; pad.rightX = -32767; pad.rightY = 32767;
+ pad.leftTrigger = 65535; pad.rightTrigger = 257;
+ const auto r = gamepadReport(7, 0, {pad});
+ check(r.size() == 14 + 1 + 23, "gamepad report: 14 header + count + 23 per pad");
+ check(r[0] == 2 && r[2] == 7 && r[14] == 1 && r[15] == 0, "type 2, sequence, one pad, index 0");
+ check(r[16] == uint8_t((BtnA | BtnMenu | BtnNexus) & 0xFF) && r[17] == 0, "button mask little-endian");
+ check(r[18] == 0xE8 && r[19] == 0x03 && r[20] == 0xFE && r[21] == 0xFF, "left stick X/Y as signed little-endian");
+ check(r[26] == 0xFF && r[27] == 0xFF && r[28] == 0x01 && r[29] == 0x01, "triggers 0..65535");
+ check(r[30] == 1 && r[31] == 0 && r[32] == 0 && r[33] == 0 && r[34] == 0 && r[35] == 0 && r[36] == 0 && r[37] == 1,
+ "physicality LE 1 then virtual physicality written big-endian, as the reference client");
+
+ veyra::remoteplay::ControllerState s;
+ s.inputActive = true;
+ s.buttons = veyra::remoteplay::ControllerState::Cross | veyra::remoteplay::ControllerState::Options |
+ veyra::remoteplay::ControllerState::Share | veyra::remoteplay::ControllerState::PS | veyra::remoteplay::ControllerState::Down;
+ s.leftY = 32767; s.rightY = -32768; s.leftX = -32768; s.l2 = 255; s.r2 = 1;
+ const GamepadFrame f = gamepadFromController(s);
+ check(f.buttons == (BtnA | BtnMenu | BtnView | BtnNexus | BtnDown), "SDL buttons map positionally; Guide is Nexus");
+ check(f.leftY == -32767 && f.rightY == 32767 && f.leftX == -32767, "sticks: Y flipped to up-positive, clamped to +-32767");
+ check(f.leftTrigger == 65535 && f.rightTrigger == 257, "triggers scaled from 0..255");
+ s.inputActive = false;
+ check(gamepadFromController(s) == GamepadFrame{}, "an inactive pad sends a neutral frame");
+
+ const uint8_t vib[] = {128, 0, 0, 0, 80, 20, 0, 5, 0x10, 0x00, 0x05, 0x00, 1};
+ const auto v = parseVibration(vib, sizeof(vib));
+ check(v && v->leftMotor == 80 && v->rightMotor == 20 && v->rightTrigger == 5 && v->durationMs == 16 && v->delayMs == 5 && v->repeat == 1, "vibration report");
+ check(!parseVibration(vib, 5), "a short vibration report is ignored");
+ const uint8_t meta2[] = {16, 0, 0x38, 0x04, 0, 0, 0x80, 0x07, 0, 0};
+ uint32_t w = 0, h = 0;
+ check(parseServerMetadata(meta2, sizeof(meta2), &w, &h) && w == 1920 && h == 1080, "server metadata: height then width");
+}
+
+// ---------------------------------------------------------------- session API
+
+void apiTests() {
+ std::string ip;
+ int port = 0;
+ check(StreamApi::teredoIpv4("2001:0:4136:e378:8000:63bf:3fff:fdd2", &ip, &port) && ip == "192.0.2.45" && port == 40000, "Teredo address decodes to the RFC 4380 example");
+ check(!StreamApi::teredoIpv4("2001:db8::1", &ip, &port), "a non-Teredo 2001: address is not decoded");
+
+ const auto consoles = StreamApi::parseConsoles(R"({"totalItems":2,"results":[{"deviceName":"客厅 Series X","serverId":"F4001234ABCD5678","powerState":"ConnectedStandby","consoleType":"XboxSeriesX","playPath":"x","outOfHomeWarning":false},{"deviceName":"broken"}],"continuationToken":null})");
+ check(consoles.size() == 1 && consoles[0].serverId == "F4001234ABCD5678" && consoles[0].name == "客厅 Series X" && consoles[0].powerState == "ConnectedStandby", "console list (entries without a server id are skipped)");
+
+ const auto ice = StreamApi::parseIce(R"([{"candidate":"a=candidate:1 1 UDP 100 2001:0:4136:e378:8000:63bf:3fff:fdd2 9002 typ host","sdpMid":"0","sdpMLineIndex":"0"},{"candidate":"a=candidate:2 1 UDP 90 192.168.1.30 9002 typ host","sdpMid":"0","sdpMLineIndex":0},{"candidate":"a=end-of-candidates"}])");
+ check(ice.size() == 4, "a Teredo candidate adds two IPv4 candidates; end-of-candidates is dropped");
+ check(ice[0].candidate.find("192.0.2.45 9002") != std::string::npos && ice[1].candidate.find("192.0.2.45 40000") != std::string::npos, "the IPv4 candidates use port 9002 and the Teredo port");
+
+ auto http = std::make_shared<FakeTransport>();
+ const std::string host = "uks.core.gssv-play-prodxhome.xboxlive.com";
+ StreamApi api(http, host, "GS");
+ api.setRetryDelayMs(1);
+ http->add(host, "/v6/servers/home", 200, R"({"results":[{"deviceName":"X","serverId":"F1","powerState":"On"}]})");
+ check(api.consoles().size() == 1, "consoles() reads the list");
+ check(http->seen.back().headers["Authorization"] == "Bearer GS", "the streaming token is the bearer");
+ http->add(host, "/v5/sessions/home/play", 200, R"({"sessionPath":"v5/sessions/home/ABC-123","state":"Provisioning"})");
+ check(api.play("F1") == "ABC-123", "play returns the session id from sessionPath");
+ {
+ const json body = json::parse(http->seen.back().body);
+ check(body["serverId"] == "F1" && body["settings"]["nanoVersion"] == "V3;WebrtcTransport.dll" && !http->seen.back().headers["X-MS-Device-Info"].empty(),
+ "play sends the server id, nano V3 and the device info header");
+ }
+ http->add(host, "/v5/sessions/home/ABC-123/state", 200, R"({"state":"Failed","errorDetails":{"code":"WNSError","message":"WaitingForServerToRegister"}})");
+ const auto st = api.state("ABC-123");
+ check(st.state == "Failed" && st.errorCode == "WNSError" && st.errorMessage == "WaitingForServerToRegister", "state with error details");
+ http->add(host, "/v5/sessions/home/ABC-123/sdp", 202, "");
+ http->add(host, "/v5/sessions/home/ABC-123/sdp", 204, "");
+ http->add(host, "/v5/sessions/home/ABC-123/sdp", 204, "");
+ http->add(host, "/v5/sessions/home/ABC-123/sdp", 200, json{{"exchangeResponse", json{{"sdp", "v=0\r\n"}, {"sdpType", "answer"}, {"status", "success"}}.dump()}}.dump());
+ check(api.exchangeSdp("ABC-123", "v=0 offer") == "v=0\r\n", "SDP exchange waits through 204 replies for the answer");
+ {
+ const json body = json::parse(http->seen[http->seen.size() - 4].body);
+ check(body["messageType"] == "offer" && body["configuration"]["input"]["maxVersion"] == 8, "the offer carries the channel versions");
+ }
+ http->add(host, "/v5/sessions/home/ABC-123/ice", 200, "");
+ http->add(host, "/v5/sessions/home/ABC-123/ice", 200, json{{"exchangeResponse", R"([{"candidate":"a=candidate:2 1 UDP 90 192.168.1.30 9002 typ host","sdpMid":"0","sdpMLineIndex":0}])"}}.dump());
+ check(api.exchangeIce("ABC-123", {{"candidate:1 1 udp 2122260223 192.168.1.10 50000 typ host", "0", 0}}).size() == 1, "ICE exchange returns the console's candidates");
+ http->add(host, "/v5/sessions/home/ABC-123/connect", 401, R"({"code":"Unauthorized"})");
+ bool threw = false;
+ try { api.connect("ABC-123", "LPT"); } catch (const ServiceError& e) { threw = e.status == 401; }
+ check(threw, "a refused connect is a ServiceError with the status");
+}
+
+// ---------------------------------------------------------------- sign-in
+
+void accountTests() {
+ const auto dir = std::filesystem::temp_directory_path() / ("veyra-xbox-test-" + std::to_string(GetCurrentProcessId()));
+ std::filesystem::create_directories(dir);
+ const auto file = dir / "account.bin";
+ int64_t now = 1'800'000'000;
+
+ auto http = std::make_shared<FakeTransport>();
+ {
+ Account account(http, file);
+ account.setClock([&] { return now; });
+ check(!account.signedIn(), "no saved sign-in at first");
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/devicecode", 200,
+ R"({"user_code":"ABCD-EFGH","device_code":"DEV","verification_uri":"https://www.microsoft.com/link","expires_in":900,"interval":5,"message":"..."})");
+ const DeviceCode code = account.beginSignIn();
+ check(code.userCode == "ABCD-EFGH" && code.verificationUri == "https://www.microsoft.com/link" && code.intervalSeconds == 5, "device code");
+ check(http->seen.back().body.find("client_id=1f907974-e22b-4810-a9de-d9647380c97e") != std::string::npos &&
+ http->seen.back().body.find("scope=xboxlive.signin%20openid%20profile%20offline_access") != std::string::npos, "device code uses the xbox.com client id and scope");
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/token", 400, R"({"error":"authorization_pending"})");
+ check(account.pollSignIn(code) == SignInPoll::Pending, "pending while the user has not signed in");
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/token", 400, R"({"error":"slow_down"})");
+ check(account.pollSignIn(code) == SignInPoll::SlowDown, "slow_down is reported");
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/token", 200, R"({"access_token":"AT1","refresh_token":"RT1","expires_in":3600})");
+ check(account.pollSignIn(code) == SignInPoll::Done && account.signedIn(), "signed in");
+ check(std::filesystem::exists(file), "the sign-in is saved");
+ std::ifstream in(file, std::ios::binary);
+ const std::string raw((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
+ check(raw.find("RT1") == std::string::npos, "the saved file does not contain the refresh token in clear");
+ }
+ {
+ Account account(http, file);
+ account.setClock([&] { return now; });
+ check(account.signedIn(), "the sign-in survives a restart");
+ http->add("user.auth.xboxlive.com", "/user/authenticate", 200, R"({"Token":"UT","NotAfter":"2027-01-01T00:00:00.0000000Z","DisplayClaims":{"xui":[{"uhs":"123"}]}})");
+ http->add("xsts.auth.xboxlive.com", "/xsts/authorize", 200, R"({"Token":"GSSV","NotAfter":"2027-01-01T00:00:00Z","DisplayClaims":{"xui":[{"uhs":"123"}]}})");
+ http->add("xhome.gssv-play-prod.xboxlive.com", "/v2/login/user", 200,
+ R"({"offeringSettings":{"regions":[{"name":"WestEurope","baseUri":"https://weu.core.gssv-play-prodxhome.xboxlive.com","isDefault":false},{"name":"EastAsia","baseUri":"https://eas.core.gssv-play-prodxhome.xboxlive.com/","isDefault":true}]},"market":"CN","gsToken":"GS","tokenType":"bearer","durationInSeconds":14400})");
+ const StreamingAccess access = account.streamingAccess();
+ check(access.host == "eas.core.gssv-play-prodxhome.xboxlive.com" && access.gsToken == "GS" && access.regionName == "EastAsia", "the default region and the streaming token");
+ const json userAuth = json::parse(http->seen[http->seen.size() - 3].body);
+ check(userAuth["Properties"]["RpsTicket"] == "d=AT1" && userAuth["RelyingParty"] == "http://auth.xboxlive.com", "user authentication uses the access token as an RPS ticket");
+ const json xsts = json::parse(http->seen[http->seen.size() - 2].body);
+ check(xsts["RelyingParty"] == "http://gssv.xboxlive.com/" && xsts["Properties"]["UserTokens"][0] == "UT", "XSTS for the gssv relying party");
+ check(http->seen.back().headers["x-gssv-client"] == "XboxComBrowser" && json::parse(http->seen.back().body)["offeringId"] == "xhome", "streaming sign-in for the xhome offering");
+ const size_t before = http->seen.size();
+ account.streamingAccess();
+ check(http->seen.size() == before, "a valid streaming token is reused");
+
+ http->add("login.live.com", "/oauth20_token.srf", 200, R"({"access_token":"LPT","refresh_token":"RT-X"})");
+ check(account.transferToken() == "LPT", "console transfer token");
+ check(http->seen.back().body.find("PURPOSE_XBOX_CLOUD_CONSOLE_TRANSFER_TOKEN") != std::string::npos && http->seen.back().body.find("refresh_token=RT1") != std::string::npos,
+ "the transfer token comes from the refresh token");
+
+ // An hour later the access token has expired: it is refreshed and the rotated refresh token kept.
+ now += 3700;
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/token", 200, R"({"access_token":"AT2","refresh_token":"RT2","expires_in":3600})");
+ http->add("login.live.com", "/oauth20_token.srf", 200, R"({"access_token":"LPT2"})");
+ check(account.transferToken() == "LPT2" && http->seen.back().body.find("refresh_token=RT2") != std::string::npos, "an expired access token is refreshed and the new refresh token used");
+ }
+ {
+ Account account(http, file);
+ account.setClock([&] { return now + 7200; });
+ http->add("login.microsoftonline.com", "/consumers/oauth2/v2.0/token", 400, R"({"error":"invalid_grant"})");
+ bool expired = false;
+ try { account.transferToken(); } catch (const ServiceError& e) { expired = e.status == 400; }
+ check(expired && !account.signedIn() && !std::filesystem::exists(file), "a refused refresh signs out and deletes the saved sign-in");
+ }
+ check(describeXboxError(R"({"Identity":"0","XErr":2148916233,"Message":""})").find(L"Xbox 档案") != std::wstring::npos, "XErr: no Xbox profile");
+ check(describeXboxError("not json").empty(), "an unknown error has no sentence");
+ std::error_code ec;
+ std::filesystem::remove_all(dir, ec);
+}
+
+// ---------------------------------------------------------------- WebRTC loopback
+
+// A second libdatachannel peer playing the console: answers the offer, sends H.264 and Opus, speaks the
+// message-channel handshake and records what the client sends.
+class FakeConsole final : public Signaling {
+public:
+ FakeConsole() {
+ rtc::Configuration config;
+ config.disableAutoNegotiation = true;
+ config.bindAddress = "127.0.0.1"; // loopback only: VPN/TUN adapters must not take the test's packets
+ pc = std::make_shared<rtc::PeerConnection>(config);
+ pc->onGatheringStateChange([this](rtc::PeerConnection::GatheringState) { cv.notify_all(); });
+ pc->onTrack([this](std::shared_ptr<rtc::Track> track) {
+ auto desc = track->description();
+ if (desc.type() == "video") {
+ desc.addSSRC(4242, "video");
+ track->setDescription(desc);
+ auto config = std::make_shared<rtc::RtpPacketizationConfig>(4242, "video", 102, rtc::H264RtpPacketizer::ClockRate);
+ track->setMediaHandler(std::make_shared<rtc::H264RtpPacketizer>(rtc::NalUnit::Separator::LongStartSequence, config, 1200));
+ video = track;
+ videoConfig = config;
+ } else if (desc.type() == "audio") {
+ desc.addSSRC(4343, "audio");
+ track->setDescription(desc);
+ auto config = std::make_shared<rtc::RtpPacketizationConfig>(4343, "audio", 111, 48000);
+ track->setMediaHandler(std::make_shared<rtc::OpusRtpPacketizer>(config));
+ audio = track;
+ audioConfig = config;
+ }
+ });
+ pc->onDataChannel([this](std::shared_ptr<rtc::DataChannel> dc) {
+ std::lock_guard lock(mutex);
+ channels.push_back(dc); // libdatachannel drops the callbacks of a channel nobody holds
+ labels.push_back(dc->label() + "/" + dc->protocol());
+ if (dc->label() == "message") {
+ message = dc;
+ dc->onMessage([this](rtc::message_variant data) {
+ std::string text;
+ if (auto* b = std::get_if<rtc::binary>(&data)) text.assign(reinterpret_cast<const char*>(b->data()), b->size());
+ else text = std::get<std::string>(data);
+ const json j = json::parse(text);
+ std::lock_guard l(mutex);
+ messages.push_back(j.value("type", "") + " " + j.value("target", ""));
+ if (j.value("type", "") == "Handshake") {
+ const std::string ack = json{{"type", "HandshakeAck"}, {"id", j.value("id", "")}, {"cv", ""}}.dump();
+ message->send(ack);
+ }
+ cv.notify_all();
+ });
+ } else if (dc->label() == "control") {
+ dc->onMessage([this](rtc::message_variant data) {
+ std::string text;
+ if (auto* b = std::get_if<rtc::binary>(&data)) text.assign(reinterpret_cast<const char*>(b->data()), b->size());
+ else text = std::get<std::string>(data);
+ std::lock_guard l(mutex);
+ control.push_back(json::parse(text).value("message", ""));
+ cv.notify_all();
+ });
+ } else if (dc->label() == "input") {
+ input = dc;
+ dc->onMessage([this](rtc::message_variant data) {
+ if (auto* b = std::get_if<rtc::binary>(&data)) {
+ std::lock_guard l(mutex);
+ reports.emplace_back(reinterpret_cast<const uint8_t*>(b->data()), reinterpret_cast<const uint8_t*>(b->data()) + b->size());
+ cv.notify_all();
+ }
+ });
+ }
+ });
+ }
+ ~FakeConsole() override { if (pc) pc->close(); }
+
+ std::string exchangeSdp(const std::string& offer) override {
+ offerSdp = offer;
+ pc->setRemoteDescription(rtc::Description(offer, rtc::Description::Type::Offer));
+ pc->setLocalDescription(rtc::Description::Type::Answer);
+ std::unique_lock lock(mutex);
+ cv.wait_for(lock, std::chrono::seconds(5), [&] { return pc->gatheringState() == rtc::PeerConnection::GatheringState::Complete; });
+ std::string sdp = std::string(*pc->localDescription());
+ // Answer without candidates: they go through the ICE exchange, as with the service.
+ std::string out, line;
+ std::istringstream in(sdp);
+ while (std::getline(in, line)) {
+ if (line.rfind("a=candidate", 0) == 0 || line.rfind("a=end-of-candidates", 0) == 0) continue;
+ out += line + "\n";
+ }
+ return out;
+ }
+
+ std::vector<IceCandidate> exchangeIce(const std::vector<IceCandidate>& local) override {
+ for (const auto& c : local) pc->addRemoteCandidate(rtc::Candidate(c.candidate, c.sdpMid));
+ std::vector<IceCandidate> out;
+ for (const auto& c : pc->localDescription()->candidates()) out.push_back({"a=" + std::string(c.candidate()), "0", 0});
+ return out;
+ }
+
+ template <typename F> bool waitFor(F f, int ms = 5000) {
+ std::unique_lock lock(mutex);
+ return cv.wait_for(lock, std::chrono::milliseconds(ms), f);
+ }
+
+ std::shared_ptr<rtc::PeerConnection> pc;
+ std::shared_ptr<rtc::Track> video, audio;
+ std::shared_ptr<rtc::RtpPacketizationConfig> videoConfig, audioConfig;
+ std::shared_ptr<rtc::DataChannel> message, input;
+ std::vector<std::shared_ptr<rtc::DataChannel>> channels;
+ std::mutex mutex;
+ std::condition_variable cv;
+ std::vector<std::string> labels, messages, control;
+ std::vector<std::vector<uint8_t>> reports;
+ std::string offerSdp;
+};
+
+std::vector<uint8_t> nal(uint8_t header, size_t size, uint8_t seed) {
+ std::vector<uint8_t> out = {0, 0, 0, 1, header};
+ for (size_t i = 0; i < size; ++i) out.push_back(uint8_t((i * 31 + seed) | 1)); // never a start-code pattern
+ return out;
+}
+
+void webrtcTests() {
+ FakeConsole console;
+ WebRtcSession session;
+ session.setBindAddress("127.0.0.1");
+ std::mutex m;
+ std::vector<std::vector<uint8_t>> units;
+ std::vector<std::vector<uint8_t>> opus;
+ std::optional<Vibration> vibration;
+ uint32_t serverW = 0, serverH = 0;
+ WebRtcCallbacks callbacks;
+ callbacks.video = [&](std::vector<uint8_t>&& unit, uint32_t, int64_t arrival) { std::lock_guard l(m); if (arrival > 0) units.push_back(std::move(unit)); };
+ callbacks.audio = [&](const uint8_t* d, size_t n, uint32_t) { std::lock_guard l(m); opus.emplace_back(d, d + n); };
+ callbacks.vibration = [&](const Vibration& v) { std::lock_guard l(m); vibration = v; };
+ callbacks.serverVideoSize = [&](uint32_t w, uint32_t h) { std::lock_guard l(m); serverW = w; serverH = h; };
+ session.setCallbacks(callbacks);
+
+ std::string error;
+ const bool started = session.start(console, &error, std::chrono::seconds(15));
+ check(started, ("the client connects to a local peer playing the console: " + error).c_str());
+ if (!started) return;
+ check(console.offerSdp.find("profile-level-id=4d001f") != std::string::npos && console.offerSdp.find("profile-level-id=42e01f") != std::string::npos,
+ "the offer lists H.264 Main and Constrained Baseline");
+ check(console.offerSdp.find("a=candidate") == std::string::npos, "the offer carries no candidates (they go through the ICE exchange)");
+ check(session.waitReady(std::chrono::seconds(5)), "the message-channel handshake completes");
+ check(console.waitFor([&] { return console.labels.size() == 4; }), "four data channels arrive");
+ {
+ std::lock_guard l(console.mutex);
+ std::vector<std::string> sorted = console.labels;
+ std::sort(sorted.begin(), sorted.end());
+ check(sorted == std::vector<std::string>{"chat/chatV1", "control/controlV1", "input/1.0", "message/messageV1"}, "channel labels and protocols as the reference client");
+ }
+ check(console.waitFor([&] { return console.control.size() >= 4; }), "control messages arrive");
+ {
+ std::lock_guard l(console.mutex);
+ check(console.control.size() >= 2 && console.control[0] == "authorizationRequest" && console.control[1] == "gamepadChanged", "control: authorization, then the pad");
+ }
+ check(console.waitFor([&] { return !console.reports.empty(); }), "the input channel receives the client metadata report");
+ {
+ std::lock_guard l(console.mutex);
+ check(!console.reports.empty() && console.reports[0].size() == 15 && console.reports[0][0] == 8, "first input report is client metadata");
+ }
+ check(console.waitFor([&] {
+ for (const auto& s : console.messages) if (s.find("/streaming/characteristics/dimensionschanged") != std::string::npos) return true;
+ return false;
+ }), "the client sends its configuration messages");
+
+ GamepadFrame pad;
+ pad.buttons = BtnA;
+ pad.leftX = 1234;
+ session.sendGamepad(pad);
+ check(console.waitFor([&] { return console.reports.size() >= 2; }), "a gamepad report arrives");
+ {
+ std::lock_guard l(console.mutex);
+ const auto r = console.reports.empty() ? std::vector<uint8_t>{} : console.reports.back();
+ const auto expected = gamepadReport(1, 0, {pad});
+ check(r.size() == expected.size() && std::equal(r.begin() + 14, r.end(), expected.begin() + 14) && r[0] == 2, "gamepad report bytes as built");
+ }
+
+ // Console -> client: a vibration report and the server's video size on the input channel.
+ const uint8_t vib[] = {128, 0, 0, 0, 60, 40, 0, 0, 100, 0, 0, 0, 0};
+ console.input->send(reinterpret_cast<const std::byte*>(vib), sizeof(vib));
+ const uint8_t size[] = {16, 0, 0x38, 0x04, 0, 0, 0x80, 0x07, 0, 0};
+ console.input->send(reinterpret_cast<const std::byte*>(size), sizeof(size));
+
+ // Media: wait until the console's tracks are open, then send an IDR access unit larger than one
+ // packet (fragmented) and a P frame, and two Opus packets.
+ check(console.waitFor([&] { return console.video && console.video->isOpen() && console.audio && console.audio->isOpen(); }), "the console's media tracks open");
+ std::vector<std::vector<uint8_t>> sent;
+ std::vector<uint8_t> idr;
+ for (const auto& part : {nal(0x67, 12, 1), nal(0x68, 4, 2), nal(0x65, 5000, 3)}) idr.insert(idr.end(), part.begin(), part.end());
+ const auto p1 = nal(0x41, 800, 4);
+ sent.push_back(idr);
+ sent.push_back(p1);
+ uint32_t ts = 0;
+ for (const auto& unit : sent) {
+ console.videoConfig->timestamp = ts;
+ console.video->sendFrame(reinterpret_cast<const std::byte*>(unit.data()), unit.size(), rtc::FrameInfo(ts));
+ ts += 1500;
+ }
+ // A third frame: the depacketizer emits a frame once the next timestamp starts.
+ const auto p2 = nal(0x41, 100, 5);
+ console.video->sendFrame(reinterpret_cast<const std::byte*>(p2.data()), p2.size(), rtc::FrameInfo(ts));
+ const std::vector<uint8_t> opus1 = {0xFC, 1, 2, 3}, opus2 = {0xFC, 4, 5, 6, 7};
+ console.audio->sendFrame(reinterpret_cast<const std::byte*>(opus1.data()), opus1.size(), rtc::FrameInfo(uint32_t(0)));
+ console.audio->sendFrame(reinterpret_cast<const std::byte*>(opus2.data()), opus2.size(), rtc::FrameInfo(uint32_t(960)));
+
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
+ while (std::chrono::steady_clock::now() < deadline) {
+ {
+ std::lock_guard l(m);
+ if (units.size() >= 2 && opus.size() >= 2 && vibration && serverW) break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ }
+ {
+ std::lock_guard l(m);
+ check(units.size() >= 2, "access units arrive");
+ check(units.size() >= 2 && units[0] == sent[0], "the fragmented IDR access unit (SPS, PPS, IDR) arrives byte for byte, Annex-B");
+ check(units.size() >= 2 && units[1] == sent[1], "the P frame arrives byte for byte");
+ check(opus.size() >= 2 && opus[0] == opus1 && opus[1] == opus2, "Opus packets arrive unchanged");
+ check(vibration && vibration->leftMotor == 60 && vibration->rightMotor == 40 && vibration->durationMs == 100, "vibration reaches the callback");
+ check(serverW == 1920 && serverH == 1080, "server video size reaches the callback");
+ }
+ session.requestKeyframe();
+ check(console.waitFor([&] { for (const auto& c : console.control) if (c == "videoKeyframeRequested") return true; return false; }), "a keyframe request goes out on the control channel");
+ const auto stats = session.stats();
+ if (!(stats.videoUnits >= 2 && stats.audioPackets >= 2 && stats.handshakeDone && stats.videoBytes > 5000))
+ std::printf("stats: units=%llu audio=%llu handshake=%d bytes=%llu\n", (unsigned long long)stats.videoUnits, (unsigned long long)stats.audioPackets, int(stats.handshakeDone), (unsigned long long)stats.bytesReceived);
+ check(stats.videoUnits >= 2 && stats.audioPackets >= 2 && stats.handshakeDone && stats.videoBytes > 5000, "statistics");
+ session.close();
+ check(!session.ready() || true, "close() returns");
+}
+
+} // namespace
+
+int main() {
+ protocolTests();
+ apiTests();
+ accountTests();
+ webrtcTests();
+ std::printf("xbox tests: %d checks, %d failures\n", g_checks, g_failures);
+ rtc::Cleanup();
+ return g_failures == 0 ? 0 : 1;
+}