Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
fix: unified repair batches 1-6 (UI, logging, capture threads, decode, engine hot path, crash handling)
Veyra Goal Agente11aa566c0b8
diff --git a/CMakeLists.txt b/CMakeLists.txtindex b368b367..2465796f 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -894,7 +894,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformendif()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)+ target_link_libraries(veyra PRIVATE veyra_engine comctl32 comdlg32 shell32 dbghelp)add_dependencies(veyra veyra_shader_present_blit)# matrix executes through the shared product libraries only.diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex d969dbda..6a294953 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -272,10 +272,14 @@ void loadColourFoldState(){colorFoldMask=preferences.colourFoldMask;}void saveColourFoldState(){+ // One load+save per click is unavoidable while the store is a whole-file+ // document; skip the write when the mask did not change.+ static uint32_t lastSavedMask=UINT32_MAX;+ if(lastSavedMask==colorFoldMask)return;veyra::ui::UiPreferenceStore store_(runtime::localDataDirectory());auto preferences=store_.load();preferences.colourFoldMask=colorFoldMask;- if(!store_.save(preferences,nullptr))veyra::log::warn("color-ui","fold state not saved");+ if(!store_.save(preferences,nullptr))veyra::log::warn("color-ui","fold state not saved");else lastSavedMask=colorFoldMask;}void layoutColorPage(int bodyWidthDip){auto place=[&](int id,int y,int height,bool hidden,int x=-1,int w=-2){@@ -891,7 +895,7 @@ bool colourFieldEdited(int index,float value){syncColorControls();return true;}-void message(const std::wstring& text){if(statusSink)statusSink(text);else putText(401,text.c_str());}+void message(const std::wstring& text){static std::wstring last;if(text==last)return;last=text;if(statusSink)statusSink(text);else putText(401,text.c_str());}bool submit(engine::EnhancementSettings s){if(!apply(s)){dirty=true;message(L"修改未接受,请查看状态栏或日志;若总增强正在切换,请稍后重试。");return false;}dirty=false;return true;}void syncProtection(const engine::ProtectionSettings& protection){const bool wasPopulating=populating;populating=true;@@ -1214,7 +1218,7 @@ void arrange(){auto batch=BeginDeferWindowPos(int(items.size()));for(auto& entry:items){bool fixed=entry.page==-1,visible=!entry.hidden&&(entry.page==page||fixed)&&(GetDlgCtrlID(entry.h)!=1120||smoothMotionHelpExpanded);int w=entry.w<0?width-entry.x-12:entry.w;int y=fixed?(GetDlgCtrlID(entry.h)==400?0:(GetDlgCtrlID(entry.h)==211||GetDlgCtrlID(entry.h)==219)?86:42):entry.y+helpOffset(entry)-scroll;if(fixed){SetWindowPos(entry.h,nullptr,dip(window,entry.x),dip(window,y),dip(window,std::max(1,w)),dip(window,42),SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOREDRAW);continue;}batch=DeferWindowPos(batch,entry.h,nullptr,dip(window,entry.x),dip(window,y),dip(window,std::max(1,w)),dip(window,entry.height),SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOREDRAW|SWP_NOCOPYBITS|(visible?SWP_SHOWWINDOW:SWP_HIDEWINDOW));}- EndDeferWindowPos(batch);RedrawWindow(body,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);InvalidateRect(window,nullptr,FALSE);+ EndDeferWindowPos(batch);RedrawWindow(body,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);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|WS_CLIPSIBLINGS|style,0,0,1,1,group==-1?window:body,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(h,WM_SETFONT,WPARAM(font),TRUE);themeControl(h);if(group!=-1)SetWindowSubclass(h,scrollOnly,950,0);items.push_back({h,group,x,y,width,height});return h;}diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cppindex 084239c9..3fdd8a67 100644--- a/apps/veyra/TelemetryWindow.cpp+++ b/apps/veyra/TelemetryWindow.cpp@@ -40,7 +40,17 @@ void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色<<L"\r\n命令槽占用 "<<c.commandSlotsInFlight<<L" / 6;观察峰值 "<<c.commandSlotHighWater<<L";呈现批次峰值 "<<c.presentationBatchHighWater<<L" / 2"<<L"\r\n槽复用等待 "<<f.slotReuseWaitCount<<L" 次 / "<<value(f.slotReuseWaitMs)<<L" ms\r\n";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;- setText(GetDlgItem(window,1),o.str());+ // Preserve the reader's scroll position and selection across the+ // 250 ms refresh (the text differs almost every tick).+ HWND edit=GetDlgItem(window,1);+ const auto firstLine=SendMessageW(edit,EM_GETFIRSTVISIBLELINE,0,0);+ DWORD selStart=0,selEnd=0;SendMessageW(edit,EM_GETSEL,WPARAM(&selStart),LPARAM(&selEnd));+ const auto text=o.str();+ wchar_t old[8]{};GetWindowTextW(edit,old,8);+ SetWindowTextW(edit,text.c_str());+ if(selEnd>selStart)SendMessageW(edit,EM_SETSEL,selStart,selEnd);+ const auto nowFirst=SendMessageW(edit,EM_GETFIRSTVISIBLELINE,0,0);+ if(firstLine!=nowFirst)SendMessageW(edit,EM_LINESCROLL,0,firstLine-nowFirst);}void arrange(){RECT r{};GetClientRect(window,&r);int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window)),height=MulDiv(r.bottom,96,veyra::ui::layoutDpi(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);};@@ -50,7 +60,7 @@ case WM_PAINT:{PaintBuffer paint(h);fillSurface(paint.dc,paint.rect,h);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_TIMER:if(!IsWindowVisible(h))return 0;refresh();return 0;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",runtime::logsDirectory().c_str(),nullptr,nullptr,SW_SHOW);return 0;diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cppindex f98d64cf..af7f15bb 100644--- a/apps/veyra/main.cpp+++ b/apps/veyra/main.cpp@@ -3,7 +3,38 @@#include "veyra/RuntimePaths.h"#include "veyra/engine/FgCompatibilityProbe.h"#include <shellapi.h>+#include <dbghelp.h>+#include <format>+#include <filesystem>+#include <string>int runVeyraApp(HINSTANCE,int);+namespace {+// Last-chance handler: NGX/XeSS/driver faults are structured exceptions the+// C++ catch in the engine worker never sees, so the final 250 ms of buffered+// log and any crash context were lost (sweep 2026-09-22 B2). Write a+// minidump next to the log, flush the logger, then let Windows terminate.+std::wstring crashDumpDirectory;+LONG WINAPI crashFilter(EXCEPTION_POINTERS* info){+ static LONG entered=0;if(InterlockedIncrement(&entered)>1)return EXCEPTION_CONTINUE_SEARCH;+ const auto code=info&&info->ExceptionRecord?info->ExceptionRecord->ExceptionCode:0u;+ const auto address=info&&info->ExceptionRecord?reinterpret_cast<uintptr_t>(info->ExceptionRecord->ExceptionAddress):0u;+ veyra::log::error("crash",std::format("unhandled exception code=0x{:08X} address=0x{:X} thread={}",code,address,GetCurrentThreadId()));+ SYSTEMTIME st{};GetLocalTime(&st);+ wchar_t name[96]{};+ swprintf_s(name,L"veyra-crash-%04u%02u%02u-%02u%02u%02u-%lu.dmp",unsigned(st.wYear),unsigned(st.wMonth),unsigned(st.wDay),unsigned(st.wHour),unsigned(st.wMinute),unsigned(st.wSecond),GetCurrentProcessId());+ const std::wstring path=(std::filesystem::path(crashDumpDirectory)/name).wstring();+ HANDLE file=CreateFileW(path.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);+ if(file!=INVALID_HANDLE_VALUE){+ MINIDUMP_EXCEPTION_INFORMATION mei{GetCurrentThreadId(),info,FALSE};+ const BOOL ok=MiniDumpWriteDump(GetCurrentProcess(),GetCurrentProcessId(),file,MiniDumpWithIndirectlyReferencedMemory,info?&mei:nullptr,nullptr,nullptr);+ CloseHandle(file);+ veyra::log::error("crash",std::format("minidump written={} path={}",ok!=FALSE,std::filesystem::path(path).string()));+ }else veyra::log::error("crash",std::format("minidump open failed error={}",GetLastError()));+ veyra::Logger::instance().flush();+ if(GetEnvironmentVariableW(L"VEYRA_TEST_RAISE_SEH",nullptr,0))return EXCEPTION_EXECUTE_HANDLER;+ return EXCEPTION_CONTINUE_SEARCH;+}+}int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);if(argv&&argc==3&&std::wstring_view(argv[1])==L"--fg-compat-probe"){@@ -24,6 +55,15 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){}veyra::log::info("app", "Veyra GUI session started");veyra::Logger::instance().flush();+ crashDumpDirectory=logPath.parent_path().wstring();+ SetUnhandledExceptionFilter(crashFilter);+ if(GetEnvironmentVariableW(L"VEYRA_TEST_RAISE_SEH",nullptr,0)){+ // Diagnostic: raise a structured exception after startup to verify+ // the dump/flush path; the filter then returns EXECUTE_HANDLER so the+ // process exits with the exception code instead of hanging on WER.+ veyra::log::info("app","VEYRA_TEST_RAISE_SEH: raising test exception");veyra::Logger::instance().flush();+ RaiseException(0xE0564559u,EXCEPTION_NONCONTINUABLE,0,nullptr);+ }const int result=runVeyraApp(instance,show);veyra::log::info("app", "Veyra GUI session stopped");veyra::Logger::instance().flush();diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex d5d29ad0..47fad7ec 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -56,7 +56,7 @@ uint32_t multiplierFromDailyIndex(int index){const int i=index+1;return (index>=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,RetiredPresetSlot,Volume,Mute,Subtitle,SubtitleLoad,SubtitleSize,ImageOpen,InspectorDrawer,TabEnhance,TabFg,TabColor,TabExport,JobProgress,Details,Brand,MediaTitle,TimeLabel,EmptyTitle,EmptyHint,ProRailVideo,ProRailCapture,WindowMin,WindowMax,WindowClose,FpsLabel,RemotePlay,TabAudio,FullscreenLock,VideoSurface=1000};// Settings-panel status text: it belongs to the player's bottom bar now, next to// the submitted-FPS readout (id 64 is free in the main window's id space).-constexpr int ColourStatus=64;+constexpr int ColourStatus=64; // transport-bar status line (settings messages + toasts)constexpr int ScreenCapture=901;bool screenFill=false;SIZE screenFitClient{},screenFitImage{};veyra::engine::EngineController engine;@@ -97,11 +97,19 @@ bool applySettings(veyra::engine::EnhancementSettings s){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,playbackBar=nullptr;+HWND mainWindow=nullptr,video=nullptr,seekBar=nullptr,playbackBar=nullptr;+// Transient status shown in the transport bar (ColourStatus) for a few seconds;+// the settings-panel message is restored afterwards. Replaces the old statusBar+// control that layout() always hid (subtitle shortcuts and open failures were+// silently swallowed, sweep 2026-09-22 D1).+std::wstring settingsStatusText,toastText;ULONGLONG toastUntil=0;+void refreshColourStatus(){const bool toast=toastUntil&&GetTickCount64()<toastUntil;if(!toast)toastUntil=0;veyra::ui::setText(GetDlgItem(mainWindow,ColourStatus),toast?toastText:settingsStatusText);}+void showToast(const std::wstring& text,unsigned ms=3000){toastText=text;toastUntil=GetTickCount64()+ms;if(mainWindow)refreshColourStatus();}veyra::ui::WorkspaceTransition transition;veyra::ui::GlassBackdrop backdrop;bool fullControls=true,fullLocked=false,menuOpen=false;ULONGLONG pointerTick=0,dashboardTick=0;void layout();-enum : UINT_PTR { TelemetryTimer=1, TransitionTimer=2, ControllerTimer=3 };+enum : UINT_PTR { TelemetryTimer=1, TransitionTimer=2, ControllerTimer=3, ResizeCoalesceTimer=4, PreferenceSaveTimer=5 };+bool interactiveResize=false,layoutPending=false;void startShellTimer(HWND window,UINT_PTR id,UINT interval){if(!SetTimer(window,id,interval,nullptr))veyra::log::error("ui-timer",std::format("start failed id={} error={}",id,GetLastError()));}@@ -240,8 +248,9 @@ void startSubtitleAutoAlign(){subtitleAlignGeneration=subtitleGeneration;subtitleAlignTrack=subtitlePrimary;subtitleAlignRunning=true;subtitleAlignReady=false;subtitleStatus=L"字幕自动对齐:正在分析音轨(最多取前 30 分钟)…";- subtitleAlignWorker=std::jthread([media,track]{- const auto result=veyra::engine::alignSubtitleToAudio(media,track,30);+ subtitleAlignWorker=std::jthread([media,track](std::stop_token stop){+ const auto result=veyra::engine::alignSubtitleToAudio(media,track,30,stop);+ if(stop.stop_requested())return;{std::lock_guard lock(subtitleAlignMutex);subtitleAlignDetail=result.detail;@@ -355,14 +364,24 @@ void layout(){for(auto entry:toolbar){int id=GetDlgCtrlID(entry.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(entry.hwnd,0,0,1,1,false);}const bool rightVisible=(pro||transition.running)&&g.panelWidth>0&&!full;settingsVisibility(rightVisible&&pro);pos(video,full?0:g.left,full?0:g.top,full?w:g.viewWidth,full?h:g.viewHeight,!(pro&&showDiagnostics&&!full));- SetWindowRgn(video,full||!pro?nullptr:CreateRoundRectRgn(0,0,dip(mainWindow,g.viewWidth),dip(mainWindow,g.viewHeight),dip(mainWindow,30),dip(mainWindow,30)),FALSE);+ { // Region only changes with size/mode; rebuilding it every layout()+ // forced a DWM region update on each tick.+ static int rgnW=-1,rgnH=-1;static bool rgnRound=false;+ const bool round=!(full||!pro);const int rw=round?dip(mainWindow,g.viewWidth):0,rh=round?dip(mainWindow,g.viewHeight):0;+ if(round!=rgnRound||rw!=rgnW||rh!=rgnH){rgnRound=round;rgnW=rw;rgnH=rh;SetWindowRgn(video,round?CreateRoundRectRgn(0,0,rw,rh,dip(mainWindow,30),dip(mainWindow,30)):nullptr,FALSE);}+ }put(Brand,8,12,52,32,!full&&pro);surface(GetDlgItem(mainWindow,Brand),RGB(16,17,18));put(Capture,0,0,1,1,false);put(Recent,0,0,1,1,false);put(WindowMin,w-124,14,32,32,!full&&pro);put(WindowMax,w-88,14,32,32,!full&&pro);put(WindowClose,w-52,14,32,32,!full&&pro);for(int id:{WindowMin,WindowMax,WindowClose})surface(GetDlgItem(mainWindow,id),background);- put(InspectorDrawer,w-384,14,76,32,!full&&pro&&w<960);put(Master,g.left+(w<960?120:190),14,116,32,!full&&pro);- put(Save,g.left+(w>=1080?502:w>=960?318:244),14,76,32,!full&&pro);+ // Header row at the 720 px minimum cannot hold Save, the drawer button and+ // the mode switch side by side (sweep 2026-09-22 D4): below 960 px the+ // save button moves into the left rail under the source buttons.+ const bool narrowHeader=w<960;+ if(narrowHeader)put(Save,12,372,44,44,!full&&pro);+ else put(Save,g.left+(w>=1080?502:318),14,76,32,!full&&pro);+ put(InspectorDrawer,w-384,14,76,32,!full&&pro&&narrowHeader);put(ProRailVideo,12,92,44,44,!full&&pro);put(ProRailCapture,12,148,44,44,!full&&pro);put(ImageOpen,12,204,44,44,!full&&pro);put(ScreenCapture,12,260,44,44,!full&&pro);for(int id:{ProRailVideo,ProRailCapture,ImageOpen})surface(GetDlgItem(mainWindow,id),RGB(16,17,18));const int tabs[]={TabEnhance,TabFg,TabAudio,TabColor,TabExport};for(int i=0;i<5;++i)put(tabs[i],g.right+12+i*((g.panelWidth-24)/5),g.top+12,(g.panelWidth-24)/5,32,rightVisible);@@ -375,13 +394,16 @@ void layout(){const int timeWidth=std::min(240,std::max(0,(tw-154)/2));put(TimeLabel,tx,barTop+10,timeWidth,20,transport);// Settings messages live here now (the panel no longer draws its own line).- put(ColourStatus,tx+tw-154-446,barTop+10,440,20,transport);+ // Status line sits between the title and the fps label; the title+ // shrinks to make room instead of both painting over each other.+ const int statusWidth=std::min(440,std::max(120,tw/3));+ put(ColourStatus,tx+tw-154-6-statusWidth,barTop+10,statusWidth,20,transport);int remoteSpace=0;#ifdef VEYRA_ENABLE_REMOTEPLAYremoteSpace=daily?60:0;put(RemotePlay,daily?tx+timeWidth:12,daily?barTop+4:316,daily?56:44,daily?28:44,!full&&(daily||pro));#endif- put(MediaTitle,tx+timeWidth+8+remoteSpace,barTop+10,std::max(1,tw-timeWidth-170-remoteSpace),20,transport);+ put(MediaTitle,tx+timeWidth+8+remoteSpace,barTop+10,std::max(1,tw-timeWidth-170-remoteSpace-statusWidth-8),20,transport);put(FpsLabel,tx+tw-154,barTop+10,154,20,transport);auto slot=[&](int id,TransportSlot item,int height=34,int offset=36){put(id,tx+item.x,barTop+offset,item.width,height,transport&&item.width>0);};slot(Open,controls.open);slot(Capture,controls.capture);slot(Recent,controls.recent);if(!full&&pro)put(Recent,12,372,44,44);@@ -396,8 +418,12 @@ for(int id:std::initializer_list<int>{Open,Capture,Recent,Master,Save,Sr,Play,Stput(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,0,0,1,1,false);pos(diagnosticPanel,g.left,g.top,g.viewWidth,h-g.top-20,!full&&pro&&showDiagnostics);- const bool empty=currentFile.empty();put(EmptyTitle,0,0,1,1,false);put(EmptyHint,0,0,1,1,false);+ pos(diagnosticPanel,g.left,g.top,g.viewWidth,h-g.top-20,!full&&pro&&showDiagnostics);+ const bool empty=currentFile.empty();+ // Empty/failed state text is visible again (it was hidden every tick).+ const bool showEmpty=!full&&(empty||target.failed)&&!pro;+ put(EmptyTitle,g.left+16,g.top+g.viewHeight/2-60,std::max(1,g.viewWidth-32),48,showEmpty);+ put(EmptyHint,g.left+16,g.top+g.viewHeight/2,std::max(1,g.viewWidth-32),72,showEmpty);for(int id:{EmptyTitle,EmptyHint})surface(GetDlgItem(mainWindow,id),background);pos(subtitleLabel,full?0:g.left,full?0:g.top,full?w:g.viewWidth,full?h:g.viewHeight,uiState.subtitles&&GetWindowTextLengthW(subtitleLabel)>0);put(JobProgress,tx,barTop+10,std::min(300,tw),24,exportJob.poll().state!=veyra::engine::ExportState::Idle&&!full);@@ -562,7 +588,7 @@ auto ref=control(L"COMBOBOX",L"",Reference,CBS_DROPDOWNLIST,0,0,170,180);for(autWNDCLASSW barClass{};barClass.lpfnWndProc=barProc;barClass.hInstance=GetModuleHandleW(nullptr);barClass.lpszClassName=L"VeyraPlaybackBar";barClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&barClass);playbackBar=CreateWindowExW(0,barClass.lpszClassName,L"播放控制条",WS_CHILD|WS_CLIPSIBLINGS,0,0,1,1,hwnd,nullptr,barClass.hInstance,nullptr);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);+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));SetWindowSubclass(video,interaction,VideoSurface,0);auto brand=control(L"STATIC",L"",Brand,SS_CENTER,0,0,100,30);SetWindowSubclass(brand,veyra::ui::brandIconProc,Brand,0);@@ -589,7 +615,7 @@ for(int id:{Open,Capture,Recent,Master,Save,Sr,ModeSwitch,WindowMin,WindowMax,WiSetPropW(GetDlgItem(hwnd,Open),L"veyra.tip",HANDLE(L"打开视频 / 图片 · Ctrl+O"));SetPropW(GetDlgItem(hwnd,Capture),L"veyra.tip",HANDLE(L"连接采集卡"));SetPropW(GetDlgItem(hwnd,Sr),L"veyra.tip",HANDLE(L"超分辨率 · 专业面板选择 DLSS / RTX 视频超分"));inspector=veyra::ui::createSettingsPanel(hwnd,engine,applySettings);// Settings messages go to the player's bottom bar instead of a line inside the panel.-veyra::ui::settingsStatusSink([](const std::wstring& text){SetWindowTextW(GetDlgItem(mainWindow,ColourStatus),text.c_str());});+veyra::ui::settingsStatusSink([](const std::wstring& text){settingsStatusText=text;refreshColourStatus();});liveStatusPanel=veyra::ui::createLiveStatusPanel(hwnd,engine);selectInspector(uiPreferences.inspector);SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,LPARAM(uiPreferences.volume*100));veyra::ui::marked(GetDlgItem(hwnd,Play));for(auto [id,help]:std::initializer_list<std::pair<int,const wchar_t*>>{{Nr,L"实验性DLSS5 NR增强:重建画面细节,效果看素材,不是游戏原生集成。"},@@ -616,7 +642,9 @@ case WM_PAINT:{veyra::ui::PaintBuffer paint(hwnd);auto g=chromeLayout(MulDiv(pai__declspec(noinline) LRESULT savePresentation(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){-case WM_APP+46:{uiPreferences.presentation=engine.snapshot().presentation;if(smokeSeconds<=0&&!preferences.save(uiPreferences,nullptr))veyra::log::warn("preferences","Could not persist presentation settings");return 0;}+case WM_APP+46:{uiPreferences.presentation=engine.snapshot().presentation;+ // Coalesce: repeated dropdown changes within a second produce one write.+ if(smokeSeconds<=0)SetTimer(hwnd,PreferenceSaveTimer,1000,nullptr);return 0;}}return DefWindowProcW(hwnd,msg,wp,lp);}@@ -645,8 +673,8 @@ case Open:case ProRailVideo:case ImageOpen:openFile(fileDialog(false));layout();case ScreenCapture:veyra::ui::showScreenCapturePanel(hwnd,[](const std::wstring& path){openFile(path);layout();},[]{engine.stop();},[]{return engine.snapshot();},[](bool fill){screenFill=fill;screenFitClient={};screenFitImage={};engine.previewView({});});break;case ModeSwitch:switchMode();break;-case WindowMin:ShowWindow(hwnd,SW_MINIMIZE);break;case WindowMax:toggleFullscreen();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 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);if(!engine.requestSettings(uiState.effective())){uiState.enhanced=masterPreviousEnabled;veyra::ui::settingsEnabled(uiState.enhanced,uiState.configured);showToast(engine.snapshot().status);veyra::log::warn("ui-master","request rejected by capability gate; toggle restored");break;}if(auto pending=engine.snapshot();pending.running){masterPendingRevision=pending.desired.revision;masterPendingSession=pending.sessionId;}break;case InspectorDrawer:uiState.drawer=!uiState.drawer;layout();break;case TabAudio:selectInspector(4);break;case TabEnhance:case TabFg:case TabColor:case TabExport:selectInspector(LOWORD(wp)-TabEnhance);break;@@ -706,10 +734,15 @@ case WM_HSCROLL:if(reinterpret_cast<HWND>(lp)==GetDlgItem(hwnd,Volume)){engine.s__declspec(noinline) LRESULT windowTimer(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){case WM_TIMER:+// A popup selector runs its own message loop; shell timer work (layout,+// dialogs, auto-open) must not run underneath it (sweep 2026-09-22 D7).+if(veyra::ui::popupSelectorOpen())return 0;#ifdef VEYRA_ENABLE_REMOTEPLAYif(wp==ControllerTimer){const auto state=engine.snapshot();if(state.remotePlay&&(state.running||state.transport==veyra::engine::TransportState::Opening)){const bool focused=GetForegroundWindow()==hwnd;engine.remotePlayController(remoteController.poll(focused));remoteController.feedback(engine.remotePlayFeedback(),focused);}else{engine.remotePlayController({});remoteController.stop();KillTimer(hwnd,ControllerTimer);}return 0;}#endif-{if(wp==TransitionTimer){transition.sample(GetTickCount64());if(!transition.running){endTransition();veyra::log::info("ui-transition","completed; final layout and swapchain resize released");}layout();return 0;}+{if(wp==ResizeCoalesceTimer){if(layoutPending){layoutPending=false;layout();}return 0;}+if(wp==PreferenceSaveTimer){KillTimer(hwnd,PreferenceSaveTimer);if(!preferences.save(uiPreferences,nullptr))veyra::log::warn("preferences","Could not persist presentation settings");return 0;}+if(wp==TransitionTimer){transition.sample(GetTickCount64());if(!transition.running){endTransition();veyra::log::info("ui-transition","completed; final layout and swapchain resize released");}layout();return 0;}if(full&&fullControls&&!menuOpen&&!veyra::ui::popupSelectorOpen()&&!GetCapture()&&GetTickCount64()-pointerTick>1600){POINT p{};GetCursorPos(&p);ScreenToClient(hwnd,&p);RECT r{};GetClientRect(hwnd,&r);if(p.y<r.bottom-veyra::ui::dip(hwnd,98)||p.x<0||p.x>=r.right||p.y>=r.bottom){fullControls=false;layout();if(GetForegroundWindow()==hwnd)SetCursor(nullptr);veyra::log::info("ui-fullscreen","controls hidden; video and subtitles only");}}if(closing){if(engine.idle()&&!exportJob.poll().active()){KillTimer(hwnd,TelemetryTimer);DestroyWindow(hwnd);}return 0;}if(!autoInput.empty()){auto file=autoInput;autoInput.clear();openFile(file);startTick=GetTickCount64();if(openColourPageOnStart){openColourPageOnStart=false;if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(2);layout();}}if(smokeControls&&startTick){const auto elapsed=GetTickCount64()-startTick;if(smokeStep==0&&elapsed>2200){engine.pause(true);smokeStep=1;}@@ -770,7 +803,7 @@ if(screenFill&¤tFile.starts_with(L"screen:")&&s.running){if(joined!=lastSubtitleLog){lastSubtitleLog=joined;veyra::log::info("subtitle-overlay",std::format("text={}",narrow(joined)));}}else if(!lastSubtitleLog.empty())lastSubtitleLog.clear();if(!subtitleStatus.empty()){- SetWindowTextW(statusBar,subtitleStatus.c_str());+ showToast(subtitleStatus);veyra::log::info("subtitle-status",narrow(subtitleStatus));subtitleStatus.clear();}@@ -787,7 +820,11 @@ if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTi}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);+static std::wstring lastStatusLine;if(text!=lastStatusLine){lastStatusLine=text;+ // Failures and first-line status changes surface as a toast; the full+ // multi-line text remains available to the diagnostics panel via logs.+ if(s.failed&&!s.status.empty())showToast(s.status,6000);}+refreshColourStatus();using namespace veyra::ui;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;}if(smokeScreenshot&&screenshotStep==0&&s.frames>20){SendMessageW(hwnd,WM_COMMAND,Save,0);screenshotStep=1;}@@ -809,7 +846,7 @@ CheckDlgButton(hwnd,Sr,(uiState.enhanced&&s.desired.sr)?BST_CHECKED:BST_UNCHECKEveyra::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::Playing?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);-if(GetCapture()!=GetDlgItem(hwnd,Volume))SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,int(std::lround(s.volume*100)));+if(GetCapture()!=GetDlgItem(hwnd,Volume)){const int volumePos=int(std::lround(s.volume*100));if(SendDlgItemMessageW(hwnd,Volume,TBM_GETPOS,0,0)!=volumePos)SendDlgItemMessageW(hwnd,Volume,TBM_SETPOS,TRUE,volumePos);}EnableWindow(seekBar,s.running&&!s.capture&&!s.image&&s.duration>0);ShowWindow(seekBar,(!full||fullControls)&&!s.capture&&!s.image&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?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.remotePlay?L"PS5 · LIVE":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);};@@ -817,9 +854,9 @@ setText(GetDlgItem(hwnd,TimeLabel),s.remotePlay?(s.remoteRatesReady?std::format(std::wstring metric=std::format(L"源帧处理 {:.1f} fps · 显示提交 {:.1f} fps · 有效生成 {}\n提交迟到 p95 {:.1f} ms · GPU / CPU 时间分别统计\n{}\n实际扫描率与光子延迟:未测",s.fps,submittedFps,s.generated,s.lateP95Ms,s.status);setText(metricLabel,metric);if(uiState.mode==Mode::Professional&&!full&&!transition.running&&GetTickCount64()-dashboardTick>=250){dashboardTick=GetTickCount64();RECT client{};GetClientRect(hwnd,&client);RECT dashboard{0,client.bottom-dip(hwnd,232),client.right,client.bottom};InvalidateRect(hwnd,&dashboard,FALSE);}exportJob.watching(preferWatching&&s.running&&s.transport==veyra::engine::TransportState::Playing);auto job=exportJob.poll();exportPanelStatus(job,!currentFile.empty()&&!s.capture&&!s.image,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);-setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");ShowWindow(GetDlgItem(hwnd,EmptyTitle),SW_HIDE);ShowWindow(GetDlgItem(hwnd,EmptyHint),SW_HIDE);+setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");static bool lastEmptyState=false;const bool emptyState=currentFile.empty()||s.failed;if(emptyState!=lastEmptyState){lastEmptyState=emptyState;layout();}if(dragging&&GetCapture()!=seekBar){dragging=false;seekPreview.released=true;}-seekPreview.tick();+seekPreview.tick(&s);if(!dragging&&s.duration>0){int position=int((s.seekPresented<s.seekRequested&&!s.failed?s.seekTarget:s.position)/s.duration*10000);if(SendMessageW(seekBar,TBM_GETPOS,0,0)!=position)SendMessageW(seekBar,TBM_SETPOS,TRUE,position);}if(!smokeViewApplied&&!smokeView.empty()&&(s.frames>0||smokeEmpty)){smokeViewApplied=true;if(smokeView==L"small")SetWindowPos(hwnd,nullptr,0,0,800,600,SWP_NOMOVE|SWP_NOZORDER);if(smokeView!=L"daily"&&smokeView!=L"empty"&&uiState.mode==veyra::ui::Mode::Daily)switchMode();if(smokeView==L"export")selectInspector(3);if(smokeView==L"diagnostics"){showDiagnostics=true;layout();}if(smokeView==L"fullscreen")toggleFullscreen();}if(smokeDualPause&&pausedPosition<0&&s.frames>20){engine.pause(true);pausedPosition=s.position;pausedFrames=s.frames;}@@ -1139,7 +1176,7 @@ if(smokeSeconds>0&&startTick&&GetTickCount64()-startTick>ULONGLONG(smokeSeconds)__declspec(noinline) LRESULT closeWindow(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp){switch(msg){-case WM_CLOSE:endTransition();if(!closing&&smokeSeconds<=0&&exportJob.poll().active()&&MessageBoxW(hwnd,L"导出尚未完成。取消导出并退出?\n选择“否”返回播放器继续导出。",L"退出 Veyra",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION)!=IDYES)return 0;if(!closing&&smokeSeconds<=0){auto snapshot=engine.snapshot();WINDOWPLACEMENT placement{sizeof(placement)};if(full)placement=windowPlacement;else GetWindowPlacement(hwnd,&placement);auto r=placement.rcNormalPosition;uiPreferences.width=MulDiv(r.right-r.left,96,veyra::ui::layoutDpi(hwnd));uiPreferences.height=MulDiv(r.bottom-r.top,96,veyra::ui::layoutDpi(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.subtitleOutline=uiState.subtitleOutline;uiPreferences.subtitleBackground=uiState.subtitleBackground;uiPreferences.subtitleSecondLanguage=uiState.subtitleSecondLanguage;uiPreferences.subtitleMargin=uiState.subtitleMargin;uiPreferences.subtitleFont=uiState.subtitleFont;uiPreferences.inspector=uiState.inspector;uiPreferences.colourFoldMask=preferences.load().colourFoldMask;uiPreferences.enhancementEnabled=uiState.enhanced?1:0;auto saved=uiState.enhanced&&snapshot.running&&snapshot.frames>0&&!snapshot.applying&&!snapshot.failed?snapshot.applied:uiState.configured;if(!preferences.save(uiPreferences,&saved))veyra::log::warn("ui-preferences","preferences save failed; existing corrupt original preserved");else veyra::log::info("ui-preferences","UI and enhancement preferences saved");}playbackPower.update(false);exportJob.cancel();closing=true;engine.stop();SetWindowTextW(statusBar,L"正在释放当前任务资源…");return 0;+case WM_CLOSE:endTransition();KillTimer(hwnd,PreferenceSaveTimer);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,veyra::ui::layoutDpi(hwnd));uiPreferences.height=MulDiv(r.bottom-r.top,96,veyra::ui::layoutDpi(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.subtitleOutline=uiState.subtitleOutline;uiPreferences.subtitleBackground=uiState.subtitleBackground;uiPreferences.subtitleSecondLanguage=uiState.subtitleSecondLanguage;uiPreferences.subtitleMargin=uiState.subtitleMargin;uiPreferences.subtitleFont=uiState.subtitleFont;uiPreferences.inspector=uiState.inspector;uiPreferences.colourFoldMask=preferences.load().colourFoldMask;uiPreferences.enhancementEnabled=uiState.enhanced?1:0;auto saved=uiState.enhanced&&snapshot.running&&snapshot.frames>0&&!snapshot.applying&&!snapshot.failed?snapshot.applied:uiState.configured;if(!preferences.save(uiPreferences,&saved))veyra::log::warn("ui-preferences","preferences save failed; existing corrupt original preserved");else veyra::log::info("ui-preferences","UI and enhancement preferences saved");}playbackPower.update(false);exportJob.cancel();closing=true;engine.stop();showToast(L"正在释放当前任务资源…",10000);return 0;}return DefWindowProcW(hwnd,msg,wp,lp);}@@ -1179,15 +1216,17 @@ case WM_APP+43:showDiagnostics=false;layout();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_ENTERSIZEMOVE:endTransition();+ interactiveResize=true;layoutPending=false;SetTimer(hwnd,ResizeCoalesceTimer,16,nullptr);SetPropW(video,L"Veyra.InteractiveMove",HANDLE(1));veyra::log::info("ui-display","interactive move begin; retaining presentation buffers");return 0;case WM_EXITSIZEMOVE:+ interactiveResize=false;layoutPending=false;KillTimer(hwnd,ResizeCoalesceTimer);RemovePropW(video,L"Veyra.InteractiveMove");layout();veyra::log::info("ui-display","interactive move end; presentation resize released");return 0;-case WM_SIZE:cancelProtection();if(wp!=SIZE_MINIMIZED&&!dpiRefreshPending){endTransition();layout();}return 0;+case WM_SIZE:cancelProtection();if(wp!=SIZE_MINIMIZED&&!dpiRefreshPending){endTransition();if(interactiveResize)layoutPending=true;else layout();}return 0;case WM_DROPFILES:{std::vector<wchar_t> file(32768);DragQueryFileW(reinterpret_cast<HDROP>(wp),0,file.data(),32768);DragFinish(reinterpret_cast<HDROP>(wp));openFile(file.data());layout();return 0;}case WM_COMMAND:return windowCommand(hwnd,msg,wp,lp);case WM_HSCROLL:return scrollCommand(hwnd,msg,wp,lp);@@ -1215,7 +1254,7 @@ case WM_DPICHANGED:{case WM_TIMER:return windowTimer(hwnd,msg,wp,lp);case WM_CLOSE:return closeWindow(hwnd,msg,wp,lp);-case WM_DESTROY:+case WM_DESTROY:if(subtitleAlignWorker.joinable())subtitleAlignWorker.request_stop();playbackPower.update(false);subtitleLoader.reset();#ifdef VEYRA_ENABLE_REMOTEPLAY@@ -1305,7 +1344,7 @@ if(!editing&&(!adjustingSlider||full)&&!veyra::ui::popupSelectorOpen()&&msg.messif(full&&!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='L'){if(!(msg.lParam&(1LL<<30)))toggleFullscreenLock();continue;}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;}}+const bool key=(!editing)&&(msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||(msg.wParam==VK_SPACE&&(GetFocus()==hwnd||GetFocus()==video))||(msg.wParam=='V'&&!(GetKeyState(VK_CONTROL)&0x8000))||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN));if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}if(msg.message==WM_MOUSEWHEEL&&GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&!veyra::ui::popupSelectorOpen()){POINT p{GET_X_LPARAM(msg.lParam),GET_Y_LPARAM(msg.lParam)};const HWND hovered=WindowFromPoint(p);if(hovered==video&&uiState.mode==veyra::ui::Mode::Professional){SendMessageW(video,msg.message,msg.wParam,msg.lParam);continue;}diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cppindex 3be2e076..d76a2983 100644--- a/apps/veyra/ui/CapturePanel.cpp+++ b/apps/veyra/ui/CapturePanel.cpp@@ -7,6 +7,7 @@#include "veyra/source/CaptureCardSource.h"#include "veyra/source/CaptureFormatRank.h"#include <future>+#include <thread>#include <format>namespace veyra::ui {namespace {@@ -177,7 +178,11 @@ 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;+case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;+ // Do not block window destruction on a device enumeration still running:+ // park the future so its destructor waits on a detached helper instead.+ if(pending.valid()&&pending.wait_for(std::chrono::seconds(0))!=std::future_status::ready){std::thread([f=std::move(pending)]()mutable{try{(void)f.get();}catch(...){}}).detach();}+ return 0;}return DefWindowProcW(h,msg,wp,lp);}}void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback,std::function<bool()> read,std::function<bool(bool)> write,std::function<int()> readIngress,std::function<bool(int)> writeIngress,std::function<bool()> readFlipped,std::function<bool(bool)> writeFlipped,std::function<int()> readBuffered,std::function<bool(int)> writeBuffered){start=std::move(callback);readSdr=std::move(read);setSdr=std::move(write);readAudioIngress=std::move(readIngress);setAudioIngress=std::move(writeIngress);readFlip=std::move(readFlipped);setFlip=std::move(writeFlipped);readBuffer=std::move(readBuffered);setBuffer=std::move(writeBuffered);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,680),parent,nullptr,wc.hInstance,nullptr);}diff --git a/apps/veyra/ui/SeekPreview.h b/apps/veyra/ui/SeekPreview.hindex 2eaa7564..2e1aeed1 100644--- a/apps/veyra/ui/SeekPreview.h+++ b/apps/veyra/ui/SeekPreview.h@@ -18,9 +18,9 @@ struct SeekPreview {if(release&&target!=submitted){engine.seek(target);submitted=target;}else tick();}- void tick() {+ void tick(const veyra::engine::PlayerSnapshot* shared=nullptr) {if(!active)return;- const auto s=engine.snapshot();+ const auto s=shared?*shared:engine.snapshot();if(s.sessionId!=session||!s.running||s.failed){*this={};return;}if(s.seekRequested!=s.seekPresented)return;if(target!=submitted){engine.seek(target);submitted=target;return;}diff --git a/apps/veyra/ui/SubtitleOverlay.cpp b/apps/veyra/ui/SubtitleOverlay.cppindex 95c9dc30..e25f3104 100644--- a/apps/veyra/ui/SubtitleOverlay.cpp+++ b/apps/veyra/ui/SubtitleOverlay.cpp@@ -68,11 +68,20 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const Sconst auto signature=signatureOf(lines,view,rect)+std::format(L"/dpi{}",GetDpiForWindow(h));if(lastSignature==signature){ShowWindow(h,SW_SHOWNOACTIVATE);return;}const int width=rect.right,height=rect.bottom;- BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=width;info.bmiHeader.biHeight=-height;- info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;+ // The DIB is reused while the overlay size is unchanged; zoom/drag only+ // re-renders into it (a 4K DIB is ~33 MB, re-allocating it per tick stalled+ // middle-button drags).+ static thread_local HBITMAP cachedBitmap=nullptr;static thread_local void* cachedBits=nullptr;static thread_local int cachedW=0,cachedH=0;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;}+ if(!cachedBitmap||cachedW!=width||cachedH!=height){+ if(cachedBitmap){DeleteObject(cachedBitmap);cachedBitmap=nullptr;cachedBits=nullptr;}+ BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=width;info.bmiHeader.biHeight=-height;+ info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;+ cachedBitmap=CreateDIBSection(screen,&info,DIB_RGB_COLORS,&cachedBits,nullptr,0);+ if(!cachedBitmap||!cachedBits){if(cachedBitmap)DeleteObject(cachedBitmap);cachedBitmap=nullptr;cachedBits=nullptr;DeleteDC(memory);ReleaseDC(nullptr,screen);return;}+ cachedW=width;cachedH=height;+ }+ auto bitmap=cachedBitmap;void* bits=cachedBits;auto previousObject=SelectObject(memory,bitmap);memset(bits,0,size_t(width)*height*4);{@@ -232,6 +241,6 @@ void updateSubtitleOverlay(HWND h,const std::vector<SubtitleLine>& lines,const SSetPropW(h,L"subtitle.error",HANDLE(1));}}- SelectObject(memory,previousObject);DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(nullptr,screen);+ SelectObject(memory,previousObject);DeleteDC(memory);ReleaseDC(nullptr,screen);}} // namespace veyra::uidiff --git a/apps/veyra/ui/WorkspaceChrome.h b/apps/veyra/ui/WorkspaceChrome.hindex 8f92d7e9..60565937 100644--- a/apps/veyra/ui/WorkspaceChrome.h+++ b/apps/veyra/ui/WorkspaceChrome.h@@ -1,4 +1,5 @@#pragma once+#include <unordered_map>#include "Theme.h"#include "veyra/engine/EngineController.h"#include <format>@@ -15,7 +16,16 @@ struct ChromeLayout {statusTop=std::min(h-186,std::max(top+336,h-330));}};-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)};glassText(dc,value.c_str(),-1,&r,flags|DT_END_ELLIPSIS);SelectObject(dc,old);DeleteObject(font);}+// Fonts are cached per (dpi,size,weight); the dashboard draws dozens of+// strings per 250 ms tick and used to create/delete an HFONT for each.+inline HFONT cachedChromeFont(HWND window,int size,int weight){+ static std::unordered_map<uint64_t,HFONT> cache;+ const uint64_t key=(uint64_t(dip(window,1000))<<40)|(uint64_t(uint32_t(size))<<16)|uint64_t(uint32_t(weight));+ auto it=cache.find(key);if(it!=cache.end())return it->second;+ if(cache.size()>64){for(auto& entry:cache)DeleteObject(entry.second);cache.clear();}+ return cache[key]=makeFont(window,size,weight);+}+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=cachedChromeFont(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)};glassText(dc,value.c_str(),-1,&r,flags|DT_END_ELLIPSIS);SelectObject(dc,old);}inline void paintChrome(HWND window,HDC dc,const ChromeLayout& l,const engine::PlayerSnapshot& s,bool full){RECT client{};GetClientRect(window,&client);if(!copyGlass(dc,client,window))FillRect(dc,&client,bgBrush());if(full)return;using namespace Gdiplus;AlphaGraphics drawing(dc);auto& g=drawing.get();g.SetSmoothingMode(SmoothingModeAntiAlias);diff --git a/include/veyra/engine/LivePairLatency.h b/include/veyra/engine/LivePairLatency.hindex 363a6dcb..538d9423 100644--- a/include/veyra/engine/LivePairLatency.h+++ b/include/veyra/engine/LivePairLatency.h@@ -26,8 +26,10 @@ public:std::nth_element(current.begin(),current.begin()+index,current.end());// One millisecond covers polling/wakeup jitter. Never add latency above// the existing policy, or compress phase by more than 0.25 ms per pair.- const auto target=std::min(legacyDelay,current[index]+10000);- const auto step=std::min<int64_t>(2500,interval/multiplier/16);+ // 0.5 ms covers wake-up jitter with MMCSS on the owner thread; the+ // per-pair step may close a subframe interval over eight pairs.+ const auto target=std::min(legacyDelay,current[index]+5000);+ const auto step=std::min<int64_t>(5000,interval/multiplier/8);selected_=std::clamp(selected_?selected_-step:legacyDelay,target,legacyDelay);return selected_;}diff --git a/include/veyra/engine/Subtitles.h b/include/veyra/engine/Subtitles.hindex b4f41f5a..61ce54fa 100644--- a/include/veyra/engine/Subtitles.h+++ b/include/veyra/engine/Subtitles.h@@ -88,7 +88,7 @@ std::wstring textAt(const SubtitleTrack&,double seconds);// Constant-offset alignment: correlates the file's speech activity with the// track's cue activity. Returns the shift to ADD to cue timestamps.struct SubtitleAlignResult { bool ok=false; int offsetMs=0; double score=0; std::wstring detail; };-SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubtitleTrack&,int maxShiftSeconds=30);+SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubtitleTrack&,int maxShiftSeconds=30,std::stop_token stop={});// Legacy helpers kept for the existing call sites/tests.std::vector<SubtitleCue> loadSrt(const std::wstring& path);diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.hindex 01fe1f9a..88f28517 100644--- a/include/veyra/gfx/PresentSink.h+++ b/include/veyra/gfx/PresentSink.h@@ -27,6 +27,10 @@ using ComPtr = Microsoft::WRL::ComPtr<T>;class PresentSink {public:static bool hdrDisplayActive(HWND);+ // The factory is cached process-wide; DXGI factories detect display+ // topology changes (IsCurrent) so a stale one is recreated on demand.+ // Creating a factory and enumerating every adapter/output each call ran+ // on the graph owner every 2 s under HDR (sweep 2026-09-22 A1).static std::optional<bool> queryHdrDisplayActive(HWND,HMONITOR* queriedMonitor=nullptr);static double displayRefreshFps(HWND);PresentSink() = default;diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex 00565183..aaed562b 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -376,6 +376,7 @@ private:ComPtr<ID3D12Resource> depthTex_;ComPtr<ID3D12Resource> genFrame_[kGeneratedPoolSlots];ComPtr<ID3D12Resource> fgDisable_[kGeneratedPoolSlots],fgDisableReadback_[kGeneratedPoolSlots],fgDisableInit_;+ std::array<const volatile uint8_t*,kGeneratedPoolSlots> fgDisableMapped_{};ComPtr<ID3D12Resource> nrZeroMotion_;ComPtr<ID3D12Resource> nrZeroDepth_;ComPtr<ID3D12Resource> nvofRawTex_;diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex 6cd0db50..157a3a0c 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -213,6 +213,13 @@ private:std::atomic<uint64_t> timelineWriteFrame_{0};std::atomic<float> gain_{1};float smoothedGain_=1,loggedGain_=-1;IMMDeviceEnumerator* enum_ = nullptr;+ // Default-endpoint change notification: flags the renderer as invalidated+ // so the existing recovery path rebuilds the endpoint promptly instead of+ // waiting for the next write to fail (sweep 2026-09-22 C6).+ struct EndpointNotifier;+ EndpointNotifier* notifier_ = nullptr;+ void registerEndpointNotification();+ void unregisterEndpointNotification();IMMDevice* device_ = nullptr;IAudioClient* client_ = nullptr;IAudioRenderClient* render_ = nullptr;diff --git a/include/veyra/source/MediaFileSource.h b/include/veyra/source/MediaFileSource.hindex e1e6ec85..b588c106 100644--- a/include/veyra/source/MediaFileSource.h+++ b/include/veyra/source/MediaFileSource.h@@ -45,6 +45,7 @@ private:uint64_t sequence_ = 0;uint64_t epoch_ = 1;uint64_t framesRead_ = 0;+ uint64_t ptsFallbacks_ = 0; // frames delivered with best_effort/dts timestampsuint64_t seekCount_ = 0;bool pendingSeekFlag_ = false;bool draining_ = false;diff --git a/src/base/Log.cpp b/src/base/Log.cppindex 2b94539a..bc41081a 100644--- a/src/base/Log.cpp+++ b/src/base/Log.cpp@@ -1,6 +1,8 @@#include "veyra/Log.h"#include "veyra/diagnostics/Redaction.h"#include <sstream>+#include <optional>+#include <regex>#include <windows.h>@@ -98,14 +100,27 @@ void Logger::write(LogLevel level, const char* component, const std::string& mesconst std::string line = std::format("{} t={} [{}] [{}] {}",timestampUtc(), threadId, levelTag(level), component, message);+ // Diagnostic extraction runs before taking the global lock and uses+ // precompiled expressions: this path is reached from the capture callback+ // and audio threads, and compiling four regexes under the lock stalled+ // them during warning bursts (sweep 2026-09-22 C1).+ std::optional<diagnostics::DiagnosticEvent> pendingEvent;+ if(level==LogLevel::Warn||level==LogLevel::Error){+ static const std::regex hrPattern("(?:HRESULT|hr)[=: ]+(0x[0-9a-f]+|[0-9]+)",std::regex::icase|std::regex::optimize);+ static const std::regex sehPattern("seh[=: ]+(0x[0-9a-f]+|[0-9]+)",std::regex::icase|std::regex::optimize);+ static const std::regex nvofPattern("(?:status|st)[=: ]+(0x[0-9a-f]+|[0-9]+)",std::regex::icase|std::regex::optimize);+ static const std::regex ngxPattern("(?:result[=: ]+|failed +)(0x[0-9a-f]+|[0-9]+)",std::regex::icase|std::regex::optimize);+ auto event=threadDiagnosticContext;event.timestamp=timestampUtc();event.severity=levelTag(level);event.component=component;+ auto extract=[&](const std::regex& pattern)->std::optional<uint64_t>{std::smatch m;if(std::regex_search(message,m,pattern)){try{return std::stoull(m[1].str(),nullptr,m[1].str().starts_with("0x")?16:10);}catch(...){}}return {};};+ if(auto c=extract(hrPattern))event.hresult=c;+ if(auto c=extract(sehPattern))event.seh=c;+ if(event.component.find("nvof")!=std::string::npos){if(auto c=extract(nvofPattern))event.nvof=c;}+ if(event.component=="ngx"||message.find("evaluate")!=std::string::npos){if(auto c=extract(ngxPattern))event.ngx=c;}+ event.stage=event.stage.empty()?"runtime":event.stage;event.message=message;event.fingerprint=event.component+"|"+event.stage+"|"+diagnostics::redact(message);+ pendingEvent=std::move(event);+ }std::lock_guard<std::mutex> lock(mutex_);- if(level==LogLevel::Warn||level==LogLevel::Error){auto event=threadDiagnosticContext;event.timestamp=timestampUtc();event.severity=levelTag(level);event.component=component;- auto extract=[&](const char* pattern)->std::optional<uint64_t>{std::smatch m;if(std::regex_search(message,m,std::regex(pattern,std::regex::icase))){try{return std::stoull(m[1].str(),nullptr,m[1].str().starts_with("0x")?16:10);}catch(...){}}return {};};- if(auto c=extract("(?:HRESULT|hr)[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.hresult=c;- if(auto c=extract("seh[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.seh=c;- if(event.component.find("nvof")!=std::string::npos){if(auto c=extract("(?:status|st)[=: ]+(0x[0-9a-f]+|[0-9]+)"))event.nvof=c;}- if(event.component=="ngx"||message.find("evaluate")!=std::string::npos){if(auto c=extract("(?:result[=: ]+|failed +)(0x[0-9a-f]+|[0-9]+)"))event.ngx=c;}- event.stage=event.stage.empty()?"runtime":event.stage;event.message=message;event.fingerprint=event.component+"|"+event.stage+"|"+diagnostics::redact(message);latestProblem_=event.component+": "+event.message;diagnostics_.add(std::move(event));}+ if(pendingEvent){latestProblem_=pendingEvent->component+": "+pendingEvent->message;diagnostics_.add(std::move(*pendingEvent));}if (consoleEnabled_) {std::fprintf(stdout, "%s\n", line.c_str());std::fflush(stdout);diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 027b6864..de7cb9ce 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -34,6 +34,7 @@#include "veyra/gfx/D3D12DeviceContext.h"#include "veyra/gfx/CommandSlotRing.h"#include "veyra/RuntimePaths.h"+#include <avrt.h>#include <chrono>#include <filesystem>#include <format>@@ -139,10 +140,21 @@ void EngineController::requestPresentation(PresentationSettings settings){presentation_=settings;++presentationRevision_;}PlayerSnapshot EngineController::snapshot()const{- std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;- copy.presentation=presentation_;+ // The flow window has its own mutex and percentile work; take it after+ // releasing the engine mutex so UI polling does not hold the owner thread+ // (sweep 2026-09-22 B3). Consecutive UI callers within 50 ms share one+ // flow snapshot.+ PlayerSnapshot copy;std::shared_ptr<FrameFlowWindow> flowWindow;+ {std::lock_guard lock(mutex_);copy=snapshot_;copy.presentation=presentation_;flowWindow=activeFlow_;}+ copy.volume=volume_;copy.muted=muted_;const bool playing=copy.running&&!copy.image&©.transport==TransportState::Playing;- if(activeFlow_)copy.metrics.flow=activeFlow_->snapshot(monotonic100ns());+ if(flowWindow){+ static std::mutex cacheMutex;static diagnostics::FrameFlowMetrics cached;static const FrameFlowWindow* cachedFor=nullptr;static int64_t cachedAt=0;+ const auto now=monotonic100ns();+ std::lock_guard lock(cacheMutex);+ if(cachedFor!=flowWindow.get()||now-cachedAt>500000){cached=flowWindow->snapshot(now);cachedFor=flowWindow.get();cachedAt=now;}+ copy.metrics.flow=cached;+ }copy.fgBudgetLimited=playing&©.metrics.flow.lastFgRejected100ns>0&&monotonic100ns()-copy.metrics.flow.lastFgRejected100ns<10000000;#ifdef VEYRA_ENABLE_REMOTEPLAYif(copy.remotePlay&&activeRemote_){@@ -159,8 +171,20 @@ PlayerSnapshot EngineController::snapshot()const{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;}+namespace {+// MMCSS registration keeps the graph owner and capture callback threads ahead+// of ordinary UI/background work; failure is logged once and ignored.+struct MmcssScope {+ HANDLE handle=nullptr;+ explicit MmcssScope(const wchar_t* task){DWORD index=0;handle=AvSetMmThreadCharacteristicsW(task,&index);+ static std::atomic<bool> reported{false};+ if(!handle&&!reported.exchange(true))veyra::log::warn("scheduler",std::format("MMCSS unavailable error={} (continuing at normal priority)",GetLastError()));}+ ~MmcssScope(){if(handle)AvRevertMmThreadCharacteristics(handle);}+};+}void EngineController::run(HWND window,std::wstring path,PlayerOptions options,std::shared_ptr<source::RemotePlayConnectDesc> remoteRequest){CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ MmcssScope mmcss(L"Pro Audio");status(L"正在初始化GPU与本地运行时…");gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;@@ -917,7 +941,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool referencesValid=hasOutput&&out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);- std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;+ // Paused: the swapchain already holds the frame; re-present+ // (present() handles resize and takes the view each call)+ // at 50 ms instead of 16 ms unless a parameter refresh is due.+ std::this_thread::sleep_for(std::chrono::milliseconds(refreshPausedFrame_?1:50));continue;}if(wasPaused&&!paused_){holdFileAudio();audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;pendingResetCause=pipeline::ResetReason::PauseResume;wasPaused=false;}// Backpressure before reading the capacity-one source mailbox:diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cppindex b14e8435..d6040d07 100644--- a/src/engine/ExportJobManager.cpp+++ b/src/engine/ExportJobManager.cpp@@ -37,7 +37,10 @@ struct ExportJobManager::Impl {~Impl(){clear();}};ExportJobManager::ExportJobManager():p_(std::make_unique<Impl>()){}-ExportJobManager::~ExportJobManager(){cancel();if(p_->process)WaitForSingleObject(p_->process,5000);p_->clear();}+// Shutdown is bounded: the job object is KILL_ON_CLOSE, so a worker still+// draining NVENC is terminated by clear() after a short grace instead of+// stalling process exit for up to five seconds.+ExportJobManager::~ExportJobManager(){cancel();if(p_->process)WaitForSingleObject(p_->process,1000);p_->clear();}bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames,int audioStreamIndex){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;};diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cppindex 49324831..00b0f883 100644--- a/src/engine/Subtitles.cpp+++ b/src/engine/Subtitles.cpp@@ -603,19 +603,15 @@ uint64_t SubtitleLoader::request(std::wstring path){}std::optional<SubtitleLoader::Result> SubtitleLoader::poll(){std::lock_guard lock(p_->mutex);auto result=std::move(p_->ready);p_->ready.reset();return result;}-SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubtitleTrack& track,int maxShiftSeconds){+SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubtitleTrack& track,int maxShiftSeconds,std::stop_token stop){SubtitleAlignResult result;if(track.cues.empty()){result.detail=L"没有可用的字幕内容";return result;}- log::info("subtitle",std::format("auto align skipped: {}",utf8(result.detail)));AVFormatContext* input=nullptr;const auto utf8Path=utf8(mediaPath);if(avformat_open_input(&input,utf8Path.c_str(),nullptr,nullptr)<0||!input){result.detail=L"无法打开媒体";return result;}- log::info("subtitle",std::format("auto align skipped: {}",utf8(result.detail)));if(avformat_find_stream_info(input,nullptr)<0){avformat_close_input(&input);result.detail=L"无法读取媒体信息";return result;}- log::info("subtitle",std::format("auto align skipped: {}",utf8(result.detail)));const int audioIndex=av_find_best_stream(input,AVMEDIA_TYPE_AUDIO,-1,-1,nullptr,0);if(audioIndex<0){avformat_close_input(&input);result.detail=L"该文件没有音轨,无法自动对齐";return result;}- log::info("subtitle",std::format("auto align skipped: {}",utf8(result.detail)));AVStream* stream=input->streams[audioIndex];const AVCodec* decoder=avcodec_find_decoder(stream->codecpar->codec_id);AVCodecContext* context=decoder?avcodec_alloc_context3(decoder):nullptr;@@ -647,7 +643,7 @@ SubtitleAlignResult alignSubtitleToAudio(const std::wstring& mediaPath,const SubAVPacket* packet=av_packet_alloc();AVFrame* frame=av_frame_alloc();const double limitSeconds=1800.0;- while(packet&&frame&&av_read_frame(input,packet)>=0){+ while(packet&&frame&&!stop.stop_requested()&&av_read_frame(input,packet)>=0){if(packet->stream_index!=audioIndex){av_packet_unref(packet);continue;}if(avcodec_send_packet(context,packet)<0){av_packet_unref(packet);continue;}av_packet_unref(packet);diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex c7167aae..6dc2d111 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -223,7 +223,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptipipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,(pts+videoOriginSeconds)*1000,sourceCount==0||repairPts||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,&packet.hardwareSurface,false)){error=true;break;}const auto readyStart=std::chrono::steady_clock::now();while(!cancel&&!graph.resolveGeneration(out)){- if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;break;}+ if(std::chrono::steady_clock::now()-readyStart>std::chrono::seconds(2)){error=true;failureReason=L"GPU 在 2 秒内未完成一帧增强(可能显卡繁忙或驱动异常)";veyra::log::error("export","frame GPU completion timed out after 2s");break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}if(error||cancel)break;diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cppindex 75cce1f5..a5feb038 100644--- a/src/gfx/CommandSlotRing.cpp+++ b/src/gfx/CommandSlotRing.cpp@@ -131,7 +131,8 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statu}}- if(target.timed && timingReadback_) {+ static const bool profileSlots=GetEnvironmentVariableW(L"VEYRA_PROFILE_SLOTS",nullptr,0)>0;+ if(target.timed && timingReadback_ && (profileSlots||veyra::log::verboseFrameLogs())) {uint64_t* data=nullptr;D3D12_RANGE range{slot*2*sizeof(uint64_t),(slot*2+2)*sizeof(uint64_t)};if(SUCCEEDED(timingReadback_->Map(0,&range,reinterpret_cast<void**>(&data)))) {const uint64_t begin=data[slot*2],end=data[slot*2+1];@@ -139,6 +140,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statuD3D12_RANGE empty{0,0};timingReadback_->Unmap(0,&empty);}target.timed=false;target.label.clear();}+ target.timed=false;HRESULT result = target.allocator->Reset();if (FAILED(result)) {status = Status::DeviceFailure;diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cppindex d92da104..dffc36da 100644--- a/src/gfx/PresentSink.cpp+++ b/src/gfx/PresentSink.cpp@@ -7,6 +7,7 @@#include <format>#include <chrono>#include <vector>+#include <mutex>#include "veyra/Log.h"#include "veyra/diagnostics/CpuStallTrace.h"@@ -28,9 +29,18 @@ std::optional<bool> PresentSink::queryHdrDisplayActive(HWND window,HMONITOR* queconst auto monitor=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);if(queriedMonitor)*queriedMonitor=monitor;if(!monitor)return std::nullopt;+ static ComPtr<IDXGIFactory1> cachedFactory;static std::mutex factoryMutex;ComPtr<IDXGIFactory1> factory;- auto hr=CreateDXGIFactory1(IID_PPV_ARGS(&factory));- if(FAILED(hr)){log::warn("display-color",std::format("CreateDXGIFactory1 query failed hr=0x{:X}",unsigned(hr)));return std::nullopt;}+ {+ std::lock_guard lock(factoryMutex);+ if(cachedFactory&&!cachedFactory->IsCurrent())cachedFactory.Reset();+ if(!cachedFactory){+ const auto hr=CreateDXGIFactory1(IID_PPV_ARGS(&cachedFactory));+ if(FAILED(hr)){log::warn("display-color",std::format("CreateDXGIFactory1 query failed hr=0x{:X}",unsigned(hr)));cachedFactory.Reset();return std::nullopt;}+ }+ factory=cachedFactory;+ }+ HRESULT hr=S_OK;for(UINT a=0;;++a){ComPtr<IDXGIAdapter1> adapter;hr=factory->EnumAdapters1(a,&adapter);if(hr==DXGI_ERROR_NOT_FOUND)break;diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex 2142bb6a..2362904e 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -2011,6 +2011,10 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame}failedBackend_=engine::FailedBackend::None;if(runFg)fgHistorySkipped_=false;+ // uploadFences_ doubles as the DLSS presentation-queue handoff fence for+ // the real frame (presentationReadyFence): it must cover the FG lists that+ // transition videoFrame_[parity] back to COMMON. Recording it before FG+ // (sweep A2, tried 2026-09-22) raised cross-queue barrier errors.uploadFences_[parity]=ring_.lastSignaledValue();prevPtsMs_ = ptsMs;@@ -2035,12 +2039,12 @@ bool EnhanceGraph::resolveFrame(FrameOutputs& out,uint32_t index)auto& frame=out.batch.frames[index];if(!frame.lease||!frame.lease->ready())return false;if(frame.kind!=FrameKind::Generated||frame.validity!=GenerationValidity::Pending)return true;- void* data=nullptr;D3D12_RANGE range{0,4};- HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);- if(FAILED(hr)){frame.validity=GenerationValidity::Failed;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}- const bool disabled=*static_cast<uint8_t*>(data)!=0;+ // Readback heaps may stay mapped; the 4-byte status is read directly.+ auto& mapped=fgDisableMapped_[frame.lease->slot];+ if(!mapped){D3D12_RANGE range{0,4};void* data=nullptr;const HRESULT hr=fgDisableReadback_[frame.lease->slot]->Map(0,&range,&data);+ if(FAILED(hr)){frame.validity=GenerationValidity::Failed;veyra::log::error("fg-status",std::format("Map hr=0x{:X}",unsigned(hr)));return true;}mapped=static_cast<const volatile uint8_t*>(data);}+ const bool disabled=*mapped!=0;const bool rejected=disabled||out.contentDuplicate;- D3D12_RANGE written{0,0};fgDisableReadback_[frame.lease->slot]->Unmap(0,&written);frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;if(veyra::log::verboseFrameLogs())veyra::log::info("fg-status",std::format("batch={} frame={} epoch={} revision={} subframe={} fence={} disable={} valid={}",out.batch.batchId,out.realFrameIndex,out.batch.identity.epoch,out.batch.identity.settingsRevision,frame.subframe,frame.lease->readyFence,disabled,!rejected));@@ -2202,7 +2206,7 @@ void EnhanceGraph::shutdown()for(unsigned i=0;i<2;++i){if(upRgb_[i]&&mappedRgb_[i])upRgb_[i]->Unmap(0,nullptr);mappedRgb_[i]=nullptr;upRgb_[i].Reset();}downsamplePass_={};residualPass_={};flowAdaptPass_={};nrTemporal_.close();nrInput_.Reset();residualRgba_.Reset();nrFlow_.Reset();baseFlow_.Reset();- for(unsigned i=0;i<kGeneratedPoolSlots;++i){fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();+ for(unsigned i=0;i<kGeneratedPoolSlots;++i){if(fgDisableMapped_[i]&&fgDisableReadback_[i]){D3D12_RANGE written{0,0};fgDisableReadback_[i]->Unmap(0,&written);}fgDisableMapped_[i]=nullptr;fgDisable_[i].Reset();fgDisableReadback_[i].Reset();generatedLeases_[i].reset();genFrame_[i].Reset();}for(auto& lease:realLeases_)lease.reset();fgDisableInit_.Reset();encPass_ = ComputePass{};blitPass_ = ComputePass{};hdrVideoSrPass_={};yuvPass_ = ComputePass{};diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cppindex ee63b4cb..9b241690 100644--- a/src/sink/CaptureAudioSession.cpp+++ b/src/sink/CaptureAudioSession.cpp@@ -25,7 +25,21 @@ struct CaptureAudioSession::Impl : AudioPcmSource {std::condition_variable wake;std::deque<Chunk> input;size_t inputBytes=0,convertingBytes=0;- std::deque<float> pcm;+ // PCM queue: contiguous storage with a head cursor instead of a deque.+ // pull() used to copy and pop_front one sample at a time under the mutex+ // (8ch/48k: ~3840 deque operations per 10 ms) while the capture thread+ // waited on the same lock (sweep 2026-09-22 C5).+ struct PcmQueue {+ std::vector<float> data;size_t head=0;+ size_t size()const{return data.size()-head;}+ bool empty()const{return size()==0;}+ void clear(){data.clear();head=0;}+ const float* begin()const{return data.data()+head;}+ float operator[](size_t i)const{return data[head+i];}+ void append(const float* first,const float* last){compact();data.insert(data.end(),first,last);}+ void popFront(size_t n){head=std::min(data.size(),head+n);if(head==data.size())clear();}+ void compact(){if(head>=65536&&head*2>=data.size()){data.erase(data.begin(),data.begin()+ptrdiff_t(head));head=0;}}+ } pcm;double headPts=0;AudioFrameTimeline pcmTimeline;uint64_t pcmHead=0,pcmTail=0;@@ -48,7 +62,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {void clearPcmLocked(){pcm.clear();haveHead=false;pcmTimeline.clear();pcmHead=pcmTail=0;pullEnd.reset();}void clearPcm(){std::lock_guard lock(mutex);clearPcmLocked();queueChanged();}void discardPcm(size_t frames){- for(size_t i=0;i<frames*layout.channels;++i)pcm.pop_front();pcmHead+=frames;+ pcm.popFront(frames*layout.channels);pcmHead+=frames;headPts=pcmTimeline.at(double(pcmHead)).value_or(headPts);pcmTimeline.discardBefore(pcmHead);queueChanged();}@@ -57,7 +71,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {std::lock_guard lock(mutex);const size_t take=std::min(frames,pcm.size()/layout.channels);*pts=haveHead?headPts:-1;- for(size_t i=0;i<take*layout.channels;++i)dst[i]=pcm[i];+ if(take)std::memcpy(dst,pcm.begin(),take*layout.channels*sizeof(float));recording.pulled(dst,take*layout.channels);discardPcm(take);pullEnd=take?std::optional<double>(headPts):std::nullopt;return take;@@ -236,7 +250,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {}else{if(!haveHead){headPts=start;haveHead=true;}pcmTimeline.append(pcmTail,count,start,end);pcmTail+=count;- pcm.insert(pcm.end(),converted.begin(),converted.begin()+size_t(count)*layout.channels);+ pcm.append(converted.data(),converted.data()+size_t(count)*layout.channels);}queueChanged();}diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cppindex 8b377951..8cb472bb 100644--- a/src/sink/NvencD3D12Encoder.cpp+++ b/src/sink/NvencD3D12Encoder.cpp@@ -25,7 +25,11 @@ struct NvencD3D12Encoder::Impl {PacketWriter writer;std::vector<uint8_t> sequence;struct Slot {ComPtr<ID3D12Resource> input,output;NV_ENC_REGISTERED_PTR registeredIn=nullptr,registeredOut=nullptr;NV_ENC_INPUT_PTR mappedIn=nullptr,mappedOut=nullptr;NV_ENC_INPUT_RESOURCE_D3D12 in{};NV_ENC_OUTPUT_RESOURCE_D3D12 out{};uint64_t value=0;bool pending=false;};std::array<Slot,4> slots;- bool check(NVENCSTATUS code,const char* op){const char* detail=code!=NV_ENC_SUCCESS&&encoder&&api.nvEncGetLastErrorString?api.nvEncGetLastErrorString(encoder):"";if(!detail)detail="";veyra::log::info("nvenc",std::format("{} status={} detail={}",op,int(code),detail));if(code!=NV_ENC_SUCCESS){const auto text=std::format("{} status={} {}",op,int(code),detail);error.assign(text.begin(),text.end());}return code==NV_ENC_SUCCESS;}+ unsigned successLogs=0;+ bool check(NVENCSTATUS code,const char* op){const char* detail=code!=NV_ENC_SUCCESS&&encoder&&api.nvEncGetLastErrorString?api.nvEncGetLastErrorString(encoder):"";if(!detail)detail="";+ // Success is logged for the first calls only; per-frame encode/lock/unlock+ // at 4X 60 fps produced 720 lines/s (sweep 2026-09-22 E1). Failures always log.+ if(code!=NV_ENC_SUCCESS||successLogs<24||veyra::log::verboseFrameLogs()){if(code==NV_ENC_SUCCESS)++successLogs;veyra::log::info("nvenc",std::format("{} status={} detail={}",op,int(code),detail));}if(code!=NV_ENC_SUCCESS){const auto text=std::format("{} status={} {}",op,int(code),detail);error.assign(text.begin(),text.end());}return code==NV_ENC_SUCCESS;}bool drain(Slot& s){if(!s.pending)return true;if(fence->GetCompletedValue()<s.value){if(FAILED(fence->SetEventOnCompletion(s.value,event))||WaitForSingleObject(event,10000)!=WAIT_OBJECT_0)return false;}diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex 3eea2dda..c6d23494 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -339,6 +339,37 @@ bool AudioRenderer::copyPcm(BYTE* destination,const float* input,size_t frames){std::memcpy(destination,mixed_.data(),frames*outputFormat_.channels*sizeof(float));return true;}+struct AudioRenderer::EndpointNotifier : IMMNotificationClient {+ std::atomic<HRESULT>* error;std::atomic<unsigned long> refs{1};+ explicit EndpointNotifier(std::atomic<HRESULT>* target):error(target){}+ ULONG STDMETHODCALLTYPE AddRef()override{return ULONG(++refs);}+ ULONG STDMETHODCALLTYPE Release()override{const ULONG n=ULONG(--refs);if(!n)delete this;return n;}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;if(id==__uuidof(IUnknown)||id==__uuidof(IMMNotificationClient)){*pp=this;AddRef();return S_OK;}*pp=nullptr;return E_NOINTERFACE;}+ HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR,DWORD)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR,const PROPERTYKEY)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow,ERole role,LPCWSTR)override{+ if(flow==eRender&&role==eConsole){+ // Same code the write path reports when the device disappears; the+ // pipeline thread treats it as a recoverable endpoint loss.+ error->store(AUDCLNT_E_DEVICE_INVALIDATED);+ log::info("audio","default render endpoint changed; scheduling endpoint rebuild");+ }+ return S_OK;+ }+};+void AudioRenderer::registerEndpointNotification(){+ if(!enum_||notifier_)return;+ notifier_=new EndpointNotifier(&lastError_);+ const HRESULT hr=enum_->RegisterEndpointNotificationCallback(notifier_);+ if(FAILED(hr)){log::warn("audio",std::format("RegisterEndpointNotificationCallback hr=0x{:08X}; device changes recover on the next write error",unsigned(hr)));notifier_->Release();notifier_=nullptr;}+}+void AudioRenderer::unregisterEndpointNotification(){+ if(!notifier_)return;+ if(enum_)enum_->UnregisterEndpointNotificationCallback(notifier_);+ notifier_->Release();notifier_=nullptr;+}bool AudioRenderer::start(AudioFormat input,double requestedBufferMs){std::lock_guard endpointLock(endpointMutex_);@@ -357,6 +388,7 @@ bool AudioRenderer::start(AudioFormat input,double requestedBufferMs)if (!checked(hr,"Create MMDeviceEnumerator")) return false;hr = enum_->GetDefaultAudioEndpoint(eRender, eConsole, &device_);if (!checked(hr,"GetDefaultAudioEndpoint")) return false;+ registerEndpointNotification();hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,reinterpret_cast<void**>(&client_));if (!checked(hr,"Activate AudioClient")) return false;@@ -590,6 +622,7 @@ void AudioRenderer::shutdown()std::lock_guard endpointLock(endpointMutex_);if (client_) { (void)client_->Stop(); (void)client_->Reset(); }#define REL(x) if (x) { x->Release(); x = nullptr; }+ unregisterEndpointNotification();REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);swr_free(&channelMix_);#undef RELdiff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex a15a2f40..d0487a30 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -4,6 +4,7 @@#include "veyra/source/CaptureTiming.h"#include "veyra/source/CaptureMediaType.h"#include "veyra/source/NativeCaptureSink.h"+#include <avrt.h>#include "veyra/source/CaptureBuffer.h"#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureCodec.h"@@ -384,6 +385,9 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {}}HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{+ // Register the DirectShow delivery thread with MMCSS once; the handle+ // lives for the thread (revert happens when the thread exits).+ static thread_local HANDLE mmcss=[]{DWORD index=0;HANDLE h=AvSetMmThreadCharacteristicsW(L"Pro Audio",&index);if(!h)log::warn("capture","MMCSS unavailable for the capture callback thread");return h;}();(void)mmcss;const auto arrival=Clock::now();BYTE* data=nullptr;REFERENCE_TIME sampleStart=0,sampleEnd=0;const bool sampleTime=sample&&sample->GetTime(&sampleStart,&sampleEnd)==S_OK;diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cppindex 27fa1169..6edfbc0e 100644--- a/src/source/MediaFileSource.cpp+++ b/src/source/MediaFileSource.cpp@@ -16,7 +16,20 @@ extern "C" {#include <libavutil/mastering_display_metadata.h>}+#include <thread>+#include <algorithm>namespace veyra::source {+namespace {+// File playback software decode: frame threading up to four workers regardless+// of resolution (1080p60 H.264/HEVC on one thread fell below real time when+// hardware decode was unavailable, sweep 2026-09-22 C2). Live capture keeps+// its own low-latency single-thread policy in CaptureCompressedDecoder.+unsigned softwareDecodeThreads(int, int) {+ const unsigned cores = std::max(1u, std::thread::hardware_concurrency());+ return std::clamp(cores / 2u, 2u, 4u);+}+}+namespace {@@ -49,7 +62,7 @@ bool MediaFileSource::fallbackToSoftware(std::string_view reason)}const auto* params = demuxer_.videoCodecParameters();if (params == nullptr || !decoder_.openSoftware(params, demuxer_.videoTimeBaseNum(),- demuxer_.videoTimeBaseDen(), params->width > 1920 || params->height > 1080 ? 4u : 1u)) {+ demuxer_.videoTimeBaseDen(), softwareDecodeThreads(params->width, params->height))) {veyra::log::error("source-file", "software fallback decoder open failed");return false;}@@ -170,7 +183,7 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)}if (!decoderOpen) {decoderOpen = decoder_.openSoftware(params, demuxer_.videoTimeBaseNum(),- demuxer_.videoTimeBaseDen(), params->width>1920||params->height>1080?4u:1u);+ demuxer_.videoTimeBaseDen(), softwareDecodeThreads(params->width, params->height));}if (!decoderOpen) {veyra::log::error("source-file", "decoder open failed");@@ -304,8 +317,17 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrameout.sequence = sequence_;const int tbNum = decoder_.frameTimeBaseNum();const int tbDen = decoder_.frameTimeBaseDen();- if (frame->pts != AV_NOPTS_VALUE && tbDen > 0) {- out.pts = pipeline::Rational{frame->pts * static_cast<int64_t>(tbNum), tbDen};+ // Prefer the container PTS; fall back to FFmpeg's best-effort estimate and+ // finally the packet DTS. Raw elementary streams and some TS/AVI muxes+ // leave pts unset on individual frames, which used to stop playback+ // outright (sweep 2026-09-22 B4). Still never invent a value.+ const int64_t stamp = frame->pts != AV_NOPTS_VALUE ? frame->pts+ : frame->best_effort_timestamp != AV_NOPTS_VALUE ? frame->best_effort_timestamp+ : frame->pkt_dts;+ if (stamp != AV_NOPTS_VALUE && tbDen > 0) {+ out.pts = pipeline::Rational{stamp * static_cast<int64_t>(tbNum), tbDen};+ if (frame->pts == AV_NOPTS_VALUE && (ptsFallbacks_++ % 300) == 0)+ veyra::log::info("source-file", std::format("frame pts missing; using {} (count={})", frame->best_effort_timestamp != AV_NOPTS_VALUE ? "best_effort_timestamp" : "pkt_dts", ptsFallbacks_));} else {out.pts = pipeline::Rational::unknown(); // never fabricate a timestamp}diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cppindex 78b51e83..460a9223 100644--- a/tests/unit/LiveGpuSchedulerTests.cpp+++ b/tests/unit/LiveGpuSchedulerTests.cpp@@ -157,10 +157,10 @@ int main(){veyra::engine::LivePairLatency phase;check(phase.select(10000000,420000,333333,4)==420000,"unknown live readiness keeps legacy phase");for(int i=0;i<8;++i)phase.observe(10000000+i,370000);- check(phase.select(10000008,420000,333333,4)==417500,"phase advance is gradual rather than a burst");+ check(phase.select(10000008,420000,333333,4)==415000,"phase advance is gradual rather than a burst");for(int i=0;i<32;++i)phase.select(10000100+i,420000,333333,4);- check(phase.select(10000200,420000,333333,4)==380000,"4X keeps measured readiness plus jitter margin");- phase.observe(10000201,410000);+ check(phase.select(10000200,420000,333333,4)==375000,"4X keeps measured readiness plus jitter margin");+ phase.observe(10000201,415000); // legacy 420000 minus the 0.5 ms margincheck(phase.select(10000202,420000,333333,4)==420000,"slow batch immediately restores conservative phase");check(phase.select(21000000,420000,333333,4)==420000,"stale readiness cannot shorten a new pair");for(unsigned multiplier:{2u,4u,6u}){@@ -170,7 +170,7 @@ int main(){for(int i=0;i<8;++i)phase.observe(30000000+i,needed);auto last=interval+90000;bool bounded=true;for(int i=0;i<80;++i){const auto delay=phase.select(30000100+i,interval+90000,interval,multiplier);- bounded&=delay>=needed&&delay<=interval+90000&&last-delay<=2500;last=delay;}+ bounded&=delay>=needed&&delay<=interval+90000&&last-delay<=5000;last=delay;}check(bounded,"2X/4X/6X preserves readiness and bounded phase at 29.97 Hz");phase.reset();check(phase.select(30001000,interval+90000,interval,multiplier)==interval+90000,"reset discards earlier readiness");}