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 tiled image processing and professional preview zoom
Veyra Goal Agent3b2806b14aef
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 8d371c23..9f26921c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -142,6 +142,7 @@ endif()# YUV→RGB shader is shared between the media pipeline and the harness.veyra_add_compute_shader(veyra_shader_yuv_to_rgb YuvToLinearRgb)+veyra_add_compute_shader(veyra_shader_rgb_to_linear RgbToLinear)# ScaleBlit: working frame -> swapchain backbuffer (Phase 6 present path).veyra_add_compute_shader(veyra_shader_scale_blit ScaleBlit)# Nv12Upload: byte buffer -> luma/chroma planes (copy-free upload path).@@ -311,7 +312,7 @@ if(TARGET veyra_ngx AND TARGET veyra_nvof AND VEYRA_FFMPEG_ROOT)target_include_directories(veyra_pipeline PRIVATE ${FFMPEG_INCLUDE_DIRS})target_link_libraries(veyra_pipeline PRIVATE veyra_ngx veyra_nvof ${FFMPEG_LIBRARIES})add_dependencies(veyra_pipeline- veyra_shader_yuv_to_rgb veyra_shader_parity_encode+ veyra_shader_yuv_to_rgb veyra_shader_rgb_to_linear veyra_shader_parity_encodeveyra_shader_parity_decode veyra_shader_scale_blitveyra_shader_nv12_upload veyra_shader_nvof_densify)endif()@@ -416,6 +417,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_include_directories(veyra_repair_contract_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)add_executable(veyra_repair_parameter_tests tests/integration/RepairParameterTests.cpp)+ add_executable(veyra_image_dimension_tests tests/integration/ImageDimensionTests.cpp)+ target_compile_features(veyra_image_dimension_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_image_dimension_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_compile_definitions(veyra_image_dimension_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")+ target_link_libraries(veyra_image_dimension_tests PRIVATE veyra_engine)target_compile_features(veyra_repair_parameter_tests PRIVATE cxx_std_20)target_include_directories(veyra_repair_parameter_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})target_compile_definitions(veyra_repair_parameter_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")@@ -430,7 +436,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp)+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp)target_compile_features(veyra_engine PUBLIC cxx_std_20)target_compile_options(veyra_engine PRIVATE /utf-8)target_compile_definitions(veyra_engine PUBLIC VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}" VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 46586779..b23b0fac 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -60,17 +60,30 @@ void pointerActivity(){if(!full)return;pointerTick=GetTickCount64();if(!fullContstd::wstring currentFile,autoInput;bool paused=false,dragging=false,closing=false;int smokeSeconds=0;ULONGLONG startTick=0;int resultCode=0;std::wstring exportOutput;unsigned exportFrames=0;unsigned cancelAfterMs=0;bool exportHevc=false;veyra::engine::PlayerOptions initialOptions;std::vector<veyra::engine::SubtitleCue> subtitles;HWND subtitleLabel=nullptr;-HFONT font=nullptr,emptyFont=nullptr;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;+HFONT font=nullptr,emptyFont=nullptr;bool smokeZoom=false;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;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));}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&&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);+ if(PtInRect(&r,p)){auto extent=engine.snapshot().metrics.resolution.output;auto view=engine.previewView();+ view.wheel(float(GET_WHEEL_DELTA_WPARAM(w))/WHEEL_DELTA,float(p.x),float(p.y),float(r.right),float(r.bottom),float(extent.width),float(extent.height));engine.previewView(view);+ veyra::log::info("preview-view",std::format("zoom={} center={},{} presentation-only",view.zoom,view.centerX,view.centerY));return 0;}+ }+ if(m==WM_MBUTTONDOWN){panning=true;panPoint={GET_X_LPARAM(l),GET_Y_LPARAM(l)};SetCapture(h);return 0;}+ if(m==WM_MOUSEMOVE&&panning){POINT p{GET_X_LPARAM(l),GET_Y_LPARAM(l)};RECT r{};GetClientRect(h,&r);auto extent=engine.snapshot().metrics.resolution.output;auto view=engine.previewView();view.pan(float(p.x-panPoint.x),float(p.y-panPoint.y),float(r.right),float(r.bottom),float(extent.width),float(extent.height));engine.previewView(view);panPoint=p;return 0;}+ if(m==WM_RBUTTONUP){engine.previewView({});return 0;}+ }+ if(id==VideoSurface&&(m==WM_MBUTTONUP||m==WM_CAPTURECHANGED)){panning=false;if(m==WM_MBUTTONUP&&GetCapture()==h)ReleaseCapture();}if(id==VideoSurface&&m==WM_SETCURSOR&&full&&!fullControls){SetCursor(nullptr);return TRUE;}if(id==VideoSurface&&m==WM_ERASEBKGND)return 1;if(id==VideoSurface&&m==WM_PAINT){veyra::ui::PaintBuffer paint(h);veyra::ui::opaqueBlack(paint.dc,paint.rect);return 0;}if(id==OriginalHold){if(m==WM_LBUTTONDOWN){holdOriginal=true;SetCapture(h);updateComparison();return 0;}if(m==WM_LBUTTONUP||m==WM_CAPTURECHANGED){holdOriginal=false;if(GetCapture()==h)ReleaseCapture();updateComparison();return 0;}}- if(id==VideoSurface&&compareMode==2&&(m==WM_LBUTTONDOWN||m==WM_MOUSEMOVE)&&(m==WM_LBUTTONDOWN||(w&MK_LBUTTON))){if(m==WM_LBUTTONDOWN)SetCapture(h);RECT r{};GetClientRect(h,&r);auto extent=engine.snapshot().metrics.resolution.output;float contentWidth=float(r.right);if(extent.width&&extent.height)contentWidth=std::min(float(r.right),float(r.bottom)*extent.width/extent.height);float left=(r.right-contentWidth)/2;compareSplit=std::clamp((float(GET_X_LPARAM(l))-left)/std::max(1.0f,contentWidth),0.0f,1.0f);updateComparison();return 0;}+ if(id==VideoSurface&&compareMode==2&&(m==WM_LBUTTONDOWN||m==WM_MOUSEMOVE)&&(m==WM_LBUTTONDOWN||(w&MK_LBUTTON))){if(m==WM_LBUTTONDOWN)SetCapture(h);RECT r{};GetClientRect(h,&r);auto extent=engine.snapshot().metrics.resolution.output;auto view=engine.previewView();float contentWidth=float(r.right);if(extent.width&&extent.height)contentWidth=std::min(float(r.right),float(r.bottom)*extent.width/extent.height);contentWidth*=view.zoom;float left=r.right*.5f-contentWidth*view.centerX;compareSplit=std::clamp((float(GET_X_LPARAM(l))-left)/std::max(1.0f,contentWidth),0.0f,1.0f);updateComparison();return 0;}if(id==VideoSurface&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}return DefSubclassProc(h,m,w,l);}@@ -80,14 +93,14 @@ 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();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;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());}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(){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;uiState.preferredComparison=compareMode;compareMode=0;holdOriginal=false;if(GetCapture())ReleaseCapture();}+ else{uiState.mode=veyra::ui::Mode::Daily;engine.previewView({});uiState.preferredComparison=compareMode;compareMode=0;holdOriginal=false;if(GetCapture())ReleaseCapture();}updateComparison();if(auto focused=GetFocus();focused&&IsChild(inspector,focused))SetFocus(GetDlgItem(mainWindow,ModeSwitch));SetWindowTextW(GetDlgItem(mainWindow,ModeSwitch),uiState.mode==veyra::ui::Mode::Daily?L"专业模式":L"返回日常模式");transition.start(uiState.mode==veyra::ui::Mode::Professional,GetTickCount64());if(full)endTransition();else{SetPropW(video,L"Veyra.ResizeDeferUntil",HANDLE(uintptr_t(GetTickCount64()+390)));SetTimer(mainWindow,2,16,nullptr);}layout();veyra::log::info("ui-transition",std::format("started target={} durationMs=240 from={}",uiState.mode==veyra::ui::Mode::Professional,transition.from));const auto after=engine.snapshot();veyra::log::info("ui-mode",std::format("professional={} hostSame={} sessionSame={} revisionSame={} positionBefore={} positionAfter={} commandMs={:.3f}",uiState.mode==veyra::ui::Mode::Professional,host==video,before.sessionId==after.sessionId,before.desired.revision==after.desired.revision,before.position,after.position,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()));}@@ -198,7 +211,7 @@ veyra::ui::icon(GetDlgItem(hwnd,Recent),Icon::Recent);veyra::ui::icon(GetDlgItemfor(int id:{Open,Capture,Recent,Master,Sr,ModeSwitch,WindowMin,WindowMax,WindowClose,Stop,Mute,Subtitle,Fullscreen,ProRailVideo,ProRailCapture,ImageOpen,Info})veyra::ui::ghost(GetDlgItem(hwnd,id));SetPropW(GetDlgItem(hwnd,Open),L"veyra.tip",HANDLE(L"打开视频 / 图片 · Ctrl+O"));SetPropW(GetDlgItem(hwnd,Capture),L"veyra.tip",HANDLE(L"连接采集卡"));SetPropW(GetDlgItem(hwnd,Sr),L"veyra.tip",HANDLE(L"DLSS 超分辨率 · 按比例提升,最高 3840×2160"));inspector=veyra::ui::createSettingsPanel(hwnd,engine,applySettings);selectInspector(uiPreferences.inspector);refreshDailyPresets();SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,LPARAM(uiPreferences.volume*100));veyra::ui::marked(GetDlgItem(hwnd,Play));-tooltips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,0,0,0,0,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);SendMessageW(tooltips,TTM_SETMAXTIPWIDTH,0,360);EnumChildWindows(hwnd,[](HWND child,LPARAM context)->BOOL{auto tip=reinterpret_cast<HWND>(context);wchar_t cls[32]{};GetClassNameW(child,cls,32);if(_wcsicmp(cls,L"BUTTON")==0||_wcsicmp(cls,L"EDIT")==0||_wcsicmp(cls,L"COMBOBOX")==0){TOOLINFOW info{sizeof(info)};info.uFlags=TTF_IDISHWND|TTF_SUBCLASS;info.hwnd=GetAncestor(child,GA_ROOT);info.uId=UINT_PTR(child);info.lpszText=LPSTR_TEXTCALLBACKW;SendMessageW(tip,TTM_ADDTOOLW,0,LPARAM(&info));}return TRUE;},LPARAM(tooltips));+SetPropW(video,L"veyra.tip",HANDLE(L"专业模式:滚轮缩放 · 中键拖动画面 · 右键恢复适应窗口。缩放不影响增强或保存尺寸。"));tooltips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,0,0,0,0,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);SendMessageW(tooltips,TTM_SETMAXTIPWIDTH,0,360);EnumChildWindows(hwnd,[](HWND child,LPARAM context)->BOOL{auto tip=reinterpret_cast<HWND>(context);wchar_t cls[32]{};GetClassNameW(child,cls,32);if(child==video||_wcsicmp(cls,L"BUTTON")==0||_wcsicmp(cls,L"EDIT")==0||_wcsicmp(cls,L"COMBOBOX")==0){TOOLINFOW info{sizeof(info)};info.uFlags=TTF_IDISHWND|TTF_SUBCLASS;info.hwnd=GetAncestor(child,GA_ROOT);info.uId=UINT_PTR(child);info.lpszText=LPSTR_TEXTCALLBACKW;SendMessageW(tip,TTM_ADDTOOLW,0,LPARAM(&info));}return TRUE;},LPARAM(tooltips));if(smokeSeconds>0)startTick=GetTickCount64();diagnosticPanel=veyra::ui::createTelemetryPanel(hwnd,engine);DragAcceptFiles(hwnd,TRUE);SetTimer(hwnd,1,100,nullptr);layout();return 0;}case WM_NCCALCSIZE:if(wp)return 0;break;case WM_NCACTIVATE:return DefWindowProcW(hwnd,msg,wp,-1);@@ -275,8 +288,14 @@ if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}if(smokeStep==1&&elapsed>2600){engine.seek(1.0);smokeStep=2;}if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}+if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);+if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;+ if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2));zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}+ if(zoomStep==1&&elapsed>3000){const bool same=s.sessionId==zoomBefore.sessionId&&s.applied.revision==zoomBefore.applied.revision&&s.metrics.resolution.output==zoomBefore.metrics.resolution.output&&(!s.image||s.nrEvaluated==zoomBefore.nrEvaluated);SendMessageW(video,WM_MBUTTONDOWN,MK_MBUTTON,MAKELPARAM(100,100));SendMessageW(video,WM_MOUSEMOVE,MK_MBUTTON,MAKELPARAM(130,110));SendMessageW(video,WM_MBUTTONUP,0,MAKELPARAM(130,110));zoomStep=same?2:-1;}+ if(zoomStep==2&&elapsed>6200){SendMessageW(video,WM_RBUTTONUP,0,0);bool reset=engine.previewView()==veyra::engine::PreviewView{};switchMode();RECT r{};GetWindowRect(video,&r);SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),MAKELPARAM(r.left+10,r.top+10));bool daily=engine.previewView()==veyra::engine::PreviewView{};switchMode();zoomStep=reset&&daily?3:-1;veyra::log::info("preview-test",std::format("pass={} unchangedSession={} unchangedRevision={} source={}x{} NR={} presentation-only zoom/pan/reset/daily",zoomStep==3,s.sessionId==zoomBefore.sessionId,s.applied.revision==zoomBefore.applied.revision,s.metrics.resolution.output.width,s.metrics.resolution.output.height,s.nrEvaluated));}+}if(compareMode||holdOriginal)text+=L"\r\n真实帧对比:两侧同一源帧;此模式不展示生成帧。";const auto problem=veyra::Logger::instance().latestProblem();if(!problem.empty()){int n=MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),nullptr,0);std::wstring detail(n,0);MultiByteToWideChar(CP_UTF8,0,problem.data(),int(problem.size()),detail.data(),n);text+=L"\r\n最近问题:"+detail.substr(0,100)+L"(详见诊断)";}veyra::ui::setText(statusBar,text);@@ -326,7 +345,7 @@ 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&&(!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(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;}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);}@@ -338,7 +357,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-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-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());@@ -349,5 +368,6 @@ wchar_t focusedClass[32]{};GetClassNameW(GetFocus(),focusedClass,32);const boolif(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='O'){SendMessageW(hwnd,WM_COMMAND,Open,0);continue;}if(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='E'){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(3);continue;}const bool key=(!editing)&&(msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||(msg.wParam==VK_SPACE&&(GetFocus()==hwnd||GetFocus()==video))||msg.wParam=='V'||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN));if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}+if(msg.message==WM_MOUSEWHEEL&&uiState.mode==veyra::ui::Mode::Professional&&GetAncestor(msg.hwnd,GA_ROOT)==hwnd){POINT p{GET_X_LPARAM(msg.lParam),GET_Y_LPARAM(msg.lParam)};if(WindowFromPoint(p)==video){SendMessageW(video,msg.message,msg.wParam,msg.lParam);continue;}}if(IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);}diff --git a/docs/ARCHITECTURE_AUDIT_2026-09-08.md b/docs/ARCHITECTURE_AUDIT_2026-09-08.mdnew file mode 100644index 00000000..b7495338--- /dev/null+++ b/docs/ARCHITECTURE_AUDIT_2026-09-08.md@@ -0,0 +1,168 @@+# 原始方案与当前架构对照审计++日期:2026-09-08。审计基线:本地 `f79ef95deb2dc0375e7a2adb936e7d4d4298f93a`。++> 后续决定与调研更新:用户要求导出完整性检查保持现状,不增加正常使用负担;下文第 6 节扩大每次导出检查的建议不再执行。深度、C 帧与新后端按实测收益重新排序,具体见 [画质、4K 超分与帧生成优化方案](QUALITY_OPTIMIZATION_PLAN_2026-09-08.md)。本审计保留原始差距记录,不把尚未实现的内容改写成已经完成。++## 1. 结论与证据边界++当前已经有真实的三入口和共享 GPU 增强主干:播放、采集、图片处理和视频导出复用 `pipeline::EnhanceGraph`,其中包含实际的 NVOF、SR、NR、parity、残差合成和 FG 调用。视频导出使用真实 D3D12 NVENC。不能把当前工程说成只有 UI 或接口壳。++但它还不是原方案完整落地的架构。主要差距在于:完整帧数据契约没有贯通;Guidance 仍内嵌在增强图中,质量验证只实现了基础 cost 门控;没有真实深度推理、C 帧验证或离线双向质量分支;产品播放与导出主动关闭硬解;字幕、导出格式和完整性验证仍比原定范围窄。++本次是源码与方案对照,不是新一轮运行验收。未修改应用源码,未构建,未执行 RTX / NGX Create/Evaluate、实卡或性能测试。下文“存在实现”不等于当前全部组合已经运行通过;静态推导的问题也不冒充已测得的视觉或延迟结果。整体状态保持 `Phase 7 / needs_review`。++## 2. 对照依据与已经批准的调整++原始基线:++- [产品规范](../VEYRA_PRODUCT_SPEC_V1.md):三模式产品范围、帧与 Guidance 契约、完整质量链。+- [施工手册](../VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md):共享引擎、颜色解析、质量验证、深度、硬解、NVENC、字幕和门禁的具体要求。+- [项目规则](../AGENTS.md)、[竞品审计](COMPETITOR_AUDIT_2026-09-03.md)、[README](../README.md) 与 [工作记录](WORKLOG.md):边界与当前状态。++以下是后续明确接受的变化,不能当成擅自偏离:++| 调整 | 当前应采用的解释 | 依据 |+|---|---|---|+| 默认实时 NR 允许约 1080p 内部处理 | 保留高分辨率底图,NR 变化回填;原生 NR 可选,视频导出保持原生处理要求。不能把实时档称为 native 4K NR | AGENTS 顶部修订;[修复方案 §3.2–3.5](REPAIR_EXECUTION_PLAN_2026-09-07.md) |+| 光流提前到源空间 | 原方案 post-SR 光流已改为 source-space NVOF,再分别适配 NR / SR / FG 的分辨率与向量尺度 | 修复方案 §3.3–3.4 |+| 深度可暂缺 | 接管计划允许 Motion Only;修复方案明确“新接深度模型不属于本次任务”。它仍是原完整方案未实现项,不能说这轮修复删掉了已经存在的模型 | [接管计划 F2](ACTIVE_DELIVERY_PLAN.md)、修复方案第 139 行 |+| 日常 / 专业 UI、后台导出进程 | 取代原三标签页;模式切换复用前台会话,独立本地进程调用共享导出库 | [双模式方案 §5–7](UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md),第 295 行 |+| 原生 DirectShow 与采集音频链 | avdevice 缺失时允许原生 DirectShow;后续 UI 方案接受控制现有 DirectShow 音频 graph 的音量 | 接管计划 F5;双模式方案第 284 行 |+| FG 3X / 4X | 是后续扩大范围,不能以原 V1 只承诺 2X 为由撤掉 | 修复方案 §3.4、帧批次与输出合同 |+| 短测与实卡验收 | 每次测试最多 300 秒,累计不限于 300 秒;当前实卡体验由用户验收。旧 30 分钟 / 默认原生 4K60 门槛不应重新强加 | AGENTS、接管计划、用户后续澄清 |+| 失败 / 取消保留 partial | 后续 UI 方案允许保留以诊断;这与原先清理策略不同,但不是未授权更改。保留文件不等于有崩溃恢复功能 | 双模式方案 §7 |++## 3. 原方案与当前实际调用链++原方案的核心结构是:++```text+FrameSource+ → 完整 FramePacket(有理 PTS、时长、颜色、epoch、GPU 所有权)+ → 统一线性工作纹理+ → 可选 SR+ → FrameWindow + GuidanceProvider+ NVOF + 多信号 confidence + 可选深度与时间稳定+ A/B 实时;可选 C 验证;导出双向 / 未来帧验证+ → parity encode → NR → parity decode → FG+ → 字幕 / OSD → FrameSink+```++当前产品的实际结构如下。光流提前、NR 分辨率拆分与残差回填是后续批准的设计:++```mermaid+flowchart TD+ UI[Win32 日常 / 专业界面] --> EC[EngineController 前台工作线程]+ EC --> FS[MediaFileSource / CaptureCardSource / WIC 图片]+ UI --> JOB[ExportJobManager 本地子进程]+ JOB --> VE[VideoExportJob + MediaFileSource]+ FS --> G[共享 pipeline::EnhanceGraph 实例]+ VE --> G+ G --> IN[AVFrame 输入与颜色转换]+ IN --> LIN[线性源图]+ LIN --> FLOW[源空间 NVOF A/B + cost 硬门控]+ FLOW --> ADAPT[FlowAdapt:NR / 底图尺度]+ LIN --> SR[可选 SR / 高分辨率底图]+ ADAPT --> SR+ SR --> NR[可选降采样 → parity → NR → parity 解码]+ ADAPT --> NR+ NR --> RES[NR 变化回填到底图]+ SR --> RES+ RES --> FG[SDR 输出转换 → 可选 FG 2X / 3X / 4X]+ ADAPT --> FG+ FG --> BATCH[FrameBatch:真实帧 / 生成帧、时间戳、资源租约]+ BATCH --> PRE[VideoPresenter + 播放字幕 / OSD]+ BATCH --> ENC[D3D12 NVENC → MP4 封装]+ BATCH --> IMG[真实帧纹理 → WIC 图片输出]+```++这里的“共享”是复用同一个产品类及其算法实现,不是前台与导出跨进程共用一个 GPU 对象。导出进程拥有自己的设备、图和资源,符合后续方案。++关键入口:[EngineController.cpp](../src/engine/EngineController.cpp) 第 66、83–86、155 行;[VideoExportJob.cpp](../src/engine/VideoExportJob.cpp) 第 23、30、82 行;[ExportJobManager.cpp](../src/engine/ExportJobManager.cpp);[实际增强图](../src/pipeline/EnhanceGraph.cpp) 第 589–1020 行。++## 4. 逐项对照++| 项目 | 原方案要求 | 当前实现与判定 |+|---|---|---|+| 平台与推理后端 | C++20 / Win32 / D3D12 / 直接 NGX;不依赖 ReShade | 产品主线符合。已有实际 Create/Evaluate 调用,不是只计数 |+| 三入口共享主干 | Source → Graph → Sink;核心算法不留在 probe | 已有真实共享图、前台控制器和导出库。输入 / 输出接口的统一程度仍不足 |+| 帧契约 | PTS、duration、color、source epoch、GPU 所有权贯通 | 类型已定义,但 graph 实际接收 AVFrame、double 毫秒、reset bool 和序号;颜色与来源 epoch 没随完整 packet 进入图 |+| Reset | 所有历史模块消费统一原因与 epoch | 图内部有实际 epoch / reset,seek、暂停恢复、drop 等已有处理;独立 ResetCoordinator 没有接入产品调用链,完整原因与源 epoch 契约未贯通 |+| 光流与 confidence | cost + 亮度残差 + 边界 / 遮挡;质量模式加双向验证;平滑降权 | 有真实 NVOF current→previous 和 /32 转换;只按 cost 硬阈值清零,不是完整质量链 |+| 深度 | 可选 DAV2 Small 推理、归一化、重投影、age / Auto 回退 | 没有模型推理 provider;NR 深度常量 0.5,FG 常量 0.9。后续修复范围明确暂不接模型 |+| A/B/C 与导出质量 | A/B 补帧;C 做质量验证;导出利用未来帧和双向信息 | A/B 补帧与帧批次已有;C 验证、离线双向质量分支缺失。导出预扫时间戳不是未来画面质量分析 |+| 硬解与场景分析 | D3D12VA 优先;GPU histogram / SAD / confidence 辅助切镜 | D3D12VA 后端存在,产品播放与导出设为 false。场景检测仅在软件输入分支采样,硬件输入分支没有对应的内容分析 |+| 实时 NR / SR / FG | 原始同 working extent,后续改为分辨率拆分与残差回填 | 后续结构已实现;SR、NR、FG 有真实路径。不能由此直接推断所有组合满足实时性能 |+| 采集 | 容量 1 mailbox、drop reset、有界 A/B(/C)、可靠时间与颜色 | 真实 DirectShow 和 mailbox 已有;packet 未填写 duration / colorInfo,存在调度数据问题。音频用后续接受的 DirectShow 链 |+| GPU 资源 | 轮转 slots、有界历史、按类型 / 尺寸的资源池、全图显存预算 | 有固定 command / real / generated / NVENC slots 和资源租约;没有产品级 QueryVideoMemoryInfo 预算与统一资源池准入 |+| 字幕 | 外置 SRT、首条内嵌文本字幕、libass 基础 ASS 样式;FG 后合成 | 播放外置 SRT 与后置覆盖存在;内嵌文本字幕 / ASS / libass 链未完成 |+| 视频导出 | D3D12 NVENC H.264 / HEVC,MP4 / MKV,remux / AAC,字幕策略 | D3D12 NVENC 与 MP4 是真实实现;目前固定 MP4,音频不兼容则拒绝,没有 AAC fallback;完整字幕处理缺失 |+| 导出验收与恢复 | 完整帧数 / 时长 / 音轨 / 首尾 / 非黑验证;失败恢复 | 产品导出完成后只重新打开并读到第一帧;专项测试曾有更广检查,但不等于每次导出都有完整验证。缺少重启后的任务恢复流程 |+| 质量诊断 | flow / depth / confidence 可视化、reset 原因、GPU pass 时间 | GPU 时间与比较显示已有;缺少完整 Guidance 可视化。quality_probe 自报 depth disabled,不能作为深度完成证明 |++## 5. 本次发现的具体问题++### 5.1 颜色的默认解释有两份,且并不一致++[MediaFileSource.cpp](../src/source/MediaFileSource.cpp) 第 71–90 行把缺失的矩阵按 SD→BT.601 / HD→BT.709 补全,把缺失 transfer 按 BT.709 补全,并记录 assumed 标记。++但 [EnhanceGraph.cpp](../src/pipeline/EnhanceGraph.cpp) 第 694、742–744 行直接重新读取 AVFrame:未显式标为 BT.601 的矩阵走 BT.709;未显式标为 BT.709 / SMPTE170M 的 transfer 走 sRGB。调用处没有把 packet.colorInfo 传入图。++因此,对缺少标签的素材,源层记录的解释和实际 shader 使用的解释可以不同。这是已定位的静态逻辑差异;本次未用测试片量化色差。优先修复方式是让解析后的 ColorDescription 成为后续所有转换的唯一依据。++此外,当前软件入口会先把 RGB 图片 / 采集帧转成 NV12,再进入线性纹理;这使 RGB 输入经历额外的 4:2:0 色度采样。原计划的直接 RGB→linear 入口仍应补齐;具体画质损失需要有针对性的图案验证。++### 5.2 采集时长缺失,FG 调度使用错误的默认值++[CaptureCardSource.cpp](../src/source/CaptureCardSource.cpp) 第 134 行 `packet={}` 后只填 PTS、来源、序号、flags 和 epoch,没有填 duration。++[FramePacket.h](../include/veyra/pipeline/FramePacket.h) 第 17–19 行的 Rational 默认值是 `0/1, known=true`。它不是 unknown。++[EngineController.cpp](../src/engine/EngineController.cpp) 第 168–170 行把这个零时长 clamp 到 `83333` 个 100ns 单位,即约 **8.33ms**,并用于采集开启 FG 时的时间线 lookahead 参数。50fps / 60fps 的真实帧周期应分别约为 20ms / 16.67ms。++这证明当前配置给调度器的时长不正确,不能据此声称实测端到端延迟等于 8.33ms,也不能据此计算一个确定的可见卡顿量。修复应从实际采集格式 / PTS 明确得到 duration,并正确区分零值与未知值。++### 5.3 现有 confidence 并没有完成原定的质量验证++[NvofDensify.hlsl](../shaders/NvofDensify.hlsl) 第 44–48 行计算 `1-cost/255`;超过阈值直接清零 motion,低于阈值保留原向量。图中使用阈值 32。[FlowAdapt.hlsl](../shaders/FlowAdapt.hlsl) 只做重采样和尺度适配,没有根据连续 confidence 平滑衰减 motion。++目前没有亮度重投影残差、出界 / 遮挡验证、双向一致性或深度残差验证。这不是“已经有 confidence 纹理,所以完整 confidence 链也完成”。原手册第 186–187 行明确要求多信号验证与平滑衰减。++加入深度模型不会自动补齐这些问题;低质量光流和不可靠的深度都需要被正确拒绝。++### 5.4 硬解接口存在,但实际产品没有启用++[EngineController.cpp](../src/engine/EngineController.cpp) 第 85 行和 [VideoExportJob.cpp](../src/engine/VideoExportJob.cpp) 第 30 行都明确设置 `preferHardwareDecode=false`。因此当前这两个入口的解码在 CPU 上,随后上传到 GPU;不能把 GPU 增强 / GPU 编码等同于硬件解码已经接通。++[EnhanceGraph.cpp](../src/pipeline/EnhanceGraph.cpp) 第 688–736 行的场景分析只在软件分支执行,当前使用 CPU 小图与直方图;D3D12 输入分支没有同等内容分析。启用硬解前应先补上或迁移场景分析,否则可能丢掉当前软件路径具备的切镜信号。这是静态覆盖缺口,本次没有触发新的硬件播放故障。++### 5.5 同名旧接口仍可能让测试结果被误读++[CMakeLists.txt](../CMakeLists.txt) 第 180 行把旧 [core/EnhanceGraph.cpp](../src/core/EnhanceGraph.cpp) 编入合同测试;第 310 行才把真实 [pipeline/EnhanceGraph.cpp](../src/pipeline/EnhanceGraph.cpp) 接入产品 pipeline。++旧 core 版本只是复制 packet / 更新计数;真实产品图有实际 GPU / NGX 实现。工程中还存在 core / pipeline 两套 FramePacket、FrameWindow 等概念,IGuidanceProvider 的实现目标当前只有 ZeroGuidanceProvider。++所以既不能拿旧 core 壳宣称产品没有实现,也不能拿这个合同测试通过证明真实产品链已通过。后续应明确隔离旧测试模型,贯通产品接口,并让集成测试覆盖实际入口。++## 6. 应如何收敛架构++不需要推翻现有播放器。应保留已经落地的共享 GPU passes、NGX / NVOF 适配、FrameBatch 资源租约、NVENC 和前端会话,围绕原始质量目标补齐数据与验证链。++建议按依赖关系执行:++1. **先贯通帧契约。** 让 Source、Graph、调度器消费一致的 duration、colorInfo、PTS、source epoch / reset reason;先修采集时长和缺省颜色。RGB 入口避免不必要的 NV12 中转。+2. **补齐 motion 的可信度验证。** cost + luma warp residual + 边界 / 遮挡,形成平滑 trust;将场景分析放到两种解码路径都能使用的位置,再接通并验证 D3D12VA。+3. **接入原定可选深度 provider。** 模型身份、GPU 推理、归一化、时间重投影、age 与 Auto 回退必须一起落地。通过对照验证后再决定哪些内容启用,不能以“模型有输出”当作画质提升。+4. **建立 C / 离线质量分支。** 有界 FrameWindow、双向一致性与未来帧验证;证明收益和延迟代价后决定默认值,保留低延迟 A/B。+5. **补齐产品边界与资源准入。** MKV / AAC / 字幕策略、每次导出的完整验证与任务恢复,以及前台与导出并行时的显存预算。++下一条唯一建议任务:**贯通真实产品的 FramePacket,先修正采集 duration 与颜色元数据的唯一解释。** 本次仅完成审计,没有自动启动这项改造。++## 7. 检查记录与剩余门槛++- 实际执行了 `git status --short`、`git rev-parse HEAD`、`rg --files`、`rg -n` 与 `Get-Content`,核对上述方案、源文件、CMake 目标和产品调用点。开始审计时工作树干净。+- 只新增本报告并在 WORKLOG 记录审计;应用源码、EXE、配置、保护门禁、runtime 和 SDK 未改。+- 本次没有构建 / 自动功能测试,没有新增 Create/Evaluate 返回码或 RTX 实测日志;也没有运行实卡。+- README 记录的统一 delivery 门禁差异仍待解决;历史专项通过不能替代当前完整门禁。当前版本实卡体验仍待用户验收。+- 原始完整产品范围中尚未完成的项目,不能通过只更新文档或增加接口类型宣布完成。当前阶段继续保持 `Phase 7 / needs_review`。diff --git a/docs/QUALITY_OPTIMIZATION_PLAN_2026-09-08.md b/docs/QUALITY_OPTIMIZATION_PLAN_2026-09-08.mdnew file mode 100644index 00000000..9d13e8ee--- /dev/null+++ b/docs/QUALITY_OPTIMIZATION_PLAN_2026-09-08.md@@ -0,0 +1,264 @@+# Veyra 画质、4K 超分与帧生成优化方案++日期:2026-09-08。代码基线:`f79ef95deb2dc0375e7a2adb936e7d4d4298f93a`。这是调研与优化方案,尚未修改产品实现。++## 1. 决策与范围++**值得继续优化,但不能承诺仅靠视频画面达到游戏原生接入的全部效果。优先级是:输入颜色与时序正确 → SR 参数正确 → 可靠运动与 UI 保护 → 对比视频专用超分 → FG 质量调优。深度模型先做收益验证,不作为默认新增负担。**++本次采用用户的最新决定:**导出完整性检查保持现状**。不增加每次导出后的全片解码、逐帧检查、音轨扫描或常驻分析任务。下文测试均为开发阶段的独立短测,不进入正常播放或导出流程。++继续保留已有决定:++- Windows / C++20 / Win32 / D3D12,直接 NGX;三个入口复用现有 `EnhanceGraph`,不更换整套引擎。+- 默认实时档允许约 1080p NR 内部处理与高分辨率残差回填;原生 NR 可选,视频导出维持原生处理要求。界面如实区分“4K 输出”和“原生 4K NR”。+- 保留 DLSS SR、实际 DLSSG 2X / 3X / 4X、采集、播放和导出;新增候选方案先独立比较,不强行替换。+- 每次测试最多 300 秒,累计测试不限于 300 秒;实卡延迟与体验仍由用户验收。++本方案综合了[原始架构审计](ARCHITECTURE_AUDIT_2026-09-08.md)、[接管计划](ACTIVE_DELIVERY_PLAN.md)、[修复方案](REPAIR_EXECUTION_PLAN_2026-09-07.md)、[原施工手册](../VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md)与当前公开资料。架构审计中“扩大每次导出的完整性验证”的建议由本次决定替代;深度接入也调整为先验证收益。++## 2. 为什么视频后处理与游戏内效果不同++需要分清三种技术:NR 改变画面的材质与光照表现;SR 重建更高分辨率画面;FG 生成中间时刻的画面。NR 输出尺寸是 4K,不能单独证明超分质量;FG 显示帧率提高,也不能单独证明运动正确。++NVIDIA 9 月 1 日研究页面把 DLSS5 的推理条件列为当前渲染画面、引擎运动向量、延续的时序状态和艺术控制值;渲染器场景属性还用于训练监督。因此,**不能把“缺少深度图”直接认定为 NR 效果差的主因,也不能把训练数据与运行时必需输入混为一谈**。[NVIDIA 研究说明](https://research.nvidia.com/labs/adlr/DLSS5/)++对 Veyra 的工程判断如下,属于据上述机制和当前代码作出的推论:++| 差异 | 对效果的影响 | Veyra 能做什么 |+|---|---|---|+| 视频 / HDMI 已经合成完毕 | UI、字幕、抗锯齿、动态模糊、压缩损失可能已写入像素 | 减少后续颜色损失;保护已知 UI 区域;不能假装拥有独立原始图层 |+| 光流来自图像估计 | 遮挡、重复纹理、粒子、镜头切换容易产生错误对应 | 双向一致性、出界与亮度残差检查,坏区域回退 |+| 没有引擎真实 jitter / 深度 / 相机状态 | SR / FG 的部分指导信息只能近似 | 明确接口单位与回退;比较更适合普通视频的算法 |+| 游戏有艺术控制与特定内容适配 | 同一个全局“强度最大”不适合所有素材 | 分开调节结构、明暗和总变化;制作经过对照的内容预设 |+| 当前使用固定实验 Feature 18 | 可调用和有输出不证明与官方游戏模型、配置及接入位置相同 | 固定 DLL 身份,针对当前输出优化,不承诺官方游戏等价 |++游戏内接入的价值可以从 Odyssey 项目看得更具体:它在 TAA 路径取得颜色、游戏运动向量、深度与 jitter,再把 NR 放在后续游戏处理和 UI 之前。这些条件不能从采集卡最终画面原样恢复。[Odyssey DLAA / NR 接入说明](https://github.com/SAOG0721/Assassins-Creed-Odyssey-DLAA/blob/e8e46e43e0bde6c47e60d80aaef78f7ea364b380/README.md)++本次检查的 NVIDIA/DLSS 与 NVIDIA-RTX/Streamline 公开主分支包含 SR / FG 等接口资料,未找到与本机 Feature 18 匹配、可直接替换现有私有参数路径的公开 NR 接口文档。这个结论限定于本次检查的公开树,不代表 NVIDIA 内部接口不存在。[DLSS SDK 快照](https://github.com/NVIDIA/DLSS/tree/a291cc7d2cc642a51566f3dfd5376f635cd1b284)、[Streamline 快照](https://github.com/NVIDIA-RTX/Streamline/tree/e8aaa6eaac968711fb62473d4ae8256dde20919b)++## 3. 类似项目实际采用的方式++以下区分“源码 / 作者实验表明了什么”和“在本机已经验证了什么”。本次没有运行这些项目的二进制,也没有复现它们的整体性能或画质宣传。++| 项目与本次固定版本 | 实际方式与证据 | 对 Veyra 的价值与限制 |+|---|---|---|+| [Magpie Experimental](https://github.com/SAOG0721/Magpie/tree/ac1cc8b0f2efc78323898395cc1336bcbecdc276),9 月 7 日 | 共享 Guidance;NVOF 前后向估计及 cost / 回投误差置信度;实验 SR、NR 与 FG。当前深度实际来自 ZeroDepth | 优先借鉴运动验证、分辨率适配和调度。**最新源码没有运行 DAV2 深度模型**,不能继续用旧版本描述当前架构 |+| [DLSS5-Reshade-AIO 私有接口实验](https://github.com/kibblerz/DLSS5-Reshade-AIO/blob/5112b4f5ed5ed0865cb56709ece751ce53c039f1/lab/PRIVATE-CONTRACT-FINDINGS.md),9 月 7 日 | 作者对 310.8 包进行像素实验,发现 `ControlMask` 与 `UIAlpha + Backbuffer` 可分别控制 NR 作用区域与 UI 保护 | 是当前 UI 问题的重要线索;资源格式、极性和效果仍须在 Veyra 固定 hash 上复验,不能只搬参数名 |+| [DLSS5-Feeder](https://github.com/jlrouzies-fr/DLSS5-Feeder/blob/d69d9174ef055f95a657750db814c93ac1ad6c1d/README.md),9 月 5 日 | ReShade 场景深度与估算运动,D3D12 同设备路径;合成 DLAA / SR 输入。普通 Present 路径的 UI 仍随场景一起处理 | 可研究资源共享。合成 jitter 的 SR 是实验,不是恢复游戏原始采样;README 明确 UI 分离仍有缺口 |+| [video2dlssnr](https://github.com/DaniilSokolyuk/video2dlssnr/tree/55a4ceb588a419b9b56497aa0b563d0c9e2b6c77),9 月 3 日 | 存在直接 SR / NR、光流相关实现;图片 SR 路径可对同一源图做多次偏移采样与积累 | 可比较 SR 参数和图片实验。重复重采样不产生新的真实视频细节;本次未发现明确许可证,不复用代码 |+| [2600th/dlss5-video-player](https://github.com/2600th/dlss5-video-player/tree/335ddc4523e3614e6dfc507c7d271b8fe0c71ebb),9 月 3 日 | FFmpeg / D3D12、估算时序指导和深度代理,构造 DLSS 类资源供拦截;架构文档标明 FG 不可用 | 不能作为“已解决高质量 FG”的证据;代理深度也不等于真实几何 |+| [dlss5-infinity-studio](https://github.com/SamG-Coder/dlss5-infinity-studio/blob/4e936b4c3df4a448a86e197396913491354ba312/README.md),9 月 1 日 | DAV2 / DirectML 深度、Streamline 与离线导出;README 同时列出零运动和切镜 reset 缺口 | **有深度模型不代表完整的时序质量链**;不因此给 Veyra 强接 Streamline 或每帧深度 |+| [dlss5-visual-enhancer](https://github.com/Merserk/dlss5-visual-enhancer/blob/3ad3da9c259636f80b5681088d711de470c895f7/README.md),9 月 7 日 | Gradio / 原生 worker;README 宣称多种 FG 目标与分段实时处理;实时缓冲配置为 2–30 秒,默认 6 秒 | 可以参考离线工作流;秒级缓冲不适合 Veyra 采集卡低延迟目标。目标 FPS 选项不证明每档都是单次原生 FG |+| [mpv 官方视频滤镜](https://github.com/mpv-player/mpv/blob/master/DOCS/man/vf.rst),9 月 8 日查阅 | `d3d11vpp` 已有 NVIDIA RTX Super Resolution 扩展入口,受设备与驱动条件影响 | 视频专用 SR 已有实际播放器接入路线;Veyra 优先研究 SDK 的 D3D12 路径,避免为此重写成 D3D11 播放器 |+| [Video2X](https://github.com/k4yt3x/video2x/tree/7db9c18d6278bbad9c3eda0e4e4ae210f9a688eb)、[RIFE 原作者项目](https://github.com/hzwer/ECCV2022-RIFE) | 面向普通视频的超分与插帧路线;Video2X 可选 Real-ESRGAN / Real-CUGAN / RIFE 等 | 适合作为离线质量参照;不能由低分辨率演示推断本机 4K 实时性能,也不把整套模型与 Python 环境塞入默认软件 |++**对旧竞品文档的更正:**[9 月 3 日竞品审计](COMPETITOR_AUDIT_2026-09-03.md)中 Magpie 的 DAV2 路径属于历史版本。本次读取的 `FrameGuidanceService::_Produce` 绑定的是 `zeroDepth.depth`;历史深度 provider 在后续整合提交中被移除。这里只能证明架构改变,不能反推作者已经证明“深度无用”。[当前 Guidance 源码](https://github.com/SAOG0721/Magpie/blob/ac1cc8b0f2efc78323898395cc1336bcbecdc276/src/Magpie.Core/FrameGuidanceService.cpp)、[整合提交](https://github.com/SAOG0721/Magpie/commit/1cde1baedab4d15934720ece4513b6a3fcc7de57)++还查阅了教程与社区问题。教程会建议打开 UI correction,社区也有开启后 UI 仍异常的反馈;两者都不足以证明当前 Veyra 的开关有效。因此下面的结论以本地接线和像素实验为依据。[Igor'sLAB 使用教程](https://www.igorslab.de/en/install-dlss-5-reshade-compatible-games/)、[UI 异常反馈](https://github.com/rakanki911/DLSS5-Swapper/issues/27)++## 4. “剔除 UI”检查结果++### 4.1 接线存在,实际保护资源缺失++当前面板对应项叫“UI修正 · 未证实”。它会经过设置验证、控制器、共享增强图,最终调用 `DLSSNR.UICorrection` 的整数参数设置,**不是单纯没有连接的 UI 按钮**。++但当前 NR 图没有提供 `DLSSNR.UI`、`UIAlpha`、`Backbuffer` 或 `ControlMask` 资源。FG 后端也明确标记其独立的 HUD-less / UI / UIAlpha 资源未提供。NR 的 UI correction 与 FG 的 UI 合成是两条不同接口,打开前者不会自动补齐后者。++源码定位:[面板读取与验证](../apps/veyra/SettingsWindow.cpp)第 32–39 行;[NR 参数提交](../src/pipeline/EnhanceGraph.cpp)第 876–893 行;[FG 资源声明](../src/ngx/DlssFgBackend.cpp)第 163–175 行。++### 4.2 本机像素实测++在 RTX 5070 上直接调用当前产品 `EnhanceGraph`,使用 1280×720 测试画面:静态背景与移动背景各一组,包含固定文字、字幕、数字、彩色 HUD 条。每个配置处理 16 帧,在第 0 / 3 / 7 / 15 帧取样;相同场景每组从 reset 开始。SR / FG 关闭,NR 与 NVOF 开启,以隔离这个参数的作用。++| 对照 | 静态背景 | 移动背景 | 解释 |+|---|---:|---:|---|+| 相同基线重复运行 | RGB 差异为 0 | RGB 差异为 0 | 当前实验可重复 |+| UI 修正 0 → 1,自动遮罩关闭 | RGB 差异为 0 | RGB 差异为 0 | 未观察到 UI 开关效果 |+| UI 修正 0 → 1,自动遮罩开启 | RGB 差异为 0 | RGB 差异为 0 | 自动遮罩没有令该开关在样本上生效 |+| 自动遮罩 0 → 1 | 全图 MAE 0.538;HUD 0.566 | 全图 MAE 0.576;HUD 0.543 | 阳性对照:自动遮罩会改变像素,但不证明能识别并保护 UI |+| 模型强度降到 0 | 全图 MAE 3.180;HUD 5.314 | 全图 MAE 3.482;HUD 5.343 | 阳性对照:NR 输出与参数链确实工作 |++MAE 按 8 位 RGB 通道值计算。最新有效运行 exit 0,用时 **4.600 秒**,包含 **192 次 NR Evaluate、180 次 NVOF Execute**;Feature 18 Create 返回 `0x1 / NVSDK_NGX_Result_Success`,非空句柄,SEH 0。比较发生在 GPU 结果回读后的内存中、PNG 编码之前。++结论:**当前版本不能把这个选项当作有效的“自动剔除 UI”。在上述两类场景、自动遮罩开 / 关组合下,它没有改变取样输出。** 这不是“任何版本、任何内容下该参数永远无效”的证明;本次也没有自动点击原生控件,而是检查控件接线并用设置 API 驱动同一个产品图。++AIO 作者的实验进一步指出:UI 修正需要配套的保护遮罩与原图资源;其 `ControlMask` 是 1 表示应用 NR,而 `UIAlpha` 是 1 表示保护,极性相反。结合本地缺失的资源,这构成下一步最有价值的验证方向,**尚不能写成 Veyra 已完成该资源合同**。[AIO 像素实验记录](https://github.com/kibblerz/DLSS5-Reshade-AIO/blob/5112b4f5ed5ed0865cb56709ece751ce53c039f1/lab/PRIVATE-CONTRACT-FINDINGS.md)++### 4.3 建议怎样做成有效功能++先实现可预测的“保护区域”,再讨论自动识别:++1. 专业模式允许框选少量 UI / 字幕区域并保存为来源预设;保持原有实验参数如实标识,不能继续把它包装成已生效的自动剔除。+2. 在现有 GPU 残差合成中使用保护遮罩:`结果 = 底图 + (1 - 保护遮罩) × NR变化`。完全保护区不叠加 NR 变化;边缘少量羽化。尽量并入已有 pass,避免独立模型和 CPU 像素往返。+3. 对已被 SR 处理的文字,单纯取“SR 后底图”只能避免 NR 进一步破坏。需要保护 SR 本身时,使用从原始源图按相同几何缩放的参考区域,并明确其清晰度折中。+4. 用固定 runtime 做全零、全一、矩形、单通道的可选 NR 资源实验。仅在保护区与非保护区像素表现符合预期后,才考虑接入 `UIAlpha + Backbuffer` 或 `ControlMask`。不把 motion confidence、NR 作用遮罩、UI 遮罩混用。+5. Veyra 自己的字幕 / OSD 继续放在 FG 后;源视频自带 HUD 没有真实透明图层,框选可能同时保留区域内的运动背景。FG 期间选择邻近真实帧保护区域,会有更新节奏或边缘接缝的折中,不能称为完美 HUD-less 分离。++自动文字 / HUD 检测暂不进入默认路线:既有误检成本,也有模型、显存与推理成本。如果后来做,必须具备时间稳定、来源切换清空、尺寸坐标变换和用户修正能力。++## 5. 执行顺序与具体改动++建议目标结构如下;虚线为指导数据。沿用共享图,分别验证模块合同,不把三个功能混成一个增强开关。源自带 HUD 的 FG 保护仍需第 4.3 节所述单独处理。++```mermaid+flowchart LR+ A[来源帧与真实时间] --> B[统一颜色与 reset]+ B --> C[一个超分器或原尺寸旁路]+ C --> D[NR 实时档或原生档]+ C --> E[残差回填与 NR 保护区域]+ D --> E+ E --> F[DLSSG 与有效帧调度]+ F --> G[自有字幕与 OSD]+ G --> H[显示或现有导出路径]+ B --> M[源空间光流与可信度]+ M -.-> C+ M -.-> D+ M -.-> F+```++### P0:修正输入与现有接口,收益不依赖新增模型++| 任务 | 当前证据与改法 | 成本与验证 |+|---|---|---|+| 时间与 reset | 采集 packet 未填 duration,默认已知零值会进入约 8.33ms 的调度 clamp;贯通真实 PTS / duration,统一来源切换、seek、cut、drop、resize、pause / resume 的历史失效 | 属于必要正确性修复,不需要额外未来帧;用 30 / 60fps 与不连续 PTS 短测 |+| 颜色元数据 | source 与 graph 对缺失 range / matrix / transfer 的默认解释不一致;统一一次解析,确保实际输入进入正确 linear 域 | 用灰阶、肤色和彩条检查;不要先靠 NR 明暗参数掩盖颜色错误 |+| RGB 输入 | 检查图片 / RGB 路径绕经 NV12 4:2:0 的额外色度损失,保留可行的直接 RGB 上传路径 | 可减少文字和彩边损失;保留视频原生 YUV 的正常解码路线 |+| PNG 红蓝通道 | 本次无 NR 的原始色块 RGB 为 245/128/38,经当前 PNG 保存后独立解码变成 38/128/245。`SetPixelFormat` 后没有检查实际协商格式 | 已证实保存路径通道交换;协商格式不匹配是待确认的具体原因。修编码格式与字节排列,不扩大每次导出的完整性检查 |+| SR 参数合同 | 当前创建参数未显式设置 feature flags;Evaluate 未显式填 `InExposureScale`、没有曝光纹理或明确自动曝光;需要逐项对照本地 NGX 头文件和官方约定 | 属于静态风险,尚未证明是哪一项造成可见缺陷。固定单变量、测实际输出,不能只看 Evaluate 成功 |++SR 要同时确认输入 / 输出尺寸、linear / HDR 标志语义、曝光、subrect、motion 单位及纹理分辨率。当前 graph 给 SR 的 motion 已适配到输出空间,**不能不改资源就照抄其他项目的 `MVLowRes` 标志**。Streamline 示例的向量约定也不能机械套入直接 NGX。已经栅格化的视频没有引擎原始 jitter;人为给同一图偏移采样属于实验,不是恢复真实采样序列。[官方 DLSS 接入要求](https://developer.nvidia.com/blog/how-to-integrate-nvidia-dlss-4-into-your-game-with-nvidia-streamline/)++相关文件:[CaptureCardSource](../src/source/CaptureCardSource.cpp)、[MediaFileSource](../src/source/MediaFileSource.cpp)、[EngineController](../src/engine/EngineController.cpp)、[EnhanceGraph](../src/pipeline/EnhanceGraph.cpp)、[SR 后端](../src/ngx/DlssSrBackend.cpp)、[图片输出](../src/sink/ImageExportSink.cpp)。先做局部数据贯通,不借此重构整个播放器。++### P1:提高 NR 的运动可靠性,并接入 UI 保护++保留当前 source-space NVOF,共用一次运动估计,再分别适配各消费者。当前 cost 阈值清零能挡住部分坏向量,但没有完整的出界、遮挡和回投一致性检验。++建议分两档验证:基础档先加入出界 / 切镜拒绝与低成本亮度重投影残差;质量档再加 **同一对 A/B 的前向、后向光流一致性**。计算方向相反不等于还要等下一张 C 帧,但会增加 GPU 工作,必须实测耗时。NVOF cost 不能独立当作绝对可信的置信度。[NVOF 编程指南](https://docs.nvidia.com/video-technologies/optical-flow-sdk/nvofa-programming-guide/index.html)、[双向光流能力说明](https://developer.nvidia.com/blog/whats-new-in-optical-flow-sdk-3-0/)++在运动不可信区域按现有合同衰减 / 清零 motion,并在独立验证通过后限制 NR 变化或降低历史依赖。清零运动本身不等于历史被安全排除;不能只把所有向量缩短就宣称解决拖影。合成遮罩需要短期稳定和切镜清空,避免保护区边缘自己闪烁。++UI 保护按第 4.3 节落地。它与运动可靠性可共享遮罩合成设施,但保持独立语义和开关。++随后比较 Style 0 / 1 / 2、模型强度、结构与明暗保留、总变化回填。优先做自然保真和较强重塑两类可解释预设,保留用户精细调整;不宣称某个未测试参数组合对真人、动漫、游戏都最佳。不引入默认多次串行 NR,也不套用论坛面向 HDR 的 paper-white 数值到当前 SDR 主线。++### P2:4K 超分保留 DLSS,并比较 RTX Video SR++**最值得新增验证的候选是 RTX Video Super Resolution。** 它针对视频超分和压缩伪影处理,官方 SDK 提供 DX12 接口并支持 RTX 50 系列,输入条件比游戏 SR 更贴近普通视频。但“更适合输入类型”是选择实验的理由,不是已经测得更清晰或更快。[RTX Video SDK 官方说明](https://developer.nvidia.com/rtx-video-sdk/getting-started)++对照三条路径:++| 路径 | 用途 | 决策标准 |+|---|---|---|+| 空间缩放基线 | 判断所谓提升是否只是尺寸变化或锐化 | 颜色、振铃、文字和时间稳定性基准 |+| 修正合同后的 DLSS SR | 保留现有能力,评估估算运动能带来的时序细节 | 实际纹理、遮挡边缘、运动拖影与 GPU 成本 |+| RTX Video SR 独立原型 | 比较压缩视频、低清片源、字幕场景 | 明确优于基线且成本可接受才进入产品选项 |++实现边界:只选择一个主超分器放在 NR 前,不默认叠加 DLSS SR 与 RTX Video SR;原生 4K 输入不把 1:1 输出称为“超分提升”。保留正确宽高比、源裁剪与输出尺寸,不通过拉伸制造“4K”。++RTX Video SR 原型先核实当前 SDK 的资源格式、同步与生命周期,在现有 D3D12 图中评估。若产生 CPU 回读、额外设备桥接或明显排队成本,不直接纳入正常路径。此次没有下载或接入 SDK;若后续采用,只引入实际需要的模块,不扩展 HDR 范围。++### P3:帧生成优先解决错误帧与调度++已有 DLSSG 真正生成帧,保留 2X / 3X / 4X 和有界 frame batch / 资源租约。下一阶段先核对每张源帧、生成帧与尾部占位的身份和 PTS;切镜、掉帧、暂停恢复时丢弃失效历史,不让旧画面插入新镜头。++官方 FG 文档的 UI 保护使用独立的 HUD-less / UI 资源合同;只有最终视频画面时,不能伪造出原本没有的透明 UI 或干净背景。[官方 DLSSG 接入指南](https://github.com/NVIDIA-RTX/Streamline/blob/e8aaa6eaac968711fb62473d4ae8256dde20919b/docs/ProgrammingGuideDLSS_G.md)++| 优化 | 处理方式 | 不应作出的承诺 |+|---|---|---|+| 正确的 A/B 时间 | 优先完成 P0;按真实帧间隔生成中间 PTS,实测 present 节奏 | 生成 FPS 不等于降低输入延迟 |+| 遮挡与坏运动 | 复用 P1 验证结果;不可靠或切镜时跳过失效生成,明确记录回退 / 占位 | 重复帧不能计作成功生成帧 |+| UI 与字幕 | 自有 OSD 后合成;已有来源 HUD 使用经过验证的保护区域或真实外部图层 | 手工矩形回填不等于完美去除 HUD |+| 倍率与预算 | 逐档测 GPU 时间、输出节奏与伪影;负载不足时明确提示,不静默改变用户画质档 | 4X 无法补救源帧处理已经超时 |+| 质量参照 | 可离线比较 RIFE 与 NVIDIA FRUC 的运动 / 遮挡处理思路 | FRUC / RIFE 不是 DLSSG,不能用它们的输出冒充 DLSSG |++NVIDIA FRUC 文档说明其插帧涉及前后向运动与遮挡处理,可用于算法对照,但不构成 Veyra 切换后端的决定。[FRUC 编程指南](https://docs.nvidia.com/video-technologies/optical-flow-sdk/nvfruc-programming-guide/index.html)++实时采集生成 A/B 之间的帧必须等到 B;额外使用 C 会再增加源帧等待。默认路线不引入 C 或竞品那种秒级播放缓冲。离线未来帧方案可另行比较,不能把采集卡内部延迟当作免费 lookahead。++### P4:深度与较大架构改动暂缓++深度实验先回答三个独立问题:当前 NR 是否对它有实际响应?当前 SR 是否受益?当前 FG 是否减少了遮挡错误?比较固定深度、受控变化与估算深度,使用同一输入和 motion,避免把多个变量一起改掉。++相对深度不能未经适配就当作引擎的投影 Z;不同模块的单位、近远方向、空间分辨率与历史规则需独立核验。只有产生稳定视觉收益,才进入 DAV2 Small / DirectML、时间稳定和 GPU 常驻资源设计。不默认增加每帧深度推理、OCR 或重型模型依赖。++硬解值得后续恢复,但要同时补上硬件帧路径的切镜检测和 reset,不能只把 `preferHardwareDecode` 改成 true。统一 Guidance 接口可以随着实际功能抽取,不为了“架构看起来完整”重写共享引擎、增加三套后端或拆更多进程。++## 6. 原方案事项的取舍++| 原方案 / 审计事项 | 本轮优化判断 |+|---|---|+| 帧颜色、PTS / duration、统一历史 reset | 必须做,优先级最高 |+| source-space flow、多信号 confidence | 保留并补强;先便宜的拒绝条件,再测 A/B 双向成本 |+| Depth Anything V2 | 保留可选研究方向;先证明收益,暂不进入默认工作量 |+| C 帧验证、离线双向完整分支 | 暂缓;A/B 双向光流检查不需要等 C,应先做小闭环 |+| 每次导出完整性扫描 | **按用户决定维持现状,不扩展** |+| PNG 通道交换 | 修已证实的编码正确性问题,不增加检查负担 |+| SR / FG 参数、真实状态、有效 UI 保护 | 必须补,属于已经暴露的产品质量问题 |+| RTX Video SR | 新增独立对照候选;以本机画质 / 成本决定是否纳入 |+| 硬解、显存准入 | 后续按实际瓶颈处理;不抢占颜色 / 时序 / UI 修复 |+| MKV / AAC / 完整字幕 / 恢复等产品范围 | 保留既有范围与缺口记录,不混入本次画质优化工作包,也不冒充完成 |+| 引擎注入、Streamline 迁移、默认多模型、多次 NR | 本方案不采用 |++## 7. 验证方法与轻量约束++以下是开发实验,不是附加在用户播放 / 导出上的检查系统。++| 对象 | 样本与方法 | 必须看什么 |+|---|---|---|+| 基础正确性 | SDR 灰阶 / 彩条、RGB 图片、30 / 60fps、seek / 切镜 / resize | 通道、色阶、真实帧时长、所有历史 reset |+| NR | 人脸、游戏、动画、细纹理、暗场;固定参数与相同历史,原图 / 低强度 / 候选盲比 | 自然程度、结构保留、文字损坏、运动对齐后的闪烁;不能只拿与原图的 PSNR 评价重塑效果 |+| UI | 全零 / 全一 / 矩形遮罩、静态 HUD + 运动背景、字幕更替 | 保护区遵守合成合同、非保护区仍增强、边缘不闪;正负对照都要有 |+| 4K SR | 已知 4K 源下采样后重建,以及真实压缩低清素材 | 真实细节、文字、振铃、运动稳定、颜色;输出尺寸正确只是必要条件 |+| FG | 快速平移、遮挡、新出现物体、粒子、切镜、HUD | 中间帧是否有效、时间位置、重复 / 占位区分、呈现节奏 |+| 成本 | 同一 GPU / 输入 / 参数,预热后记录各 pass GPU 时间与显存 | 平均和 P95、排队 / CPU 等待;未实测前不承诺提升百分比 |++每个实验进程设不超过 300 秒的退出限制,失败保留日志。同一组只改变一个因素,保存输入、源码 / EXE / runtime 身份、配置、重复基线和阳性对照。++资源原则:默认新增模型数为零;正常路径不增加 GPU→CPU 像素回读;不增加无界历史;能融合进现有残差 / 颜色 pass 的遮罩不另开重型处理链。A/B 双向、RTX Video SR、深度等开销需要实测,未证明收益前不能默默加入默认档。++首个实施闭环建议:**P0 的帧时长与颜色合同修复**。随后完成现有 SR 参数核验与 UI 保护。后端选型和深度实验都不应该抢在这些基础正确性之前。++## 8. 本次执行证据与边界++实际执行:本地源码 / 文档读取,Git 状态与身份检查,GitHub API 及公开资料核对,隔离诊断程序构建和 RTX GPU 短测。没有构建新产品 EXE、没有运行全部 delivery gate、没有执行实卡验收、没有测试新 SR / FG 性能,也没有确认第三方项目在本机的速度或画质。++本次未改应用源码、用户配置、SDK / runtime 或保护门禁;只新增本方案、更新架构审计的建议说明与 WORKLOG。公开资料缓存和临时诊断程序均位于被 Git 忽略的 `logs/research/20260908/`,未复制到产品源码或上传。第三方可借鉴机制不等于自动取得代码 / SDK / runtime 分发权,现有项目许可边界保持。++应用 EXE SHA256 保持:++```text+7EEA31511FFA649F3E6B0829F5D1D3A5D454010167A70137786D4430F71E9514+```++实际使用的 NR 文件仍为规定的 310.8.0.0、165840496 字节、有效 NVIDIA 签名:++```text+E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E+```++最新实验命令(在项目根目录):++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\logs\research\20260908\build-run-ui-probe.ps1+```++该脚本仅借用当前构建的编译参数与产品库,在忽略目录编译自写 probe;使用无窗口进程运行,测试内部 245 秒截止、外部约 275 秒 watchdog。++实验过程包括:首次程序输出完成但旧 runner 未取得 ExitCode,脚本失败,不作为通过;修复进程结果读取后短测 exit 0 / 4.230 秒;发现 PNG 色块异常后增加 NR-off 与原始图片对照,最新短测 exit 0 / 4.600 秒。失败记录保留,未只保留成功结果。++最新证据:++- [结果与构建时间](../logs/research/20260908/ui-1f853a0238804d8db3b26e3f763d7033/ui-probe-result.json):诊断构建 2.684 秒;进程 4.600 秒。+- [实际 Create / Evaluate、参数与色块日志](../logs/research/20260908/ui-1f853a0238804d8db3b26e3f763d7033/ui-probe.stdout.log):Create 在第 33 行,汇总在第 1079 行。+- [逐组像素对照](../logs/research/20260908/ui-1f853a0238804d8db3b26e3f763d7033/ui-effect-results.csv):`changed_rgb` 是发生变化的 RGB 通道样本数,不是独立像素数量。+- [诊断源码](../logs/research/20260908/ui_effect_probe.cpp)、[构建与运行脚本](../logs/research/20260908/build-run-ui-probe.ps1)。++诊断 EXE SHA256:`0B0674016A029EAA81A0C6111EF3F895DFA601377D76A20FD6E204F13C62C405`;源码 SHA256:`DBEE9D6D215ED37EC741CCE47515B75C154EB42E7877B953194EE6438C62DE35`。++PNG 的独立解码使用 Windows `System.Drawing.Bitmap.GetPixel(1100,140)`:源图保存后 RGB 为 38/128/245;NR-off 保存后为 36/128/244,而内存分别为 245/128/38 与 244/128/36。它定位到保存路径,不能据此误报“NR 把颜色变蓝”。本次尚未记录 WIC 协商返回的 GUID,因此没有把具体编码协商原因写成已经完全证明。[独立像素读取记录](../logs/research/20260908/ui-1f853a0238804d8db3b26e3f763d7033/png-channel-check.json)++文档检查:本方案、架构审计与 WORKLOG 的本地链接有效、代码围栏成对、无行尾空格;`git diff --check` 通过。Git 状态仅包含这三份文档,应用 EXE 与诊断源码 hash 均重新核对一致。++整体状态仍为 **Phase 7 / needs_review**。现有统一 delivery gate 的尾帧计数差异、实卡与其他原合同缺口没有被本次专项替代,也没有修改门禁来取得通过。本次交付完成的是优化方案和 UI 参数检查。diff --git a/docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md b/docs/REVIEW_IMAGES_PREVIEW_2026-09-08.mdnew file mode 100644index 00000000..27dcd150--- /dev/null+++ b/docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md@@ -0,0 +1,9 @@+# Q1a / Q1b / Q2 scoped review — 2026-09-08++Independent fresh-context reviewer: review_tiles_zoom. Final verdict PASS for implemented RGB/odd dimensions, tiles, preview transform and save recovery; whole Goal remains in progress. Initial P2 save exception/destruction-order finding was fixed, not waived.++Reviewer confirms all-exit queue drain before presenter/graph resource release, local exception preservation, owned partial cleanup after WIC handles release, successful rename disarming cleanup, bounded band conversion with existing decode-back check unchanged.++Independent final evidence: preflight71 PASS; phase7 logs/delivery/3e2dd5557c6f44f1ad734e95b362d4e6/result.json41.144s EXE5E7BC723B647903851C4DD0265F6CDC1A16BBDCE9AEEF07D6E213808F49BE95E; image-de9653bdbcbd4014ad6dc009a17258fd6.565s actual NR Create0x1 Success,SEH0,14 long-image Evaluates,bandedPNG/JPEG; reviewer-save-2b1ecd334adf4cacaab21a183f7ad683/app.log injected failure after WritePixels, same-path retry, no partial, matching input/output SHA,app exit0. Reviewer wrote no project files; before/after diff22c13c236098ae8fe8beb42ed82484468e7097ac.++Unclosed evidence scope: two-dimensional tile intersections and neural seam/context quality; real hover/focus routing and rendered pixel geometry; actual memory exhaustion (injection is branch evidence only); video/model/codec dimension boundaries; Q3–Q7; user capture acceptance and distribution rights. These are not covered by this scoped PASS and are not redefined away.diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex f3a4f45e..4e09ee84 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -25,6 +25,12 @@7. 光流三档为性能/平衡/质量;界面记录实际应用档。30/50/60模式用于识别内容节奏,不会把源时间轴重采样成指定帧率。静止画面不能确认较低内容帧率。8. 进度条定位,Space播放/暂停;F11、Alt+Enter、视频区域双击或全屏按钮切换,Esc退出全屏。全屏只展示铺满显示器的视频和字幕,控制条覆盖在底部;鼠标离开控制条并静止约1.6秒后,操作条与鼠标隐藏,移动鼠标会唤回。参数面板在全屏隐藏,退出恢复原窗口与模式。设备丢失会停止并报错,重新打开源恢复,不是无缝恢复。+## 图片尺寸与预览缩放++图片支持竖图、长图和奇数尺寸。超出单张GPU纹理能力或较大面积的图片自动分块增强,保留完整尺寸用于PNG/JPEG保存;状态会标明分块NR,其上下文不等同整图NR。实际可用尺寸仍受解码器、内存与GPU能力限制。图片不运行光流或帧生成。++专业模式:鼠标悬停画面后滚轮缩放(以鼠标位置为中心),按住中键拖动,右键恢复适应窗口。切回日常模式或打开新媒体时恢复适应窗口。缩放只影响预览,不重启增强,也不改变保存/导出尺寸。大图缩放从完整增强结果取景。+## 对比、性能与诊断- 专业模式按住V或“按住原图”临时查看原图;可用“原图/增强切换”和“分屏拖动”,并选择输入原画或增强前底图作为参考。对比显示同一源帧的GPU参考,生成帧没有天然原图时明确使用真实帧对比。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 254c6ba4..d2039a88 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,3 +1,43 @@+# 2026-09-08 优化 Goal 启动与 preflight 停点++用户明确开启目标模式,新增解除不合理媒体尺寸限制、专业预览悬停滚轮缩放,并实施现有优化方案;导出完整性检查保持现状。Goal 和 BACKLOG 已建立。++执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`,2.604秒 exit1,唯一失败 README hash。当前 README 与此前用户要求更新并上传的 f79ef95 一致;其他控制与两份二进制身份通过。按 AGENTS 明确停工条款,未自行修改控制清单/gate,已准备仅两处 hash 同步的未应用提案 logs/optimization-goal-20260908/,等待明确授权。++只读定位到 EngineController.cpp:89 对所有来源统一拒绝 3840×2160 以外和奇数尺寸,专业缩放需接 AppShell/VideoPresenter。新行为尚未实现;本轮未构建、未运行 GPU/实卡。STATE/JOURNAL/EVIDENCE/INBOX 同步,整体仍 Phase7 未验收。++---++# 2026-09-08 画质优化调研与 UI 修正像素检查++用户要求保持现有导出完整性检查,核对官方 / GitHub / 其他渠道的 NR、4K SR、FG 路线,以及当前 UI 修正是否有效,并合并旧方案给出优化建议。交付见 [优化方案](QUALITY_OPTIMIZATION_PLAN_2026-09-08.md);架构审计加注最新决定,保留历史差距事实。本次不实施产品改动、不扩大导出检查,也不自动启动新后端或深度模型接入。++核对 NVIDIA DLSS5 研究说明、公开 DLSS / Streamline 文档、RTX Video SDK、NVOF / FRUC,以及固定提交的 Magpie、AIO、Feeder、video2dlssnr、Odyssey、2600th、Infinity Studio、Visual Enhancer,另参考 mpv / Video2X / RIFE 与教程和社区反馈。重点更正:NR 推理输入与 SR / FG 不能混同;本次 Magpie 最新源码使用 ZeroDepth,旧 DAV2 描述仅适用于历史版本;AIO 作者像素实验给出 UIAlpha / Backbuffer 资源线索,不能当成本机已验证的接口合同。++当前面板 `UI修正 · 未证实` 实际连接 `DLSSNR.UICorrection`,但 NR 未提供 UI / UIAlpha / Backbuffer / ControlMask,FG 也未提供其独立 UI 资源。自写隔离 probe 链接现有产品库,在 RTX 5070 上以静态 / 移动背景和固定文字 HUD 驱动真实 EnhanceGraph。自动遮罩开、关两种配置下,切换 UI 修正的四个取样帧 RGB 差异全部为零;重复基线也为零,而自动遮罩与强度零对照会改变像素。因此不能把当前选项当作有效的自动 UI 剔除;结论限定于所测内容和设置,不是任何场景永远无效的证明。未自动点击原生 UI 控件。++实际执行命令:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\logs\research\20260908\build-run-ui-probe.ps1`。最新诊断构建 2.684 秒、运行 4.600 秒、exit 0;192 次 NR Evaluate、180 次 NVOF Execute;Feature 18 Create `0x1 / Success`、非空句柄、SEH 0。最新证据位于 `logs/research/20260908/ui-1f853a0238804d8db3b26e3f763d7033/` 的 result JSON / stdout / CSV。诊断 EXE `0B0674016A029EAA81A0C6111EF3F895DFA601377D76A20FD6E204F13C62C405`;源码 `DBEE9D6D215ED37EC741CCE47515B75C154EB42E7877B953194EE6438C62DE35`。++失败与补测:首次程序产生完整输出但旧 Start-Process runner 没拿到 ExitCode,脚本失败,不算通过;改用显式 Process 结果读取后运行 4.230 秒 exit 0。看到 PNG 色块通道异常后增加 NR-off 与源图保存对照,得到上述最终 4.600 秒结果。三次进程均小于 300 秒,失败日志保留。CPU 源 RGB 245/128/38 经当前 PNG 保存后独立解码为 38/128/245;NR-off 内存为 244/128/36、保存后为 36/128/244,定位到保存路径。WIC 实际协商 GUID 尚未测得,因此仅将未处理格式协商列为疑似原因。UI 对照在 PNG 编码之前进行,不受该问题影响。++只新增方案、更新架构审计说明与本 WORKLOG;第三方文本缓存、自写诊断源码 / EXE / 图片与结果均在 Git 忽略目录。应用 EXE SHA256 仍为 `7EEA31511FFA649F3E6B0829F5D1D3A5D454010167A70137786D4430F71E9514`,指定 NR / add-on 身份一致,add-on 未加载。未修改产品、配置、runtime、SDK 或保护文件,未运行全部 delivery gate / 新 SR-FG 性能 / 实卡测试,未提交或上传。整体仍 `Phase 7 / needs_review`;旧尾帧 gate 差异不由本次专项解决。++文档检查:方案、审计与 WORKLOG 的本地链接 / 代码围栏 / 行尾空格检查通过,`git diff --check` 通过;Git 状态只有这三份文档,EXE 和诊断源码 hash 复核一致。PNG 的独立 System.Drawing 读取结果另存于最终实验目录的 `png-channel-check.json`。++下一条建议任务:先完成帧时长与颜色合同修复,再核验 SR 参数、实现确定有效的 UI 保护与运动可靠性增强;RTX Video SR 和深度先独立测收益。导出完整性检查保持现状。++---++# 2026-09-08 原始方案与当前架构审计++用户要求核对原始方案并对照当前架构。本地基线 `f79ef95`,工作树初始干净。完整对照见 [架构审计](ARCHITECTURE_AUDIT_2026-09-08.md)。确认真实产品复用 `pipeline::EnhanceGraph`,但完整帧 / 颜色 / reset 契约未贯通,深度推理与 C / 离线双向质量分支缺失,confidence 仅 cost 硬门控,播放器 / 导出主动选择软件解码;字幕、导出格式与完整验证也未达到原方案全部范围。++具体静态问题:采集 packet 未填 duration,默认 known zero 被调度器 clamp 到约 8.33ms;source 层与 graph 对缺失颜色标签的默认解释不一致。没有把这两项静态推导说成已测得画质或实卡延迟。报告单独列出后续已批准的分辨率 / 残差、源空间光流、深度暂缓、双模式 UI、独立导出进程和短测规则,避免混同为擅自偏离。++本次仅运行 Git / rg / 文件读取及文档检查;只改审计文档与本记录。未构建,未执行 RTX / NGX 或实卡测试,未改变应用、EXE、保护文件与 runtime,也未提交或上传。整体仍 `Phase 7 / needs_review`。下一条建议任务:贯通真实产品 FramePacket,先修采集 duration 与颜色元数据的唯一解释;本次尚未开始实现。++---+# 2026-09-08 GitHub 源码存档准备与 README用户明确要求建立 Git 存档并上传到 `Likely7/Veyra-DLSS-Video-Player`。本次只修改 README、保留远端既有 LICENSE,并补充存档记录;应用源码与最终 UI v4 EXE 未改,不重新运行构建、GPU 或实卡测试,也不改变 Phase 7 / needs_review。@@ -1030,3 +1070,49 @@ R3.1:从 player_probe 抽取真实成员建立 veyra_sinks(WasapiAudioSink- 重新计算 10 个受保护文件 SHA256,更新 `loop/CONTROL_HASHES.json`,并同步基础 `scripts/loop-gate.ps1` 的 manifest hash。- 修改后再次运行 preflight:**70/70,exit 0**;STATE 当前 Phase 5 `in_progress`、Phase 6/7 locked、3 个 open P0/P1、5 个 blocker,状态机与 Git 指针检查全部通过。++## 2026-09-08 optimization blocked audit 3 — Goal blocked++Previous and current continuation classified no progress, not verified process waits. Read-only revalidation confirms unchanged README F226D0A7 / manifest expectation 781FAFD8, manifest hash 26559334; no explicit authorization for the exact two-hash synchronization. Same blocker for three consecutive Goal turns including startup. Under the explicit control-plane stop rule there is no permitted independent implementation remaining. Mark Goal blocked, retain full Q0–Q8 scope and unapplied proposal; no product/control edits, build or GPU test. Resume requires explicit authorization recorded in INBOX, then exact synchronization and fresh preflight. Not complete.++## 2026-09-08 Q1a RGB / odd dimensions and static NR isolation++Phase 7 optimization remains in progress. Q1b large-image tiling, Q2 zoom and Q3-Q7 quality work are not passed. Real capture remains unexecuted.++Changes: ResolutionPlan/EnhanceGraph accept odd extents up to actual single-texture 16384; WIC arbitrary 8192 guard removed with checked UINT byte bounds; RGB upload and RgbToLinear avoid 4:2:0 conversion; PNG negotiated BGRA packing fixed; ScaleBlit exact 1:1 load avoids long-image floating-point interpolation error. Static images skip NVOF and FG capability/Create/warmup, reject FG enable, normalize image settings to 1X. Product per-export integrity checks unchanged.++Build command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release (exit0; logs/optimization-goal-20260908/build-static-final.log).+Image command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/optimization-goal-20260908/run-image-tests.ps1 (latest image-c17dd1e5813b494e9d25344ebd0c93e1, exit0,4.4185s; EXE 60EEF44E1E36B97182D0EE53A09A782444D7AA01864CD1B617D5677703CF9008).+Five NR-off cases 1x1,257x513,97x9001,4097x257,257x4097 have max RGB error0 and exact PNG readback. 257x513 and97x9001 real NR: Feature18 Create0x1 Success,handle non-null,SEH0,Evaluate1,nonblack output. FG capability/Create absent; direct enable and 2X apply rejected. This proves execution/dimensions, not NR quality equivalence.++Historical failures retained: image-ece8... missing shader dependency (fixed CMake); image-fe18... long1:1 error6 (fixed ScaleBlit). phase7-rgb failed old 23-frame assertion: actual 12source+11generated+1hold=24,120Hz,0.2sec,audio preserved. Developer delivery gate now checks all those identities/duration/rate for H264/HEVC; it does not change export behavior or add product scans.++Gate command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7. Q1a run4c37adc29e6e406c9f7e398fd2a286cd passed; independent reviewer run3af42697442443a6b79e3aab2e78c04b passed41.461s. Static-FG fix runb3c3df19f8b94d3eae6bcfde6aa68679 exit0 preceded final controller normalization/test assertions, so do not claim identical final executable coverage. Independent review_rgb_foundation scoped PASS with P2 static-FG finding subsequently fixed; this subsequent fix awaits review.++Next: Q1b bounded tiles using the same EnhanceGraph, full-size image export and viewport rendering. Inputs beyond single-texture limit still fail explicitly; memory/model/codec limits are real and arbitrary input support is not complete. No runtime replacement, push, artifact upload, packaging or shutdown.++## 2026-09-08 Q1b tiles and Q2 preview candidate (cycles 53–54)++Previous turn classified progress, not wait/no-progress. Fresh preflight passed; STOP absent. Q1a static FG isolation integrated into Q1b. Added TiledImageProcessor using shared EnhanceGraph (1280 core,128 context halo,64 overlap feather; spatial tiles reset independently). Real full-sized CPU result retained for image save. EngineControllerImage presents bounded viewport sampled from full result, reprocesses on settings only, supports original comparison, cancel and rollback. Normal presentation uses PreviewView UVs; professional wheel anchors cursor, middle pan/right reset; new media/daily reset fit. Product video export integrity unchanged.++Release build: scripts/build.ps1 -Root . -Preset x64-release, exit0; logs/optimization-goal-20260908/build-q1b-final.log. Current app SHA256 0409DACD716950F3B674D0B105AAC9972B1B85A8AAC8362EECAA27314166F0E6. Shader identities recorded separately; EXE hash alone does not prove shader identity.++Tests: image-55da6ef7d941450cbbb8d934852191a0, exit0,6.400s (run-image-tests.ps1,275s watchdog). NR-off single texture five sizes exact; 17001x17 and17x17001 tiled14 each, maxError0 including independent half-transparent white->188/transparent->black fixtures; cancellation after first tile returns no output. Real NR97x17001:14 tiles,14 Evaluates, full dimensions,PNG exact readback (pixel quality/equivalence not asserted). Earlier single257x513 and97x9001 real NR remain covered. UiContractTests pass includes pointer anchoring/inverse wheel/pan math.++Application --smoke-zoom --smoke-seconds 9/10 tests: zoom-large-5ae8f78c7c5442ca982871c5638d7c82 (17x17001 NRoff) saved same PNG SHA3E3331C3FF73E636F4F37467F8F0175EE2F1158772E24A5EB0AC1F1A69F525C1 despite zoom; zoom-nr-7918200c1f554761b4af22d7ffd68db4 normal257x513 NR1 unchanged; final app zoom-large-nr-0b7a2fdd8cef4cc1855094d3d3cedbe8 NR14 unchanged,97x17001 full save. Session/revision/output extent preserved; zoom/pan/reset/daily flags pass. App processes bounded25s. Runtime output/dimensions covered; screenshot pixel comparison and real pointer hover routing still need stronger evidence.++Final phase7: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/bb35fca4c4e64b269caa7a5eb4243a2d/result.json 41.140s, same app0409..., all software checks pass. Prior run0ff376...41.203s is older app1B943... . Software gate is not full Goal approval. Q1 video model/codec edge limits and tiled visual seams/quality still need review; Q3–Q7 remain. No capture hardware claim, publishing or shutdown.++### Cycle55 reviewer P2 recovery fix — 2026-09-08++review_tiles_zoom independently passed software gates (3637158bbc434cb3aa6af32f9d62935c40.906s; image-bb9100790cf54d5c85237c8afc1da9d0 6.465s) but scoped verdict FAIL for unhandled save allocation exception and presenter-before-drain unwind. Finding accepted and repaired, not dismissed by green gates.++All-exit cleanup guard now drains shared queue before presenter/graph destruction. Large-image save and settings exceptions retain last successful result; ordinary image saves also preserve playback. WIC channel packing is bounded to row bands instead of another full-size image; existing decode-back extent verification remains unchanged. Partial file is CREATE_NEW-owned and removed after WIC closes on failure, or disarmed after successful rename. No new integrity scans or video-export changes.++Fault injection is opt-in VEYRA_TEST_LARGE_IMAGE_SAVE_THROW=1, once after actual WIC WritePixels (partial exists), not actual system memory exhaustion. App save-recovery-15610c7429934b15803b3e0a5cbc6751 9s smoke/25s watchdog: exception caught; session/output retained; same-path retry success; no partial remains; saved SHA equals source3E3331...525C1. Zoom session/revision/output assertions still pass.++Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-final.log/build-save-tests.log). Final app SHA5E7BC723B647903851C4DD0265F6CDC1A16BBDCE9AEEF07D6E213808F49BE95E. Image integration image-98845305ab6045a79311ef503ecfee9d exit0,6.515s: prior cases, cancellation, new PNG/JPEG multiple-band1024x3073 solid RGB fixtures pass. Final phase7 via scripts/loop-gate.ps1 exit0; logs/delivery/04815e94852a435a83840eaa45ba0ac1/result.json41.246s matches final app. Reviewer recheck pending.++Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.++Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 7b9862be..7502b8c1 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -8,6 +8,9 @@#include <functional>#include "veyra/engine/EnhancementSettings.h"#include "veyra/diagnostics/FrameMetrics.h"+#include "veyra/engine/PreviewView.h"+namespace veyra::sink { struct RgbaImage; }+namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::engine {struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;EnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native;return s;}@@ -39,6 +42,8 @@ public:void stop();void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}void pause(bool p);+ void previewView(PreviewView view){if(!std::isfinite(view.zoom)||!std::isfinite(view.centerX)||!std::isfinite(view.centerY))return;std::lock_guard lock(mutex_);view.zoom=std::clamp(view.zoom,.05f,64.0f);previewView_=view;}+ PreviewView previewView()const{std::lock_guard lock(mutex_);return previewView_;}void setVolume(float gain,bool mute);void seek(double seconds){seekSeconds_.store(seconds);}void saveFrame(const std::wstring& path);@@ -46,11 +51,13 @@ public:PlayerSnapshot snapshot()const;private:void run(HWND,std::wstring,PlayerOptions);+ void runLargeImage(HWND,const sink::RgbaImage&,PlayerOptions,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&);void post(std::function<void()>);void dispatch();void status(const std::wstring&,bool failed=false);mutable std::mutex mutex_;PlayerSnapshot snapshot_;+ PreviewView previewView_;std::wstring savePath_;std::thread worker_;std::condition_variable wake_;std::function<void()> pending_;bool shutdown_=false,busy_=false;diff --git a/include/veyra/engine/PreviewView.h b/include/veyra/engine/PreviewView.hnew file mode 100644index 00000000..5c094bcb--- /dev/null+++ b/include/veyra/engine/PreviewView.h@@ -0,0 +1,22 @@+#pragma once+#include <algorithm>+#include <cmath>+namespace veyra::engine {+struct PreviewView {+ float zoom=1,centerX=.5f,centerY=.5f;+ bool operator==(const PreviewView&)const=default;+ 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);+ const float next=std::clamp(zoom*std::pow(1.2f,steps),.05f,64.0f);+ centerX+=(x-clientW*.5f)/(imageW*fit)*(1/zoom-1/next);+ centerY+=(y-clientH*.5f)/(imageH*fit)*(1/zoom-1/next);+ zoom=next;+ }+ void pan(float dx,float dy,float clientW,float clientH,float imageW,float imageH){+ if(clientW<=0||clientH<=0||imageW<=0||imageH<=0)return;+ const float fit=std::min(clientW/imageW,clientH/imageH)*zoom;+ centerX-=dx/(imageW*fit);centerY-=dy/(imageH*fit);+ }+};+}diff --git a/include/veyra/engine/TiledImageProcessor.h b/include/veyra/engine/TiledImageProcessor.hnew file mode 100644index 00000000..11d42457--- /dev/null+++ b/include/veyra/engine/TiledImageProcessor.h@@ -0,0 +1,19 @@+#pragma once+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/sink/ImageExportSink.h"+#include <atomic>+#include <functional>++namespace veyra::engine {+// Static images only: bounded GPU residency, full-resolution CPU result.+// Context padding and overlap reduce tile boundaries; this is not equivalent+// to running the neural model with whole-image context.+class TiledImageProcessor {+public:+ struct Stats { uint32_t tiles=0; uint64_t nrEvaluations=0; };+ static bool process(gfx::D3D12DeviceContext&, gfx::CommandSlotRing&,+ const sink::RgbaImage&, sink::RgbaImage&, pipeline::EnhanceGraphDesc,+ const std::atomic<bool>& cancel, Stats&,+ const std::function<void(uint32_t,uint32_t)>& progress={});+};+}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 623124c5..80f03b13 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -2,6 +2,7 @@#include "veyra/diagnostics/GpuTimer.h"#include "veyra/gfx/PresentSink.h"#include "veyra/pipeline/GpuPassUtils.h"+#include "veyra/engine/PreviewView.h"#include <chrono>namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::pipeline { class EnhanceGraph; }@@ -9,7 +10,7 @@ namespace veyra::engine {class VideoPresenter {public:bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&);- bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={});+ bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});void close();uint64_t submittedCount() const {return sink_.presentCount();}diagnostics::GpuSample blitTiming(ID3D12Fence* f){gpuTimer_.collect(f);return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 70c5777b..92d5b633 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -60,6 +60,8 @@ struct EnhanceGraphDesc {bool enableNvofStandalone = false; // run NVOF+densify per frame without FG (quality core)bool noFeatures = false; // VEYRA_NO_FEATURES: NVOF/NGX objects skippedbool noNgx = false; // VEYRA_NO_NGX: core/features skipped, NVOF only+ bool rgbInput = false; // allocate direct RGBA ingestion before NGX creation+ bool stillImage = false; // no temporal motion/FG history for a single imageuint32_t nrWidth=0,nrHeight=0; // zero preserves legacy native working extentuint32_t fgMultiplier=2;uint64_t settingsRevision=1;@@ -168,7 +170,7 @@ public:// setNrEnabled also refreshes the section-5 blit SRV (slot 2) so the// videoFrame source follows workRgba (NR off) or finalRgba (NR on).void setNrEnabled(bool on);- void setFgEnabled(bool on) { fgEnabled_ = on; }+ void setFgEnabled(bool on) { fgEnabled_ = on && !desc_.stillImage; }bool fgCreated() const;private:@@ -198,6 +200,9 @@ private:ComPtr<ID3D12Resource> lumaTex_;ComPtr<ID3D12Resource> chromaTex_;ComPtr<ID3D12Resource> srcRgba_;+ ComPtr<ID3D12Resource> rgbTex_,upRgb_[2];+ uint8_t* mappedRgb_[2]={};+ size_t rgbPitch_=0;ComPtr<ID3D12Resource> workRgba_;ComPtr<ID3D12Resource> nrInput_,residualRgba_,nrFlow_,baseFlow_;ComPtr<ID3D12Resource> proxyTex_;@@ -220,6 +225,7 @@ private:std::vector<uint8_t> nv12Buf_;ComputePass yuvPass_, encPass_, decPass_, blitPass_, uploadPass_, densifyPass_;+ ComputePass rgbPass_;ComputePass downsamplePass_,residualPass_,flowAdaptPass_;DescriptorStager stager_;Microsoft::WRL::ComPtr<ID3D12Resource> sourceReferences_[2],baseReferences_[2];diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.hindex 24049ab4..13b40595 100644--- a/include/veyra/pipeline/ResolutionPlan.h+++ b/include/veyra/pipeline/ResolutionPlan.h@@ -6,7 +6,8 @@ namespace veyra::pipeline {struct Extent {uint32_t width=0,height=0;bool operator==(const Extent&) const = default;- bool valid() const {return width>=2&&height>=2&&width<=3840&&height<=2160&&!(width%2)&&!(height%2);}+ // D3D12 texture extent, not a product aspect-ratio or video-format policy.+ bool valid() const {return width>=1&&height>=1&&width<=16384&&height<=16384;}};enum class NrSizePolicy { Realtime, Native };struct ResolutionPlan {@@ -16,11 +17,11 @@ struct ResolutionPlan {static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0) {if(!source.valid())throw std::invalid_argument("invalid SDR source extent");ResolutionPlan p; p.source=source;p.base=source;- if(sr){const double scale=std::min(3840.0/source.width,2160.0/source.height);p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}+ if(sr){const double scale=std::min(3840.0/source.width,2160.0/source.height);if(scale>1.0)p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}p.srApplied=sr&&p.base!=source;p.nr=p.base;if(!exporting&&policy==NrSizePolicy::Realtime) {const double scale=std::min({1.0,1920.0/p.base.width,1080.0/p.base.height});- p.nr={std::max(2u,uint32_t(p.base.width*scale)&~1u),std::max(2u,uint32_t(p.base.height*scale)&~1u)};+ if(scale<1.0)p.nr={std::max(1u,std::min(p.base.width,uint32_t(p.base.width*scale)&~1u)),std::max(1u,std::min(p.base.height,uint32_t(p.base.height*scale)&~1u))};}p.flow=source;p.fg=p.output=p.base;p.settingsRevision=revision;return p;}diff --git a/loop/BACKLOG.md b/loop/BACKLOG.mdindex f0f03fc7..eb9a0128 100644--- a/loop/BACKLOG.md+++ b/loop/BACKLOG.md@@ -1,6 +1,20 @@# Veyra Launch V1 Backlog-## 当前唯一队列(F6,2026-09-07)+## 当前唯一队列:2026-09-08 优化 Goal++按用户最新请求与 docs/QUALITY_OPTIMIZATION_PLAN_2026-09-08.md 执行;导出完整性检查保持现状,每次测试最多 300 秒。历史队列不删,不把未完成项改写为完成。++- [x] **Q0 控制基线同步 — 用户确认后已执行,preflight 71/71**:preflight 唯一失败 README hash,来自已授权的 f79ef95 文档更新;原 proposal 与授权后执行记录在 logs/optimization-goal-20260908/;已恢复施工。+- [ ] **Q1 输入尺寸**:解除统一 3840×2160 / 偶数尺寸拒绝,适配竖图、长图、奇数尺寸与实际 GPU/model 能力;不偷偷裁剪或冒充原生处理。+- [ ] **Q2 专业预览缩放**:画面悬停滚轮缩放,不抢设置面板滚动,不改变增强/导出分辨率、不重启源或 NGX。+- [ ] **Q3 颜色与时间**:duration / metadata / reset、RGB 中转损失、PNG 通道交换;导出检查不扩展。+- [ ] **Q4 SR 合同**:曝光、标志、motion 纹理/单位、subrect/reset;真实 GPU 对照。+- [ ] **Q5 UI 保护**:GPU 确定区域保护,私有资源先单独复验;区分 NR/SR/FG 与实验项。+- [ ] **Q6 motion/FG**:可信度、切镜与历史、真实 2X/3X/4X 调度;A/B 双向按成本验证,不增加默认 C 帧等待。+- [ ] **Q7 候选收益**:RTX Video SR 与深度按方案独立验证,未证明收益不默认堆模型,缺依赖/条款如实记录。+- [ ] **Q8 软件门禁与独立只读复核**:处理旧尾帧合同差异,不降低验证;真实短测、Reviewer、本地 checkpoint;实卡/分发另留档。++## 历史交付队列(F6,2026-09-07)- [x] 真实共享输入/NR guidance/资源修复,Win32播放器、WIC图片、D3D12 NVENC视频、DirectShow输入实现。- [x] 用户确认默认实时内部处理档,保留原生4K可选/原生4K导出。diff --git a/loop/CONTROL_HASHES.json b/loop/CONTROL_HASHES.jsonindex 0c8340ef..f3b099ef 100644--- a/loop/CONTROL_HASHES.json+++ b/loop/CONTROL_HASHES.json@@ -12,7 +12,7 @@},{"path": "README.md",- "sha256": "781FAFD857A82A19FCC09FDEDB2E00EE2465099E32B5A0857127D648316336E0"+ "sha256": "F226D0A74E56E79D16F4FBE34130B0B27DAFACE0631388D0BE09C8ED46753A33"},{"path": "VEYRA_AGENT_EXECUTION_PLAYBOOK_V1.md",diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.mdindex c7fd6649..2d4f41c6 100644--- a/loop/EVIDENCE.md+++ b/loop/EVIDENCE.md@@ -1,5 +1,9 @@# Veyra Gate Evidence+## 2026-09-08 optimization Goal startup — preflight FAIL++Executed `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`: exit1, 2.604 seconds, sole failure control:README.md. Other controls and both binary identities passed. README matches user-authorized f79ef95; manifest expects earlier README. Full output is in the task tool record; logs/optimization-goal-20260908/control-rebaseline-proposal.json is explicitly an observation/proposal, not fabricated gate output. Proposal is unexecuted; see cycle49/INBOX. No product build/Create/Evaluate this cycle; previous Phase7 records do not approve the new Goal's changes.+## Current capture fix candidate — 2026-09-07 (not independently approved)EXE4A9BA4B321DEEC17C5E3562AF03EF75A316856200A8708FA8E692475A05B59C9. Actual real-card source FPS~49.4–49.8 atMJPEG1080p50,0capture drops; final NR195/NVOF193/FG193. Logs `logs/capture-fix-20260907/`. Visible file/image/export gate `logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json`,47.309s,21 checks. Full evidence/caveats `docs/CAPTURE_LATENCY_FIX_2026-09-07.md`. Reviewer attempt ended without verdict, needs_review; old PASS below only applies to its old binary. Do not mark physical latency/audio/FG display cadence verified.@@ -388,3 +392,53 @@ Protected delivery04388 FAIL legacy23 assertion; protected7 unchanged and fixedUser requested direct bottom controls, a free consistent icon set, and glass app selectors. Baseline97ccd19; single writer retained. Native toolbar + Lucide ISC/MIT subset + accessible list/combo popup implemented. Fixed DeferWindowPos hide/show merge, SR effective-state sync, popup synchronous cancel and focus/notification lifetimes. True desktop acrylic and opaque video retained.Final executable7EEA31511FFA649F3E6B0829F5D1D3A5D454010167A70137786D4430F71E9514: controls/14popup cases PASS1.312s, switch40 PASS15.008s, nativeNR/SR/NaN/bottom controls PASS25.858s. Previous build differs by12DIP compactSR width: fullUI PASS141.503s; image/video/SR/export PASS80.914s. Evidence is version-qualified in docs/UI_CONTROLS_V4_DELIVERY_2026-09-08.md, not combined into a fake Phase7 pass. Actual1280/720 and popup keyboard screenshots retained locally. Independent readonly review scope recorded in docs/REVIEW_UI_CONTROLS_V4_2026-09-08.md. Protected hashes unchanged. No capture stream, runtime change, upload, packaging or shutdown. Global needs_review unchanged. Next: user UI and original capture acceptance.++## 2026-09-08 optimization blocked audit 2++Previous Goal turn classified progress (identified preflight failure and exact authorized-README origin). This automatic continuation is no progress, not a verified process wait: README still F226D0A7 versus expected 781FAFD8; manifest still 26559334; no STOP and no explicit authorization received. Proposal unchanged, no product or control edits. Same blocker for second consecutive Goal turn; goal remains active under the three-turn blocked threshold. No build/GPU/gate rerun performed.++## 2026-09-08 optimization blocked audit 3 — Goal blocked++Previous and current continuation classified no progress, not verified process waits. Read-only revalidation confirms unchanged README F226D0A7 / manifest expectation 781FAFD8, manifest hash 26559334; no explicit authorization for the exact two-hash synchronization. Same blocker for three consecutive Goal turns including startup. Under the explicit control-plane stop rule there is no permitted independent implementation remaining. Mark Goal blocked, retain full Q0–Q8 scope and unapplied proposal; no product/control edits, build or GPU test. Resume requires explicit authorization recorded in INBOX, then exact synchronization and fresh preflight. Not complete.++## 2026-09-08 Q1a RGB / odd dimensions and static NR isolation++Phase 7 optimization remains in progress. Q1b large-image tiling, Q2 zoom and Q3-Q7 quality work are not passed. Real capture remains unexecuted.++Changes: ResolutionPlan/EnhanceGraph accept odd extents up to actual single-texture 16384; WIC arbitrary 8192 guard removed with checked UINT byte bounds; RGB upload and RgbToLinear avoid 4:2:0 conversion; PNG negotiated BGRA packing fixed; ScaleBlit exact 1:1 load avoids long-image floating-point interpolation error. Static images skip NVOF and FG capability/Create/warmup, reject FG enable, normalize image settings to 1X. Product per-export integrity checks unchanged.++Build command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release (exit0; logs/optimization-goal-20260908/build-static-final.log).+Image command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/optimization-goal-20260908/run-image-tests.ps1 (latest image-c17dd1e5813b494e9d25344ebd0c93e1, exit0,4.4185s; EXE 60EEF44E1E36B97182D0EE53A09A782444D7AA01864CD1B617D5677703CF9008).+Five NR-off cases 1x1,257x513,97x9001,4097x257,257x4097 have max RGB error0 and exact PNG readback. 257x513 and97x9001 real NR: Feature18 Create0x1 Success,handle non-null,SEH0,Evaluate1,nonblack output. FG capability/Create absent; direct enable and 2X apply rejected. This proves execution/dimensions, not NR quality equivalence.++Historical failures retained: image-ece8... missing shader dependency (fixed CMake); image-fe18... long1:1 error6 (fixed ScaleBlit). phase7-rgb failed old 23-frame assertion: actual 12source+11generated+1hold=24,120Hz,0.2sec,audio preserved. Developer delivery gate now checks all those identities/duration/rate for H264/HEVC; it does not change export behavior or add product scans.++Gate command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7. Q1a run4c37adc29e6e406c9f7e398fd2a286cd passed; independent reviewer run3af42697442443a6b79e3aab2e78c04b passed41.461s. Static-FG fix runb3c3df19f8b94d3eae6bcfde6aa68679 exit0 preceded final controller normalization/test assertions, so do not claim identical final executable coverage. Independent review_rgb_foundation scoped PASS with P2 static-FG finding subsequently fixed; this subsequent fix awaits review.++Next: Q1b bounded tiles using the same EnhanceGraph, full-size image export and viewport rendering. Inputs beyond single-texture limit still fail explicitly; memory/model/codec limits are real and arbitrary input support is not complete. No runtime replacement, push, artifact upload, packaging or shutdown.++## 2026-09-08 Q1b tiles and Q2 preview candidate (cycles 53–54)++Previous turn classified progress, not wait/no-progress. Fresh preflight passed; STOP absent. Q1a static FG isolation integrated into Q1b. Added TiledImageProcessor using shared EnhanceGraph (1280 core,128 context halo,64 overlap feather; spatial tiles reset independently). Real full-sized CPU result retained for image save. EngineControllerImage presents bounded viewport sampled from full result, reprocesses on settings only, supports original comparison, cancel and rollback. Normal presentation uses PreviewView UVs; professional wheel anchors cursor, middle pan/right reset; new media/daily reset fit. Product video export integrity unchanged.++Release build: scripts/build.ps1 -Root . -Preset x64-release, exit0; logs/optimization-goal-20260908/build-q1b-final.log. Current app SHA256 0409DACD716950F3B674D0B105AAC9972B1B85A8AAC8362EECAA27314166F0E6. Shader identities recorded separately; EXE hash alone does not prove shader identity.++Tests: image-55da6ef7d941450cbbb8d934852191a0, exit0,6.400s (run-image-tests.ps1,275s watchdog). NR-off single texture five sizes exact; 17001x17 and17x17001 tiled14 each, maxError0 including independent half-transparent white->188/transparent->black fixtures; cancellation after first tile returns no output. Real NR97x17001:14 tiles,14 Evaluates, full dimensions,PNG exact readback (pixel quality/equivalence not asserted). Earlier single257x513 and97x9001 real NR remain covered. UiContractTests pass includes pointer anchoring/inverse wheel/pan math.++Application --smoke-zoom --smoke-seconds 9/10 tests: zoom-large-5ae8f78c7c5442ca982871c5638d7c82 (17x17001 NRoff) saved same PNG SHA3E3331C3FF73E636F4F37467F8F0175EE2F1158772E24A5EB0AC1F1A69F525C1 despite zoom; zoom-nr-7918200c1f554761b4af22d7ffd68db4 normal257x513 NR1 unchanged; final app zoom-large-nr-0b7a2fdd8cef4cc1855094d3d3cedbe8 NR14 unchanged,97x17001 full save. Session/revision/output extent preserved; zoom/pan/reset/daily flags pass. App processes bounded25s. Runtime output/dimensions covered; screenshot pixel comparison and real pointer hover routing still need stronger evidence.++Final phase7: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/bb35fca4c4e64b269caa7a5eb4243a2d/result.json 41.140s, same app0409..., all software checks pass. Prior run0ff376...41.203s is older app1B943... . Software gate is not full Goal approval. Q1 video model/codec edge limits and tiled visual seams/quality still need review; Q3–Q7 remain. No capture hardware claim, publishing or shutdown.++### Cycle55 reviewer P2 recovery fix — 2026-09-08++review_tiles_zoom independently passed software gates (3637158bbc434cb3aa6af32f9d62935c40.906s; image-bb9100790cf54d5c85237c8afc1da9d0 6.465s) but scoped verdict FAIL for unhandled save allocation exception and presenter-before-drain unwind. Finding accepted and repaired, not dismissed by green gates.++All-exit cleanup guard now drains shared queue before presenter/graph destruction. Large-image save and settings exceptions retain last successful result; ordinary image saves also preserve playback. WIC channel packing is bounded to row bands instead of another full-size image; existing decode-back extent verification remains unchanged. Partial file is CREATE_NEW-owned and removed after WIC closes on failure, or disarmed after successful rename. No new integrity scans or video-export changes.++Fault injection is opt-in VEYRA_TEST_LARGE_IMAGE_SAVE_THROW=1, once after actual WIC WritePixels (partial exists), not actual system memory exhaustion. App save-recovery-15610c7429934b15803b3e0a5cbc6751 9s smoke/25s watchdog: exception caught; session/output retained; same-path retry success; no partial remains; saved SHA equals source3E3331...525C1. Zoom session/revision/output assertions still pass.++Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-final.log/build-save-tests.log). Final app SHA5E7BC723B647903851C4DD0265F6CDC1A16BBDCE9AEEF07D6E213808F49BE95E. Image integration image-98845305ab6045a79311ef503ecfee9d exit0,6.515s: prior cases, cancellation, new PNG/JPEG multiple-band1024x3073 solid RGB fixtures pass. Final phase7 via scripts/loop-gate.ps1 exit0; logs/delivery/04815e94852a435a83840eaa45ba0ac1/result.json41.246s matches final app. Reviewer recheck pending.++Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.++Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.diff --git a/loop/INBOX.md b/loop/INBOX.mdindex b9bccacf..4dd96b9c 100644--- a/loop/INBOX.md+++ b/loop/INBOX.md@@ -1,5 +1,11 @@# Veyra Human Inbox+## RESOLVED · 2026-09-08 用户明确确认两处 hash 同步++preflight exit1,唯一失败 README hash。当前 README 匹配用户授权的存档提交 f79ef95;其他控制与二进制身份通过。拟仅将 CONTROL_HASHES.json 的 README 项由 781FAFD857A82A19FCC09FDEDB2E00EE2465099E32B5A0857127D648316336E0 同步到 F226D0A74E56E79D16F4FBE34130B0B27DAFACE0631388D0BE09C8ED46753A33,并将 scripts/loop-gate.ps1 固定 manifest hash 由 26559334D3A520682A42B20FD8127F3F297E70686CF139DC9325087047FDC8FC 同步到 4D5A30F73E06B59B3D6AD5D4A0AE106A0C3AD808D758418B21CC339D2E28779B。++不改 README 内容、其他控制 hash、逻辑、阈值或 runtime。用户回复“确认,给你全部权限”后,上述两处同步已执行;preflight 71/71 通过。此前 proposal 与失败日志保留在 logs/optimization-goal-20260908/,当前无需再次授权。+## 当前交付后唯一用户验收项(2026-09-07)本机软件已交付,独立复核PASS见docs/REVIEW_F6.md。请接入采集卡,按docs/USER_GUIDE.md测试视频设备/格式/HDMI音频、NR/FG、停止重开、断连和体感延迟。未做实卡测试,不声明硬件通过。NVOF/NVENC本机依赖已能构建运行,不再因为历史SDK阻塞停工。公开分发依然未授权,不能上传/打包运行时。以下旧阻塞为历史,不应自动重启长测或改驱动。diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex a548e5a9..a49e5c9b 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -1,5 +1,13 @@# Veyra Loop Journal+## Cycle 49 — 2026-09-08 optimization Goal startup / control drift diagnosis++User started Goal for arbitrary media dimensions, professional preview wheel zoom, and the quality optimization plan; retain export integrity checks and 300-second per-test limit. Unique task: preflight / reconcile before product edits. Hypothesis: prior user-requested archive README no longer matches old control ledger. Expected edits: runtime state only until preflight passes. Actual command: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`; exit 1 in 2.604 seconds, sole failed check control:README.md. Other control files and both binary identities passed.++Git confirms README exactly matches user-authorized f79ef95, but manifest retains old README hash. Unapplied proposal: logs/optimization-goal-20260908/control-rebaseline-proposal.json and CONTROL_HASHES.proposed.json. Only README entry plus gate's pinned manifest hash would change, no thresholds or logic. Explicit control-stop rule requires authorization; no self-rebaseline or product edit. Local status paused, first occurrence only; Goal is not complete or marked blocked.++Read-only source evidence: EngineController.cpp:89 rejects width>3840, height>2160 or odd dimensions, including images. Presenter currently fits the viewport; no professional preview wheel zoom handler found. Future work must adapt actual GPU/model extents, not merely delete the guard. No build/GPU/media test this cycle. Proposal and diagnosis are new evidence; queue and historical phase evidence preserved.+## Cycle 48 — independent review and local handoffReviewer initial FAIL found3 P1: realtime affected still-image size; NVENC cancel callback outlived block-local captures; second audio source read failure silently dropped audio. Fixed !isImage, scoped EncoderCloser before callback captures die, fail-closed audio inspection. Added real4K image and cancel regression to short gate. Also Play after Stop/EOF now reopens source. Build exit0. Reviewer rerun preflight/phase5=0/0, PASS, logs/delivery/9be0614da5d642e394a35c71d80f6207/result.json,40.31s; cancel43 submitted NVENC pictures/exit3/partial only. Code frozen after PASS. See docs/REVIEW_F6.md. Preserve user-deleted test clip; stage only implementation/document files, local checkpoint only, no package/push.@@ -1322,3 +1330,71 @@ Protected delivery04388 FAIL legacy23 assertion; protected7 unchanged and fixedUser requested direct bottom controls, a free consistent icon set, and glass app selectors. Baseline97ccd19; single writer retained. Native toolbar + Lucide ISC/MIT subset + accessible list/combo popup implemented. Fixed DeferWindowPos hide/show merge, SR effective-state sync, popup synchronous cancel and focus/notification lifetimes. True desktop acrylic and opaque video retained.Final executable7EEA31511FFA649F3E6B0829F5D1D3A5D454010167A70137786D4430F71E9514: controls/14popup cases PASS1.312s, switch40 PASS15.008s, nativeNR/SR/NaN/bottom controls PASS25.858s. Previous build differs by12DIP compactSR width: fullUI PASS141.503s; image/video/SR/export PASS80.914s. Evidence is version-qualified in docs/UI_CONTROLS_V4_DELIVERY_2026-09-08.md, not combined into a fake Phase7 pass. Actual1280/720 and popup keyboard screenshots retained locally. Independent readonly review scope recorded in docs/REVIEW_UI_CONTROLS_V4_2026-09-08.md. Protected hashes unchanged. No capture stream, runtime change, upload, packaging or shutdown. Global needs_review unchanged. Next: user UI and original capture acceptance.++## 2026-09-08 optimization blocked audit 2++Previous Goal turn classified progress (identified preflight failure and exact authorized-README origin). This automatic continuation is no progress, not a verified process wait: README still F226D0A7 versus expected 781FAFD8; manifest still 26559334; no STOP and no explicit authorization received. Proposal unchanged, no product or control edits. Same blocker for second consecutive Goal turn; goal remains active under the three-turn blocked threshold. No build/GPU/gate rerun performed.++## 2026-09-08 optimization blocked audit 3 — Goal blocked++Previous and current continuation classified no progress, not verified process waits. Read-only revalidation confirms unchanged README F226D0A7 / manifest expectation 781FAFD8, manifest hash 26559334; no explicit authorization for the exact two-hash synchronization. Same blocker for three consecutive Goal turns including startup. Under the explicit control-plane stop rule there is no permitted independent implementation remaining. Mark Goal blocked, retain full Q0–Q8 scope and unapplied proposal; no product/control edits, build or GPU test. Resume requires explicit authorization recorded in INBOX, then exact synchronization and fresh preflight. Not complete.++## Cycle 50 — explicit authorization and resume+User confirmed exact prior two-hash synchronization (确认,给你全部权限). Applied only README hash in manifest and pinned manifest hash in gate; no validation logic/threshold changes. Revalidate before Q1. Full objective unchanged.++## Cycle 51 — Q1a RGB/odd-size ingestion foundation+Hypothesis: direct RGBA ingestion avoids 4:2:0 damage and odd-size truncation. Implement bounded GPU RGBA upload and shader, generalized valid texture extents/ceil chroma sizes, WIC allocation bounds and PNG negotiated packing. Test independent shader pixel roundtrip + portrait/odd native NR; full large-image tiling remains Q1b, not claimed done. Product export integrity procedure unchanged.++## Cycle 52 — static image temporal isolation+Independent Q1a review passed with P2: still images create/warm FG. Skip capability/create/warmup for still images; reject direct FG settings and normalize controller image settings to multiplier 1. Extend real NR test to long portrait before claiming support. Prior phase7 passed: logs/delivery/4c37adc29e6e406c9f7e398fd2a286cd; independent logs/delivery/3af42697442443a6b79e3aab2e78c04b (41.461s). Goal remains incomplete.++## 2026-09-08 Q1a RGB / odd dimensions and static NR isolation++Phase 7 optimization remains in progress. Q1b large-image tiling, Q2 zoom and Q3-Q7 quality work are not passed. Real capture remains unexecuted.++Changes: ResolutionPlan/EnhanceGraph accept odd extents up to actual single-texture 16384; WIC arbitrary 8192 guard removed with checked UINT byte bounds; RGB upload and RgbToLinear avoid 4:2:0 conversion; PNG negotiated BGRA packing fixed; ScaleBlit exact 1:1 load avoids long-image floating-point interpolation error. Static images skip NVOF and FG capability/Create/warmup, reject FG enable, normalize image settings to 1X. Product per-export integrity checks unchanged.++Build command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release (exit0; logs/optimization-goal-20260908/build-static-final.log).+Image command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/optimization-goal-20260908/run-image-tests.ps1 (latest image-c17dd1e5813b494e9d25344ebd0c93e1, exit0,4.4185s; EXE 60EEF44E1E36B97182D0EE53A09A782444D7AA01864CD1B617D5677703CF9008).+Five NR-off cases 1x1,257x513,97x9001,4097x257,257x4097 have max RGB error0 and exact PNG readback. 257x513 and97x9001 real NR: Feature18 Create0x1 Success,handle non-null,SEH0,Evaluate1,nonblack output. FG capability/Create absent; direct enable and 2X apply rejected. This proves execution/dimensions, not NR quality equivalence.++Historical failures retained: image-ece8... missing shader dependency (fixed CMake); image-fe18... long1:1 error6 (fixed ScaleBlit). phase7-rgb failed old 23-frame assertion: actual 12source+11generated+1hold=24,120Hz,0.2sec,audio preserved. Developer delivery gate now checks all those identities/duration/rate for H264/HEVC; it does not change export behavior or add product scans.++Gate command: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7. Q1a run4c37adc29e6e406c9f7e398fd2a286cd passed; independent reviewer run3af42697442443a6b79e3aab2e78c04b passed41.461s. Static-FG fix runb3c3df19f8b94d3eae6bcfde6aa68679 exit0 preceded final controller normalization/test assertions, so do not claim identical final executable coverage. Independent review_rgb_foundation scoped PASS with P2 static-FG finding subsequently fixed; this subsequent fix awaits review.++Next: Q1b bounded tiles using the same EnhanceGraph, full-size image export and viewport rendering. Inputs beyond single-texture limit still fail explicitly; memory/model/codec limits are real and arbitrary input support is not complete. No runtime replacement, push, artifact upload, packaging or shutdown.++## Cycle 53 — Q1b bounded static-image tiles+Previous goal turn classified progress: static-image FG isolation and 97x9001 real NR evidence. Fresh preflight exit0; no STOP. Implement reusable image processor on shared EnhanceGraph with bounded overlapping GPU tiles, explicit per-tile reset, full-resolution CPU output and cancellation. Image-only readback; no video pipeline readback. Verify >16384 long inputs, transparent/boundary pixels and actual NR before UI integration. Q1 remains incomplete until integrated and reviewed.++## Cycle 54 — viewport transform required by large-image presentation / Q2+Q1b tiled service and app save smoke pass (>16384 edge, original full resolution retained). Current bounded preview loses zoom detail; add coherent presentation-only view transform and regenerate large-image viewport from full CPU result. Normal video uses pixel shader UV transform. Wheel only professional hover, middle drag pan and reset, no NGX/source or output-size changes. This is a Q1/Q2 dependency, not an arbitrary queue bypass.++## 2026-09-08 Q1b tiles and Q2 preview candidate (cycles 53–54)++Previous turn classified progress, not wait/no-progress. Fresh preflight passed; STOP absent. Q1a static FG isolation integrated into Q1b. Added TiledImageProcessor using shared EnhanceGraph (1280 core,128 context halo,64 overlap feather; spatial tiles reset independently). Real full-sized CPU result retained for image save. EngineControllerImage presents bounded viewport sampled from full result, reprocesses on settings only, supports original comparison, cancel and rollback. Normal presentation uses PreviewView UVs; professional wheel anchors cursor, middle pan/right reset; new media/daily reset fit. Product video export integrity unchanged.++Release build: scripts/build.ps1 -Root . -Preset x64-release, exit0; logs/optimization-goal-20260908/build-q1b-final.log. Current app SHA256 0409DACD716950F3B674D0B105AAC9972B1B85A8AAC8362EECAA27314166F0E6. Shader identities recorded separately; EXE hash alone does not prove shader identity.++Tests: image-55da6ef7d941450cbbb8d934852191a0, exit0,6.400s (run-image-tests.ps1,275s watchdog). NR-off single texture five sizes exact; 17001x17 and17x17001 tiled14 each, maxError0 including independent half-transparent white->188/transparent->black fixtures; cancellation after first tile returns no output. Real NR97x17001:14 tiles,14 Evaluates, full dimensions,PNG exact readback (pixel quality/equivalence not asserted). Earlier single257x513 and97x9001 real NR remain covered. UiContractTests pass includes pointer anchoring/inverse wheel/pan math.++Application --smoke-zoom --smoke-seconds 9/10 tests: zoom-large-5ae8f78c7c5442ca982871c5638d7c82 (17x17001 NRoff) saved same PNG SHA3E3331C3FF73E636F4F37467F8F0175EE2F1158772E24A5EB0AC1F1A69F525C1 despite zoom; zoom-nr-7918200c1f554761b4af22d7ffd68db4 normal257x513 NR1 unchanged; final app zoom-large-nr-0b7a2fdd8cef4cc1855094d3d3cedbe8 NR14 unchanged,97x17001 full save. Session/revision/output extent preserved; zoom/pan/reset/daily flags pass. App processes bounded25s. Runtime output/dimensions covered; screenshot pixel comparison and real pointer hover routing still need stronger evidence.++Final phase7: powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/loop-gate.ps1 -Gate phase7 exit0; logs/delivery/bb35fca4c4e64b269caa7a5eb4243a2d/result.json 41.140s, same app0409..., all software checks pass. Prior run0ff376...41.203s is older app1B943... . Software gate is not full Goal approval. Q1 video model/codec edge limits and tiled visual seams/quality still need review; Q3–Q7 remain. No capture hardware claim, publishing or shutdown.++## Cycle 55 — reviewer P2 save exception / cleanup+Independent review_tiles_zoom FAIL: unhandled large-image save allocation exception loses result and can destroy presenter before queue drain. Gates pass but do not dismiss finding. Add all-exit drain cleanup and local save/settings exception handling, bounded row packing in PNG/JPEG with same existing decode-back integrity check and owned partial cleanup. Inject one save allocation failure, verify session/NR preserved and retry same path succeeds. No actual memory exhaustion.++### Cycle55 reviewer P2 recovery fix — 2026-09-08++review_tiles_zoom independently passed software gates (3637158bbc434cb3aa6af32f9d62935c40.906s; image-bb9100790cf54d5c85237c8afc1da9d0 6.465s) but scoped verdict FAIL for unhandled save allocation exception and presenter-before-drain unwind. Finding accepted and repaired, not dismissed by green gates.++All-exit cleanup guard now drains shared queue before presenter/graph destruction. Large-image save and settings exceptions retain last successful result; ordinary image saves also preserve playback. WIC channel packing is bounded to row bands instead of another full-size image; existing decode-back extent verification remains unchanged. Partial file is CREATE_NEW-owned and removed after WIC closes on failure, or disarmed after successful rename. No new integrity scans or video-export changes.++Fault injection is opt-in VEYRA_TEST_LARGE_IMAGE_SAVE_THROW=1, once after actual WIC WritePixels (partial exists), not actual system memory exhaustion. App save-recovery-15610c7429934b15803b3e0a5cbc6751 9s smoke/25s watchdog: exception caught; session/output retained; same-path retry success; no partial remains; saved SHA equals source3E3331...525C1. Zoom session/revision/output assertions still pass.++Build scripts/build.ps1 -Root . -Preset x64-release exit0 (build-save-recovery-final.log/build-save-tests.log). Final app SHA5E7BC723B647903851C4DD0265F6CDC1A16BBDCE9AEEF07D6E213808F49BE95E. Image integration image-98845305ab6045a79311ef503ecfee9d exit0,6.515s: prior cases, cancellation, new PNG/JPEG multiple-band1024x3073 solid RGB fixtures pass. Final phase7 via scripts/loop-gate.ps1 exit0; logs/delivery/04815e94852a435a83840eaa45ba0ac1/result.json41.246s matches final app. Reviewer recheck pending.++Read-only Q3 diagnosis: CaptureCardSource packet duration is still default known0; downstream clamp selects83333 ticks incorrectly. Source colorInfo defaults BT709/SD601 but graph reads unresolved AVFrame fields and uses different transfer/matrix defaults. Capture RGB32 also leaves transfer/matrix unspecified and alpha is not guaranteed meaningful. Next Q3 must resolve once, carry actual sample/nominal duration, and retain explicit fallback logging; no Q3 code changes yet.++Independent recheck PASS for implemented Q1a/Q1b/Q2 and cycle55 save recovery; see docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md. Current Phase7/Goal remains in_progress. Prepare local checkpoint only; next close remaining input/preview evidence, then Q3–Q7.diff --git a/loop/STATE.json b/loop/STATE.jsonindex ee61e0d4..9fd382d0 100644--- a/loop/STATE.json+++ b/loop/STATE.json@@ -1,12 +1,12 @@{"schemaVersion": 1,"engineVersion": "veyra-loop-v1",- "objective": "Ship Launch V1, not an MVP: one shared engine, native 4K SDR capture/player/export, Feature 18, DLSSG 2X, bounded live lookahead, D3D12 NVENC H.264/HEVC, and product recovery/diagnostics.",- "status": "needs_review",+ "objective": "User-started optimization Goal: remove arbitrary input dimension limits, professional preview wheel zoom, implement current verified quality repairs; retain export integrity checks; each test <=300 seconds.",+ "status": "running","phase": {"id": 7,- "name": "Capture latency repair; physical throughput retested, review/user experience pending",- "state": "gate_passed",+ "name": "2026-09-08 dimensions, professional zoom and quality optimization",+ "state": "in_progress","gate": "phase7"},"phases": [@@ -68,40 +68,47 @@},{"id": 7,- "name": "Capture latency repair; physical throughput retested, review/user experience pending",- "status": "gate_passed",- "gateEvidence": "logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json plus logs/capture-fix-20260907/final-nr-fg.log; capture latency repair candidate",- "reviewEvidence": "Current repair attempt ended without a final reviewer verdict. docs/REVIEW_F6.md applies only to the historical checkpoint below.",- "commit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031"+ "name": "2026-09-08 dimensions, professional zoom and quality optimization",+ "status": "in_progress",+ "gateEvidence": null,+ "reviewEvidence": null,+ "commit": null}],"cycle": {- "completed": 48,+ "completed": 55,"maximum": 120,"sameFailureAttempts": 0,"maximumSameFailureAttempts": 3,"noProgressCycles": 0,"maximumNoProgressCycles": 5},- "currentTask": "Repair v2 known defects fixed and read-only reviewed; broader physical/performance acceptance remains.",+ "currentTask": "Q1a/Q1b/Q2 implemented scope independently reviewed PASS; remaining visual/video-boundary evidence open","lastGate": {- "name": "visible consolidated delivery regression",+ "name": "phase7","status": "passed","exitCode": 0,- "evidence": "logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json"+ "evidence": "logs/delivery/04815e94852a435a83840eaa45ba0ac1/result.json41.246s final app5E7BC723..."},- "lastFailureFingerprint": null,- "failureLedger": [],+ "lastFailureFingerprint": "",+ "failureLedger": [+ {+ "fingerprint": "preflight|control:README.md|expected781FAFD8_actualF226D0A7",+ "attempts": 1,+ "hypothesis": "Prior user-authorized README update not synchronized into control manifest",+ "result": "Confirmed README matches f79ef95; no control mutation",+ "proposal": "logs/optimization-goal-20260908/control-rebaseline-proposal.json"+ }+ ],"baselineCommit": "2086282478ae5d1e07e8162d47148633b59882fe","lastGoodCommit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031","openP0P1Findings": [],"blockers": [- "Read-only reviewer attempt failed without final verdict; needs_review, no new checkpoint.","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": "User accepts current UI and capture experience; see docs/UI_REPAIR_V3_DELIVERY_2026-09-08.md. Old Phase records are not new gate proof.",- "updatedAt": "2026-09-07T13:20:00Z",+ "nextAction": "Close Q1/Q2 remaining 2D tile/visual-hover/video capability evidence, then Q3 duration/color and Q4-Q7 quality work.",+ "updatedAt": "2026-09-08T09:04:53.6024326Z","deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md","captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending","testInvocationLimitSeconds": 300,@@ -109,7 +116,12 @@"logs/f6-diag.json: diagnostic native1080 12frames exit0 (prior to statistics stride correction rebuild)","logs/f4-encode-1080.mp4: actual D3D12 NVENC H264+audio","logs/f4-encode-4k-hevc-fg.mp4: actual D3D12 NVENC HEVC 4K120+audio 39frames",- "preflight 71 checks exit0"+ "preflight 71 checks exit0",+ "Q1a independent review_rgb_foundation scoped PASS; logs/delivery/3af42697442443a6b79e3aab2e78c04b/result.json 41.461s",+ "Static NR test image-c17dd1e5813b494e9d25344ebd0c93e1 4.4185s exit0; 97x9001 and 257x513 actual NR Create/Evaluate; FG capability/create absent and enable rejected",+ "Q1b/Q2 candidate app0409DACD...; final image-55da6...6.400s, zoom-large-nr-0b7a...10s, phase7 bb35fca...41.140s; review pending",+ "Cycle55 saved failure/retry recovered: save-recovery-15610...; image988453...6.515s includes multi-band PNG/JPEG; phase7 04815...41.246s",+ "docs/REVIEW_IMAGES_PREVIEW_2026-09-08.md: independent scoped PASS; final phase7 3e2dd555...41.144s; save retry and image matrix independently verified"],"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb","localDelivery": "capture_fix_candidate_needs_review",@@ -157,7 +169,7 @@"report": "docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md","baselineCommit": "ddc515d","exeSha256": "2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6",- "updatedAt": "2026-09-07T19:38:07.275382+00:00",+ "updatedAt": "2026-09-08T03:38:07.275382+08:00","softwareEvidence": ["logs/ui-dual-mode/de337338b71e43618c4beaa488d54afb/result.json","logs/repair-v2/joint-91436d0b0f4145c2b6fe6794ff146c68/result.json",@@ -193,7 +205,7 @@"logs/repair-v2/joint-f3c40457ea02481c87dfce0739f51c74/result.json","logs/ui-dual-mode/4k-719b7f3002fa42b88abbad8ba0262137/result.json"],- "updatedAt": "2026-09-08T03:16:19.278371+00:00",+ "updatedAt": "2026-09-08T11:16:19.278371+08:00","testLimitScope": "per_invocation","testLimitSeconds": 300,"desktopMaterial": "Windows Desktop Acrylic; actual independent red/blue behind-window proof; empty video opaque black",@@ -230,5 +242,25 @@"phaseApprovalUnchanged": true,"captureHardwareTested": false,"nextAction": "User validates direct toolbar and themed selectors; existing capture acceptance remains with user."+ },+ "historicalPhase7AtOptimizationStart": {+ "id": 7,+ "name": "Capture latency repair; physical throughput retested, review/user experience pending",+ "status": "gate_passed",+ "gateEvidence": "logs/delivery/01b72df768524af9ab0aa8d2e3dbb59e/result.json plus logs/capture-fix-20260907/final-nr-fg.log; capture latency repair candidate",+ "reviewEvidence": "Current repair attempt ended without a final reviewer verdict. docs/REVIEW_F6.md applies only to the historical checkpoint below.",+ "commit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031"+ },+ "optimizationGoal": {+ "status": "running",+ "baselineCommit": "f79ef95deb2dc0375e7a2adb936e7d4d4298f93a",+ "plan": "docs/QUALITY_OPTIMIZATION_PLAN_2026-09-08.md",+ "exportIntegrityChecks": "unchanged",+ "testInvocationLimitSeconds": 300,+ "productModified": true,+ "consecutiveBlockedGoalTurns": 0,+ "previousGoalTurnClassification": "progress: static FG isolation, long native NR evidence",+ "currentGoalTurnClassification": "progress: >16384 tiled images in app with full-size save, professional viewport zoom, current gates passed",+ "controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization"}}diff --git a/scripts/gates/delivery.ps1 b/scripts/gates/delivery.ps1index 129e6fe4..10a29fd5 100644--- a/scripts/gates/delivery.ps1+++ b/scripts/gates/delivery.ps1@@ -53,7 +53,12 @@ try{Run "inspect-$codec" $ffprobe @('-v','error','-count_frames','-show_streams','-of','json',$file) 10$streams=(Get-Content "$dir/inspect-$codec.stdout.log" -Raw|ConvertFrom-Json).streams$v=@($streams|Where-Object codec_type -eq 'video')[0];$a=@($streams|Where-Object codec_type -eq 'audio')- Check "decode-$codec" ($v.width -eq 3840 -and $v.height -eq 2160 -and $v.codec_name -eq $codec -and [int]$v.nb_read_frames -eq 23 -and $a.Count -ge 1) 'all short exported frames decoded; native4K 2X CFR timeline + audio'+ # The approved CFR tail policy preserves all 12/60 seconds: 12 source+ # pictures + 11 actual interpolations + 1 explicit tail hold = 24/120.+ # This is a developer gate only; the per-export integrity path is unchanged.+ $exportLog=Get-Content "$dir/export-$codec.stdout.log" -Raw+ Check "frame-kinds-$codec" ($exportLog -match 'export-counts\] source=12 generated=11 hold=1 output=24 multiplier=2') '12 real + 11 generated + 1 declared CFR tail hold; never count hold as DLSSG'+ Check "decode-$codec" ($v.width -eq 3840 -and $v.height -eq 2160 -and $v.codec_name -eq $codec -and [int]$v.nb_read_frames -eq 24 -and $v.avg_frame_rate -eq '120/1' -and [math]::Abs([double]$v.duration-0.2) -lt 0.00001 -and $a.Count -ge 1) 'all short frames decoded; native4K 2X CFR frame count, duration, rate and audio'}Run cancel "$bin/veyra.exe" @($clip4k,'--export-out',"$dir/cancel.mp4",'--cancel-after-ms','3000') 15 3Check cancel-not-success ((-not (Test-Path "$dir/cancel.mp4")) -and (Test-Path "$dir/cancel.mp4.partial")) 'cancel drains with live callback; never promotes incomplete output'diff --git a/scripts/loop-gate.ps1 b/scripts/loop-gate.ps1index e08438f8..b740b911 100644--- a/scripts/loop-gate.ps1+++ b/scripts/loop-gate.ps1@@ -157,7 +157,7 @@ foreach ($requiredFile in $requiredFiles) {}$controlManifestPath = Join-Path $root "loop\CONTROL_HASHES.json"-$expectedControlManifestHash = "26559334D3A520682A42B20FD8127F3F297E70686CF139DC9325087047FDC8FC"+$expectedControlManifestHash = "4D5A30F73E06B59B3D6AD5D4A0AE106A0C3AD808D758418B21CC339D2E28779B"if (Test-Path -LiteralPath $controlManifestPath -PathType Leaf) {$actualControlManifestHash = (Get-FileHash -LiteralPath $controlManifestPath -Algorithm SHA256).Hash.ToUpperInvariant()$manifestHashValid = $actualControlManifestHash -eq $expectedControlManifestHashdiff --git a/shaders/PresentBlit.hlsl b/shaders/PresentBlit.hlslindex 0223405c..a072557f 100644--- a/shaders/PresentBlit.hlsl+++ b/shaders/PresentBlit.hlsl@@ -30,9 +30,14 @@ VSOut vsMain(uint vertexId : SV_VertexID)float4 psMain(VSOut input) : SV_Target{- (void)srcDims;- (void)dstDims;- float4 color=sourceTex.SampleLevel(linearClamp,input.uv,0);+ // zoom==0 retains the original contract for diagnostic harness callers.+ float2 uv=input.uv;+ if(srcDims.w>0){+ float fit=min(dstDims.x/srcDims.x,dstDims.y/srcDims.y)*srcDims.w;+ uv=(input.uv-.5)*dstDims.xy/(srcDims.xy*fit)+dstDims.zw;+ if(any(uv<0)||any(uv>1))return float4(0,0,0,1);+ }+ float4 color=sourceTex.SampleLevel(linearClamp,uv,0);if(srcDims.z>0.5){float3 c=max(color.rgb,0);color.rgb=lerp(1.055*pow(c,1.0/2.4)-0.055,c*12.92,step(c,0.0031308));}return color;}diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlslnew file mode 100644index 00000000..273c6594--- /dev/null+++ b/shaders/RgbToLinear.hlsl@@ -0,0 +1,15 @@+cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint reserved; };+Texture2D<float4> sourceRgb : register(t0);+RWTexture2D<float4> linearRgb : register(u0);+float decode(float v) {+ if (transfer == 2) return v < 0.081 ? v / 4.5 : pow((v + 0.099) / 1.099, 1.0 / 0.45);+ if (transfer == 0) return v;+ return v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4);+}+[numthreads(16,16,1)]+void main(uint3 p : SV_DispatchThreadID) {+ if (p.x >= width || p.y >= height) return;+ float4 c=sourceRgb[p.xy];+ // Present onto the player's opaque black canvas; never discard RGB chroma.+ linearRgb[p.xy]=float4(float3(decode(c.r),decode(c.g),decode(c.b))*c.a,1);+}diff --git a/shaders/ScaleBlit.hlsl b/shaders/ScaleBlit.hlslindex 06af2653..da890c92 100644--- a/shaders/ScaleBlit.hlsl+++ b/shaders/ScaleBlit.hlsl@@ -25,6 +25,11 @@ void main(uint3 groupId : SV_GroupID, uint3 localId : SV_GroupThreadID, uint3 glif (globalId.x >= outputWidth || globalId.y >= outputHeight) {return;}+ float4 value;+ if(sourceWidth==outputWidth&&sourceHeight==outputHeight){+ // Avoid reciprocal/interpolation rounding on tall 1:1 images.+ value=sourceTex[globalId.xy];+ }else{// Map output pixel center back into source coordinates.const float scaleX = float(sourceWidth) / float(outputWidth);const float scaleY = float(sourceHeight) / float(outputHeight);@@ -44,7 +49,8 @@ void main(uint3 groupId : SV_GroupID, uint3 localId : SV_GroupThreadID, uint3 glconst float4 s11 = sourceTex[uint2(x1, y1)];const float4 top = lerp(s00, s10, fx);const float4 bottom = lerp(s01, s11, fx);- float4 value = lerp(top, bottom, fy);+ value = lerp(top, bottom, fy);+ }if (encodeSrgb > 0.5) {const float3 c = max(value.rgb, 0.0);value.rgb = select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0/2.4) - 0.055);diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 6f09749f..e1144d54 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -42,7 +42,7 @@ void EngineController::dispatch(){void EngineController::post(std::function<void()> task){ {std::lock_guard lock(mutex_);stop_=true;pending_=std::move(task);}wake_.notify_one(); }bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!pending_;}void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){- {std::lock_guard lock(mutex_);snapshot_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ {std::lock_guard lock(mutex_);snapshot_={};previewView_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}@@ -50,7 +50,7 @@ void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(svoid EngineController::setVolume(float gain,bool mute){if(!std::isfinite(gain))return;volume_=std::clamp(gain,0.0f,1.0f);muted_=mute;}bool EngineController::requestSettings(EnhancementSettings s){if(!s.validate().empty()){veyra::log::warn("settings","invalid whole settings transaction rejected");status(L"整套设置无效,未应用任何字段",false);return false;}- std::lock_guard lock(mutex_);s.revision=++nextRevision_;desired_=s;snapshot_.desired=s;snapshot_.applying=true;return true;+ std::lock_guard lock(mutex_);if(snapshot_.image)s.multiplier=1;s.revision=++nextRevision_;desired_=s;snapshot_.desired=s;snapshot_.applying=true;return true;}void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(mutex_);savePath_=path;}void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){@@ -77,17 +77,21 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){uint32_t width=0,height=0;double duration=0;if(isImage){if(!sink::loadImage(path,image)){status(L"无法解码PNG/JPEG",true);break;}- imageFrame=av_frame_alloc();imageFrame->format=AV_PIX_FMT_RGBA;imageFrame->width=image.width;imageFrame->height=image.height;imageFrame->pts=0;imageFrame->color_range=AVCOL_RANGE_JPEG;+ if(!pipeline::Extent{image.width,image.height}.valid()||uint64_t(image.width)*image.height>16777216){+ runLargeImage(window,image,options,ctx,ring);break;+ }+ imageFrame=av_frame_alloc();imageFrame->format=AV_PIX_FMT_RGBA;imageFrame->width=image.width;imageFrame->height=image.height;imageFrame->pts=0;imageFrame->color_range=AVCOL_RANGE_JPEG;imageFrame->colorspace=AVCOL_SPC_RGB;imageFrame->color_trc=AVCOL_TRC_IEC61966_2_1;if(av_frame_get_buffer(imageFrame,32)<0){status(L"图片资源分配失败",true);break;}for(unsigned y=0;y<image.height;++y)memcpy(imageFrame->data[0]+size_t(y)*imageFrame->linesize[0],image.pixels.data()+size_t(y)*image.width*4,size_t(image.width)*4);width=image.width;height=image.height;options.fg=false;+ {std::lock_guard lock(mutex_);desired_.multiplier=1;snapshot_.image=true;snapshot_.desired=desired_;}}else{source::SourceOpenDesc od;od.path=path;od.preferHardwareDecode=false;if(!(isCapture?captureSource.configure(od):activeSource->open(od))){status(L"无法打开视频,请查看诊断",true);break;}width=activeSource->info().width;height=activeSource->info().height;duration=activeSource->info().duration.toDouble();}- if(width>3840||height>2160||width%2||height%2){status(L"仅支持偶数尺寸SDR输入,最大3840×2160",true);break;}- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;+ if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.rgbInput=isImage;gd.stillImage=isImage;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;@@ -109,8 +113,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){// Save the currently displayed result before a settings transaction// invalidates it. Keep a request queued until a frame exists.std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}- if(!save.empty()){sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();- if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在)",true);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}+ if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();+ if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}+ catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}+ if(isImage)requested.multiplier=1;const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;if(requested.revision!=previous.revision){auto next=PlayerOptions::from(requested);auto nextDesc=gd;@@ -133,7 +139,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){}if(!transaction&&((paused_&&seek<0)||(isImage&&hasOutput))){if(audioStarted)audioPipe.setPaused(true);wasPaused=true;- if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity)){status(L"画面呈现失败",true);break;}+ if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){status(L"画面呈现失败",true);break;}std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;}if(wasPaused&&!paused_){if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}@@ -190,7 +196,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){frameWaitMs+=elapsedMs(waitStart);if(stop_||paused_||seekSeconds_>=0){interrupted=true;break;}const auto begin=Clock::now();const auto before=presenter.submittedCount();- if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity)){presentFailed=true;break;}+ if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}framePresentMs+=elapsedMs(begin);item.lease->consumerFence=ring.lastSignaledValue();if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}diff --git a/src/engine/EngineControllerImage.cpp b/src/engine/EngineControllerImage.cppnew file mode 100644index 00000000..c27f9cee--- /dev/null+++ b/src/engine/EngineControllerImage.cpp@@ -0,0 +1,92 @@+#include "veyra/engine/EngineController.h"+#include "veyra/engine/TiledImageProcessor.h"+#include "veyra/engine/VideoPresenter.h"+#include "veyra/gfx/CommandSlotRing.h"+#include <filesystem>+#include <format>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}+namespace veyra::engine {+void EngineController::runLargeImage(HWND window,const sink::RgbaImage& original,PlayerOptions options,+ gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring) {+ {std::lock_guard lock(mutex_);snapshot_.image=true;snapshot_.running=true;desired_.multiplier=1;snapshot_.desired=desired_;}+ // A bounded presentation texture is independent of the full-resolution+ // result retained for saving. Preview changes never rerun the NR tiles.+ RECT initialClient{};GetClientRect(window,&initialClient);+ const uint32_t width=uint32_t(std::clamp(initialClient.right,1L,2048L)),height=uint32_t(std::clamp(initialClient.bottom,1L,2048L));+ pipeline::EnhanceGraphDesc previewDesc;previewDesc.sourceWidth=previewDesc.workWidth=width;previewDesc.sourceHeight=previewDesc.workHeight=height;+ previewDesc.rgbInput=true;previewDesc.stillImage=true;previewDesc.noFeatures=true;previewDesc.enableNr=false;previewDesc.enableFg=false;+ pipeline::EnhanceGraph preview(ctx,ring);VideoPresenter presenter;+ struct Cleanup {+ gfx::CommandSlotRing& ring;VideoPresenter& presenter;pipeline::EnhanceGraph& graph;+ ~Cleanup(){ring.drainQueue();presenter.close();graph.shutdown();}+ } cleanup{ring,presenter,preview};+ if(!preview.initialize(previewDesc)||!presenter.open(ctx,window,preview)||!preview.createViews()){status(L"大图预览初始化失败",true);return;}+ const auto freeFrame=[](AVFrame* p){av_frame_free(&p);};std::unique_ptr<AVFrame,decltype(freeFrame)> frame(av_frame_alloc(),freeFrame);+ if(!frame){status(L"大图预览内存不足",true);return;}+ frame->format=AV_PIX_FMT_RGBA;frame->width=width;frame->height=height;+ frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;frame->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(frame.get(),32)<0){status(L"大图预览内存不足",true);return;}+ sink::RgbaImage enhanced;EnhancementSettings applied;applied.revision=0;+ pipeline::EnhanceGraph::FrameOutputs out;bool havePreview=false;+ int lastComparison=-1;float lastSplit=-1;uint64_t previewRevision=0;PreviewView lastView;RECT lastClient{};+ while(!stop_){+ EnhancementSettings requested;std::wstring save;+ {std::lock_guard lock(mutex_);requested=desired_;if(!enhanced.pixels.empty())save.swap(savePath_);}+ if(!save.empty()){+ try {+ auto ext=std::filesystem::path(save).extension().wstring();for(auto& c:ext)c=towlower(c);+ if(!sink::saveImage(save,enhanced,ext==L".jpg"||ext==L".jpeg"))status(L"图片保存失败(目标可能已存在)",false);+ else {status(L"图片已保存,完整结果仍可继续预览");veyra::log::info("image-save",std::format("tiled full-resolution saved extent={}x{} revision={}",enhanced.width,enhanced.height,applied.revision));}+ }catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining full result/session: {}",e.what()));status(L"保存异常,增强结果已保留;可再次保存",false);}+ }+ 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.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();+ sink::RgbaImage candidate;TiledImageProcessor::Stats stats;+ status(L"正在分块增强大图,保留完整输出尺寸…");+ bool processed=false;+ try{processed=TiledImageProcessor::process(ctx,ring,original,candidate,desc,stop_,stats,[this](uint32_t n,uint32_t total){status(std::format(L"大图分块增强 {}/{} · 每块独立上下文",n,total));});}+ catch(const std::exception& e){veyra::log::warn("image-tiles",std::format("settings exception; retaining previous result: {}",e.what()));}+ if(!processed){+ if(stop_)break;+ if(enhanced.pixels.empty()){status(L"大图分块增强失败,请查看诊断",true);break;}+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=applied;+ snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=false;+ snapshot_.status=L"大图参数应用失败,已保留上一结果";continue;+ }+ enhanced=std::move(candidate);applied=requested;lastComparison=-1;+ {std::lock_guard lock(mutex_);snapshot_.applied=applied;snapshot_.desired=desired_;snapshot_.applying=desired_.revision!=applied.revision;+ snapshot_.nrEvaluated=stats.nrEvaluations;snapshot_.frames=1;snapshot_.transport=TransportState::Playing;+ auto& plan=snapshot_.metrics.resolution;plan.source=plan.base=plan.output={original.width,original.height};plan.nr={std::min(1280u,original.width)+256,std::min(1280u,original.height)+256};plan.flow=plan.fg={};plan.srApplied=false;plan.settingsRevision=applied.revision;+ snapshot_.status=std::format(L"{}×{} · 分块NR(非整图上下文)· 保存保留完整尺寸",original.width,original.height);}+ }+ const int comparison=comparisonMode_.load();const float split=comparisonSplit_.load();+ const auto view=previewView();RECT client{};GetClientRect(window,&client);+ if(client.right<1||client.bottom<1){std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;}+ if(comparison!=lastComparison||split!=lastSplit||view!=lastView||client.right!=lastClient.right||client.bottom!=lastClient.bottom){+ // Source and enhanced use exactly the same coordinates. The full+ // image buffers, rather than the preview, remain the save source.+ for(uint32_t y=0;y<height;++y)for(uint32_t x=0;x<width;++x){+ const double fit=std::min(double(client.right)/original.width,double(client.bottom)/original.height)*view.zoom;+ const double u=((x+.5)/width-.5)*client.right/(original.width*fit)+view.centerX;+ const double v=((y+.5)/height-.5)*client.bottom/(original.height*fit)+view.centerY;+ auto* dst=frame->data[0]+size_t(y)*frame->linesize[0]+size_t(x)*4;+ if(u<0||u>=1||v<0||v>=1){dst[0]=dst[1]=dst[2]=0;dst[3]=255;continue;}+ const uint32_t sx=std::min(original.width-1,uint32_t(u*original.width)),sy=std::min(original.height-1,uint32_t(v*original.height));+ const bool reference=comparison==1||(comparison==2&&u<split);+ const auto& image=reference?original:enhanced;+ memcpy(dst,image.pixels.data()+(size_t(sy)*image.width+sx)*4,4);+ }+ out={};if(!preview.process(frame.get(),0,true,out,++previewRevision)){status(L"大图预览上传失败",true);break;}+ havePreview=true;lastComparison=comparison;lastSplit=split;lastView=view;lastClient=client;+ }+ if(havePreview&&!presenter.present(ctx,ring,preview,out.videoSlot,false,0,false,.5f,{},PreviewView{0,.5f,.5f})){status(L"大图呈现失败",true);break;}+ std::this_thread::sleep_for(std::chrono::milliseconds(16));+ }+ out={}; // Cleanup drains before either presenter or graph releases GPU objects.+}+}diff --git a/src/engine/TiledImageProcessor.cpp b/src/engine/TiledImageProcessor.cppnew file mode 100644index 00000000..586db3ec--- /dev/null+++ b/src/engine/TiledImageProcessor.cpp@@ -0,0 +1,79 @@+#include "veyra/engine/TiledImageProcessor.h"+#include "veyra/gfx/CommandSlotRing.h"+#include <algorithm>+#include <cmath>+#include <format>+#include <limits>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}+namespace veyra::engine {+bool TiledImageProcessor::process(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,+ const sink::RgbaImage& input,sink::RgbaImage& output,pipeline::EnhanceGraphDesc desc,+ const std::atomic<bool>& cancel,Stats& stats,const std::function<void(uint32_t,uint32_t)>& progress) {+ stats={};output={};+ const uint64_t pixels=uint64_t(input.width)*input.height;+ if(!input.width||!input.height||pixels>std::numeric_limits<size_t>::max()/4||input.pixels.size()!=pixels*4||cancel)return false;+ // This path preserves input resolution; SR is not an implicit tile resize.+ if(desc.enableSr){veyra::log::error("image-tiles","SR requires a separate full-image output plan");return false;}+ constexpr uint32_t coreLimit=1280,halo=128,overlap=64;+ const uint32_t coreW=std::min(coreLimit,input.width),coreH=std::min(coreLimit,input.height);+ const uint32_t tileW=coreW+2*halo,tileH=coreH+2*halo;+ const uint32_t countX=(input.width-1)/coreW+1,countY=(input.height-1)/coreH+1;+ if(uint64_t(countX)*countY>UINT32_MAX)return false;+ const uint32_t total=countX*countY;+ desc.sourceWidth=desc.workWidth=desc.nrWidth=tileW;+ desc.sourceHeight=desc.workHeight=desc.nrHeight=tileH;+ desc.rgbInput=true;desc.stillImage=true;desc.enableFg=false;desc.enableNvofStandalone=false;+ pipeline::EnhanceGraph graph(ctx,ring);+ if(!graph.initialize(desc)||!graph.createViews())return false;+ AVFrame* raw=av_frame_alloc();+ const auto freeFrame=[](AVFrame* p){av_frame_free(&p);};+ std::unique_ptr<AVFrame,decltype(freeFrame)> frame(raw,freeFrame);+ if(!frame)return false;+ frame->format=AV_PIX_FMT_RGBA;frame->width=tileW;frame->height=tileH;+ frame->color_range=AVCOL_RANGE_JPEG;frame->color_trc=AVCOL_TRC_IEC61966_2_1;frame->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(frame.get(),32)<0)return false;+ sink::RgbaImage result;result.width=input.width;result.height=input.height;+ std::vector<float> weights;+ try{result.pixels.resize(size_t(pixels)*4);weights.resize(size_t(pixels));}+ catch(const std::bad_alloc&){veyra::log::error("image-tiles","insufficient host memory for full-resolution image");return false;}+ for(uint32_t row=0;row<countY;++row)for(uint32_t col=0;col<countX;++col){+ if(cancel)return false;+ const int64_t originX=int64_t(col)*coreW,originY=int64_t(row)*coreH;+ for(uint32_t y=0;y<tileH;++y){+ const auto sy=uint32_t(std::clamp(originY+int64_t(y)-halo,int64_t(0),int64_t(input.height)-1));+ auto* dst=frame->data[0]+size_t(y)*frame->linesize[0];+ for(uint32_t x=0;x<tileW;++x){+ const auto sx=uint32_t(std::clamp(originX+int64_t(x)-halo,int64_t(0),int64_t(input.width)-1));+ memcpy(dst+size_t(x)*4,input.pixels.data()+(size_t(sy)*input.width+sx)*4,4);+ }+ }+ 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)||+ !sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),tile))return false;+ if(tile.width!=tileW||tile.height!=tileH)return false;+ out={};+ const int64_t x0=std::max(int64_t(0),originX-overlap),y0=std::max(int64_t(0),originY-overlap);+ const int64_t x1=std::min(int64_t(input.width),originX+coreW+overlap),y1=std::min(int64_t(input.height),originY+coreH+overlap);+ for(int64_t y=y0;y<y1;++y)for(int64_t x=x0;x<x1;++x){+ const auto ramp=[](int64_t p,int64_t origin,uint32_t core){+ return std::min({1.0f,float(p-origin+overlap+1)/overlap,float(origin+core+overlap-p)/overlap});+ };+ const float weight=ramp(x,originX,coreW)*ramp(y,originY,coreH);+ const size_t index=size_t(y)*input.width+size_t(x);+ const size_t tileIndex=(size_t(y-originY+halo)*tileW+size_t(x-originX+halo))*4;+ const float sum=weights[index]+weight;+ for(unsigned c=0;c<4;++c)result.pixels[index*4+c]=uint8_t(std::clamp(std::lround((result.pixels[index*4+c]*weights[index]+tile.pixels[tileIndex+c]*weight)/sum),0l,255l));+ weights[index]=sum;+ }+ ++stats.tiles;stats.nrEvaluations=graph.metrics().nrEvaluateCount;+ if(progress)progress(stats.tiles,total);+ }+ if(cancel||!ring.drainQueue())return false;+ veyra::log::info("image-tiles",std::format("full={}x{} gpuTile={}x{} tiles={} NR={} contextHalo={} overlap={} resetEachTile=1",input.width,input.height,tileW,tileH,stats.tiles,stats.nrEvaluations,halo,overlap));+ output=std::move(result);return true;+}+}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex 3623ab08..bf3b1479 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -17,7 +17,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhreturn true;}void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}-bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity) {+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;const auto now=std::chrono::steady_clock::now();const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));@@ -39,18 +39,17 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// Compute contain in CURRENT client coordinates, then map back to buffer// coordinates so that the onscreen image keeps its aspect throughout.const float scale=std::min(float(rc.right)/graph.workWidth(),float(rc.bottom)/graph.workHeight());- const float w=graph.workWidth()*scale*sink_.bufferWidth()/rc.right,h=graph.workHeight()*scale*sink_.bufferHeight()/rc.bottom;- D3D12_VIEWPORT viewport{(sink_.bufferWidth()-w)*0.5f,(sink_.bufferHeight()-h)*0.5f,w,h,0,1};+ D3D12_VIEWPORT viewport{0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,1};D3D12_RECT rect{0,0,LONG(sink_.bufferWidth()),LONG(sink_.bufferHeight())};list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&rect);ID3D12DescriptorHeap* heaps[]={pass_.heap.Get()};list->SetDescriptorHeaps(1,heaps);list->SetGraphicsRootSignature(pass_.rootSig.Get());list->SetPipelineState(pass_.pso.Get());- float dims[8]={float(graph.workWidth()),float(graph.workHeight()),0,0,float(sink_.bufferWidth()),float(sink_.bufferHeight()),0,0};list->SetGraphicsRoot32BitConstants(0,8,dims,0);+ float dims[8]={float(graph.workWidth()),float(graph.workHeight()),0,view.zoom,float(rc.right),float(rc.bottom),view.centerX,view.centerY};list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);if(comparison&&!generated){auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);dims[2]=1;list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(8+slot+(baseReference?2:0))*pass_.increment});- if(comparison==2)rect.right=LONG(viewport.TopLeftX+viewport.Width*std::clamp(split,0.0f,1.0f));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);+ if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*graph.workWidth()*scale*view.zoom)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 30385e59..a5d00f4d 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -67,18 +67,21 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)nrW_=desc.nrWidth?desc.nrWidth:workW_; nrH_=desc.nrHeight?desc.nrHeight:workH_;nvofW_ = srcW_;nvofH_ = srcH_;+ if(!Extent{srcW_,srcH_}.valid()||!Extent{workW_,workH_}.valid()){+ veyra::log::error("resolution","source/output exceeds D3D12 texture dimensions or is empty");return false;+ }if(!Extent{nrW_,nrH_}.valid()||nrW_>workW_||nrH_>workH_){veyra::log::error("resolution","invalid NR extent");return false;}veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));srEnabled_ = desc.enableSr;nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;- fgEnabled_ = desc.enableFg && !desc.noNgx;+ fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage;nvofStandalone_ = desc.enableNvofStandalone && !desc.noFeatures;Status st = Status::Ok;lumaPitch_ = (static_cast<size_t>(srcW_) + 255) & ~size_t(255);chromaPitch_ = lumaPitch_;lumaSize_ = lumaPitch_ * srcH_;- chromaSize_ = chromaPitch_ * (srcH_ / 2);+ chromaSize_ = chromaPitch_ * ((srcH_ + 1) / 2);dPitch_ = (static_cast<size_t>(workW_) * 4 + 255) & ~size_t(255);const size_t dSize = dPitch_ * workH_;nv12Buf_.resize(lumaSize_ + chromaSize_);@@ -125,7 +128,15 @@ bool EnhanceGraph::createResources()upZeroDepth_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);upZeroMotion_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);lumaTex_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R8_UNORM, true);- chromaTex_ = makeTexture(context_.device(), srcW_ / 2, srcH_ / 2, DXGI_FORMAT_R8G8_UNORM, true);+ chromaTex_ = makeTexture(context_.device(), (srcW_+1) / 2, (srcH_+1) / 2, DXGI_FORMAT_R8G8_UNORM, true);+ if(desc_.rgbInput){+ rgbPitch_=(size_t(srcW_)*4+255)&~size_t(255);+ rgbTex_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,false);+ if(!rgbTex_)return false;+ for(unsigned i=0;i<2;++i){upRgb_[i]=makeUploadBuffer(context_.device(),rgbPitch_*srcH_);+ if(!upRgb_[i]||FAILED(upRgb_[i]->Map(0,nullptr,reinterpret_cast<void**>(&mappedRgb_[i]))))return false;+ }+ }srcRgba_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);workRgba_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}@@ -250,6 +261,7 @@ bool EnhanceGraph::initZeroAndDepthTextures()bool EnhanceGraph::initNvof(){+ if(desc_.stillImage){mvecSource_="single-image (no temporal motion)";return true;}if (desc_.noFeatures) {veyra::log::info("graph", "VEYRA_NO_FEATURES: NVOF session skipped");return true;@@ -317,6 +329,9 @@ bool EnhanceGraph::initNgxFeatures()return false;}+ fgCapsAvailable_ = false;+ fgMultiFrameMax_ = 0;+ if (!desc_.stillImage) {fgBackend_ = std::make_unique<ngx::DlssFgBackend>();ngx::DlssFgBackend::Capability fgCaps{};const bool fgAvailable = fgBackend_->queryCapability(*coreHost_, fgCaps, st);@@ -329,6 +344,7 @@ bool EnhanceGraph::initNgxFeatures()fgMultiFrameMax_ = fgCaps.multiFrameCountMax;veyra::log::info("graph", std::format("FG capability available={} multiFrameMax={}",fgCaps.available, fgCaps.multiFrameCountMax));+ }nrAdapter_ = std::make_unique<ngx::DlssNrRuntimeAdapter>();if (!nrAdapter_->load(desc_.runtimeAbsPath.c_str(), st) ||@@ -385,10 +401,11 @@ bool EnhanceGraph::initNgxFeatures()(void)ring_.waitIdle();}+ // Still images have no temporal pair and must not depend on FG support.// FG create + warm-up evaluate BEFORE descriptor views (the runtime// allocates internals at the first evaluate and would fail after views// exist on this system).- {+ if (!desc_.stillImage) {ngx::DlssFgBackend::CreateDesc fd{};fd.width = workW_; fd.height = workH_;fd.renderWidth = workW_; fd.renderHeight = workH_;@@ -455,6 +472,7 @@ bool EnhanceGraph::createComputePasses()if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1))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;if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8, 1, 1)) return false;if (!decPass_.loadShader("ParityDecode.dxil", cs) || !decPass_.create(context_.device(), cs, 8)) return false;if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 16, 1, 1)) return false;@@ -516,6 +534,10 @@ bool EnhanceGraph::createViews()makeUav(context_.device(),nrFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,1));makeUav(context_.device(),baseFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,2));// Immutable per-resource views.+ if(desc_.rgbInput){+ stagedSrv(rgbTex_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,rgbPass_,0);+ makeUav(context_.device(),srcRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(rgbPass_,1));+ }if (viewsTex) stagedSrv(lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, yuvPass_, 0);if (viewsTex) stagedSrv(chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);if (viewsUav) makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));@@ -628,7 +650,23 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameif (list == nullptr) { veyra::log::error("graph", "ring acquire"); return false; }gpuTimer_.frame({epoch_,desc_.settingsRevision,realFrameIndex_+1},context_.fence());gpuTimer_.mark(list,GpuStage::Color);- if (frame->format == AV_PIX_FMT_D3D12) {+ if(desc_.rgbInput){+ if(frame->format!=AV_PIX_FMT_RGBA&&frame->format!=AV_PIX_FMT_BGRA){+ veyra::log::error("graph","direct RGB input contract requires RGBA/BGRA frame");return false;+ }+ if(frame->width!=int(srcW_)||frame->height!=int(srcH_))return false;+ for(uint32_t y=0;y<srcH_;++y){+ auto* dst=mappedRgb_[parity]+y*rgbPitch_;const auto* src=frame->data[0]+ptrdiff_t(y)*frame->linesize[0];+ if(frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(srcW_)*4);+ else for(uint32_t x=0;x<srcW_;++x){dst[x*4]=src[x*4+2];dst[x*4+1]=src[x*4+1];dst[x*4+2]=src[x*4];dst[x*4+3]=src[x*4+3];}+ }+ tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=rgbTex_.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;+ src.pResource=upRgb_[parity].Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,srcW_,srcH_,1,UINT(rgbPitch_)};+ list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);+ tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ } else if (frame->format == AV_PIX_FMT_D3D12) {auto* d3dFrame = reinterpret_cast<AVD3D12VAFrame*>(frame->data[0]);if (d3dFrame == nullptr || d3dFrame->texture == nullptr) {veyra::log::error("graph", "null d3d12va frame");@@ -714,8 +752,8 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramepreviousLuma_=std::move(sample);if(!directUpload){for (uint32_t y = 0; y < srcH_; ++y)std::memcpy(mappedLuma_[parity] + y * lumaPitch_, planes[0] + y * lumaPitch_, srcW_);- for (uint32_t y = 0; y < srcH_ / 2; ++y)- std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, srcW_);}+ for (uint32_t y = 0; y < (srcH_+1) / 2; ++y)+ std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, ((srcW_+1)/2)*2);}auto copyPlane = [&](ID3D12Resource* texture, ID3D12Resource* upload,DXGI_FORMAT format, UINT width, UINT height, UINT pitch) {tracker_.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);@@ -730,7 +768,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramecopyPlane(lumaTex_.Get(), upLuma_[parity].Get(), DXGI_FORMAT_R8_UNORM,srcW_, srcH_, static_cast<UINT>(lumaPitch_));copyPlane(chromaTex_.Get(), upChroma_[parity].Get(), DXGI_FORMAT_R8G8_UNORM,- srcW_/2, srcH_/2, static_cast<UINT>(chromaPitch_));+ (srcW_+1)/2, (srcH_+1)/2, static_cast<UINT>(chromaPitch_));tracker_.transition(list, lumaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}@@ -738,7 +776,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// 2. YUV -> RGBA16F.tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- {+ if(desc_.rgbInput){+ const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(frame->color_trc==AVCOL_TRC_LINEAR?0u:(frame->color_trc==AVCOL_TRC_BT709?2u:1u)),0,0,0,0,0};+ rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);+ list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);+ }else{const float constants[8] = { frame->color_range == AVCOL_RANGE_JPEG ? 0.0f : 1.0f,(frame->colorspace == AVCOL_SPC_BT470BG || frame->colorspace == AVCOL_SPC_SMPTE170M) ? 0.0f : 1.0f,(frame->color_trc == AVCOL_TRC_BT709 || frame->color_trc == AVCOL_TRC_SMPTE170M) ? 2.0f : 1.0f, 0.0f,@@ -1044,7 +1086,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_.fgMultiplier=std::max(2u,s.multiplier);desc_.enableNvofStandalone=s.nr;nvofStandalone_=s.nr;+ 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));return true;@@ -1140,6 +1182,8 @@ void EnhanceGraph::shutdown()// Staged explicit release (scope-end destructors then have nothing left).decPass_ = ComputePass{};+ rgbPass_={};rgbTex_.Reset();+ for(unsigned i=0;i<2;++i){if(upRgb_[i]&&mappedRgb_[i])upRgb_[i]->Unmap(0,nullptr);mappedRgb_[i]=nullptr;upRgb_[i].Reset();}downsamplePass_={};residualPass_={};flowAdaptPass_={};nrInput_.Reset();residualRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();for(unsigned i=0;i<6;++i){fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();diff --git a/src/sink/ImageExportSink.cpp b/src/sink/ImageExportSink.cppindex cd73201e..25f09938 100644--- a/src/sink/ImageExportSink.cpp+++ b/src/sink/ImageExportSink.cpp@@ -6,6 +6,7 @@#include <wrl/client.h>#include <cstring>#include <filesystem>+#include <limits>namespace veyra::sink {using Microsoft::WRL::ComPtr;bool readRgba8(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,RgbaImage& img) {@@ -40,7 +41,12 @@ bool loadImage(const std::wstring& path,RgbaImage& img) {FAILED(fac->CreateDecoderFromFilename(path.c_str(),nullptr,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&dec))||FAILED(dec->GetFrame(0,&frame))||FAILED(fac->CreateFormatConverter(&conv))||FAILED(conv->Initialize(frame.Get(),GUID_WICPixelFormat32bppRGBA,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom))||- FAILED(conv->GetSize(&img.width,&img.height))||img.width==0||img.height==0||img.width>8192||img.height>8192) return false;+ FAILED(conv->GetSize(&img.width,&img.height))||img.width==0||img.height==0) return false;+ // WIC CopyPixels has a UINT byte-count contract. Do not substitute an+ // arbitrary 4K/8K edge limit for checked byte arithmetic.+ if(uint64_t(img.width)*img.height>std::numeric_limits<UINT>::max()/4){+ log::error("image","decoded RGBA exceeds WIC CopyPixels buffer capacity");return false;+ }ComPtr<IWICMetadataQueryReader> metadata;UINT orientation=1;if(SUCCEEDED(frame->GetMetadataQueryReader(&metadata))){PROPVARIANT value{};@@ -56,23 +62,45 @@ bool loadImage(const std::wstring& path,RgbaImage& img) {return SUCCEEDED(oriented->CopyPixels(nullptr,img.width*4,static_cast<UINT>(img.pixels.size()),img.pixels.data()));}bool saveImage(const std::wstring& path,const RgbaImage& img,bool jpeg) {- if(img.pixels.size()!=size_t(img.width)*img.height*4||std::filesystem::exists(path))return false;+ const uint64_t pixelCount=uint64_t(img.width)*img.height;+ if(!img.width||!img.height||pixelCount>SIZE_MAX/4||img.pixels.size()!=pixelCount*4||std::filesystem::exists(path))return false;const auto temp=path+L".partial";- if(std::filesystem::exists(temp))return false;+ // Own the partial file exclusively; clean it on failure/exception after+ // WIC releases its handles. Never remove an existing caller's partial.+ HANDLE file=CreateFileW(temp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr);+ if(file==INVALID_HANDLE_VALUE)return false;+ CloseHandle(file);+ struct Partial {const std::wstring& path;bool active=true;~Partial(){if(active)DeleteFileW(path.c_str());}} partial{temp};ComPtr<IWICImagingFactory> fac;ComPtr<IWICStream> stream;ComPtr<IWICBitmapEncoder> enc;ComPtr<IWICBitmapFrameEncode> frame;ComPtr<IPropertyBag2> opts;if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&fac)))||FAILED(fac->CreateStream(&stream))||FAILED(stream->InitializeFromFilename(temp.c_str(),GENERIC_WRITE))||FAILED(fac->CreateEncoder(jpeg?GUID_ContainerFormatJpeg:GUID_ContainerFormatPng,nullptr,&enc))||FAILED(enc->Initialize(stream.Get(),WICBitmapEncoderNoCache))||FAILED(enc->CreateNewFrame(&frame,&opts))||FAILED(frame->Initialize(opts.Get()))||FAILED(frame->SetSize(img.width,img.height)))return false;- auto format=jpeg?GUID_WICPixelFormat24bppBGR:GUID_WICPixelFormat32bppRGBA;+ auto format=jpeg?GUID_WICPixelFormat24bppBGR:GUID_WICPixelFormat32bppBGRA;if(FAILED(frame->SetPixelFormat(&format)))return false;- std::vector<uint8_t> bgr;- const uint8_t* pixels=img.pixels.data();UINT stride=img.width*4;- if(jpeg){bgr.resize(size_t(img.width)*img.height*3);for(size_t i=0;i<img.pixels.size()/4;++i){bgr[i*3]=pixels[i*4+2];bgr[i*3+1]=pixels[i*4+1];bgr[i*3+2]=pixels[i*4];}pixels=bgr.data();stride=img.width*3;}- if(FAILED(frame->WritePixels(img.height,stride,stride*img.height,const_cast<BYTE*>(pixels)))||FAILED(frame->Commit())||FAILED(enc->Commit()))return false;+ if(format!=(jpeg?GUID_WICPixelFormat24bppBGR:GUID_WICPixelFormat32bppBGRA)){+ log::error("image","encoder negotiated an unsupported pixel format");return false;+ }+ const UINT channels=jpeg?3:4;+ if(!img.width||!img.height||img.width>UINT_MAX/channels)return false;+ const UINT stride=img.width*channels;+ const UINT bandHeight=std::min(img.height,std::max(1u,(8u*1024*1024)/stride));+ std::vector<uint8_t> bgr(size_t(stride)*bandHeight);+ for(UINT row=0;row<img.height;){+ const UINT rows=std::min(bandHeight,img.height-row);+ const auto* pixels=img.pixels.data()+size_t(row)*img.width*4;+ for(size_t i=0;i<size_t(rows)*img.width;++i){bgr[i*channels]=pixels[i*4+2];bgr[i*channels+1]=pixels[i*4+1];bgr[i*channels+2]=pixels[i*4];if(!jpeg)bgr[i*4+3]=pixels[i*4+3];}+ if(FAILED(frame->WritePixels(rows,stride,stride*rows,bgr.data())))return false;+ static LONG saveFaultInjected=0;+ if(GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)&&InterlockedCompareExchange(&saveFaultInjected,1,0)==0)throw std::bad_alloc();+ row+=rows;+ }+ if(FAILED(frame->Commit())||FAILED(enc->Commit()))return false;frame.Reset();enc.Reset();stream.Reset();RgbaImage check;if(!loadImage(temp,check)||check.width!=img.width||check.height!=img.height)return false;- return MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;+ const bool moved=MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;+ if(moved)partial.active=false;+ return moved;}}diff --git a/tests/integration/ImageDimensionTests.cpp b/tests/integration/ImageDimensionTests.cppnew file mode 100644index 00000000..14bfefaf--- /dev/null+++ b/tests/integration/ImageDimensionTests.cpp@@ -0,0 +1,93 @@+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/engine/EnhancementSettings.h"+#include "veyra/engine/TiledImageProcessor.h"+#include <filesystem>+#include <iostream>+#include <cmath>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/pixfmt.h>+}+using namespace veyra;+bool run(unsigned width,unsigned height,bool nr,const std::filesystem::path& directory){+ 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.workWidth=width;gd.sourceHeight=gd.workHeight=height;+ gd.rgbInput=true;gd.stillImage=true;gd.enableFg=false;gd.enableNr=nr;gd.noFeatures=!nr;+ gd.runtimeAbsPath=(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/nvidia").wstring();+ if(!graph.initialize(gd)||!graph.createViews())return false;+ if(graph.fgCapabilityAvailable()||graph.fgCreated())return false;+ graph.setFgEnabled(true);if(graph.fgEnabled())return false;+ engine::EnhancementSettings settings;settings.multiplier=2;+ if(graph.applySettings(settings))return false;+ AVFrame* f=av_frame_alloc();f->width=width;f->height=height;f->format=AV_PIX_FMT_RGBA;+ f->color_range=AVCOL_RANGE_JPEG;f->color_trc=AVCOL_TRC_IEC61966_2_1;f->colorspace=AVCOL_SPC_RGB;+ if(av_frame_get_buffer(f,32)<0){av_frame_free(&f);return false;}+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){auto* p=f->data[0]+size_t(y)*f->linesize[0]+x*4;+ p[0]=uint8_t((x*13+y*7)%256);p[1]=uint8_t((x*3+y*11)%256);p[2]=uint8_t((x*5+y*17+113)%256);p[3]=255;}+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage result;+ bool ok=graph.process(f,0,true,out,1)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result);+ int maxError=0;uint64_t brightness=0;+ if(ok){ok=result.width==width&&result.height==height;+ for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x)for(unsigned c=0;c<3;++c){const int value=result.pixels[(size_t(y)*width+x)*4+c];brightness+=value;maxError=std::max(maxError,std::abs(value-int(f->data[0][size_t(y)*f->linesize[0]+x*4+c])));}+ ok=ok&&brightness>0&&(nr?graph.metrics().nrEvaluateCount==1:maxError<=1);+ const auto path=directory/(std::to_string(width)+"x"+std::to_string(height)+(nr?"-nr.png":"-off.png"));+ sink::RgbaImage decoded;ok=ok&&sink::saveImage(path.wstring(),result)&&sink::loadImage(path.wstring(),decoded);+ ok=ok&&decoded.width==width&&decoded.height==height&&decoded.pixels==result.pixels;+ }+ std::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){+ 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);+ for(size_t i=0;i<source.pixels.size();i+=4){source.pixels[i]=uint8_t(i/4%251);source.pixels[i+1]=uint8_t(i/width%239);source.pixels[i+2]=113;source.pixels[i+3]=255;}+ // Independent display contract: half-transparent white composites to+ // 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();+ 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&&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;+ 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;+ std::cout<<"IMAGE_TILED_CANCEL pass="<<ok<<std::endl;+ }+ ring.shutdown();ctx.shutdown();return ok;+}+bool codecBands(const std::filesystem::path& directory){+ sink::RgbaImage source;source.width=1024;source.height=3073;source.pixels.resize(size_t(source.width)*source.height*4);+ for(unsigned y=0;y<source.height;++y)for(unsigned x=0;x<source.width;++x){auto* p=source.pixels.data()+(size_t(y)*source.width+x)*4;p[std::min(2u,y/1024)]=255;p[3]=255;}+ bool ok=true;+ for(bool jpeg:{false,true}){sink::RgbaImage decoded;const auto path=directory/(jpeg?"banded.jpg":"banded.png");+ ok=ok&&sink::saveImage(path.wstring(),source,jpeg)&&sink::loadImage(path.wstring(),decoded)&&decoded.width==source.width&&decoded.height==source.height;+ if(!ok)break;+ if(!jpeg)ok=decoded.pixels==source.pixels;+ else for(unsigned y:{512u,1536u,2560u})for(unsigned c=0;c<3;++c){auto i=(size_t(y)*source.width+512)*4+c;ok=ok&&std::abs(int(decoded.pixels[i])-int(source.pixels[i]))<=5;}+ }+ std::cout<<"IMAGE_CODEC_BANDS pass="<<ok<<std::endl;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;}}+ if(ok)ok=run(257,513,true,directory);+ if(ok)ok=run(97,9001,true,directory);+ if(ok)ok=tiled(17001,17,false,directory);+ if(ok)ok=tiled(17,17001,false,directory);+ if(ok)ok=tiled(97,17001,true,directory);+ if(ok)ok=codecBands(directory);+ CoUninitialize();return ok?0:1;+}diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cppindex 78a40ba7..b4c4eddc 100644--- a/tests/unit/UiContractTests.cpp+++ b/tests/unit/UiContractTests.cpp@@ -4,12 +4,17 @@#include "../../apps/veyra/ui/TransportLayout.h"#include "../../apps/veyra/ui/UiPreferenceStore.h"#include "veyra/sink/AudioGain.h"+#include "veyra/engine/PreviewView.h"#include <iostream>#include <vector>#include <stdexcept>void require(bool value,const char* why){if(!value)throw std::runtime_error(why);}int wmain(int argc,wchar_t** argv){try{using namespace veyra;+ {engine::PreviewView v;v.wheel(3,800,300,1000,600,1920,1080);require(std::abs(v.zoom-1.728f)<.0001f,"wheel scale");+ const float anchored=(800-500)/(1920.0f*(1000.0f/1920)*v.zoom)+v.centerX;require(std::abs(anchored-.8f)<.0001f,"pointer anchor fixed");+ v.wheel(-3,800,300,1000,600,1920,1080);require(std::abs(v.zoom-1)<.0001f&&std::abs(v.centerX-.5f)<.0001f,"inverse wheel returns same view");+ v.pan(100,0,1000,600,1920,1080);require(std::abs(v.centerX-.4f)<.0001f,"pan measured in displayed pixels");}ui::UiSessionState state;state.configured.multiplier=4;state.configured.sr=true;state.configured.model.intensity=.37f;state.configured.residual.color=1.4f;auto before=state.effective();require(state.mode==ui::Mode::Daily,"startup Daily");state.mode=ui::Mode::Professional;require(state.effective()==before,"mode cannot alter settings");state.enhanced=false;auto bypass=state.effective();require(!bypass.nr&&!bypass.sr&&bypass.multiplier==1,"true full bypass");state.enhanced=true;require(state.effective()==before,"restore all settings");ui::ChromeLayout daily(1440,900,false,false);require(daily.left==0&&daily.top==0&&daily.viewWidth==1440&&daily.viewHeight==812&&daily.bottom==812,"daily video owns all space above transport");