Skip to content

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

C++

fix(streaming): hardware AV1/HEVC decode, 150 Mbps default, pairing kept, Reflex unload

Veyra Goal Agent2ada46f010a2
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d65759e1..288ade58 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -708,6 +708,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_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_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)
+ target_include_directories(veyra_stream_decode_bench PRIVATE ${FFMPEG_INCLUDE_DIRS})
+ target_link_libraries(veyra_stream_decode_bench PRIVATE veyra_sources ${FFMPEG_LIBRARIES} d3d12 dxgi)
add_executable(veyra_yuy2_color_tests tests/integration/Yuy2ColorTests.cpp)
target_compile_features(veyra_yuy2_color_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_yuy2_color_tests PRIVATE veyra_engine)
diff --git a/docs/STREAM_FIELD_FIXES_2026-10-01.md b/docs/STREAM_FIELD_FIXES_2026-10-01.md
new file mode 100644
index 00000000..92b60609
--- /dev/null
+++ b/docs/STREAM_FIELD_FIXES_2026-10-01.md
@@ -0,0 +1,84 @@
+# 串流实机反馈修复(2026-10-01,beta 4)
+
+来源:双机测试者用 beta 2(PC 串流)实测后的聊天记录、`veyra-qml.log`(两份)和一个崩溃转储 `veyra-crash-20261001-131137-4772.dmp`。
+用户要求:码率拉满并可自定义;查卡顿;查"开光流后跑不满"和防闪烁;画面一顿一顿;修掉。分支 `codex/xbox-20261001`。
+
+## 1. 画面一顿一顿 / 帧率上不去(已找到根因并修复)
+
+**证据**:PC 串流时 moonlight-common-c 报了 685 次 `Video decode unit queue overflow`(解码队列 15 帧满了,丢掉并重新要关键帧),
+引擎每秒只拿到 15–48 帧,读到的画面已在队列里放了 100–280 ms(`readAgeMs`)。引擎自己的 GPU 时间只有 2–4 ms,不是瓶颈;
+`mailboxOverwritten=0` 说明是解码线程产出慢。
+
+**根因**:本项目的 FFmpeg 同时带 libdav1d 和原生 AV1 解码器,`avcodec_find_decoder(AV1)` 返回的是 **libdav1d**(只有软件路径)。
+所以"D3D12VA 打开成功"后第一帧其实是软件帧,被判为不可导入,退回单线程软件解码。测试者选的是 AV1(`formats=0x1000`)。
+
+**复现**(`tools/stream_decode_bench`,本机 RTX 5070,150 Mbps CBR 噪声测试流,60 fps 节奏):
+
+| 流 | 修复前 | 修复后 |
+|---|---|---|
+| AV1 1080p | 软件 25.4 ms/帧,39 fps | d3d12va,0.4 ms 提交,60 fps |
+| AV1 4K | 软件 35.9 ms/帧,27.5 fps | d3d12va,60 fps |
+| HEVC 4K | D3D12VA 第一张图后报错("hardware accelerator failed",之后建纹理失败) | d3d11va,60 fps |
+| H.264 4K | d3d12va 60 fps | 不变 |
+
+HEVC 4K 的 D3D12VA 失败在系统自带的 FFmpeg 8.1.1 上同样出现;文件播放早已因此让 HEVC 走 D3D11VA(`docs/DIAG_HEVC_D3D12VA_AND_EXPORT_CFR_2026-09-17.md`)。
+
+**修复**(只对串流来源生效,采集卡路径不变):
+- `FFmpegVideoDecoder::setPreferNativeAv1Hardware`:硬件打开时用原生 `av1` 解码器(带 hwaccel)。
+- `CaptureCompressedDecoder::setStreamProfile(true)`(Moonlight、Xbox 调用):AV1/H.264 → D3D12VA;HEVC → D3D11VA(独立设备,共享纹理给图);
+ 硬件在第一张画面前就失败(显卡不支持该编码)时自动换软件解码;软件解码给多个低延迟线程。
+- Moonlight 来源把 D3D11VA 画面的纹理视图交给图(与文件播放同一入口)。
+- 软件解码仍是最后手段:150 Mbps 下每帧 25–45 ms,跟不上 60 帧,统计浮层会显示"软件解码"。
+
+## 2. 码率(已改)
+
+- 默认码率 150 Mbps(原来是"自动":1080p60 约 20、4K60 约 80)。设置改成滑块,5–500 Mbps 任意(5 的倍数)。
+ 旧设置里保存的"自动"读入时按新默认 150 处理。默认没有直接放 500:无线网络下高码率会丢包,反而一顿一顿;有线千兆可自己拉到 300–500。
+- 主机画面简单(桌面、静止)时编码器实际输出远低于上限,这是正常的。统计浮层(Ctrl+Alt+Shift+S)现在显示**实际收到的码率**和收/解帧率
+ (以前这两个帧率字段没有计算,一直显示"—");日志每 10 秒一行 `[moonlight] stream ...`,含后端、帧率、码率、各段耗时。
+
+## 3. 配对:第二次要重新配对、配完还连不上(已修复)
+
+**根因**:Sunshine 只在带客户端证书的 HTTPS 请求里报告"已配对",普通 HTTP 一律报 0。局域网自动发现和"手动添加"探测用的是不带证书的 HTTP,
+软件把这个 0 当真,把已配对的主机改成"未配对"并保存。用户再去配对同一个证书,主机那边就出现重复记录,之后连不上,只能在主机端删掉重配。
+
+**修复**:`ServerInfo::pairStatusKnown` —— 只有 HTTPS 的回答(或主机明确拒绝我们的证书)才会改配对状态;探测已知主机时带上保存的证书走 HTTPS;
+点"配对"时先用保存的证书确认,主机仍信任就不再走 PIN;启动时主机明确不认我们才标为未配对。模拟主机改成和 Sunshine 一样(HTTP 永远 PairStatus 0),
+新增测试"再次发现的主机仍是已配对""主机仍信任时不需要重新配对"(模型测试 42 → 47 项,连跑 3 次通过)。
+**已经出问题的测试者**:在主机 Sunshine 网页里删掉旧的 Veyra 客户端,本机也删掉主机,重新配对一次即可。
+
+## 4. 退出时崩溃(转储分析,已修复可能原因)
+
+转储:退出时引擎线程在 `D3D12Core.dll+0xD285` 读取 `0x7FFD4F73F710` 失败,发生在"device context shutdown complete"之后,
+该地址不属于任何已加载模块,正好落在 NVIDIA 用户态驱动 `nvwgf2umx.dll` 之后的空档里——典型的"回调进了已卸载的 DLL"。
+(用 /MAP 重新链接 beta 2 的同一份代码,.text 段与包内逐字节相同,以此还原栈:`EngineController::run → ~D3D12DeviceContext → … → D3D12`。)
+这个会话开关过 6 次 NVIDIA Reflex,`ReflexSession` 每次重开和退出都 `NvAPI_Unload + FreeLibrary(nvapi64.dll)`,而驱动在设备最终释放时还会用到 nvapi 的设备状态。
+**修复**:nvapi64.dll 加载一次后固定在进程里(`GET_MODULE_HANDLE_EX_FLAG_PIN`),不再卸载;关闭 Reflex 只关睡眠模式。
+没有调试器符号与驱动 PDB,不能 100% 断定,下个包请继续收集崩溃转储。
+
+## 5. "开光流后 1440p 只有 52 帧"、防闪烁(排查结论:不是回归)
+
+日志(RTX 5060 Ti,4K 采集,NR 内部处理 1440p):NR 本身约 15 ms,NVIDIA 光流约 2.5 ms,残差/防闪约 0.7 ms,颜色约 1.2 ms,合计约 20 ms,
+超过 60 帧每帧 16.7 ms 的预算 → 51–52 帧。关掉光流约 17 ms,勉强 57–60 帧,但防闪失去运动补偿,闪烁回来——和测试者看到的一致。
+NR 内部 1080p 时:NR 9 ms + 光流 2 ms,稳定 60 帧。
+与 1.4.4 对比:分辨率计划(光流跟随 NR 内部尺寸)和 NVOF 会话代码与 1.4.4 完全相同;1.4.4 只要开 NR 就**总是**跑光流,没有开关。
+所以"以前默认有光流也能跑满"多半是以前 NR 内部用的是 1080p。建议:5060 Ti 这一档 4K 采集用 NR 1080p;或把光流后端换成 AMD FidelityFX(日志里 1080p 只要 0.5 ms)。
+
+## 6. 玩一段时间掉到 10 帧(未定位,已加诊断)
+
+05:53 那次:没有任何设置变化,所有 GPU 阶段同时逐渐变慢(NR 13→33 ms、颜色 1.1→7.5 ms、光流 3→8 ms),像是显卡降频或显存被挤到系统内存。
+那个进程每次改设置记录的显存占用从 0.3 GB 涨到 9.5 GB。本机用 4K 文件做了两组复现(开关光流 20 次;全屏切换 40 次后再重建),
+每次重建只多约 2 MB,没有复现大量增长。现在采集/串流时每秒在 `[frame-rate]` 行记录 `vramMiB`/`budgetMiB`,下次出现时能看出是不是显存。
+请测试者出现时同时看一下显卡温度和频率(任务管理器或 GPU-Z)。
+
+## 未处理
+
+- 聊天截图里有一条关于鼠标的问题,截图分辨率太低看不清,需要测试者重述。
+- 没有真实 Sunshine / Xbox 主机,以上串流修复只在本机解码基准和模拟主机上验证;HEVC D3D11VA 串流路径未见真机。
+
+## 验证
+
+- `veyra_stream_decode_bench`:上表四种流,修复后全部 60 fps、无回退(`tests/stream-fix-20261001/`)。
+- 单元测试:Moonlight 协议 134、模型 47(×3)、Xbox 72、effect chain、easing、preset、repair 243、qml data —— 全部通过。
+- PC 串流对话框端到端(模拟主机)通过;截图 `tests/stream-fix-20261001/ui-demo/05-settings.png`(码率滑块)。
+ 截图改用 PrintWindow,避免被别的窗口挡住。
diff --git a/docs/TEST_PACKAGE_2.0.0beta3.md b/docs/TEST_PACKAGE_2.0.0beta3.md
index e7f057ae..3697a775 100644
--- a/docs/TEST_PACKAGE_2.0.0beta3.md
+++ b/docs/TEST_PACKAGE_2.0.0beta3.md
@@ -76,7 +76,7 @@ PC 串流的主机列表、设置和配对身份存在 `%LOCALAPPDATA%\Veyra\moo
- 登录是否成功;主机能否列出;从"开始串流"到出画面要几秒;
- 画面分辨率(统计浮层第一行)、码率、延迟感受;手柄和震动是否正常;
- 任何错误提示的原文、崩溃、卡死。
-- 日志:`logs eyra-qml.log`,搜 `xbox`。连不上时,用环境变量 `VEYRA_XBOX_RTC_DEBUG=1` 启动一次(详细网络日志,含本机局域网地址,发给我前可以自行查看)。
+- 日志:`logs\veyra-qml.log`,搜 `xbox`。连不上时,用环境变量 `VEYRA_XBOX_RTC_DEBUG=1` 启动一次(详细网络日志,含本机局域网地址,发给我前可以自行查看)。
## 已知情况
diff --git a/docs/TEST_PACKAGE_2.0.0beta4.md b/docs/TEST_PACKAGE_2.0.0beta4.md
new file mode 100644
index 00000000..6af142ed
--- /dev/null
+++ b/docs/TEST_PACKAGE_2.0.0beta4.md
@@ -0,0 +1,105 @@
+# Veyra 2.0.0 beta 4(PC 串流 + Xbox 串流)测试说明
+
+## 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/gfx/ReflexSession.h b/include/veyra/gfx/ReflexSession.h
index b390b0c3..2c3de152 100644
--- a/include/veyra/gfx/ReflexSession.h
+++ b/include/veyra/gfx/ReflexSession.h
@@ -19,13 +19,18 @@ class ReflexSession {
using Sleep=int(__cdecl*)(IUnknown*);
using Marker=int(__cdecl*)(IUnknown*,MarkerParams*);
HMODULE module_=nullptr;ID3D12Device* device_=nullptr;
- Set set_=nullptr;Sleep sleep_=nullptr;Marker marker_=nullptr;Init unload_=nullptr;
+ Set set_=nullptr;Sleep sleep_=nullptr;Marker marker_=nullptr;
bool initialized_=false,active_=false,driverEnabled_=false;uint64_t next_=0,sleeps_=0,markers_=0;
public:
- ~ReflexSession(){close();}
+ ~ReflexSession(){close();} // the module stays pinned, see close()
bool active()const{return active_;}
bool disablePending()const{return driverEnabled_&&!active_;}
- void close(){disable();device_=nullptr;if(initialized_&&unload_)unload_();initialized_=false;if(module_)FreeLibrary(module_);module_=nullptr;set_=nullptr;sleep_=nullptr;marker_=nullptr;unload_=nullptr;driverEnabled_=false;}
+ // nvapi64.dll stays loaded and initialized for the life of the process: the driver keeps
+ // per-device sleep-mode state that is called back when the D3D12 device is finally
+ // released. NvAPI_Unload + FreeLibrary here (on every re-enable and at shutdown) could
+ // leave that callback pointing into an unloaded module; a field dump of 2026-10-01
+ // crashed in D3D12Core on exit, reading code just past the NVIDIA user-mode driver.
+ void close(){disable();device_=nullptr;driverEnabled_=false;}
bool disable(){
active_=false;
if(driverEnabled_&&set_){SleepParams p{};p.version=sizeof(p)|(1u<<16);const int r=set_(device_,&p);log::info("reflex",std::format("disable status={} successfulSleeps={} successfulMarkers={}",r,sleeps_,markers_));if(r)return false;driverEnabled_=false;}
@@ -34,16 +39,23 @@ public:
bool enable(ID3D12Device* device){
if(active_&&device_==device)return true;
if(!disable())return false;
- close();device_=device;wchar_t system[MAX_PATH]{};GetSystemDirectoryW(system,MAX_PATH);
- const std::wstring path=std::wstring(system)+L"\\nvapi64.dll";
- module_=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);
- auto query=module_?reinterpret_cast<Query>(GetProcAddress(module_,"nvapi_QueryInterface")):nullptr;
- if(!query)return false;
- auto init=reinterpret_cast<Init>(query(0x0150E828));unload_=reinterpret_cast<Init>(query(0xD22BDD7E));
- set_=reinterpret_cast<Set>(query(0xac1ca9e0));sleep_=reinterpret_cast<Sleep>(query(0x852cd1d2));marker_=reinterpret_cast<Marker>(query(0xd9984c05));
- if(!init||!set_||!sleep_||!marker_||!unload_)return false;
- const int initialized=init();initialized_=initialized==0;
- if(!initialized_){log::warn("reflex",std::format("initialize status={}",initialized));return false;}
+ close();device_=device;
+ if(!initialized_){
+ if(!module_){
+ wchar_t system[MAX_PATH]{};GetSystemDirectoryW(system,MAX_PATH);
+ const std::wstring path=std::wstring(system)+L"\\nvapi64.dll";
+ module_=LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);
+ HMODULE pinned=nullptr; // never unloaded, see close()
+ if(module_)GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_PIN,reinterpret_cast<LPCWSTR>(module_),&pinned);
+ }
+ auto query=module_?reinterpret_cast<Query>(GetProcAddress(module_,"nvapi_QueryInterface")):nullptr;
+ if(!query)return false;
+ auto init=reinterpret_cast<Init>(query(0x0150E828));
+ set_=reinterpret_cast<Set>(query(0xac1ca9e0));sleep_=reinterpret_cast<Sleep>(query(0x852cd1d2));marker_=reinterpret_cast<Marker>(query(0xd9984c05));
+ if(!init||!set_||!sleep_||!marker_)return false;
+ const int initialized=init();initialized_=initialized==0;
+ if(!initialized_){log::warn("reflex",std::format("initialize status={}",initialized));return false;}
+ }
SleepParams p{};p.version=sizeof(p)|(1u<<16);p.low=1;p.markers=1;
const int result=set_(device_,&p);log::info("reflex",std::format("enable status={} intervalUs=0 boost=0",result));
sleeps_=markers_=0;return active_=driverEnabled_=result==0;
diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.h
index 9ff526a6..c500e2a6 100644
--- a/include/veyra/media/FFmpegVideoDecoder.h
+++ b/include/veyra/media/FFmpegVideoDecoder.h
@@ -86,6 +86,12 @@ public:
uint64_t adapterLuid, ID3D12Device* d3d12Device, bool lowLatency = false);
void close();
+ // This FFmpeg build registers libdav1d ahead of the native AV1 decoder, and
+ // libdav1d has no hardware path: avcodec_find_decoder(AV1) silently gives a
+ // software decoder to openD3D12VA/openD3D11VA. Streaming sources set this so
+ // the hardware opens use the native "av1" decoder (the one with the hwaccels).
+ void setPreferNativeAv1Hardware(bool prefer) { preferNativeAv1_ = prefer; }
+
bool opened() const { return context_ != nullptr; }
int width() const;
int height() const;
@@ -162,6 +168,7 @@ private:
int frameTimeBaseDen_ = 0;
DecoderStats stats_{};
bool hwAccelActive_ = false;
+ bool preferNativeAv1_ = false;
HardwareDecodeKind hwAccelKind_ = HardwareDecodeKind::None;
int lastFrameFormat_ = -1;
uint64_t gpuQueueWaitCount_ = 0;
diff --git a/include/veyra/moonlight/Types.h b/include/veyra/moonlight/Types.h
index 597b83da..c589b9d2 100644
--- a/include/veyra/moonlight/Types.h
+++ b/include/veyra/moonlight/Types.h
@@ -45,6 +45,10 @@ struct ServerInfo {
int maxLumaPixelsHevc = 0;
int currentGame = 0; // 0 unless the host is busy streaming
bool paired = false;
+ // Only an answer over HTTPS with our client certificate says whether the host
+ // still trusts us: Sunshine reports PairStatus 0 over plain HTTP to anyone.
+ // False means `paired` must not be used to forget a pairing.
+ bool pairStatusKnown = false;
bool nvidiaServerSoftware = false; // GFE / RTX Experience report "MJOLNIR"
std::vector<DisplayMode> displayModes;
diff --git a/include/veyra/source/CaptureCompressedDecoder.h b/include/veyra/source/CaptureCompressedDecoder.h
index 20397ded..7c97295d 100644
--- a/include/veyra/source/CaptureCompressedDecoder.h
+++ b/include/veyra/source/CaptureCompressedDecoder.h
@@ -16,6 +16,8 @@ struct AVFrame;
struct ID3D12Device;
struct ID3D12CommandQueue;
+namespace veyra::pipeline { struct HardwareSurfaceInput; }
+
namespace veyra::source {
class CaptureCompressedDecoder {
@@ -34,6 +36,16 @@ public:
//
// `extradata` (SPS/PPS from MPEG2VIDEOINFO) may be empty; the bitstream's
// in-band parameter sets are then required.
+ // Streaming sources (PC and Xbox streaming) call this before open(): AV1
+ // then uses the native decoder with D3D12VA (the libdav1d decoder FFmpeg
+ // would pick has no hardware path), HEVC decodes through D3D11VA on its own
+ // device (HEVC D3D12VA fails at 4K and can remove the shared device on
+ // NVIDIA drivers, see FFmpegVideoDecoder::openD3D11VA), a hardware decoder
+ // that fails before its first picture is replaced by the software one, and
+ // the software decoder runs several low-delay threads. Capture cards keep
+ // the original behaviour.
+ void setStreamProfile(bool enabled);
+
bool open(CaptureCodec codec, unsigned width, unsigned height,
const uint8_t* extradata, size_t extradataBytes,
ID3D12Device* device, ID3D12CommandQueue* queue);
@@ -49,6 +61,10 @@ public:
bool decode(const uint8_t* data, size_t bytes, int64_t pts100ns,
AVFrame* nv12Target, AVFrame** out, bool& hardware);
+ // For D3D11VA frames (AV_PIX_FMT_D3D11) the texture the graph reads is not
+ // inside the AVFrame: this fills the borrowed view of the last frame.
+ bool hardwareSurface(pipeline::HardwareSurfaceInput& out) const;
+
bool opened() const;
bool hardwareActive() const;
bool waitingForInput() const;
diff --git a/include/veyra/source/MoonlightSessionSource.h b/include/veyra/source/MoonlightSessionSource.h
index fe7fdfde..5b34f393 100644
--- a/include/veyra/source/MoonlightSessionSource.h
+++ b/include/veyra/source/MoonlightSessionSource.h
@@ -74,6 +74,7 @@ struct MoonlightStats {
bool encrypted = false;
uint64_t units = 0, decoded = 0, dropped = 0, decodeErrors = 0, idrRequests = 0;
double receivedFps = 0, decodedFps = 0;
+ double videoMbps = 0; // video payload actually received
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
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index 7f4f0651..900ae6f2 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -611,8 +611,6 @@ Item {
{ id: "1440p", label: "1440p · 2560×1440" }, { id: "4k", label: "4K · 3840×2160" },
{ id: "native", label: "本机屏幕分辨率" }]
readonly property var rates: [30, 60, 90, 120, 144].map(v => ({ id: String(v), label: v + " fps" }))
- readonly property var bitrates: [{ id: "0", label: "自动(按分辨率与帧率)" }].concat(
- [5, 10, 15, 20, 30, 40, 50, 60, 80, 100, 120, 150].map(m => ({ id: String(m), label: m + " Mbps" })))
function labelOf(list, id, fallback) { const f = list.find(x => String(x.id) === String(id)); return f ? f.label : fallback }
function stateText(s) {
return s === "online" ? "在线" : s === "unpaired" ? "未配对" : s === "busy" ? "在线 · 有游戏在运行"
@@ -821,8 +819,26 @@ Item {
}
VRow {
label: "码率"
- hint: "自动:1080p60 约 20 Mbps,4K60 约 80 Mbps;局域网有线可以放心调高"
- VSelect { objectName: "moonlight-bitrate"; implicitWidth: 190; value: mlDialog.labelOf(mlDialog.bitrates, mlDialog.cfg.bitrate || 0, "自动"); options: mlDialog.bitrates; onPicked: id => mlDialog.ml.set("bitrate", Number(id)) }
+ hint: "默认 150 Mbps;有线千兆可以拉到 300–500,无线卡顿时调低。主机画面简单时实际码率会低于这里的上限"
+ RowLayout {
+ spacing: 10
+ VSlider {
+ id: bitrateSlider
+ objectName: "moonlight-bitrate"
+ implicitWidth: 170
+ from: 5; to: 500
+ live: false
+ value: mlDialog.cfg.bitrate || 150
+ onMoved: v => mlDialog.ml.set("bitrate", Math.max(5, Math.round(v / 5) * 5))
+ }
+ Text {
+ Layout.preferredWidth: 72
+ text: Math.max(5, Math.round((bitrateSlider.dragging ? bitrateSlider.dragValue : bitrateSlider.value) / 5) * 5) + " Mbps"
+ color: Theme.t1
+ font.family: Theme.fontMono
+ font.pixelSize: Theme.fsSmall
+ }
+ }
}
VRow {
label: "编码"
diff --git a/qml/Veyra/StreamHud.qml b/qml/Veyra/StreamHud.qml
index 6b5c7d6f..29598cee 100644
--- a/qml/Veyra/StreamHud.qml
+++ b/qml/Veyra/StreamHud.qml
@@ -45,6 +45,7 @@ Rectangle {
visible: !hud.xboxOn
text: "主机 " + hud.ms(s.hostMs) + " · 往返 " + hud.ms(s.rttMs) + " · 接收 " + hud.ms(s.receiveMs)
+ " · 排队 " + hud.ms(s.queueMs) + " · 解码 " + hud.ms(s.decodeMs)
+ + " · 码率 " + (s.videoMbps > 0 ? s.videoMbps.toFixed(1) + " Mbps" : "—")
color: Theme.t2
font.family: Theme.fontMono
font.pixelSize: 11
diff --git a/scripts/moonlight/make-beta.py b/scripts/moonlight/make-beta.py
index e0c5fec5..d145e5ba 100644
--- a/scripts/moonlight/make-beta.py
+++ b/scripts/moonlight/make-beta.py
@@ -42,7 +42,7 @@ 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'):
+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'):
if (repo / 'docs' / name).exists():
shutil.copy2(repo / 'docs' / name, pkg / 'docs' / name)
shutil.copy2(repo / notes, pkg / '测试说明.md')
diff --git a/scripts/moonlight/ui-demo.py b/scripts/moonlight/ui-demo.py
index 79c29aa9..8e587f99 100644
--- a/scripts/moonlight/ui-demo.py
+++ b/scripts/moonlight/ui-demo.py
@@ -60,13 +60,26 @@ def screenshot(pid, path):
if not win:
return False
hwnd, rect = win
- ps = ('Add-Type -AssemblyName System.Drawing; '
- f'$b = New-Object System.Drawing.Bitmap({rect.r - rect.l},{rect.b - rect.t}); '
- '$g = [System.Drawing.Graphics]::FromImage($b); '
- f'$g.CopyFromScreen({rect.l},{rect.t},0,0,$b.Size); '
- f'$b.Save("{path}"); $g.Dispose(); $b.Dispose()')
- subprocess.run(['powershell', '-NoProfile', '-Command', ps], check=True, timeout=60)
- return True
+ # PrintWindow(PW_RENDERFULLCONTENT) reads the window's own composed content, so another
+ # window on top of it (a terminal, the IDE) does not end up in the picture.
+ width, height = rect.r - rect.l, rect.b - rect.t
+ gdi32 = ctypes.windll.gdi32
+ window_dc = user32.GetWindowDC(ctypes.c_void_p(hwnd))
+ memory_dc = gdi32.CreateCompatibleDC(window_dc)
+ bitmap = gdi32.CreateCompatibleBitmap(window_dc, width, height)
+ gdi32.SelectObject(memory_dc, bitmap)
+ printed = user32.PrintWindow(ctypes.c_void_p(hwnd), memory_dc, 2)
+ try:
+ from PIL import Image
+ buffer = ctypes.create_string_buffer(width * height * 4)
+ header = (ctypes.c_uint32 * 10)(40, width, ctypes.c_uint32(-height).value, 1 | (32 << 16), 0, 0, 0, 0, 0, 0)
+ gdi32.GetDIBits(memory_dc, bitmap, 0, height, buffer, header, 0)
+ Image.frombuffer('RGBA', (width, height), buffer, 'raw', 'BGRA', 0, 1).convert('RGB').save(str(path))
+ finally:
+ gdi32.DeleteObject(bitmap)
+ gdi32.DeleteDC(memory_dc)
+ user32.ReleaseDC(ctypes.c_void_p(hwnd), window_dc)
+ return bool(printed)
result = 1
diff --git a/scripts/moonlight/vram-cycle.qml b/scripts/moonlight/vram-cycle.qml
new file mode 100644
index 00000000..d96a0189
--- /dev/null
+++ b/scripts/moonlight/vram-cycle.qml
@@ -0,0 +1,24 @@
+ // Injected by scripts/moonlight/ui-demo.py (with this file as the snippet): plays the clip named by
+ // __CLIP__ (replaced before injection) with NR on, switches NR's optical flow off and on twenty times (every switch
+ // rebuilds the graph) and quits. The [memory] lines in the log then show whether adapter memory
+ // returns to the same level after each rebuild.
+ Timer {
+ interval: 250; running: true; repeat: true
+ property int step: 0
+ property int ticks: 0
+ property int cycles: 0
+ function log(text) { veyra.logUi("mltest", text) }
+ onTriggered: { try {
+ ++ticks
+ if (step === 0 && ticks === 8) { veyra.openPath("__CLIP__"); step = 1; ticks = 0; return }
+ if (step === 1 && ticks === 16) { veyra.nrEnabled = true; step = 2; ticks = 0; return }
+ if (step === 2 && ticks === 16) {
+ veyra.nrMotionSource = veyra.nrMotionSource === 1 ? 0 : 1
+ log("MLTEST_CYCLE " + (++cycles) + " flow=" + veyra.nrMotionSource)
+ ticks = 0
+ if (cycles >= 20) step = 3
+ return
+ }
+ if (step === 3 && ticks === 16) { running = false; log("MLTEST_DONE"); console.log("MLTEST_PASS"); Qt.quit() }
+ } catch (e) { running = false; log("MLTEST_FAIL " + e.message); Qt.quit() } }
+ }
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index b292b9c2..e6035898 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1943,7 +1943,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(isCapture&&Clock::now()>=nextTimingLog){
logFrameFlow(measured.flow,"active");
const auto rates=snapshot();
- veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0)));
+ // Adapter memory every second: a long session that slowly runs out of video
+ // memory gets slower in every pass at once (field log 2026-10-01).
+ uint64_t vramBudget=0,vramUsage=0;ctx.videoMemoryInfo(vramBudget,vramUsage);
+ veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 vramMiB={} budgetMiB={} (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0),vramUsage>>20,vramBudget>>20));
veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} singleGpuOwner=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveScheduler?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));
nextTimingLog=Clock::now()+std::chrono::seconds(1);
}
diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cpp
index 80f5ef4c..c6a794c0 100644
--- a/src/media/FFmpegVideoDecoder.cpp
+++ b/src/media/FFmpegVideoDecoder.cpp
@@ -103,8 +103,9 @@ bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,
// Legacy bounded packet pumps keep the default single thread. The file
// source can supply compressed lookahead until receiveFrame succeeds and
// explicitly opts into at most four codec workers; no application frame
- // queue and no capture lookahead are introduced.
- context_->thread_count = int(std::clamp(softwareThreads,1u,4u));
+ // queue and no capture lookahead are introduced. Streaming fallbacks ask
+ // for up to eight low-delay workers (dav1d then threads inside one frame).
+ context_->thread_count = int(std::clamp(softwareThreads,1u,8u));
context_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
if (lowLatency) {
// Live capture: never trade latency for throughput. Frame threading
@@ -146,7 +147,8 @@ bool FFmpegVideoDecoder::openD3D12VA(const AVCodecParameters* codecParameters,
frameTimeBaseNum_ = streamTimeBaseNum;
frameTimeBaseDen_ = streamTimeBaseDen;
- const AVCodec* codec = avcodec_find_decoder(codecParameters->codec_id);
+ const AVCodec* codec = preferNativeAv1_ && codecParameters->codec_id == AV_CODEC_ID_AV1 ? avcodec_find_decoder_by_name("av1") : nullptr;
+ if (codec == nullptr) codec = avcodec_find_decoder(codecParameters->codec_id);
if (codec == nullptr) {
log::error("media", "decoder: no decoder for d3d12va codec");
return false;
@@ -370,7 +372,8 @@ bool FFmpegVideoDecoder::openD3D11VA(const AVCodecParameters* codecParameters,
frameTimeBaseNum_ = streamTimeBaseNum;
frameTimeBaseDen_ = streamTimeBaseDen;
- const AVCodec* codec = avcodec_find_decoder(codecParameters->codec_id);
+ const AVCodec* codec = preferNativeAv1_ && codecParameters->codec_id == AV_CODEC_ID_AV1 ? avcodec_find_decoder_by_name("av1") : nullptr;
+ if (codec == nullptr) codec = avcodec_find_decoder(codecParameters->codec_id);
if (codec == nullptr) {
log::error("media", "decoder: no decoder for d3d11va codec");
return false;
diff --git a/src/moonlight/Client.cpp b/src/moonlight/Client.cpp
index c1c3b1d2..2394213e 100644
--- a/src/moonlight/Client.cpp
+++ b/src/moonlight/Client.cpp
@@ -139,14 +139,20 @@ ServerInfo ServerClient::serverInfo(bool fastFail) {
if (httpsPossible) {
// Always try HTTPS first, since it properly reports the pairing status.
try {
- return parseServerInfo(checkedRoot(request(true, "serverinfo", "", timeout)));
+ ServerInfo info = parseServerInfo(checkedRoot(request(true, "serverinfo", "", timeout)));
+ info.pairStatusKnown = true;
+ return info;
} catch (const StatusError& e) {
if (e.status != 401) throw;
} catch (const TransportError& e) {
// Certificate mismatch or a client certificate the host does not know: fall back to HTTP.
if (e.kind != TransportError::Kind::Tls) throw;
}
- return parseServerInfo(checkedRoot(request(false, "serverinfo", "", timeout)));
+ // The host turned our certificate away: that is a real "not paired".
+ ServerInfo info = parseServerInfo(checkedRoot(request(false, "serverinfo", "", timeout)));
+ info.paired = false;
+ info.pairStatusKnown = true;
+ return info;
}
// Before pairing only HTTP is used. It also tells us the HTTPS port.
const ServerInfo info = parseServerInfo(checkedRoot(request(false, "serverinfo", "", timeout)));
diff --git a/src/source/CaptureCompressedDecoder.cpp b/src/source/CaptureCompressedDecoder.cpp
index b06f663a..38ae9430 100644
--- a/src/source/CaptureCompressedDecoder.cpp
+++ b/src/source/CaptureCompressedDecoder.cpp
@@ -7,14 +7,18 @@ extern "C" {
#include <libswscale/swscale.h>
}
+#include <algorithm>
#include <chrono>
#include <cstring>
+#include <d3d12.h>
+#include <thread>
#include <emmintrin.h>
#include <format>
#include "veyra/Log.h"
#include "veyra/media/FFmpegVideoDecoder.h"
#include "veyra/pipeline/CaptureUploadFrame.h"
+#include "veyra/pipeline/FramePacket.h"
namespace veyra::source {
@@ -57,6 +61,7 @@ struct CaptureCompressedDecoder::Impl {
media::FFmpegVideoDecoder decoder;
AVCodecParameters* parameters = nullptr;
SwsContext* sws = nullptr;
+ bool stream = false; // setStreamProfile(): PC / Xbox streaming
bool hardwareRequested = false;
bool hardware = false;
bool hardwareChecked = false;
@@ -128,16 +133,41 @@ struct CaptureCompressedDecoder::Impl {
codec = CaptureCodec::None;
width = height = 0;
hardwareRequested = hardware = hardwareChecked = waiting = false;
+ decoder.setPreferNativeAv1Hardware(false);
depthWarningLogged = false;
frames = failures = fallbacks = 0;
decodeMs = convertMs = 0;
error.clear();
}
+ // Streams only: a GPU without this codec (for example AV1 before RTX 30)
+ // or a driver that rejects it fails before the first picture. Switch to
+ // software once; the caller asks the host for a key frame anyway.
+ void fallBackBeforeFirstPicture()
+ {
+ if (!stream || !hardware || frames != 0) return;
+ log::warn("capture-decode", std::format("codec={} hardware decode failed before the first picture; switching to the software decoder",
+ captureCodecKey(codec)));
+ decoder.close();
+ hardware = false;
+ if (!openSoftwareDecoder()) {
+ error = "software fallback after a failed hardware decoder failed";
+ return;
+ }
+ decoder.recoverAtKeyframe();
+ ++fallbacks;
+ }
+
bool openSoftwareDecoder()
{
if (parameters == nullptr) return false;
- return decoder.openSoftware(parameters, 1, 10000000, 1, true);
+ // Streams get slice/tile threads; low delay keeps them inside one frame,
+ // so latency does not grow. Software stays a last resort: at 150 Mbps
+ // one frame still takes 25-45 ms here (bench 2026-10-01), so the stream
+ // sources prefer every hardware path above.
+ const unsigned threads = stream && codec != CaptureCodec::Mjpeg
+ ? std::clamp(std::thread::hardware_concurrency() / 2u, 2u, 8u) : 1u;
+ return decoder.openSoftware(parameters, 1, 10000000, threads, true);
}
bool convertToNv12(const AVFrame& frame, AVFrame* target)
@@ -220,7 +250,16 @@ bool CaptureCompressedDecoder::open(CaptureCodec codec, unsigned width, unsigned
// decoder as the recorded fallback.
if (codec != CaptureCodec::Mjpeg && device != nullptr && queue != nullptr) {
p.hardwareRequested = true;
- if (p.decoder.openD3D12VA(p.parameters, 1, 10000000, device, queue, true)) {
+ bool opened = false;
+ if (p.stream && codec == CaptureCodec::Hevc) {
+ const LUID luid = device->GetAdapterLuid();
+ opened = p.decoder.openD3D11VA(p.parameters, 1, 10000000,
+ (uint64_t(uint32_t(luid.HighPart)) << 32) | uint64_t(luid.LowPart), device, true);
+ } else {
+ p.decoder.setPreferNativeAv1Hardware(p.stream);
+ opened = p.decoder.openD3D12VA(p.parameters, 1, 10000000, device, queue, true);
+ }
+ if (opened) {
p.hardware = true;
} else {
log::warn("capture-decode", std::format(
@@ -282,6 +321,7 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
if (!sent) {
p.error = "decoder rejected the compressed payload";
++p.failures;
+ p.fallBackBeforeFirstPicture();
return false;
}
}
@@ -290,6 +330,7 @@ bool CaptureCompressedDecoder::decode(const uint8_t* data, size_t bytes, int64_t
if (p.decoder.receiveStatus() == media::DecodeReceiveStatus::Error) {
p.error = "decoder receive failed";
++p.failures;
+ p.fallBackBeforeFirstPicture();
} else {
p.error.clear();
p.waiting = true;
@@ -343,7 +384,7 @@ bool CaptureCompressedDecoder::waitingForInput() const { return p_->waiting; }
void CaptureCompressedDecoder::recoverAtKeyframe() { p_->decoder.recoverAtKeyframe(); }
const char* CaptureCompressedDecoder::backendName() const
{
- if (p_->hardware) return "d3d12va";
+ if (p_->hardware) return p_->stream && p_->codec == CaptureCodec::Hevc ? "d3d11va" : "d3d12va";
if (p_->hardwareRequested) return "software(after d3d12va)";
return p_->decoder.opened() ? "software" : "none";
}
@@ -354,5 +395,18 @@ uint64_t CaptureCompressedDecoder::hardwareFallbacks() const { return p_->fallba
double CaptureCompressedDecoder::decodeMsAverage() const { return p_->decodeMs; }
double CaptureCompressedDecoder::convertMsAverage() const { return p_->convertMs; }
void CaptureCompressedDecoder::close() { p_->close(); }
+void CaptureCompressedDecoder::setStreamProfile(bool enabled) { p_->stream = enabled; }
+bool CaptureCompressedDecoder::hardwareSurface(pipeline::HardwareSurfaceInput& out) const
+{
+ const auto& view = p_->decoder.hardwareSurface();
+ if (!p_->hardware || view.texture == nullptr) return false;
+ out.texture = view.texture;
+ out.subresourceIndex = view.subresourceIndex;
+ out.waitFence = view.waitFence;
+ out.waitValue = view.waitValue;
+ out.textureWidth = view.textureWidth;
+ out.textureHeight = view.textureHeight;
+ return true;
+}
} // namespace veyra::source
diff --git a/src/source/MoonlightSessionSource.cpp b/src/source/MoonlightSessionSource.cpp
index dddaf7aa..c2ce7fb5 100644
--- a/src/source/MoonlightSessionSource.cpp
+++ b/src/source/MoonlightSessionSource.cpp
@@ -85,7 +85,7 @@ std::wstring describeTermination(int code) {
}
pipeline::SourcePixelFormat pixelFormatOf(const AVFrame& frame) {
- if (frame.format == AV_PIX_FMT_D3D12 && frame.hw_frames_ctx) {
+ if ((frame.format == AV_PIX_FMT_D3D12 || frame.format == AV_PIX_FMT_D3D11) && 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;
@@ -160,7 +160,7 @@ struct MoonlightSessionSource::Impl {
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<uint64_t> units{0}, decoded{0}, dropped{0}, errors{0}, idr{0}, bytes{0};
std::atomic<int64_t> lastFrameNumber{0};
std::atomic<bool> terminated{false};
std::atomic<int> terminationCode{0};
@@ -179,9 +179,30 @@ struct MoonlightSessionSource::Impl {
uint16_t rumbleLow = 0, rumbleHigh = 0;
Clock::time_point feedbackSent{};
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;
+ double hostLatencyMs = 0, receiveMs = 0, queueMs = 0, decodeMs = 0, receivedFps = 0, decodedFps = 0, videoMbps = 0;
+ std::chrono::steady_clock::time_point rateStart = Clock::now(), logStart = Clock::now();
+ uint64_t rateUnits = 0, rateDecoded = 0, rateBytes = 0;
+
+ // Once a second: frame and bit rates for the overlay; every ten seconds a log line,
+ // so a field log shows whether the host, the network or the decoder sets the pace.
+ void updateRates() {
+ const auto now = Clock::now();
+ const double seconds = std::chrono::duration<double>(now - rateStart).count();
+ if (seconds < 1.0) return;
+ const uint64_t u = units.load(), d = decoded.load(), b = bytes.load();
+ std::lock_guard lock(statsMutex);
+ receivedFps = double(u - rateUnits) / seconds;
+ decodedFps = double(d - rateDecoded) / seconds;
+ videoMbps = double(b - rateBytes) * 8.0 / seconds / 1e6;
+ rateUnits = u; rateDecoded = d; rateBytes = b;
+ rateStart = now;
+ if (now - logStart >= std::chrono::seconds(10)) {
+ logStart = now;
+ log::info("moonlight", std::format("stream {} received={:.1f}fps decoded={:.1f}fps video={:.1f}Mbps decodeMs={:.2f} queueMs={:.2f} receiveMs={:.2f} hostMs={:.1f} dropped={} errors={} idr={}",
+ decoder.backendName(), receivedFps, decodedFps, videoMbps, decodeMs, queueMs, receiveMs, hostLatencyMs,
+ dropped.load(), errors.load(), idr.load()));
+ }
+ }
~Impl() {
if (dummyTarget) av_frame_free(&dummyTarget);
@@ -265,6 +286,7 @@ struct MoonlightSessionSource::Callbacks {
: (videoFormat & VIDEO_FORMAT_MASK_H265) ? CaptureCodec::Hevc
: (videoFormat & VIDEO_FORMAT_MASK_AV1) ? CaptureCodec::Av1 : CaptureCodec::None;
if (p.codec == CaptureCodec::None) return -1;
+ p.decoder.setStreamProfile(true);
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;
@@ -322,6 +344,8 @@ struct MoonlightSessionSource::Callbacks {
if (!LiWaitForNextVideoFrame(&handle, &du)) break;
int status = DR_OK;
++p.units;
+ p.bytes += uint64_t(std::max(0, du->fullLength));
+ p.updateRates();
const int64_t nowHost = host100ns();
const uint64_t nowLib = LiGetMicroseconds();
@@ -391,6 +415,12 @@ struct MoonlightSessionSource::Callbacks {
packet.duration = pipeline::Rational{nominal, 10000000};
packet.arrivalHost100ns = matchedArrival;
packet.decodedHost100ns = host100ns();
+ // D3D11VA (HEVC) pictures reach the graph through a borrowed view, not the AVFrame.
+ if (hardware && frame->format == AV_PIX_FMT_D3D11 && !p.decoder.hardwareSurface(packet.hardwareSurface)) {
+ ++p.errors;
+ LiCompleteVideoFrame(handle, DR_OK);
+ continue;
+ }
if (recovering) { packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity); recovering = false; }
auto fallback = fallbackColor(p.hdrStream);
@@ -407,8 +437,8 @@ struct MoonlightSessionSource::Callbacks {
info = self.info_;
}
info.color = packet.colorInfo;
- info.hardwareDecodeActive = frame->format == AV_PIX_FMT_D3D12;
- info.videoDecodePath = info.hardwareDecodeActive ? "d3d12va" : "software";
+ info.hardwareDecodeActive = frame->format == AV_PIX_FMT_D3D12 || frame->format == AV_PIX_FMT_D3D11;
+ info.videoDecodePath = p.decoder.backendName();
if (info.width != unsigned(frame->width) || info.height != unsigned(frame->height)) {
info.width = unsigned(frame->width);
info.height = unsigned(frame->height);
@@ -792,6 +822,9 @@ MoonlightStats MoonlightSessionSource::stats() const {
s.receiveMs = p_->receiveMs;
s.queueMs = p_->queueMs;
s.decodeMs = p_->decodeMs;
+ s.receivedFps = p_->receivedFps;
+ s.decodedFps = p_->decodedFps;
+ s.videoMbps = p_->videoMbps;
}
std::lock_guard lib(p_->libMutex);
if (p_->streaming.load() && s.state == MoonlightStats::State::Streaming) {
diff --git a/src/source/XboxSessionSource.cpp b/src/source/XboxSessionSource.cpp
index 64f32d6e..916ddb2a 100644
--- a/src/source/XboxSessionSource.cpp
+++ b/src/source/XboxSessionSource.cpp
@@ -421,6 +421,7 @@ void XboxSessionSource::decodeLoop() {
}
if (!seenKeyframe && !startsDecoding(unit.data)) { ++p.dropped; requestKeyframe(); continue; }
if (!p.decoderOpen) {
+ p.decoder.setStreamProfile(true);
if (!p.decoder.open(CaptureCodec::H264, p.width, p.height, nullptr, 0, p.desc.decodeDevice.get(), p.desc.decodeQueue.get())) {
log::error("xbox", "no usable H.264 decoder");
setState(XboxStats::State::Failed, L"没有可用的 H.264 解码器。");
diff --git a/src/ui/MoonlightModel.cpp b/src/ui/MoonlightModel.cpp
index a8d1d23c..c27ae3bd 100644
--- a/src/ui/MoonlightModel.cpp
+++ b/src/ui/MoonlightModel.cpp
@@ -17,6 +17,8 @@
#include "veyra/moonlight/Pairing.h"
#include "veyra/moonlight/StreamConfig.h"
+#include <format>
+
namespace veyra::ui {
namespace {
@@ -41,10 +43,14 @@ QString describe(const std::exception& e) {
}
constexpr int kVersion = 1;
+// Testers asked for the stream at full rate by default (2026-10-01): 150 Mbps is what a
+// wired gigabit LAN and Wi-Fi 6 carry comfortably; the slider goes to 500 Mbps.
+constexpr int kDefaultBitrateMbps = 150;
+constexpr int kMaxBitrateMbps = 500;
QVariantMap defaultSettings() {
return QVariantMap{
- {"res", "1080p"}, {"fps", 60}, {"bitrate", 0}, {"codec", 0}, {"hdr", false},
+ {"res", "1080p"}, {"fps", 60}, {"bitrate", kDefaultBitrateMbps}, {"codec", 0}, {"hdr", false},
{"audio", 2}, {"gamepad", true}, {"sops", false}, {"hostAudio", false}, {"captureInput", true},
};
}
@@ -52,7 +58,7 @@ QVariantMap defaultSettings() {
bool validSetting(const QString& key, const QVariant& value) {
if (key == "res") return QStringList{"720p", "1080p", "1440p", "4k", "native"}.contains(value.toString());
if (key == "fps") return QList<int>{30, 60, 90, 120, 144}.contains(value.toInt());
- if (key == "bitrate") { const int v = value.toInt(); return v == 0 || (v >= 1 && v <= 500); } // Mbps; 0 is automatic
+ if (key == "bitrate") { const int v = value.toInt(); return v >= 1 && v <= kMaxBitrateMbps; } // Mbps
if (key == "codec") return value.toInt() >= 0 && value.toInt() <= 3;
if (key == "audio") return QList<int>{2, 6, 8}.contains(value.toInt());
return key == "hdr" || key == "gamepad" || key == "sops" || key == "hostAudio" || key == "captureInput";
@@ -243,7 +249,10 @@ void MoonlightModel::applyInfo(Host& host, const moonlight::ServerInfo& info) {
host.httpsPort = info.httpsPort;
host.codecSupport = info.serverCodecModeSupport;
host.nvidia = info.nvidiaServerSoftware;
- host.paired = host.paired && info.paired; // the host may have forgotten us
+ // The host may have forgotten us, but only an HTTPS answer can say so. Discovery and
+ // first contact ask over plain HTTP, where Sunshine always reports "not paired";
+ // trusting that turned every saved pairing into "unpaired" (field report 2026-10-01).
+ if (info.pairStatusKnown) host.paired = host.paired && info.paired;
host.currentGame = info.currentGame;
host.online = true;
}
@@ -251,10 +260,20 @@ void MoonlightModel::applyInfo(Host& host, const moonlight::ServerInfo& info) {
// A host that was asked once, off the job queue: used for found hosts and manual adds.
void MoonlightModel::probe(const QString& address, int port, bool manual) {
std::erase_if(probes_, [](std::jthread& t) { return !t.joinable(); });
- probes_.emplace_back([this, address, port, manual](std::stop_token stop) {
+ // A host we already know is asked with its saved certificate (over HTTPS), so the
+ // answer can confirm the pairing instead of only saying "online".
+ QString cert;
+ int httpsPort = moonlight::kDefaultHttpsPort;
+ bool nvidia = false;
+ if (const Host* known = findByAddress(address, port); known && known->paired) {
+ cert = known->cert;
+ httpsPort = known->httpsPort;
+ nvidia = known->nvidia;
+ }
+ probes_.emplace_back([this, address, port, manual, cert, httpsPort, nvidia](std::stop_token stop) {
try {
const moonlight::Identity id = identity();
- moonlight::ServerClient client(id, moonlight::HostAddress{utf8(address), uint16_t(port)}, {}, moonlight::kDefaultHttpsPort, true);
+ moonlight::ServerClient client(id, moonlight::HostAddress{utf8(address), uint16_t(port)}, utf8(cert), uint16_t(httpsPort), !nvidia);
client.setCancel(&cancel_);
const moonlight::ServerInfo info = client.serverInfo(true);
if (stop.stop_requested()) return;
@@ -408,13 +427,35 @@ void MoonlightModel::pair(const QString& id) {
startJob(tr("配对中:请在主机的 Sunshine 网页(https://%1:47990 的 PIN 页面)输入上面的 PIN。").arg(h.address),
[this, h, pin](const std::atomic<bool>& cancel) -> std::function<void()> {
const moonlight::Identity id = identity();
+ // Still trusted with the certificate we saved? Then pairing again is not needed
+ // (and pairing an already paired client is what left hosts unreachable before).
+ if (!h.cert.isEmpty()) {
+ try {
+ moonlight::ServerClient check(id, moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
+ check.setCancel(&cancel);
+ const moonlight::ServerInfo info = check.serverInfo(true);
+ if (info.pairStatusKnown && info.paired) {
+ log::info("moonlight-ui", "pair: the host still trusts this computer; no PIN needed");
+ const QString hostId = h.id;
+ return [this, hostId, info] {
+ pin_.clear();
+ if (Host* host = find(hostId)) {
+ applyInfo(*host, info);
+ host->paired = true;
+ host->saved = true;
+ saveStore();
+ }
+ status_ = tr("这台电脑和主机仍是配对状态,不需要重新配对。");
+ if (apps_.isEmpty()) reloadApps();
+ };
+ }
+ } catch (const std::exception&) {}
+ }
moonlight::ServerClient client(id, moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, {}, uint16_t(h.httpsPort), !h.nvidia);
client.setCancel(&cancel);
const moonlight::ServerInfo info = client.serverInfo(true);
- if (info.paired) {
- // The host already trusts a client with this id. Nothing to do unless we lost its certificate.
- }
const moonlight::PairOutcome outcome = moonlight::pairWithHost(client, id, info, pin, &cancel);
+ log::info("moonlight-ui", std::format("pair: result={} detail={}", int(outcome.result), outcome.detail));
const QString hostId = h.id;
return [this, outcome, hostId, info] {
pin_.clear();
@@ -587,7 +628,14 @@ bool MoonlightModel::launchSelected(int appId) {
moonlight::ServerClient client(id, moonlight::HostAddress{utf8(h.address), uint16_t(h.port)}, utf8(h.cert), uint16_t(h.httpsPort), !h.nvidia);
client.setCancel(&cancel);
const moonlight::ServerInfo info = client.serverInfo();
- if (!info.paired) return [this] { status_ = tr("主机不再认得这台电脑,请重新配对。"); };
+ if (info.pairStatusKnown && !info.paired) {
+ log::warn("moonlight-ui", "launch: the host no longer trusts this computer");
+ const QString hostId = h.id;
+ return [this, hostId] {
+ if (Host* host = find(hostId)) { host->paired = false; saveStore(); }
+ status_ = tr("主机不再认得这台电脑(可能在 Sunshine 里被删除了),请重新配对。");
+ };
+ }
if (info.currentGame != 0 && info.currentGame != appId)
return [this] { status_ = tr("主机正在运行另一个游戏。先选它继续,或点「退出游戏」结束它(未保存的进度会丢失),再开始新的。"); };
if (moonlight::chooseVideoFormats(options.codec, options.hdr, info.serverCodecModeSupport, options.av1HardwareDecode) == 0)
@@ -632,7 +680,7 @@ void MoonlightModel::updateStream(bool active, const source::MoonlightStats& s)
{"state", names[size_t(s.state)]}, {"message", QString::fromStdWString(s.message)},
{"codec", qs(s.codec)}, {"hdr", s.hdr}, {"hardware", s.hardwareDecode},
{"width", int(s.width)}, {"height", int(s.height)}, {"fps", s.fps},
- {"receivedFps", s.receivedFps}, {"decodedFps", s.decodedFps},
+ {"receivedFps", s.receivedFps}, {"decodedFps", s.decodedFps}, {"videoMbps", s.videoMbps},
{"hostMs", s.hostLatencyMs}, {"receiveMs", s.receiveMs}, {"queueMs", s.queueMs}, {"decodeMs", s.decodeMs},
{"rttMs", s.rttMs}, {"rttVarianceMs", s.rttVarianceMs},
{"lost", double(s.fecFailed)}, {"recovered", double(s.fecRecovered)}, {"packets", double(s.videoPackets)},
diff --git a/tests/moonlight/MockHost.h b/tests/moonlight/MockHost.h
index e416e3c9..32062b38 100644
--- a/tests/moonlight/MockHost.h
+++ b/tests/moonlight/MockHost.h
@@ -230,7 +230,9 @@ private:
const auto replace = [&](const std::string& from, const std::string& to) { const auto at = info.find(from); if (at != std::string::npos) info.replace(at, from.size(), to); };
replace("<HttpsPort>48000</HttpsPort>", "<HttpsPort>" + std::to_string(httpsPort) + "</HttpsPort>");
replace("<currentgame>7</currentgame>", "<currentgame>" + std::to_string(currentGame.load()) + "</currentgame>");
- replace("<PairStatus>1</PairStatus>", std::string("<PairStatus>") + (pairedClientDer_.empty() ? "0" : "1") + "</PairStatus>");
+ // Like Sunshine: only an HTTPS request (which needs the paired client certificate)
+ // is told "paired"; plain HTTP always answers 0.
+ replace("<PairStatus>1</PairStatus>", std::string("<PairStatus>") + (tls && !pairedClientDer_.empty() ? "1" : "0") + "</PairStatus>");
return info;
}
if (q.command == "applist") return tls ? kAppListXml : fail(401, "The client is not authorized");
diff --git a/tests/moonlight/ModelTests.cpp b/tests/moonlight/ModelTests.cpp
index 0010a5a0..b8283899 100644
--- a/tests/moonlight/ModelTests.cpp
+++ b/tests/moonlight/ModelTests.cpp
@@ -77,6 +77,7 @@ int main(int argc, char** argv) {
check(entry.value("name").toString() == "DESKTOP-TEST" && entry.value("state").toString() == "unpaired", "it is listed by the name the host reports, unpaired");
check(model.state().value("selected").toString() == hostId, "and selected");
check(entry.value("saved").toBool(), "a manually added host is saved");
+ check(model.state().value("settings").toMap().value("bitrate").toInt() == 150, "a new host streams at 150 Mbps by default");
// --- pairing with the PIN the dialog shows
model.pair(hostId);
@@ -150,6 +151,18 @@ int main(int argc, char** argv) {
check(model.state().value("lastLabel").toString().contains("Desktop"), "the last stream is remembered for resuming");
check(waitFor([&] { return model.apps().size() == 3; }), "apps reload from the saved pairing (pinned certificate works)");
+ // --- finding the same host again (network search / adding by address) must not lose the pairing:
+ // the probe asks with the saved certificate; Sunshine says "not paired" to plain HTTP (field report 2026-10-01)
+ model.addHost(address);
+ check(waitFor([&] { return idle(model) && model.hosts().value(0).toMap().value("state").toString() != "checking"; }), "the second probe finishes");
+ waitFor([] { return false; }, 400); // let the probe answer land
+ check(model.hosts().size() == 1 && model.hosts().value(0).toMap().value("paired").toBool(), "a host found again stays paired");
+
+ // --- "pair" on a host that still trusts us needs no PIN
+ model.pair(hostId);
+ check(waitFor([&] { return idle(model); }), "the pairing check finishes");
+ check(model.state().value("paired").toBool() && statusOf(model).contains(QString::fromUtf8("不需要重新配对")), "pairing again is skipped while the host still trusts us");
+
// --- a host that no longer knows us
host.forgetPairing();
model.refresh();
diff --git a/tools/stream_decode_bench/main.cpp b/tools/stream_decode_bench/main.cpp
new file mode 100644
index 00000000..04b39024
--- /dev/null
+++ b/tools/stream_decode_bench/main.cpp
@@ -0,0 +1,159 @@
+// Stream decode bench: replays a recorded H.264/HEVC/AV1 stream through the same
+// CaptureCompressedDecoder (D3D12VA on a shared device) that the PC/Xbox stream
+// sources use, at the stream's frame rate, and reports how long each decode takes.
+// It keeps decoded pictures alive the way the engine does (one waiting in the
+// mailbox, one being read, two held by the graph) so pool pressure is realistic.
+//
+// usage: veyra_stream_decode_bench <file> [fps=60] [seconds=0 (whole file)] [--burst] [--software]
+// --burst feeds frames back to back instead of at the frame rate (throughput).
+#include <windows.h>
+#include <d3d12.h>
+#include <dxgi1_6.h>
+#include <wrl/client.h>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavcodec/bsf.h>
+#include <libavformat/avformat.h>
+#include <libavutil/frame.h>
+}
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <deque>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "veyra/source/CaptureCompressedDecoder.h"
+
+using Microsoft::WRL::ComPtr;
+using Clock = std::chrono::steady_clock;
+
+int wmain(int argc, wchar_t** argv) {
+ if (argc < 2) { std::printf("usage: veyra_stream_decode_bench <file> [fps] [seconds] [--burst]\n"); return 2; }
+ // FFmpeg takes UTF-8 file names on Windows.
+ const int bytes = WideCharToMultiByte(CP_UTF8, 0, argv[1], -1, nullptr, 0, nullptr, nullptr);
+ std::string path(size_t(std::max(bytes, 1)) - 1, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, argv[1], -1, path.data(), bytes, nullptr, nullptr);
+ const double fps = argc > 2 ? _wtof(argv[2]) : 60.0;
+ const double seconds = argc > 3 ? _wtof(argv[3]) : 0.0;
+ bool burst = false;
+ bool software = false;
+ for (int i = 1; i < argc; ++i) {
+ if (std::wstring(argv[i]) == L"--burst") burst = true;
+ if (std::wstring(argv[i]) == L"--software") software = true; // the fallback path
+ }
+
+ AVFormatContext* input = nullptr;
+ if (avformat_open_input(&input, path.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(input, nullptr) < 0) {
+ std::printf("cannot open %s\n", path.c_str());
+ return 1;
+ }
+ const int stream = av_find_best_stream(input, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
+ if (stream < 0) { std::printf("no video stream\n"); return 1; }
+ const AVCodecParameters* par = input->streams[stream]->codecpar;
+ veyra::source::CaptureCodec codec = par->codec_id == AV_CODEC_ID_H264 ? veyra::source::CaptureCodec::H264
+ : par->codec_id == AV_CODEC_ID_HEVC ? veyra::source::CaptureCodec::Hevc
+ : par->codec_id == AV_CODEC_ID_AV1 ? veyra::source::CaptureCodec::Av1 : veyra::source::CaptureCodec::None;
+ if (codec == veyra::source::CaptureCodec::None) { std::printf("unsupported codec\n"); return 1; }
+
+ // Annex-B for H.264/HEVC, like the stream sources receive it.
+ const AVBitStreamFilter* filter = av_bsf_get_by_name(par->codec_id == AV_CODEC_ID_H264 ? "h264_mp4toannexb"
+ : par->codec_id == AV_CODEC_ID_HEVC ? "hevc_mp4toannexb" : "null");
+ AVBSFContext* bsf = nullptr;
+ av_bsf_alloc(filter, &bsf);
+ avcodec_parameters_copy(bsf->par_in, par);
+ bsf->time_base_in = input->streams[stream]->time_base;
+ av_bsf_init(bsf);
+
+ std::vector<std::vector<uint8_t>> units;
+ size_t totalBytes = 0;
+ AVPacket* packet = av_packet_alloc();
+ while (av_read_frame(input, packet) >= 0) {
+ if (packet->stream_index == stream) {
+ av_bsf_send_packet(bsf, packet);
+ while (av_bsf_receive_packet(bsf, packet) == 0) {
+ units.emplace_back(packet->data, packet->data + packet->size);
+ totalBytes += size_t(packet->size);
+ av_packet_unref(packet);
+ }
+ }
+ av_packet_unref(packet);
+ }
+ av_packet_free(&packet);
+ av_bsf_free(&bsf);
+ const unsigned width = unsigned(par->width), height = unsigned(par->height);
+ avformat_close_input(&input);
+ if (units.empty()) { std::printf("no packets\n"); return 1; }
+ std::printf("%s: %zu units, %ux%u, average %.1f KB/unit (%.1f Mbps at %.0f fps)\n", path.c_str(), units.size(), width, height,
+ double(totalBytes) / units.size() / 1024.0, double(totalBytes) * 8.0 / units.size() * fps / 1e6, fps);
+
+ ComPtr<IDXGIFactory6> factory;
+ CreateDXGIFactory2(0, IID_PPV_ARGS(&factory));
+ ComPtr<IDXGIAdapter1> adapter;
+ factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter));
+ ComPtr<ID3D12Device> device;
+ if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) { std::printf("no D3D12 device\n"); return 1; }
+ D3D12_COMMAND_QUEUE_DESC qd{};
+ qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
+ ComPtr<ID3D12CommandQueue> queue;
+ device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue));
+
+ veyra::source::CaptureCompressedDecoder decoder;
+ decoder.setStreamProfile(true);
+ if (!decoder.open(codec, width, height, nullptr, 0, software ? nullptr : device.Get(), software ? nullptr : queue.Get())) { std::printf("decoder open failed\n"); return 1; }
+ std::printf("backend=%s\n", decoder.backendName());
+
+ // The engine-side holders: mailbox, current read, two graph parities.
+ std::deque<std::shared_ptr<AVFrame>> held;
+ std::vector<double> decodeMs;
+ const auto interval = std::chrono::duration<double>(1.0 / fps);
+ const size_t limit = seconds > 0 ? std::min(units.size(), size_t(seconds * fps)) : units.size();
+ const auto start = Clock::now();
+ size_t produced = 0, late = 0;
+ for (size_t i = 0; i < limit; ++i) {
+ if (!burst) {
+ const auto due = start + std::chrono::duration_cast<Clock::duration>(interval * double(i));
+ if (Clock::now() < due) std::this_thread::sleep_until(due);
+ else if (Clock::now() - due > interval) ++late;
+ }
+ AVFrame* target = av_frame_alloc();
+ target->format = 23; // NV12; only used if the decoder falls back to software
+ target->width = int(width);
+ target->height = int(height);
+ av_frame_get_buffer(target, 32);
+ AVFrame* out = nullptr;
+ bool hardware = false;
+ const auto begin = Clock::now();
+ const bool ok = decoder.decode(units[i].data(), units[i].size(), int64_t(i) * 166667, target, &out, hardware);
+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - begin).count();
+ decodeMs.push_back(ms);
+ if (ok && out) {
+ ++produced;
+ AVFrame* clone = hardware ? av_frame_clone(out) : target;
+ if (hardware) av_frame_free(&target);
+ held.emplace_back(clone, [](AVFrame* f) { av_frame_free(&f); });
+ while (held.size() > 4) held.pop_front();
+ } else {
+ av_frame_free(&target);
+ }
+ }
+ const double wall = std::chrono::duration<double>(Clock::now() - start).count();
+ held.clear();
+ std::vector<double> sorted = decodeMs;
+ std::sort(sorted.begin(), sorted.end());
+ double sum = 0;
+ for (double v : decodeMs) sum += v;
+ const auto pct = [&](double p) { return sorted[std::min(sorted.size() - 1, size_t(p * double(sorted.size())))]; };
+ std::printf("frames=%zu produced=%zu wall=%.2fs throughput=%.1f fps late=%zu\n", limit, produced, wall, double(limit) / wall, late);
+ std::printf("decode ms: avg=%.2f p50=%.2f p95=%.2f p99=%.2f max=%.2f\n", sum / double(decodeMs.size()), pct(0.5), pct(0.95), pct(0.99), sorted.back());
+ int over = 0;
+ for (double v : decodeMs) if (v > 1000.0 / fps) ++over;
+ std::printf("decodes slower than one frame interval: %d\n", over);
+ std::printf("final backend=%s fallbacks=%llu failures=%llu\n", decoder.backendName(),
+ (unsigned long long)decoder.hardwareFallbacks(), (unsigned long long)decoder.decodeFailures());
+ return 0;
+}