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(capture): Magewell Pro Capture low-latency mode (MWCapture SDK)
Veyra Goal Agent5ad38bef90b8
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 288ade58..f79f58d2 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -536,8 +536,19 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/source/AverMediaAudioSwitch.cppsrc/source/CaptureCompressedDecoder.cppsrc/source/WasapiAudioInput.cpp+ src/source/MagewellCapture.cpp)veyra_apply_warnings(veyra_sources)+ # Magewell Pro Capture low-latency video: compiled against the vendor SDK headers when+ # VEYRA_MAGEWELL_SDK_DIR points at them (kept outside the source tree); LibMWCapture.dll is+ # loaded at run time. Without the headers the feature reports itself unavailable.+ set(VEYRA_MAGEWELL_SDK_DIR "" CACHE PATH "MWCapture SDK root containing Include/LibMWCapture")+ if(VEYRA_MAGEWELL_SDK_DIR AND EXISTS "${VEYRA_MAGEWELL_SDK_DIR}/Include/LibMWCapture/MWCapture.h")+ set_source_files_properties(src/source/MagewellCapture.cpp PROPERTIES+ COMPILE_DEFINITIONS VEYRA_HAS_MAGEWELL=1+ INCLUDE_DIRECTORIES "${VEYRA_MAGEWELL_SDK_DIR}/Include;${VEYRA_MAGEWELL_SDK_DIR}/Include/LibMWCapture")+ message(STATUS "Magewell SDK headers: ${VEYRA_MAGEWELL_SDK_DIR}")+ endif()target_compile_options(veyra_sources PRIVATE /WX-)target_compile_features(veyra_sources PRIVATE cxx_std_20)target_link_libraries(veyra_sources PUBLIC veyra_sinks)@@ -708,6 +719,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_definitions(veyra_capture_compressed_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)target_include_directories(veyra_capture_compressed_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})target_link_libraries(veyra_capture_compressed_tests PRIVATE veyra_sources veyra_gfx ${FFMPEG_LIBRARIES})+ add_executable(veyra_magewell_probe tools/magewell_probe/main.cpp)+ target_compile_features(veyra_magewell_probe PRIVATE cxx_std_20)+ target_compile_definitions(veyra_magewell_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)+ target_link_libraries(veyra_magewell_probe PRIVATE veyra_sources)add_executable(veyra_stream_decode_bench tools/stream_decode_bench/main.cpp)target_compile_features(veyra_stream_decode_bench PRIVATE cxx_std_20)target_compile_definitions(veyra_stream_decode_bench PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 244273e4..59d9f21d 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -614,3 +614,15 @@ Linked from the vcpkg tree (pins in `scripts/xbox/dependency-lock.json`):**usrsctp** 0.9.5.0 (BSD-3-Clause), **libsrtp** 2.8.0 (BSD-3-Clause), **plog** 1.1.11 (MIT) and**nlohmann/json** 3.12.0 (MIT). MPL-2.0 is file-level copyleft and compatible with GPL-3.0; the MPL sources used arethe published upstream releases plus the patch above. License texts: `licenses/xbox/`.++## Magewell MWCapture SDK (Pro Capture low-latency capture, 2026-10-01)++- Component: Magewell MWCapture SDK for Windows 3.3.1.1596 (Nanjing Magewell Electronics Co., Ltd.).+- Use: `src/source/MagewellCapture.cpp` is compiled against the SDK header files (kept outside the+ source tree, CMake `VEYRA_MAGEWELL_SDK_DIR`) and loads `LibMWCapture.dll` at run time; the call+ sequence follows the SDK example `Examples/Applications/LowLatency`. Test packages carry the+ unmodified `LibMWCapture.dll` in `runtime/magewell/`.+- Licence: the header files and library are licensed for use, modification and redistribution with+ Magewell's copyright notice and disclaimer retained; the full text is in+ `licenses/magewell/MWCapture-SDK-NOTICE.txt`. The SDK as a whole (examples, tools) is under+ Magewell's EULA and is not redistributed.diff --git a/docs/MAGEWELL_LOW_LATENCY_2026-10-01.md b/docs/MAGEWELL_LOW_LATENCY_2026-10-01.mdnew file mode 100644index 00000000..234b7d89--- /dev/null+++ b/docs/MAGEWELL_LOW_LATENCY_2026-10-01.md@@ -0,0 +1,40 @@+# 美乐威 Pro Capture 低延迟模式(2026-10-01,beta 5)++来源:群友反馈"美乐威采集卡有低延迟模式(逐行),要适配 SDK"。用户要求:做一个美乐威专用的按钮。++## 原理(美乐威官方说明)++- 普通模式:一帧先完整进采集卡内存,再整帧 DMA 到电脑内存。+- 低延迟模式:卡收到 64/128/256 行就开始 DMA,"部分通知"按块告诉软件。整帧在最后一行到达后很快就完整在内存里。+- 官方数据:1080p60 采集延迟约 21.7 → 17 ms,4K60 约 37.6 → 22.6 ms。+- 只有 **Pro Capture(PCIe)** 系列支持;USB Capture 和第一代设备不支持。低延迟占一个通道的两条传输通道之一。+- DirectShow 做不到,只能用美乐威 MWCapture SDK。++参考:<https://www.magewell.cn/developer/28/detail>,<https://www.magewell.cn/developer/15/detail>,SDK 示例 `Examples/Applications/LowLatency`。++## 实现++- `src/source/MagewellCapture.cpp`:运行时加载 `LibMWCapture.dll`(先找软件目录 `runtime\magewell\`,再找系统),+ 按官方示例的顺序:`MWRegisterNotify(FRAME_BUFFERING)` → `MWCaptureVideoFrameToVirtualAddressEx(iNewestBuffering, cyPartialNotify=64)`+ → 等到 `bFrameCompleted`。缓冲区页对齐并 `MWPinVideoBuffer`。按 DirectShow 设备路径(PCI 实例)找对应的 SDK 通道,找不到且只有一块卡时用那一块,日志记录两边的路径。+- 接入现有采集卡来源(`CaptureCardSource`):DirectShow 照常协商格式、音频照常;开了低延迟且设备是美乐威 PCIe 卡(`ven_1cd7`)、格式是 NV12/P010/YUY2/RGB32 时,+ 视频改由 SDK 线程写入同一个邮箱帧,DirectShow 的视频帧被忽略。SDK 线程若启动失败或中途退出,DirectShow 视频自动接回,不会黑屏。+ 时间轴接在 DirectShow 最后一帧之后继续,不跳到卡的时钟。+- 界面:采集卡对话框"设备"组新增"美乐威低延迟模式"开关。非美乐威 PCIe 设备时开关灰掉并说明;开启后提示一行状态+ ("低延迟采集中 · 一帧从开始进卡到完整进内存 x ms",或没启用的原因)。偏好 `magewellLowLatency` 保存在用户偏好里,下次连接生效。+- 构建:SDK 头文件放在 `E:/项目/Veyra/deps/magewell/3.3.1.1596`(不进源码库),CMake `VEYRA_MAGEWELL_SDK_DIR`;没有头文件的构建里该功能报"不可用"。+- 许可:SDK 头文件和库的许可允许使用、修改、再分发,需保留版权声明和免责声明 → 测试包带原样 `runtime\magewell\LibMWCapture.dll`(3.3.1.1596,SHA-256 `360259C4…92F9`)+ 和 `licenses\magewell\MWCapture-SDK-NOTICE.txt`。SDK 安装程序(未签名)没有运行,用 innoextract 1.9 只解包。++## 验证++- 本机没有美乐威卡。已验证:运行库能加载、`MWCaptureInitInstance` 成功、枚举到 0 个通道时正确拒绝并给出原因(`veyra_magewell_probe`)。+- 本机另一块 USB 采集卡(非美乐威)在开关打开时照常走 DirectShow:118 fps,0 丢帧。+- 采集对话框截图:`tests/stream-fix-20261001/capshot/`。+- **未验证(需要有 Pro Capture 卡的群友)**:通道匹配、低延迟画面、颜色、实际延迟数值、长时间稳定性、拔插与换信号、音画同步。++## 给测试者++1. 采集卡对话框选美乐威 Pro Capture 设备,格式选 NV12(或 YUY2/P010),打开"美乐威低延迟模式",点"连接并开始"。+2. 对话框里那行状态应显示"低延迟采集中 · … ms"。+3. 关掉开关再连一次对比延迟手感;日志 `logs\veyra-qml.log` 搜 `magewell`(含通道匹配、每 600 帧一次延迟统计)。diff --git a/docs/TEST_PACKAGE_2.0.0beta5.md b/docs/TEST_PACKAGE_2.0.0beta5.mdnew file mode 100644index 00000000..b9ed0e43--- /dev/null+++ b/docs/TEST_PACKAGE_2.0.0beta5.md@@ -0,0 +1,120 @@+# Veyra 2.0.0 beta 5(PC 串流 + Xbox 串流 + 美乐威低延迟)测试说明++## beta 5 新增:美乐威 Pro Capture 低延迟模式++- 采集卡对话框「设备」里新增 **美乐威低延迟模式** 开关。只有美乐威 **Pro Capture(PCIe 内置卡)** 能用;USB Capture 系列和其他品牌的卡开关是灰的。+- 原理:采集卡收到 64 行就开始往电脑传,整帧更早到达。美乐威官方数据:1080p60 约省 5 ms,4K60 约省 15 ms。+- 用法:选美乐威设备 → 格式选 NV12(YUY2、P010、RGB32 也行)→ 打开开关 → 点「连接并开始」。开关下面那行会显示"低延迟采集中 · 一帧从开始进卡到完整进内存 x ms"。+- 美乐威的运行库已经放在包里(`runtime\magewell\LibMWCapture.dll`),不用另装 SDK;美乐威驱动照常要装。+- 如果低延迟启动失败,会自动回到普通采集,画面不会断,那行会写原因。+- **作者手上没有美乐威卡,这个功能完全没在真卡上跑过。** 请有 Pro Capture 的群友测:能不能出画面、颜色对不对、开关前后延迟手感、音画是否同步、长时间是否稳定;+ 日志 `logseyra-qml.log` 搜 `magewell` 发给我。++其余内容与 beta 4 相同(见下)。++---+++## beta 4 相对 beta 3 的修改(根据双机测试反馈)++- **PC 串流一顿一顿、帧率上不去**:根因是选 AV1 时实际一直在用单线程软件解码(每帧 25–36 ms,跟不上 60 帧,解码队列反复溢出)。+ 现在 AV1 / H.264 走 D3D12 硬件解码,HEVC 走 D3D11 硬件解码(原来 HEVC 4K 硬解会失败)。本机 150 Mbps 测试流 1080p/4K 都稳定 60 帧。+- **码率**:默认 150 Mbps,设置里改成滑块,5–500 Mbps 任意调。有线千兆可以拉到 300–500;无线卡顿就调低。+ 主机画面简单时实际码率会远低于上限,这是编码器正常行为。统计浮层(Ctrl+Alt+Shift+S)现在显示**实际码率**和收/解帧率。+- **第二次要重新配对、配完连不上**:软件把局域网发现时主机的"未配对"(Sunshine 对不带证书的查询一律这么回答)当真了。已修复。+ **已经遇到这个问题的电脑**:先在主机 Sunshine 网页的已配对列表里删掉旧的 Veyra,再在本机删除主机、重新配对一次,以后就不会再丢。+- **退出时偶尔崩溃**:转储指向 NVIDIA Reflex 关闭时卸载了 nvapi,已改为不再卸载。如果还崩,请继续发 `veyra-crash-*.dmp`。+- **开光流后 1440p 只有 52 帧**:查过了,不是新 bug。RTX 5060 Ti 上 NR 内部 1440p 一项就要约 15 ms,光流再加 2.5 ms,超过 60 帧的 16.7 ms;+ 1.4.4 开 NR 时也总是跑光流。建议 NR 内部分辨率用 1080p(NR 9 ms + 光流 2 ms,稳 60),或者光流后端换成 AMD(约 0.5 ms)。+- **玩一段时间掉到 10 帧**:还没定位。日志现在每秒记录显存占用;再出现时请记下时间、看一下显卡温度和频率,并发日志。+- 聊天截图里有一条关于**鼠标**的问题,图太小看不清,请再描述一次。++详细排查记录见包内 `docs/STREAM_FIELD_FIXES_2026-10-01.md`。++---+++本包(与 beta 3 相同)在 2.0.0 beta 的基础上新增 **PC 串流** 和 **Xbox 串流**(见文末)。PC 串流:把另一台电脑(装了 Sunshine 的主机)的画面串流到本机播放,+再交给软件自己的降噪、超分、补帧和调色。**这是第一次接入,只在没有真实主机的情况下做过离线测试,+请有两台电脑的测试者重点验证。**其余功能与 2.0.0 beta 相同,见同目录 `RELEASE_NOTES.md`。++新界面程序是 `veyra_qml_ui.exe`,整个文件夹可拷到别的电脑运行,设置和日志都在这个文件夹里。+PC 串流的主机列表、设置和配对身份存在 `%LOCALAPPDATA%\Veyra\moonlight\`(身份文件用 Windows DPAPI 加密)。++## 准备(两台电脑)++1. **被串流的电脑(主机)**:安装 [Sunshine](https://app.lizardbyte.dev/Sunshine)(本软件不自带,也不代为下载)。+ 显卡需要能硬件编码(NVIDIA / AMD / Intel 均可)。在 Sunshine 网页(`https://主机IP:47990`)里确认有「Desktop」或游戏条目。+2. **播放的电脑(本机)**:两台电脑在同一个局域网,最好有线。主机防火墙放行 Sunshine(安装时默认处理)。+3. 打开本软件 → 首页 **「PC 串流」** 卡(或专业/节点页的片源菜单 → PC 串流…)。++## 测试步骤++1. 主机应自动出现在列表里(没有就在「手动添加」填它的 IP)。状态为「未配对」。+2. 点「配对」:软件显示 4 位 PIN;到主机的 Sunshine 网页 → **PIN** 页,输入这个 PIN 并提交。成功后出现游戏列表。+3. 选「Desktop」或一个游戏,点「开始串流」。先用默认设置(1080p · 60 fps · 150 Mbps · 自动编码)。+4. 连上后:画面是否出现、声音是否正常、键盘鼠标是否在主机上生效(连上后键鼠会自动交给主机)、手柄是否可用、手柄震动是否回传。+5. 键盘鼠标被主机占用时:**Ctrl+Alt+Shift+Z 释放**,点击画面重新捕获,**Ctrl+Alt+Shift+Q 断开**,**Ctrl+Alt+Shift+S** 显示/隐藏统计浮层。+6. 在专业页打开 NR / 超分 / 补帧,看串流画面能否正常增强(补帧默认是关的,和其它片源一样由你打开)。+7. 再试:4K · 60 fps、HEVC、AV1、HDR(主机显示器需开 HDR,编码选 HEVC 或 AV1)、5.1 声道、断开后再「继续」同一个游戏。+8. 局域网内故意拔网线几秒再接上,看是否报错、是否能重连(**重连还没有做,预期是报「连接中断」,请记录现象**)。++## 请重点记录++- 能否连上、从点「开始串流」到出画面要几秒;+- 延迟感受(画面里的鼠标移动、按键反应);统计浮层里的「主机 / 往返 / 接收 / 排队 / 解码」各几毫秒;+- 4K60 是否稳定,FEC「未恢复」包数和丢帧数是否持续增长;+- HDR 颜色是否正确(和主机屏幕对比);+- 任何崩溃、卡死、花屏、声音断续。++## 反馈时请附上++- 主机:显卡型号、Sunshine 版本、编码器(Sunshine 网页里看);本机:显卡、驱动、Windows 版本;+- `logs\veyra-qml.log`(出问题后先退出软件再拷,搜 `moonlight`);+- 统计浮层截图或录屏。++## 已知情况与限制++- **未在真实 Sunshine 上验证过任何串流**:连接、画面、声音、输入、HDR、4K60 都是未知数,这正是本次要测的。+ 离线只验证了协议解析、配对、界面流程和输入转换。+- 设备名以「Veyra」向主机报到;若某个主机拒绝配对或在它的已配对列表里显示异常,请告诉我主机软件和版本。+- 没有做:断线自动重连、陀螺仪与触摸板、多手柄、扳机震动、游戏封面图、Windows 键/Alt+Tab 的捕获(这些仍归系统)。+- 解码用硬件(AV1/H.264 用 D3D12VA,HEVC 用 D3D11VA);显卡不支持该编码时自动退回软件解码,但软件解码在高码率下跟不上 60 帧,只输出 8 位,HDR 需要硬解。+- AV1 只在你明确选择时才使用;「自动」只在 HEVC 与 H.264 之间选。+- 「让主机切换到串流分辨率」默认关:主机保持自己的分辨率,画面由主机缩放。+- 补帧优化内核和社区 NR 运行库仍是实验组件,见 2.0.0 beta 说明;仅供内部测试,请勿外传。+++---++# Xbox 串流(非官方、实验)++在首页点 **「Xbox 串流」**(或片源菜单 → Xbox 串流…)。串流的是**你自己的** Xbox 主机,画面同样交给软件的降噪/超分/补帧/调色。++**非官方**:与 Greenlight 等开源客户端相同的方式连接微软的串流服务,不隶属于微软;微软随时可能改动导致失效。账号风险由使用者自行承担(你已确认接受)。++## 准备++1. 主机:用你的账号登录;**设置 → 设备和连接 → 远程功能** 里打开"启用远程功能";电源模式选"睡眠"(即时启动)才能被远程唤醒。+2. 本机和主机最好在同一个局域网(有线更好)。开着代理/加速器/TUN 的电脑也可以,软件已经处理了这类网卡带来的一个连接问题;如果仍连不上,先试着关掉代理再连。++## 步骤++1. 点「登录」:对话框显示一个登录码。用手机或浏览器打开 **microsoft.com/link**,输入登录码,用你的 Xbox(微软)账号登录。软件看不到你的密码;登录信息加密保存在本机,"退出登录"会删除它。+2. 登录后自动列出账号下的主机(型号、电源状态)。选一台,点「开始串流」。主机在睡眠时会被唤醒,可能要等十几秒。+3. 连上后:画面、声音、手柄(默认把电脑手柄当作主机手柄)、震动。Ctrl+Alt+Shift+S 显示统计(往返、解码、码率、丢帧)。+4. 在专业页打开 NR / 超分 / 补帧,看画面能否正常增强。++## 请记录并反馈++- 登录是否成功;主机能否列出;从"开始串流"到出画面要几秒;+- 画面分辨率(统计浮层第一行)、码率、延迟感受;手柄和震动是否正常;+- 任何错误提示的原文、崩溃、卡死。+- 日志:`logs\veyra-qml.log`,搜 `xbox`。连不上时,用环境变量 `VEYRA_XBOX_RTC_DEBUG=1` 启动一次(详细网络日志,含本机局域网地址,发给我前可以自行查看)。++## 已知情况++- **从未在真实账号和主机上测试过**:除了"微软能正常给出登录码"这一步,登录后的每一步都是第一次见真机。这正是本次要测的。+- 只协商 H.264(参考客户端的做法),通常最高 1080p60,画质不如 PC 串流。+- 不支持:键盘鼠标、多手柄、语音聊天、云游戏(xCloud)。+- 断线不会自动重连,需要重新开始。diff --git a/include/veyra/source/MagewellCapture.h b/include/veyra/source/MagewellCapture.hnew file mode 100644index 00000000..abddc0e5--- /dev/null+++ b/include/veyra/source/MagewellCapture.h@@ -0,0 +1,78 @@+#pragma once+// Magewell Pro Capture low-latency video (MWCapture SDK, "low latency mode + partial notify").+//+// Magewell's PCIe Pro Capture cards can start the DMA of a frame after the first 64-256 lines+// have reached the card instead of after the whole frame, so the frame is complete in host+// memory almost as soon as its last line arrives (Magewell: 1080p60 capture latency ~21.7 ms ->+// ~17 ms, 4K60 ~37.6 ms -> ~22.6 ms). DirectShow cannot ask for that; the vendor SDK can.+// USB Capture models and first-generation cards do not support it.+//+// LibMWCapture.dll is loaded at run time (runtime\magewell next to the program first, then the+// system), so builds and machines without it simply keep the ordinary DirectShow capture.+// Calling sequence follows the SDK's Examples\Applications\LowLatency.+#include <cstdint>+#include <functional>+#include <memory>+#include <string>+#include <string_view>++namespace veyra::source::magewell {++// The DirectShow device path of a Magewell PCIe card (PCI vendor 0x1CD7). USB Capture models+// enumerate as USB devices and are deliberately excluded: they have no low-latency mode.+bool isProCaptureDevicePath(std::wstring_view directShowPath);++// True when this build knows the SDK and LibMWCapture.dll could be loaded. `detail` says+// which file was used or why not.+bool runtimeAvailable(std::wstring* detail = nullptr);++// The user's choice (capture dialog). Read when a capture device is connected.+void setLowLatencyPreference(bool enabled);+bool lowLatencyPreference();++// One line for the capture dialog: active with its measured latency, or why it is not active.+std::wstring statusText();++// Pixel formats the SDK can write in the layout the capture path already expects.+enum class Format : uint8_t { Nv12, Yuy2, P010, Bgra };++struct VideoRequest {+ std::wstring directShowPath; // the device the user picked+ Format format = Format::Nv12;+ unsigned width = 0, height = 0;+ unsigned stride = 0; // bytes per luma/packed row, as the capture layout expects+ size_t frameBytes = 0; // whole frame in that layout+ bool bottomUp = false; // RGB DIB orientation of the layout+ int partialLines = 64; // DMA starts after this many lines (64/128/256)+};++struct VideoStats {+ uint64_t frames = 0, timeouts = 0, signalChanges = 0;+ double frameStartToHostMs = 0; // average: frame started arriving -> whole frame in host memory+};++class LowLatencyVideo {+public:+ // data/bytes: one complete frame; deviceSeconds: when the frame started arriving (card clock);+ // discontinuity: the signal changed or frames were skipped since the previous call.+ using Deliver = std::function<void(const uint8_t* data, size_t bytes, double deviceSeconds, bool discontinuity)>;++ LowLatencyVideo();+ ~LowLatencyVideo();+ LowLatencyVideo(const LowLatencyVideo&) = delete;+ LowLatencyVideo& operator=(const LowLatencyVideo&) = delete;++ // Opens the matching SDK channel and starts the capture thread. False (with `error`) means+ // the caller keeps using DirectShow for video.+ bool start(const VideoRequest& request, Deliver deliver, std::wstring& error);+ void stop();+ bool running() const;+ VideoStats stats() const;++private:+ bool startImpl(const VideoRequest& request, Deliver deliver, std::wstring& error);+ struct Impl;+ std::unique_ptr<Impl> p_;+};++} // namespace veyra::source::magewelldiff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 71be84e6..b138127a 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -125,6 +125,10 @@ class QmlPlayerBridge : public QObject {Q_PROPERTY(int captureBufferMode READ captureBufferMode WRITE setCaptureBufferMode NOTIFY settingsChanged)Q_PROPERTY(bool captureQueryBusy READ captureQueryBusy NOTIFY captureChanged)Q_PROPERTY(QString captureStatus READ captureStatus NOTIFY captureChanged)+ // Magewell Pro Capture low-latency mode (MagewellCapture.h): whether the selected device is+ // one, and a one-line state (active with its latency, missing runtime, or why it fell back).+ Q_PROPERTY(bool captureMagewellDevice READ captureMagewellDevice NOTIFY captureChanged)+ Q_PROPERTY(QString captureMagewellStatus READ captureMagewellStatus NOTIFY snapshotChanged)// --- screen-capture dialog ---------------------------------------------Q_PROPERTY(QVariantList screenTargets READ screenTargets NOTIFY captureChanged)@@ -485,6 +489,8 @@ public:void setCaptureDeviceId(const QString& value);QString captureDeviceLabel() const;bool captureForceSdr() const;+ bool captureMagewellDevice() const;+ QString captureMagewellStatus() const;void setCaptureForceSdr(bool value);bool captureFlipVertical() const;void setCaptureFlipVertical(bool value);diff --git a/licenses/magewell/MWCapture-SDK-NOTICE.txt b/licenses/magewell/MWCapture-SDK-NOTICE.txtnew file mode 100644index 00000000..b9bb2875--- /dev/null+++ b/licenses/magewell/MWCapture-SDK-NOTICE.txt@@ -0,0 +1,37 @@+Magewell MWCapture SDK (Windows 3.3.1.1596) - notice for the header files and library used by Veyra++Veyra compiles its Magewell Pro Capture low-latency path (src/source/MagewellCapture.cpp) against+the SDK header files and loads LibMWCapture.dll at run time; the beta packages carry that+library unmodified in runtime\magewell\LibMWCapture.dll+(SHA-256 360259C46A0F62713EF9FCAD2B403596EF007AC04D9B37A1E9C949C8459B92F9, version 3.3.1.1596).+The header files are not part of the Veyra source tree.++The licence printed in the SDK's header files and examples, reproduced as required:++ MAGEWELL PROPRIETARY INFORMATION++ The following license only applies to head files and library within Magewell's SDK+ and not to Magewell's SDK as a whole.++ Copyrights (c) Nanjing Magewell Electronics Co., Ltd. ("Magewell") All rights reserved.++ Magewell grands to any person who obtains the copy of Magewell's head files and library+ the rights,including without limitation, to use, modify, publish, sublicense, distribute+ the Software on the conditions that all the following terms are met:+ - The above copyright notice shall be retained in any circumstances.+ -The following disclaimer shall be included in the software and documentation and/or+ other materials provided for the purpose of publish, distribution or sublicense.++ THE SOFTWARE IS PROVIDED BY MAGEWELL "AS IS" AND ANY EXPRESS, INCLUDING BUT NOT LIMITED TO,+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.+ IN NO EVENT SHALL MAGEWELL BE LIABLE++ FOR ANY CLAIM, DIRECT OR INDIRECT DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT,+ TORT OR OTHERWISE, ARISING IN ANY WAY OF USING THE SOFTWARE.++ CONTACT INFORMATION:+ http://www.magewell.com/++Source: https://www.magewell.cn/downloads (Magewell_Capture_SDK_Windows_3.3.1.1596.zip,+SHA-256 B463EE004050C05F06BD2A0BA0B906C2CA4D5D4D65F57D4E9DA57E00B2096C5A, downloaded 2026-10-01).diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex 900ae6f2..20b37319 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -329,6 +329,21 @@ Item {onPicked: id => veyra.captureFormatKey = id}}+ VRow {+ objectName: "capture-magewell-row"+ label: "美乐威低延迟模式"+ hint: !veyra.captureMagewellDevice+ ? "仅美乐威 Pro Capture(PCIe 内置卡)可用;USB Capture 系列不支持"+ : (veyra.captureMagewellStatus.length > 0 ? veyra.captureMagewellStatus + " · " : "")+ + "采集卡收到 64 行就开始传,整帧更早到达(官方:1080p60 约省 5 ms,4K60 约省 15 ms)。开关后点「连接」重新连接生效"+ VSwitch {+ objectName: "capture-magewell"+ enabled: veyra.captureMagewellDevice+ opacity: enabled ? 1 : 0.35+ checked: veyra.captureMagewellDevice && veyra.preferences.magewellLowLatency === true+ onToggled: veyra.setPreference("magewellLowLatency", checked)+ }+ }VRow {label: "设备帧率 FPS"hint: "0 = 沿用所选格式;设备返回其他帧率会报错,不在软件中偷偷丢帧"diff --git a/scripts/moonlight/make-beta.py b/scripts/moonlight/make-beta.pyindex d145e5ba..3b3587e8 100644--- a/scripts/moonlight/make-beta.py+++ b/scripts/moonlight/make-beta.py@@ -42,15 +42,21 @@ shutil.copytree(build / 'qml/Veyra', pkg / 'qml/Veyra')for name in ('LICENSE', 'THIRD_PARTY_NOTICES.md'):shutil.copy2(repo / name, pkg / name)(pkg / 'docs').mkdir(exist_ok=True)-for name in ('MOONLIGHT_EXECUTION_2026-10-01.md', 'STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md', 'XBOX_EXECUTION_2026-10-01.md', 'STREAM_FIELD_FIXES_2026-10-01.md'):+for name in ('MOONLIGHT_EXECUTION_2026-10-01.md', 'STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md', 'XBOX_EXECUTION_2026-10-01.md', 'STREAM_FIELD_FIXES_2026-10-01.md', 'MAGEWELL_LOW_LATENCY_2026-10-01.md'):if (repo / 'docs' / name).exists():shutil.copy2(repo / 'docs' / name, pkg / 'docs' / name)shutil.copy2(repo / notes, pkg / '测试说明.md')(pkg / 'licenses').mkdir(exist_ok=True)-for sub in ('moonlight', 'xbox'):+for sub in ('moonlight', 'xbox', 'magewell'):if (repo / 'licenses' / sub).exists():shutil.copytree(repo / 'licenses' / sub, pkg / 'licenses' / sub, dirs_exist_ok=True)+# Magewell Pro Capture low-latency mode: the SDK library, unmodified (see licenses/magewell).+magewell = Path('E:/项目/Veyra/deps/magewell/3.3.1.1596/bin/x64/LibMWCapture.dll')+if magewell.exists():+ (pkg / 'runtime/magewell').mkdir(parents=True, exist_ok=True)+ shutil.copy2(magewell, pkg / 'runtime/magewell/LibMWCapture.dll')+mf = pkg / 'runtime/experimental/release-runtime-manifest.json'if mf.exists():manifest = json.loads(mf.read_text(encoding='utf-8-sig'))diff --git a/scripts/moonlight/ui-demo.py b/scripts/moonlight/ui-demo.pyindex 8e587f99..64cee3cb 100644--- a/scripts/moonlight/ui-demo.py+++ b/scripts/moonlight/ui-demo.py@@ -45,19 +45,25 @@ def find_window(pid):def visit(hwnd, _):owner = ctypes.c_ulong()user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))- if owner.value == pid and user32.IsWindowVisible(hwnd):+ if owner.value == pid and user32.IsWindowVisible(hwnd) and not user32.IsIconic(hwnd):rect = RECT()user32.GetWindowRect(hwnd, ctypes.byref(rect))if rect.r - rect.l > 400:found.append((hwnd, rect))return Trueuser32.EnumWindows(visit, 0)+ # The main window is the largest one; the native video window and tool windows are smaller.+ found.sort(key=lambda w: (w[1].r - w[1].l) * (w[1].b - w[1].t), reverse=True)return found[0] if found else Nonedef screenshot(pid, path):win = find_window(pid)if not win:+ time.sleep(1.0) # the window can be between two states (dialog animation, region update)+ win = find_window(pid)+ if not win:+ print(' no window for pid', pid, 'alive' if app_proc and app_proc.poll() is None else 'exited')return Falsehwnd, rect = win# PrintWindow(PW_RENDERFULLCONTENT) reads the window's own composed content, so another@@ -79,7 +85,15 @@ def screenshot(pid, path):gdi32.DeleteObject(bitmap)gdi32.DeleteDC(memory_dc)user32.ReleaseDC(ctypes.c_void_p(hwnd), window_dc)- return bool(printed)+ if not printed:+ # Fall back to the screen pixels (correct whenever nothing covers the window).+ ps = ('Add-Type -AssemblyName System.Drawing; '+ f'$b = New-Object System.Drawing.Bitmap({width},{height}); '+ '$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 Trueresult = 1diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 7df5f61b..7e71a4e1 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -36,6 +36,7 @@ extern "C" {#include <mutex>#include <condition_variable>#include <atomic>+#include <optional>#include <format>#include <chrono>#include "veyra/source/CaptureAudioClock.h"@@ -46,6 +47,7 @@ extern "C" {#include <libavutil/frame.h>#include <libavutil/pixfmt.h>}+#include "veyra/source/MagewellCapture.h"namespace veyra::source {using Microsoft::WRL::ComPtr;namespace {@@ -366,6 +368,42 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {std::wstring audioError;AudioInputRecovery audioRecovery;SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;+ // Magewell Pro Capture low-latency video (MagewellCapture.h). While it runs, the DirectShow+ // video samples are ignored and its frames enter the same native mailbox below; if it stops+ // on its own, DirectShow delivery resumes by itself.+ std::unique_ptr<magewell::LowLatencyVideo> magewell;+ magewell::VideoRequest magewellRequest;bool magewellWanted=false;+ std::atomic<bool> magewellDelivering{false}; // set after start, cleared before stop+ bool externalTimeAnchored=false;double externalTimeOffset=0;+ void deliverExternal(const uint8_t* data,size_t bytes,double deviceSeconds,bool discontinuity){+ const auto arrival=Clock::now();+ AVFrame* staged=nullptr;bool written=false;+ {std::lock_guard lock(mutex);if(stagingFrame&&!stagingBusy){stagingBusy=true;staged=stagingFrame;}}+ if(staged)written=writeCaptureFrame(layout,data,bytes,*staged,verticalFlip.load());+ {+ std::lock_guard lock(mutex);+ if(staged)stagingBusy=false;+ if(!staged||!written||!pendingFrame){++dropped;return;}+ // Continue the stream's timeline from the last DirectShow sample instead of jumping+ // to the card's clock, so the audio mapping and cadence checks see one timeline.+ if(!externalTimeAnchored){+ externalTimeOffset=(received?pendingTime+(nominalDuration100ns>0?double(nominalDuration100ns)/1e7:1.0/60):0.0)-deviceSeconds;+ externalTimeAnchored=true;+ }+ const double time=deviceSeconds+externalTimeOffset;+ std::swap(stagingFrame,pendingFrame);+ if(pending)++dropped;+ pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,discontinuity,received>0,pendingTime,time,info.averageFps);+ pending=true;pendingTime=time;pendingArrival=arrival;+ pendingDuration=captureDuration(0,0,false,nominalDuration100ns);+ if(!received)firstArrival=arrival;+ ++received;latestArrival=arrival;+ recentArrivals.push_back(arrival);+ while(recentArrivals.size()>1&&(recentArrivals.size()>1024||arrival-recentArrivals.front()>std::chrono::seconds(2)))recentArrivals.pop_front();+ }+ wake.notify_one();+ if(frameEvent)SetEvent(frameEvent);+ }HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}// Decode worker loop: pop a compressed payload, decode it with our own@@ -487,6 +525,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {}}HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{+ if(!compressedPath&&magewellDelivering.load()&&magewell->running())return S_OK; // the SDK delivers video// Register the DirectShow delivery thread with MMCSS once; the handle// lives for the thread (revert happens when the thread exits).static thread_local HANDLE mmcss=[]{DWORD index=0;HANDLE h=AvSetMmThreadCharacteristicsW(L"Pro Audio",&index);if(!h)log::warn("capture","MMCSS unavailable for the capture callback thread");return h;}();(void)mmcss;@@ -997,6 +1036,25 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cle}}p.elgatoHdr=std::move(elgatoHdr);+ p.magewellWanted=false;+ if(magewell::lowLatencyPreference()&&magewell::isProCaptureDevicePath(devicePath)){+ const auto& l=p.layout;+ const bool semiplanarOk=l.chromaOffset==size_t(l.stride)*l.height&&l.chromaStride==l.stride;+ std::optional<magewell::Format> mw;+ if(compressedPath||!direct)mw.reset();+ else if(l.packing==CapturePacking::Nv12&&semiplanarOk)mw=magewell::Format::Nv12;+ else if(l.packing==CapturePacking::P010&&semiplanarOk)mw=magewell::Format::P010;+ else if(l.packing==CapturePacking::Yuy2)mw=magewell::Format::Yuy2;+ else if(l.packing==CapturePacking::Bgr32||l.packing==CapturePacking::Bgra32)mw=magewell::Format::Bgra;+ if(mw){+ p.magewellRequest={};p.magewellRequest.directShowPath=devicePath;p.magewellRequest.format=*mw;+ p.magewellRequest.width=l.width;p.magewellRequest.height=l.height;p.magewellRequest.stride=l.stride;+ p.magewellRequest.frameBytes=l.sampleBytes;p.magewellRequest.bottomUp=l.bottomUp;p.magewellRequest.partialLines=64;+ p.magewellWanted=true;+ }else{+ log::warn("magewell",std::format("low latency not available for this capture format (packing={} compressed={}); using DirectShow",int(l.packing),compressedPath));+ }+ }p.configured=true;reconnectDesc_=desc;reconnectInfo_=p.info;reconnectFormat_=selectedKey;// Log the upstream type after DirectShow has finished negotiation. The@@ -1315,6 +1373,15 @@ bool CaptureCardSource::start(){p.audioRecovery.reset(GetTickCount64());p.lastFrame=Impl::Clock::now();const auto hr=p.control->Run();p.info.opened=SUCCEEDED(hr);if(p.info.opened&&p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";+ if(p.info.opened&&p.magewellWanted){+ p.externalTimeAnchored=false;+ p.magewell=std::make_unique<magewell::LowLatencyVideo>();+ std::wstring why;+ if(!p.magewell->start(p.magewellRequest,[&p](const uint8_t* data,size_t bytes,double t,bool d){p.deliverExternal(data,bytes,t,d);},why)){+ log::warn("magewell",std::format("low latency not started; DirectShow video continues ({})",narrowForLog(why)));+ p.magewell.reset();+ }else p.magewellDelivering=true;+ }veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} nominalFps={:.3f} mailbox=1 ownedBuffers=2",unsigned(hr),p.info.width,p.info.height,p.info.averageFps));return p.info.opened;}void CaptureCardSource::recoverAudio(float gain,unsigned syncMode,int offsetMs){@@ -1436,7 +1503,9 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c*frame=delivered;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;}void CaptureCardSource::close()noexcept{- auto& p=*p_;if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}+ auto& p=*p_;+ p.magewellDelivering=false;+ if(p.magewell){p.magewell->stop();p.magewell.reset();}if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}if(p.wasapi)p.wasapi->stop();p.wasapi.reset();p.elgatoHdr.reset();p.averMediaSwitch.stop();p.embeddedAudioUnavailable=false;diff --git a/src/source/MagewellCapture.cpp b/src/source/MagewellCapture.cppnew file mode 100644index 00000000..08c185ec--- /dev/null+++ b/src/source/MagewellCapture.cpp@@ -0,0 +1,376 @@+#include "veyra/source/MagewellCapture.h"++#include <windows.h>+#include <avrt.h>++#include <algorithm>+#include <atomic>+#include <chrono>+#include <cwctype>+#include <filesystem>+#include <format>+#include <mutex>+#include <thread>+#include <vector>++#include "veyra/Log.h"++#ifdef VEYRA_HAS_MAGEWELL+// Magewell's own headers (MWCapture SDK 3.3.1.1596, kept outside the source tree under+// deps/magewell). Their licence lets the header files and library be used, modified and+// redistributed with Magewell's copyright notice and disclaimer; see THIRD_PARTY_NOTICES.md.+#include <LibMWCapture/MWCapture.h>+#endif++namespace veyra::source::magewell {++namespace {++std::atomic<bool> g_preference{false};+// What the capture dialog shows (statusText()).+std::mutex g_statusMutex;+std::wstring g_lastError;+std::atomic<bool> g_active{false};+std::atomic<double> g_latencyMs{0};++void setLastError(std::wstring text) {+ std::lock_guard lock(g_statusMutex);+ g_lastError = std::move(text);+}++std::string narrow(const std::wstring& text) {+ if (text.empty()) return {};+ const int size = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), int(text.size()), nullptr, 0, nullptr, nullptr);+ std::string out(size_t(std::max(size, 0)), '\0');+ if (size > 0) WideCharToMultiByte(CP_UTF8, 0, text.c_str(), int(text.size()), out.data(), size, nullptr, nullptr);+ return out;+}++std::wstring lower(std::wstring_view text) {+ std::wstring out(text);+ for (auto& c : out) c = wchar_t(std::towlower(c));+ return out;+}++// "\\?\pci#ven_1cd7&dev_0010&...#4&2b0f...&0&00e0#{guid}\global" -> "pci#ven_1cd7&dev_0010&...#4&2b0f...&0&00e0"+std::wstring instanceOf(std::wstring_view path) {+ std::wstring text = lower(path);+ if (text.starts_with(L"\\\\?\\")) text.erase(0, 4);+ if (const auto guid = text.find(L"#{"); guid != std::wstring::npos) text.erase(guid);+ return text;+}++std::filesystem::path programDirectory() {+ wchar_t buffer[MAX_PATH * 4]{};+ const DWORD length = GetModuleFileNameW(nullptr, buffer, DWORD(std::size(buffer)));+ return std::filesystem::path(std::wstring(buffer, length)).parent_path();+}++#ifdef VEYRA_HAS_MAGEWELL+struct Api {+ HMODULE module = nullptr;+ std::wstring where;+ bool ready = false;+ decltype(&MWCaptureInitInstance) initInstance = nullptr;+ decltype(&MWRefreshDevice) refreshDevice = nullptr;+ decltype(&MWGetChannelCount) channelCount = nullptr;+ decltype(&MWGetChannelInfoByIndex) channelInfo = nullptr;+ decltype(&MWGetDevicePath) devicePath = nullptr;+ decltype(&MWOpenChannelByPath) openChannel = nullptr;+ decltype(&MWCloseChannel) closeChannel = nullptr;+ decltype(&MWPinVideoBuffer) pinBuffer = nullptr;+ decltype(&MWUnpinVideoBuffer) unpinBuffer = nullptr;+ decltype(&MWStartVideoCapture) startCapture = nullptr;+ decltype(&MWStopVideoCapture) stopCapture = nullptr;+ decltype(&MWGetVideoBufferInfo) bufferInfo = nullptr;+ decltype(&MWGetVideoFrameInfo) frameInfo = nullptr;+ decltype(&MWGetVideoSignalStatus) signalStatus = nullptr;+ decltype(&MWRegisterNotify) registerNotify = nullptr;+ decltype(&MWUnregisterNotify) unregisterNotify = nullptr;+ decltype(&MWGetNotifyStatus) notifyStatus = nullptr;+ decltype(&MWGetDeviceTime) deviceTime = nullptr;+ decltype(&MWCaptureVideoFrameToVirtualAddressEx) captureFrame = nullptr;+ decltype(&MWGetVideoCaptureStatus) captureStatus = nullptr;+};++// Loaded once and kept for the life of the process (the SDK instance is never torn down).+Api& api() {+ static Api a = [] {+ Api x;+ const auto bundled = programDirectory() / L"runtime" / L"magewell" / L"LibMWCapture.dll";+ if (std::filesystem::exists(bundled)) {+ x.module = LoadLibraryExW(bundled.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);+ if (x.module) x.where = bundled.wstring();+ }+ if (!x.module) {+ // Installed by Magewell's own software (driver / SDK runtime).+ x.module = LoadLibraryExW(L"LibMWCapture.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);+ if (x.module) x.where = L"LibMWCapture.dll (system)";+ }+ if (!x.module) { x.where = L"LibMWCapture.dll not found"; return x; }+ bool all = true;+ const auto bind = [&](auto& slot, const char* name) {+ slot = reinterpret_cast<std::remove_reference_t<decltype(slot)>>(GetProcAddress(x.module, name));+ if (!slot) { all = false; log::error("magewell", std::format("missing export {}", name)); }+ };+ bind(x.initInstance, "MWCaptureInitInstance");+ bind(x.refreshDevice, "MWRefreshDevice");+ bind(x.channelCount, "MWGetChannelCount");+ bind(x.channelInfo, "MWGetChannelInfoByIndex");+ bind(x.devicePath, "MWGetDevicePath");+ bind(x.openChannel, "MWOpenChannelByPath");+ bind(x.closeChannel, "MWCloseChannel");+ bind(x.pinBuffer, "MWPinVideoBuffer");+ bind(x.unpinBuffer, "MWUnpinVideoBuffer");+ bind(x.startCapture, "MWStartVideoCapture");+ bind(x.stopCapture, "MWStopVideoCapture");+ bind(x.bufferInfo, "MWGetVideoBufferInfo");+ bind(x.frameInfo, "MWGetVideoFrameInfo");+ bind(x.signalStatus, "MWGetVideoSignalStatus");+ bind(x.registerNotify, "MWRegisterNotify");+ bind(x.unregisterNotify, "MWUnregisterNotify");+ bind(x.notifyStatus, "MWGetNotifyStatus");+ bind(x.deviceTime, "MWGetDeviceTime");+ bind(x.captureFrame, "MWCaptureVideoFrameToVirtualAddressEx");+ bind(x.captureStatus, "MWGetVideoCaptureStatus");+ if (!all) { x.where += L" (incomplete exports)"; return x; }+ x.ready = x.initInstance() != FALSE;+ if (!x.ready) x.where += L" (MWCaptureInitInstance failed)";+ log::info("magewell", std::format("runtime {} ready={}", narrow(x.where), x.ready));+ return x;+ }();+ return a;+}++DWORD fourccOf(Format format) {+ switch (format) {+ case Format::Nv12: return MWFOURCC_NV12;+ case Format::Yuy2: return MWFOURCC_YUY2;+ case Format::P010: return MWFOURCC_P010;+ case Format::Bgra: return MWFOURCC_BGRA;+ }+ return 0;+}+#endif++} // namespace++bool isProCaptureDevicePath(std::wstring_view directShowPath) {+ return lower(directShowPath).find(L"ven_1cd7") != std::wstring::npos;+}++bool runtimeAvailable(std::wstring* detail) {+#ifdef VEYRA_HAS_MAGEWELL+ auto& a = api();+ if (detail) *detail = a.where;+ return a.ready;+#else+ if (detail) *detail = L"this build has no Magewell SDK support";+ return false;+#endif+}++void setLowLatencyPreference(bool enabled) {+ if (g_preference.exchange(enabled) != enabled)+ log::info("magewell", std::format("low-latency preference={} (takes effect on the next connect)", enabled));+}+bool lowLatencyPreference() { return g_preference.load(); }++std::wstring statusText() {+ if (g_active.load()) {+ const double ms = g_latencyMs.load();+ return ms > 0 ? std::format(L"低延迟采集中 · 一帧从开始进卡到完整进内存 {:.1f} ms", ms) : std::wstring(L"低延迟采集中");+ }+ std::lock_guard lock(g_statusMutex);+ return g_lastError.empty() ? std::wstring() : L"未启用:" + g_lastError;+}++struct LowLatencyVideo::Impl {+ VideoRequest request;+ Deliver deliver;+ std::thread thread;+ HANDLE stopEvent = nullptr;+ std::atomic<bool> running{false};+ mutable std::mutex statsMutex;+ VideoStats stats;+#ifdef VEYRA_HAS_MAGEWELL+ HCHANNEL channel = nullptr;+ void loop();+#endif+};++LowLatencyVideo::LowLatencyVideo() : p_(std::make_unique<Impl>()) {}+LowLatencyVideo::~LowLatencyVideo() { stop(); }+bool LowLatencyVideo::running() const { return p_->running.load(); }+VideoStats LowLatencyVideo::stats() const { std::lock_guard lock(p_->statsMutex); return p_->stats; }++bool LowLatencyVideo::start(const VideoRequest& request, Deliver deliver, std::wstring& error) {+ stop();+ const bool ok = startImpl(request, std::move(deliver), error);+ setLastError(ok ? std::wstring() : error);+ return ok;+}++bool LowLatencyVideo::startImpl(const VideoRequest& request, Deliver deliver, std::wstring& error) {+#ifdef VEYRA_HAS_MAGEWELL+ auto& a = api();+ if (!a.ready) { error = L"没有可用的美乐威运行库(" + a.where + L")"; return false; }+ if (!request.width || !request.height || !request.stride || !request.frameBytes) { error = L"采集格式无效"; return false; }+ a.refreshDevice();+ const int count = a.channelCount();+ const std::wstring wantedPath = lower(request.directShowPath), wantedInstance = instanceOf(request.directShowPath);+ int exact = -1, byInstance = -1, proCount = 0, onlyPro = -1, instanceMatches = 0;+ for (int i = 0; i < count; ++i) {+ MWCAP_CHANNEL_INFO info{};+ if (a.channelInfo(i, &info) != MW_SUCCEEDED) continue;+ wchar_t path[MAX_PATH * 2]{};+ if (a.devicePath(i, path) != MW_SUCCEEDED) continue;+ const bool pro = info.wFamilyID == MW_FAMILY_ID_PRO_CAPTURE;+ log::info("magewell", std::format("channel {} family={} product={} board={} channel={} path={}", i, info.wFamilyID,+ info.szProductName, int(info.byBoardIndex), int(info.byChannelIndex), narrow(path)));+ if (!pro) continue;+ ++proCount; onlyPro = i;+ if (lower(path) == wantedPath) exact = i;+ if (instanceOf(path) == wantedInstance) { byInstance = i; ++instanceMatches; }+ }+ int chosen = exact >= 0 ? exact : instanceMatches == 1 ? byInstance : -1;+ if (chosen < 0 && proCount == 1) {+ chosen = onlyPro;+ log::warn("magewell", "no channel path matched the DirectShow device; using the only Pro Capture channel");+ }+ log::info("magewell", std::format("directshow path={} chosen channel={} (exact={} instance={}x{} pro={})",+ narrow(request.directShowPath), chosen, exact, byInstance, instanceMatches, proCount));+ if (chosen < 0) { error = L"找不到与所选设备对应的美乐威 Pro Capture 通道"; return false; }+ wchar_t path[MAX_PATH * 2]{};+ a.devicePath(chosen, path);+ p_->channel = a.openChannel(path);+ if (!p_->channel) { error = L"打开美乐威采集通道失败"; return false; }+ p_->request = request;+ p_->deliver = std::move(deliver);+ p_->stats = {};+ p_->stopEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);+ p_->running = true;+ g_active = true;+ g_latencyMs = 0;+ p_->thread = std::thread([impl = p_.get()] { impl->loop(); });+ log::info("magewell", std::format("low-latency video started {}x{} fourcc=0x{:08X} stride={} bytes={} partialLines={}",+ request.width, request.height, fourccOf(request.format), request.stride, request.frameBytes, request.partialLines));+ return true;+#else+ (void)request; (void)deliver;+ error = L"此版本未包含美乐威 SDK 支持";+ return false;+#endif+}++void LowLatencyVideo::stop() {+ if (p_->stopEvent) SetEvent(p_->stopEvent);+ if (p_->thread.joinable()) p_->thread.join();+#ifdef VEYRA_HAS_MAGEWELL+ if (p_->channel) { api().closeChannel(p_->channel); p_->channel = nullptr; }+#endif+ if (p_->stopEvent) { CloseHandle(p_->stopEvent); p_->stopEvent = nullptr; }+ g_active = false;+ if (p_->running.exchange(false)) {+ const auto s = stats();+ log::info("magewell", std::format("low-latency video stopped frames={} timeouts={} signalChanges={} frameStartToHostMs={:.2f}",+ s.frames, s.timeouts, s.signalChanges, s.frameStartToHostMs));+ }+}++#ifdef VEYRA_HAS_MAGEWELL+void LowLatencyVideo::Impl::loop() {+ auto& a = api();+ DWORD taskIndex = 0;+ HANDLE mmcss = AvSetMmThreadCharacteristicsW(L"Capture", &taskIndex);+ // Page-aligned and pinned: the card writes the frame straight into it by DMA.+ const size_t allocation = (request.frameBytes + 4095) & ~size_t(4095);+ auto* buffer = static_cast<uint8_t*>(VirtualAlloc(nullptr, allocation, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));+ HANDLE captureEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ HANDLE notifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ HNOTIFY notify = 0;+ bool pinned = false, capturing = false;+ const DWORD fourcc = fourccOf(request.format);+ do {+ if (!buffer || !captureEvent || !notifyEvent) { log::error("magewell", "buffer/event allocation failed"); break; }+ if (a.pinBuffer(channel, buffer, DWORD(request.frameBytes)) != MW_SUCCEEDED) { log::error("magewell", "MWPinVideoBuffer failed"); break; }+ pinned = true;+ if (a.startCapture(channel, captureEvent) != MW_SUCCEEDED) { log::error("magewell", "MWStartVideoCapture failed"); break; }+ capturing = true;+ notify = a.registerNotify(channel, notifyEvent,+ MWCAP_NOTIFY_VIDEO_FRAME_BUFFERING | MWCAP_NOTIFY_VIDEO_SIGNAL_CHANGE | MWCAP_NOTIFY_VIDEO_INPUT_SOURCE_CHANGE);+ if (!notify) { log::error("magewell", "MWRegisterNotify failed"); break; }+ bool discontinuity = true;+ double latencyAverage = 0;+ for (;;) {+ HANDLE waitOn[] = {stopEvent, notifyEvent};+ const DWORD woken = WaitForMultipleObjects(2, waitOn, FALSE, 1000);+ if (woken == WAIT_OBJECT_0) break;+ if (woken == WAIT_TIMEOUT) { std::lock_guard lock(statsMutex); ++stats.timeouts; discontinuity = true; continue; }+ ULONGLONG bits = 0;+ if (a.notifyStatus(channel, notify, &bits) != MW_SUCCEEDED) continue;+ if (bits & (MWCAP_NOTIFY_VIDEO_SIGNAL_CHANGE | MWCAP_NOTIFY_VIDEO_INPUT_SOURCE_CHANGE)) {+ discontinuity = true;+ std::lock_guard lock(statsMutex); ++stats.signalChanges;+ }+ if (!(bits & MWCAP_NOTIFY_VIDEO_FRAME_BUFFERING)) continue;+ MWCAP_VIDEO_SIGNAL_STATUS signal{};+ if (a.signalStatus(channel, &signal) != MW_SUCCEEDED || signal.state != MWCAP_VIDEO_SIGNAL_LOCKED) { discontinuity = true; continue; }+ MWCAP_VIDEO_BUFFER_INFO bufferInfo{};+ if (a.bufferInfo(channel, &bufferInfo) != MW_SUCCEEDED) continue;+ MWCAP_VIDEO_FRAME_INFO frameInfo{};+ if (a.frameInfo(channel, bufferInfo.iNewestBuffering, &frameInfo) != MW_SUCCEEDED) continue;+ // Low latency: capture the frame that is still arriving; the DMA starts after+ // `partialLines` lines and the capture event fires per completed part.+ const MW_RESULT started = a.captureFrame(channel, bufferInfo.iNewestBuffering, buffer, DWORD(request.frameBytes), DWORD(request.stride),+ request.bottomUp ? TRUE : FALSE, 0, fourcc, int(request.width), int(request.height), 0, request.partialLines,+ 0, nullptr, 0, 100, 0, 100, 0, MWCAP_VIDEO_DEINTERLACE_BLEND, MWCAP_VIDEO_ASPECT_RATIO_IGNORE, nullptr, nullptr, 0, 0,+ MWCAP_VIDEO_COLOR_FORMAT_UNKNOWN, MWCAP_VIDEO_QUANTIZATION_UNKNOWN, MWCAP_VIDEO_SATURATION_UNKNOWN);+ if (started != MW_SUCCEEDED) { discontinuity = true; continue; }+ bool completed = false, stopping = false;+ while (!completed) {+ HANDLE partWait[] = {stopEvent, captureEvent};+ const DWORD part = WaitForMultipleObjects(2, partWait, FALSE, 200);+ if (part == WAIT_OBJECT_0) { stopping = true; break; }+ if (part == WAIT_TIMEOUT) break;+ MWCAP_VIDEO_CAPTURE_STATUS status{};+ if (a.captureStatus(channel, &status) != MW_SUCCEEDED) break;+ completed = status.bFrameCompleted != FALSE;+ }+ if (stopping) break;+ if (!completed) { discontinuity = true; std::lock_guard lock(statsMutex); ++stats.timeouts; continue; }+ LONGLONG now = 0;+ a.deviceTime(channel, &now);+ const LONGLONG frameStart = frameInfo.allFieldStartTimes[0];+ if (frameStart > 0 && now >= frameStart) {+ const double ms = double(now - frameStart) / 10000.0;+ latencyAverage = latencyAverage > 0 ? latencyAverage * 0.97 + ms * 0.03 : ms;+ }+ deliver(buffer, request.frameBytes, double(frameStart) / 1e7, discontinuity);+ discontinuity = false;+ uint64_t frames = 0;+ {+ std::lock_guard lock(statsMutex);+ frames = ++stats.frames;+ stats.frameStartToHostMs = latencyAverage;+ }+ g_latencyMs = latencyAverage;+ if (frames % 600 == 0)+ log::info("magewell", std::format("frames={} frameStartToHostMs={:.2f} (frame started arriving -> whole frame in host memory)", frames, latencyAverage));+ }+ } while (false);+ if (notify) a.unregisterNotify(channel, notify);+ if (capturing) a.stopCapture(channel);+ if (pinned) a.unpinBuffer(channel, buffer);+ if (buffer) VirtualFree(buffer, 0, MEM_RELEASE);+ if (captureEvent) CloseHandle(captureEvent);+ if (notifyEvent) CloseHandle(notifyEvent);+ if (mmcss) AvRevertMmThreadCharacteristics(mmcss);+ // An early exit (pin/start failed) hands video back to DirectShow (see CaptureCardSource).+ if (!stats.frames) setLastError(L"美乐威采集启动失败,已回到普通采集(详见日志 magewell)");+ g_active = false;+ running = false;+}+#endif++} // namespace veyra::source::magewelldiff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 6f60a6f4..3c468f2d 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -39,6 +39,7 @@#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureColorOverride.h"#include "veyra/source/CaptureFrameRate.h"+#include "veyra/source/MagewellCapture.h"#include "CapturePreferenceStore.h"#ifdef VEYRA_ENABLE_REMOTEPLAY// SDL3-static's system libraries (see CMakeLists: kept off the link line).@@ -643,6 +644,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst// Before anything opens: the renderer reads the output choice at start().applyPreference(QStringLiteral("audioDevice"));applyPreference(QStringLiteral("audioForceStereo"));+ applyPreference(QStringLiteral("magewellLowLatency"));const bool presetsLoaded = impl_->facade.importLegacyStores();const auto presetNotice = utf8Of(impl_->facade.error());if (!presetNotice.isEmpty())@@ -1408,6 +1410,13 @@ void QmlPlayerBridge::setCaptureBufferMode(int value) {}bool QmlPlayerBridge::captureQueryBusy() const { return impl_->captureBusy; }QString QmlPlayerBridge::captureStatus() const { return impl_->captureStatus; }+bool QmlPlayerBridge::captureMagewellDevice() const { return source::magewell::isProCaptureDevicePath(impl_->captureDevice); }+QString QmlPlayerBridge::captureMagewellStatus() const {+ std::wstring runtime;+ if (!source::magewell::runtimeAvailable(&runtime))+ return tr("找不到美乐威运行库 LibMWCapture.dll(应在软件的 runtime\\magewell 文件夹里,或装美乐威驱动/SDK)");+ return QString::fromStdWString(source::magewell::statusText());+}void QmlPlayerBridge::refreshCaptureDevices() {impl_->capturePrefs = ui::CapturePreferenceStore(impl_->dataDir).load();queryCapture(0, {});@@ -4031,7 +4040,8 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {{"subtitleSize", {16, 56}}, {"subtitleFont", {0, 5}}, {"subtitleOutline", {0, 3}},{"subtitleMargin", {0, 240}}, {"subtitleLines", {0, 8}}};static const QStringList flags{"subtitleEnabled", "subtitleBackground", "subtitleFit",- "subtitleSecondLanguage", "audioForceStereo", "holdCompare"};+ "subtitleSecondLanguage", "audioForceStereo", "holdCompare",+ "magewellLowLatency"};QVariant stored;if (ranges.contains(key)) {bool ok = false; const int n = value.toInt(&ok);@@ -4088,6 +4098,7 @@ bool QmlPlayerBridge::setPreference(const QString& key, const QVariant& value) {void QmlPlayerBridge::applyPreference(const QString& key) {if (key == QLatin1String("audioDevice")) sink::setPreferredRenderEndpoint(impl_->prefString("audioDevice").toStdWString());else if (key == QLatin1String("audioForceStereo")) sink::setForceStereoDownmix(impl_->prefBool("audioForceStereo", false));+ else if (key == QLatin1String("magewellLowLatency")) source::magewell::setLowLatencyPreference(impl_->prefBool("magewellLowLatency", false));}QVariantList QmlPlayerBridge::audioDevices() const {QVariantList out;diff --git a/tools/magewell_probe/main.cpp b/tools/magewell_probe/main.cppnew file mode 100644index 00000000..c9ee8818--- /dev/null+++ b/tools/magewell_probe/main.cpp@@ -0,0 +1,43 @@+// Magewell probe: loads LibMWCapture.dll the way the player does, lists the SDK's capture+// channels and, given a DirectShow device path, tries to start the low-latency capture for a few+// seconds. Without a Pro Capture card it shows that the runtime loads and that no channel matches.+//+// usage: veyra_magewell_probe [directshow-device-path] [width height]+#include <windows.h>++#include <chrono>+#include <cstdio>+#include <string>+#include <thread>++#include "veyra/source/MagewellCapture.h"++using namespace veyra::source;++int wmain(int argc, wchar_t** argv) {+ std::wstring detail;+ const bool available = magewell::runtimeAvailable(&detail);+ std::wprintf(L"runtime available=%d (%s)\n", available, detail.c_str());+ if (!available) return 2;+ magewell::VideoRequest request;+ request.directShowPath = argc > 1 ? argv[1] : L"\\\\?\\pci#ven_1cd7&dev_0000#probe#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\\global";+ request.width = argc > 3 ? unsigned(_wtoi(argv[2])) : 1920;+ request.height = argc > 3 ? unsigned(_wtoi(argv[3])) : 1080;+ request.format = magewell::Format::Nv12;+ request.stride = request.width;+ request.frameBytes = size_t(request.stride) * request.height * 3 / 2;+ magewell::LowLatencyVideo video;+ std::wstring error;+ uint64_t frames = 0;+ if (!video.start(request, [&](const uint8_t*, size_t, double, bool) { ++frames; }, error)) {+ std::wprintf(L"start: %s\n", error.c_str());+ std::wprintf(L"status: %s\n", magewell::statusText().c_str());+ return 1;+ }+ std::this_thread::sleep_for(std::chrono::seconds(5));+ const auto stats = video.stats();+ video.stop();+ std::wprintf(L"frames=%llu timeouts=%llu frameStartToHostMs=%.2f\n", (unsigned long long)stats.frames,+ (unsigned long long)stats.timeouts, stats.frameStartToHostMs);+ return stats.frames ? 0 : 1;+}