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(export): NVENC apiVersion fallback, CFR tail snap, present-sink FG export
Veyra Goal Agent6c70eb2b2635
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 5c7487c8..130a6130 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -221,7 +221,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.SetPropW(item(219),L"veyra.tip",HANDLE(L"直播兼容模式:切换显示交换链,会短暂停顿;不改变增强算法或导出。不保证所有捕获方式有效。"));add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);add(L"STATIC",L"补帧方式",1111,0,1,12,50,-1,24);- combo(208,1,78,{L"DLSS 帧生成",L"Intel XeSS · 实验显示补帧 2X",L"AMD FSR 帧生成 · 2X"});+ combo(208,1,78,{L"DLSS 帧生成",L"Intel XeSS · 实验显示补帧 2X-4X",L"AMD FSR 帧生成 · 2X"});add(L"STATIC",L"补帧倍率",1112,0,1,12,122,-1,24);combo(202,1,150,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});add(L"STATIC",L"运动估算",1113,0,1,12,194,-1,24);diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex e2fd2e70..8ff4bbb3 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -564,6 +564,22 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a// 6X (and 2X/3X/4X) can be exercised from the command line for diagnostics and// smoke tests; the interactive UI uses the capability-driven list instead.{int fgArgc=0;auto fgArgv=CommandLineToArgvW(GetCommandLineW(),&fgArgc);for(int i=1;i<fgArgc;++i){if(!_wcsicmp(fgArgv[i],L"--fg-multiplier")&&i+1<fgArgc){const int value=_wtoi(fgArgv[i+1]);if(value>=2&&value<=6){initialOptions.fgMultiplier=uint32_t(value);initialOptions.fg=true;}else if(value==1){initialOptions.fg=false;initialOptions.fgMultiplier=2;}}else if(!_wcsicmp(fgArgv[i],L"--fg-xess")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::XeSS;if(initialOptions.fgMultiplier<2)initialOptions.fgMultiplier=2;initialOptions.fg=true;}else if(!_wcsicmp(fgArgv[i],L"--fg-fsr")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Fsr;if(initialOptions.fgMultiplier<2)initialOptions.fgMultiplier=2;initialOptions.fg=true;}else if(!_wcsicmp(fgArgv[i],L"--fg-dlss")){initialOptions.settings.frameGenerationBackend=veyra::engine::FrameGenerationBackend::Dlss;}}if(fgArgv)LocalFree(fgArgv);}+// Backend flags must not be mistaken for the input path: the pass above leaves+// the last unrecognised token in autoInput, so "clip --fg-xess --fg-multiplier 4"+// tried to open a file named "--fg-xess". Re-derive the positional argument with+// every value-taking flag known, so --fg-xess / --fg-fsr / --fg-dlss work+// anywhere on the command line instead of only at the end.+{+ int positionalArgc=0;auto positionalArgv=CommandLineToArgvW(GetCommandLineW(),&positionalArgc);std::wstring positional;+ const wchar_t* valueFlags[]={L"--export-worker",L"--smoke-view",L"--smoke-dual-export",L"--smoke-seconds",L"--export-out",L"--max-frames",L"--cancel-after-ms",L"--smoke-save",L"--fg-multiplier",L"--capture-audio",L"--video-sr"};+ for(int i=1;i<positionalArgc;++i){const std::wstring a=positionalArgv[i];+ bool takesValue=false;for(const wchar_t* flag:valueFlags)if(a==flag){takesValue=true;break;}+ if(takesValue){++i;continue;}+ if(a.starts_with(L"--"))continue;+ positional=a;}+ if(!positional.empty())autoInput=positional;+ if(positionalArgv)LocalFree(positionalArgv);+}if(workerMapping){const int code=veyra::engine::runExportWorker(workerMapping);CoUninitialize();return code;}if(smokeSeconds<=0&&exportOutput.empty()){uiPreferences=preferences.load();initialOptions=veyra::engine::PlayerOptions::from(preferences.startup(initialOptions.snapshot()));engine.setVolume(uiPreferences.volume,uiPreferences.muted);uiState.subtitles=uiPreferences.subtitles;subtitlePixels=uiPreferences.subtitleSize;}engine.requestSettings(initialOptions.snapshot());diff --git a/apps/veyra/ui/SettingHelp.h b/apps/veyra/ui/SettingHelp.hindex 8210c79c..548e03fc 100644--- a/apps/veyra/ui/SettingHelp.h+++ b/apps/veyra/ui/SettingHelp.h@@ -35,7 +35,7 @@ inline const wchar_t* settingHelp(int id){case 205:return L"选择内容节奏。采集60→30适合60Hz信号里重复的30帧游戏内容;真60帧别硬砍半。时间戳仍保留。";case 206:return L"让框选区域少受NR改动,最多4块。只管NR,不给超分和补帧当保镖。";case 207:return L"选择DLSS SR或RTX视频超分,以及视频超分质量。两条路线各有脾气,试着看画质和耗时。";- case 208:return L"选择DLSS或实验XeSS补帧。XeSS目前为预览2X,不支持视频导出;别只看名字,看实际效果。";+ case 208:return L"选择DLSS、实验XeSS或AMD FSR补帧。XeSS/FSR的生成帧只存在于显示交换链,导出管线拿不到;导出时会自动改用DLSS补帧,显卡不支持则关闭补帧,提示和日志都会写明。别只看名字,看实际效果。";case 209:return L"选择运动估算后端。NVOF、FidelityFX、GPU DIS负责看出物体怎么动。DIS是实验算法,走通用计算单元,可能和NR抢活干,不保证更快;选它不会换掉你的补帧方式,也不会解锁AMD NR。";case 211:return L"把增强参数恢复为内建默认。调迷路了就走这里,保存的用户预设不会被删。";case 213:return L"在画面上拖框添加NR保护区域,Esc取消。把不想被改的地方圈出来。";diff --git a/docs/EXPORT_REPAIR_AND_FG_EXPORT_2026-09-16.md b/docs/EXPORT_REPAIR_AND_FG_EXPORT_2026-09-16.mdnew file mode 100644index 00000000..1f97af95--- /dev/null+++ b/docs/EXPORT_REPAIR_AND_FG_EXPORT_2026-09-16.md@@ -0,0 +1,123 @@+# 2026-09-16 导出失败两例修复 + XeSS/FSR 补帧导出(隔离分支)++分支 `codex/framegen-fsr-dolby-20260916`,未合并 main、未推送、未发布。+用户指令原文:"修,并且看看是不是用XeSS补帧没办法导出,也一起修了"。++## 1. 案例一:所有导出进程死在 NVENC 会话打开(用户 A)++证据(`C:\Users\123\Desktop\导出失败\export-worker-*.log`,5 个 worker 一致):++```+[nvenc] CreateInstance status=0 detail=+[nvenc] OpenD3D12Session status=15 detail=+```++`status=15` = `NV_ENC_ERR_INVALID_VERSION`。同一日志里设备创建、NVOF、NGX、DLSS-G+能力查询全部正常,唯独 NVENC 会话按版本号被拒。机器为 RTX 5060,驱动+32.0.15.8157;用户重装驱动后现象消失,指向 System32 里 `nvEncodeAPI64.dll`+的身份/版本与驱动不一致。++修法(`src/sink/NvencD3D12Encoder.cpp`):首次用编译期 `NVENCAPI_VERSION`+打不开时,按 13.0 → 12.0 → 11.0 降级重试(跳过刚失败的主版本),成功后在日志里+写明实际接受的版本。H.264/HEVC + D3D12 + 低延迟在 11.0 起全部可用,因此降级不改变+产品能力。++本机(RTX 5070 / 驱动 32.0.16.1656)复现不出"陈旧 DLL",因此加了仅测试用钩子+`VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=1` 强制跳过第一次打开,验证阶梯本身:++```+[nvenc] test-only: skipping the first OpenD3D12Session so the apiVersion ladder runs+[nvenc] OpenD3D12Session retry apiVersion=13.0 status=0+[nvenc] OpenD3D12Session accepted apiVersion=13.0 (compiled 13.0 was refused)+[export-verify] decoded=300 expected=300 eof=true cancelled=false passed=true+```++结论边界:阶梯已实现并验证可运行/可恢复,但"用户那台机器上的失败"本机无法复现,+需要该用户在实际发生的环境下用新包复测。++## 2. 案例二:99% 处整体失败(用户 B,两份 12MB worker 日志同点)++证据(`C:\Users\123\Desktop\BUG 导出失败 99卡死\export-worker-11628.log`):++```+[media] demuxer: opened ... durationUs=854150000 timeBase=1/1000+[source-file] opened 1920x1080 dur=854.15s avgFps=60.000 container=matroska,webm codec=hevc+[export-timeline] CFR declared=60/1 candidate=60/1 timestampQuantum=0.001 sampled=120+[export-timeline] CFR rejected source=51247 pts=854.133 expected=854.1166666666667+```++854.15s × 60fps ⇒ 约 51249 帧,出错索引 51247 是流的最后几帧之一;偏差+16.33ms ≈ 恰好一个帧间隔 ⇒ **最后一帧时间戳晚一格**(容器/编码器尾帧取整或最后+GOP 截断)。`CfrTimeline` 的相位窗逐帧收紧,尾帧一格格子就被判为"不均匀",25 分钟+的导出在最后 1 帧整体失败。++修法:++- `include/veyra/engine/CfrTimeline.h` 新增 `tailAccepts(index,pts,estimatedFrames)`:+ 仅当该帧属于"容器时长 × 帧率"估算出的**最后 3 帧**、且偏差 ≤ 1.5 帧间隔 + 1 个+ 量化步长时放行;估算不到总帧数(duration 缺失)时不放行。+- `src/engine/VideoExportJob.cpp`:拒绝时先走 `tailAccepts`,命中则计 `tailSnapped`+ 并 warn;未命中仍硬失败,但文案改成可读的"源文件第 N 帧时间戳偏移 X 毫秒…已停止+ 写入并保留 partial"。完成消息在发生尾部对齐时写明"尾部 N 帧已按恒定帧率对齐"。++为什么这样做是安全的:编码器写包用的是**输出帧序号**(`writer` 的 `pts=outputIndex`+再按输出时基重采样),输出本来就是严格 CFR 网格;尾部对齐只改变最后一帧的显示时长,+不移动任何已写帧,也不影响音轨交错(音轨按输出网格推进)。中间跳变仍走硬失败路径,+不能用尾帧通道蒙混。++## 3. XeSS / AMD FSR 补帧导出(用户新问题)++结论:**不是没接线,是取不到纹理。**++- XeSS-FG 3.0.2 头文件只有 `xefg_swapchain.h` / `xefg_swapchain_d3d12.h` / `xefg_swapchain_debug.h`;+ `libxess_fg.dll` 导出表里只有 `xefgSwapChain*`(`...CreateContext/InitFromSwapChain/TagFrameResource/+ SetPresentId/...`),没有任何"非交换链、输出到应用纹理"的入口。+- FSR 侧,FFX 的交换链上下文由 provider 自己持有代理链(`FsrFgPresenter` 只拿到+ `IDXGISwapChain4*`)。生成帧直接进显示链路。+- 因此导出管线(NVENC 取纹理编码)不可能拿到这两条路径的生成帧。旧实现直接拒绝整个+ 导出任务,用户拿不到任何文件。++新行为(`VideoExportJob.cpp`):++1. 请求 XeSS/FSR 补帧时,导出改用**图内 DLSS 补帧**(导出本来就要求 NVIDIA NVENC),+ 开始前把替换关系写进进度提示与日志(`present-sink frame generation cannot feed the+ encoder requested=... ; substituting the in-graph DLSS path`)。+2. DLSS 初始化因倍率被拒时降级到 2X,并提示"本次导出降为 2X"。+3. DLSS 整体不可用(例如无 DLSS-G 的显卡)时,改成只输出原始帧并提示"补帧关闭",+ 任务仍然产出完整文件。+4. 三种结果都会出现在 `export-timeline` / `export-counts` / 完成消息里,不静默。++## 4. 本机验证(RTX 5070,全部逐帧解码验证)++测试素材(复现案例二):`out/tail-jump.mkv` —— 300 帧 1080p30,MKV 1ms 量化,+最后一帧 PTS = 10.000s(网格应为 9.967s),由 ffmpeg `setpts` 构造。++| 命令 | 结果 |+| --- | --- |+| `veyra.exe out/tail-jump.mkv --export-out out/tail-jump-export.mp4 --no-nr --no-sr --no-fg` | exit 0;300 帧 @30fps;`tailSnapped=1`;`export-verify decoded=300 passed=true` |+| `... --fg-xess --fg-multiplier 4` | exit 0;1200 帧 @120fps;`backend=DLSS`、替换提示写入 note;逐帧验证通过 |+| `... --fg-fsr --fg-multiplier 2` | exit 0;600 帧 @60fps;`note=AMD FSR补帧由显示交换链直接生成…` |+| `VEYRA_TEST_FG_MULTIFRAME_MAX=1 ... --fg-dlss --fg-multiplier 4` | exit 0;4X→2X 降级;600 帧 @60fps |+| `VEYRA_TEST_FG_MULTIFRAME_MAX=0 ... --fg-dlss --fg-multiplier 4` | exit 0;补帧整体关闭;300 帧 @30fps |+| `VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=1 ...` | 阶梯恢复;300 帧;exit 0 |++自动检查:`veyra_repair_contract_tests.exe` 169 项 0 失败(新增 4 项尾帧规则,含+"中间跳变不得走尾帧通道");`scripts/gates/delivery.ps1` PASS,+`logs/delivery/95a4effb615949cbaedd502d87272cb1/result.json`(46.9s)。++## 5. 顺带修掉的 CLI 缺陷++`apps/veyra/ui/AppShell.cpp`:`--fg-xess` / `--fg-fsr` / `--fg-dlss` 在第一遍参数解析里+没有被识别,会落进位置参数 `autoInput`,于是 `clip.mp4 --fg-xess …` 会去打开名为+`--fg-xess` 的文件(`demuxer: avformat_open_input failed code=-2`)。改为在位置参数+重新推导时把已知带值开关全部跳过,GPU 后端参数现在与位置无关。该路径只服务于测试/诊断+入口,UI 不受影响。++## 6. 未做与边界(如实)++- **FFX 非交换链 FG**:`ffxCreateContextDescFrameGeneration` ++ `ffxDispatchDescFrameGeneration{outputs[4]}` 确实存在(FidelityFX SDK 2.3.0),+ 理论上能实现"真正的 FSR 补帧导出"。本轮未实现,列入后续任务。+- **XeSS 补帧导出**:SDK 没有非交换链入口,只能替换或关闭,永远拿不到真正的 XeSS 帧。+- **案例一现场复现**:本机驱动正常,无法复现陈旧 `nvEncodeAPI64.dll`,需要原用户复测。+- **未测**:AMD 显卡上的 FSR 补帧导出(导出路径仍只支持 NVENC);40/30 系实机导出。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 516ed90c..d46d0a6b 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -69,6 +69,17 @@- 证据:本机 30 秒 FSR 运行 `real=839/generated=838/presented=1677`、`presentSubmitFps=30.00`、`gpuFgBatchP95Ms=0.197`;delivery 短测 PASS `logs/delivery/442f41e29b684e7e87174bc075d4e282/result.json`。- **边界(如实)**:FgBatch 为**应用侧**计时(提供方内部的插值工作不经过我们的队列,无法打点);用户机器上"SDK提交=0"的原始触发未能在本机复现(本机 r3 正常),累计对齐是针对该症状的根治性修法,需要用户在 r4 包上复测确认。+### 2026-09-16 导出失败两例修复 + XeSS/FSR 补帧导出(用户:"修,并且看看是不是用XeSS补帧没办法导出,也一起修了")++两位粉丝群用户的导出失败日志逐条定位到根因,并按"必须能出文件"的目标修掉;完整复现素材、命令与证据见 [导出修复与补帧导出](EXPORT_REPAIR_AND_FG_EXPORT_2026-09-16.md)。++- **案例一(5 个 worker 全部 0 帧失败)**:`[nvenc] OpenD3D12Session status=15`(`NV_ENC_ERR_INVALID_VERSION`)。同一日志里设备/NVOF/NGX/DLSS-G 全部正常,只有 NVENC 会话按版本号被拒(RTX 5060 / 驱动 32.0.15.8157,重装驱动后用户侧消失)。`NvencD3D12Encoder` 改为首次失败后按 13.0→12.0→11.0 降级重试并记录实际接受的版本;H.264/HEVC+D3D12+低延迟在 11.0 起都覆盖。本机复现不出陈旧 DLL,用仅测试钩子 `VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=1` 验证阶梯能跑通并恢复(300 帧导出 exit 0、逐帧验证通过)。+- **案例二(99% 处整体失败,两份 12MB 日志同点)**:`CFR rejected source=51247 pts=854.133 expected=854.1166666666667`。60fps MKV(1ms 量化,854.15s)**最后一帧时间戳整整晚一个帧间隔**,被逐帧收紧的相位窗拒绝,25 分钟导出死在最后 1 帧。新增 `CfrTimeline::tailAccepts()`:只对"容器时长×帧率"估算出的最后 3 帧放行 ≤1.5 帧间隔偏差(估不出总帧数则不放行),编码器本来就按帧序写 CFR 网格,因此尾部对齐只改最后一帧显示时长、不动已写帧、不影响音画;中间跳变仍硬失败;成功/失败文案分别写明"尾部 N 帧已按恒定帧率对齐"与"第 N 帧偏移 X 毫秒…保留 partial"。+- **XeSS/FSR 补帧导出**:结论是取不到纹理,不是没接线 —— XeSS-FG 3.0.2 只有 `xefg_swapchain*` 头与 `xefgSwapChain*` 导出(无任何输出到应用纹理的入口),FSR 交换链上下文由 provider 自己持有代理链,生成帧直接进显示链路。旧实现直接拒绝整个导出;新行为是改用图内 DLSS 补帧(导出本就要求 NVENC),DLSS 被拒则降 2X、整体不可用则只出原始帧,三种结果都写进提示/日志/完成消息,不静默。+- **本机证据**:自造复现素材 `out/tail-jump.mkv`(300 帧 1080p30,尾帧 10.000s 而非 9.967s):无补帧 300 帧 @30fps、`--fg-xess 4X` 1200 帧 @120fps(backend=DLSS 替换)、`--fg-fsr 2X` 600 帧 @60fps、`VEYRA_TEST_FG_MULTIFRAME_MAX=1` 降级 2X 600 帧、`=0` 补帧关闭 300 帧 —— 全部 exit 0 且逐帧解码验证通过;修复合同测试新增 4 项尾帧规则后 169 项 0 失败;delivery 短测 PASS `logs/delivery/95a4effb615949cbaedd502d87272cb1/result.json`(46.9s)。+- **顺带修**:`--fg-xess/--fg-fsr/--fg-dlss` 在第一遍参数解析里未识别会落进 `autoInput`(`clip.mp4 --fg-xess` 会去打开名为 `--fg-xess` 的文件),已改为位置无关;设置页补帧方式与帮助文案同步更新。+- **未做(如实)**:FFX SDK 2.3.0 的非交换链 FG(`ffxDispatchDescFrameGeneration{outputs[4]}`)理论上能做真正的 FSR 补帧导出,本轮未实现;XeSS 无此入口,只能替换/关闭;案例一的陈旧 DLL 现场本机无法复现,需原用户用新包复测。+## 2026-09-15 采集卡直播窗口标题修复(第三方工具“识别不到 Veyra”)用户反馈除 OBS 外各平台直播工具无法识别“正在采集中的 Veyra”,且顺序敏感:先抓到窗口再开采集卡正常,先开采集卡再抓就抓不到。实机取证确认根因是 Veyra 自己:采集卡来源 `capture:`/`capture2:` 连接串被当文件名写进主窗口标题,实测标题长 776 字符(`Veyra — capture2:<十六进制设备路径>:...`),空闲/播放文件时为正常短名;直播伴侣日志把该标题截断到 259 字符后参与来源命名,其包内前端以 `${exe} ${title}` 命名来源。同场会话的 mediasdk_server 日志显示“采集卡已运行再添加 game 来源”的 hook 通路实际成功(`Load Shared Texture Success, size: 842 x 494`、`OnAutoSwitchMode from Window to Game`、GameSource 连续 60 秒以上有数据),因此本轮不做换链/画面的猜测性改动。diff --git a/include/veyra/engine/CfrTimeline.h b/include/veyra/engine/CfrTimeline.hindex b453fe66..6cf832b8 100644--- a/include/veyra/engine/CfrTimeline.h+++ b/include/veyra/engine/CfrTimeline.h@@ -18,6 +18,20 @@ public:}double fps() const { return double(num_) / den_; }double expected(uint64_t index) const { return origin_ + double(index) * den_ / num_; }+ // Tail-only recovery for containers whose last frame(s) sit off the common+ // quantizer phase: encoders round the final timestamp, and a truncated last+ // GOP loses one grid slot. Both used to abort a multi-hour export at the+ // very end. The encoder writes output frames on the grid from the frame+ // index, so a snapped tail can only change the last frame's display+ // duration; it cannot desync audio or shift any earlier frame.+ // `estimatedFrames` (container duration x rate) confines the exception to+ // the real tail, so a mid-stream gap can never take this path.+ bool tailAccepts(uint64_t index, double pts, uint64_t estimatedFrames) const {+ if(!valid() || !std::isfinite(pts)) return false;+ if(estimatedFrames == 0 || index + 3 < estimatedFrames) return false;+ const double interval = double(den_) / num_;+ return std::abs(pts - expected(index)) <= 1.5 * interval + quantum_;+ }bool accepts(uint64_t index, double pts) {if(!valid() || !std::isfinite(pts) || (havePrevious_ && pts<=previous_))return false;const double error=pts-expected(index);diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex b9f23f4c..a80ac3b5 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -22,14 +22,26 @@ namespace veyra::engine {namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames,const std::function<bool()>& frameBoundary,const std::function<void(const ExportCounts&)>& counts){if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}+ // XeSS-FG and AMD FSR-FG interpolate inside the present swapchain: the+ // provider presents the extra frames itself, so no output texture ever+ // reaches the application (XeSS-FG 3.0.2 exports only xefgSwapChain*, and+ // the FSR-FG context owns the proxy swapchain). Refusing the job left those+ // users with no file at all, so export now runs the in-graph DLSS path and+ // states the substitution; if that backend cannot initialise either, the+ // job still completes without frame generation instead of failing.+ std::wstring fgNote;+ auto appendFgNote=[&](const std::wstring& extra){if(!fgNote.empty())fgNote+=L";";fgNote+=extra;};if(options.fg&&presentSinkFrameGeneration(options.settings.frameGenerationBackend)){- progress(0,L"XeSS / AMD FSR 帧生成目前仅支持预览;导出请选择 DLSS 或关闭补帧");- veyra::log::warn("export","present-sink frame generation export rejected: the swapchain interpolation APIs have no encoder texture output contract");- return false;+ const auto requested=options.settings.frameGenerationBackend;+ fgNote=std::format(L"{}补帧由显示交换链直接生成,导出取不到它的画面;本次导出改用 DLSS 补帧 {}X",+ requested==FrameGenerationBackend::XeSS?L"XeSS":L"AMD FSR",options.fgMultiplier);+ veyra::log::warn("export",std::format("present-sink frame generation cannot feed the encoder requested={} multiplier={}; substituting the in-graph DLSS path",frameGenerationBackendName(requested),options.fgMultiplier));+ options.settings.frameGenerationBackend=FrameGenerationBackend::Dlss;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;+ uint64_t tailSnapped=0;std::wstring failureReason;auto failAv=[&](const wchar_t* stage,int code){char error[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(code,error,sizeof(error));@@ -65,15 +77,44 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptipipeline::FramePacket firstPacket;const AVFrame* firstFrame=nullptr;if(source.read(firstPacket,&firstFrame)!=source::SourceReadStatus::Frame||!firstFrame){failureReason=L"导出预读首帧失败";break;}info=source.info(); // retain this frame for the export, without decoding it again- const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});- outputRate=rate;- veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den));const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision,options.settings.srTarget);pipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();hdrExport=gd.hdrOutput;gd.captureBitDepth=info.color.pixelFormat==pipeline::SourcePixelFormat::P010?10:info.color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;if(gd.hdrOutput&&!hevc){failureReason=L"HDR视频请使用HEVC Main10导出(选择HEVC)";break;}gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();- if(!graph.initialize(gd)||!graph.createViews())break;+ // One attempt per frame-generation request. A rejected multiplier is a+ // capability statement, not an infrastructure failure: retry at 2X (the+ // floor every DLSS-G capable GPU honours) and only then fall back to a+ // real-frames-only export, so the user keeps a usable file either way.+ bool graphReady=false,fgFailure=false;+ auto startGraph=[&](bool fg,uint32_t multiplier){+ gd.enableFg=fg;gd.fgMultiplier=fg?multiplier:1;+ if(graph.initialize(gd)&&graph.createViews()){graphReady=true;return;}+ fgFailure=graph.failedBackend()==FailedBackend::Fg;+ graph.shutdown();+ };+ if(options.fg){+ startGraph(true,options.fgMultiplier);+ if(!graphReady&&fgFailure&&options.fgMultiplier>2){+ startGraph(true,2);+ if(graphReady){+ veyra::log::warn("export",std::format("DLSS frame generation rejected multiplier={} on this adapter; exporting at 2X",options.fgMultiplier));+ options.fgMultiplier=2;appendFgNote(L"DLSS 补帧在该显卡上不支持请求的倍率,本次导出降为 2X");+ }+ }+ if(!graphReady&&fgFailure){+ startGraph(false,1);+ if(graphReady){+ veyra::log::warn("export","DLSS frame generation unavailable; exporting real frames only");+ options.fg=false;options.fgMultiplier=1;appendFgNote(L"DLSS 补帧无法初始化,本次导出只输出原始帧(补帧关闭)");+ }+ }+ } else startGraph(false,1);+ if(!graphReady){if(failureReason.empty())failureReason=L"增强管线初始化失败,请查看诊断";break;}+ if(!fgNote.empty())progress(0,fgNote);+ const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});+ outputRate=rate;+ veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} fg={} backend={} note={} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den,options.fg?options.fgMultiplier:1,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));outputWidth=gd.workWidth;outputHeight=gd.workHeight;if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;@@ -108,6 +149,10 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptimuxResult=avformat_write_header(mux,nullptr);if(muxResult<0){failAv(L"写入MP4文件头",muxResult);break;}headerWritten=true;uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;+ // Container duration x rate bounds the tail exception below: only the+ // last frames of the real stream may sit off the CFR grid.+ const double durationSeconds=info.duration.toDouble();+ const uint64_t estimatedFrames=durationSeconds>0?uint64_t(std::llround(durationSeconds*double(rateNum)/rateDen)):0;while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;source::SourceReadStatus rs;if(sourceCount==0){packet=firstPacket;frame=firstFrame;rs=source::SourceReadStatus::Frame;}@@ -116,8 +161,14 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiif(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();const double expectedPts=timeline.expected(sourceCount);if(!timeline.accepts(sourceCount,packet.pts.toDouble())){- progress(0,L"此文件时间戳不均匀,当前CFR导出不支持;已保留partial,未改写音画时间轴");- veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={}",sourceCount,packet.pts.toDouble(),expectedPts));error=true;break;+ const double pts=packet.pts.toDouble(),deviationMs=(pts-expectedPts)*1000.0;+ if(timeline.tailAccepts(sourceCount,pts,estimatedFrames)){+ ++tailSnapped;+ veyra::log::warn("export-timeline",std::format("tail snap source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));+ } else {+ progress(0,std::format(L"源文件第 {} 帧时间戳偏移 {:.1f} 毫秒,无法按恒定帧率无损对齐;已停止写入并保留 partial",sourceCount,deviationMs));+ veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={} deviationMs={:.3f} estimatedFrames={} outputIndex={}",sourceCount,pts,expectedPts,deviationMs,estimatedFrames,outputIndex));error=true;break;+ }}pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,false)){error=true;break;}const auto readyStart=std::chrono::steady_clock::now();@@ -144,7 +195,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiif(error||cancel)break;if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!enc.encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}if(error)break;- veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1));+ veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} backend={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));progress(.99,L"正在收尾:等待编码器输出剩余帧");if(!enc.finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看NVENC诊断";break;}if(!writeAudioUntil(audioEndSeconds))break;@@ -191,7 +242,11 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiif(!ok&&!cancel){const DWORD error=GetLastError();failureReason=std::format(L"视频验证已通过,但保存文件名失败(Windows错误 {});可保留partial文件",error);veyra::log::error("export-rename",std::format("MoveFileExW failed error={} partial={}",error,utf8(partial)));}}}- if(ok)progress(1,L"视频导出完成,逐帧完整性验证通过");+ if(ok){+ std::wstring done=L"视频导出完成,逐帧完整性验证通过";+ if(tailSnapped>0)done=std::format(L"视频导出完成,逐帧完整性验证通过(尾部 {} 帧时间戳已按恒定帧率对齐)",tailSnapped);+ progress(1,fgNote.empty()?done:fgNote+L";"+done);+ }else {std::wstring message=cancel?L"导出已取消":failureReason.empty()?L"视频导出失败,请查看诊断":failureReason;std::error_code ec;diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cppindex 89337b51..83c11caa 100644--- a/src/sink/NvencD3D12Encoder.cpp+++ b/src/sink/NvencD3D12Encoder.cpp@@ -40,7 +40,29 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&using Create=NVENCSTATUS(NVENCAPI*)(NV_ENCODE_API_FUNCTION_LIST*);auto create=reinterpret_cast<Create>(GetProcAddress(p.dll,"NvEncodeAPICreateInstance"));p.api.version=NV_ENCODE_API_FUNCTION_LIST_VER;if(!create||!p.check(create(&p.api),"CreateInstance"))return false;NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS open{};open.version=NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;open.apiVersion=NVENCAPI_VERSION;open.device=ctx.device();open.deviceType=NV_ENC_DEVICE_TYPE_DIRECTX;- if(!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session"))return false;+ // Some systems carry an older nvEncodeAPI64.dll (System32 copy from a+ // mixed driver/tool install) which rejects the compiled 13.1 declaration+ // with NV_ENC_ERR_INVALID_VERSION (status 15) - observed on a user RTX+ // 5060 where every export died here. Older API versions are fully+ // sufficient for our usage (H.264/HEVC, D3D12, low latency), so retry+ // downwards before giving up.+ // Test-only: pretend the compiled declaration was refused, so the fallback+ // ladder below still gets exercised on a healthy driver. Never set by the UI.+ const bool forcedMiss=GetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",nullptr,0)>0;+ if(forcedMiss)veyra::log::warn("nvenc","test-only: skipping the first OpenD3D12Session so the apiVersion ladder runs");+ if(forcedMiss||!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session")) {+ const uint32_t fallbackVersions[]={NVENCAPI_MAJOR_VERSION,13u,12u,11u};+ bool opened=false;uint32_t accepted=0;+ for(const uint32_t major:fallbackVersions){+ if(!forcedMiss&&major==NVENCAPI_MAJOR_VERSION)continue; // already refused above+ open.apiVersion=major;+ const auto result=p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder);+ log::info("nvenc",std::format("OpenD3D12Session retry apiVersion={}.0 status={}",major,unsigned(result)));+ if(result==NV_ENC_SUCCESS){opened=true;accepted=major;break;}+ }+ if(!opened)return false;+ log::info("nvenc",std::format("OpenD3D12Session accepted apiVersion={}.0 (compiled {}.0 was refused)",accepted,NVENCAPI_MAJOR_VERSION));+ }p.hdr=graph.hdrOutput();if(p.hdr&&!hevc){veyra::log::error("nvenc","HDR export requires HEVC Main10");return false;}p.inputFormat=p.hdr?NV_ENC_BUFFER_FORMAT_YUV420_10BIT:NV_ENC_BUFFER_FORMAT_NV12;const GUID codec=hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex 66849cbc..7875e072 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -371,6 +371,18 @@ int main(){engine::CfrTimeline ticks(60,1,1.0/60,0);bool exactTicks=true;for(unsigned i=0;i<120;++i)exactTicks &= ticks.accepts(i,i/60.0);check(exactTicks&&!ticks.accepts(120,121.0/60),"one-tick CFR accepted but missing frame rejected");std::vector<double> mkv;for(unsigned i=0;i<24;++i)mkv.push_back(std::round(i*1000.0/60)/1000);check(engine::CfrTimeline::select(29990,499,.001,mkv)==std::pair<int,int>{60,1},"misdeclared MKV rate selects consistent standard CFR candidate");+ {+ // User report 2026-09-16: a 854.15s / 60fps MKV whose final frame sits+ // exactly one frame interval late aborted a 25 minute export at 99%.+ // The grid write is index based, so only that last frame's duration may+ // move - and only when the stream really ends there.+ engine::CfrTimeline tail(60,1,.001,0);bool seated=true;+ for(unsigned i=0;i<51247;++i)seated &= tail.accepts(i,std::round(i*1000.0/60)/1000);+ check(seated&&!tail.accepts(51247,854.133),"a one-frame tail jump still breaks the strict CFR phase test");+ check(tail.tailAccepts(51247,854.133,51249)&&tail.tailAccepts(51248,854.15,51249),"tail snap covers the real end of stream");+ check(!tail.tailAccepts(51247,854.133,60000)&&!tail.tailAccepts(100,std::round(100*1000.0/60)/1000+.1,60000),"tail snap never covers a mid-stream gap");+ check(!tail.tailAccepts(51247,854.9,51249)&&!tail.tailAccepts(51247,854.133,0),"tail snap rejects larger deviations and unknown streams");+ }using Reason=pipeline::ResetReason;check(diagnostics::resetCause(0,Reason::PauseResume,Reason::SceneCut)==Reason::PauseResume&&diagnostics::resetCause(0,Reason::Seek,Reason::None)==Reason::Seek&&