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): engine source, Xbox dialog and home card (X2, X3)

Veyra Goal Agent5a6ba03132f6
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f2a09337..d65759e1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -566,8 +566,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
if(VEYRA_ENABLE_XBOX)
set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
include(VeyraXbox)
+ find_package(Opus CONFIG REQUIRED)
target_compile_definitions(veyra_sources PUBLIC VEYRA_ENABLE_XBOX=1)
- target_link_libraries(veyra_sources PUBLIC veyra_xbox_protocol)
+ target_sources(veyra_sources PRIVATE src/source/XboxSessionSource.cpp)
+ target_link_libraries(veyra_sources PUBLIC veyra_xbox_protocol PRIVATE Opus::opus)
endif()
add_executable(veyra_source_tests
@@ -812,6 +814,15 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
target_compile_definitions(veyra_moonlight_model PUBLIC VEYRA_ENABLE_MOONLIGHT=1 PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_moonlight_model PUBLIC veyra_moonlight_protocol veyra_base Qt6::Core Qt6::Gui)
target_link_libraries(veyra_qml_bridge PUBLIC veyra_moonlight_model)
+ if(VEYRA_ENABLE_XBOX)
+ add_library(veyra_xbox_model STATIC src/ui/XboxModel.cpp include/veyra/ui/XboxModel.h)
+ set_target_properties(veyra_xbox_model PROPERTIES AUTOMOC ON)
+ target_compile_features(veyra_xbox_model PUBLIC cxx_std_20)
+ target_include_directories(veyra_xbox_model PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${FFMPEG_INCLUDE_DIRS})
+ target_compile_definitions(veyra_xbox_model PUBLIC VEYRA_ENABLE_XBOX=1 PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_xbox_model PUBLIC veyra_xbox_protocol veyra_base Qt6::Core Qt6::Gui)
+ target_link_libraries(veyra_qml_bridge PUBLIC veyra_xbox_model)
+ endif()
add_executable(veyra_moonlight_model_tests tests/moonlight/ModelTests.cpp)
target_compile_features(veyra_moonlight_model_tests PRIVATE cxx_std_20)
diff --git a/docs/XBOX_EXECUTION_2026-10-01.md b/docs/XBOX_EXECUTION_2026-10-01.md
index 6353529f..e65ab524 100644
--- a/docs/XBOX_EXECUTION_2026-10-01.md
+++ b/docs/XBOX_EXECUTION_2026-10-01.md
@@ -13,8 +13,8 @@
| 阶段 | 内容 | 状态 |
|---|---|---|
| X1 | 依赖(libdatachannel 等经 vcpkg)、登录、会话 API、WebRTC 会话与协议 | 完成,离线 72 项通过 |
-| X2 | 引擎来源、解码、音频、手柄与震动 | 未开始 |
-| X3 | 前端:首页卡片、Xbox 对话框(登录码、主机列表)、统计 | 未开始 |
+| X2 | 引擎来源、解码、音频、手柄与震动 | 代码完成,编译通过,未连过真机 |
+| X3 | 前端:首页卡片、Xbox 对话框(登录码、主机列表)、统计 | 完成,截图检查;未登录真实账号 |
| X4 | 用户本人账号与主机实测;beta | 需要用户 |
## X1 记录
@@ -29,3 +29,16 @@
- WebRTC:第二个本地 libdatachannel 节点扮演主机,走真实的 ICE/DTLS/SCTP/RTP:四条通道的名字与协议、握手与授权、客户端元数据与手柄报告逐字节、分片的 IDR 访问单元逐字节还原为 Annex-B、Opus 原样、震动与画面尺寸回调、关键帧请求。
- **未验证**:任何与微软服务器或真实 Xbox 的交互。假服务和本地"主机"都是按 Greenlight 的协议理解写的,只证明客户端自洽、本地 WebRTC 链路可用。
- 调试开关:环境变量 `VEYRA_XBOX_RTC_DEBUG=1` 打开 libdatachannel 的详细日志与候选地址日志(现场排查用)。
+
+## X2/X3 记录
+
+- `XboxSessionSource`(引擎来源):登录串流服务 → `play` → 轮询状态(`ReadyToConnect` 时发转移令牌)→ WebRTC → 握手;H.264 进共享的硬解(失败回落软解),先等关键帧/SPS 再解码,解码出错或积压时请求关键帧(每 500 ms 最多一次);视频队列最多 8 个访问单元,超出丢最旧(低延迟优先)。Opus 立体声 48 kHz 进与采集卡相同的音频会话。30 秒保活;会话结束时在后台线程通知服务器结束,不阻塞引擎。
+- 手柄:每 4 ms 读一次 SDL,变化即发,至少每 33 ms 一次心跳(参考客户端的做法);断开时发一个全松开的帧。震动按报告的时长自动停止。
+- 引擎:`openXbox`、快照里的 `xboxActive`/`xbox`;`isStream` 现在包括 Xbox;PS5、Moonlight 路径不变。
+- 前端:首页 6 张卡(Xbox 串流,标"账号登录 · 实验"),专业页/节点页片源菜单加"Xbox 串流…";Xbox 对话框:顶部固定"非官方"提示、登录(大号登录码 + 打开 microsoft.com/link)、主机列表(型号与电源状态)、手柄开关;"继续上次"支持 Xbox;统计浮层同时支持 PC 与 Xbox(Ctrl+Alt+Shift+S)。
+- 验证:
+ - 对微软真实服务只做了一项无账号检查:用产品同一个客户端身份请求设备登录码,微软正常发码(8 位、microsoft.com/link、900 秒有效)。
+ - 首页与 Xbox 对话框截图(未登录态):`tests/xbox-20261001/ui-shots-r1`。
+ - 在这个构建上重跑 Moonlight 端到端界面检查,通过(`tests/xbox-20261001/moonlight-regression`)。
+ - 全部单元测试通过(Xbox 72、Moonlight 协议 134、模型 42、原有 UI/效果/修复/预设测试)。
+- **未验证(需要你本人)**:用真实账号登录、列出主机、真实串流(画面、声音、手柄、震动、延迟)。没有现成的 HEVC/高码率协商:参考客户端只协商 H.264,通常最高 1080p60。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 73cffef9..fdf6d11b 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -16,9 +16,12 @@
#ifdef VEYRA_ENABLE_MOONLIGHT
#include "veyra/source/MoonlightSessionSource.h"
#endif
+#ifdef VEYRA_ENABLE_XBOX
+#include "veyra/source/XboxSessionSource.h"
+#endif
#include "veyra/media/AudioTrack.h"
#include "veyra/sink/VideoEncoder.h"
-namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; }
+namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; struct XboxConnectDesc; class XboxSessionSource; }
namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }
namespace veyra::sink { struct RgbaImage; }
namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }
@@ -116,6 +119,9 @@ struct PlayerSnapshot {
#ifdef VEYRA_ENABLE_MOONLIGHT
bool moonlightActive=false;source::MoonlightStats moonlight;
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ bool xboxActive=false;source::XboxStats xbox;
+#endif
};
class EngineController {
public:
@@ -141,6 +147,12 @@ public:
void moonlightMouseButton(int button, bool down);
void moonlightScroll(int delta, bool horizontal);
void moonlightReleaseInput();
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ void openXbox(HWND, source::XboxConnectDesc, PlayerOptions);
+ // Pad and rumble for the running Xbox session; no-ops when none is streaming.
+ void xboxController(const remoteplay::ControllerState&);
+ remoteplay::ControllerFeedback xboxFeedback();
#endif
void stop();
void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}
@@ -154,7 +166,7 @@ public:
void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);
PlayerSnapshot snapshot()const;
private:
- void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={},std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest={});
+ void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={},std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest={},std::shared_ptr<source::XboxConnectDesc> xboxRequest={});
void runLargeImage(HWND,const sink::RgbaImage&,PlayerOptions,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&);
void post(std::function<void()>);
void dispatch();
@@ -166,6 +178,7 @@ private:
std::shared_ptr<FrameFlowWindow> activeFlow_;
std::shared_ptr<source::RemotePlaySessionSource> activeRemote_;
std::shared_ptr<source::MoonlightSessionSource> activeMoonlight_;
+ std::shared_ptr<source::XboxSessionSource> activeXbox_;
PreviewView previewView_;
std::wstring savePath_;
std::thread worker_;
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index c741ca46..dbf01a07 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -45,6 +45,7 @@ enum class SourceKind : uint8_t {
TestPattern, // synthetic harness input
ScreenCapture,
Moonlight, // Sunshine / GameStream host stream (moonlight-common-c transport)
+ Xbox, // Xbox home streaming (WebRTC, unofficial)
};
inline const char* sourceKindName(SourceKind k) {
@@ -56,6 +57,7 @@ inline const char* sourceKindName(SourceKind k) {
case SourceKind::TestPattern: return "TestPattern";
case SourceKind::ScreenCapture: return "ScreenCapture";
case SourceKind::Moonlight: return "Moonlight";
+ case SourceKind::Xbox: return "Xbox";
default: return "Unknown";
}
}
diff --git a/include/veyra/source/XboxSessionSource.h b/include/veyra/source/XboxSessionSource.h
new file mode 100644
index 00000000..9ade0334
--- /dev/null
+++ b/include/veyra/source/XboxSessionSource.h
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+// XboxSessionSource: one home-streaming session from the user's own Xbox console (unofficial; protocol of
+// Greenlight). It provisions the session through Microsoft's streaming service, receives H.264 and Opus
+// over WebRTC (libdatachannel), decodes the video with the shared hardware decoder and plays the audio.
+// The effect chain is not part of it.
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <thread>
+
+#include "veyra/remoteplay/Types.h"
+#include "veyra/sink/CaptureAudioSession.h"
+#include "veyra/source/IFrameSource.h"
+
+struct AVFrame;
+struct ID3D12Device;
+struct ID3D12CommandQueue;
+
+namespace veyra::xbox { class Account; }
+
+namespace veyra::source {
+
+struct XboxConnectDesc {
+ std::shared_ptr<xbox::Account> account;
+ std::string serverId; // the console
+ std::string consoleName; // for messages
+ bool gamepad = true; // forward the PC's controller
+ std::string locale = "zh-CN";
+ std::shared_ptr<ID3D12Device> decodeDevice;
+ std::shared_ptr<ID3D12CommandQueue> decodeQueue;
+};
+
+struct XboxStats {
+ enum class State : uint8_t { Idle, Starting, Connecting, Streaming, Ended, Failed };
+ State state = State::Idle;
+ std::wstring message; // progress while starting; the reason when Ended or Failed
+ uint32_t width = 0, height = 0;
+ bool hardwareDecode = false;
+ uint64_t units = 0, decoded = 0, dropped = 0, decodeErrors = 0, keyframeRequests = 0;
+ double receivedFps = 0, decodedFps = 0, videoMbps = 0;
+ double decodeMs = 0, rttMs = 0;
+};
+
+class XboxSessionSource final : public IFrameSource {
+public:
+ XboxSessionSource();
+ ~XboxSessionSource() override;
+ XboxSessionSource(const XboxSessionSource&) = delete;
+ XboxSessionSource& operator=(const XboxSessionSource&) = delete;
+
+ // Starts the console session and connects. Blocks until the stream is up or failed (up to about a
+ // minute while the console wakes); false means see stats().message. cancel() aborts it from another thread.
+ bool connect(XboxConnectDesc desc);
+ void cancel() { cancel_ = true; }
+
+ bool open(const SourceOpenDesc&) override { return false; }
+ const SourceInfo& info() const override { return info_; }
+ SourceReadStatus read(pipeline::FramePacket&, const AVFrame**) override;
+ bool seek(const pipeline::Rational&) override { return false; }
+ void close() noexcept override;
+
+ XboxStats stats() const;
+ uint64_t skipped() const;
+ uint64_t unitsReceived() const;
+ sink::CaptureAudioState audioState() const { return audio_.snapshot(); }
+ void setAudioGain(float value) { audio_.setGain(value); }
+ void setAudioSync(unsigned mode, int offset) { audio_.setSync(mode, offset); }
+ void videoPresented(double ptsMs, int64_t host100ns);
+ void videoReset(bool resetAudio = true) { audio_.videoReset(resetAudio); }
+
+ // Controller 0; sent when it changes and at least every 33 ms (the console expects a heartbeat).
+ void controller(const remoteplay::ControllerState& state);
+ remoteplay::ControllerFeedback takeFeedback();
+
+private:
+ struct Impl;
+ void run(XboxConnectDesc desc);
+ void decodeLoop();
+ void publish(std::shared_ptr<AVFrame> frame, const pipeline::FramePacket& packet, const SourceInfo& info);
+ void setState(XboxStats::State state, std::wstring message);
+
+ std::unique_ptr<Impl> p_;
+ mutable std::mutex mutex_;
+ std::condition_variable ready_;
+ std::atomic<bool> cancel_{false};
+ bool initialized_ = false, started_ = false;
+ SourceInfo info_, publishedInfo_;
+ struct Frame { std::shared_ptr<AVFrame> frame; pipeline::FramePacket packet; SourceInfo info; };
+ std::optional<Frame> latest_;
+ std::shared_ptr<AVFrame> view_;
+ uint64_t sequence_ = 0, skipped_ = 0;
+ bool openFlagPending_ = true;
+ XboxStats stats_;
+ sink::CaptureAudioSession audio_;
+ std::jthread owner_;
+};
+
+} // namespace veyra::source
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 6b46bac9..71be84e6 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -41,6 +41,7 @@
namespace veyra::ui {
class MoonlightModel;
+class XboxModel;
class QmlPlayerBridge : public QObject {
Q_OBJECT
@@ -161,6 +162,8 @@ class QmlPlayerBridge : public QObject {
// PC streaming (Moonlight / Sunshine): hosts, pairing, apps and stream settings live in
// `moonlight` (null when the build has no Moonlight); capture state and the stats overlay here.
Q_PROPERTY(QObject* moonlight READ moonlightModel CONSTANT)
+ // Xbox home streaming (unofficial): sign-in, consoles and stream state; null without Xbox support.
+ Q_PROPERTY(QObject* xbox READ xboxModel CONSTANT)
Q_PROPERTY(bool moonlightCaptured READ moonlightCaptured NOTIFY moonlightUiChanged)
Q_PROPERTY(bool moonlightStatsVisible READ moonlightStatsVisible WRITE setMoonlightStatsVisible NOTIFY moonlightUiChanged)
@@ -545,6 +548,9 @@ public:
Q_INVOKABLE void openMoonlightDialog();
Q_INVOKABLE void moonlightCapture(bool on);
Q_INVOKABLE void moonlightDisconnect();
+ QObject* xboxModel() const;
+ Q_INVOKABLE void openXboxDialog();
+ Q_INVOKABLE void xboxDisconnect();
Q_INVOKABLE void ps5Load();
Q_INVOKABLE bool ps5Set(const QString& key, const QVariant& value);
Q_INVOKABLE void ps5SelectProfile(const QString& id);
@@ -1006,6 +1012,10 @@ private:
void tickCapture();
void tickPs5();
void tickMoonlight();
+ void tickXbox();
+#ifdef VEYRA_ENABLE_XBOX
+ void setupXbox();
+#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
void setupMoonlight();
#endif
diff --git a/include/veyra/ui/XboxModel.h b/include/veyra/ui/XboxModel.h
new file mode 100644
index 00000000..a5ae7dc7
--- /dev/null
+++ b/include/veyra/ui/XboxModel.h
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+// The "Xbox 串流" side of the UI (unofficial): Microsoft device-code sign-in, the consoles on the account,
+// and starting a stream. Network work runs on worker threads and reports back on the UI thread.
+#include <QObject>
+#include <QVariantList>
+#include <QVariantMap>
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <thread>
+
+#include "veyra/source/XboxSessionSource.h"
+#include "veyra/xbox/Account.h"
+
+namespace veyra::ui {
+
+class XboxModel final : public QObject {
+ Q_OBJECT
+ // {signedIn, busy, status, code, verificationUri, selected, gamepad, streaming, stream{...}, lastLabel}
+ Q_PROPERTY(QVariantMap state READ state NOTIFY changed)
+ // [{id, name, type, power, selected}]
+ Q_PROPERTY(QVariantList consoles READ consoles NOTIFY changed)
+public:
+ struct Launch {
+ source::XboxConnectDesc desc;
+ QString label;
+ };
+ using LaunchFn = std::function<bool(Launch)>;
+
+ explicit XboxModel(QObject* parent = nullptr);
+ ~XboxModel() override;
+
+ void setLaunchHandler(LaunchFn handler) { launch_ = std::move(handler); }
+ void updateStream(bool active, const source::XboxStats& stats);
+
+ QVariantMap state() const;
+ QVariantList consoles() const { return consoles_; }
+
+ Q_INVOKABLE void load();
+ Q_INVOKABLE void signIn();
+ Q_INVOKABLE void openSignInPage();
+ Q_INVOKABLE void signOut();
+ Q_INVOKABLE void refresh();
+ Q_INVOKABLE void select(const QString& id);
+ Q_INVOKABLE void cancel();
+ Q_INVOKABLE bool connectStream();
+ Q_INVOKABLE bool resumeLast();
+ Q_INVOKABLE bool set(const QString& key, const QVariant& value);
+
+ QString lastLabel() const { return lastName_; }
+
+signals:
+ void changed();
+ void started();
+ void notice(const QString& text, bool isError);
+
+private:
+ void startJob(const QString& status, std::function<std::function<void()>(const std::atomic<bool>&)> work);
+ void loadSettings();
+ void saveSettings() const;
+ bool launchConsole(const QString& id, const QString& name);
+
+ LaunchFn launch_;
+ std::shared_ptr<xbox::Account> account_;
+ QVariantList consoles_;
+ QString selected_, status_, code_, verificationUri_, lastId_, lastName_;
+ bool busy_ = false, gamepad_ = true, loaded_ = false, streamActive_ = false, signingIn_ = false;
+ QVariantMap stream_;
+ std::atomic<bool> cancel_{false};
+ std::jthread worker_;
+};
+
+} // namespace veyra::ui
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index 4c2a14fa..7f4f0651 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -18,7 +18,7 @@ Item {
anchors.fill: parent
z: 100
- // Which dialog is showing: "" | capture | ps5 | moonlight | screen | subtitle | audio
+ // Which dialog is showing: "" | capture | ps5 | moonlight | xbox | screen | subtitle | audio
property string dialog: ""
function open(key) {
@@ -34,6 +34,7 @@ Item {
signal startCapture()
signal startPs5()
signal startMoonlight()
+ signal startXbox()
signal startScreen()
// Scrim (M16): the design dims the page behind the dialog, opacity .2s linear.
@@ -871,6 +872,148 @@ Item {
DNote { objectName: "moonlight-status"; visible: (mlDialog.st.status || "").length > 0; text: (mlDialog.st.busy ? "处理中 · " : "") + (mlDialog.st.status || "") }
}
+ // --- Xbox 串流(非官方) ---------------------------------------------------
+ // Sign in with the Xbox (Microsoft) account on Microsoft's own page via a device code, pick a console,
+ // start. The software never sees the password; only a refresh token is kept, encrypted for this user.
+ DLayer {
+ id: xbDialog
+ objectName: "xbox-dialog"
+ key: "xbox"
+ glyph: "gamepad"
+ title: "Xbox 串流"
+ sub: "串流你自己的 Xbox 主机 · 非官方实验功能 · 增强与调色沿用软件自己的处理链"
+ dialogWidth: 680
+ readonly property var xb: veyra.xbox
+ readonly property var st: xb ? xb.state : ({})
+ readonly property var list: xb ? xb.consoles : []
+ actions: st.streaming ? [
+ { label: "关闭" },
+ { label: "断开", primary: true }
+ ] : !st.signedIn ? [
+ { label: st.busy ? "取消操作" : "关闭" }
+ ] : [
+ { label: st.busy ? "取消操作" : "关闭" },
+ { label: "开始串流", primary: true, icon: "play" }
+ ]
+ onActionTriggered: label => {
+ if (label === "断开") { veyra.xboxDisconnect(); host.close(); return }
+ if (label === "取消操作") { xb.cancel(); return }
+ if (label === "关闭") { host.close(); return }
+ if (st.signedIn && !st.busy && (st.selected || "").length > 0) xb.connectStream()
+ }
+ Connections {
+ target: xbDialog
+ function onShownChanged() { if (xbDialog.shown && xbDialog.xb) xbDialog.xb.load() }
+ }
+ Connections {
+ target: xbDialog.xb
+ function onStarted() { host.close(); host.startXbox() }
+ }
+
+ DNote {
+ text: "非官方:使用与 Greenlight 等开源客户端相同的方式连接微软的串流服务,不隶属于微软,微软随时可能改动导致失效。仅限你自己的账号和主机。"
+ }
+ DSection { text: "账号" }
+ DGroup {
+ VRow {
+ label: xbDialog.st.signedIn ? "已登录" : "未登录"
+ hint: xbDialog.st.signedIn ? "登录信息加密保存在本机;退出会删除它" : "用你的 Xbox(微软)账号在微软的页面登录,软件看不到密码"
+ RowLayout {
+ spacing: 6
+ VSpinner { visible: xbDialog.st.busy === true; Layout.alignment: Qt.AlignVCenter }
+ VButton { objectName: "xbox-signin"; visible: !xbDialog.st.signedIn; text: "登录"; primary: true; enabled: !xbDialog.st.busy; onClicked: xbDialog.xb.signIn() }
+ VButton { visible: xbDialog.st.signedIn; text: "退出登录"; ghost: true; enabled: !xbDialog.st.busy; onClicked: xbDialog.xb.signOut() }
+ }
+ }
+ }
+ // The device code, large, with the page to type it into.
+ Rectangle {
+ visible: (xbDialog.st.code || "").length > 0
+ objectName: "xbox-code-box"
+ Layout.fillWidth: true
+ Layout.topMargin: 8
+ implicitHeight: codeCol.implicitHeight + 28
+ radius: 11
+ color: Theme.accentSoft
+ border.width: 1
+ border.color: Theme.accent
+ ColumnLayout {
+ id: codeCol
+ anchors.fill: parent
+ anchors.margins: 14
+ spacing: 8
+ Text {
+ Layout.fillWidth: true
+ text: "在手机或浏览器打开 " + (xbDialog.st.verificationUri || "https://www.microsoft.com/link") + ",输入下面的登录码:"
+ color: Theme.t2
+ font.family: Theme.fontUi
+ font.pixelSize: Theme.fsSmall
+ wrapMode: Text.WordWrap
+ }
+ Text {
+ objectName: "xbox-code"
+ Layout.alignment: Qt.AlignHCenter
+ text: xbDialog.st.code || ""
+ color: Theme.t1
+ font.family: Theme.fontMono
+ font.pixelSize: 30
+ font.letterSpacing: 4
+ }
+ VButton { Layout.alignment: Qt.AlignHCenter; text: "在浏览器打开登录页"; ghost: true; onClicked: xbDialog.xb.openSignInPage() }
+ }
+ }
+
+ DSection { visible: !!xbDialog.st.signedIn; text: "主机" }
+ Repeater {
+ model: xbDialog.st.signedIn ? xbDialog.list : []
+ delegate: Rectangle {
+ id: consoleRow
+ required property var modelData
+ readonly property bool picked: xbDialog.st.selected === modelData.id
+ objectName: "xbox-console-" + modelData.id
+ Layout.fillWidth: true
+ Layout.topMargin: 6
+ implicitHeight: 54
+ radius: 11
+ color: picked ? Theme.accentSoft : (consoleHover.hovered ? Theme.card3 : Theme.card2)
+ border.width: 1
+ border.color: picked ? Theme.accent : Theme.stroke
+ HoverHandler { id: consoleHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler {
+ onTapped: xbDialog.xb.select(consoleRow.modelData.id)
+ onDoubleTapped: { xbDialog.xb.select(consoleRow.modelData.id); if (!xbDialog.st.busy) xbDialog.xb.connectStream() }
+ }
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 14
+ anchors.rightMargin: 12
+ spacing: 12
+ VDot { off: consoleRow.modelData.power === "关机"; warn: consoleRow.modelData.power === "正在更新"; Layout.alignment: Qt.AlignVCenter }
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 1
+ Text { Layout.fillWidth: true; text: consoleRow.modelData.name; color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: Theme.fsBody; font.weight: Font.Medium; elide: Text.ElideRight }
+ Text { Layout.fillWidth: true; text: consoleRow.modelData.type + " · " + consoleRow.modelData.power; color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: Theme.fsSmall; elide: Text.ElideRight }
+ }
+ }
+ }
+ }
+ DGroup {
+ visible: !!xbDialog.st.signedIn
+ VRow {
+ label: "主机列表"
+ hint: "主机要用同一个账号登录,并在 设置 → 设备和连接 → 远程功能 里启用远程功能"
+ VButton { text: "刷新"; ghost: true; enabled: !xbDialog.st.busy; onClicked: xbDialog.xb.refresh() }
+ }
+ VRow {
+ label: "手柄"
+ hint: "把电脑手柄当作主机上的手柄"
+ VSwitch { objectName: "xbox-gamepad"; checked: xbDialog.st.gamepad !== false; onToggled: xbDialog.xb.set("gamepad", checked) }
+ }
+ }
+ DNote { objectName: "xbox-status"; visible: (xbDialog.st.status || "").length > 0; text: (xbDialog.st.busy ? "处理中 · " : "") + (xbDialog.st.status || "") }
+ }
+
// --- 屏幕捕获 ---------------------------------------------------------
DLayer {
id: screenDialog
diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qml
index d94bc4c1..fb2b259a 100644
--- a/qml/Veyra/HomePage.qml
+++ b/qml/Veyra/HomePage.qml
@@ -78,12 +78,12 @@ VPage {
}
}
- // .srcgrid: 164px cards, gap 12. Five cards since PC streaming (868 wide in a
- // 1280 window); a narrower window wraps them onto a second row.
+ // .srcgrid: 164px cards, gap 12. Six cards since PC and Xbox streaming (1044 wide,
+ // fits a 1280 window); a narrower window wraps them onto a second row.
Flow {
id: srcGrid
Layout.alignment: Qt.AlignHCenter
- Layout.preferredWidth: Math.min(868, root.width - 48)
+ Layout.preferredWidth: Math.min(1044, root.width - 48)
spacing: 12
Repeater {
// Subtitles name what is really there: the device of the last capture
@@ -96,6 +96,8 @@ VPage {
sub: veyra.remotePlayHost.length > 0 ? "已保存主机 " + veyra.remotePlayHost : "局域网串流", act: "ps5" },
{ glyph: "cast", title: "PC 串流",
sub: veyra.moonlight && veyra.moonlight.state.lastLabel ? veyra.moonlight.state.lastLabel : "Sunshine 主机", act: "moonlight" },
+ { glyph: "gamepad", title: "Xbox 串流",
+ sub: veyra.xbox && veyra.xbox.state.lastLabel ? veyra.xbox.state.lastLabel : "账号登录 · 实验", act: "xbox" },
{ glyph: "monitor", title: "屏幕捕获", sub: "窗口或显示器", act: "screen" }
]
// The layout owns the slot's position, so the card inside it is free to
@@ -166,6 +168,7 @@ VPage {
case "capture": veyra.openCaptureDialog(); break
case "ps5": veyra.openPs5Dialog(); break
case "moonlight": veyra.openMoonlightDialog(); break
+ case "xbox": veyra.openXboxDialog(); break
case "screen": veyra.openScreenCaptureDialog(); break
}
}
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index 03deb99c..542bb2ed 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -251,6 +251,7 @@ Window {
onStartCapture: if (root.page === "home") root.goPage("min")
onStartPs5: if (root.page === "home") root.goPage("min")
onStartMoonlight: if (root.page === "home") root.goPage("min")
+ onStartXbox: if (root.page === "home") root.goPage("min")
onStartScreen: if (root.page === "home") root.goPage("min")
}
@@ -421,6 +422,13 @@ Window {
veyra.moonlightCapture(true)
}
}
+ // Stream statistics on and off. While a PC stream has the keyboard, the capture filter sees the keys
+ // first and toggles the same switch.
+ Shortcut {
+ sequence: "Ctrl+Alt+Shift+S"
+ enabled: (veyra.moonlight && veyra.moonlight.state.streaming === true) || (veyra.xbox && veyra.xbox.state.streaming === true)
+ onActivated: veyra.moonlightStatsVisible = !veyra.moonlightStatsVisible
+ }
StreamHud {
id: streamHud
x: 16
@@ -543,7 +551,7 @@ Window {
function onNotice(text, isError) { toast.show(text, isError) }
function onNavigate(p) {
// A dialog key opens the dialog; anything else is a page.
- if (p === "capture" || p === "ps5" || p === "moonlight" || p === "screen"
+ if (p === "capture" || p === "ps5" || p === "moonlight" || p === "xbox" || p === "screen"
|| p === "subtitle" || p === "audio" || p === "save" || p === "manage") {
dialogs.open(p)
return
diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qml
index 3d1f889b..17f884b3 100644
--- a/qml/Veyra/NodePage.qml
+++ b/qml/Veyra/NodePage.qml
@@ -383,7 +383,7 @@ VPage {
VButton {
id: nodeSourceBtn
objectName: "node-source-button"
- iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "screen" ? "monitor"
+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "xbox" ? "gamepad" : veyra.sourceKind === "screen" ? "monitor"
: veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"
text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"
maxTextWidth: 180
@@ -1543,6 +1543,7 @@ VPage {
.concat([{ label: "打开文件…", icon: "folder", act: "file" },
{ label: "PS5 串流…", icon: "gamepad", act: "ps5" },
{ label: "PC 串流…", icon: "cast", act: "moonlight" },
+ { label: "Xbox 串流…", icon: "gamepad", act: "xbox" },
{ label: "屏幕捕获…", icon: "monitor", act: "screen" },
{ sep: true },
{ label: "采集卡设置…", icon: "settings", act: "capture" }])
@@ -1550,6 +1551,7 @@ VPage {
if (o.act === "file") veyra.openFileDialog()
else if (o.act === "ps5") veyra.openPs5Dialog()
else if (o.act === "moonlight") veyra.openMoonlightDialog()
+ else if (o.act === "xbox") veyra.openXboxDialog()
else if (o.act === "screen") veyra.openScreenCaptureDialog()
else if (o.act === "capture") veyra.openCaptureDialog()
}
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 12bf32b3..ecf42ad1 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -356,7 +356,7 @@ VPage {
VButton {
id: sourceBtn
objectName: "pro-source-button"
- iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "screen" ? "monitor"
+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "xbox" ? "gamepad" : veyra.sourceKind === "screen" ? "monitor"
: veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"
text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"
maxTextWidth: 260
@@ -1727,6 +1727,7 @@ VPage {
.concat([{ label: "打开文件…", icon: "folder", act: "file" },
{ label: "PS5 串流…", icon: "gamepad", act: "ps5" },
{ label: "PC 串流…", icon: "cast", act: "moonlight" },
+ { label: "Xbox 串流…", icon: "gamepad", act: "xbox" },
{ label: "屏幕捕获…", icon: "monitor", act: "screen" },
{ sep: true },
{ label: "采集卡设置…", icon: "settings", act: "capture" }])
@@ -1734,6 +1735,7 @@ VPage {
if (o.act === "file") veyra.openFileDialog()
else if (o.act === "ps5") veyra.openPs5Dialog()
else if (o.act === "moonlight") veyra.openMoonlightDialog()
+ else if (o.act === "xbox") veyra.openXboxDialog()
else if (o.act === "screen") veyra.openScreenCaptureDialog()
else if (o.act === "capture") veyra.openCaptureDialog()
}
diff --git a/qml/Veyra/StreamHud.qml b/qml/Veyra/StreamHud.qml
index b05ef290..6b5c7d6f 100644
--- a/qml/Veyra/StreamHud.qml
+++ b/qml/Veyra/StreamHud.qml
@@ -1,7 +1,7 @@
-// The PC stream's own numbers (Ctrl+Alt+Shift+S while streaming): what the host and the network
-// contribute before the picture reaches the software's effect chain. The software's own processing
-// time is on the performance readouts of the professional page; nothing here is invented: a value the
-// host does not report (older Sunshine has no host latency) shows as a dash.
+// The stream's own numbers (Ctrl+Alt+Shift+S while streaming): what the host and the network contribute
+// before the picture reaches the software's effect chain, for PC (Moonlight) and Xbox streams. The
+// software's own processing time is on the performance readouts of the professional page; nothing here is
+// invented: a value the stream does not report shows as a dash.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
@@ -10,8 +10,11 @@ Rectangle {
id: hud
objectName: "stream-hud"
readonly property var ml: veyra.moonlight
- readonly property var s: ml && ml.state.stream ? ml.state.stream : ({})
- readonly property bool shown: !!ml && ml.state.streaming === true && veyra.moonlightStatsVisible
+ readonly property var xb: veyra.xbox
+ readonly property bool xboxOn: !!xb && xb.state.streaming === true
+ readonly property bool pcOn: !!ml && ml.state.streaming === true
+ readonly property var s: xboxOn ? (xb.state.stream || ({})) : pcOn ? (ml.state.stream || ({})) : ({})
+ readonly property bool shown: (xboxOn || pcOn) && veyra.moonlightStatsVisible
// Cut out of the native video window like the dialogs, so it is readable over the picture.
readonly property bool videoCover: true
property real coverRadius: 10
@@ -31,14 +34,15 @@ Rectangle {
anchors.centerIn: parent
spacing: 4
Text {
- text: (s.width > 0 ? s.width + "×" + s.height : "") + " · " + (s.codec || "") + (s.hdr ? " HDR" : "")
- + " · " + (s.hardware ? "硬件解码" : "软件解码")
+ text: (hud.xboxOn ? "Xbox · " : "PC · ") + (s.width > 0 ? s.width + "×" + s.height : "") + " · " + (s.codec || "")
+ + (s.hdr ? " HDR" : "") + " · " + (s.hardware ? "硬件解码" : "软件解码")
color: Theme.t1
font.family: Theme.fontMono
font.pixelSize: 12
font.weight: Font.DemiBold; font.variableAxes: Theme.axesDemiBold
}
Text {
+ visible: !hud.xboxOn
text: "主机 " + hud.ms(s.hostMs) + " · 往返 " + hud.ms(s.rttMs) + " · 接收 " + hud.ms(s.receiveMs)
+ " · 排队 " + hud.ms(s.queueMs) + " · 解码 " + hud.ms(s.decodeMs)
color: Theme.t2
@@ -46,15 +50,25 @@ Rectangle {
font.pixelSize: 11
}
Text {
- text: "收 " + hud.num(s.receivedFps) + " / 解 " + hud.num(s.decodedFps) + " fps · 包 " + (s.packets || 0)
- + " · FEC 恢复 " + (s.recovered || 0) + " · 未恢复 " + (s.lost || 0) + " · 丢帧 " + (s.dropped || 0)
+ visible: hud.xboxOn
+ text: "往返 " + hud.ms(s.rttMs) + " · 解码 " + hud.ms(s.decodeMs) + " · 码率 " + (s.videoMbps > 0 ? s.videoMbps.toFixed(1) + " Mbps" : "—")
+ color: Theme.t2
+ font.family: Theme.fontMono
+ font.pixelSize: 11
+ }
+ Text {
+ text: hud.xboxOn
+ ? "收 " + hud.num(s.receivedFps) + " / 解 " + hud.num(s.decodedFps) + " fps · 丢帧 " + (s.dropped || 0) + " · 关键帧请求 " + (s.keyframes || 0)
+ : "收 " + hud.num(s.receivedFps) + " / 解 " + hud.num(s.decodedFps) + " fps · 包 " + (s.packets || 0)
+ + " · FEC 恢复 " + (s.recovered || 0) + " · 未恢复 " + (s.lost || 0) + " · 丢帧 " + (s.dropped || 0)
color: (s.lost || 0) > 0 ? Theme.warn : Theme.t2
font.family: Theme.fontMono
font.pixelSize: 11
}
Text {
- text: veyra.moonlightCaptured ? "键盘鼠标已交给主机 · Ctrl+Alt+Shift+Z 释放 · +Q 断开" : "键盘鼠标未捕获 · 点击画面捕获"
- color: veyra.moonlightCaptured ? Theme.ok : Theme.t3
+ text: hud.xboxOn ? "Ctrl+Alt+Shift+S 隐藏" :
+ veyra.moonlightCaptured ? "键盘鼠标已交给主机 · Ctrl+Alt+Shift+Z 释放 · +Q 断开" : "键盘鼠标未捕获 · 点击画面捕获"
+ color: !hud.xboxOn && veyra.moonlightCaptured ? Theme.ok : Theme.t3
font.family: Theme.fontUi
font.pixelSize: 11
}
diff --git a/scripts/moonlight/ui-demo.py b/scripts/moonlight/ui-demo.py
index 605d4ae3..79c29aa9 100644
--- a/scripts/moonlight/ui-demo.py
+++ b/scripts/moonlight/ui-demo.py
@@ -1,6 +1,6 @@
"""End-to-end check of the PC streaming dialog against the mock host (no real Sunshine, no real stream).
-usage: python ui-demo.py <staged-app-dir> <mockhost.exe> <out-dir>
+usage: python ui-demo.py <staged-app-dir> <mockhost.exe> <out-dir> [<snippet.qml>]
<staged-app-dir> is a copy of the app with its Qt runtime (veyra_qml_ui.exe + qml). The script injects
ui-demo.qml into the staged Main.qml (restoring it afterwards), starts the mock host, runs the app with a
@@ -27,7 +27,7 @@ for f in (pin_file, stop_file):
main = app / 'qml/Veyra/Main.qml'
original = main.read_bytes()
source = original.decode('utf-8-sig')
-snippet = (here / 'ui-demo.qml').read_text(encoding='utf8')
+snippet = (Path(sys.argv[4]) if len(sys.argv) > 4 else here / 'ui-demo.qml').read_text(encoding='utf8')
index = source.rfind('}')
main.write_text(source[:index] + snippet + source[index:], encoding='utf8')
diff --git a/scripts/xbox/ui-shots.qml b/scripts/xbox/ui-shots.qml
new file mode 100644
index 00000000..1bd07910
--- /dev/null
+++ b/scripts/xbox/ui-shots.qml
@@ -0,0 +1,25 @@
+ // Injected by scripts/moonlight/ui-demo.py (with this file as the snippet): screenshots of the home page
+ // and the Xbox dialog in the signed-out state. Contacts no service.
+ Timer {
+ interval: 250; running: true; repeat: true
+ property int step: 0
+ property int ticks: 0
+ function log(text) { veyra.logUi("mltest", text) }
+ onTriggered: { try {
+ ++ticks
+ if (step === 0 && ticks === 10) { log("MLTEST_SHOT x1-home"); step = 1; ticks = 0; return }
+ if (step === 1 && ticks === 14) {
+ if (veyra.xbox === null) throw new Error("no Xbox model in this build")
+ dialogs.open("xbox"); step = 2; ticks = 0; return
+ }
+ if (step === 2 && ticks === 8) {
+ if (veyra.xbox.state.signedIn) throw new Error("unexpectedly signed in")
+ log("MLTEST_SHOT x2-xbox-signed-out"); step = 3; ticks = 0; return
+ }
+ if (step === 3 && ticks === 14) {
+ dialogs.open("moonlight"); step = 4; ticks = 0; return
+ }
+ if (step === 4 && ticks === 8) { log("MLTEST_SHOT x3-moonlight"); step = 5; ticks = 0; return }
+ if (step === 5 && ticks === 14) { running = false; log("MLTEST_DONE"); console.log("MLTEST_PASS"); Qt.quit() }
+ } catch (e) { running = false; log("MLTEST_FAIL " + e.message); Qt.quit() } }
+ }
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 89167277..b292b9c2 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -107,6 +107,10 @@ void EngineController::moonlightScroll(int delta,bool horizontal){VEYRA_MOONLIGH
void EngineController::moonlightReleaseInput(){VEYRA_MOONLIGHT_INPUT(releaseInput());}
#undef VEYRA_MOONLIGHT_INPUT
#endif
+#ifdef VEYRA_ENABLE_XBOX
+void EngineController::xboxController(const remoteplay::ControllerState& state){std::shared_ptr<source::XboxSessionSource> x;{std::lock_guard lock(mutex_);x=activeXbox_;}if(x)x->controller(state);}
+remoteplay::ControllerFeedback EngineController::xboxFeedback(){std::shared_ptr<source::XboxSessionSource> x;{std::lock_guard lock(mutex_);x=activeXbox_;}return x?x->takeFeedback():remoteplay::ControllerFeedback{};}
+#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
void EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc desc,PlayerOptions opts){
auto request=std::make_shared<source::MoonlightConnectDesc>(std::move(desc));
@@ -114,6 +118,13 @@ void EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc de
post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"moonlight:",opts,{},request);});
}
#endif
+#ifdef VEYRA_ENABLE_XBOX
+void EngineController::openXbox(HWND window,source::XboxConnectDesc desc,PlayerOptions opts){
+ auto request=std::make_shared<source::XboxConnectDesc>(std::move(desc));
+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.xboxActive=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}
+ post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"xbox:",opts,{},{},request);});
+}
+#endif
void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}
void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}
void EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}
@@ -212,6 +223,12 @@ PlayerSnapshot EngineController::snapshot()const{
copy.moonlight=activeMoonlight_->stats();
copy.captureAudio=activeMoonlight_->audioState();copy.audioAvailable=copy.captureAudio.available;
}
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(copy.xboxActive&&activeXbox_){
+ copy.xbox=activeXbox_->stats();
+ copy.captureAudio=activeXbox_->audioState();copy.audioAvailable=copy.captureAudio.available;
+ }
#endif
auto& flow=copy.metrics.flow;
if(!playing){flow.sourceCompletedFps=flow.outputCompletedFps=flow.validGeneratedFps=flow.presentSubmitFps=flow.xessSdkSubmitFps=0;}
@@ -230,7 +247,7 @@ struct MmcssScope {
~MmcssScope(){if(handle)AvRevertMmThreadCharacteristics(handle);}
};
}
-void EngineController::run(HWND window,std::wstring path,PlayerOptions options,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest,std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest){
+void EngineController::run(HWND window,std::wstring path,PlayerOptions options,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest,std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest,std::shared_ptr<source::XboxConnectDesc> xboxRequest){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
MmcssScope mmcss(L"Pro Audio");
status(L"正在初始化GPU与本地运行时…");
@@ -257,8 +274,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#else
(void)moonlightRequest;const bool isMoonlight=false;
#endif
- // PS5 and Moonlight are both decoded network streams with the same live scheduling.
- const bool isStream=isRemote||isMoonlight;
+#ifdef VEYRA_ENABLE_XBOX
+ auto xb=xboxRequest?std::make_shared<source::XboxSessionSource>():nullptr;
+ const bool isXbox=bool(xb);
+ {std::lock_guard lock(mutex_);activeXbox_=xb;}
+#else
+ (void)xboxRequest;const bool isXbox=false;
+#endif
+ // PS5, Moonlight and Xbox are all decoded network streams with the same live scheduling.
+ const bool isStream=isRemote||isMoonlight||isXbox;
const bool isCapture=physicalCapture||options.captureReplayForTest||isStream||isScreen;
// File replay has no hardware arrival clock; retain its continuous PTS anchor.
const bool pairAnchoredLive=physicalCapture||isStream||isScreen;
@@ -269,6 +293,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
if(moon)activeSource=moon.get();
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb)activeSource=xb.get();
#endif
if(options.captureReplayForTest)veyra::log::info("capture-test","file replay exercises live scheduler; no physical capture device or latency measurement");
bool audioStarted=false;bool failed=false;
@@ -346,6 +373,24 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(stop_||!cachedFrame)break;
}
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb){
+ status(L"正在连接 Xbox…");
+ ctx.device()->AddRef();xboxRequest->decodeDevice=std::shared_ptr<ID3D12Device>(ctx.device(),[](ID3D12Device* device){device->Release();});
+ ctx.directQueue()->AddRef();xboxRequest->decodeQueue=std::shared_ptr<ID3D12CommandQueue>(ctx.directQueue(),[](ID3D12CommandQueue* queue){queue->Release();});
+ if(!xb->connect(std::move(*xboxRequest))){const auto message=xb->stats().message;status(message.empty()?L"Xbox 串流连接失败,请查看诊断":message,true);break;}
+ xboxRequest.reset();
+ const auto firstFrameDeadline=Clock::now()+std::chrono::seconds(20);
+ while(!stop_){
+ const AVFrame* first=nullptr;const auto result=xb->read(cachedPacket,&first);
+ if(result==source::SourceReadStatus::Frame){cachedFrame=av_frame_clone(first);break;}
+ if(result==source::SourceReadStatus::Error){const auto message=xb->stats().message;status(message.empty()?L"Xbox 没有返回可解码的画面,请重新连接。":message,true);break;}
+ if(Clock::now()>firstFrameDeadline){status(L"已连接 Xbox,但 20 秒内没有收到画面。请重新连接。",true);break;}
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ if(stop_||!cachedFrame)break;
+ }
+#endif
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){
status(L"正在连接 PS5…");
@@ -364,7 +409,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(stop_||!cachedFrame)break;
}else{
#endif
- if(!isMoonlight&&!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(isScreen?screenSource.status():physicalCapture&&!captureSource.errorMessage().empty()?captureSource.errorMessage():!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}
+ if(!isMoonlight&&!isXbox&&!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(isScreen?screenSource.status():physicalCapture&&!captureSource.errorMessage().empty()?captureSource.errorMessage():!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}
#ifdef VEYRA_ENABLE_REMOTEPLAY
}
#endif
@@ -555,7 +600,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
captureSource.setBufferMode(unsigned(options.settings.captureBuffer));
if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}
{std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.nominalSourceFps=isImage?0:activeSource->info().averageFps;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}
- status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isRemote?L"PS5 串流":isMoonlight?L"PC 串流":isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));
+ status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isRemote?L"PS5 串流":isMoonlight?L"PC 串流":isXbox?L"Xbox 串流":isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));
pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;
bool initialRemoteFramePending=isStream;
bool initialFileFramePending=!isImage&&!isCapture;
@@ -890,6 +935,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(moon){moon->setAudioGain(gain);moon->setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
const auto state=moon->audioState();
std::lock_guard lock(mutex_);snapshot_.audioAvailable=state.available;snapshot_.captureAudio=state;}
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb){xb->setAudioGain(gain);xb->setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
+ const auto state=xb->audioState();
+ std::lock_guard lock(mutex_);snapshot_.audioAvailable=state.available;snapshot_.captureAudio=state;}
#endif
// Save the latest processed real frame before a settings transaction
// invalidates it (live rendering can be one batch behind processing).
@@ -950,6 +1000,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#ifdef VEYRA_ENABLE_MOONLIGHT
if(moon)moon->videoReset(false);
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb)xb->videoReset(false);
+#endif
// A drain may outlive several slider notifications. Build
// only the latest pending configuration at this boundary.
@@ -1081,6 +1134,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#ifdef VEYRA_ENABLE_MOONLIGHT
if(moon)moon->videoReset();
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb)xb->videoReset();
+#endif
}
if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;
@@ -1155,6 +1211,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
if(moon){const auto message=moon->stats().message;status(message.empty()?L"串流中断,请检查主机和网络后重新连接。":message,true);break;}
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb){const auto message=xb->stats().message;status(message.empty()?L"Xbox 串流中断,请重新连接。":message,true);break;}
#endif
status(isScreen?screenSource.status():isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}
}
@@ -1573,6 +1632,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
&moon,
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ &xb,
#endif
&seekDecoded,&seekStarted,&audio,&audioPipe,&audioStarted,&cadence,&ctx,&fileAudioAlignPending,&fileAwaitingVideo,&fileInputEnded,&frameFlow,&graph,&host100ns,&isCapture,&isImage,&livePresent,&liveScheduler,&nextFgDeadlineLog,&nowMs,&options,&pendingCompletions,&physicalCapture,&presentEntryDeviation,&presentReturnDeviation,&presentationEffective,&presentationGeneration,&presentationSkippedGenerated,&presenter,&ring,&runSessionId,&seekPreviewPending,&traceFrame,&traceSubframes,watch,step,timeline,captureArrival,baselineReady,delayEnhanced,activeSeekId,lineage,jobGeneration,rereadCached,sourceIntervalMs,flow=frameFlow](int64_t now)->LiveGpuScheduler::Step{
using State=LiveGpuScheduler::State;auto& batch=watch->output;auto& s=*step;
@@ -1713,6 +1775,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
if(didPresent&&moon)moon->videoPresented(double(item.pts100ns)/10000,host100ns());
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(didPresent&&xb)xb->videoPresented(double(item.pts100ns)/10000,host100ns());
#endif
if(didPresent&&!generated&&!rereadCached){
const auto returned=host100ns();
@@ -1787,6 +1852,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;
}
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ if(xb){captureStats.received=xb->unitsReceived();captureStats.dropped=xb->skipped();captureStats.delivered=sourceFrames;
+ captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;
+ }
+#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
if(moon){captureStats.received=moon->unitsReceived();captureStats.dropped=moon->skipped();captureStats.delivered=sourceFrames;
captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;
@@ -1889,6 +1959,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
#ifdef VEYRA_ENABLE_MOONLIGHT
{std::lock_guard lock(mutex_);activeMoonlight_.reset();}
if(moon)moon->close();
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ {std::lock_guard lock(mutex_);activeXbox_.reset();}
+ if(xb)xb->close();
#endif
// Each step is logged: a session that stopped responding after a remote
// play failure left "graph shutdown complete" as its last line.
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
index b76c8079..9e12999a 100644
--- a/src/engine/Subtitles.cpp
+++ b/src/engine/Subtitles.cpp
@@ -579,7 +579,7 @@ struct SubtitleLoader::Impl {
};
try{
std::vector<SubtitleTrack> external;
- if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")||path.starts_with(L"moonlight:")||path.starts_with(L"screen:")){publish({},true);continue;}
+ if(path.empty()||path.starts_with(L"capture:")||path.starts_with(L"capture2:")||path.starts_with(L"remoteplay:")||path.starts_with(L"moonlight:")||path.starts_with(L"xbox:")||path.starts_with(L"screen:")){publish({},true);continue;}
for(const wchar_t* extension:{L".srt",L".ass",L".ssa",L".vtt"}){
if(stop.stop_requested())break;
auto candidate=std::filesystem::path(path);candidate.replace_extension(extension);
diff --git a/src/source/XboxSessionSource.cpp b/src/source/XboxSessionSource.cpp
new file mode 100644
index 00000000..64f32d6e
--- /dev/null
+++ b/src/source/XboxSessionSource.cpp
@@ -0,0 +1,678 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Session flow after Greenlight's streammanager.ts / stream page (unknownskl/greenlight, MIT).
+#include "veyra/source/XboxSessionSource.h"
+
+#include <windows.h>
+#include <mmreg.h>
+
+#include <opus/opus.h>
+
+extern "C" {
+#include <libavutil/frame.h>
+#include <libavutil/hwcontext.h>
+}
+
+#include <algorithm>
+#include <chrono>
+#include <format>
+#include <vector>
+
+#include "veyra/Log.h"
+#include "veyra/pipeline/ColorMetadata.h"
+#include "veyra/sink/AudioFormat.h"
+#include "veyra/source/CaptureCompressedDecoder.h"
+#include "veyra/xbox/Account.h"
+#include "veyra/xbox/StreamApi.h"
+#include "veyra/xbox/WebRtcSession.h"
+
+namespace veyra::source {
+namespace {
+
+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::wstring widen(const std::string& text) {
+ if (text.empty()) return {};
+ const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0);
+ std::wstring out(size_t(std::max(size, 0)), L'\0');
+ if (size > 0) MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), out.data(), size);
+ return out;
+}
+
+pipeline::SourcePixelFormat pixelFormatOf(const AVFrame& frame) {
+ if (frame.format == AV_PIX_FMT_D3D12 && frame.hw_frames_ctx) {
+ const auto* context = reinterpret_cast<const AVHWFramesContext*>(frame.hw_frames_ctx->data);
+ return context->sw_format == AV_PIX_FMT_NV12 ? pipeline::SourcePixelFormat::NV12
+ : context->sw_format == AV_PIX_FMT_P010 ? pipeline::SourcePixelFormat::P010 : pipeline::SourcePixelFormat::Unknown;
+ }
+ switch (frame.format) {
+ case AV_PIX_FMT_NV12: return pipeline::SourcePixelFormat::NV12;
+ case AV_PIX_FMT_YUV420P: return pipeline::SourcePixelFormat::Yuv420P;
+ default: return pipeline::SourcePixelFormat::Unknown;
+ }
+}
+
+// Console streams are 8-bit H.264 SDR: BT.709 limited range, shown with the same code values as a capture card.
+pipeline::ColorDescription fallbackColor() {
+ pipeline::ColorDescription c;
+ c.pixelFormat = pipeline::SourcePixelFormat::NV12;
+ c.range = pipeline::ColorRange::Limited;
+ c.rangeAssumed = true;
+ c.matrixAssumed = c.transferAssumed = c.primariesAssumed = true;
+ c.matrix = pipeline::YuvMatrix::BT709;
+ c.transfer = pipeline::TransferFunction::BT709;
+ c.primaries = pipeline::ColorPrimaries::BT709;
+ c.preserveSdrCodeValues = true;
+ return c;
+}
+
+AVFrame* allocNv12(unsigned width, unsigned height) {
+ AVFrame* frame = av_frame_alloc();
+ if (!frame) return nullptr;
+ frame->format = AV_PIX_FMT_NV12;
+ frame->width = int(width);
+ frame->height = int(height);
+ if (av_frame_get_buffer(frame, 32) < 0) { av_frame_free(&frame); return nullptr; }
+ return frame;
+}
+
+double movingAverage(double current, double sample) { return current > 0 ? current * 0.95 + sample * 0.05 : sample; }
+
+// True when the access unit carries an IDR slice or a sequence parameter set (a point to start decoding).
+bool startsDecoding(const std::vector<uint8_t>& unit) {
+ for (size_t i = 0; i + 3 < unit.size(); ++i) {
+ if (unit[i] == 0 && unit[i + 1] == 0 && unit[i + 2] == 1) {
+ const uint8_t type = unit[i + 3] & 0x1F;
+ if (type == 5 || type == 7) return true;
+ i += 2;
+ }
+ }
+ return false;
+}
+
+std::wstring describeSessionFailure(const std::string& code, const std::string& message) {
+ if (message.find("WaitingForServerToRegister") != std::string::npos)
+ return L"主机没有连上 Xbox 服务。请确认主机开着,或处于“睡眠(即时启动)”模式,并在主机的 设置 → 设备和连接 → 远程功能 里打开“启用远程功能”。";
+ if (code == "ConsoleNotFound" || message.find("not found") != std::string::npos)
+ return L"找不到这台主机,可能已从账号里移除。请刷新主机列表。";
+ if (message.find("InUse") != std::string::npos || message.find("busy") != std::string::npos)
+ return L"这台主机正在被别的设备串流。请先在那边断开。";
+ return std::format(L"主机拒绝了串流({} {})。", widen(code), widen(message));
+}
+
+class ApiSignaling final : public xbox::Signaling {
+public:
+ ApiSignaling(xbox::StreamApi& api, std::string session) : api_(api), session_(std::move(session)) {}
+ std::string exchangeSdp(const std::string& offer) override { return api_.exchangeSdp(session_, offer); }
+ std::vector<xbox::IceCandidate> exchangeIce(const std::vector<xbox::IceCandidate>& local) override { return api_.exchangeIce(session_, local); }
+private:
+ xbox::StreamApi& api_;
+ std::string session_;
+};
+
+} // namespace
+
+struct XboxSessionSource::Impl {
+ XboxConnectDesc desc;
+ std::shared_ptr<xbox::HttpsTransport> http;
+ std::unique_ptr<xbox::StreamApi> api;
+ std::string host, gsToken;
+ std::string sessionId;
+ xbox::WebRtcSession rtc;
+ std::atomic<bool> streaming{false}, ended{false};
+ std::wstring endReason;
+ std::mutex endMutex;
+
+ // Video: the WebRTC thread queues access units; the decode thread drains them.
+ struct Unit { std::vector<uint8_t> data; uint32_t rtp; int64_t arrival; };
+ std::mutex queueMutex;
+ std::condition_variable queueCv;
+ std::deque<Unit> queue;
+ bool stopDecode = false;
+ std::thread decodeThread, keepaliveThread;
+ CaptureCompressedDecoder decoder;
+ bool decoderOpen = false;
+ AVFrame* dummyTarget = nullptr;
+ unsigned width = 1920, height = 1080;
+ Clock::time_point lastKeyframeRequest{};
+
+ struct Meta { int64_t pts; int64_t arrival; };
+ std::deque<Meta> presented;
+ std::mutex presentedMutex;
+
+ // Audio
+ OpusDecoder* opus = nullptr;
+ std::vector<float> pcm;
+ uint64_t audioSamples = 0;
+ bool audioDiscontinuity = true;
+ bool audioReady = false;
+
+ // Input and feedback
+ std::mutex inputMutex;
+ xbox::GamepadFrame lastPad;
+ Clock::time_point lastPadSent{};
+ bool padSent = false;
+ std::mutex feedbackMutex;
+ remoteplay::ControllerFeedback feedback;
+ bool feedbackPending = false;
+ Clock::time_point rumbleUntil{};
+ bool rumbling = false;
+
+ std::atomic<uint64_t> units{0}, decoded{0}, dropped{0}, errors{0};
+ std::mutex statsMutex;
+ double decodeMs = 0;
+ mutable Clock::time_point rateStart = Clock::now();
+ mutable uint64_t rateUnits = 0, rateDecoded = 0, rateBytes = 0;
+ mutable double receivedFps = 0, decodedFps = 0, videoMbps = 0;
+
+ ~Impl() {
+ if (dummyTarget) av_frame_free(&dummyTarget);
+ if (opus) opus_decoder_destroy(opus);
+ }
+};
+
+XboxSessionSource::XboxSessionSource() : p_(std::make_unique<Impl>()) {}
+
+XboxSessionSource::~XboxSessionSource() { close(); }
+
+void XboxSessionSource::setState(XboxStats::State state, std::wstring message) {
+ std::lock_guard lock(mutex_);
+ stats_.state = state;
+ stats_.message = std::move(message);
+}
+
+bool XboxSessionSource::connect(XboxConnectDesc desc) {
+ close();
+ {
+ std::lock_guard lock(mutex_);
+ initialized_ = started_ = false;
+ latest_.reset();
+ view_.reset();
+ sequence_ = skipped_ = 0;
+ openFlagPending_ = true;
+ stats_ = {};
+ stats_.state = XboxStats::State::Starting;
+ info_ = {};
+ }
+ p_ = std::make_unique<Impl>();
+ cancel_ = false;
+ owner_ = std::jthread([this, request = std::move(desc)]() mutable { run(std::move(request)); });
+ std::unique_lock lock(mutex_);
+ ready_.wait(lock, [&] { return initialized_; });
+ if (!started_) {
+ lock.unlock();
+ close();
+ return false;
+ }
+ info_ = publishedInfo_;
+ return true;
+}
+
+void XboxSessionSource::run(XboxConnectDesc desc) {
+ auto& p = *p_;
+ p.desc = std::move(desc);
+ const auto fail = [&](std::wstring message) {
+ log::error("xbox", "connect failed");
+ std::lock_guard lock(mutex_);
+ stats_.state = XboxStats::State::Failed;
+ stats_.message = std::move(message);
+ initialized_ = true;
+ started_ = false;
+ ready_.notify_all();
+ };
+ const auto cancelled = [&] { return cancel_.load(); };
+
+ try {
+ if (!p.desc.account || !p.desc.account->signedIn()) { fail(L"请先登录 Xbox 账号。"); return; }
+ setState(XboxStats::State::Starting, L"正在登录 Xbox 串流服务…");
+ const xbox::StreamingAccess access = p.desc.account->streamingAccess();
+ p.http = xbox::makeWinHttpTransport(&cancel_);
+ p.api = std::make_unique<xbox::StreamApi>(p.http, access.host, access.gsToken);
+ p.host = access.host;
+ p.gsToken = access.gsToken;
+ log::info("xbox", "streaming region " + access.regionName + " host " + access.host);
+
+ setState(XboxStats::State::Starting, L"正在唤醒主机并准备串流…");
+ p.sessionId = p.api->play(p.desc.serverId, p.desc.locale);
+ log::info("xbox", "session " + p.sessionId);
+ bool connectSent = false;
+ const auto deadline = Clock::now() + std::chrono::seconds(120);
+ for (;;) {
+ if (cancelled()) { fail(L"已取消。"); return; }
+ if (Clock::now() > deadline) { fail(L"主机长时间没有准备好串流。请确认主机开着并且网络正常。"); return; }
+ const xbox::SessionState state = p.api->state(p.sessionId);
+ log::info("xbox", "session state " + state.state);
+ if (state.state == "Provisioned") break;
+ if (state.state == "Failed") { fail(describeSessionFailure(state.errorCode, state.errorMessage)); return; }
+ if (state.state == "ReadyToConnect" && !connectSent) {
+ p.api->connect(p.sessionId, p.desc.account->transferToken());
+ connectSent = true;
+ continue;
+ }
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ }
+
+ setState(XboxStats::State::Connecting, L"正在建立连接…");
+ xbox::WebRtcCallbacks callbacks;
+ callbacks.video = [this](std::vector<uint8_t>&& unit, uint32_t rtp, int64_t arrival) {
+ auto& q = *p_;
+ ++q.units;
+ std::lock_guard lock(q.queueMutex);
+ // Latency first: keep only a short backlog; a decoder that falls behind drops the oldest.
+ while (q.queue.size() >= 8) { q.queue.pop_front(); ++q.dropped; }
+ q.queue.push_back({std::move(unit), rtp, arrival});
+ q.queueCv.notify_one();
+ };
+ callbacks.audio = [this](const uint8_t* data, size_t size, uint32_t) {
+ auto& q = *p_;
+ if (!q.audioReady || !q.opus) return;
+ const int frames = opus_decode_float(q.opus, data, opus_int32(size), q.pcm.data(), 5760, 0);
+ if (frames <= 0) { q.audioDiscontinuity = true; return; }
+ const double ptsMs = double(q.audioSamples) * 1000.0 / 48000.0;
+ audio_.push(q.pcm.data(), size_t(frames) * 2 * sizeof(float), ptsMs, q.audioDiscontinuity);
+ q.audioDiscontinuity = false;
+ q.audioSamples += uint64_t(frames);
+ };
+ callbacks.vibration = [this](const xbox::Vibration& v) {
+ if (v.gamepad != 0) return;
+ auto& q = *p_;
+ std::lock_guard lock(q.feedbackMutex);
+ q.feedback.rumble = true;
+ q.feedback.left = uint8_t(std::min(100, int(v.leftMotor)) * 255 / 100);
+ q.feedback.right = uint8_t(std::min(100, int(v.rightMotor)) * 255 / 100);
+ q.feedbackPending = true;
+ q.rumbling = q.feedback.left || q.feedback.right;
+ q.rumbleUntil = Clock::now() + std::chrono::milliseconds(v.durationMs ? v.durationMs : 1000);
+ };
+ callbacks.serverVideoSize = [this](uint32_t w, uint32_t h) {
+ std::lock_guard lock(mutex_);
+ stats_.width = w;
+ stats_.height = h;
+ };
+ callbacks.ended = [this](const std::string& reason) {
+ auto& q = *p_;
+ std::lock_guard lock(q.endMutex);
+ q.endReason = reason == "the console ended the stream" ? L"主机结束了串流。" : L"与主机的连接中断了。";
+ q.ended = true;
+ };
+ p.rtc.setCallbacks(std::move(callbacks));
+
+ // Audio output: stereo float at 48 kHz.
+ int opusError = 0;
+ p.opus = opus_decoder_create(48000, 2, &opusError);
+ if (p.opus && opusError == OPUS_OK) {
+ p.pcm.assign(5760 * 2, 0.f);
+ sink::AudioFormat layout;
+ layout.channels = 2;
+ layout.mask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
+ const WAVEFORMATEXTENSIBLE wave = sink::floatWave(layout);
+ p.audioReady = audio_.configure(wave.Format, sizeof(wave));
+ if (!p.audioReady) log::warn("xbox-audio", "the audio output could not be configured; the stream continues without sound");
+ }
+
+ ApiSignaling signaling(*p.api, p.sessionId);
+ std::string error;
+ if (!p.rtc.start(signaling, &error)) {
+ fail(L"无法和主机建立连接:" + widen(error) + L"。请确认本机网络没有拦截 UDP,主机与本机最好在同一局域网。");
+ return;
+ }
+ if (!p.rtc.waitReady(std::chrono::seconds(10))) { fail(L"主机连上了,但没有完成握手。请重试。"); return; }
+
+ // Decode and keepalive.
+ p.stopDecode = false;
+ p.decodeThread = std::thread([this] { decodeLoop(); });
+ p.keepaliveThread = std::thread([this] {
+ auto& q = *p_;
+ auto next = Clock::now() + std::chrono::seconds(30);
+ while (!cancel_.load() && !q.ended.load()) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(200));
+ if (Clock::now() < next) continue;
+ next = Clock::now() + std::chrono::seconds(30);
+ try {
+ q.api->keepalive(q.sessionId);
+ } catch (const xbox::ServiceError& e) {
+ log::warn("xbox", std::format("keepalive HTTP {}", e.status));
+ if (e.status == 404) { std::lock_guard lock(q.endMutex); q.endReason = L"串流会话已在服务器端结束。"; q.ended = true; }
+ } catch (const std::exception& e) {
+ log::warn("xbox", std::string("keepalive: ") + e.what());
+ }
+ }
+ });
+ {
+ std::lock_guard lock(p.inputMutex);
+ p.streaming = true;
+ }
+ {
+ std::lock_guard lock(mutex_);
+ stats_.state = XboxStats::State::Streaming;
+ stats_.message.clear();
+ publishedInfo_ = info_;
+ publishedInfo_.opened = true;
+ publishedInfo_.kind = pipeline::SourceKind::Xbox;
+ publishedInfo_.averageFps = 60.0;
+ publishedInfo_.nominalRateNum = 60;
+ publishedInfo_.nominalRateDen = 1;
+ publishedInfo_.timestampQuantum = 1.0 / 60.0;
+ publishedInfo_.duration = pipeline::Rational::unknown();
+ publishedInfo_.width = p.width;
+ publishedInfo_.height = p.height;
+ publishedInfo_.displayAspect = 16.0 / 9.0;
+ publishedInfo_.videoCodecName = "H.264";
+ publishedInfo_.color = fallbackColor();
+ info_ = publishedInfo_;
+ initialized_ = true;
+ started_ = true;
+ }
+ ready_.notify_all();
+ log::info("xbox", "streaming");
+ while (!cancel_.load() && !p.ended.load()) std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ if (p.ended.load()) {
+ std::wstring reason;
+ { std::lock_guard lock(p.endMutex); reason = p.endReason; }
+ setState(XboxStats::State::Ended, reason);
+ }
+ } catch (const xbox::ServiceError& e) {
+ log::error("xbox", std::format("service error {} {}", e.status, e.what()));
+ std::wstring message = xbox::describeXboxError(e.body);
+ if (message.empty()) {
+ if (e.status == 401 || e.status == 403 || std::string(e.what()) == "sign-in expired") message = L"Xbox 登录已失效,请重新登录。";
+ else message = std::format(L"Xbox 服务返回错误(HTTP {})。", e.status);
+ }
+ if (!initialized_) fail(std::move(message));
+ else setState(XboxStats::State::Failed, std::move(message));
+ } catch (const xbox::NetworkError& e) {
+ log::error("xbox", std::string("network: ") + e.what());
+ std::wstring message = cancel_ ? L"已取消。" : L"连不上 Xbox 服务,请检查网络。(" + widen(e.what()) + L")";
+ if (!initialized_) fail(std::move(message));
+ else setState(XboxStats::State::Failed, std::move(message));
+ } catch (const std::exception& e) {
+ log::error("xbox", std::string("session failed: ") + e.what());
+ if (!initialized_) fail(L"Xbox 串流出错:" + widen(e.what()));
+ else setState(XboxStats::State::Failed, L"Xbox 串流出错:" + widen(e.what()));
+ }
+}
+
+void XboxSessionSource::decodeLoop() {
+ auto& p = *p_;
+ bool seenKeyframe = false, recovering = false;
+ int64_t lastPts = -1;
+ uint32_t lastRtp = 0;
+ int64_t rtpHigh = 0;
+ bool haveRtp = false;
+ std::deque<Impl::Meta> metas;
+ const auto requestKeyframe = [&] {
+ const auto now = Clock::now();
+ if (now - p.lastKeyframeRequest < std::chrono::milliseconds(500)) return;
+ p.lastKeyframeRequest = now;
+ p.rtc.requestKeyframe();
+ };
+ log::info("xbox", "decode thread started");
+ for (;;) {
+ Impl::Unit unit;
+ {
+ std::unique_lock lock(p.queueMutex);
+ p.queueCv.wait(lock, [&] { return p.stopDecode || !p.queue.empty(); });
+ if (p.stopDecode) break;
+ unit = std::move(p.queue.front());
+ p.queue.pop_front();
+ }
+ if (!seenKeyframe && !startsDecoding(unit.data)) { ++p.dropped; requestKeyframe(); continue; }
+ if (!p.decoderOpen) {
+ if (!p.decoder.open(CaptureCodec::H264, p.width, p.height, nullptr, 0, p.desc.decodeDevice.get(), p.desc.decodeQueue.get())) {
+ log::error("xbox", "no usable H.264 decoder");
+ setState(XboxStats::State::Failed, L"没有可用的 H.264 解码器。");
+ p.ended = true;
+ break;
+ }
+ p.decoderOpen = true;
+ if (!p.dummyTarget) p.dummyTarget = allocNv12(16, 16);
+ log::info("xbox", std::string("decoder ") + p.decoder.backendName());
+ }
+ // 90 kHz RTP timestamps, unwrapped, to 100 ns ticks.
+ if (haveRtp && unit.rtp < lastRtp && lastRtp - unit.rtp > 0x80000000u) rtpHigh += int64_t(1) << 32;
+ lastRtp = unit.rtp;
+ haveRtp = true;
+ int64_t pts = (rtpHigh + int64_t(unit.rtp)) * 1000 / 9;
+ if (pts <= lastPts) pts = lastPts + 166667;
+ lastPts = pts;
+ metas.push_back({pts, unit.arrival});
+ if (metas.size() > 64) metas.pop_front();
+
+ const auto begin = Clock::now();
+ const bool needsTarget = p.decoder.framesDecoded() == 0 || !p.decoder.hardwareActive();
+ AVFrame* target = needsTarget ? allocNv12(p.width, p.height) : p.dummyTarget;
+ AVFrame* out = nullptr;
+ bool hardware = false;
+ const bool produced = target && p.decoder.decode(unit.data.data(), unit.data.size(), pts, target, &out, hardware);
+ const double decodeMs = std::chrono::duration<double, std::milli>(Clock::now() - begin).count();
+ if (!produced) {
+ if (needsTarget && target) av_frame_free(&target);
+ if (!p.decoder.waitingForInput()) {
+ ++p.errors;
+ seenKeyframe = false;
+ recovering = true;
+ requestKeyframe();
+ }
+ continue;
+ }
+ std::shared_ptr<AVFrame> frame;
+ if (hardware) {
+ AVFrame* cloned = av_frame_clone(out);
+ if (cloned) frame.reset(cloned, [](AVFrame* f) { av_frame_free(&f); });
+ if (needsTarget && target) av_frame_free(&target);
+ } else {
+ frame.reset(target, [](AVFrame* f) { av_frame_free(&f); });
+ }
+ if (!frame) { ++p.errors; continue; }
+ seenKeyframe = true;
+ if (unsigned(frame->width) != p.width || unsigned(frame->height) != p.height) {
+ p.width = unsigned(frame->width);
+ p.height = unsigned(frame->height);
+ }
+
+ int64_t arrival = unit.arrival;
+ const int64_t framePts = frame->pts != AV_NOPTS_VALUE ? frame->pts : pts;
+ for (const auto& meta : metas) if (meta.pts == framePts) { arrival = meta.arrival; break; }
+
+ pipeline::FramePacket packet{};
+ packet.sourceKind = pipeline::SourceKind::Xbox;
+ packet.pts = pipeline::Rational{framePts, 10000000};
+ packet.duration = pipeline::Rational{166667, 10000000};
+ packet.arrivalHost100ns = arrival;
+ packet.decodedHost100ns = host100ns();
+ if (recovering) { packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity); recovering = false; }
+ auto fallback = fallbackColor();
+ packet.colorInfo = pipeline::resolveFrameColor(*frame, fallback);
+ packet.colorInfo.pixelFormat = pixelFormatOf(*frame);
+ if (packet.colorInfo.pixelFormat == pipeline::SourcePixelFormat::Unknown) { ++p.errors; continue; }
+
+ SourceInfo info;
+ {
+ std::lock_guard lock(mutex_);
+ info = info_;
+ stats_.width = unsigned(frame->width);
+ stats_.height = unsigned(frame->height);
+ }
+ info.color = packet.colorInfo;
+ info.hardwareDecodeActive = frame->format == AV_PIX_FMT_D3D12;
+ info.videoDecodePath = info.hardwareDecodeActive ? "d3d12va" : "software";
+ if (info.width != unsigned(frame->width) || info.height != unsigned(frame->height)) {
+ info.width = unsigned(frame->width);
+ info.height = unsigned(frame->height);
+ info.displayAspect = frame->height > 0 ? double(frame->width) / double(frame->height) : 0.0;
+ packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Resize);
+ }
+ {
+ std::lock_guard lock(p.presentedMutex);
+ p.presented.push_back({framePts, arrival});
+ if (p.presented.size() > 64) p.presented.pop_front();
+ }
+ {
+ std::lock_guard lock(p.statsMutex);
+ p.decodeMs = movingAverage(p.decodeMs, decodeMs);
+ }
+ ++p.decoded;
+ publish(std::move(frame), packet, info);
+ }
+ log::info("xbox", "decode thread stopped");
+}
+
+void XboxSessionSource::publish(std::shared_ptr<AVFrame> frame, const pipeline::FramePacket& packet, const SourceInfo& info) {
+ std::lock_guard lock(mutex_);
+ Frame item{std::move(frame), packet, info};
+ item.packet.sequence = ++sequence_;
+ if (openFlagPending_) {
+ item.packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Open);
+ openFlagPending_ = false;
+ }
+ if (latest_) {
+ ++skipped_;
+ item.packet.flags |= latest_->packet.flags;
+ item.packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Drop);
+ }
+ latest_ = std::move(item);
+}
+
+SourceReadStatus XboxSessionSource::read(pipeline::FramePacket& packet, const AVFrame** frame) {
+ if (frame) *frame = nullptr;
+ std::lock_guard lock(mutex_);
+ if (stats_.state == XboxStats::State::Failed || stats_.state == XboxStats::State::Ended) return SourceReadStatus::Error;
+ if (!latest_) return started_ ? SourceReadStatus::Waiting : SourceReadStatus::Error;
+ packet = latest_->packet;
+ info_ = latest_->info;
+ view_ = std::move(latest_->frame);
+ latest_.reset();
+ if (frame) *frame = view_.get();
+ return SourceReadStatus::Frame;
+}
+
+void XboxSessionSource::videoPresented(double ptsMs, int64_t host) {
+ std::optional<int64_t> arrival;
+ if (p_) {
+ std::lock_guard lock(p_->presentedMutex);
+ const int64_t pts100 = int64_t(ptsMs * 10000.0);
+ for (const auto& meta : p_->presented) if (std::llabs(meta.pts - pts100) < 5) { arrival = meta.arrival; break; }
+ }
+ audio_.videoPresented(ptsMs, host, arrival);
+}
+
+void XboxSessionSource::controller(const remoteplay::ControllerState& state) {
+ if (!p_) return;
+ auto& p = *p_;
+ const xbox::GamepadFrame frame = xbox::gamepadFromController(state);
+ std::lock_guard lock(p.inputMutex);
+ if (!p.streaming.load() || !p.desc.gamepad) return;
+ const auto now = Clock::now();
+ if (p.padSent && frame == p.lastPad && now - p.lastPadSent < std::chrono::milliseconds(33)) return;
+ p.rtc.sendGamepad(frame);
+ p.lastPad = frame;
+ p.lastPadSent = now;
+ p.padSent = true;
+}
+
+remoteplay::ControllerFeedback XboxSessionSource::takeFeedback() {
+ remoteplay::ControllerFeedback out;
+ if (!p_) return out;
+ auto& p = *p_;
+ std::lock_guard lock(p.feedbackMutex);
+ if (p.feedbackPending) {
+ out = p.feedback;
+ p.feedbackPending = false;
+ } else if (p.rumbling && Clock::now() >= p.rumbleUntil) {
+ // The report carries a duration; stop when it runs out (SDL would otherwise keep going for seconds).
+ out.rumble = true;
+ out.left = out.right = 0;
+ p.rumbling = false;
+ }
+ return out;
+}
+
+XboxStats XboxSessionSource::stats() const {
+ XboxStats s;
+ {
+ std::lock_guard lock(mutex_);
+ s = stats_;
+ }
+ if (!p_) return s;
+ auto& p = *p_;
+ s.units = p.units.load();
+ s.decoded = p.decoded.load();
+ s.dropped = p.dropped.load() + skipped();
+ s.decodeErrors = p.errors.load();
+ s.hardwareDecode = p.decoderOpen && p.decoder.hardwareActive();
+ const xbox::WebRtcStats r = p.rtc.stats();
+ s.keyframeRequests = r.keyframeRequests;
+ s.rttMs = r.rttMs;
+ std::lock_guard lock(p.statsMutex);
+ s.decodeMs = p.decodeMs;
+ const auto now = Clock::now();
+ const double seconds = std::chrono::duration<double>(now - p.rateStart).count();
+ if (seconds >= 1.0) {
+ p.receivedFps = double(s.units - p.rateUnits) / seconds;
+ p.decodedFps = double(s.decoded - p.rateDecoded) / seconds;
+ p.videoMbps = double(r.videoBytes - p.rateBytes) * 8.0 / seconds / 1e6;
+ p.rateUnits = s.units;
+ p.rateDecoded = s.decoded;
+ p.rateBytes = r.videoBytes;
+ p.rateStart = now;
+ }
+ s.receivedFps = p.receivedFps;
+ s.decodedFps = p.decodedFps;
+ s.videoMbps = p.videoMbps;
+ return s;
+}
+
+uint64_t XboxSessionSource::unitsReceived() const { return p_ ? p_->units.load() : 0; }
+
+uint64_t XboxSessionSource::skipped() const {
+ std::lock_guard lock(mutex_);
+ return skipped_;
+}
+
+void XboxSessionSource::close() noexcept {
+ cancel_ = true;
+ if (owner_.joinable()) owner_.join();
+ if (p_) {
+ auto& p = *p_;
+ {
+ std::lock_guard lock(p.inputMutex);
+ if (p.streaming.exchange(false) && p.padSent) p.rtc.sendGamepad(xbox::GamepadFrame{}); // release everything on the console
+ }
+ p.rtc.close();
+ {
+ std::lock_guard lock(p.queueMutex);
+ p.stopDecode = true;
+ }
+ p.queueCv.notify_all();
+ if (p.decodeThread.joinable()) p.decodeThread.join();
+ if (p.keepaliveThread.joinable()) p.keepaliveThread.join();
+ if (p.decoderOpen) { p.decoder.close(); p.decoderOpen = false; }
+ // End the console session so the next start does not find it busy (best effort, short timeout).
+ // The session's own transport is cancelled by now, and teardown must not wait on the network:
+ // a detached request with its own transport and copies of what it needs.
+ if (p.api && !p.sessionId.empty()) {
+ std::thread([host = p.host, token = p.gsToken, id = p.sessionId] {
+ try {
+ xbox::StreamApi(xbox::makeWinHttpTransport(), host, token).stop(id);
+ log::info("xbox", "session " + id + " stopped");
+ } catch (const std::exception& e) {
+ log::warn("xbox", std::string("session stop: ") + e.what());
+ }
+ }).detach();
+ p.sessionId.clear();
+ }
+ }
+ audio_.stop();
+ std::lock_guard lock(mutex_);
+ latest_.reset();
+ view_.reset();
+ info_ = {};
+ started_ = false;
+ if (stats_.state == XboxStats::State::Streaming || stats_.state == XboxStats::State::Connecting || stats_.state == XboxStats::State::Starting)
+ stats_.state = XboxStats::State::Idle;
+}
+
+} // namespace veyra::source
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index ed991a41..6f60a6f4 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -53,6 +53,9 @@
#include "veyra/remoteplay/PsnAuth.h"
#include "veyra/source/RemotePlaySource.h"
#endif
+#ifdef VEYRA_ENABLE_XBOX
+#include "veyra/ui/XboxModel.h"
+#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
#include "veyra/ui/MoonlightInputCapture.h"
#include "veyra/ui/MoonlightModel.h"
@@ -564,6 +567,12 @@ struct QmlPlayerBridge::Impl {
std::unique_ptr<ui::MoonlightInputCapture> moonlightCapture;
std::unique_ptr<ui::MoonlightModel> moonlight;
#endif
+#ifdef VEYRA_ENABLE_XBOX
+ QTimer* xboxTimer = nullptr;
+ bool xboxWasActive = false;
+ int xboxStatsTicks = 0;
+ std::unique_ptr<ui::XboxModel> xbox; // last: joins its worker first
+#endif
};
namespace {
@@ -627,6 +636,9 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
if (qApp) qApp->installEventFilter(this);
#ifdef VEYRA_ENABLE_MOONLIGHT
setupMoonlight();
+#endif
+#ifdef VEYRA_ENABLE_XBOX
+ setupXbox();
#endif
// Before anything opens: the renderer reads the output choice at start().
applyPreference(QStringLiteral("audioDevice"));
@@ -753,6 +765,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
tickCapture();
tickPs5();
tickMoonlight();
+ tickXbox();
// Geometry uses the source DAR and the same transform as mouse/compare.
if (impl_->snapshot.running && impl_->videoWindow) {
const bool fresh = impl_->aspectSession != impl_->snapshot.sessionId;
@@ -1705,6 +1718,90 @@ void QmlPlayerBridge::setMoonlightStatsVisible(bool visible) {
}
void QmlPlayerBridge::openMoonlightDialog() { emit navigate(QStringLiteral("moonlight")); }
+// --- Xbox home streaming (unofficial) ------------------------------------------------------------------
+QObject* QmlPlayerBridge::xboxModel() const {
+#ifdef VEYRA_ENABLE_XBOX
+ return impl_->xbox.get();
+#else
+ return nullptr;
+#endif
+}
+void QmlPlayerBridge::openXboxDialog() { emit navigate(QStringLiteral("xbox")); }
+void QmlPlayerBridge::xboxDisconnect() {
+#ifdef VEYRA_ENABLE_XBOX
+ if (impl_->snapshot.xboxActive) stopPlayback();
+#endif
+}
+
+#ifdef VEYRA_ENABLE_XBOX
+void QmlPlayerBridge::setupXbox() {
+ auto& i = *impl_;
+ i.xbox = std::make_unique<ui::XboxModel>();
+ connect(i.xbox.get(), &ui::XboxModel::notice, this, &QmlPlayerBridge::notice);
+ i.xbox->setLaunchHandler([this](ui::XboxModel::Launch launch) -> bool {
+ auto& j = *impl_;
+ if (!j.videoWindow) return false;
+ rememberPosition(true);
+ j.openingSource = true;
+ j.sourceLabel = L"Xbox · " + launch.label.toStdWString();
+ j.resumeSession = 0;
+ j.screenFillActive = false;
+ const bool pad = launch.desc.gamepad;
+ const QString label = launch.label;
+ auto request = std::make_shared<source::XboxConnectDesc>(std::move(launch.desc));
+ openAfterCinema(tr("正在连接 Xbox · %1").arg(label), [this, request, pad] {
+ auto& k = *impl_;
+ if (k.preOpen) k.preOpen();
+ k.engine.previewView({});
+ k.engine.openXbox(k.videoWindow, std::move(*request), k.options);
+ k.openingSessionId = k.engine.snapshot().sessionId;
+ refreshSubtitles({});
+#ifdef VEYRA_ENABLE_REMOTEPLAY
+ // The pad is polled on the UI thread at 250 Hz; the session sends changes and a 33 ms heartbeat.
+ if (pad) {
+ if (!k.controller.start()) veyra::log::warn("xbox-input", "SDL gamepad initialization failed");
+ if (!k.xboxTimer) {
+ k.xboxTimer = new QTimer(this);
+ k.xboxTimer->setTimerType(Qt::PreciseTimer);
+ connect(k.xboxTimer, &QTimer::timeout, this, [this] {
+ auto& m = *impl_;
+ if (!m.snapshot.xboxActive) { m.controller.stop(); m.xboxTimer->stop(); return; }
+ const bool focused = QGuiApplication::focusWindow() != nullptr;
+ m.engine.xboxController(m.controller.poll(focused));
+ m.controller.feedback(m.engine.xboxFeedback(), focused);
+ });
+ }
+ k.xboxTimer->start(4);
+ } else {
+ if (k.xboxTimer) k.xboxTimer->stop();
+ k.controller.stop();
+ }
+#else
+ (void)pad;
+#endif
+ });
+ rememberSource(QStringLiteral("xbox"), label);
+ return true;
+ });
+}
+
+void QmlPlayerBridge::tickXbox() {
+ auto& i = *impl_;
+ if (!i.xbox) return;
+ const auto& s = i.snapshot;
+ const bool active = s.xboxActive;
+ if (active != i.xboxWasActive) {
+ i.xboxWasActive = active;
+ i.xbox->updateStream(active, s.xbox);
+ } else if (active && ++i.xboxStatsTicks >= 15) {
+ i.xboxStatsTicks = 0;
+ i.xbox->updateStream(true, s.xbox);
+ }
+}
+#else
+void QmlPlayerBridge::tickXbox() {}
+#endif
+
void QmlPlayerBridge::moonlightCapture(bool on) {
#ifdef VEYRA_ENABLE_MOONLIGHT
auto& i = *impl_;
@@ -5292,6 +5389,8 @@ QVariantMap QmlPlayerBridge::lastSource() const {
saved[QStringLiteral("summary")] = tr("PS5 串流 · %1").arg(saved.value(QStringLiteral("label")).toString());
} else if (kind == QLatin1String("moonlight")) {
saved[QStringLiteral("summary")] = tr("PC 串流 · %1").arg(saved.value(QStringLiteral("label")).toString());
+ } else if (kind == QLatin1String("xbox")) {
+ saved[QStringLiteral("summary")] = tr("Xbox 串流 · %1").arg(saved.value(QStringLiteral("label")).toString());
} else if (kind == QLatin1String("screen")) {
saved[QStringLiteral("summary")] = tr("屏幕捕获 · %1").arg(saved.value(QStringLiteral("label")).toString());
} else if (hasCaptureSession()) {
@@ -5321,6 +5420,17 @@ void QmlPlayerBridge::resumeLastSource() {
if (!ps5Connect()) emit notice(tr("没能继续上次的 PS5 串流:%1").arg(impl_->ps5Status), true);
#else
emit notice(tr("此版本不含 PS5 串流"), true);
+#endif
+ return;
+ }
+ if (kind == QLatin1String("xbox")) {
+#ifdef VEYRA_ENABLE_XBOX
+ if (!impl_->xbox || !impl_->xbox->resumeLast()) {
+ emit notice(tr("没能继续上次的 Xbox 串流,请在 Xbox 串流窗口里重新选择"), true);
+ emit navigate(QStringLiteral("xbox"));
+ }
+#else
+ emit notice(tr("此版本不含 Xbox 串流"), true);
#endif
return;
}
@@ -5401,6 +5511,7 @@ QString QmlPlayerBridge::sourceTitle() const {
}
if (kind == QLatin1String("ps5")) return tr("PS5 串流 · %1").arg(impl_->liveLabel);
if (kind == QLatin1String("moonlight")) return tr("PC 串流 · %1").arg(impl_->liveLabel);
+ if (kind == QLatin1String("xbox")) return tr("Xbox 串流 · %1").arg(impl_->liveLabel);
return tr("屏幕捕获 · %1").arg(impl_->liveLabel);
}
// "1080p60" / "1080p59.94": the reported height and nominal rate only.
diff --git a/src/ui/XboxModel.cpp b/src/ui/XboxModel.cpp
new file mode 100644
index 00000000..68e3744b
--- /dev/null
+++ b/src/ui/XboxModel.cpp
@@ -0,0 +1,259 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/ui/XboxModel.h"
+
+#include <QDesktopServices>
+#include <QFile>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QMetaObject>
+#include <QSaveFile>
+#include <QUrl>
+#include <chrono>
+
+#include "veyra/Log.h"
+#include "veyra/xbox/StreamApi.h"
+
+namespace veyra::ui {
+namespace {
+
+QString qs(const std::string& text) { return QString::fromUtf8(text.data(), qsizetype(text.size())); }
+
+QString describe(const std::exception& e) {
+ if (const auto* service = dynamic_cast<const xbox::ServiceError*>(&e)) {
+ const std::wstring xerr = xbox::describeXboxError(service->body);
+ if (!xerr.empty()) return QString::fromStdWString(xerr);
+ if (service->status == 400 || service->status == 401 || service->status == 403) return QObject::tr("Xbox 登录已失效,请重新登录。");
+ return QObject::tr("Xbox 服务返回错误(HTTP %1)。").arg(service->status);
+ }
+ if (dynamic_cast<const xbox::NetworkError*>(&e)) return QObject::tr("连不上 Xbox 服务,请检查网络。(%1)").arg(qs(e.what()));
+ return QObject::tr("出错了:%1").arg(qs(e.what()));
+}
+
+QString powerText(const std::string& power) {
+ if (power == "On") return QObject::tr("开机");
+ if (power == "ConnectedStandby") return QObject::tr("睡眠(可唤醒)");
+ if (power == "SystemUpdate") return QObject::tr("正在更新");
+ if (power == "Off") return QObject::tr("关机");
+ return qs(power);
+}
+
+QString typeText(const std::string& type) {
+ if (type == "XboxSeriesX") return QStringLiteral("Xbox Series X");
+ if (type == "XboxSeriesS") return QStringLiteral("Xbox Series S");
+ if (type == "XboxOne") return QStringLiteral("Xbox One");
+ if (type == "XboxOneS") return QStringLiteral("Xbox One S");
+ if (type == "XboxOneX") return QStringLiteral("Xbox One X");
+ return qs(type);
+}
+
+QString settingsPath() { return QString::fromStdWString((xbox::dataDirectory() / L"settings.json").wstring()); }
+
+} // namespace
+
+XboxModel::XboxModel(QObject* parent) : QObject(parent) {
+ account_ = std::make_shared<xbox::Account>(xbox::makeWinHttpTransport(), xbox::dataDirectory() / L"account.bin");
+}
+
+XboxModel::~XboxModel() { cancel_ = true; }
+
+void XboxModel::loadSettings() {
+ QFile file(settingsPath());
+ if (!file.open(QIODevice::ReadOnly)) return;
+ const QJsonObject o = QJsonDocument::fromJson(file.readAll()).object();
+ lastId_ = o.value("lastConsole").toString();
+ lastName_ = o.value("lastName").toString();
+ gamepad_ = o.value("gamepad").toBool(true);
+}
+
+void XboxModel::saveSettings() const {
+ std::error_code ec;
+ std::filesystem::create_directories(xbox::dataDirectory(), ec);
+ QSaveFile file(settingsPath());
+ if (!file.open(QIODevice::WriteOnly)) return;
+ file.write(QJsonDocument(QJsonObject{{"lastConsole", lastId_}, {"lastName", lastName_}, {"gamepad", gamepad_}}).toJson());
+ file.commit();
+}
+
+QVariantMap XboxModel::state() const {
+ return QVariantMap{
+ {"signedIn", account_->signedIn()}, {"busy", busy_}, {"status", status_}, {"code", code_},
+ {"verificationUri", verificationUri_}, {"signingIn", signingIn_}, {"selected", selected_}, {"gamepad", gamepad_},
+ {"streaming", streamActive_}, {"stream", stream_}, {"lastLabel", lastName_},
+ };
+}
+
+void XboxModel::startJob(const QString& status, std::function<std::function<void()>(const std::atomic<bool>&)> work) {
+ if (busy_) { status_ = tr("正在处理上一个操作,请稍候,或先点取消。"); emit changed(); return; }
+ busy_ = true;
+ cancel_ = false;
+ status_ = status;
+ emit changed();
+ if (worker_.joinable()) worker_.join();
+ worker_ = std::jthread([this, work = std::move(work)] {
+ std::function<void()> done;
+ try {
+ done = work(cancel_);
+ } catch (const std::exception& e) {
+ const QString text = describe(e);
+ done = [this, text] { status_ = text; };
+ }
+ QMetaObject::invokeMethod(this, [this, done = std::move(done)] {
+ busy_ = false;
+ if (done) done();
+ emit changed();
+ }, Qt::QueuedConnection);
+ });
+}
+
+void XboxModel::cancel() {
+ cancel_ = true;
+ if (busy_) { status_ = tr("正在取消…"); emit changed(); }
+}
+
+void XboxModel::load() {
+ if (!loaded_) { loadSettings(); loaded_ = true; }
+ if (account_->signedIn() && consoles_.isEmpty()) refresh();
+ emit changed();
+}
+
+void XboxModel::signIn() {
+ signingIn_ = true;
+ code_.clear();
+ startJob(tr("正在向微软请求登录码…"), [this](const std::atomic<bool>& cancel) -> std::function<void()> {
+ const xbox::DeviceCode code = account_->beginSignIn();
+ const QString user = qs(code.userCode), uri = qs(code.verificationUri);
+ QMetaObject::invokeMethod(this, [this, user, uri] {
+ code_ = user;
+ verificationUri_ = uri;
+ status_ = tr("在手机或浏览器打开 %1,输入上面的登录码,用你的 Xbox(微软)账号登录。登录完成后这里会自动继续。").arg(uri);
+ emit changed();
+ }, Qt::QueuedConnection);
+ int interval = code.intervalSeconds;
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(code.expiresInSeconds);
+ for (;;) {
+ for (int i = 0; i < interval * 10; ++i) {
+ if (cancel.load()) return [this] { signingIn_ = false; code_.clear(); status_ = tr("已取消登录。"); };
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ }
+ if (std::chrono::steady_clock::now() > deadline) return [this] { signingIn_ = false; code_.clear(); status_ = tr("登录码已过期,请重新点“登录”。"); };
+ std::string detail;
+ const xbox::SignInPoll result = account_->pollSignIn(code, &detail);
+ if (result == xbox::SignInPoll::Pending) continue;
+ if (result == xbox::SignInPoll::SlowDown) { interval += 5; continue; }
+ if (result == xbox::SignInPoll::Done) break;
+ const QString why = result == xbox::SignInPoll::Expired ? tr("登录码已过期,请重新点“登录”。")
+ : result == xbox::SignInPoll::Declined ? tr("登录被拒绝了。")
+ : tr("登录失败(%1)。").arg(qs(detail));
+ return [this, why] { signingIn_ = false; code_.clear(); status_ = why; };
+ }
+ // Signed in: prove the streaming sign-in works and read the consoles straight away.
+ const xbox::StreamingAccess access = account_->streamingAccess();
+ const auto list = xbox::StreamApi(xbox::makeWinHttpTransport(&cancel), access.host, access.gsToken).consoles();
+ QVariantList consoles;
+ for (const auto& c : list)
+ consoles << QVariantMap{{"id", qs(c.serverId)}, {"name", qs(c.name)}, {"type", typeText(c.consoleType)}, {"power", powerText(c.powerState)}};
+ return [this, consoles] {
+ signingIn_ = false;
+ code_.clear();
+ consoles_ = consoles;
+ if (selected_.isEmpty() && !consoles_.isEmpty()) selected_ = consoles_.front().toMap().value("id").toString();
+ status_ = consoles_.isEmpty() ? tr("已登录,但这个账号下没有找到主机。请在主机上用同一个账号登录,并在 设置 → 设备和连接 → 远程功能 里启用远程功能。")
+ : tr("已登录。");
+ emit notice(tr("已登录 Xbox"), false);
+ };
+ });
+}
+
+void XboxModel::openSignInPage() {
+ QDesktopServices::openUrl(QUrl(verificationUri_.isEmpty() ? QStringLiteral("https://www.microsoft.com/link") : verificationUri_));
+}
+
+void XboxModel::signOut() {
+ if (busy_) return;
+ account_->signOut();
+ consoles_.clear();
+ selected_.clear();
+ status_ = tr("已退出登录,本机保存的登录信息已删除。");
+ emit changed();
+}
+
+void XboxModel::refresh() {
+ if (!account_->signedIn()) { emit changed(); return; }
+ startJob(tr("正在读取主机列表…"), [this](const std::atomic<bool>& cancel) -> std::function<void()> {
+ const xbox::StreamingAccess access = account_->streamingAccess();
+ const auto list = xbox::StreamApi(xbox::makeWinHttpTransport(&cancel), access.host, access.gsToken).consoles();
+ QVariantList consoles;
+ for (const auto& c : list)
+ consoles << QVariantMap{{"id", qs(c.serverId)}, {"name", qs(c.name)}, {"type", typeText(c.consoleType)}, {"power", powerText(c.powerState)}};
+ return [this, consoles] {
+ consoles_ = consoles;
+ bool known = false;
+ for (const QVariant& c : std::as_const(consoles_)) known = known || c.toMap().value("id").toString() == selected_;
+ if (!known) selected_ = consoles_.isEmpty() ? QString() : (lastId_.isEmpty() ? consoles_.front().toMap().value("id").toString() : lastId_);
+ status_ = consoles_.isEmpty() ? tr("这个账号下没有找到主机。请在主机上用同一个账号登录,并启用远程功能。") : QString();
+ };
+ });
+}
+
+void XboxModel::select(const QString& id) {
+ if (selected_ == id) return;
+ selected_ = id;
+ emit changed();
+}
+
+bool XboxModel::set(const QString& key, const QVariant& value) {
+ if (key == "gamepad") { gamepad_ = value.toBool(); saveSettings(); emit changed(); return true; }
+ return false;
+}
+
+bool XboxModel::launchConsole(const QString& id, const QString& name) {
+ if (!account_->signedIn()) { status_ = tr("请先登录 Xbox 账号。"); emit changed(); return false; }
+ if (!launch_ || id.isEmpty()) return false;
+ Launch launch;
+ launch.desc.account = account_;
+ launch.desc.serverId = id.toStdString();
+ launch.desc.consoleName = name.toStdString();
+ launch.desc.gamepad = gamepad_;
+ launch.label = name.isEmpty() ? QStringLiteral("Xbox") : name;
+ if (!launch_(std::move(launch))) { status_ = tr("无法开始串流,请查看日志。"); emit changed(); return false; }
+ lastId_ = id;
+ lastName_ = name;
+ saveSettings();
+ status_ = tr("正在连接主机…(主机在睡眠时唤醒需要一点时间)");
+ emit changed();
+ emit started();
+ return true;
+}
+
+bool XboxModel::connectStream() {
+ if (busy_) return false;
+ QString name;
+ for (const QVariant& c : std::as_const(consoles_)) if (c.toMap().value("id").toString() == selected_) name = c.toMap().value("name").toString();
+ return launchConsole(selected_, name);
+}
+
+bool XboxModel::resumeLast() {
+ if (!loaded_) { loadSettings(); loaded_ = true; }
+ if (lastId_.isEmpty()) return false;
+ return launchConsole(lastId_, lastName_);
+}
+
+void XboxModel::updateStream(bool active, const source::XboxStats& s) {
+ QVariantMap now;
+ if (active) {
+ const char* names[] = {"idle", "starting", "connecting", "streaming", "ended", "failed"};
+ now = QVariantMap{
+ {"state", names[size_t(s.state)]}, {"message", QString::fromStdWString(s.message)}, {"codec", "H.264"},
+ {"hardware", s.hardwareDecode}, {"width", int(s.width)}, {"height", int(s.height)},
+ {"receivedFps", s.receivedFps}, {"decodedFps", s.decodedFps}, {"videoMbps", s.videoMbps},
+ {"decodeMs", s.decodeMs}, {"rttMs", s.rttMs}, {"dropped", double(s.dropped)},
+ {"decodeErrors", double(s.decodeErrors)}, {"keyframes", double(s.keyframeRequests)},
+ };
+ }
+ if (now == stream_ && active == streamActive_) return;
+ stream_ = now;
+ streamActive_ = active;
+ emit changed();
+}
+
+} // namespace veyra::ui
diff --git a/tests/xbox/XboxTests.cpp b/tests/xbox/XboxTests.cpp
index e2400b28..024c6868 100644
--- a/tests/xbox/XboxTests.cpp
+++ b/tests/xbox/XboxTests.cpp
@@ -463,7 +463,24 @@ void webrtcTests() {
} // namespace
-int main() {
+int main(int argc, char** argv) {
+ // --live-device-code: asks Microsoft for a sign-in code with the client id the product uses (no account
+ // is involved, nothing is signed in). Confirms the first step of the real service still answers.
+ if (argc > 1 && std::string(argv[1]) == "--live-device-code") {
+ const auto dir = std::filesystem::temp_directory_path() / "veyra-xbox-live-check";
+ Account account(makeWinHttpTransport(), dir / "unused.bin");
+ try {
+ const DeviceCode code = account.beginSignIn();
+ std::printf("device code issued: user code %zu characters, verification %s, expires in %d s, interval %d s\n",
+ code.userCode.size(), code.verificationUri.c_str(), code.expiresInSeconds, code.intervalSeconds);
+ return code.userCode.empty() ? 1 : 0;
+ } catch (const ServiceError& e) {
+ std::printf("service error %d: %s\n", e.status, e.body.substr(0, 300).c_str());
+ } catch (const std::exception& e) {
+ std::printf("error: %s\n", e.what());
+ }
+ return 1;
+ }
protocolTests();
apiTests();
accountTests();