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): session source and engine integration (S2a)
Veyra Goal Agent3c5045bb8bfc
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 00a35c33..290c2e57 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -61,6 +61,12 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")include(VeyraWarnings)include(VeyraShaders)+# NVIDIA's static NGX core shim (nvsdk_ngx_s*.lib) is built against the+# static CRT (MT/MTd); match it for the diagnostic tools that link it.+set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")++# Moonlight targets come after the runtime setting: they link into the same+# executables as the rest of the engine, so they must use the static CRT too.if(VEYRA_ENABLE_MOONLIGHT)set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")include(VeyraMoonlight)@@ -72,10 +78,6 @@ if(VEYRA_ENABLE_MOONLIGHT)veyra_apply_warnings(veyra_moonlight_protocol_tests)endif()-# NVIDIA's static NGX core shim (nvsdk_ngx_s*.lib) is built against the-# static CRT (MT/MTd); match it for the diagnostic tools that link it.-set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")-# ---------------------------------------------------------------------------# Targets grow phase by phase; only what actually compiles is declared.# ---------------------------------------------------------------------------@@ -547,6 +549,13 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_sources PUBLIC veyra_remoteplay_chiaki)endif()+ if(VEYRA_ENABLE_MOONLIGHT)+ find_package(Opus CONFIG REQUIRED)+ target_compile_definitions(veyra_sources PUBLIC VEYRA_ENABLE_MOONLIGHT=1)+ target_sources(veyra_sources PRIVATE src/source/MoonlightSessionSource.cpp)+ target_link_libraries(veyra_sources PUBLIC veyra_moonlight_protocol veyra_moonlight_common_c PRIVATE Opus::opus)+ endif()+add_executable(veyra_source_teststests/integration/MediaFileSourceTests.cpp)diff --git a/docs/MOONLIGHT_EXECUTION_2026-10-01.md b/docs/MOONLIGHT_EXECUTION_2026-10-01.mdindex 5c75f6eb..77fa74e1 100644--- a/docs/MOONLIGHT_EXECUTION_2026-10-01.md+++ b/docs/MOONLIGHT_EXECUTION_2026-10-01.md@@ -12,7 +12,7 @@|---|---|---|| S0 | 依赖固定(`scripts/moonlight/dependency-lock.json` + 校验脚本)、CMake 开关、许可记录 | 完成 || S1 | 协议层(Qt 无关):XML、加密、HTTP(S)、主机请求、配对、身份存储 | 完成,离线测试 69 项通过 |-| S2 | 会话来源:`LiStartConnection`、视频解码、音频、遥测、引擎接入 | 未开始 |+| S2 | 会话来源:`LiStartConnection`、视频解码、音频、遥测、引擎接入 | 代码完成(S2a),只做了编译与离线检查,未连过任何主机 || S3 | 输入:手柄、键鼠捕获、保留键 | 未开始 || S4 | 前端:首页卡片、PC 串流页、配对对话框、设置、串流中 UI | 未开始 || S5 | 质量:HDR、AV1、丢包与重连、稳定性 | 未开始 |@@ -41,6 +41,16 @@**发现的测试自身问题**:Windows 上回环口被拒绝的连接有时要约 2 秒才报错,可能与 2 秒超时撞车而报成 Timeout;相应测试已同时接受 Connect 与 Timeout。+## S2a 记录(会话来源与引擎接入)++- `MoonlightSessionSource`(`IFrameSource`):`connect()` 先 launch/resume,再 `LiStartConnection`,失败由库自行清理;拉取式渲染(`LiWaitForNextVideoFrame` / `LiCompleteVideoFrame`)由一个解码线程处理,复用采集卡的 `CaptureCompressedDecoder`(D3D12VA 硬解,失败回落软解 NV12);丢帧放在解码之后,被跳过的帧记到下一帧的 Drop 标志,与 PS5 来源同一约定。+- Opus 多声道经 `CaptureAudioSession`,增益与音画同步沿用采集卡的设置。+- 引擎:`openMoonlight()`、`snapshot()` 带 `moonlightActive` 与 `MoonlightStats`;`isStream`(采集卡、PS5、Moonlight 共用的"实时来源"判断)替换了原来散落的 `isCapture || isRemote` 分支,PS5 与采集路径行为不变。+- 码率与编码选择(`StreamConfig.h`,纯函数,有测试):默认码率表取自 moonlight-qt,1080p60=20 Mbps、4K60=80 Mbps;HDR 只提供 10 位格式;AV1 只在已知有硬解时自动提供。+- 构建陷阱(已处理):① Moonlight 目标必须放在 `CMAKE_MSVC_RUNTIME_LIBRARY`(静态 CRT)设置之后,否则与 Qt 目标链接时 `msvcprt`/`libcpmt` 重复定义;② 带 Moonlight 的 `veyra_qml_ui` 链接行超过响应文件阈值,`link.exe` 按 ANSI 读响应文件,`E:\项目` 下的 Qt 库路径打不开。本机构建用 `C:eyra-deps\qt-veyra`(指向 Qt 的目录联接)作前缀;这是本机环境,不进仓库。+- 验证:`veyra_moonlight_protocol_tests` 87 项通过;整个 `veyra_qml_ui` 链接成功;`veyra_qml_data_tests`、`veyra_qml_easing_tests`、`veyra_ui_contract_tests`、`veyra_effect_chain_tests`、`veyra_repair_contract_tests`、`veyra_preset_library_tests` 通过。+- **未验证**:任何真实串流(连接、解码、音频、HDR、丢包恢复);解码流水线还没有离线单测;`connect()` 会阻塞引擎线程直到启动完成,首帧最多等 20 秒;软解回落只出 8 位,HDR 需要硬解;手柄震动与输入是空实现(S3);断线重连未做(S5)。+## 下一步-S2:`MoonlightSessionSource`(拉取模式 `LiWaitForNextVideoFrame`、每帧立即解码、丢帧放在解码后且不标不连续)、Opus 多声道、遥测与延迟分解;先做离线可测的部分(解码单元拼接、HDR 元数据、时间戳换算)。+S3 输入(手柄、键鼠、保留键)与 S4 前端(桥接接口、主机与应用列表、配对对话框、串流页与设置)。diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 4f5e1726..4f33ca7d 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -13,9 +13,12 @@#include "veyra/engine/PreviewView.h"#include "veyra/sink/CaptureAudioSession.h"#include "veyra/remoteplay/SessionInbox.h"+#ifdef VEYRA_ENABLE_MOONLIGHT+#include "veyra/source/MoonlightSessionSource.h"+#endif#include "veyra/media/AudioTrack.h"#include "veyra/sink/VideoEncoder.h"-namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; }+namespace veyra::source { struct RemotePlayConnectDesc; class RemotePlaySessionSource; struct MoonlightConnectDesc; class MoonlightSessionSource; }namespace veyra::remoteplay { struct ControllerState;struct ControllerFeedback; }namespace veyra::sink { struct RgbaImage; }namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }@@ -110,6 +113,9 @@ struct PlayerSnapshot {bool remoteRecovering=false;unsigned remoteReconnectAttempts=0;std::wstring remoteRecoveryMessage;remoteplay::SessionInbox::Snapshot remoteStream;double remoteReceivedFps=0,remoteDecodedFps=0;bool remoteRatesReady=false;uint64_t remoteReceived=0,remoteDecoded=0,remoteIngressDropped=0;+#ifdef VEYRA_ENABLE_MOONLIGHT+ bool moonlightActive=false;source::MoonlightStats moonlight;+#endif};class EngineController {public:@@ -124,6 +130,9 @@ public:remoteplay::ControllerFeedback remotePlayFeedback();void remotePlayController(const remoteplay::ControllerState&);void remotePlayLoginPin(std::string);+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ void openMoonlight(HWND, source::MoonlightConnectDesc, PlayerOptions);#endifvoid stop();void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}@@ -137,7 +146,7 @@ public:void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);PlayerSnapshot snapshot()const;private:- void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={});+ void run(HWND,std::wstring,PlayerOptions,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest={},std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest={});void runLargeImage(HWND,const sink::RgbaImage&,PlayerOptions,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&);void post(std::function<void()>);void dispatch();@@ -148,6 +157,7 @@ private:uint64_t presentationRevision_=1;std::shared_ptr<FrameFlowWindow> activeFlow_;std::shared_ptr<source::RemotePlaySessionSource> activeRemote_;+ std::shared_ptr<source::MoonlightSessionSource> activeMoonlight_;PreviewView previewView_;std::wstring savePath_;std::thread worker_;diff --git a/include/veyra/moonlight/StreamConfig.h b/include/veyra/moonlight/StreamConfig.hnew file mode 100644index 00000000..76338bb9--- /dev/null+++ b/include/veyra/moonlight/StreamConfig.h@@ -0,0 +1,71 @@+// SPDX-License-Identifier: GPL-3.0-only+// Pure decisions about a stream: the default bitrate and which video formats to+// offer the host. Kept free of the C library so they can be tested offline.+// The bitrate table is moonlight-qt's (StreamingPreferences::getDefaultBitrate).+#pragma once+#include <algorithm>+#include <cmath>++#include "veyra/moonlight/Types.h"++namespace veyra::moonlight {++// VIDEO_FORMAT_* bits of moonlight-common-c (the session source static_asserts+// that these still match Limelight.h).+constexpr int kFormatH264 = 0x0001;+constexpr int kFormatH265 = 0x0100;+constexpr int kFormatH265Main10 = 0x0200;+constexpr int kFormatAv1Main8 = 0x1000;+constexpr int kFormatAv1Main10 = 0x2000;+constexpr int kFormatMask10Bit = kFormatH265Main10 | kFormatAv1Main10;++enum class CodecChoice { Auto, H264, Hevc, Av1 };++// Default video bitrate in kbit/s. The resolution factor is interpolated between+// fixed points (Shield's long standing defaults); above 60 fps the frame rate+// factor grows with the square root, not linearly.+inline int defaultBitrateKbps(int width, int height, int fps, bool yuv444 = false) {+ const float frameRateFactor = (fps <= 60 ? float(fps) : std::sqrt(float(fps) / 60.f) * 60.f) / 30.f;+ struct Point { int pixels; int factor; };+ static constexpr Point table[] = {+ {640 * 360, 1}, {854 * 480, 2}, {1280 * 720, 5}, {1920 * 1080, 10}, {2560 * 1440, 20}, {3840 * 2160, 40},+ };+ constexpr int count = int(sizeof(table) / sizeof(table[0]));+ const int pixels = width * height;+ float resolutionFactor = float(table[count - 1].factor);+ for (int i = 0; i < count; ++i) {+ if (pixels == table[i].pixels) { resolutionFactor = float(table[i].factor); break; }+ if (pixels < table[i].pixels) {+ resolutionFactor = i == 0 ? float(table[0].factor)+ : float(pixels - table[i - 1].pixels) / float(table[i].pixels - table[i - 1].pixels) * float(table[i].factor - table[i - 1].factor) + float(table[i - 1].factor);+ break;+ }+ }+ if (yuv444) resolutionFactor *= 2;+ return int(std::lround(resolutionFactor * frameRateFactor)) * 1000;+}++// The VIDEO_FORMAT_* mask to offer: what the user asked for, limited to what the+// host reports it can encode (`serverCodecModeSupport`, SCM_* bits). H.264 is+// always available. AV1 is only offered automatically when the caller knows it can+// decode it in hardware. 0 means the host cannot do what was asked.+inline int chooseVideoFormats(CodecChoice choice, bool hdr, int serverCodecModeSupport, bool av1HardwareDecode) {+ const bool hevc = (serverCodecModeSupport & kServerHevc) != 0;+ const bool hevc10 = (serverCodecModeSupport & kServerHevcMain10) != 0;+ const bool av1 = (serverCodecModeSupport & kServerAv1Main8) != 0;+ const bool av110 = (serverCodecModeSupport & kServerAv1Main10) != 0;+ int mask = 0;+ const auto add = [&](bool allowed, int bit) { if (allowed) mask |= bit; };+ if (hdr) {+ // HDR needs a 10-bit format: H.264 cannot carry it here.+ if (choice == CodecChoice::Auto || choice == CodecChoice::Hevc) add(hevc10, kFormatH265Main10);+ if (choice == CodecChoice::Av1 || (choice == CodecChoice::Auto && av1HardwareDecode)) add(av110, kFormatAv1Main10);+ } else {+ if (choice == CodecChoice::Auto || choice == CodecChoice::H264) mask |= kFormatH264;+ if (choice == CodecChoice::Auto || choice == CodecChoice::Hevc) add(hevc, kFormatH265);+ if (choice == CodecChoice::Av1 || (choice == CodecChoice::Auto && av1HardwareDecode)) add(av1, kFormatAv1Main8);+ }+ return mask;+}++} // namespace veyra::moonlightdiff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.hindex 264e0425..c741ca46 100644--- a/include/veyra/pipeline/FramePacket.h+++ b/include/veyra/pipeline/FramePacket.h@@ -44,6 +44,7 @@ enum class SourceKind : uint8_t {Image, // WIC single imageTestPattern, // synthetic harness inputScreenCapture,+ Moonlight, // Sunshine / GameStream host stream (moonlight-common-c transport)};inline const char* sourceKindName(SourceKind k) {@@ -54,6 +55,7 @@ inline const char* sourceKindName(SourceKind k) {case SourceKind::Image: return "Image";case SourceKind::TestPattern: return "TestPattern";case SourceKind::ScreenCapture: return "ScreenCapture";+ case SourceKind::Moonlight: return "Moonlight";default: return "Unknown";}}diff --git a/include/veyra/source/MoonlightSessionSource.h b/include/veyra/source/MoonlightSessionSource.hnew file mode 100644index 00000000..38767d5e--- /dev/null+++ b/include/veyra/source/MoonlightSessionSource.h@@ -0,0 +1,140 @@+// SPDX-License-Identifier: GPL-3.0-only+#pragma once++// MoonlightSessionSource: one streaming session from a Sunshine / GameStream+// host, presented to the engine through the same source contract as capture+// cards and PS5 Remote Play. moonlight-common-c owns the network protocol+// (RTSP, RTP, FEC, ENet control); this class launches the app on the host,+// decodes the video with the shared hardware decoder path and plays the audio.+// The effect chain (NR / SR / frame generation / colour) is not part of it.+//+// moonlight-common-c keeps process-global state, so only one session can exist+// at a time; connect() on a second instance fails while one is active.+#include <atomic>+#include <condition_variable>+#include <cstdint>+#include <deque>+#include <memory>+#include <mutex>+#include <optional>+#include <string>+#include <thread>++#include "veyra/moonlight/Client.h"+#include "veyra/moonlight/StreamConfig.h"+#include "veyra/sink/CaptureAudioSession.h"+#include "veyra/source/IFrameSource.h"++struct AVFrame;+struct ID3D12Device;+struct ID3D12CommandQueue;++namespace veyra::source {++struct MoonlightStreamOptions {+ int width = 1920, height = 1080, fps = 60;+ int bitrateKbps = 0; // 0: the default for the resolution and frame rate+ moonlight::CodecChoice codec = moonlight::CodecChoice::Auto;+ bool hdr = false; // offer only 10-bit formats+ int audioChannels = 2; // 2, 6 or 8+ bool sops = false; // let the host change its own resolution+ bool localAudio = false; // keep playing audio on the host as well+ int displayRefreshHz = 0; // told to the host when known+ int gamepadMask = 0; // bit per connected controller+ bool av1HardwareDecode = false; // lets "automatic" offer AV1+};++struct MoonlightConnectDesc {+ moonlight::Identity identity; // wiped as soon as the app has been launched+ moonlight::HostAddress address;+ uint16_t httpsPort = moonlight::kDefaultHttpsPort;+ std::string serverCertPem; // pinned at pairing+ moonlight::ServerInfo host; // a fresh serverinfo answer+ int appId = 0;+ bool resume = false; // the app already runs on the host+ MoonlightStreamOptions options;+ // Set by the engine; shared ownership keeps the adapter and queue alive until+ // the decoder owner has stopped, including after a failed connect.+ std::shared_ptr<ID3D12Device> decodeDevice;+ std::shared_ptr<ID3D12CommandQueue> decodeQueue;+};++struct MoonlightStats {+ enum class State : uint8_t { Idle, Launching, Connecting, Streaming, Ended, Failed };+ State state = State::Idle;+ std::wstring message; // what to tell the user when Ended or Failed+ int errorCode = 0; // moonlight-common-c code, 0 = none+ uint32_t width = 0, height = 0;+ double fps = 0; // requested+ std::string codec; // "H.264", "HEVC", "HEVC 10-bit", "AV1"...+ bool hdr = false;+ bool hardwareDecode = false;+ bool encrypted = false;+ uint64_t units = 0, decoded = 0, dropped = 0, decodeErrors = 0, idrRequests = 0;+ double receivedFps = 0, decodedFps = 0;+ double hostLatencyMs = 0; // average host capture+encode, reported by Sunshine+ double receiveMs = 0; // first packet to complete frame+ double queueMs = 0; // complete frame to decoder start+ double decodeMs = 0;+ double rttMs = 0, rttVarianceMs = 0;+ uint32_t videoPackets = 0, fecPackets = 0, fecRecovered = 0, fecFailed = 0, outOfSequence = 0;+};++class MoonlightSessionSource final : public IFrameSource {+public:+ MoonlightSessionSource();+ ~MoonlightSessionSource() override;++ MoonlightSessionSource(const MoonlightSessionSource&) = delete;+ MoonlightSessionSource& operator=(const MoonlightSessionSource&) = delete;++ // Launches (or resumes) the app, connects and starts decoding. Blocks until+ // the stream is up or failed; false means see stats().message.+ bool connect(MoonlightConnectDesc desc);++ bool open(const SourceOpenDesc&) override { return false; } // credentials do not fit; use connect()+ const SourceInfo& info() const override { return info_; }+ SourceReadStatus read(pipeline::FramePacket&, const AVFrame**) override;+ bool seek(const pipeline::Rational&) override { return false; }+ void close() noexcept override;++ // Ends the session. `quitApp` also closes the app on the host (otherwise it+ // keeps running and can be resumed).+ void disconnect(bool quitApp);++ MoonlightStats stats() const;+ uint64_t skipped() const;+ uint64_t unitsReceived() const; // cheap: no library calls+ sink::CaptureAudioState audioState() const { return audio_.snapshot(); }+ void setAudioGain(float value) { audio_.setGain(value); }+ void setAudioSync(unsigned mode, int offset) { audio_.setSync(mode, offset); }+ void videoPresented(double ptsMs, int64_t host100ns);+ void videoReset(bool resetAudio = true) { audio_.videoReset(resetAudio); }++ // The C callbacks of moonlight-common-c land here (static trampolines in the .cpp).+ struct Callbacks;++private:+ friend struct Callbacks;+ struct Impl;++ void run(std::stop_token stop, MoonlightConnectDesc desc);+ void publish(std::shared_ptr<AVFrame> frame, const pipeline::FramePacket& packet, const SourceInfo& info);++ std::unique_ptr<Impl> p_;+ mutable std::mutex mutex_;+ std::condition_variable ready_;+ std::jthread owner_;+ std::atomic<bool> cancel_{false};+ bool initialized_ = false, started_ = false;+ SourceInfo info_, publishedInfo_;+ struct Frame { std::shared_ptr<AVFrame> frame; pipeline::FramePacket packet; SourceInfo info; };+ std::optional<Frame> latest_;+ std::shared_ptr<AVFrame> view_;+ uint64_t sequence_ = 0, skipped_ = 0;+ bool openFlagPending_ = true;+ MoonlightStats stats_;+ sink::CaptureAudioSession audio_;+};++} // namespace veyra::sourcediff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex c02c1515..831d70bb 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -95,6 +95,13 @@ remoteplay::ControllerFeedback EngineController::remotePlayFeedback(){std::lock_void EngineController::remotePlayController(const remoteplay::ControllerState& state){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->controller(state);}void EngineController::remotePlayLoginPin(std::string pin){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->loginPin(std::move(pin));}#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+void EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc desc,PlayerOptions opts){+ auto request=std::make_shared<source::MoonlightConnectDesc>(std::move(desc));+ {std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.moonlightActive=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}+ post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"moonlight:",opts,{},request);});+}+#endifvoid EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}void EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}@@ -187,6 +194,12 @@ PlayerSnapshot EngineController::snapshot()const{copy.remoteReceived=s.video.accessUnits;copy.remoteDecoded=s.decodedFrames;copy.remoteIngressDropped=s.video.dropped;copy.remotePlaySkipped=activeRemote_->skipped();copy.captureAudio=activeRemote_->audioState();copy.audioAvailable=copy.captureAudio.available;}+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(copy.moonlightActive&&activeMoonlight_){+ copy.moonlight=activeMoonlight_->stats();+ copy.captureAudio=activeMoonlight_->audioState();copy.audioAvailable=copy.captureAudio.available;+ }#endifauto& flow=copy.metrics.flow;if(!playing){flow.sourceCompletedFps=flow.outputCompletedFps=flow.validGeneratedFps=flow.presentSubmitFps=flow.xessSdkSubmitFps=0;}@@ -205,7 +218,7 @@ struct MmcssScope {~MmcssScope(){if(handle)AvRevertMmThreadCharacteristics(handle);}};}-void EngineController::run(HWND window,std::wstring path,PlayerOptions options,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest){+void EngineController::run(HWND window,std::wstring path,PlayerOptions options,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest,std::shared_ptr<source::MoonlightConnectDesc> moonlightRequest){CoInitializeEx(nullptr,COINIT_MULTITHREADED);MmcssScope mmcss(L"Pro Audio");status(L"正在初始化GPU与本地运行时…");@@ -225,13 +238,25 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#else(void)remoteRequest;const bool isRemote=false;#endif- const bool isCapture=physicalCapture||options.captureReplayForTest||isRemote||isScreen;+#ifdef VEYRA_ENABLE_MOONLIGHT+ auto moon=moonlightRequest?std::make_shared<source::MoonlightSessionSource>():nullptr;+ const bool isMoonlight=bool(moon);+ {std::lock_guard lock(mutex_);activeMoonlight_=moon;}+#else+ (void)moonlightRequest;const bool isMoonlight=false;+#endif+ // PS5 and Moonlight are both decoded network streams with the same live scheduling.+ const bool isStream=isRemote||isMoonlight;+ const bool isCapture=physicalCapture||options.captureReplayForTest||isStream||isScreen;// File replay has no hardware arrival clock; retain its continuous PTS anchor.- const bool pairAnchoredLive=physicalCapture||isRemote||isScreen;+ const bool pairAnchoredLive=physicalCapture||isStream||isScreen;source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;if(isScreen)activeSource=&screenSource;#ifdef VEYRA_ENABLE_REMOTEPLAYif(remote)activeSource=remote.get();+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon)activeSource=moon.get();#endifif(options.captureReplayForTest)veyra::log::info("capture-test","file replay exercises live scheduler; no physical capture device or latency measurement");bool audioStarted=false;bool failed=false;@@ -291,6 +316,24 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(physicalCapture)captureSource.setVerticalFlip(options.settings.captureFlipVertical);if(physicalCapture)captureSource.setBufferMode(unsigned(options.settings.captureBuffer));if(physicalCapture)captureSource.setCpuUnpack(options.captureCpuUnpack);+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon){+ status(L"正在连接串流主机…");+ ctx.device()->AddRef();moonlightRequest->decodeDevice=std::shared_ptr<ID3D12Device>(ctx.device(),[](ID3D12Device* device){device->Release();});+ ctx.directQueue()->AddRef();moonlightRequest->decodeQueue=std::shared_ptr<ID3D12CommandQueue>(ctx.directQueue(),[](ID3D12CommandQueue* queue){queue->Release();});+ if(!moon->connect(std::move(*moonlightRequest))){const auto message=moon->stats().message;status(message.empty()?L"串流连接失败,请查看诊断":message,true);break;}+ moonlightRequest.reset();+ const auto firstFrameDeadline=Clock::now()+std::chrono::seconds(20);+ while(!stop_){+ const AVFrame* first=nullptr;const auto result=moon->read(cachedPacket,&first);+ if(result==source::SourceReadStatus::Frame){cachedFrame=av_frame_clone(first);break;}+ if(result==source::SourceReadStatus::Error){const auto message=moon->stats().message;status(message.empty()?L"主机没有返回可解码的画面,请检查主机和网络后重新连接。":message,true);break;}+ if(Clock::now()>firstFrameDeadline){status(L"已连接,但 20 秒内没有收到画面。请检查主机画面输出和编码设置。",true);break;}+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ if(stop_||!cachedFrame)break;+ }+#endif#ifdef VEYRA_ENABLE_REMOTEPLAYif(remote){status(L"正在连接 PS5…");@@ -309,7 +352,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(stop_||!cachedFrame)break;}else{#endif- if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(isScreen?screenSource.status():physicalCapture&&!captureSource.errorMessage().empty()?captureSource.errorMessage():!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}+ if(!isMoonlight&&!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(isScreen?screenSource.status():physicalCapture&&!captureSource.errorMessage().empty()?captureSource.errorMessage():!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}#ifdef VEYRA_ENABLE_REMOTEPLAY}#endif@@ -500,9 +543,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,scaptureSource.setBufferMode(unsigned(options.settings.captureBuffer));if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}{std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.nominalSourceFps=isImage?0:activeSource->info().averageFps;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}- status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isRemote?L"PS5 串流":isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));+ status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isRemote?L"PS5 串流":isMoonlight?L"PC 串流":isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;- bool initialRemoteFramePending=isRemote;+ bool initialRemoteFramePending=isStream;bool initialFileFramePending=!isImage&&!isCapture;uint64_t activeSeekId=0;Clock::time_point seekStarted{};@@ -830,6 +873,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(remote){remote->setAudioGain(gain);remote->setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);const auto state=remote->audioState();const auto session=remote->sessionSnapshot();const auto rates=remote->rates();std::lock_guard lock(mutex_);snapshot_.audioAvailable=state.available;snapshot_.captureAudio=state;snapshot_.remotePlayState=int(session.state);snapshot_.remotePlaySkipped=remote->skipped();snapshot_.remoteReceivedFps=rates.receivedFps;snapshot_.remoteDecodedFps=rates.decodedFps;snapshot_.remoteRatesReady=rates.ready;snapshot_.remoteReceived=rates.received;snapshot_.remoteDecoded=rates.decoded;snapshot_.remoteIngressDropped=rates.ingressDropped;}+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon){moon->setAudioGain(gain);moon->setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);+ const auto state=moon->audioState();+ std::lock_guard lock(mutex_);snapshot_.audioAvailable=state.available;snapshot_.captureAudio=state;}#endif// Save the latest processed real frame before a settings transaction// invalidates it (live rendering can be one batch behind processing).@@ -887,6 +935,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#ifdef VEYRA_ENABLE_REMOTEPLAYif(remote)remote->videoReset(false);#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon)moon->videoReset(false);+#endif// A drain may outlive several slider notifications. Build// only the latest pending configuration at this boundary.@@ -1015,6 +1066,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#ifdef VEYRA_ENABLE_REMOTEPLAYif(remote)remote->videoReset();#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon)moon->videoReset();+#endif}if(audioStarted)audioPipe.setPaused(true);wasPaused=true;const bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;@@ -1086,11 +1140,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s}#ifdef VEYRA_ENABLE_REMOTEPLAYif(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon){const auto message=moon->stats().message;status(message.empty()?L"串流中断,请检查主机和网络后重新连接。":message,true);break;}#endifstatus(isScreen?screenSource.status():isCapture?L"采集信号中断,请检查设备连接或格式":source.errorMessage().empty()?L"视频解码或时间戳错误":source.errorMessage(),true);break;}}if(isScreen){std::lock_guard lock(mutex_);snapshot_.sourceNotice=screenSource.status();}- if((isRemote||isScreen)&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height||(isScreen&&gd.hdrInput!=activeSource->info().color.isHdrPath()))){+ if((isStream||isScreen)&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height||(isScreen&&gd.hdrInput!=activeSource->info().color.isHdrPath()))){drainLivePresentation();if(!ring.drainQueue()){status(L"串流尺寸切换排空失败",true);break;}width=uint32_t(frame->width);height=uint32_t(frame->height);describeStages(stageRequest(options),options.snapshot(),gd);@@ -1156,7 +1213,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s// A PS5 callback is a compressed AU, not a decoded video frame.// Its decode baseline must not consume the entire FG lookahead// budget. Still measure full ingress latency from captureArrival.- const auto liveInputReady=isRemote&&pkt.decodedHost100ns>0?pkt.decodedHost100ns:captureArrival;+ const auto liveInputReady=isStream&&pkt.decodedHost100ns>0?pkt.decodedHost100ns:captureArrival;const auto sourceArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100;// A skipped preview candidate breaks the temporal span the// motion/NR/FG history was built on: the next processed frame@@ -1279,7 +1336,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst auto now=host100ns(),deadline=liveTimeline.deadline(lastGenerated);const double elapsed=elapsedMs(processStart);const bool admitted=fgBudget.admit(now,deadline,elapsed,presentP95,warmingHistory);- logAdmission(batch,now,deadline,elapsed,presentP95,admitted,warmingHistory,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):"continuous");+ logAdmission(batch,now,deadline,elapsed,presentP95,admitted,warmingHistory,pairAnchoredLive?(isStream?"decoded-pair":"capture-pair"):"continuous");return admitted?pipeline::EnhanceGraph::FgDecision::Evaluate:pipeline::EnhanceGraph::FgDecision::Skip;};}@@ -1445,7 +1502,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sprocessTimes.add(processMs);traceFrame(diagnostics::TraceKind::Submitted,out.batch.identity,out.batch.batchId,std::max(out.videoFenceValue,out.genFenceValue),out.batch.b100ns,out.fgSkippedBeforeEval,out.fgEvaluated,processMs);frameFlow->cpu(diagnostics::CpuStage::Decode,decodeMs,host100ns());- if(isRemote&&pkt.decodedHost100ns>0&&!rereadCached)frameFlow->cpu(diagnostics::CpuStage::DecodedQueue,std::max(0.0,double(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100-pkt.decodedHost100ns)/10000),host100ns());+ if(isStream&&pkt.decodedHost100ns>0&&!rereadCached)frameFlow->cpu(diagnostics::CpuStage::DecodedQueue,std::max(0.0,double(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100-pkt.decodedHost100ns)/10000),host100ns());frameFlow->update([&](auto& m){m.lastSubmit100ns=host100ns();});frameFlow->cpu(diagnostics::CpuStage::Submit,processMs,host100ns());frameFlow->cpu(diagnostics::CpuStage::SlotWait,processSlotWaitMs,host100ns());@@ -1456,13 +1513,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sveyra::log::info("capture-rate",std::format("revision={} requested60To30={} active={} transportFps={} originalPtsPreserved=true",options.settings.revision,options.settings.content==ContentRate::Capture60To30,halfRate,isCapture?activeSource->info().averageFps:0));}const bool pairPacing=pairAnchoredLive&&options.fg;- if(isCapture&&!rereadCached&&(isRemote||pairPacing||!liveTimeline.anchored(out.batch.identity.epoch))){+ if(isCapture&&!rereadCached&&(isStream||pairPacing||!liveTimeline.anchored(out.batch.identity.epoch))){const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);// File replay has no device pacing and still needs its PTS// clock. Physical capture without FG presents as soon as ready.const bool paceSourcePts=options.fg||!physicalCapture;if(!liveTimeline.anchored(out.batch.identity.epoch)||(pairPacing&&frames==0))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));- if(pairPacing||isRemote)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?pairDelay:0,paceSourcePts);+ if(pairPacing||isStream)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?pairDelay:0,paceSourcePts);else if(!liveTimeline.anchored(out.batch.identity.epoch))liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);}if(!isImage&&!isCapture&&frames==0){anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}@@ -1501,6 +1558,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(!liveScheduler->push([this,&anchor,&anchorMs,&captureSource,&fedXessGenerated,&fedXessPresented,&lastFilePresentLateness,&lastFilePresentedMs,&liveSubmissions,&presentationCompletedReal,#ifdef VEYRA_ENABLE_REMOTEPLAY&remote,+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ &moon,#endif&seekDecoded,&seekStarted,&audio,&audioPipe,&audioStarted,&cadence,&ctx,&fileAudioAlignPending,&fileAwaitingVideo,&fileInputEnded,&frameFlow,&graph,&host100ns,&isCapture,&isImage,&livePresent,&liveScheduler,&nextFgDeadlineLog,&nowMs,&options,&pendingCompletions,&physicalCapture,&presentEntryDeviation,&presentReturnDeviation,&presentationEffective,&presentationGeneration,&presentationSkippedGenerated,&presenter,&ring,&runSessionId,&seekPreviewPending,&traceFrame,&traceSubframes,watch,step,timeline,captureArrival,baselineReady,delayEnhanced,activeSeekId,lineage,jobGeneration,rereadCached,sourceIntervalMs,flow=frameFlow](int64_t now)->LiveGpuScheduler::Step{using State=LiveGpuScheduler::State;auto& batch=watch->output;auto& s=*step;@@ -1638,6 +1698,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(didPresent&&physicalCapture&&!generated&&!rereadCached)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns(),captureArrival);#ifdef VEYRA_ENABLE_REMOTEPLAYif(didPresent&&remote)remote->videoPresented(double(item.pts100ns)/10000,host100ns());+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(didPresent&&moon)moon->videoPresented(double(item.pts100ns)/10000,host100ns());#endifif(didPresent&&!generated&&!rereadCached){const auto returned=host100ns();@@ -1711,6 +1774,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(remote){const auto rp=remote->sessionSnapshot();captureStats.received=rp.video.accessUnits;captureStats.dropped=remote->skipped();captureStats.delivered=sourceFrames;captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;}+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ if(moon){captureStats.received=moon->unitsReceived();captureStats.dropped=moon->skipped();captureStats.delivered=sourceFrames;+ captureStats.readAgeMs=double(std::max<int64_t>(0,host100ns()-pkt.arrivalHost100ns))/10000;+ }#endifloopTrace.mark("captureStats");diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;uint32_t slotsInFlight=0;@@ -1805,6 +1873,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s#ifdef VEYRA_ENABLE_REMOTEPLAY{std::lock_guard lock(mutex_);activeRemote_.reset();}if(remote)remote->close();+#endif+#ifdef VEYRA_ENABLE_MOONLIGHT+ {std::lock_guard lock(mutex_);activeMoonlight_.reset();}+ if(moon)moon->close();#endif// Each step is logged: a session that stopped responding after a remote// play failure left "graph shutdown complete" as its last line.diff --git a/src/source/MoonlightSessionSource.cpp b/src/source/MoonlightSessionSource.cppnew file mode 100644index 00000000..f92648b6--- /dev/null+++ b/src/source/MoonlightSessionSource.cpp@@ -0,0 +1,776 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/source/MoonlightSessionSource.h"++#include <windows.h>+#include <mmreg.h>++#include <Limelight.h>+#include <opus/opus_multistream.h>++extern "C" {+#include <libavutil/frame.h>+#include <libavutil/hwcontext.h>+}++#include <algorithm>+#include <chrono>+#include <cstdarg>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <format>+#include <vector>++#include "veyra/Log.h"+#include "veyra/moonlight/Crypto.h"+#include "veyra/pipeline/ColorMetadata.h"+#include "veyra/sink/AudioFormat.h"+#include "veyra/source/CaptureCompressedDecoder.h"++namespace veyra::source {++// The protocol layer repeats a few constants of Limelight.h so it can be tested without the C+// library; if the library ever changes them, fail here rather than negotiate the wrong format.+static_assert(moonlight::kFormatH264 == VIDEO_FORMAT_H264 && moonlight::kFormatH265 == VIDEO_FORMAT_H265 &&+ moonlight::kFormatH265Main10 == VIDEO_FORMAT_H265_MAIN10 && moonlight::kFormatAv1Main8 == VIDEO_FORMAT_AV1_MAIN8 &&+ moonlight::kFormatAv1Main10 == VIDEO_FORMAT_AV1_MAIN10 &&+ (VIDEO_FORMAT_MASK_10BIT & moonlight::kFormatMask10Bit) == moonlight::kFormatMask10Bit,+ "VIDEO_FORMAT constants differ from moonlight-common-c");+static_assert(moonlight::kServerH264 == SCM_H264 && moonlight::kServerHevc == SCM_HEVC && moonlight::kServerHevcMain10 == SCM_HEVC_MAIN10 &&+ moonlight::kServerAv1Main8 == SCM_AV1_MAIN8 && moonlight::kServerAv1Main10 == SCM_AV1_MAIN10,+ "SCM constants differ from moonlight-common-c");++namespace {++using Clock = std::chrono::steady_clock;++int64_t host100ns() {+ return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count() / 100;+}++std::wstring widen(const std::string& text) {+ if (text.empty()) return {};+ const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0);+ std::wstring out(size_t(std::max(size, 0)), L'\0');+ if (size > 0) MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), out.data(), size);+ return out;+}++const char* codecLabel(int videoFormat) {+ if (videoFormat & VIDEO_FORMAT_MASK_H264) return "H.264";+ if (videoFormat & VIDEO_FORMAT_MASK_H265) return (videoFormat & VIDEO_FORMAT_MASK_10BIT) ? "HEVC 10-bit" : "HEVC";+ if (videoFormat & VIDEO_FORMAT_MASK_AV1) return (videoFormat & VIDEO_FORMAT_MASK_10BIT) ? "AV1 10-bit" : "AV1";+ return "?";+}++// What a connection failure or termination means to the user.+std::wstring describeTermination(int code) {+ switch (code) {+ case ML_ERROR_GRACEFUL_TERMINATION: return L"主机上的游戏已经退出,串流结束。";+ case ML_ERROR_NO_VIDEO_TRAFFIC: return L"没有收到视频数据。通常是防火墙或端口转发没有放行 UDP 47998–48010。";+ case ML_ERROR_NO_VIDEO_FRAME: return L"长时间收不到完整画面。网络很不稳定,或码率设得太高。";+ case ML_ERROR_UNEXPECTED_EARLY_TERMINATION: return L"串流刚开始就被主机结束,常见原因是主机无法抓取画面(受保护内容或显示器未连接)。";+ case ML_ERROR_PROTECTED_CONTENT: return L"主机上正在显示受保护的内容,无法串流。";+ case ML_ERROR_FRAME_CONVERSION: return L"主机转换画面失败。开启 HDR 时,主机桌面分辨率与串流分辨率不兼容会这样。";+ default: return std::format(L"连接中断(错误码 {})。请检查网络和主机。", code);+ }+}++pipeline::SourcePixelFormat pixelFormatOf(const AVFrame& frame) {+ if (frame.format == AV_PIX_FMT_D3D12 && frame.hw_frames_ctx) {+ const auto* context = reinterpret_cast<const AVHWFramesContext*>(frame.hw_frames_ctx->data);+ return context->sw_format == AV_PIX_FMT_NV12 ? pipeline::SourcePixelFormat::NV12+ : context->sw_format == AV_PIX_FMT_P010 ? pipeline::SourcePixelFormat::P010 : pipeline::SourcePixelFormat::Unknown;+ }+ switch (frame.format) {+ case AV_PIX_FMT_NV12: return pipeline::SourcePixelFormat::NV12;+ case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_P010: return pipeline::SourcePixelFormat::P010;+ case AV_PIX_FMT_YUV420P: return pipeline::SourcePixelFormat::Yuv420P;+ default: return pipeline::SourcePixelFormat::Unknown;+ }+}++// A PC desktop or game: sRGB content carried as BT.709, displayed with the same code+// values (like capture cards and files); 10-bit streams are HDR10 (BT.2020 / PQ).+pipeline::ColorDescription fallbackColor(bool hdr) {+ pipeline::ColorDescription c;+ c.pixelFormat = hdr ? pipeline::SourcePixelFormat::P010 : pipeline::SourcePixelFormat::NV12;+ c.range = pipeline::ColorRange::Limited;+ c.rangeAssumed = true;+ c.matrixAssumed = c.transferAssumed = c.primariesAssumed = true;+ if (hdr) {+ c.matrix = pipeline::YuvMatrix::BT2020NCL;+ c.transfer = pipeline::TransferFunction::PQ;+ c.primaries = pipeline::ColorPrimaries::BT2020;+ } else {+ c.matrix = pipeline::YuvMatrix::BT709;+ c.transfer = pipeline::TransferFunction::BT709;+ c.primaries = pipeline::ColorPrimaries::BT709;+ c.preserveSdrCodeValues = true;+ }+ return c;+}++AVFrame* allocNv12(unsigned width, unsigned height) {+ AVFrame* frame = av_frame_alloc();+ if (!frame) return nullptr;+ frame->format = AV_PIX_FMT_NV12;+ frame->width = int(width);+ frame->height = int(height);+ if (av_frame_get_buffer(frame, 32) < 0) { av_frame_free(&frame); return nullptr; }+ return frame;+}++std::atomic<MoonlightSessionSource*> g_active{nullptr};++double movingAverage(double current, double sample) { return current > 0 ? current * 0.95 + sample * 0.05 : sample; }++} // namespace++struct MoonlightSessionSource::Impl {+ MoonlightSessionSource* owner = nullptr;+ MoonlightConnectDesc desc; // device/queue only after the launch (identity wiped)++ // Video+ CaptureCompressedDecoder decoder;+ CaptureCodec codec = CaptureCodec::None;+ unsigned width = 0, height = 0;+ int videoFormat = 0;+ bool hdrStream = false;+ std::thread decodeThread;+ std::atomic<bool> decodeStop{false};+ AVFrame* dummyTarget = nullptr; // passed while the hardware path owns the pictures+ struct Meta { int64_t pts; int64_t arrival; };+ std::deque<Meta> presented; // pts -> arrival of recent frames (for the audio sync)+ std::mutex presentedMutex;++ // Audio+ OpusMSDecoder* opus = nullptr;+ int audioChannels = 0, samplesPerFrame = 0;+ uint64_t audioSamples = 0;+ bool audioDiscontinuity = true;+ std::vector<float> pcm;++ // Counters written by the library threads+ std::atomic<uint64_t> units{0}, decoded{0}, dropped{0}, errors{0}, idr{0};+ std::atomic<int64_t> lastFrameNumber{0};+ std::atomic<bool> terminated{false};+ std::atomic<int> terminationCode{0};+ std::atomic<bool> streaming{false};+ // The library allows its statistics calls only between LiStartConnection and LiStopConnection:+ // stats() holds this while it calls them, close() takes it to clear `streaming` first.+ std::mutex libMutex;+ std::mutex statsMutex;+ double hostLatencyMs = 0, receiveMs = 0, queueMs = 0, decodeMs = 0, receivedFps = 0, decodedFps = 0;+ std::chrono::steady_clock::time_point rateStart = Clock::now();+ uint64_t rateUnits = 0, rateDecoded = 0;++ ~Impl() {+ if (dummyTarget) av_frame_free(&dummyTarget);+ if (opus) opus_multistream_decoder_destroy(opus);+ }+};++struct MoonlightSessionSource::Callbacks {+ // -- connection -------------------------------------------------------------------------+ static void stageStarting(int stage) { log::info("moonlight", std::format("stage starting: {}", LiGetStageName(stage))); }+ static void stageComplete(int stage) { log::info("moonlight", std::format("stage complete: {}", LiGetStageName(stage))); }+ static void stageFailed(int stage, int error) {+ log::warn("moonlight", std::format("stage failed: {} error={}", LiGetStageName(stage), error));+ if (auto* self = g_active.load()) {+ std::lock_guard lock(self->mutex_);+ self->stats_.errorCode = error;+ self->stats_.message = std::format(L"连接在“{}”阶段失败(错误码 {})。请确认主机上的 Sunshine 正在运行,并且防火墙放行了 TCP 47984/47989/48010 与 UDP 47998–48010。",+ widen(LiGetStageName(stage)), error);+ }+ }+ static void started() { log::info("moonlight", "connection started"); }+ static void terminated(int error) {+ log::warn("moonlight", std::format("connection terminated code={}", error));+ if (auto* self = g_active.load()) {+ self->p_->terminationCode = error;+ self->p_->terminated = true;+ std::lock_guard lock(self->mutex_);+ self->stats_.errorCode = error;+ self->stats_.message = describeTermination(error);+ self->stats_.state = error == ML_ERROR_GRACEFUL_TERMINATION ? MoonlightStats::State::Ended : MoonlightStats::State::Failed;+ }+ }+ static void logMessage(const char* format, ...) {+ char line[512];+ va_list args;+ va_start(args, format);+ std::vsnprintf(line, sizeof(line), format, args);+ va_end(args);+ std::string text(line);+ while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back();+ if (!text.empty()) log::info("moonlight-lib", text);+ }+ static void rumble(unsigned short, unsigned short, unsigned short) {} // input/feedback: stage S3+ static void connectionStatus(int status) {+ log::info("moonlight", status == CONN_STATUS_POOR ? "connection status: poor" : "connection status: okay");+ }+ static void setHdrMode(bool enabled) { log::info("moonlight", std::format("host HDR mode: {}", enabled)); }++ // -- video (pull renderer) ---------------------------------------------------------------+ static int drSetup(int videoFormat, int width, int height, int redrawRate, void*, int) {+ auto* self = g_active.load();+ if (!self) return -1;+ auto& p = *self->p_;+ p.videoFormat = videoFormat;+ p.width = unsigned(width);+ p.height = unsigned(height);+ p.hdrStream = (videoFormat & VIDEO_FORMAT_MASK_10BIT) != 0;+ p.codec = (videoFormat & VIDEO_FORMAT_MASK_H264) ? CaptureCodec::H264+ : (videoFormat & VIDEO_FORMAT_MASK_H265) ? CaptureCodec::Hevc+ : (videoFormat & VIDEO_FORMAT_MASK_AV1) ? CaptureCodec::Av1 : CaptureCodec::None;+ if (p.codec == CaptureCodec::None) return -1;+ if (!p.decoder.open(p.codec, p.width, p.height, nullptr, 0, p.desc.decodeDevice.get(), p.desc.decodeQueue.get())) {+ log::error("moonlight", std::format("no usable decoder for {}", codecLabel(videoFormat)));+ return -1;+ }+ if (!p.dummyTarget) p.dummyTarget = allocNv12(16, 16);+ log::info("moonlight", std::format("video setup {} {}x{} redraw={} backend={}", codecLabel(videoFormat), width, height, redrawRate, p.decoder.backendName()));+ {+ std::lock_guard lock(self->mutex_);+ self->stats_.codec = codecLabel(videoFormat);+ self->stats_.hdr = p.hdrStream;+ self->stats_.width = p.width;+ self->stats_.height = p.height;+ self->info_.width = p.width;+ self->info_.height = p.height;+ self->info_.displayAspect = height > 0 ? double(width) / double(height) : 0.0;+ self->info_.videoCodecName = codecLabel(videoFormat);+ self->info_.color = fallbackColor(p.hdrStream);+ }+ return 0;+ }+ static void drStart() {+ auto* self = g_active.load();+ if (!self) return;+ auto& p = *self->p_;+ p.decodeStop = false;+ p.decodeThread = std::thread([self] { decodeLoop(*self); });+ }+ static void drStop() {+ auto* self = g_active.load();+ if (!self) return;+ self->p_->decodeStop = true;+ LiWakeWaitForVideoFrame();+ }+ static void drCleanup() {+ auto* self = g_active.load();+ if (!self) return;+ auto& p = *self->p_;+ p.decodeStop = true;+ LiWakeWaitForVideoFrame();+ if (p.decodeThread.joinable()) p.decodeThread.join();+ p.decoder.close();+ }++ static void decodeLoop(MoonlightSessionSource& self) {+ auto& p = *self.p_;+ std::vector<uint8_t> unit;+ bool seenIdr = false, recovering = false;+ int64_t lastPts = -1;+ const int64_t nominal = std::max<int64_t>(1, int64_t(10000000.0 / std::max(1.0, self.stats_.fps)));+ std::deque<Impl::Meta> metas;+ log::info("moonlight", "decode thread started");+ while (!p.decodeStop.load()) {+ VIDEO_FRAME_HANDLE handle = nullptr;+ PDECODE_UNIT du = nullptr;+ if (!LiWaitForNextVideoFrame(&handle, &du)) break;+ int status = DR_OK;+ ++p.units;++ const int64_t nowHost = host100ns();+ const uint64_t nowLib = LiGetMicroseconds();+ const uint64_t ageUs = nowLib >= du->receiveTimeUs ? nowLib - du->receiveTimeUs : 0;+ const int64_t arrival = nowHost - int64_t(ageUs) * 10;++ if (!seenIdr && du->frameType != FRAME_TYPE_IDR) {+ LiCompleteVideoFrame(handle, DR_NEED_IDR);+ continue;+ }+ // A gap in frame numbers is a frame the network lost (FEC could not repair).+ const int64_t previousNumber = p.lastFrameNumber.exchange(du->frameNumber);+ if (previousNumber != 0 && du->frameNumber > previousNumber + 1) p.dropped += uint64_t(du->frameNumber - previousNumber - 1);++ unit.clear();+ for (PLENTRY entry = du->bufferList; entry; entry = entry->next)+ unit.insert(unit.end(), reinterpret_cast<const uint8_t*>(entry->data), reinterpret_cast<const uint8_t*>(entry->data) + entry->length);++ // The host's capture clock is the stream's timeline; it must still strictly increase.+ int64_t pts = int64_t(du->presentationTimeUs) * 10;+ if (pts <= lastPts) pts = lastPts + nominal;+ lastPts = pts;+ metas.push_back({pts, arrival});+ if (metas.size() > 64) metas.pop_front();++ const auto decodeBegin = Clock::now();+ // While the hardware path owns the pictures the target is never written; before the first+ // hardware picture (the decoder may still fall back to software) it must be a real frame.+ const bool needsTarget = p.decoder.framesDecoded() == 0 || !p.decoder.hardwareActive();+ AVFrame* target = needsTarget ? allocNv12(p.width, p.height) : p.dummyTarget;+ AVFrame* out = nullptr;+ bool hardware = false;+ const bool produced = target && p.decoder.decode(unit.data(), unit.size(), pts, target, &out, hardware);+ const double decodeMs = std::chrono::duration<double, std::milli>(Clock::now() - decodeBegin).count();++ if (!produced) {+ if (needsTarget && target) av_frame_free(&target);+ if (!p.decoder.waitingForInput()) {+ ++p.errors;+ ++p.idr;+ recovering = true;+ status = DR_NEED_IDR;+ seenIdr = false;+ }+ LiCompleteVideoFrame(handle, status);+ continue;+ }++ std::shared_ptr<AVFrame> frame;+ if (hardware) {+ AVFrame* cloned = av_frame_clone(out);+ if (cloned) frame.reset(cloned, [](AVFrame* f) { av_frame_free(&f); });+ if (needsTarget && target) av_frame_free(&target);+ } else {+ frame.reset(target, [](AVFrame* f) { av_frame_free(&f); }); // the picture was converted into it+ }+ if (!frame) { ++p.errors; LiCompleteVideoFrame(handle, DR_OK); continue; }+ seenIdr = true;++ int64_t matchedArrival = arrival;+ const int64_t framePts = frame->pts != AV_NOPTS_VALUE ? frame->pts : pts;+ for (const auto& meta : metas) if (meta.pts == framePts) { matchedArrival = meta.arrival; break; }++ pipeline::FramePacket packet{};+ packet.sourceKind = pipeline::SourceKind::Moonlight;+ packet.pts = pipeline::Rational{framePts, 10000000};+ packet.duration = pipeline::Rational{nominal, 10000000};+ packet.arrivalHost100ns = matchedArrival;+ packet.decodedHost100ns = host100ns();+ if (recovering) { packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity); recovering = false; }++ auto fallback = fallbackColor(p.hdrStream);+ packet.colorInfo = pipeline::resolveFrameColor(*frame, fallback);+ packet.colorInfo.pixelFormat = pixelFormatOf(*frame);+ if (packet.colorInfo.pixelFormat == pipeline::SourcePixelFormat::Unknown) {+ ++p.errors;+ LiCompleteVideoFrame(handle, DR_OK);+ continue;+ }+ SourceInfo info;+ {+ std::lock_guard lock(self.mutex_);+ info = self.info_;+ }+ info.color = packet.colorInfo;+ info.hardwareDecodeActive = frame->format == AV_PIX_FMT_D3D12;+ info.videoDecodePath = info.hardwareDecodeActive ? "d3d12va" : "software";+ if (info.width != unsigned(frame->width) || info.height != unsigned(frame->height)) {+ info.width = unsigned(frame->width);+ info.height = unsigned(frame->height);+ info.displayAspect = frame->height > 0 ? double(frame->width) / double(frame->height) : 0.0;+ packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Resize);+ }+ {+ std::lock_guard lock(p.presentedMutex);+ p.presented.push_back({framePts, matchedArrival});+ if (p.presented.size() > 64) p.presented.pop_front();+ }++ // Statistics: the host reports its capture+encode time in 0.1 ms; the library timestamps+ // the first packet of the frame, its completion and our dequeue.+ {+ std::lock_guard lock(p.statsMutex);+ if (du->frameHostProcessingLatency) p.hostLatencyMs = movingAverage(p.hostLatencyMs, du->frameHostProcessingLatency / 10.0);+ p.receiveMs = movingAverage(p.receiveMs, double(int64_t(du->enqueueTimeUs) - int64_t(du->receiveTimeUs)) / 1000.0);+ p.queueMs = movingAverage(p.queueMs, double(int64_t(nowLib) - int64_t(du->enqueueTimeUs)) / 1000.0);+ p.decodeMs = movingAverage(p.decodeMs, decodeMs);+ ++p.decoded;+ }+ self.publish(std::move(frame), packet, info);+ LiCompleteVideoFrame(handle, DR_OK);+ }+ log::info("moonlight", "decode thread stopped");+ }++ // -- audio ---------------------------------------------------------------------------------+ static int arInit(int audioConfiguration, const POPUS_MULTISTREAM_CONFIGURATION config, void*, int) {+ auto* self = g_active.load();+ if (!self) return -1;+ auto& p = *self->p_;+ int error = 0;+ p.opus = opus_multistream_decoder_create(config->sampleRate, config->channelCount, config->streams, config->coupledStreams, config->mapping, &error);+ if (!p.opus || error != OPUS_OK) {+ log::error("moonlight-audio", std::format("Opus decoder creation failed: {}", error));+ return -1;+ }+ p.audioChannels = config->channelCount;+ p.samplesPerFrame = config->samplesPerFrame;+ p.pcm.assign(size_t(p.samplesPerFrame) * size_t(p.audioChannels), 0.f);+ p.audioSamples = 0;+ p.audioDiscontinuity = true;+ sink::AudioFormat layout;+ layout.channels = unsigned(config->channelCount);+ layout.mask = uint32_t(CHANNEL_MASK_FROM_AUDIO_CONFIGURATION(audioConfiguration));+ if (!layout.valid() || config->sampleRate != 48000) {+ log::error("moonlight-audio", std::format("unsupported audio layout channels={} mask=0x{:X} rate={}", layout.channels, layout.mask, config->sampleRate));+ return -1;+ }+ const WAVEFORMATEXTENSIBLE wave = sink::floatWave(layout);+ if (!self->audio_.configure(wave.Format, sizeof(wave))) {+ log::error("moonlight-audio", "the audio output could not be configured; the stream continues without sound");+ // Video stays available: a missing audio device must not end the session.+ opus_multistream_decoder_destroy(p.opus);+ p.opus = nullptr;+ return 0;+ }+ log::info("moonlight-audio", std::format("Opus {} ch, {} streams, {} coupled, {} samples per frame", config->channelCount, config->streams, config->coupledStreams, config->samplesPerFrame));+ return 0;+ }+ static void arStart() {+ if (auto* self = g_active.load(); self && self->p_->opus) self->audio_.start();+ }+ static void arStop() {+ if (auto* self = g_active.load(); self && self->p_->opus) self->audio_.stop();+ }+ static void arCleanup() {+ auto* self = g_active.load();+ if (!self) return;+ auto& p = *self->p_;+ if (p.opus) { opus_multistream_decoder_destroy(p.opus); p.opus = nullptr; }+ }+ static void arDecode(char* sample, int length) {+ auto* self = g_active.load();+ if (!self) return;+ auto& p = *self->p_;+ if (!p.opus) return;+ const int frames = opus_multistream_decode_float(p.opus, reinterpret_cast<const unsigned char*>(sample), length, p.pcm.data(), p.samplesPerFrame, 0);+ if (frames <= 0) { p.audioDiscontinuity = true; return; }+ const double ptsMs = double(p.audioSamples) * 1000.0 / 48000.0;+ self->audio_.push(p.pcm.data(), size_t(frames) * size_t(p.audioChannels) * sizeof(float), ptsMs, p.audioDiscontinuity);+ p.audioDiscontinuity = false;+ p.audioSamples += uint64_t(frames);+ }+};++MoonlightSessionSource::MoonlightSessionSource() : p_(std::make_unique<Impl>()) { p_->owner = this; }++MoonlightSessionSource::~MoonlightSessionSource() { close(); }++bool MoonlightSessionSource::connect(MoonlightConnectDesc desc) {+ close();+ MoonlightSessionSource* expected = nullptr;+ if (!g_active.compare_exchange_strong(expected, this)) {+ log::error("moonlight", "another Moonlight session is already active");+ return false;+ }+ {+ std::lock_guard lock(mutex_);+ initialized_ = started_ = false;+ latest_.reset();+ view_.reset();+ sequence_ = skipped_ = 0;+ openFlagPending_ = true;+ stats_ = {};+ stats_.state = MoonlightStats::State::Launching;+ stats_.fps = desc.options.fps;+ info_ = {};+ }+ p_ = std::make_unique<Impl>();+ p_->owner = this;+ cancel_ = false;+ owner_ = std::jthread([this, request = std::move(desc)](std::stop_token stop) mutable { run(stop, std::move(request)); });+ std::unique_lock lock(mutex_);+ ready_.wait(lock, [&] { return initialized_; });+ if (!started_) {+ lock.unlock();+ close();+ return false;+ }+ info_ = publishedInfo_;+ return true;+}++void MoonlightSessionSource::run(std::stop_token, MoonlightConnectDesc desc) {+ const auto fail = [&](std::wstring message, int code = 0) {+ log::error("moonlight", std::format("connect failed: code={}", code));+ std::lock_guard lock(mutex_);+ stats_.state = MoonlightStats::State::Failed;+ stats_.message = std::move(message);+ stats_.errorCode = code;+ initialized_ = true;+ started_ = false;+ ready_.notify_all();+ };+ try {+ const auto& o = desc.options;+ const int formats = moonlight::chooseVideoFormats(o.codec, o.hdr, desc.host.serverCodecModeSupport, o.av1HardwareDecode);+ if (!formats) {+ fail(o.hdr ? L"主机不支持所选的 HDR 编码。HDR 需要主机支持 HEVC 10-bit 或 AV1 10-bit。" : L"主机不支持所选的编码。");+ return;+ }++ STREAM_CONFIGURATION config;+ LiInitializeStreamConfiguration(&config);+ config.width = o.width;+ config.height = o.height;+ config.fps = o.fps;+ config.bitrate = o.bitrateKbps > 0 ? o.bitrateKbps : moonlight::defaultBitrateKbps(o.width, o.height, o.fps);+ config.packetSize = 1392;+ config.streamingRemotely = STREAM_CFG_AUTO;+ config.audioConfiguration = o.audioChannels >= 8 ? AUDIO_CONFIGURATION_71_SURROUND+ : o.audioChannels >= 6 ? AUDIO_CONFIGURATION_51_SURROUND : AUDIO_CONFIGURATION_STEREO;+ config.supportedVideoFormats = formats;+ config.clientRefreshRateX100 = o.displayRefreshHz > 0 ? o.displayRefreshHz * 100 : 0;+ config.colorSpace = (formats & VIDEO_FORMAT_MASK_10BIT) ? COLORSPACE_REC_2020 : COLORSPACE_REC_709;+ config.colorRange = COLOR_RANGE_LIMITED;+ config.encryptionFlags = ENCFLG_ALL;+ const std::string key = moonlight::crypto::randomBytes(16);+ const std::string ivPrefix = moonlight::crypto::randomBytes(4);+ std::memcpy(config.remoteInputAesKey, key.data(), sizeof(config.remoteInputAesKey));+ std::memcpy(config.remoteInputAesIv, ivPrefix.data(), 4);++ moonlight::LaunchRequest launch;+ launch.appId = desc.appId;+ launch.width = o.width;+ launch.height = o.height;+ launch.fps = o.fps;+ std::memcpy(launch.remoteInputKey.data(), key.data(), 16);+ std::memcpy(launch.remoteInputKeyId.data(), ivPrefix.data(), 4);+ launch.hdr = (formats & VIDEO_FORMAT_MASK_10BIT) != 0;+ launch.sops = o.sops;+ launch.localAudio = o.localAudio;+ launch.surroundAudioInfo = SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(config.audioConfiguration);+ launch.gamepadMask = o.gamepadMask;+ launch.extraQuery = LiGetLaunchUrlQueryParameters();++ moonlight::ServerClient client(desc.identity, desc.address, desc.serverCertPem, desc.httpsPort, !desc.host.nvidiaServerSoftware);+ client.setCancel(&cancel_);+ std::string rtspUrl;+ try {+ rtspUrl = client.launch(desc.resume ? "resume" : "launch", launch, desc.host.nvidiaServerSoftware);+ } catch (const moonlight::StatusError& e) {+ fail(e.status == 401 ? L"主机不认识这台电脑,请重新配对。" : std::format(L"主机拒绝了启动请求({})。", widen(e.what())), e.status);+ return;+ } catch (const moonlight::TransportError& e) {+ if (e.kind == moonlight::TransportError::Kind::Cancelled) { fail(L"已取消。"); return; }+ fail(e.kind == moonlight::TransportError::Kind::Tls ? L"与主机的加密连接失败,主机的证书可能已改变,请重新配对。" : L"连不上主机,请检查网络和主机是否开机。");+ return;+ }+ // The identity (the client's private key) is not needed any more.+ SecureZeroMemory(desc.identity.keyPem.data(), desc.identity.keyPem.size());+ desc.identity = {};+ if (rtspUrl.empty()) { fail(L"主机没有返回串流地址。"); return; }+ if (cancel_.load()) { fail(L"已取消。"); return; }++ {+ std::lock_guard lock(mutex_);+ stats_.state = MoonlightStats::State::Connecting;+ stats_.encrypted = true;+ }+ p_->desc = std::move(desc);+ const auto& d = p_->desc;++ SERVER_INFORMATION server;+ LiInitializeServerInformation(&server);+ const std::string address = d.address.host;+ server.address = address.c_str();+ server.serverInfoAppVersion = d.host.appVersion.c_str();+ server.serverInfoGfeVersion = d.host.gfeVersion.empty() ? nullptr : d.host.gfeVersion.c_str();+ server.rtspSessionUrl = rtspUrl.c_str();+ server.serverCodecModeSupport = d.host.serverCodecModeSupport;++ CONNECTION_LISTENER_CALLBACKS listener;+ LiInitializeConnectionCallbacks(&listener);+ listener.stageStarting = Callbacks::stageStarting;+ listener.stageComplete = Callbacks::stageComplete;+ listener.stageFailed = Callbacks::stageFailed;+ listener.connectionStarted = Callbacks::started;+ listener.connectionTerminated = Callbacks::terminated;+ listener.logMessage = Callbacks::logMessage;+ listener.rumble = Callbacks::rumble;+ listener.connectionStatusUpdate = Callbacks::connectionStatus;+ listener.setHdrMode = Callbacks::setHdrMode;++ DECODER_RENDERER_CALLBACKS video;+ LiInitializeVideoCallbacks(&video);+ video.setup = Callbacks::drSetup;+ video.start = Callbacks::drStart;+ video.stop = Callbacks::drStop;+ video.cleanup = Callbacks::drCleanup;+ video.submitDecodeUnit = nullptr;+ video.capabilities = CAPABILITY_PULL_RENDERER;++ AUDIO_RENDERER_CALLBACKS audio;+ LiInitializeAudioCallbacks(&audio);+ audio.init = Callbacks::arInit;+ audio.start = Callbacks::arStart;+ audio.stop = Callbacks::arStop;+ audio.cleanup = Callbacks::arCleanup;+ audio.decodeAndPlaySample = Callbacks::arDecode;+ // Sunshine sends 5 ms packets; the audio path copes with any duration.+ audio.capabilities = CAPABILITY_SUPPORTS_ARBITRARY_AUDIO_DURATION;++ log::info("moonlight", std::format("connecting {}x{}@{} {} kbps formats=0x{:X} audio={}ch", o.width, o.height, o.fps, config.bitrate, formats, o.audioChannels));+ const int result = LiStartConnection(&server, &config, &listener, &video, &audio, nullptr, 0, nullptr, 0);+ // The session key material is no longer needed here either.+ SecureZeroMemory(config.remoteInputAesKey, sizeof(config.remoteInputAesKey));+ if (result != 0) {+ std::wstring message;+ {+ std::lock_guard lock(mutex_);+ message = stats_.message;+ }+ fail(message.empty() ? std::format(L"无法建立串流连接(错误码 {})。", result) : message, result);+ return;+ }+ {+ std::lock_guard lock(mutex_);+ stats_.state = MoonlightStats::State::Streaming;+ publishedInfo_ = info_;+ publishedInfo_.opened = true;+ publishedInfo_.kind = pipeline::SourceKind::Moonlight;+ publishedInfo_.averageFps = double(o.fps);+ publishedInfo_.nominalRateNum = o.fps;+ publishedInfo_.nominalRateDen = 1;+ publishedInfo_.timestampQuantum = 1.0 / double(std::max(1, o.fps));+ publishedInfo_.duration = pipeline::Rational::unknown();+ info_ = publishedInfo_;+ initialized_ = true;+ started_ = true;+ }+ p_->streaming = true;+ ready_.notify_all();+ // From here the library's own threads run the stream; this thread only waits to be stopped.+ while (!cancel_.load() && !p_->terminated.load()) std::this_thread::sleep_for(std::chrono::milliseconds(50));+ } catch (const std::exception& e) {+ log::error("moonlight", std::format("session failed: {}", e.what()));+ fail(L"串流处理异常,已停止,请查看日志。");+ }+}++void MoonlightSessionSource::publish(std::shared_ptr<AVFrame> frame, const pipeline::FramePacket& packet, const SourceInfo& info) {+ std::lock_guard lock(mutex_);+ Frame item{std::move(frame), packet, info};+ item.packet.sequence = ++sequence_;+ if (openFlagPending_) {+ item.packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Open);+ openFlagPending_ = false;+ }+ // A picture the engine never asked for is a skipped source frame: flag it so temporal+ // effects reset their history, exactly like the capture mailbox does.+ if (latest_) {+ ++skipped_;+ item.packet.flags |= latest_->packet.flags;+ item.packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Drop);+ }+ latest_ = std::move(item);+}++SourceReadStatus MoonlightSessionSource::read(pipeline::FramePacket& packet, const AVFrame** frame) {+ if (frame) *frame = nullptr;+ std::lock_guard lock(mutex_);+ if (stats_.state == MoonlightStats::State::Failed || stats_.state == MoonlightStats::State::Ended) return SourceReadStatus::Error;+ if (!latest_) return started_ ? SourceReadStatus::Waiting : SourceReadStatus::Error;+ packet = latest_->packet;+ info_ = latest_->info;+ view_ = std::move(latest_->frame);+ latest_.reset();+ if (frame) *frame = view_.get();+ return SourceReadStatus::Frame;+}++void MoonlightSessionSource::videoPresented(double ptsMs, int64_t host) {+ std::optional<int64_t> arrival;+ {+ std::lock_guard lock(p_->presentedMutex);+ const int64_t pts100 = int64_t(ptsMs * 10000.0);+ for (const auto& meta : p_->presented) if (std::llabs(meta.pts - pts100) < 5) { arrival = meta.arrival; break; }+ }+ audio_.videoPresented(ptsMs, host, arrival);+}++void MoonlightSessionSource::disconnect(bool quitApp) {+ // The HTTP request needs the identity the session has already wiped; quitting the app on the+ // host is therefore left to the caller (bridge), which holds the host record. Here it only ends the stream.+ (void)quitApp;+ cancel_ = true;+}++void MoonlightSessionSource::close() noexcept {+ cancel_ = true;+ if (owner_.joinable()) owner_.request_stop();+ // LiStopConnection joins the library threads; the decode thread ends through the stop callback.+ if (g_active.load() == this) {+ LiInterruptConnection();+ bool wasStreaming = false;+ {+ std::lock_guard lib(p_->libMutex);+ wasStreaming = p_->streaming.exchange(false);+ }+ if (wasStreaming) LiStopConnection();+ }+ if (owner_.joinable()) owner_.join();+ if (p_ && p_->decodeThread.joinable()) { p_->decodeStop = true; LiWakeWaitForVideoFrame(); p_->decodeThread.join(); }+ audio_.stop();+ {+ std::lock_guard lock(mutex_);+ latest_.reset();+ view_.reset();+ info_ = {};+ started_ = false;+ if (stats_.state == MoonlightStats::State::Streaming || stats_.state == MoonlightStats::State::Connecting || stats_.state == MoonlightStats::State::Launching)+ stats_.state = MoonlightStats::State::Idle;+ }+ MoonlightSessionSource* self = this;+ g_active.compare_exchange_strong(self, nullptr);+}++MoonlightStats MoonlightSessionSource::stats() const {+ MoonlightStats s;+ {+ std::lock_guard lock(mutex_);+ s = stats_;+ s.dropped = 0;+ }+ if (!p_) return s;+ s.units = p_->units.load();+ s.decoded = p_->decoded.load();+ s.dropped = p_->dropped.load() + skipped();+ s.decodeErrors = p_->errors.load();+ s.idrRequests = p_->idr.load();+ s.hardwareDecode = p_->decoder.hardwareActive();+ {+ std::lock_guard lock(p_->statsMutex);+ s.hostLatencyMs = p_->hostLatencyMs;+ s.receiveMs = p_->receiveMs;+ s.queueMs = p_->queueMs;+ s.decodeMs = p_->decodeMs;+ }+ std::lock_guard lib(p_->libMutex);+ if (p_->streaming.load() && s.state == MoonlightStats::State::Streaming) {+ uint32_t rtt = 0, variance = 0;+ if (LiGetEstimatedRttInfo(&rtt, &variance)) { s.rttMs = double(rtt); s.rttVarianceMs = double(variance); }+ if (const RTP_VIDEO_STATS* video = LiGetRTPVideoStats()) {+ s.videoPackets = video->packetCountVideo;+ s.fecPackets = video->packetCountFec;+ s.fecRecovered = video->packetCountFecRecovered;+ s.fecFailed = video->packetCountFecFailed;+ s.outOfSequence = video->packetCountOOS;+ }+ }+ return s;+}++uint64_t MoonlightSessionSource::unitsReceived() const { return p_ ? p_->units.load() : 0; }++uint64_t MoonlightSessionSource::skipped() const {+ std::lock_guard lock(mutex_);+ return skipped_;+}++} // namespace veyra::sourcediff --git a/tests/moonlight/ProtocolTests.cpp b/tests/moonlight/ProtocolTests.cppindex a3c2eba3..01a13845 100644--- a/tests/moonlight/ProtocolTests.cpp+++ b/tests/moonlight/ProtocolTests.cpp@@ -30,6 +30,7 @@#include "veyra/moonlight/Http.h"#include "veyra/moonlight/IdentityStore.h"#include "veyra/moonlight/Pairing.h"+#include "veyra/moonlight/StreamConfig.h"#include "veyra/moonlight/Xml.h"using namespace veyra::moonlight;@@ -393,6 +394,30 @@ void cryptoTests() {check(generatePin().size() == 4, "pin has four digits");}+void streamConfigTests() {+ // moonlight-qt's table: 1080p60 = 20 Mbps, 4K60 = 80 Mbps, 720p30 = 5 Mbps.+ check(defaultBitrateKbps(1920, 1080, 60) == 20000, "1080p60 default bitrate");+ check(defaultBitrateKbps(3840, 2160, 60) == 80000, "4K60 default bitrate");+ check(defaultBitrateKbps(1280, 720, 30) == 5000, "720p30 default bitrate");+ check(defaultBitrateKbps(3840, 2160, 30) == 40000, "4K30 default bitrate");+ check(defaultBitrateKbps(3840, 2160, 120) == 113000, "frame rate factor grows with the square root above 60 fps");+ check(defaultBitrateKbps(1920, 1080, 60, true) == 40000, "4:4:4 doubles the bitrate");+ check(defaultBitrateKbps(2560, 1440, 60) > defaultBitrateKbps(1920, 1080, 60) && defaultBitrateKbps(2560, 1440, 60) < defaultBitrateKbps(3840, 2160, 60), "bitrate grows with resolution");+ check(defaultBitrateKbps(320, 200, 30) == 1000, "never below the smallest table entry");+ check(defaultBitrateKbps(7680, 4320, 60) == 80000, "never above the largest table entry");++ const int sunshine = 197377; // H.264, HEVC, HEVC Main10, AV1 Main8, AV1 Main10+ check(chooseVideoFormats(CodecChoice::Auto, false, sunshine, false) == (kFormatH264 | kFormatH265), "auto SDR offers H.264 and HEVC, not AV1 without hardware decode");+ check(chooseVideoFormats(CodecChoice::Auto, false, sunshine, true) == (kFormatH264 | kFormatH265 | kFormatAv1Main8), "auto SDR adds AV1 when it decodes in hardware");+ check(chooseVideoFormats(CodecChoice::Hevc, false, sunshine, false) == kFormatH265, "HEVC only");+ check(chooseVideoFormats(CodecChoice::Auto, true, sunshine, false) == kFormatH265Main10, "auto HDR offers HEVC Main10 only");+ check(chooseVideoFormats(CodecChoice::Auto, true, sunshine, true) == (kFormatH265Main10 | kFormatAv1Main10), "auto HDR adds AV1 Main10 with hardware decode");+ check(chooseVideoFormats(CodecChoice::H264, true, sunshine, true) == 0, "HDR cannot be carried by H.264");+ check(chooseVideoFormats(CodecChoice::Hevc, false, kServerH264, false) == 0, "a host without HEVC cannot give HEVC");+ check(chooseVideoFormats(CodecChoice::Auto, false, kServerH264, true) == kFormatH264, "an H.264-only host still streams");+ check((chooseVideoFormats(CodecChoice::Av1, true, sunshine, false) & kFormatMask10Bit) == kFormatAv1Main10, "explicit AV1 HDR");+}+void storeTests() {wchar_t temp[MAX_PATH];GetTempPathW(MAX_PATH, temp);@@ -529,6 +554,7 @@ int main() {xmlTests();cryptoTests();storeTests();+ streamConfigTests();protocolTests();std::printf("moonlight protocol tests: %d checks, %d failures\n", g_checks, g_failures);return g_failures == 0 ? 0 : 1;