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++
feat(ui): implement daily cinema and professional workspace with isolated export
Veyra Goal Agentb6b251da8745
diff --git a/CMakeLists.txt b/CMakeLists.txtindex d2d1eb2a..25151186 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -430,7 +430,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/Subtitles.cpp)+ 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)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")@@ -440,7 +440,12 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_options(veyra_repair_preset_tests PRIVATE /utf-8)target_compile_definitions(veyra_repair_preset_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)target_include_directories(veyra_repair_preset_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)- add_executable(veyra WIN32 apps/veyra/main.cpp apps/veyra/SettingsWindow.cpp apps/veyra/TelemetryWindow.cpp)+ add_executable(veyra_ui_contract_tests tests/unit/UiContractTests.cpp src/engine/PresetStore.cpp)+ target_compile_features(veyra_ui_contract_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_ui_contract_tests PRIVATE /utf-8)+ target_compile_definitions(veyra_ui_contract_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_include_directories(veyra_ui_contract_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ add_executable(veyra WIN32 apps/veyra/main.cpp apps/veyra/ui/AppShell.cpp apps/veyra/ui/CapturePanel.cpp apps/veyra/ui/SubtitleOverlay.cpp apps/veyra/SettingsWindow.cpp apps/veyra/TelemetryWindow.cpp)target_compile_features(veyra PRIVATE cxx_std_20)target_compile_options(veyra PRIVATE /utf-8)target_link_libraries(veyra PRIVATE veyra_engine comctl32 comdlg32 shell32)@@ -504,3 +509,6 @@ if(VEYRA_CLIP_TOOLS_ROOT AND EXISTS "${VEYRA_CLIP_TOOLS_ROOT}/include/libavcodec"${VEYRA_CLIP_TOOLS_ROOT}/lib/avformat.lib""${VEYRA_CLIP_TOOLS_ROOT}/lib/avutil.lib")endif()++# Layered child subtitle windows require a modern-Windows compatibility manifest.+target_link_options(veyra PRIVATE "/MANIFESTINPUT:${CMAKE_CURRENT_SOURCE_DIR}/apps/veyra/veyra.manifest")diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 8c04f4bc..6279c5d8 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -1,50 +1,89 @@#include "SettingsWindow.h"+#include "ui/Theme.h"#include "veyra/engine/PresetStore.h"#include <filesystem>-#include "DpiWindow.h"#include <sstream>#include <iomanip>#include <array>namespace veyra::ui {namespace {-unsigned windowDpi=96;HWND window=nullptr;engine::EngineController* controller=nullptr;HFONT font=nullptr;-engine::PresetStore store(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/user-presets.v1");bool loaded=false;-const wchar_t* labels[]={L"模型强度 [0,1]",L"局部明暗 [0,1]",L"局部结构 [0,1]",L"肤质结构 [-1/0–2](效果未证实)",L"风格 [0,2整数](实验)",L"自动遮罩 [0/1](实验)",L"画面内UI修正 [0/1](效果未证实)",L"总变化强度 [0,2]",L"暗化变化 [0,2]",L"亮化变化 [0,2]",L"色彩变化 [0,2]",L"明度变化 [0,2]"};+HWND window=nullptr;engine::EngineController* controller=nullptr;HFONT font=nullptr;+std::function<void(engine::EnhancementSettings)> apply;+engine::PresetStore store(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/user-presets.v1");bool loaded=false,dirty=false,populating=false,enhancementEnabled=true;int page=0,scroll=0,contentHeight=0;uint64_t displayedRevision=0;+struct Item{HWND h;int page,x,y,w,height;};std::vector<Item> items;+const wchar_t* labels[]={L"模型强度",L"局部明暗",L"局部结构",L"肤质 · 未证实",L"风格 · 实验",L"自动遮罩 · 实验",L"UI修正 · 未证实",L"总变化强度",L"暗化变化",L"亮化变化",L"色彩变化",L"明度变化"};void loadStore(){if(!loaded){store.load();loaded=true;}}void message(const std::wstring& text){SetDlgItemTextW(window,401,text.c_str());}-void populate(engine::EnhancementSettings s){float v[]={s.model.intensity,s.model.tone,s.model.structure,s.model.skin,float(s.model.style),float(s.model.autoMask),float(s.model.uiCorrection),s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance};for(int i=0;i<12;++i){std::wostringstream o;o<<std::setprecision(7)<<v[i];SetDlgItemTextW(window,100+i,o.str().c_str());}CheckDlgButton(window,200,s.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(window,201,s.sr?BST_CHECKED:BST_UNCHECKED);SendDlgItemMessageW(window,202,CB_SETCURSEL,s.multiplier-1,0);SendDlgItemMessageW(window,203,CB_SETCURSEL,int(s.nrPolicy),0);SendDlgItemMessageW(window,204,CB_SETCURSEL,int(s.flow),0);SendDlgItemMessageW(window,205,CB_SETCURSEL,int(s.content),0);}+void populate(engine::EnhancementSettings s){populating=true;float v[]={s.model.intensity,s.model.tone,s.model.structure,s.model.skin,float(s.model.style),float(s.model.autoMask),float(s.model.uiCorrection),s.residual.total,s.residual.darken,s.residual.brighten,s.residual.color,s.residual.luminance};for(int i=0;i<12;++i){std::wostringstream o;o<<std::setprecision(7)<<v[i];SetDlgItemTextW(window,100+i,o.str().c_str());SendDlgItemMessageW(window,600+i,TBM_SETPOS,TRUE,LPARAM(v[i]*(i>=4&&i<=6?1:100)));}CheckDlgButton(window,200,s.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(window,201,s.sr?BST_CHECKED:BST_UNCHECKED);SendDlgItemMessageW(window,202,CB_SETCURSEL,s.multiplier-1,0);SendDlgItemMessageW(window,203,CB_SETCURSEL,int(s.nrPolicy),0);SendDlgItemMessageW(window,204,CB_SETCURSEL,int(s.flow),0);SendDlgItemMessageW(window,205,CB_SETCURSEL,int(s.content),0);displayedRevision=s.revision;populating=false;dirty=false;}bool read(engine::EnhancementSettings& s){s=controller->snapshot().desired;float v[12]{};for(int i=0;i<12;++i){wchar_t b[64]{};GetDlgItemTextW(window,100+i,b,64);wchar_t* end=nullptr;v[i]=wcstof(b,&end);if(end==b||*end||!std::isfinite(v[i])){message(L"请输入完整的有限数值;未提交设置");return false;}}for(int i=4;i<7;++i)if(v[i]!=std::floor(v[i])||v[i]<0||v[i]>(i==4?2:1)){message(L"风格/遮罩/UI修正必须为整数");return false;}- s.model={v[0],v[1],v[2],v[3],int(v[4]),int(v[5]),int(v[6])};s.residual={v[7],v[8],v[9],v[10],v[11]};s.nr=IsDlgButtonChecked(window,200)==BST_CHECKED;s.sr=IsDlgButtonChecked(window,201)==BST_CHECKED;s.multiplier=uint32_t(SendDlgItemMessageW(window,202,CB_GETCURSEL,0,0)+1);s.nrPolicy=static_cast<pipeline::NrSizePolicy>(SendDlgItemMessageW(window,203,CB_GETCURSEL,0,0));s.flow=static_cast<engine::FlowQuality>(SendDlgItemMessageW(window,204,CB_GETCURSEL,0,0));s.content=static_cast<engine::ContentRate>(SendDlgItemMessageW(window,205,CB_GETCURSEL,0,0));if(!s.validate().empty()){message(L"参数超出显示范围,整套设置未提交");return false;}return true;}-void refreshPresets(){auto list=GetDlgItem(window,300);SendMessageW(list,CB_RESETCONTENT,0,0);for(auto& p:store.entries())SendMessageW(list,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(p.name.c_str()));if(!store.entries().empty())SendMessageW(list,CB_SETCURSEL,0,0);}+ s.model={v[0],v[1],v[2],v[3],int(v[4]),int(v[5]),int(v[6])};s.residual={v[7],v[8],v[9],v[10],v[11]};s.nr=IsDlgButtonChecked(window,200)==BST_CHECKED;s.sr=IsDlgButtonChecked(window,201)==BST_CHECKED;s.multiplier=uint32_t(SendDlgItemMessageW(window,202,CB_GETCURSEL,0,0)+1);s.nrPolicy=static_cast<pipeline::NrSizePolicy>(SendDlgItemMessageW(window,203,CB_GETCURSEL,0,0));s.flow=static_cast<engine::FlowQuality>(SendDlgItemMessageW(window,204,CB_GETCURSEL,0,0));s.content=static_cast<engine::ContentRate>(SendDlgItemMessageW(window,205,CB_GETCURSEL,0,0));if(!s.validate().empty()){message(L"参数越界,未提交。悬停数值框查看允许范围。");return false;}return true;}++void refreshPresets(){auto list=GetDlgItem(window,300);SendMessageW(list,CB_RESETCONTENT,0,0);for(auto& p:store.entries())SendMessageW(list,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(p.name.c_str()));if(!store.entries().empty())SendMessageW(list,CB_SETCURSEL,0,0);PostMessageW(GetParent(window),WM_APP+42,0,0);}+void arrange(){if(!window)return;RECT r{};GetClientRect(window,&r);int width=MulDiv(r.right,96,GetDpiForWindow(window)),height=MulDiv(r.bottom,96,GetDpiForWindow(window));const int sticky=88,viewport=std::max(1,height-sticky);contentHeight=0;for(auto& item:items)if(item.page==page)contentHeight=std::max(contentHeight,item.y+(GetDlgCtrlID(item.h)>=202&&GetDlgCtrlID(item.h)<=205?36:item.height)+12);scroll=std::clamp(scroll,0,std::max(0,contentHeight-viewport));+ auto batch=BeginDeferWindowPos(int(items.size()));for(auto& item:items){bool fixed=item.page==-1;bool visible=item.page==page||fixed;int w=item.w<0?width-item.x-12:item.w;int y=fixed?(GetDlgCtrlID(item.h)==400?0:42):item.y-scroll+sticky;int itemHeight=fixed?42:item.height;batch=DeferWindowPos(batch,item.h,fixed?HWND_TOP:nullptr,dip(window,item.x),dip(window,y),dip(window,std::max(1,w)),dip(window,itemHeight),SWP_NOACTIVATE|(fixed?0:SWP_NOZORDER)|(visible?SWP_SHOWWINDOW:SWP_HIDEWINDOW));if(!fixed){auto clip=CreateRectRgn(0,dip(window,std::max(0,sticky-y)),dip(window,std::max(1,w)),dip(window,std::max(0,std::min(itemHeight,height-y))));SetWindowRgn(item.h,clip,FALSE);}}EndDeferWindowPos(batch);InvalidateRect(window,nullptr,FALSE);+}+HWND add(const wchar_t* cls,const wchar_t* text,int id,DWORD style,int group,int x,int y,int width,int height){auto h=CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|style,0,0,1,1,window,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(h,WM_SETFONT,WPARAM(font),TRUE);themeControl(h);items.push_back({h,group,x,y,width,height});return h;}+void button(const wchar_t* title,int id,int group,int x,int y,int width=-1){add(L"BUTTON",title,id,BS_PUSHBUTTON|WS_TABSTOP,group,x,y,width,36);}+void combo(int id,int group,int y,std::initializer_list<const wchar_t*> names){auto h=add(L"COMBOBOX",L"",id,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,group,12,y,-1,200);for(auto name:names)SendMessageW(h,CB_ADDSTRING,0,LPARAM(name));}LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){-case WM_CREATE:{window=h;const auto dpi=GetDpiForWindow(h);windowDpi=dpi;font=CreateFontW(-MulDiv(15,dpi,96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");- auto add=[&](const wchar_t* cls,const wchar_t* text,int id,DWORD style,int x,int y,int w,int height){auto c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,text,WS_CHILD|WS_VISIBLE|style,MulDiv(x,dpi,96),MulDiv(y,dpi,96),MulDiv(w,dpi,96),MulDiv(height,dpi,96),h,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;};- for(int i=0;i<12;++i){add(L"STATIC",labels[i],0,0,12,12+i*29,290,24);add(L"EDIT",L"",100+i,ES_AUTOHSCROLL|WS_TABSTOP,307,10+i*29,90,25);}- add(L"BUTTON",L"启用DLSS5 NR",200,BS_AUTOCHECKBOX,420,12,190,25);add(L"BUTTON",L"SR输出4K底图",201,BS_AUTOCHECKBOX,420,42,190,25);- auto combo=[&](int id,int y,std::initializer_list<const wchar_t*> names){auto c=add(L"COMBOBOX",L"",id,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,420,y,260,180);for(auto n:names)SendMessageW(c,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(n));};- combo(202,78,{L"关闭补帧",L"DLSSG 2X",L"DLSSG 3X(需硬件支持)",L"DLSSG 4X(需硬件支持)"});combo(203,114,{L"实时NR:约1080内部处理",L"原生NR:性能成本较高"});combo(204,150,{L"光流:性能",L"光流:平衡",L"光流:质量"});combo(205,186,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏"});- add(L"BUTTON",L"整套应用",210,BS_PUSHBUTTON|WS_TABSTOP,420,226,125,30);add(L"BUTTON",L"恢复内建默认",211,BS_PUSHBUTTON,552,226,128,30);- add(L"STATIC",L"实验参数沿用本地Feature18键;并非NVIDIA官方预设。\n实际效果需逐项验证。导出冻结启动时快照。",0,0,420,270,265,72);- add(L"COMBOBOX",L"",300,CBS_DROPDOWNLIST|WS_VSCROLL,12,375,300,180);add(L"EDIT",L"新预设",301,ES_AUTOHSCROLL,325,375,355,26);- const wchar_t* buttons[]={L"载入预设",L"新建",L"复制当前",L"重命名",L"删除",L"设为默认"};for(int i=0;i<6;++i)add(L"BUTTON",buttons[i],310+i,BS_PUSHBUTTON,12+i*113,413,108,30);- add(L"STATIC",L"",400,0,12,455,668,65);add(L"STATIC",L"",401,0,12,525,668,70);loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);return 0;}-case WM_COMMAND:{const int id=LOWORD(wp);engine::EnhancementSettings s;wchar_t name[128]{};GetDlgItemTextW(h,301,name,128);const auto index=size_t(SendDlgItemMessageW(h,300,CB_GETCURSEL,0,0));bool ok=true;- if(id==210){if(read(s)&&controller->requestSettings(s))message(L"设置已请求;在真实帧边界确认Applied后生效");}- else if(id==211){s={};populate(s);controller->requestSettings(s);message(L"已请求恢复内建默认;用户预设保留");}- else if(id==310&&index<store.entries().size()){s=store.entries()[index].settings;populate(s);controller->requestSettings(s);}+case WM_CREATE:{window=h;font=makeFont(h);items.clear();+ add(L"BUTTON",L"DLSS5 NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);+ add(L"BUTTON",L"SR 输出4K底图",201,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,56,-1,36);+ combo(203,0,104,{L"实时NR · 约1080内部处理",L"原生NR · 高性能成本"});+ add(L"STATIC",L"模型参数",1100,0,0,12,146,-1,24);+ for(int i=0;i<12;++i){const int y=174+i*62+(i>=7?32:0);add(L"STATIC",labels[i],1000+i,0,0,12,y,176,28);add(L"EDIT",L"",100+i,ES_AUTOHSCROLL|WS_TABSTOP|ES_RIGHT,0,202,y,-1,28);const wchar_t* ranges[]={L"范围:0–1",L"范围:0–1",L"范围:0–1",L"-1表示默认;其余范围0–2(效果未证实)",L"整数0、1、2(实验)",L"整数0或1(实验)",L"整数0或1(效果未证实)",L"范围:0–2",L"范围:0–2",L"范围:0–2",L"范围:0–2",L"范围:0–2"};SetPropW(GetDlgItem(h,100+i),L"veyra.tip",HANDLE(ranges[i]));auto slider=add(TRACKBAR_CLASSW,L"",600+i,TBS_HORZ|TBS_NOTICKS|WS_TABSTOP,0,12,y+32,-1,16);SendMessageW(slider,TBM_SETRANGE,TRUE,MAKELPARAM(i==3?-100:0,i>=4&&i<=6?(i==4?2:1):i<3?100:200));}+ add(L"STATIC",L"增强变化量",1101,0,0,12,606,-1,24);+ add(L"STATIC",L"肤质 / 风格 / 遮罩 / UI键为本地实验参数。未验证的效果不会标成可用能力。",1102,0,0,12,956,-1,70);+ button(L"应用整套设置",210,0,12,1034);marked(GetDlgItem(h,210));button(L"恢复内建默认",211,0,12,1078);+ add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);+ combo(202,1,52,{L"关闭补帧",L"DLSSG 2X",L"DLSSG 3X · 需硬件支持",L"DLSSG 4X · 需硬件支持"});+ combo(204,1,104,{L"光流 · 性能",L"光流 · 平衡",L"光流 · 质量"});+ combo(205,1,156,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏"});+ add(L"STATIC",L"运动为估算输入。倍率不代表实际显示帧率。比较时只展示真实帧;采集补帧需要等待下一张源帧。",1104,0,1,12,210,-1,100);+ button(L"应用补帧与当前参数",212,1,12,326);marked(GetDlgItem(h,212));+ add(L"STATIC",L"用户预设",1105,0,2,12,12,-1,30);combo(300,2,56,{});add(L"EDIT",L"新预设",301,ES_AUTOHSCROLL|WS_TABSTOP,2,12,108,-1,36);SendDlgItemMessageW(h,301,EM_SETLIMITTEXT,48,0);+ const wchar_t* names[]={L"载入所选预设",L"新建内建默认预设",L"保存当前参数为新预设",L"重命名所选",L"删除所选",L"设为启动增强默认"};for(int i=0;i<6;++i)button(names[i],310+i,2,12,164+i*44);+ add(L"STATIC",L"启动界面始终为日常模式。默认预设只决定增强参数;预设文件损坏时保留原文件。",1106,0,2,12,438,-1,82);+ add(L"STATIC",L"原生画质导出",1107,0,3,12,12,-1,32);combo(500,3,60,{L"H.264 · MP4",L"HEVC · MP4"});SendDlgItemMessageW(h,500,CB_SETCURSEL,0,0);+ add(L"STATIC",L"冻结启动时整套参数;NR按原生尺寸处理。保留兼容音轨。VFR不改写为CFR;字幕不烧录。",1108,0,3,12,108,-1,94);+ button(L"选择位置并导出视频",501,3,12,212);marked(GetDlgItem(h,501));button(L"保存当前图片 / 视频帧",502,3,12,256);+ button(L"暂停 / 继续导出",503,3,12,310);button(L"取消导出",504,3,12,354);+ add(L"BUTTON",L"优先观看 · 降低导出占用",505,BS_AUTOCHECKBOX|WS_TABSTOP,3,12,406,-1,36);CheckDlgButton(h,505,BST_CHECKED);+ add(L"STATIC",L"",506,0,3,12,458,-1,120);add(L"STATIC",L"",507,0,3,12,588,-1,80);+ add(L"STATIC",L"",400,0,-1,12,900,-1,92);add(L"STATIC",L"",401,0,-1,12,996,-1,86);+ loadStore();refreshPresets();populate(controller->snapshot().desired);message(store.error());SetTimer(h,1,250,nullptr);arrange();return 0;}+case WM_SIZE:arrange();return 0;+case WM_PAINT:{PAINTSTRUCT ps{};auto dc=BeginPaint(h,&ps);RECT r{};GetClientRect(h,&r);FillRect(dc,&r,panelBrush());int height=MulDiv(r.bottom,96,GetDpiForWindow(h));if(contentHeight>height){float ratio=float(height)/contentHeight;int thumb=std::max(dip(h,30),int(r.bottom*ratio));int y=int((r.bottom-thumb)*float(scroll)/std::max(1,contentHeight-height));RECT bar{r.right-dip(h,5),y,r.right-dip(h,2),y+thumb};roundRect(dc,bar,line,dip(h,2));}EndPaint(h,&ps);return 0;}+case WM_LBUTTONDOWN:case WM_MOUSEMOVE:if(msg==WM_LBUTTONDOWN&&GET_X_LPARAM(lp)<([](HWND w){RECT r{};GetClientRect(w,&r);return r.right;})(h)-dip(h,12))break;if(msg==WM_LBUTTONDOWN)SetCapture(h);if(GetCapture()==h){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h));scroll=int(float(GET_Y_LPARAM(lp))/std::max(1L,r.bottom)*std::max(0,contentHeight-height));arrange();return 0;}break;+case WM_LBUTTONUP:if(GetCapture()==h)ReleaseCapture();return 0;+case WM_VSCROLL:{switch(LOWORD(wp)){case SB_LINEUP:scroll-=40;break;case SB_LINEDOWN:scroll+=40;break;case SB_PAGEUP:scroll-=240;break;case SB_PAGEDOWN:scroll+=240;break;case SB_THUMBTRACK:{SCROLLINFO si{sizeof(si),SIF_TRACKPOS};GetScrollInfo(h,SB_VERT,&si);scroll=si.nTrackPos;break;}}arrange();return 0;}+case WM_MOUSEWHEEL:scroll-=GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA*90;arrange();return 0;+case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);+case WM_COMMAND:{const int id=LOWORD(wp);if(HIWORD(wp)==EN_SETFOCUS){for(auto& item:items)if(GetDlgCtrlID(item.h)==id&&item.page==page){RECT r{};GetClientRect(h,&r);int height=MulDiv(r.bottom,96,GetDpiForWindow(h))-88;if(item.y<scroll)scroll=item.y;if(item.y+item.height>scroll+height)scroll=item.y+item.height-height;arrange();break;}}if(!populating&&(HIWORD(wp)==EN_CHANGE&&id>=100&&id<=111||HIWORD(wp)==CBN_SELCHANGE&&id>=202&&id<=205||id==200||id==201)){dirty=true;message(L"参数草稿尚未应用。无效草稿保留;切换面板不会提交。");}+ engine::EnhancementSettings s;wchar_t name[128]{};GetDlgItemTextW(h,301,name,128);const auto index=size_t(SendDlgItemMessageW(h,300,CB_GETCURSEL,0,0));bool ok=true;+ if(id==210||id==212){KillTimer(h,2);if(read(s)){apply(s);dirty=false;message(L"设置已请求;在真实帧边界确认已应用后生效");}}+ else if(id==211){s={};populate(s);apply(s);message(L"已请求恢复内建默认;用户预设保留");}+ else if(id==310&&index<store.entries().size()){s=store.entries()[index].settings;populate(s);apply(s);}else if(id==311){ok=store.put(name,{});refreshPresets();}else if(id==312){if(read(s))ok=store.put(name,s);refreshPresets();}else if(id==313){ok=store.rename(index,name);refreshPresets();}- else if(id==314){ok=store.erase(index);refreshPresets();}+ else if(id==314&&index<store.entries().size()){if(MessageBoxW(h,(L"删除预设“"+store.entries()[index].name+L"”?当前画质不受影响。").c_str(),L"删除预设",MB_YESNO|MB_ICONQUESTION)==IDYES){ok=store.erase(index);refreshPresets();}}else if(id==315)ok=store.setDefault(index);+ else if(id>=501&&id<=505)SendMessageW(GetParent(h),WM_APP+41,id,id==501?SendDlgItemMessageW(h,500,CB_GETCURSEL,0,0):id==505?IsDlgButtonChecked(h,505):0);if(!ok)message(store.error());return 0;}-case WM_TIMER:{auto s=controller->snapshot();std::wostringstream o;o<<L"期望版本 "<<s.desired.revision<<L" / 已应用版本 "<<s.applied.revision<<(s.applying?L"(应用中)":L"")<<L"\n已应用:强度 "<<s.applied.model.intensity<<L" / 明暗 "<<s.applied.model.tone<<L" / 结构 "<<s.applied.model.structure<<L" / 变化量 "<<s.applied.residual.total<<L" / 倍率 "<<s.applied.multiplier<<L"\n"<<s.status;SetDlgItemTextW(h,400,o.str().c_str());return 0;}-case WM_DPICHANGED:changeDpi(h,wp,lp,windowDpi,font);return 0;-case WM_CLOSE:DestroyWindow(h);return 0;-case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;+case WM_HSCROLL:{int id=GetDlgCtrlID(reinterpret_cast<HWND>(lp));if(id>=600&&id<612){int index=id-600;float v=float(SendMessageW(reinterpret_cast<HWND>(lp),TBM_GETPOS,0,0))/(index>=4&&index<=6?1:100);if(index==3&&v<0)v=-1;std::wostringstream o;o<<std::setprecision(4)<<v;SetDlgItemTextW(h,100+index,o.str().c_str());SetTimer(h,2,120,nullptr);}return 0;}+case WM_TIMER:{if(wp==2){KillTimer(h,2);engine::EnhancementSettings setting;if(read(setting)){apply(setting);dirty=false;message(enhancementEnabled?L"已请求参数;帧边界确认生效":L"增强关闭中:已保存待启用参数");}return 0;}auto s=controller->snapshot();if(enhancementEnabled&&!dirty&&displayedRevision!=s.desired.revision)populate(s.desired);std::wostringstream o;o<<L"期望版本 "<<s.desired.revision<<L" / 已应用 "<<s.applied.revision<<(s.applying?L" · 应用中":L"")<<L"\n强度 "<<s.applied.model.intensity<<L" · 变化量 "<<s.applied.residual.total<<L" · 倍率 "<<s.applied.multiplier<<L"X";setText(GetDlgItem(h,400),o.str());return 0;}+case WM_DESTROY:KillTimer(h,1);KillTimer(h,2);DeleteObject(font);window=nullptr;items.clear();return 0;}return DefWindowProcW(h,msg,wp,lp);}}engine::EnhancementSettings defaultSettings(){loadStore();return store.defaultSettings();}-void showSettings(HWND parent,engine::EngineController& engine){controller=&engine;if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraSettings";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);auto dpi=GetDpiForWindow(parent);CreateWindowExW(0,wc.lpszClassName,L"参数与用户预设",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,MulDiv(720,dpi,96),MulDiv(645,dpi,96),parent,nullptr,wc.hInstance,nullptr);}+std::vector<std::wstring> presetNames(){loadStore();std::vector<std::wstring> out;for(auto& p:store.entries())out.push_back(p.name);return out;}+bool presetAt(size_t index,engine::EnhancementSettings& out){loadStore();if(index>=store.entries().size())return false;out=store.entries()[index].settings;return true;}+HWND createSettingsPanel(HWND parent,engine::EngineController& engine,std::function<void(engine::EnhancementSettings)> callback){controller=&engine;apply=std::move(callback);WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraInspector";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);return CreateWindowExW(WS_EX_CONTROLPARENT,wc.lpszClassName,L"专业参数",WS_CHILD|WS_CLIPCHILDREN,0,0,328,500,parent,nullptr,wc.hInstance,nullptr);}+void settingsVisibility(bool visible){if(window&&!visible)KillTimer(window,2);}+void settingsPage(int value){if(window)KillTimer(window,2);page=std::clamp(value,0,3);scroll=0;arrange();}+void settingsEnabled(bool enabled,const engine::EnhancementSettings& configured){enhancementEnabled=enabled;if(window&&!enabled&&!dirty)populate(configured);if(window&&!enabled)message(L"增强已关闭。修改只保存待启用配置;开启后整套应用。");}+void settingsDpi(){if(!window)return;auto old=font;font=makeFont(window);for(auto& item:items)SendMessageW(item.h,WM_SETFONT,WPARAM(font),TRUE);DeleteObject(old);arrange();}+void exportPanelStatus(const engine::ExportJobSnapshot& job,bool canExport,bool canSave){if(!window)return;setText(GetDlgItem(window,506),job.state==engine::ExportState::Idle?L"尚无导出任务":job.message+L"\n"+std::to_wstring(int(job.progress*100))+L"% · 源帧 "+std::to_wstring(job.sourceFrames)+L" / 编码 "+std::to_wstring(job.encoded)+L"\n生成 "+std::to_wstring(job.generated)+L" / CFR占位 "+std::to_wstring(job.holds)+L"\n作业 "+std::to_wstring(job.jobId)+L" · 冻结版本 "+std::to_wstring(job.frozenRevision));setText(GetDlgItem(window,507),job.output.empty()?L"目标由保存窗口选择":L"输出:"+std::filesystem::path(job.output).filename().wstring());EnableWindow(GetDlgItem(window,501),canExport&&!job.active());EnableWindow(GetDlgItem(window,502),canSave);EnableWindow(GetDlgItem(window,503),job.state==engine::ExportState::Running||job.state==engine::ExportState::Paused);EnableWindow(GetDlgItem(window,504),job.active());}}diff --git a/apps/veyra/SettingsWindow.h b/apps/veyra/SettingsWindow.hindex bd5bb513..af20cd71 100644--- a/apps/veyra/SettingsWindow.h+++ b/apps/veyra/SettingsWindow.h@@ -1,4 +1,13 @@#pragma once-#include <windows.h>#include "veyra/engine/EngineController.h"-namespace veyra::ui { void showSettings(HWND,engine::EngineController&);engine::EnhancementSettings defaultSettings(); }+#include "veyra/engine/ExportJobManager.h"+#include <vector>+namespace veyra::ui {+engine::EnhancementSettings defaultSettings();+std::vector<std::wstring> presetNames();+bool presetAt(size_t,engine::EnhancementSettings&);+HWND createSettingsPanel(HWND,engine::EngineController&,std::function<void(engine::EnhancementSettings)>);+void settingsEnabled(bool,const engine::EnhancementSettings&);+void settingsVisibility(bool);void settingsPage(int);void settingsDpi();+void exportPanelStatus(const engine::ExportJobSnapshot&,bool canExport,bool canSave);+}diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cppindex 9255728d..e26ea6d9 100644--- a/apps/veyra/TelemetryWindow.cpp+++ b/apps/veyra/TelemetryWindow.cpp@@ -2,7 +2,7 @@#include "veyra/Log.h"#include <shellapi.h>#include <filesystem>-#include "DpiWindow.h"+#include "ui/Theme.h"#include <sstream>#include <iomanip>namespace veyra::ui {@@ -16,16 +16,21 @@ void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色o<<L"\r\nCPU与调度(毫秒,独立于GPU):取帧 "<<value(s.metrics.decodeCpuMs)<<L" / 图提交 "<<value(s.metrics.submitCpuMs)<<L" / GPU就绪等待 "<<value(s.metrics.gpuWaitCpuMs)<<L"\r\n截止时间等待 "<<value(s.metrics.deadlineWaitCpuMs)<<L" / Present调用 "<<value(s.metrics.presentCpuMs)<<L"\r\n源帧 "<<s.metrics.sourceFrames<<L" / 有效生成 "<<s.metrics.validGenerated<<L" / 实际提交 "<<s.metrics.submitted<<L" / 过期补帧 "<<s.metrics.expired<<L"\r\n当前批次容量 "<<s.metrics.queueWatermark<<L"(上限4);采集入口容量1;采集丢弃 "<<s.captureDropped<<L"\r\n实际提交频率(最近1秒观察):"<<value(s.submissionFps)<<L"fps;实际显示扫描率/光子延迟:未测\r\n";const auto flowName=s.applied.flow==engine::FlowQuality::Performance?L"性能":s.applied.flow==engine::FlowQuality::Balanced?L"平衡":L"质量";o<<L"光流请求:"<<flowName<<L";实际SDK perf="<<s.flowPerf<<L";grid=4(已验证SDK能力)\r\n内容节奏:"<<(s.contentFps?std::to_wstring(s.contentFps)+L"fps":L"未确认(静态或证据不足)")<<L";保留源时间戳,重复内容不计有效生成\r\n"<<s.status;- SetDlgItemTextW(window,1,o.str().c_str());+ setText(GetDlgItem(window,1),o.str());}-LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){switch(m){case WM_CREATE:{preview.clear();window=h;auto dpi=GetDpiForWindow(h);windowDpi=dpi;font=CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");auto add=[&](const wchar_t* c,const wchar_t* t,int id,DWORD style,int y,int height){auto child=CreateWindowExW(WS_EX_CLIENTEDGE,c,t,WS_CHILD|WS_VISIBLE|style,10,MulDiv(y,dpi,96),MulDiv(820,dpi,96),MulDiv(height,dpi,96),h,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(child,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);};- add(L"EDIT",L"",1,ES_MULTILINE|ES_READONLY|WS_VSCROLL,10,340);add(L"BUTTON",L"查看 / 刷新脱敏诊断预览",3,BS_PUSHBUTTON,360,28);add(L"EDIT",L"点击上方按钮查看诊断。复制只会复制这里预览过的脱敏文字。",2,ES_MULTILINE|ES_READONLY|WS_VSCROLL,398,150);add(L"BUTTON",L"复制上方脱敏预览",4,BS_PUSHBUTTON,558,28);add(L"BUTTON",L"打开本应用日志目录",5,BS_PUSHBUTTON,596,28);SetTimer(h,1,250,nullptr);refresh();return 0;}+void arrange(){RECT r{};GetClientRect(window,&r);int width=MulDiv(r.right,96,GetDpiForWindow(window)),height=MulDiv(r.bottom,96,GetDpiForWindow(window));auto pos=[&](int id,int x,int y,int w,int h){MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,y),dip(window,std::max(1,w)),dip(window,std::max(1,h)),TRUE);};bool wide=width>=700;pos(6,width-56,8,40,32);pos(7,16,10,width-80,32);pos(1,16,52,wide?width/2-24:width-32,wide?height-116:height/2-68);pos(2,wide?width/2+8:16,wide?96:height/2+36,wide?width/2-24:width-32,wide?height-160:height/2-100);pos(3,wide?width/2+8:16,wide?52:height/2-8,wide?width/2-24:width-32,36);pos(4,16,height-52,width/2-24,36);pos(5,width/2+8,height-52,width/2-24,36);}+LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){switch(m){case WM_CREATE:{preview.clear();window=h;font=makeFont(h,13);auto add=[&](const wchar_t* c,const wchar_t* t,int id,DWORD style){auto child=CreateWindowExW(0,c,t,WS_CHILD|WS_VISIBLE|style,0,0,1,1,h,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(child,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);themeControl(child);};+ add(L"EDIT",L"",1,ES_MULTILINE|ES_READONLY|WS_VSCROLL|WS_TABSTOP);add(L"BUTTON",L"查看 / 刷新脱敏预览",3,BS_PUSHBUTTON|WS_TABSTOP);add(L"EDIT",L"点击上方按钮查看诊断。复制只会复制这里预览过的脱敏文字。",2,ES_MULTILINE|ES_READONLY|WS_VSCROLL|WS_TABSTOP);add(L"BUTTON",L"复制已预览内容",4,BS_PUSHBUTTON|WS_TABSTOP);add(L"BUTTON",L"打开本应用日志目录",5,BS_PUSHBUTTON|WS_TABSTOP);add(L"BUTTON",L"关闭诊断",6,BS_PUSHBUTTON|WS_TABSTOP);icon(GetDlgItem(h,6),Icon::Close);add(L"STATIC",L"性能与诊断 / 播放会话",7,0);SetTimer(h,1,250,nullptr);arrange();refresh();return 0;}+case WM_SIZE:arrange();return 0;+case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(m,w,l);+case WM_TIMER:refresh();return 0;-case WM_COMMAND:if(LOWORD(w)==3){preview=wide(Logger::instance().diagnosticReport());SetDlgItemTextW(h,2,preview.c_str());}else if(LOWORD(w)==4&&!preview.empty()){+case WM_COMMAND:if(LOWORD(w)==6){SendMessageW(GetParent(h),WM_APP+43,0,0);}else if(LOWORD(w)==3){preview=wide(Logger::instance().diagnosticReport());SetDlgItemTextW(h,2,preview.c_str());}else if(LOWORD(w)==4&&!preview.empty()){if(OpenClipboard(h)){HGLOBAL data=GlobalAlloc(GMEM_MOVEABLE,(preview.size()+1)*sizeof(wchar_t));if(data){if(void* p=GlobalLock(data)){memcpy(p,preview.c_str(),(preview.size()+1)*sizeof(wchar_t));GlobalUnlock(data);EmptyClipboard();if(!SetClipboardData(CF_UNICODETEXT,data))GlobalFree(data);}else GlobalFree(data);}CloseClipboard();}}else if(LOWORD(w)==5)ShellExecuteW(h,L"open",(std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs").c_str(),nullptr,nullptr,SW_SHOW);return 0;-case WM_DPICHANGED:changeDpi(h,w,l,windowDpi,font);return 0;+case WM_CLOSE:DestroyWindow(h);return 0;case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;}return DefWindowProcW(h,m,w,l);}}-void showTelemetry(HWND parent,engine::EngineController& controller){engine=&controller;if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraTelemetry";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);RegisterClassW(&wc);auto dpi=GetDpiForWindow(parent);CreateWindowExW(0,wc.lpszClassName,L"性能与诊断中心",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,MulDiv(860,dpi,96),MulDiv(675,dpi,96),parent,nullptr,wc.hInstance,nullptr);}+HWND createTelemetryPanel(HWND parent,engine::EngineController& controller){engine=&controller;WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraTelemetry";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);return CreateWindowExW(WS_EX_CONTROLPARENT,wc.lpszClassName,L"性能与诊断中心",WS_CHILD|WS_CLIPCHILDREN,0,0,800,620,parent,nullptr,wc.hInstance,nullptr);}+void telemetryDpi(){if(!window)return;auto old=font;font=makeFont(window,13);EnumChildWindows(window,[](HWND child,LPARAM f)->BOOL{SendMessageW(child,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(old);arrange();}}diff --git a/apps/veyra/TelemetryWindow.h b/apps/veyra/TelemetryWindow.hindex b167b48c..06fa31b1 100644--- a/apps/veyra/TelemetryWindow.h+++ b/apps/veyra/TelemetryWindow.h@@ -1,4 +1,4 @@#pragma once#include <windows.h>#include "veyra/engine/EngineController.h"-namespace veyra::ui {void showTelemetry(HWND,engine::EngineController&);}+namespace veyra::ui {HWND createTelemetryPanel(HWND,engine::EngineController&);void telemetryDpi();}diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cppindex 8655f9ca..18e62595 100644--- a/apps/veyra/main.cpp+++ b/apps/veyra/main.cpp@@ -1,155 +1,3 @@#include <windows.h>-#include "SettingsWindow.h"-#include "TelemetryWindow.h"-#include <objbase.h>-#include <commctrl.h>-#include <commdlg.h>-#include <shellapi.h>-#include <filesystem>-#include <format>-#include <string>-#include <chrono>-#include "veyra/engine/EngineController.h"-#include "veyra/engine/VideoExportJob.h"-#include "veyra/source/CaptureCardSource.h"-#include "veyra/Log.h"-#include "veyra/engine/Subtitles.h"-namespace {-enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent,Multiplier,Settings,OriginalHold,CompareToggle,Split,Reference,Fullscreen,VideoSurface=1000};-veyra::engine::EngineController engine;-struct ToolbarItem{HWND hwnd;int width;};std::vector<ToolbarItem> toolbar;-bool full=false,holdOriginal=false,referenceBase=false;int compareMode=0;float compareSplit=.5f;WINDOWPLACEMENT windowPlacement{sizeof(windowPlacement)};-HWND mainWindow=nullptr,video=nullptr,statusBar=nullptr,seekBar=nullptr;-std::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;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;-HWND captureWindow=nullptr,captureDevice=nullptr,captureFormat=nullptr,captureAudio=nullptr;-std::vector<veyra::source::CaptureFormat> captureFormats;-void openFile(const std::wstring&);-void layout();-void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}-void toggleFullscreen(){full=!full;if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE);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,WS_OVERLAPPEDWINDOW|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");layout();}-LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_PTR){- 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);compareSplit=std::clamp(float(short(LOWORD(l)))/std::max(1L,r.right),0.0f,1.0f);updateComparison();return 0;}- if(id==VideoSurface&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}- return DefSubclassProc(h,m,w,l);-}-void refreshFormats(){SendMessageW(captureFormat,CB_RESETCONTENT,0,0);int i=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0));captureFormats=i>=0?veyra::source::CaptureCardSource::formats(i):std::vector<veyra::source::CaptureFormat>{};for(auto& f:captureFormats)SendMessageW(captureFormat,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(f.label.c_str()));if(!captureFormats.empty())SendMessageW(captureFormat,CB_SETCURSEL,0,0);}-LRESULT CALLBACK captureProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){if(msg==WM_CREATE){auto add=[&](const wchar_t* cls,const wchar_t* text,int id,DWORD style,int y){return CreateWindowExW(0,cls,text,WS_CHILD|WS_VISIBLE|style,12,y,510,200,hwnd,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);};-captureDevice=add(L"COMBOBOX",L"",1,CBS_DROPDOWNLIST|WS_VSCROLL,15);captureFormat=add(L"COMBOBOX",L"",2,CBS_DROPDOWNLIST|WS_VSCROLL,55);captureAudio=add(L"COMBOBOX",L"",3,CBS_DROPDOWNLIST|WS_VSCROLL,95);-auto devices=veyra::source::CaptureCardSource::devices();for(auto& name:devices)SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));if(!devices.empty())SendMessageW(captureDevice,CB_SETCURSEL,0,0);else SendMessageW(captureDevice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"未找到采集设备,请连接后重新打开"));-SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(L"不监听音频(可选择下方HDMI音频输入)"));for(auto& name:veyra::source::CaptureCardSource::devices(true))SendMessageW(captureAudio,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));SendMessageW(captureAudio,CB_SETCURSEL,0,0);refreshFormats();-CreateWindowExW(0,L"STATIC",L"设备 / 实际格式 / HDMI音频。增强采用主界面设置。实卡验收由用户完成;补帧必须等待下一张源帧到达。",WS_CHILD|WS_VISIBLE,12,140,510,64,hwnd,nullptr,GetModuleHandleW(nullptr),nullptr);-CreateWindowExW(0,L"BUTTON",L"开始采集",WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,12,211,180,32,hwnd,reinterpret_cast<HMENU>(4),GetModuleHandleW(nullptr),nullptr);return 0;}-if(msg==WM_COMMAND){if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)refreshFormats();if(LOWORD(wp)==4){int d=int(SendMessageW(captureDevice,CB_GETCURSEL,0,0)),f=int(SendMessageW(captureFormat,CB_GETCURSEL,0,0)),a=int(SendMessageW(captureAudio,CB_GETCURSEL,0,0))-1;if(d>=0&&f>=0&&size_t(f)<captureFormats.size()){openFile(std::format(L"capture:{}:{}:{}",d,captureFormats[f].index,a));DestroyWindow(hwnd);}else MessageBoxW(hwnd,L"请选择支持的1080p/4K 30/60格式。",L"采集",MB_OK);}return 0;}if(msg==WM_DESTROY){captureWindow=nullptr;return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}-void showCapture(){if(captureWindow){SetForegroundWindow(captureWindow);return;}WNDCLASSW wc{};wc.lpfnWndProc=captureProc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);captureWindow=CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,550,295,mainWindow,nullptr,wc.hInstance,nullptr);}-veyra::engine::PlayerOptions options(){return veyra::engine::PlayerOptions::from(engine.snapshot().desired);}--std::wstring fileDialog(bool save){wchar_t name[32768]{};OPENFILENAMEW ofn{};ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=mainWindow;ofn.lpstrFile=name;ofn.nMaxFile=32768;-ofn.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;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|style,x,y,w,h,mainWindow,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(hwnd,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);if(id>=Open&&id<=Fullscreen&&id!=Seek)toolbar.push_back({hwnd,w});return hwnd;}-void layout(){if(!mainWindow||!video)return;RECT r{};GetClientRect(mainWindow,&r);const int dpi=GetDpiForWindow(mainWindow);auto px=[&](int x){return MulDiv(x,dpi,96);};int x=px(8),y=px(8),row=px(32),gap=px(6);for(auto item:toolbar){const int id=GetDlgCtrlID(item.hwnd);ShowWindow(item.hwnd,full&&id!=Fullscreen?SW_HIDE:SW_SHOW);if(full){if(id==Fullscreen)MoveWindow(item.hwnd,std::max(0L,r.right-px(115)),px(8),px(108),row,TRUE);continue;}const int w=px(item.width);if(x+w>r.right-px(8)){x=px(8);y+=row+gap;}wchar_t cls[32]{};GetClassNameW(item.hwnd,cls,32);MoveWindow(item.hwnd,x,y,w,wcscmp(cls,L"ComboBox")==0?px(180):row,TRUE);x+=w+gap;}- const int top=full?0:y+row+gap,bottom=full?0:px(126);MoveWindow(video,full?0:px(8),top,std::max(1L,r.right-(full?0:px(16))),std::max(1L,r.bottom-top-bottom),TRUE);- ShowWindow(seekBar,full?SW_HIDE:SW_SHOW);ShowWindow(statusBar,full?SW_HIDE:SW_SHOW);MoveWindow(subtitleLabel,px(8),std::max(0L,r.bottom-px(full?48:120)),std::max(1L,r.right-px(16)),px(32),TRUE);MoveWindow(seekBar,px(8),std::max(0L,r.bottom-px(88)),std::max(1L,r.right-px(16)),px(24),TRUE);MoveWindow(statusBar,px(12),std::max(0L,r.bottom-px(61)),std::max(1L,r.right-px(24)),px(56),TRUE);- if(full){SetWindowPos(GetDlgItem(mainWindow,Fullscreen),HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);SetWindowPos(subtitleLabel,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);}-}--LRESULT CALLBACK proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){-case WM_CREATE:{mainWindow=hwnd;font=CreateFontW(-16,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");-control(L"BUTTON",L"打开视频/图片",Open,BS_PUSHBUTTON,10,10,150,30);control(L"BUTTON",L"播放",Play,BS_PUSHBUTTON,168,10,68,30);control(L"BUTTON",L"停止",Stop,BS_PUSHBUTTON,244,10,62,30);control(L"BUTTON",L"保存图片",Save,BS_PUSHBUTTON,314,10,95,30);-control(L"BUTTON",L"DLSS5 NR",Nr,BS_AUTOCHECKBOX,425,10,110,30);control(L"BUTTON",L"SR 4K",Sr,BS_AUTOCHECKBOX,518,10,78,30);control(L"BUTTON",L"补帧",Fg,BS_AUTOCHECKBOX,600,10,78,30);CheckDlgButton(hwnd,Nr,BST_CHECKED);-control(L"BUTTON",L"采集",Capture,BS_PUSHBUTTON,690,10,75,30);control(L"BUTTON",L"导出视频",Export,BS_PUSHBUTTON,773,10,103,30);control(L"BUTTON",L"性能/诊断",Info,BS_PUSHBUTTON,884,10,100,30);-control(L"BUTTON",L"实时NR档",Realtime,BS_AUTOCHECKBOX,952,10,100,30);-control(L"BUTTON",L"最近打开",Recent,BS_PUSHBUTTON,1072,10,75,30);-auto mult=control(L"COMBOBOX",L"",Multiplier,CBS_DROPDOWNLIST,1150,10,70,180);for(auto label:{L"2X",L"3X",L"4X"})SendMessageW(mult,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(mult,CB_SETCURSEL,initialOptions.fgMultiplier-2,0);-control(L"BUTTON",L"参数与预设",Settings,BS_PUSHBUTTON,1225,10,100,30);-auto original=control(L"BUTTON",L"按住原图 V",OriginalHold,BS_PUSHBUTTON,0,0,110,30);SetWindowSubclass(original,interaction,OriginalHold,0);-control(L"BUTTON",L"原图/增强切换",CompareToggle,BS_PUSHBUTTON,0,0,120,30);control(L"BUTTON",L"分屏拖动",Split,BS_PUSHBUTTON,0,0,95,30);-auto ref=control(L"COMBOBOX",L"",Reference,CBS_DROPDOWNLIST,0,0,170,180);for(auto label:{L"对比:输入原画",L"对比:增强前底图"})SendMessageW(ref,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(ref,CB_SETCURSEL,0,0);control(L"BUTTON",L"全屏 F11",Fullscreen,BS_PUSHBUTTON,0,0,108,30);-subtitleLabel=control(L"STATIC",L"",0,SS_CENTER,8,640,1100,32);-video=control(L"STATIC",L"",VideoSurface,SS_BLACKRECT|SS_NOTIFY,8,52,1100,610);seekBar=control(TRACKBAR_CLASSW,L"",Seek,TBS_HORZ,8,675,1100,24);SendMessageW(seekBar,TBM_SETRANGE,TRUE,MAKELPARAM(0,10000));statusBar=control(L"STATIC",L"打开本地视频或PNG/JPEG。本地实验运行时,非NVIDIA官方产品。",0,SS_LEFT,12,708,1080,36);-SetWindowSubclass(video,interaction,VideoSurface,0);-DragAcceptFiles(hwnd,TRUE);SetTimer(hwnd,1,200,nullptr);layout();return 0;}-case WM_SIZE:if(wp!=SIZE_MINIMIZED)layout();return 0;-case WM_DROPFILES:{wchar_t file[32768]{};DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file,32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file);return 0;}-case WM_COMMAND:switch(LOWORD(wp)){-case Open:openFile(fileDialog(false));break;-case Recent:{wchar_t recent[32768]{};GetPrivateProfileStringW(L"Player",L"最近打开",L"",recent,32768,(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());openFile(recent);break;}-case Play:{auto s=engine.snapshot();if(!currentFile.empty()&&(!s.running||(s.duration>0&&s.position>=s.duration-0.1))){openFile(currentFile);break;}paused=!paused;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}-case Stop:engine.stop();break;-case Save:{auto name=fileDialog(true);if(!name.empty())engine.saveFrame(name);break;}-case Multiplier:case Realtime:case Nr:case Sr:case Fg:{auto changed=engine.snapshot().desired;const auto id=LOWORD(wp);-if(id==Nr)changed.nr=IsDlgButtonChecked(hwnd,Nr)==BST_CHECKED;-if(id==Sr)changed.sr=IsDlgButtonChecked(hwnd,Sr)==BST_CHECKED;-if(id==Realtime)changed.nrPolicy=IsDlgButtonChecked(hwnd,Realtime)==BST_CHECKED?veyra::pipeline::NrSizePolicy::Realtime:veyra::pipeline::NrSizePolicy::Native;-if(id==Fg)changed.multiplier=IsDlgButtonChecked(hwnd,Fg)==BST_CHECKED?uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2):1;-if(id==Multiplier&&HIWORD(wp)==CBN_SELCHANGE&&changed.multiplier>1)changed.multiplier=uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2);-engine.requestSettings(changed);break;}--case Fullscreen:toggleFullscreen();break;-case VideoSurface:if(HIWORD(wp)==STN_DBLCLK)toggleFullscreen();break;-case CompareToggle:compareMode=compareMode==1?0:1;updateComparison();break;-case Split:compareMode=compareMode==2?0:2;updateComparison();break;-case Reference:referenceBase=SendDlgItemMessageW(hwnd,Reference,CB_GETCURSEL,0,0)==1;updateComparison();break;-case Settings:veyra::ui::showSettings(hwnd,engine);break;-case Capture:showCapture();break;-case Export:{if(currentFile.empty())break;wchar_t name[32768]{};OPENFILENAMEW d{};d.lStructSize=sizeof(d);d.hwndOwner=hwnd;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"MP4视频\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){int codec=MessageBoxW(hwnd,L"使用HEVC编码?“是”为HEVC,“否”为H.264。导出冻结当前参数,NR默认原生尺寸;不覆盖已有文件。",L"视频导出",MB_YESNOCANCEL);if(codec!=IDCANCEL)engine.startExport(currentFile,name,options(),codec==IDYES);}break;}-case Info:veyra::ui::showTelemetry(hwnd,engine);break;-}return 0;-case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==seekBar){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(!dragging&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;-case WM_KEYDOWN:if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){toggleFullscreen();return 0;}if(wp==VK_ESCAPE&&full){toggleFullscreen();return 0;}if(wp=='V'){holdOriginal=true;updateComparison();return 0;}break;-case WM_KEYUP:if(wp=='V'){holdOriginal=false;updateComparison();return 0;}break;-case WM_SYSKEYDOWN:if(wp==VK_RETURN&&(lp&(1LL<<29))){toggleFullscreen();return 0;}break;-case WM_ACTIVATEAPP:if(!wp){holdOriginal=false;updateComparison();}break;-case WM_DPICHANGED:{auto rect=reinterpret_cast<RECT*>(lp);if(!full)SetWindowPos(hwnd,nullptr,rect->left,rect->top,rect->right-rect->left,rect->bottom-rect->top,SWP_NOZORDER|SWP_NOACTIVATE);auto oldFont=font;font=CreateFontW(-MulDiv(15,HIWORD(wp),96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");EnumChildWindows(hwnd,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(oldFont);layout();return 0;}--case WM_TIMER:{if(closing){if(engine.idle()){KillTimer(hwnd,1);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;-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;}-}auto s=engine.snapshot();CheckDlgButton(hwnd,Nr,s.desired.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,s.desired.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,s.desired.multiplier>1?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,s.desired.nrPolicy==veyra::pipeline::NrSizePolicy::Realtime?BST_CHECKED:BST_UNCHECKED);if(s.desired.multiplier>1)SendDlgItemMessageW(hwnd,Multiplier,CB_SETCURSEL,s.desired.multiplier-2,0);SetWindowTextW(subtitleLabel,veyra::engine::subtitleAt(subtitles,s.position).c_str());-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(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"(详见诊断)";}-SetWindowTextW(statusBar,text.c_str());if(!dragging&&s.duration>0)SendMessageW(seekBar,TBM_SETPOS,TRUE,LPARAM(s.position/s.duration*10000));-if(smokeRollback&&startTick){if(settingsStep==0&&s.frames>20){auto changed=s.desired;if(smokeRollbackFlow)changed.nr=false;else{changed.model.style=2;changed.model.intensity=.35f;}engine.requestSettings(changed);settingsStep=1;}if(settingsStep==1&&s.frames>50&&s.desired.model.style==0&&s.applied.model.style==0&&!s.applying&&(!smokeRollbackFlow||(s.applied.nr&&s.nvofExecuted>30))){settingsStep=3;veyra::log::info("rollback-test",std::format("whole snapshot restored revision={} position={} style={} intensity={}",s.applied.revision,s.position,s.applied.model.style,s.applied.model.intensity));}}-if(smokeUi&&startTick){const auto elapsed=GetTickCount64()-startTick;-if(uiStep==0&&elapsed>2300){SendMessageW(hwnd,WM_KEYDOWN,VK_F11,0);uiStep=1;}-if(uiStep==1&&elapsed>2800){const bool entered=full&&(GetWindowLongPtrW(hwnd,GWL_STYLE)&WS_POPUP);SendMessageW(hwnd,WM_KEYDOWN,VK_ESCAPE,0);veyra::log::info("ui-test",std::format("F11 entered={} Esc restored={}",entered,!full));uiStep=entered&&!full?2:-1;}-if(uiStep==2&&elapsed>3300){SendMessageW(hwnd,WM_SYSKEYDOWN,VK_RETURN,1LL<<29);uiStep=3;}-if(uiStep==3&&elapsed>3800){const bool entered=full;SendMessageW(hwnd,WM_COMMAND,MAKEWPARAM(VideoSurface,STN_DBLCLK),LPARAM(video));veyra::log::info("ui-test",std::format("AltEnter entered={} doubleClick restored={}",entered,!full));uiStep=entered&&!full?4:-1;}-if(uiStep==4&&elapsed>4200){compareMode=2;compareSplit=.4f;updateComparison();uiStep=5;}-if(uiStep==5&&elapsed>4800){referenceBase=true;updateComparison();uiStep=6;}-if(uiStep==6&&elapsed>5500){holdOriginal=true;updateComparison();uiStep=7;}-if(uiStep==7&&elapsed>5900){holdOriginal=false;compareMode=0;updateComparison();veyra::log::info("ui-test",std::format("completed={} NR evaluations={} (no fullscreen NR re-create expected)",true,s.nrEvaluated));uiStep=8;}-}-if(smokeSettings&&startTick){const auto elapsed=GetTickCount64()-startTick;-if(settingsStep==0&&s.frames>20){auto change=s.desired;change.model.intensity=.6f;change.model.tone=.7f;change.residual.total=.4f;change.residual.color=.8f;engine.requestSettings(change);settingsStep=1;}-if(settingsStep==1&&s.applied.model.intensity==.6f&&elapsed>3300){auto change=s.desired;change.sr=true;engine.requestSettings(change);settingsStep=2;}-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;}-}-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&&!s.failed&&(!smokeSettings||settingsStep==3)&&(!smokeRollback||settingsStep==3)&&(!smokeUi||uiStep==8)?0:1;PostMessageW(hwnd,WM_CLOSE,0,0);}return 0;}-case WM_CLOSE:closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;-case WM_DESTROY:DeleteObject(font);PostQuitMessage(resultCode);return 0;-}return DefWindowProcW(hwnd,msg,wp,lp);}-}-int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){-SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_BAR_CLASSES};InitCommonControlsEx(&controls);-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"--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);-engine.requestSettings(initialOptions.snapshot());-if(!exportOutput.empty()){std::atomic<bool> cancel{false},finished{false};std::thread cancelTimer;if(cancelAfterMs)cancelTimer=std::thread([&]{const auto start=GetTickCount64();while(!finished&&GetTickCount64()-start<cancelAfterMs)std::this_thread::sleep_for(std::chrono::milliseconds(5));if(!finished)cancel=true;});bool ok=veyra::engine::exportVideo(autoInput,exportOutput,initialOptions,exportHevc,cancel,[](double,const std::wstring& s){OutputDebugStringW(s.c_str());},exportFrames);finished=true;if(cancelTimer.joinable())cancelTimer.join();veyra::log::info("app",std::format("export result={}",ok));CoUninitialize();return ok?0:cancel?3:1;}-WNDCLASSEXW wc{sizeof(wc)};wc.hInstance=instance;wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraApp";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);RegisterClassExW(&wc);-auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — 本地实验版",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,1200,800,nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){if(GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&(msg.message==WM_KEYDOWN||msg.message==WM_KEYUP||msg.message==WM_SYSKEYDOWN)){-const bool key=msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||msg.wParam==VK_SPACE||msg.wParam=='V'||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN);if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}-TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);-}+int runVeyraApp(HINSTANCE,int);+int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){return runVeyraApp(instance,show);}diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppnew file mode 100644index 00000000..1fd36d60--- /dev/null+++ b/apps/veyra/ui/AppShell.cpp@@ -0,0 +1,289 @@+#include <windows.h>+#include "../SettingsWindow.h"+#include "Theme.h"+#include "WorkspaceChrome.h"+#include "UiSessionState.h"+#include "UiPreferenceStore.h"+#include "CapturePanel.h"+#include "SubtitleOverlay.h"+#include "veyra/engine/ExportJobManager.h"+#include <future>+#include <psapi.h>+#pragma comment(lib,"psapi.lib")+#include "../TelemetryWindow.h"+#include <objbase.h>+#include <commctrl.h>+#include <commdlg.h>+#include <shellapi.h>+#include <filesystem>+#include <format>+#include <string>+#include <chrono>+#include "veyra/engine/EngineController.h"+#include "veyra/engine/VideoExportJob.h"+#include "veyra/source/CaptureCardSource.h"+#include "veyra/Log.h"+#include "veyra/engine/Subtitles.h"+namespace {+constexpr DWORD ShellStyle=WS_POPUP|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX|WS_SYSMENU|WS_CLIPCHILDREN;+enum {Open=101,Play,Stop,Save,Nr,Sr,Fg,Seek,Info,Capture,Export,Realtime,Recent,Multiplier,Settings,OriginalHold,CompareToggle,Split,Reference,Fullscreen,ModeSwitch=220,Master,DailyPreset,Volume,Mute,Subtitle,SubtitleLoad,SubtitleSize,ImageOpen,InspectorDrawer,TabEnhance,TabFg,TabPresets,TabExport,JobProgress,Details,Brand,MediaTitle,TimeLabel,EmptyTitle,EmptyHint,ProRailVideo,ProRailCapture,WindowMin,WindowMax,WindowClose,VideoSurface=1000};+veyra::engine::EngineController engine;+veyra::engine::ExportJobManager exportJob;+veyra::ui::UiSessionState uiState;+veyra::ui::UiPreferenceStore preferences(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local");veyra::ui::UiPreferences uiPreferences;+HWND inspector=nullptr,metricLabel=nullptr,tooltips=nullptr,diagnosticPanel=nullptr;bool showDiagnostics=false,inspectorResizing=false;int proposedInspectorWidth=320;bool preferWatching=true,jobPaused=false;int subtitlePixels=22;+veyra::engine::EnhancementSettings lastSuccessful,jobExpected;bool haveSuccessful=false;uint64_t masterPendingRevision=0,masterPendingSession=0;bool masterPreviousEnabled=true;+std::wstring smokeView;bool smokeViewApplied=false;+std::wstring smokeDualOutput;bool smokeEmpty=false;DWORD modeGdiStart=0,modeHandlesStart=0;SIZE_T modePrivateStart=0;+bool smokeDual=false,smokeDualPause=false,smokeMaster=false,smokeMasterReject=false,smokeAudio=false,smokeJob=false,smokeJobCancel=false,smokeJobExit=false;int dualStep=0,masterStep=0,audioStep=0,jobStep=0;double pausedPosition=-1,jobPosition=0;uint64_t pausedFrames=0;ULONGLONG jobPauseTick=0;HANDLE workerMapping=nullptr;+void switchMode();void selectInspector(int);void refreshDailyPresets();+void applySettings(veyra::engine::EnhancementSettings s){uiState.configured=s;if(uiState.enhanced)engine.requestSettings(s);else veyra::log::info("ui-settings","enhancement off: draft saved for explicit enable");}++struct ToolbarItem{HWND hwnd;int width;};std::vector<ToolbarItem> toolbar;+bool full=false,holdOriginal=false,referenceBase=false;int compareMode=0;float compareSplit=.5f;WINDOWPLACEMENT windowPlacement{sizeof(windowPlacement)};+HWND mainWindow=nullptr,video=nullptr,statusBar=nullptr,seekBar=nullptr;+std::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;+void openFile(const std::wstring&);+void layout();+void updateComparison(){engine.comparison(holdOriginal?1:compareMode,referenceBase,compareSplit);}+void toggleFullscreen(){full=!full;if(full){GetWindowPlacement(mainWindow,&windowPlacement);SetWindowLongPtrW(mainWindow,GWL_STYLE,WS_POPUP|WS_VISIBLE);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");layout();}+LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_PTR){+ if(id==VideoSurface&&m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(h,&ps);RECT r{};GetClientRect(h,&r);FillRect(dc,&r,veyra::ui::bgBrush());EndPaint(h,&ps);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&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}+ return DefSubclassProc(h,m,w,l);+}+veyra::engine::PlayerOptions options(){return veyra::engine::PlayerOptions::from(engine.snapshot().desired);}++std::wstring fileDialog(bool save){wchar_t name[32768]{};OPENFILENAMEW ofn{};ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=mainWindow;ofn.lpstrFile=name;ofn.nMaxFile=32768;+ofn.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());}+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();}+ 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"← 返回日常模式");layout();+ 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()));+}+void layout(){if(!mainWindow||!video)return;const auto layoutBegin=std::chrono::steady_clock::now();using namespace veyra::ui;RECT r{};GetClientRect(mainWindow,&r);int w=MulDiv(r.right,96,GetDpiForWindow(mainWindow)),h=MulDiv(r.bottom,96,GetDpiForWindow(mainWindow));const bool pro=uiState.mode==Mode::Professional;setText(GetDlgItem(mainWindow,Brand),pro?L"V":L"V E Y R A");ChromeLayout g(w,h,pro,uiState.drawer,uiPreferences.inspectorWidth);if(pro&&uiState.diagnostics){g.viewHeight-=132;g.bottom-=132;}auto batch=BeginDeferWindowPos(72);+ auto pos=[&](HWND c,int x,int y,int width,int height,bool show=true){if(!c)return;if(!show&&c!=subtitleLabel){batch=DeferWindowPos(batch,c,nullptr,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_HIDEWINDOW);return;}batch=DeferWindowPos(batch,c,nullptr,dip(mainWindow,x),dip(mainWindow,y),dip(mainWindow,std::max(1,width)),dip(mainWindow,std::max(1,height)),SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREDRAW|SWP_NOCOPYBITS|(show?SWP_SHOWWINDOW:SWP_HIDEWINDOW));};+ auto put=[&](int id,int x,int y,int width,int height=36,bool show=true){pos(GetDlgItem(mainWindow,id),x,y,width,height,show);};+ for(auto item:toolbar){int id=GetDlgCtrlID(item.hwnd);if(id!=Open&&id!=Capture&&id!=Recent&&id!=Play&&id!=Stop&&id!=Fullscreen&&id!=OriginalHold&&id!=Split&&id!=CompareToggle&&id!=Reference&&id!=Info)pos(item.hwnd,0,0,1,1,false);}+ auto target=engine.snapshot();+ const bool rightVisible=pro&&g.panelWidth>0;veyra::ui::settingsVisibility(rightVisible&&!full);+ pos(video,full?0:g.left,full?0:g.top,full?w:g.viewWidth,full?h:g.viewHeight,!(pro&&showDiagnostics&&!full));+ SetWindowRgn(video,full?nullptr:CreateRoundRectRgn(0,0,dip(mainWindow,g.viewWidth),dip(mainWindow,g.viewHeight),dip(mainWindow,pro?32:4),dip(mainWindow,pro?32:4)),FALSE);+ put(Brand,pro?8:g.left,pro?12:24,pro?52:116,32,!full);surface(GetDlgItem(mainWindow,Brand),pro?RGB(16,17,18):cinema);+ put(Open,g.left+138,22,104,36,!full&&!pro);put(Capture,g.left+250,22,94,36,!full&&!pro);put(Recent,g.left+354,22,90,36,!full&&!pro&&w>=1000);+ put(ModeSwitch,w-292,14,160,32,!full);surface(GetDlgItem(mainWindow,ModeSwitch),pro?background:cinema);marked(GetDlgItem(mainWindow,ModeSwitch),false);+ put(WindowMin,w-124,14,32,32,!full);put(WindowMax,w-88,14,32,32,!full);put(WindowClose,w-52,14,32,32,!full);+ for(int id:{WindowMin,WindowMax,WindowClose})surface(GetDlgItem(mainWindow,id),pro?background:cinema);+ put(InspectorDrawer,w-384,14,76,32,!full&&pro&&w<960);+ put(Master,pro?g.left+(w<960?120:190):g.left+g.viewWidth-250,pro?14:66,116,32,!full);put(DailyPreset,pro?g.left+318:g.left+g.viewWidth-128,pro?14:66,pro?172:128,200,!full&&(w>=1080||!pro));+ for(int id:{Open,Capture,Recent,Master,DailyPreset})surface(GetDlgItem(mainWindow,id),pro?background:cinema);+ put(ProRailVideo,12,92,44,44,!full&&pro);put(ProRailCapture,12,148,44,44,!full&&pro);put(ImageOpen,12,204,44,44,!full&&pro);+ for(int id:{ProRailVideo,ProRailCapture,ImageOpen})surface(GetDlgItem(mainWindow,id),RGB(16,17,18));+ for(int i=0;i<4;++i)put(TabEnhance+i,g.right+12+i*((g.panelWidth-24)/4),g.top+12,(g.panelWidth-24)/4,32,!full&&rightVisible);+ pos(inspector,g.right+12,g.top+56,g.panelWidth-24,g.viewHeight-68,!full&&rightVisible);+ int barTop=pro?g.bottom:g.top+g.viewHeight;int tx=g.left+16,tw=g.viewWidth-32;+ pos(seekBar,pro?tx:g.left,pro?barTop+4:barTop-6,pro?tw:g.viewWidth,12,!full&&!target.capture&&!target.image);surface(seekBar,pro?panel:cinemaPanel);+ put(TimeLabel,tx,barTop+11,tw,20,!full);surface(GetDlgItem(mainWindow,TimeLabel),pro?panel:cinemaPanel);+ put(MediaTitle,tx+4,barTop+40,std::max(80,tw/2-96),30,!full);surface(GetDlgItem(mainWindow,MediaTitle),pro?panel:cinemaPanel);+ put(Play,tx+tw/2-22,barTop+33,44,44,!full);put(Stop,tx+tw/2-68,barTop+37,36,36,!full&&tw>=560);+ put(Mute,tx+tw-242,barTop+37,36,36,!full&&tw>=650);put(Volume,tx+tw-206,barTop+46,82,18,!full&&tw>=650);+ put(Subtitle,tx+tw-104,barTop+37,40,36,!full);put(Fullscreen,full?w-58:tx+tw-48,full?14:barTop+37,40,36,true);+ for(int id:{Play,Stop,Mute,Volume,Subtitle,Fullscreen})surface(GetDlgItem(mainWindow,id),pro?panel:cinemaPanel);+ put(OriginalHold,tx,barTop+160,96,32,!full&&pro);put(Split,tx+102,barTop+160,92,32,!full&&pro);put(CompareToggle,tx+200,barTop+160,96,32,!full&&pro&&tw>=600);put(Reference,tx+(tw>=600?302:200),barTop+160,std::min(172,tw-(tw>=600?302:200)-88),180,!full&&pro&&tw>=500);+ put(Details,tx+tw-76,barTop+160,76,32,!full&&pro);put(Info,12,h-66,44,44,!full&&pro);+ pos(metricLabel,tx,barTop+212,tw,120,!full&&pro&&uiState.diagnostics);+ pos(statusBar,g.left,g.top+8,g.viewWidth,44,false);pos(diagnosticPanel,g.left,g.top,g.viewWidth,h-g.top-20,!full&&pro&&showDiagnostics);+ const bool empty=currentFile.empty();put(EmptyTitle,g.left+24,g.top+g.viewHeight/2-40,g.viewWidth-48,48,!full&&empty);put(EmptyHint,g.left+24,g.top+g.viewHeight/2+14,g.viewWidth-48,68,!full&&empty);+ for(int id:{EmptyTitle,EmptyHint})surface(GetDlgItem(mainWindow,id),background);+ pos(subtitleLabel,full?20:g.left+20,full?h-118:g.top+g.viewHeight-118,full?w-40:g.viewWidth-40,108,uiState.subtitles&&GetWindowTextLengthW(subtitleLabel)>0);+ put(JobProgress,g.left+16,g.top+14,std::min(320,g.viewWidth-32),32,exportJob.poll().state!=veyra::engine::ExportState::Idle&&!full);+ const auto layoutQueued=std::chrono::steady_clock::now();EndDeferWindowPos(batch);const auto layoutCommitted=std::chrono::steady_clock::now();if(empty&&!full){for(int id:{EmptyTitle,EmptyHint})SetWindowPos(GetDlgItem(mainWindow,id),HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);}if(diagnosticPanel&&showDiagnostics&&pro&&!full)SetWindowPos(diagnosticPanel,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);SetWindowPos(subtitleLabel,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);if(rightVisible&&!full)SetWindowPos(inspector,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);SetWindowPos(GetDlgItem(mainWindow,Fullscreen),HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);if(diagnosticPanel&&showDiagnostics&&pro&&!full)SetWindowPos(diagnosticPanel,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);if(auto focused=GetFocus();focused&&IsChild(mainWindow,focused)&&!IsWindowVisible(focused))SetFocus(mainWindow);RedrawWindow(mainWindow,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);if(smokeDual)veyra::log::info("ui-layout-timing",std::format("queueMs={:.3f} commitMs={:.3f} zorderMs={:.3f}",std::chrono::duration<double,std::milli>(layoutQueued-layoutBegin).count(),std::chrono::duration<double,std::milli>(layoutCommitted-layoutQueued).count(),std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-layoutCommitted).count()));+}++void subtitleMenu(){HMENU menu=CreatePopupMenu();AppendMenuW(menu,MF_STRING|(uiState.subtitles?MF_CHECKED:0),Subtitle,L"显示字幕");AppendMenuW(menu,MF_STRING,SubtitleLoad,L"载入外部 SRT…");AppendMenuW(menu,MF_STRING,SubtitleSize,L"切换字幕字号");RECT r{};GetWindowRect(GetDlgItem(mainWindow,Subtitle),&r);TrackPopupMenu(menu,TPM_LEFTALIGN|TPM_BOTTOMALIGN,r.left,r.top,0,mainWindow,nullptr);DestroyMenu(menu);}+void startVideoExport(bool hevc){auto s=engine.snapshot();if(currentFile.empty()||s.capture||s.image||!s.frames||s.applying||s.failed||exportJob.poll().active())return;wchar_t name[32768]{};OPENFILENAMEW d{sizeof(d)};d.hwndOwner=mainWindow;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"MP4视频\0*.mp4\0";d.lpstrDefExt=L"mp4";d.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;if(GetSaveFileNameW(&d)){exportJob.start(currentFile,name,s.applied,hevc);jobPaused=false;layout();}}++LRESULT CALLBACK proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){+case WM_CREATE:{mainWindow=hwnd;font=veyra::ui::makeFont(hwnd);veyra::ui::titleTheme(hwnd);uiState.configured=initialOptions.snapshot();+control(L"BUTTON",L"打开视频",Open,BS_PUSHBUTTON,10,10,150,30);control(L"BUTTON",L"播放",Play,BS_PUSHBUTTON,168,10,68,30);control(L"BUTTON",L"停止",Stop,BS_PUSHBUTTON,244,10,62,30);control(L"BUTTON",L"保存图片",Save,BS_PUSHBUTTON,314,10,95,30);+control(L"BUTTON",L"DLSS5 NR",Nr,BS_AUTOCHECKBOX,425,10,110,30);control(L"BUTTON",L"SR 4K",Sr,BS_AUTOCHECKBOX,518,10,78,30);control(L"BUTTON",L"补帧",Fg,BS_AUTOCHECKBOX,600,10,78,30);CheckDlgButton(hwnd,Nr,BST_CHECKED);+control(L"BUTTON",L"采集",Capture,BS_PUSHBUTTON,690,10,75,30);control(L"BUTTON",L"导出视频",Export,BS_PUSHBUTTON,773,10,103,30);control(L"BUTTON",L"性能/诊断",Info,BS_PUSHBUTTON,884,10,100,30);+control(L"BUTTON",L"实时NR档",Realtime,BS_AUTOCHECKBOX,952,10,100,30);+control(L"BUTTON",L"最近打开",Recent,BS_PUSHBUTTON,1072,10,75,30);+auto mult=control(L"COMBOBOX",L"",Multiplier,CBS_DROPDOWNLIST,1150,10,70,180);for(auto label:{L"2X",L"3X",L"4X"})SendMessageW(mult,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(mult,CB_SETCURSEL,initialOptions.fgMultiplier-2,0);+control(L"BUTTON",L"参数与预设",Settings,BS_PUSHBUTTON,1225,10,100,30);+auto original=control(L"BUTTON",L"按住原图 V",OriginalHold,BS_PUSHBUTTON,0,0,110,30);SetWindowSubclass(original,interaction,OriginalHold,0);+control(L"BUTTON",L"原图/增强切换",CompareToggle,BS_PUSHBUTTON,0,0,120,30);control(L"BUTTON",L"分屏拖动",Split,BS_PUSHBUTTON,0,0,95,30);+auto ref=control(L"COMBOBOX",L"",Reference,CBS_DROPDOWNLIST,0,0,170,180);for(auto label:{L"对比:输入原画",L"对比:增强前底图"})SendMessageW(ref,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));SendMessageW(ref,CB_SETCURSEL,0,0);control(L"BUTTON",L"全屏",Fullscreen,BS_PUSHBUTTON,0,0,108,30);+subtitleLabel=veyra::ui::createSubtitleOverlay(hwnd);+video=control(L"STATIC",L"",VideoSurface,SS_BLACKRECT|SS_NOTIFY,8,52,1100,610);seekBar=control(TRACKBAR_CLASSW,L"",Seek,TBS_HORZ,8,675,1100,24);SendMessageW(seekBar,TBM_SETRANGE,TRUE,MAKELPARAM(0,10000));statusBar=control(L"STATIC",L"打开本地视频或PNG/JPEG。本地实验运行时,非NVIDIA官方产品。",0,SS_LEFT,12,708,1080,36);+SetWindowSubclass(video,interaction,VideoSurface,0);+control(L"STATIC",L"V E Y R A",Brand,SS_CENTER,0,0,100,30);+control(L"BUTTON",L"切换专业模式 →",ModeSwitch,BS_PUSHBUTTON,0,0,164,36);veyra::ui::marked(GetDlgItem(hwnd,ModeSwitch));+control(L"BUTTON",L"增强已开启",Master,BS_PUSHBUTTON,0,0,126,36);+control(L"COMBOBOX",L"",DailyPreset,CBS_DROPDOWNLIST,0,0,180,200);+control(L"BUTTON",L"视频",ProRailVideo,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"采集",ProRailCapture,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"图片",ImageOpen,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTON",L"参数",InspectorDrawer,BS_PUSHBUTTON,0,0,84,36);+const wchar_t* tabs[]={L"增强",L"补帧",L"预设",L"导出"};for(int i=0;i<4;++i)control(L"BUTTON",tabs[i],TabEnhance+i,BS_PUSHBUTTON,0,0,76,36);+control(L"BUTTON",L"音量",Mute,BS_PUSHBUTTON,0,0,54,36);auto vol=control(TRACKBAR_CLASSW,L"音量",Volume,TBS_HORZ|TBS_NOTICKS,0,0,80,26);SendMessageW(vol,TBM_SETRANGE,TRUE,MAKELPARAM(0,100));SendMessageW(vol,TBM_SETPOS,TRUE,100);+control(L"BUTTON",L"字幕",Subtitle,BS_PUSHBUTTON,0,0,62,36);control(L"STATIC",L"尚未打开媒体",MediaTitle,SS_LEFT|SS_ENDELLIPSIS,0,0,250,26);control(L"STATIC",L"00:00 / 00:00",TimeLabel,SS_LEFT,0,0,200,20);+control(L"STATIC",L"开始观看",EmptyTitle,SS_CENTER,0,0,500,48);emptyFont=veyra::ui::makeFont(hwnd,26,FW_NORMAL);SendDlgItemMessageW(hwnd,EmptyTitle,WM_SETFONT,WPARAM(emptyFont),TRUE);control(L"STATIC",L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中",EmptyHint,SS_CENTER,0,0,500,68);+control(L"BUTTON",L"性能 ▾",Details,BS_PUSHBUTTON,0,0,112,32);control(L"BUTTON",L"",JobProgress,BS_PUSHBUTTON,0,0,280,32);metricLabel=control(L"STATIC",L"",0,SS_LEFT,0,0,500,132);+control(L"BUTTON",L"最小化",WindowMin,BS_PUSHBUTTON,0,0,32,32);control(L"BUTTON",L"最大化",WindowMax,BS_PUSHBUTTON,0,0,32,32);control(L"BUTTON",L"关闭窗口",WindowClose,BS_PUSHBUTTON,0,0,32,32);+using veyra::ui::Icon;veyra::ui::icon(GetDlgItem(hwnd,WindowMin),Icon::Minimize);veyra::ui::icon(GetDlgItem(hwnd,WindowMax),Icon::Maximize);veyra::ui::icon(GetDlgItem(hwnd,WindowClose),Icon::Close);+veyra::ui::icon(GetDlgItem(hwnd,Play),Icon::Play);veyra::ui::icon(GetDlgItem(hwnd,Stop),Icon::Stop);veyra::ui::icon(GetDlgItem(hwnd,Mute),Icon::Volume);veyra::ui::icon(GetDlgItem(hwnd,Subtitle),Icon::Subtitle);veyra::ui::icon(GetDlgItem(hwnd,Fullscreen),Icon::Fullscreen);+veyra::ui::icon(GetDlgItem(hwnd,ProRailVideo),Icon::Video);veyra::ui::icon(GetDlgItem(hwnd,ProRailCapture),Icon::Capture);veyra::ui::icon(GetDlgItem(hwnd,ImageOpen),Icon::Image);veyra::ui::icon(GetDlgItem(hwnd,Info),Icon::Subtitle);+veyra::ui::icon(GetDlgItem(hwnd,Open),Icon::Video,true);veyra::ui::icon(GetDlgItem(hwnd,Capture),Icon::Capture,true);+for(int id:{Open,Capture,Recent,WindowMin,WindowMax,WindowClose,Stop,Mute,Subtitle,Fullscreen,ProRailVideo,ProRailCapture,ImageOpen,Info})veyra::ui::ghost(GetDlgItem(hwnd,id));+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));+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&&!full)return 0;break;+case WM_NCHITTEST:{LRESULT hit=DefWindowProcW(hwnd,msg,wp,lp);if(hit==HTCLIENT&&!full){POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};ScreenToClient(hwnd,&p);RECT r{};GetClientRect(hwnd,&r);int edge=veyra::ui::dip(hwnd,7);bool left=p.x<edge,right=p.x>=r.right-edge,top=p.y<edge,bottom=p.y>=r.bottom-edge;if(top&&left)return HTTOPLEFT;if(top&&right)return HTTOPRIGHT;if(bottom&&left)return HTBOTTOMLEFT;if(bottom&&right)return HTBOTTOMRIGHT;if(left)return HTLEFT;if(right)return HTRIGHT;if(top)return HTTOP;if(bottom)return HTBOTTOM;if(p.y<veyra::ui::dip(hwnd,54))return HTCAPTION;}return hit;}+case WM_PAINT:{PAINTSTRUCT ps{};HDC dc=BeginPaint(hwnd,&ps);RECT r{};GetClientRect(hwnd,&r);veyra::ui::ChromeLayout g(MulDiv(r.right,96,GetDpiForWindow(hwnd)),MulDiv(r.bottom,96,GetDpiForWindow(hwnd)),uiState.mode==veyra::ui::Mode::Professional,uiState.drawer,uiPreferences.inspectorWidth);if(g.pro&&uiState.diagnostics){g.viewHeight-=132;g.bottom-=132;}veyra::ui::paintChrome(hwnd,dc,g,engine.snapshot(),full);if(inspectorResizing){int x=veyra::ui::dip(hwnd,g.w-proposedInspectorWidth-27);auto pen=CreatePen(PS_SOLID,1,veyra::ui::accent);auto old=SelectObject(dc,pen);MoveToEx(dc,x,veyra::ui::dip(hwnd,68),nullptr);LineTo(dc,x,r.bottom-veyra::ui::dip(hwnd,20));SelectObject(dc,old);DeleteObject(pen);}EndPaint(hwnd,&ps);return 0;}+case WM_LBUTTONDOWN:{if(uiState.mode==veyra::ui::Mode::Professional&&!full){RECT r{};GetClientRect(hwnd,&r);int w=MulDiv(r.right,96,GetDpiForWindow(hwnd)),x=MulDiv(GET_X_LPARAM(lp),96,GetDpiForWindow(hwnd));if(w>=1180&&abs(x-(w-uiPreferences.inspectorWidth-27))<8){inspectorResizing=true;proposedInspectorWidth=uiPreferences.inspectorWidth;SetCapture(hwnd);return 0;}}break;}+case WM_MOUSEMOVE:if(inspectorResizing){RECT r{};GetClientRect(hwnd,&r);proposedInspectorWidth=std::clamp(MulDiv(r.right-GET_X_LPARAM(lp),96,GetDpiForWindow(hwnd))-27,296,420);InvalidateRect(hwnd,nullptr,FALSE);return 0;}break;+case WM_LBUTTONUP:if(inspectorResizing){inspectorResizing=false;ReleaseCapture();uiPreferences.inspectorWidth=proposedInspectorWidth;layout();return 0;}break;+case WM_CAPTURECHANGED:if(inspectorResizing){inspectorResizing=false;InvalidateRect(hwnd,nullptr,FALSE);}break;+case WM_NOTIFY:{auto header=reinterpret_cast<NMHDR*>(lp);if(header->code==TTN_GETDISPINFOW){auto info=reinterpret_cast<NMTTDISPINFOW*>(lp);HWND child=reinterpret_cast<HWND>(header->idFrom);if(auto tip=GetPropW(child,L"veyra.tip"))info->lpszText=reinterpret_cast<wchar_t*>(tip);else{static wchar_t value[512];GetWindowTextW(child,value,512);info->lpszText=value;}return 0;}break;}+case WM_GETMINMAXINFO:{auto info=reinterpret_cast<MINMAXINFO*>(lp);info->ptMinTrackSize={veyra::ui::dip(hwnd,720),veyra::ui::dip(hwnd,540)};return 0;}+case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORBTN:case WM_CTLCOLORLISTBOX:return veyra::ui::colors(msg,wp,lp);+case WM_APP+43:showDiagnostics=false;layout();return 0;+case WM_APP+42:refreshDailyPresets();return 0;+case WM_APP+41:switch(wp){case 501:startVideoExport(lp!=0);break;case 502:{auto path=fileDialog(true);if(!path.empty())engine.saveFrame(path);break;}case 503:jobPaused=!jobPaused;exportJob.pause(jobPaused);break;case 504:exportJob.cancel();break;case 505:preferWatching=lp==BST_CHECKED;break;}return 0;+case WM_SIZE:if(wp!=SIZE_MINIMIZED)layout();return 0;+case WM_DROPFILES:{wchar_t file[32768]{};DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file,32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file);layout();return 0;}+case WM_COMMAND:switch(LOWORD(wp)){+case Open:case ProRailVideo:case ImageOpen:openFile(fileDialog(false));layout();break;+case ModeSwitch:switchMode();break;+case WindowMin:ShowWindow(hwnd,SW_MINIMIZE);break;case WindowMax:ShowWindow(hwnd,IsZoomed(hwnd)?SW_RESTORE:SW_MAXIMIZE);break;case WindowClose:SendMessageW(hwnd,WM_CLOSE,0,0);break;+case Master:if(masterPendingRevision)break;masterPreviousEnabled=uiState.enhanced;if(uiState.enhanced)uiState.configured=engine.snapshot().desired;uiState.enhanced=!uiState.enhanced;veyra::ui::settingsEnabled(uiState.enhanced,uiState.configured);engine.requestSettings(uiState.effective());if(auto pending=engine.snapshot();pending.running){masterPendingRevision=pending.desired.revision;masterPendingSession=pending.sessionId;}break;+case DailyPreset:if(HIWORD(wp)==CBN_SELCHANGE){veyra::engine::EnhancementSettings setting;auto index=SendDlgItemMessageW(hwnd,DailyPreset,CB_GETCURSEL,0,0);if(index>0&&veyra::ui::presetAt(size_t(index-1),setting))applySettings(setting);}break;+case InspectorDrawer:uiState.drawer=!uiState.drawer;layout();break;+case TabEnhance:case TabFg:case TabPresets:case TabExport:selectInspector(LOWORD(wp)-TabEnhance);break;+case JobProgress:if(uiState.mode==veyra::ui::Mode::Daily)switchMode();uiState.drawer=true;selectInspector(3);layout();break;+case Details:uiState.diagnostics=!uiState.diagnostics;SetWindowTextW(GetDlgItem(hwnd,Details),uiState.diagnostics?L"性能 ▴":L"性能 ▾");layout();break;+case Mute:{auto s=engine.snapshot();engine.setVolume(s.volume,!s.muted);break;}+case Subtitle:if(lp)subtitleMenu();else{uiState.subtitles=!uiState.subtitles;layout();}break;+case SubtitleLoad:{wchar_t name[32768]{};OPENFILENAMEW d{sizeof(d)};d.hwndOwner=hwnd;d.lpstrFile=name;d.nMaxFile=32768;d.lpstrFilter=L"SubRip 字幕\0*.srt\0";d.Flags=OFN_FILEMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&d)){subtitles=veyra::engine::loadSrt(name);uiState.subtitles=true;layout();}break;}+case SubtitleSize:subtitlePixels=subtitlePixels==22?28:subtitlePixels==28?34:22;break;+case Recent:{wchar_t recent[32768]{};GetPrivateProfileStringW(L"Player",L"最近打开",L"",recent,32768,(std::filesystem::path(VEYRA_PROJECT_ROOT)/"runtime_local/veyra.ini").wstring().c_str());openFile(recent);break;}+case Play:{auto s=engine.snapshot();if(s.capture||s.image||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping)break;if(!currentFile.empty()&&(!s.running||s.transport==veyra::engine::TransportState::Ended)){openFile(currentFile);break;}paused=s.transport==veyra::engine::TransportState::Playing;engine.pause(paused);SetWindowTextW(GetDlgItem(hwnd,Play),paused?L"播放":L"暂停");break;}+case Stop:engine.stop();break;+case Save:{auto name=fileDialog(true);if(!name.empty())engine.saveFrame(name);break;}+case Multiplier:case Realtime:case Nr:case Sr:case Fg:{auto changed=engine.snapshot().desired;const auto id=LOWORD(wp);+if(id==Nr)changed.nr=IsDlgButtonChecked(hwnd,Nr)==BST_CHECKED;+if(id==Sr)changed.sr=IsDlgButtonChecked(hwnd,Sr)==BST_CHECKED;+if(id==Realtime)changed.nrPolicy=IsDlgButtonChecked(hwnd,Realtime)==BST_CHECKED?veyra::pipeline::NrSizePolicy::Realtime:veyra::pipeline::NrSizePolicy::Native;+if(id==Fg)changed.multiplier=IsDlgButtonChecked(hwnd,Fg)==BST_CHECKED?uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2):1;+if(id==Multiplier&&HIWORD(wp)==CBN_SELCHANGE&&changed.multiplier>1)changed.multiplier=uint32_t(SendDlgItemMessageW(hwnd,Multiplier,CB_GETCURSEL,0,0)+2);+engine.requestSettings(changed);break;}++case Fullscreen:toggleFullscreen();break;+case VideoSurface:if(HIWORD(wp)==STN_DBLCLK)toggleFullscreen();break;+case CompareToggle:compareMode=compareMode==1?0:1;updateComparison();break;+case Split:compareMode=compareMode==2?0:2;updateComparison();break;+case Reference:referenceBase=SendDlgItemMessageW(hwnd,Reference,CB_GETCURSEL,0,0)==1;updateComparison();break;+case Settings:if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(0);break;+case Capture:case ProRailCapture:veyra::ui::showCapturePanel(hwnd,[](const std::wstring& path){openFile(path);layout();});break;+case Export:if(uiState.mode==veyra::ui::Mode::Professional)startVideoExport(false);break;+case Info:showDiagnostics=!showDiagnostics;layout();break;+}return 0;+case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==GetDlgItem(hwnd,Volume)){engine.setVolume(float(SendDlgItemMessageW(hwnd,Volume,TBM_GETPOS,0,0))/100,false);return 0;}if(reinterpret_cast<HWND>(lp)==seekBar){dragging=LOWORD(wp)==TB_THUMBTRACK;auto s=engine.snapshot();if(!dragging&&s.duration>0)engine.seek(s.duration*SendMessageW(seekBar,TBM_GETPOS,0,0)/10000.0);}return 0;+case WM_KEYDOWN:if(wp==VK_SPACE){SendMessageW(hwnd,WM_COMMAND,Play,0);return 0;}if(wp==VK_F11){toggleFullscreen();return 0;}if(wp==VK_ESCAPE&&full){toggleFullscreen();return 0;}if(wp=='V'&&uiState.mode==veyra::ui::Mode::Professional){holdOriginal=true;updateComparison();return 0;}break;+case WM_KEYUP:if(wp=='V'){holdOriginal=false;updateComparison();return 0;}break;+case WM_SYSKEYDOWN:if(wp==VK_RETURN&&(lp&(1LL<<29))){toggleFullscreen();return 0;}break;+case WM_ACTIVATEAPP:if(!wp){holdOriginal=false;updateComparison();}break;+case WM_DPICHANGED:{auto rect=reinterpret_cast<RECT*>(lp);if(!full)SetWindowPos(hwnd,nullptr,rect->left,rect->top,rect->right-rect->left,rect->bottom-rect->top,SWP_NOZORDER|SWP_NOACTIVATE);auto oldFont=font;font=CreateFontW(-MulDiv(15,HIWORD(wp),96),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");EnumChildWindows(hwnd,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(oldFont);DeleteObject(emptyFont);emptyFont=veyra::ui::makeFont(hwnd,26);SendDlgItemMessageW(hwnd,EmptyTitle,WM_SETFONT,WPARAM(emptyFont),TRUE);veyra::ui::settingsDpi();veyra::ui::telemetryDpi();layout();return 0;}++case WM_TIMER:{if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,1);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;+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;}+}auto s=engine.snapshot();CheckDlgButton(hwnd,Nr,s.desired.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,s.desired.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,s.desired.multiplier>1?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,s.desired.nrPolicy==veyra::pipeline::NrSizePolicy::Realtime?BST_CHECKED:BST_UNCHECKED);if(s.desired.multiplier>1)SendDlgItemMessageW(hwnd,Multiplier,CB_SETCURSEL,s.desired.multiplier-2,0);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(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);+using namespace veyra::ui;+if(uiState.enhanced&&s.frames>0&&!s.applying&&!s.failed){lastSuccessful=s.applied;haveSuccessful=true;}+if(masterPendingRevision&&!s.applying){if(s.sessionId==masterPendingSession&&s.rejectedRevision==masterPendingRevision&&s.desired.revision<masterPendingRevision){uiState.enhanced=masterPreviousEnabled;settingsEnabled(uiState.enhanced,uiState.configured);veyra::log::warn("ui-master","transaction rolled back; UI restored to actual enabled state");}masterPendingRevision=0;}+setText(GetDlgItem(hwnd,Master),masterPendingRevision?L"正在应用…":uiState.enhanced?L"增强已开启":L"增强已关闭");selected(GetDlgItem(hwnd,Master),uiState.enhanced);+veyra::ui::icon(GetDlgItem(hwnd,Play),s.transport==veyra::engine::TransportState::Playing?veyra::ui::Icon::Pause:veyra::ui::Icon::Play);veyra::ui::icon(GetDlgItem(hwnd,Mute),s.muted?veyra::ui::Icon::Muted:veyra::ui::Icon::Volume);+setText(GetDlgItem(hwnd,Play),s.transport==veyra::engine::TransportState::Paused||s.transport==veyra::engine::TransportState::Ended||!s.running?L"▶":L"Ⅱ");+setText(GetDlgItem(hwnd,Mute),!s.audioAvailable?L"无音轨":s.muted?L"静音":L"音量");EnableWindow(GetDlgItem(hwnd,Volume),s.audioAvailable);EnableWindow(GetDlgItem(hwnd,Mute),s.audioAvailable);+EnableWindow(seekBar,s.running&&!s.capture&&!s.image&&s.duration>0);ShowWindow(seekBar,!full&&!s.capture&&!s.image&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional)?SW_SHOW:SW_HIDE);EnableWindow(GetDlgItem(hwnd,Play),!currentFile.empty()&&!s.capture&&!s.image);EnableWindow(GetDlgItem(hwnd,Stop),s.running);+setText(GetDlgItem(hwnd,MediaTitle),currentFile.empty()?L"尚未打开媒体":s.capture?L"采集卡 · LIVE":std::filesystem::path(currentFile).filename().wstring());+auto stamp=[](double v){int seconds=std::max(0,int(v));return std::format(L"{:02}:{:02}:{:02}",seconds/3600,seconds/60%60,seconds%60);};+setText(GetDlgItem(hwnd,TimeLabel),s.capture?L"LIVE · 采集卡实时输入":s.image?L"静态图片":stamp(s.position)+L" / "+stamp(s.duration)+(s.transport==veyra::engine::TransportState::Opening?L" · 正在打开…":s.failed?L" · 发生错误,详见专业诊断":L""));+std::wstring metric=std::format(L"源帧处理 {:.1f} fps · 有效生成 {} · 实际提交 {}\n提交迟到 p95 {:.1f} ms · GPU / CPU 时间分别统计\n{}\n实际扫描率与光子延迟:未测",s.fps,s.generated,s.metrics.submitted,s.lateP95Ms,s.status);setText(metricLabel,metric);+if(uiState.mode==Mode::Professional){RECT client{};GetClientRect(hwnd,&client);RECT dashboard{0,client.bottom-dip(hwnd,232),client.right,client.bottom};InvalidateRect(hwnd,&dashboard,FALSE);}+exportJob.watching(preferWatching&&s.running&&s.transport==veyra::engine::TransportState::Playing);auto job=exportJob.poll();exportPanelStatus(job,!currentFile.empty()&&!s.capture&&!s.image&&s.frames>0&&!s.applying,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);+setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");ShowWindow(GetDlgItem(hwnd,EmptyTitle),(currentFile.empty()||s.failed)&&!full?SW_SHOW:SW_HIDE);ShowWindow(GetDlgItem(hwnd,EmptyHint),(currentFile.empty()||s.failed)&&!full?SW_SHOW:SW_HIDE);+if(!dragging&&s.duration>0)SendMessageW(seekBar,TBM_SETPOS,TRUE,LPARAM(s.position/s.duration*10000));+if(!smokeViewApplied&&!smokeView.empty()&&(s.frames>0||smokeEmpty)){smokeViewApplied=true;if(smokeView==L"small")SetWindowPos(hwnd,nullptr,0,0,800,600,SWP_NOMOVE|SWP_NOZORDER);if(smokeView!=L"daily"&&smokeView!=L"empty"&&uiState.mode==veyra::ui::Mode::Daily)switchMode();if(smokeView==L"export")selectInspector(3);if(smokeView==L"diagnostics"){showDiagnostics=true;layout();}if(smokeView==L"fullscreen")toggleFullscreen();}+if(smokeDualPause&&pausedPosition<0&&s.frames>20){engine.pause(true);pausedPosition=s.position;pausedFrames=s.frames;}+if(smokeDual&&startTick&&s.frames>10&&dualStep<40&&GetTickCount64()-startTick>ULONGLONG(1500+dualStep*200)){if(dualStep==4){modeGdiStart=GetGuiResources(GetCurrentProcess(),GR_GDIOBJECTS);GetProcessHandleCount(GetCurrentProcess(),&modeHandlesStart);PROCESS_MEMORY_COUNTERS_EX pm{};pm.cb=sizeof(pm);GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pm),sizeof(pm));modePrivateStart=pm.PrivateUsage;}switchMode();+if(smokeDualPause&&pausedPosition>=0&&s.transport==veyra::engine::TransportState::Paused){auto after=engine.snapshot();if(after.position!=s.position||after.frames!=s.frames)dualStep=-100;}++dualStep;if(dualStep==40){DWORD handles=0;GetProcessHandleCount(GetCurrentProcess(),&handles);PROCESS_MEMORY_COUNTERS_EX pm{};pm.cb=sizeof(pm);GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pm),sizeof(pm));veyra::log::info("ui-resources",std::format("gdiStart={} gdiEnd={} handlesStart={} handlesEnd={} privateStart={} privateEnd={}",modeGdiStart,GetGuiResources(GetCurrentProcess(),GR_GDIOBJECTS),modeHandlesStart,handles,modePrivateStart,pm.PrivateUsage));}}+if((smokeDual||smokeJobCancel||smokeJobExit)&&!smokeDualOutput.empty()&&s.frames>20){jobExpected=s.applied;jobExpected.nrPolicy=veyra::pipeline::NrSizePolicy::Native;exportJob.start(currentFile,smokeDualOutput,s.applied,false,(smokeJob||smokeJobCancel||smokeJobExit)?120:24);smokeDualOutput.clear();jobStep=1;jobPosition=s.position;}+if((smokeJobCancel||smokeJobExit)&&jobStep==1&&job.state==veyra::engine::ExportState::Running&&job.sourceFrames>=10){if(smokeJobExit){veyra::log::info("ui-job-test","parent close with active worker; cooperative cancellation requested");resultCode=0;PostMessageW(hwnd,WM_CLOSE,0,0);}else exportJob.cancel();jobStep=2;}+if(smokeJobCancel&&jobStep==2&&job.state==veyra::engine::ExportState::Cancelled){jobStep=4;veyra::log::info("ui-job-test",std::format("cancelled=true foregroundContinues={} source={} encoded={}",s.running,job.sourceFrames,job.encoded));}+if(smokeJob&&jobStep==1&&job.state==veyra::engine::ExportState::Running){exportJob.pause(true);jobStep=2;jobPauseTick=GetTickCount64();auto changed=s.desired;changed.model.intensity=.65f;engine.requestSettings(changed);}+if(smokeJob&&jobStep==2&&job.state==veyra::engine::ExportState::Paused&&GetTickCount64()-jobPauseTick>650){veyra::log::info("ui-job-test",std::format("paused=true foregroundAdvanced={} position={} startPosition={} session={}",s.position>jobPosition,s.position,jobPosition,s.sessionId));exportJob.pause(false);jobStep=s.position>jobPosition?3:-1;}+if(smokeJob&&jobStep==3&&job.state==veyra::engine::ExportState::Succeeded){const bool frozenSame=job.frozen==jobExpected&&job.frozenRevision==jobExpected.revision&&s.applied.model.intensity!=jobExpected.model.intensity;jobStep=frozenSame?4:-1;veyra::log::info("ui-job-test",std::format("success=true foregroundFrames={} changedAppliedIntensity={} jobFrozenRevisionIndependent={} frozenRevision={} frozenIntensity={} source={} generated={} holds={} encoded={}",s.frames,s.applied.model.intensity,frozenSame,jobExpected.revision,jobExpected.model.intensity,job.sourceFrames,job.generated,job.holds,job.encoded));}+if(smokeMaster&&startTick){if(masterStep==0&&s.frames>20){SendMessageW(hwnd,WM_COMMAND,Master,0);masterStep=1;}else if(smokeMasterReject&&masterStep==1&&!s.applying&&!masterPendingRevision&&s.rejectedRevision&&uiState.enhanced&&s.applied.nr){masterStep=3;veyra::log::info("ui-master-test","rejected bypass restored actual enabled UI");}else if(masterStep==1&&!s.applying&&!s.applied.nr&&!s.applied.sr&&s.applied.multiplier==1){SendMessageW(hwnd,WM_COMMAND,Master,0);masterStep=2;}else if(masterStep==2&&!s.applying&&s.applied.nr==uiState.configured.nr&&s.applied.model==uiState.configured.model&&s.applied.residual==uiState.configured.residual){masterStep=3;veyra::log::info("ui-master-test","full bypass applied and all configured parameters restored");}}+if(smokeAudio&&startTick&&s.audioAvailable){auto elapsed=GetTickCount64()-startTick;if(audioStep==0&&elapsed>1500){engine.setVolume(.5f,false);audioStep=1;}else if(audioStep==1&&elapsed>2500){engine.setVolume(0,false);audioStep=2;}else if(audioStep==2&&elapsed>3500){engine.setVolume(.8f,true);audioStep=3;}else if(audioStep==3&&elapsed>4500){engine.setVolume(1,false);audioStep=4;}}+if(smokeRollback&&startTick){if(settingsStep==0&&s.frames>20){auto changed=s.desired;if(smokeRollbackFlow)changed.nr=false;else{changed.model.style=2;changed.model.intensity=.35f;}engine.requestSettings(changed);settingsStep=1;}if(settingsStep==1&&s.frames>50&&s.desired.model.style==0&&s.applied.model.style==0&&!s.applying&&(!smokeRollbackFlow||(s.applied.nr&&s.nvofExecuted>30))){settingsStep=3;veyra::log::info("rollback-test",std::format("whole snapshot restored revision={} position={} style={} intensity={}",s.applied.revision,s.position,s.applied.model.style,s.applied.model.intensity));}}+if(smokeUi&&startTick){const auto elapsed=GetTickCount64()-startTick;+if(uiStep==0&&elapsed>2300){SendMessageW(hwnd,WM_KEYDOWN,VK_F11,0);uiStep=1;}+if(uiStep==1&&elapsed>2800){const bool entered=full&&(GetWindowLongPtrW(hwnd,GWL_STYLE)&WS_POPUP);SendMessageW(hwnd,WM_KEYDOWN,VK_ESCAPE,0);veyra::log::info("ui-test",std::format("F11 entered={} Esc restored={}",entered,!full));uiStep=entered&&!full?2:-1;}+if(uiStep==2&&elapsed>3300){SendMessageW(hwnd,WM_SYSKEYDOWN,VK_RETURN,1LL<<29);uiStep=3;}+if(uiStep==3&&elapsed>3800){const bool entered=full;SendMessageW(hwnd,WM_COMMAND,MAKEWPARAM(VideoSurface,STN_DBLCLK),LPARAM(video));veyra::log::info("ui-test",std::format("AltEnter entered={} doubleClick restored={}",entered,!full));uiStep=entered&&!full?4:-1;}+if(uiStep==4&&elapsed>4200){compareMode=2;compareSplit=.4f;updateComparison();uiStep=5;}+if(uiStep==5&&elapsed>4800){referenceBase=true;updateComparison();uiStep=6;}+if(uiStep==6&&elapsed>5500){holdOriginal=true;updateComparison();uiStep=7;}+if(uiStep==7&&elapsed>5900){holdOriginal=false;compareMode=0;updateComparison();veyra::log::info("ui-test",std::format("completed={} NR evaluations={} (no fullscreen NR re-create expected)",true,s.nrEvaluated));uiStep=8;}+}+if(smokeSettings&&startTick){const auto elapsed=GetTickCount64()-startTick;+if(settingsStep==0&&s.frames>20){auto change=s.desired;change.model.intensity=.6f;change.model.tone=.7f;change.residual.total=.4f;change.residual.color=.8f;engine.requestSettings(change);settingsStep=1;}+if(settingsStep==1&&s.applied.model.intensity==.6f&&elapsed>3300){auto change=s.desired;change.sr=true;engine.requestSettings(change);settingsStep=2;}+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;}+}+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&&(!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: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:DeleteObject(font);DeleteObject(emptyFont);PostQuitMessage(resultCode);return 0;+}return DefWindowProcW(hwnd,msg,wp,lp);}+}+int runVeyraApp(HINSTANCE instance,int show){+Gdiplus::GdiplusStartupInput graphicsInput;ULONG_PTR graphicsToken=0;Gdiplus::GdiplusStartup(&graphicsToken,&graphicsInput,nullptr);struct GraphicsCleanup{ULONG_PTR token;~GraphicsCleanup(){Gdiplus::GdiplusShutdown(token);}} graphicsCleanup{graphicsToken};+SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_BAR_CLASSES};InitCommonControlsEx(&controls);+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-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());+if(!exportOutput.empty()){std::atomic<bool> cancel{false},finished{false};std::thread cancelTimer;if(cancelAfterMs)cancelTimer=std::thread([&]{const auto start=GetTickCount64();while(!finished&&GetTickCount64()-start<cancelAfterMs)std::this_thread::sleep_for(std::chrono::milliseconds(5));if(!finished)cancel=true;});bool ok=veyra::engine::exportVideo(autoInput,exportOutput,initialOptions,exportHevc,cancel,[](double,const std::wstring& s){OutputDebugStringW(s.c_str());},exportFrames);finished=true;if(cancelTimer.joinable())cancelTimer.join();veyra::log::info("app",std::format("export result={}",ok));CoUninitialize();return ok?0:cancel?3:1;}+WNDCLASSEXW wc{sizeof(wc)};wc.hInstance=instance;wc.lpfnWndProc=proc;wc.lpszClassName=L"VeyraApp";wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);wc.hbrBackground=veyra::ui::bgBrush();RegisterClassExW(&wc);+auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — 本地实验版",ShellStyle,CW_USEDEFAULT,CW_USEDEFAULT,std::min(MulDiv(uiPreferences.width,GetDpiForSystem(),96),GetSystemMetrics(SM_CXSCREEN)),std::min(MulDiv(uiPreferences.height,GetDpiForSystem(),96),GetSystemMetrics(SM_CYSCREEN)-40),nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;if(uiPreferences.positioned&&smokeSeconds<=0){RECT target{uiPreferences.x,uiPreferences.y,uiPreferences.x+MulDiv(uiPreferences.width,GetDpiForSystem(),96),uiPreferences.y+MulDiv(uiPreferences.height,GetDpiForSystem(),96)};MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&target,MONITOR_DEFAULTTONEAREST),&mi);int width=std::min(target.right-target.left,mi.rcWork.right-mi.rcWork.left),height=std::min(target.bottom-target.top,mi.rcWork.bottom-mi.rcWork.top);SetWindowPos(hwnd,nullptr,std::clamp(target.left,mi.rcWork.left,mi.rcWork.right-width),std::clamp(target.top,mi.rcWork.top,mi.rcWork.bottom-height),width,height,SWP_NOZORDER|SWP_NOACTIVATE);}CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){if(GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&(msg.message==WM_KEYDOWN||msg.message==WM_KEYUP||msg.message==WM_SYSKEYDOWN)){+wchar_t focusedClass[32]{};GetClassNameW(GetFocus(),focusedClass,32);const bool editing=_wcsicmp(focusedClass,L"Edit")==0||_wcsicmp(focusedClass,L"ComboBox")==0;+if(!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(IsDialogMessageW(hwnd,&msg))continue;TranslateMessage(&msg);DispatchMessageW(&msg);}CoUninitialize();return int(msg.wParam);+}diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cppnew file mode 100644index 00000000..bb902a52--- /dev/null+++ b/apps/veyra/ui/CapturePanel.cpp@@ -0,0 +1,35 @@+#include "CapturePanel.h"+#include "Theme.h"+#include "veyra/source/CaptureCardSource.h"+#include <future>+#include <format>+namespace veyra::ui {+namespace {+HWND window=nullptr;HFONT font=nullptr;std::function<void(const std::wstring&)> start;+struct Query {int device=-1;std::vector<std::wstring> video,audio;std::vector<source::CaptureFormat> formats;};+std::future<Query> pending;bool busy=false;int queriedDevice=-1;ULONGLONG queryStarted=0;+std::vector<source::CaptureFormat> formats;+void query(int device){if(busy)return;busy=true;queriedDevice=device;queryStarted=GetTickCount64();SetDlgItemTextW(window,8,L"正在查询设备能力…当前播放继续");EnableWindow(GetDlgItem(window,4),FALSE);EnableWindow(GetDlgItem(window,5),FALSE);EnableWindow(GetDlgItem(window,1),FALSE);+ pending=std::async(std::launch::async,[device]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);Query result;result.device=device;try{if(device<0){result.video=source::CaptureCardSource::devices();result.audio=source::CaptureCardSource::devices(true);}else result.formats=source::CaptureCardSource::formats(unsigned(device));}catch(...){}CoUninitialize();return result;});+}+void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,GetDpiForWindow(window));const int ys[]={0,44,114,184,308,308,14,84,240,154};for(int id=1;id<=9;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,id<=3?180:id==8?56:id==4||id==5?36:24),TRUE);}}+LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){+case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar_t* cls,const wchar_t* label,int id,DWORD style){auto c=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,0,0,1,1,h,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,WPARAM(font),TRUE);themeControl(c);};+ for(int i=1;i<=3;++i)add(L"COMBOBOX",L"",i,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);+ add(L"BUTTON",L"连接并开始观看",4,BS_PUSHBUTTON|WS_TABSTOP);marked(GetDlgItem(h,4));add(L"BUTTON",L"刷新设备",5,BS_PUSHBUTTON|WS_TABSTOP);+ add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"HDMI 音频监听",9,0);+ EnableWindow(GetDlgItem(h,4),FALSE);arrange();SetTimer(h,1,100,nullptr);if(!busy)query(-1);return 0;}+case WM_TIMER:if(busy&&pending.wait_for(std::chrono::seconds(0))==std::future_status::ready){auto result=pending.get();busy=false;EnableWindow(GetDlgItem(h,5),TRUE);EnableWindow(GetDlgItem(h,1),TRUE);if(result.device<0){SendDlgItemMessageW(h,1,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,3,CB_RESETCONTENT,0,0);formats.clear();for(auto& name:result.video)SendDlgItemMessageW(h,1,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(L"不监听音频"));for(auto& name:result.audio)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);SetDlgItemTextW(h,8,result.video.empty()?L"未找到采集设备。连接后点击刷新。":L"请选择设备以查询实际格式;点击连接前不会中断当前视频。");}+ else{formats=std::move(result.formats);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);for(auto& format:formats)SendDlgItemMessageW(h,2,CB_ADDSTRING,0,LPARAM(format.label.c_str()));if(!formats.empty())SendDlgItemMessageW(h,2,CB_SETCURSEL,0,0);EnableWindow(GetDlgItem(h,4),!formats.empty());SetDlgItemTextW(h,8,formats.empty()?L"设备未提供支持的1080p/4K 30/60格式,或正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");}}+ else if(busy&&GetTickCount64()-queryStarted>5000)SetDlgItemTextW(h,8,L"设备查询耗时较长。可以关闭此面板,当前播放不受影响。");return 0;+case WM_COMMAND:if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)query(int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)));else if(LOWORD(wp)==5)query(-1);else if(LOWORD(wp)==4){int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)),format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0)),audio=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0))-1;if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()){start(std::format(L"capture:{}:{}:{}",device,formats[format].index,audio));DestroyWindow(h);}}return 0;+case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);+case WM_SIZE:arrange();return 0;+case WM_DPICHANGED:{auto r=reinterpret_cast<RECT*>(lp);SetWindowPos(h,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER|SWP_NOACTIVATE);auto old=font;font=makeFont(h);EnumChildWindows(h,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(old);arrange();return 0;}+case WM_KEYDOWN:if(wp==VK_ESCAPE){DestroyWindow(h);return 0;}break;+case WM_CLOSE:DestroyWindow(h);return 0;+case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;+}return DefWindowProcW(h,msg,wp,lp);}+}+void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback){start=std::move(callback);if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡 · 连接设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,560),dip(parent,410),parent,nullptr,wc.hInstance,nullptr);}+}diff --git a/apps/veyra/ui/CapturePanel.h b/apps/veyra/ui/CapturePanel.hnew file mode 100644index 00000000..c9334942--- /dev/null+++ b/apps/veyra/ui/CapturePanel.h@@ -0,0 +1,5 @@+#pragma once+#include <windows.h>+#include <string>+#include <functional>+namespace veyra::ui {void showCapturePanel(HWND,std::function<void(const std::wstring&)>);}diff --git a/apps/veyra/ui/SubtitleOverlay.cpp b/apps/veyra/ui/SubtitleOverlay.cppnew file mode 100644index 00000000..aff49245--- /dev/null+++ b/apps/veyra/ui/SubtitleOverlay.cpp@@ -0,0 +1,19 @@+#include "SubtitleOverlay.h"+#include "Theme.h"+#include "veyra/Log.h"+#include <format>+namespace veyra::ui {+namespace {+LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){if(msg==WM_NCHITTEST)return HTTRANSPARENT;if(msg==WM_PAINT){PAINTSTRUCT ps{};BeginPaint(h,&ps);EndPaint(h,&ps);return 0;}return DefWindowProcW(h,msg,wp,lp);}+}+HWND createSubtitleOverlay(HWND parent){WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraSubtitleOverlay";RegisterClassW(&wc);return CreateWindowExW(WS_EX_LAYERED|WS_EX_TRANSPARENT|WS_EX_NOACTIVATE,wc.lpszClassName,L"",WS_CHILD,0,0,1,1,parent,nullptr,wc.hInstance,nullptr);}+void updateSubtitleOverlay(HWND h,const std::wstring& text,int size){+ RECT r{};GetClientRect(h,&r);if(text.empty()||r.right<1||r.bottom<1){ShowWindow(h,SW_HIDE);SetWindowTextW(h,L"");return;}+ wchar_t old[4096]{};GetWindowTextW(h,old,4096);const auto extent=MAKELONG(r.right,r.bottom);if(text==old&&GetPropW(h,L"subtitle.extent")==HANDLE(INT_PTR(extent))&&GetPropW(h,L"subtitle.size")==HANDLE(INT_PTR(dip(h,size)))){ShowWindow(h,SW_SHOWNOACTIVATE);return;}+ BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=r.right;info.bmiHeader.biHeight=-r.bottom;info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;+ HDC screen=GetDC(nullptr),memory=CreateCompatibleDC(screen);void* bits=nullptr;auto bitmap=CreateDIBSection(screen,&info,DIB_RGB_COLORS,&bits,nullptr,0);if(!bitmap||!bits){if(bitmap)DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(nullptr,screen);return;}auto previous=SelectObject(memory,bitmap);memset(bits,0,size_t(r.right)*r.bottom*4);+ {using namespace Gdiplus;Bitmap canvas(r.right,r.bottom,r.right*4,PixelFormat32bppPARGB,static_cast<BYTE*>(bits));Graphics graphics(&canvas);graphics.SetSmoothingMode(SmoothingModeAntiAlias);graphics.SetTextRenderingHint(TextRenderingHintAntiAliasGridFit);FontFamily family(L"Microsoft YaHei UI");StringFormat format;format.SetAlignment(StringAlignmentCenter);format.SetLineAlignment(StringAlignmentCenter);GraphicsPath path;path.AddString(text.c_str(),int(text.size()),&family,FontStyleBold,float(dip(h,size)),RectF(4,0,float(r.right-8),float(r.bottom)),&format);Pen outline(Color(220,0,0,0),float(dip(h,3)));outline.SetLineJoin(LineJoinRound);graphics.DrawPath(&outline,&path);SolidBrush white(Color(255,246,246,246));graphics.FillPath(&white,&path);}+ SIZE dimensions{r.right,r.bottom};POINT origin{};BLENDFUNCTION blend{AC_SRC_OVER,0,255,AC_SRC_ALPHA};if(UpdateLayeredWindow(h,screen,nullptr,&dimensions,memory,&origin,0,&blend,ULW_ALPHA)){SetWindowTextW(h,text.c_str());SetPropW(h,L"subtitle.extent",HANDLE(INT_PTR(extent)));SetPropW(h,L"subtitle.size",HANDLE(INT_PTR(dip(h,size))));ShowWindow(h,SW_SHOWNOACTIVATE);if(!GetPropW(h,L"subtitle.logged")){log::info("subtitle",std::format("layered update succeeded extent={}x{}",r.right,r.bottom));SetPropW(h,L"subtitle.logged",HANDLE(1));}}else if(!GetPropW(h,L"subtitle.error")){log::error("subtitle",std::format("UpdateLayeredWindow failed error={}",GetLastError()));SetPropW(h,L"subtitle.error",HANDLE(1));}+ SelectObject(memory,previous);DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(nullptr,screen);+}+}diff --git a/apps/veyra/ui/SubtitleOverlay.h b/apps/veyra/ui/SubtitleOverlay.hnew file mode 100644index 00000000..19803fd8--- /dev/null+++ b/apps/veyra/ui/SubtitleOverlay.h@@ -0,0 +1,4 @@+#pragma once+#include <windows.h>+#include <string>+namespace veyra::ui {HWND createSubtitleOverlay(HWND);void updateSubtitleOverlay(HWND,const std::wstring&,int size);}diff --git a/apps/veyra/ui/Theme.h b/apps/veyra/ui/Theme.hnew file mode 100644index 00000000..984b364f--- /dev/null+++ b/apps/veyra/ui/Theme.h@@ -0,0 +1,74 @@+#pragma once+#include <windows.h>+#include <windowsx.h>+#include <commctrl.h>+#include <uxtheme.h>+#include <objbase.h>+#include <ocidl.h>+#include <gdiplus.h>+#include <algorithm>+#include <string>+#pragma comment(lib,"uxtheme.lib")+#pragma comment(lib,"dwmapi.lib")+#pragma comment(lib,"gdiplus.lib")+#include <dwmapi.h>+namespace veyra::ui {+inline constexpr COLORREF background=RGB(9,10,11),panel=RGB(27,28,30),raised=RGB(40,41,43),line=RGB(58,60,63),textColor=RGB(236,238,240),secondary=RGB(151,157,164),accent=RGB(230,122,49),cinema=RGB(32,48,62),cinemaPanel=RGB(23,34,43);+inline HBRUSH bgBrush(){static auto b=CreateSolidBrush(background);return b;}+inline HBRUSH panelBrush(){static auto b=CreateSolidBrush(panel);return b;}+inline HBRUSH raisedBrush(){static auto b=CreateSolidBrush(raised);return b;}+inline int dip(HWND h,int v){return MulDiv(v,GetDpiForWindow(h),96);}+inline HFONT makeFont(HWND h,int size=14,int weight=FW_NORMAL){return CreateFontW(-dip(h,size),0,0,0,weight,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");}+inline void titleTheme(HWND h){BOOL enabled=TRUE;DwmSetWindowAttribute(h,20,&enabled,sizeof(enabled));DWORD corner=2;DwmSetWindowAttribute(h,33,&corner,sizeof(corner));}+inline COLORREF surface(HWND h){auto prop=GetPropW(h,L"veyra.surface");return prop?COLORREF(uintptr_t(prop)-1):panel;}+inline void surface(HWND h,COLORREF c){SetPropW(h,L"veyra.surface",HANDLE(uintptr_t(c)+1));InvalidateRect(h,nullptr,FALSE);}+inline Gdiplus::Color color(COLORREF c,BYTE a=255){return Gdiplus::Color(a,GetRValue(c),GetGValue(c),GetBValue(c));}+inline void rounded(Gdiplus::GraphicsPath& p,Gdiplus::RectF r,float radius){float d=std::min({radius*2,r.Width,r.Height});p.AddArc(r.X,r.Y,d,d,180,90);p.AddArc(r.GetRight()-d,r.Y,d,d,270,90);p.AddArc(r.GetRight()-d,r.GetBottom()-d,d,d,0,90);p.AddArc(r.X,r.GetBottom()-d,d,d,90,90);p.CloseFigure();}+inline void roundRect(HDC dc,RECT r,COLORREF c,int radius){Gdiplus::Graphics g(dc);g.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);Gdiplus::GraphicsPath path;rounded(path,{float(r.left),float(r.top),float(r.right-r.left-1),float(r.bottom-r.top-1)},float(radius));Gdiplus::SolidBrush brush(color(c));g.FillPath(&brush,&path);}+inline void fillSurface(HDC dc,RECT r,HWND h){auto b=CreateSolidBrush(surface(h));FillRect(dc,&r,b);DeleteObject(b);}+inline LRESULT colors(UINT msg,WPARAM w,LPARAM l=0){HDC dc=reinterpret_cast<HDC>(w);HWND h=reinterpret_cast<HWND>(l);COLORREF bg=msg==WM_CTLCOLOREDIT?raised:surface(h);SetTextColor(dc,msg==WM_CTLCOLOREDIT?textColor:secondary);SetBkColor(dc,bg);SetBkMode(dc,TRANSPARENT);SetDCBrushColor(dc,bg);return reinterpret_cast<LRESULT>(GetStockObject(DC_BRUSH));}+enum class Icon { None,Play,Pause,Stop,Volume,Muted,Fullscreen,Video,Capture,Image,Subtitle,Minimize,Maximize,Close,Back };+inline void icon(HWND h,Icon icon,bool caption=false){SetPropW(h,L"veyra.icon",HANDLE(INT_PTR(icon)));if(caption)SetPropW(h,L"veyra.caption",HANDLE(1));else RemovePropW(h,L"veyra.caption");InvalidateRect(h,nullptr,FALSE);}+inline void drawIcon(HDC dc,Icon icon,float x,float y,float size,COLORREF c){using namespace Gdiplus;Graphics g(dc);g.SetSmoothingMode(SmoothingModeAntiAlias);Pen pen(color(c),std::max(1.4f,size/13));pen.SetStartCap(LineCapRound);pen.SetEndCap(LineCapRound);SolidBrush brush(color(c));const float a=size/2;auto line=[&](float x1,float y1,float x2,float y2){g.DrawLine(&pen,x+x1*a,y+y1*a,x+x2*a,y+y2*a);};+ switch(icon){case Icon::Play:{PointF p[]={{x-a*.45f,y-a*.8f},{x+a*.85f,y},{x-a*.45f,y+a*.8f}};g.FillPolygon(&brush,p,3);break;}case Icon::Pause:g.FillRectangle(&brush,x-a*.55f,y-a*.7f,a*.35f,a*1.4f);g.FillRectangle(&brush,x+a*.2f,y-a*.7f,a*.35f,a*1.4f);break;+ case Icon::Stop:g.FillRectangle(&brush,x-a*.55f,y-a*.55f,a*1.1f,a*1.1f);break;+ case Icon::Volume:case Icon::Muted:{PointF p[]={{x-a*.9f,y-a*.28f},{x-a*.5f,y-a*.28f},{x,y-a*.7f},{x,y+a*.7f},{x-a*.5f,y+a*.28f},{x-a*.9f,y+a*.28f}};g.DrawPolygon(&pen,p,6);if(icon==Icon::Muted){line(.35f,-.4f,.85f,.4f);line(.35f,.4f,.85f,-.4f);}else{g.DrawArc(&pen,x-a*.4f,y-a*.6f,a*1.2f,a*1.2f,-60,120);g.DrawArc(&pen,x-a*.7f,y-a*.95f,a*1.9f,a*1.9f,-60,120);}break;}+ case Icon::Fullscreen:for(int sx:{-1,1})for(int sy:{-1,1}){line(sx*.85f,sy*.35f,sx*.85f,sy*.85f);line(sx*.35f,sy*.85f,sx*.85f,sy*.85f);}break;+ case Icon::Video:g.DrawRectangle(&pen,x-a*.85f,y-a*.65f,a*1.7f,a*1.3f);{PointF p[]={{x-a*.2f,y-a*.35f},{x+a*.4f,y},{x-a*.2f,y+a*.35f}};g.FillPolygon(&brush,p,3);}break;+ case Icon::Capture:g.DrawRectangle(&pen,x-a*.85f,y-a*.6f,a*1.7f,a*1.2f);line(-.4f,1,.4f,1);line(0,.6f,0,1);g.FillEllipse(&brush,x-a*.16f,y-a*.16f,a*.32f,a*.32f);break;+ case Icon::Image:g.DrawRectangle(&pen,x-a*.85f,y-a*.7f,a*1.7f,a*1.4f);line(-.6f,.4f,-.1f,-.2f);line(-.1f,-.2f,.3f,.2f);line(.3f,.2f,.65f,-.1f);g.FillEllipse(&brush,x+a*.25f,y-a*.5f,a*.24f,a*.24f);break;+ case Icon::Subtitle:g.DrawRectangle(&pen,x-a*.9f,y-a*.6f,a*1.8f,a*1.2f);line(-.6f,.2f,-.1f,.2f);line(.15f,.2f,.6f,.2f);break;+ case Icon::Minimize:line(-.6f,0,.6f,0);break;case Icon::Maximize:g.DrawRectangle(&pen,x-a*.55f,y-a*.55f,a*1.1f,a*1.1f);break;+ case Icon::Close:line(-.5f,-.5f,.5f,.5f);line(-.5f,.5f,.5f,-.5f);break;case Icon::Back:line(.2f,-.6f,-.5f,0);line(-.5f,0,.2f,.6f);break;default:break;}+}+inline LRESULT CALLBACK buttonPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_PTR){+ if(m==WM_ERASEBKGND)return 1;+ if(m==WM_MOUSEMOVE){if(!GetPropW(h,L"veyra.hover")){SetPropW(h,L"veyra.hover",HANDLE(1));TRACKMOUSEEVENT t{sizeof(t),TME_LEAVE,h,0};TrackMouseEvent(&t);InvalidateRect(h,nullptr,FALSE);}}+ if(m==WM_MOUSELEAVE){RemovePropW(h,L"veyra.hover");InvalidateRect(h,nullptr,FALSE);}+ if(m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(h,&ps);RECT r{};GetClientRect(h,&r);fillSurface(dc,r,h);+ const bool marked=GetPropW(h,L"veyra.accent")!=nullptr,selected=GetPropW(h,L"veyra.selected")!=nullptr,hover=GetPropW(h,L"veyra.hover")!=nullptr,down=SendMessageW(h,BM_GETSTATE,0,0)&BST_PUSHED,check=SendMessageW(h,BM_GETCHECK,0,0)==BST_CHECKED,ghost=GetPropW(h,L"veyra.ghost")!=nullptr;+ const auto ico=static_cast<Icon>(INT_PTR(GetPropW(h,L"veyra.icon")));bool caption=GetPropW(h,L"veyra.caption")!=nullptr;+ COLORREF fill=marked?accent:(down||selected?line:hover?raised:surface(h));if(!ghost||hover||selected||marked)roundRect(dc,r,fill,ico==Icon::Play||ico==Icon::Pause?std::min(r.right,r.bottom)/2:dip(h,8));+ wchar_t value[512]{};GetWindowTextW(h,value,512);auto f=reinterpret_cast<HFONT>(SendMessageW(h,WM_GETFONT,0,0));auto old=SelectObject(dc,f);SetBkMode(dc,TRANSPARENT);COLORREF ink=!IsWindowEnabled(h)?RGB(90,96,103):marked?RGB(24,31,36):selected?textColor:hover?textColor:secondary;SetTextColor(dc,ink);+ if(ico!=Icon::None){drawIcon(dc,ico,caption?float(dip(h,18)):r.right/2.f,r.bottom/2.f,float(dip(h,ico==Icon::Play||ico==Icon::Pause?22:17)),ink);if(caption){r.left=dip(h,34);DrawTextW(dc,value,-1,&r,DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);}}+ else if((GetWindowLongPtrW(h,GWL_STYLE)&BS_TYPEMASK)==BS_AUTOCHECKBOX){RECT toggle{r.right-dip(h,40),r.bottom/2-dip(h,8),r.right-dip(h,10),r.bottom/2+dip(h,8)};roundRect(dc,toggle,check?accent:line,dip(h,8));RECT knob{toggle.left+dip(h,check?16:3),toggle.top+dip(h,3),toggle.left+dip(h,check?26:13),toggle.top+dip(h,13)};roundRect(dc,knob,check?panel:secondary,dip(h,5));r.left=dip(h,12);r.right-=dip(h,46);DrawTextW(dc,value,-1,&r,DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);}else DrawTextW(dc,value,-1,&r,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);+ if(GetFocus()==h){RECT outline{};GetClientRect(h,&outline);InflateRect(&outline,-3,-3);DrawFocusRect(dc,&outline);}SelectObject(dc,old);EndPaint(h,&ps);return 0;}+ if(m==WM_ENABLE||m==WM_SETFOCUS||m==WM_KILLFOCUS||m==BM_SETCHECK||m==WM_SETTEXT||m==BM_SETSTATE){auto result=DefSubclassProc(h,m,w,l);InvalidateRect(h,nullptr,FALSE);return result;}+ return DefSubclassProc(h,m,w,l);+}+inline LRESULT CALLBACK comboPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_PTR){+ if(m==WM_ERASEBKGND)return 1;if(m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(h,&ps);RECT r{};GetClientRect(h,&r);fillSurface(dc,r,h);roundRect(dc,r,raised,dip(h,7));int index=int(SendMessageW(h,CB_GETCURSEL,0,0));wchar_t value[512]{};if(index>=0&&SendMessageW(h,CB_GETLBTEXTLEN,index,0)<512)SendMessageW(h,CB_GETLBTEXT,index,LPARAM(value));auto old=SelectObject(dc,HFONT(SendMessageW(h,WM_GETFONT,0,0)));SetBkMode(dc,TRANSPARENT);SetTextColor(dc,IsWindowEnabled(h)?secondary:RGB(85,88,92));RECT label=r;label.left+=dip(h,12);label.right-=dip(h,26);DrawTextW(dc,value,-1,&label,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);auto pen=CreatePen(PS_SOLID,dip(h,1),secondary);auto op=SelectObject(dc,pen);int x=r.right-dip(h,15),y=r.bottom/2;MoveToEx(dc,x-dip(h,3),y-dip(h,1),nullptr);LineTo(dc,x,y+dip(h,2));LineTo(dc,x+dip(h,3),y-dip(h,1));SelectObject(dc,op);DeleteObject(pen);SelectObject(dc,old);EndPaint(h,&ps);return 0;}+ auto result=DefSubclassProc(h,m,w,l);if(m==CB_SETCURSEL||m==WM_SETFOCUS||m==WM_KILLFOCUS||m==WM_ENABLE)InvalidateRect(h,nullptr,FALSE);return result;+}+inline LRESULT CALLBACK trackPaint(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR,DWORD_PTR){+ if(m==WM_ERASEBKGND)return 1;+ if(m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(h,&ps);RECT r{};GetClientRect(h,&r);fillSurface(dc,r,h);int minimum=int(SendMessageW(h,TBM_GETRANGEMIN,0,0)),maximum=int(SendMessageW(h,TBM_GETRANGEMAX,0,0));float progress=float(SendMessageW(h,TBM_GETPOS,0,0)-minimum)/std::max(1,maximum-minimum);int margin=dip(h,6),y=r.bottom/2,x=margin+int((r.right-margin*2)*progress);RECT rail{margin,y-dip(h,1),r.right-margin,y+dip(h,2)},fill=rail;fill.right=x;roundRect(dc,rail,line,dip(h,2));roundRect(dc,fill,IsWindowEnabled(h)?accent:secondary,dip(h,2));RECT dot{x-dip(h,5),y-dip(h,5),x+dip(h,5),y+dip(h,5)};roundRect(dc,dot,IsWindowEnabled(h)?accent:line,dip(h,5));InflateRect(&dot,-dip(h,2),-dip(h,2));roundRect(dc,dot,surface(h),dip(h,3));EndPaint(h,&ps);return 0;}+ if(m==WM_LBUTTONDOWN||m==WM_MOUSEMOVE&&GetCapture()==h||m==WM_LBUTTONUP&&GetCapture()==h){if(!IsWindowEnabled(h))return 0;if(m==WM_LBUTTONDOWN)SetCapture(h);RECT r{};GetClientRect(h,&r);int minimum=int(SendMessageW(h,TBM_GETRANGEMIN,0,0)),maximum=int(SendMessageW(h,TBM_GETRANGEMAX,0,0));float fraction=std::clamp(float(GET_X_LPARAM(l)-dip(h,6))/std::max(1L,r.right-dip(h,12)),0.0f,1.0f);int value=minimum+int(fraction*(maximum-minimum));SendMessageW(h,TBM_SETPOS,TRUE,value);SendMessageW(GetParent(h),WM_HSCROLL,MAKEWPARAM(m==WM_LBUTTONUP?TB_THUMBPOSITION:TB_THUMBTRACK,value),LPARAM(h));if(m==WM_LBUTTONUP)ReleaseCapture();return 0;}+ auto result=DefSubclassProc(h,m,w,l);if(m==TBM_SETPOS||m==WM_ENABLE||m==WM_SIZE)InvalidateRect(h,nullptr,FALSE);return result;+}+inline void themeControl(HWND h){wchar_t cls[32]{};GetClassNameW(h,cls,32);SetWindowTheme(h,L"DarkMode_Explorer",nullptr);if(_wcsicmp(cls,L"BUTTON")==0)SetWindowSubclass(h,buttonPaint,900,0);else if(_wcsicmp(cls,L"COMBOBOX")==0){SetWindowLongPtrW(h,GWL_EXSTYLE,GetWindowLongPtrW(h,GWL_EXSTYLE)&~WS_EX_CLIENTEDGE);SetWindowSubclass(h,comboPaint,901,0);SendMessageW(h,CB_SETITEMHEIGHT,WPARAM(-1),dip(h,30));}else if(_wcsicmp(cls,TRACKBAR_CLASSW)==0)SetWindowSubclass(h,trackPaint,902,0);}+inline void marked(HWND h,bool on=true){if(on)SetPropW(h,L"veyra.accent",HANDLE(1));else RemovePropW(h,L"veyra.accent");InvalidateRect(h,nullptr,FALSE);}+inline void ghost(HWND h,bool on=true){if(on)SetPropW(h,L"veyra.ghost",HANDLE(1));else RemovePropW(h,L"veyra.ghost");InvalidateRect(h,nullptr,FALSE);}+inline void selected(HWND h,bool on){if(on)SetPropW(h,L"veyra.selected",HANDLE(1));else RemovePropW(h,L"veyra.selected");InvalidateRect(h,nullptr,FALSE);}+inline void setText(HWND h,const std::wstring& value){wchar_t old[4096]{};GetWindowTextW(h,old,4096);if(value!=old)SetWindowTextW(h,value.c_str());}+}diff --git a/apps/veyra/ui/UiPreferenceStore.h b/apps/veyra/ui/UiPreferenceStore.hnew file mode 100644index 00000000..b66430d5--- /dev/null+++ b/apps/veyra/ui/UiPreferenceStore.h@@ -0,0 +1,30 @@+#pragma once+#include "UiSessionState.h"+#include "veyra/engine/PresetStore.h"+#include <filesystem>+#include <fstream>+#include <sstream>+namespace veyra::ui {+struct UiPreferences {+ float volume=1;bool muted=false,subtitles=true;+ int inspectorWidth=320;+ int width=1280,height=800,x=0,y=0,inspector=0,subtitleSize=22;bool positioned=false;+};+class UiPreferenceStore {+ std::filesystem::path folder_;+ bool corrupt_=false;+public:+ explicit UiPreferenceStore(std::filesystem::path folder):folder_(std::move(folder)){}+ UiPreferences load(){UiPreferences result;auto path=folder_/"ui-preferences.v1";if(!std::filesystem::exists(path))return result;+ if(std::filesystem::file_size(path)>2048){corrupt_=true;return result;}std::ifstream file(path);std::string magic;int version=0,mute,sub,pos;UiPreferences read;+ if(!(file>>magic>>version>>read.volume>>mute>>sub>>read.width>>read.height>>read.x>>read.y>>pos>>read.inspector>>read.subtitleSize)||magic!="VEYRA_UI"||(version!=1&&version!=2)||!std::isfinite(read.volume)||read.volume<0||read.volume>1||mute<0||mute>1||sub<0||sub>1||pos<0||pos>1||read.width<720||read.width>10000||read.height<540||read.height>10000||abs(int64_t(read.x))>100000||abs(int64_t(read.y))>100000||read.inspector<0||read.inspector>3||read.subtitleSize<18||read.subtitleSize>36){corrupt_=true;return result;}+ if(version==2&&(!(file>>read.inspectorWidth)||read.inspectorWidth<296||read.inspectorWidth>420)){corrupt_=true;return result;}file>>std::ws;if(!file.eof()){corrupt_=true;return result;}read.muted=mute;read.subtitles=sub;read.positioned=pos;return read;+ }+ engine::EnhancementSettings startup(engine::EnhancementSettings fallback){engine::PresetStore last(folder_/"last-applied.v1");if(!last.load()||last.entries().empty())return fallback;return last.entries().front().settings;}+ bool save(const UiPreferences& p,const engine::EnhancementSettings* applied){+ bool ok=true;std::filesystem::create_directories(folder_);if(applied){engine::PresetStore last(folder_/"last-applied.v1");ok=last.load()&&last.put(L"Last applied",*applied,true);}+ if(corrupt_)return false;std::ostringstream out;out<<"VEYRA_UI 2\n"<<p.volume<<' '<<p.muted<<' '<<p.subtitles<<' '<<p.width<<' '<<p.height<<' '<<p.x<<' '<<p.y<<' '<<p.positioned<<' '<<p.inspector<<' '<<p.subtitleSize<<' '<<p.inspectorWidth<<'\n';+ auto target=folder_/"ui-preferences.v1",tmp=folder_/(L"ui-preferences.tmp-"+std::to_wstring(GetCurrentProcessId()));auto data=out.str();HANDLE file=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;DWORD written=0;bool saved=WriteFile(file,data.data(),DWORD(data.size()),&written,nullptr)&&written==data.size()&&FlushFileBuffers(file);CloseHandle(file);if(saved)saved=MoveFileExW(tmp.c_str(),target.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE;return ok&&saved;+ }+};+}diff --git a/apps/veyra/ui/UiSessionState.h b/apps/veyra/ui/UiSessionState.hnew file mode 100644index 00000000..70ba56c2--- /dev/null+++ b/apps/veyra/ui/UiSessionState.h@@ -0,0 +1,18 @@+#pragma once+#include "veyra/engine/EnhancementSettings.h"+namespace veyra::ui {+enum class Mode { Daily, Professional };+struct UiSessionState {+ Mode mode=Mode::Daily;+ bool enhanced=true,subtitles=true,diagnostics=false,drawer=false;+ int inspector=0,preferredComparison=0;+ engine::EnhancementSettings configured;+ // An explicit user toggle creates a settings transaction. Mode changes do+ // not call this function and cannot change enhancement configuration.+ engine::EnhancementSettings effective()const{auto result=configured;if(!enhanced){result.nr=false;result.sr=false;result.multiplier=1;}return result;}+};+struct WorkspaceGeometry {+ int width,height,header=52,bottom=96,rail=0,inspector=0,diagnostics=0;+ WorkspaceGeometry(int w,int h,bool pro,bool details,bool drawer):width(w),height(h){if(pro){rail=w<1180?56:72;inspector=w>=960? (w<1180?296:328):(drawer?296:0);diagnostics=details?180:36;}}+};+}diff --git a/apps/veyra/ui/WorkspaceChrome.h b/apps/veyra/ui/WorkspaceChrome.hnew file mode 100644index 00000000..0c7c87e6--- /dev/null+++ b/apps/veyra/ui/WorkspaceChrome.h@@ -0,0 +1,53 @@+#pragma once+#include "Theme.h"+#include "veyra/engine/EngineController.h"+#include <format>+namespace veyra::ui {+struct ChromeLayout {+ int w,h,left,top,viewWidth,viewHeight,right,panelWidth,bottom;+ bool pro,drawer;+ ChromeLayout(int width,int height,bool professional,bool showDrawer,int inspectorWidth=320):w(width),h(height),pro(professional),drawer(showDrawer){+ panelWidth=pro?(w>=1180?std::clamp(inspectorWidth,296,420):w>=960?296:showDrawer?296:0):0;+ left=pro?(w>=960?84:68):(w>=1000?64:24);top=pro?68:(h>=720?104:76);+ right=w-panelWidth-20;viewWidth=pro?((w>=960||showDrawer)?right-left-14:w-left-20):w-left*2;+ viewHeight=pro?std::max(160,h-306):std::max(180,std::min(int(viewWidth*9.0/16),h-top-138));+ bottom=top+viewHeight+14;+ }+};+inline void chromeText(HDC dc,HWND window,std::wstring value,int x,int y,int w,int h,int size,COLORREF c,int weight=FW_NORMAL,UINT flags=DT_LEFT|DT_SINGLELINE|DT_VCENTER){auto font=makeFont(window,size,weight);auto old=SelectObject(dc,font);SetTextColor(dc,c);SetBkMode(dc,TRANSPARENT);RECT r{dip(window,x),dip(window,y),dip(window,x+w),dip(window,y+h)};DrawTextW(dc,value.c_str(),-1,&r,flags|DT_END_ELLIPSIS);SelectObject(dc,old);DeleteObject(font);}+inline void paintChrome(HWND window,HDC dc,const ChromeLayout& l,const engine::PlayerSnapshot& s,bool full){+ RECT client{};GetClientRect(window,&client);if(full){FillRect(dc,&client,bgBrush());return;}+ auto rect=[&](int x,int y,int w,int h){return RECT{dip(window,x),dip(window,y),dip(window,x+w),dip(window,y+h)};};+ using namespace Gdiplus;Graphics g(dc);g.SetSmoothingMode(SmoothingModeAntiAlias);+ if(!l.pro){LinearGradientBrush bg(Point(0,0),Point(0,client.bottom),color(cinema),color(RGB(20,31,41)));g.FillRectangle(&bg,0,0,client.right,client.bottom);+ // Restrained ambient shadow below the single cinema surface.+ for(int i=18;i>0;--i){auto r=rect(l.left-i/2,l.top+i/2,l.viewWidth+i,l.viewHeight+88+i/2);GraphicsPath p;rounded(p,{float(r.left),float(r.top),float(r.right-r.left),float(r.bottom-r.top)},float(dip(window,5)));SolidBrush shadow(Color(BYTE(3),0,0,0));g.FillPath(&shadow,&p);}+ roundRect(dc,rect(l.left,l.top,l.viewWidth,l.viewHeight+88),cinemaPanel,dip(window,5));+ chromeText(dc,window,L"V E Y R A",l.left,l.h-46,160,24,12,RGB(118,133,144),FW_MEDIUM);+ chromeText(dc,window,L"本地增强播放器",l.w-238,l.h-46,174,24,12,RGB(118,133,144));+ }else{+ FillRect(dc,&client,bgBrush());roundRect(dc,rect(4,4,64,l.h-8),RGB(16,17,18),dip(window,22));+ roundRect(dc,rect(l.left,l.top,l.viewWidth,l.viewHeight),panel,dip(window,20));+ roundRect(dc,rect(l.left,l.bottom,l.viewWidth,l.h-l.bottom-20),panel,dip(window,20));+ if(l.panelWidth){roundRect(dc,rect(l.right,l.top,l.panelWidth,l.viewHeight),panel,dip(window,20));roundRect(dc,rect(l.right,l.bottom,l.panelWidth,l.h-l.bottom-20),panel,dip(window,20));}+ chromeText(dc,window,L"专业工作台",l.left,18,180,24,13,secondary);+ const auto& resolution=s.metrics.resolution;+ auto extent=[](uint32_t w,uint32_t h){return w&&h?std::format(L"{} × {}",w,h):std::wstring(L"—");};+ const int column=std::min(154,(l.viewWidth-40)/3),size=l.viewWidth<600?13:17;+ const std::wstring dimensions[]={extent(resolution.source.width,resolution.source.height),extent(resolution.base.width,resolution.base.height),!s.applied.nr?L"关闭":extent(resolution.nr.width,resolution.nr.height)};+ const wchar_t* headings[]={L"SOURCE",L"OUTPUT",L"NR PROCESS"};+ for(int i=0;i<3;++i){chromeText(dc,window,headings[i],l.left+20+i*column,l.bottom+94,column-4,20,10,secondary);chromeText(dc,window,dimensions[i],l.left+20+i*column,l.bottom+118,column-4,30,size,textColor);}+ if(l.panelWidth){+ chromeText(dc,window,s.transport==engine::TransportState::Playing?L"实时处理状态":L"最近处理样本",l.right+22,l.bottom+16,l.panelWidth-44,24,13,textColor,FW_MEDIUM);+ chromeText(dc,window,L"NR单阶段 · 16.7 ms 参考刻度",l.right+22,l.bottom+42,l.panelWidth-44,16,10,secondary);+ const auto sample=s.metrics.gpu[size_t(diagnostics::GpuStage::Nr)];+ float cx=float(dip(window,l.right+86)),cy=float(dip(window,l.bottom+105)),radius=float(dip(window,45));Pen track(color(line),float(dip(window,3)));Pen arc(color(accent),float(dip(window,3)));g.DrawArc(&track,cx-radius,cy-radius,radius*2,radius*2,140,260);if(sample.milliseconds)g.DrawArc(&arc,cx-radius,cy-radius,radius*2,radius*2,140,float(std::clamp(*sample.milliseconds/16.667,0.0,1.0)*260));+ chromeText(dc,window,sample.milliseconds?std::format(L"{:.1f}",*sample.milliseconds):L"—",l.right+41,l.bottom+78,90,38,27,textColor,FW_NORMAL,DT_CENTER|DT_SINGLELINE|DT_VCENTER);+ chromeText(dc,window,L"NR · ms",l.right+43,l.bottom+112,86,20,10,secondary,FW_NORMAL,DT_CENTER|DT_SINGLELINE|DT_VCENTER);+ chromeText(dc,window,L"源帧处理",l.right+158,l.bottom+65,130,20,11,secondary);+ chromeText(dc,window,s.frames?std::format(L"{:.1f} fps",s.fps):L"未测",l.right+158,l.bottom+88,130,30,19,textColor);+ chromeText(dc,window,s.applied.nrPolicy==pipeline::NrSizePolicy::Realtime?L"实时档 · 非原生4K NR":L"原生 NR",l.right+22,l.bottom+170,l.panelWidth-44,22,11,secondary);+ }+ }+}+}diff --git a/apps/veyra/veyra.manifest b/apps/veyra/veyra.manifestnew file mode 100644index 00000000..0f977fc8--- /dev/null+++ b/apps/veyra/veyra.manifest@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />+ </application>+ </compatibility>+</assembly>diff --git a/docs/DELIVERY_STATUS.md b/docs/DELIVERY_STATUS.mdindex a0917252..d7446b37 100644--- a/docs/DELIVERY_STATUS.md+++ b/docs/DELIVERY_STATUS.md@@ -1,3 +1,17 @@+# 2026-09-08 双模式UI本机软件交付++已实现批准的UI0–UI9:默认日常影院界面、专业四区工作台、共享视频宿主与无重开切换、完整参数/预设、真实音量和透明字幕、后台冻结设置导出、诊断/全屏/小窗口。最初普通Win32排布在用户反馈后重新实现。++基线本地存档`ddc515d`;当前EXE SHA256 `2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6`。UI全套15子检查109.583秒PASS;Repair v2 18项PASS,子进程计时合计70.712秒;4K补充23检查14.178秒PASS。真实4K输入/底图/光流/FG/输出、1080内部NR短测59.55源fps、落后P95 1.77ms。每次调用最多300秒,累计历史保留。++受保护delivery脚本此次34.736秒后在旧23帧断言FAIL;基线已有CFR tail hold,当前12源帧2X正确输出24帧/120fps/0.2秒。保护文件未改,补测不替代Phase gate。全项目仍needs_review;当前UI软件交付不等于实卡、多屏物理DPI、长稳、完整组合性能或公开发行通过。++详情、文件、命令、错误码、截图和复核范围:[双模式交付报告](UI_DUAL_MODE_DELIVERY_2026-09-08.md)。操作:[使用指南](USER_GUIDE.md)。下一条用户验收:从Veyra.cmd启动,在真实采集卡上检查新界面切换、声音和体感延迟。本轮未开启采集流、未更改外部应用或运行时、未上传发布。++---++以下保留历史版本记录,旧的“当前EXE/尚未施工/已通过”不代表本次状态:+# 当前本机状态 — 2026-09-08 Repair v2## 双模式UI改版计划已确认,尚未施工diff --git a/docs/REVIEW_UI_DUAL_MODE_2026-09-08.md b/docs/REVIEW_UI_DUAL_MODE_2026-09-08.mdnew file mode 100644index 00000000..96ebcb49--- /dev/null+++ b/docs/REVIEW_UI_DUAL_MODE_2026-09-08.md@@ -0,0 +1,30 @@+# 双模式UI独立只读复核++日期:2026-09-08。Reviewer:独立新上下文子Agent `review_dual_mode`。主Agent归档其实际返回结论;Reviewer未写文件、启动测试/GPU或采集,不把只读审查称为独立重跑。++## 最终返回结论++> UI0–UI9 限定的软件实现与短测范围通过复核,未发现尚未关闭的代码阻断。++- UI all:15项成功,109.583秒;40次模式切换P95 4.2ms、最大13.591ms。446次提交保持epoch1,最大间隔20.3844ms,无Feature创建、reset或source open。+- Repair v2:18个case零失败,子进程耗时合计70.7119369秒。+- 当前4K补充:23项通过,14.178107秒。实际4线程、完整测试摘要、首遍读取与EOS后seek0重读的有效YUV像素Adler32和PTS、原生图尺寸、分项导出计数及AAC均有明确断言。+- 当前日常/专业真实截图已查看,字幕可见,专业四区完整。最终产品测试EXE SHA256:`2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6`。++## 审查后已关闭的问题++总增强失败事务归属与UI回滚、隐藏页去抖定时器、空闲停止状态、后台导出终态/关闭清理、非零起始PTS进度、窄窗口参数重叠、模式切换超过16ms、透明字幕不可见、实际worker冻结设置断言及4K补测仅靠退出码的防漏缺口均经过修正和对应证据检查。++后续核心性能改动也只读审查了:文件解码receive/send及有上限的frame-threading、seek flush、EOF drain/销毁,mapped upload写入前对应fence、stride/颜色参数、原始CPU luma取样和有超时/停止条件的FG readiness轮询。未发现新增代码阻断。++## 不能扩大的结论++受保护`scripts/gates/delivery.ps1`相对`ddc515d`未修改,仍因旧23帧断言FAIL。基线已存在CFR尾部保持,12source+11generated+1hold=24帧/120fps/0.2秒符合当前合同。补充回归不替代保护门禁。本结论不宣布全局Phase、用户视觉/实卡、多屏物理DPI穿越、扫描/光子延迟、长期稳定或公开发行通过。++证据:++- `logs/ui-dual-mode/de337338b71e43618c4beaa488d54afb/result.json`+- `logs/repair-v2/joint-91436d0b0f4145c2b6fe6794ff146c68/result.json`+- `logs/ui-dual-mode/4k-f764b1a5ef894f46b050cbbf728103ec/result.json`+- `logs/delivery/39c5c9d100234c92beaf7eb5d5cab1c0/result.json`+- `logs/ui-dual-mode/visual-candidate/daily-current.jpg`、`professional-current.jpg`diff --git a/docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md b/docs/UI_DUAL_MODE_DELIVERY_2026-09-08.mdnew file mode 100644index 00000000..f16386a0--- /dev/null+++ b/docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md@@ -0,0 +1,133 @@+# Veyra 双模式原生界面交付记录++日期:2026-09-08。用户授权先建立本地Git存档、完成已批准UI0–UI9方案,并在完成后关机。基线存档:`ddc515d`。本次不使用用户拒绝的设计技能,不修改专有运行时,不占用采集视频流,不发布或上传项目。++状态:UI0–UI9限定本机软件施工与短测完成,用户视觉/实卡验收待进行。受保护旧delivery gate仍因23帧断言失败,未改文件或冒充PASS。旧Phase 0–7字段保留历史含义,不用UI改版宣布公开首发完成。++## 1. 实际界面与交互++- 默认日常模式:深蓝渐变背景、单一影院画面、橙色细进度条、居中圆形播放键和矢量音量/字幕/全屏图标。提供视频、采集配置、最近文件、总增强和预设选择。+- 专业模式:黑色外壳、窄图标栏、圆角视频与参数卡片、底部播放/尺寸信息卡、独立NR阶段耗时仪表。增强、补帧、预设、导出集中在右侧。+- 模式切换保持同一个video HWND和source session,不重新打开媒体、不加载另一套增强预设。专业比较状态单独记住;返回日常恢复正常增强显示。+- 800×600窗口可展开参数栏,展开时预览收窄,参数与画面各有独立区域。右栏可滚动,期望/已应用版本和错误区固定。窗口控件使用原生编辑/选择语义和统一深色绘制。+- 全屏支持F11、Alt+Enter、视频双击、按钮及Esc恢复。编辑框内V、空格保持输入;专业V比较不会占用输入框。+- 总开关真实旁路NR/SR/补帧,恢复时使用配置快照;失败按来源会话与被拒绝的确切事务恢复UI,不把任意新版本号误判为失败。+- 独立字幕层在FG后的桌面合成阶段显示,中文和英文两行透明字幕已在实际窗口验证。应用内音量通过真实PCM增益渐变生效。++本次复现参考图的配色、空间关系、卡片形态、控制条与图标语言。它是实际播放器界面;未把参考图贴进程序冒充实现,也不宣称无人机仪表、影视素材和每个像素均与参考图相同。++## 2. 已补齐的工程功能++| 区域 | 实现与边界 |+|---|---|+| UI组织 | `main.cpp`只保留入口,壳、布局、主题、采集配置、字幕、偏好各自独立;继续使用Win32/D3D12共享引擎 |+| 参数 | 7项模型与5项变化量参数、严格值域/整数验证、120ms滑杆去抖、整套应用及回滚;隐藏/换页取消未发出的提交 |+| 偏好 | UI偏好独立版本化文件;确认成功的增强快照另存;坏文件保留;正常重启始终日常模式 |+| 采集配置 | 设备与格式查询在独立COM工作任务中进行,连接需要明确选择;本次只看配置/枚举,未开始采集 |+| 音量 | 文件WASAPI浮点PCM约5ms增益渐变;采集使用自身DirectShow图音量能力,不修改系统总音量 |+| 后台导出 | 同EXE无界面worker、匿名映射冻结完整设置、受限继承句柄列表、Job Object随父进程关闭清理;继续调用共享VideoExportJob |+| 导出控制 | 暂停/继续、取消、观看优先、封装/验证状态;源帧/生成/Hold/编码实数计数和作业ID/冻结版本;取消保留partial |+| 进度 | 使用源PTS减视频起始PTS;编码阶段最多99%,IPC最多99.9%,确认子进程成功退出才给100% |+| 诊断 | 在专业区域显示实际GPU/CPU/帧身份和失败信息;先脱敏预览再复制,无自动上传 |++观看优先只在完整导出源帧之间让出时间,不丢源帧、不暗中降低导出质量。两个作业仍共享物理GPU,不保证任意4K/4X组合同时实时。NR仪表显示单阶段GPU测量,不是整图耗时或显示延迟。++## 3. 文件与构建++主要改动:++- `apps/veyra/main.cpp`、`apps/veyra/ui/*`、`SettingsWindow.*`、`TelemetryWindow.*`、`veyra.manifest`。+- `include/veyra/engine/*`和`src/engine/*`中的EngineController、ExportJobManager、VideoExportJob。+- `FFmpegVideoDecoder.*`、`MediaFileSource.cpp`、`EnhanceGraph.cpp`:有上限的文件解码并行和上传拷贝优化。+- `include/veyra/sink/AudioGain.h`、`WasapiAudioSink.*`、`CaptureCardSource.*`。+- `CMakeLists.txt`、`tests/unit/UiContractTests.cpp`、`tests/integration/MediaFileSourceTests.cpp`、`scripts/acceptance/ui-dual-mode.ps1`及`ui-4k-regression.ps1`。+- 本报告、使用指南、交付状态、WORKLOG和loop恢复记录。++构建命令:++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root . -Preset x64-release+```++最终应用构建日志:`logs/ui-dual-mode/build-upload-direct.log`,exit0;随后仅增加解码集成检查,`build-threaded-test.log`构建exit0、约2.48秒,未改变应用二进制。EXE SHA256:`2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6`。入口仍为项目根目录`Veyra.cmd`,不是安装包,不应移动项目路径。++透明子窗口需要现代Windows兼容性声明;已补入manifest,并对PARGB画布直接绘制,记录UpdateLayeredWindow结果。技术依据:[Microsoft Window Features](https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features)、[应用兼容性manifest](https://learn.microsoft.com/en-us/windows/win32/w8cookbook/application--executable--manifest)。++## 4. 实测与证据++每次测试调用最多300秒,构建单独计时;历史累计保留而不作为后续调用剩余额度。所有视频来自项目合成素材或由它生成的测试音视频;没有使用用户采集内容。++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/ui-dual-mode.ps1 -Root . -MaxRuntimeSeconds 300 -Case all+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/repair-v2.ps1 -Root . -MaxRuntimeSeconds 300 -Case all+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root .+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/acceptance/ui-4k-regression.ps1 -Root . -MaxRuntimeSeconds 300+```++| 调用 | 真实结果 |+|---|---|+| UI全套 `de337338b71e43618c4beaa488d54afb` | PASS,15子检查exit0,109.583秒;EXE为上列2DE332… |+| Repair v2 `joint-91436d0b0f4145c2b6fe6794ff146c68` | 18项全部exit0;子进程计时合计70.712秒(不是整个脚本墙钟);整次调用受300秒限制 |+| 受保护delivery `39c5c9d100234c92beaf7eb5d5cab1c0` | **FAIL**,34.736秒;14检查先通过,旧23帧断言失败,后续HEVC/cancel未在该gate执行 |+| 当前4K合同补测 `4k-f764b1a5ef894f46b050cbbf728103ec` | PASS,23检查,14.178秒;两codec原生4K CFR、AAC、实际解码、取消,以及4K B帧多线程输入的EOF/seek均通过;不替代受保护gate |++模式切换40次(20往返):P95 **4.200ms**,最大13.591ms;区间446次提交、唯一epoch1、最大提交间隔20.3844ms,无Feature创建/reset/source open。GDI13→13、handles718→718,播放切换期间private bytes不增长。暂停中40次切换保持PTS和源帧计数。CPU命令耗时和主机提交间隔不是物理显示延迟。++后台导出:冻结revision3/intensity1,前台后续成功应用0.65,实际worker仍使用冻结值;前台累计540帧,导出source120/generated0/hold0/encoded120。导出暂停时前台位置0.333→2.967秒且session1不变。ffmpeg全流解码和ffprobe确认H264/AAC。取消/父进程退出均已有活动worker和源帧,未留下孤儿PID或伪成功文件,partial保留。++当前RTX/NVIDIA runtime真实执行:`player.stdout.log`记录Feature18 Create `0x1 / Success / handle=non-null / seh=0`,DLSSG Create `3840×2160`同样成功;最终NR248、NVOF247、有效generated247,FG Evaluate返回`0x1`。4K输入/底图/光流/FG/输出保持3840×2160,内部NR1920×1080,源处理59.55fps、绝对落后P95 1.77ms。1080诊断60次NR、59次NVOF、2294个非零motion、D3D诊断0错,正常路径回读0;native4K12次NR只证明短片正确运行,不证明4K NR实时或高质量motion(该4K样本nonZeroMotionCount为0)。诊断输出PNG实际查看非黑。++历史Repair计时账本累计487.669秒,失败与此前运行均保留;并未清零来绕过限制。该累计不是本轮单次测试上限。++4K输入检查使用24帧真实B帧H264/HEVC合成素材:首遍读取和EOS后seek0重读,共两遍;每帧有效YUV像素的Adler32和PTS与1线程基线均匹配。脚本明确断言实际4线程日志与9项检查零失败,也断言导出图全部尺寸为原生4K、source/generated/hold/output分项计数及AAC编码,避免只靠进程exit0放行。++UI套件覆盖默认状态/384组合的纯布局数据与四种DPI比例、真实PCM增益、偏好与坏文件保护;播放和暂停各40次模式切换;真实增强关闭/恢复及故障注入后的UI恢复;音量;边看边导出/暂停/继续/冻结设置;取消及活跃worker退出清理。纯数据DPI检查不等于多屏物理缩放验收。++成功导出会同时核对保存的完整冻结快照和真正worker日志中的revision/intensity,并检查ffmpeg解码、ffprobe音视频流。取消和父进程关闭检查明确活动标记、无孤儿PID、无成功文件、已有partial保留。++## 5. 实际窗口截图++目录:`logs/ui-dual-mode/visual-candidate/`。++| 文件 | 实际观察 |+|---|---|+| `daily-current.jpg` | 当前2DE332… EXE的日常影院式界面和透明双语字幕 |+| `professional-current.jpg` | 当前2DE332… EXE的黑色四区工作台;结束后保留画面及最近处理样本 |+| `export.png` | 专业导出页、输出选择和任务控制 |+| `diagnostics.png` | 指标/脱敏区域覆盖正确,无底层播放器控件穿透 |+| `capture-setup.png` | 实际采集配置窗口;未选择格式、未连接设备 |+| `empty.png` | 空白首页提示可见,已去掉灰色占位覆盖 |+| `fullscreen.png` | 实际2560×1440窗口画面;Esc恢复原窗口 |+| `small.png` / `small-drawer.png` | 800×600窗口和修复后的参数栏布局 |+| `keyboard.png` | 编辑框内实际V/空格输入,未触发播放或比较 |++其余状态截图来自本轮较早视觉候选,用于记录相同主视觉;最终EXE的日常/专业复查另有上述明确文件。`subtitles.png`及`professional-final.png`是上一候选DBAD5B…的字幕检查,并非当前二进制截图。截图未经合成或美化。早期失败的`small-drawer-before-fix.png`仅是缺陷记录,不是交付截图。++## 6. 本轮暴露并修正的问题++1. 最初的普通Win32控件排布不符合用户参考。重新实现了整体壳、影院控制条、矢量图标、圆角卡片、原生控件主题和仪表。+2. 延迟布局重复登记同一HWND,造成按钮缺失;修正布局清单。+3. GDI+依赖头文件顺序导致一次编译失败;补COM头文件。一次链接失败因为自己的视觉测试EXE仍运行,等待测试退出后再构建。+4. 增强开关失败后UI仍显示新状态;增加事务归属与确切拒绝版本,修正合法后续调参/换源的竞态。+5. 隐藏页120ms定时器仍可能提交;隐藏/换页取消定时器。空闲停止状态、活跃导出退出提示、导出终态文案一起修正。+6. 诊断面板被视频/控件覆盖;修正同级裁剪与z序。空白首页提示也恢复到视频上方。+7. 模式耗时P95约23ms超出16ms目标。分段计时定位到EndDeferWindowPos触发隐藏面板重复布局;隐藏页改为保留尺寸,批量失效交由绘制消息处理。修复单项实测P95 3.754ms、最大14.208ms;446次提交最大间隔20.1665ms,epoch不变,无Create/reset/source open。+8. 800×600参数抽屉与视频/仪表重叠;改为独立列,三组尺寸文字自适应列宽,真实窗口复查无重叠。+9. 字幕初次实际窗口检查不可见;补compatibility manifest、显式PARGB绘制与隐藏字幕几何初始化。最终日志`subtitle-run.log`记录成功1112×108,截图显示透明双行文字。+10. 非零起始PTS可能提前显示100%;按相对视频时间计算并限制成功前进度。+11. 真4K底图/光流/FG/输出的实时档初测45.95fps、落后P95约895ms。历史通过日志的光流/FG/输出实际1080,不能直接比较;4K分辨率修复在本轮基线ddc515d中已存在。本次只对高分辨率文件解码使用最多4线程,直接将8位YUV转换写入已受fence保护的上传slot,并缩短有上限的FG就绪轮询间隔。最终59.55源fps、落后P95 1.77ms;保持4K输出及1080内部NR,不是原生4K NR实时承诺。+12. 受保护delivery脚本随后在旧的23帧断言停止。本轮基线已使用12 source + 11 generated + 1 tail hold = 24帧,120fps/0.2秒才保持原时长。该gate保持FAIL,文件hash未改;单独补测当前CFR合同,两codec真实解码/音轨/取消通过,不能用补测宣布旧Phase门禁通过。++没有删除失败日志,也没有放宽门槛让失败通过。++## 7. 独立复核与未测范围++独立新上下文只读Reviewer `review_dual_mode`最终结论:**UI0–UI9限定的软件实现与短测范围通过复核,未发现尚未关闭的代码阻断。** 已核对代码、实际窗口截图、同一EXE的UI15项/Repair18项/4K23项证据,前次防漏断言已关闭。Reviewer未写文件或启动测试/GPU/采集;不是独立重跑证明。完整归档见[独立复核记录](REVIEW_UI_DUAL_MODE_2026-09-08.md)。++七个受保护文件与R0基线hash一致,根目录/暂存NR和addon身份一致,用户删除的测试视频仍不存在,运行时/SDK/日志与图像仍被Git忽略。索引:`logs/ui-dual-mode/evidence-index.json`;保护核对:`logs/ui-dual-mode/protected-final.json`。++当前Phase仍为历史Phase7本机候选,UI0–UI9单独记状态。已有NVOF+confidence路线、DLSSNR实验身份及NR实时档边界不变;Depth provider、原生游戏输入等未实现能力不会因为UI更新被标成完成。++尚未验收:本版本实卡视频/声音/断线恢复、多屏物理DPI穿越、实际扫描/光子延迟、长时间稳定,以及所有4K SR+4X组合的实时性能。采集设备驱动若长时间卡住查询,底层驱动兼容性仍需实卡判断。本次不把无设备或仅枚举算采集端到端通过。++下一条唯一用户验收任务:用`Veyra.cmd`启动新界面,在实际采集卡上验收日常/专业切换、声音和体感延迟。专有runtime分发权仍未解决,仅本机研发交付。diff --git a/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md b/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.mdindex 24a06c1b..da9c167e 100644--- a/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md+++ b/docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md@@ -1,7 +1,7 @@# Veyra 双模式界面改版执行文档日期:2026-09-08-状态:**设计方向已确认;本次仅交付执行文档,尚未开始界面代码施工。**+状态:**用户随后授权施工,UI0–UI9已实现;实测、复核与未验范围见[双模式交付记录](UI_DUAL_MODE_DELIVERY_2026-09-08.md)。下文保留批准时的实施合同,未来时态不代表当前进度。**项目:`C:\Users\123\Desktop\Veyra DLSS Video Player`施工编号:UI0 → UI9,独立于旧 Phase 0–7。diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 7f4f51c3..f29174f2 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -1,13 +1,21 @@-# Veyra 本机使用 — Repair v2+# Veyra 本机使用 — 日常 / 专业双模式双击项目根目录 `Veyra.cmd`。实际程序为 `out/build/x64-release/veyra.exe`;本机 runtime / shader 路径在构建时绑定,不要移动项目目录。这不是可公开分发的安装包。+## 两种界面++启动始终进入日常模式。深蓝影院界面提供打开视频、最近文件、采集卡入口、增强总开关、预设选择、进度、播放、音量、字幕和全屏。右上角“切换专业模式”进入黑色工作台:左侧图标栏切换来源,右侧四个标签集中增强、补帧、预设和导出;下方显示真实处理尺寸和最近NR阶段耗时。++两种模式保留同一个视频宿主和播放会话,不重新打开文件,不套用另一套画质参数。专业模式的对比状态会记住,但日常模式恢复正常增强显示。小窗口通过“参数”按钮打开右侧抽屉。++增强总开关关闭时真正旁路NR、SR与补帧,开启后恢复配置。关闭期间在专业面板调整参数,只保存待启用配置。界面显示“正在应用”时,以右栏已应用版本为准;失败会恢复实际状态。+## 播放和参数-1. 点“打开视频/图片”或拖入 H.264/HEVC 视频、PNG/JPEG 图片。+1. 点“打开视频”或拖入 H.264/HEVC 视频;PNG/JPEG图片自动进入专业模式。Ctrl+O打开文件。空格在视频/主窗口焦点下播放、暂停;输入框保留正常输入。2. “SR 4K”把底图超分至4K;“实时NR档”保留该4K底图,约1080p内部NR的变化由GPU回填。状态显示输入、底图、NR、光流、FG与输出实际尺寸。3. 取消“实时NR档”可选原生NR,性能成本更高,不承诺原生4K60。“补帧”配合2X/3X/4X选择,倍率表示每对源帧的总时间格数;无效生成或reset不会计作有效补帧。-4. “参数与预设”提供7项NR参数及5项变化量参数。Desired与Applied分开显示,真实帧边界整套应用,失败回滚;参数修改不重新打开视频或归零进度。修改尺寸/光流会有有界资源重建。+4. 专业模式“增强”提供7项NR参数及5项变化量参数。可滚动查看,悬停数值框查看范围;数值框修改后点“应用整套设置”,滑杆采用120毫秒去抖。期望与已应用版本固定显示,真实帧边界整套应用,失败回滚;切换面板会保留草稿并取消尚未发出的延迟提交。参数修改不重新打开视频或归零进度。修改尺寸/光流会有有界资源重建。5. 肤质结构、风格、自动遮罩、画面内UI修正属于实验参数。当前合成样本未观察到肤质/UI修正的像素变化,不能保证实际效果;风格和自动遮罩已观察到变化。6. 预设支持新建、复制当前、重命名、删除、设默认、恢复内建默认,保存在 `runtime_local/user-presets.v1`。配置损坏会保留原文件并报错,不静默覆盖。7. 光流三档为性能/平衡/质量;界面记录实际应用档。30/50/60模式用于识别内容节奏,不会把源时间轴重采样成指定帧率。静止画面不能确认较低内容帧率。@@ -15,19 +23,22 @@## 对比、性能与诊断-- 按住V或“按住原图”临时查看原图;可用“原图/增强切换”和“分屏拖动”,并选择输入原画或增强前底图作为参考。对比显示同一源帧的GPU参考,生成帧没有天然原图时明确使用真实帧对比。+- 专业模式按住V或“按住原图”临时查看原图;可用“原图/增强切换”和“分屏拖动”,并选择输入原画或增强前底图作为参考。对比显示同一源帧的GPU参考,生成帧没有天然原图时明确使用真实帧对比。- “性能/诊断”中GPU timestamp与CPU解码、提交、等待、Present分开。实际提交频率不等同物理屏幕扫描;没有测到的项目显示未测,不以源帧率乘倍率代替。- 诊断包括真实失败码、阶段/尺寸/帧身份与运行时标识;相同问题合并计数、固定上限。复制前可预览脱敏文本;不自动上传任何内容。-- 同名 UTF-8/UTF-16LE `.srt` 在FG后的独立字幕区域显示;暂不解码内嵌字幕,也不烧录字幕进导出文件。+- 同名 UTF-8/UTF-16LE `.srt` 在FG后的透明字幕层显示;字幕按钮可开关、载入外部SRT或调整字号。暂不解码内嵌字幕,也不烧录字幕进导出文件。+- 音量与静音只控制Veyra自己的音频,不修改Windows总音量。无音轨时控件禁用。采集音量依设备图是否提供音频控制,实际能力会反馈。## 图片与视频导出-- “保存图片”保存当前真实源帧的增强PNG/JPEG。不会覆盖已有文件。-- “导出视频”选择新MP4路径和H.264/HEVC。启动时冻结设置;实时NR档不降低导出分辨率,4K输入默认原生4K NR。编码使用D3D12 NVENC input/fence,CPU只接压缩码流。+- 专业模式“导出”页的“保存当前图片 / 视频帧”保存当前真实源帧的增强PNG/JPEG。不会覆盖已有文件。+- Ctrl+E进入专业导出页。选择新MP4路径和H.264/HEVC后启动独立作业,观看继续。启动时冻结完整已应用设置;后续播放器调参不改变该作业。实时NR档不降低导出分辨率,4K输入默认原生4K NR。编码使用D3D12 NVENC input/fence,CPU只接压缩码流。+- 页内提供暂停、继续、取消及“优先观看”。优先观看在完整源帧之间给导出让出时间,保留全部源帧;同一GPU仍可能争用,不保证所有4K组合同时实时。封装/验证期间不能暂停,只有子进程确认成功才显示100%。+- 可查看作业ID、冻结设置版本、源帧、有效生成、CFR占位与编码计数。日常模式也显示任务状态入口,点击返回专业导出页。- 默认保留第一条可封装MP4的音轨;不兼容编码明确拒绝,不静默丢音轨。无多音轨选择或音频转码。- CFR输出支持2X/3X/4X;缺失/无效生成及尾部保持帧明确记为Hold。先采样最多120帧时间戳,只存元数据,再从头读取导出;全程继续验证时间轴,不均匀时间戳会拒绝。- 对量化短片,原始精确帧率可能无法唯一推断;优先使用与时间戳一致的标准标称帧率,否则选择一致的标准候选,再尝试非标准标称帧率,日志记录声明值和候选值。不宣称恢复了唯一原始帧率。-- “停止”取消任务;已产生的 `.partial` 保留诊断,不改名成成功文件。预检查即失败时可能还没创建partial。重新导出使用新名称,不支持断点续编。+- 播放器“停止”只停止当前来源;导出通过专业页“取消导出”取消。正常退出时如果有活跃作业,会提示取消并退出或返回继续。已产生的 `.partial` 保留诊断,不改名成成功文件。预检查即失败时可能还没创建partial。重新导出使用新名称,不支持断点续编。## 采集卡与边界@@ -35,4 +46,6 @@仅Windows x64/NVIDIA/SDR,偶数尺寸最高3840×2160;HDR不支持。Depth provider未实现,当前为NVOF motion + confidence门控,不等同游戏原生深度/运动向量。短测不证明长期稳定、所有采集卡兼容或画质优于其他产品。实际屏幕扫描/光子延迟、多屏物理DPI穿越尚未测量。专有runtime分发权未解决,不打包、上传或发布DLL/SDK。-详细结果见 `docs/REPAIR_V2_DELIVERY_2026-09-08.md`。测试限制已按用户2026-09-08澄清改为每次最多300秒,历史累计时间仅作报告。+窗口尺寸、位置、音量、字幕等保存在独立UI偏好中;只保存成功应用的画质。损坏的原配置保留,不静默覆盖。程序每次重启仍默认日常模式。++双模式结果见 `docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md`,底层既有修复见 `docs/REPAIR_V2_DELIVERY_2026-09-08.md`。测试限制为每次最多300秒,历史累计时间仅作报告。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 4aa26948..2464f853 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,3 +1,17 @@+# 2026-09-08 双模式UI本机软件交付++已实现批准的UI0–UI9:默认日常影院界面、专业四区工作台、共享视频宿主与无重开切换、完整参数/预设、真实音量和透明字幕、后台冻结设置导出、诊断/全屏/小窗口。最初普通Win32排布在用户反馈后重新实现。++基线本地存档`ddc515d`;当前EXE SHA256 `2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6`。UI全套15子检查109.583秒PASS;Repair v2 18项PASS,子进程计时合计70.712秒;4K补充23检查14.178秒PASS。真实4K输入/底图/光流/FG/输出、1080内部NR短测59.55源fps、落后P95 1.77ms。每次调用最多300秒,累计历史保留。++受保护delivery脚本此次34.736秒后在旧23帧断言FAIL;基线已有CFR tail hold,当前12源帧2X正确输出24帧/120fps/0.2秒。保护文件未改,补测不替代Phase gate。全项目仍needs_review;当前UI软件交付不等于实卡、多屏物理DPI、长稳、完整组合性能或公开发行通过。++详情、文件、命令、错误码、截图和复核范围:[双模式交付报告](UI_DUAL_MODE_DELIVERY_2026-09-08.md)。操作:[使用指南](USER_GUIDE.md)。下一条用户验收:从Veyra.cmd启动,在真实采集卡上检查新界面切换、声音和体感延迟。本轮未开启采集流、未更改外部应用或运行时、未上传发布。++---++以下保留历史版本记录,旧的“当前EXE/尚未施工/已通过”不代表本次状态:+# Veyra Worklog## 2026-09-08 Dual-mode UI execution document onlydiff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 11172ee4..7b9862be 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -13,7 +13,10 @@ struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; uint32_t fgEnhancementSettings 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;}static PlayerOptions from(EnhancementSettings s){PlayerOptions o;o.nr=s.nr;o.sr=s.sr;o.fg=s.multiplier>1;o.fgMultiplier=std::max(2u,s.multiplier);o.realtime=s.nrPolicy==pipeline::NrSizePolicy::Realtime;o.settings=s;return o;}};+enum class TransportState { Empty, Opening, Playing, Paused, Ended, Stopping, Failed };struct PlayerSnapshot {+ TransportState transport=TransportState::Empty;+ uint64_t sessionId=0,rejectedRevision=0;float volume=1;bool muted=false,audioAvailable=false;std::wstring status=L"请打开视频或图片";EnhancementSettings desired,applied;bool applying=false;double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;@@ -35,7 +38,8 @@ public:void open(HWND video,const std::wstring& path,PlayerOptions options);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){paused_.store(p);}+ void pause(bool p);+ void setVolume(float gain,bool mute);void seek(double seconds){seekSeconds_.store(seconds);}void saveFrame(const std::wstring& path);void startExport(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc);@@ -51,7 +55,8 @@ private:std::thread worker_;std::condition_variable wake_;std::function<void()> pending_;bool shutdown_=false,busy_=false;EnhancementSettings desired_;uint64_t nextRevision_=1;- std::atomic<bool> stop_{false},paused_{false};+ std::atomic<bool> stop_{false},paused_{false},muted_{false};+ std::atomic<float> volume_{1};uint64_t sessionId_=0;std::atomic<double> seekSeconds_{-1};std::atomic<int> comparisonMode_{0};std::atomic<bool> comparisonBase_{false};std::atomic<float> comparisonSplit_{.5f};};diff --git a/include/veyra/engine/ExportJobManager.h b/include/veyra/engine/ExportJobManager.hnew file mode 100644index 00000000..5206e817--- /dev/null+++ b/include/veyra/engine/ExportJobManager.h@@ -0,0 +1,25 @@+#pragma once+#include "veyra/engine/EngineController.h"+#include <memory>+namespace veyra::engine {+enum class ExportState { Idle, Preparing, Running, Paused, Finishing, Succeeded, Failed, Cancelled };+struct ExportJobSnapshot {+ ExportState state=ExportState::Idle;+ double progress=0;+ uint64_t jobId=0,frozenRevision=0,sourceFrames=0,generated=0,holds=0,encoded=0;+ EnhancementSettings frozen;+ std::wstring message,output;+ bool active()const{return state>=ExportState::Preparing&&state<=ExportState::Finishing;}+};+// One isolated NGX context in a child process. Anonymous inherited mapping is+// the entire IPC capability; no discoverable pipe, shell or config pathname.+class ExportJobManager {+public:+ ExportJobManager();~ExportJobManager();+ bool start(const std::wstring&,const std::wstring&,EnhancementSettings,bool hevc,unsigned maxFrames=0);+ void cancel();void pause(bool);void watching(bool);+ ExportJobSnapshot poll();+private:struct Impl;std::unique_ptr<Impl> p_;+};+int runExportWorker(HANDLE mapping);+}diff --git a/include/veyra/engine/VideoExportJob.h b/include/veyra/engine/VideoExportJob.hindex b2bc6a9b..033688fd 100644--- a/include/veyra/engine/VideoExportJob.h+++ b/include/veyra/engine/VideoExportJob.h@@ -2,7 +2,8 @@#include "veyra/engine/EngineController.h"#include <functional>namespace veyra::engine {+struct ExportCounts {uint64_t source=0,generated=0,holds=0,encoded=0;};bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,- unsigned maxFrames=0);+ unsigned maxFrames=0,const std::function<bool()>& frameBoundary={},const std::function<void(const ExportCounts&)>& counts={});}diff --git a/include/veyra/media/FFmpegVideoDecoder.h b/include/veyra/media/FFmpegVideoDecoder.hindex f6010d4d..c60b0df1 100644--- a/include/veyra/media/FFmpegVideoDecoder.h+++ b/include/veyra/media/FFmpegVideoDecoder.h@@ -38,7 +38,7 @@ public:// Den` is the DEMUXER stream time base: decoder frame PTS pass through in// that base when the codec context itself carries none.bool openSoftware(const AVCodecParameters* codecParameters,- int streamTimeBaseNum = 0, int streamTimeBaseDen = 0);+ int streamTimeBaseNum = 0, int streamTimeBaseDen = 0, unsigned softwareThreads = 1);// D3D12VA hardware decode on the SHARED Veyra device (Playbook 13.2):// creates an AV_HWDEVICE_TYPE_D3D12VA context wrapping `device`/`queue`,diff --git a/include/veyra/sink/AudioGain.h b/include/veyra/sink/AudioGain.hnew file mode 100644index 00000000..51af400e--- /dev/null+++ b/include/veyra/sink/AudioGain.h@@ -0,0 +1,11 @@+#pragma once+#include <algorithm>+#include <cmath>+#include <cstddef>+namespace veyra::sink {+// 5 ms full-scale ramp at 48 kHz, independent of PTS and renderer clock.+inline void applyStereoGain(float* samples,size_t frames,float target,float& current){+ target=std::isfinite(target)?std::clamp(target,0.0f,1.0f):0;+ for(size_t i=0;i<frames;++i){current+=std::clamp(target-current,-1.0f/240,1.0f/240);samples[i*2]*=current;samples[i*2+1]*=current;}+}+}diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex fd92ed92..84ec01ba 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -127,6 +127,7 @@ private:class AudioRenderer {public:bool start();+ void setGain(float value){gain_.store(value);}// Called by the audio thread after prefill: begins playback anchored at// the PTS of the sample that will be written first.@@ -152,6 +153,7 @@ public:void shutdown();private:+ std::atomic<float> gain_{1};float smoothedGain_=1,loggedGain_=-1;IMMDeviceEnumerator* enum_ = nullptr;IMMDevice* device_ = nullptr;IAudioClient* client_ = nullptr;diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.hindex 7d7a95c5..fde896de 100644--- a/include/veyra/source/CaptureCardSource.h+++ b/include/veyra/source/CaptureCardSource.h@@ -18,6 +18,7 @@ public:// or start audio until the presenter and enhancement graph are ready.bool configure(const SourceOpenDesc&);bool start();+ bool setAudioGain(float); // call on the graph owner thread; never system volumeCaptureMetrics metrics()const;const SourceInfo& info()const override;SourceReadStatus read(pipeline::FramePacket&,const AVFrame**)override;diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.mdindex 1e99221e..c61c0064 100644--- a/loop/EVIDENCE.md+++ b/loop/EVIDENCE.md@@ -365,3 +365,13 @@ Current evidence and unresolved review findings: docs/REPAIR_PROGRESS_2026-09-08## Repair v2 final known-fix delivery 2026-09-08Joint joint-a077b89fd39348e4a49f4195c9d4e416: 18/18 software checks, 71.0278864s. EXE 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. Read-only review_known_fixes PASS in scoped fixes; global needs_review and old Phase fields unchanged. Per-invocation <=300 seconds; cumulative 346.3985650s preserved. Full evidence, failures and performance limits: docs/REPAIR_V2_DELIVERY_2026-09-08.md. No capture or publication.++## 2026-09-08 UI0–UI9 final software record++Baseline ddc515d. Current EXE 2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6. Final app build logs/ui-dual-mode/build-upload-direct.log exit0; source-only integration test build build-threaded-test.log exit0. UI logs/ui-dual-mode/de337338b71e43618c4beaa488d54afb/result.json: 15 subprocesses exit0/109.583s; switch40 P95 4.2ms/max13.591, 446 submissions/epoch1/maxgap20.3844ms/no Create/reset/open; GDI/handle stable. Repair logs/repair-v2/joint-91436d0b0f4145c2b6fe6794ff146c68/result.json:18 exit0/70.7119369s subprocess sum, lifetime ledger487.6690411 preserved. Current-CFR supplement logs/ui-dual-mode/4k-f764b1a5ef894f46b050cbbf728103ec/result.json:23 checks/14.178107s PASS, actual 1-vs-4-thread 4K H264/HEVC B-frame first read and post-EOS seek0 reread, effective YUV pixel Adler32 and PTS equal, native4K 12+11+1=24frames/120fps/0.2s/AAC/decode/cancel.++Protected gate logs/delivery/39c5c9d100234c92beaf7eb5d5cab1c0/result.json remains FAIL at legacy23 assertion, 34.736374s. Earlier runs de8ddbf1e89c41d78543802c299f3a3a and 64e5c18cc8834dfba5f991549d726477 failed player lateness at45.95/55.68fps. Historical1080 flow/FG/output gate cannot prove current full4K performance. Bounded four-thread file decode, fenced direct YUV upload and .2ms FG readiness polling preserve full4K base/flow/FG/output, NR1080; current59.55fps/P951.77ms, NR248/NVOF247/FG247, Create/Evaluate0x1 Success. Never weakened protected assertions or lowered extents. Root/staged NR and addon hashes match; seven protected hashes unchanged; deleted user test video remains absent. No capture or publication.++Visual checks via native UI: same EXE daily-current.jpg/professional-current.jpg in logs/ui-dual-mode/visual-candidate, transparent bilingual subtitles, complete four-card Pro repaint. Other visual states from prior same-UI candidate include capture setup only, export, diagnostics, 800x600 drawer, 2560x1440 fullscreen, and edit focus. Earlier subtitle/layout/mode-latency failures retained and repaired. Readonly review_dual_mode reviewed code and evidence; exact final conclusion in docs/REVIEW_UI_DUAL_MODE_2026-09-08.md. Historical Phase fields are not UI proof. User authorized normal shutdown after local task completion; final checkpoint and shutdown dispatch recorded separately.++Next: user visual/capture audio/latency acceptance. Report docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md.diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex c8f6f199..b698b0cb 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -1283,3 +1283,17 @@ User explicitly clarified 300 seconds means each test invocation, not lifetime a## Repair v2 final known-fix delivery 2026-09-08Joint joint-a077b89fd39348e4a49f4195c9d4e416: 18/18 software checks, 71.0278864s. EXE 1DFE9A6A6963A73350B7677392516DFB23E6C208FABF4514388457183DDDA266. Read-only review_known_fixes PASS in scoped fixes; global needs_review and old Phase fields unchanged. Per-invocation <=300 seconds; cumulative 346.3985650s preserved. Full evidence, failures and performance limits: docs/REPAIR_V2_DELIVERY_2026-09-08.md. No capture or publication.+++## 2026-09-08 UI0–UI5 implementation+User explicitly authorized local checkpoint, full approved UI plan, and shutdown after completion. Baseline archived in local commit ddc515d; no push. Implementing native shared-HWND Daily/Professional shell, embedded settings, per-application PCM gain, asynchronous capture capability query, and isolated export worker with anonymous inherited mapping and kill-on-close job. Two builds passed; first 20 round-trip mode test exited 0. Visual review exposed duplicate HWND entries in deferred layout (missing toolbar controls); correction in progress. This is not delivery proof. No capture stream started. Next: persistence, diagnostics, layout/keyboard tests, concurrent export, independent read-only review.++## 2026-09-08 UI0–UI9 final software record++Baseline ddc515d. Current EXE 2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6. Final app build logs/ui-dual-mode/build-upload-direct.log exit0; source-only integration test build build-threaded-test.log exit0. UI logs/ui-dual-mode/de337338b71e43618c4beaa488d54afb/result.json: 15 subprocesses exit0/109.583s; switch40 P95 4.2ms/max13.591, 446 submissions/epoch1/maxgap20.3844ms/no Create/reset/open; GDI/handle stable. Repair logs/repair-v2/joint-91436d0b0f4145c2b6fe6794ff146c68/result.json:18 exit0/70.7119369s subprocess sum, lifetime ledger487.6690411 preserved. Current-CFR supplement logs/ui-dual-mode/4k-f764b1a5ef894f46b050cbbf728103ec/result.json:23 checks/14.178107s PASS, actual 1-vs-4-thread 4K H264/HEVC B-frame first read and post-EOS seek0 reread, effective YUV pixel Adler32 and PTS equal, native4K 12+11+1=24frames/120fps/0.2s/AAC/decode/cancel.++Protected gate logs/delivery/39c5c9d100234c92beaf7eb5d5cab1c0/result.json remains FAIL at legacy23 assertion, 34.736374s. Earlier runs de8ddbf1e89c41d78543802c299f3a3a and 64e5c18cc8834dfba5f991549d726477 failed player lateness at45.95/55.68fps. Historical1080 flow/FG/output gate cannot prove current full4K performance. Bounded four-thread file decode, fenced direct YUV upload and .2ms FG readiness polling preserve full4K base/flow/FG/output, NR1080; current59.55fps/P951.77ms, NR248/NVOF247/FG247, Create/Evaluate0x1 Success. Never weakened protected assertions or lowered extents. Root/staged NR and addon hashes match; seven protected hashes unchanged; deleted user test video remains absent. No capture or publication.++Visual checks via native UI: same EXE daily-current.jpg/professional-current.jpg in logs/ui-dual-mode/visual-candidate, transparent bilingual subtitles, complete four-card Pro repaint. Other visual states from prior same-UI candidate include capture setup only, export, diagnostics, 800x600 drawer, 2560x1440 fullscreen, and edit focus. Earlier subtitle/layout/mode-latency failures retained and repaired. Readonly review_dual_mode reviewed code and evidence; exact final conclusion in docs/REVIEW_UI_DUAL_MODE_2026-09-08.md. Historical Phase fields are not UI proof. User authorized normal shutdown after local task completion; final checkpoint and shutdown dispatch recorded separately.++Next: user visual/capture audio/latency acceptance. Report docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md.diff --git a/loop/STATE.json b/loop/STATE.jsonindex 700838a3..810992f1 100644--- a/loop/STATE.json+++ b/loop/STATE.json@@ -133,9 +133,9 @@]},"uiRedesign": {- "status": "design_approved_implementation_not_started",+ "status": "local_software_checks_passed_user_acceptance_pending","plan": "docs/UI_DUAL_MODE_EXECUTION_PLAN_2026-09-08.md",- "currentDeliverable": "execution_document_only",+ "currentDeliverable": "native_dual_mode_app","defaultMode": "daily","professionalScope": ["fine settings",@@ -147,10 +147,37 @@"invariants": ["same preview source and video host on mode switch","no implicit settings change",- "existing app unchanged in documentation turn"+ "daily on normal restart",+ "capture stream reserved for user",+ "protected controls unchanged"],- "nextAction": "On implementation request, start UI0 inventory then UI1 shared state and stable video host",+ "nextAction": "User accepts UI and capture audio/latency using Veyra.cmd; no further unattended product expansion","testLimitScope": "per_invocation",- "testLimitSeconds": 300+ "testLimitSeconds": 300,+ "report": "docs/UI_DUAL_MODE_DELIVERY_2026-09-08.md",+ "baselineCommit": "ddc515d",+ "exeSha256": "2DE33230CD3A6556BC8E1399DD93BB8959B8EF37B2BACEF23D1486590AA4D3C6",+ "updatedAt": "2026-09-07T19:38:07.275382+00:00",+ "softwareEvidence": [+ "logs/ui-dual-mode/de337338b71e43618c4beaa488d54afb/result.json",+ "logs/repair-v2/joint-91436d0b0f4145c2b6fe6794ff146c68/result.json",+ "logs/ui-dual-mode/4k-f764b1a5ef894f46b050cbbf728103ec/result.json"+ ],+ "protectedDeliveryGate": {+ "status": "failed_obsolete_23_frame_assertion",+ "evidence": "logs/delivery/39c5c9d100234c92beaf7eb5d5cab1c0/result.json",+ "modified": false,+ "doesNotAdvanceOldPhase": true+ },+ "review": "review_dual_mode independent readonly; see docs/REVIEW_UI_DUAL_MODE_2026-09-08.md",+ "remainingLimits": [+ "user visual acceptance",+ "actual capture video/audio/disconnect",+ "physical scanout/photon latency",+ "physical multi-monitor DPI",+ "long stability",+ "all SR4K+4X realtime combinations",+ "proprietary distribution blocked"+ ]}}diff --git a/scripts/acceptance/ui-4k-regression.ps1 b/scripts/acceptance/ui-4k-regression.ps1new file mode 100644index 00000000..3afe5386--- /dev/null+++ b/scripts/acceptance/ui-4k-regression.ps1@@ -0,0 +1,68 @@+[CmdletBinding()]+param([string]$Root=(Join-Path $PSScriptRoot '../..'),[ValidateRange(1,300)][int]$MaxRuntimeSeconds=300)+Set-StrictMode -Version Latest+$ErrorActionPreference='Stop'+$Root=(Resolve-Path -LiteralPath $Root).Path+Set-Location -LiteralPath $Root+# Supplement the CURRENT Repair v2 CFR contract. The protected delivery gate+# remains unchanged and FAILED at its older 23-frame assertion; this is not a+# replacement Phase gate or a way to claim that protected gate passed.+$timer=[Diagnostics.Stopwatch]::StartNew()+$run=[guid]::NewGuid().ToString('N')+$dir=Join-Path $Root ('logs/ui-dual-mode/4k-'+$run)+New-Item -ItemType Directory -Path $dir|Out-Null+$bin=Join-Path $Root 'out/build/x64-release'+$checks=[Collections.Generic.List[object]]::new()+function Check([string]$Name,[bool]$Passed,[string]$Detail){+ $checks.Add([ordered]@{name=$Name;passed=$Passed;detail=$Detail})+ if(-not $Passed){throw "$Name : $Detail"}+}+function Run([string]$Name,[string]$Exe,[string[]]$Argv,[int]$ExpectedExit=0){+ $remaining=$MaxRuntimeSeconds-$timer.Elapsed.TotalSeconds+ if($remaining -lt 1){throw 'Per-invocation time limit reached'}+ $watch=[Diagnostics.Stopwatch]::StartNew()+ $p=Start-Process -FilePath $Exe -ArgumentList @($Argv|ForEach-Object{'"'+$_.Replace('"','\"')+'"'}) -PassThru -WindowStyle Hidden -RedirectStandardOutput "$dir/$Name.stdout.log" -RedirectStandardError "$dir/$Name.stderr.log"+ $processHandle=$p.Handle+ if(-not $p.WaitForExit([int]([Math]::Min(60,$remaining)*1000))){+ & "$env:SystemRoot/System32/taskkill.exe" /PID $p.Id /T /F|Out-Null+ throw "$Name timed out"+ }+ Check "$Name-exit" ($p.ExitCode -eq $ExpectedExit) "exit=$($p.ExitCode) expected=$ExpectedExit seconds=$($watch.Elapsed.TotalSeconds)"+}+$passed=$false;$failure=$null+try {+ if(Test-Path -LiteralPath 'loop/STOP'){throw 'User STOP exists'}+ $ffmpeg=(Get-Command ffmpeg).Source;$ffprobe=(Get-Command ffprobe).Source+ $source=(Resolve-Path 'loop/local/fixed_clips/test_av_4k.mp4').Path+ foreach($codec in @('h264','hevc')){+ $fixture="$dir/bframes-$codec.mp4"+ $encoder=if($codec -eq 'h264'){'libx264'}else{'libx265'}+ $args=@('-nostdin','-v','error','-i',$source,'-frames:v','24','-an','-c:v',$encoder,'-preset','ultrafast','-bf','2','-g','12','-threads','4')+ if($codec -eq 'hevc'){$args+=@('-x265-params','pools=4:frame-threads=4:log-level=error')}+ Run "fixture-$codec" $ffmpeg ($args+@($fixture))+ Run "fixture-inspect-$codec" $ffprobe @('-v','error','-count_frames','-show_streams','-of','json',$fixture)+ $stream=(Get-Content "$dir/fixture-inspect-$codec.stdout.log" -Raw|ConvertFrom-Json).streams[0]+ Check "fixture-bframes-$codec" ($stream.has_b_frames -gt 0 -and [int]$stream.nb_read_frames -eq 24) '24 real 4K frames with B-frame reorder'+ Run "threaded-EOS-seek-$codec" "$bin/veyra_source_tests.exe" @($fixture,'--threaded')+ $threadLog=Get-Content "$dir/threaded-EOS-seek-$codec.stdout.log" -Raw+ Check "threaded-proof-$codec" ($threadLog -match 'threads=1 ' -and $threadLog -match 'threads=4 activeThreadType=1' -and $threadLog -match 'threaded-file: 9 checks, 0 failures' -and ([regex]::Matches($threadLog,'\[PASS\] threaded:every-pixel-and-PTS-equal')).Count -eq 2) 'actual frame-threaded codec, first read plus seek-after-EOS reread, all effective YUV pixel Adler32 and PTS match'+ $file="$dir/native-$codec.mp4"+ $exportArgs=@($source,'--export-out',$file,'--max-frames','12','--fg')+ if($codec -eq 'hevc'){$exportArgs+='--hevc'}+ Run "export-$codec" "$bin/veyra.exe" $exportArgs+ $exportLog=Get-Content "$dir/export-$codec.stdout.log" -Raw+ Check "native-graph-counts-$codec" ($exportLog -match '\[resolution\] source=3840x2160 base=3840x2160 nr=3840x2160 flow=3840x2160 fg=3840x2160 output=3840x2160' -and $exportLog -match '\[export-counts\] source=12 generated=11 hold=1 output=24 multiplier=2 ') 'actual graph extents and separate source/generated/hold/output counters'+ Run "inspect-$codec" $ffprobe @('-v','error','-count_frames','-show_streams','-of','json',$file)+ $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 "native-CFR-$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.r_frame_rate -eq '120/1' -and [Math]::Abs([double]$v.duration-0.2) -lt 0.001 -and $a.Count -eq 1 -and $a[0].codec_name -eq 'aac' -and [Math]::Abs([double]$a[0].duration-[double]$v.duration) -lt 0.05) '12 source + 11 generated + 1 explicit tail hold = 24 CFR frames at 120fps, preserves 0.2s source duration and AAC'+ Run "decode-$codec" $ffmpeg @('-nostdin','-v','error','-xerror','-i',$file,'-f','null','-')+ }+ Run 'cancel' "$bin/veyra.exe" @($source,'--export-out',"$dir/cancel.mp4",'--cancel-after-ms','3000') 3+ Check 'cancel-partial' ((-not(Test-Path "$dir/cancel.mp4")) -and (Test-Path "$dir/cancel.mp4.partial")) 'cancel never promotes unfinished native4K output'+ Check 'time-limit' ($timer.Elapsed.TotalSeconds -lt $MaxRuntimeSeconds) 'single test invocation <=300 seconds'+ $passed=$true+} catch {$failure=$_.ToString()}+[ordered]@{runId=$run;passed=$passed;seconds=$timer.Elapsed.TotalSeconds;exeSha256=(Get-FileHash "$bin/veyra.exe").Hash;sourceTestSha256=(Get-FileHash "$bin/veyra_source_tests.exe").Hash;error=$failure;checks=$checks;protectedGate='unchanged; latest run failed obsolete 23-frame assertion';scope='current CFR and threaded file input regression; no capture or long stability'}|ConvertTo-Json -Depth 8|Set-Content "$dir/result.json" -Encoding UTF8+Write-Host "4K current-contract regression passed=$passed evidence=$dir/result.json error=$failure"+if($passed){exit 0}else{exit 1}diff --git a/scripts/acceptance/ui-dual-mode.ps1 b/scripts/acceptance/ui-dual-mode.ps1new file mode 100644index 00000000..a9c56326--- /dev/null+++ b/scripts/acceptance/ui-dual-mode.ps1@@ -0,0 +1,89 @@+[CmdletBinding()]+param([Parameter(Mandatory=$true)][string]$Root,+ [ValidateRange(1,300)][int]$MaxRuntimeSeconds=300,+ [ValidateSet('state','switch','pause','master','masterreject','audio','export','canceljob','exitjob','all')][string]$Case='all')+Set-StrictMode -Version Latest+$ErrorActionPreference='Stop'+$Root=(Resolve-Path -LiteralPath $Root).Path+$timer=[Diagnostics.Stopwatch]::StartNew()+$runId=[guid]::NewGuid().ToString('N')+$runDir=Join-Path $Root ('logs/ui-dual-mode/'+$runId)+New-Item -ItemType Directory -Path $runDir | Out-Null+$items=[Collections.Generic.List[object]]::new()+$oldLog=$env:VEYRA_LOG_FILE+$oldReject=$env:VEYRA_TEST_REJECT_NR_DISABLE+$exe=Join-Path $Root 'out/build/x64-release/veyra.exe'+$clip=Join-Path $Root 'loop/local/fixed_clips/corpus/translation_1080p60.mp4'+function Run-Check([string]$name,[string]$program,[string]$arguments){+ $remaining=$MaxRuntimeSeconds-$timer.Elapsed.TotalSeconds+ if($remaining -le 0){throw 'This invocation reached its time limit'}+ $clock=[Diagnostics.Stopwatch]::StartNew();$p=$null;$code=125+ try {+ $p=Start-Process -FilePath $program -ArgumentList $arguments -WorkingDirectory $Root -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $runDir ($name+'.stdout.log')) -RedirectStandardError (Join-Path $runDir ($name+'.stderr.log'))+ $handle=$p.Handle+ if($p.WaitForExit([int][Math]::Max(1,$remaining*1000))){$code=$p.ExitCode}else{$code=124}+ } finally {if($null -ne $p -and -not $p.HasExited){& "$env:SystemRoot/System32/taskkill.exe" /PID $p.Id /T /F | Out-Null;$p.WaitForExit()};$clock.Stop()}+ $items.Add([ordered]@{name=$name;command=$program+' '+$arguments;exitCode=$code;seconds=$clock.Elapsed.TotalSeconds})+ if($code -ne 0){throw "$name failed: $code"}+}+$passed=$false;$problem=''+try {+ if((Get-FileHash -LiteralPath $clip).Hash -ne '62BA4375DA00C9B14ECE97485AE2C06223401AE873EF0CAD8520B736A5D4D236'){throw 'Synthetic media identity mismatch'}+ if($Case -in @('all','state')){Run-Check 'state' (Join-Path $Root 'out/build/x64-release/veyra_ui_contract_tests.exe') ('"'+(Join-Path $runDir 'preferences')+'"')}+ foreach($name in @('switch','pause','master','masterreject','audio','export','canceljob','exitjob')){+ if($Case -notin @('all',$name)){continue}+ $env:VEYRA_LOG_FILE=Join-Path $runDir ($name+'.app.log')+ $flags=switch($name){'switch'{'--smoke-dual'}'pause'{'--smoke-dual-pause'}'master'{'--smoke-master'}'masterreject'{'--smoke-master-reject'}'audio'{'--smoke-audio'}'export'{'--smoke-dual --smoke-job --smoke-dual-export "'+(Join-Path $runDir 'concurrent.mp4')+'"'}}+ if($name -in @('canceljob','exitjob')){$flags=$(if($name -eq 'canceljob'){'--smoke-job-cancel'}else{'--smoke-job-exit'})+' --smoke-dual-export "'+(Join-Path $runDir ($name+'.mp4'))+'"'}+ $input=$clip+ if($name -in @('audio','export','canceljob','exitjob')){+ $input=Join-Path $runDir ($name+'-audio.mp4')+ Run-Check ($name+'-fixture') (Get-Command ffmpeg).Source ('-nostdin -v error -i "'+$clip+'" -f lavfi -i "sine=frequency=440:sample_rate=48000:duration=9" -t 9 -c:v copy -c:a aac "'+$input+'"')+ }+ if($name -eq 'masterreject'){$env:VEYRA_TEST_REJECT_NR_DISABLE='1'}else{$env:VEYRA_TEST_REJECT_NR_DISABLE=$oldReject}+ Run-Check $name $exe ('--smoke-seconds 14 --nr --no-sr --no-fg '+$flags+' "'+$input+'"')+ $log=Get-Content -LiteralPath $env:VEYRA_LOG_FILE -Raw+ if($name -eq 'switch'){+ $lines=@($log -split '\r?\n');$first=[Array]::FindIndex($lines,[Predicate[string]]{param($line) $line.Contains('[ui-mode]')});$last=[Array]::FindLastIndex($lines,[Predicate[string]]{param($line) $line.Contains('[ui-mode]')});$interval=($lines[$first..$last] -join "`n")+ if($interval -match 'CreateFeature id=|Create DLSSG|\[source-file\] opened|reset=1'){throw 'Mode interval recreated feature, source or history'}+ $submits=[regex]::Matches($interval,'\[submit\].*epoch=(\d+).*host100ns=(\d+)')+ $epochs=@($submits|ForEach-Object{$_.Groups[1].Value}|Select-Object -Unique);$times=@($submits|ForEach-Object{[long]$_.Groups[2].Value});$maxGap=0.0+ for($n=1;$n -lt $times.Count;$n++){$maxGap=[Math]::Max($maxGap,($times[$n]-$times[$n-1])/10000.0)}+ [ordered]@{submissionCount=$times.Count;epochs=$epochs;maxSubmissionGapMs=$maxGap;noCreateResetOrSourceOpen=$true}|ConvertTo-Json|Set-Content (Join-Path $runDir 'switch-submission.json')+ if($times.Count -lt 10 -or $epochs.Count -ne 1 -or $maxGap -gt 100){throw "Switch submission continuity failed: maxGap=$maxGap epochs=$($epochs.Count)"}+ }+ if($name -in @('switch','pause','export')){+ $matches=[regex]::Matches($log,'\[ui-mode\].*commandMs=([0-9.]+)')+ if($matches.Count -ne 40 -or $log -match 'hostSame=false|sessionSame=false|revisionSame=false'){throw 'Mode identity contract failed'}+ $values=@($matches|ForEach-Object{[double]$_.Groups[1].Value}|Sort-Object)+ $p95=$values[[int][Math]::Floor(($values.Count-1)*.95)]+ [ordered]@{count=$values.Count;p95Ms=$p95;maxMs=$values[-1];allMs=$values}|ConvertTo-Json -Depth 5|Set-Content (Join-Path $runDir ($name+'.mode-times.json'))+ if($p95 -gt 16 -or $values[-1] -gt 50){throw "Mode UI command threshold failed: p95=$p95 max=$($values[-1])"}+ }+ if($name -eq 'masterreject' -and $log -notmatch 'rejected bypass restored actual enabled UI'){throw 'Rejected master transaction UI evidence missing'}+ if($name -eq 'audio' -and ($log -notmatch 'target=0.5 reached=0.5' -or $log -notmatch 'target=0 reached=0')){throw 'Actual PCM gain/mute evidence missing'}+ if($name -in @('canceljob','exitjob')){+ if($name -eq 'exitjob' -and $log -notmatch 'parent close with active worker; cooperative cancellation requested'){throw 'Active-worker parent close marker missing'}+ $pidMatch=[regex]::Match($log,'\[export-worker\] started pid=(\d+)')+ if(-not $pidMatch.Success -or (Get-Process -Id ([int]$pidMatch.Groups[1].Value) -ErrorAction SilentlyContinue)){throw 'Worker orphan or missing start evidence'}+ if((Test-Path (Join-Path $runDir ($name+'.mp4'))) -or -not (Test-Path (Join-Path $runDir ($name+'.mp4.partial')))){throw 'Cancelled output protection failed'}+ if($name -eq 'canceljob' -and $log -notmatch 'cancelled=true foregroundContinues=true'){throw 'Foreground cancellation continuity missing'}+ }+ if($name -eq 'export'){+ if($log -notmatch 'foregroundAdvanced=true' -or $log -notmatch 'success=true foregroundFrames='){throw 'Concurrent export evidence missing'}+ $workerId=[regex]::Match($log,'\[export-worker\] started pid=(\d+)').Groups[1].Value+ $workerLog=Get-Content -LiteralPath (Join-Path $Root ('logs/export-worker-'+$workerId+'.log')) -Raw+ $frozen=[regex]::Match($log,'jobFrozenRevisionIndependent=true frozenRevision=(\d+) frozenIntensity=([0-9.]+)')+ if(-not $frozen.Success -or $workerLog -notmatch ('\[export-frozen\] revision='+$frozen.Groups[1].Value+' .*intensity='+[regex]::Escape($frozen.Groups[2].Value)+' ')){throw 'Actual worker frozen revision/intensity mismatch'}+ Run-Check 'concurrent-decode' (Get-Command ffmpeg).Source ('-nostdin -v error -i "'+(Join-Path $runDir 'concurrent.mp4')+'" -f null -')+ Run-Check 'concurrent-probe' (Get-Command ffprobe).Source ('-v error -show_streams -of json "'+(Join-Path $runDir 'concurrent.mp4')+'"')+ }+ }+ $passed=$true+}catch{$problem=$_.Exception.Message;Write-Host $problem}+finally{+ $env:VEYRA_LOG_FILE=$oldLog;$env:VEYRA_TEST_REJECT_NR_DISABLE=$oldReject;$timer.Stop()+ [ordered]@{runId=$runId;passed=$passed;case=$Case;seconds=$timer.Elapsed.TotalSeconds;perInvocationLimit=$MaxRuntimeSeconds;exeSha256=(Get-FileHash -LiteralPath $exe).Hash;items=$items;failure=$problem;limits=@('software short tests only','capture hardware reserved for user','physical scanout/photon latency unmeasured')}|ConvertTo-Json -Depth 8|Set-Content (Join-Path $runDir 'result.json')+ Write-Host "UI evidence=$runDir passed=$passed"+}+if($passed){exit 0}else{exit 1}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex fae6e1c2..1922047f 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -36,16 +36,18 @@ EngineController::~EngineController(){ {std::lock_guard lock(mutex_);shutdown_=tvoid EngineController::dispatch(){for(;;){std::function<void()> task;{std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return shutdown_||bool(pending_);});if(shutdown_)break;task=std::move(pending_);pending_={};busy_=true;stop_=false;}try{task();}catch(const std::exception&){status(L"任务异常,已停止;请查看诊断",true);}- {std::lock_guard lock(mutex_);busy_=false;snapshot_.running=false;}+ {std::lock_guard lock(mutex_);busy_=false;snapshot_.running=false;if(snapshot_.transport==TransportState::Stopping)snapshot_.transport=TransportState::Empty;}}}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_={};savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ {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_);}post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}-void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};}+void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}+void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}+void 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;@@ -54,8 +56,8 @@ void EngineController::saveFrame(const std::wstring& path){std::lock_guard lock(void EngineController::startExport(const std::wstring& input,const std::wstring& output,PlayerOptions opts,bool hevc){const auto frozen=opts.snapshot();post([this,input,output,frozen,hevc]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);bool ok=exportVideo(input,output,PlayerOptions::from(frozen),hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}-PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);return snapshot_;}-void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;}+PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;return copy;}+void EngineController::status(const std::wstring& s,bool failed){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.failed=failed;if(failed)snapshot_.transport=TransportState::Failed;}void EngineController::run(HWND window,std::wstring path,PlayerOptions options){CoInitializeEx(nullptr,COINIT_MULTITHREADED);status(L"正在初始化GPU与本地运行时…");@@ -93,15 +95,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){gd.runtimeAbsPath=std::filesystem::path(VEYRA_PROJECT_ROOT).wstring()+L"\\runtime_local\\nvidia";if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}if(isCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}- {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}+ {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,width,height,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时NR变化回填":L"原生NR(性能成本较高)"));pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false;std::deque<double> latenessSamples;- TimingWindow captureAges,scheduleWaits,processTimes,presentTimes;auto nextTimingLog=Clock::now()+std::chrono::seconds(1);+ TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;auto nextTimingLog=Clock::now()+std::chrono::seconds(1);auto anchor=Clock::now(),statsStart=anchor;double anchorMs=0;uint64_t frames=0,sourceFrames=0;bool wasPaused=false;double discardBefore=0;PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;DeadlineWait deadlineWait;auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};while(!stop_){+ const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);+ if(isCapture){const bool available=captureSource.setAudioGain(gain);std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;}EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;}const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;if(requested.revision!=previous.revision){@@ -116,7 +120,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}}else if(accepted)accepted=graph.applySettings(requested);if(accepted){options=next;gd=nextDesc;transaction=true;reset=true;}- else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.applying=false;snapshot_.status=L"设置应用失败,已恢复上一套参数";}+ else {std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"设置应用失败,已恢复上一套参数";}}std::wstring save;{std::lock_guard lock(mutex_);save.swap(savePath_);}if(!save.empty()&&hasOutput){sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();@@ -135,11 +139,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){const auto decodeStart=Clock::now();pipeline::FramePacket pkt;const AVFrame* frame=imageFrame;if(transaction&&cachedFrame){frame=cachedFrame;pkt=cachedPacket;}- else if(!isImage){auto rs=activeSource->read(pkt,&frame);if(rs==source::SourceReadStatus::Waiting)continue;if(rs==source::SourceReadStatus::Eos){status(L"视频已播放完毕");paused_=true;continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(L"视频解码或时间戳错误",true);break;}}+ else if(!isImage){auto rs=activeSource->read(pkt,&frame);if(rs==source::SourceReadStatus::Waiting)continue;if(rs==source::SourceReadStatus::Eos){status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}}const bool rereadCached=transaction&&frame==cachedFrame;if(isImage)pkt.sequence=1;if(!rereadCached)++sourceFrames;- const double decodeMs=elapsedMs(decodeStart);+ const double decodeMs=elapsedMs(decodeStart);decodeTimes.add(decodeMs);const double pts=isImage?0:pkt.pts.toDouble()*1000;if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}if(pts+0.1<discardBefore)continue;@@ -152,7 +156,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);gd=previousDesc;if(graph.initialize(gd)&&presenter.open(ctx,window,graph)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence)){- std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.applying=false;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;+ std::lock_guard lock(mutex_);if(desired_.revision==requested.revision)desired_=previous;snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_.revision!=previous.revision;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;}else{status(L"参数回滚失败,已停止",true);break;}}else{status(L"增强执行失败;请查看日志",true);break;}}@@ -164,17 +168,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){const auto duration100ns=pkt.duration.isUnknown()?200000:std::clamp<int64_t>(pkt.duration.to100ns(),83333,1000000);liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100,options.fg?duration100ns:0);}- if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;}anchor=Clock::now();anchorMs=pts;}+ if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;{std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;}}anchor=Clock::now();anchorMs=pts;}auto nowMs=[&](){const double a=audioStarted?audio.mediaTimeMs():-1;return a>=0?a:anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();};double frameWaitMs=0,framePresentMs=0;const auto readyStart=Clock::now();while(!stop_&&!paused_&&seekSeconds_<0&&!graph.resolveGeneration(out)){if(elapsedMs(readyStart)>2000){status(L"补帧 GPU 就绪超时",true);stop_=true;break;}- deadlineWait.slice();+ deadlineWait.slice(.2);}if(stop_)break;if(paused_||seekSeconds_>=0){reset=true;veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}- const double gpuWaitMs=elapsedMs(readyStart);+ const double gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);bool interrupted=false,presentFailed=false;for(uint32_t i=0;i<out.batch.count;++i){auto& item=out.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;@@ -205,6 +209,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=captureAges.p95();snapshot_.schedulingWaitP95Ms=scheduleWaits.p95();snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentTimes.p95();}+ if(!isCapture&&Clock::now()>=nextTimingLog){veyra::log::info("player-timing",std::format("decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} processed={}",decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),sourceFrames));nextTimingLog=Clock::now()+std::chrono::seconds(1);}if(isCapture&&Clock::now()>=nextTimingLog){veyra::log::info("capture-timing",std::format("received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} nr={} nvof={} generated={} (not HDMI-to-display latency)",captureStats.received,frames,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,captureAges.p95(),processTimes.p95(),scheduleWaits.p95(),presentTimes.p95(),graph.metrics().nrEvaluateCount,graph.metrics().nvofExecuteCount,graph.metrics().fgGeneratedFrames));nextTimingLog=Clock::now()+std::chrono::seconds(1);diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cppnew file mode 100644index 00000000..3105e66b--- /dev/null+++ b/src/engine/ExportJobManager.cpp@@ -0,0 +1,86 @@+#include "veyra/engine/ExportJobManager.h"+#include "veyra/engine/VideoExportJob.h"+#include "veyra/Log.h"+#include <filesystem>+#include <format>+#include <chrono>+#include <type_traits>+namespace veyra::engine {+namespace {+constexpr DWORD magic=0x56585931;+struct Shared {+ DWORD signature=magic,version=1,bytes=sizeof(Shared);+ EnhancementSettings settings;+ wchar_t input[32768]{},output[32768]{};+ unsigned hevc=0,maxFrames=0;+ volatile LONG64 sourceFrames=0,generated=0,holds=0,encoded=0;+ volatile LONG messageLock=0;wchar_t message[1024]{};+ volatile LONG cancel=0,pause=0,watching=0,state=LONG(ExportState::Preparing),progress=0;+};+static_assert(std::is_trivially_copyable_v<Shared>);+void close(HANDLE& h){if(h&&h!=INVALID_HANDLE_VALUE)CloseHandle(h);h=nullptr;}+const wchar_t* label(ExportState s){switch(s){case ExportState::Preparing:return L"正在准备独立导出任务";case ExportState::Running:return L"正在编码 · 原生NR · D3D12 NVENC";case ExportState::Paused:return L"导出已暂停,观看继续";case ExportState::Finishing:return L"正在封装和验证输出";case ExportState::Succeeded:return L"导出完成,输出解码验证通过";case ExportState::Failed:return L"导出失败;详见独立任务日志,partial已保留";case ExportState::Cancelled:return L"导出已取消;已写入的partial保留";default:return L"尚无导出任务";}}+}+struct ExportJobManager::Impl {+ HANDLE mapping=nullptr,process=nullptr,job=nullptr;Shared* shared=nullptr;+ ExportJobSnapshot snapshot;ULONGLONG cancelAt=0;+ void clear(){if(shared){UnmapViewOfFile(shared);shared=nullptr;}close(process);close(job);close(mapping);cancelAt=0;}+ ~Impl(){clear();}+};+ExportJobManager::ExportJobManager():p_(std::make_unique<Impl>()){}+ExportJobManager::~ExportJobManager(){cancel();if(p_->process)WaitForSingleObject(p_->process,5000);p_->clear();}+bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames){+ if(poll().active())return false;p_->clear();p_->snapshot={};+ auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;log::error("export-worker",std::format("launch failed error={}",error));return false;};+ if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.rfind(L"capture:",0)==0)return fail(L"请选择本地视频与有效导出设置");+ if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial"))return fail(L"输出或partial文件已存在,请选择新文件名");+ SECURITY_ATTRIBUTES sa{sizeof(sa),nullptr,TRUE};+ p_->mapping=CreateFileMappingW(INVALID_HANDLE_VALUE,&sa,PAGE_READWRITE,0,sizeof(Shared),nullptr);+ if(!p_->mapping)return fail(L"无法创建导出通信资源");+ p_->shared=static_cast<Shared*>(MapViewOfFile(p_->mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!p_->shared)return fail(L"无法映射导出通信资源");+ new(p_->shared) Shared{};auto& s=*p_->shared;s.settings=settings;s.settings.nrPolicy=pipeline::NrSizePolicy::Native;s.hevc=hevc;s.maxFrames=maxFrames;+ wcscpy_s(s.input,input.c_str());wcscpy_s(s.output,output.c_str());+ p_->job=CreateJobObjectW(nullptr,nullptr);JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ if(!p_->job||!SetInformationJobObject(p_->job,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))return fail(L"无法建立导出进程生命周期");+ SIZE_T bytes=0;InitializeProcThreadAttributeList(nullptr,1,0,&bytes);std::vector<std::byte> attrs(bytes);+ STARTUPINFOEXW si{};si.StartupInfo.cb=sizeof(si);si.StartupInfo.dwFlags=STARTF_USESHOWWINDOW;si.StartupInfo.wShowWindow=SW_HIDE;si.lpAttributeList=reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrs.data());+ if(!InitializeProcThreadAttributeList(si.lpAttributeList,1,0,&bytes))return fail(L"无法初始化导出进程");+ const bool attr=UpdateProcThreadAttribute(si.lpAttributeList,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,&p_->mapping,sizeof(HANDLE),nullptr,nullptr)!=FALSE;+ wchar_t exe[32768]{};GetModuleFileNameW(nullptr,exe,32768);auto cmd=std::format(L"\"{}\" --export-worker {}",exe,reinterpret_cast<uintptr_t>(p_->mapping));PROCESS_INFORMATION pi{};+ const bool started=attr&&CreateProcessW(exe,cmd.data(),nullptr,nullptr,TRUE,EXTENDED_STARTUPINFO_PRESENT|CREATE_SUSPENDED|CREATE_NO_WINDOW|BELOW_NORMAL_PRIORITY_CLASS,nullptr,nullptr,&si.StartupInfo,&pi);+ DeleteProcThreadAttributeList(si.lpAttributeList);SetHandleInformation(p_->mapping,HANDLE_FLAG_INHERIT,0);+ if(!started)return fail(L"无法启动导出进程");p_->process=pi.hProcess;+ if(!AssignProcessToJobObject(p_->job,p_->process)){TerminateProcess(p_->process,1);CloseHandle(pi.hThread);return fail(L"导出进程隔离失败");}+ if(ResumeThread(pi.hThread)==DWORD(-1)){TerminateProcess(p_->process,1);CloseHandle(pi.hThread);return fail(L"无法运行导出进程");}CloseHandle(pi.hThread);+ p_->snapshot.state=ExportState::Preparing;p_->snapshot.output=output;p_->snapshot.jobId=(GetTickCount64()<<16)^pi.dwProcessId;p_->snapshot.frozenRevision=settings.revision;p_->snapshot.frozen=s.settings;+ log::info("export-worker",std::format("started pid={} frozenRevision={} nativeNR=true independentPlayback=true",pi.dwProcessId,settings.revision));return true;+}+void ExportJobManager::cancel(){if(p_->shared&&p_->snapshot.active()){InterlockedExchange(&p_->shared->cancel,1);if(!p_->cancelAt)p_->cancelAt=GetTickCount64();}}+void ExportJobManager::pause(bool v){if(p_->shared)InterlockedExchange(&p_->shared->pause,v);}+void ExportJobManager::watching(bool v){if(p_->shared)InterlockedExchange(&p_->shared->watching,v);}+ExportJobSnapshot ExportJobManager::poll(){+ if(!p_->shared)return p_->snapshot;+ auto& s=*p_->shared;p_->snapshot.sourceFrames=InterlockedCompareExchange64(&s.sourceFrames,0,0);p_->snapshot.generated=InterlockedCompareExchange64(&s.generated,0,0);p_->snapshot.holds=InterlockedCompareExchange64(&s.holds,0,0);p_->snapshot.encoded=InterlockedCompareExchange64(&s.encoded,0,0);p_->snapshot.state=static_cast<ExportState>(InterlockedCompareExchange(&s.state,0,0));p_->snapshot.progress=InterlockedCompareExchange(&s.progress,0,0)/10000.0;+ if(p_->cancelAt&&GetTickCount64()-p_->cancelAt>5000&&WaitForSingleObject(p_->process,0)==WAIT_TIMEOUT)TerminateJobObject(p_->job,3);+ if(WaitForSingleObject(p_->process,0)==WAIT_OBJECT_0){DWORD code=1;GetExitCodeProcess(p_->process,&code);p_->snapshot.state=code==0?ExportState::Succeeded:code==3||p_->cancelAt?ExportState::Cancelled:ExportState::Failed;if(code==0)p_->snapshot.progress=1;p_->snapshot.message=label(p_->snapshot.state);p_->clear();}+ if(p_->shared&&InterlockedCompareExchange(&p_->shared->messageLock,1,0)==0){if(p_->shared->message[0])p_->snapshot.message=p_->shared->message;InterlockedExchange(&p_->shared->messageLock,0);}if(p_->snapshot.message.empty()||p_->snapshot.state==ExportState::Paused||p_->snapshot.state==ExportState::Cancelled)p_->snapshot.message=label(p_->snapshot.state);return p_->snapshot;+}+int runExportWorker(HANDLE mapping){+ auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;+ if(s->signature!=magic||s->version!=1||s->bytes!=sizeof(Shared)||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}+ Logger::instance().openFile((std::filesystem::path(VEYRA_PROJECT_ROOT)/"logs"/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());+ const auto settings=s->settings;log::info("export-frozen",std::format("revision={} nr={} sr={} multiplier={} intensity={} tone={} structure={} skin={} style={} autoMask={} ui={} total={} darken={} brighten={} color={} luminance={} flow={} content={} nativeNR=true",settings.revision,settings.nr,settings.sr,settings.multiplier,settings.model.intensity,settings.model.tone,settings.model.structure,settings.model.skin,settings.model.style,settings.model.autoMask,settings.model.uiCorrection,settings.residual.total,settings.residual.darken,settings.residual.brighten,settings.residual.color,settings.residual.luminance,int(settings.flow),int(settings.content)));std::atomic<bool> cancel=false,done=false;+ std::thread monitor([&]{while(!done){if(InterlockedCompareExchange(&s->cancel,0,0))cancel=true;std::this_thread::sleep_for(std::chrono::milliseconds(10));}});+ auto frameBoundary=[&]{+ while(!cancel&&InterlockedCompareExchange(&s->pause,0,0)){InterlockedExchange(&s->state,LONG(ExportState::Paused));std::this_thread::sleep_for(std::chrono::milliseconds(20));}+ InterlockedExchange(&s->state,LONG(ExportState::Running));+ // Yield only between complete source frames. No source-frame drops or+ // quality changes. Both contexts still share the physical GPU budget.+ if(InterlockedCompareExchange(&s->watching,0,0))for(int i=0;i<5&&!cancel;++i)std::this_thread::sleep_for(std::chrono::milliseconds(10));+ return !cancel;+ };+ bool ok=false;try{ok=exportVideo(s->input,s->output,PlayerOptions::from(settings),s->hevc!=0,cancel,[&](double p,const std::wstring& message){if(InterlockedCompareExchange(&s->messageLock,1,0)==0){wcsncpy_s(s->message,message.c_str(),_TRUNCATE);InterlockedExchange(&s->messageLock,0);}+InterlockedExchange(&s->progress,LONG(std::clamp(p,0.0,.999)*10000));if(message==L"正在封装和验证输出")InterlockedExchange(&s->state,LONG(ExportState::Finishing));},s->maxFrames,frameBoundary,[&](const ExportCounts& count){InterlockedExchange64(&s->sourceFrames,count.source);InterlockedExchange64(&s->generated,count.generated);InterlockedExchange64(&s->holds,count.holds);InterlockedExchange64(&s->encoded,count.encoded);});}catch(...){log::error("export-worker","unhandled job exception");}+ done=true;monitor.join();InterlockedExchange(&s->state,LONG(ok?ExportState::Succeeded:cancel?ExportState::Cancelled:ExportState::Failed));UnmapViewOfFile(s);CloseHandle(mapping);return ok?0:cancel?3:1;+}+}diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex 0f88a9e5..0b029c91 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -17,7 +17,7 @@ extern "C" {}namespace veyra::engine {namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }-bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames){+bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptions options,bool hevc,std::atomic<bool>& cancel,const std::function<void(double,const std::wstring&)>& progress,unsigned maxFrames,const std::function<bool()>& frameBoundary,const std::function<void(const ExportCounts&)>& counts){if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial")){progress(0,L"目标或partial文件已存在,请使用其他名称");return false;}gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();@@ -70,7 +70,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiauto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;- while(!cancel){pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}+ while(!cancel){if(frameBoundary&&!frameBoundary())break;pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){error=true;break;}if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();const double expectedPts=timeline.expected(sourceCount);if(!timeline.accepts(sourceCount,packet.pts.toDouble())){@@ -96,7 +96,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiauto& real=out.batch.frames[out.batch.count-1];if(!enc.encode(real.lease->slot,false,outputIndex++)){error=true;break;}real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;- ++sourceCount;progress(info.duration.toDouble()>0?packet.pts.toDouble()/info.duration.toDouble():0,std::format(L"正在导出:{}张源帧 / {}张编码帧(D3D12 NVENC)",sourceCount,outputIndex));+ ++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});progress(info.duration.toDouble()>0?std::clamp((packet.pts.toDouble()-videoOriginSeconds)/info.duration.toDouble(),0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧(D3D12 NVENC)",sourceCount,outputIndex));if(maxFrames&&sourceCount>=maxFrames)break;}if(error||cancel)break;@@ -104,11 +104,11 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiif(error)break;veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1));if(!enc.finish()||!writeAudioUntil(audioEndSeconds)||av_write_trailer(mux)<0)break;- ok=written>0;+ ok=written>0;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});}while(false); }catch(const std::exception&){progress(0,L"导出异常,已保留partial,请查看诊断");ok=false;}enc.close();if(mux){if(mux->pb)avio_closep(&mux->pb);avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();- if(ok){source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;pipeline::FramePacket pkt;const AVFrame* frame=nullptr;ok=check.open(od)&&check.read(pkt,&frame)==source::SourceReadStatus::Frame;check.close();if(ok)ok=MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;}+ if(ok){progress(.999,L"正在封装和验证输出");source::MediaFileSource check;source::SourceOpenDesc od;od.path=partial;od.preferHardwareDecode=false;pipeline::FramePacket pkt;const AVFrame* frame=nullptr;ok=check.open(od)&&check.read(pkt,&frame)==source::SourceReadStatus::Frame;check.close();if(ok)ok=MoveFileExW(partial.c_str(),output.c_str(),MOVEFILE_WRITE_THROUGH)!=FALSE;}progress(ok?1:0,ok?L"视频导出完成,解码回读成功":cancel?L"导出已取消,partial文件已保留":L"视频导出失败,partial文件已保留,请查看诊断");return ok;}}diff --git a/src/media/FFmpegVideoDecoder.cpp b/src/media/FFmpegVideoDecoder.cppindex e8b823cd..a1b083cb 100644--- a/src/media/FFmpegVideoDecoder.cpp+++ b/src/media/FFmpegVideoDecoder.cpp@@ -10,6 +10,7 @@ extern "C" {}#include <format>+#include <algorithm>#include "veyra/Log.h"@@ -36,7 +37,7 @@ FFmpegVideoDecoder::~FFmpegVideoDecoder()}bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,- int streamTimeBaseNum, int streamTimeBaseDen)+ int streamTimeBaseNum, int streamTimeBaseDen, unsigned softwareThreads){if (context_ != nullptr) {close();@@ -62,10 +63,12 @@ bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,avcodec_free_context(&context_);return false;}- // Single-threaded decode: frame-threading adds a ~thread-count output- // delay, which deadlocks bounded in-flight pumps like the Phase 3- // pipeline (Playbook: decoded-ready queue cap 1..4).- context_->thread_count = 1;+ // Legacy bounded packet pumps keep the default single thread. The file+ // source can supply compressed lookahead until receiveFrame succeeds and+ // explicitly opts into at most four codec workers; no application frame+ // queue and no capture lookahead are introduced.+ context_->thread_count = int(std::clamp(softwareThreads,1u,4u));+ context_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;if (avcodec_open2(context_, codec, nullptr) < 0) {log::error("media", "decoder: avcodec_open2 failed");avcodec_free_context(&context_);@@ -79,8 +82,8 @@ bool FFmpegVideoDecoder::openSoftware(const AVCodecParameters* codecParameters,}stats_ = DecoderStats{};- log::info("media", std::format("decoder: software decoder opened codec={} {}x{} pixFmt={}",- codec->name, context_->width, context_->height, static_cast<int>(context_->pix_fmt)));+ log::info("media", std::format("decoder: software decoder opened codec={} {}x{} pixFmt={} threads={} activeThreadType={}",+ codec->name, context_->width, context_->height, static_cast<int>(context_->pix_fmt),context_->thread_count,context_->active_thread_type));return true;}diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex b1494d75..30385e59 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -695,11 +695,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameconst int* coefficients=sws_getCoefficients(colorSpace);const int full=frame->color_range==AVCOL_RANGE_JPEG?1:0;if(sws_setColorspaceDetails(nv12Ctx_,coefficients,full,coefficients,full,0,1<<16,1<<16)<0)return false;- uint8_t* planes[2] = { nv12Buf_.data(), nv12Buf_.data() + lumaSize_ };+ // Planar 8-bit YUV already exposes CPU luma for cadence analysis.+ // Convert directly into the fenced upload slot instead of writing and+ // copying another full NV12 frame. Never sample write-combined memory.+ const bool directUpload=frame->format==AV_PIX_FMT_YUV420P||frame->format==AV_PIX_FMT_YUVJ420P||frame->format==AV_PIX_FMT_NV12;+ uint8_t* planes[2] = { directUpload?mappedLuma_[parity]:nv12Buf_.data(), directUpload?mappedChroma_[parity]:nv12Buf_.data() + lumaSize_ };const int strides[2] = { static_cast<int>(lumaPitch_), static_cast<int>(chromaPitch_) };sws_scale(nv12Ctx_, frame->data, frame->linesize, 0, frame->height, planes, strides);std::vector<uint8_t> sample;sample.reserve(64*36);std::vector<double> hist(256,0);double sad=0;- for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=planes[0][size_t(y*srcH_/36)*lumaPitch_+x*srcW_/64];hist[v]+=1.0/(64*36);sample.push_back(v);}+ for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=directUpload?frame->data[0][ptrdiff_t(y*srcH_/36)*frame->linesize[0]+x*srcW_/64]:planes[0][size_t(y*srcH_/36)*lumaPitch_+x*srcW_/64];hist[v]+=1.0/(64*36);sample.push_back(v);}if(previousLuma_.size()==sample.size())for(size_t i=0;i<sample.size();++i)sad+=std::abs(int(sample[i])-int(previousLuma_[i]))/(255.0*sample.size());cadence_.observe(ptsMs,sad,previousLuma_.size()==sample.size());out.measuredContentRate=cadence_.confirmedRate(desc_.contentRate);@@ -708,10 +712,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frameconst auto analysis=scene_.analyze(realFrameIndex_,hist,sad,static_cast<uint64_t>(std::max(0.0,ptsMs)*1000));if(analysis.isSceneCut||analysis.isCadenceBreak){reset=true;prevValid_=false;if(analysis.isSceneCut)++metrics_.sceneCutCount;}previousLuma_=std::move(sample);- for (uint32_t y = 0; y < srcH_; ++y)+ 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_);+ std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, srcW_);}auto copyPlane = [&](ID3D12Resource* texture, ID3D12Resource* upload,DXGI_FORMAT format, UINT width, UINT height, UINT pitch) {tracker_.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex f2fb4806..e67c6cc1 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -1,3 +1,4 @@+#include "veyra/sink/AudioGain.h"// WasapiAudioSink implementation - moved verbatim from tools/player_probe// main.cpp (lines ~172-686, Phase 6 session evidence). Semantics preserved:// watermarked bounded production ring, event-driven pump, PTS-anchored master@@ -285,6 +286,9 @@ bool AudioRenderer::pumpOnce(AudioPipeline& pipeline, double* firstWrittenPtsMs)BYTE* dest = nullptr;if (FAILED(render_->GetBuffer(avail, &dest))) return false;if (got > 0) {+ const float target=std::clamp(gain_.load(),0.0f,1.0f);+ applyStereoGain(chunk_.data(),got,target,smoothedGain_);+ if(target!=loggedGain_&&std::abs(smoothedGain_-target)<.00001f){loggedGain_=target;log::info("audio-gain",std::format("target={} reached={} framesWritten={} clockPreserved=true applicationPCM=true",target,smoothedGain_,framesWritten_));}std::memcpy(dest, chunk_.data(), got * 8);if (got < avail) {std::memset(dest + got * 8, 0, (avail - got) * 8);diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex e9caf9f5..a9203dd9 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -38,6 +38,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {uint64_t received=0,dropped=0,lastDrop=0,sequence=0;Clock::time_point pendingArrival{},readArrival{},firstArrival{},latestArrival{};ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;+ float lastAudioGain=-1;bool audioGainSupported=false;SourceInfo info;bool bottomUp=true;unsigned stride=0;Clock::time_point lastFrame;HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{return --refs;}@@ -71,8 +72,15 @@ std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<stdstd::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;std::vector<CaptureFormat> out;if(!configuration(device,g,b,f,c))return out;int count=0,size=0;if(FAILED(c->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;std::vector<BYTE> caps(size);for(int i=0;i<count;++i){AM_MEDIA_TYPE* t=nullptr;if(FAILED(c->GetStreamCaps(i,&t,caps.data())))continue;BITMAPINFOHEADER* bm=nullptr;REFERENCE_TIME duration=0;if(t->formattype==FORMAT_VideoInfo&&t->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* vi=reinterpret_cast<VIDEOINFOHEADER*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}else if(t->formattype==FORMAT_VideoInfo2&&t->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* vi=reinterpret_cast<VIDEOINFOHEADER2*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}if(bm&&bm->biWidth>0&&bm->biWidth<=3840&&abs(bm->biHeight)<=2160&&duration>0){unsigned w=bm->biWidth,h=abs(bm->biHeight);double fps=1e7/duration;if((w==1920&&h==1080||w==3840&&h==2160)&&fps>=29&&fps<=61)out.push_back({i,w,h,fps,std::format(L"{} x {} @ {:.2f} fps [format {}]",w,h,fps,i)});}freeType(t);}return out;}const SourceInfo& CaptureCardSource::info()const{return p_->info;}+bool CaptureCardSource::setAudioGain(float gain){+ auto& p=*p_;if(!p.graph||!p.audioFilter)return false;+ if(gain==p.lastAudioGain)return p.audioGainSupported;+ ComPtr<IBasicAudio> audio;HRESULT hr=p.graph.As(&audio);+ if(SUCCEEDED(hr)){long attenuation=gain<=0?-10000:long(std::clamp(2000.0*std::log10(double(gain)),-10000.0,0.0));hr=audio->put_Volume(attenuation);}+ p.lastAudioGain=gain;p.audioGainSupported=SUCCEEDED(hr);log::info("capture-audio",std::format("application gain={} hr=0x{:X}",gain,unsigned(hr)));return p.audioGainSupported;+}bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}-bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();auto& p=*p_;unsigned index=0;int format=0,audio=-1;if(swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d",&index,&format,&audio)!=3)return false;+bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAudioGain=-1;auto& p=*p_;unsigned index=0;int format=0,audio=-1;if(swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d",&index,&format,&audio)!=3)return false;if(!configuration(index,p.graph,p.builder,p.device,p.config))return false;int count=0,size=0;if(FAILED(p.config->GetNumberOfCapabilities(&count,&size))||format<0||format>=count||size<=0||size>65536)return false;std::vector<BYTE> caps(size);AM_MEDIA_TYPE* native=nullptr;if(FAILED(p.config->GetStreamCaps(format,&native,caps.data())))return false;HRESULT hr=p.config->SetFormat(native);freeType(native);if(FAILED(hr))return false;if(FAILED(CoCreateInstance(SampleGrabberClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.grabFilter)))||FAILED(p.grabFilter.As(&p.grab))||FAILED(p.graph->AddFilter(p.grabFilter.Get(),L"Latest frame mailbox")))return false;diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex 3328d683..29143c51 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -117,7 +117,7 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)}if (!decoderOpen) {decoderOpen = decoder_.openSoftware(params, demuxer_.videoTimeBaseNum(),- demuxer_.videoTimeBaseDen());+ demuxer_.videoTimeBaseDen(), params->width>1920||params->height>1080?4u:1u);}if (!decoderOpen) {veyra::log::error("source-file", "decoder open failed");diff --git a/tests/integration/MediaFileSourceTests.cpp b/tests/integration/MediaFileSourceTests.cppindex f4136f54..44883b87 100644--- a/tests/integration/MediaFileSourceTests.cpp+++ b/tests/integration/MediaFileSourceTests.cpp@@ -5,6 +5,12 @@// and EOS drain. Requires the corpus (generated by veyra_clip_gen).#include <cstdio>#include <string>+#include <vector>+#include <cstring>+extern "C" {+#include <libavutil/frame.h>+#include <libavutil/adler32.h>+}#include "veyra/source/MediaFileSource.h"@@ -24,11 +30,61 @@ void check(const char* name, bool ok) {} // namespace+// A short 4K B-frame fixture exercises codec lookahead, EOS drain and a seek+// after EOS. Compare every pixel (excluding row padding) and PTS against the+// existing single-thread decoder; counts alone would miss stale/reordered data.+int threadedFileTest(const std::wstring& clip) {+ struct Signature { int64_t pts; uint32_t pixels; };+ auto signature=[](const AVFrame* f) {+ uint32_t crc=1;+ for(int plane=0;plane<3;++plane) {+ const int w=plane?f->width/2:f->width,h=plane?f->height/2:f->height;+ for(int y=0;y<h;++y) crc=av_adler32_update(crc,f->data[plane]+ptrdiff_t(y)*f->linesize[plane],w);+ }+ return Signature{f->pts,crc};+ };+ media::FFmpegDemuxer demux;+ media::FFmpegVideoDecoder decoder;+ if(!demux.open(clip)||!decoder.openSoftware(demux.videoCodecParameters(),demux.videoTimeBaseNum(),demux.videoTimeBaseDen(),1)) return 1;+ std::vector<Signature> reference;+ bool draining=false;+ for(int guard=0;guard<1000;++guard) {+ if(const AVFrame* f=decoder.receiveFrame()) {+ if(f->format!=AV_PIX_FMT_YUV420P||f->width!=3840||f->height!=2160) return 1;+ reference.push_back(signature(f));+ } else if(draining) break;+ else { bool eof=false; if(demux.readVideoPacket(eof)) { if(!decoder.sendPacket(demux.currentPacket())) return 1; }+ else { if(!eof||!decoder.sendPacket(nullptr)) return 1; draining=true; } }+ }+ check("threaded:reference-drained-24",draining&&reference.size()==24);+ if(reference.size()!=24) return 1;+ MediaFileSource src;SourceOpenDesc desc;desc.path=clip;desc.preferHardwareDecode=false;+ if(!src.open(desc)) return 1;+ for(int pass=0;pass<2;++pass) {+ if(pass) check("threaded:seek-after-EOS",src.seek(pipeline::Rational{0,1}));+ size_t count=0;bool matches=true,monotonic=true;SourceReadStatus status=SourceReadStatus::Error;+ pipeline::FramePacket packet;const AVFrame* frame=nullptr;+ while(count<100&&(status=src.read(packet,&frame))==SourceReadStatus::Frame) {+ const auto actual=signature(frame);+ matches=matches&&count<reference.size()&&actual.pts==reference[count].pts&&actual.pixels==reference[count].pixels;+ if(count&&count<reference.size()) monotonic=monotonic&&actual.pts>reference[count-1].pts;+ if(pass&&count==0) check("threaded:seek-epoch-flag",packet.sourceEpoch==src.epoch()&&(packet.flags&static_cast<uint32_t>(pipeline::FrameFlagBits::Seek))!=0);+ ++count;+ }+ check("threaded:EOS-exact-count",status==SourceReadStatus::Eos&&count==reference.size());+ check("threaded:every-pixel-and-PTS-equal",matches);+ check("threaded:PTS-monotonic",monotonic);+ }+ std::printf("threaded-file: %d checks, %d failures\n",g_checks,g_failures);+ return g_failures?1:0;+}+int main(int argc, char** argv) {std::wstring clip = L"loop/local/fixed_clips/corpus/translation_1080p60.mp4";if (argc > 1) {clip.assign(argv[1], argv[1] + std::strlen(argv[1]));}+ if(argc>2&&std::strcmp(argv[2],"--threaded")==0) return threadedFileTest(clip);std::printf("source-file: open + metadata\n");MediaFileSource src;diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cppnew file mode 100644index 00000000..f08817e4--- /dev/null+++ b/tests/unit/UiContractTests.cpp@@ -0,0 +1,20 @@+#include "../../apps/veyra/ui/UiSessionState.h"+#include "../../apps/veyra/ui/WorkspaceChrome.h"+#include "../../apps/veyra/ui/UiPreferenceStore.h"+#include "veyra/sink/AudioGain.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;+ 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");+ for(int dpi:{96,120,144,192})for(int width:{720,900,960,1180,1280,1920})for(int height:{540,720,800,1080})for(bool pro:{false,true})for(bool drawer:{false,true}){+ ui::ChromeLayout l(width,height,pro,drawer);require(l.left>=0&&l.top>=0&&l.viewWidth>0&&l.viewHeight>0,"nonnegative viewport");require(l.left+l.viewWidth<=width&&l.top+l.viewHeight<=height,"viewport contained");if(pro&&(width>=960||drawer))require(l.left+l.viewWidth<l.right&&l.right+l.panelWidth<=width,"disjoint inspector");+ require(MulDiv(l.viewWidth,dpi,96)>0,"DPI physical extent");+ }+ std::vector<float> tone(4800*2,1);float gain=1;sink::applyStereoGain(tone.data(),4800,.5f,gain);require(std::abs(gain-.5f)<1e-6,"gain ramp reaches half");for(size_t i=480;i<tone.size();++i)require(std::abs(tone[i]-.5f)<1e-6,"actual PCM scaled");tone.assign(tone.size(),1);sink::applyStereoGain(tone.data(),4800,0,gain);require(gain==0,"mute reaches zero");for(size_t i=480;i<tone.size();++i)require(tone[i]==0,"muted PCM exactly zero");+ if(argc>1){auto dir=std::filesystem::path(argv[1]);ui::UiPreferenceStore prefs(dir);ui::UiPreferences p;p.volume=.45f;p.muted=true;p.inspector=3;p.width=1180;require(prefs.save(p,&before),"atomic preferences save");ui::UiPreferenceStore loaded(dir);auto restored=loaded.load();require(restored.volume==p.volume&&restored.muted&&restored.inspector==3,"preferences round trip");auto setting=loaded.startup({});before.revision=setting.revision;require(setting==before,"all confirmed parameters round trip");auto path=dir/"ui-preferences.v1";{std::ofstream bad(path);bad<<"UNKNOWN 9 invalid";}ui::UiPreferenceStore damaged(dir);damaged.load();require(!damaged.save(p,nullptr),"corrupt preference cannot be overwritten");std::ifstream f(path);std::string data((std::istreambuf_iterator<char>(f)),{});require(data=="UNKNOWN 9 invalid","corrupt original preserved");}+ std::cout<<"PASS: mode/bypass, 384 layout cases at four DPI scales, actual PCM gain/mute, confirmed settings persistence/corruption\n";return 0;+}catch(const std::exception& e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}}