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(moonlight): PC streaming dialog, host model, discovery and stats overlay (S4)

Veyra Goal Agent88fefaa4d889
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4260c031..eb443d40 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -76,6 +76,12 @@ if(VEYRA_ENABLE_MOONLIGHT)
target_compile_definitions(veyra_moonlight_protocol_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(veyra_moonlight_protocol_tests PRIVATE veyra_moonlight_protocol)
veyra_apply_warnings(veyra_moonlight_protocol_tests)
+ # The same fake host as a process, for the end-to-end UI check (scripts/moonlight/ui-demo.py).
+ add_executable(veyra_moonlight_mockhost tests/moonlight/MockHostServer.cpp)
+ target_compile_features(veyra_moonlight_mockhost PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_moonlight_mockhost PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_moonlight_mockhost PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/moonlight)
+ target_link_libraries(veyra_moonlight_mockhost PRIVATE veyra_moonlight_protocol)
endif()
# ---------------------------------------------------------------------------
@@ -789,6 +795,21 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
set_target_properties(veyra_qml_bridge PROPERTIES AUTOMOC ON)
if(VEYRA_ENABLE_MOONLIGHT)
target_sources(veyra_qml_bridge PRIVATE src/ui/MoonlightInputCapture.cpp include/veyra/ui/MoonlightInputCapture.h)
+ # The PC streaming model (hosts, pairing, apps, settings) is its own small library so it can be
+ # tested against the mock host without the whole player.
+ add_library(veyra_moonlight_model STATIC src/ui/MoonlightModel.cpp include/veyra/ui/MoonlightModel.h)
+ set_target_properties(veyra_moonlight_model PROPERTIES AUTOMOC ON)
+ target_compile_features(veyra_moonlight_model PUBLIC cxx_std_20)
+ target_include_directories(veyra_moonlight_model PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${FFMPEG_INCLUDE_DIRS})
+ 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)
+
+ add_executable(veyra_moonlight_model_tests tests/moonlight/ModelTests.cpp)
+ target_compile_features(veyra_moonlight_model_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_moonlight_model_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_moonlight_model_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/moonlight)
+ target_link_libraries(veyra_moonlight_model_tests PRIVATE veyra_moonlight_model)
endif()
target_compile_features(veyra_qml_bridge PRIVATE cxx_std_20)
target_include_directories(veyra_qml_bridge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src ${FFMPEG_INCLUDE_DIRS}
diff --git a/cmake/VeyraMoonlight.cmake b/cmake/VeyraMoonlight.cmake
index dcb3a95f..f9b4e7dc 100644
--- a/cmake/VeyraMoonlight.cmake
+++ b/cmake/VeyraMoonlight.cmake
@@ -50,9 +50,10 @@ add_library(veyra_moonlight_protocol STATIC
"${VEYRA_ROOT}/src/moonlight/Http.cpp"
"${VEYRA_ROOT}/src/moonlight/Client.cpp"
"${VEYRA_ROOT}/src/moonlight/Pairing.cpp"
- "${VEYRA_ROOT}/src/moonlight/IdentityStore.cpp")
+ "${VEYRA_ROOT}/src/moonlight/IdentityStore.cpp"
+ "${VEYRA_ROOT}/src/moonlight/Discovery.cpp")
target_compile_features(veyra_moonlight_protocol PUBLIC cxx_std_20)
set_target_properties(veyra_moonlight_protocol PROPERTIES CXX_EXTENSIONS OFF)
target_compile_definitions(veyra_moonlight_protocol PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_include_directories(veyra_moonlight_protocol PUBLIC "${VEYRA_ROOT}/include")
-target_link_libraries(veyra_moonlight_protocol PUBLIC OpenSSL::SSL OpenSSL::Crypto PRIVATE ws2_32 crypt32 shell32 ole32 advapi32 user32)
+target_link_libraries(veyra_moonlight_protocol PUBLIC OpenSSL::SSL OpenSSL::Crypto PRIVATE ws2_32 crypt32 shell32 ole32 advapi32 user32 dnsapi)
diff --git a/include/veyra/moonlight/Discovery.h b/include/veyra/moonlight/Discovery.h
new file mode 100644
index 00000000..0f7f3d1e
--- /dev/null
+++ b/include/veyra/moonlight/Discovery.h
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Finds Sunshine / GameStream hosts on the local network: they advertise "_nvstream._tcp" over
+// mDNS / DNS-SD. Uses the Windows DNS-SD API (dnsapi, Windows 10 2004+), so nothing is added to the
+// build. Found hosts are only candidates: the caller asks each one for serverinfo before trusting it.
+#pragma once
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <string>
+
+namespace veyra::moonlight {
+
+struct DiscoveredHost {
+ std::string instance; // "Sunshine-PC._nvstream._tcp.local"
+ std::string hostName; // "DESKTOP-ABC.local"
+ std::string address; // dotted IPv4 (or the host name when no address came back)
+ uint16_t port = 47989;
+};
+
+class Discovery {
+public:
+ // Called on a system thread pool thread, possibly more than once per host.
+ using Callback = std::function<void(const DiscoveredHost&)>;
+
+ Discovery();
+ ~Discovery();
+ Discovery(const Discovery&) = delete;
+ Discovery& operator=(const Discovery&) = delete;
+
+ // False when the DNS-SD API is unavailable or refused the browse; the caller then relies on
+ // manual addresses.
+ bool start(Callback callback);
+ void stop();
+ bool running() const;
+
+ struct State; // opaque; the DNS callbacks in the .cpp need the name
+
+private:
+ std::shared_ptr<State> state_;
+};
+
+} // namespace veyra::moonlight
diff --git a/include/veyra/ui/MoonlightModel.h b/include/veyra/ui/MoonlightModel.h
new file mode 100644
index 00000000..d40d407d
--- /dev/null
+++ b/include/veyra/ui/MoonlightModel.h
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+// The "PC 串流" side of the UI: known hosts (saved, or found on the network), pairing, the app list of
+// the selected host, the stream-core settings and starting a stream. All network work runs on worker
+// threads and reports back on the UI thread; nothing here blocks the interface. The effect chain is not
+// part of it (it is the software's own, shared by every source).
+#include <QObject>
+#include <QVariantList>
+#include <QVariantMap>
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <thread>
+
+#include "veyra/moonlight/Discovery.h"
+#include "veyra/moonlight/IdentityStore.h"
+#include "veyra/source/MoonlightSessionSource.h"
+
+namespace veyra::ui {
+
+class MoonlightModel final : public QObject {
+ Q_OBJECT
+ // {busy, status, pin, pairing, selected, settings{...}, discovering, stream{...}, ready}
+ Q_PROPERTY(QVariantMap state READ state NOTIFY changed)
+ // [{id, name, address, state: online|unpaired|busy|offline|checking, paired, running, gpu, selected}]
+ Q_PROPERTY(QVariantList hosts READ hosts NOTIFY changed)
+ // [{id, name, running, hdr}] of the selected host
+ Q_PROPERTY(QVariantList apps READ apps NOTIFY changed)
+public:
+ struct Launch {
+ source::MoonlightConnectDesc desc;
+ QString label; // "host · app", for the source title
+ bool captureInput = true;
+ };
+ // Starts the stream (the bridge opens the engine session); false if it could not.
+ using LaunchFn = std::function<bool(Launch)>;
+
+ explicit MoonlightModel(QObject* parent = nullptr);
+ ~MoonlightModel() override;
+
+ void setLaunchHandler(LaunchFn handler) { launch_ = std::move(handler); }
+ // Fed by the bridge while a session runs (a few times a second).
+ void updateStream(bool active, const source::MoonlightStats& stats);
+
+ QVariantMap state() const;
+ QVariantList hosts() const;
+ QVariantList apps() const { return apps_; }
+
+ // Dialog opened / closed: loads the store, starts the network search and a status refresh.
+ Q_INVOKABLE void load();
+ Q_INVOKABLE void unload();
+ Q_INVOKABLE void refresh();
+ Q_INVOKABLE void addHost(const QString& address);
+ Q_INVOKABLE void select(const QString& id);
+ Q_INVOKABLE void pair(const QString& id);
+ Q_INVOKABLE void cancel();
+ Q_INVOKABLE void forget(const QString& id);
+ Q_INVOKABLE void quitApp();
+ Q_INVOKABLE bool connectStream(int appId);
+ Q_INVOKABLE bool resumeLast();
+ Q_INVOKABLE bool set(const QString& key, const QVariant& value);
+
+ // For "继续上次" and the home card.
+ int hostCount() const { return int(hosts_.size()); }
+ QString lastLabel() const { return lastLabel_; }
+
+signals:
+ void changed();
+ void started(); // the stream was handed to the player; the dialog can close
+ void notice(const QString& text, bool isError);
+
+private:
+ struct Host {
+ QString id, name, address, mac, cert, gpu, version;
+ int port = moonlight::kDefaultHttpPort, httpsPort = moonlight::kDefaultHttpsPort;
+ int codecSupport = moonlight::kServerH264;
+ bool paired = false, nvidia = false, saved = false;
+ QVariantMap settings;
+ // not persisted
+ bool online = false, checking = false;
+ int currentGame = 0;
+ };
+ void loadStore();
+ bool saveStore() const;
+ Host* find(const QString& id);
+ const Host* find(const QString& id) const;
+ Host* findByAddress(const QString& address, int port);
+ QVariantMap settingsOf(const Host* host) const;
+ source::MoonlightStreamOptions optionsFor(const Host* host) const;
+ void startJob(const QString& status, std::function<std::function<void()>(const std::atomic<bool>&)> work);
+ void probe(const QString& address, int port, bool manual);
+ void discovered(const QString& address, int port);
+ void applyInfo(Host& host, const moonlight::ServerInfo& info);
+ void reloadApps();
+ moonlight::Identity identity();
+ bool launchSelected(int appId);
+
+ LaunchFn launch_;
+ std::vector<Host> hosts_;
+ QVariantList apps_;
+ QVariantMap defaults_;
+ QString selected_, status_, pin_, lastHost_, lastLabel_;
+ int lastApp_ = 0;
+ bool busy_ = false, pairing_ = false, loaded_ = false, streamActive_ = false;
+ QVariantMap stream_;
+ int runningApp_ = 0;
+
+ std::mutex identityMutex_;
+ std::optional<moonlight::Identity> identity_;
+ std::atomic<bool> cancel_{false};
+ moonlight::Discovery discovery_;
+ std::vector<std::jthread> probes_; // short serverinfo checks of found hosts
+ std::jthread worker_; // last: joined first
+};
+
+} // namespace veyra::ui
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 94a66571..6b46bac9 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -40,6 +40,8 @@
namespace veyra::ui {
+class MoonlightModel;
+
class QmlPlayerBridge : public QObject {
Q_OBJECT
// --- professional-page readouts ---------------------------------------
@@ -156,6 +158,11 @@ class QmlPlayerBridge : public QObject {
// forwarding and gyro calibration. `ps5` carries the form state.
Q_PROPERTY(QVariantMap ps5 READ ps5 NOTIFY ps5Changed)
Q_PROPERTY(QVariantList ps5Profiles READ ps5Profiles NOTIFY ps5Changed)
+ // 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)
+ Q_PROPERTY(bool moonlightCaptured READ moonlightCaptured NOTIFY moonlightUiChanged)
+ Q_PROPERTY(bool moonlightStatsVisible READ moonlightStatsVisible WRITE setMoonlightStatsVisible NOTIFY moonlightUiChanged)
// Shell preferences that are not enhancement settings: screenshot folder,
// subtitle look, audio output. Stored in <data>/qml-preferences.v1.json and
@@ -531,6 +538,13 @@ public:
QVariantMap ps5() const;
QVariantList ps5Profiles() const;
+ QObject* moonlightModel() const;
+ bool moonlightCaptured() const;
+ bool moonlightStatsVisible() const;
+ void setMoonlightStatsVisible(bool visible);
+ Q_INVOKABLE void openMoonlightDialog();
+ Q_INVOKABLE void moonlightCapture(bool on);
+ Q_INVOKABLE void moonlightDisconnect();
Q_INVOKABLE void ps5Load();
Q_INVOKABLE bool ps5Set(const QString& key, const QVariant& value);
Q_INVOKABLE void ps5SelectProfile(const QString& id);
@@ -931,6 +945,7 @@ public:
signals:
void nodeAnchorsChanged();
void ps5Changed();
+ void moonlightUiChanged();
void imageBatchChanged();
void audioDevicesChanged();
void subtitlesChanged();
@@ -990,6 +1005,10 @@ private:
void tickImageBatch();
void tickCapture();
void tickPs5();
+ void tickMoonlight();
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ void setupMoonlight();
+#endif
void queryCapture(int kind, std::wstring device);
// Opens a device/stream URI (capture, screen) the way openPath opens a file.
void openSourceUri(const std::wstring& uri, const std::wstring& label);
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index eb475dcd..4c2a14fa 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 | screen | subtitle | audio
+ // Which dialog is showing: "" | capture | ps5 | moonlight | screen | subtitle | audio
property string dialog: ""
function open(key) {
@@ -33,6 +33,7 @@ Item {
signal startCapture()
signal startPs5()
+ signal startMoonlight()
signal startScreen()
// Scrim (M16): the design dims the page behind the dialog, opacity .2s linear.
@@ -559,6 +560,317 @@ Item {
DNote { visible: (veyra.ps5.status || "").length > 0; text: (veyra.ps5.busy ? "处理中 · " : "") + (veyra.ps5.status || "") }
}
+ // --- PC 串流(Sunshine / GameStream) ----------------------------------
+ // Hosts, pairing, the host's apps and the stream-core settings. The effect chain is not here: once
+ // connected, the picture goes through the software's own pages like any other source.
+ DLayer {
+ id: mlDialog
+ objectName: "moonlight-dialog"
+ key: "moonlight"
+ glyph: "cast"
+ title: "PC 串流"
+ sub: "串流另一台电脑(Sunshine 主机)· 增强与调色沿用软件自己的处理链"
+ dialogWidth: 760
+ readonly property var ml: veyra.moonlight
+ readonly property var st: ml ? ml.state : ({})
+ readonly property var hostList: ml ? ml.hosts : []
+ readonly property var appList: ml ? ml.apps : []
+ readonly property var cfg: st.settings || ({})
+ property int pickedApp: -1
+ readonly property int effectiveApp: pickedApp >= 0 ? pickedApp
+ : (st.runningApp > 0 ? st.runningApp : (appList.length > 0 ? appList[0].id : -1))
+ readonly property bool canStart: !!st.paired && !!st.online && !st.busy && effectiveApp >= 0 && !st.streaming
+ actions: st.streaming ? [
+ { label: "关闭" },
+ { label: "断开", primary: true }
+ ] : [
+ { label: st.busy ? "取消操作" : "关闭" },
+ { label: "开始串流", primary: true, icon: "play" }
+ ]
+ onActionTriggered: label => {
+ if (label === "断开") { veyra.moonlightDisconnect(); host.close(); return }
+ if (label === "取消操作") { ml.cancel(); return }
+ if (label === "关闭") { host.close(); return }
+ if (canStart) ml.connectStream(effectiveApp)
+ }
+ Connections {
+ target: mlDialog
+ function onShownChanged() {
+ if (!mlDialog.ml) return
+ if (mlDialog.shown) { mlDialog.pickedApp = -1; mlDialog.ml.load() }
+ else mlDialog.ml.unload()
+ }
+ }
+ Connections {
+ target: mlDialog.ml
+ function onStarted() { host.close(); host.startMoonlight() }
+ }
+ readonly property var resolutions: [
+ { id: "720p", label: "720p · 1280×720" }, { id: "1080p", label: "1080p · 1920×1080" },
+ { id: "1440p", label: "1440p · 2560×1440" }, { id: "4k", label: "4K · 3840×2160" },
+ { id: "native", label: "本机屏幕分辨率" }]
+ readonly property var rates: [30, 60, 90, 120, 144].map(v => ({ id: String(v), label: v + " fps" }))
+ readonly property var bitrates: [{ id: "0", label: "自动(按分辨率与帧率)" }].concat(
+ [5, 10, 15, 20, 30, 40, 50, 60, 80, 100, 120, 150].map(m => ({ id: String(m), label: m + " Mbps" })))
+ function labelOf(list, id, fallback) { const f = list.find(x => String(x.id) === String(id)); return f ? f.label : fallback }
+ function stateText(s) {
+ return s === "online" ? "在线" : s === "unpaired" ? "未配对" : s === "busy" ? "在线 · 有游戏在运行"
+ : s === "checking" ? "检查中…" : "离线"
+ }
+
+ DSection { text: "主机" }
+ DNote {
+ visible: mlDialog.hostList.length === 0
+ text: "还没有主机。在要被串流的电脑上安装 Sunshine(官网 app.lizardbyte.dev/Sunshine,软件不自带),"
+ + "两台电脑接在同一个局域网,这里会自动出现;也可以在下面手填它的 IP。首次使用需要配对。"
+ }
+ Repeater {
+ model: mlDialog.hostList
+ delegate: Rectangle {
+ id: hostRow
+ required property var modelData
+ Layout.fillWidth: true
+ Layout.topMargin: 6
+ implicitHeight: 54
+ radius: 11
+ color: modelData.selected ? Theme.accentSoft : (hostHover.hovered ? Theme.card3 : Theme.card2)
+ border.width: 1
+ border.color: modelData.selected ? Theme.accent : Theme.stroke
+ objectName: "moonlight-host-" + modelData.id
+ HoverHandler { id: hostHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: mlDialog.ml.select(hostRow.modelData.id) }
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 14
+ anchors.rightMargin: 10
+ spacing: 12
+ VDot {
+ warn: hostRow.modelData.state === "unpaired"
+ off: hostRow.modelData.state === "offline" || hostRow.modelData.state === "checking"
+ Layout.alignment: Qt.AlignVCenter
+ }
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 1
+ Text {
+ Layout.fillWidth: true
+ text: hostRow.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: hostRow.modelData.address + " · " + mlDialog.stateText(hostRow.modelData.state)
+ + (hostRow.modelData.gpu.length > 0 ? " · " + hostRow.modelData.gpu : "")
+ color: Theme.t3
+ font.family: Theme.fontUi
+ font.pixelSize: Theme.fsSmall
+ elide: Text.ElideRight
+ }
+ }
+ VTag { visible: hostRow.modelData.paired; text: "已配对"; kind: "ok" }
+ VButton {
+ visible: !hostRow.modelData.paired && hostRow.modelData.state !== "offline"
+ objectName: "moonlight-pair-" + hostRow.modelData.id
+ text: "配对"
+ primary: true
+ enabled: !mlDialog.st.busy
+ onClicked: mlDialog.ml.pair(hostRow.modelData.id)
+ }
+ VButton {
+ text: "删除"
+ ghost: true
+ enabled: !mlDialog.st.busy
+ onClicked: mlDialog.ml.forget(hostRow.modelData.id)
+ }
+ }
+ }
+ }
+ DGroup {
+ VRow {
+ label: "手动添加"
+ hint: "IP 或主机名,端口不是 47989 时写成 192.168.1.20:47989"
+ RowLayout {
+ spacing: 6
+ VTextField { id: mlAddress; objectName: "moonlight-address"; implicitWidth: 190; placeholder: "192.168.1.x"; onEdited: text => { if (text.length > 0) { mlDialog.ml.addHost(text); mlAddress.text = "" } } }
+ VSpinner { visible: mlDialog.st.busy === true; Layout.alignment: Qt.AlignVCenter }
+ VButton { text: "添加"; ghost: true; enabled: !mlDialog.st.busy && mlAddress.text.length > 0; onClicked: { mlDialog.ml.addHost(mlAddress.text); mlAddress.text = "" } }
+ VButton { text: "刷新"; ghost: true; enabled: !mlDialog.st.busy; onClicked: mlDialog.ml.refresh() }
+ }
+ }
+ }
+ // The PIN the user types into the host's Sunshine page.
+ Rectangle {
+ visible: mlDialog.st.pairing === true
+ objectName: "moonlight-pin-box"
+ Layout.fillWidth: true
+ Layout.topMargin: 8
+ implicitHeight: pinCol.implicitHeight + 28
+ radius: 11
+ color: Theme.accentSoft
+ border.width: 1
+ border.color: Theme.accent
+ ColumnLayout {
+ id: pinCol
+ anchors.fill: parent
+ anchors.margins: 14
+ spacing: 6
+ Text {
+ Layout.fillWidth: true
+ text: "在主机上打开 Sunshine 网页(https://主机IP:47990),进入「PIN」页,输入下面的数字并提交:"
+ color: Theme.t2
+ font.family: Theme.fontUi
+ font.pixelSize: Theme.fsSmall
+ wrapMode: Text.WordWrap
+ }
+ Text {
+ objectName: "moonlight-pin"
+ Layout.alignment: Qt.AlignHCenter
+ text: mlDialog.st.pin || ""
+ color: Theme.t1
+ font.family: Theme.fontMono
+ font.pixelSize: 34
+ font.letterSpacing: 10
+ }
+ }
+ }
+
+ DSection { visible: !!mlDialog.st.paired; text: "游戏与程序 · " + (mlDialog.st.hostName || "") }
+ DNote {
+ visible: !!mlDialog.st.selected && !mlDialog.st.paired && !mlDialog.st.pairing
+ text: "这台主机还没有和本机配对。点「配对」,在主机的 Sunshine 网页里输入软件给出的 PIN。"
+ }
+ DNote {
+ visible: !!mlDialog.st.paired && !mlDialog.st.online
+ text: "主机现在连不上(离线、休眠,或地址变了)。开机后点「刷新」。"
+ }
+ Flow {
+ visible: !!mlDialog.st.paired && !!mlDialog.st.online
+ Layout.fillWidth: true
+ spacing: 8
+ Repeater {
+ model: mlDialog.appList
+ delegate: Rectangle {
+ id: appCard
+ required property var modelData
+ readonly property bool picked: mlDialog.effectiveApp === modelData.id
+ objectName: "moonlight-app-" + modelData.id
+ width: 168
+ height: 64
+ radius: 11
+ color: picked ? Theme.accentSoft : (appHover.hovered ? Theme.card3 : Theme.card2)
+ border.width: 1
+ border.color: picked ? Theme.accent : Theme.stroke
+ HoverHandler { id: appHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler {
+ onTapped: mlDialog.pickedApp = appCard.modelData.id
+ onDoubleTapped: { mlDialog.pickedApp = appCard.modelData.id; if (mlDialog.canStart) mlDialog.ml.connectStream(appCard.modelData.id) }
+ }
+ ColumnLayout {
+ anchors.fill: parent
+ anchors.margins: 11
+ spacing: 4
+ Text {
+ Layout.fillWidth: true
+ text: appCard.modelData.name
+ color: Theme.t1
+ font.family: Theme.fontUi
+ font.pixelSize: Theme.fsBody
+ font.weight: Font.Medium
+ elide: Text.ElideRight
+ }
+ RowLayout {
+ spacing: 6
+ VTag { visible: appCard.modelData.running; text: "运行中"; kind: "acc" }
+ VTag { visible: appCard.modelData.hdr; text: "HDR" }
+ }
+ }
+ }
+ }
+ }
+ RowLayout {
+ visible: !!mlDialog.st.paired && !!mlDialog.st.online && mlDialog.st.runningApp > 0
+ Layout.fillWidth: true
+ Layout.topMargin: 8
+ spacing: 8
+ Text {
+ Layout.fillWidth: true
+ text: "主机上有游戏在运行。断开串流不会结束它;选它并开始即可继续。"
+ color: Theme.t3
+ font.family: Theme.fontUi
+ font.pixelSize: Theme.fsSmall
+ wrapMode: Text.WordWrap
+ }
+ VButton { objectName: "moonlight-quit-app"; text: "退出游戏"; ghost: true; enabled: !mlDialog.st.busy; onClicked: mlDialog.ml.quitApp() }
+ }
+
+ DSection { text: "串流设置(只影响串流本身,按主机保存)" }
+ DGroup {
+ VRow {
+ label: "分辨率"
+ hint: "主机按这个尺寸编码;软件的超分与增强在收到之后再做"
+ VSelect { objectName: "moonlight-res"; implicitWidth: 190; value: mlDialog.labelOf(mlDialog.resolutions, mlDialog.cfg.res, "1080p · 1920×1080"); options: mlDialog.resolutions; onPicked: id => mlDialog.ml.set("res", id) }
+ }
+ VRow {
+ label: "帧率"
+ VSelect { objectName: "moonlight-fps"; implicitWidth: 130; value: (mlDialog.cfg.fps || 60) + " fps"; options: mlDialog.rates; onPicked: id => mlDialog.ml.set("fps", Number(id)) }
+ }
+ VRow {
+ label: "码率"
+ hint: "自动:1080p60 约 20 Mbps,4K60 约 80 Mbps;局域网有线可以放心调高"
+ VSelect { objectName: "moonlight-bitrate"; implicitWidth: 190; value: mlDialog.labelOf(mlDialog.bitrates, mlDialog.cfg.bitrate || 0, "自动"); options: mlDialog.bitrates; onPicked: id => mlDialog.ml.set("bitrate", Number(id)) }
+ }
+ VRow {
+ label: "编码"
+ hint: mlDialog.cfg.codec === 3 ? "AV1 需要主机显卡能编码、本机显卡能解码" : "自动:优先 HEVC,主机不支持时用 H.264"
+ VSeg {
+ objectName: "moonlight-codec"
+ options: [{ id: "0", label: "自动" }, { id: "1", label: "H.264" }, { id: "2", label: "HEVC" }, { id: "3", label: "AV1" }]
+ current: String(mlDialog.cfg.codec || 0)
+ onPicked: id => mlDialog.ml.set("codec", Number(id))
+ }
+ }
+ VRow {
+ label: "HDR"
+ hint: mlDialog.st.hdrHost ? "需要主机显示器开启 HDR,且编码选 HEVC 或 AV1;本机需要硬件解码" : "这台主机没有报告 10 位编码能力"
+ VSwitch { objectName: "moonlight-hdr"; enabled: !!mlDialog.st.hdrHost || mlDialog.cfg.hdr === true; checked: mlDialog.cfg.hdr === true; onToggled: mlDialog.ml.set("hdr", checked) }
+ }
+ VRow {
+ label: "声道"
+ VSeg {
+ objectName: "moonlight-audio"
+ options: [{ id: "2", label: "立体声" }, { id: "6", label: "5.1" }, { id: "8", label: "7.1" }]
+ current: String(mlDialog.cfg.audio || 2)
+ onPicked: id => mlDialog.ml.set("audio", Number(id))
+ }
+ }
+ VRow {
+ label: "手柄"
+ hint: "把电脑手柄当作主机上的 Xbox 手柄(1 号)"
+ VSwitch { objectName: "moonlight-gamepad"; checked: mlDialog.cfg.gamepad !== false; onToggled: mlDialog.ml.set("gamepad", checked) }
+ }
+ VRow {
+ label: "自动捕获键盘鼠标"
+ hint: "开始后键鼠交给主机;Ctrl+Alt+Shift+Z 释放,+Q 断开,+S 统计"
+ VSwitch { objectName: "moonlight-capture"; checked: mlDialog.cfg.captureInput !== false; onToggled: mlDialog.ml.set("captureInput", checked) }
+ }
+ VRow {
+ label: "让主机切换到串流分辨率"
+ hint: "关闭时主机保持自己的分辨率,画面由主机缩放"
+ VSwitch { objectName: "moonlight-sops"; checked: mlDialog.cfg.sops === true; onToggled: mlDialog.ml.set("sops", checked) }
+ }
+ VRow {
+ label: "主机同时出声"
+ hint: "默认只在本机出声"
+ VSwitch { objectName: "moonlight-hostaudio"; checked: mlDialog.cfg.hostAudio === true; onToggled: mlDialog.ml.set("hostAudio", checked) }
+ }
+ }
+ DNote { objectName: "moonlight-status"; visible: (mlDialog.st.status || "").length > 0; text: (mlDialog.st.busy ? "处理中 · " : "") + (mlDialog.st.status || "") }
+ }
+
// --- 屏幕捕获 ---------------------------------------------------------
DLayer {
id: screenDialog
diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qml
index 05c4b62a..d94bc4c1 100644
--- a/qml/Veyra/HomePage.qml
+++ b/qml/Veyra/HomePage.qml
@@ -78,9 +78,12 @@ VPage {
}
}
- // .srcgrid: repeat(4, 164px), gap 12.
- RowLayout {
+ // .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.
+ Flow {
+ id: srcGrid
Layout.alignment: Qt.AlignHCenter
+ Layout.preferredWidth: Math.min(868, root.width - 48)
spacing: 12
Repeater {
// Subtitles name what is really there: the device of the last capture
@@ -91,6 +94,8 @@ VPage {
sub: veyra.hasCaptureSession ? veyra.captureSessionSummary.split(" · ")[0] : "HDMI 采集设备", act: "capture" },
{ glyph: "gamepad", title: "PS5 串流",
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: "monitor", title: "屏幕捕获", sub: "窗口或显示器", act: "screen" }
]
// The layout owns the slot's position, so the card inside it is free to
@@ -160,6 +165,7 @@ VPage {
case "file": veyra.openFileDialog(); break
case "capture": veyra.openCaptureDialog(); break
case "ps5": veyra.openPs5Dialog(); break
+ case "moonlight": veyra.openMoonlightDialog(); break
case "screen": veyra.openScreenCaptureDialog(); break
}
}
@@ -179,7 +185,7 @@ VPage {
// The last source actually used: capture card, PS5 or screen capture.
readonly property var last: veyra.lastSource
visible: last.kind !== undefined
- implicitWidth: 692
+ implicitWidth: srcGrid.width
implicitHeight: 54
radius: 14
border.width: 1
@@ -237,7 +243,7 @@ VPage {
Flow {
id: recent
Layout.alignment: Qt.AlignHCenter
- Layout.preferredWidth: 692
+ Layout.preferredWidth: srcGrid.width
visible: veyra.recentFiles.length > 0
spacing: 8
Text {
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index 0d56cc38..03deb99c 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -250,6 +250,7 @@ Window {
// The dialogs open the source through the bridge; show the picture.
onStartCapture: if (root.page === "home") root.goPage("min")
onStartPs5: if (root.page === "home") root.goPage("min")
+ onStartMoonlight: if (root.page === "home") root.goPage("min")
onStartScreen: if (root.page === "home") root.goPage("min")
}
@@ -408,6 +409,24 @@ Window {
root.toggleFullscreen()
}
}
+ // A click on the picture of a PC stream takes the keyboard and mouse back after a release
+ // (Ctrl+Alt+Shift+Z). While captured the clicks belong to the host and never get here.
+ TapHandler {
+ enabled: veyra.moonlight && veyra.moonlight.state.streaming === true && !veyra.moonlightCaptured && dialogs.dialog === ""
+ onTapped: eventPoint => {
+ const p = eventPoint.position
+ if (root.page !== "min" && root.page !== "pro" && root.page !== "node") return
+ if (p.x < videoHost.x || p.y < videoHost.y || p.x > videoHost.x + videoHost.width
+ || p.y > videoHost.y + videoHost.height) return
+ veyra.moonlightCapture(true)
+ }
+ }
+ StreamHud {
+ id: streamHud
+ x: 16
+ y: root.fullscreen ? 16 : 52
+ z: 90
+ }
FullscreenBar {
id: fullBar
owner: root
@@ -524,7 +543,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 === "screen"
+ if (p === "capture" || p === "ps5" || p === "moonlight" || 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 e84698d9..3d1f889b 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 === "screen" ? "monitor"
+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "screen" ? "monitor"
: veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"
text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"
maxTextWidth: 180
@@ -1542,12 +1542,14 @@ VPage {
? [{ label: veyra.sourceTitle, note: veyra.sourceFormatText, checked: true, icon: "video", act: "" }] : [])
.concat([{ label: "打开文件…", icon: "folder", act: "file" },
{ label: "PS5 串流…", icon: "gamepad", act: "ps5" },
+ { label: "PC 串流…", icon: "cast", act: "moonlight" },
{ label: "屏幕捕获…", icon: "monitor", act: "screen" },
{ sep: true },
{ label: "采集卡设置…", icon: "settings", act: "capture" }])
onPicked: (i, o) => {
if (o.act === "file") veyra.openFileDialog()
else if (o.act === "ps5") veyra.openPs5Dialog()
+ else if (o.act === "moonlight") veyra.openMoonlightDialog()
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 e5f4be99..12bf32b3 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 === "screen" ? "monitor"
+ iconName: veyra.sourceKind === "ps5" ? "gamepad" : veyra.sourceKind === "moonlight" ? "cast" : veyra.sourceKind === "screen" ? "monitor"
: veyra.sourceKind === "image" ? "image" : veyra.sourceKind === "file" ? "film" : "video"
text: veyra.sourceTitle.length > 0 ? veyra.sourceTitle : "片源"
maxTextWidth: 260
@@ -1726,12 +1726,14 @@ VPage {
checked: true, icon: "video", act: "" }] : [])
.concat([{ label: "打开文件…", icon: "folder", act: "file" },
{ label: "PS5 串流…", icon: "gamepad", act: "ps5" },
+ { label: "PC 串流…", icon: "cast", act: "moonlight" },
{ label: "屏幕捕获…", icon: "monitor", act: "screen" },
{ sep: true },
{ label: "采集卡设置…", icon: "settings", act: "capture" }])
onPicked: (i, o) => {
if (o.act === "file") veyra.openFileDialog()
else if (o.act === "ps5") veyra.openPs5Dialog()
+ else if (o.act === "moonlight") veyra.openMoonlightDialog()
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
new file mode 100644
index 00000000..b05ef290
--- /dev/null
+++ b/qml/Veyra/StreamHud.qml
@@ -0,0 +1,62 @@
+// 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.
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+
+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
+ // 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
+
+ function ms(v) { return v > 0 ? v.toFixed(1) + " ms" : "—" }
+ function num(v) { return v > 0 ? v.toFixed(1) : "—" }
+
+ visible: shown
+ width: col.implicitWidth + 28
+ height: col.implicitHeight + 24
+ radius: 10
+ color: Qt.rgba(0.04, 0.04, 0.05, 0.86)
+ border.width: 1
+ border.color: Theme.stroke2
+ ColumnLayout {
+ id: col
+ anchors.centerIn: parent
+ spacing: 4
+ Text {
+ text: (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 {
+ text: "主机 " + hud.ms(s.hostMs) + " · 往返 " + hud.ms(s.rttMs) + " · 接收 " + hud.ms(s.receiveMs)
+ + " · 排队 " + hud.ms(s.queueMs) + " · 解码 " + hud.ms(s.decodeMs)
+ color: Theme.t2
+ font.family: Theme.fontMono
+ 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)
+ 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
+ font.family: Theme.fontUi
+ font.pixelSize: 11
+ }
+ }
+}
diff --git a/qml/Veyra/qmldir b/qml/Veyra/qmldir
index d6de6625..db7ae2ff 100644
--- a/qml/Veyra/qmldir
+++ b/qml/Veyra/qmldir
@@ -3,6 +3,7 @@ singleton Theme 1.0 Theme.qml
VAccordion 1.0 VAccordion.qml
VSubGroup 1.0 VSubGroup.qml
DialogHost 1.0 DialogHost.qml
+StreamHud 1.0 StreamHud.qml
VBackdrop 1.0 VBackdrop.qml
VButton 1.0 VButton.qml
VCard 1.0 VCard.qml
diff --git a/scripts/moonlight/ui-demo.py b/scripts/moonlight/ui-demo.py
new file mode 100644
index 00000000..605d4ae3
--- /dev/null
+++ b/scripts/moonlight/ui-demo.py
@@ -0,0 +1,136 @@
+"""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>
+
+<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
+disposable data directory, feeds the PIN the dialog shows to the mock host, takes a screenshot at each
+MLTEST_SHOT line and exits 0 when the app reports MLTEST_PASS.
+"""
+import ctypes
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+app, mock, out = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
+here = Path(__file__).resolve().parent
+out.mkdir(parents=True, exist_ok=True)
+work = out / 'work'
+work.mkdir(exist_ok=True)
+pin_file, stop_file = work / 'pin.txt', work / 'stop.txt'
+for f in (pin_file, stop_file):
+ if f.exists():
+ f.unlink()
+
+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')
+index = source.rfind('}')
+main.write_text(source[:index] + snippet + source[index:], encoding='utf8')
+
+user32 = ctypes.windll.user32
+
+
+class RECT(ctypes.Structure):
+ _fields_ = [('l', ctypes.c_long), ('t', ctypes.c_long), ('r', ctypes.c_long), ('b', ctypes.c_long)]
+
+
+def find_window(pid):
+ found = []
+
+ @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
+ def visit(hwnd, _):
+ owner = ctypes.c_ulong()
+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
+ if owner.value == pid and user32.IsWindowVisible(hwnd):
+ rect = RECT()
+ user32.GetWindowRect(hwnd, ctypes.byref(rect))
+ if rect.r - rect.l > 400:
+ found.append((hwnd, rect))
+ return True
+ user32.EnumWindows(visit, 0)
+ return found[0] if found else None
+
+
+def screenshot(pid, path):
+ win = find_window(pid)
+ if not win:
+ return False
+ hwnd, rect = win
+ ps = ('Add-Type -AssemblyName System.Drawing; '
+ f'$b = New-Object System.Drawing.Bitmap({rect.r - rect.l},{rect.b - rect.t}); '
+ '$g = [System.Drawing.Graphics]::FromImage($b); '
+ f'$g.CopyFromScreen({rect.l},{rect.t},0,0,$b.Size); '
+ f'$b.Save("{path}"); $g.Dispose(); $b.Dispose()')
+ subprocess.run(['powershell', '-NoProfile', '-Command', ps], check=True, timeout=60)
+ return True
+
+
+result = 1
+mock_proc = app_proc = None
+try:
+ mock_proc = subprocess.Popen([str(mock), '--pin-file', str(pin_file), '--stop-file', str(stop_file)],
+ stdout=subprocess.PIPE, text=True)
+ ports = mock_proc.stdout.readline().split()
+ assert ports[0] == 'PORTS', ports
+ address = f'127.0.0.1:{ports[1]}'
+ log = out / 'app.log'
+ if log.exists():
+ log.unlink()
+ env = os.environ.copy()
+ env.update(VEYRA_LOG_FILE=str(log), VEYRA_MOONLIGHT_DATA=str(work / 'data'), VEYRA_MOONLIGHT_NO_DISCOVERY='1',
+ QML_DISABLE_DISK_CACHE='1', QML2_IMPORT_PATH=str(app / 'qml'), TEMP=str(work), TMP=str(work))
+ command = [str(app / 'veyra_qml_ui.exe'), '--data-dir', str(work / 'profile'), '--exit-after', '290000',
+ '--ml-address=' + address]
+ app_proc = subprocess.Popen(command, cwd=app, env=env, stdout=(out / 'stdio.log').open('w'), stderr=subprocess.STDOUT)
+ seen = 0
+ exited = False
+ deadline = time.time() + 295
+ verdict = None
+ while time.time() < deadline and verdict is None:
+ time.sleep(0.2)
+ if app_proc.poll() is not None and not log.exists():
+ break
+ lines = log.read_text(encoding='utf8', errors='replace').splitlines() if log.exists() else []
+ for line in lines[seen:]:
+ if 'MLTEST_PIN ' in line:
+ pin = line.split('MLTEST_PIN ')[1].strip()
+ time.sleep(0.4)
+ screenshot(app_proc.pid, out / '03-pairing.png')
+ pin_file.write_text(pin)
+ print('PIN from the dialog handed to the mock host:', pin)
+ elif 'MLTEST_SHOT ' in line:
+ name = line.split('MLTEST_SHOT ')[1].strip()
+ time.sleep(0.6)
+ ok = screenshot(app_proc.pid, out / f'{name}.png')
+ print('shot', name, 'ok' if ok else 'NO WINDOW')
+ elif 'MLTEST_STREAM' in line:
+ print(line.split('mltest', 1)[-1].strip())
+ elif 'MLTEST_FAIL' in line:
+ verdict = 'FAIL ' + line.split('MLTEST_FAIL', 1)[1].strip()
+ elif 'MLTEST_DONE' in line:
+ verdict = 'PASS'
+ seen = len(lines)
+ if app_proc.poll() is not None and verdict is None:
+ # read the log once more: the last lines may have been written just before the exit
+ if exited:
+ verdict = 'FAIL app exited early with code %s' % app_proc.returncode
+ exited = True
+ print('RESULT', verdict)
+ result = 0 if verdict == 'PASS' else 1
+finally:
+ main.write_bytes(original)
+ stop_file.write_text('x')
+ if app_proc and app_proc.poll() is None:
+ time.sleep(2)
+ if app_proc.poll() is None:
+ app_proc.kill()
+ if mock_proc:
+ try:
+ mock_proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ mock_proc.kill()
+sys.exit(result)
diff --git a/scripts/moonlight/ui-demo.qml b/scripts/moonlight/ui-demo.qml
new file mode 100644
index 00000000..2823341b
--- /dev/null
+++ b/scripts/moonlight/ui-demo.qml
@@ -0,0 +1,102 @@
+ // Injected into a staged copy of Main.qml by scripts/moonlight/ui-demo.py: drives the PC streaming
+ // dialog against the mock host (add host, pair, app list, settings, a launch that fails at RTSP) and
+ // reports through the log. Never part of the product.
+ Timer {
+ id: mlDemo
+ interval: 250; running: true; repeat: true
+ property int step: 0
+ property int ticks: 0
+ property int total: 0
+ readonly property string address: {
+ // One argument (--ml-address=host:port): a bare value would be taken for a file to open.
+ const a = Qt.application.arguments
+ for (let i = 0; i < a.length; ++i) if (a[i].indexOf("--ml-address=") === 0) return a[i].substring(13)
+ return ""
+ }
+ function log(text) { veyra.logUi("mltest", text) }
+ function shot(name) { log("MLTEST_SHOT " + name) }
+ function check(ok, label) { if (!ok) throw new Error(label) }
+ function next(n) { step = n; ticks = 0 }
+ readonly property var ml: veyra.moonlight
+ onTriggered: { try {
+ ++ticks; ++total
+ if (total > 900) throw new Error("bounded step=" + step)
+ const st = ml.state
+ if (step === 0) {
+ if (ticks < 8) return
+ check(ml !== null, "the build has the PC streaming model")
+ dialogs.open("moonlight")
+ next(1); return
+ }
+ if (step === 1) {
+ if (ticks < 8) return
+ check(ml.hosts.length === 0, "no hosts at first")
+ shot("01-empty")
+ next(11); return
+ }
+ if (step === 11) {
+ if (ticks < 14) return // the screenshot is taken by another process; give it time
+ ml.addHost(address)
+ next(2); return
+ }
+ if (step === 2) {
+ if (ml.hosts.length !== 1) { if (ticks > 40) throw new Error("host did not appear: " + st.status); return }
+ check(ml.hosts[0].state === "unpaired", "host listed as unpaired: " + ml.hosts[0].state)
+ if (ticks < 6) return
+ shot("02-host-unpaired")
+ next(12); return
+ }
+ if (step === 12) {
+ if (ticks < 14) return
+ ml.pair(ml.hosts[0].id)
+ next(3); return
+ }
+ if (step === 3) {
+ if (!st.pin) { if (ticks > 20) throw new Error("no pin shown"); return }
+ log("MLTEST_PIN " + st.pin) // the script photographs the PIN box, then hands the PIN to the mock host
+ next(4); return
+ }
+ if (step === 4) {
+ if (!st.paired || ml.apps.length === 0 || st.busy) { if (ticks > 80) throw new Error("not paired in time: " + st.status); return }
+ check(ml.apps.length === 3, "three apps")
+ if (ticks < 4) return
+ shot("04-paired-apps")
+ next(14); return
+ }
+ if (step === 14) {
+ if (ticks < 14) return
+ ml.set("res", "4k"); ml.set("fps", 120); ml.set("codec", 2); ml.set("hdr", true); ml.set("bitrate", 100)
+ next(5); return
+ }
+ if (step === 5) {
+ if (ticks < 6) return
+ shot("05-settings")
+ next(15); return
+ }
+ if (step === 15) {
+ if (ticks < 14) return
+ ml.connectStream(881448767)
+ next(6); return
+ }
+ if (step === 6) {
+ // The mock has no RTSP server: the launch request succeeds, the connection then fails and the
+ // player reports it (the library retries for about a minute before giving up).
+ if (ticks < 8 || !veyra.failed) {
+ if (ticks > 360) throw new Error("no failure reported: status=" + st.status)
+ return
+ }
+ log("MLTEST_STREAM failed " + veyra.statusText)
+ check(veyra.statusText.indexOf("10061") >= 0 || veyra.statusText.indexOf("连接") >= 0, "the failure is explained: " + veyra.statusText)
+ shot("06-connect-failed")
+ next(7); return
+ }
+ if (step === 7) {
+ if (ticks < 12) return
+ shot("07-after-failure")
+ running = false
+ log("MLTEST_DONE")
+ console.log("MLTEST_PASS")
+ Qt.quit(); return
+ }
+ } catch (e) { running = false; log("MLTEST_FAIL " + e.message); console.log("MLTEST_FAIL " + e.message); Qt.quit() } }
+ }
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
index 00b0f883..b76c8079 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"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"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/moonlight/Discovery.cpp b/src/moonlight/Discovery.cpp
new file mode 100644
index 00000000..2aa8f107
--- /dev/null
+++ b/src/moonlight/Discovery.cpp
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/moonlight/Discovery.h"
+
+// windns.h picks the wide record layout under UNICODE; the DNS-SD callbacks deliver wide names.
+#ifndef UNICODE
+#define UNICODE
+#endif
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <windns.h>
+
+#include <algorithm>
+#include <map>
+#include <mutex>
+#include <set>
+#include <vector>
+
+namespace veyra::moonlight {
+namespace {
+
+std::string narrow(const wchar_t* text) {
+ if (!text) return {};
+ const int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
+ if (length <= 1) return {};
+ std::string out(size_t(length - 1), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), length, nullptr, nullptr);
+ return out;
+}
+
+} // namespace
+
+struct Discovery::State {
+ struct Job {
+ std::wstring name;
+ DNS_SERVICE_CANCEL cancel{};
+ };
+ Callback callback;
+ std::mutex mutex;
+ bool stopped = false;
+ bool browsing = false;
+ DNS_SERVICE_CANCEL browseCancel{};
+ std::set<std::wstring> seen;
+ std::vector<std::unique_ptr<Job>> jobs;
+};
+
+namespace {
+
+// Callbacks carry a raw key; the registry maps it back to a live State, so a late callback after
+// stop() finds nothing and does nothing.
+std::mutex g_registryMutex;
+std::map<const void*, std::weak_ptr<Discovery::State>> g_registry;
+
+std::shared_ptr<Discovery::State> lookup(const void* key) {
+ std::lock_guard lock(g_registryMutex);
+ const auto it = g_registry.find(key);
+ return it == g_registry.end() ? nullptr : it->second.lock();
+}
+
+VOID WINAPI resolved(DWORD status, PVOID context, PDNS_SERVICE_INSTANCE instance) {
+ auto state = lookup(context);
+ if (!state) {
+ if (instance) DnsServiceFreeInstance(instance);
+ return;
+ }
+ if (status == ERROR_SUCCESS && instance) {
+ DiscoveredHost host;
+ host.instance = narrow(instance->pszInstanceName);
+ host.hostName = narrow(instance->pszHostName);
+ host.port = 47989; // the HTTP port; the advertised port is the same on Sunshine, and serverinfo corrects the rest
+ if (instance->wPort != 0) host.port = instance->wPort;
+ if (instance->ip4Address) {
+ char text[INET_ADDRSTRLEN] = {};
+ IN_ADDR address{};
+ address.S_un.S_addr = *instance->ip4Address;
+ if (InetNtopA(AF_INET, &address, text, sizeof(text))) host.address = text;
+ }
+ if (host.address.empty()) host.address = host.hostName;
+ if (!host.address.empty()) {
+ bool stopped;
+ { std::lock_guard lock(state->mutex); stopped = state->stopped; }
+ if (!stopped && state->callback) state->callback(host);
+ }
+ }
+ if (instance) DnsServiceFreeInstance(instance);
+}
+
+VOID WINAPI browsed(DWORD status, PVOID context, PDNS_RECORD records) {
+ auto state = lookup(context);
+ if (state && status == ERROR_SUCCESS) {
+ for (PDNS_RECORD record = records; record; record = record->pNext) {
+ if (record->wType != DNS_TYPE_PTR || !record->Data.PTR.pNameHost) continue;
+ const std::wstring name = record->Data.PTR.pNameHost;
+ std::lock_guard lock(state->mutex);
+ if (state->stopped || !state->seen.insert(name).second) continue;
+ auto job = std::make_unique<Discovery::State::Job>();
+ job->name = name;
+ DNS_SERVICE_RESOLVE_REQUEST request{};
+ request.Version = DNS_QUERY_REQUEST_VERSION1;
+ request.InterfaceIndex = 0;
+ request.QueryName = job->name.data();
+ request.pResolveCompletionCallback = resolved;
+ request.pQueryContext = state.get(); // keyed by the State: one registry entry covers every resolve
+ const DNS_STATUS result = DnsServiceResolve(&request, &job->cancel);
+ if (result != DNS_REQUEST_PENDING) {
+ state->seen.erase(name); // try again when it is announced next
+ continue;
+ }
+ state->jobs.push_back(std::move(job));
+ }
+ }
+ if (records) DnsRecordListFree(records, DnsFreeRecordList);
+}
+
+} // namespace
+
+Discovery::Discovery() = default;
+Discovery::~Discovery() { stop(); }
+
+bool Discovery::start(Callback callback) {
+ stop();
+ auto state = std::make_shared<State>();
+ state->callback = std::move(callback);
+ {
+ std::lock_guard lock(g_registryMutex);
+ g_registry[state.get()] = state;
+ }
+ DNS_SERVICE_BROWSE_REQUEST request{};
+ request.Version = DNS_QUERY_REQUEST_VERSION1;
+ request.InterfaceIndex = 0;
+ request.QueryName = L"_nvstream._tcp.local";
+ request.pBrowseCallback = browsed;
+ request.pQueryContext = state.get();
+ const DNS_STATUS result = DnsServiceBrowse(&request, &state->browseCancel);
+ if (result != DNS_REQUEST_PENDING) {
+ std::lock_guard lock(g_registryMutex);
+ g_registry.erase(state.get());
+ return false;
+ }
+ state->browsing = true;
+ state_ = std::move(state);
+ return true;
+}
+
+void Discovery::stop() {
+ auto state = std::move(state_);
+ if (!state) return;
+ {
+ std::lock_guard lock(g_registryMutex);
+ g_registry.erase(state.get()); // late callbacks now find nothing
+ }
+ std::vector<std::unique_ptr<State::Job>> jobs;
+ bool browsing;
+ {
+ std::lock_guard lock(state->mutex);
+ state->stopped = true;
+ browsing = state->browsing;
+ state->browsing = false;
+ jobs = std::move(state->jobs);
+ }
+ // Cancelling can wait for a callback that is running; it must not hold the lock that callback takes.
+ if (browsing) DnsServiceBrowseCancel(&state->browseCancel);
+ for (auto& job : jobs) DnsServiceResolveCancel(&job->cancel);
+}
+
+bool Discovery::running() const { return state_ != nullptr; }
+
+} // namespace veyra::moonlight
diff --git a/src/moonlight/IdentityStore.cpp b/src/moonlight/IdentityStore.cpp
index 1159e791..1a46c8f4 100644
--- a/src/moonlight/IdentityStore.cpp
+++ b/src/moonlight/IdentityStore.cpp
@@ -48,6 +48,9 @@ bool take(const uint8_t*& cursor, const uint8_t* end, std::string& text) {
} // namespace
std::filesystem::path dataDirectory() {
+ // Tests and demos point this somewhere disposable; it is not a user setting.
+ wchar_t override[MAX_PATH] = {};
+ if (GetEnvironmentVariableW(L"VEYRA_MOONLIGHT_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");
diff --git a/src/ui/MoonlightModel.cpp b/src/ui/MoonlightModel.cpp
new file mode 100644
index 00000000..a8d1d23c
--- /dev/null
+++ b/src/ui/MoonlightModel.cpp
@@ -0,0 +1,648 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/ui/MoonlightModel.h"
+
+#include <QFile>
+#include <QGuiApplication>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QMetaObject>
+#include <QRegularExpression>
+#include <QSaveFile>
+#include <QScreen>
+#include <algorithm>
+
+#include "veyra/Log.h"
+#include "veyra/moonlight/Client.h"
+#include "veyra/moonlight/Pairing.h"
+#include "veyra/moonlight/StreamConfig.h"
+
+namespace veyra::ui {
+namespace {
+
+QString qs(const std::string& text) { return QString::fromUtf8(text.data(), qsizetype(text.size())); }
+std::string utf8(const QString& text) { const QByteArray b = text.toUtf8(); return std::string(b.constData(), size_t(b.size())); }
+
+QString describe(const std::exception& e) {
+ if (const auto* transport = dynamic_cast<const moonlight::TransportError*>(&e)) {
+ switch (transport->kind) {
+ case moonlight::TransportError::Kind::Connect: return QObject::tr("连不上主机:请确认地址正确、主机已开机且 Sunshine 在运行,并且防火墙放行了 TCP 47984 / 47989。");
+ case moonlight::TransportError::Kind::Timeout: return QObject::tr("主机没有及时回应,请检查网络。");
+ case moonlight::TransportError::Kind::Tls: return QObject::tr("主机的证书与配对时保存的不一致(主机重装过,或这不是配对过的那台)。请删除这台主机后重新配对。");
+ case moonlight::TransportError::Kind::Cancelled: return QObject::tr("已取消。");
+ case moonlight::TransportError::Kind::Protocol: return QObject::tr("主机的回应无法识别(不是 Sunshine / GameStream 主机?)。");
+ }
+ }
+ if (const auto* status = dynamic_cast<const moonlight::StatusError*>(&e)) {
+ if (status->status == 401) return QObject::tr("主机不认识这台电脑,请重新配对。");
+ return QObject::tr("主机拒绝了请求(%1)。").arg(status->status);
+ }
+ return QObject::tr("出错了:%1").arg(qs(e.what()));
+}
+
+constexpr int kVersion = 1;
+
+QVariantMap defaultSettings() {
+ return QVariantMap{
+ {"res", "1080p"}, {"fps", 60}, {"bitrate", 0}, {"codec", 0}, {"hdr", false},
+ {"audio", 2}, {"gamepad", true}, {"sops", false}, {"hostAudio", false}, {"captureInput", true},
+ };
+}
+
+bool validSetting(const QString& key, const QVariant& value) {
+ if (key == "res") return QStringList{"720p", "1080p", "1440p", "4k", "native"}.contains(value.toString());
+ if (key == "fps") return QList<int>{30, 60, 90, 120, 144}.contains(value.toInt());
+ if (key == "bitrate") { const int v = value.toInt(); return v == 0 || (v >= 1 && v <= 500); } // Mbps; 0 is automatic
+ if (key == "codec") return value.toInt() >= 0 && value.toInt() <= 3;
+ if (key == "audio") return QList<int>{2, 6, 8}.contains(value.toInt());
+ return key == "hdr" || key == "gamepad" || key == "sops" || key == "hostAudio" || key == "captureInput";
+}
+
+QString stateOf(bool online, bool checking, bool paired, int currentGame) {
+ if (checking && !online) return "checking";
+ if (!online) return "offline";
+ if (!paired) return "unpaired";
+ return currentGame != 0 ? "busy" : "online";
+}
+
+} // namespace
+
+MoonlightModel::MoonlightModel(QObject* parent) : QObject(parent), defaults_(defaultSettings()) {}
+
+MoonlightModel::~MoonlightModel() {
+ cancel_ = true;
+ discovery_.stop();
+ // members join their threads (worker_ and probes_) as they are destroyed
+}
+
+// --- persistence -----------------------------------------------------------------------------
+
+void MoonlightModel::loadStore() {
+ hosts_.clear();
+ defaults_ = defaultSettings();
+ QFile file(QString::fromStdWString((moonlight::dataDirectory() / L"hosts.json").wstring()));
+ if (!file.open(QIODevice::ReadOnly)) return;
+ QJsonParseError parseError;
+ const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &parseError);
+ if (parseError.error != QJsonParseError::NoError || !doc.isObject()) {
+ log::warn("moonlight-ui", "hosts.json is damaged; starting without saved hosts");
+ return;
+ }
+ const QJsonObject root = doc.object();
+ const QJsonObject savedDefaults = root.value("defaults").toObject();
+ for (auto it = savedDefaults.begin(); it != savedDefaults.end(); ++it)
+ if (validSetting(it.key(), it.value().toVariant())) defaults_[it.key()] = it.value().toVariant();
+ const QJsonObject last = root.value("last").toObject();
+ lastHost_ = last.value("host").toString();
+ lastApp_ = last.value("app").toInt();
+ lastLabel_ = last.value("label").toString();
+ for (const QJsonValue& value : root.value("hosts").toArray()) {
+ const QJsonObject o = value.toObject();
+ Host h;
+ h.id = o.value("id").toString();
+ h.address = o.value("address").toString();
+ if (h.id.isEmpty() || h.address.isEmpty() || find(h.id)) continue;
+ h.name = o.value("name").toString();
+ h.mac = o.value("mac").toString();
+ h.cert = o.value("cert").toString();
+ h.gpu = o.value("gpu").toString();
+ h.version = o.value("version").toString();
+ h.port = o.value("port").toInt(moonlight::kDefaultHttpPort);
+ h.httpsPort = o.value("httpsPort").toInt(moonlight::kDefaultHttpsPort);
+ h.codecSupport = o.value("codecSupport").toInt(moonlight::kServerH264);
+ h.paired = o.value("paired").toBool() && !h.cert.isEmpty();
+ h.nvidia = o.value("nvidia").toBool();
+ h.saved = true;
+ h.settings = defaults_;
+ const QJsonObject s = o.value("settings").toObject();
+ for (auto it = s.begin(); it != s.end(); ++it)
+ if (validSetting(it.key(), it.value().toVariant())) h.settings[it.key()] = it.value().toVariant();
+ hosts_.push_back(std::move(h));
+ }
+}
+
+bool MoonlightModel::saveStore() const {
+ QJsonObject root;
+ root["version"] = kVersion;
+ root["defaults"] = QJsonObject::fromVariantMap(defaults_);
+ root["last"] = QJsonObject{{"host", lastHost_}, {"app", lastApp_}, {"label", lastLabel_}};
+ QJsonArray array;
+ for (const Host& h : hosts_) {
+ if (!h.saved) continue;
+ array.append(QJsonObject{{"id", h.id}, {"name", h.name}, {"address", h.address}, {"port", h.port}, {"httpsPort", h.httpsPort},
+ {"mac", h.mac}, {"cert", h.cert}, {"gpu", h.gpu}, {"version", h.version}, {"codecSupport", h.codecSupport},
+ {"paired", h.paired}, {"nvidia", h.nvidia}, {"settings", QJsonObject::fromVariantMap(h.settings)}});
+ }
+ root["hosts"] = array;
+ std::error_code ec;
+ std::filesystem::create_directories(moonlight::dataDirectory(), ec);
+ QSaveFile file(QString::fromStdWString((moonlight::dataDirectory() / L"hosts.json").wstring()));
+ if (!file.open(QIODevice::WriteOnly)) return false;
+ file.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
+ return file.commit();
+}
+
+MoonlightModel::Host* MoonlightModel::find(const QString& id) {
+ for (Host& h : hosts_) if (h.id == id) return &h;
+ return nullptr;
+}
+const MoonlightModel::Host* MoonlightModel::find(const QString& id) const {
+ for (const Host& h : hosts_) if (h.id == id) return &h;
+ return nullptr;
+}
+MoonlightModel::Host* MoonlightModel::findByAddress(const QString& address, int port) {
+ for (Host& h : hosts_) if (h.address.compare(address, Qt::CaseInsensitive) == 0 && h.port == port) return &h;
+ return nullptr;
+}
+
+moonlight::Identity MoonlightModel::identity() {
+ std::lock_guard lock(identityMutex_);
+ if (!identity_) {
+ std::error_code ec;
+ std::filesystem::create_directories(moonlight::dataDirectory(), ec);
+ identity_ = moonlight::loadOrCreateIdentity(moonlight::dataDirectory() / L"client.identity");
+ }
+ return *identity_;
+}
+
+// --- state for QML ------------------------------------------------------------------------------
+
+QVariantMap MoonlightModel::settingsOf(const Host* host) const {
+ QVariantMap out = defaultSettings();
+ const QVariantMap& source = host ? host->settings : defaults_;
+ for (auto it = source.begin(); it != source.end(); ++it) out[it.key()] = it.value();
+ return out;
+}
+
+QVariantMap MoonlightModel::state() const {
+ const Host* host = find(selected_);
+ return QVariantMap{
+ {"busy", busy_}, {"status", status_}, {"pin", pin_}, {"pairing", pairing_}, {"selected", selected_},
+ {"settings", settingsOf(host)}, {"discovering", discovery_.running()}, {"ready", loaded_},
+ {"paired", host && host->paired}, {"online", host && host->online}, {"runningApp", runningApp_},
+ {"hostName", host ? (host->name.isEmpty() ? host->address : host->name) : QString()},
+ {"stream", stream_}, {"streaming", streamActive_}, {"lastLabel", lastLabel_},
+ {"hdrHost", host && (host->codecSupport & (moonlight::kServerHevcMain10 | moonlight::kServerAv1Main10)) != 0},
+ {"av1Host", host && (host->codecSupport & (moonlight::kServerAv1Main8 | moonlight::kServerAv1Main10)) != 0},
+ {"hevcHost", host && (host->codecSupport & (moonlight::kServerHevc | moonlight::kServerHevcMain10)) != 0},
+ };
+}
+
+QVariantList MoonlightModel::hosts() const {
+ QVariantList out;
+ for (const Host& h : hosts_) {
+ out << QVariantMap{
+ {"id", h.id}, {"name", h.name.isEmpty() ? h.address : h.name}, {"address", h.address},
+ {"state", stateOf(h.online, h.checking, h.paired, h.currentGame)}, {"paired", h.paired}, {"saved", h.saved},
+ {"running", h.currentGame != 0}, {"gpu", h.gpu}, {"selected", h.id == selected_},
+ };
+ }
+ return out;
+}
+
+// --- worker plumbing -----------------------------------------------------------------------------
+
+void MoonlightModel::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;
+ pairing_ = false;
+ if (done) done();
+ emit changed();
+ }, Qt::QueuedConnection);
+ });
+}
+
+void MoonlightModel::cancel() {
+ cancel_ = true;
+ if (busy_) { status_ = tr("正在取消…"); emit changed(); }
+}
+
+void MoonlightModel::applyInfo(Host& host, const moonlight::ServerInfo& info) {
+ if (!info.hostname.empty()) host.name = qs(info.hostname);
+ host.mac = qs(info.mac);
+ host.gpu = qs(info.gpuModel);
+ host.version = qs(info.appVersion);
+ host.httpsPort = info.httpsPort;
+ host.codecSupport = info.serverCodecModeSupport;
+ host.nvidia = info.nvidiaServerSoftware;
+ host.paired = host.paired && info.paired; // the host may have forgotten us
+ host.currentGame = info.currentGame;
+ host.online = true;
+}
+
+// A host that was asked once, off the job queue: used for found hosts and manual adds.
+void MoonlightModel::probe(const QString& address, int port, bool manual) {
+ std::erase_if(probes_, [](std::jthread& t) { return !t.joinable(); });
+ probes_.emplace_back([this, address, port, manual](std::stop_token stop) {
+ try {
+ const moonlight::Identity id = identity();
+ moonlight::ServerClient client(id, moonlight::HostAddress{utf8(address), uint16_t(port)}, {}, moonlight::kDefaultHttpsPort, true);
+ client.setCancel(&cancel_);
+ const moonlight::ServerInfo info = client.serverInfo(true);
+ if (stop.stop_requested()) return;
+ QMetaObject::invokeMethod(this, [this, address, port, manual, info] {
+ Host* known = nullptr;
+ for (Host& h : hosts_) if (h.id == qs(info.uniqueId)) known = &h;
+ if (!known) known = findByAddress(address, port);
+ if (!known) {
+ Host h;
+ h.id = qs(info.uniqueId);
+ h.address = address;
+ h.port = port;
+ hosts_.push_back(std::move(h));
+ known = &hosts_.back();
+ }
+ known->id = qs(info.uniqueId);
+ known->address = address;
+ known->port = port;
+ known->settings = known->settings.isEmpty() ? defaults_ : known->settings;
+ applyInfo(*known, info);
+ if (manual) { known->saved = true; selected_ = known->id; saveStore(); reloadApps(); }
+ else if (known->saved) saveStore();
+ if (selected_.isEmpty() && known->paired) { selected_ = known->id; reloadApps(); }
+ emit changed();
+ }, Qt::QueuedConnection);
+ } catch (const std::exception& e) {
+ if (!manual || stop.stop_requested()) return;
+ const QString text = describe(e);
+ QMetaObject::invokeMethod(this, [this, text] { status_ = text; emit changed(); }, Qt::QueuedConnection);
+ }
+ });
+}
+
+void MoonlightModel::discovered(const QString& address, int port) { probe(address, port, false); }
+
+// --- dialog lifecycle -----------------------------------------------------------------------------
+
+void MoonlightModel::load() {
+ if (!loaded_) {
+ loadStore();
+ loaded_ = true;
+ if (selected_.isEmpty()) {
+ if (const Host* last = find(lastHost_)) selected_ = last->id;
+ else if (!hosts_.empty()) selected_ = hosts_.front().id;
+ }
+ }
+ // VEYRA_MOONLIGHT_NO_DISCOVERY keeps the tests from picking up real hosts on the network.
+ if (!discovery_.running() && qEnvironmentVariableIsEmpty("VEYRA_MOONLIGHT_NO_DISCOVERY")) {
+ const bool started = discovery_.start([this](const moonlight::DiscoveredHost& host) {
+ const QString address = qs(host.address);
+ const int port = host.port;
+ QMetaObject::invokeMethod(this, [this, address, port] { discovered(address, port); }, Qt::QueuedConnection);
+ });
+ if (!started) log::warn("moonlight-ui", "network search is not available; hosts must be added by address");
+ }
+ refresh();
+ emit changed();
+}
+
+void MoonlightModel::unload() {
+ discovery_.stop();
+ emit changed();
+}
+
+void MoonlightModel::refresh() {
+ if (hosts_.empty() || busy_) { emit changed(); return; }
+ for (Host& h : hosts_) h.checking = true;
+ // One job checks every known host in turn; a dead host costs its connect timeout, not the dialog.
+ struct Target { QString id, address, cert; int port, httpsPort; bool nvidia; };
+ std::vector<Target> targets;
+ for (const Host& h : hosts_) targets.push_back({h.id, h.address, h.cert, h.port, h.httpsPort, h.nvidia});
+ startJob(tr("正在检查主机…"), [this, targets](const std::atomic<bool>& cancel) -> std::function<void()> {
+ struct Result { QString id; bool online = false; moonlight::ServerInfo info; };
+ auto results = std::make_shared<std::vector<Result>>();
+ const moonlight::Identity id = identity();
+ for (const Target& t : targets) {
+ if (cancel.load()) break;
+ Result r;
+ r.id = t.id;
+ try {
+ moonlight::ServerClient client(id, moonlight::HostAddress{utf8(t.address), uint16_t(t.port)}, utf8(t.cert), uint16_t(t.httpsPort), !t.nvidia);
+ client.setCancel(&cancel);
+ r.info = client.serverInfo(true);
+ r.online = true;
+ } catch (const std::exception&) {}
+ results->push_back(std::move(r));
+ }
+ return [this, results] {
+ for (Host& h : hosts_) h.checking = false;
+ for (const Result& r : *results) {
+ Host* h = find(r.id);
+ if (!h) continue;
+ if (r.online) applyInfo(*h, r.info);
+ else { h->online = false; h->currentGame = 0; }
+ }
+ bool changedStore = false;
+ for (const Host& h : hosts_) changedStore = changedStore || h.saved;
+ if (changedStore) saveStore();
+ status_.clear();
+ const Host* selected = find(selected_);
+ if (selected && selected->paired && selected->online) reloadApps();
+ };
+ });
+}
+
+// --- hosts -----------------------------------------------------------------------------------------
+
+void MoonlightModel::addHost(const QString& address) {
+ QString text = address.trimmed();
+ int port = moonlight::kDefaultHttpPort;
+ // "host", "host:port", "[v6]" and "[v6]:port"; a bare IPv6 literal has several colons and no port.
+ if (text.startsWith('[')) {
+ const int close = text.indexOf(']');
+ if (close < 0) { status_ = tr("地址格式不对。"); emit changed(); return; }
+ const QString rest = text.mid(close + 1);
+ if (rest.startsWith(':')) port = rest.mid(1).toInt();
+ text = text.mid(1, close - 1);
+ } else if (text.count(':') == 1) {
+ port = text.section(':', 1).toInt();
+ text = text.section(':', 0, 0);
+ }
+ if (text.isEmpty() || text.size() > 253 || port < 1 || port > 65535 || text.contains(QRegularExpression("[\\s/\\\\]"))) {
+ status_ = tr("请填写主机的 IP 地址或名称,例如 192.168.1.20。");
+ emit changed();
+ return;
+ }
+ status_ = tr("正在连接 %1…").arg(text);
+ emit changed();
+ probe(text, port, true);
+}
+
+void MoonlightModel::select(const QString& id) {
+ if (selected_ == id) return;
+ selected_ = id;
+ apps_.clear();
+ runningApp_ = 0;
+ emit changed();
+ const Host* h = find(id);
+ if (h && h->paired && h->online) reloadApps();
+}
+
+void MoonlightModel::pair(const QString& id) {
+ const Host* host = find(id);
+ if (!host || busy_) return;
+ pin_ = qs(moonlight::generatePin());
+ pairing_ = true;
+ selected_ = id;
+ struct Copy { QString id, address, cert; int port, httpsPort; bool nvidia; };
+ const Copy h{host->id, host->address, host->cert, host->port, host->httpsPort, host->nvidia};
+ const std::string pin = utf8(pin_);
+ startJob(tr("配对中:请在主机的 Sunshine 网页(https://%1:47990 的 PIN 页面)输入上面的 PIN。").arg(h.address),
+ [this, h, pin](const std::atomic<bool>& cancel) -> std::function<void()> {
+ const moonlight::Identity id = identity();
+ moonlight::ServerClient client(id, moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, {}, uint16_t(h.httpsPort), !h.nvidia);
+ client.setCancel(&cancel);
+ const moonlight::ServerInfo info = client.serverInfo(true);
+ if (info.paired) {
+ // The host already trusts a client with this id. Nothing to do unless we lost its certificate.
+ }
+ const moonlight::PairOutcome outcome = moonlight::pairWithHost(client, id, info, pin, &cancel);
+ const QString hostId = h.id;
+ return [this, outcome, hostId, info] {
+ pin_.clear();
+ Host* host = find(hostId);
+ using R = moonlight::PairResult;
+ switch (outcome.result) {
+ case R::Paired:
+ if (host) {
+ host->cert = qs(outcome.serverCertPem);
+ host->paired = true;
+ host->saved = true;
+ applyInfo(*host, info);
+ host->paired = true;
+ saveStore();
+ reloadApps();
+ }
+ status_ = tr("配对成功。");
+ emit notice(tr("已和主机配对"), false);
+ break;
+ case R::PinWrong: status_ = tr("主机上输入的 PIN 和这里显示的不一致,请重新配对。"); break;
+ case R::AlreadyInProgress: status_ = tr("主机正在和另一台设备配对,请稍后再试。"); break;
+ case R::Cancelled: status_ = tr("已取消配对。"); break;
+ case R::Failed: status_ = tr("配对失败(%1)。请确认主机上的 Sunshine 在运行,并在它的网页里输入了 PIN。").arg(qs(outcome.detail)); break;
+ }
+ };
+ });
+}
+
+void MoonlightModel::forget(const QString& id) {
+ const Host* host = find(id);
+ if (!host || busy_) return;
+ const QString hostId = host->id;
+ struct Copy { QString address, cert; int port, httpsPort; bool nvidia, paired; };
+ const Copy h{host->address, host->cert, host->port, host->httpsPort, host->nvidia, host->paired};
+ startJob(tr("正在删除…"), [this, h](const std::atomic<bool>& cancel) -> std::function<void()> {
+ // Tell the host to forget us too, when we can; a dead host must not keep the entry alive.
+ bool told = false;
+ if (h.paired) {
+ try {
+ moonlight::ServerClient client(identity(), moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
+ client.setCancel(&cancel);
+ client.unpair();
+ told = true;
+ } catch (const std::exception&) {}
+ }
+ return [this, told, h] { status_ = h.paired && !told ? tr("已从本机删除;主机没有回应,它那边的配对记录需要在 Sunshine 网页里自己清除。") : tr("已删除。"); };
+ });
+ // The list changes at once; the job only talks to the host.
+ std::erase_if(hosts_, [&](const Host& x) { return x.id == hostId; });
+ if (selected_ == hostId) { selected_.clear(); apps_.clear(); runningApp_ = 0; }
+ if (lastHost_ == hostId) { lastHost_.clear(); lastLabel_.clear(); lastApp_ = 0; }
+ saveStore();
+ emit changed();
+}
+
+// --- apps ------------------------------------------------------------------------------------------
+
+void MoonlightModel::reloadApps() {
+ const Host* host = find(selected_);
+ if (!host || !host->paired || busy_) return;
+ struct Copy { QString id, address, cert; int port, httpsPort; bool nvidia; };
+ const Copy h{host->id, host->address, host->cert, host->port, host->httpsPort, host->nvidia};
+ startJob(tr("正在读取游戏列表…"), [this, h](const std::atomic<bool>& cancel) -> std::function<void()> {
+ moonlight::ServerClient client(identity(), moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
+ client.setCancel(&cancel);
+ const moonlight::ServerInfo info = client.serverInfo(true);
+ const std::vector<moonlight::AppEntry> apps = client.appList();
+ return [this, h, info, apps] {
+ Host* host = find(h.id);
+ if (!host) return;
+ applyInfo(*host, info);
+ if (selected_ != h.id) return;
+ apps_.clear();
+ for (const auto& a : apps)
+ apps_ << QVariantMap{{"id", a.id}, {"name", qs(a.name)}, {"running", info.currentGame != 0 && info.currentGame == a.id}, {"hdr", a.hdrSupported}};
+ runningApp_ = info.currentGame;
+ status_ = apps.empty() ? tr("主机上没有配置任何游戏或程序(在 Sunshine 网页的 Applications 里添加)。") : QString();
+ };
+ });
+}
+
+void MoonlightModel::quitApp() {
+ const Host* host = find(selected_);
+ if (!host || !host->paired || busy_) return;
+ struct Copy { QString id, address, cert; int port, httpsPort; bool nvidia; };
+ const Copy h{host->id, host->address, host->cert, host->port, host->httpsPort, host->nvidia};
+ startJob(tr("正在退出主机上的游戏…"), [this, h](const std::atomic<bool>& cancel) -> std::function<void()> {
+ moonlight::ServerClient client(identity(), moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
+ client.setCancel(&cancel);
+ client.quit();
+ const moonlight::ServerInfo info = client.serverInfo(true);
+ return [this, h, info] {
+ if (Host* host = find(h.id)) applyInfo(*host, info);
+ for (QVariant& a : apps_) { QVariantMap m = a.toMap(); m["running"] = false; a = m; }
+ runningApp_ = info.currentGame;
+ status_ = tr("已请求主机退出游戏。");
+ };
+ });
+}
+
+// --- settings ---------------------------------------------------------------------------------------
+
+bool MoonlightModel::set(const QString& key, const QVariant& value) {
+ if (!validSetting(key, value)) return false;
+ QVariant stored = value;
+ if (key == "hdr" || key == "gamepad" || key == "sops" || key == "hostAudio" || key == "captureInput") stored = value.toBool();
+ else if (key != "res") stored = value.toInt();
+ if (Host* host = find(selected_)) {
+ if (host->settings.isEmpty()) host->settings = defaults_;
+ host->settings[key] = stored;
+ }
+ defaults_[key] = stored; // the next new host starts from the latest choice
+ saveStore();
+ emit changed();
+ return true;
+}
+
+source::MoonlightStreamOptions MoonlightModel::optionsFor(const Host* host) const {
+ const QVariantMap s = settingsOf(host);
+ source::MoonlightStreamOptions o;
+ const QString res = s.value("res").toString();
+ if (res == "720p") { o.width = 1280; o.height = 720; }
+ else if (res == "1440p") { o.width = 2560; o.height = 1440; }
+ else if (res == "4k") { o.width = 3840; o.height = 2160; }
+ else if (res == "native") {
+ if (const QScreen* screen = QGuiApplication::primaryScreen()) {
+ const QSize size = screen->size() * screen->devicePixelRatio();
+ o.width = std::clamp(size.width() & ~1, 640, 7680);
+ o.height = std::clamp(size.height() & ~1, 360, 4320);
+ }
+ } else { o.width = 1920; o.height = 1080; }
+ o.fps = s.value("fps").toInt();
+ const int mbps = s.value("bitrate").toInt();
+ o.bitrateKbps = mbps > 0 ? mbps * 1000 : 0;
+ o.codec = static_cast<moonlight::CodecChoice>(std::clamp(s.value("codec").toInt(), 0, 3));
+ o.hdr = s.value("hdr").toBool();
+ o.audioChannels = s.value("audio").toInt();
+ o.sops = s.value("sops").toBool();
+ o.localAudio = s.value("hostAudio").toBool();
+ o.gamepadMask = s.value("gamepad").toBool() ? 1 : 0;
+ o.av1HardwareDecode = false; // AV1 only on request until the decoder reports what the GPU can do
+ return o;
+}
+
+// --- starting a stream ---------------------------------------------------------------------------------
+
+bool MoonlightModel::connectStream(int appId) { return launchSelected(appId); }
+
+bool MoonlightModel::resumeLast() {
+ if (!loaded_) { loadStore(); loaded_ = true; }
+ if (lastHost_.isEmpty() || lastApp_ < 0 || !find(lastHost_)) return false;
+ selected_ = lastHost_;
+ return launchSelected(lastApp_);
+}
+
+bool MoonlightModel::launchSelected(int appId) {
+ const Host* host = find(selected_);
+ if (!host || !host->paired) { status_ = tr("请先和这台主机配对。"); emit changed(); return false; }
+ if (busy_ || !launch_) return false;
+ const source::MoonlightStreamOptions options = optionsFor(host);
+ const bool captureInput = settingsOf(host).value("captureInput").toBool();
+ QString appName;
+ for (const QVariant& a : std::as_const(apps_)) if (a.toMap().value("id").toInt() == appId) appName = a.toMap().value("name").toString();
+ if (appName.isEmpty() && appId == lastApp_ && host->id == lastHost_) appName = lastLabel_.section(" · ", 1);
+ const QString hostName = host->name.isEmpty() ? host->address : host->name;
+ struct Copy { QString id, address, cert; int port, httpsPort; bool nvidia; };
+ const Copy h{host->id, host->address, host->cert, host->port, host->httpsPort, host->nvidia};
+ startJob(tr("正在联系主机…"), [this, h, appId, options, captureInput, appName, hostName](const std::atomic<bool>& cancel) -> std::function<void()> {
+ const moonlight::Identity id = identity();
+ moonlight::ServerClient client(id, moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
+ client.setCancel(&cancel);
+ const moonlight::ServerInfo info = client.serverInfo();
+ if (!info.paired) return [this] { status_ = tr("主机不再认得这台电脑,请重新配对。"); };
+ if (info.currentGame != 0 && info.currentGame != appId)
+ return [this] { status_ = tr("主机正在运行另一个游戏。先选它继续,或点「退出游戏」结束它(未保存的进度会丢失),再开始新的。"); };
+ if (moonlight::chooseVideoFormats(options.codec, options.hdr, info.serverCodecModeSupport, options.av1HardwareDecode) == 0)
+ return [this, hdr = options.hdr] { status_ = hdr ? tr("这台主机没有 10 位(HDR)编码能力,或选择的编码不支持 HDR。请关闭 HDR,或换编码。")
+ : tr("主机不支持所选的编码,请改成「自动」。"); };
+ auto launch = std::make_shared<Launch>();
+ launch->desc.identity = id;
+ launch->desc.address = moonlight::HostAddress{utf8(h.address), uint16_t(h.port)};
+ launch->desc.httpsPort = info.httpsPort;
+ launch->desc.serverCertPem = utf8(h.cert);
+ launch->desc.host = info;
+ launch->desc.appId = appId;
+ launch->desc.resume = info.currentGame == appId && appId != 0;
+ launch->desc.options = options;
+ launch->label = appName.isEmpty() ? hostName : hostName + QStringLiteral(" · ") + appName;
+ launch->captureInput = captureInput;
+ const QString hostId = h.id;
+ return [this, launch, hostId, appId] {
+ const QString label = launch->label; // the handler takes the whole launch
+ if (!launch_ || !launch_(std::move(*launch))) {
+ status_ = tr("无法开始串流,请查看日志。");
+ return;
+ }
+ lastHost_ = hostId;
+ lastApp_ = appId;
+ lastLabel_ = label;
+ saveStore();
+ status_ = tr("正在建立串流…");
+ emit started();
+ };
+ });
+ return true;
+}
+
+// --- stream state from the bridge ---------------------------------------------------------------------
+
+void MoonlightModel::updateStream(bool active, const source::MoonlightStats& s) {
+ QVariantMap now;
+ if (active) {
+ const char* names[] = {"idle", "launching", "connecting", "streaming", "ended", "failed"};
+ now = QVariantMap{
+ {"state", names[size_t(s.state)]}, {"message", QString::fromStdWString(s.message)},
+ {"codec", qs(s.codec)}, {"hdr", s.hdr}, {"hardware", s.hardwareDecode},
+ {"width", int(s.width)}, {"height", int(s.height)}, {"fps", s.fps},
+ {"receivedFps", s.receivedFps}, {"decodedFps", s.decodedFps},
+ {"hostMs", s.hostLatencyMs}, {"receiveMs", s.receiveMs}, {"queueMs", s.queueMs}, {"decodeMs", s.decodeMs},
+ {"rttMs", s.rttMs}, {"rttVarianceMs", s.rttVarianceMs},
+ {"lost", double(s.fecFailed)}, {"recovered", double(s.fecRecovered)}, {"packets", double(s.videoPackets)},
+ {"dropped", double(s.dropped)}, {"decodeErrors", double(s.decodeErrors)},
+ };
+ }
+ if (now == stream_ && active == streamActive_) return;
+ stream_ = now;
+ streamActive_ = active;
+ emit changed();
+}
+
+} // namespace veyra::ui
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index fe5e9be2..ed991a41 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -53,6 +53,10 @@
#include "veyra/remoteplay/PsnAuth.h"
#include "veyra/source/RemotePlaySource.h"
#endif
+#ifdef VEYRA_ENABLE_MOONLIGHT
+#include "veyra/ui/MoonlightInputCapture.h"
+#include "veyra/ui/MoonlightModel.h"
+#endif
#include <future>
#include <functional>
#include <map>
@@ -552,6 +556,14 @@ struct QmlPlayerBridge::Impl {
options = engine::PlayerOptions::from(s,order);
return true;
}
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ // --- PC streaming (Moonlight). Last, so they are destroyed first: the model joins its workers.
+ QTimer* moonlightTimer = nullptr;
+ bool moonlightWantCapture = false, moonlightStatsVisible = false, moonlightWasActive = false;
+ int moonlightStatsTicks = 0;
+ std::unique_ptr<ui::MoonlightInputCapture> moonlightCapture;
+ std::unique_ptr<ui::MoonlightModel> moonlight;
+#endif
};
namespace {
@@ -613,6 +625,9 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
connect(this,&QmlPlayerBridge::settingsChanged,this,&QmlPlayerBridge::fgChoicesChanged);
impl_->loadPrefs();
if (qApp) qApp->installEventFilter(this);
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ setupMoonlight();
+#endif
// Before anything opens: the renderer reads the output choice at start().
applyPreference(QStringLiteral("audioDevice"));
applyPreference(QStringLiteral("audioForceStereo"));
@@ -737,6 +752,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
tickImageBatch();
tickCapture();
tickPs5();
+ tickMoonlight();
// 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;
@@ -1655,6 +1671,148 @@ QVariantMap QmlPlayerBridge::ps5() const {
return out;
}
QVariantList QmlPlayerBridge::ps5Profiles() const { return impl_->ps5ProfileList; }
+
+// --- PC streaming (Moonlight / Sunshine) -----------------------------------------------------------
+QObject* QmlPlayerBridge::moonlightModel() const {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ return impl_->moonlight.get();
+#else
+ return nullptr;
+#endif
+}
+bool QmlPlayerBridge::moonlightCaptured() const {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ return impl_->moonlightCapture && impl_->moonlightCapture->captured();
+#else
+ return false;
+#endif
+}
+bool QmlPlayerBridge::moonlightStatsVisible() const {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ return impl_->moonlightStatsVisible;
+#else
+ return false;
+#endif
+}
+void QmlPlayerBridge::setMoonlightStatsVisible(bool visible) {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ if (impl_->moonlightStatsVisible == visible) return;
+ impl_->moonlightStatsVisible = visible;
+ emit moonlightUiChanged();
+#else
+ (void)visible;
+#endif
+}
+void QmlPlayerBridge::openMoonlightDialog() { emit navigate(QStringLiteral("moonlight")); }
+
+void QmlPlayerBridge::moonlightCapture(bool on) {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ auto& i = *impl_;
+ if (!i.moonlightCapture) return;
+ if (!on) {
+ i.moonlightWantCapture = false;
+ i.moonlightCapture->capture(false);
+ return;
+ }
+ if (!i.snapshot.moonlightActive || !i.videoWindow) return;
+ i.moonlightCapture->setWindow(GetAncestor(i.videoWindow, GA_ROOT));
+ // The tick keeps trying until the window is in the foreground (right after connecting it may not be yet).
+ i.moonlightWantCapture = !i.moonlightCapture->capture(true);
+#else
+ (void)on;
+#endif
+}
+
+void QmlPlayerBridge::moonlightDisconnect() {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ moonlightCapture(false);
+ if (impl_->snapshot.moonlightActive) stopPlayback();
+#endif
+}
+
+#ifdef VEYRA_ENABLE_MOONLIGHT
+void QmlPlayerBridge::setupMoonlight() {
+ auto& i = *impl_;
+ i.moonlight = std::make_unique<ui::MoonlightModel>();
+ i.moonlightCapture = std::make_unique<ui::MoonlightInputCapture>(i.engine);
+ connect(i.moonlightCapture.get(), &ui::MoonlightInputCapture::capturedChanged, this, [this](bool) { emit moonlightUiChanged(); });
+ connect(i.moonlightCapture.get(), &ui::MoonlightInputCapture::releaseRequested, this, [this] {
+ impl_->moonlightWantCapture = false;
+ emit notice(tr("已释放键盘和鼠标(点击画面重新捕获)"), false);
+ });
+ connect(i.moonlightCapture.get(), &ui::MoonlightInputCapture::quitRequested, this, [this] { moonlightDisconnect(); });
+ connect(i.moonlightCapture.get(), &ui::MoonlightInputCapture::statsRequested, this, [this] { setMoonlightStatsVisible(!moonlightStatsVisible()); });
+ connect(i.moonlight.get(), &ui::MoonlightModel::notice, this, &QmlPlayerBridge::notice);
+ i.moonlight->setLaunchHandler([this](ui::MoonlightModel::Launch launch) -> bool {
+ auto& j = *impl_;
+ if (!j.videoWindow) return false;
+ rememberPosition(true);
+ j.openingSource = true;
+ j.sourceLabel = L"PC · " + launch.label.toStdWString();
+ j.resumeSession = 0;
+ j.screenFillActive = false;
+ const bool pad = (launch.desc.options.gamepadMask & 1) != 0;
+ j.moonlightWantCapture = launch.captureInput;
+ const QString label = launch.label;
+ auto request = std::make_shared<source::MoonlightConnectDesc>(std::move(launch.desc));
+ openAfterCinema(tr("正在连接 %1").arg(label), [this, request, pad] {
+ auto& k = *impl_;
+ if (k.preOpen) k.preOpen();
+ k.engine.previewView({});
+ k.engine.openMoonlight(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 and sent only when it changes.
+ if (pad) {
+ if (!k.controller.start()) veyra::log::warn("moonlight-input", "SDL gamepad initialization failed");
+ if (!k.moonlightTimer) {
+ k.moonlightTimer = new QTimer(this);
+ k.moonlightTimer->setTimerType(Qt::PreciseTimer);
+ connect(k.moonlightTimer, &QTimer::timeout, this, [this] {
+ auto& m = *impl_;
+ if (!m.snapshot.moonlightActive) { m.controller.stop(); m.moonlightTimer->stop(); return; }
+ const bool focused = QGuiApplication::focusWindow() != nullptr;
+ m.engine.moonlightController(m.controller.poll(focused));
+ m.controller.feedback(m.engine.moonlightFeedback(), focused);
+ });
+ }
+ k.moonlightTimer->start(4);
+ } else {
+ if (k.moonlightTimer) k.moonlightTimer->stop();
+ k.controller.stop();
+ }
+#else
+ (void)pad;
+#endif
+ });
+ rememberSource(QStringLiteral("moonlight"), label);
+ return true;
+ });
+}
+
+void QmlPlayerBridge::tickMoonlight() {
+ auto& i = *impl_;
+ if (!i.moonlight) return;
+ const auto& s = i.snapshot;
+ const bool active = s.moonlightActive;
+ if (active != i.moonlightWasActive) {
+ i.moonlightWasActive = active;
+ if (!active) {
+ i.moonlightWantCapture = false;
+ if (i.moonlightCapture) i.moonlightCapture->capture(false);
+ }
+ i.moonlight->updateStream(active, s.moonlight);
+ } else if (active && ++i.moonlightStatsTicks >= 15) {
+ i.moonlightStatsTicks = 0;
+ i.moonlight->updateStream(true, s.moonlight);
+ }
+ // Take the keyboard and mouse as soon as the picture is up (and again when the window comes to the front).
+ if (active && i.moonlightWantCapture && s.moonlight.state == source::MoonlightStats::State::Streaming) moonlightCapture(true);
+}
+#else
+void QmlPlayerBridge::tickMoonlight() {}
+#endif
void QmlPlayerBridge::ps5Load() {
#ifdef VEYRA_ENABLE_REMOTEPLAY
auto& i = *impl_;
@@ -5132,6 +5290,8 @@ QVariantMap QmlPlayerBridge::lastSource() const {
saved[QStringLiteral("summary")] = captureSessionSummary();
} else if (kind == QLatin1String("ps5")) {
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("screen")) {
saved[QStringLiteral("summary")] = tr("屏幕捕获 · %1").arg(saved.value(QStringLiteral("label")).toString());
} else if (hasCaptureSession()) {
@@ -5161,6 +5321,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("moonlight")) {
+#ifdef VEYRA_ENABLE_MOONLIGHT
+ if (!impl_->moonlight || !impl_->moonlight->resumeLast()) {
+ emit notice(tr("没能继续上次的 PC 串流,请在 PC 串流窗口里重新选择"), true);
+ emit navigate(QStringLiteral("moonlight"));
+ }
+#else
+ emit notice(tr("此版本不含 PC 串流"), true);
#endif
return;
}
@@ -5229,6 +5400,7 @@ QString QmlPlayerBridge::sourceTitle() const {
return tr("采集卡 · %1").arg(name.isEmpty() ? impl_->liveLabel : name);
}
if (kind == QLatin1String("ps5")) return tr("PS5 串流 · %1").arg(impl_->liveLabel);
+ if (kind == QLatin1String("moonlight")) return tr("PC 串流 · %1").arg(impl_->liveLabel);
return tr("屏幕捕获 · %1").arg(impl_->liveLabel);
}
// "1080p60" / "1080p59.94": the reported height and nominal rate only.
diff --git a/tests/moonlight/MockHost.h b/tests/moonlight/MockHost.h
new file mode 100644
index 00000000..e416e3c9
--- /dev/null
+++ b/tests/moonlight/MockHost.h
@@ -0,0 +1,300 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// A fake Sunshine host on loopback for the Moonlight tests: serverinfo, applist, launch and the host side
+// of the five-step pairing (with real TLS and client certificate pinning). It shares the client's protocol
+// understanding, so it proves the client is self-consistent, not that a real host accepts it.
+#pragma once
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+#include <openssl/bio.h>
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <openssl/x509.h>
+
+#include <atomic>
+#include <chrono>
+#include <map>
+#include <mutex>
+#include <string>
+#include <thread>
+
+#include "veyra/moonlight/Client.h"
+#include "veyra/moonlight/Crypto.h"
+#include "veyra/moonlight/Xml.h"
+
+namespace veyra::moonlight::mock {
+
+// ---------------------------------------------------------------- fixtures
+
+inline const char* kServerInfoXml =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<root status_code=\"200\"><hostname>DESKTOP-TEST</hostname><appversion>7.1.431.-1</appversion>"
+ "<GfeVersion>3.23.0.74</GfeVersion><uniqueid>ABCD1234EF567890</uniqueid><HttpsPort>48000</HttpsPort>"
+ "<ExternalPort>47999</ExternalPort><MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC><mac>AA:BB:CC:DD:EE:FF</mac>"
+ "<LocalIP>192.168.1.20</LocalIP><ServerCodecModeSupport>197377</ServerCodecModeSupport>"
+ "<SupportedDisplayMode><DisplayMode><Width>3840</Width><Height>2160</Height><RefreshRate>60</RefreshRate></DisplayMode>"
+ "<DisplayMode><Width>1920</Width><Height>1080</Height><RefreshRate>60</RefreshRate></DisplayMode></SupportedDisplayMode>"
+ "<PairStatus>1</PairStatus><currentgame>7</currentgame><state>SUNSHINE_SERVER_BUSY</state></root>";
+
+inline const char* kAppListXml =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<root status_code=\"200\">"
+ "<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>"
+ "<App><IsHdrSupported>0</IsHdrSupported><AppTitle>Tom &amp; Jerry &lt;Deluxe&gt; &#x4E2D;</AppTitle><ID>12</ID></App>"
+ "<App><AppTitle/><ID>13</ID></App>"
+ "</root>";
+
+// ---------------------------------------------------------------- mock host
+
+inline std::string hexOf(const std::string& bytes) { return xml::toHex(bytes); }
+
+struct Query {
+ std::string command;
+ std::map<std::string, std::string> args;
+};
+
+inline Query parseRequestLine(const std::string& request) {
+ Query q;
+ const auto space1 = request.find(' ');
+ const auto space2 = request.find(' ', space1 + 1);
+ std::string target = request.substr(space1 + 1, space2 - space1 - 1);
+ const auto mark = target.find('?');
+ q.command = target.substr(1, mark == std::string::npos ? std::string::npos : mark - 1);
+ if (mark != std::string::npos) {
+ size_t pos = mark + 1;
+ while (pos < target.size()) {
+ const auto amp = target.find('&', pos);
+ const std::string pair = target.substr(pos, amp == std::string::npos ? std::string::npos : amp - pos);
+ const auto eq = pair.find('=');
+ q.args[pair.substr(0, eq)] = eq == std::string::npos ? "" : pair.substr(eq + 1);
+ pos = amp == std::string::npos ? target.size() : amp + 1;
+ }
+ }
+ return q;
+}
+
+class MockHost {
+public:
+ explicit MockHost(const std::string& pin) : pin_(pin) {
+ identity = createIdentity();
+ WSADATA data;
+ WSAStartup(MAKEWORD(2, 2), &data);
+ httpListen_ = listenOnLoopback(httpPort);
+ httpsListen_ = listenOnLoopback(httpsPort);
+ ctx_ = SSL_CTX_new(TLS_server_method());
+ BIO* certBio = BIO_new_mem_buf(identity.certPem.data(), int(identity.certPem.size()));
+ BIO* keyBio = BIO_new_mem_buf(identity.keyPem.data(), int(identity.keyPem.size()));
+ X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
+ EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);
+ SSL_CTX_use_certificate(ctx_, cert);
+ SSL_CTX_use_PrivateKey(ctx_, key);
+ X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);
+ SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
+ // Only the client certificate that completed pairing may use HTTPS.
+ SSL_CTX_set_cert_verify_callback(ctx_, [](X509_STORE_CTX* store, void* arg) -> int {
+ auto* self = static_cast<MockHost*>(arg);
+ X509* peer = X509_STORE_CTX_get0_cert(store);
+ unsigned char* der = nullptr;
+ const int length = i2d_X509(peer, &der);
+ std::string presented(reinterpret_cast<char*>(der), size_t(length));
+ OPENSSL_free(der);
+ std::lock_guard lock(self->mutex_);
+ return !self->pairedClientDer_.empty() && presented == self->pairedClientDer_ ? 1 : 0;
+ }, this);
+ httpThread_ = std::thread([this] { acceptLoop(httpListen_, false); });
+ httpsThread_ = std::thread([this] { acceptLoop(httpsListen_, true); });
+ }
+
+ ~MockHost() {
+ stop_ = true;
+ closesocket(httpListen_);
+ closesocket(httpsListen_);
+ if (httpThread_.joinable()) httpThread_.join();
+ if (httpsThread_.joinable()) httpsThread_.join();
+ SSL_CTX_free(ctx_);
+ }
+
+ void enterPin() { pinEntered_ = true; }
+ // The PIN the user would type on the host; the pairing step that derives the key waits for it.
+ void setPin(const std::string& pin) {
+ { std::lock_guard lock(mutex_); pin_ = pin; }
+ pinEntered_ = true;
+ }
+ std::atomic<int> currentGame{7};
+ void forgetPairing() {
+ std::lock_guard lock(mutex_);
+ pairedClientDer_.clear();
+ }
+ void presentDifferentCertificate() {
+ // Swap to a new identity the client has never pinned.
+ Identity other = createIdentity();
+ BIO* certBio = BIO_new_mem_buf(other.certPem.data(), int(other.certPem.size()));
+ BIO* keyBio = BIO_new_mem_buf(other.keyPem.data(), int(other.keyPem.size()));
+ X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
+ EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);
+ SSL_CTX_use_certificate(ctx_, cert);
+ SSL_CTX_use_PrivateKey(ctx_, key);
+ X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);
+ }
+
+ Identity identity;
+ uint16_t httpPort = 0, httpsPort = 0;
+ std::atomic<bool> busyPairing{false};
+ std::atomic<int> unpairCalls{0};
+ std::atomic<int> launchCalls{0};
+ std::string lastLaunch; // guarded by mutex_
+
+ std::string launchQuery() { std::lock_guard lock(mutex_); return lastLaunch; }
+
+private:
+ SOCKET listenOnLoopback(uint16_t& port) {
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ sockaddr_in address{};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = 0;
+ bind(s, reinterpret_cast<sockaddr*>(&address), sizeof(address));
+ listen(s, 8);
+ int length = sizeof(address);
+ getsockname(s, reinterpret_cast<sockaddr*>(&address), &length);
+ port = ntohs(address.sin_port);
+ return s;
+ }
+
+ void acceptLoop(SOCKET listener, bool tls) {
+ while (!stop_) {
+ SOCKET client = accept(listener, nullptr, nullptr);
+ if (client == INVALID_SOCKET) return;
+ std::thread([this, client, tls] { serve(client, tls); }).detach();
+ }
+ }
+
+ void serve(SOCKET client, bool tls) {
+ SSL* ssl = nullptr;
+ if (tls) {
+ ssl = SSL_new(ctx_);
+ SSL_set_fd(ssl, static_cast<int>(client));
+ if (SSL_accept(ssl) != 1) { SSL_free(ssl); closesocket(client); return; }
+ }
+ auto readBytes = [&](char* buffer, int size) { return ssl ? SSL_read(ssl, buffer, size) : recv(client, buffer, size, 0); };
+ auto writeBytes = [&](const std::string& data) {
+ size_t sent = 0;
+ while (sent < data.size()) {
+ const int n = ssl ? SSL_write(ssl, data.data() + sent, int(data.size() - sent)) : send(client, data.data() + sent, int(data.size() - sent), 0);
+ if (n <= 0) return;
+ sent += size_t(n);
+ }
+ };
+ std::string request;
+ char chunk[2048];
+ while (request.find("\r\n\r\n") == std::string::npos) {
+ const int n = readBytes(chunk, sizeof(chunk));
+ if (n <= 0) break;
+ request.append(chunk, size_t(n));
+ }
+ if (request.find("\r\n\r\n") != std::string::npos) {
+ const Query q = parseRequestLine(request);
+ std::string body = route(q, tls);
+ writeBytes(respond(q, tls, body));
+ }
+ if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); }
+ closesocket(client);
+ }
+
+ // The three framings a real host uses must all parse: content-length, chunked, close-delimited.
+ std::string respond(const Query& q, bool tls, const std::string& body) {
+ if (!tls && q.command == "serverinfo") {
+ std::string out = "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
+ const size_t half = body.size() / 2;
+ char size[16];
+ std::snprintf(size, sizeof(size), "%zx\r\n", half);
+ out += size + body.substr(0, half) + "\r\n";
+ std::snprintf(size, sizeof(size), "%zx\r\n", body.size() - half);
+ out += size + body.substr(half) + "\r\n0\r\n\r\n";
+ return out;
+ }
+ if (q.command == "applist") return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nConnection: close\r\n\r\n" + body;
+ return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nContent-Length: " + std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body;
+ }
+
+ static std::string ok(const std::string& inner) { return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"200\">" + inner + "</root>"; }
+ static std::string fail(int code, const std::string& message) {
+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"" + std::to_string(code) + "\" status_message=\"" + message + "\"></root>";
+ }
+
+ std::string route(const Query& q, bool tls) {
+ std::lock_guard lock(mutex_);
+ if (q.command == "serverinfo") {
+ std::string info = kServerInfoXml;
+ // Report the real ports and the real pairing state of this mock.
+ const auto replace = [&](const std::string& from, const std::string& to) { const auto at = info.find(from); if (at != std::string::npos) info.replace(at, from.size(), to); };
+ replace("<HttpsPort>48000</HttpsPort>", "<HttpsPort>" + std::to_string(httpsPort) + "</HttpsPort>");
+ replace("<currentgame>7</currentgame>", "<currentgame>" + std::to_string(currentGame.load()) + "</currentgame>");
+ replace("<PairStatus>1</PairStatus>", std::string("<PairStatus>") + (pairedClientDer_.empty() ? "0" : "1") + "</PairStatus>");
+ return info;
+ }
+ if (q.command == "applist") return tls ? kAppListXml : fail(401, "The client is not authorized");
+ if (q.command == "unpair") { ++unpairCalls; pairedClientDer_.clear(); stage_ = 0; return ok(""); }
+ if (q.command == "launch" || q.command == "resume") { ++launchCalls; lastLaunch = q.command; for (const auto& [k, v] : q.args) lastLaunch += "&" + k + "=" + v; return ok("<sessionUrl0>rtsp://127.0.0.1:48010</sessionUrl0><gamesession>1</gamesession>"); }
+ if (q.command == "cancel") return ok("<cancel>1</cancel>");
+ if (q.command == "appasset") return "\x89PNG-MOCK";
+ if (q.command == "pair") return pair(q, tls);
+ return fail(404, "unknown");
+ }
+
+ // The host side of the five stage pairing handshake.
+ std::string pair(const Query& q, bool tls) {
+ const bool sha256 = true; // appversion 7.x
+ const size_t hashLength = 32;
+ const auto get = [&](const char* name) { const auto it = q.args.find(name); return it == q.args.end() ? std::string() : it->second; };
+ if (!tls && get("phrase") == "getservercert") {
+ if (busyPairing) return ok("<paired>1</paired><plaincert></plaincert>");
+ mutex_.unlock(); // the PIN is typed by a human; do not hold the lock while waiting
+ for (int i = 0; i < 100 && !pinEntered_; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ mutex_.lock();
+ if (!pinEntered_) return fail(500, "pin timeout");
+ salt_ = *xml::fromHex(get("salt"));
+ clientCertPem_ = *xml::fromHex(get("clientcert"));
+ aesKey_ = crypto::digest(salt_ + pin_, sha256).substr(0, 16);
+ stage_ = 1;
+ return ok("<paired>1</paired><plaincert>" + hexOf(identity.certPem) + "</plaincert>");
+ }
+ if (!tls && !get("clientchallenge").empty() && stage_ == 1) {
+ const std::string challenge = crypto::aesEcbDecrypt(*xml::fromHex(get("clientchallenge")), aesKey_);
+ serverSecret_ = crypto::randomBytes(16);
+ serverChallenge_ = crypto::randomBytes(16);
+ const std::string hash = crypto::digest(challenge + crypto::certificateSignature(identity.certPem) + serverSecret_, sha256);
+ stage_ = 2;
+ return ok("<paired>1</paired><challengeresponse>" + hexOf(crypto::aesEcbEncrypt(hash + serverChallenge_, aesKey_)) + "</challengeresponse>");
+ }
+ if (!tls && !get("serverchallengeresp").empty() && stage_ == 2) {
+ clientHash_ = crypto::aesEcbDecrypt(*xml::fromHex(get("serverchallengeresp")), aesKey_).substr(0, hashLength);
+ stage_ = 3;
+ return ok("<paired>1</paired><pairingsecret>" + hexOf(serverSecret_ + crypto::sign(identity, serverSecret_)) + "</pairingsecret>");
+ }
+ if (!tls && !get("clientpairingsecret").empty() && stage_ == 3) {
+ const std::string blob = *xml::fromHex(get("clientpairingsecret"));
+ const std::string clientSecret = blob.substr(0, 16);
+ const bool signatureOk = crypto::verify(clientSecret, blob.substr(16), clientCertPem_);
+ const bool hashOk = crypto::digest(serverChallenge_ + crypto::certificateSignature(clientCertPem_) + clientSecret, sha256) == clientHash_;
+ if (!signatureOk || !hashOk) { stage_ = 0; return ok("<paired>0</paired>"); }
+ pairedClientDer_ = crypto::certificateDer(clientCertPem_);
+ stage_ = 4;
+ return ok("<paired>1</paired>");
+ }
+ if (tls && get("phrase") == "pairchallenge") return ok("<paired>1</paired>");
+ return fail(400, "unexpected pairing request");
+ }
+
+ std::string pin_;
+ std::atomic<bool> pinEntered_{false};
+ std::atomic<bool> stop_{false};
+ SOCKET httpListen_ = INVALID_SOCKET, httpsListen_ = INVALID_SOCKET;
+ SSL_CTX* ctx_ = nullptr;
+ std::thread httpThread_, httpsThread_;
+ std::mutex mutex_;
+ int stage_ = 0;
+ std::string salt_, aesKey_, clientCertPem_, pairedClientDer_, serverSecret_, serverChallenge_, clientHash_;
+};
+
+} // namespace veyra::moonlight::mock
diff --git a/tests/moonlight/MockHostServer.cpp b/tests/moonlight/MockHostServer.cpp
new file mode 100644
index 00000000..46944bd5
--- /dev/null
+++ b/tests/moonlight/MockHostServer.cpp
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// The mock Sunshine host as a stand-alone process, for driving the real UI in an end-to-end check
+// (scripts/moonlight/ui-demo.py). It prints "PORTS <http> <https>" and then serves until told to stop.
+// --pin-file <path> the PIN the user would type on the host is read from this file (and the file
+// deleted) whenever it appears
+// --stop-file <path> exits when this file appears
+// --game <id> the game reported as running (default 0)
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <string>
+
+#include "MockHost.h"
+
+using namespace veyra::moonlight::mock;
+
+int main(int argc, char** argv) {
+ std::string pinFile, stopFile;
+ int game = 0;
+ for (int i = 1; i + 1 < argc; ++i) {
+ if (!std::strcmp(argv[i], "--pin-file")) pinFile = argv[++i];
+ else if (!std::strcmp(argv[i], "--stop-file")) stopFile = argv[++i];
+ else if (!std::strcmp(argv[i], "--game")) game = std::atoi(argv[++i]);
+ }
+ MockHost host("");
+ host.currentGame = game;
+ std::printf("PORTS %u %u\n", unsigned(host.httpPort), unsigned(host.httpsPort));
+ std::fflush(stdout);
+ namespace fs = std::filesystem;
+ for (;;) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ std::error_code ec;
+ if (!stopFile.empty() && fs::exists(stopFile, ec)) break;
+ if (!pinFile.empty() && fs::exists(pinFile, ec)) {
+ std::string pin;
+ { std::ifstream in(pinFile); std::getline(in, pin); }
+ while (!pin.empty() && (pin.back() == '\r' || pin.back() == ' ')) pin.pop_back();
+ if (!pin.empty()) {
+ fs::remove(pinFile, ec);
+ host.setPin(pin);
+ std::printf("PIN accepted\n");
+ std::fflush(stdout);
+ }
+ }
+ }
+ return 0;
+}
diff --git a/tests/moonlight/ModelTests.cpp b/tests/moonlight/ModelTests.cpp
new file mode 100644
index 00000000..0010a5a0
--- /dev/null
+++ b/tests/moonlight/ModelTests.cpp
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// The PC streaming model (hosts, pairing, apps, settings, starting a stream) against the mock host, through
+// the same Qt interface the QML dialog uses. Needs no display (offscreen platform) and no real host.
+#include <QCoreApplication>
+#include <QElapsedTimer>
+#include <QGuiApplication>
+#include <QTemporaryDir>
+#include <QThread>
+#include <cstdio>
+#include <functional>
+
+#include "MockHost.h"
+#include "veyra/ui/MoonlightModel.h"
+
+using namespace veyra;
+using namespace veyra::moonlight::mock;
+using veyra::ui::MoonlightModel;
+
+namespace {
+
+int g_failures = 0, g_checks = 0;
+void check(bool ok, const char* what) {
+ ++g_checks;
+ if (!ok) { ++g_failures; std::printf("FAIL %s\n", what); }
+ else if (qEnvironmentVariableIsSet("VEYRA_TEST_VERBOSE")) std::printf("ok %s\n", what);
+ std::fflush(stdout);
+}
+
+void progress(const char* text) {
+ if (qEnvironmentVariableIsSet("VEYRA_TEST_VERBOSE")) { std::puts(text); std::fflush(stdout); }
+}
+
+bool waitFor(const std::function<bool()>& condition, int timeoutMs = 15000) {
+ QElapsedTimer timer;
+ timer.start();
+ while (!condition()) {
+ if (timer.elapsed() > timeoutMs) return false;
+ QCoreApplication::processEvents(QEventLoop::AllEvents, 20);
+ QThread::msleep(5);
+ }
+ return true;
+}
+
+bool idle(MoonlightModel& model) { return !model.state().value("busy").toBool(); }
+QString statusOf(MoonlightModel& model) { return model.state().value("status").toString(); }
+
+} // namespace
+
+int main(int argc, char** argv) {
+ qputenv("QT_QPA_PLATFORM", "offscreen");
+ QGuiApplication app(argc, argv);
+ QTemporaryDir data;
+ qputenv("VEYRA_MOONLIGHT_DATA", data.path().toLocal8Bit());
+ qputenv("VEYRA_MOONLIGHT_NO_DISCOVERY", "1");
+
+ MockHost host("");
+ const QString address = QStringLiteral("127.0.0.1:%1").arg(host.httpPort);
+ QString hostId;
+ {
+ MoonlightModel model;
+ std::optional<MoonlightModel::Launch> launched;
+ int startedSignals = 0;
+ QObject::connect(&model, &MoonlightModel::started, [&] { ++startedSignals; });
+ model.setLaunchHandler([&](MoonlightModel::Launch launch) { launched = std::move(launch); return true; });
+
+ model.load();
+ check(waitFor([&] { return idle(model); }), "load finishes");
+ check(model.hosts().isEmpty(), "no hosts at first");
+
+ // --- adding a host
+ model.addHost("not a host");
+ check(!statusOf(model).isEmpty() && model.hosts().isEmpty(), "an address with spaces is refused");
+ model.addHost(address);
+ check(waitFor([&] { return model.hosts().size() == 1; }), "a host appears after adding it by address");
+ const QVariantMap entry = model.hosts().value(0).toMap();
+ hostId = entry.value("id").toString();
+ check(entry.value("name").toString() == "DESKTOP-TEST" && entry.value("state").toString() == "unpaired", "it is listed by the name the host reports, unpaired");
+ check(model.state().value("selected").toString() == hostId, "and selected");
+ check(entry.value("saved").toBool(), "a manually added host is saved");
+
+ // --- pairing with the PIN the dialog shows
+ model.pair(hostId);
+ const QString pin = model.state().value("pin").toString();
+ check(model.state().value("pairing").toBool() && pin.size() == 4, "pairing shows a 4 digit PIN at once");
+ host.setPin(pin.toStdString());
+ check(waitFor([&] { return model.state().value("paired").toBool() && idle(model); }), "pairing with the right PIN succeeds");
+ check(model.state().value("pin").toString().isEmpty() && !model.state().value("pairing").toBool(), "the PIN is cleared afterwards");
+
+ // --- the app list arrives by itself after pairing
+ check(waitFor([&] { return model.apps().size() == 3 && idle(model); }), "the app list is read after pairing");
+ const QVariantList apps = model.apps();
+ check(apps.value(0).toMap().value("name").toString() == "Desktop" && apps.value(0).toMap().value("hdr").toBool(), "first app is the Desktop with HDR");
+ check(apps.value(1).toMap().value("name").toString() == QString::fromUtf8("Tom & Jerry <Deluxe> 中"), "entities in names are decoded");
+ check(model.state().value("runningApp").toInt() == 7, "the host's running game is reported");
+
+ // --- settings
+ check(model.set("fps", 120) && model.set("res", "4k") && model.set("bitrate", 100) && model.set("codec", 2), "valid settings are accepted");
+ check(!model.set("fps", 55) && !model.set("res", "8k") && !model.set("audio", 3) && !model.set("nonsense", 1), "invalid settings are refused");
+ const QVariantMap cfg = model.state().value("settings").toMap();
+ check(cfg.value("fps").toInt() == 120 && cfg.value("res").toString() == "4k" && cfg.value("bitrate").toInt() == 100, "settings are read back");
+
+ // --- starting: another game runs on the host (id 7, not the app chosen)
+ check(model.connectStream(881448767), "connectStream starts the job");
+ check(waitFor([&] { return idle(model); }), "the launch check finishes");
+ check(!launched && statusOf(model).contains(QString::fromUtf8("另一个游戏")), "another running game blocks a new launch with an explanation");
+
+ // --- HDR with a codec that cannot carry it
+ host.currentGame = 0;
+ model.set("hdr", true);
+ model.set("codec", 1); // H.264
+ model.connectStream(881448767);
+ check(waitFor([&] { return idle(model); }), "second launch check finishes");
+ check(!launched && statusOf(model).contains("HDR"), "HDR with H.264 is refused before anything is launched");
+
+ // --- a normal launch
+ model.set("codec", 2); // HEVC + HDR: the mock reports 10 bit HEVC
+ model.connectStream(881448767);
+ check(waitFor([&] { return launched.has_value(); }), "the launch handler is called");
+ if (launched) {
+ const auto& d = launched->desc;
+ check(d.appId == 881448767 && !d.resume && d.options.width == 3840 && d.options.height == 2160 && d.options.fps == 120, "4K120 goes to the session");
+ check(d.options.bitrateKbps == 100000 && d.options.hdr && d.options.codec == moonlight::CodecChoice::Hevc, "bitrate, HDR and codec go to the session");
+ check(d.identity.valid() && !d.serverCertPem.empty() && d.host.paired && d.host.uniqueId == "ABCD1234EF567890", "credentials, pinned certificate and a fresh serverinfo go along");
+ check(launched->label.contains("DESKTOP-TEST") && launched->label.contains("Desktop"), "the label names the host and the app");
+ }
+ check(startedSignals == 1, "started() is emitted once");
+
+ // --- resuming the running game
+ launched.reset();
+ host.currentGame = 881448767;
+ check(waitFor([&] { return idle(model); }), "idle again");
+ model.connectStream(881448767);
+ check(waitFor([&] { return launched.has_value(); }), "resume launches");
+ check(launched && launched->desc.resume, "launching the app that already runs is a resume");
+ }
+
+ progress("block 1 destroyed");
+ // --- everything survives a restart
+ {
+ MoonlightModel model;
+ progress("second model constructed");
+ model.load();
+ progress("second model loaded");
+ check(waitFor([&] { return idle(model); }), "second model loads");
+ check(model.hosts().size() == 1, "the saved host is back");
+ const QVariantMap entry = model.hosts().value(0).toMap();
+ check(entry.value("paired").toBool() && entry.value("id").toString() == hostId, "still paired");
+ check(waitFor([&] { return model.hosts().value(0).toMap().value("state").toString() != "checking" && idle(model); }), "the status refresh finishes");
+ check(model.state().value("settings").toMap().value("fps").toInt() == 120, "settings were saved per host");
+ check(model.state().value("lastLabel").toString().contains("Desktop"), "the last stream is remembered for resuming");
+ check(waitFor([&] { return model.apps().size() == 3; }), "apps reload from the saved pairing (pinned certificate works)");
+
+ // --- a host that no longer knows us
+ host.forgetPairing();
+ model.refresh();
+ check(waitFor([&] { return idle(model) && model.hosts().value(0).toMap().value("state").toString() == "unpaired"; }), "a host that forgot us shows as unpaired");
+
+ // --- forgetting
+ model.forget(hostId);
+ check(model.hosts().isEmpty(), "forgetting removes the host at once");
+ check(waitFor([&] { return idle(model); }), "the unpair request finishes");
+ }
+ {
+ MoonlightModel model;
+ model.load();
+ check(waitFor([&] { return idle(model); }) && model.hosts().isEmpty(), "a forgotten host stays forgotten");
+ }
+
+ std::printf("moonlight model tests: %d checks, %d failures\n", g_checks, g_failures);
+ return g_failures == 0 ? 0 : 1;
+}
diff --git a/tests/moonlight/ProtocolTests.cpp b/tests/moonlight/ProtocolTests.cpp
index 0747c212..695c4a8f 100644
--- a/tests/moonlight/ProtocolTests.cpp
+++ b/tests/moonlight/ProtocolTests.cpp
@@ -29,6 +29,7 @@
#include "veyra/moonlight/Client.h"
#include "veyra/moonlight/Crypto.h"
+#include "veyra/moonlight/Discovery.h"
#include "veyra/moonlight/Http.h"
#include "veyra/moonlight/IdentityStore.h"
#include "veyra/moonlight/Pairing.h"
@@ -36,8 +37,10 @@
#include "veyra/moonlight/InputMap.h"
#include "veyra/moonlight/InputRouter.h"
#include "veyra/moonlight/Xml.h"
+#include "MockHost.h"
using namespace veyra::moonlight;
+using namespace veyra::moonlight::mock;
namespace {
@@ -49,272 +52,6 @@ void check(bool ok, const char* what) {
if (!ok) { ++g_failures; std::printf("FAIL %s\n", what); }
}
-// ---------------------------------------------------------------- fixtures
-
-const char* kServerInfoXml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
- "<root status_code=\"200\"><hostname>DESKTOP-TEST</hostname><appversion>7.1.431.-1</appversion>"
- "<GfeVersion>3.23.0.74</GfeVersion><uniqueid>ABCD1234EF567890</uniqueid><HttpsPort>48000</HttpsPort>"
- "<ExternalPort>47999</ExternalPort><MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC><mac>AA:BB:CC:DD:EE:FF</mac>"
- "<LocalIP>192.168.1.20</LocalIP><ServerCodecModeSupport>197377</ServerCodecModeSupport>"
- "<SupportedDisplayMode><DisplayMode><Width>3840</Width><Height>2160</Height><RefreshRate>60</RefreshRate></DisplayMode>"
- "<DisplayMode><Width>1920</Width><Height>1080</Height><RefreshRate>60</RefreshRate></DisplayMode></SupportedDisplayMode>"
- "<PairStatus>1</PairStatus><currentgame>7</currentgame><state>SUNSHINE_SERVER_BUSY</state></root>";
-
-const char* kAppListXml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
- "<root status_code=\"200\">"
- "<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>"
- "<App><IsHdrSupported>0</IsHdrSupported><AppTitle>Tom &amp; Jerry &lt;Deluxe&gt; &#x4E2D;</AppTitle><ID>12</ID></App>"
- "<App><AppTitle/><ID>13</ID></App>"
- "</root>";
-
-// ---------------------------------------------------------------- mock host
-
-std::string hexOf(const std::string& bytes) { return xml::toHex(bytes); }
-
-struct Query {
- std::string command;
- std::map<std::string, std::string> args;
-};
-
-Query parseRequestLine(const std::string& request) {
- Query q;
- const auto space1 = request.find(' ');
- const auto space2 = request.find(' ', space1 + 1);
- std::string target = request.substr(space1 + 1, space2 - space1 - 1);
- const auto mark = target.find('?');
- q.command = target.substr(1, mark == std::string::npos ? std::string::npos : mark - 1);
- if (mark != std::string::npos) {
- size_t pos = mark + 1;
- while (pos < target.size()) {
- const auto amp = target.find('&', pos);
- const std::string pair = target.substr(pos, amp == std::string::npos ? std::string::npos : amp - pos);
- const auto eq = pair.find('=');
- q.args[pair.substr(0, eq)] = eq == std::string::npos ? "" : pair.substr(eq + 1);
- pos = amp == std::string::npos ? target.size() : amp + 1;
- }
- }
- return q;
-}
-
-class MockHost {
-public:
- explicit MockHost(const std::string& pin) : pin_(pin) {
- identity = createIdentity();
- WSADATA data;
- WSAStartup(MAKEWORD(2, 2), &data);
- httpListen_ = listenOnLoopback(httpPort);
- httpsListen_ = listenOnLoopback(httpsPort);
- ctx_ = SSL_CTX_new(TLS_server_method());
- BIO* certBio = BIO_new_mem_buf(identity.certPem.data(), int(identity.certPem.size()));
- BIO* keyBio = BIO_new_mem_buf(identity.keyPem.data(), int(identity.keyPem.size()));
- X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
- EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);
- SSL_CTX_use_certificate(ctx_, cert);
- SSL_CTX_use_PrivateKey(ctx_, key);
- X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);
- SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
- // Only the client certificate that completed pairing may use HTTPS.
- SSL_CTX_set_cert_verify_callback(ctx_, [](X509_STORE_CTX* store, void* arg) -> int {
- auto* self = static_cast<MockHost*>(arg);
- X509* peer = X509_STORE_CTX_get0_cert(store);
- unsigned char* der = nullptr;
- const int length = i2d_X509(peer, &der);
- std::string presented(reinterpret_cast<char*>(der), size_t(length));
- OPENSSL_free(der);
- std::lock_guard lock(self->mutex_);
- return !self->pairedClientDer_.empty() && presented == self->pairedClientDer_ ? 1 : 0;
- }, this);
- httpThread_ = std::thread([this] { acceptLoop(httpListen_, false); });
- httpsThread_ = std::thread([this] { acceptLoop(httpsListen_, true); });
- }
-
- ~MockHost() {
- stop_ = true;
- closesocket(httpListen_);
- closesocket(httpsListen_);
- if (httpThread_.joinable()) httpThread_.join();
- if (httpsThread_.joinable()) httpsThread_.join();
- SSL_CTX_free(ctx_);
- }
-
- void enterPin() { pinEntered_ = true; }
- void forgetPairing() {
- std::lock_guard lock(mutex_);
- pairedClientDer_.clear();
- }
- void presentDifferentCertificate() {
- // Swap to a new identity the client has never pinned.
- Identity other = createIdentity();
- BIO* certBio = BIO_new_mem_buf(other.certPem.data(), int(other.certPem.size()));
- BIO* keyBio = BIO_new_mem_buf(other.keyPem.data(), int(other.keyPem.size()));
- X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);
- EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);
- SSL_CTX_use_certificate(ctx_, cert);
- SSL_CTX_use_PrivateKey(ctx_, key);
- X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);
- }
-
- Identity identity;
- uint16_t httpPort = 0, httpsPort = 0;
- std::atomic<bool> busyPairing{false};
- std::atomic<int> unpairCalls{0};
- std::atomic<int> launchCalls{0};
- std::string lastLaunch; // guarded by mutex_
-
- std::string launchQuery() { std::lock_guard lock(mutex_); return lastLaunch; }
-
-private:
- SOCKET listenOnLoopback(uint16_t& port) {
- SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- sockaddr_in address{};
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- address.sin_port = 0;
- bind(s, reinterpret_cast<sockaddr*>(&address), sizeof(address));
- listen(s, 8);
- int length = sizeof(address);
- getsockname(s, reinterpret_cast<sockaddr*>(&address), &length);
- port = ntohs(address.sin_port);
- return s;
- }
-
- void acceptLoop(SOCKET listener, bool tls) {
- while (!stop_) {
- SOCKET client = accept(listener, nullptr, nullptr);
- if (client == INVALID_SOCKET) return;
- std::thread([this, client, tls] { serve(client, tls); }).detach();
- }
- }
-
- void serve(SOCKET client, bool tls) {
- SSL* ssl = nullptr;
- if (tls) {
- ssl = SSL_new(ctx_);
- SSL_set_fd(ssl, static_cast<int>(client));
- if (SSL_accept(ssl) != 1) { SSL_free(ssl); closesocket(client); return; }
- }
- auto readBytes = [&](char* buffer, int size) { return ssl ? SSL_read(ssl, buffer, size) : recv(client, buffer, size, 0); };
- auto writeBytes = [&](const std::string& data) {
- size_t sent = 0;
- while (sent < data.size()) {
- const int n = ssl ? SSL_write(ssl, data.data() + sent, int(data.size() - sent)) : send(client, data.data() + sent, int(data.size() - sent), 0);
- if (n <= 0) return;
- sent += size_t(n);
- }
- };
- std::string request;
- char chunk[2048];
- while (request.find("\r\n\r\n") == std::string::npos) {
- const int n = readBytes(chunk, sizeof(chunk));
- if (n <= 0) break;
- request.append(chunk, size_t(n));
- }
- if (request.find("\r\n\r\n") != std::string::npos) {
- const Query q = parseRequestLine(request);
- std::string body = route(q, tls);
- writeBytes(respond(q, tls, body));
- }
- if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); }
- closesocket(client);
- }
-
- // The three framings a real host uses must all parse: content-length, chunked, close-delimited.
- std::string respond(const Query& q, bool tls, const std::string& body) {
- if (!tls && q.command == "serverinfo") {
- std::string out = "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
- const size_t half = body.size() / 2;
- char size[16];
- std::snprintf(size, sizeof(size), "%zx\r\n", half);
- out += size + body.substr(0, half) + "\r\n";
- std::snprintf(size, sizeof(size), "%zx\r\n", body.size() - half);
- out += size + body.substr(half) + "\r\n0\r\n\r\n";
- return out;
- }
- if (q.command == "applist") return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nConnection: close\r\n\r\n" + body;
- return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nContent-Length: " + std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body;
- }
-
- static std::string ok(const std::string& inner) { return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"200\">" + inner + "</root>"; }
- static std::string fail(int code, const std::string& message) {
- return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"" + std::to_string(code) + "\" status_message=\"" + message + "\"></root>";
- }
-
- std::string route(const Query& q, bool tls) {
- std::lock_guard lock(mutex_);
- if (q.command == "serverinfo") {
- std::string info = kServerInfoXml;
- // Report the real ports and the real pairing state of this mock.
- const auto replace = [&](const std::string& from, const std::string& to) { const auto at = info.find(from); if (at != std::string::npos) info.replace(at, from.size(), to); };
- replace("<HttpsPort>48000</HttpsPort>", "<HttpsPort>" + std::to_string(httpsPort) + "</HttpsPort>");
- replace("<PairStatus>1</PairStatus>", std::string("<PairStatus>") + (pairedClientDer_.empty() ? "0" : "1") + "</PairStatus>");
- return info;
- }
- if (q.command == "applist") return tls ? kAppListXml : fail(401, "The client is not authorized");
- if (q.command == "unpair") { ++unpairCalls; pairedClientDer_.clear(); stage_ = 0; return ok(""); }
- if (q.command == "launch" || q.command == "resume") { ++launchCalls; lastLaunch = q.command; for (const auto& [k, v] : q.args) lastLaunch += "&" + k + "=" + v; return ok("<sessionUrl0>rtsp://127.0.0.1:48010</sessionUrl0><gamesession>1</gamesession>"); }
- if (q.command == "cancel") return ok("<cancel>1</cancel>");
- if (q.command == "appasset") return "\x89PNG-MOCK";
- if (q.command == "pair") return pair(q, tls);
- return fail(404, "unknown");
- }
-
- // The host side of the five stage pairing handshake.
- std::string pair(const Query& q, bool tls) {
- const bool sha256 = true; // appversion 7.x
- const size_t hashLength = 32;
- const auto get = [&](const char* name) { const auto it = q.args.find(name); return it == q.args.end() ? std::string() : it->second; };
- if (!tls && get("phrase") == "getservercert") {
- if (busyPairing) return ok("<paired>1</paired><plaincert></plaincert>");
- mutex_.unlock(); // the PIN is typed by a human; do not hold the lock while waiting
- for (int i = 0; i < 100 && !pinEntered_; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(50));
- mutex_.lock();
- if (!pinEntered_) return fail(500, "pin timeout");
- salt_ = *xml::fromHex(get("salt"));
- clientCertPem_ = *xml::fromHex(get("clientcert"));
- aesKey_ = crypto::digest(salt_ + pin_, sha256).substr(0, 16);
- stage_ = 1;
- return ok("<paired>1</paired><plaincert>" + hexOf(identity.certPem) + "</plaincert>");
- }
- if (!tls && !get("clientchallenge").empty() && stage_ == 1) {
- const std::string challenge = crypto::aesEcbDecrypt(*xml::fromHex(get("clientchallenge")), aesKey_);
- serverSecret_ = crypto::randomBytes(16);
- serverChallenge_ = crypto::randomBytes(16);
- const std::string hash = crypto::digest(challenge + crypto::certificateSignature(identity.certPem) + serverSecret_, sha256);
- stage_ = 2;
- return ok("<paired>1</paired><challengeresponse>" + hexOf(crypto::aesEcbEncrypt(hash + serverChallenge_, aesKey_)) + "</challengeresponse>");
- }
- if (!tls && !get("serverchallengeresp").empty() && stage_ == 2) {
- clientHash_ = crypto::aesEcbDecrypt(*xml::fromHex(get("serverchallengeresp")), aesKey_).substr(0, hashLength);
- stage_ = 3;
- return ok("<paired>1</paired><pairingsecret>" + hexOf(serverSecret_ + crypto::sign(identity, serverSecret_)) + "</pairingsecret>");
- }
- if (!tls && !get("clientpairingsecret").empty() && stage_ == 3) {
- const std::string blob = *xml::fromHex(get("clientpairingsecret"));
- const std::string clientSecret = blob.substr(0, 16);
- const bool signatureOk = crypto::verify(clientSecret, blob.substr(16), clientCertPem_);
- const bool hashOk = crypto::digest(serverChallenge_ + crypto::certificateSignature(clientCertPem_) + clientSecret, sha256) == clientHash_;
- if (!signatureOk || !hashOk) { stage_ = 0; return ok("<paired>0</paired>"); }
- pairedClientDer_ = crypto::certificateDer(clientCertPem_);
- stage_ = 4;
- return ok("<paired>1</paired>");
- }
- if (tls && get("phrase") == "pairchallenge") return ok("<paired>1</paired>");
- return fail(400, "unexpected pairing request");
- }
-
- std::string pin_;
- std::atomic<bool> pinEntered_{false};
- std::atomic<bool> stop_{false};
- SOCKET httpListen_ = INVALID_SOCKET, httpsListen_ = INVALID_SOCKET;
- SSL_CTX* ctx_ = nullptr;
- std::thread httpThread_, httpsThread_;
- std::mutex mutex_;
- int stage_ = 0;
- std::string salt_, aesKey_, clientCertPem_, pairedClientDer_, serverSecret_, serverChallenge_, clientHash_;
-};
-
// ---------------------------------------------------------------- tests
void xmlTests() {
@@ -612,6 +349,26 @@ void routerTests() {
check(other.keys.back().vk == 'Z' && hotkeys.takeReserved() == Reserved::None, "after a reset Z is an ordinary key");
}
+void discoveryTests() {
+ // There is no Sunshine host here, so this only proves that the DNS-SD browse starts and stops
+ // cleanly (also repeatedly, and with a late callback after stop), not that a host is found.
+ std::atomic<int> found{0};
+ Discovery discovery;
+ const bool started = discovery.start([&](const DiscoveredHost&) { ++found; });
+ check(started == discovery.running(), "running() follows start()");
+ if (started) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(800));
+ discovery.stop();
+ check(!discovery.running(), "stop() ends the browse");
+ check(discovery.start([&](const DiscoveredHost&) { ++found; }), "a second start works");
+ discovery.stop();
+ discovery.stop();
+ check(true, "stopping twice is harmless");
+ } else {
+ std::printf("note: DNS-SD browse is not available on this machine\n");
+ }
+}
+
void inputTests() {
using veyra::remoteplay::ControllerState;
{
@@ -669,6 +426,7 @@ int main() {
streamConfigTests();
inputTests();
routerTests();
+ discoveryTests();
protocolTests();
std::printf("moonlight protocol tests: %d checks, %d failures\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;