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: recover Xbox video after decode errors and compressed frame loss

Veyra Goal Agent81b755bf012f
diff --git a/AGENTS.md b/AGENTS.md
index f30fed46..8d99b2de 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-05 当前采集/Xbox现场反馈**:用户提交 `logs(4).7z`,最后明确 `veyra-qml(28).log` 为“xbox问题”。按 `docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md` 在 E 盘 `capture-xbox-field-20261005` / `codex/capture-xbox-field-20261005` 从 `33d6685` 隔离排查修复。这次仅涉及 Xbox 视频错误/丢AU后的关键帧恢复、有界硬解重开与必要软件回退、采集时间线诊断标签、定向测试/文档/本地候选;覆盖这些接点的历史冻结,不改 NR/颜色/补帧算法或串流协议。每轮先运行 `py -3.11 -B scripts/acceptance/capture-xbox-control.py`,不可变基线独立于旧 guards;main、其它 18 个工作区、用户配置和已有包保留。无新 merge/push/Release、压力测试、关机或子 Agent 授权;所有产物 E 盘,真实 Xbox/AMD 效果未实测不得称通过。
+
> **2026-10-05 NR 强度与画面调控授权**:用户明确要求“自动调控做为开关,在NR里,也可以选择手动调节,然后保留原版的强度5,开始吧搞定他”。仅在 `E:/项目/Veyra/worktrees/nr-strength-protection-20261005` / `codex/nr-strength-protection-20261005` 从本地 main `de18fc4` 隔离实施。按 `docs/NR_STRENGTH_PROTECTION_PLAN_2026-10-05.md` 修改共享 NR settings/预设/会话、graph/时域接点、残差 shader、QML bridge/逐层面板、翻译、来源 notice、必要 CMake/定向测试与本地打包;此明确范围覆盖历史 UI-only 冻结。默认调控关闭,保留原有路径及总变化量 0–5;自动和手动设置分别保存,不更换、修改或下载 NR DLL,不改采集/解码/音频/补帧/旧 Win32。允许本轮必要 commit/tag/源码 bundle 存档和完整本地候选交付,不包含新 merge/push/Release/关机,不派 Agent。所有产物 E 盘,测试每进程≤300秒、构建≤900秒,不制造 GPU 压力。每轮先运行 `py -3.11 -B scripts/acceptance/nr-protection-control.py guard`;旧 guard/baseline 保留,当前不可变基线独立保存。
> **2026-10-05 本地 main 合并授权**:用户在 Codex 接管 Claude 最新验收和现场修复后明确要求“先合并到main,然后有其他修复等你做”。本次允许提交继承的未提交修复、存档、打标签和本地合并;已将 NR 性能分支及 `claude/field-fixes-20261005` 修复提交 `6e9d827` 合入本地 `main`,合并提交 `f7ced91`。此条覆盖这批工作的历史“不 merge”限制;不包含新的 push/Release、旧 UI 删除或剩余修复实施授权。合并记录见 `docs/MERGE_MAIN_2026-10-05.md`,后续新修复按用户下一条具体要求处理。来源分支和其他工作树保留,桌面旧工作区与用户配置不改,运行库/SDK/模型不得进入源码 Git。
diff --git a/docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md b/docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md
new file mode 100644
index 00000000..a7bf5fed
--- /dev/null
+++ b/docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md
@@ -0,0 +1,125 @@
+# 采集帧率与 Xbox 解码恢复:现场修复记录
+
+本轮按用户最后确认的 `veyra-qml(28).log` 处理 Xbox 补帧后画面停止,
+保留 `logs(4).7z` 的采集帧率诊断。26 是被更正的本地文件播放日志,不代替 Xbox。
+日志、SDP 和转储只作证据;没有连接用户账号、Xbox 或真实 AMD 主机。
+
+## 证据能够说明什么
+
+- Xbox:RX9070XT,H.264 D3D12VA,1080p 输入,4K 工作尺寸。
+ 原日志第 2597 行首次报错,时间 `2026-10-05T06:35:07.516Z`;第 9341 行最后报错,
+ `06:41:00.274Z`。487 条 ERROR 全部是
+ `decoder: send_packet failed code=-22 text=Invalid argument`。
+ FSR4 FG provider 4.0.1 的独立 context 在 `06:35:07.658Z` 有初始化记录,
+ 但解码错误继续;有声音和已建好的 FG context 不代表视频仍推进。
+ 一次 engine-stall 的 total 为 34528.187ms、tail 为 34124.415ms。
+ 这些证据确定了解码持续失败、宿主恢复缺口,不能确定触发 EINVAL 的 driver/FG/位流原因。
+- 采集:RTX5080,2560×1440 RGB24,标称 60Hz,4K RTX SR + 1440p NR + DLSS3X。
+ session2/revision16 的 59 个窗口,callback FPS 中位 60、GPU 完成 FPS 中位 55;
+ source PTS 和 sample duration 中位 16.667ms。
+ 第 5565→6363 行的 55.608s,received +3337(60.009/s)、processed +3028(54.453/s)、
+ mailbox dropped +308。源输入继续约 60Hz,消费处理欠速。
+ 滚动 GPU-ready P95 的窗口中位为 18.269ms,不能把 P95 当平均单帧耗时或把各阶段 P95 相加。
+ 软件提交/完成 FPS 也不是物理屏幕刷新率或屏幕端到端延迟。
+- 7z 中另有 crash dump,保留原始证据,本次不对它作未经定位的根因归属。
+
+输入复本与 manifest 在 `E:/项目/Veyra/logs/capture-xbox-field-20261005/input/`;
+`capture-xbox-evidence.py` 校验原 SHA256 并写不含 SDP/凭据的 `field-evidence.json`。
+原始日志和转储不进 Git、源码包或用户便携包。
+
+## 修改与对抗检查
+
+1. `XboxSessionSource.cpp` 的错误路径原先只请求关键帧。现在在硬错误以及压缩 AU 队列溢出后
+ 调用现有 `recoverAtKeyframe()` 清参考链、清待匹配元数据,并沿用 500ms 的关键帧请求限流。
+ 队列丢帧的断点挂在第一条幸存 AU;反复溢出会传递断点,连续输入不会凭空多次 reset。
+2. `VideoDecodeRecovery.h` 给每个连接一份有界预算:单次错误清历史;三个连续硬错误才允许
+ 一次硬解重开;再次持续失败可回退一次软件。成功出帧只清连续错误,不补充重开预算。
+ 软件仍连续失败则明确结束,不循环挂着旧画面。NeedInput 不计入硬错误。
+3. 首个恢复画面带 Discontinuity,复用共享图的 SR/NR/FG/flow 历史 reset;latest mailbox
+ 已有的 flags 传播保留此断点。原始 RTP、arrival、音频和序号继续,不重新编造一条 60fps 时间线。
+4. 会话的 ready/end 更新原先可能覆盖 decoder 的 Failed 状态并清空原因,现在保留失败状态和信息。
+ 状态查询改读原子 `hardwareDecodeStatus`,不并发读取正在 close/open 的 worker-owned decoder。
+ decoder 的所有操作仍在原解码线程;没有给逐帧增加 CPU fence wait 或像素回读。
+5. `EngineController.cpp` 只把采集诊断的 pacing 条件从 `pairAnchoredLive` 改为实际 `pairPacing`。
+ 无 FG 的物理采集原本 ready-driven,日志却可能写 capture-pair;调度行为和帧率数字未改。
+ Claude 已完成的 source-step cadence、丢帧相位和电源节流修复仍保留。
+
+没有修改 NR/颜色/SR/补帧算法、协议、音频链或运行库字节。
+新增及修改共 14 个作用域文件:上述三个产品文件,两个现有测试文件,五个
+`scripts/acceptance/capture-xbox-*.py`,AGENTS/WORKLOG/本轮 PLAN/本记录。
+
+## 构建与本地验收
+
+工作树 `E:/项目/Veyra/worktrees/capture-xbox-field-20261005`,
+分支 `codex/capture-xbox-field-20261005`,起点 `33d6685a3a75d3d4e8ac5d32996b163ef1f488dc`。
+测试每进程 timeout≤290s,构建≤890s;仅普通负载,一个 GPU 测试进程一次,没有竞争/压力程序。
+所有 TEMP/TMP 只对子进程定向到 E 盘本任务。
+
+| 检查 | 命令与实际证据 |
+| --- | --- |
+| 生产构建 | `py -3.11 -B scripts/acceptance/capture-xbox-build.py build7`;QML app、Xbox、codec、scene、timing 五目标退出 0。继承 field-fixes/B 的 patched FFmpeg + dav1d、Qt6.8.3、静态 libass,保留已有第三方编译 warning,未把 warning 称为零。`logs/.../build7.log`。 |
+| Xbox 本地协议及预算 | `capture-xbox-tests.py xbox1 xbox`:97 checks / 0 failures,包含新恢复策略/队列断点反例及本地 loopback WebRTC。未传 `--live-device-code`,没有远端登录。 |
+| 既有场景节奏 | `capture-xbox-tests.py scene1 scene`:18 / 0,真实断档仍 reset,预览跳源帧不引起伪节奏断档。 |
+| 既有采集/实时调度合同 | `capture-xbox-tests.py timing1 timing`:78 PASS,包含标称间隔、真实源 PTS、缺 B 输入保留旧完整 pair、mailbox 边界、实际 FPS 衰减等。 |
+| H.264 真实解码 | 最终 `codec10`(无 B)/`codec11`(B2)均 ALL PASS 0;使用现有 GTA6 片段在 E 盘生成 1080p30/4s、GOP30 的本地夹具,明确传媒体参数,不接受 SKIP。验证 EAGAIN 重送、D3D11VA 反复 open/close、软/硬解、丢 AU 后关键帧的像素/PTS、坏包后的 flush、硬解重开与软件替换,并持有旧 D3D12 AVFrame lease 跨 close/open。无 B 输出120/120;B2 在未发送 EOF 的实时接口下输出118/118,完整 EOF packet-retry 对照120帧。两种后端恢复 IDR PTS 都是10000000。 |
+| 完整便携包 | 最终 `smoke-AMD3` / `smoke-NVIDIA3` 均 PASS / exit0;干净 PATH、独立 `--data-dir`,MKV ASS events=5、内嵌字体 container=1,无 Qt/产品 ERROR。AMD 包在 RTX 上仅验证可启动及基础路径,不冒充 AMD NR/FSR4 推理。 |
+| 生产补帧/NR 回归 | 最终 `hot-NVIDIA3` 43.828s / PASS:FSR3.1→XeSS2X→DLSS2X→FSR3.1→关闭,实际 provider 和源位置继续;再测试原版 NR 两层强度5、风格1自动/风格2手动及 PNG,Main.qml 注入在 finally 原字节恢复。实际软件提交读数均60FPS,非物理屏幕或真实Xbox读数。 |
+
+以上脚本从本工作树运行:
+
+```powershell
+py -3.11 -B scripts/acceptance/capture-xbox-control.py
+py -3.11 -B scripts/acceptance/capture-xbox-evidence.py
+py -3.11 -B scripts/acceptance/capture-xbox-tests.py codec10 codec 'E:/项目/Veyra/tests/capture-xbox-field-20261005/recovery-h264-1080p30-b0.mp4'
+py -3.11 -B scripts/acceptance/capture-xbox-tests.py codec11 codec 'E:/项目/Veyra/tests/capture-xbox-field-20261005/recovery-h264-1080p30-b2.mp4'
+py -3.11 -B scripts/acceptance/capture-xbox-tests.py smoke-AMD3 smoke 'E:/项目/Veyra/test-packages/capture-xbox-field-20261005/Veyra-2.0.3-streamfix1-AMD-win64-portable'
+py -3.11 -B scripts/acceptance/capture-xbox-tests.py smoke-NVIDIA3 smoke 'E:/项目/Veyra/test-packages/capture-xbox-field-20261005/Veyra-2.0.3-streamfix1-NVIDIA-win64-portable'
+py -3.11 -B scripts/acceptance/capture-xbox-tests.py hot-NVIDIA3 hot 'E:/项目/Veyra/test-packages/capture-xbox-field-20261005/Veyra-2.0.3-streamfix1-NVIDIA-win64-portable'
+py -3.11 -B scripts/acceptance/capture-xbox-package.py finalize
+```
+
+### 失败和测试判据修正
+
+- `codec1` 因继承测试入口的 ANSI argv 无法打开中文绝对路径而 SKIP,runner 明确判失败;
+ 改为 E 盘独立 cwd 下的 ASCII 相对文件名,并 hash 验证夹具复制。
+- `codec2` 的旧 12s 长 GOP/B 帧夹具不适合这个有界恢复验证;原断言还把当前输入包 PTS 当成
+ 重排序输出的 PTS。改为 GOP30 的多 IDR 夹具,按下一 IDR 自己的 PTS 检查,不通过改产品 PTS 取巧。
+- `codec4/5` 想用连续坏包制造九次硬错误,但 NONKEY discard 会合法地将部分坏包变为 NeedInput。
+ 保留失败记录;CPU 预算测试验证连续错误决策,真实 codec 测试分别验证真实坏包后 flush 和
+ decoder 替换/旧帧寿命,不把等待输入伪造成错误。本地坏包为 InvalidData,未复制 AMD 的 EINVAL 触发器。
+- `hot-NVIDIA1` 以固定 5s 等待误判 DLSS 源位置停止;记录显示 context 创建 9293.573ms,
+ 断言退出前已经有真实/生成帧提交。改为 provider ready 后再观察位置的连续推进,保留 180s 总期限;
+ 不把首次初始化耗时当成永久卡死,也不因此改补帧算法。`hot-NVIDIA2` 已通过修正判据。
+- 首次 staging 复制了旧 NVIDIA 包后来生成的五份本地配置。副本从本轮候选移至本轮私有 logs
+ 下 quarantine;原包和配置不修改。打包现在只复制原 manifest 列出的 payload,明确排除 user-data。
+ refresh 曾因源包新增配置不存在于候选而中止,未以忽略运行库 hash 的方式放过;该错误已修复。
+
+## 交付、存档与剩余缺口
+
+新候选在 `E:/项目/Veyra/test-packages/capture-xbox-field-20261005/`,AMD/NVIDIA 同一个 EXE,
+版本 `2.0.3-streamfix1`,最终 SHA256/源码 commit/所有 payload hash 以该目录 `DELIVERY.json` 为准。
+生产 EXE SHA256 `0450db056d0611cb416d5594981fa1ac6e28128fc5b0e4ef5e1f14b96e1c0ddb`,
+Main.qml SHA256 `d33df73b6f84efd7109e4dcfd428453740d04b9d8538e37800a19c49c98a4632`。
+最终打包在上述检查通过后执行,不以本机短测称为已验真实主机。
+本地验收存档标签为 `checkpoint/capture-xbox-field-code-verified-20261005`;
+源码 ZIP、已验证的 final bundle 和两包 ZIP 的最终身份在外置 DELIVERY/日志中记录。
+finalize 只有在 git clean、测试对应同一个 EXE、QML 原字节恢复、所有组件 hash 一致时才执行,
+并验证 ZIP CRC 与每个 payload 的 SHA256。SOURCE/代码验收与真实 Xbox 未验边界分开报告。
+
+继承的运行组件原字节:NVIDIA 215 项、AMD 686 项;没有新 proprietary runtime、模型、DLL 修改。
+旧 AMD 模板早于 libass,补入同 EXE 的八份已审计 libass/字体依赖版权通知;
+保留原依赖源码下载地址和 vcpkg `30ef65cad9` 的 libass 对应构建说明。
+新 application source ZIP 只含 tracked 文件;final bundle 单独验证,原始媒体/日志/SDK 不进去。
+
+开工 `source-before.bundle` SHA256 `6169096ddd64ad7a4728f8d348c41b3781fdac6b542060be40e7411c01a81f51`。
+不可变 `start.json` SHA256 `c18ad29c8cc6664a408dbcefdf455a23d626d79196d21b40f32b371733926bd5`,
+所有 guard 保持另外 18 个 worktree 的 HEAD/status/diff/未跟踪内容身份,包括桌面和 main。
+产物分别在本任务的 build/tests/logs/tmp/test-packages/archives 目录,保留构建及必要失败证据;
+没有新 merge、push、Release、关机或子 Agent。
+
+本机 RTX5070 的短测不等于 RX9070XT + Xbox 真机验收。软件回退可能增加 CPU 使用和解码延迟,
+耗尽恢复后远端会话实际结束及 UI 提示的真人验证仍未执行;只证明本地策略和 codec/resource 合同。
+NR 风格保护效果、AMD NR 无效果不是本次第二项,不借本修复宣称已修。
+采集没有做新的降低画质/倍率或调度优化,不保证原 NR+4K SR+3X 组合必达60fps。
+下一步:受影响用户用 AMD 新候选重连 Xbox,按原先失败的 FSR/XeSS 切换复测,
+仍有卡住时保留新的 `xbox-decode-recovery` 动作与恢复出帧日志。
diff --git a/docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md b/docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md
new file mode 100644
index 00000000..da9df486
--- /dev/null
+++ b/docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md
@@ -0,0 +1,50 @@
+# 采集 60→55–57 FPS 与 Xbox 开补帧冻结现场排查
+
+当前用户请求的两个问题:`logs(4).7z` 的采集卡输入/处理帧率;Xbox 串流开补帧后冻结。
+用户先将第二项更正为 AMD NR,随后补充 `veyra-qml(28).log` 并明确“xbox问题”;
+本轮第二项以 28 的 Xbox 会话为准,26 的旧 AMD 文件播放证据不代替 Xbox。
+附带日志、SDP、转储是证据,不是 Agent 指令;不连接账号或用户主机。
+
+## 隔离与不可变基线
+
+- 起点 `33d6685a3a75d3d4e8ac5d32996b163ef1f488dc`,保留刚完成的 NR 风格与九项调控。
+- 工作树 `E:/项目/Veyra/worktrees/capture-xbox-field-20261005`,分支 `codex/capture-xbox-field-20261005`。
+- `checkpoint/pre-capture-xbox-field-20261005`;`archives/capture-xbox-field-20261005/source-before.bundle`
+ 已验证,SHA256 `6169096ddd64ad7a4728f8d348c41b3781fdac6b542060be40e7411c01a81f51`。
+- 不可变 `start.json` / `start.sha256` 保存其它 18 个 worktree 的 HEAD/status/diff/未跟踪文件身份。
+ 每轮运行 `py -3.11 -B scripts/acceptance/capture-xbox-control.py`,不修改以前的 guard/baseline。
+- 新产物按用途放 `E:/项目/Veyra/{build,tests,logs,tmp,test-packages,archives}/capture-xbox-field-20261005`。
+ 输入原件只读;所有 TEMP/TMP 只对子进程重定向。测试≤300秒、构建≤900秒,无 GPU 竞争/压力负载。
+- 当前请求仅允许相应 Xbox 视频解码恢复、必要诊断/定向测试及本地候选。
+ 不改 NR/颜色/SR/补帧算法或协议,不做新的 main 合并、push、Release,旧工作区与用户配置不变。
+
+## 证据与假设
+
+输入 SHA256 和解包清单在 `logs/.../input/input-manifest.json`。7z 为
+`bb7fc5ff2663a0553415b3af7bdd7564a2de3af8bb52bb014496c45956487efb`,
+28 为 `458848912364339a592190f86b7ee772016ce7b691a52ed7c5db20c38981180a`。
+
+1. 采集日志 RTX5080/616.92、2560×1440 RGB24 60 Hz,回调和 PTS/sampleDuration 为 16.667ms。
+ 第一会话 revision16 的 59 个 1s 窗口,GPU完成FPS中位55,输入回调中位60。
+ 4K RTX Video SR + 1440p NR + 光流 + DLSS3X;滚动GPU就绪P95中位18.269ms。
+ 同窗口 received 从20673到24010,processed从180到3208、mailbox dropped从1416到1724。
+ 这些值不能冒充整机物理显示FPS/端到端延迟,多个阶段P95不能相加当作平均单帧耗时。
+2. 严重后台历史连锁重置在 Claude 已修(源序号折算节奏、丢帧用标称相位、电源节流退出),起点包含。
+ 保留针对真实断档/跳帧的旧测试。仅修正日志在无FG时误写 capture-pair 的标签;不篡改源PTS或帧率数字。
+ 55–57的现有证据是处理欠速,不能承诺只改时间线便恢复所有增强组合60fps。
+3. 28 是 RX9070XT 的真实 Xbox/H.264 D3D12VA,FSR4 FG与XeSS初始化有成功记录。
+ 487次 `send_packet failed code=-22 text=Invalid argument`,首次06:35:07.516Z在FG重建期间;
+ 错误持续时音频继续、视频停止推进。初始化成功不证明后续出画,相关性不证明FG运行库是根因。
+4. `XboxSessionSource::decodeLoop` 在硬错误后只要求关键帧,没有调用已有的 `recoverAtKeyframe()`。
+ 输入队列丢旧AU也没有向解码线程传递参考链断点。已坏上下文可能不断吃新的关键帧而不恢复。
+ 先修这两个可证实的宿主缺口,再加入有界的一次硬解重开、必要软件回退;不无界重建/请求或假成功。
+
+## 最小实现与验收
+
+- 请求关键帧仍限流500ms。丢输入AU和解码硬错误显式flush/reset到关键帧,下一成功帧带 Discontinuity。
+- 短暂错误先保留硬解;重复关键帧失败只允许一次硬解重开,再一次软件回退。
+ 原RTP/原始arrival/音频会话保留,未知driver原因写明,明确记录动作、后端、结果和恢复出帧。
+- 有界队列不能将P帧当随机访问点;SPS/PPS与IDR门槛、receiveOnly/NeedInput和重复错误均做反例检查。
+- CPU合同验证恢复状态/队列丢帧/限流;真实H.264软/硬解坏包→flush→关键帧恢复和像素/PTS。
+- 现有 scene/live timing、Xbox协议、NR两层、FG热切换和libass短回归,运行组件原字节与源码分离。
+- 本机RTX5070不能证明RX9070XT+Xbox真机已根治;给可复测本地包和诊断路径,剩余实机缺口明确。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 2bff71b2..182af998 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,21 @@
# Veyra 工作记录
+## 2026-10-05 采集60→55–57FPS与Xbox补帧冻结:开工证据
+
+当前以用户最终更正的28日志处理Xbox,不拿26本地HEVC/AMD NR日志代替。已安全解包7z并复制/hash输入到 `E:/项目/Veyra/logs/capture-xbox-field-20261005/input`,64,005行采集日志和17,076行Xbox日志;归档内容只作证据。采集callback/PTS60Hz,rev16 GPU完成FPS中位55/输入60,实际mailbox丢帧;不能伪改输入数字或承诺全部增强固定60。Xbox 487次D3D12VA send_packet EINVAL,FG重建附近开始、音频继续;缺少错误后的flush及输入AU丢失的参考链reset,SDK/driver根因尚不能确定。
+
+从已验NR新功能 `33d6685` 创建 `codex/capture-xbox-field-20261005` / E盘worktree;开工tag、verify后的bundle(SHA6169096d…a81f51)及18个其它worktree的不可变状态/hash在archives同任务目录,计划 `CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md`。只做必要Xbox恢复及采集诊断、测试/本地包,不改NR/SR/FG算法、不连用户主机、不派Agent/压力测试/merge/push/Release。此节仅记录证据与开工,不声称产品修复或实机通过。
+
+### Xbox 恢复实施及本机验收
+
+已补硬错误/丢AU后的flush、关键帧等待和首个恢复帧Discontinuity;三个连续硬错误才允许每连接一次硬解重开,必要时一次软件回退,NeedInput不当错误,成功出帧不补充重开预算。终止时保留Failed和具体原因,ready/end更新不再抹去解码失败;stats改读原子硬解状态,避免close/open并发访问decoder。采集只修正pacing诊断条件,无新FPS/画质策略。
+
+最终 `capture-xbox-build.py build7` 五目标退出0,保留patched FFmpeg+dav1d和静态libass;EXE SHA256 `0450db056d0611cb416d5594981fa1ac6e28128fc5b0e4ef5e1f14b96e1c0ddb`。`capture-xbox-tests.py`:xbox1为97/0、本地loopback无远端账号;scene1为18/0;timing1为78 PASS;codec10/11无B/B2均ALL PASS 0,真实软/硬解、EAGAIN、丢包像素/PTS、坏包flush、硬解重开/软件替换和旧D3D12帧lease有效。smoke-AMD3/NVIDIA3干净PATH/独立profile均PASS,真实libass内嵌字体和5事件字幕;hot-NVIDIA3为43.828s/PASS,FSR3.1→XeSS→DLSS→FSR3.1→关闭后两层原版NR强度5、风格1自动/2手动继续播放及PNG。实际命令、失败(ANSI夹具、B重排序、NeedInput注入误判、首次DLSS创建约9s误判)和证据见 `docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md`,不把失败抹为通过。
+
+候选 `E:/项目/Veyra/test-packages/capture-xbox-field-20261005/Veyra-2.0.3-streamfix1-{AMD,NVIDIA}-win64-portable`,相应source ZIP、bundle、ZIP/逐文件hash与最终交付摘要在该任务的test-packages/archives/logs。NVIDIA 215项、AMD 686项已批准组件原字节保留;AMD补同EXE需要的8份libass依赖版权通知,无新运行二进制。只复制旧manifest payload并排除旧包后生成的用户配置,误继承副本隔离到本任务logs,原包/用户配置不改。14文件guard保持其余18工作树/main/桌面身份不变;本地commit/tag存档,无新merge/push/Release或关机。
+
+RX9070XT+真实Xbox、现场耗尽恢复的结束/UI提示、实卡采集与长稳未执行。软件回退可能增加CPU/解码耗时;487次EINVAL的底层触发器未确定。本次不是AMD NR无效果修复,也没有证明采集原增强组合已到60FPS;现场counter证明输入60.009/s、处理54.453/s。下一步仅受影响用户用新AMD候选复测原FSR/XeSS切换并保留新恢复日志。
+
## 2026-10-05 NR 风格 1/2 色偏与调控参数续修
用户反馈原版 NR 强度 5 的风格 1/2 色偏较大、旧手动控制主要局部压缩明显;接续已验首轮 `9eb3b1c`,原包保留。tag `checkpoint/pre-nr-style-controls-20261005` 与续修前 bundle `E:/项目/Veyra/archives/nr-strength-protection-20261005/style-controls/source-before.bundle`(SHA256 `19703EFD383E2B012AF6FFDE0663395CB2276D0A9FCA3D524DD6AE16D2EBF42C`)已核验。三个风格原本均已接入,问题是共用规则遗漏低色度染色及亮度变化后的饱和度,已分别设置自动参数。
diff --git a/include/veyra/xbox/VideoDecodeRecovery.h b/include/veyra/xbox/VideoDecodeRecovery.h
new file mode 100644
index 00000000..aee26fd7
--- /dev/null
+++ b/include/veyra/xbox/VideoDecodeRecovery.h
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include <cstddef>
+
+namespace veyra::xbox {
+enum class VideoDecodeRecoveryAction { ResetHistory, ReopenHardware, UseSoftware, Stop };
+
+// A bad decoder must not be retried forever with new IDRs. Keep transient
+// loss on hardware, reopen that context once, then fall back once per session.
+// A successful picture clears consecutive errors, not the bounded reopen budget.
+class VideoDecodeRecovery {
+public:
+ VideoDecodeRecoveryAction failed(bool hardware) {
+ if (++consecutiveFailures_ < 3) return VideoDecodeRecoveryAction::ResetHistory;
+ consecutiveFailures_ = 0;
+ if (hardware && !hardwareReopened_) {
+ hardwareReopened_ = true;
+ return VideoDecodeRecoveryAction::ReopenHardware;
+ }
+ if (hardware && !softwareUsed_) {
+ softwareUsed_ = true;
+ return VideoDecodeRecoveryAction::UseSoftware;
+ }
+ return VideoDecodeRecoveryAction::Stop;
+ }
+ void picture() { consecutiveFailures_ = 0; }
+private:
+ unsigned consecutiveFailures_ = 0;
+ bool hardwareReopened_ = false, softwareUsed_ = false;
+};
+
+// Call while holding the source queue lock, before adding the new AU. Loss
+// belongs to the first surviving AU, even when the IDR itself was discarded.
+template<class Queue>
+std::size_t trimVideoInputs(Queue& queue, std::size_t capacity) {
+ if (!capacity) capacity = 1;
+ std::size_t dropped = 0;
+ while (queue.size() >= capacity) { queue.pop_front(); ++dropped; }
+ if (dropped && !queue.empty()) queue.front().inputLoss = true;
+ return dropped;
+}
+}
diff --git a/scripts/acceptance/capture-xbox-build.py b/scripts/acceptance/capture-xbox-build.py
new file mode 100644
index 00000000..d00c2f8a
--- /dev/null
+++ b/scripts/acceptance/capture-xbox-build.py
@@ -0,0 +1,31 @@
+"""Build this isolated repair with the current libass/patched FFmpeg dependencies."""
+from pathlib import Path
+import os, subprocess, sys
+ROOT=Path(__file__).resolve().parents[2]; BASE=Path('E:/项目/Veyra'); TASK='capture-xbox-field-20261005'
+label=sys.argv[1];assert label.replace('-','').isalnum()
+BUILD=BASE/'build'/TASK; TMP=BASE/'tmp'/TASK/'build'; LOG=BASE/'logs'/TASK/(label+'.log')
+for p in (BUILD,TMP,LOG.parent):p.mkdir(parents=True,exist_ok=True)
+guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/capture-xbox-control.py')]
+subprocess.run(guard,check=True)
+settings=[];cache=BASE/'build/field-fixes-20261005/B/CMakeCache.txt'
+for line in cache.read_text(encoding='utf8').splitlines():
+ if ':' not in line or '=' not in line or line.startswith(('#','//')):continue
+ keytype,value=line.split('=',1);key,kind=keytype.split(':',1)
+ if kind in ('INTERNAL','STATIC') or key=='VEYRA_DISPLAY_VERSION':continue
+ if key.startswith('VEYRA_') or key in ('CMAKE_PREFIX_PATH','CMAKE_MAKE_PROGRAM','PROTOC','PKG_CONFIG_EXECUTABLE'):
+ if key=='VEYRA_LIBASS_ROOT':assert (Path(value)/'include/ass/ass.h').is_file()
+ settings.append(f'set({key} [[{value}]] CACHE {kind} "Accepted dependencies" FORCE)')
+assert any('VEYRA_LIBASS_ROOT' in l for l in settings)
+settings.append('set(VEYRA_DISPLAY_VERSION [[2.0.3-streamfix1]] CACHE STRING "Local field repair" FORCE)')
+(TMP/'dependencies.cmake').write_text('\n'.join(settings),encoding='utf8')
+targets=sys.argv[2:] or ['veyra_qml_ui','veyra_xbox_tests','veyra_capture_compressed_tests','veyra_scene_tests','veyra_live_timing_tests']
+assert all(t.replace('_','').isalnum() for t in targets)
+cmd=TMP/'build.cmd'
+cmd.write_text('@echo off\nchcp 65001 >nul\ncall "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat" >nul 2>&1\nif errorlevel 1 exit /b 4\n"%TASK_CMAKE%" --preset x64-release -S "%TASK_ROOT%" -B "%TASK_BUILD%" -C "%TASK_TMP%\\dependencies.cmake"\nif errorlevel 1 exit /b 5\n"%TASK_CMAKE%" --build "%TASK_BUILD%" --parallel 6 --target '+ ' '.join(targets)+'\nexit /b %errorlevel%\n',encoding='ascii')
+env=os.environ.copy();env.update(TEMP=str(TMP),TMP=str(TMP),VSLANG='1033',TASK_ROOT=str(ROOT),TASK_BUILD=str(BUILD),TASK_TMP=str(TMP),TASK_CMAKE='C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe')
+with LOG.open('x',encoding='utf8') as out:
+ try:rc=subprocess.run(['cmd.exe','/d','/c',str(cmd)],cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,timeout=890).returncode
+ except subprocess.TimeoutExpired:rc=124
+print('BUILD',rc,LOG);print('\n'.join(LOG.read_text(encoding='utf8',errors='replace').splitlines()[-22:]))
+subprocess.run(guard,check=True)
+raise SystemExit(rc)
diff --git a/scripts/acceptance/capture-xbox-control.py b/scripts/acceptance/capture-xbox-control.py
new file mode 100644
index 00000000..77a2bceb
--- /dev/null
+++ b/scripts/acceptance/capture-xbox-control.py
@@ -0,0 +1,35 @@
+"""Scope guard for the two current field reports; preserves previous worktrees."""
+from pathlib import Path
+import hashlib, json, subprocess
+
+BASE=Path('E:/项目/Veyra'); TASK='capture-xbox-field-20261005'
+ROOT=Path(__file__).resolve().parents[2]; ARCH=BASE/'archives'/TASK
+allowed={
+ 'AGENTS.md','docs/WORKLOG.md','docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md',
+ 'docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md',
+ 'include/veyra/xbox/VideoDecodeRecovery.h','src/source/XboxSessionSource.cpp',
+ 'src/engine/EngineController.cpp','tests/xbox/XboxTests.cpp',
+ 'tests/unit/CaptureCompressedDecoderTests.cpp',
+ 'scripts/acceptance/capture-xbox-control.py','scripts/acceptance/capture-xbox-build.py',
+ 'scripts/acceptance/capture-xbox-tests.py','scripts/acceptance/capture-xbox-evidence.py',
+ 'scripts/acceptance/capture-xbox-package.py'
+}
+def git(root,*args):return subprocess.check_output(['git','-c','core.safecrlf=false','-C',str(root),*args],stderr=subprocess.PIPE)
+def sha(data):return hashlib.sha256(data).hexdigest()
+startfile=ARCH/'start.json'
+assert sha(startfile.read_bytes())==(ARCH/'start.sha256').read_text().strip(),'immutable start receipt changed'
+start=json.loads(startfile.read_text(encoding='utf8'))
+assert ROOT.resolve()==Path(start['root']).resolve()
+assert git(ROOT,'branch','--show-current').decode().strip()==start['branch']
+assert git(ROOT,'merge-base','HEAD',start['start']).decode().strip()==start['start']
+changed=set(git(ROOT,'diff','--name-only',start['start']).decode('utf8').splitlines())
+changed.update(f for f in git(ROOT,'ls-files','--others','--exclude-standard','-z').decode('utf8').split('\0') if f)
+assert changed<=allowed, f'out of scope: {sorted(changed-allowed)}'
+for record in start['protected']:
+ path=Path(record['path'])
+ assert git(path,'rev-parse','HEAD').decode().strip()==record['head'],f'protected HEAD changed: {path}'
+ assert sha(git(path,'status','--porcelain=v1','--untracked-files=all'))==record['statusSha256'],f'protected status changed: {path}'
+ assert sha(git(path,'diff','--binary'))==record['workingDiffSha256'],f'protected content changed: {path}'
+ assert sha(git(path,'diff','--cached','--binary'))==record['indexDiffSha256'],f'protected index changed: {path}'
+ for f,digest in record['untracked'].items():assert sha((path/f).read_bytes())==digest,f'protected untracked changed: {path/f}'
+print('CAPTURE/XBOX GUARD PASS',len(changed),'scoped files;',len(start['protected']),'worktrees unchanged')
diff --git a/scripts/acceptance/capture-xbox-evidence.py b/scripts/acceptance/capture-xbox-evidence.py
new file mode 100644
index 00000000..cf0ecce1
--- /dev/null
+++ b/scripts/acceptance/capture-xbox-evidence.py
@@ -0,0 +1,65 @@
+"""Summarize immutable field inputs without publishing SDP, credentials or the dump."""
+from pathlib import Path
+from datetime import datetime
+import hashlib, json, re, statistics
+
+BASE=Path('E:/项目/Veyra'); TASK='capture-xbox-field-20261005'
+LOG=BASE/'logs'/TASK; INPUT=LOG/'input'
+inputs={
+ 'logs(4).7z':'bb7fc5ff2663a0553415b3af7bdd7564a2de3af8bb52bb014496c45956487efb',
+ 'veyra-qml(26).log':'111743001597ff1ba82442f68e9a557e651505df46022a49ded8448e6255d9a2',
+ 'veyra-qml(28).log':'458848912364339a592190f86b7ee772016ce7b691a52ed7c5db20c38981180a',
+ 'archive/logs/veyra-qml.log':'cc9af8a15440a62d26608f0cb92a71c0b2a0cbf2921fec7597e0a3af21d8cba8'}
+manifest=[]
+for rel,expected in inputs.items():
+ p=INPUT/rel; digest=hashlib.sha256(p.read_bytes()).hexdigest()
+ assert digest==expected,rel
+ manifest.append({'path':rel,'bytes':p.stat().st_size,'sha256':digest})
+rx=re.compile(r'^(\S+) t=(\d+) \[(.*?)\] \[([^]]+)\] (.*)$')
+kv=re.compile(r'(\w+)=([^\s]+)')
+def number(v):
+ try:return float(v) if '.' in v else int(v)
+ except ValueError:return v
+def rows(path):
+ session=0
+ for n,line in enumerate(path.read_text(encoding='utf8',errors='replace').splitlines(),1):
+ m=rx.match(line)
+ if not m:continue
+ stamp,thread,level,tag,message=m.groups()
+ if 'Veyra QML session started' in message:session+=1
+ yield {'line':n,'stamp':stamp,'session':session,'level':level.strip(),'tag':tag,
+ 'message':message,**{k:number(v) for k,v in kv.findall(message)}}
+def median(data,key):return statistics.median(r[key] for r in data if isinstance(r.get(key),(int,float)))
+capture=list(rows(INPUT/'archive/logs/veyra-qml.log'))
+timings=[r for r in capture if r['tag']=='capture-timing' and r['session']==2 and r.get('revision')==16]
+rates=[r for r in capture if r['tag']=='frame-rate' and r['session']==2 and r.get('revision')==16]
+callbacks=[r for r in capture if r['tag']=='capture-callback']
+assert len(timings)==len(rates)==59
+a,b=timings[3],timings[-1]
+seconds=(datetime.fromisoformat(b['stamp'].replace('Z','+00:00'))-datetime.fromisoformat(a['stamp'].replace('Z','+00:00'))).total_seconds()
+delta={key:b[key]-a[key] for key in ('received','processed','dropped')}
+capture_summary={
+ 'windows':len(timings),'windowFrom':timings[0]['stamp'],'windowTo':b['stamp'],
+ 'callbackFpsMedian':median(timings,'callbackFps'),'gpuCompletedFpsMedian':median(rates,'gpuCompletedFps'),
+ 'rollingGpuReadyP95MedianMs':median(timings,'gpuReadyP95Ms'),
+ 'callbackArrivalMedianMs':median(callbacks,'arrivalDeltaMs'),'sourcePtsDeltaMedianMs':median(callbacks,'ptsDeltaMs'),
+ 'sampleDurationMedianMs':median(callbacks,'sampleDurationMs'),
+ 'counterWindow':{'first':{key:a[key] for key in ('line','stamp','received','processed','dropped')},
+ 'last':{key:b[key] for key in ('line','stamp','received','processed','dropped')},
+ 'seconds':seconds,'deltas':delta,'receivedPerSecond':delta['received']/seconds,
+ 'processedPerSecond':delta['processed']/seconds},
+ 'conclusion':'The source continued near 60 Hz; enhancement consumption was below source rate. P95 values are not mean per-frame times.'}
+xbox=list(rows(INPUT/'veyra-qml(28).log'))
+errors=[r for r in xbox if r['level']=='ERROR']
+decoder_errors=[r for r in errors if 'decoder: send_packet failed code=-22 text=Invalid argument' in r['message']]
+assert len(errors)==len(decoder_errors)==487
+safe=lambda r:{key:r[key] for key in ('line','stamp','tag','message')}
+fg=[safe(r) for r in xbox if r['tag'] in ('fsr-fg','xess-fg') and any(s in r['message'] for s in ('independent context','initialized','created','version='))]
+stalls=[safe(r) for r in xbox if r['tag']=='engine-stall' and r.get('totalMs',0)>=1000]
+xbox_summary={'hardDecodeErrors':len(errors),'firstError':safe(errors[0]),'lastError':safe(errors[-1]),
+ 'fgProviderEvidence':fg[:16],'stallEvidence':stalls[:8],
+ 'conclusion':'The field log proves persistent H.264 decode failure and failed recovery. It does not establish which AMD driver/FG/bitstream condition triggered EINVAL.'}
+result={'inputs':manifest,'capture':capture_summary,'xbox':xbox_summary,
+ 'scope':'28 is the confirmed Xbox report; 26 is retained only as superseded evidence.'}
+(LOG/'field-evidence.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
+print(json.dumps({'capture':capture_summary,'xbox':{k:v for k,v in xbox_summary.items() if k not in ('fgProviderEvidence','stallEvidence')}},ensure_ascii=False,indent=2))
diff --git a/scripts/acceptance/capture-xbox-package.py b/scripts/acceptance/capture-xbox-package.py
new file mode 100644
index 00000000..1708b193
--- /dev/null
+++ b/scripts/acceptance/capture-xbox-package.py
@@ -0,0 +1,160 @@
+"""Stage/finalize isolated vendor packages without changing accepted runtime bytes."""
+from pathlib import Path
+import hashlib, json, shutil, subprocess, sys, zipfile
+
+ROOT=Path(__file__).resolve().parents[2]
+BASE=Path('E:/项目/Veyra'); TASK='capture-xbox-field-20261005'; VERSION='2.0.3-streamfix1'
+PARENT=BASE/'test-packages'/TASK; LOG=BASE/'logs'/TASK; ARCH=BASE/'archives'/TASK
+mode=sys.argv[1]; assert mode in ('stage','refresh','finalize')
+vendors=sys.argv[2:] or ['AMD','NVIDIA']; assert vendors and set(vendors)<= {'AMD','NVIDIA'}
+sources={
+ 'AMD':BASE/'releases/release-2.0.3-20261004/Veyra-2.0.3-AMD-win64-portable',
+ 'NVIDIA':BASE/'test-packages/nr-strength-protection-20261005/Veyra-2.0.3-nr-controls2-NVIDIA-win64-portable'}
+BUILD=BASE/'build'/TASK
+guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/capture-xbox-control.py')]
+subprocess.run(guard,check=True)
+for p in (PARENT,LOG,ARCH):p.mkdir(parents=True,exist_ok=True)
+def sha(p):
+ h=hashlib.sha256()
+ with p.open('rb') as f:
+ for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
+ return h.hexdigest()
+def save(p,obj):p.write_text(json.dumps(obj,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
+def git(*args):return subprocess.check_output(['git','-C',str(ROOT),*args],encoding='utf8',stderr=subprocess.PIPE).strip()
+def component(rel):
+ return rel.startswith(('runtime/','runtime_local/','models/','licenses/')) or Path(rel).suffix.lower()=='.dll' or rel in ('release-runtime-manifest.json','vfg-runtime-manifest.json')
+def private(rel):
+ return rel.startswith(('runtime_local/user-data-','logs/','tmp/','outputs/','screenshots/','profile/'))
+head=git('rev-parse','HEAD'); dirty=bool(git('status','--porcelain'))
+source_zip=PARENT/f'Veyra-{VERSION}-veyra-source.zip'
+if mode=='finalize':
+ assert not dirty,'Commit the validated source before packaging'
+ for name in ('xbox1','scene1','timing1','codec10','codec11','smoke-AMD3','smoke-NVIDIA3','hot-NVIDIA3'):
+ result=json.loads((LOG/(name+'.json')).read_text(encoding='utf8'))
+ assert result['passed'],name
+ if name.startswith(('smoke-','hot-')):assert result['exeSha256']==sha(BUILD/'veyra_qml_ui.exe'),name
+ if name.startswith('codec'):assert result['exeSha256']==sha(BUILD/'veyra_capture_compressed_tests.exe'),name
+ assert not source_zip.exists()
+ files=[f for f in subprocess.check_output(['git','-C',str(ROOT),'ls-files','-z']).decode('utf8').split('\0') if f]
+ with zipfile.ZipFile(source_zip,'x',zipfile.ZIP_DEFLATED,compresslevel=6) as z:
+ for rel in sorted(files):
+ assert not rel.startswith(('runtime/','runtime_local/','third_party_local/','models/'))
+ assert Path(rel).suffix.lower() not in ('.dll','.lib','.pdb','.addon64','.onnx','.bin')
+ z.write(ROOT/rel,arcname=f'Veyra-{VERSION}-source/'+rel)
+ with zipfile.ZipFile(source_zip) as z:
+ assert z.testzip() is None
+ for rel in files:assert hashlib.sha256(z.read(f'Veyra-{VERSION}-source/'+rel)).hexdigest()==sha(ROOT/rel),rel
+ bundle=ARCH/'source-final.bundle';assert not bundle.exists()
+ subprocess.run(['git','-C',str(ROOT),'bundle','create',str(bundle),'HEAD'],check=True)
+ with (LOG/'source-final-verify.log').open('w',encoding='utf8') as out:
+ subprocess.run(['git','-C',str(ROOT),'bundle','verify',str(bundle)],stdout=out,stderr=subprocess.STDOUT,check=True)
+delivery=[]
+common_manifest=json.loads((sources['NVIDIA']/'package-manifest.json').read_text(encoding='utf8'))
+common_licenses={row['path']:row['sha256'] for row in common_manifest['files'] if row['path'].startswith('licenses/libass/')}
+assert len(common_licenses)==8
+for vendor in vendors:
+ source=sources[vendor]; app=PARENT/f'Veyra-{VERSION}-{vendor}-win64-portable'
+ manifest=json.loads((source/'package-manifest.json').read_text(encoding='utf8'))
+ # Verify the accepted source package before copying or loading its runtime.
+ for row in manifest['files']:
+ if private(row['path']):continue
+ p=source/row['path'];assert p.resolve().is_relative_to(source.resolve())
+ assert p.is_file() and sha(p)==row['sha256'],str(p)
+ source_paths=[row['path'] for row in manifest['files'] if not private(row['path'])]
+ immutable={rel:sha(source/rel) for rel in source_paths if component(rel)}
+ if mode=='stage':
+ assert not app.exists()
+ app.mkdir(parents=True)
+ # A previously delivered app may now have the user's saved data next
+ # to it. Copy only manifest-listed payloads, never an entire live app.
+ for rel in source_paths:
+ destination=app/rel;assert destination.resolve().is_relative_to(app.resolve())
+ destination.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(source/rel,destination)
+ # Isolate only copies inadvertently inherited by the first staging run.
+ # Both resolved move paths must be within this task, never the source app.
+ for copied in (app/'runtime_local').glob('user-data-*'):
+ if not copied.is_dir():continue
+ destination=LOG/'quarantined-config-copies'/vendor/copied.name
+ assert copied.resolve().is_relative_to(app.resolve()) and app.resolve().is_relative_to(PARENT.resolve())
+ assert destination.resolve().is_relative_to(LOG.resolve()) and not destination.exists()
+ destination.parent.mkdir(parents=True,exist_ok=True)
+ shutil.move(str(copied),str(destination))
+ print('EXCLUDED copied configuration directory',vendor,copied.name,flush=True)
+ if mode in ('stage','refresh'):
+ assert app.is_dir()
+ shutil.copy2(BUILD/'veyra_qml_ui.exe',app/'veyra_qml_ui.exe')
+ shutil.copytree(ROOT/'qml',app/'qml',dirs_exist_ok=True)
+ shutil.copytree(BUILD/'shaders',app/'shaders',dirs_exist_ok=True)
+ for name in ('README.md','README_CN.md','README_EN.md','THIRD_PARTY_NOTICES.md'):
+ shutil.copy2(ROOT/name,app/name)
+ for name in ('CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md',):shutil.copy2(ROOT/'docs'/name,app/'docs'/name)
+ (app/'STREAM_FIX_LOCAL.md').write_text(
+ 'Xbox 解码恢复本地候选 2.0.3-streamfix1(未发布)\n\n'
+ '针对日志 28 的 H.264 解码持续 Invalid argument:错误或输入队列丢 AU 后清理参考历史并等待关键帧;'
+ '连续失败时每会话最多一次硬解重开、一次软件回退;恢复首帧带时间线断点,日志标签 xbox-decode-recovery。'
+ '软件回退可能增加 CPU 使用和解码耗时,视频仍无法恢复时明确报错。运行库与补帧算法未更换。\n\n'
+ '采集 60→55–57 的现场输入仍约 60Hz,已有增强组合处理欠速;本次只修正日志节奏标签,未承诺恢复该组合 60FPS。'
+ '保留此前 NR 强度 5、三种风格与自动/手动画面调控。\n\n'
+ '本机 RTX5070 的本地协议、软/硬解和正常负载短测不等于 RX9070XT + Xbox 实机通过。'
+ '请在受影响电脑上连接 Xbox,切换原先出问题的 FSR/XeSS 补帧,出现问题时保留这次的新日志。\n',encoding='utf8')
+ else:
+ assert sha(app/'veyra_qml_ui.exe')==sha(BUILD/'veyra_qml_ui.exe')
+ for p in (ROOT/'qml').rglob('*'):
+ if p.is_file():assert sha(app/'qml'/p.relative_to(ROOT/'qml'))==sha(p),str(p)
+ shutil.copy2(ROOT/'docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md',app/'docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md')
+ # Both vendor apps now use the same statically linked libass build; the
+ # older AMD release template predates those common dependency notices.
+ for rel,digest in common_licenses.items():
+ p=sources['NVIDIA']/rel;assert sha(p)==digest
+ destination=app/rel;destination.parent.mkdir(parents=True,exist_ok=True)
+ if not destination.exists():shutil.copy2(p,destination)
+ assert sha(destination)==digest
+ for rel,digest in immutable.items():assert sha(app/rel)==digest,rel
+ all_files=sorted(p for p in app.rglob('*') if p.is_file())
+ expected_paths=set(source_paths)|{'package-manifest.json','local-package-manifest.json','STREAM_FIX_LOCAL.md',
+ 'docs/CAPTURE_XBOX_FIELD_PLAN_2026-10-05.md','docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md'}|set(common_licenses)
+ expected_paths.update('qml/'+p.relative_to(ROOT/'qml').as_posix() for p in (ROOT/'qml').rglob('*') if p.is_file())
+ expected_paths.update('shaders/'+p.relative_to(BUILD/'shaders').as_posix() for p in (BUILD/'shaders').rglob('*') if p.is_file())
+ extras={p.relative_to(app).as_posix() for p in all_files}-expected_paths
+ assert not extras, f'Unexpected candidate payloads: {sorted(extras)}'
+ for p in all_files:
+ rel=p.relative_to(app).as_posix()
+ assert not private(rel) and not p.is_symlink(),rel
+ assert p.suffix.lower() not in ('.lib','.pdb','.addon64','.pyc','.whl','.dmp','.log'),rel
+ excluded={'package-manifest.json','local-package-manifest.json'}
+ records=[{'path':p.relative_to(app).as_posix(),'size':p.stat().st_size,'sha256':sha(p)} for p in all_files if p.name not in excluded]
+ manifest.update(candidate=VERSION,displayVersion=VERSION,sourceCommit=head,sourceArchiveCommit=head,
+ baseCommit='33d6685a3a75d3d4e8ac5d32996b163ef1f488dc',worktreeDirty=dirty,
+ localOnly=True,releaseReady=False,executableSha256=sha(app/'veyra_qml_ui.exe'),
+ validationRecord='docs/CAPTURE_XBOX_FIELD_EXECUTION_2026-10-05.md',
+ hardwareValidation='RTX5070 local short tests only; RX9070XT + Xbox and physical capture reproduction unverified')
+ manifest['files']=records
+ manifest['commonLibassLicenseHashes']=common_licenses
+ manifest['correspondingSource']['libass']=common_manifest['correspondingSource']['libass']
+ if mode=='finalize':
+ manifest['correspondingSource'].update(application='../'+source_zip.name,applicationSha256=sha(source_zip),
+ displayVersionOverride='-DVEYRA_DISPLAY_VERSION='+VERSION)
+ save(app/'package-manifest.json',manifest)
+ save(app/'local-package-manifest.json',{'purpose':'Xbox hard decode recovery; local field candidate',
+ 'sourceCommit':head,'worktreeDirty':dirty,'releaseReady':False,'displayVersion':VERSION,
+ 'sourcePackage':str(source),'unchangedInheritedComponents':immutable,'files':records,
+ 'exeSha256':sha(app/'veyra_qml_ui.exe'),'packageManifestSha256':sha(app/'package-manifest.json')})
+ receipt={'vendor':vendor,'candidate':str(app),'exeSha256':sha(app/'veyra_qml_ui.exe'),
+ 'fileCount':len(records)+2,'unchangedComponentCount':len(immutable),'mode':mode}
+ if mode=='finalize':
+ archive=PARENT/(app.name+'.zip');assert not archive.exists()
+ print('ARCHIVE',vendor,len(records)+2,'files',flush=True)
+ with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=6) as z:
+ for p in sorted(app.rglob('*')):
+ if p.is_file():z.write(p,arcname=p.relative_to(PARENT).as_posix())
+ with zipfile.ZipFile(archive) as z:
+ assert z.testzip() is None
+ for row in records:assert hashlib.sha256(z.read(app.name+'/'+row['path'])).hexdigest()==row['sha256'],row['path']
+ for name in excluded:assert hashlib.sha256(z.read(app.name+'/'+name)).hexdigest()==sha(app/name)
+ receipt.update(archive=str(archive),archiveBytes=archive.stat().st_size,archiveSha256=sha(archive),
+ sourceCommit=head,sourceZip=str(source_zip),sourceZipSha256=sha(source_zip),
+ packageManifestSha256=sha(app/'package-manifest.json'),zipCrcAndAllPayloadHashesPassed=True)
+ delivery.append(receipt); print(json.dumps(receipt,ensure_ascii=False),flush=True)
+save(LOG/('packages-'+mode+'.json'),delivery)
+if mode=='finalize':save(PARENT/'DELIVERY.json',delivery)
+subprocess.run(guard,check=True)
diff --git a/scripts/acceptance/capture-xbox-tests.py b/scripts/acceptance/capture-xbox-tests.py
new file mode 100644
index 00000000..a9ec5e15
--- /dev/null
+++ b/scripts/acceptance/capture-xbox-tests.py
@@ -0,0 +1,170 @@
+"""Run scoped local regressions with isolated artifacts and no live Xbox login."""
+from pathlib import Path
+import hashlib, json, os, re, shutil, subprocess, sys, time
+
+ROOT = Path(__file__).resolve().parents[2]
+BASE = Path('E:/项目/Veyra'); TASK = 'capture-xbox-field-20261005'
+label = sys.argv[1]; case = sys.argv[2]
+assert label.replace('-', '').isalnum()
+if case in ('smoke','hot'):
+ app=Path(sys.argv[3]).resolve()
+ assert app.is_relative_to((BASE/'test-packages'/TASK).resolve()) and (app/'veyra_qml_ui.exe').is_file()
+ log=BASE/'logs'/TASK/(label+'.log'); engine_log=log.with_name(label+'-engine.log')
+ out=BASE/'tests'/TASK/label; tmp=BASE/'tmp'/TASK/label
+ for p in (out,tmp):p.mkdir(parents=True,exist_ok=False)
+ (out/'screenshots').mkdir()
+ guard=[sys.executable,'-B',str(ROOT/'scripts/acceptance/capture-xbox-control.py')]
+ subprocess.run(guard,check=True)
+ env={k:v for k,v in os.environ.items() if not k.upper().startswith(('VEYRA_','QT_','QSG_'))}
+ windows=Path(env['WINDIR'])
+ env.update(TEMP=str(tmp),TMP=str(tmp),CUDA_CACHE_PATH=str(tmp/'cuda-cache'),
+ VEYRA_LOG_FILE=str(engine_log),QML_DISABLE_DISK_CACHE='1',QT_FORCE_STDERR_LOGGING='1',
+ PATH=os.pathsep.join(map(str,(app,windows/'System32',windows,windows/'System32/Wbem'))))
+ args=[str(app/'veyra_qml_ui.exe'),'--data-dir',str(out/'profile'),'--page','pro',
+ '--size','1280x800','--obs-game-capture','--exit-after','190000' if case=='hot' else '8000']
+ main=app/'qml/Veyra/Main.qml'; original=main.read_bytes()
+ assert original==(ROOT/'qml/Veyra/Main.qml').read_bytes()
+ if case=='smoke':
+ media=BASE/'tests/field-fixes-20261005/media/fx-embedded.mkv';assert media.is_file()
+ args.append(str(media))
+ else:
+ media=BASE/'tests/hotfix-2.0.0-20261002/media/gta6-1080p30-60s.mp4';assert media.is_file()
+ injection=r'''
+ Timer {
+ interval:250;running:true;repeat:true
+ property int stage:0
+ property int ticks:0
+ property int total:0
+ property int current:0
+ property int readyTicks:0
+ property double beforePosition:0
+ property double readyPosition:0
+ property var cases:["fsr3","xess","dlss","fsr3"]
+ function require(ok,why){if(!ok)throw new Error(why)}
+ function next(value){stage=value;ticks=0}
+ function startCase(){
+ beforePosition=veyra.position
+ veyra.fgBackendName=cases[current];veyra.fgMultiplier=2;veyra.fgEnabled=true
+ readyTicks=0
+ next(2)
+ }
+ onTriggered:{try{
+ ++ticks;++total
+ require(total<720,"180s bounded deadline stage="+stage)
+ require(!veyra.failed,"playback failed "+veyra.statusText)
+ if(stage===0){
+ if(ticks<8)return
+ veyra.muted=true;veyra.nodeMode=0;veyra.nrEnabled=false;veyra.srEnabled=false;veyra.fgEnabled=false
+ veyra.openPath(__MEDIA__);next(1)
+ }else if(stage===1){
+ if(!veyra.running||veyra.applying||veyra.position<.5)return
+ startCase()
+ }else if(stage===2){
+ if(veyra.applying||!veyra.fgActive){readyTicks=0;return}
+ if(!readyTicks){readyPosition=veyra.position;readyTicks=1;return}
+ if(++readyTicks<16)return
+ require(veyra.running&&veyra.fgActive,"FG not active "+cases[current])
+ require(veyra.fgBackendName===cases[current]&&veyra.fgMultiplier===2,"backend not applied")
+ require(veyra.position>readyPosition+1,"source stopped after ready "+cases[current])
+ console.log("STREAM_FIX_FG_CASE",cases[current],veyra.position,veyra.submitFps,veyra.fgProviderText)
+ ++current
+ if(current<cases.length){startCase();return}
+ beforePosition=veyra.position;veyra.fgEnabled=false;next(3)
+ }else if(stage===3){
+ if(ticks<12||veyra.applying)return
+ require(veyra.running&&!veyra.fgActive&&veyra.position>beforePosition+.5,"FG disable stopped playback")
+ veyra.nrEnabled=true
+ const first=veyra.nrLayers[0].index
+ require(veyra.setNrLayerParameter(first,"runtime",3),"original NR selection")
+ require(veyra.setNrLayerParameter(first,"style",1),"NR style 1")
+ require(veyra.setNrLayerParameter(first,"total",5),"NR strength 5")
+ require(veyra.setNrLayerParameter(first,"correctionEnabled",1),"NR protection")
+ require(veyra.duplicateNrLayer(first)>=0,"second NR layer")
+ const second=veyra.nrLayers[1].index
+ require(veyra.setNrLayerParameter(second,"style",2),"second NR style 2")
+ require(veyra.setNrLayerParameter(second,"correctionAuto",0),"second manual NR")
+ beforePosition=veyra.position;readyTicks=0;next(4)
+ }else if(stage===4){
+ if(veyra.applying||!veyra.nrActive){readyTicks=0;return}
+ if(!readyTicks){readyPosition=veyra.position;readyTicks=1;return}
+ if(++readyTicks<16)return
+ require(veyra.running&&veyra.nrActive&&veyra.nrLayers.length===2,"two-layer NR inactive")
+ require(veyra.position>readyPosition+.5,"NR preview stopped after ready")
+ require(veyra.setPreference("screenshotDir",__SCREENSHOTS__),"screenshot directory")
+ veyra.takeScreenshot()
+ console.log("STREAM_FIX_NR_CASE",JSON.stringify(veyra.nrLayers));next(5)
+ }else if(stage===5){
+ if(ticks<8)return
+ console.log("STREAM_FIX_HOT_PASS");Qt.quit()
+ }
+ }catch(e){console.error("STREAM_FIX_HOT_FAIL",e.message);Qt.quit()}}
+ }
+'''.replace('__MEDIA__',json.dumps(str(media))).replace('__SCREENSHOTS__',json.dumps(str(out/'screenshots')))
+ source=original.decode('utf8'); at=source.rfind('}');assert at>0
+ main.write_text(source[:at]+injection+source[at:],encoding='utf8')
+ begin=time.monotonic()
+ try:
+ with log.open('xb') as console:
+ try:rc=subprocess.run(args,cwd=app,env=env,stdout=console,stderr=subprocess.STDOUT,timeout=200).returncode
+ except subprocess.TimeoutExpired:rc=124
+ finally:main.write_bytes(original)
+ console=log.read_text(encoding='utf8',errors='replace')
+ text=engine_log.read_text(encoding='utf8',errors='replace') if engine_log.exists() else ''
+ bad=[line for line in (text+'\n'+console).splitlines() if any(word in line for word in ('[ERROR]','[FATAL]','ReferenceError:','TypeError:','no root object','STREAM_FIX_HOT_FAIL'))]
+ ass=[line for line in text.splitlines() if '[libass]' in line]
+ passed=rc==0 and not bad
+ if case=='smoke':passed=passed and any('track ready events=5' in line for line in ass) and any('fonts configured container=1' in line for line in ass)
+ else:
+ passed=passed and 'STREAM_FIX_HOT_PASS' in console and console.count('STREAM_FIX_FG_CASE')==4 and 'STREAM_FIX_NR_CASE' in console and bool(list((out/'screenshots').glob('*.png')))
+ assert main.read_bytes()==original
+ result={'passed':passed,'exit':rc,'seconds':round(time.monotonic()-begin,3),'args':args,
+ 'exeSha256':hashlib.sha256((app/'veyra_qml_ui.exe').read_bytes()).hexdigest(),
+ 'mainQmlSha256':hashlib.sha256(original).hexdigest(),'log':str(log),'engineLog':str(engine_log),
+ 'libass':ass[:8],'errors':bad[:20]}
+ log.with_suffix('.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
+ print('LOCAL APP',case,'PASS' if passed else 'FAIL',log)
+ print('\n'.join(bad[:12] or [line for line in console.splitlines() if 'STREAM_FIX_' in line]))
+ subprocess.run(guard,check=True)
+ raise SystemExit(0 if passed else 1)
+BUILD = BASE/'build'/TASK
+APP = BASE/'test-packages/nr-strength-protection-20261005/Veyra-2.0.3-nr-controls2-NVIDIA-win64-portable'
+cases = {'xbox': 'veyra_xbox_tests', 'scene': 'veyra_scene_tests',
+ 'timing': 'veyra_live_timing_tests', 'codec': 'veyra_capture_compressed_tests'}
+assert case in cases
+LOG = BASE/'logs'/TASK/(label+'.log'); TMP = BASE/'tmp'/TASK/label
+OUT = BASE/'tests'/TASK/label
+for p in (LOG.parent, TMP, OUT): p.mkdir(parents=True, exist_ok=True)
+guard = [sys.executable, '-B', str(ROOT/'scripts/acceptance/capture-xbox-control.py')]
+subprocess.run(guard, check=True)
+exe = BUILD/(cases[case]+'.exe'); assert exe.is_file()
+args = [str(exe)]
+fixture = None
+if case == 'codec':
+ fixture = Path(sys.argv[3]); assert fixture.resolve().is_relative_to(BASE.resolve()) and fixture.is_file()
+ # The inherited main(char**) fixture loader is ANSI on Windows. Run from
+ # the isolated Unicode directory with an ASCII relative media argument.
+ local_fixture = OUT/('input'+fixture.suffix)
+ assert not local_fixture.exists()
+ shutil.copy2(fixture, local_fixture)
+ assert hashlib.sha256(local_fixture.read_bytes()).digest() == hashlib.sha256(fixture.read_bytes()).digest()
+ args.append(local_fixture.name)
+env = {k:v for k,v in os.environ.items() if not k.upper().startswith('VEYRA_')}
+env.update(TEMP=str(TMP), TMP=str(TMP), VEYRA_LOG_FILE=str(OUT/'product.log'),
+ PATH=str(APP)+os.pathsep+env.get('PATH', ''))
+begin = time.monotonic()
+with LOG.open('xb') as log:
+ try:
+ rc = subprocess.run(args, cwd=OUT, env=env, stdout=log,
+ stderr=subprocess.STDOUT, timeout=290).returncode
+ except subprocess.TimeoutExpired:
+ rc = 124
+content = LOG.read_text(encoding='utf8', errors='replace')
+passed = rc == 0 and not re.search(r'^(?:FAIL\b|FAILURES\b|SKIP\b)', content, re.MULTILINE)
+result = {'passed':passed, 'exit':rc, 'seconds':round(time.monotonic()-begin, 3),
+ 'args':args, 'exeSha256':hashlib.sha256(exe.read_bytes()).hexdigest(), 'log':str(LOG)}
+if fixture: result['fixtureSha256'] = hashlib.sha256(fixture.read_bytes()).hexdigest()
+LOG.with_suffix('.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf8')
+lines=[line for line in content.splitlines() if re.match(r'^(?:\[?(?:PASS|FAIL)\b|ALL PASS\b|FAILURES\b|SKIP\b|xbox tests:|SCENE-TESTS:|hardware frames=|software frames=)',line)]
+print('\n'.join(lines[-90:])); print('LOCAL TEST', case, 'PASS' if passed else 'FAIL', LOG)
+subprocess.run(guard, check=True)
+raise SystemExit(0 if passed else 1)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 40102b10..63bb372e 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1964,7 +1964,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// File replay has no device pacing and still needs its PTS
// clock. Physical capture without FG presents as soon as ready.
const bool paceSourcePts=options.fg||!physicalCapture;
- if(!liveTimeline.anchored(out.batch.identity.epoch)||(pairPacing&&frames==0))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,pairAnchoredLive?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));
+ if(!liveTimeline.anchored(out.batch.identity.epoch)||(pairPacing&&frames==0))veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={} pacing={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg,pairPacing?(isRemote?"decoded-pair":"capture-pair"):paceSourcePts?"source-pts":"capture-ready"));
if(pairPacing||isStream)liveTimeline.resetPair(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?pairDelay:0,paceSourcePts);
else if(!liveTimeline.anchored(out.batch.identity.epoch))liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,liveInputReady,options.fg?duration100ns:0,paceSourcePts);
}
diff --git a/src/source/XboxSessionSource.cpp b/src/source/XboxSessionSource.cpp
index 44eb9a6d..020a6a97 100644
--- a/src/source/XboxSessionSource.cpp
+++ b/src/source/XboxSessionSource.cpp
@@ -2,6 +2,7 @@
// Session flow after Greenlight's streammanager.ts / stream page (unknownskl/greenlight, MIT).
#include "veyra/source/XboxSessionSource.h"
#include "veyra/xbox/DisconnectPolicy.h"
+#include "veyra/xbox/VideoDecodeRecovery.h"
#include <windows.h>
#include <mmreg.h>
@@ -129,7 +130,7 @@ struct XboxSessionSource::Impl {
std::mutex endMutex;
// Video: the WebRTC thread queues access units; the decode thread drains them.
- struct Unit { std::vector<uint8_t> data; uint32_t rtp; int64_t arrival; };
+ struct Unit { std::vector<uint8_t> data; uint32_t rtp; int64_t arrival; bool inputLoss=false; };
std::mutex queueMutex;
std::condition_variable queueCv;
std::deque<Unit> queue;
@@ -137,6 +138,7 @@ struct XboxSessionSource::Impl {
std::thread decodeThread, keepaliveThread;
CaptureCompressedDecoder decoder;
bool decoderOpen = false;
+ std::atomic<bool> hardwareDecodeStatus{false}; // stats never inspect the worker-owned decoder
AVFrame* dummyTarget = nullptr;
unsigned width = 1920, height = 1080;
Clock::time_point lastKeyframeRequest{};
@@ -269,8 +271,9 @@ void XboxSessionSource::run(XboxConnectDesc desc) {
++q.units;
std::lock_guard lock(q.queueMutex);
// Latency first: keep only a short backlog; a decoder that falls behind drops the oldest.
- while (q.queue.size() >= 8) { q.queue.pop_front(); ++q.dropped; }
- q.queue.push_back({std::move(unit), rtp, arrival});
+ const auto lost = xbox::trimVideoInputs(q.queue, 8);
+ q.dropped += lost;
+ q.queue.push_back({std::move(unit), rtp, arrival, lost>0&&q.queue.empty()});
q.queueCv.notify_one();
};
callbacks.audio = [this](const uint8_t* data, size_t size, uint32_t) {
@@ -370,8 +373,12 @@ void XboxSessionSource::run(XboxConnectDesc desc) {
}
{
std::lock_guard lock(mutex_);
- stats_.state = XboxStats::State::Streaming;
- stats_.message.clear();
+ // A decoder startup failure can race this session-ready update.
+ // Preserve the failure and its reason instead of reviving it.
+ if (stats_.state != XboxStats::State::Failed) {
+ stats_.state = XboxStats::State::Streaming;
+ stats_.message.clear();
+ }
publishedInfo_ = info_;
publishedInfo_.opened = true;
publishedInfo_.kind = pipeline::SourceKind::Xbox;
@@ -390,15 +397,20 @@ void XboxSessionSource::run(XboxConnectDesc desc) {
started_ = true;
}
ready_.notify_all();
- log::info("xbox", "streaming");
+ if (!p.ended.load()) log::info("xbox", "streaming");
while (!cancelled() && !p.ended.load()) std::this_thread::sleep_for(std::chrono::milliseconds(50));
if (p.ended.load()) {
std::wstring reason;
std::string code;
{ std::lock_guard lock(p.endMutex); reason = p.endReason; code = p.disconnectReason; }
- { std::lock_guard lock(mutex_); stats_.state = XboxStats::State::Ended;
- stats_.message = std::move(reason); stats_.disconnectReason = code;
- stats_.reconnectable = xbox::reconnectableDisconnect(code); }
+ { std::lock_guard lock(mutex_);
+ // Decode recovery can explicitly fail while the transport is
+ // still connected. Do not erase that error with an empty end.
+ if (stats_.state != XboxStats::State::Failed) {
+ stats_.state = XboxStats::State::Ended;
+ stats_.message = std::move(reason); stats_.disconnectReason = code;
+ stats_.reconnectable = xbox::reconnectableDisconnect(code);
+ } }
}
} catch (const xbox::ServiceError& e) {
log::error("xbox", std::format("service error {} {}", e.status, e.what()));
@@ -423,7 +435,8 @@ void XboxSessionSource::run(XboxConnectDesc desc) {
void XboxSessionSource::decodeLoop() {
auto& p = *p_;
- bool seenKeyframe = false, recovering = false;
+ bool seenKeyframe = false, recovering = false, forceSoftware = false;
+ xbox::VideoDecodeRecovery recovery;
int64_t lastPts = -1;
uint32_t lastRtp = 0;
int64_t rtpHigh = 0;
@@ -445,16 +458,30 @@ void XboxSessionSource::decodeLoop() {
unit = std::move(p.queue.front());
p.queue.pop_front();
}
+ if (unit.inputLoss) {
+ // A missing compressed AU invalidates H.264's reference chain.
+ // An IDR request alone does not repair an already broken decode
+ // context. The field log shows sustained errors after FG rebuilds.
+ if (p.decoderOpen) p.decoder.recoverAtKeyframe();
+ seenKeyframe = false;
+ recovering = true;
+ metas.clear();
+ requestKeyframe();
+ log::warn("xbox-decode-recovery", "input queue lost access units; history reset, waiting for keyframe");
+ }
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())) {
+ if (!p.decoder.open(CaptureCodec::H264, p.width, p.height, nullptr, 0,
+ forceSoftware ? nullptr : p.desc.decodeDevice.get(),
+ forceSoftware ? nullptr : p.desc.decodeQueue.get())) {
log::error("xbox", "no usable H.264 decoder");
setState(XboxStats::State::Failed, L"没有可用的 H.264 解码器。");
p.ended = true;
break;
}
p.decoderOpen = true;
+ p.hardwareDecodeStatus.store(p.decoder.hardwareActive(), std::memory_order_relaxed);
if (!p.dummyTarget) p.dummyTarget = allocNv12(16, 16);
log::info("xbox", std::string("decoder ") + p.decoder.backendName());
}
@@ -474,6 +501,7 @@ void XboxSessionSource::decodeLoop() {
AVFrame* out = nullptr;
bool hardware = false;
const bool produced = target && p.decoder.decode(unit.data.data(), unit.data.size(), pts, target, &out, hardware);
+ p.hardwareDecodeStatus.store(p.decoder.hardwareActive(), std::memory_order_relaxed);
const double decodeMs = std::chrono::duration<double, std::milli>(Clock::now() - begin).count();
if (!produced) {
if (needsTarget && target) av_frame_free(&target);
@@ -481,6 +509,27 @@ void XboxSessionSource::decodeLoop() {
++p.errors;
seenKeyframe = false;
recovering = true;
+ metas.clear();
+ const std::string error = p.decoder.lastError();
+ const bool wasHardware = p.decoder.hardwareActive();
+ const auto action = recovery.failed(wasHardware);
+ const char* name = action == xbox::VideoDecodeRecoveryAction::ResetHistory ? "reset-history" :
+ action == xbox::VideoDecodeRecoveryAction::ReopenHardware ? "reopen-hardware" :
+ action == xbox::VideoDecodeRecoveryAction::UseSoftware ? "use-software" : "stop";
+ log::warn("xbox-decode-recovery", std::format("action={} backend={} errors={} detail={}",
+ name, p.decoder.backendName(), p.errors.load(), error));
+ if (action == xbox::VideoDecodeRecoveryAction::Stop) {
+ setState(XboxStats::State::Failed, L"Xbox 视频解码连续失败,恢复后仍无法出画。请重连,并保留日志。");
+ p.ended = true;
+ break;
+ }
+ if (action == xbox::VideoDecodeRecoveryAction::ResetHistory) p.decoder.recoverAtKeyframe();
+ else {
+ p.hardwareDecodeStatus.store(false, std::memory_order_relaxed);
+ p.decoder.close();
+ p.decoderOpen = false;
+ if (action == xbox::VideoDecodeRecoveryAction::UseSoftware) forceSoftware = true;
+ }
requestKeyframe();
}
continue;
@@ -494,6 +543,7 @@ void XboxSessionSource::decodeLoop() {
frame.reset(target, [](AVFrame* f) { av_frame_free(&f); });
}
if (!frame) { ++p.errors; continue; }
+ recovery.picture();
seenKeyframe = true;
if (unsigned(frame->width) != p.width || unsigned(frame->height) != p.height) {
p.width = unsigned(frame->width);
@@ -512,7 +562,12 @@ void XboxSessionSource::decodeLoop() {
packet.duration = pipeline::Rational{166667, 10000000};
packet.arrivalHost100ns = arrival;
packet.decodedHost100ns = host100ns();
- if (recovering) { packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity); recovering = false; }
+ if (recovering) {
+ packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);
+ log::info("xbox-decode-recovery", std::format("picture restored backend={} pts100ns={} errors={}",
+ p.decoder.backendName(), framePts, p.errors.load()));
+ recovering = false;
+ }
auto fallback = fallbackColor();
packet.colorInfo = pipeline::resolveFrameColor(*frame, fallback);
packet.colorInfo.pixelFormat = pixelFormatOf(*frame);
@@ -637,7 +692,7 @@ XboxStats XboxSessionSource::stats() const {
s.decoded = p.decoded.load();
s.dropped = p.dropped.load() + skipped();
s.decodeErrors = p.errors.load();
- s.hardwareDecode = p.decoderOpen && p.decoder.hardwareActive();
+ s.hardwareDecode = p.hardwareDecodeStatus.load(std::memory_order_relaxed);
const xbox::WebRtcStats r = p.rtc.stats();
s.keyframeRequests = r.keyframeRequests;
s.rttMs = r.rttMs;
@@ -684,6 +739,7 @@ void XboxSessionSource::close() noexcept {
if (p.decodeThread.joinable()) p.decodeThread.join();
if (p.keepaliveThread.joinable()) p.keepaliveThread.join();
p.rtc.close();
+ p.hardwareDecodeStatus.store(false, std::memory_order_relaxed);
if (p.decoderOpen) { p.decoder.close(); p.decoderOpen = false; }
// End the console session so the next start does not find it busy (best effort, short timeout).
// The session's own transport is cancelled by now, and teardown must not wait on the network:
diff --git a/tests/unit/CaptureCompressedDecoderTests.cpp b/tests/unit/CaptureCompressedDecoderTests.cpp
index 4e7e3a8f..21de9d49 100644
--- a/tests/unit/CaptureCompressedDecoderTests.cpp
+++ b/tests/unit/CaptureCompressedDecoderTests.cpp
@@ -223,6 +223,109 @@ bool packetRetryTest(const char* path,gfx::D3D12DeviceContext& device) {
return ok;
}
+// Exercise the real codec's hard-error/reset boundary used by Xbox. This is
+// a local H.264 replay, not a real Xbox/RX9000 driver reproduction.
+bool hardErrorRecovery(ElementaryStream& stream, ID3D12Device* device, ID3D12CommandQueue* queue) {
+ if(stream.codec!=source::CaptureCodec::H264)return true;
+ source::CaptureCompressedDecoder decoder;
+ decoder.setStreamProfile(true);
+ if(!decoder.open(stream.codec,unsigned(stream.width),unsigned(stream.height),nullptr,0,device,queue))return false;
+ AVFrame* target=av_frame_alloc();
+ if(!target)return false;
+ target->format=AV_PIX_FMT_NV12;target->width=stream.width;target->height=stream.height;
+ if(av_frame_get_buffer(target,32)<0){av_frame_free(&target);return false;}
+ AVFrame* output=nullptr;bool hardware=false;size_t at=0;unsigned warm=0;
+ for(;at<stream.accessUnits.size()&&warm<8;++at){
+ const auto& unit=stream.accessUnits[at];
+ if(decoder.decode(unit.data(),unit.size(),stream.pts[at],target,&output,hardware))++warm;
+ else if(!decoder.waitingForInput()){av_frame_free(&target);return false;}
+ }
+ if(warm!=8||at==0){av_frame_free(&target);return false;}
+ const auto isIdr=[](const std::vector<uint8_t>& unit){
+ for(size_t i=0;i+3<unit.size();++i)
+ if(unit[i]==0&&unit[i+1]==0&&unit[i+2]==1&&(unit[i+3]&31)==5)return true;
+ return false;
+ };
+ int64_t recoveryPts=AV_NOPTS_VALUE;
+ for(size_t next=at;next<stream.accessUnits.size();++next)
+ if(isIdr(stream.accessUnits[next])){recoveryPts=stream.pts[next];break;}
+ if(recoveryPts==AV_NOPTS_VALUE){
+ std::cout<<"FAIL recovery fixture has no future IDR\n";
+ av_frame_free(&target);return false;
+ }
+ const uint8_t invalid[]={0,0,0,1,0x80}; // forbidden_zero_bit, no valid slice
+ const bool badProduced=decoder.decode(invalid,sizeof(invalid),stream.pts[at-1]+1,target,&output,hardware);
+ bool ok=warm==8&&!badProduced&&!decoder.waitingForInput();
+ decoder.recoverAtKeyframe();
+ ok=ok&&!decoder.decode(nullptr,0,0,target,&output,hardware)&&decoder.waitingForInput();
+ bool restored=false;
+ // Feed dependent packets too: reset must withhold them rather than expose
+ // stale/broken references. The next real IDR restores original timestamps.
+ for(;ok&&at<stream.accessUnits.size()&&!restored;++at){
+ const auto& unit=stream.accessUnits[at];
+ const bool produced=decoder.decode(unit.data(),unit.size(),stream.pts[at],target,&output,hardware);
+ if(produced){
+ // A B-frame stream can emit the IDR after later packets. Its PTS
+ // must belong to the first new IDR, not to the packet sent today.
+ restored=output&&(output->flags&AV_FRAME_FLAG_KEY)&&output->pts==recoveryPts;
+ ok=restored;
+ }else ok=decoder.waitingForInput();
+ }
+ std::cout<<((ok&&restored)?"PASS ":"FAIL ")<<"hard H.264 error -> flush -> keyframe recovery backend="
+ <<decoder.backendName()<<" warm="<<warm<<" restored="<<restored<<" expectedPts="<<recoveryPts<<'\n';
+ av_frame_free(&target);return ok&&restored;
+}
+
+// Hold an old hardware frame across context replacement, as the player's
+// mailbox/graph can do, and verify actual reopen + software fallback output.
+bool decoderReplacement(ElementaryStream& stream, gfx::D3D12DeviceContext& device) {
+ source::CaptureCompressedDecoder decoder;
+ decoder.setStreamProfile(true);
+ AVFrame* target=av_frame_alloc();
+ if(!target)return false;
+ target->format=AV_PIX_FMT_NV12;target->width=stream.width;target->height=stream.height;
+ if(av_frame_get_buffer(target,32)<0){av_frame_free(&target);return false;}
+ AVFrame* output=nullptr;AVFrame* held=nullptr;bool hardware=false;size_t at=0;
+ bool ok=decoder.open(stream.codec,unsigned(stream.width),unsigned(stream.height),nullptr,0,device.device(),device.directQueue());
+ const auto isIdr=[](const std::vector<uint8_t>& unit){
+ for(size_t i=0;i+3<unit.size();++i)
+ if(unit[i]==0&&unit[i+1]==0&&unit[i+2]==1&&(unit[i+3]&31)==5)return true;
+ return false;
+ };
+ const auto prime=[&](unsigned count,bool seekIdr,bool expectHardware){
+ if(seekIdr)while(at<stream.accessUnits.size()&&!isIdr(stream.accessUnits[at]))++at;
+ if(at>=stream.accessUnits.size())return false;
+ const int64_t keyPts=stream.pts[at];unsigned pictures=0;
+ for(;at<stream.accessUnits.size()&&pictures<count;++at){
+ const auto& unit=stream.accessUnits[at];
+ if(decoder.decode(unit.data(),unit.size(),stream.pts[at],target,&output,hardware)){
+ if(hardware!=expectHardware)return false;
+ if(seekIdr&&pictures==0&&(!(output->flags&AV_FRAME_FLAG_KEY)||output->pts!=keyPts))return false;
+ ++pictures;
+ }else if(!decoder.waitingForInput())return false;
+ }
+ return pictures==count;
+ };
+ ok=ok&&prime(8,false,true);
+ if(ok)held=av_frame_clone(output);
+ ok=ok&&held&&held->format==AV_PIX_FMT_D3D12;
+ unsigned reopened=0,software=0;
+ // The CPU Xbox suite verifies the bounded error decisions. Here verify
+ // their resource/codec effects; a malformed AU can legitimately become
+ // NeedInput under NONKEY discard, so it cannot fake consecutive errors.
+ for(unsigned phase=0;ok&&phase<2;++phase){
+ decoder.close();
+ ok=decoder.open(stream.codec,unsigned(stream.width),unsigned(stream.height),nullptr,0,
+ phase==0?device.device():nullptr,phase==0?device.directQueue():nullptr);
+ if(phase==0)++reopened;else ++software;
+ ok=ok&&prime(1,true,phase==0);
+ }
+ ok=ok&&reopened==1&&software==1&&held&&held->data[0]&&held->buf[0];
+ std::cout<<(ok?"PASS ":"FAIL ")<<"decoder replacement with a leased old D3D12 frame; hardwareReopens="
+ <<reopened<<" softwareFallbacks="<<software<<'\n';
+ decoder.close();av_frame_free(&held);av_frame_free(&target);return ok;
+}
+
} // namespace
int main(int argc, char** argv)
@@ -263,6 +366,9 @@ int main(int argc, char** argv)
check(software.failures == 0 && software.frames > 0, "software decode produces frames without errors");
bool samePixels=true;for(const auto& [pts,pixels]:recovery.pixels){auto found=software.pixels.find(pts);samePixels=samePixels&&found!=software.pixels.end()&&found->second==pixels;}
check(recovery.recovered&&recovery.failures==0&&samePixels,"packet loss resumes at keyframe with reference-identical pixels and PTS");
+ check(hardErrorRecovery(stream,nullptr,nullptr),"Xbox hard-error boundary recovers on the software codec");
+ check(hardErrorRecovery(stream,context.device(),context.directQueue()),"Xbox hard-error boundary recovers on D3D12VA");
+ check(decoderReplacement(stream,context),"Xbox decoder replacement preserves output PTS and old-frame lifetime");
// B-frame reordering may emit a slightly different count on the software
// path; the hardware and software backends must stay within one frame.
const uint64_t difference = hardware.frames > software.frames ? hardware.frames - software.frames : software.frames - hardware.frames;
diff --git a/tests/xbox/XboxTests.cpp b/tests/xbox/XboxTests.cpp
index fd0bcec0..854f237c 100644
--- a/tests/xbox/XboxTests.cpp
+++ b/tests/xbox/XboxTests.cpp
@@ -29,6 +29,7 @@
#include "veyra/xbox/StreamApi.h"
#include "veyra/xbox/WebRtcSession.h"
#include "veyra/xbox/DisconnectPolicy.h"
+#include "veyra/xbox/VideoDecodeRecovery.h"
using namespace veyra::xbox;
using json = nlohmann::json;
@@ -539,6 +540,36 @@ void webrtcTests() {
} // namespace
int main(int argc, char** argv) {
+ {
+ VideoDecodeRecovery recovery;
+ check(recovery.failed(true)==VideoDecodeRecoveryAction::ResetHistory,
+ "one decode error resets references without replacing hardware");
+ recovery.picture();
+ check(recovery.failed(true)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(true)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(true)==VideoDecodeRecoveryAction::ReopenHardware,
+ "three consecutive hard errors permit one hardware reopen");
+ recovery.picture();
+ check(recovery.failed(true)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(true)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(true)==VideoDecodeRecoveryAction::UseSoftware,
+ "a recovered picture does not refill the hardware reopen budget");
+ check(recovery.failed(false)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(false)==VideoDecodeRecoveryAction::ResetHistory&&
+ recovery.failed(false)==VideoDecodeRecoveryAction::Stop,
+ "persistent failure after software fallback ends explicitly");
+ struct Unit { unsigned id; bool inputLoss=false; };
+ std::deque<Unit> queue;
+ for(unsigned i=0;i<8;++i)queue.push_back({i});
+ check(trimVideoInputs(queue,8)==1&&queue.size()==7&&queue.front().id==1&&queue.front().inputLoss,
+ "dropped compressed AU marks the first survivor for reference reset");
+ queue.push_back({8});
+ check(trimVideoInputs(queue,8)==1&&queue.front().id==2&&queue.front().inputLoss,
+ "repeated queue overflow propagates the lost-chain boundary");
+ queue.pop_front();
+ check(trimVideoInputs(queue,8)==0&&!queue.front().inputLoss,
+ "continuous queued units do not invent extra resets");
+ }
check(reconnectableDisconnect("KickForServerShutdown"), "server service restart is recoverable");
check(reconnectableDisconnect("connection lost"), "transport loss is recoverable");
check(!reconnectableDisconnect("KickForStreamingClientDisconnect") && !reconnectableDisconnect("unknown server disconnect"), "unknown kicks and takeover are not retried");