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++
Add manual NR protection regions with professional selection and presets
Veyra Goal Agent674c72651d71
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex ecdd138e..284bea87 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -33,7 +33,11 @@ const wchar_t* labels[]={L"模型强度",L"局部明暗",L"局部结构",L"肤void loadStore(){if(!loaded){store.load();loaded=true;}}void message(const std::wstring& text){putText(401,text.c_str());}bool submit(engine::EnhancementSettings s){if(!apply(s)){dirty=true;message(L"总增强正在切换;草稿保留,请稍后应用。");return false;}dirty=false;return true;}-void populate(engine::EnhancementSettings s){populating=true;float v[]={s.model.intensity,s.model.tone,s.model.structure,s.model.skin,float(s.model.style),float(s.model.autoMask),float(s.model.uiCorrection),s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance};for(int i=0;i<12;++i){std::wostringstream o;o<<std::setprecision(7)<<v[i];putText(100+i,o.str().c_str());send(600+i,TBM_SETPOS,TRUE,LPARAM(v[i]*(i>=4&&i<=6?1:100)));}check(200,s.nr?BST_CHECKED:BST_UNCHECKED);check(201,s.sr?BST_CHECKED:BST_UNCHECKED);send(202,CB_SETCURSEL,s.multiplier-1,0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);displayedRevision=s.revision;populating=false;dirty=false;}+void syncProtection(const engine::ProtectionSettings& protection){+ check(206,protection.enabled?BST_CHECKED:BST_UNCHECKED);unsigned count=0;for(auto q:protection.regions)count+=!q.empty();+ putText(206,(L"NR保护区域 · "+std::to_wstring(count)+L"/4").c_str());+}+void populate(engine::EnhancementSettings s){populating=true;float v[]={s.model.intensity,s.model.tone,s.model.structure,s.model.skin,float(s.model.style),float(s.model.autoMask),float(s.model.uiCorrection),s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance};for(int i=0;i<12;++i){std::wostringstream o;o<<std::setprecision(7)<<v[i];putText(100+i,o.str().c_str());send(600+i,TBM_SETPOS,TRUE,LPARAM(v[i]*(i>=4&&i<=6?1:100)));}syncProtection(s.protection);check(200,s.nr?BST_CHECKED:BST_UNCHECKED);check(201,s.sr?BST_CHECKED:BST_UNCHECKED);send(202,CB_SETCURSEL,s.multiplier-1,0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);displayedRevision=s.revision;populating=false;dirty=false;}bool read(engine::EnhancementSettings& s){s=enhancementEnabled?controller->snapshot().desired:configuredSettings;float v[12]{};for(int i=0;i<12;++i){wchar_t b[64]{};GetWindowTextW(item(100+i),b,64);wchar_t* end=nullptr;v[i]=wcstof(b,&end);if(end==b||*end||!std::isfinite(v[i])){message(L"请输入完整的有限数值;未提交设置");return false;}}for(int i=4;i<7;++i)if(v[i]!=std::floor(v[i])||v[i]<0||v[i]>(i==4?2:1)){message(L"风格/遮罩/UI修正必须为整数");return false;}s.model={v[0],v[1],v[2],v[3],int(v[4]),int(v[5]),int(v[6])};s.residual={v[7],v[8],v[9],v[10],v[11]};if(enhancementEnabled){s.nr=checked(200)==BST_CHECKED;s.sr=checked(201)==BST_CHECKED;}s.multiplier=uint32_t(send(202,CB_GETCURSEL,0,0)+1);s.nrPolicy=static_cast<pipeline::NrSizePolicy>(send(203,CB_GETCURSEL,0,0));s.flow=static_cast<engine::FlowQuality>(send(204,CB_GETCURSEL,0,0));s.content=static_cast<engine::ContentRate>(send(205,CB_GETCURSEL,0,0));if(!s.validate().empty()){message(L"参数越界,未提交。悬停数值框查看允许范围。");return false;}return true;}@@ -82,6 +86,10 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();add(L"BUTTON",L"优先观看 · 降低导出占用",505,BS_AUTOCHECKBOX|WS_TABSTOP,3,12,406,-1,36);check(505,BST_CHECKED);add(L"STATIC",L"",506,0,3,12,458,-1,120);add(L"STATIC",L"",507,0,3,12,588,-1,80);add(L"STATIC",L"",400,0,-1,12,900,-1,92);add(L"STATIC",L"",401,0,-1,12,996,-1,86);+ for(auto& entry:items)if(entry.page==0&&entry.y>=146)entry.y+=176;+ add(L"BUTTON",L"NR保护区域",206,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,146,-1,36);+ button(L"框选区域",213,0,12,188,140);button(L"清除区域",214,0,162,188);+ add(L"STATIC",L"最多4区,左键拖框,Esc取消。仅抑制NR变化;不保护SR或补帧。可随预设保存;换源清空。",1109,0,0,12,232,-1,82);loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);arrange();return 0;}case WM_SIZE:arrange();return 0;case WM_ERASEBKGND:return 1;@@ -89,7 +97,7 @@ case WM_PAINT:{PaintBuffer paint(h);fillSurface(paint.dc,paint.rect,h);return 0;case WM_VSCROLL:{switch(LOWORD(wp)){case SB_LINEUP:scroll-=40;break;case SB_LINEDOWN:scroll+=40;break;case SB_PAGEUP:scroll-=240;break;case SB_PAGEDOWN:scroll+=240;break;case SB_THUMBTRACK:{SCROLLINFO si{sizeof(si),SIF_TRACKPOS};GetScrollInfo(h,SB_VERT,&si);scroll=si.nTrackPos;break;}}arrange();return 0;}case WM_MOUSEWHEEL:scroll-=GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA*90;arrange();return 0;case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);-case WM_COMMAND:{const int id=LOWORD(wp);if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){KillTimer(h,2);const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。数值草稿保持。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h))-88;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange();break;}}if(!populating&&(HIWORD(wp)==EN_CHANGE&&id>=100&&id<=111||HIWORD(wp)==CBN_SELCHANGE&&id>=202&&id<=205)){dirty=true;message(L"参数草稿尚未应用。无效草稿保留;切换面板不会提交。");}+case WM_COMMAND:{const int id=LOWORD(wp);if((id==206||id==213||id==214)&&HIWORD(wp)==BN_CLICKED){KillTimer(h,2);const auto accepted=SendMessageW(GetParent(h),WM_APP+45,id,checked(206));message(accepted?(id==213?L"请在画面中左键拖动框选;Esc取消。":L"已请求更新NR保护区域;其他草稿保留。"):L"未能操作:请先打开画面,或清除已满的4个区域。");return 0;}if((id==200||id==201)&&HIWORD(wp)==BN_CLICKED){KillTimer(h,2);const bool accepted=SendMessageW(GetParent(h),WM_APP+44,id,checked(id))!=0;message(accepted?L"已请求开关;确认帧边界结果后生效。数值草稿保持。":L"总增强正在切换,请待当前事务完成。");return 0;}if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h))-88;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange();break;}}if(!populating&&(HIWORD(wp)==EN_CHANGE&&id>=100&&id<=111||HIWORD(wp)==CBN_SELCHANGE&&id>=202&&id<=205)){dirty=true;message(L"参数草稿尚未应用。无效草稿保留;切换面板不会提交。");}engine::EnhancementSettings s;wchar_t name[128]{};GetWindowTextW(item(301),name,128);const auto index=size_t(send(300,CB_GETCURSEL,0,0));bool ok=true;if(id==210||id==212){KillTimer(h,2);if(read(s)&&submit(s)){message(L"设置已请求;在真实帧边界确认已应用后生效");}}else if(id==211){s={};if(submit(s)){populate(s);message(L"已请求恢复内建默认;用户预设保留");}}@@ -102,7 +110,7 @@ case WM_COMMAND:{const int id=LOWORD(wp);if((id==200||id==201)&&HIWORD(wp)==BN_Celse if(id>=501&&id<=505)SendMessageW(GetParent(h),WM_APP+41,id,id==501?send(500,CB_GETCURSEL,0,0):id==505?checked(505):0);if(!ok)message(store.error());return 0;}case WM_HSCROLL:{int id=GetDlgCtrlID(reinterpret_cast<HWND>(lp));if(id>=600&&id<612){int index=id-600;float v=float(SendMessageW(reinterpret_cast<HWND>(lp),TBM_GETPOS,0,0))/(index>=4&&index<=6?1:100);if(index==3&&v<0)v=-1;std::wostringstream o;o<<std::setprecision(4)<<v;putText(100+index,o.str().c_str());SetTimer(h,2,120,nullptr);}return 0;}-case WM_TIMER:{if(wp==2){KillTimer(h,2);engine::EnhancementSettings setting;if(read(setting)&&submit(setting)){message(enhancementEnabled?L"已请求参数;帧边界确认生效":L"增强关闭中:已保存待启用参数");}return 0;}auto s=controller->snapshot();if(enhancementEnabled&&!dirty&&displayedRevision!=s.desired.revision)populate(s.desired);check(200,enhancementEnabled&&s.desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.desired.sr?BST_CHECKED:BST_UNCHECKED);std::wostringstream o;if(!s.running&&!s.frames&&s.transport!=engine::TransportState::Opening)o<<L"未打开媒体 · 设置待启用\n";else o<<L"期望版本 "<<s.desired.revision<<L" / 已应用 "<<s.applied.revision<<(s.applying?L" · 应用中":L"")<<L"\n强度 "<<s.applied.model.intensity<<L" · 变化量 "<<s.applied.residual.total<<L" · 倍率 "<<s.applied.multiplier<<L"X";setText(item(400),o.str());return 0;}+case WM_TIMER:{if(wp==2){KillTimer(h,2);engine::EnhancementSettings setting;if(read(setting)&&submit(setting)){message(enhancementEnabled?L"已请求参数;帧边界确认生效":L"增强关闭中:已保存待启用参数");}return 0;}auto s=controller->snapshot();syncProtection(enhancementEnabled?s.desired.protection:configuredSettings.protection);if(enhancementEnabled&&!dirty&&displayedRevision!=s.desired.revision)populate(s.desired);check(200,enhancementEnabled&&s.desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enhancementEnabled&&s.desired.sr?BST_CHECKED:BST_UNCHECKED);std::wostringstream o;if(!s.running&&!s.frames&&s.transport!=engine::TransportState::Opening)o<<L"未打开媒体 · 设置待启用\n";else o<<L"期望版本 "<<s.desired.revision<<L" / 已应用 "<<s.applied.revision<<(s.applying?L" · 应用中":L"")<<L"\n强度 "<<s.applied.model.intensity<<L" · 变化量 "<<s.applied.residual.total<<L" · 倍率 "<<s.applied.multiplier<<L"X";setText(item(400),o.str());return 0;}case WM_DESTROY:KillTimer(h,1);KillTimer(h,2);DeleteObject(font);window=nullptr;body=nullptr;items.clear();return 0;}return DefWindowProcW(h,msg,wp,lp);}}@@ -113,7 +121,7 @@ bool presetAt(size_t index,engine::EnhancementSettings& out){loadStore();if(indeHWND createSettingsPanel(HWND parent,engine::EngineController& engine,std::function<bool(engine::EnhancementSettings)> callback){controller=&engine;apply=std::move(callback);WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraInspector";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);return CreateWindowExW(WS_EX_CONTROLPARENT,wc.lpszClassName,L"专业参数",WS_CHILD|WS_CLIPCHILDREN,0,0,328,500,parent,nullptr,wc.hInstance,nullptr);}void settingsVisibility(bool visible){if(window&&!visible)KillTimer(window,2);}void settingsPage(int value){if(window)KillTimer(window,2);page=std::clamp(value,0,3);scroll=0;arrange();}-void settingsEnabled(bool enabled,const engine::EnhancementSettings& configured){enhancementEnabled=enabled;configuredSettings=configured;if(window&&!enabled&&!dirty&&displayedRevision!=configured.revision)populate(configured);if(window){auto desired=controller->snapshot().desired;check(200,enabled&&desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enabled&&desired.sr?BST_CHECKED:BST_UNCHECKED);if(!enabled)message(L"增强已关闭。数值修改保存待启用配置;点击 NR / 超分可直接开启。");}}+void settingsEnabled(bool enabled,const engine::EnhancementSettings& configured){enhancementEnabled=enabled;configuredSettings=configured;if(window)syncProtection(enabled?controller->snapshot().desired.protection:configured.protection);if(window&&!enabled&&!dirty&&displayedRevision!=configured.revision)populate(configured);if(window){auto desired=controller->snapshot().desired;check(200,enabled&&desired.nr?BST_CHECKED:BST_UNCHECKED);check(201,enabled&&desired.sr?BST_CHECKED:BST_UNCHECKED);if(!enabled)message(L"增强已关闭。数值修改保存待启用配置;点击 NR / 超分可直接开启。");}}void settingsDpi(){if(!window)return;auto old=font;font=makeFont(window);for(auto& item:items)SendMessageW(item.h,WM_SETFONT,WPARAM(font),TRUE);DeleteObject(old);arrange();}void exportPanelStatus(const engine::ExportJobSnapshot& job,bool canExport,bool canSave){if(!window)return;setText(item(506),job.state==engine::ExportState::Idle?L"尚无导出任务":job.message+L"\n"+std::to_wstring(int(job.progress*100))+L"% · 源帧 "+std::to_wstring(job.sourceFrames)+L" / 编码 "+std::to_wstring(job.encoded)+L"\n生成 "+std::to_wstring(job.generated)+L" / CFR占位 "+std::to_wstring(job.holds)+L"\n作业 "+std::to_wstring(job.jobId)+L" · 冻结版本 "+std::to_wstring(job.frozenRevision));setText(item(507),job.output.empty()?L"目标由保存窗口选择":L"输出:"+std::filesystem::path(job.output).filename().wstring());EnableWindow(item(501),canExport&&!job.active());EnableWindow(item(502),canSave);EnableWindow(item(503),job.state==engine::ExportState::Running||job.state==engine::ExportState::Paused);EnableWindow(item(504),job.active());}}diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex ff86538b..e87cdad0 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -8,6 +8,7 @@#include "UiPreferenceStore.h"#include "CapturePanel.h"#include "SubtitleOverlay.h"+#include "ProtectionOverlay.h"#include "veyra/engine/ExportJobManager.h"#include <future>#include <psapi.h>@@ -65,8 +66,30 @@ void openFile(const std::wstring&);void layout();void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}void toggleFullscreen(){endTransition();full=!full;DWORD corner=full?1:2;DwmSetWindowAttribute(mainWindow,33,&corner,sizeof(corner));fullControls=true;pointerTick=GetTickCount64();if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromWindow(mainWindow,MONITOR_DEFAULTTONEAREST),&mi);SetWindowPos(mainWindow,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_FRAMECHANGED);}else{SetWindowLongPtrW(mainWindow,GWL_STYLE,ShellStyle|WS_VISIBLE);MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&windowPlacement.rcNormalPosition,MONITOR_DEFAULTTONEAREST),&mi);auto& r=windowPlacement.rcNormalPosition;if(r.right<mi.rcWork.left||r.left>mi.rcWork.right||r.bottom<mi.rcWork.top||r.top>mi.rcWork.bottom){OffsetRect(&r,mi.rcWork.left-r.left,mi.rcWork.top-r.top);}SetWindowPlacement(mainWindow,&windowPlacement);SetWindowPos(mainWindow,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);}SetWindowTextW(GetDlgItem(mainWindow,Fullscreen),full?L"退出全屏":L"全屏 F11");SetCursor(LoadCursorW(nullptr,IDC_ARROW));layout();veyra::log::info("ui-fullscreen",std::format("enabled={} video-only viewport; transport auto-hides",full));}+bool smokeProtection=false;int protectionStep=0;uint64_t protectionSession=0;bool protectionOverlayShown=false;+bool protectionArmed=false,protectionDragging=false;POINT protectionStart{};std::pair<float,float> protectionSourceStart;HWND protectionOverlay=nullptr;+void cancelProtection(){protectionArmed=protectionDragging=false;if(protectionOverlay)ShowWindow(protectionOverlay,SW_HIDE);if(video&&GetCapture()==video)ReleaseCapture();}+std::pair<float,float> protectionPoint(HWND h,POINT p){RECT r{};GetClientRect(h,&r);auto e=engine.snapshot().metrics.resolution.output;return engine.previewView().sourcePoint(float(p.x),float(p.y),float(r.right),float(r.bottom),float(e.width),float(e.height));}LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_PTR){static POINT panPoint{};static bool panning=false;+ if(id==VideoSurface&&protectionArmed){+ if(m==WM_SETCURSOR){SetCursor(LoadCursorW(nullptr,IDC_CROSS));return TRUE;}+ if(m==WM_KEYDOWN&&w==VK_ESCAPE){cancelProtection();return 0;}+ if(m==WM_LBUTTONDOWN){POINT p{GET_X_LPARAM(l),GET_Y_LPARAM(l)};auto uv=protectionPoint(h,p);if(uv.first<0||uv.first>1||uv.second<0||uv.second>1)return 0;+ protectionStart=p;protectionSourceStart=uv;protectionDragging=true;SetFocus(h);SetCapture(h);return 0;}+ if(m==WM_MOUSEMOVE&&protectionDragging){POINT p{GET_X_LPARAM(l),GET_Y_LPARAM(l)};+ if(!protectionOverlay)protectionOverlay=veyra::ui::createSubtitleOverlay(h);+ veyra::ui::protectionOutline(protectionOverlay,h,{std::min(p.x,protectionStart.x),std::min(p.y,protectionStart.y),std::max(p.x,protectionStart.x),std::max(p.y,protectionStart.y)});return 0;}+ if(m==WM_LBUTTONUP&&protectionDragging){POINT p{GET_X_LPARAM(l),GET_Y_LPARAM(l)};auto uv=protectionPoint(h,p);uv.first=std::clamp(uv.first,0.0f,1.0f);uv.second=std::clamp(uv.second,0.0f,1.0f);+ auto settings=uiState.enhanced?engine.snapshot().desired:uiState.configured;bool accepted=false;+ if(std::abs(p.x-protectionStart.x)>=3&&std::abs(p.y-protectionStart.y)>=3)for(auto& q:settings.protection.regions)if(q.empty()){+ q={std::min(uv.first,protectionSourceStart.first),std::min(uv.second,protectionSourceStart.second),std::max(uv.first,protectionSourceStart.first),std::max(uv.second,protectionSourceStart.second)};+ settings.protection.enabled=true;accepted=applySettings(settings);break;}+ cancelProtection();veyra::log::info("ui-protection",std::format("rectangle accepted={} source-normalized NR-only",accepted));return 0;}+ if(m==WM_CAPTURECHANGED&&protectionDragging){protectionDragging=false;protectionArmed=false;if(protectionOverlay)ShowWindow(protectionOverlay,SW_HIDE);}+ if(m==WM_MOUSEWHEEL||m==WM_MBUTTONDOWN||m==WM_RBUTTONUP)return 0;+ }+if(id==VideoSurface&&uiState.mode==veyra::ui::Mode::Professional){if(m==WM_MOUSEWHEEL){POINT p{GET_X_LPARAM(l),GET_Y_LPARAM(l)};ScreenToClient(h,&p);RECT r{};GetClientRect(h,&r);@@ -93,11 +116,12 @@ std::wstring fileDialog(bool save){wchar_t name[32768]{};OPENFILENAMEW ofn{};ofnofn.lpstrFilter=save?L"PNG图片\0*.png\0JPEG图片\0*.jpg\0":L"视频 / 图片\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.png;*.jpg;*.jpeg\0所有文件\0*.*\0";ofn.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);ofn.lpstrDefExt=save?L"png":nullptr;return (save?GetSaveFileNameW(&ofn):GetOpenFileNameW(&ofn))?name:L"";}-void openFile(const std::wstring& file){if(file.empty())return;auto ext=std::filesystem::path(file).extension().wstring();for(auto& c:ext)c=towlower(c);if((ext==L".png"||ext==L".jpg"||ext==L".jpeg")&&uiState.mode==veyra::ui::Mode::Daily)switchMode();engine.previewView({});currentFile=file;subtitles=veyra::engine::loadSrt(std::filesystem::path(file).replace_extension(L".srt").wstring());paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"暂停");engine.open(video,file,options());SetWindowTextW(mainWindow,(L"Veyra — "+std::filesystem::path(file).filename().wstring()).c_str());if(smokeSeconds<=0)WritePrivateProfileStringW(L"Player",L"最近打开",file.c_str(),(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());}+void openFile(const std::wstring& file){if(file.empty())return;cancelProtection();auto openOptions=options();if(file!=currentFile){openOptions.settings.protection={};uiState.configured.protection={};}auto ext=std::filesystem::path(file).extension().wstring();for(auto& c:ext)c=towlower(c);if((ext==L".png"||ext==L".jpg"||ext==L".jpeg")&&uiState.mode==veyra::ui::Mode::Daily)switchMode();engine.previewView({});currentFile=file;subtitles=veyra::engine::loadSrt(std::filesystem::path(file).replace_extension(L".srt").wstring());paused=false;SetWindowTextW(GetDlgItem(mainWindow,Play),L"暂停");engine.open(video,file,openOptions);SetWindowTextW(mainWindow,(L"Veyra — "+std::filesystem::path(file).filename().wstring()).c_str());if(smokeSeconds<=0)WritePrivateProfileStringW(L"Player",L"最近打开",file.c_str(),(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());}HWND control(const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x,int y,int w,int h){auto hwnd=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|style|(_wcsicmp(cls,L"STATIC")?WS_TABSTOP:0),x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);veyra::ui::themeControl(hwnd);if(id>=Open&&id<=Fullscreen&&id!=Seek)toolbar.push_back({hwnd,w});return hwnd;}void refreshDailyPresets(){auto h=GetDlgItem(mainWindow,DailyPreset);if(!h)return;SendMessageW(h,CB_RESETCONTENT,0,0);SendMessageW(h,CB_ADDSTRING,0,LPARAM(L"当前自定义设置"));for(auto& name:veyra::ui::presetNames())SendMessageW(h,CB_ADDSTRING,0,LPARAM(name.c_str()));SendMessageW(h,CB_SETCURSEL,0,0);}void selectInspector(int page){uiState.inspector=page;veyra::ui::settingsPage(page);for(int i=0;i<4;++i)veyra::ui::selected(GetDlgItem(mainWindow,TabEnhance+i),i==page);}void switchMode(){+ cancelProtection();const auto start=std::chrono::steady_clock::now();const auto before=engine.snapshot();const auto host=video;if(uiState.mode==veyra::ui::Mode::Daily){uiState.mode=veyra::ui::Mode::Professional;compareMode=uiState.preferredComparison;}else{uiState.mode=veyra::ui::Mode::Daily;engine.previewView({});uiState.preferredComparison=compareMode;compareMode=0;holdOriginal=false;if(GetCapture())ReleaseCapture();}@@ -227,12 +251,16 @@ case WM_CAPTURECHANGED:if(inspectorResizing){inspectorResizing=false;InvalidateRcase WM_NOTIFY:{auto header=reinterpret_cast<NMHDR*>(lp);if(header->code==TTN_GETDISPINFOW){auto info=reinterpret_cast<NMTTDISPINFOW*>(lp);HWND child=reinterpret_cast<HWND>(header->idFrom);if(auto tip=GetPropW(child,L"veyra.tip"))info->lpszText=reinterpret_cast<wchar_t*>(tip);else{static wchar_t value[512];GetWindowTextW(child,value,512);info->lpszText=value;}return 0;}break;}case WM_GETMINMAXINFO:{auto info=reinterpret_cast<MINMAXINFO*>(lp);info->ptMinTrackSize={veyra::ui::dip(hwnd,720),veyra::ui::dip(hwnd,540)};return 0;}case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORBTN:case WM_CTLCOLORLISTBOX:return veyra::ui::colors(msg,wp,lp);+case WM_APP+45:{if(masterPendingRevision)return 0;auto settings=uiState.enhanced?engine.snapshot().desired:uiState.configured;+ if(wp==213){auto current=engine.snapshot();if(uiState.mode!=veyra::ui::Mode::Professional||!current.running||!current.frames)return 0;bool space=false;for(auto q:settings.protection.regions)space|=q.empty();if(!space)return 0;cancelProtection();protectionArmed=true;SetFocus(video);return 1;}+ if(wp==214){cancelProtection();settings.protection={};}else if(wp==206)settings.protection.enabled=lp==BST_CHECKED;else return 0;+ return applySettings(settings)?1:0;}case WM_APP+44:{if(masterPendingRevision)return 0;auto setting=uiState.enhanced?engine.snapshot().desired:uiState.configured;const bool enabled=lp==BST_CHECKED;if(wp==200)setting.nr=enabled;else if(wp==201)setting.sr=enabled;else return 0;const bool enablesMaster=enabled&&!uiState.enhanced;if(enablesMaster){masterPreviousEnabled=false;uiState.enhanced=true;}applySettings(setting);if(auto pending=engine.snapshot();enablesMaster&&pending.running){masterPendingRevision=pending.desired.revision;masterPendingSession=pending.sessionId;}veyra::log::info("ui-feature",std::format("click={} enabled={} requestedRevision={} draft-independent=true",wp==200?"NR":"SR",enabled,engine.snapshot().desired.revision));return 1;}case WM_APP+43:showDiagnostics=false;layout();return 0;case WM_APP+42:refreshDailyPresets();return 0;case WM_APP+41:switch(wp){case 501:startVideoExport(lp!=0);break;case 502:{auto path=fileDialog(true);if(!path.empty())engine.saveFrame(path);break;}case 503:jobPaused=!jobPaused;exportJob.pause(jobPaused);break;case 504:exportJob.cancel();break;case 505:preferWatching=lp==BST_CHECKED;break;}return 0;-case WM_SIZE:if(wp!=SIZE_MINIMIZED){endTransition();layout();}return 0;+case WM_SIZE:cancelProtection();if(wp!=SIZE_MINIMIZED){endTransition();layout();}return 0;case WM_DROPFILES:{wchar_t file[32768]{};DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file,32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file);layout();return 0;}case WM_COMMAND:switch(LOWORD(wp)){case Open:case ProRailVideo:case ImageOpen:openFile(fileDialog(false));layout();break;@@ -273,7 +301,7 @@ case Export:if(uiState.mode==veyra::ui::Mode::Professional)startVideoExport(falscase 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&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;-case WM_KEYDOWN: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_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;case WM_THEMECHANGED:veyra::ui::glassTextTheme().reset();[[fallthrough]];@@ -346,7 +374,23 @@ if(settingsStep==1&&s.applied.model.intensity==.6f&&elapsed>3300){auto change=s.if(settingsStep==2&&s.applied.sr&&elapsed>4500){auto invalid=s.desired;invalid.model.intensity=2;const bool rejected=!engine.requestSettings(invalid);veyra::log::info("settings-test",std::format("invalid-rejected={} position={} revision={} settingsStep={}",rejected,s.position,s.applied.revision,settingsStep));settingsStep=rejected?3:-1;}}tickRepairChecks(hwnd,s);-if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={} capture={} processedFps={:.2f} callbackFps={:.2f} captureDropped={} callbackToPresentReturnP95Ms={:.3f} schedulingWaitP95Ms={:.3f} processCpuP95Ms={:.3f} presentCpuP95Ms={:.3f} nrEvaluated={} nvofExecuted={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep,s.capture,s.fps,s.captureFps,s.captureDropped,s.captureAgeP95Ms,s.schedulingWaitP95Ms,s.processCpuP95Ms,s.presentCpuP95Ms,s.nrEvaluated,s.nvofExecuted));resultCode=(s.frames>0||smokeEmpty)&&!s.failed&&(!smokeZoom||zoomStep==3)&&(!smokeRepair||repairStep==10)&&(!smokeSettings||settingsStep==3)&&(!smokeRollback||settingsStep==3)&&(!smokeUi||uiStep==8)&&(!smokeDual||dualStep==40)&&(!smokeMaster||masterStep==3)&&(!smokeAudio||audioStep==4)&&(!(smokeJob||smokeJobCancel)||jobStep==4)?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}+if(smokeProtection&&startTick&&GetTickCount64()-startTick>1500){+ auto indicator=[&](bool enabled,const wchar_t* count){wchar_t text[128]{},draft[64]{};auto control=veyra::ui::settingsControlForTest(206);GetWindowTextW(control,text,128);GetWindowTextW(veyra::ui::settingsControlForTest(100),draft,64);return (SendMessageW(control,BM_GETCHECK,0,0)==BST_CHECKED)==enabled&&std::wstring(text).find(count)!=std::wstring::npos&&std::wstring(draft)==L"0.42";};+ if(protectionStep==0&&s.frames){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();if(!transition.running){+ SetWindowTextW(veyra::ui::settingsControlForTest(100),L"0.42");protectionSession=s.sessionId;auto view=engine.previewView();view.zoom=2;engine.previewView(view);RECT r{};GetClientRect(video,&r);auto e=s.metrics.resolution.output;+ const float scale=std::min(float(r.right)/e.width,float(r.bottom)/e.height)*view.zoom;+ auto pixel=[&](float u,float v){return POINT{LONG(r.right*.5f+(u-view.centerX)*e.width*scale),LONG(r.bottom*.5f+(v-view.centerY)*e.height*scale)};};+ auto a=pixel(.4f,.4f),b=pixel(.6f,.6f);SendMessageW(veyra::ui::settingsControlForTest(213),BM_CLICK,0,0);SendMessageW(video,WM_LBUTTONDOWN,MK_LBUTTON,MAKELPARAM(a.x,a.y));SendMessageW(video,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(b.x,b.y));+ protectionOverlayShown=protectionOverlay&&IsWindowVisible(protectionOverlay);SendMessageW(video,WM_LBUTTONUP,0,MAKELPARAM(b.x,b.y));protectionStep=1;+ }}else if(protectionStep==1&&s.applied.protection.enabled&&indicator(true,L"1/4")){auto q=s.applied.protection.regions[0];bool pass=s.sessionId==protectionSession&&std::abs(q.left-.4f)<.01f&&std::abs(q.top-.4f)<.01f&&std::abs(q.right-.6f)<.01f&&std::abs(q.bottom-.6f)<.01f&&protectionOverlayShown;+ veyra::log::info("protection-ui-test",std::format("zoom2 rectangle={} overlay={} unchangedSession={} bounds={},{},{},{}",pass,protectionOverlayShown,s.sessionId==protectionSession,q.left,q.top,q.right,q.bottom));+ SendMessageW(veyra::ui::settingsControlForTest(214),BM_CLICK,0,0);protectionStep=pass?2:-1;+ }else if(protectionStep==2&&!s.applied.protection.enabled&&indicator(false,L"0/4")){SendMessageW(veyra::ui::settingsControlForTest(213),BM_CLICK,0,0);SendMessageW(hwnd,WM_KEYDOWN,VK_ESCAPE,0);bool pass=!protectionArmed&&!protectionDragging;protectionStep=pass?3:-1;veyra::log::info("protection-ui-test",std::format("clear/cancel dirty-draft-preserved pass={}",pass));if(pass)SendMessageW(hwnd,WM_COMMAND,Master,0);}+ else if(protectionStep==3&&!uiState.enhanced&&!masterPendingRevision){auto c=uiState.configured;const auto revision=c.revision;c.protection.enabled=true;c.protection.regions[0]={.1f,.2f,.8f,.9f};bool pass=applySettings(c)&&indicator(true,L"1/4");c.protection={};pass=applySettings(c)&&indicator(false,L"0/4")&&c.revision==revision&&pass;+ protectionStep=pass?4:-1;veyra::log::info("protection-ui-test",std::format("master-off unchanged-revision dirty-draft-preserved pass={}",pass));SendMessageW(hwnd,WM_COMMAND,Master,0);}++}+if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)*1000){veyra::log::info("app",std::format("smoke frames={} generated={} failed={} latenessMs={:.2f} absLatenessP95Ms={:.2f} controlsStep={} capture={} processedFps={:.2f} callbackFps={:.2f} captureDropped={} callbackToPresentReturnP95Ms={:.3f} schedulingWaitP95Ms={:.3f} processCpuP95Ms={:.3f} presentCpuP95Ms={:.3f} nrEvaluated={} nvofExecuted={}",s.frames,s.generated,s.failed,s.lateMs,s.lateP95Ms,smokeStep,s.capture,s.fps,s.captureFps,s.captureDropped,s.captureAgeP95Ms,s.schedulingWaitP95Ms,s.processCpuP95Ms,s.presentCpuP95Ms,s.nrEvaluated,s.nvofExecuted));resultCode=(s.frames>0||smokeEmpty)&&!s.failed&&(!smokeZoom||zoomStep==3)&&(!smokeProtection||protectionStep==4)&&(!smokeRepair||repairStep==10)&&(!smokeSettings||settingsStep==3)&&(!smokeRollback||settingsStep==3)&&(!smokeUi||uiStep==8)&&(!smokeDual||dualStep==40)&&(!smokeMaster||masterStep==3)&&(!smokeAudio||audioStep==4)&&(!(smokeJob||smokeJobCancel)||jobStep==4)?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}case WM_CLOSE:endTransition();if(!closing&&smokeSeconds<=0&&exportJob.poll().active()&&MessageBoxW(hwnd,L"导出尚未完成。取消导出并退出?\n选择“否”返回播放器继续导出。",L"退出 Veyra",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION)!=IDYES)return 0;if(!closing&&smokeSeconds<=0){auto snapshot=engine.snapshot();WINDOWPLACEMENT placement{sizeof(placement)};if(full)placement=windowPlacement;else GetWindowPlacement(hwnd,&placement);auto r=placement.rcNormalPosition;uiPreferences.width=MulDiv(r.right-r.left,96,GetDpiForWindow(hwnd));uiPreferences.height=MulDiv(r.bottom-r.top,96,GetDpiForWindow(hwnd));uiPreferences.x=r.left;uiPreferences.y=r.top;uiPreferences.positioned=true;uiPreferences.volume=snapshot.volume;uiPreferences.muted=snapshot.muted;uiPreferences.subtitles=uiState.subtitles;uiPreferences.subtitleSize=subtitlePixels;uiPreferences.inspector=uiState.inspector;const bool confirmed=snapshot.frames>0&&!snapshot.applying&&!snapshot.failed;if(!preferences.save(uiPreferences,haveSuccessful?&lastSuccessful:nullptr))veyra::log::warn("ui-preferences","preferences not saved; corrupt original preserved");}exportJob.cancel();closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;case WM_DESTROY:backdrop.detach();DeleteObject(font);DeleteObject(emptyFont);PostQuitMessage(resultCode);return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}@@ -358,7 +402,7 @@ CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);std::filesystem::create_directories(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs");wchar_t logOverride[32768]{};GetEnvironmentVariableW(L"VEYRA_LOG_FILE",logOverride,32768);veyra::Logger::instance().openFile(logOverride[0]?std::wstring(logOverride):(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs/veyra-app.log").wstring());initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);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/ProtectionOverlay.h b/apps/veyra/ui/ProtectionOverlay.hnew file mode 100644index 00000000..cb28ae81--- /dev/null+++ b/apps/veyra/ui/ProtectionOverlay.h@@ -0,0 +1,18 @@+#pragma once+#include "SubtitleOverlay.h"+#include "Theme.h"+namespace veyra::ui {+// Selection-only overlay. Never reads or modifies the video swapchain.+inline void protectionOutline(HWND h,HWND video,RECT box){+ RECT r{};GetClientRect(video,&r);if(r.right<1||r.bottom<1)return;+ SetWindowPos(h,HWND_TOP,0,0,r.right,r.bottom,SWP_NOACTIVATE);+ BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=r.right;info.bmiHeader.biHeight=-r.bottom;info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;+ HDC screen=GetDC(nullptr),memory=CreateCompatibleDC(screen);void* bits=nullptr;auto bitmap=CreateDIBSection(screen,&info,DIB_RGB_COLORS,&bits,nullptr,0);+ if(!bitmap||!bits){if(bitmap)DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(nullptr,screen);return;}+ auto previous=SelectObject(memory,bitmap);memset(bits,0,size_t(r.right)*r.bottom*4);+ {using namespace Gdiplus;Bitmap canvas(r.right,r.bottom,r.right*4,PixelFormat32bppPARGB,static_cast<BYTE*>(bits));Graphics g(&canvas);Pen pen(Color(255,240,132,49),float(dip(h,2)));g.DrawRectangle(&pen,Rect(box.left,box.top,std::max(1L,box.right-box.left),std::max(1L,box.bottom-box.top)));}+ SIZE size{r.right,r.bottom};POINT origin{};BLENDFUNCTION blend{AC_SRC_OVER,0,255,AC_SRC_ALPHA};+ if(UpdateLayeredWindow(h,screen,nullptr,&size,memory,&origin,0,&blend,ULW_ALPHA))ShowWindow(h,SW_SHOWNOACTIVATE);+ SelectObject(memory,previous);DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(nullptr,screen);+}+}diff --git a/docs/REVIEW_NR_PROTECTION_2026-09-08.md b/docs/REVIEW_NR_PROTECTION_2026-09-08.mdnew file mode 100644index 00000000..63cb53d8--- /dev/null+++ b/docs/REVIEW_NR_PROTECTION_2026-09-08.md@@ -0,0 +1,11 @@+# Manual NR protection review — 2026-09-08++review_protection: new-context read-only review of cycles64–65. Initial verdict FAIL for P2 stale protection checkbox/count with dirty numeric drafts or unchanged revision while master enhancement off. Fixed dedicated syncProtection; numeric drafts are not repopulated. Final scoped PASS, no remaining introduced P0/P1/P2.++Independent GPU matrix image-aaab094e151b4904b989eb43cdf8242c19.563s: Feature18 Create0x1 non-null SEH0, NR4, changed191323channels, protected/outsideerror0; full-protected2561square nine tiles/nineNR evaluates error0. Preset roundtrip/legacy upgrade/invalid/corrupt tests PASS. No new normal playback/video-export pixel readback found.++Final independent preflight PASS; phase7 logs/delivery/a178db7f0e0e4a4a8555d0b66e764f0a/result.json41.477s,75checksPASS. Finalapp SHA2560654C61F11D9FC50436B964F385E4028E6458C4B9D186B6DCD5B0796C383B4F5. UI logs/optimization-goal-20260908/protection-final-review-a2044089e105466f91c8857a306187a2/app.log exit0,9secondsmoke/25secondwatchdog: actualbuttons/zoom2rectangle/visibleoverlay/sessionassertions PASS; numeric0.42draft survives selection/clear/Esc; master-off same-revision indicators pass; NR4failedfalse.++Initial reviewer setup failures (wrong input path, hidden root) are retained in ignored logs; correct visible launch passed. Final tracked fingerprint9af8dfb05978f33ef832e1c557e0a76e2d9e77a4 unchanged. Untracked overlay initially independently reviewed hash390809D9DEF189952B86B8235C6D7005283AF77BC535DAAD3ED4211C3A321713. GPU/preset code did not change in UI correction and was not redundantly rerun.++Scope: manual NR change suppression only. No visual-design screenshot acceptance; feathered/partial-tile/natural/moving quality, SR/FG protection and privateUI resources still unproved. Q6/Q7 and physical capture remain open. This is not full Q5 or Goal approval.diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 7739bb50..866669d1 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1155,3 +1155,19 @@ Cycle62 independent PASS: docs/REVIEW_CAPTURE_RGB_2026-09-08.md. phase7 afe022a9- Review pending. Natural/known4K reconstruction, UI protection, motion/FG quality and candidate ROI remain. Export integrity unchanged; physical capture not executed.Cycle63 independent scoped PASS: docs/REVIEW_SR_CONTRACT_2026-09-08.md. phase7 1168a76f41.678s/image0d5938b316.225s/SR60a70819e65.925s. Actual4K colorbars output visually inspected; not natural content. Next atomic Q5 GPU protected regions within residual composition, source-normalized coordinates, then professional rectangle selection/preset persistence; do not label private UI correction effective or forget SR/FG distinction.++## Cycles64–65 — manual NR protection and professional selection+- ProtectionSettings: up to4 source-normalized rectangles, finite/in-order validation and0..32 inward feather pixels, defaultdisabled. Residual GPU pass24 constants folds mask into existing NR delta composition; full protection returns base. No normal pixel readback, extra inference or per-frame CPU pixel processing.+- Player/new graph/settings rollback/export share protection fields. Large image tiles map source-normalized rectangles into padded tile coordinates (128halo exceeds32feather). Normalized regions survive output sizing; current feature explicitly protects NR changes only, not SR or FG.+- Preset schema2 serializes all protection fields; schema1 remains readable and upgrades on save. Unknown/corrupt files remain protected. Existing export integrity unchanged; worker structure size handshake retained.+- Professional controls: NR protection toggle/count, rectangle/clear buttons; visible notes maximum4, Esc, NR-only, preset persistence and source-change clearing. Layered selection outline only during drag; sourcePoint uses same zoom/pan geometry. Main Esc, mode change and resize cancel; source switch clears via new-session options even during master transaction. Existing private UI correction remains unverified.+- Build scripts/build.ps1 -Root project -Preset x64-release logs build-protection / presets / ui / ui-smoke / final / buttons all exit0. Replaced pair<int,int> sentinel with float to remove new conversion warnings.+- GPU image matrix image-a812c02d15ad45159670b325703a99fb19.450s/275watchdog PASS: real NR4; no-mask/empty/full/rectangle positive-negative comparisons show changed191323 channels, protectedError0 and outsideError0. Full-protected2561x2561 nine-tile NR maxError0. Existing SR/colors/oddimages/capture synthetic also pass. Feather blend visual/temporal quality not yet measured.+- veyra_repair_preset_tests.exe unique ignoredpath PASS: all fields, invalid region, legacy1 read→2write/reload, corrupt preservation. Unit test process under1s.+- phase7-protection.log0815b4cbc2dd4dd08d982cb1a0da302d PASS75. phase7-protection-ui.log b9de57f797724808a2b70df8fbe24239 PASS75,41.751s (app0A5CE... before smoke-only route refinement).+- Actual Win32 app --nr --no-fg --smoke-protection --smoke-seconds9 on257x513image (25s watchdog): protection-ui-ed8f1a8475fd4012826360032da1bdf3 PASS; final protection-buttons-329fc51ef4ed4cd3a1ebef948d7b7760 PASS uses actual SettingsWindow BM_CLICK handlers213/214, zoom2 rectangle bounds0.39898235,0.39979756,0.5989973,0.5991903, overlayvisible, unchangedSession, applied settings, clear/Esc PASS. Synthetic UI messages, not physical user gesture/visual style approval.+- Current app SHA256098F6950511922F20413DCCD4E05B86311A09D94743EE895C9B838E92A9756A1. Review pending. Q5 private resource experiments, SR/FG region policy, natural/moving/feathered quality, Q6/Q7 remain. Physical capture unexecuted.++Protection reviewer initial FAILP2: dirty numeric draft / unchanged revision master-off prevented checkbox/count populate. Fixed syncProtection independent of numericpopulate, calledtimerandsettingsEnabled. FinalactualUIprotection-indicators-cd408855c24d4741aa481db9a2329ba9 exit0 (9secondsmoke25watchdog): dirty0.42 draft retained throughrectangle/clear/Esc; master-offsame-revision regionon/off indicators correct, draftretained; masterrestored. Build-protection-indicators exit0; app0654C61F11D9FC50436B964F385E4028E6458C4B9D186B6DCD5B0796C383B4F5. Independent recheck pending; GPU code unchanged.++Final protection review scopedPASS afterP2fix: docs/REVIEW_NR_PROTECTION_2026-09-08.md. Independent finalphase7a178db7f41.477s/UIa20440899s PASS. CurrentmanualNR protection delivered locally; fullQ5/Goalnotcomplete. Next: feathered/partialtile/moving validation, private UIAlpha/Backbuffer/ControlMask isolated fixedruntime experiment; SR/FG referencepolicy; sourceNVOFcurrent->previous confirmed(NvOfSession inputB=current/referenceA=previous, densify negate0), Q6 bounds/photometricconfidence and Q7ROI thereafter.diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex bd3c56ae..d722a488 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -1,5 +1,6 @@#pragma once#include <cmath>+#include <array>#include <cstdint>#include <string>#include "veyra/pipeline/ResolutionPlan.h"@@ -15,10 +16,28 @@ struct ResidualSettings {float total=1,darken=1,brighten=1,color=1,luminance=1;bool operator==(const ResidualSettings&) const = default;};+struct ProtectionRect {+ float left=0,top=0,right=0,bottom=0;+ bool empty()const{return left==right||top==bottom;}+ bool operator==(const ProtectionRect&)const=default;+};+struct ProtectionSettings {+ bool enabled=false;+ float featherPixels=2;+ std::array<ProtectionRect,4> regions{};+ bool operator==(const ProtectionSettings&)const=default;+ std::string validate()const{+ if(!std::isfinite(featherPixels)||featherPixels<0||featherPixels>32)return "invalid protection feather";+ for(auto r:regions){for(float v:{r.left,r.top,r.right,r.bottom})if(!std::isfinite(v)||v<0||v>1)return "invalid protection rectangle";+ if(r.left>r.right||r.top>r.bottom)return "inverted protection rectangle";}+ return {};+ }+};struct EnhancementSettings {uint64_t revision=1;NrSettings model;ResidualSettings residual;+ ProtectionSettings protection;bool nr=true,sr=false;uint32_t multiplier=1;pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;@@ -27,6 +46,7 @@ struct EnhancementSettings {bool operator==(const EnhancementSettings&) const = default;std::string validate() const {auto range=[](float v,float hi){return std::isfinite(v)&&v>=0&&v<=hi;};+ if(auto error=protection.validate();!error.empty())return error;if(!revision)return "settingsRevision must be nonzero";if(!range(model.intensity,1)||!range(model.tone,1)||!range(model.structure,1))return "model parameter out of range";if(model.skin!=-1&&!range(model.skin,2))return "skin parameter out of range";diff --git a/include/veyra/engine/PreviewView.h b/include/veyra/engine/PreviewView.hindex 5c094bcb..5145d4ee 100644--- a/include/veyra/engine/PreviewView.h+++ b/include/veyra/engine/PreviewView.h@@ -1,10 +1,16 @@#pragma once#include <algorithm>#include <cmath>+#include <utility>namespace veyra::engine {struct PreviewView {float zoom=1,centerX=.5f,centerY=.5f;bool operator==(const PreviewView&)const=default;+ std::pair<float,float> sourcePoint(float x,float y,float cw,float ch,float iw,float ih)const{+ if(cw<=0||ch<=0||iw<=0||ih<=0)return {-1.0f,-1.0f};+ const float fit=std::min(cw/iw,ch/ih)*zoom;+ return {centerX+(x-cw*.5f)/(iw*fit),centerY+(y-ch*.5f)/(ih*fit)};+ }void wheel(float steps,float x,float y,float clientW,float clientH,float imageW,float imageH){if(clientW<=0||clientH<=0||imageW<=0||imageH<=0||!std::isfinite(steps))return;const float fit=std::min(clientW/imageW,clientH/imageH);diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex c0ff916f..9b38c14c 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -70,6 +70,7 @@ struct EnhanceGraphDesc {engine::ContentRate contentRate=engine::ContentRate::Transport;engine::NrSettings model;engine::ResidualSettings residual;+ engine::ProtectionSettings protection;std::wstring runtimeAbsPath; // absolute runtime_local/nvidia path// Optional stage instrumentation hook (GPU timing experiments).std::function<void(const char*)> stageMark;diff --git a/include/veyra/pipeline/GpuPassUtils.h b/include/veyra/pipeline/GpuPassUtils.hindex 4cbced6a..c9a5f7ec 100644--- a/include/veyra/pipeline/GpuPassUtils.h+++ b/include/veyra/pipeline/GpuPassUtils.h@@ -106,7 +106,7 @@ struct ComputePass {ComPtr<ID3D12RootSignature> rootSig;ComPtr<ID3D12PipelineState> pso;ComPtr<ID3D12DescriptorHeap> heap;- UINT increment = 0;+ UINT increment = 0, constantCount = 8;bool loadShader(const char* name, std::vector<uint8_t>& bytes) const{@@ -127,8 +127,10 @@ struct ComputePass {}bool create(ID3D12Device* device, const std::vector<uint8_t>& cs, UINT heapSlots,- UINT srvCount = 3, UINT uavCount = 1)+ UINT srvCount = 3, UINT uavCount = 1, UINT constants = 8){+ if(constants==0||constants>60)return false;+ constantCount=constants;D3D12_DESCRIPTOR_RANGE1 srvRange{};srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;srvRange.NumDescriptors = srvCount;@@ -141,7 +143,7 @@ struct ComputePass {rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;rp[0].Constants.ShaderRegister = 0;- rp[0].Constants.Num32BitValues = 8;+ rp[0].Constants.Num32BitValues = constantCount;rp[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;rp[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;rp[1].DescriptorTable.NumDescriptorRanges = 1;@@ -172,14 +174,14 @@ struct ComputePass {return true;}- void bind(ID3D12GraphicsCommandList* list, const float constants[8],+ void bind(ID3D12GraphicsCommandList* list, const float* constants,uint64_t srvGpu, uint64_t uavGpu) const{ID3D12DescriptorHeap* heaps[] = { heap.Get() };list->SetDescriptorHeaps(1, heaps);list->SetComputeRootSignature(rootSig.Get());list->SetPipelineState(pso.Get());- list->SetComputeRoot32BitConstants(0, 8, constants, 0);+ list->SetComputeRoot32BitConstants(0, constantCount, constants, 0);const D3D12_GPU_DESCRIPTOR_HANDLE srv{ srvGpu };const D3D12_GPU_DESCRIPTOR_HANDLE uav{ uavGpu };list->SetComputeRootDescriptorTable(1, srv);diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.mdindex 6b8b9e84..6ac414ab 100644--- a/loop/EVIDENCE.md+++ b/loop/EVIDENCE.md@@ -468,3 +468,9 @@ Cycle62 independent scoped PASS: docs/REVIEW_CAPTURE_RGB_2026-09-08.md; full GoaCycle63 SR fixed image87b550aa16.462s and motion60c12206415.8s PASS; diagnostic failurebd4905c3 root-caused/repaired actual texture sizes. Official linear flags0x41; same-size/height-only validated. WORKLOG details; review pending.Cycle63 reviewer scoped PASS: docs/REVIEW_SR_CONTRACT_2026-09-08.md. FullQ4 visual reconstruction and Q5-Q7 remain.++Cycles64-65 protection GPU imagea812c02d19.450s PASS, presets migration PASS, phase7b9de57f741.751s PASS, finalactualbuttons329fc51e UI9s PASS. App098F6950... NR-only, feather quality/SR/FG/natural andQ6Q7 open. WORKLOG details.++Protection P2 fixed; actualUIcd4088559s PASS dirty draft+master-off same revision indicators. App0654C61F... independent recheckpending.++Protection final independent scopedPASS: docs/REVIEW_NR_PROTECTION_2026-09-08.md; app0654C61F... phase7a178db7f41.477s. P2closed withdirty/master-off regressions; Q5b/Q6/Q7 stillopen.diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex 6d708ffc..0da84223 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -1448,3 +1448,15 @@ Cycle63 evidence: SR60 diagnostic failed76 D3D errors, CopyTextureRegion used4KCycle63 final60frame diagnostic PASS after actual resource extent fix. Freeze project writes/GPU for independent scoped reviewer.Cycle63 review complete: scopedPASS, tracked fingerprint unchanged. Local checkpoint; prepare Q5 protection GPU contract and UI/preset closure.++Cycle64 before edit: GPU manual NR protection, maximum4 normalized rectangles with inward pixel feather, defaultdisabled. Thread settings/preset/export/tiled paths, real protected/unprotected GPU pixel checks. Keep private UICorrection experimental, SR/FG protection not claimed; UI closure next cycle. Prior turn progress eba2ec8.++Cycle64 GPU tests PASS: imagea812c02d19.450s protected/outsideerrors0; full2561-square tiledNR9 evaluations maxError0; preset legacy/v2 migration PASS; phase7 0815b4cb PASS. Cycle65 before edit: professional rectangle selection UI, normalized zoom/pan mapping, explicit NR-only labels, clear/toggle and schema-backed presets. No SR/FG automatic-protection claim.++Cycle65 after edit: finalactualSettingsWindow buttons smoke PASS, source-change options hardened, mainEsc cancel wired; independent review pending. Freeze tracked writes/GPU.++Cycles64-65 reviewer FAILP2 protection indicators stale under dirty drafts / unchanged revision master-off. GPU/phase7/preset/UI normal path independentlyPASS; tracked fingerprintunchanged. Fix dedicated sync without numeric repopulation, extend realUI smoke dirty/master-off before recheck.++P2 dedicated indicator synchronization and regression passed locally. Freeze again for reviewerrecheck; no further GPU/codechanges.++Cycles64-65 finalreviewPASS fingerprintunchanged; localcheckpoint before next protection/quality evidence. No push/release/physicalcaptureclaim.diff --git a/loop/STATE.json b/loop/STATE.jsonindex b133fc21..2cff7ef1 100644--- a/loop/STATE.json+++ b/loop/STATE.json@@ -76,19 +76,19 @@}],"cycle": {- "completed": 63,+ "completed": 65,"maximum": 120,"sameFailureAttempts": 0,"maximumSameFailureAttempts": 3,"noProgressCycles": 0,"maximumNoProgressCycles": 5},- "currentTask": "Cycle63 SR color/extent contract independently reviewed PASS; quality scope still open",+ "currentTask": "Manual NR protection GPU/UI/preset path independently reviewed PASS; full quality goal ongoing","lastGate": {"name": "phase7","status": "passed","exitCode": 0,- "evidence": "logs/delivery/1168a76f88224761a80b1cdfe975f3f7/result.json41.678s app37361B9C..."+ "evidence": "logs/delivery/a178db7f0e0e4a4a8555d0b66e764f0a/result.json41.477s app0654C61F..."},"lastFailureFingerprint": "","failureLedger": [@@ -107,8 +107,8 @@"Current USB2 1080p50 physical throughput passed; user perceived latency/audio/actual FG display cadence still need confirmation.","Public proprietary runtime distribution rights unresolved; local delivery only."],- "nextAction": "Q5 protected regions: GPU residual composition and source-normalized coordinates, professional rectangle UI plus preset persistence; then SR/FG protection and remaining natural quality/Q6/Q7 comparisons",- "updatedAt": "2026-09-08T09:56:33.5048414Z",+ "nextAction": "Validate feathered/partial-tile/moving protection; isolated private NR resources and SR/FG reference policy; then Q6 motion confidence/FG and Q7 candidate ROI/natural reconstruction comparisons",+ "updatedAt": "2026-09-08T10:20:30.0786887Z","deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md","captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending","testInvocationLimitSeconds": 300,@@ -125,7 +125,8 @@"Cycles56-61:2Dtile,actualGPUpreview,rootqueuehover,odd/tallH264,14 timing checks,4 GPU color goldens; review pending","docs/REVIEW_COLOR_TIMING_2026-09-08.md: scoped independent PASS; phase7 31051b6d 41.143s, image GPU matrix and timing14 passed","docs/REVIEW_CAPTURE_RGB_2026-09-08.md: independent phase7afe022a9 41.407s and image9ac2822f11.487s PASS; synthetic RGB only",- "docs/REVIEW_SR_CONTRACT_2026-09-08.md: independent scopedPASS; SR60a70819e6 actual motion andGBV0, image route/color golden passed"+ "docs/REVIEW_SR_CONTRACT_2026-09-08.md: independent scopedPASS; SR60a70819e6 actual motion andGBV0, image route/color golden passed",+ "docs/REVIEW_NR_PROTECTION_2026-09-08.md: scopedPASS afterP2syncfix; GPU/presets andactualUI dirty/master-off independently verified"],"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb","localDelivery": "capture_fix_candidate_needs_review",@@ -263,8 +264,8 @@"testInvocationLimitSeconds": 300,"productModified": true,"consecutiveBlockedGoalTurns": 0,- "previousGoalTurnClassification": "progress: reviewed direct RGB capture checkpointd731ccf",- "currentGoalTurnClassification": "progress: SR flags/extent GPU tests and diagnostic source-space repair",+ "previousGoalTurnClassification": "progress: SR checkpointeba2ec8 independently reviewed",+ "currentGoalTurnClassification": "progress: GPU NR protection, normalized UI selection and preset compatibility implemented/tested","controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization"}}diff --git a/shaders/NrResidualComposite.hlsl b/shaders/NrResidualComposite.hlslindex 8f4a3d65..4d9054da 100644--- a/shaders/NrResidualComposite.hlsl+++ b/shaders/NrResidualComposite.hlsl@@ -2,14 +2,23 @@ Texture2D<float4> baseTex:register(t0);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;float3 unused;}+cbuffer Params:register(b0){float total;float darken;float brighten;float color;float luminance;float protectionEnabled;float featherPixels;float unused;float4 regions[4];}// 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){uint w,h,nw,nh;baseTex.GetDimensions(w,h);nrInput.GetDimensions(nw,nh);if(id.x>=w||id.y>=h)return;float4 base=baseTex[id.xy];- if(total==0){outputTex[id.xy]=base;return;}+ float protection=0;+ if(protectionEnabled>0){+ float2 p=float2(id.xy)+0.5;+ for(uint i=0;i<4;++i){float4 r=regions[i]*float4(w,h,w,h);+ if(r.z<=r.x||r.w<=r.y)continue;+ float edge=min(min(p.x-r.x,r.z-p.x),min(p.y-r.y,r.w-p.y));+ protection=max(protection,featherPixels>0?smoothstep(0,featherPixels,edge):(edge>=0?1:0));+ }+ }+ if(total==0||protection>=1){outputTex[id.xy]=base;return;}float2 pos=(float2(id.xy)+0.5)*float2(nw,nh)/float2(w,h)-0.5;int2 origin=(int2)floor(pos);float2 f=frac(pos);float3 delta=0;float weights=0;for(int y=0;y<2;++y)for(int x=0;x<2;++x){@@ -22,5 +31,5 @@ cbuffer Params:register(b0){float total;float darken;float brighten;float color;delta/=max(weights,1e-6);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;}- outputTex[id.xy]=float4(max(0,base.rgb+total*delta),base.a);+ outputTex[id.xy]=float4(max(0,base.rgb+total*(1-protection)*delta),base.a);}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex dc68687b..3a3463bd 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -95,7 +95,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,1);gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.enableSr=resolution.srApplied;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=options.nr;- gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;+ gd.noFeatures=false;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.contentRate=options.settings.content;gd.runtimeAbsPath=std::filesystem::path(VEYRA_PROJECT_ROOT).wstring()+L"\\runtime_local\\nvidia";if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}if(isCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}@@ -123,7 +123,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){const auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision);nextDesc.workWidth=plan.base.width;nextDesc.workHeight=plan.base.height;nextDesc.nrWidth=plan.nr.width;nextDesc.nrHeight=plan.nr.height;nextDesc.enableSr=plan.srApplied;nextDesc.enableNr=next.nr;nextDesc.enableFg=next.fg;nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.enableNvofStandalone=next.nr;- nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;+ nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;const bool rebuild=gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight;bool accepted=ring.drainQueue();out={};hasOutput=false;if(accepted&&rebuild){presenter.close();graph.shutdown();accepted=graph.initialize(nextDesc)&&presenter.open(ctx,window,graph)&&graph.createViews();diff --git a/src/engine/EngineControllerImage.cpp b/src/engine/EngineControllerImage.cppindex c27f9cee..cf85036c 100644--- a/src/engine/EngineControllerImage.cpp+++ b/src/engine/EngineControllerImage.cpp@@ -44,7 +44,7 @@ void EngineController::runLargeImage(HWND window,const sink::RgbaImage& original}if(requested.revision!=applied.revision){pipeline::EnhanceGraphDesc desc;desc.enableNr=requested.nr;desc.noFeatures=!requested.nr;- desc.model=requested.model;desc.residual=requested.residual;desc.settingsRevision=requested.revision;+ desc.model=requested.model;desc.residual=requested.residual;desc.protection=requested.protection;desc.settingsRevision=requested.revision;desc.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();sink::RgbaImage candidate;TiledImageProcessor::Stats stats;status(L"正在分块增强大图,保留完整输出尺寸…");diff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex 34eb79d3..ebe0100e 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -13,14 +13,16 @@ bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=Lstd::wstring trim(std::wstring s){auto a=s.find_first_not_of(L" \t\r\n");if(a==s.npos)return {};auto b=s.find_last_not_of(L" \t\r\n");return s.substr(a,b-a+1);}}std::string PresetStore::serialize()const{- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 1\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';- for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<'\n';}return o.str();+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 2\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<'\n';}return o.str();}bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||version!=1||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version!=1&&version!=2)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;+ if(version==2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;+ for(auto& q:s.protection.regions)if(!(in>>q.left>>q.top>>q.right>>q.bottom))return false;}p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);if(!s.validate().empty())return false;out.push_back(std::move(p));diff --git a/src/engine/TiledImageProcessor.cpp b/src/engine/TiledImageProcessor.cppindex 586db3ec..12d54247 100644--- a/src/engine/TiledImageProcessor.cpp+++ b/src/engine/TiledImageProcessor.cpp@@ -50,6 +50,16 @@ bool TiledImageProcessor::process(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRmemcpy(dst+size_t(x)*4,input.pixels.data()+(size_t(sy)*input.width+sx)*4,4);}}+ // Source-normalized regions are mapped to this padded tile. Halo exceeds+ // the maximum feather, so clipping at tile edges cannot alter core pixels.+ engine::EnhancementSettings tileSettings;tileSettings.nr=desc.enableNr;tileSettings.model=desc.model;tileSettings.residual=desc.residual;tileSettings.protection=desc.protection;+ for(auto& q:tileSettings.protection.regions){+ q.left=std::clamp(float(q.left*input.width-originX+halo)/tileW,0.0f,1.0f);+ q.right=std::clamp(float(q.right*input.width-originX+halo)/tileW,0.0f,1.0f);+ q.top=std::clamp(float(q.top*input.height-originY+halo)/tileH,0.0f,1.0f);+ q.bottom=std::clamp(float(q.bottom*input.height-originY+halo)/tileH,0.0f,1.0f);+ }+ tileSettings.revision=desc.settingsRevision;if(!graph.applySettings(tileSettings))return false;pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage tile;// Every tile is a new spatial image, never a temporal neighbour.if(!graph.process(frame.get(),0,true,out,uint64_t(stats.tiles)+1)||diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex 96036d61..27427dea 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -41,7 +41,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpticonst AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});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);- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.enableSr=resolution.srApplied;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.enableSr=resolution.srApplied;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;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.contentRate=options.settings.content;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();if(!graph.initialize(gd)||!graph.createViews())break;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;diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 9dc43c4e..3a8f533a 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -59,6 +59,7 @@ EnhanceGraph::~EnhanceGraph()// ---------------------------------------------------------------------------bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc){+ if(!desc.protection.validate().empty())return false;desc_ = desc;tracker_={};prevValid_=false;cadence_.reset();scene_.reset();previousLuma_.clear();diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={desc.sourceWidth,desc.sourceHeight};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={desc.workWidth,desc.workHeight};initDiagnostic.resolution.nr={desc.nrWidth?desc.nrWidth:desc.workWidth,desc.nrHeight?desc.nrHeight:desc.workHeight};initDiagnostic.resolution.flow=initDiagnostic.resolution.source;initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";Logger::diagnosticContext(initDiagnostic);srcW_ = desc.sourceWidth;@@ -470,7 +471,7 @@ bool EnhanceGraph::createComputePasses(){std::vector<uint8_t> cs;if(!downsamplePass_.loadShader("NrDownsample.dxil",cs)||!downsamplePass_.create(context_.device(),cs,2,1,1))return false;- if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1))return false;+ if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1,24))return false;if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3,1,1))return false;if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1)) return false;if(desc_.rgbInput&&(!rgbPass_.loadShader("RgbToLinear.dxil",cs)||!rgbPass_.create(context_.device(),cs,4,1,1)))return false;@@ -997,7 +998,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif(nrEnabled_&&nrHandle_){gpuTimer_.mark(list,GpuStage::Residual);tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- const auto& r=desc_.residual;const float c[8]={r.total,r.darken,r.brighten,r.color,r.luminance,0,0,0};+ const auto& r=desc_.residual;float c[24]={r.total,r.darken,r.brighten,r.color,r.luminance,desc_.protection.enabled?1.0f:0.0f,desc_.protection.featherPixels,0};+ for(size_t i=0;i<4;++i){const auto q=desc_.protection.regions[i];c[8+i*4]=q.left;c[9+i*4]=q.top;c[10+i*4]=q.right;c[11+i*4]=q.bottom;}residualPass_.bind(list,c,gpuHandleOf(residualPass_,0).ptr,gpuHandleOf(residualPass_,3).ptr);list->Dispatch((workW_+15)/16,(workH_+15)/16,1);tracker_.uavBarrier(list,residualRgba_.Get());tracker_.transition(list,residualRgba_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);gpuTimer_.mark(list,GpuStage::Residual,true);}@@ -1109,7 +1111,7 @@ bool EnhanceGraph::resolveGeneration(FrameOutputs& out)bool EnhanceGraph::applySettings(const engine::EnhancementSettings& s){if(!s.validate().empty()||(s.multiplier>1&&(!fgCapsAvailable_||s.multiplier-1>uint32_t(fgMultiFrameMax_))))return false;- desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.settingsRevision=s.revision;+ desc_.contentRate=s.content;desc_.model=s.model;desc_.residual=s.residual;desc_.protection=s.protection;desc_.settingsRevision=s.revision;desc_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr&&!desc_.stillImage;nvofStandalone_=desc_.enableNvofStandalone;setNrEnabled(s.nr);setFgEnabled(s.multiplier>1);veyra::log::info("settings",std::format("requested revision={} intensity={} tone={} structure={} skin={} style={} autoMask={} UI={} residual={}/{}/{}/{}/{} multiplier={}",s.revision,s.model.intensity,s.model.tone,s.model.structure,s.model.skin,s.model.style,s.model.autoMask,s.model.uiCorrection,s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance,s.multiplier));diff --git a/tests/integration/ImageDimensionTests.cpp b/tests/integration/ImageDimensionTests.cppindex e7d7852f..f0a8472a 100644--- a/tests/integration/ImageDimensionTests.cpp+++ b/tests/integration/ImageDimensionTests.cpp@@ -43,7 +43,7 @@ bool run(unsigned width,unsigned height,bool nr,const std::filesystem::path& dirstd::cout<<"IMAGE_DIMENSION "<<width<<'x'<<height<<" nr="<<nr<<" maxError8="<<maxError<<" nrEvaluations="<<graph.metrics().nrEvaluateCount<<" pass="<<ok<<std::endl;out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();return ok;}-bool tiled(unsigned width,unsigned height,bool nr,const std::filesystem::path& directory){+bool tiled(unsigned width,unsigned height,bool nr,const std::filesystem::path& directory,bool protect=false){gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc device;if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;sink::RgbaImage source;source.width=width;source.height=height;source.pixels.resize(size_t(width)*height*4);@@ -52,16 +52,17 @@ bool tiled(unsigned width,unsigned height,bool nr,const std::filesystem::path& d// sRGB 188 over black; fully transparent color contributes nothing.if(!nr){source.pixels[0]=source.pixels[1]=source.pixels[2]=255;source.pixels[3]=128;source.pixels[7]=0;}pipeline::EnhanceGraphDesc gd;gd.enableNr=nr;gd.noFeatures=!nr;gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();+ if(protect){gd.protection.enabled=true;gd.protection.featherPixels=0;gd.protection.regions[0]={0,0,1,1};}std::atomic<bool> cancel=false;engine::TiledImageProcessor::Stats stats;sink::RgbaImage result;bool ok=engine::TiledImageProcessor::process(ctx,ring,source,result,gd,cancel,stats);int maxError=0;uint64_t brightness=0;if(ok){ok=result.width==width&&result.height==height&&result.pixels.size()==source.pixels.size();for(size_t i=0;i<result.pixels.size();++i){int expected=source.pixels[i];if(!nr&&i<8)expected=i%4==3?255:(i<4?188:0);maxError=std::max(maxError,std::abs(int(result.pixels[i])-expected));if(i%4!=3)brightness+=result.pixels[i];}- ok=ok&&brightness>0&&(nr?stats.nrEvaluations==stats.tiles:maxError<=1);- sink::RgbaImage decoded;auto path=directory/(std::to_string(width)+"x"+std::to_string(height)+(nr?"-tiled-nr.png":"-tiled-off.png"));+ ok=ok&&brightness>0&&(nr?stats.nrEvaluations==stats.tiles&&(!protect||maxError<=1):maxError<=1);+ sink::RgbaImage decoded;auto path=directory/(std::to_string(width)+"x"+std::to_string(height)+(protect?"-tiled-protected.png":nr?"-tiled-nr.png":"-tiled-off.png"));ok=ok&&sink::saveImage(path.wstring(),result)&&sink::loadImage(path.wstring(),decoded)&&decoded.pixels==result.pixels&&decoded.width==width&&decoded.height==height;}- std::cout<<"IMAGE_TILED "<<width<<'x'<<height<<" nr="<<nr<<" tiles="<<stats.tiles<<" evaluations="<<stats.nrEvaluations<<" maxError8="<<maxError<<" pass="<<ok<<std::endl;+ std::cout<<"IMAGE_TILED "<<width<<'x'<<height<<" nr="<<nr<<" protect="<<protect<<" tiles="<<stats.tiles<<" evaluations="<<stats.nrEvaluations<<" maxError8="<<maxError<<" pass="<<ok<<std::endl;if(ok&&!nr){cancel=false;sink::RgbaImage abandoned;engine::TiledImageProcessor::Stats partial;const bool accepted=engine::TiledImageProcessor::process(ctx,ring,source,abandoned,gd,cancel,partial,[&](uint32_t,uint32_t){cancel=true;});ok=!accepted&&abandoned.pixels.empty()&&partial.tiles==1;@@ -151,6 +152,36 @@ bool srPixels(unsigned iw,unsigned ih,unsigned ow,unsigned oh,const std::filesysstd::cout<<"SR_PIXELS "<<iw<<'x'<<ih<<" -> "<<ow<<'x'<<oh<<" interiorMaxError8="<<error<<" evaluates="<<evals<<" pass="<<ok<<std::endl;ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();return ok;}+bool protectionPixels(){+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc device;+ if(!ctx.initialize(device,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return false;+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.sourceHeight=gd.workWidth=gd.workHeight=256;gd.rgbInput=gd.stillImage=true;gd.enableNr=true;gd.enableFg=false;+ gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();+ if(!graph.initialize(gd)||!graph.createViews())return false;+ AVFrame* f=av_frame_alloc();f->format=AV_PIX_FMT_RGBA;f->width=f->height=256;+ if(av_frame_get_buffer(f,32)<0){av_frame_free(&f);return false;}+ for(unsigned y=0;y<256;++y)for(unsigned x=0;x<256;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;p[0]=(x*7+y*3)%256;p[1]=(x*3+y*11)%256;p[2]=(x*5+y*17)%256;p[3]=255;}+ sink::RgbaImage baseline;bool ok=true;int protectedError=0,outsideError=0;uint64_t changed=0;+ for(unsigned mode=0;mode<4&&ok;++mode){+ engine::EnhancementSettings settings;settings.protection.enabled=mode>0;settings.protection.featherPixels=0;+ if(mode==2)settings.protection.regions[0]={0,0,1,1};+ if(mode==3)settings.protection.regions[0]={.25f,.25f,.75f,.75f};+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage result;+ ok=graph.applySettings(settings)&&graph.process(f,0,true,out,mode+1)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result);+ if(ok){if(!mode)baseline=result;+ for(unsigned y=0;y<256;++y)for(unsigned x=0;x<256;++x)for(unsigned c=0;c<3;++c){auto i=(size_t(y)*256+x)*4+c;auto original=f->data[0][size_t(y)*f->linesize[0]+x*4+c];+ if(!mode){changed+=result.pixels[i]!=original;continue;}+ bool protectedPixel=mode==2||(mode==3&&x>=64&&x<192&&y>=64&&y<192);+ if(protectedPixel)protectedError=std::max(protectedError,std::abs(int(result.pixels[i])-int(original)));+ else outsideError=std::max(outsideError,std::abs(int(result.pixels[i])-int(baseline.pixels[i])));+ }+ }out={};+ }+ ok=ok&&changed>100&&protectedError<=1&&outsideError==0&&graph.metrics().nrEvaluateCount==4;+ std::cout<<"PROTECTION_PIXELS empty/full/rectangle changed="<<changed<<" protectedError8="<<protectedError<<" outsideError8="<<outsideError<<" nr="<<graph.metrics().nrEvaluateCount<<" pass="<<ok<<std::endl;+ ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();return ok;+}int wmain(int argc,wchar_t** argv){if(argc!=2)return 2;CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::path directory(argv[1]);std::filesystem::create_directories(directory);bool ok=true;for(auto e:{pipeline::Extent{1,1},{257,513},{97,9001},{4097,257},{257,4097}}){if(!run(e.width,e.height,false,directory)){ok=false;break;}}@@ -167,5 +198,7 @@ int wmain(int argc,wchar_t** argv){if(ok)ok=srPixels(256,128,256,256,directory);if(ok)ok=srPixels(256,256,256,256,directory);if(ok)ok=captureRgb(false)&&captureRgb(true);+ if(ok)ok=protectionPixels();+ if(ok)ok=tiled(2561,2561,true,directory,true);CoUninitialize();return ok?0:1;}diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex 46ce5586..d135db0e 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -1,8 +1,12 @@#include "veyra/engine/PresetStore.h"#include <iostream>#include <fstream>-int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;+int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;ok=ok&&a.put(L"test",s)&&a.setDefault(0)&&!a.put(L"test",s);PresetStore b(p);ok=ok&&b.load()&&b.defaultSettings()==s&&b.rename(0,L"renamed")&&b.defaultSettings()==s;auto invalid=s;invalid.model.tone=9;ok=ok&&!b.put(L"bad",invalid)&&b.entries().size()==1&&b.erase(0)&&b.entries().empty();+ auto badRegion=s;badRegion.protection.regions[0].left=2;ok=ok&&!b.put(L"invalid region",badRegion);+ {std::ofstream legacy(p);legacy<<"VEYRA_PRESETS 1\n\"legacy\" 1\n\"legacy\" 1 1 1 -1 0 0 0 1 1 1 1 1 1 0 1 0 1 0\n";}+ PresetStore old(p);ok=ok&&old.load()&&!old.defaultSettings().protection.enabled&&old.put(L"v2",s);+ PresetStore upgraded(p);ok=ok&&upgraded.load()&&upgraded.entries().size()==2&&upgraded.entries()[1].settings==s;{std::ofstream f(p);f<<"VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";}PresetStore c(p);ok=ok&&!c.load()&&!c.put(L"override",{});std::ifstream f(p);std::string data((std::istreambuf_iterator<char>(f)),{});ok=ok&&data=="VEYRA_PRESETS 99\ncorrupt mediaPath executable must reject";std::cout<<"preset roundtrip, all fields, duplicate, rename-default, delete, validation, unknown schema, corrupt-preservation="<<ok<<'\n';return ok?0:1;}