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 live scrub previews, NR shadow extrapolation and export diagnostics

Veyra Goal Agentf7bc4ebffe57
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 1911d425..aca88d49 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -80,6 +80,7 @@ std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool
std::vector<veyra::engine::SubtitleCue> subtitles;HWND subtitleLabel=nullptr;
HFONT font=nullptr,emptyFont=nullptr;bool smokeZoom=false,smokeHover=false;ULONGLONG hoverPostedTick=0;int zoomStep=0;veyra::engine::PlayerSnapshot zoomBefore;bool smokeRollback=false,smokeRollbackFlow=false,smokeUi=false;int uiStep=0;bool smokeSettings=false;int settingsStep=0;bool smokeControls=false;int smokeStep=0;std::wstring smokeSave;
std::wstring screenshotPath;ULONGLONG screenshotTick=0;bool screenshotPending=false,smokeScreenshot=false;int screenshotStep=0;
+#include "SeekPreview.h"
void openFile(const std::wstring&);
void layout();
void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}
@@ -247,7 +248,34 @@ void takeScreenshot(){
screenshotPending=true;screenshotTick=GetTickCount64();
engine.saveFrame(screenshotPath);SetWindowTextW(GetDlgItem(mainWindow,Save),L"保存中…");
}
-void startVideoExport(bool hevc){auto s=engine.snapshot();if(currentFile.empty()||s.capture||s.image||!s.frames||s.applying||s.failed||exportJob.poll().active())return;std::vector<wchar_t> name(32768);OPENFILENAMEW d{sizeof(d)};d.hwndOwner=mainWindow;d.lpstrFile=name.data();d.nMaxFile=32768;d.lpstrFilter=L"MP4视频\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){exportJob.start(currentFile,name.data(),s.applied,hevc);jobPaused=false;layout();}}
+void startVideoExport(bool hevc){
+ const auto s=engine.snapshot();
+ const wchar_t* reason=nullptr;
+ if(currentFile.empty()||s.capture||s.image)reason=L"请先打开一个本地视频。";
+ else if(!s.frames||s.applying)reason=L"视频或效果正在初始化,请稍后重试。";
+ else if(exportJob.poll().active())reason=L"已有导出任务,请先完成或取消当前任务。";
+ if(reason){veyra::log::warn("export-dialog","request rejected by source/settings/job state");MessageBoxW(mainWindow,reason,L"暂时无法导出",MB_OK|MB_ICONINFORMATION);return;}
+ // Export owns a separate worker. A failed preview must not leave an
+ // enabled export button that silently ignores clicks; use applied settings.
+ std::vector<wchar_t> name(32768);
+ const auto suggested=std::filesystem::path(currentFile).stem().wstring()+L"-Veyra.mp4";
+ wcsncpy_s(name.data(),name.size(),suggested.c_str(),_TRUNCATE);
+ OPENFILENAMEW d{sizeof(d)};d.hwndOwner=mainWindow;d.lpstrFile=name.data();d.nMaxFile=DWORD(name.size());
+ d.lpstrFilter=L"MP4视频\0*.mp4\0";d.lpstrDefExt=L"mp4";
+ d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;
+ veyra::log::info("export-dialog","opening destination dialog");
+ if(GetSaveFileNameW(&d)){
+ // Never imply overwrite support: the worker deliberately preserves
+ // existing files, including a recoverable partial from an earlier job.
+ if(std::filesystem::exists(name.data())||std::filesystem::exists(std::wstring(name.data())+L".partial")){
+ MessageBoxW(mainWindow,L"这个名称的文件或 partial 已存在。为保留原文件,请使用新名称。",L"请选择新名称",MB_OK|MB_ICONINFORMATION);return;
+ }
+ exportJob.start(currentFile,name.data(),s.applied,hevc);jobPaused=false;layout();
+ }else if(const auto error=CommDlgExtendedError()){
+ veyra::log::error("export-dialog",std::format("GetSaveFileNameW failed code=0x{:08X}",error));
+ MessageBoxW(mainWindow,std::format(L"无法打开保存位置窗口,错误 0x{:08X}。详见诊断日志。",error).c_str(),L"导出窗口错误",MB_OK|MB_ICONERROR);
+ }else veyra::log::info("export-dialog","destination dialog cancelled");
+}
#include "UiRepairChecks.h"
#include "TransportChecks.h"
@@ -349,8 +377,8 @@ case Subtitle:if(lp)subtitleMenu();else{uiState.subtitles=!uiState.subtitles;lay
case SubtitleLoad:{std::vector<wchar_t> name(32768);OPENFILENAMEW d{sizeof(d)};d.hwndOwner=hwnd;d.lpstrFile=name.data();d.nMaxFile=32768;d.lpstrFilter=L"SubRip 字幕\0*.srt\0";d.Flags=OFN_FILEMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&d)){subtitles=veyra::engine::loadSrt(name.data());uiState.subtitles=true;layout();}break;}
case SubtitleSize:subtitlePixels=subtitlePixels==22?28:subtitlePixels==28?34:22;break;
case Recent:{std::vector<wchar_t> recent(32768);GetPrivateProfileStringW(L"Player",L"最近打开",L"",recent.data(),32768,(veyra::runtime::localDataDirectory()/"veyra.ini").wstring().c_str());openFile(recent.data());break;}
-case Play:{auto s=engine.snapshot();if(s.capture||s.image||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping)break;if(!currentFile.empty()&&(!s.running||s.transport==veyra::engine::TransportState::Ended)){openFile(currentFile);break;}paused=s.transport==veyra::engine::TransportState::Playing;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}
-case Stop:engine.stop();break;
+case Play:{auto s=engine.snapshot();if(s.capture||s.image||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping)break;if(!currentFile.empty()&&(!s.running||s.transport==veyra::engine::TransportState::Ended)){openFile(currentFile);break;}if(seekPreview.active){seekPreview.resume=!seekPreview.resume;paused=!seekPreview.resume;break;}paused=s.transport==veyra::engine::TransportState::Playing;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}
+case Stop:seekPreview={};engine.stop();break;
case Save:takeScreenshot();break;
case Sr:SendMessageW(hwnd,WM_APP+44,201,IsDlgButtonChecked(hwnd,Sr));break;
case Multiplier:case Realtime:case Nr:case Fg:{auto changed=engine.snapshot().desired;const auto id=LOWORD(wp);
@@ -385,7 +413,7 @@ case Capture:case ProRailCapture:veyra::ui::showCapturePanel(hwnd,[](const std::
case Export:if(uiState.mode==veyra::ui::Mode::Professional)startVideoExport(false);break;
case Info:showDiagnostics=!showDiagnostics;layout();break;
}return 0;
-case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==GetDlgItem(hwnd,Volume)){engine.setVolume(float(SendDlgItemMessageW(hwnd,Volume,TBM_GETPOS,0,0))/100,false);return 0;}if(reinterpret_cast<HWND>(lp)==seekBar){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(!dragging&&LOWORD(wp)!=TB_ENDTRACK&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;
+case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==GetDlgItem(hwnd,Volume)){engine.setVolume(float(SendDlgItemMessageW(hwnd,Volume,TBM_GETPOS,0,0))/100,false);return 0;}if(reinterpret_cast<HWND>(lp)==seekBar&&LOWORD(wp)!=TB_ENDTRACK){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(s.duration>0)seekPreview.update(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0,!dragging);}return 0;
case WM_KEYDOWN:if(wp==VK_ESCAPE&&protectionArmed){cancelProtection();return 0;}if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){toggleFullscreen();return 0;}if(wp==VK_ESCAPE&&full){toggleFullscreen();return 0;}if(wp=='V'&&uiState.mode==veyra::ui::Mode::Professional){holdOriginal=true;updateComparison();return 0;}break;
case WM_KEYUP:if(wp=='V'){holdOriginal=false;updateComparison();return 0;}break;
case WM_SYSKEYDOWN:if(wp==VK_RETURN&&(lp&(1LL<<29))){toggleFullscreen();return 0;}break;
@@ -462,7 +490,8 @@ std::wstring metric=std::format(L"源帧处理 {:.1f} fps · 显示提交 {:
if(uiState.mode==Mode::Professional&&!full&&!transition.running&&GetTickCount64()-dashboardTick>=250){dashboardTick=GetTickCount64();RECT client{};GetClientRect(hwnd,&client);RECT dashboard{0,client.bottom-dip(hwnd,232),client.right,client.bottom};InvalidateRect(hwnd,&dashboard,FALSE);}
exportJob.watching(preferWatching&&s.running&&s.transport==veyra::engine::TransportState::Playing);auto job=exportJob.poll();exportPanelStatus(job,!currentFile.empty()&&!s.capture&&!s.image&&s.frames>0&&!s.applying,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);
setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");ShowWindow(GetDlgItem(hwnd,EmptyTitle),SW_HIDE);ShowWindow(GetDlgItem(hwnd,EmptyHint),SW_HIDE);
-if(dragging&&GetCapture()!=seekBar)dragging=false;
+if(dragging&&GetCapture()!=seekBar){dragging=false;seekPreview.released=true;}
+seekPreview.tick();
if(!dragging&&s.duration>0){int position=int((s.seekPresented<s.seekRequested&&!s.failed?s.seekTarget:s.position)/s.duration*10000);if(SendMessageW(seekBar,TBM_GETPOS,0,0)!=position)SendMessageW(seekBar,TBM_SETPOS,TRUE,position);}
if(!smokeViewApplied&&!smokeView.empty()&&(s.frames>0||smokeEmpty)){smokeViewApplied=true;if(smokeView==L"small")SetWindowPos(hwnd,nullptr,0,0,800,600,SWP_NOMOVE|SWP_NOZORDER);if(smokeView!=L"daily"&&smokeView!=L"empty"&&uiState.mode==veyra::ui::Mode::Daily)switchMode();if(smokeView==L"export")selectInspector(3);if(smokeView==L"diagnostics"){showDiagnostics=true;layout();}if(smokeView==L"fullscreen")toggleFullscreen();}
if(smokeDualPause&&pausedPosition<0&&s.frames>20){engine.pause(true);pausedPosition=s.position;pausedFrames=s.frames;}
diff --git a/apps/veyra/ui/SeekPreview.h b/apps/veyra/ui/SeekPreview.h
new file mode 100644
index 00000000..9569682c
--- /dev/null
+++ b/apps/veyra/ui/SeekPreview.h
@@ -0,0 +1,29 @@
+// A single in-flight preview plus the latest pointer target. Waiting for the
+// presented frame prevents rapid mouse events from cancelling every decode.
+struct SeekPreview {
+ bool active=false,released=false,resume=false;
+ uint64_t session=0;
+ double target=-1,submitted=-1;
+ void update(double seconds,bool release) {
+ auto s=engine.snapshot();
+ if(!s.running||s.capture||s.image||s.duration<=0)return;
+ if(!active||session!=s.sessionId){
+ *this={};active=true;session=s.sessionId;
+ resume=s.transport==veyra::engine::TransportState::Playing;
+ engine.pause(true);
+ }
+ target=seconds;released=release;
+ // Mouse release supersedes even an outstanding preview: the final
+ // exact target must never be dropped behind a busy preview.
+ if(release){engine.seek(target);submitted=target;}
+ else tick();
+ }
+ void tick() {
+ if(!active)return;
+ const auto s=engine.snapshot();
+ if(s.sessionId!=session||!s.running||s.failed){*this={};return;}
+ if(s.seekRequested!=s.seekPresented)return;
+ if(target!=submitted){engine.seek(target);submitted=target;return;}
+ if(released){const bool play=resume;*this={};engine.pause(!play);}
+ }
+} seekPreview;
diff --git a/apps/veyra/ui/TransportChecks.h b/apps/veyra/ui/TransportChecks.h
index b1d28f06..d5fcc588 100644
--- a/apps/veyra/ui/TransportChecks.h
+++ b/apps/veyra/ui/TransportChecks.h
@@ -8,6 +8,7 @@ void tickTransportChecks(HWND hwnd,const veyra::engine::PlayerSnapshot& s){
auto settled=[&]{return s.seekRequested==s.seekPresented&&std::abs(s.position-transportTarget)<.2;};
auto hit=[&]{RECT r{};GetWindowRect(seekBar,&r);for(int n:{1,3,5,7,9})for(LONG y:{2L,(r.bottom-r.top)/2,(r.bottom-r.top)-3})if(WindowFromPoint({r.left+(r.right-r.left)*n/10,r.top+y})!=seekBar)return false;return true;};
auto point=[&](double fraction){RECT r{};GetClientRect(seekBar,&r);return MAKELPARAM(veyra::ui::dip(seekBar,6)+int((r.right-veyra::ui::dip(seekBar,12))*fraction),r.bottom/2);};
+ auto pointer=[&](UINT message,double fraction){const auto p=point(fraction);POINT screen{GET_X_LPARAM(p),GET_Y_LPARAM(p)};ClientToScreen(seekBar,&screen);SetCursorPos(screen.x,screen.y);SendMessageW(seekBar,message,message==WM_LBUTTONUP?0:MK_LBUTTON,p);};
auto post=[&](HWND focus,WPARAM key){SetFocus(focus);PostMessageW(focus,WM_KEYDOWN,key,1);PostMessageW(focus,WM_KEYUP,key,1LL<<31);};
switch(transportStep){
case 0:
@@ -22,17 +23,17 @@ void tickTransportChecks(HWND hwnd,const veyra::engine::PlayerSnapshot& s){
pointerActivity();
if(!require(GetFocus()==hwnd,"fullscreen_reclaims_playback_focus")||!require(hit(),"professional_fullscreen_seek_entire_hitbox"))break;
transportRequest=s.seekRequested;
- SendMessageW(seekBar,WM_LBUTTONDOWN,MK_LBUTTON,point(.2));
- SendMessageW(seekBar,WM_MOUSEMOVE,MK_LBUTTON,point(.4));
+ pointer(WM_LBUTTONDOWN,.2);
+ pointer(WM_MOUSEMOVE,.4);
transportTick=GetTickCount64();transportStep=2;break;
case 2:
if(GetTickCount64()-transportTick<1900)return;
- if(!require(fullControls&&dragging&&GetCapture()==seekBar&&s.seekRequested==transportRequest,"drag_retains_controls_and_defers_decode_until_release"))break;
- SendMessageW(seekBar,WM_LBUTTONUP,0,point(.4));
+ if(!require(fullControls&&dragging&&GetCapture()==seekBar&&s.seekPresented>transportRequest&&s.seekPresented==s.seekRequested&&std::abs(s.position-s.duration*.4)<s.duration*.001,"drag_presents_latest_frame_while_mouse_still_held"))break;
+ pointer(WM_LBUTTONUP,.4);
transportTarget=engine.snapshot().seekTarget;transportStep=3;break;
case 3:
if(!settled())return;
- if(!require(std::abs(transportTarget-s.duration*.4)<s.duration*.001&&!dragging&&!GetCapture(),"drag_release_presents_requested_frame"))break;
+ if(!require(std::abs(transportTarget-s.duration*.4)<s.duration*.001&&!dragging&&!GetCapture()&&s.transport==veyra::engine::TransportState::Paused,"drag_release_presents_requested_frame_and_preserves_pause"))break;
transportTarget=s.position+10;post(GetDlgItem(hwnd,Volume),VK_RIGHT);transportStep=4;break;
case 4:
if(!settled())return;
@@ -54,11 +55,26 @@ void tickTransportChecks(HWND hwnd,const veyra::engine::PlayerSnapshot& s){
case 8:
if(!full)toggleFullscreen();pointerActivity();
if(!require(hit(),"daily_fullscreen_seek_entire_hitbox"))break;
- SendMessageW(seekBar,WM_LBUTTONDOWN,MK_LBUTTON,point(.2));SendMessageW(seekBar,WM_LBUTTONUP,0,point(.2));
+ pointer(WM_LBUTTONDOWN,.2);pointer(WM_LBUTTONUP,.2);
transportTarget=engine.snapshot().seekTarget;transportStep=9;break;
case 9:
if(!settled())return;
if(!require(std::abs(transportTarget-s.duration*.2)<s.duration*.001,"daily_fullscreen_click_presents_requested_frame"))break;
- transportStep=10;veyra::log::info("ui-transport-test","PASS fullscreen drag/click, paused seek, focus, queued arrows, windowed slider isolation");break;
+ engine.pause(false);paused=false;transportStep=11;break;
+ case 11:
+ if(s.transport!=veyra::engine::TransportState::Playing)return;
+ transportRequest=s.seekPresented;
+ pointer(WM_LBUTTONDOWN,.3);pointer(WM_MOUSEMOVE,.5);
+ transportTick=GetTickCount64();transportStep=12;break;
+ case 12:
+ if(GetTickCount64()-transportTick<1900)return;
+ if(!require(dragging&&s.seekPresented>transportRequest&&std::abs(s.position-s.duration*.5)<s.duration*.001&&s.transport==veyra::engine::TransportState::Paused,"playing_drag_shows_frame_with_transport_temporarily_paused"))break;
+ pointer(WM_LBUTTONUP,.6);transportTarget=engine.snapshot().seekTarget;transportStep=13;break;
+ case 13:
+ // The timer's snapshot precedes SeekPreview::tick(), which may have
+ // just resumed playback. Observe the next snapshot before asserting.
+ if(s.seekRequested!=s.seekPresented||seekPreview.active||s.transport!=veyra::engine::TransportState::Playing)return;
+ if(!require(s.transport==veyra::engine::TransportState::Playing&&s.position>=transportTarget-.1&&s.position<transportTarget+1,"release_supersedes_preview_and_resumes_playback"))break;
+ transportStep=10;veyra::log::info("ui-transport-test","PASS live drag preview, exact release, pause/resume, focus, queued arrows, windowed slider isolation");break;
}
}
diff --git a/docs/SCRUB_NR_EXPORT_REPAIR_2026-09-15.md b/docs/SCRUB_NR_EXPORT_REPAIR_2026-09-15.md
new file mode 100644
index 00000000..b89cfed6
--- /dev/null
+++ b/docs/SCRUB_NR_EXPORT_REPAIR_2026-09-15.md
@@ -0,0 +1,44 @@
+# 拖动预览、NR参数与导出收尾修复
+
+日期:2026-09-15。分支:`codex/user-issues-repair-20260915`;本轮基线 `0b49279`。仅本地候选,未发布。
+
+## 结论与验收范围
+
+| 项目 | 确认的问题 | 本轮处理 | 验收与限制 |
+| --- | --- | --- | --- |
+| 拖动时显示画面 | WM_HSCROLL 明确忽略 THUMBTRACK,仅松手请求 seek | SeekPreview 保留一个在途请求和最新指针目标;前一帧显示后继续请求最新位置,松手立即覆盖为精确目标 | 真实4K文件、全屏暂停/播放拖动及方向键自动测试通过;刷新速度受关键帧解码和所开增强耗时限制,不承诺逐鼠标事件或60fps预览 |
+| NR强度2暗部全黑 | 在线性光中外推 `base + 2*(NR-base)` 可成为负数,最后 max(0) 导致细节整片归零 | 对超过原NR暗化端点的加强量使用正值、切线连续的延伸;强度0原图、0至1正常混合、默认1原端点保持。HDR合法负分量不按SDR黑色截断 | GPU合成测试、真实NR参数测试通过;没有复制Magpie代码或宣称画质等同。加强暗化仍会变暗,并非把强度2改成强度1 |
+| 导出99%失败 | 旧代码混合编码finish/音轨/trailer结果;关闭输出未检查错误;视频包写失败仍增加written;验证/改名错误解释不足 | 正确计数成功写入的帧;分开记录封装收尾、关闭刷新、逐帧验证、MoveFileEx错误;显示逐帧验证进度;保留partial | 完整3600帧有效视频+改名锁测试、损坏最后一帧测试通过。缺反馈者原文件/日志,不能认定其根因,更未取消完整性校验 |
+| 点击导出没窗口 | 按钮启用条件不含failed,但点击处理函数遇到failed静默返回 | 导出使用独立worker及已应用参数,允许已有帧的失败预览发起;其他不可导出状态明确提示;记录CommDlgExtendedError并给默认文件名 | 实际UI点击观察到“另存为”及默认文件名,取消无任务。未知机器的系统弹窗错误仍需新日志 |
+
+## NR参数逐层审查
+
+SettingsWindow控件100/101/102/103分别提交模型强度、局部明暗、局部结构、肤质;107至111分别提交total/darken/brighten/color/luminance。模型浮点字段经NGX F32,风格/自动遮罩/UI修正经I32,未发现错接字段。范围:前三项0至1,肤质-1自动或0至2,残差五项0至2。残差常量顺序与HLSL一致。
+
+旧 `RepairParameterTests.cpp` 在默认效果改为关闭之后,没有设置 `s.nr=true`,applySettings实际关闭了NR。因此原测试不能继续证明参数有作用。现已显式开启,并要求18组各4帧、累计72次真实Evaluate。
+
+真实测试:intensity/tone/structure/style/autoMask及五个残差控制均观察到输出变化;肤质、UI修正在该合成素材上未观察到变化,继续保持未证实标识。未知运行库、实际人脸/UI素材和Magpie同帧对照尚未验证。
+
+暗部GPU独立夹具使用原始线性0.10、NR结果0.04。旧强度2得到-0.02后归零;新结果0.016,保持正值、暗于默认结果。0/0.5/1分别仍为0.10/0.07/0.04;逐项测试五控件0/0.5/1/2,中性颜色不会因“色彩变化”产生色偏。HDR默认测试保留(-0.2,3,0.75),零残差/零强度保留原图。这里没有修改输入gamma、输出transfer或整体对比度。
+
+## 导出验证
+
+`FileSafetyTests -- export-lock-final` 在封装关闭后持有只读文件句柄,允许解码、禁止rename。真实解码3600/3600帧成功后,MoveFileEx返回Windows32;必须报告“验证已通过,但保存文件名失败”。这证明一种99%保存失败机制,不能冒充反馈者复现。
+
+`export-corrupt-output` 在校验前破坏最后一个视频包;必须失败并保留partial。能够被播放器播放或被MKV重封装不代表每一帧、时间戳和结尾均完整。当前CFR帧数、时间戳及HDR格式验证继续保留。已有目标文件不覆盖,界面要求新名称。
+
+## 实际命令与证据
+
+- 构建:`cmd.exe /c out\build\veyra-build-x64-release.cmd`,日志 `logs/scrub-nr-export-build[-b/-c/-d/-e]-20260915.log`,均exit0。使用现有patched FFmpeg,未改运行组件。
+- `scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_repair_shader_tests.exe -TimeoutSeconds 45 -LogPrefix logs/scrub-nr-shader-20260915`:exit0,暗部/零残差/HDR有符号端点通过。
+- 同wrapper运行 `veyra_repair_parameter_tests.exe`,120秒上限,`logs/scrub-nr-parameters-20260915.stdout.log`:exit0,72次Evaluate;实际NGX创建/执行日志保留。
+- GUI:`veyra.exe <用户4K视频> --no-nr --no-sr --no-fg --smoke-transport --smoke-seconds 24`,wrapper55秒上限。最终 `logs/scrub-transport-c-20260915.stdout.log` / `logs/scrub-transport-c-app-20260915.log` exit0。首次失败为测试读取了恢复前的旧快照;第二次目标受系统鼠标消息影响,测试只发送合成坐标却未同步真实指针。修正测试等待下一快照及测试指针定位,保留两次失败日志,不删除失败记录。
+- `veyra_file_safety_tests.exe export-lock-final loop/local/fixed_clips/test_av_1080p.mp4 logs/export-lock-20260915.mp4`,wrapper120秒上限:exit0,`logs/export-lock-20260915.stdout.log`。
+- 对应 `export-corrupt-output` 模式:exit0,`logs/export-corrupt-20260915.stdout.log`,损坏结尾被拦下。
+- 使用computer-use实际打开专业导出页,滚动到按钮、点击,确认“另存为”、`test_av_1080p-Veyra.mp4`及保存类型。取消后恢复界面,未发起导出。`logs/export-dialog-app-20260915.log`记录打开/取消。
+
+## 未完成项与下一步
+
+反馈者99%失败的原文件/导出参数/独立worker日志尚未取得;不能宣称该用户问题已根治。NR需用户对问题素材复测。此前HDR转SDR的固定峰值/色域裁切改善仍在待修范围,本轮没有把暗部残差保护当作HDR映射修复。
+
+HDR后续已查阅[ITU-R BT.2390-6](https://www.itu.int/dms_pub/itu-r/opb/rep/R-REP-BT.2390-6-2019-PDF-E.pdf)的EETF和YRGB方法及[BT.2446-1](https://www.itu.int/dms_pub/itu-r/opb/rep/R-REP-BT.2446-1-2021-PDF-E.pdf)。下一条实现任务是以独立标准参照替换粗糙HDR转SDR曲线及逐通道裁切,解析静态峰值、保留原生HDR不变并加入彩色测试;不能以“缺问题片源”为由永久搁置已知算法缺口。原生杜比视界、XeSS SDK内部精确计时及未到手硬件验收仍不冒充完成。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 0ce5ccae..9b053029 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2241,3 +2241,13 @@ WASAPI输入使用共享模式事件采集,按 `IAudioCaptureClient::GetBuffer
最终delivery.ps1 exit0,logs/delivery/1987bb07e103441591d6dacf2e632cac/result.json,实际NR/NVOF、4K和GUI/导出相关检查通过;capture awaiting仍保留。候选hash 00DD5FD72B1849006F86041723B150E9EDF3D19575DFBCC5B0E47CE2BF86AD8E,入口out/start-user-issues-candidate.cmd。XeSS旧版历史9057d2f/83f90ba面板也显式不可测;当前SDK状态字段无内部耗时,用户对应旧截图/版本未知,未伪造计时。
本地按显式源文件清单提交,全屏前轮代码/审计文档一并存档;运行库、SDK、配置、日志/fixture不入Git,未push/发布。DirectShow实卡音频热恢复、非NVIDIA实机、40系/OBS/PS5原问题均未因此视为实机通过;原生DV与XeSS内部计时仍未实现,HDR转SDR没有无证据改曲线。下一步为候选问题设备复测及其原始证据定位。
+
+## 2026-09-15 拖动实时预览、NR强度暗部与导出收尾
+
+用户要求拖动途中出画面、检查NR全部参数及强度2暗部、调查导出99%失败和不弹保存窗口。实现及逐文件/测试细节见 `docs/SCRUB_NR_EXPORT_REPAIR_2026-09-15.md`。新增SeekPreview在UI保留单在途+最新目标,拖动临时暂停运输、显示每次已完成预览,释放优先精确定位并恢复先前播放状态。NR残差外推可能负值截黑,新增暗部切线连续正值延伸,不改输入/输出transfer和默认NR端点。旧参数测试未显式开启NR的漏洞已修,18组72次实际Evaluate;肤质/UI修正仍未证实。
+
+VideoExportJob修正视频包失败仍计数、检查关闭刷新、细分编码尾帧/MP4索引/验证/改名失败;验证报告帧号/PTS/源错误,长验证显示已检查帧数。ExportJobManager识别细分收尾进度。导出按钮不再因failed静默返回,使用独立worker已应用设置;其他拒绝和系统保存弹窗错误明确提示。既有文件/partial保留,不弱化帧数/时间戳/EOS验证。
+
+实际构建脚本scrub-nr-export-build系列exit0;shader45秒上限exit0、真实NR参数120秒上限exit0、最终GUI24秒/55秒上限exit0;前两次GUI测试失败及修正原因保留在对应文档。真实3600帧文件锁测试export-lock-final在全部解码通过后得到Windows32,并正确报告保存失败;export-corrupt-output破坏尾包后正确拒绝成功,两项各120秒上限exit0。computer-use实际点击导出按钮,观察另存为窗口及默认名字,取消未导出。
+
+完整 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915` exit0:`logs/delivery/582eaf50540a4f2f82abf2b7b82b3cfc/result.json`。实际NR/NVOF、原生4K、GUI/图片、H264/HEVC4K2X导出/音轨/取消通过,采集待实卡。候选EXE SHA256 `E0FE742B3EC7B83BEA18390EA7E61472D5CBB925F8DC0A6809F925EE92DB86E9`,入口保持 `out/start-user-issues-candidate.cmd`。未改运行组件、SDK、版本或发布。反馈者99%根因尚缺原文件/日志,不能拿注入文件锁替代真实复现。后续继续独立的HDR转SDR曲线/色域修复。
diff --git a/shaders/NrResidualComposite.hlsl b/shaders/NrResidualComposite.hlsl
index 7610bfc2..ac477911 100644
--- a/shaders/NrResidualComposite.hlsl
+++ b/shaders/NrResidualComposite.hlsl
@@ -3,6 +3,18 @@ Texture2D<float4> nrInput:register(t1);
Texture2D<float4> nrFinal:register(t2);
RWTexture2D<float4> outputTex:register(u0);
cbuffer Params:register(b0){float total;float darken;float brighten;float color;float luminance;float protectionEnabled;float featherPixels;float unused;float4 regions[4];}
+// Extrapolating a negative linear-light residual can cross zero even when
+// both input images contain shadow detail. Continue below the unboosted
+// endpoint with a positive, tangent-matched curve instead of hard clipping.
+// Identity and 0..1 mixing remain exact. Signed HDR gamut components remain
+// signed; this is a residual-strength safeguard, not an input/output gamma.
+float shadowSafe(float base,float rawDelta,float requestedDelta){
+ float anchorDelta=min(rawDelta,0.0);
+ float anchor=base+anchorDelta;
+ if(base>=0&&anchor>0&&requestedDelta<anchorDelta)
+ return anchor/(1.0+(anchorDelta-requestedDelta)/anchor);
+ return base+requestedDelta;
+}
// Bilateral resampling of the change uses the preserved high-resolution base
// as the edge guide. It never interpolates the high-resolution base itself.
[numthreads(16,16,1)] void main(uint3 id:SV_DispatchThreadID){
@@ -29,8 +41,12 @@ cbuffer Params:register(b0){float total;float darken;float brighten;float color;
delta+=(nrFinal[q].rgb-low)*weight;weights+=weight;
}
delta/=max(weights,1e-6);
+ float3 rawDelta=delta;
if(darken!=1||brighten!=1)delta=min(delta,0)*darken+max(delta,0)*brighten;
if(color!=1||luminance!=1){float dy=dot(delta,float3(0.2126,0.7152,0.0722));delta=dy*luminance+(delta-dy)*color;}
- float3 result=base.rgb+total*(1-protection)*delta;
+ delta*=total*(1-protection);
+ float3 result=float3(shadowSafe(base.r,rawDelta.r,delta.r),
+ shadowSafe(base.g,rawDelta.g,delta.g),
+ shadowSafe(base.b,rawDelta.b,delta.b));
outputTex[id.xy]=float4(unused>0.5?result:max(0,result),base.a);
}
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index 93fc8c44..cfed14b9 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -85,7 +85,7 @@ int runExportWorker(HANDLE mapping){
return !cancel;
};
bool ok=false;try{ok=exportVideo(s->input,s->output,PlayerOptions::from(settings),s->hevc!=0,cancel,[&](double p,const std::wstring& message){if(InterlockedCompareExchange(&s->messageLock,1,0)==0){wcsncpy_s(s->message,message.c_str(),_TRUNCATE);InterlockedExchange(&s->messageLock,0);}
-InterlockedExchange(&s->progress,LONG(std::clamp(p,0.0,.999)*10000));if(message==L"正在封装和验证输出")InterlockedExchange(&s->state,LONG(ExportState::Finishing));},s->maxFrames,frameBoundary,[&](const ExportCounts& count){InterlockedExchange64(&s->sourceFrames,count.source);InterlockedExchange64(&s->generated,count.generated);InterlockedExchange64(&s->holds,count.holds);InterlockedExchange64(&s->encoded,count.encoded);});}catch(...){log::error("export-worker","unhandled job exception");}
+InterlockedExchange(&s->progress,LONG(std::clamp(p,0.0,.999)*10000));if(p>=.99)InterlockedExchange(&s->state,LONG(ExportState::Finishing));},s->maxFrames,frameBoundary,[&](const ExportCounts& count){InterlockedExchange64(&s->sourceFrames,count.source);InterlockedExchange64(&s->generated,count.generated);InterlockedExchange64(&s->holds,count.holds);InterlockedExchange64(&s->encoded,count.encoded);});}catch(...){log::error("export-worker","unhandled job exception");}
done=true;monitor.join();InterlockedExchange(&s->state,LONG(ok?ExportState::Succeeded:cancel?ExportState::Cancelled:ExportState::Failed));UnmapViewOfFile(s);CloseHandle(mapping);return ok?0:cancel?3:1;
}
}
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 79c797b8..ec3975eb 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -31,6 +31,12 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
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;
std::wstring failureReason;
+ auto failAv=[&](const wchar_t* stage,int code){
+ char error[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(code,error,sizeof(error));
+ failureReason=std::format(L"{}失败(错误 {})",stage,code);
+ veyra::log::error("export",std::format("stage={} code={} detail={}",utf8(stage),code,error));
+ return false;
+ };
bool hdrExport=false;
uint32_t outputWidth=0,outputHeight=0;AVRational outputRate{};
const auto partial=output+L".partial";
@@ -88,16 +94,19 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
const auto tb=audioInput->streams[audioIndex]->time_base;const int64_t ts=audioPacket->pts!=AV_NOPTS_VALUE?audioPacket->pts:audioPacket->dts;const double time=ts==AV_NOPTS_VALUE?0:ts*av_q2d(tb)-videoOriginSeconds;if(time>seconds)return true;
const int64_t origin=av_rescale_q(static_cast<int64_t>(videoOriginSeconds*1000000),{1,1000000},tb);
if(audioPacket->pts!=AV_NOPTS_VALUE)audioPacket->pts-=origin;if(audioPacket->dts!=AV_NOPTS_VALUE)audioPacket->dts-=origin;
- av_packet_rescale_ts(audioPacket,tb,audioStream->time_base);audioPacket->stream_index=audioStream->index;audioPacket->pos=-1;audioPending=false;if(av_interleaved_write_frame(mux,audioPacket)<0)return false;
+ av_packet_rescale_ts(audioPacket,tb,audioStream->time_base);audioPacket->stream_index=audioStream->index;audioPacket->pos=-1;audioPending=false;const int rc=av_interleaved_write_frame(mux,audioPacket);if(rc<0)return failAv(L"写入音轨",rc);
}};
auto writer=[&](const uint8_t* bytes,size_t size,int64_t pts,bool key){if(!headerWritten)return false;
AVPacket* pkt=av_packet_alloc();if(!pkt)return false;if(av_new_packet(pkt,int(size))<0){av_packet_free(&pkt);return false;}memcpy(pkt->data,bytes,size);pkt->stream_index=videoStream->index;pkt->pts=pkt->dts=pts;pkt->duration=1;if(key)pkt->flags|=AV_PKT_FLAG_KEY;
- av_packet_rescale_ts(pkt,{rate.den,rate.num},videoStream->time_base);const bool good=av_interleaved_write_frame(mux,pkt)>=0;av_packet_free(&pkt);++written;audioEndSeconds=(pts+1)*double(rate.den)/rate.num;return good&&writeAudioUntil(audioEndSeconds);};
+ av_packet_rescale_ts(pkt,{rate.den,rate.num},videoStream->time_base);const int rc=av_interleaved_write_frame(mux,pkt);av_packet_free(&pkt);if(rc<0)return failAv(L"写入视频帧",rc);++written;audioEndSeconds=(pts+1)*double(rate.den)/rate.num;return writeAudioUntil(audioEndSeconds);};
// Must drain before rate/writeAudioUntil/writer leave scope, including cancel/error.
struct EncoderCloser {sink::NvencD3D12Encoder& encoder;~EncoderCloser(){encoder.close();}} closer{enc};
if(!enc.open(ctx,ring,graph,hevc,rate.num,rate.den,writer))break;
auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());
- if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;
+ int muxResult=avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE);
+ if(muxResult<0){failAv(L"创建输出文件",muxResult);break;}
+ muxResult=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;
while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;
source::SourceReadStatus rs;
@@ -136,35 +145,51 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
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));
- if(!enc.finish()||!writeAudioUntil(audioEndSeconds)||av_write_trailer(mux)<0)break;
+ progress(.99,L"正在收尾:等待编码器输出剩余帧");
+ if(!enc.finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看NVENC诊断";break;}
+ if(!writeAudioUntil(audioEndSeconds))break;
+ progress(.995,L"正在收尾:写入MP4索引");
+ muxResult=av_write_trailer(mux);
+ if(muxResult<0){failAv(L"写入MP4索引",muxResult);break;}
ok=written>0;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});
- }while(false); }catch(const std::exception&){progress(0,L"导出异常,已保留partial,请查看诊断");ok=false;}
- enc.close();if(mux){if(mux->pb)avio_closep(&mux->pb);avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);
+ }while(false); }catch(const std::exception& e){veyra::log::error("export",std::format("exception: {}",e.what()));failureReason=L"导出异常,请查看诊断";ok=false;}
+ enc.close();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);
ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();
if(ok){
progress(.999,L"正在封装和验证输出");
source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;
ok=!cancel&&check.open(od);
+ if(!ok&&!cancel){failureReason=L"无法重新打开输出验证:"+check.errorMessage();veyra::log::error("export-verify",utf8(failureReason));}
const auto info=check.info();
CfrTimeline verifiedTimeline(outputRate.num,outputRate.den,info.timestampQuantum,0);
- ok=ok&&info.width==outputWidth&&info.height==outputHeight&&verifiedTimeline.valid();
+ const bool headerValid=info.width==outputWidth&&info.height==outputHeight&&verifiedTimeline.valid();
+ if(ok&&!headerValid)veyra::log::error("export-verify",std::format("header actual={}x{} expected={}x{} rate={}/{} quantum={}",info.width,info.height,outputWidth,outputHeight,outputRate.num,outputRate.den,info.timestampQuantum));
+ ok=ok&&headerValid;
uint64_t decoded=0;bool reachedEos=false;
while(ok&&!cancel){
pipeline::FramePacket pkt;const AVFrame* frame=nullptr;const auto rs=check.read(pkt,&frame);
if(rs==source::SourceReadStatus::Eos){reachedEos=true;break;}
- if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()||decoded>=uint64_t(written)||!verifiedTimeline.accepts(decoded,pkt.pts.toDouble())){ok=false;break;}
+ if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()||decoded>=uint64_t(written)||!verifiedTimeline.accepts(decoded,pkt.pts.toDouble())){
+ veyra::log::error("export-verify",std::format("frame={} status={} pts={} expectedPts={} written={} decoder={}",decoded,int(rs),pkt.pts.toDouble(),verifiedTimeline.expected(decoded),written,utf8(check.errorMessage())));
+ ok=false;break;
+ }
if(hdrExport){
const auto* format=av_pix_fmt_desc_get(static_cast<AVPixelFormat>(frame->format));
if(!format||format->comp[0].depth<10||pkt.colorInfo.transfer!=pipeline::TransferFunction::PQ||
pkt.colorInfo.primaries!=pipeline::ColorPrimaries::BT2020||pkt.colorInfo.matrix!=pipeline::YuvMatrix::BT2020NCL){ok=false;break;}
}
++decoded;
+ if(decoded%120==0)progress(.999,std::format(L"正在逐帧验证:{} / {} 帧",decoded,written));
}
ok=ok&&!cancel&&reachedEos&&decoded==uint64_t(written);
veyra::log::info("export-verify",std::format("decoded={} expected={} eof={} cancelled={} passed={}",decoded,written,reachedEos,bool(cancel),ok));
check.close();
- if(!ok&&!cancel)failureReason=L"输出完整性验证失败,未生成正式文件";
- if(ok)ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
+ if(!ok&&!cancel&&failureReason.empty())failureReason=std::format(L"输出验证未通过(解码 {} / {} 帧),详见export-verify日志",decoded,written);
+ if(ok){
+ progress(.999,L"验证通过,正在保存正式文件");
+ ok=!cancel&&MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;
+ if(!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"视频导出完成,逐帧完整性验证通过");
else {
diff --git a/tests/integration/FileSafetyTests.cpp b/tests/integration/FileSafetyTests.cpp
index b96311f7..ffca0047 100644
--- a/tests/integration/FileSafetyTests.cpp
+++ b/tests/integration/FileSafetyTests.cpp
@@ -106,18 +106,24 @@ bool corruptLastVideoPacket(const std::filesystem::path& file){
}
void exportFaultTest(const std::wstring& path,const std::wstring& output,const std::wstring& mode){
- std::atomic<bool> cancel=false;bool injected=false;std::wstring finalMessage;
+ std::atomic<bool> cancel=false;bool injected=false;std::wstring finalMessage;HANDLE outputLock=INVALID_HANDLE_VALUE;
engine::PlayerOptions options;options.nr=options.sr=options.fg=false;unsigned boundaries=0;
const bool ok=engine::exportVideo(path,output,options,false,cancel,[&](double progress,const std::wstring& message){
finalMessage=message;
- if(progress==.999){
+ if(!injected&&progress==.999){
if(mode==L"export-corrupt-output"){injected=corruptLastVideoPacket(output+L".partial");check(injected,"damaged final encoded packet before integrity check");}
else if(mode==L"export-cancel-verify"){cancel=true;injected=true;}
+ else if(mode==L"export-lock-final"){
+ outputLock=CreateFileW((output+L".partial").c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,0,nullptr);
+ injected=outputLock!=INVALID_HANDLE_VALUE;
+ }
}
},0,[&]{if(mode==L"export-abort-boundary"&&++boundaries>10){injected=true;return false;}return true;});
+ if(outputLock!=INVALID_HANDLE_VALUE)CloseHandle(outputLock);
check(injected&&!ok,"injected failure/cancellation cannot report success");
check(!std::filesystem::exists(output)&&std::filesystem::exists(output+L".partial"),"failed output stays partial, never promoted");
check(finalMessage.find(L"完成")==std::wstring::npos,"completion message does not claim success");
+ if(mode==L"export-lock-final")check(finalMessage.find(L"验证已通过")!=std::wstring::npos&&finalMessage.find(L"Windows错误 32")!=std::wstring::npos,"valid video with rename lock reports saving failure, not corrupt media");
}
void exportWorkerTest(const std::wstring& path,const std::wstring& output){
diff --git a/tests/integration/RepairParameterTests.cpp b/tests/integration/RepairParameterTests.cpp
index e5135f68..cc174a76 100644
--- a/tests/integration/RepairParameterTests.cpp
+++ b/tests/integration/RepairParameterTests.cpp
@@ -12,8 +12,10 @@ extern "C" {
int main(){using namespace veyra;CoInitializeEx(nullptr,COINIT_MULTITHREADED);gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;pipeline::EnhanceGraph graph(ctx,ring);Status st;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;bool ok=ctx.initialize(dd,st)&&ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=1920;gd.sourceHeight=gd.workHeight=1080;gd.enableNr=true;gd.enableFg=false;gd.enableSr=false;gd.enableNvofStandalone=true;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();ok=ok&&graph.initialize(gd)&&graph.createViews();
AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=1920;f->height=1080;f->color_range=AVCOL_RANGE_JPEG;ok=ok&&av_frame_get_buffer(f,32)>=0;
for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;float noise=float((x*73+y*91)%31)-15;bool face=(x-960)*(x-960)/2+(y-540)*(y-540)<200*200;float base=95+45*std::sin(x*.02f)*std::cos(y*.026f)+noise;p[0]=uint8_t(std::clamp(base+(face?55:0),0.f,255.f));p[1]=uint8_t(std::clamp(base+(face?15:0),0.f,255.f));p[2]=uint8_t(std::clamp(base-(face?10:0),0.f,255.f));p[3]=255;}
-sink::RgbaImage baseline;unsigned ordinal=0;const char* names[]={"baseline","intensity","localTone","localStructure","skin-experimental","style-experimental","autoMask-experimental","UI-experimental","residual-total-zero"};
-for(unsigned mode=0;ok&&mode<9;++mode){engine::EnhancementSettings s;s.revision=mode+1;s.multiplier=1;if(mode==1)s.model.intensity=0;if(mode==2)s.model.tone=0;if(mode==3)s.model.structure=0;if(mode==4)s.model.skin=1.5f;if(mode==5)s.model.style=1;if(mode==6)s.model.autoMask=1;if(mode==7)s.model.uiCorrection=1;if(mode==8)s.residual.total=0;ok=graph.applySettings(s);sink::RgbaImage result;
+sink::RgbaImage baseline;unsigned ordinal=0;const char* names[]={"baseline","intensity","localTone","localStructure","skin-experimental","style-experimental","autoMask-experimental","UI-experimental","residual-total-zero","total-two","darken-zero","darken-two","brighten-zero","brighten-two","color-zero","color-two","luminance-zero","luminance-two"};
+for(unsigned mode=0;ok&&mode<std::size(names);++mode){engine::EnhancementSettings s;s.nr=true;s.revision=mode+1;s.multiplier=1;if(mode==1)s.model.intensity=0;if(mode==2)s.model.tone=0;if(mode==3)s.model.structure=0;if(mode==4)s.model.skin=1.5f;if(mode==5)s.model.style=1;if(mode==6)s.model.autoMask=1;if(mode==7)s.model.uiCorrection=1;if(mode==8)s.residual.total=0;if(mode==9)s.residual.total=2;if(mode==10)s.residual.darken=0;if(mode==11)s.residual.darken=2;if(mode==12)s.residual.brighten=0;if(mode==13)s.residual.brighten=2;if(mode==14)s.residual.color=0;if(mode==15)s.residual.color=2;if(mode==16)s.residual.luminance=0;if(mode==17)s.residual.luminance=2;ok=graph.applySettings(s);sink::RgbaImage result;
for(int j=0;ok&&j<4;++j){pipeline::EnhanceGraph::FrameOutputs out;ok=graph.process(f,(ordinal++)*20.0,j==0,out);if(j==3&&ok)ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result);}
if(!ok)break;if(mode==0)baseline=result;double mae=0;uint64_t changed=0;for(size_t k=0;k<result.pixels.size();k+=4)for(int c=0;c<3;++c){int d=std::abs(int(result.pixels[k+c])-baseline.pixels[k+c]);mae+=d;changed+=d!=0;}mae/=result.width*result.height*3.0;std::cout<<"PARAM name="<<names[mode]<<" appliedRevision="<<s.revision<<" changedRGB="<<changed<<" meanAbs8bit="<<mae<<" effect="<<(changed?"observed-on-synthetic":"not-proven-on-synthetic")<<'\n';}
+const auto evaluates=graph.metrics().nrEvaluateCount;ok=ok&&evaluates==std::size(names)*4;
+std::cout<<"NR actual evaluations="<<evaluates<<" expected="<<std::size(names)*4<<" pass="<<ok<<std::endl;
ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;}
diff --git a/tests/integration/RepairShaderTests.cpp b/tests/integration/RepairShaderTests.cpp
index df21d0da..92629557 100644
--- a/tests/integration/RepairShaderTests.cpp
+++ b/tests/integration/RepairShaderTests.cpp
@@ -30,5 +30,45 @@ int main(){
float c[24]={strength,0.5f,1.5f,2,0,0,0,0};residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
readback->Map(0,&range,&data);values=static_cast<float*>(data);bool identity=true;for(int y=0;y<16;++y)for(int x=0;x<16;++x)identity=identity&&values[y*64+x*4]==(((x+y)%2)?0.75f:0.25f);readback->Unmap(0,&written);ok=ok&&identity;std::cout<<"zero residual strength="<<strength<<" base identity="<<identity<<std::endl;
}
+ auto neural=makeTexture(ctx.device(),8,8,DXGI_FORMAT_R32G32B32A32_FLOAT,true);
+ makeSrv(ctx.device(),neural.Get(),DXGI_FORMAT_R32G32B32A32_FLOAT,cpuHandleOf(residual,2));
+ auto fill=[&](ID3D12Resource* texture,unsigned width,unsigned height,float r,float g,float b){
+ upload->Map(0,nullptr,&data);auto* v=static_cast<float*>(data);
+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){auto at=y*64+x*4;v[at]=r;v[at+1]=g;v[at+2]=b;v[at+3]=1;}
+ upload->Unmap(0,nullptr);list=ring.acquireNext(slot,status);
+ states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_DEST);
+ dst.pResource=texture;src.PlacedFootprint.Footprint={DXGI_FORMAT_R32G32B32A32_FLOAT,width,height,1,256};
+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);states.transition(list,texture,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
+ return ring.submitAndSignal(slot)&&ring.waitIdle();
+ };
+ // Known positive source and NR shadows. Doubling the old residual made
+ // .10 + 2*(.04-.10) negative, destroying all of this patch's detail.
+ ok=ok&&fill(base.Get(),16,16,.10f,.10f,.10f)&&fill(low.Get(),8,8,.10f,.10f,.10f)&&fill(neural.Get(),8,8,.04f,.04f,.04f);
+ for(unsigned control=0;control<5;++control)for(float strength:{0.f,.5f,1.f,2.f}){
+ float c[24]={1,1,1,1,1,0,0,0};c[control]=strength;
+ list=ring.acquireNext(slot,status);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ residual.bind(list,c,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);
+ states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ readback->Map(0,&range,&data);values=static_cast<float*>(data);
+ bool valid=true;for(int y=0;y<16;++y)for(int x=0;x<16;++x)for(int channel=0;channel<3;++channel){
+ const float v=values[y*64+x*4+channel];valid&=std::isfinite(v)&&v>0&&v<=.10001f;
+ if(strength==1||control==2||control==3)valid&=std::abs(v-.04f)<1e-6f;
+ if(control==0&&strength<=1)valid&=std::abs(v-(.10f-.06f*strength))<1e-6f;
+ if((control==0||control==1||control==4)&&strength==2)valid&=v<.04f;
+ }
+ std::cout<<"shadow control="<<control<<" strength="<<strength<<" output="<<values[0]<<" valid="<<valid<<std::endl;
+ readback->Unmap(0,&written);ok&=valid;
+ }
+ // The HDR working space can legitimately contain negative RGB and >1
+ // highlights. Default residual settings must not clamp either boundary.
+ ok=ok&&fill(base.Get(),16,16,-.1f,2.f,.5f)&&fill(low.Get(),8,8,-.1f,2.f,.5f)&&fill(neural.Get(),8,8,-.2f,3.f,.75f);
+ list=ring.acquireNext(slot,status);states.transition(list,result.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ float hdr[24]={1,1,1,1,1,0,0,1};residual.bind(list,hdr,gpuHandleOf(residual,0).ptr,gpuHandleOf(residual,3).ptr);list->Dispatch(1,1,1);
+ states.uavBarrier(list,result.Get());states.transition(list,result.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);copy(result.Get(),16,16);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 2;
+ readback->Map(0,&range,&data);values=static_cast<float*>(data);
+ bool hdrIdentity=std::abs(values[0]+.2f)<1e-6f&&std::abs(values[1]-3.f)<1e-6f&&std::abs(values[2]-.75f)<1e-6f;
+ readback->Unmap(0,&written);ok&=hdrIdentity;std::cout<<"HDR signed endpoint preserved="<<hdrIdentity<<std::endl;
ring.drainQueue();return ok?0:1;
}