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: show completed processing FPS and sample 60fps capture at 30fps
Veyra Goal Agentf6d24d3798e4
diff --git a/CMakeLists.txt b/CMakeLists.txtindex fee6ecf7..f669989f 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -158,6 +158,8 @@ endif()# YUV→RGB shader is shared between the media pipeline and the harness.veyra_add_compute_shader(veyra_shader_yuv_to_rgb YuvToLinearRgb)veyra_add_compute_shader(veyra_shader_rgb_to_linear RgbToLinear)+veyra_add_compute_shader(veyra_shader_yuy2_to_linear Yuy2ToLinear)+add_dependencies(veyra_shader_rgb_to_linear veyra_shader_yuy2_to_linear)# ScaleBlit: working frame -> swapchain backbuffer (Phase 6 present path).veyra_add_compute_shader(veyra_shader_scale_blit ScaleBlit)# Nv12Upload: byte buffer -> luma/chroma planes (copy-free upload path).@@ -387,6 +389,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform# composes veyra_media; no second decode implementation exists.add_dependencies(veyra_pipeline veyra_shader_nr_downsample veyra_shader_nr_residual veyra_shader_flow_adapt)add_library(veyra_sources STATIC+ src/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cppsrc/source/CaptureCardSource.cpp)@@ -427,6 +430,22 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_executable(veyra_repair_parameter_tests tests/integration/RepairParameterTests.cpp)add_executable(veyra_image_dimension_tests tests/integration/ImageDimensionTests.cpp)+ add_executable(veyra_capture_color_probe tools/capture_color_probe/main.cpp)+ add_executable(veyra_capture_color_tests tests/unit/CaptureColorContractTests.cpp)+ add_executable(veyra_presentation_worker_tests tests/unit/PresentationWorkerTests.cpp)+ target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_presentation_worker_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ add_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)+ target_compile_features(veyra_live_presentation_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_live_presentation_tests PRIVATE veyra_engine)+ target_compile_features(veyra_capture_color_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_capture_color_tests PRIVATE veyra_sources)+ add_executable(veyra_yuy2_color_tests tests/integration/Yuy2ColorTests.cpp)+ target_compile_features(veyra_yuy2_color_tests PRIVATE cxx_std_20)+ target_link_libraries(veyra_yuy2_color_tests PRIVATE veyra_engine)+ target_compile_features(veyra_capture_color_probe PRIVATE cxx_std_20)+ target_compile_definitions(veyra_capture_color_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_link_libraries(veyra_capture_color_probe PRIVATE veyra_engine)target_compile_features(veyra_image_dimension_tests PRIVATE cxx_std_20)target_include_directories(veyra_image_dimension_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})target_compile_definitions(veyra_image_dimension_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}")diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex a17bbd14..8710b3d7 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -111,7 +111,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();add(L"STATIC",L"补帧与运动估算",1103,0,1,12,12,-1,30);combo(202,1,52,{L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧"});combo(204,1,104,{L"NR / DLSS光流 · 性能",L"NR / DLSS光流 · 平衡",L"NR / DLSS光流 · 质量"});- combo(205,1,156,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏"});+ combo(205,1,156,{L"采用源时间戳",L"自动识别内容节奏",L"识别30fps内容节奏",L"识别50fps内容节奏",L"识别60fps内容节奏",L"采集60→30fps处理(PS5 30帧)"});add(L"STATIC",L"FRUC倍率越高,耗时越多。光流档位用于NR/DLSS;FRUC内部自动控制。补帧需等待下一张源帧,倍率不等于实测显示帧率。",1104,0,1,12,210,-1,100);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);send(301,EM_SETLIMITTEXT,48,0);diff --git a/apps/veyra/main.cpp b/apps/veyra/main.cppindex 18e62595..225520c7 100644--- a/apps/veyra/main.cpp+++ b/apps/veyra/main.cpp@@ -1,3 +1,13 @@#include <windows.h>+#include "veyra/Log.h"+#include "veyra/RuntimePaths.h"int runVeyraApp(HINSTANCE,int);-int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){return runVeyraApp(instance,show);}+int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,LPWSTR,int show){+ const auto logPath=(veyra::runtime::logsDirectory()/L"veyra-app.log").wstring();+ (void)veyra::Logger::instance().openFile(logPath);+ veyra::log::info("app", "Veyra GUI session started");+ const int result=runVeyraApp(instance,show);+ veyra::log::info("app", "Veyra GUI session stopped");+ veyra::Logger::instance().flush();+ return result;+}diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 00f88097..9850368c 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -30,7 +30,7 @@#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};+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,FpsLabel,VideoSurface=1000};veyra::engine::EngineController engine;veyra::engine::ExportJobManager exportJob;veyra::ui::UiSessionState uiState;@@ -163,8 +163,10 @@ void layout(){pos(playbackBar,0,h-88,w,88,full&&fullControls);pos(seekBar,full?0:pro?tx:g.left,barTop-5,full?w:pro?tw:g.viewWidth,12,transport&&!target.capture&&!target.image&&!(pro&&showDiagnostics&&!full));surface(seekBar,pro&&!full?panel:cinemaPanel);const bool daily=!pro&&!full&&!transition.running;TransportLayout controls(tw,daily);- put(TimeLabel,tx,barTop+10,std::min(300,tw/2),20,transport);- put(MediaTitle,tx+std::min(310,tw/2),barTop+10,tw-std::min(310,tw/2),20,transport);+ const int timeWidth=std::min(240,std::max(0,(tw-154)/2));+ put(TimeLabel,tx,barTop+10,timeWidth,20,transport);+ put(MediaTitle,tx+timeWidth+8,barTop+10,std::max(1,tw-timeWidth-170),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,260,44,44);if(daily)slot(Master,controls.master);slot(Sr,controls.sr);@@ -174,7 +176,7 @@ void layout(){icon(GetDlgItem(mainWindow,Open),Icon::Video,controls.captions);icon(GetDlgItem(mainWindow,Capture),Icon::Capture,controls.captions);icon(GetDlgItem(mainWindow,Master),Icon::Enhance,pro||controls.captions);icon(GetDlgItem(mainWindow,Sr),Icon::Upscale,true);icon(GetDlgItem(mainWindow,ModeSwitch),pro?Icon::PanelClose:Icon::PanelOpen,pro||controls.captions);- for(int id:{Open,Capture,Recent,Master,Sr,Play,Stop,Mute,Volume,Subtitle,Fullscreen,TimeLabel,MediaTitle,ModeSwitch})surface(GetDlgItem(mainWindow,id),pro&&!full?panel:cinemaPanel);+ for(int id:{Open,Capture,Recent,Master,Sr,Play,Stop,Mute,Volume,Subtitle,Fullscreen,TimeLabel,MediaTitle,FpsLabel,ModeSwitch})surface(GetDlgItem(mainWindow,id),pro&&!full?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);@@ -188,7 +190,7 @@ void layout(){auto batch=BeginDeferWindowPos(int(placements.size()));for(const auto& p:placements){if(!batch)break;batch=DeferWindowPos(batch,p.child,nullptr,p.x,p.y,p.width,p.height,p.flags);}if(batch)EndDeferWindowPos(batch);else for(const auto& p:placements)SetWindowPos(p.child,nullptr,p.x,p.y,p.width,p.height,p.flags);auto front=[&](HWND child){if(child&&IsWindowVisible(child))SetWindowPos(child,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE|SWP_NOREDRAW);};- front(playbackBar);for(int id:{Open,Capture,Recent,Master,Sr,Play,Stop,Mute,Volume,Subtitle,Fullscreen,WindowMin,WindowClose,TimeLabel,MediaTitle,ModeSwitch,JobProgress,EmptyTitle,EmptyHint})front(GetDlgItem(mainWindow,id));front(inspector);front(subtitleLabel);if(showDiagnostics&&pro&&!full)front(diagnosticPanel);+ front(playbackBar);for(int id:{Open,Capture,Recent,Master,Sr,Play,Stop,Mute,Volume,Subtitle,Fullscreen,WindowMin,WindowClose,TimeLabel,MediaTitle,FpsLabel,ModeSwitch,JobProgress,EmptyTitle,EmptyHint})front(GetDlgItem(mainWindow,id));front(inspector);front(subtitleLabel);if(showDiagnostics&&pro&&!full)front(diagnosticPanel);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("frameMs={:.3f} animation={}",std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-layoutBegin).count(),transition.running));@@ -228,6 +230,7 @@ control(L"BUTTON",L"视频",ProRailVideo,BS_PUSHBUTTON,0,0,64,44);control(L"BUTTconst 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"处理 0.0 fps",FpsLabel,SS_RIGHT,0,0,154,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);@@ -321,7 +324,9 @@ if(smokeStep==2&&elapsed>3200){engine.pause(false);smokeStep=3;}if(smokeStep==3&&elapsed>4100&&!smokeSave.empty()){engine.saveFrame(smokeSave);smokeStep=4;}if(smokeStep==4&&elapsed>5200&&GetEnvironmentVariableW(L"VEYRA_TEST_LARGE_IMAGE_SAVE_THROW",nullptr,0)){const auto retained=engine.snapshot();if(!retained.failed&&retained.running&&retained.frames>0){engine.saveFrame(smokeSave);smokeStep=5;veyra::log::info("image-save-test","retry after injected allocation failure; result/session retained");}}}auto s=engine.snapshot();const auto subtitleText=uiState.subtitles&&!(showDiagnostics&&uiState.mode==veyra::ui::Mode::Professional&&!full)?veyra::engine::subtitleAt(subtitles,s.position):L"";veyra::ui::updateSubtitleOverlay(subtitleLabel,subtitleText,subtitlePixels);-auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);+const double submittedFps=s.submissionFps.value_or(0.0);+veyra::ui::setText(GetDlgItem(hwnd,FpsLabel),std::format(L"处理 {:.1f} fps",s.fps));+auto text=s.capture?std::format(L"{}\r\n输入 {:.1f} / 已处理 {:.1f} / 显示提交 {:.1f}fps | 回调至Present返回p95 {:.1f}ms(非总延迟)| 丢弃 {} | 有效生成 {}",s.status,s.captureFps,s.fps,submittedFps,s.captureAgeP95Ms,s.captureDropped,s.generated):std::format(L"{}\r\n{:.1f} / {:.1f}秒 已处理 {:.1f}fps 提交迟到 {:+.1f}ms 源帧 {} / 有效生成 {}",s.status,s.position,s.duration,s.fps,s.lateMs,s.frames,s.generated);if(smokeZoom&&startTick&&s.frames>0){const auto elapsed=GetTickCount64()-startTick;if(zoomStep==0&&elapsed>1300){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();zoomBefore=s;RECT r{};GetWindowRect(video,&r);const LPARAM point=MAKELPARAM(r.left+(r.right-r.left)*7/10,r.top+(r.bottom-r.top)/2);if(smokeHover){SetFocus(GetDlgItem(hwnd,ModeSwitch));PostMessageW(hwnd,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);hoverPostedTick=GetTickCount64();zoomStep=4;}else{SendMessageW(video,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA*3),point);zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;}}if(zoomStep==4&&GetTickCount64()-hoverPostedTick>150){zoomStep=std::abs(engine.previewView().zoom-1.728f)<.001f?1:-1;veyra::log::info("preview-hover-test",std::format("root-message routed={} focusIsButton={}",zoomStep==1,GetFocus()==GetDlgItem(hwnd,ModeSwitch)));}@@ -342,8 +347,8 @@ setText(GetDlgItem(hwnd,Mute),!s.audioAvailable?L"无音轨":s.muted?L"静音":LEnableWindow(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.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);+setText(GetDlgItem(hwnd,TimeLabel),s.capture?std::format(L"输入 {:.1f} fps{}",s.captureFps,s.captureHalfRate?L" · 60→30":s.applied.content==veyra::engine::ContentRate::Capture60To30?L" · 不适用":L""):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 · 显示提交 {:.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.frames>0&&!s.applying,s.running&&s.frames>0);setText(GetDlgItem(hwnd,JobProgress),job.message+std::format(L" {}% · 查看",int(job.progress*100)));ShowWindow(GetDlgItem(hwnd,JobProgress),job.state==veyra::engine::ExportState::Idle||full?SW_HIDE:SW_SHOW);setText(GetDlgItem(hwnd,EmptyTitle),s.failed?L"播放已停止":L"开始观看");setText(GetDlgItem(hwnd,EmptyHint),s.failed?s.status:L"打开本地视频,或连接采集卡\n精细调整与原生导出在专业模式中");ShowWindow(GetDlgItem(hwnd,EmptyTitle),SW_HIDE);ShowWindow(GetDlgItem(hwnd,EmptyHint),SW_HIDE);diff --git a/docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md b/docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.mdnew file mode 100644index 00000000..a1867e5d--- /dev/null+++ b/docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md@@ -0,0 +1,255 @@+# 基础画质与性能修复执行文档 — 2026-09-09++> 后续执行状态:用户取消实卡A/B后,原生转换与调度修复已实施并通过离线GPU/软件短测。见 [实际修复记录](BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md)。本文下方为开工前审计与原计划,不能当作最新“未实施”状态。++状态:**排查已有实证,产品修复尚未实施;Phase 7 继续 in_progress,基础画质验收重开。**++本文件对应用户最新反馈:OBS 原始采集预览更清晰,Veyra 出现色彩断层;Magpie 叠加增强后体感与 GPU 占用明显更好。用户要求先查原因、交接给下一位 Agent 修复,并授权必要时复用开源源码。本轮不继续堆功能、不重做前端、不加重导出完整性检查。单次测试不超过 300 秒,可以进行多次独立短测。++本文件覆盖旧交接中“先做统计窗口”的优先顺序:**先取得基础画质失真的同帧证据并修复,再优化同条件增强性能。** 用户体感是缺陷报告,不可因一次旧 gate 通过而驳回;同样不能把尚未证实的猜测写成根因。++## 1. 接手时先看这六条++1. 当前源码 HEAD:`181a047269a761d93b5e408c4b0008fa8477c89d`,分支 `agent/veyra-v1-loop`。开工时已有未提交交接/loop 文档和两份竞品方案;保留它们,不 reset/clean。+2. **确实发现采集设计缺口:** `CaptureCardSource.cpp` 强制 DirectShow 输出 RGB32,丢失原生 YUY2 与颜色来源信息;OBS 当前实测是直接接收 YUY2。这是第一条需要用同帧像素证实/排除的失真链。+3. **没有证明整个 GPU bypass 都错误。** 本轮真实 RTX GPU 窄测,256×64 RGB 多色阶图与 BGR0 红蓝细线经共享图关闭增强后的最大 8-bit 通道误差均为 0。此测试未经过实卡转换、窗口缩放、DWM 或显示器。+4. **当前找到的 Magpie 日志不支持“同样三项全开输出 4K”。** 日志中的 SR/NR/FG 多为 2560×1440,较早 SR 为 1535×971→2276×1440。不能由这些数据推算 3840×2160 下的优势倍数。继续排查 Veyra,不能用此差异替基础画质缺陷开脱。+5. **DLL 多不等于速度快或功能完整。** Veyra 已有可工作的 D3D12 NGX 视频 SR;Magpie 走另一套 VFX/CUDA 接口。没有证据证明 Veyra 少打包了其当前后端运行所必需的 DLL。不要为了“补全依赖”先塞一套 VFX SDK。+6. `Likely7/Veyra-NRVideo` 的 `v0.0.1` **已公开发布**。2026-09-09 本轮 `gh release view` 返回 `isDraft=false,isPrerelease=false,publishedAt=2026-09-09T11:00:36Z`。不要再向用户说尚未发布。本轮未改动远端 Release;后续不要把旧版标为画质已验收。++## 2. 本轮证据与边界++本地证据目录(gitignored):`logs/obs-magpie-rootcause-20260909/`。++| 证据 | 内容 |+| --- | --- |+| `evidence/magpie.log`、`evidence/magpie.1.log` | 用户实测产生的原始日志快照,避免下次启动轮转覆盖 |+| `evidence/magpie-config.json` | 用户最后保存的效果组快照;不可当作较早所有测试的配置 |+| `evidence/obs.log` | OBS 2026-09-09 19:22–19:55 会话;含真实采集类型/分辨率/帧率 |+| `evidence/magpie-build-manifest.json` | Magpie 0.6.6,源码 commit `9824d758b162ad3c5b5acc81e2e14c83f138e13d` |+| `upstream/Magpie/` | 上述精确 commit 的 SR/NR/FG/VFX/光流/Renderer 源码及 LICENSE,仅供本地对照;未执行其脚本或编译 |+| `upstream/obs-win-dshow.cpp` | OBS commit `012c6c23c73283ee5591ae00d08af14d9eeb8279` 的官方采集实现;这是源码参考,不宣称与用户安装 OBS 完全同版 |+| `build_probe.py`、`baseline_probe.cpp`、`build_probe.cmd` | 本轮诊断入口:复用当前产品库与现有测试函数,不改生产源码 |+| `build-probe.log`、`baseline-probe.log`、`baseline-result.json` | 窄测构建/执行与探针 EXE 身份 |+| `baseline-images/256x64-off.png` | GPU 基础图输出;诊断回读仅用于审计,不加入正常采集路径 |+| `audit-manifest.json` | 本轮保存的日志、代码、二进制/Shader 身份与状态,见生成记录 |++本轮命令与实际结果:++```powershell+git status --short+git log -3 --oneline+python logs/obs-magpie-rootcause-20260909/build_probe.py+gh release view v0.0.1 -R Likely7/Veyra-NRVideo --json url,isDraft,isPrerelease,publishedAt+python logs/obs-magpie-rootcause-20260909/finalize_audit.py+git diff --check+```++探针最终构建与运行均 exit 0,输出:++```text+IMAGE_DIMENSION 256x64 nr=0 maxError8=0 nrEvaluations=0 pass=1+CAPTURE_RGB nr=0 maxError8=0 cuts=1 nrEvaluations=0 nvof=0 pass=1+```++首次探针构建包装脚本因只匹配 `/c`、实际 Ninja 使用 `-c` 而 StopIteration;修正命令匹配后完成。不是产品编译或 GPU 故障。单次最终调用约 5.4 秒。++交接整理脚本仅生成本地证据 manifest 并检查 JSON/身份,未运行 GPU;保存 39 项审计文件与 28 项产品/Shader/运行时身份,原版 NR 哈希匹配。只读比较确认既有控制面漂移为 AGENTS.md、README.md;没有更改锁定值。++**未执行:** 新的实卡 A/B、同帧 OBS/Veyra截图、同配置 Magpie/Veyra 性能测试、SR/NR/FG 本轮 Create/Evaluate、完整 delivery gate、独立 Reviewer。当前运行的 Veyra 会话未关闭。不要把用户日志和历史测试冒充本轮受控实验。++## 3. Magpie 实际测了什么++### 3.1 从日志纠正比较条件++OBS `evidence/obs.log`:++- 19:41:01:USB3 Video,1920×1080、60fps、YUY2,buffering disabled。+- 19:41:12 起一段:3840×2160、18fps、YUY2。+- 19:42:09:改回 1920×1080、60fps、YUY2。+- OBS 画布/输出设置是 2560×1440,显示器日志为 2560×1440、100Hz、8-bit SDR。这不代表每个来源都经过编码设置中的 NV12;不能把 OBS 编码输出格式误当预览纹理格式。++Magpie `evidence/magpie.1.log`:++- L1206–1217:NR 1535×971;DLSS SR 1535×971→2276×1440;FG backbuffer 2276×1440、2×;目标矩形 2276×1440。+- L1816–1819:NR 2560×1440;SR 2560×1440→2560×1440;FG 2560×1440、2×。+- L2154–2157:同为 2560×1440,SR 仍为 1:1,光流参数有所变化。++Magpie `evidence/magpie.log`:++- L1155–1166:NR 2560×1440、未开启 NR 输入降分辨率;VFX quality=4,input/output format=28;FG 2560×1440、2×;目标矩形 2560×1440。+- L1531–1541:最后一段 NR 2560×1440 + FG 2560×1440 2×,该段没有 SR 初始化;最后保存的“DLSS5+超分+帧生成”效果组实际上只有 NR 和 FG 两项。+- L1575 以后多个 NR GPU 窗口均值约 9.7–10.1ms;最终呈现 ring 日志 captured 约 35–37fps、queued 约 70–73fps。queued 是提交统计,不是独立测得的物理显示帧率,也不必然等于 HDMI 内容变化率。++4K 是 1440p 的 2.25 倍像素。这里不能据此推导线性耗时比,但应明确它们负载不同。“Ultra”是质量名称,不会自动把输出改为 4K;效果组名字也不能证明内部功能已启用。旧助手曾把界面设置、文件清单和实际处理等同,这些说法不应继续沿用。++### 3.2 可借鉴的实现(已核对精确源码)++| 模块 | Magpie 实际实现 | Veyra 当前实现 | 后续动作 |+| --- | --- | --- | --- |+| 视频 SR | `RTXVideoDenoiser.cpp:106–231`:`NvVFX_CreateEffect("VideoSuperRes")`、RGBA U8 CUDA图像、D3D11映射/Transfer、`NvVFX_Run`,最后显式 stream synchronize | `VideoSrBackend.cpp:10–41`:D3D12 NGX `Feature_Reserved16`,`Input1/Output` 与 `VSR.QualityLevel` | 接口不同;用同帧/同尺寸/同质量比较后才决定要不要增加 VFX 后端。不要宣称对方零复制、零等待 |+| 游戏 SR | `DLSSSRUpscaler.cpp:140–156`:Balanced、preset J、低分辨率 motion、AutoExposure;输入输出来自效果链 | `DlssSrBackend.cpp:90–104`:线性 FP16、IsHDR+AutoExposure、输出尺寸 motion | 核对资源语义,不机械复制标志。先做同尺寸成本与画质对照;SR flags 影响质量也影响成本 |+| NR 缩放 | `DLSSNRFilter.cpp`:Lanczos2 抗混叠降采样,FP16有符号残差,Catmull-Rom 分离两遍上采样 | `NrDownsample.hlsl` 区域平均、`NrResidualComposite.hlsl` 2×2边缘引导残差 | 纹理、渐变、光晕、闪烁同源评测;更复杂滤波也可能更慢/振铃,不能只看锐度 |+| 处理顺序 | 用户早期日志 NR 在1535×971,SR之后才到2276×1440;效果组允许顺序配置 | 固定 SR→NR→FG,实时NR会再降采样并回填 | 保持现有顺序作为基线;可另做 NR→SR→FG 实验比较。不能未经比较就替换默认或把较低NR尺寸算成算法提速 |+| 光流 | 可选双向;用户日志 profile=2S、grid2、SLOW,零depth | 源分辨率 NVOF、grid/置信度、FlowAdapt给不同consumer | 优先复用已验证的光流语义和时序测试;不加常驻深度来碰运气 |+| 调度 | 有界呈现ring=2,独立前后端发布及fence;仍有CPU等待 | `EngineController.cpp:180–205` 在同一循环等待整批FG,再按PTS呈现,完成后才取下一源帧 | 解耦源/处理/呈现并保留lease和有界背压,不是删除fence |++精确源码入口:++- [Magpie VFX 后端](https://github.com/SAOG0721/Magpie/blob/9824d758b162ad3c5b5acc81e2e14c83f138e13d/src/Magpie.Core/RTXVideoDenoiser.cpp)+- [Magpie NR 与滤波](https://github.com/SAOG0721/Magpie/blob/9824d758b162ad3c5b5acc81e2e14c83f138e13d/src/Magpie.Core/DLSSNRFilter.cpp)+- [Magpie 呈现调度](https://github.com/SAOG0721/Magpie/blob/9824d758b162ad3c5b5acc81e2e14c83f138e13d/src/Magpie.Core/Renderer.cpp)+- [OBS DirectShow 输入](https://github.com/obsproject/obs-studio/blob/012c6c23c73283ee5591ae00d08af14d9eeb8279/plugins/win-dshow/win-dshow.cpp)++## 4. 基础画质:已确定的事实和待证实根因++### Q1:采集前置颜色转换不受控(P0,首查)++`src/source/CaptureCardSource.cpp:95–114`:SetFormat选择上游YUY2后,SampleGrabber强制 `MEDIASUBTYPE_RGB32`,再用 `RenderStream` 自动连接。中间允许插入解码/颜色转换filter,但当前没有记录实际插入的CLSID与各pin media type。回调收到的是已转好的8-bit BGR0;随后只设置 `color_range=JPEG`,矩阵/transfer由 `ColorMetadata.h` 默认推断为709/sRGB。++**确认的缺口:** 转换并非 Veyra 可验证的一次显式YUY2→RGB;上游range/matrix/chroma位置/transfer无法从当前packet追溯。默认猜测被包装成完整RGB图后,后续GPU再正确也无法恢复之前丢失的颜色和细节。++**尚未证明:** 是哪个具体filter把这张卡转坏、用了601还是709、是否压缩了范围。不要写成已确认“601误用”或“6-bit量化”。++OBS源码 `win-dshow.cpp:417–438,553–575,1169–1174` 明确把YUY2作为YUY2传给 `obs_source_frame2`,保留每行 `width*2` 和显式颜色参数。可复用其capture格式/元数据处理;不要移植整套OBS界面。++### Q2:显示缩放质量与颜色域(P0/P1)++`src/engine/VideoPresenter.cpp:43–51` 和 `shaders/PresentBlit.hlsl` 使用线性采样器对已编码的RGBA8结果作窗口缩放。`src/gfx/PresentSink.cpp:111–117` 为8-bit UNORM交换链;当前没有显式检查/选择输出色彩空间,也没有最终量化抖动。++已确认只有双线性窗口缩放,缩小时缺少专用抗混叠滤波。它能解释部分细节/边缘观感差,但**不能仅凭这点断言就是用户所见色带的根因**。8-bit SDR本身并非bug;RGB无增强窄测已保留256级输入。直接改10-bit或加deband不能代替找到错误发生的位置。++NR实时回填期间发生的色带应另查 `ParityEncode/Decode`、8-bit Proxy/Neural、残差上采样/饱和裁剪,不可与“所有增强关闭”混为同一问题。++### Q3:缺少真正贯穿采集到显示的画质门禁(P0)++已有 `CaptureSourceTests.cpp` 检查回调、mailbox、读者生命周期、帧龄,没有同帧颜色准确度。已有 `captureRgb(false)` 在**转换后的BGR0入口**注入合成帧,因此即使上游DirectShow转坏它仍然通过。本轮的maxError=0也只能证明这段。++当前证据能把问题范围缩小为:**优先采集原生→RGB转换,以及GPU结果→最终窗口显示;若只在NR开启时出现,则进入NR分支单查。** 色带第一责任节点仍待原始样本确认;禁止把候选原因写成完整闭环根因。++## 5. 性能:代码中确实存在的成本++| 项目 | 位置与事实 | 修复边界 |+| --- | --- | --- |+| 输出尺寸固定冲4K | `ResolutionPlan.h:20`:SR开启就按3840×2160盒子放大;FG也处理base尺寸,不跟随1440p显示窗口 | 明确显示/输出目标,提供源/1440p/2160p或适配窗口;4K仍可选,导出保持选定原生尺寸,不静默降画质 |+| CPU采集RGB扩展与重排 | `CaptureCardSource.cpp:53` RGB32全帧mailbox复制;`EnhanceGraph.cpp:698–717` BGR0逐像素CPU重排为RGBA,再upload | 原生YUY2为2字节/像素,RGB32为4;GPU上传原格式并转换可省CPU重排和部分带宽。别把原始YUY2说成需要NVDEC硬解 |+| 同线程处理+呈现 | `EngineController.cpp:180–205` 完整FG结果等待和deadline等待阻止下一次graph提交 | 有界生产/消费解耦,记录ready/lease/consumer fence;过期只丢允许丢的采集帧/子帧 |+| 逐帧多pass与冗余副本 | `EnhanceGraph.cpp:956–958` 总是复制input/base reference;NR原生尺寸仍经过downsample/残差等pass;源和working同尺寸仍有blit | 根据功能做pass计划与资源复用;相同引用可alias,但不能破坏同帧对比、FG历史或在途资源 |+| 常规事件同步写盘 | `src/base/Log.cpp:write` 每条格式化、锁、写文件和flush;VSR与SR每次Evaluate也记录成功 | 错误/身份/设置事务保留;常规帧事件有界缓冲/聚合,测吞吐与证据丢失计数 |+| 统计跨配置 | `TimingWindow`/lateness/sourceFrames跨revision;每帧为多组1200样本排序 | 按实际applied revision重建统计窗口,低频刷新,区分GPU阶段/CPU等待/源吞吐/提交率 |+| FRUC reset风暴 | `EnhanceGraph.cpp:1072` reset触发worker重建;drop再reset可形成反馈 | 先计原因和耗时,验证轻量reseed等价后替换;不是关闭reset或吞掉错误 |+| GPU/CPU依赖混合测时 | FG阶段包含等待/IPC;不能用单阶段NR表盘说“总延迟” | 使用同批次时间轴;P95相加无意义;GPU利用率并非画质/延迟指标 |++过去实卡日志的低VSR+实时NR约59.51源fps,高VSR+原生NR约30fps,是历史同卡证据。可用来选诊断起点,不能直接与本轮Magpie1440p数据算速度倍数,也不能以“5070不够”结束调查。++## 6. 下一位 Agent 的执行顺序++### R0:保存现场,建立可比输入(必须先做)++- 读取本文和最新AGENTS/HANDOFF,记录git dirty、EXE/Shader/runtime SHA、适配器/驱动/屏幕/设置revision。+- 保留本轮OBS/Magpie快照;用户运行时的设置文件不擅自改写。每个新测试独立run-id,进程有不超过300秒的外部上限。+- 使用固定静止测试信号经HDMI进同一张卡,含黑阶0–32、完整灰阶、近黑彩色渐变、饱和色块、1/2像素彩色细线、斜线与文字。另用同一个有帧号的移动视频测试时序。+- OBS和Veyra必须协商相同卡/针脚/1920×1080 60 YUY2或3840×2160 18 YUY2;确认源输出SDR、范围、画面比例和裁剪一致。不要把不同时间运动画面直接相减。+- 单GPU测试串行。读取用户日志无需抢占设备;需要实卡自动化时先确认进程占用,必要时使用文件重放完成独立部分。++### R1:四段抓帧,锁定色带首次出现的位置(P0,第一条实施任务)++新增仅诊断启用的 `CaptureColorProbe` 和 `CaptureColorContractTests`,正常播放不开启回读。生产输入元数据扩展留在共享source/pipeline接口。++抓取同一个静止图/确定的帧号:++1. **A 原生**:DirectShow源输出pin的YUY2/NV12原始sample、实际stride、orientation、色彩元数据及provenance。+2. **B 现有转换**:当前自动filter输出BGR0,用同一份原生sample重放给转换链,或静止源顺序采集;明确标注是否严格同帧。+3. **C GPU结果**:RGB ingress线性FP16和无增强videoFrame,保持源分辨率1:1。+4. **D 显示**:实际VideoPresenter backbuffer与OBS同尺寸预览/源截图。backbuffer正确而窗口错误时,查DWM、acrylic视频隔离、缩放/DPI、ICC/HDR/驱动视频颜色处理;不再修改前面已正确节点。++每段输出尺寸/格式/颜色契约、逐通道最大误差/RMSE、灰阶单调性、每段灰阶distinct levels、黑白端点、连续平台长度、彩色细线对比度;PNG无损保存,不用JPEG/社交软件缩略图。++建立独立参考:原生YUY2按确定的601/709+full/limited转换,与明确配置的FFmpeg及OBS交叉核对。中性色块、ramp内部远离色度边界可用≤1–2码值误差起步;不同chroma重建滤波的边缘误差单列,不能用全图宽阈值掩盖range错误。++**退出条件:报告必须写出“A/B/C/D哪一步首次偏离”,并保存失败样本。若未找到,不准宣布色带已修复。**++### R2:按证据修采集与无增强路径(P0)++涉及 `CaptureCardSource.cpp/.h`、`ColorMetadata.h`、`FramePacket.h`、`EnhanceGraph.cpp`、新YUY2转换shader、`CapturePanel.cpp`。++- 常态优先原生YUY2/NV12,显式协商/回读media type;关闭任意RGB转换filter自动插入。支持RGB32作为有日志的兼容路径,MJPEG单独明确解码;保留格式枚举和4K18。+- 类型解析支持VideoInfo/VideoInfo2、stride、负高度/方向、sample长度检查;YUY2的422色度不能先转NV12丢成420。保留latest-frame mailbox+读者所有权,不持有驱动单sample导致饥饿。+- 增加设备颜色设置:自动/601/709、自动/limited/full;自动推断显示assumed,设置按设备模式保存并实时安全应用。传递已知元数据,别对未知值装作确定。+- GPU直接消费packed格式,重排/范围/矩阵集中一次完成;旁路保持输入码值和细节。关闭全部增强时不运行NR、SR、FG、光流或无用的残差路径。+- 明确区分video signal transfer和display transfer;不要仅看到BT.709标签就把所有视频强制套同一幂函数。用R1参考图决定等价契约。+- 所有修改必须同时回归图像/视频/采集,不复制三套转换实现。++**验收:R1坏样本恢复、1:1颜色误差可解释、无额外色度降采样;真实1080p60/4K18能开关/重连,audio/PTS不退化。**++### R3:修最终显示(P0/P1,依R1结果)++- 1:1保证像素中心正确;缩小时用抗混叠缩放,放大时提供与OBS相当的bicubic/Lanczos路径或明确显示当前过滤器。+- FP16颜色尽量保留到最后一次输出量化;只有需要RGBA8的后端边界才转换。先修错误,再按渐变证据决定是否加入轻量最终dither。+- 明确SDR swapchain色彩空间/支持查询;确认视频alpha=1且不被Desktop Acrylic调色。换壁纸/移动到底色不同窗口上,视频区像素应保持一致。+- A/B比较必须同一有效画面尺寸与缩放方法;导出PNG正确而屏幕差,优先检查此阶段。+- 测试窗口缩放/专业模式切换/100%与125%或150%DPI/全屏,视频几何与黑边保持;现有窗口崩溃回归不能被破坏。++### R4:配置与性能基线(P1,画质正确后)++首先修revision统计与实际分辨率展示。明确source、SR输入输出、NR、flow、FG、present texture、窗口/物理屏幕尺寸;不再只写“超分4K”。++最小矩阵:全关、SR低、NR原生、NR实时、SR+NR、SR+NR+DLSS2X;再选代表性场景比较4X和FRUC2X/4X。1080p60与4K18分开;文件15fps可用于15→60的4X验证。++与Magpie先对齐**两端实际相同输出/NR尺寸/源帧率/后端/倍率/内容**,包括一组1440p和一组真实2160p。在1440p显示器上内部4K再缩回1440p必须标明,不叫物理4K显示。重复/缺帧和切镜样本不能只取流畅段。++每次10–30秒验证可运行,然后60–120秒稳态测量;预热单列。记录CPU采集/重排/提交/等待、各GPU阶段、源真实处理率、有效子帧率、提交间隔P50/P95/P99/max、过期数、reset耗时、GPU功耗/频率/温度。GPU 60%与99%只作辅助,不能当主验收。++### R5:优化已测瓶颈(P1)++一次只改一个可回退模块:++1. 原生capture格式GPU转换,减少CPU全帧copy/reorder。+2. 按功能裁剪pass/分配;同尺寸旁路用资源引用,去掉无消费者的重复副本;保持对比lease。+3. 有界处理/呈现解耦,呈现线程等待deadline不阻塞下一个源帧的GPU提交;资源只能在consumer fence完成后复用。设置/seek/drop用epoch作废,不能凭线程数声称并行。+4. 常规日志批量写入、统计低频计算;错误和关键状态保留。+5. 修FRUC reset重建风暴;单独量化IPC、GPU等待和算法成本,必要时试官方支持的CUDA互通,保持失败回退。++**验收:** 同源同质量输出无退化,阶段GPU/CPU时间和呈现长间隔至少有明确可复现改善,帧龄不因隐藏大队列增加;源丢帧、有效生成数、用户体感一起报告。不能把降低模型尺寸/强度叫同等质量的纯性能优化。++### R6:有限复用Magpie/OBS(用户已授权)++Veyra根LICENSE已经是GPLv3,用户本次明确允许必要时copy/复用开源代码。可以按兼容许可证直接移植**具体模块**,不用再坚持已失效的闭源禁抄假设。++该最新用户决定记录在本文与HANDOFF;本轮不修改锁定的AGENTS或CONTROL_HASHES。接手者应结合仓库现有GPLv3 LICENSE与用户本次明确复用授权理解旧“闭源Veyra”的条件,而不是从旧措辞推导出必须重新征求同一授权。++推荐优先级:OBS原生capture类型/颜色契约 → Magpie残差缩放/光流与生成有效性处理 → 呈现节奏机制 → VFX视频后端(仅同条件实测值得时)。保持Veyra现有Win32 UI、三入口共享引擎和D3D12主干;D3D11模块需明确interop代价,不为了复制方便把产品改成必须先开OBS。++每个复用项创建来源记录:仓库URL、固定commit、原文件/函数、许可证和copyright、复制范围、修改说明、单独回归证据。保留原作者声明,更新 `THIRD_PARTY_NOTICES.md`;禁止改名抹掉归因。公开说明仍讲Veyra功能,但许可证归因不能因“README不提别的项目”而删除。++源码GPL不覆盖其NVIDIA SDK/DLL。现有固定身份运行时规则保留;本次授权不是把Magpie社区patch版NR替换进Veyra、改DLL或把SDK提交Git的授权。先用已批准的原版NR测调用/颜色/滤波;若确需比较另一runtime,作为独立变量单独处理。++## 7. 必须新增的可失败门禁++以下名字是**待实现目标**,不要声称已经存在或通过:++- `CaptureColorContractTests`:native YUY2/NV12/BGR0、601/709、full/limited、stride/方向、未知元数据;测试真实生产转换函数。+- `BaselinePresentationColorTests`:全关RGB/YUY2渐变→present读回;1:1与缩放、alpha隔离、near-black和chroma细线;同时测试NR=off与总开关off的实际applied状态。+- 同源性能报告器:按revision与run-id隔离统计,输出阶段耗时/提交间隔/帧龄/有效FG,解析真实日志而非GUI理论数。++之后运行与变更有关的现有窄测,再运行现有统一 `scripts/gates/delivery.ps1` / phase7入口;**现有delivery通过不能代替新增基础画质检查。** 完整命令以脚本参数为准,单次进程有300秒上限;导出完整性检查保持原状。++已经存在且本轮成功运行的最窄诊断命令:++```powershell+python logs/obs-magpie-rootcause-20260909/build_probe.py+```++它基于现有编译库生成旁路探针。生产代码改动后先构建对应库再重跑;切勿把旧库结果当新源码通过。++## 8. 交付要求与停止条件++- 第一份代码交付必须含“色带首次出现节点”的失败/修复样本与命令;不要先改皮肤、换显卡、加锐化/deband掩盖。+- 文档区分:用户观察、本机日志、源码事实、本轮执行、仍待验证;未验证的FPS与性能倍率不进入README/Release。+- 不因用户着急清掉失败日志、改门槛、删除必要fence/reset;不自动添加深度模型或OCR。+- 相同问题三个不同方案仍无新证据时,保存样本与失败指纹,不循环随机改参数。+- 最终需要单独的新上下文只读复核与用户实卡验收;此文不授予自己签署Reviewer PASS。+- 当前 `loop/CONTROL_HASHES.json` 有早期AGENTS/README锁定值;发布阶段这些文件已改过。接手先报告实际漂移及授权来源,不通过改manifest/gate伪造preflight通过。本次未改控制hash。+- 已发布0.0.1的状态处理与后续版本发布单独执行;本轮没有推送、替换、删除Release或修改用户运行时。++**下一条唯一实施任务:R1,添加诊断用原生采集与转换后/显示后同帧抓取,查明损失首次出现的位置,并以坏样本驱动R2/R3修复。**diff --git a/docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md b/docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.mdnew file mode 100644index 00000000..39349b35--- /dev/null+++ b/docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md@@ -0,0 +1,107 @@+# 原生采集颜色与实时调度修复 — 2026-09-09++状态:本机修复候选已构建;Phase 7 仍 in_progress。本文是本次实际实现记录,取代此前方案中的“修复尚未实施”。不将软件短测当作实卡画质、长期稳定或与其他软件同条件性能验收。++## 用户最新决定++用户先准备了实卡,随后明确“**不用测试这个,可以确定就是 YUY2 的转换**”。本轮据此停止实卡 A/B,不打开或占用设备,直接改造已确认不受控的转换路径;用构造像素和文件回放验证实现。不能据此写成已经逐段实测证明全部色带只有一个根因。++导出完整性检查、现有 SR/NR/FG 后端和用户默认画质决定保留。不加入深度模型、OCR、新 SDK 或前端重做;不修改 NVIDIA DLL;无远端发布操作。++## 已修改的生产路径++### 1. 原生采集进入共享图++旧的未压缩采集也强制经过 DirectShow 的 RGB32 转换器。现在 YUY2、NV12、RGB32 都根据驱动实际返回的媒体类型,用自有 DirectShow 接收端及 `ConnectDirect` 连接。YUY2 不先转 RGB32,也不先压成 NV12;压缩 MJPEG 仍走明确记录的解码/RGB32 兼容路径。诊断入口可以显式选择旧 RGB 路径,产品 UI 不启用这个诊断开关。++接收端解析 VideoInfo/VideoInfo2、行距、平面偏移、方向、采样时间和颜色范围/矩阵。YUV 对两种 biHeight 符号均按 top-down 读,RGB 保留 DIB bottom-up 规则。剔除行尾 padding,短样本在复制前拒绝;连接后的不兼容动态格式要求重开,不使用旧尺寸继续读。驱动第一次样本重复声明同一媒体类型正常接收。入口保留容量 1 mailbox,不增加无界缓存。++颜色来源有明确标记:显式 full/limited、BT.601/BT.709 优先;缺失信息使用标记为 assumed 的默认值。SDR 采集按显示端编码值做 sRGB 工作空间往返,避免把 YUV 解出的显示颜色再按摄像机 OETF 改亮。未支持的显式颜色类型拒绝,不假称支持 HDR。真实驱动是否提供正确范围仍需用户现场判断。++### 2. 一次 GPU YUY2 转换++`Yuy2ToLinear.hlsl` 直接读 Y0/U/Y1/V,维持 4:2:2 色度,到 linear FP16 工作纹理后沿用共享 SR → NR → FG → 输出路径。范围归一化和 YUV 矩阵只在此做一次,不经中间 8-bit RGB 量化。最终仍有 SDR 8-bit 输出的正常量化,并非端到端 10-bit。++同尺寸且无 SR 时,source/work 共用纹理;source/base 对比参考共用已留存的同帧纹理,跳过重复 blit/copy。同尺寸 NR 输入也共用 work,跳过身份缩放。仍保留保护异步呈现的历史纹理、lease、barrier 和 fence,不删除真正需要的同步。++RGB 显式 limited 范围也补上 16–235 归一化。通用颜色解析不再覆盖 source 已解析、但标记 assumed 的颜色契约。++### 3. 采集处理与显示截止时间分开++采集新增独立呈现 worker,容量为两个批次(含正在显示的批次)。等待子帧显示时间不会直接占住取帧/处理线程。满载时先等可用 lease,再读取 mailbox 中最新输入;历史中断、暂停、设置切换、保存和退出先取消/排空再改资源。++GPU 队列和 ring 的操作仍由 mutex 串行保护。`graph.process` 内部等待和 FRUC 互通仍可能阻塞呈现提交;这是有限的流水化改进,不能宣称已实现完全并行,或已达到其他软件的 GPU 占用。文件播放保留音频时钟及源帧顺序;导出未采用丢帧策略。++### 4. 统计与日志++- 统计窗口在 applied revision 真正改变后清空;源帧、生成帧和提交计数采用同一 revision 基数。GPU timestamp 不再被旧 source ID 阻止收集,旧 revision 的 GPU 样本显示 pending。+- 呈现 worker 每批完成时直接累计统计窗口,避免 producer 读取较慢丢掉中间样本。取消保留已提交子帧计数;没有实际提交不生成假的 0ms 延迟样本。窗口零尺寸跳过 Present 不覆盖最后有效提交时间。+- CPU 图提交时间修正计算方向。采集“callback 到 Present 返回”按 worker 的实际提交时间计算,仍不是 HDMI 到显示器光子的物理延迟。+- P95 采用最多 1200 个样本、250ms 缓存,避免每帧完整排序。文件日志按字节数/下次写入达到时间阈值批量 flush,警告、错误及显式 flush 立即刷新;不是有后台定时器保证闲置时 250ms 落盘。++## 修改文件++| 范围 | 文件 |+| --- | --- |+| 采集 | `include/veyra/source/CaptureMediaType.h`、`NativeCaptureSink.h`、`IFrameSource.h`;`src/source/NativeCaptureSink.cpp`、`CaptureCardSource.cpp` |+| GPU 颜色与资源 | `shaders/Yuy2ToLinear.hlsl`、`RgbToLinear.hlsl`;`include/veyra/pipeline/ColorMetadata.h`、`EnhanceGraph.h`;`src/pipeline/EnhanceGraph.cpp` |+| 调度/统计 | `include/veyra/engine/PresentationWorker.h`、`TimingWindow.h`、`EngineController.h`、`VideoPresenter.h`;`include/veyra/diagnostics/GpuTimer.h`;`src/engine/EngineController.cpp` |+| 日志 | `include/veyra/Log.h`、`src/base/Log.cpp` |+| FRUC 依赖 | `scripts/package-portable.ps1`:为 FRUC 添加固定身份的 cudart 依赖白名单,仅修改脚本,未执行打包 |+| 构建/验证 | `CMakeLists.txt`;新增 CaptureColorContract、Yuy2Color、PresentationWorker、LivePresentation 测试;调整原 CaptureSource 测试;`tools/capture_color_probe/main.cpp` |++## 实际验证++证据目录:`logs/baseline-repair-20260909/`。GPU 测试在本机 RTX 5070 实际执行,没有使用实卡。每项通过独立子进程执行,外部 timeout=290 秒,满足单次不超过 300 秒。++构建命令(最终生产二进制对应 `final-build4.log`,exit 0):++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root 'C:\Users\123\Desktop\Veyra DLSS Video Player' -Preset x64-release+```++| 实际运行目标/参数 | 结果 | 日志 |+| --- | --- | --- |+| `veyra_capture_color_tests.exe` | 26 项通过:生产接收端、COM allocator、方向、stride、NV12、短样本、动态格式 | `final-capture-contract.log` |+| `veyra_presentation_worker_tests.exe` | 11 项通过:双批次上限、取消、恢复、失败传播、统计重置 | `final-worker-contract.log` |+| `veyra_yuy2_color_tests.exe` | 601/709 × full/limited 四组,最大误差 1/255;显示误差 0 | `final-yuy2-pixels.log` |+| 同上 `--rgb` | full/limited 通道及端点,最大误差 1/255;显示误差 0 | `final-rgb-pixels.log` |+| 同上 `--4k` | 实际 3840×2160,四组最大误差 1/255;显示误差 0 | `final-yuy2-4k.log` |+| 同上 `--nr` | 1080p YUY2 真实 NR 执行、非黑输出、显示误差 0 | `final-yuy2-nr.log` |+| 同上 `--temporal` | 8 帧 NR,NVOF Execute 7 次、NR motion 7 帧,显示误差 0 | `final-yuy2-temporal2.log` |+| `veyra_live_presentation_tests.exe loop/local/fixed_clips/test_av_1080p.mp4 logs/baseline-repair-20260909/final-live-replay2` | 10 项通过:实际 live worker、NR/2X/4X、暂停改设置/恢复、关闭后的统计、退出 | `final-live-replay2.log` |+| 同上测试目标 `logs/video-sdk-trial-20260909/known-pan15.mp4 logs/baseline-repair-20260909/final-live-fruc-pan --fruc` | 15fps 已知平移输入,FRUC 后端的同样 10 项通过 | `final-live-fruc-pan.log` |+| `veyra_preview_geometry_tests.exe logs/baseline-repair-20260909/final-preview` | fit/zoom/pan/reference/reset 像素回归通过 | `final-preview.log` |++NR 是修改画面的处理,NR 模式里的 sourceError 不是基础颜色误差验收值;这些 NR 测试检查实际执行、非黑输出及显示是否再改色,不能把 NR 后误差较大解读成 bypass 出错,也不能据此证明 NR 主观画质优秀。++真实运行日志含 NR `CreateFeature result=0x1 (NVSDK_NGX_Result_Success)`、DLSSG `Evaluate ... result=0x1 ... seh=0`,temporal 的 `nvOFDestroy status=0 executes=7`。CPU 契约测试注入动态格式错误 `0x80040200` 是预期拒绝,最终 failures=0。++失败如实保留:早期编译缺 d3d9 类型/std::abs 头文件已补齐;第一次 temporal 测试漏开测试描述的 `enableNvofStandalone`,执行计数为 0 而失败,按产品配置补齐测试设置后为 7/7。第一次 delivery 的 23 项功能检查全过,但末尾 `Get-FileHash` 因启动环境未加载模块而 exit 1,不能冒充整套 PASS。仅用忽略目录中的 `delivery-env.ps1` 从 `$PSHOME` 导入系统 Utility 模块后重跑,未修改验收脚本或控制 hash。++## 独立复核与边界++独立只读 reviewer `review_native_capture` 已检查接收端、颜色、资源别名、双批次 lease、reset/drain/析构及统计。发现的动态媒体类型、RGB limited 和统计边界已修;最终限定意见:本轮所提问题均关闭,所审范围无其他未修 P0/P1/P2。Reviewer 核对了真实日志但未自行运行 GPU,也未验收实卡。++既有 `AGENTS.md`/`README.md` 相对 CONTROL_HASHES 的漂移保留,本轮没有改控制面或声明 preflight 已通过。完整 Phase 7 不因此改为 complete。尚未完成:新路径在用户设备上的连接兼容性和主观颜色确认、同尺寸/同配置下的性能对照、FRUC 重建成本、间歇节奏问题及长期稳定性。++下一条任务:让用户运行本机新版本确认原生 YUY2 实际画面;不自动恢复已取消的实卡 A/B。若继续做性能优化,先保存相同输入/输出尺寸、NR 档位、FG 后端/倍率的阶段与等待时间,再决定下一项改造,不承诺 GPU 占用的未测降幅。++当前可执行文件:`out/build/x64-release/veyra.exe`。根目录 `Veyra.cmd` 仍指向它。没有更新已发布的 v0.0.1 Release。++## 最终短测汇总++实际命令为 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/baseline-repair-20260909/delivery-env.ps1 -Root 'C:\Users\123\Desktop\Veyra DLSS Video Player'`。包装只导入该 PowerShell 自带的 Utility 模块,然后调用原 `scripts/gates/delivery.ps1`。++最终 exit 0,23 项通过,42.569 秒。结果:`logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json`。1080p 60 次 NR、59 次 NVOF、GPU validation 错误 0、正常路径回读 0;native4K 12 次 NR;4K 输入实时档播放 240 源帧/239 生成帧,观察到绝对 lateness P95=1.50ms(不是物理延迟);图像原生4K保存、H.264/HEVC 4K 2X CFR 各24输出帧且保留音频、取消导出不晋升完整文件均通过。++最终生产 EXE SHA256:`61618AF18F7B985BD4C1FECA06EBE7A07C30EAA01B2CC0682A217E89EAD3C372`。根目录与 runtime_local 中 NR SHA256 均仍为固定 `E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E`。++### FRUC 额外修复及失败记录++1. 新 live replay 使用 FRUC 时,第一次初始化因本机开发运行目录缺 `NvOFFRUC.dll` 拒绝。旧发布路径改为相对 runtime_local 后,本机没有同步放入该文件。+2. 从已安装 Optical Flow SDK 5.0.7 的 `NvOFFRUC/NvOFFRUCSample/bin/win64` 复制固定文件,先校验 SHA256 `5A0B6701D30709E25E7E5B92CA46B18AAB1459160CECD4F629872369D85C8B0A` 及有效 NVIDIA 签名。随后初始化报 `LoadLibrary error=126`。+3. MSVC `dumpbin /dependents runtime_local/nvidia/NvOFFRUC.dll` 确认直接依赖 `cudart64_110.dll`。同 SDK 目录的这个文件 SHA256 为 `EDC35E7D0FA3F257BBEDFA7888911080C5696ACDD40B6187B6DD0173F20759AD`、签名 Valid/NVIDIA;本地复制到同一 runtime 目录后实际 Create/Register/Process result=0、seh=0。两个文件都被 gitignore,未提交源码。打包白名单同步补齐固定 cudart 项,仅语法检查通过,未执行打包;已发布的旧包没有因此改变,后续发版需带上此依赖。+4. 通用 test_av_1080p 素材下 FRUC 返回 repeated=true,无法满足测试“有效生成大于0”的断言;保留 `final-live-fruc3.log` 失败,不把重复帧改计为生成。换用既有、明确有平移运动的 `known-pan15.mp4`,同一测试所有断言通过。此处是测试素材与生成断言匹配,不是降低断言或隐藏产品错误。++FRUC 三份前置失败日志 `final-live-fruc.log`、`final-live-fruc2.log`、`final-live-fruc3.log` 均保留。最终 `final-live-fruc-pan.log` exit 0,约10秒;仍不代表自然场景总体插帧画质验收。diff --git a/docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md b/docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.mdnew file mode 100644index 00000000..aa2360ff--- /dev/null+++ b/docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md@@ -0,0 +1,222 @@+# Veyra 对照同类项目的改进执行方案++日期:2026-09-09。状态:方案已整理,以下新增改进尚未实施。当前 Phase 7 仍在进行,不以本文推进验收状态。++用户本次要求先暂停对“一卡、恢复、又一卡”的现场追查,整理对照方案。本文件依据已经固定版本的 GitHub 调查、当前源码和既有本机测试,不代表新一轮竞品实测。最近自然运行日志只有界面操作,未记录对应卡顿;具体后端与触发原因仍未确认。++## 1. 推荐路线++先把统计和帧调度做可靠,再降低 FRUC 互通成本和文件解码成本,最后补有证据的画质改进。保留现有 SR → NR → FG 顺序、两个 SR 后端和两个 FG 后端。++这轮最有价值的目标是:同样的画面设置下减少等待、周期性停顿和无效处理,保证每张有效帧按正确时间交付。不是通过增加缓冲、显示理论倍数或暗中降低 NR 分辨率让数字变好。++建议分成三批交付:++1. **第一批必做:配置隔离统计、轻量日志、有界处理与呈现调度、重置事件核对。** 先建立可比较基线,再逐项修改。+2. **第二批做实验后决定:FRUC CUDA 互通、文件硬解、重复 GPU 拷贝消减。** 只合入同源对照证明有收益且正确的方案。+3. **第三批按画质证据推进:运动置信度、NR/SR 运动稳定性、保护区域的 FG 语义。** 深度模型和预渲染缓存暂不加入默认运行路径。++导出完整性检查保持现状;开发短测不进入用户每次导出流程。每次测试调用最多 300 秒,累计不受“五分钟一轮”限制。++## 2. 对照项目:借鉴什么,舍弃什么++固定提交、来源链接与初次事实核对见 [GitHub 性能审计](GITHUB_PERFORMANCE_AUDIT_2026-09-09.md)。下表是对已取得材料的归纳,不是第三方性能排名。++| 项目 | 已核对的方法 | Veyra 应吸收的部分 | 不采用或不作推断的部分 |+| --- | --- | --- | --- |+| Magpie Experimental | 有界输出、输入节奏控制、卡顿后重新校准时钟;SR/NR/FG 分开;同帧对多子帧生成 | 明确输入、处理、呈现三种节奏;避免迟到帧成批追赶;保留生成有效性与 fence | 不复制实现;它也有 CPU 等待与切换卡顿。不能把其帧同步文档当成本机 GPU 加速证明 |+| NVEnc | FRUC 用 CUDA 设备指针,按目标 PTS 管理多个实例;RTX VSR 分档 | FRUC CUDA 互通试验;每实例历史与目标时刻明确绑定;按真实输出检查多倍插值 | 离线编码吞吐不是采集显示延迟;不照搬忽略重复回退标志的行为 |+| RTXVideoProcessor | GPU 解码帧池、GPU 颜色转换、VSR、GPU 编码,异步读包 | 文件模式硬解与有界帧池;减少 CPU 像素往返 | 其大容量队列不适合实时采集;GPU 内仍有 copy/synchronize;没有 NR+FG,速度不可横向套用 |+| 2600th/dlss5-video-player | 先做 NR 神经缓存,再播放缓存;播放时 SR 可独立开启 | 将来可提供用户主动选择的文件预处理 | 不放进采集模式;不把预处理后的流畅播放称为实时 NR;暂不增加缓存管理体系 |+| video2dlssnr | SR → 光流 → NR → 合成;视频循环存在 CPU raw 输入/输出和等待 | 验证顺序、颜色与参数合同;观察线程重叠的用途 | 当前无明确许可证,不复用代码;不退回 raw pipe,不照抄“全链零 CPU 往返”宣传 |+| DLSS5-Feeder | 游戏内场景深度、估算运动、合成 DLAA 合同、资源互通 | 运动信任度与资源时序检查思路 | HDMI 没有游戏原生几何;不接 ReShade、不制造“等同原生”输入,不用合成 jitter 许诺恢复真实细节 |+| Zonnery/dlss5-nr-player | 已审计材料以 raw pipe、上传/回读和占位指导为主 | 作为最简调用方式的边界参照 | 不作为低延迟架构目标;固定 head 不等于完成新的逐项性能验证 |++补充纠正旧文档:9 月 3 日 Magpie 的 DAV2 描述属于历史版本;本轮固定提交的 Guidance 使用 ZeroDepth。不能据此说深度永远无用,也不能继续拿旧 provider 描述其当前实现。详见 [上一版优化方案的更正](QUALITY_OPTIMIZATION_PLAN_2026-09-08.md)。++## 3. 当前结构与真正需要改变的位置++增强图的顺序已经合理,现阶段不为猜测重排算法:++```text+文件 / 图片 / 采集+ → 颜色与时间戳解析+ → SR:DLSS 或 RTX Video(可关闭)+ → NR:实时内部尺寸或原生尺寸(可关闭)+ → FG:DLSS 或 FRUC(可关闭)+ → 播放器字幕 / OSD+ → 呈现或现有导出 sink+```++NVOF 与置信度按各消费者的资源和坐标合同供给;FRUC 使用自己的内部光流,不能假定可直接复用 NR 的 NVOF 结果。++当前 `EngineController` 同一循环中先处理,再等待整批生成结果,按 PTS 等待并呈现各子帧,最后读取下一源帧。底层有 command slot ring,并不代表这些工作已经充分重叠。FRUC 还需 CPU 提交确认;完整 reset 会停止并新建 worker。++目标结构是“同一个增强图,有界资源,多种来源调度”:++```text+采集回调 → latest mailbox(1) ┐+文件解码 → 有界帧池 / 背压 ├→ 图提交 → 有界待呈现批次 → 按 PTS 呈现+图片单帧 → 无时序处理 ┘ ↑ │+ └── fence / lease 回收+```++先做单一引擎所有者下的事件循环:GPU 提交、完成轮询、呈现截止时间、控制命令都可推进,不在整批子帧的等待中停止读取来源。若测量仍证实 CPU API 长时间阻塞,再将受影响的提交或呈现拆为明确所有者的线程;不是直接让多个线程并发调用同一个 graph。++资源上限必须先按现有 slot 和消费者 fence 算清。第一版待呈现队列最多保留一个尚未消费完的源帧批次(4X 最多四项),生产方拿不到安全空闲 slot 就背压;不为凑并行扩大 A/B/C history,不把逻辑队列长度当作实际资源池峰值。++## 4. 第一批:必须修正的基础++### P0-A:统计按真正应用的配置隔离++**证据:** 当前 TimingWindow 保留 1200 个样本,多个统计跨设置变化;NR 表盘只测 NR。用户之前开 FG 后 20ms→6ms 的一次异常已证实是隐藏页面串改 NR 尺寸,该设置缺陷已修,不能再次把它当作未知管线加速。++**实施:**++- 每条样本绑定 session、实际 applied revision、reset epoch、源帧号及批次号。异步完成的旧样本不混进新配置。+- requested 配置仍在应用中时不重置成“新配置已测”。回滚按实际生效 revision 归档。+- 配置、来源或尺寸改变时重建短窗口;预热单列,不删去卡顿时段。窗口同时设时间界限与容量上限。+- 日常模式保持简洁;专业模式直接显示输入 fps、源处理 fps、有效生成 fps、提交 fps,以及真实 SR/NR/FG 尺寸与后端。+- SR、NR、FG 阶段耗时分列;FRUC 当前指标标明包括队列等待/提交区间。GPU 时间与 CPU 等待不重复相加为“总延迟”。+- 无样本显示“未测”;Present 调用数只叫提交帧率。物理显示帧率与 HDMI→屏幕延迟仍须外部测量。++**验收:** 高频切换 NR 原生/实时、SR 后端、FG 开关和倍率,旧 GPU 完成回调不得污染新窗口;应用失败回滚仍显示实际配置。源 15→4X 的显示标签能分别表达源 15、目标 60、实际有效生成及提交速率。++主要位置:`src/engine/EngineController.cpp`、诊断快照结构、`apps/veyra/ui/AppShell.cpp` 和 GPU 指标聚合处。++### P0-B:把逐帧日志开销移出关键等待路径++**证据:** `src/base/Log.cpp` 每次写日志持锁并 fflush,当前逐帧有多条记录。存在开销不等于已证明它是主要瓶颈。++**实施:** 固定容量的结构化记录缓冲,后台批量写出;错误、设备丢失、NGX/NVOF/HRESULT/SEH、配置事务和 reset 证据保留。正常 UI 用低频摘要,详细追踪按需开启。缓冲溢出计数和故障尾部必须可追溯,不能静默丢掉失败码或无限增大队列。++GPU timestamp 仍异步回收,不能为写日志增加 GPU fence 等待。分位数不再在每帧重复复制并排序长窗口,改在低频快照时计算。++**验收:** 同配置 A/B 比较 CPU 提交时间、日志队列峰值、长间隔事件与源丢帧;故障注入仍能留下真实失败和配置身份。若没有可重复收益,不宣传 FPS 提升。++### P0-C:有界处理与呈现解耦++**借鉴:** Magpie 的节奏和有界队列原则;实现仍遵循 Veyra 单一所有者、资源 lease/fence 合同。++**实施:**++1. 将批次就绪、源读取、图提交、下一呈现截止时间拆成可推进状态;等待显示某个子帧时,允许提交资源足够的后续源帧工作。+2. 生成有效性在真实完成后判定;无效、过期、被取消的生成帧分别计数。不能以 Present 次数冒充真实生成。+3. 采集保持 mailbox=1,迟到时舍弃已经没有显示价值的生成帧,不瞬间追赶全部欠帧。真正源间断仍触发统一历史 reset。+4. 文件不丢源帧,保留音频主时钟、PTS 和有界背压。持续无法实时运行时明确提示,由用户选择减小增强负载;不靠改 PTS 或暗中丢帧隐藏问题。+5. seek、暂停、模式切换、resize、source switch 和 device lost 取消旧 epoch 的呈现;GPU 未完成的纹理必须等消费者 fence 回收,不能直接重用。+6. 普通呈现迟到与源内容间断分别记录。时钟校准不能伪装成新的素材序列,也不能用“清零 lateness”掩盖持续积压。++**验收:** 真实源序号/PTS 不混乱、无跨 epoch 呈现、无纹理提前覆盖;固定资源上限,A/V 不退步;同负载下提交间隔 P95/P99、最大间隔、过期生成率与捕获丢帧能重复改善。++### P0-D:重置成本与重复触发核对++**证据:** FRUC fresh worker reset 确实有启动成本;“掉帧→重启→更多掉帧”只是已知风险,目前没有对应用户卡顿的日志证明。++**先做:** 每个 reset 记录原因、源序列断点、epoch、排空/停止/启动/首对恢复耗时;检查同一个源边界是否被多个标志重复处理。一次边界合并为一次原子 reset,不能跨新的间断继续使用旧历史。++**再做:** 轻量 reseed 只作为独立实验,与 fresh worker 在切镜、PTS 回退、丢帧、重复帧后连续多个输出做像素和 PTS 对照。FRUC 的 skip-warp 不直接视为清空全部历史。++若轻量路径不能证明正确,保留 fresh worker。持续过载可提出用户可选的低倍率/暂停 FG 策略,但不能自动改用户手动配置,或无提示地把开启状态显示为已生效。++## 5. 第二批:超分与补帧的成本改进++### P1-A:FRUC CUDA 互通试验++NVEnc 的结构证明多实例、按 PTS 调用的路线有参考价值。我们目前 4X 使用三个实例,不是 SDK 内置“一次推理出三帧”;不要承诺改个资源类型就获得游戏 MFG 的复用能力。++在保留隔离 worker 的前提下,试验同 adapter 的 D3D12 共享资源/外部同步 → CUDA 可接受的设备资源 → FRUC → 共享输出。先确认 SDK 对布局、pitch、格式、CUDA 上下文和外部同步的实际要求;映射后若仍需设备内复制,也必须计时,不能称完全零拷贝。++拆分测量父进程拷贝、IPC 确认、SDK 调用、GPU 就绪与输出回收。在同尺寸、格式、素材、NR/SR 设置下比较现有 D3D11 worker 与 CUDA 候选。RGBA/NV12 的颜色差异另做检查,不把换成低精度格式后的速度当作同等画质胜出。++**建议进入产品的条件:** 至少三次短测均改善关键路径,收益大于本机运行波动,PTS/有效生成率/画质/重置可靠性无退步。预先将“阶段 P95 下降至少 10%”设为试验收益目标,不是现有门禁或必达承诺;若未达到,保留候选报告并停止扩建,不合入没有收益的复杂度。++### P1-B:文件硬解与 GPU 帧池++优先接通同适配器 D3D12VA 可用路径;若依赖能力不满足,再比较明确的 CUDA 互通候选,不同时造两套主解码系统。借鉴 RTXVideoProcessor 的帧池和异步读包思想,但采用小型有界队列和用户控制命令可取消的背压。++H.264/HEVC 硬解帧携带颜色、时间戳及 GPU 生命周期进入共享图,避免解码后整帧回读再上传。软件回退明确显示原因,保持可用。比较 CPU 占用、decode 时间、上传量、总吞吐与首帧/seek 行为。++**边界:** 原始 YUY2 采集不需要 H.264/HEVC 解码,这项主要改善文件播放;不保证解决当前采集卡顿,也不改变 NR 本身约 23ms 的原生 4K 代价。MJPEG 是否有可用硬解另查能力,不作默认承诺。++### P1-C:减少重复工作,保持处理尺寸诚实++- 核对原图、SR 底图和比较输出的重复保留是否能改为 lease 引用或按需复制;按住原图、分屏、截图、UI 保护必须仍对应同一源帧。+- 只在源身份和功能合同证明可跳过时缓存工作;不能把窗口重绘等同新源帧,也不能把静态重复画面冒充新增内容帧率。+- 避免无效的中间颜色转换;颜色、parity、range 和 resource state 检查优先于融合 pass。+- 用同源平移、遮挡、文字与纹理比较 DLSS SR 和 RTX Video SR 各档;保留用户选择。SR 低档+实时 NR 是有本机数据支持的实时候选,不擅自改成所有素材的最佳默认。+- 暂不改成 FG → SR → NR:那会提高后续高成本 pass 的调用次数,还会改变历史和画质合同。++## 6. 第三批:把上一版画质方案接续起来++上一版 [画质优化方案](QUALITY_OPTIMIZATION_PLAN_2026-09-08.md) 是历史起点,不能将其中“待实现”原样重复施工。依据 WORKLOG 与各专项复核:++| 原计划方向 | 当前已有成果 / 边界 | 本轮后续动作 |+| --- | --- | --- |+| 输入尺寸、奇数尺寸、颜色与预览 | 已有分块、尺寸/颜色/缩放专项修复与证据 | 性能优化后做针对性回归,不重写输入体系 |+| SR 参数与运动合同 | 已做方向、缩放、重建与运动响应实验 | 做自然运动的同源 SR 后端 A/B;空间更清晰不能掩盖时间闪烁 |+| 手动 UI / 字幕保护 | 已有保护区域、羽化、时序样本验证 | 保留;明确 NR 保护与 FG 插值保护不同,烧录 HUD 不能宣称完美分离 |+| 私有 UI 资源合同 | 部分试验未达到预期,旧 UI correction 开关不能当自动识别成功 | 不为追宣传强接未知合同;实验标识保留 |+| 运动置信度 | 已实现 cost、出界、亮度回投等门控;切镜/边界有专项验证 | 用遮挡、粒子、细线自然素材找失败,再局部改进,不全帧加重计算 |+| 双向光流 | 已有独立实验,尚未成为默认质量路径 | 先比较 A/B 两帧双向检查的成本与收益;需要 C 的额外验证明确计入 lookahead,不当免费未来帧 |+| 深度 | NR/SR/FG 已有响应试验,未证明引入默认深度模型有足够收益 | 暂不加入默认路径;只在明确失败场景出现可重复收益后考虑可选 Small provider |+| 视频专用 SR / FRUC | 已接入可选后端,并有实际调用和短测 | 现在做性能、节奏与自然画质对照,不重复“开始接入” |++质量验收分开记录:清晰度、时间闪烁、遮挡伪影、文字变化、有效生成率。FRUC 有返回成功但全部 repeated 的已有样本,必须继续计为没有有效插帧;不能拿 API 成功代替画质通过。++## 7. 统一对照方法与执行次序++### 7.1 基线++先记录当前源码差异、EXE/worker/runtime 身份和实际 applied 配置,保留现有未提交改动。每个实验用独立 run-id,不覆盖旧日志。第一批修改前后使用同一素材、适配器、输出尺寸、显示方式和电源环境;GPU 测试串行执行。++优先使用可重放文件:1080p60、1080p15、4K18。15fps 用来核对 4X60 的低源帧率场景;4K18 对应当前采集卡实际公开模式,不虚构 1440p30。最终由用户实卡确认输入间隔、音频与体感。++先测原图、仅 NR、仅低档 VSR、低档 VSR+实时 NR。然后在同一基础上对比 DLSS/FRUC 的 2X/4X;3X 做正确性与中间成本核对,不把所有设置做成无意义的组合爆炸。原生 NR 与高档 SR 作为成本对照单列。++每个新方案先一次 10–30 秒窄测;出现收益后才做三次 60–120 秒比较。每次完整调用硬上限 300 秒。切换/重置/故障窄测另开,不把预热和故障恢复混入稳态中位数,也不从报告删掉它们。++### 7.2 必须记录的证据++| 类别 | 指标与用途 |+| --- | --- |+| 身份 | 输入 hash、配置 revision、实际处理尺寸、后端、EXE/runtime/worker hash |+| 来源 | 收到/处理/丢弃源帧数、源间隔分布、已知内容变化率与名义 fps 的差别 |+| 生成 | 真实有效子帧、SDK repeated、无效/过期/取消数、各子帧 PTS |+| GPU / CPU | 各阶段 P50/P95/P99、CPU 解码/提交/等待、IPC、日志写入与分位数计算 |+| 呈现节奏 | 提交间隔分布、最大间隔、目标 deadline 偏差、连续卡顿事件的时间轴;全部标明非物理扫描 |+| 生命周期 | reset 原因/次数/耗时、epoch、队列/slot 峰值、显存峰值、失败码与设备丢失 |+| 整体限制 | A/V 漂移、源处理吞吐;用户实卡体验单列;温度/频率/功耗与日志时间对齐 |++可将“有效稳定片段中提交间隔超过目标输出周期两倍”作为诊断事件定义,但必须同时标出源重复、SDK 回退、切镜和显示刷新率,不拿这一个阈值机械判画质。没有足够有效样本时 P99 标未测。++### 7.3 如何判断软件收益与算力不足++源 60fps 的到达周期约 16.7ms;源 20fps 为 50ms;源 15fps 为 66.7ms。20→4X80 的目标输出间隔是 12.5ms,不要求把 SR+NR 对同一源帧执行四遍。既有 FRUC 2/3/4X 的 9.22/18.36/27.13ms 是含等待的阶段区间,不可当作纯插帧核耗时。++- GPU 阶段成本相近,而排队、迟到和长间隔减少:支持软件调度改善的结论。+- 同依赖链总工作持续超过源到达预算且没有可用重叠:该配置无法保持实时,需要用户选择较低负载;不能只看 NR 单阶段。+- 平均吞吐够但间隔长短交替:重点检查呈现节奏、SDK 回退、reset 与突发等待。+- 更平顺但采集帧年龄或音画延迟显著增加:不能作为低延迟采集方案的成功。++并行阶段不要简单相加,阶段 P95 的和也不等于整条链的 P95;用同一批次时间轴和实际稳态输出验证。++## 8. 暂不做的项目与原因++- **默认每帧深度模型:** 当前收益证据不足,新增推理和显存负担确定存在。+- **常驻自动 HUD 检测/OCR:** 不能保证烧录 UI 分离,先保留已验证的手动保护。+- **秒级缓存或无限预取:** 不适合采集低延迟;文件预渲染仅保留为将来主动操作。+- **并行接 Streamline、游戏注入或替换私有 DLL:** 不解决已知调度问题,会引入新的接口与生命周期变量。+- **删 reset、删 fence、直接复用在途纹理:** 可以让数字短暂好看,却破坏正确性。+- **默认自动降档/4X 自动变 2X:** 当前设置实时生效的语义应保持,先显示超载原因;自动模式需要独立产品决定和滞回设计。+- **加重导出完整性检查、先建议更换显卡:** 不符合用户约定,也没有足够依据。++## 9. 交付与回退++每项独立差异、独立证据,失败回退该项,不推倒当前可用后端。顺序为 P0-A → 基线 → P0-B → P0-C/P0-D → P1-A → P1-B/P1-C → 场景驱动的质量改进;P0-D 的轻量 reseed 需要独立实验,不能阻止先交付统计和调度修正。++未来代码交付需完成相关窄测、现有统一软件 gate 及所需只读复核;保存真失败和已知边界。竞品仅作接口/行为参考,不因本文自动获得代码复用或二进制分发授权。++本次只新增方案并同步交接索引/工作记录:没有改产品代码、默认设置、导出检查、保护控制文件或 NVIDIA 依赖;没有运行新的构建/GPU/实卡测试。此前 FRUC 独立检查虽有通过记录,最终 Reviewer 整体结论仍缺失,不由本文补成通过。++**下一条明确实施任务:P0-A,按实际应用配置隔离性能统计,并把 NR 耗时、有效生成率和提交节奏分开呈现。**diff --git a/docs/GITHUB_PERFORMANCE_AUDIT_2026-09-09.md b/docs/GITHUB_PERFORMANCE_AUDIT_2026-09-09.mdnew file mode 100644index 00000000..22b23cfd--- /dev/null+++ b/docs/GITHUB_PERFORMANCE_AUDIT_2026-09-09.md@@ -0,0 +1,72 @@+# GitHub实现与Veyra卡顿归因 — 2026-09-09++用户已反馈刚完成的版本实测没问题。本次按新请求只读核对GitHub源码、官方接口和已有本机性能日志;没有安装/运行竞争产品,没有改动增强管线,也没有占用采集卡进行新的受控对照。因此可以确认结构和已测预算,不能给出“软件占70%、硬件占30%”之类无依据比例。++## 结论++两类原因同时存在。5070没有被证实故障;原生4K NR与高质量SR/高倍FG的总负载确实可能超过16.7ms/源帧;另一方面,Veyra还有调度、同步、重置和诊断开销需要优化。更换显卡不能替代软件修正,优化软件也不能承诺把约23ms的原生4K NR变成6ms。++当前只读nvidia-smi:RTX5070,driver616.56,GPU5%,显存966/12227MiB,46°C,39.32W,250W功率限额,图形2625MHz。这是查询瞬间的轻负载状态,不是卡顿期间的数据;不能用它排除满载时降频或其他软件竞争。用户旧截图99%也不能定位具体阶段或证明硬件损坏。++## 固定审计版本++GitHub API返回的默认分支head,源码/文档只下载到ignored logs/github-audit-20260909;没有执行仓库脚本、下载二进制或复用实现。++| 仓库 | head |+| --- | --- |+| SAOG0721/Magpie | `ac1cc8b0f2efc78323898395cc1336bcbecdc276` |+| rigaya/NVEnc | `bf825096600e226b0923b7feed54ca5f83a38522` |+| DrC0ns0le/RTXVideoProcessor | `7ee725726025aa4f04dff178fb9346186d17c95b` |+| 2600th/dlss5-video-player | `335ddc4523e3614e6dfc507c7d271b8fe0c71ebb` |+| DaniilSokolyuk/video2dlssnr | `55a4ceb588a419b9b56497aa0b563d0c9e2b6c77` |+| jlrouzies-fr/DLSS5-Feeder | `d69d9174ef055f95a657750db814c93ac1ad6c1d` |+| Zonnery/dlss5-nr-player | `e9c37bec513991bf25a204e3e6dbfe4b8a7dffb2` |++## 同类如何处理++1. **Magpie Experimental**:SR/NR/DLSSFG分开的原生后端,估算guidance,NR可以降低内部输入分辨率。DLSSFrameGenerator在同一对源帧上用multiFrameCount/index循环生成子帧,保留有效性标志;有D3D11/D3D12共享fence和CPU等待,不是“完全没等待”。Front Edge Sync控制基础输入节奏,输出保持有界队列,卡顿后重建节奏而不积攒欠帧。其最新帧同步指南明确该次只有构建/CPU检查,不能拿它当GPU实测加速结论。它自己的切换卡顿报告记录过NR约15ms但真实速率31→7fps,因此也区分推理成本和捕获/呈现停顿。参考[帧同步](https://github.com/SAOG0721/Magpie/blob/ac1cc8b0f2efc78323898395cc1336bcbecdc276/docs/FRAME_SYNC_GUIDE.md)、[FG源码](https://github.com/SAOG0721/Magpie/blob/ac1cc8b0f2efc78323898395cc1336bcbecdc276/src/Magpie.Core/DLSSFrameGenerator.cpp#L676)、[其问题分析](https://github.com/SAOG0721/Magpie/blob/ac1cc8b0f2efc78323898395cc1336bcbecdc276/docs/experimental/reviews/20260905-v0.6.5-r9-dlssnr-switching-stutter-REVIEW.md)。不据他人的不同GPU/不同尺寸日志给Veyra下性能结论。++2. **NVEnc**:成熟视频处理工具,支持RTX Video VSR质量1–4及FRUC double/目标fps。FRUC采用CUDA设备指针,按目标输出PTS维护多个handle,每个handle跟踪自己的上次输入;不是重复输入同一实例直接变4X。这支持我们多实例方案的合理性,但它比我们少一层D3D11互通,值得做CUDA直连的本机对照。它是编码管线,不能直接当作实时采集延迟基准;其wrapper还忽略了FRUC重复标志,我们不会照搬这一点。参考[FRUC调度](https://github.com/rigaya/NVEnc/blob/bf825096600e226b0923b7feed54ca5f83a38522/NVEncCore/NVEncFilterNVOFFRUC.cpp#L337)、[CUDA接口](https://github.com/rigaya/NVEnc/blob/bf825096600e226b0923b7feed54ca5f83a38522/NVEncNVOFFRUC/NVEncNVOFFRUC.cpp#L185)。++3. **RTXVideoProcessor**:CUDA解码帧池→GPU颜色转换→RTX VSR→GPU编码帧,异步demux。但源码仍有GPU内部copy与cudaStreamSynchronize,README的zero-copy主要指不回CPU,并非零复制/零等待;也有CPU fallback。它只做VSR/HDR,不包含Feature18和DLSSFG,因此其“4070倍速”不能证明我们的5070同时NR+FG应有同等吞吐。参考[GPU处理](https://github.com/DrC0ns0le/RTXVideoProcessor/blob/7ee725726025aa4f04dff178fb9346186d17c95b/src/rtx_processor.cpp#L485)、[帧池/路径](https://github.com/DrC0ns0le/RTXVideoProcessor/blob/7ee725726025aa4f04dff178fb9346186d17c95b/src/main.cpp#L114)。++4. **2600th/dlss5-video-player**:先在隐藏worker逐帧NR、读回并编码成神经缓存,再播放原片/缓存,播放时可另开DLSS SR。缓存保留源尺寸、SR独立。这让文件观看不必现场承担NR全开销,但不适用于无法预知未来的实时采集。参考[setup](https://github.com/2600th/dlss5-video-player/blob/335ddc4523e3614e6dfc507c7d271b8fe0c71ebb/docs/DLSS5_SETUP.md)、[离线循环](https://github.com/2600th/dlss5-video-player/blob/335ddc4523e3614e6dfc507c7d271b8fe0c71ebb/src/OfflineNeuralRenderer.cpp#L400)。++5. **video2dlssnr**:SR→光流→NR→合成顺序与我们主链一致。README写“无CPU往返”,实际视频路径nr.cpp有stdin fread、GPU EndAndWait和ReadbackRgba8、stdout fwrite;有线程队列提高重叠,并非完整显存直通。不能按宣传推断其优于我们。参考[视频循环源码](https://github.com/DaniilSokolyuk/video2dlssnr/blob/55a4ceb588a419b9b56497aa0b563d0c9e2b6c77/src/nr.cpp#L1385)。当前无许可证,不复用代码。++6. **DLSS5-Feeder**:游戏ReShade深度和估算motion→合成DLAA contract→神经消费者;与纯HDMI输入不具有相同数据前提。当前README还明确“优化”标签不保证每台机器/游戏变快。这是注入架构参考,不是5070实时视频性能对照。参考[README](https://github.com/jlrouzies-fr/DLSS5-Feeder/blob/d69d9174ef055f95a657750db814c93ac1ad6c1d/README.md)。++官方[FRUC指南](https://docs.nvidia.com/video-technologies/optical-flow-sdk/nvfruc-programming-guide/index.html)确认NVOFA+CUDA、两帧间插值和D3D11/CUDA资源,不支持“全部只用光流专用硬件所以没GPU开销”的说法。[RTX Video SDK](https://developer.nvidia.com/rtx-video-sdk)提供视频超分/HDR;FRUC来自Optical Flow SDK,两者不是同一算法。++## 我们已定位的成本++此前同一USB3Video1080p60受控数据(不是本轮新测):++| 配置 | SR阶段中位ms | NR阶段中位ms | 实际源处理fps |+| --- | ---: | ---: | ---: |+| 视频SR最高 + 原生4K NR | 6.617 | 22.911 | 约30 |+| 视频SR最高 + 实时NR | 6.497 | 6.100 | 51.16 |+| 视频SR低 + 实时NR | 1.505 | 6.366 | 59.51 |++见PHYSICAL_CAPTURE_DIAGNOSIS_2026-09-09.md。仅第一行SR+NR已约29.5ms,还没算flow、FG、其他pass与呈现;在现有同队列依赖路径上不能满足16.7ms。第二行余量很小,第三行能近60说明整条软件并非固定锁30或5070无法处理4K输出。历史“打开FG,20ms变6ms”已查到NR4K→1080设置串改,修复为单字段实时提交;那次不是FG让NR加速。++FRUC新短测1080p已知平移阶段区间中位2/3/4X=9.22/18.36/27.13ms,包含GPU队列等待及IPC提交,不是纯核耗时。3/4倍成本明显增加是真实结果;本轮没有与DLSS同源同配置完整A/B,不用旧DLSS2.5ms与此直接算倍数。++## 软件内部确实存在、但需量化的点++- `EngineController.cpp:180–205`:同一线程等待整批FG有效性、依PTS逐帧呈现,结束后才读下个源帧。GPU有slot ring不等于decode/处理/呈现已充分并行;捕获回调虽独立,容量1mailbox在处理/呈现落后时仍会覆盖源帧。正确优化是有界的生产/消费解耦和保留lease/fence,不能删除等待后让纹理被覆盖。+- `EnhanceGraph.cpp:1072`:FRUC在所有历史中断上重启worker,可能“掉帧→重启→更掉帧”。用户目前说实测没问题,因此这仍是压力场景风险,不能谎称已经复现其当前体验。应分别统计reset原因/次数/时间;轻量reseed必须先与fresh worker做后续像素一致性验证。+- `Log.cpp:write` 每条记录持锁fprintf+fflush;源、提交、GPU timestamp等每帧多条。确实存在同步文件写开销,但没有A/B测出其占比。保留错误/身份/事务证据,把常规逐帧事件缓冲或按需采样,比删日志更合理。+- `EnhanceGraph.cpp:956`:每源帧始终保留原图和SR底图两份GPU拷贝,保障即时同帧对比。可能优化为按需/引用复用,但需要保持对比语义及lease生命周期,不能把必要副本武断叫成bug。+- `EngineController.cpp` 的TimingWindow/late samples跨配置混合,NR表盘仅NR单阶段。这个显示问题已经有证据,必须先修,才能让用户可靠比较配置。+- 普通文件当前软件解码;可借鉴CUDA/D3D12VA硬解+GPU帧池,但原始YUY2采集并没有H264/HEVC需要NVDEC解码,硬解不会让原生4K NR的23ms消失。++## 优先顺序与可判定实验++1. 按settingsRevision隔离统计:显示输入/有效源处理/有效生成/提交fps;分开SR/NR/FG阶段、CPU解码、GPU ready、deadline、Present、reset。先消除“6ms是总延迟”的误读。+2. 同一1080p60与4K18源固定NR尺寸,做原图、VSR低/高、NR、二者组合、分别DLSS2/4和FRUC2/4。每次60–120秒,独立日志窗口,记录nvidia-smi功耗/频率/温度/负载并与时间轴对齐。不得用实时NR冒充原生4K或跨素材比耗时。+3. 相同设置测日志缓冲与原路径、解耦present前后:若阶段GPU时长稳定而deadline/CPU等待/丢帧下降,即证明软件调度收益;若GPU关键路径长期超过预算,则仍需降档/内部尺寸或更强硬件。+4. FRUC另做CUDA直接资源互通的小型对照,只在证明收益和reset/颜色正确后替换D3D11worker路径。NVEnc存在此结构是可行性参考,不是必然加速证明。+5. 文件模式硬解和可选缓存放后;不改变用户实时采集的产品定位,不偷换处理顺序或用离线缓存冒充实时。++本次结论:先修可观测性和软件调度,再用同源A/B确定收益;目前没有足够依据让用户换显卡。原生4K NR60fps仍不在本机默认实时档承诺内。测试验收不等于公开分发许可,未推送/发布任何源码或二进制。diff --git a/docs/HANDOFF_2026-09-09.md b/docs/HANDOFF_2026-09-09.mdindex 885d33eb..3cf218bd 100644--- a/docs/HANDOFF_2026-09-09.md+++ b/docs/HANDOFF_2026-09-09.md@@ -1,5 +1,17 @@# Veyra 交接 — 2026-09-09+> 2026-09-10 最新入口:[实时处理FPS与采集60→30交接](HANDOFF_2026-09-10.md)。此前颜色/异步呈现/Drop/光流/日志优化已同步;新显示按一秒GPU完成计数,新模式在GPU前隔帧取样。下文历史“统计未修”等以新报告为准,FRUC重置问题仍未解决。用户说明自然运行时曾调整画质,不能据此确定固定配置补帧故障。++> **22:30 性能反馈增量优先:** [原生NR性能复核与修复](NATIVE_NR_PERFORMANCE_2026-09-09.md)。运行中的采集设置不再重算旧帧建新时间线;回调arrival随帧传递,保留driver断点,复用定时器。DLSS/FRUC引擎回放各12项、CPU22项、delivery23项45.671秒通过。新增同尺寸1440p NR GPU实测中位9.75ms,与Magpie同尺寸约9.7–10.1ms接近,但不能宣称全管线追平。用户强调顺序可拖动、体验差异不大,不以改顺序作已确定方案。FRUC重建循环候选像素验收失败已撤下,原实现也由`--reset-pixels`复现重置后重复/偏移;**P1仍未解决**。最终EXE SHA256 `8E1A694229257A66DA5F36DE439423632631B310E81258EA032C92CB5FFA159D`。下一项为同负载完整链路逐段等待与呈现节奏诊断;禁止用下文旧通过结论抹去本次失败。++> **最新修复候选已落地:** [原生采集颜色与实时调度修复记录](BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md)。原生YUY2直入GPU、转换/stride修正、同尺寸拷贝消减、异步采集呈现及统计已实现;RTX离线像素、DLSS/FRUC实时回放和42.569秒完整软件短测通过。用户取消实卡A/B,本轮没有占设备,主观色带效果未冒充实测。FRUC本机缺失的两项依赖已补齐,打包清单已修;旧GitHub包本轮未更新。整体Phase7继续in_progress。下文“尚未实施/R1先测”等为先前审计记录,以本段及新报告为准。++> **最新接管入口:** [基础画质与性能修复执行文档](BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md)。用户实测报告 OBS 原始采集比 Veyra 清晰且后者出现色带;优先级改为先定位原生采集→转换→GPU→显示四段的首次失真,再做同条件性能优化。已确认强制 DirectShow RGB32、颜色元数据缺口、固定 4K 输出和处理/呈现串行等成本;色带的首个责任节点尚未闭环。本轮 GPU 无增强窄测 maxError8=0,未做新实卡对照或 NR/SR/FG 测试,未修生产代码。下一项执行新文档 R1,旧“先修统计窗口”建议后移。+>+> **当前发布事实:** `Likely7/Veyra-NRVideo` 的 v0.0.1 已公开发布(2026-09-09T11:00:36Z,非 draft、非 prerelease);下文“未发布/仅本地”的旧阶段记录不再代表远端现状。本轮未修改远端。用户本次允许必要的兼容开源代码复用,Veyra 已有 GPLv3 LICENSE;复用范围、固定来源和归因要求见新文档 R6,NVIDIA SDK/runtime 仍不得混入源码。本轮保留 AGENTS/控制 hash,不以改锁定值绕过既有漂移。++> 2026-09-09 后续:用户要求暂停间歇卡顿现场追查,先整理竞品改进方案。见 [竞品对照改进执行方案](COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md)。新增方案未实施;下一项建议为按实际 applied revision 隔离统计,再逐项验证日志、调度与 FRUC 互通成本。不要将方案当作新性能测试或已修复证明。+## 当前状态本机实验开发版;Phase7优化仍在进行。交接存档不代表公开分发许可、长期稳定性或物理端到端延迟验收。入口 `Veyra.cmd`,Release程序 `out/build/x64-release/veyra.exe`。不要移动本机runtime路径。当前说明以本文件及USER_GUIDE为准,旧报告为历史证据。@@ -22,11 +34,11 @@ Maker构建通过,实际RTX UI回归通过:`logs/video-sdk-trial-20260909/bu- Cycle78:SR运动响应诊断,未擅自更改默认算法。见SR_MOTION_RESPONSE_2026-09-08.md。- Cycle79:窗口拖拽/缩放栈溢出修复,AppShell大局部数组改为按需堆缓冲;旧独立短测通过。- Cycle80:取消采集格式30/60fps白名单;USB3Video公开4K18 YUY2/MJPEG,固件没有1440p。见CAPTURE_CARD_AUDIT_2026-09-08.md。-- Cycle81–83:RTX Video SR官方本地SDK试验与可选共享后端接入。开关决定SR启停,下拉选择DLSS或视频SR档位;SR→NR→DLSSG顺序不变。FRUC有独立D3D11试验,未接入产品。见RTX_VIDEO_FRUC_TRIAL_2026-09-09.md及RTX_VIDEO_SR_INTEGRATION_2026-09-09.md。+- Cycle81–83:RTX Video SR官方本地SDK试验与可选共享后端接入。开关决定SR启停,下拉选择DLSS或视频SR档位;SR→NR→DLSSG顺序不变。FRUC在当时仅为独立试验;当前已由Cycle87–88可选后端取代,见FRUC_INTEGRATION_2026-09-09.md。见RTX_VIDEO_FRUC_TRIAL_2026-09-09.md及RTX_VIDEO_SR_INTEGRATION_2026-09-09.md。- Cycle84:真实1080p60卡对照,原生4K NR约23ms、实时NR约6ms。视频SR最高约6.5ms、低约1.5ms;实时NR+低SR接近60源fps。不能把这些阶段耗时当物理延迟。测试恢复时遗漏FG2、留下关闭,已向用户纠正。见PHYSICAL_CAPTURE_DIAGNOSIS_2026-09-09.md。- Cycle85:用户FG开关导致NR22→6ms,日志证明NR4K→1080;旧设置整页提交存在串改缺陷。已修复并独立通过;Cycle86进一步改为单字段即时提交。见SETTINGS_PAGE_SCOPE_REPAIR_2026-09-09.md。-## 下一位接手先做什么+## 旧交接建议(最新优先顺序见本文顶部与基础画质修复文档)1. 查看git存档、loop/STATE.json与本报告末尾最终验收结果,保留用户本地配置和未提交改动。每次测试上限300秒,实卡由用户验收,不自动占用。2. 优先修正性能指标窗口:EngineController TimingWindow仍保留1200历史采样,改配置后统计会混入旧值。UI必须区分NR单阶段、其他GPU阶段、处理吞吐与未测物理延迟;不能相加后伪称实测端到端。@@ -49,3 +61,13 @@ Maker构建通过,实际RTX UI回归通过:`logs/video-sdk-trial-20260909/buEXE SHA256: `3BD470D51AD43F7C461F23AB6F9F9B7234DC6F33D84C9DDEB35A463663264E2C`。构建日志 `logs/video-sdk-trial-20260909/build-cycle86.log`;独立review前后跟踪指纹 `9d45fe7ff6b19a67b3a42db2215928b1aecf5b4f`不变,之后仅更新交接记录。单次测试均不足300秒。Cycle86修复可交本机实测;整体Phase7优化仍in_progress,既有统计窗口/间歇时序/实卡体验/长期稳定风险未宣称消失。下一任务见HANDOFF优先处理配置相关统计窗口。本地Git checkpoint包括Cycles78–86已核对源码、使用指南、交接报告与授权的GOAL_PROMPT删除;不包含runtime/SDK/个人媒体,不push。实际提交ID以本次 `git log -1` 为准,避免在commit内容中制造自指hash。+++## Cycle87–88增量++FRUC与1000fps时间戳接入及真实测试见[FRUC_INTEGRATION_2026-09-09.md](FRUC_INTEGRATION_2026-09-09.md)。新增同目录veyra_fruc_worker.exe为必须保留的本地自编辅助程序,FRUC关闭时不启动。预设schema4记录后端,保留旧版本读取。整体Phase7与分发状态不变;下一步先让用户用实卡比较2X,再评估4X成本与drop触发重置;不把构造平移成功当总体画质成功。独立review/gate结果稍后追加。+++## 独立检查与用户反馈补充++独立review_fruc已报告CPU16+27项/preset、实际2/3/4pixel/PTS/连续reset、UI全后端切换和自有worker进程故障测试通过,无新增已确认P0/P1/P2消息。preflight69 PASS;其实际phase7日志 `logs/video-sdk-trial-20260909/review-fruc-gate-phase7.log` 为73 PASS,delivery `logs/delivery/1c195ef6d3684879b220fc8c13439e83/result.json`。Reviewer随后额度耗尽,未返回最终整体结论;因此记录为independent_checks_passed / final_verdict_unavailable,不伪造最终Reviewer PASS。用户随后明确“我已经测试没问题”,记录用户本次体验通过,不外推其未说明的配置与长期稳定性。程序SHA256 BD76BA1F3D66DF30286E450AD1742E773F48989B5815C175BDC0A297ABF4E94D;workerSHA256 B6F267C3B1C73DE0CB99C4BAD4B5DA9355C42DF7E7F37F21C9891B02B80412A3。diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.mdnew file mode 100644index 00000000..cb2f8c9a--- /dev/null+++ b/docs/HANDOFF_2026-09-10.md@@ -0,0 +1,53 @@+# 当前交接:处理帧率与采集 60→30++2026-09-10,Phase 7 `in_progress`。本地开发存档,不代表整体性能问题解决;不 push、不更新 Release、不打包运行时。++## 最新决定与实现++用户说明上一轮帧率变化发生在自己调整画质期间,不能将自然日志当作固定配置的补帧故障证明,撤回此前确定归因。本轮完成实时处理FPS、PS5稳定30fps经60fps采集的处理选项,并同步此前成果。++- 底栏右侧 `处理 x.x fps` 在日常、专业及全屏控制条可见,全屏控件自动隐藏时随之隐藏。诊断使用同一指标。+- `FrameRateWindow` 统计最近一秒GPU完成的真实帧,不乘FG倍率,不使用会话平均、源到达或CPU提交次数。`EnhanceGraph::resolveGeneration` 对无FG真实帧也非阻塞检查GPU fence。暂停/停止/图片显示0,停流一秒内归零;成功切换设置重置窗口。最多8192个事件,支持1000fps计数。+- 内容节奏选择器末尾新增 `采集60→30fps处理(PS5 30帧)`,保留旧选项和值。“识别30fps”只检测节奏,原来不会降低GPU处理次数。现有预设字段保存新枚举。+- `CaptureHalfRate` 在采集read后、GPU graph前隔帧取样,60→30、59.94→29.97。选中帧保留原始PTS,duration为两个传输周期,FG以约33.3ms间隔配对;2X/4X目标约60/120fps,不保证实际达到。+- 只对标称59–61fps的采集生效;18/30/120fps不会误减半,不适用采集显示“不适用”。文件播放与导出不丢源帧,音频路径不变。+- 每个传输包仍读出,有意跳过单独记 `captureRateSkipped`。mailbox容量1、呈现两批次上限不变;真正Drop/断点仍reset全部历史,边界帧不被取样吞掉。++这是明确的隔帧取样,不是自动去重,不能恢复PS5内部时间戳。稳定A,A,B,B输入适用;游戏帧间隔波动、HUD独立60fps、重复相位变化可能漏取独特画面,应切回源时间戳比较。++## 之前的实现一起存档++1. 原生YUY2/NV12 DirectShow接收、一次GPU颜色转换、范围/矩阵/stride校正、同尺寸拷贝消减。离线颜色证据见 `BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md`;用户撤回的实卡同帧A/B没有执行。+2. 两批次异步呈现。Drop使temporal history失效,但不再每次排空完成的真实帧;跨generation生成帧跳过。显式重配/resize仍排空。+3. 采集设置使用新到达帧和真实arrival,暂停可重算缓存;复用DeadlineWait。实时档光流内部尺寸限制至NR内部尺寸以内,motion再换算至NR/FG尺寸,原生/导出保留原尺寸策略。顺序仍SR→NR→FG。+4. 对比关闭不保存额外source/base参考;默认关闭成功逐帧日志,`VEYRA_VERBOSE_FRAME_LOGS=1`启用。按revision重置计时窗口,记录槽位等待、GPU各阶段、Present与过期计数,GUI写文件日志。+5. 本地FRUC依赖补齐及打包allowlist源代码变更一并存档,DLL/SDK不入Git;远端旧包没有更新。++## 实际验证++本机RTX5070,测试串行,单项外部timeout290秒,没有打开实体采集卡。路径相对项目根目录。++| 命令 / 场景 | 结果与证据 |+| --- | --- |+| `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <root> -Preset x64-release` | exit0,`logs/build-fps-capture30-20260910-final.log` |+| `veyra_live_timing_tests.exe` | 41 PASS:60/59.94、抖动、断点、停流归零、1000fps |+| `veyra_presentation_worker_tests.exe` | 11 PASS:有界、取消、失败、统计清空 |+| `veyra_repair_preset_tests.exe logs/capture30-presets-20260910.txt` | PASS:新选项往返、旧schema |+| `veyra_live_presentation_tests.exe loop/local/fixed_clips/test_av_1080p.mp4 logs/fps-capture30-20260910/live-half-final --half-rate` | 19 PASS;GPU约30fps、切回约60fps、NR/DLSS2X/4X、暂停/设置/退出。`logs/baseline-repair-20260909/capture30-live-final.log` |+| `python scripts/acceptance/ui-processing-fps.py` | 日常/专业/窄窗口:文字可见、边界内、实时数值、暂停0;`logs/baseline-repair-20260909/capture30-ui-final.log` |+| `veyra_live_presentation_tests.exe logs/video-sdk-trial-20260909/known-pan15.mp4 logs/fps-capture30-20260910/live-fruc --fruc` | 14 PASS;既有FRUC回放、设置、暂停、完成FPS,`logs/baseline-repair-20260909/capture30-fruc.log`。不覆盖已知reset-pixels失败 |+| `powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/baseline-repair-20260909/delivery-env.ps1 -Root <root>` | 原版delivery23 PASS,45.317秒。`logs/delivery/910fe667d2574babaa3b02a7aa9bb3e2/result.json` |++测试EXE均在 `out/build/x64-release/`。live日志有 `interval100ns=333334`、`gpuCompletedFps=30.00`、`rateSkipped=63`,切回 `interval100ns=166667`;这是处理/提交而非屏幕扫描。delivery包含实际NR/NVOF/GBV、native4K、播放、图像、NVENC音轨/CFR/取消。包装仅导入系统Utility模块,gate与导出检查没有改。++本次两项初始失败保留:独立单测Windows min宏编译失败,改括号调用后通过;UI脚本误认辅助根窗口,改为从标签取根窗口并统一DPI坐标后通过。++EXE SHA256:`A0DB6D6109EDE751A91762664A1589A90134A673BEAE2F5722313A53088BE646`。NR仍为AGENTS指定SHA,签名Valid。++## 边界与下一步++原生4K NR成本、临界负载FG deadline/帧节奏、FRUC重置后像素与重建等待、自然运动质量、PS5实卡体验和长期稳定仍未验收。软件短测不抵消 `NATIVE_NR_PERFORMANCE_2026-09-09.md` 的FRUC失败。既有控制hash漂移保留,没有改控制面自我放行;本轮无新的独立Reviewer结论。++下一条任务:用户在固定30fps PS5场景、采集60fps下选择新增模式,观察输入约60/处理约30,对比关闭、2X、4X。性能归因必须固定尺寸、SR质量、NR内部尺寸、FG倍率和applied revision。++启动 `Veyra.cmd`,实际程序 `out/build/x64-release/veyra.exe`。本地Git仅保存源码/文档,不含SDK、runtime、模型、媒体、日志,也未更新GitHub。diff --git a/docs/NATIVE_NR_PERFORMANCE_2026-09-09.md b/docs/NATIVE_NR_PERFORMANCE_2026-09-09.mdnew file mode 100644index 00000000..9b53dff4--- /dev/null+++ b/docs/NATIVE_NR_PERFORMANCE_2026-09-09.md@@ -0,0 +1,66 @@+# 原生 NR 性能复核与本轮修复++日期:2026-09-09。状态:Phase7 in_progress;计时修复已验证,整体性能问题未解决。用户明确不再做实卡颜色 A/B,本轮未打开采集卡,未修改 Magpie、运行时或远端 Release。++## 结论与证据边界++用户反馈 Magpie 同时开启 SR/NR/FG 仍流畅,Veyra 原生 NR 卡顿且 GPU 占用高;用户补充 Magpie 可拖动改变顺序,实际体验差异不大。不能用一次 NR→SR 日志把整体差距归因于顺序,更不能把用户的实际体验判为错误。++本轮额外运行了 Veyra 原生 2560×1440 NR:90次 Evaluate、89次 NVOF,88条已完成 GPU NR timestamp,中位 **9.74784ms**、平均 **9.76670ms**、P95 **10.11734ms**。Magpie 已存同尺寸原生 NR 的120帧窗口平均为 **9.718–10.095ms**。这支持“同尺寸 NR 单次执行没有显示出倍数级差距”,不证明两者全管线、同素材、GPU占用或实际显示延迟相等。Veyra 测试素材为固定4K视频缩到1440p,没有同时启用SR/FG。++Veyra 用户运行日志中的原生4K NR 中位22.450ms、P95 24.268ms是真实 GPU NR 阶段计时。不能据此声称5070无法运行所有4K输出组合,也不能承诺仅修计时就把4K NR降到10ms。++## 自然运行日志++冻结证据位于 `logs/native-nr-performance-20260909/`,含 `veyra-app.log`、`magpie.log`、`magpie.1.log`、`analyze.py`、`veyra-summary.json`。Veyra日志为UTC,Magpie日志为本地UTC+8。阶段摘要按应用revision区间分组,边界可能包含少量上一revision延迟回收的timestamp;中位值不是逐帧配对的竞品benchmark。++| 运行片段(本地时间) | 实际链路/观察 |+| --- | --- |+| Magpie 21:47:13 | SR1535×971→2276×1440,然后NR2276×1440、FG2276×1440;NR GPU窗口平均9.227/9.279ms |+| Magpie 21:52:14 | NR1535×971、SR→3840×2160、FG backbuffer2560×1440;NR GPU窗口约5ms |+| Magpie 19:55 | NR2560×1440;GPU窗口平均9.718–10.095ms |+| Veyra revision15 21:37:55 | 输入1080p60、SR4K、NR4K、FG4K;NR22.450ms;callback到Present返回P95约71ms,丢帧持续增加 |+| Veyra revision16 | 恢复实时NR1080,NR约5.929ms;callback到Present返回P95约29.3ms |+| Veyra revision21 21:39:31 | FRUC2X;处理CPU P95约335ms、画面年龄约346ms;worker约每330ms重建,生成数不增长 |+| Veyra revision27 21:42:14 | NR关闭、处理CPU约2ms,但画面年龄约109ms;设置重算缓存帧把约49ms旧帧年龄加入新时间线 |++Magpie来源行:`magpie.1.log:2198/2351/2398/2409/1531/1575–1671`;最新组合 `magpie.log:390–393`。其中确有超分4K中间纹理,不能说“根本没开4K”。但没有在这些保留片段中找到NR实际3840×2160的对应测试,不能把屏幕上的“4K”标签当每一阶段的尺寸证明。截图13.529ms不是HDMI到显示的延迟;FG的0.037ms也不能直接当完整GPU插值成本。不同阶段存在重叠/嵌套计时,不能简单相加。++## 已落地的改动++- `FramePacket.h`:帧包携带采集回调的单调时钟时间。`CaptureCardSource.cpp` 将真实 arrival 与对应帧一起传递,供时间线和画面年龄使用。+- `EngineController.cpp`:运行中的采集设置事务读取新帧;等待时保留事务与回滚信息。暂停时才重算缓存;等待途中暂停也能转回缓存。缓存重算不建立新的live时间线。新epoch以回调时间锚定,不以处理开始时间锚定。+- `CaptureTiming.h`、`CaptureCardSource.cpp`:区分连续回调间的时钟异常和消费者漏读;driver discontinuity跨mailbox覆盖保留。Drop仍使全部历史reset,没有删除reset规约。+- `EngineController.cpp`:实时呈现线程复用会话级DeadlineWait,消除每批次创建/销毁定时器。双批次容量和FG因果lookahead保持。+- `LivePresentationTimingTests.cpp`、`LivePresentationTests.cpp`:覆盖回调断点保留、新帧设置、暂停缓存预览和真实引擎事务。未修改颜色公式、NR参数、处理顺序、默认NR策略或导出检查。++## FRUC 未解决,候选已撤下++确认旧实现每次reset重建worker,造成“耗时→丢帧→reset”的循环。尝试了状态更新bSkipWarp、延后重建/保持未播种worker、进程内相对时间基准及首对预热。像素测试未通过,不能只因API返回成功就交付。++重要补证:撤回所有FRUC生产改动后,原实现的重置后像素检查仍失败。`nrperf-baseline-fruc-reset.log` 中epoch1/2首对MAE等于重复上一帧;epoch3/4第二对误差更高,而API返回0且repeated=false。异常不只存在于轻量reset候选;也不能武断归咎于SDK,需要继续查共享纹理生命周期、同步、输入首帧和时间语义。++保留 `veyra_fruc_tests.exe 2 <pan.nv12> --reset-pixels` 作为明确失败的附加复现入口。常规既有短测仅验证初始平移像素和静态reset可调用,未曾覆盖本项。不能用常规短测或delivery通过覆盖这个失败。++本地候选补丁:`logs/native-nr-performance-20260909/fruc-recovery-candidate.diff`,含前轮graph改动上下文,仅供人工核对,禁止整份盲目套用。失败日志均在 `logs/baseline-repair-20260909/nrperf-fruc*.log`。最终FRUC Backend/Worker/Protocol及graph FRUC生产段保持本轮前行为,因此重建循环仍存在。++## 本轮实际验证++下列命令由 `python logs/baseline-repair-20260909/run.py <标签> <命令...>` 包装,每次外部timeout290秒。全部为本机RTX5070,测试之间串行,不占实卡。++1. `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <项目目录> -Preset x64-release`:exit0,`nrperf-final-build.log`。+2. `out/build/x64-release/veyra_live_timing_tests.exe`:22项PASS,`nrperf-timing.log`。+3. `veyra_live_presentation_tests.exe loop/local/fixed_clips/test_av_1080p.mp4 logs/native-nr-performance-20260909/live-dlss`:12项PASS,实际NR/DLSS2X/4X、设置/暂停/恢复/退出。+4. `veyra_live_presentation_tests.exe logs/video-sdk-trial-20260909/known-pan15.mp4 logs/native-nr-performance-20260909/live-fruc --fruc`:12项PASS,使用既有FRUC;不证明重置后所有插值像素正确。+5. `veyra_fruc_tests.exe 2 logs/video-sdk-trial-20260909/pan.nv12 --reset-pixels`:**exit1,未解决**;`nrperf-baseline-fruc-reset.log`。+6. `powershell.exe -NoProfile -ExecutionPolicy Bypass -File logs/baseline-repair-20260909/delivery-env.ps1 -Root <项目目录>`:原版delivery23项PASS,45.671秒,`logs/delivery/d3b2dd62224a4df986941a8a4a1cb8a6/result.json`。包装仅导入系统Utility模块,未改gate;非preflight或实卡验收。+7. `veyra_quality_probe.exe --input logs/native-nr-performance-20260909/native1440.mp4 --native --guidance motion --frames 90 --json-file logs/native-nr-performance-20260909/native1440.json`:exit0,90NR/89NVOF,失败0,正常路径像素回读0;真实NR阶段timestamp来自`nrperf-native1440.log`。probe为吞吐运行,CPU fence计数86不能解释为实卡每帧必然等待的额外延迟。+8. `git diff --check`:PASS;NR固定SHA一致;没有提交SDK/runtime、push或发布。++可运行程序:`out/build/x64-release/veyra.exe`,SHA256 `8E1A694229257A66DA5F36DE439423632631B310E81258EA032C92CB5FFA159D`。根目录 `Veyra.cmd` 指向本机构建。旧GitHub包没有更新。++## 下一步执行边界++下一条任务:在保持用户现有顺序的条件下,给同尺寸同倍率的完整采集管线建立逐段CPU等待/GPU执行/呈现节奏证据,再修已定位的热点。以同一源尺寸、NR尺寸、SR质量、FG输出尺寸、实际输入/显示帧率匹配,分别记录源回调、mailbox读取、上传slot等待、graph锁等待、NVOF、SR、NR、FG、GPUready和Present提交。不能用理论FPS或GPU占用百分比单独归因。用户未批准改变顺序,不自动添加或替换产品路线。++FRUC分支须先通过重置后的真实像素复现,再恢复轻量化工作;不要盲目跳过历史reset或把重复帧计作有效生成。显卡负载、自然运动、实卡感受与长期稳定仍未验收。已有控制hash漂移保留,没有改控制面自我放行。diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex d21b6f66..754ef5d8 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -1,5 +1,13 @@# Veyra 本机使用 — 日常 / 专业双模式+## 2026-09-10 实时FPS与PS5 30帧++底栏右侧“处理 fps”是最近一秒GPU真正完成的真实帧数量,不含补帧,不等于屏幕扫描率。暂停/停止显示0,切换配置重新计数;呈现提交在诊断里单独列出。++PS5固定30fps、采集卡只能60fps:设备保持60fps,进入专业模式“补帧与运动估算”,内容节奏选择“采集60→30fps处理(PS5 30帧)”。输入仍约60,处理应约30;59.94对应29.97。再选2X目标约60fps或4X目标约120fps,实际受GPU和生成有效性限制。选“采用源时间戳”实时恢复完整处理。++新选项是GPU前隔帧取样,适合稳定重复帧,不是自动去重;帧间隔不均匀或HUD单独60fps时可能漏取,应对比原始模式。旧“识别30fps”只检测不减计算。文件播放/导出不丢帧,18/30/120fps采集不会误减半。完整状态见 [当前交接](HANDOFF_2026-09-10.md),下文历史未修统计窗口等说明以此为准。+双击项目根目录 `Veyra.cmd`。实际程序为 `out/build/x64-release/veyra.exe`;本机 runtime / shader 路径在构建时绑定,不要移动项目目录。这不是可公开分发的安装包。## 两种界面@@ -60,7 +68,7 @@日常模式直接点底部“采集”图标,专业模式点左侧采集图标,选择真实视频设备、实际格式和HDMI音频输入。先NR开、FG关检查视频声音,再选补帧倍率。补帧需要等待下一源帧,不能消除采集卡固有延迟。当前修复版本的实卡验收由用户完成,本轮未占用采集卡。-仅Windows x64/NVIDIA/SDR,偶数尺寸最高3840×2160;HDR不支持。Depth provider未实现,当前为NVOF motion + confidence门控,不等同游戏原生深度/运动向量。短测不证明长期稳定、所有采集卡兼容或画质优于其他产品。实际屏幕扫描/光子延迟、多屏物理DPI穿越尚未测量。专有runtime分发权未解决,不打包、上传或发布DLL/SDK。+平台为Windows x64/NVIDIA/SDR,4K视频为当前主要验证范围;图片支持不同长宽与大图分块,仍受内存和GPU资源限制;HDR不支持。Depth provider未实现,当前为NVOF motion + confidence门控,不等同游戏原生深度/运动向量。短测不证明长期稳定、所有采集卡兼容或画质优于其他产品。实际屏幕扫描/光子延迟、多屏物理DPI穿越尚未测量。发布采用用户授权的实验Runtime Pack;SDK/runtime仍不得进入源码,当前本机修复未更新远端Release。窗口尺寸、位置、音量、字幕等保存在独立UI偏好中;只保存成功应用的画质。损坏的原配置保留,不静默覆盖。程序每次重启仍默认日常模式。@@ -69,4 +77,4 @@## 2026-09-09 当前交接-最新交接见 [HANDOFF_2026-09-09.md](HANDOFF_2026-09-09.md)。RTX Video SR已接入共享管线;专业模式补帧页现可切换DLSS或NVIDIA FRUC,选择关闭/2X/3X/4X,均实时应用;详见[FRUC接入记录](FRUC_INTEGRATION_2026-09-09.md)。FRUC更高倍率开销更高,SDK可能退回原帧;跳转/切镜/采集掉帧会重建并可能短暂卡顿。播放器时间戳支持到1000fps,实际吞吐取决于尺寸/处理链/硬件;已测256×144无增强约999fps,不是4K千帧保证。NR表盘只表示NR阶段GPU耗时,不是采集到屏幕总延迟,统计窗口混合旧配置的问题尚待处理。USB3Video实卡已实测1080p60与4K18;设备未公开1440p格式,不人为伪造模式。+最新交接见 [HANDOFF_2026-09-10.md](HANDOFF_2026-09-10.md)。RTX Video SR已接入共享管线;专业模式补帧页可切换DLSS或NVIDIA FRUC,选择关闭/2X/3X/4X,均实时应用;详见[FRUC接入记录](FRUC_INTEGRATION_2026-09-09.md)。FRUC更高倍率开销更高,SDK可能退回原帧;重置后像素和重建卡顿仍有已知问题。播放器时间戳支持到1000fps,实际吞吐取决于尺寸/处理链/硬件;已测256×144无增强约999fps,不是4K千帧保证。NR表盘只表示NR阶段GPU耗时,不是采集到屏幕总延迟;当前已按设置revision隔离统计。USB3Video实卡曾测1080p60与4K18;设备未公开1440p格式,不人为伪造模式。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 5254787b..d1ee6a05 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,3 +1,9 @@+# 2026-09-10 当前修复与本地存档++新增一秒GPU完成FPS和采集60→30;同步此前颜色/异步呈现/Drop reset/实时光流/日志改动。文件、命令与边界见 `docs/HANDOFF_2026-09-10.md`。Release exit0;CPU41/worker11/预设PASS;真实engine half-rate19 PASS;UI日常/专业/窄窗口PASS;delivery23 PASS45.317秒,run `910fe667d2574babaa3b02a7aa9bb3e2`。未打开实卡,不是整体Phase7通过。++初次Windows min宏编译失败和UI辅助根窗口误认已修正,失败日志保留。用户纠正自然FPS变化发生在调画质期间,撤回对该段的确定异常归因。NR固定SHA与Valid签名核对。FRUC重置像素、临界负载节奏仍开放;不改控制面、不push。用户授权本地Git存档当前源码/文档,不含SDK/runtime/媒体/日志。+# 2026-09-08 优化 Goal 启动与 preflight 停点用户明确开启目标模式,新增解除不合理媒体尺寸限制、专业预览悬停滚轮缩放,并实施现有优化方案;导出完整性检查保持现状。Goal 和 BACKLOG 已建立。@@ -1322,3 +1328,35 @@ User requested1000fps support andFRUC2/3/4. Source timing admission120→1000, e用户选择完整开箱即用的实验 Runtime Pack,并明确接受该 Pack 可能被 GitHub 下架或被权利方要求移除的风险。`AGENTS.md` 已锁定源码/Release 物理隔离:NVIDIA 二进制、SDK、头文件、库、样例和压缩包不得进入 Git、LFS、源码或资源;仅经 manifest 白名单、固定 SHA-256、有效 NVIDIA Authenticode 签名和适用许可证检查的用户包 Release 资产可携带运行时。不得篡改/重签名/隐藏、不得从游戏或驱动缓存提取,且不得宣称 NVIDIA 官方支持。`FrucWorker` 改为从 EXE 相对的 `runtime_local/nvidia/NvOFFRUC.dll` 加载,移除开发机绝对路径。`scripts/package-portable.ps1` 以显式 allowlist 打包 `nvngx_dlss.dll`、`nvngx_dlssg.dll`、`nvngx_dlssnr.dll`、`nvngx_vsr.dll`、`NvOFFRUC.dll`,生成 `release-runtime-manifest.json`,附带 RTX / Optical Flow 许可证并排除 SDK 开发文件。Release 构建通过;最新 ZIP SHA256 `C3BA5C6E138557D3F4A208737CCC2542CE5687DA1BA7F0AD534F009DA4AE1E6F`。独立解压后五个 DLL 的 SHA-256 均匹配 manifest、Authenticode 均为 Valid,包内未发现 PDB/LIB/头文件/样例/SDK 目录;`veyra.exe --smoke-empty --smoke-seconds 3 --no-nr --no-sr --no-fg` 退出码 0。尚未 commit、push、tag 或创建 GitHub Release;README 控制面 hash 漂移仍未自行重基线。++## 2026-09-09 OBS/Magpie 实卡反馈:基础画质审计与修复交接++交付 docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md,优先级改为先找色带首次失真节点,再比较同尺寸性能。确认 DirectShow 强制 RGB32 与原生颜色元数据缺失、固定 SR 4K 目标、处理/呈现串行、逐帧复制/日志等设计成本;不宣称已证明具体转换器用了错误矩阵。保存用户 OBS/Magpie 日志、精确源码与身份于 gitignored 的 logs/obs-magpie-rootcause-20260909/。Magpie 现有日志多为 1440p,不能冒充与 Veyra 同等 4K 实测。++实际命令:python logs/obs-magpie-rootcause-20260909/build_probe.py。复用当前编译的产品库/Shader,构建仅诊断入口;build/run 均 exit 0,IMAGE_DIMENSION 256x64 nr=0 maxError8=0,CAPTURE_RGB nr=0 maxError8=0 cuts=1 nvof=0。首次包装脚本匹配编译参数失败,修正后约 5.4 秒完成。此结果仅覆盖合成 RGB/BGR0 到 GPU 无增强输出,不覆盖实卡转换或最终窗口;未新执行 SR/NR/FG、完整 delivery 或独立审查。证据 baseline-result.json、baseline-probe.log、audit-manifest.json。++gh release view v0.0.1 -R Likely7/Veyra-NRVideo --json url,isDraft,isPrerelease,publishedAt 确认已公开发布,时间 2026-09-09T11:00:36Z。纠正旧“尚未发布”记录,不修改远端。保留开工前文档改动,生产代码和运行时未修改,AGENTS/CONTROL_HASHES 未修改,不自我放行历史 hash 漂移。用户授权兼容 OSS 模块复用记录在新方案 R6,保留版权/源码义务与 NVIDIA 二进制边界。++Phase 7 仍 in_progress,产品修复待执行;下一条任务 R1:对原生采集、转换后、GPU 输出和最终显示做同帧定位,再按坏样本修 R2/R3。单次测试 <=300 秒,导出完整性检查保持现状。++## 2026-09-09 原生 YUY2 与实时呈现修复交付++用户撤回实卡 A/B(“不用测试这个,可以确定就是YUY2的转换”),本轮未打开采集设备。实际实现见 docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md:原生 YUY2/NV12 DirectShow 接收、一次 GPU YUY2→linearFP16、颜色元数据/stride/方向校正,同尺寸 blit/copy 消减、两个批次的异步采集呈现、revision 隔离统计与批量文件日志。保存/暂停/重配置/退出仍按 lease/fence 排空。不能说已同帧实测证明全部色带只有一个根因。++Release 构建 final-build4.log exit0;CPU契约26项、worker11项;YUY2 601/709×full/limited、原生4K及RGB范围 GPU 基准最大误差<=1/255,显示误差0。YUY2八帧NR含7次NVOF/7帧motion;实际Engine文件回放live worker的DLSS2X/4X/暂停恢复/设置/退出10项PASS,FRUC已知15fps平移素材同样10项PASS。没有占实卡。单项均外部timeout290秒。++delivery最终 logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json,23项PASS、42.569秒;NR/NVOF/GBV零错误、4K播放、4K图像、NVENC H264/HEVC音频和2X CFR、取消检查通过。第一次delivery所有功能检查通过但最后Get-FileHash模块未加载而exit1,保留2d62b4ad日志,仅包装导入平台Utility模块后重跑,未改原gate。早期编译头文件遗漏、temporal测试未开启NVOF配置的失败与修正也保留。++独立review_native_capture最终限定复核:所提动态格式/RGB范围/异步统计问题均关闭,审查范围无其他未修P0/P1/P2;它核对源码和真实日志,没有自行执行GPU或实卡,不记整体Phase7 PASS。++另发现旧路径迁移导致本机FRUC运行目录缺NvOFFRUC.dll及其直接依赖cudart64_110.dll。由已有本地SDK复制固定SHA/有效NVIDIA签名的两项到gitignored runtime_local,不修改文件内容。打包allowlist添加固定cudart依赖;仅语法检查,未执行打包或发布。实际FRUC平移回放通过;通用test_av素材返回repeated=true的失败保留,不当有效生成。已发布旧包未更新。++EXE SHA256: 61618AF18F7B985BD4C1FECA06EBE7A07C30EAA01B2CC0682A217E89EAD3C372。原版NR固定SHA一致。已有控制面漂移保留,不改AGENTS/README/CONTROL_HASHES、不声称preflight通过。整体Phase7仍in_progress;下一条任务是用户实测本机新YUY2路径,再按同尺寸同配置证据继续性能优化。FRUC互通/重建等待、GPU临界区、自然运动效果和长期稳定性仍有边界。未push、未重新发布Release。++## 2026-09-09 原生 NR 性能再反馈++完整记录、文件清单、实际命令见 `docs/NATIVE_NR_PERFORMANCE_2026-09-09.md`。完成采集设置fresh帧/arrival锚点、暂停等待、driver断点跨mailbox保留与DeadlineWait复用。最终构建`nrperf-final-build.log` exit0;CPU22、live DLSS12/FRUC12通过;delivery `d3b2dd62224a4df986941a8a4a1cb8a6` 23项45.671秒通过。EXE `8E1A694229257A66DA5F36DE439423632631B310E81258EA032C92CB5FFA159D`。++FRUC候选bSkipWarp/延后重建/时间归零/首对预热均未通过新增reset后像素检查,生产改动撤回,失败证据和候选diff保留。原FRUC新增`--reset-pixels`同样exit1:API成功而部分重复/偏移,不能称原实现通过更严格验收;重建循环未解决。既有短测通过不覆盖这一失败。++本机原生1440p NR额外执行90帧/89NVOF,88条完成GPU timestamp:中位9.74784ms、P95 10.11734ms;Magpie既有同尺寸窗口平均9.718–10.095ms。素材/全链路不完全匹配,只说明纯NR同尺寸未显示倍数差距。用户补充顺序可拖动且实测差异不大,已撤回“顺序是主因”的推断;不变更产品路线。下一任务是同尺寸、同倍率完整链路CPU等待/GPU/呈现节奏诊断。未占实卡、未修改runtime/控制面、未push发布。Phase7仍in_progress。diff --git a/include/veyra/Log.h b/include/veyra/Log.hindex abfc17de..3622f5e7 100644--- a/include/veyra/Log.h+++ b/include/veyra/Log.h@@ -47,6 +47,8 @@ private:std::mutex mutex_;std::FILE* file_ = nullptr;bool consoleEnabled_ = true;+ uint64_t lastFileFlushTick_=0;+ size_t bufferedLogBytes_=0;diagnostics::DiagnosticHistory diagnostics_;std::string latestProblem_;};@@ -58,6 +60,7 @@ void trace(const char* component, const std::string& message);void info(const char* component, const std::string& message);void warn(const char* component, const std::string& message);void error(const char* component, const std::string& message);+bool verboseFrameLogs();// Key=value helper used by call sites that need structured fields.inline std::string kv(const char* key, uint64_t value)diff --git a/include/veyra/diagnostics/GpuTimer.h b/include/veyra/diagnostics/GpuTimer.hindex 851c23be..9a257cbf 100644--- a/include/veyra/diagnostics/GpuTimer.h+++ b/include/veyra/diagnostics/GpuTimer.h@@ -11,7 +11,7 @@ class GpuTimer {Microsoft::WRL::ComPtr<ID3D12QueryHeap> heap_;Microsoft::WRL::ComPtr<ID3D12Resource> readback_;std::array<Pending,slots> pending_{};uint64_t frequency_=0;int active_=-1;- FrameMetrics last_;+ FrameMetrics last_;uint64_t lastCollectedFence_=0;public:bool initialize(ID3D12Device* device,ID3D12CommandQueue* queue){close();HRESULT hr=queue->GetTimestampFrequency(&frequency_);if(FAILED(hr)||!frequency_)return false;@@ -23,9 +23,9 @@ public:for(unsigned slot=0;slot<slots;++slot){auto& p=pending_[slot];if(!p.fence||p.fence>completed)continue;void* data=nullptr;D3D12_RANGE range{slot*stride*8,(slot+1)*stride*8};auto hr=readback_->Map(0,&range,&data);if(FAILED(hr)){log::error("gpu-timestamp",std::format("Map hr=0x{:X}",unsigned(hr)));p.fence=0;continue;}FrameMetrics m;m.identity=p.id;auto values=static_cast<const uint64_t*>(data)+slot*stride;for(unsigned stage=0;stage<stages;++stage)if(p.mask&(1u<<stage)){auto& v=m.gpu[stage];v.begin=values[stage*2];v.end=values[stage*2+1];v.frequency=frequency_;if(v.end>=v.begin){v.state=SampleState::Measured;v.milliseconds=double(v.end-v.begin)*1000/frequency_;}else v.state=SampleState::Unavailable;- log::info("gpu-timestamp",std::format("frame={} epoch={} revision={} stage={} begin={} end={} frequency={} ms={} (GPU queue timestamps)",p.id.sourceFrameId,p.id.epoch,p.id.settingsRevision,stage,v.begin,v.end,frequency_,v.milliseconds.value_or(-1)));+ if(log::verboseFrameLogs())log::info("gpu-timestamp",std::format("frame={} epoch={} revision={} stage={} begin={} end={} frequency={} ms={} (GPU queue timestamps)",p.id.sourceFrameId,p.id.epoch,p.id.settingsRevision,stage,v.begin,v.end,frequency_,v.milliseconds.value_or(-1)));}- D3D12_RANGE written{0,0};readback_->Unmap(0,&written);if(m.identity.sourceFrameId>=last_.identity.sourceFrameId)last_=m;p.fence=0;+ D3D12_RANGE written{0,0};readback_->Unmap(0,&written);if(p.fence>=lastCollectedFence_){last_=m;lastCollectedFence_=p.fence;}p.fence=0;}}void frame(pipeline::FrameIdentity id,ID3D12Fence* fence){collect(fence);active_=-1;if(!heap_||!readback_)return;auto i=unsigned(id.sourceFrameId%slots);if(pending_[i].fence)return;active_=int(i);pending_[i]={id,0,0};}@@ -34,6 +34,6 @@ public:void resolve(ID3D12GraphicsCommandList* list){if(active_<0)return;auto mask=pending_[active_].mask;for(unsigned i=0;i<stages;++i)if(mask&(1u<<i)){unsigned index=active_*stride+i*2;list->ResolveQueryData(heap_.Get(),D3D12_QUERY_TYPE_TIMESTAMP,index,2,readback_.Get(),index*8);}}void submitted(uint64_t fence){if(active_>=0)pending_[active_].fence=fence;active_=-1;}const FrameMetrics& last()const{return last_;}- void close(){heap_.Reset();readback_.Reset();pending_={};last_={};active_=-1;frequency_=0;}+ void close(){heap_.Reset();readback_.Reset();pending_={};last_={};lastCollectedFence_=0;active_=-1;frequency_=0;}};}diff --git a/include/veyra/engine/CaptureHalfRate.h b/include/veyra/engine/CaptureHalfRate.hnew file mode 100644index 00000000..c934e809--- /dev/null+++ b/include/veyra/engine/CaptureHalfRate.h@@ -0,0 +1,25 @@+#pragma once+#include <cmath>+#include <cstdint>+namespace veyra::engine {+// Explicit 60/59.94 transport -> 30/29.97 sampling before any GPU work.+// Keeps original PTS. It does not claim to detect unique pictures or repair+// irregular game cadence. Quarter-slot tolerance absorbs timestamp jitter.+class CaptureHalfRate {+public:+ void reset(){anchored_=false;}+ static bool supported(double fps){return std::isfinite(fps)&&fps>=59&&fps<=61;}+ bool accept(int64_t pts,int64_t transportInterval,bool boundary){+ if(boundary||!anchored_||pts<last_||pts-last_>transportInterval*6){+ anchored_=true;next_=pts+transportInterval*2;last_=pts;return true;+ }+ last_=pts;+ if(pts+transportInterval/4<next_)return false;+ const auto period=transportInterval*2;+ next_+=((pts+transportInterval/4-next_)/period+1)*period;+ return true;+ }+private:+ bool anchored_=false;int64_t next_=0,last_=0;+};+}diff --git a/include/veyra/engine/ContentCadence.h b/include/veyra/engine/ContentCadence.hindex 0ed616dd..0f78c8ac 100644--- a/include/veyra/engine/ContentCadence.h+++ b/include/veyra/engine/ContentCadence.h@@ -22,7 +22,7 @@ public:const int requested=mode==ContentRate::Fps30?30:mode==ContentRate::Fps50?50:mode==ContentRate::Fps60?60:0;return mode==ContentRate::Transport?0:requested?(rate_==requested?rate_:0):rate_;}- bool conflicts(ContentRate mode)const{return rate_!=0&&mode>=ContentRate::Fps30&&confirmedRate(mode)==0;}+ bool conflicts(ContentRate mode)const{return rate_!=0&&mode>=ContentRate::Fps30&&mode<=ContentRate::Fps60&&confirmedRate(mode)==0;}private:std::deque<int> changes_;std::deque<double>deltas_;double last_=-1;int rate_=0;};}diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 7502b8c1..697c4e2c 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -9,10 +9,12 @@#include "veyra/engine/EnhancementSettings.h"#include "veyra/diagnostics/FrameMetrics.h"#include "veyra/engine/PreviewView.h"+#include "veyra/engine/FrameRateWindow.h"namespace veyra::sink { struct RgbaImage; }namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }namespace veyra::engine {struct PlayerOptions { bool nr=true,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;+ bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UIEnhancementSettings 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;}};@@ -28,6 +30,8 @@ struct PlayerSnapshot {uint32_t flowPerf=0;int contentFps=0;uint64_t frames=0,generated=0;uint64_t captureReceived=0,captureDropped=0,nrEvaluated=0,nvofExecuted=0;+ uint64_t captureRateSkipped=0,processedCompleted=0;+ bool captureHalfRate=false;double captureFps=0,captureReadAgeMs=0,captureAgeMs=0,captureAgeP95Ms=0;double schedulingWaitP95Ms=0,processCpuP95Ms=0,presentCpuP95Ms=0;bool running=false,failed=false,image=false,capture=false;@@ -57,6 +61,7 @@ private:void status(const std::wstring&,bool failed=false);mutable std::mutex mutex_;PlayerSnapshot snapshot_;+ FrameRateWindow processingRate_;PreviewView previewView_;std::wstring savePath_;std::thread worker_;diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex a8c8b59c..e46bdcb6 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -7,7 +7,7 @@namespace veyra::engine {enum class FrameGenerationBackend { Dlss, Fruc };enum class FlowQuality { Performance, Balanced, Quality };-enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60 };+enum class ContentRate { Transport, Auto, Fps30, Fps50, Fps60, Capture60To30 };struct NrSettings {float intensity=1,tone=1,structure=1,skin=-1;int32_t style=0,autoMask=0,uiCorrection=0;@@ -59,7 +59,7 @@ struct EnhancementSettings {if(videoSrQuality>4)return "invalid video SR quality";if(multiplier<1||multiplier>4)return "unsupported multiplier";if(nrPolicy!=pipeline::NrSizePolicy::Realtime&&nrPolicy!=pipeline::NrSizePolicy::Native)return "invalid NR size policy";- if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Fps60)return "invalid flow/content mode";+ if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Capture60To30)return "invalid flow/content mode";return {};}};diff --git a/include/veyra/engine/FrameRateWindow.h b/include/veyra/engine/FrameRateWindow.hnew file mode 100644index 00000000..39a6d2d1--- /dev/null+++ b/include/veyra/engine/FrameRateWindow.h@@ -0,0 +1,26 @@+#pragma once+#include <algorithm>+#include <cstdint>+#include <deque>+namespace veyra::engine {+// Completion events, not source arrivals or generated-frame multipliers.+// Call under the owning controller's mutex. All times use monotonic 100 ns.+class FrameRateWindow {+public:+ void reset(int64_t now){start_=now;times_.clear();}+ void complete(int64_t now){+ times_.push_back(now);+ while(times_.size()>8192||(!times_.empty()&×_.front()<=now-window))times_.pop_front();+ }+ double rate(int64_t now)const{+ const auto elapsed=(std::min)(window,(std::max<int64_t>)(0,now-start_));+ if(elapsed<1000000)return 0;+ const auto first=std::upper_bound(times_.begin(),times_.end(),now-window);+ return double(times_.end()-first)*10000000.0/double(elapsed);+ }+private:+ static constexpr int64_t window=10000000;+ int64_t start_=0;+ std::deque<int64_t> times_;+};+}diff --git a/include/veyra/engine/LivePresentationResetPolicy.h b/include/veyra/engine/LivePresentationResetPolicy.hnew file mode 100644index 00000000..cfac3ed6--- /dev/null+++ b/include/veyra/engine/LivePresentationResetPolicy.h@@ -0,0 +1,21 @@+#pragma once++#include "veyra/pipeline/FramePacket.h"+#include <cstdint>++namespace veyra::engine {++// A capture mailbox overwrite breaks temporal processing history, but it does+// not invalidate already-produced real frames. Keep those real frames eligible+// for presentation while suppressing generated frames from the prior epoch.+constexpr bool presentationDrainRequired(bool explicitReset, pipeline::FrameFlags flags) {+ return explicitReset+ || pipeline::hasFrameFlag(flags, pipeline::FrameFlagBits::Resize)+ || pipeline::hasFrameFlag(flags, pipeline::FrameFlagBits::DeviceLost);+}++constexpr bool generatedPresentationCurrent(uint64_t jobGeneration, uint64_t currentGeneration) {+ return jobGeneration == currentGeneration;+}++} // namespace veyra::enginediff --git a/include/veyra/engine/PresentationWorker.h b/include/veyra/engine/PresentationWorker.hnew file mode 100644index 00000000..de5ebd49--- /dev/null+++ b/include/veyra/engine/PresentationWorker.h@@ -0,0 +1,46 @@+#pragma once+#include <atomic>+#include <chrono>+#include <condition_variable>+#include <deque>+#include <functional>+#include <mutex>+#include <string>+#include <thread>+namespace veyra::engine {+// Two leased batches including the active batch. Sleeping for presentation+// deadlines must not stop the source/graph thread from submitting the next one.+class PresentationWorker {+public:+ using Cancelled=std::function<bool()>;+ using Job=std::function<bool(const Cancelled&)>;+ explicit PresentationWorker(Cancelled interrupt):interrupt_(std::move(interrupt)),thread_([this]{run();}){}+ ~PresentationWorker(){stopping_=true;++epoch_;wake_.notify_all();if(thread_.joinable())thread_.join();}+ PresentationWorker(const PresentationWorker&)=delete;+ bool waitForSlot(){+ std::unique_lock lock(mutex_);+ while(queue_.size()+unsigned(active_)>=2&&!failed_&&!stopping_&&!interrupt_())wake_.wait_for(lock,std::chrono::milliseconds(1));+ return !failed_&&!stopping_&&!interrupt_();+ }+ bool push(Job job){std::lock_guard lock(mutex_);if(failed_||stopping_||queue_.size()+unsigned(active_)>=2)return false;queue_.push_back({epoch_.load(),std::move(job)});wake_.notify_all();return true;}+ void cancelAndDrain(){+ ++epoch_;std::unique_lock lock(mutex_);queue_.clear();wake_.notify_all();wake_.wait(lock,[&]{return !active_;});+ }+ bool failed()const{std::lock_guard lock(mutex_);return failed_;}+private:+ struct Entry{uint64_t epoch;Job job;};+ Cancelled interrupt_;mutable std::mutex mutex_;std::condition_variable wake_;std::deque<Entry> queue_;+ bool active_=false,failed_=false;std::atomic<bool> stopping_{false};std::atomic<uint64_t> epoch_{0};std::thread thread_;+ void run(){+ for(;;){Entry entry;{+ std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return stopping_||!queue_.empty();});if(stopping_)break;+ entry=std::move(queue_.front());queue_.pop_front();active_=true;+ }+ bool ok=true;try{ok=entry.job([&,generation=entry.epoch]{return stopping_||epoch_!=generation||interrupt_();});}catch(...){ok=false;}+ // Drop captured FrameOutputs/leases before advertising a reusable slot.+ entry.job={};{+ std::lock_guard lock(mutex_);active_=false;if(!ok){failed_=true;queue_.clear();}wake_.notify_all();+ }}+ }+};+}diff --git a/include/veyra/engine/TimingWindow.h b/include/veyra/engine/TimingWindow.hnew file mode 100644index 00000000..e8e7fe13--- /dev/null+++ b/include/veyra/engine/TimingWindow.h@@ -0,0 +1,22 @@+#pragma once+#include <algorithm>+#include <chrono>+#include <cmath>+#include <deque>+#include <vector>+namespace veyra::engine {+class TimingWindow {+ std::deque<double> values_;+ mutable double cached_=0;+ mutable std::chrono::steady_clock::time_point refresh_{};+public:+ void add(double v){if(!std::isfinite(v)||v<0)return;values_.push_back(v);if(values_.size()>1200)values_.pop_front();}+ void clear(){values_.clear();cached_=0;refresh_={};}+ double p95()const{+ if(values_.empty())return 0;const auto now=std::chrono::steady_clock::now();+ if(now<refresh_)return cached_;+ std::vector<double> sorted(values_.begin(),values_.end());const size_t i=(sorted.size()-1)*95/100;+ std::nth_element(sorted.begin(),sorted.begin()+i,sorted.end());cached_=sorted[i];refresh_=now+std::chrono::milliseconds(250);return cached_;+ }+};+}diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.hindex 4bf669f0..f911435e 100644--- a/include/veyra/engine/VideoPresenter.h+++ b/include/veyra/engine/VideoPresenter.h@@ -11,12 +11,12 @@ namespace veyra::engine {class VideoPresenter {public:bool open(gfx::D3D12DeviceContext&, HWND, pipeline::EnhanceGraph&);- bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});+ bool present(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,unsigned slot,bool generated,bool referencesValid=true,int comparison=0,bool baseReference=false,float split=.5f,pipeline::FrameIdentity identity={},PreviewView view={});void close();// Explicit integration-test capture only; never called by playback/export.bool readPresentedFrameForTest(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,sink::RgbaImage&);uint64_t submittedCount() const {return sink_.presentCount();}-diagnostics::GpuSample blitTiming(ID3D12Fence* f){gpuTimer_.collect(f);return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}+diagnostics::GpuSample blitTiming(ID3D12Fence* f,uint64_t revision=0){gpuTimer_.collect(f);if(revision&&gpuTimer_.last().identity.settingsRevision!=revision){diagnostics::GpuSample pending;pending.state=diagnostics::SampleState::Pending;return pending;}return gpuTimer_.last().gpu[size_t(diagnostics::GpuStage::Blit)];}private:diagnostics::GpuTimer gpuTimer_;gfx::PresentSink sink_;diff --git a/include/veyra/gfx/CommandSlotRing.h b/include/veyra/gfx/CommandSlotRing.hindex abcd4107..99eb2d98 100644--- a/include/veyra/gfx/CommandSlotRing.h+++ b/include/veyra/gfx/CommandSlotRing.h@@ -82,6 +82,8 @@ public:// Query heap for D3D12_QUERY_TYPE_TIMESTAMP entries (two per slot).ID3D12QueryHeap* timestampHeap() const { return timestampHeap_.Get(); }uint64_t cpuWaitCount() const { return cpuWaitCount_; }+ double cpuWaitMilliseconds() const { return cpuWaitMilliseconds_; }+ uint64_t submitCount() const { return submitCount_; }const std::vector<double>& gpuCommandTimesMs() const { return gpuCommandTimesMs_; }private:@@ -104,7 +106,8 @@ private:ComPtr<ID3D12QueryHeap> timestampHeap_;std::vector<Slot> slots_;ComPtr<ID3D12Resource> timingReadback_;- uint64_t timestampFrequency_ = 0, cpuWaitCount_ = 0;+ uint64_t timestampFrequency_ = 0, cpuWaitCount_ = 0, submitCount_ = 0;+ double cpuWaitMilliseconds_ = 0;std::vector<double> gpuCommandTimesMs_;};diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.hindex 4a83da5b..1e43c71d 100644--- a/include/veyra/pipeline/ColorMetadata.h+++ b/include/veyra/pipeline/ColorMetadata.h@@ -36,9 +36,11 @@ inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescriptioncase AVCOL_TRC_BT2020_10:case AVCOL_TRC_BT2020_12:c.transfer=TransferFunction::BT2020_10;c.transferAssumed=false;break;default:break;}- if(c.range==ColorRange::Unknown||c.rangeAssumed){c.range=(rgb||frame.format==AV_PIX_FMT_YUVJ420P||frame.format==AV_PIX_FMT_YUVJ422P||frame.format==AV_PIX_FMT_YUVJ444P)?ColorRange::Full:ColorRange::Limited;c.rangeAssumed=true;}- if(c.matrix==YuvMatrix::Unknown||c.matrixAssumed){c.matrix=rgb||frame.height>=700?YuvMatrix::BT709:YuvMatrix::BT601;c.matrixAssumed=true;}- if(c.transfer==TransferFunction::Unknown||c.transferAssumed){c.transfer=rgb?TransferFunction::SRGB:TransferFunction::BT709;c.transferAssumed=true;}+ // A source's documented fallback is still a resolved contract. Preserve+ // it (and its provenance) unless the frame supplies explicit metadata.+ if(c.range==ColorRange::Unknown){c.range=(rgb||frame.format==AV_PIX_FMT_YUVJ420P||frame.format==AV_PIX_FMT_YUVJ422P||frame.format==AV_PIX_FMT_YUVJ444P)?ColorRange::Full:ColorRange::Limited;c.rangeAssumed=true;}+ if(c.matrix==YuvMatrix::Unknown){c.matrix=rgb||frame.height>=700?YuvMatrix::BT709:YuvMatrix::BT601;c.matrixAssumed=true;}+ if(c.transfer==TransferFunction::Unknown){c.transfer=rgb?TransferFunction::SRGB:TransferFunction::BT709;c.transferAssumed=true;}return c;}inline uint32_t transferCode(TransferFunction t){return t==TransferFunction::Linear?0u:t==TransferFunction::BT709?2u:1u;}diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.hindex ece84f90..7ef92252 100644--- a/include/veyra/pipeline/EnhanceGraph.h+++ b/include/veyra/pipeline/EnhanceGraph.h@@ -66,8 +66,10 @@ struct EnhanceGraphDesc {bool noFeatures = false; // VEYRA_NO_FEATURES: NVOF/NGX objects skippedbool noNgx = false; // VEYRA_NO_NGX: core/features skipped, NVOF onlybool rgbInput = false; // allocate direct RGBA ingestion before NGX creation+ bool yuy2Input = false; // packed Y0 U Y1 V -> linear FP16; never subsample to NV12bool stillImage = false; // no temporal motion/FG history for a single imageuint32_t nrWidth=0,nrHeight=0; // zero preserves legacy native working extent+ uint32_t flowWidth=0,flowHeight=0; // zero preserves legacy source-space NVOF extentuint32_t fgMultiplier=2;engine::FrameGenerationBackend frameGenerationBackend=engine::FrameGenerationBackend::Dlss;uint64_t settingsRevision=1;@@ -121,7 +123,7 @@ public:// does not own the demuxer). `reset` marks the first frame of a new// temporal epoch (open/seek/...): NVOF/FG history is not consumed.// Returns false on hard failure (run verdict must FAIL).- bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr);+ bool process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId = 0, const ColorDescription* color = nullptr, bool retainReferences = true);// Nonblocking. The scheduler polls at a GPU-ready/deadline boundary; no// full image readback and no waits inside the graph's individual passes.bool resolveGeneration(FrameOutputs& out);@@ -152,6 +154,8 @@ public:uint32_t workHeight() const { return workH_; }uint32_t nrWidth() const {return nrW_;}uint32_t nrHeight() const {return nrH_;}+ uint32_t flowWidth() const {return nvofW_;}+ uint32_t flowHeight() const {return nvofH_;}uint32_t actualFlowPerf() const;diagnostics::FrameMetrics gpuMetrics(){gpuTimer_.collect(contextFence());return gpuTimer_.last();}ID3D12Fence* contextFence() const;diff --git a/include/veyra/pipeline/FrameBatch.h b/include/veyra/pipeline/FrameBatch.hindex f78f8520..09c221e0 100644--- a/include/veyra/pipeline/FrameBatch.h+++ b/include/veyra/pipeline/FrameBatch.h@@ -18,6 +18,7 @@ struct FrameLease {Microsoft::WRL::ComPtr<ID3D12Resource> texture,sourceReference,baseReference;uint64_t readyFence=0,consumerFence=0;uint32_t slot=0;+ bool referencesValid=false;};struct BatchFrame {FrameIdentity identity;diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.hindex bbe2e3cd..57d3cf01 100644--- a/include/veyra/pipeline/FramePacket.h+++ b/include/veyra/pipeline/FramePacket.h@@ -155,6 +155,7 @@ struct FramePacket {FrameFlags flags = 0;ColorDescription colorInfo;uint64_t sourceEpoch = 1; // ResetCoordinator epoch at frame boundary+ int64_t arrivalHost100ns = 0; // capture callback steady_clock; 0 when unavailableGpuTextureHandle color; // canonical linear RGBA16F working texturediff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.hindex 13b40595..75eacaf0 100644--- a/include/veyra/pipeline/ResolutionPlan.h+++ b/include/veyra/pipeline/ResolutionPlan.h@@ -23,7 +23,13 @@ struct ResolutionPlan {const double scale=std::min({1.0,1920.0/p.base.width,1080.0/p.base.height});if(scale<1.0)p.nr={std::max(1u,std::min(p.base.width,uint32_t(p.base.width*scale)&~1u)),std::max(1u,std::min(p.base.height,uint32_t(p.base.height*scale)&~1u))};}- p.flow=source;p.fg=p.output=p.base;p.settingsRevision=revision;return p;+ p.flow=source;+ // NVOF reads source-space color. In the explicitly labelled realtime+ // path it must not silently remain at native 4K after NR was reduced.+ // Inputs smaller than the realtime NR extent stay at their native size.+ if(!exporting&&policy==NrSizePolicy::Realtime&&+ (p.nr.width<p.source.width||p.nr.height<p.source.height))p.flow=p.nr;+ p.fg=p.output=p.base;p.settingsRevision=revision;return p;}};}diff --git a/include/veyra/source/CaptureMediaType.h b/include/veyra/source/CaptureMediaType.hnew file mode 100644index 00000000..db73a99a--- /dev/null+++ b/include/veyra/source/CaptureMediaType.h@@ -0,0 +1,81 @@+#pragma once+#include "veyra/pipeline/ColorMetadata.h"+#include <windows.h>+#include <dshow.h>+#include <dvdmedia.h>+#include <d3d9.h>+#include <dxva2api.h>+#include <cstring>+#include <limits>+#include <cmath>++namespace veyra::source {+struct CaptureMediaLayout {+ unsigned width=0,height=0,stride=0,rowBytes=0;+ size_t sampleBytes=0;+ bool bottomUp=false;+ AVPixelFormat format=AV_PIX_FMT_NONE;+ REFERENCE_TIME duration=0;+ pipeline::ColorDescription color;+};+// Parse negotiated memory layout, not the UI's requested dimensions. YUV is+// top-down for either sign of biHeight; only RGB DIBs use bottom-up storage.+inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out){+ out={};if(type.majortype!=MEDIATYPE_Video||!type.pbFormat)return false;+ BITMAPINFOHEADER bm{};DWORD flags=0;+ if(type.formattype==FORMAT_VideoInfo&&type.cbFormat>=sizeof(VIDEOINFOHEADER)){+ const auto& v=*reinterpret_cast<const VIDEOINFOHEADER*>(type.pbFormat);bm=v.bmiHeader;out.duration=v.AvgTimePerFrame;+ }else if(type.formattype==FORMAT_VideoInfo2&&type.cbFormat>=sizeof(VIDEOINFOHEADER2)){+ const auto& v=*reinterpret_cast<const VIDEOINFOHEADER2*>(type.pbFormat);bm=v.bmiHeader;out.duration=v.AvgTimePerFrame;flags=v.dwControlFlags;+ }else return false;+ const auto height=std::abs(int64_t(bm.biHeight));+ if(bm.biWidth<=0||bm.biWidth>3840||height<1||height>2160)return false;+ out.width=unsigned(bm.biWidth);out.height=unsigned(height);+ if(type.subtype==MEDIASUBTYPE_YUY2){if(out.width%2)return false;out.format=AV_PIX_FMT_YUYV422;out.rowBytes=out.width*2;}+ else if(type.subtype==MEDIASUBTYPE_NV12){if(out.width%2||out.height%2)return false;out.format=AV_PIX_FMT_NV12;out.rowBytes=out.width;}+ else if(type.subtype==MEDIASUBTYPE_RGB32){out.format=AV_PIX_FMT_BGR0;out.rowBytes=out.width*4;out.bottomUp=bm.biHeight>0;}+ else return false;+ const unsigned rows=out.format==AV_PIX_FMT_NV12?out.height*3/2:out.height;+ out.stride=out.rowBytes;+ if(bm.biSizeImage){+ // Fixed uncompressed allocation may include per-row padding. Reject+ // ambiguous/incomplete layouts instead of reading subsequent rows wrong.+ if(bm.biSizeImage%rows||bm.biSizeImage/rows<out.rowBytes)return false;+ out.stride=bm.biSizeImage/rows;+ }+ out.sampleBytes=size_t(out.stride)*rows;+ if(out.sampleBytes>size_t(std::numeric_limits<LONG>::max()))return false;+ AVFrame frame{};frame.format=out.format;frame.width=int(out.width);frame.height=int(out.height);+ out.color=pipeline::resolveFrameColor(frame);+ // SDR capture is already display-referred R'G'B' after the YUV matrix.+ // Preserve those code values through the sRGB working round trip, like+ // the old RGB ingress, instead of applying a camera OETF a second time.+ out.color.transfer=pipeline::TransferFunction::SRGB;out.color.transferAssumed=true;+ if(flags&AMCONTROL_COLORINFO_PRESENT){+ DXVA2_ExtendedFormat ext{};ext.value=flags;+ if(ext.NominalRange==DXVA2_NominalRange_0_255){out.color.range=pipeline::ColorRange::Full;out.color.rangeAssumed=false;}+ else if(ext.NominalRange==DXVA2_NominalRange_16_235){out.color.range=pipeline::ColorRange::Limited;out.color.rangeAssumed=false;}+ else if(ext.NominalRange!=DXVA2_NominalRange_Unknown)return false;+ if(ext.VideoTransferMatrix==DXVA2_VideoTransferMatrix_BT601){out.color.matrix=pipeline::YuvMatrix::BT601;out.color.matrixAssumed=false;}+ else if(ext.VideoTransferMatrix==DXVA2_VideoTransferMatrix_BT709){out.color.matrix=pipeline::YuvMatrix::BT709;out.color.matrixAssumed=false;}+ else if(ext.VideoTransferMatrix!=DXVA2_VideoTransferMatrix_Unknown)return false;+ if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_10){out.color.transfer=pipeline::TransferFunction::Linear;out.color.transferAssumed=false;}+ else if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_sRGB){out.color.transferAssumed=false;}+ else if(ext.VideoTransferFunction!=DXVA2_VideoTransFunc_Unknown&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_709&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_22)return false;+ }+ return true;+}+inline bool copyCaptureSample(const CaptureMediaLayout& layout,const uint8_t* src,size_t bytes,AVFrame& dst){+ if(!src||bytes<layout.sampleBytes||dst.format!=layout.format||dst.width!=int(layout.width)||dst.height!=int(layout.height)||!dst.data[0]||dst.linesize[0]<int(layout.rowBytes))return false;+ if(layout.format==AV_PIX_FMT_NV12&&(!dst.data[1]||dst.linesize[1]<int(layout.width)))return false;+ for(unsigned y=0;y<layout.height;++y)std::memcpy(dst.data[0]+ptrdiff_t(y)*dst.linesize[0],src+size_t(layout.bottomUp?layout.height-1-y:y)*layout.stride,layout.rowBytes);+ if(layout.format==AV_PIX_FMT_NV12)for(unsigned y=0;y<layout.height/2;++y)std::memcpy(dst.data[1]+ptrdiff_t(y)*dst.linesize[1],src+size_t(layout.height+y)*layout.stride,layout.width);+ return true;+}+inline bool equivalentCaptureTypes(const AM_MEDIA_TYPE& a,const AM_MEDIA_TYPE& b){+ CaptureMediaLayout x,y;if(!captureMediaLayout(a,x)||!captureMediaLayout(b,y))return false;+ return x.format==y.format&&x.width==y.width&&x.height==y.height&&x.stride==y.stride&&x.bottomUp==y.bottomUp&&x.duration==y.duration&&+ x.color.range==y.color.range&&x.color.matrix==y.color.matrix&&x.color.transfer==y.color.transfer&&+ x.color.rangeAssumed==y.color.rangeAssumed&&x.color.matrixAssumed==y.color.matrixAssumed&&x.color.transferAssumed==y.color.transferAssumed;+}+}diff --git a/include/veyra/source/CaptureTiming.h b/include/veyra/source/CaptureTiming.hindex c66f0724..2a994992 100644--- a/include/veyra/source/CaptureTiming.h+++ b/include/veyra/source/CaptureTiming.h@@ -2,6 +2,12 @@#include "veyra/pipeline/FramePacket.h"#include <limits>namespace veyra::source {+inline bool captureDiscontinuity(bool pending,bool retained,bool driver,bool havePrevious,+ double previous,double current,double nominalFps){+ const double maxGap=nominalFps>0?2.5/nominalFps:0.1;+ return (pending&&retained)||driver||+ (havePrevious&&(current<=previous||current-previous>maxGap));+}inline pipeline::Rational captureDuration(int64_t start,int64_t end,bool completeSampleTime,int64_t nominal100ns){if(completeSampleTime&&end>start){const auto delta=uint64_t(end)-uint64_t(start);diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.hindex a1d1d569..b9b40e9d 100644--- a/include/veyra/source/IFrameSource.h+++ b/include/veyra/source/IFrameSource.h@@ -20,6 +20,7 @@ struct SourceOpenDesc {bool preferHardwareDecode = true; // D3D12VA first, software fallback explicitvoid* d3d12Device = nullptr; // ID3D12Device* when hardware decode is wantedvoid* d3d12Queue = nullptr; // ID3D12CommandQueue*+ bool legacyCaptureRgbForDiagnostic = false; // explicit A/B only; never set by the player};struct SourceInfo {diff --git a/include/veyra/source/NativeCaptureSink.h b/include/veyra/source/NativeCaptureSink.hnew file mode 100644index 00000000..dde2ff2b--- /dev/null+++ b/include/veyra/source/NativeCaptureSink.h@@ -0,0 +1,10 @@+#pragma once+#include <windows.h>+#include <dshow.h>+#include <wrl/client.h>+#include <functional>+namespace veyra::source {+// Native terminal filter: no legacy SampleGrabber orientation/VideoInfo2+// restriction, conversion filter or extra queue. Callback borrows the sample.+HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE&,std::function<HRESULT(IMediaSample*)>,Microsoft::WRL::ComPtr<IBaseFilter>&,Microsoft::WRL::ComPtr<IPin>&);+}diff --git a/loop/EVIDENCE.md b/loop/EVIDENCE.mdindex 4b0f125f..da61ced0 100644--- a/loop/EVIDENCE.md+++ b/loop/EVIDENCE.md@@ -1,5 +1,9 @@# Veyra Gate Evidence+## 2026-09-10 FPS / capture60-to30++Release build exit0; CPU41, worker11, preset roundtrip PASS; actual RTX engine replay half-rate19 PASS with ~30 completed FPS and return to ~60. UI daily/professional/small visible bounded live FPS and pause-zero PASS. Original delivery23 PASS45.317s: `logs/delivery/910fe667d2574babaa3b02a7aa9bb3e2/result.json`. Full commands, hash and failure records: `docs/HANDOFF_2026-09-10.md`. No new physical capture or independent Reviewer verdict. Phase7 remains in_progress; known FRUC reset pixels unresolved; no claim of scanout FPS or end-to-end latency. Runtime hash/signature unchanged, local Git only.+## 2026-09-08 optimization Goal startup — preflight FAILExecuted `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`: exit1, 2.604 seconds, sole failure control:README.md. Other controls and both binary identities passed. README matches user-authorized f79ef95; manifest expects earlier README. Full output is in the task tool record; logs/optimization-goal-20260908/control-rebaseline-proposal.json is explicitly an observation/proposal, not fabricated gate output. Proposal is unexecuted; see cycle49/INBOX. No product build/Create/Evaluate this cycle; previous Phase7 records do not approve the new Goal's changes.@@ -596,3 +600,41 @@ Cycle86 safety stop: build passed (logs/video-sdk-trial-20260909/build-cycle86.lEXE SHA256: `3BD470D51AD43F7C461F23AB6F9F9B7234DC6F33D84C9DDEB35A463663264E2C`。构建日志 `logs/video-sdk-trial-20260909/build-cycle86.log`;独立review前后跟踪指纹 `9d45fe7ff6b19a67b3a42db2215928b1aecf5b4f`不变,之后仅更新交接记录。单次测试均不足300秒。Cycle86修复可交本机实测;整体Phase7优化仍in_progress,既有统计窗口/间歇时序/实卡体验/长期稳定风险未宣称消失。下一任务见HANDOFF优先处理配置相关统计窗口。本地Git checkpoint包括Cycles78–86已核对源码、使用指南、交接报告与授权的GOAL_PROMPT删除;不包含runtime/SDK/个人媒体,不push。实际提交ID以本次 `git log -1` 为准,避免在commit内容中制造自指hash。+++## Cycle87–88 FRUC/high-FPS candidate++User requested1000fps support andFRUC2/3/4. Source timing admission120→1000, exact timestamp validation retained. OptionalFRUC behind sharedgraph, UI/preset/export propagated, DLSS retained. Same-process multiinstance required per-instanceCUDAcontext; destroy/recreate repeatedlyRegister4/warpSEH, so stopped that approach and isolated runtime in hidden ownedworker with GPUsharedtextures/fence. No normal pixelreadback. Fullreset freshworker is correct in triple-reset tests but has startupcost/capture-drop feedbackrisk. Maker pixel/PTS2/3/4PASS; playbackknownpan有效5/10/15子帧与实际播放计数、NVENC24/36/48frame输出、1000fps2000frames/999.34processedfps及UI切换PASS. Specificcommands/logs/failures in docs/FRUC_INTEGRATION_2026-09-09.md. 最终lazy创建候选等待独立review/preflight/phase7;整体Phase7未完成,不push。+++## 独立检查与用户反馈补充++独立review_fruc已报告CPU16+27项/preset、实际2/3/4pixel/PTS/连续reset、UI全后端切换和自有worker进程故障测试通过,无新增已确认P0/P1/P2消息。preflight69 PASS;其实际phase7日志 `logs/video-sdk-trial-20260909/review-fruc-gate-phase7.log` 为73 PASS,delivery `logs/delivery/1c195ef6d3684879b220fc8c13439e83/result.json`。Reviewer随后额度耗尽,未返回最终整体结论;因此记录为independent_checks_passed / final_verdict_unavailable,不伪造最终Reviewer PASS。用户随后明确“我已经测试没问题”,记录用户本次体验通过,不外推其未说明的配置与长期稳定性。程序SHA256 BD76BA1F3D66DF30286E450AD1742E773F48989B5815C175BDC0A297ABF4E94D;workerSHA256 B6F267C3B1C73DE0CB99C4BAD4B5DA9355C42DF7E7F37F21C9891B02B80412A3。+++## 用户新请求:GitHub性能归因++已固定7个仓库head,只读源码/官方文档+既有GPU日志;报告docs/GITHUB_PERFORMANCE_AUDIT_2026-09-09.md。确认原生4KNR硬预算与软件同步/日志/重置/统计问题并存,不提供未测占比。未运行竞品、未改runtime/产品代码、未占实卡。下一条任务:配置revision隔离统计,再同源逐项A/B定位等待与计算;不先建议换卡。++## 2026-09-09 竞品对照改进方案(仅文档)++用户暂停间歇卡顿现场追查,要求先对照已有竞品写改进方案。新增 docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md,按固定 GitHub 审计、当前 controller/FRUC 源码、旧质量方案及已完成专项整理。先统计/日志/有界调度与 reset,再做 CUDA FRUC、硬解和拷贝消减实验;深度/缓存不加入默认路径。明确每项证据、动作、验收与回退,保留导出完整性检查和单次 300 秒约定。最新自然日志未包含用户所述卡顿的处理证据,不给周期性卡顿下确定归因。同步 HANDOFF 索引和 STATE 文档条目,未改产品代码/依赖/默认设置或保护门禁。未运行新的构建/GPU/实卡测试,未推进 Phase 7 或补造 Reviewer 结论。+## 2026-09-09 基础画质审计 — 已执行范围++新交接 docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md;本地证据 logs/obs-magpie-rootcause-20260909/audit-manifest.json。真实 GPU 合成 RGB/BGR0 无增强旁路:python logs/obs-magpie-rootcause-20260909/build_probe.py,最终 build/run exit 0,两项 maxError8=0;只覆盖已编译共享图,不包含实卡转换与 VideoPresenter/DWM。未新执行 NR/SR/FG、同条件竞品性能、delivery 或独立 Reviewer。原生 YUY2 强制转 RGB32 的元数据缺口和显示缩放为优先排查方向;色带根因未闭环,产品未修。++Magpie 本地日志显示多数 1440p 处理,不能由 GPU60% 推断同4K速度。用户授权必要兼容 OSS 模块复用,归因/许可证和运行时分离保持。远端 v0.0.1 已公开经 gh 查询确认,本轮未变更。Phase7 仍 in_progress;下一条 R1 同帧四段定位。++## 2026-09-09 原生 YUY2 与实时呈现修复交付++用户撤回实卡 A/B(“不用测试这个,可以确定就是YUY2的转换”),本轮未打开采集设备。实际实现见 docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md:原生 YUY2/NV12 DirectShow 接收、一次 GPU YUY2→linearFP16、颜色元数据/stride/方向校正,同尺寸 blit/copy 消减、两个批次的异步采集呈现、revision 隔离统计与批量文件日志。保存/暂停/重配置/退出仍按 lease/fence 排空。不能说已同帧实测证明全部色带只有一个根因。++Release 构建 final-build4.log exit0;CPU契约26项、worker11项;YUY2 601/709×full/limited、原生4K及RGB范围 GPU 基准最大误差<=1/255,显示误差0。YUY2八帧NR含7次NVOF/7帧motion;实际Engine文件回放live worker的DLSS2X/4X/暂停恢复/设置/退出10项PASS,FRUC已知15fps平移素材同样10项PASS。没有占实卡。单项均外部timeout290秒。++delivery最终 logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json,23项PASS、42.569秒;NR/NVOF/GBV零错误、4K播放、4K图像、NVENC H264/HEVC音频和2X CFR、取消检查通过。第一次delivery所有功能检查通过但最后Get-FileHash模块未加载而exit1,保留2d62b4ad日志,仅包装导入平台Utility模块后重跑,未改原gate。早期编译头文件遗漏、temporal测试未开启NVOF配置的失败与修正也保留。++独立review_native_capture最终限定复核:所提动态格式/RGB范围/异步统计问题均关闭,审查范围无其他未修P0/P1/P2;它核对源码和真实日志,没有自行执行GPU或实卡,不记整体Phase7 PASS。++另发现旧路径迁移导致本机FRUC运行目录缺NvOFFRUC.dll及其直接依赖cudart64_110.dll。由已有本地SDK复制固定SHA/有效NVIDIA签名的两项到gitignored runtime_local,不修改文件内容。打包allowlist添加固定cudart依赖;仅语法检查,未执行打包或发布。实际FRUC平移回放通过;通用test_av素材返回repeated=true的失败保留,不当有效生成。已发布旧包未更新。++EXE SHA256: 61618AF18F7B985BD4C1FECA06EBE7A07C30EAA01B2CC0682A217E89EAD3C372。原版NR固定SHA一致。已有控制面漂移保留,不改AGENTS/README/CONTROL_HASHES、不声称preflight通过。整体Phase7仍in_progress;下一条任务是用户实测本机新YUY2路径,再按同尺寸同配置证据继续性能优化。FRUC互通/重建等待、GPU临界区、自然运动效果和长期稳定性仍有边界。未push、未重新发布Release。diff --git a/loop/JOURNAL.md b/loop/JOURNAL.mdindex 9b4caa41..95c0b4e5 100644--- a/loop/JOURNAL.md+++ b/loop/JOURNAL.md@@ -1,5 +1,9 @@# Veyra Loop Journal+## 2026-09-10 User-directed FPS / capture sampling checkpoint++Added GPU-completed one-second FPS, explicit PS5 30-in-60 sampling before GPU, UI and focused regressions. Original PTS, capacity-one ingress and two-batch worker retained; files/export never decimate. No Goal phase advancement or protected control edits. Initial Windows min compile failure and UI root-window test error corrected. CPU41/worker11/preset, RTX half-rate19, UI three layouts and original delivery23 PASS45.317s. Details: docs/HANDOFF_2026-09-10.md. User explains prior FPS changes as quality adjustments; no fixed-config failure inferred. No physical capture this turn. Local source/docs commit authorized; no remote publication.+## Cycle 49 — 2026-09-08 optimization Goal startup / control drift diagnosisUser started Goal for arbitrary media dimensions, professional preview wheel zoom, and the quality optimization plan; retain export integrity checks and 300-second per-test limit. Unique task: preflight / reconcile before product edits. Hypothesis: prior user-requested archive README no longer matches old control ledger. Expected edits: runtime state only until preflight passes. Actual command: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\loop-gate.ps1 -Gate preflight`; exit 1 in 2.604 seconds, sole failed check control:README.md. Other control files and both binary identities passed.@@ -1673,3 +1677,67 @@ Cycle86 resumed: user explicitly confirmed deletion and requested removal of itsEXE SHA256: `3BD470D51AD43F7C461F23AB6F9F9B7234DC6F33D84C9DDEB35A463663264E2C`。构建日志 `logs/video-sdk-trial-20260909/build-cycle86.log`;独立review前后跟踪指纹 `9d45fe7ff6b19a67b3a42db2215928b1aecf5b4f`不变,之后仅更新交接记录。单次测试均不足300秒。Cycle86修复可交本机实测;整体Phase7优化仍in_progress,既有统计窗口/间歇时序/实卡体验/长期稳定风险未宣称消失。下一任务见HANDOFF优先处理配置相关统计窗口。本地Git checkpoint包括Cycles78–86已核对源码、使用指南、交接报告与授权的GOAL_PROMPT删除;不包含runtime/SDK/个人媒体,不push。实际提交ID以本次 `git log -1` 为准,避免在commit内容中制造自指hash。+++## Cycle87–88 plan: user requested 1000fps admission and optional FRUC+Audit high-rate timing and remove120fps policy ceilings up to1000 without claiming physical1000fps. Add FRUC behind shared graph, GPU-only D3D12/D3D11 shared textures/fence, one independent FRUC stream per subframe (official API forbids duplicate input per instance). Keep DLSS selectable, resets/repeats honest. Validate build, high-rate timestamp tests, actual FRUC pixel/PTS and UI/backend switches; no export integrity weakening.+++## Cycle87–88 FRUC/high-FPS candidate++User requested1000fps support andFRUC2/3/4. Source timing admission120→1000, exact timestamp validation retained. OptionalFRUC behind sharedgraph, UI/preset/export propagated, DLSS retained. Same-process multiinstance required per-instanceCUDAcontext; destroy/recreate repeatedlyRegister4/warpSEH, so stopped that approach and isolated runtime in hidden ownedworker with GPUsharedtextures/fence. No normal pixelreadback. Fullreset freshworker is correct in triple-reset tests but has startupcost/capture-drop feedbackrisk. Maker pixel/PTS2/3/4PASS; playbackknownpan有效5/10/15子帧与实际播放计数、NVENC24/36/48frame输出、1000fps2000frames/999.34processedfps及UI切换PASS. Specificcommands/logs/failures in docs/FRUC_INTEGRATION_2026-09-09.md. 最终lazy创建候选等待独立review/preflight/phase7;整体Phase7未完成,不push。+++## 独立检查与用户反馈补充++独立review_fruc已报告CPU16+27项/preset、实际2/3/4pixel/PTS/连续reset、UI全后端切换和自有worker进程故障测试通过,无新增已确认P0/P1/P2消息。preflight69 PASS;其实际phase7日志 `logs/video-sdk-trial-20260909/review-fruc-gate-phase7.log` 为73 PASS,delivery `logs/delivery/1c195ef6d3684879b220fc8c13439e83/result.json`。Reviewer随后额度耗尽,未返回最终整体结论;因此记录为independent_checks_passed / final_verdict_unavailable,不伪造最终Reviewer PASS。用户随后明确“我已经测试没问题”,记录用户本次体验通过,不外推其未说明的配置与长期稳定性。程序SHA256 BD76BA1F3D66DF30286E450AD1742E773F48989B5815C175BDC0A297ABF4E94D;workerSHA256 B6F267C3B1C73DE0CB99C4BAD4B5DA9355C42DF7E7F37F21C9891B02B80412A3。+++## 用户新请求:GitHub性能归因++已固定7个仓库head,只读源码/官方文档+既有GPU日志;报告docs/GITHUB_PERFORMANCE_AUDIT_2026-09-09.md。确认原生4KNR硬预算与软件同步/日志/重置/统计问题并存,不提供未测占比。未运行竞品、未改runtime/产品代码、未占实卡。下一条任务:配置revision隔离统计,再同源逐项A/B定位等待与计算;不先建议换卡。++## 2026-09-09 竞品对照改进方案(仅文档)++用户暂停间歇卡顿现场追查,要求先对照已有竞品写改进方案。新增 docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md,按固定 GitHub 审计、当前 controller/FRUC 源码、旧质量方案及已完成专项整理。先统计/日志/有界调度与 reset,再做 CUDA FRUC、硬解和拷贝消减实验;深度/缓存不加入默认路径。明确每项证据、动作、验收与回退,保留导出完整性检查和单次 300 秒约定。最新自然日志未包含用户所述卡顿的处理证据,不给周期性卡顿下确定归因。同步 HANDOFF 索引和 STATE 文档条目,未改产品代码/依赖/默认设置或保护门禁。未运行新的构建/GPU/实卡测试,未推进 Phase 7 或补造 Reviewer 结论。+## 2026-09-09 基础画质审计交接++用户反馈 OBS 清晰度/色带及 Magpie 性能后,保存日志和固定上游源码,检查采集→共享图→显示及调度。运行现有产品库的最窄 GPU 无增强探针,最终两项 maxError8=0;未占用实卡、改生产代码或替换 runtime。第一版构建包装匹配参数失败后修正,失败与最终日志均据实记录。交付 docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md,同步 HANDOFF/STATE/EVIDENCE/WORKLOG,不修改保护控制面或发布远端。实卡失真第一节点仍待验证,不标 complete。++下一动作:R1 同帧原生/转换/GPU/显示诊断;其结果驱动 R2/R3。旧统计窗口优先级后移。兼容开源模块复用按用户最新授权及 GPL 来源记录执行,专有运行时仍隔离。单次测试最多300秒。++## 2026-09-09 R1/R2 基础画质修复开工++用户明确要求开始修复,并已准备静止实卡信号、授权测试。先构建诊断入口保存旧 RGB32 链路 raw/GPU/present 样本,然后加入原生 YUY2 有界采集与一次 GPU 颜色转换;对同源逐段比较、CPU/GPU契约和1080p/4K设备做短测。保留已有文档改动和控制面锁定值,不以历史 preflight 漂移自我放行。每个测试外部上限300秒。尚未修复或通过验收。++## 2026-09-09 原生 YUY2 与实时呈现修复交付++用户撤回实卡 A/B(“不用测试这个,可以确定就是YUY2的转换”),本轮未打开采集设备。实际实现见 docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md:原生 YUY2/NV12 DirectShow 接收、一次 GPU YUY2→linearFP16、颜色元数据/stride/方向校正,同尺寸 blit/copy 消减、两个批次的异步采集呈现、revision 隔离统计与批量文件日志。保存/暂停/重配置/退出仍按 lease/fence 排空。不能说已同帧实测证明全部色带只有一个根因。++Release 构建 final-build4.log exit0;CPU契约26项、worker11项;YUY2 601/709×full/limited、原生4K及RGB范围 GPU 基准最大误差<=1/255,显示误差0。YUY2八帧NR含7次NVOF/7帧motion;实际Engine文件回放live worker的DLSS2X/4X/暂停恢复/设置/退出10项PASS,FRUC已知15fps平移素材同样10项PASS。没有占实卡。单项均外部timeout290秒。++delivery最终 logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json,23项PASS、42.569秒;NR/NVOF/GBV零错误、4K播放、4K图像、NVENC H264/HEVC音频和2X CFR、取消检查通过。第一次delivery所有功能检查通过但最后Get-FileHash模块未加载而exit1,保留2d62b4ad日志,仅包装导入平台Utility模块后重跑,未改原gate。早期编译头文件遗漏、temporal测试未开启NVOF配置的失败与修正也保留。++独立review_native_capture最终限定复核:所提动态格式/RGB范围/异步统计问题均关闭,审查范围无其他未修P0/P1/P2;它核对源码和真实日志,没有自行执行GPU或实卡,不记整体Phase7 PASS。++另发现旧路径迁移导致本机FRUC运行目录缺NvOFFRUC.dll及其直接依赖cudart64_110.dll。由已有本地SDK复制固定SHA/有效NVIDIA签名的两项到gitignored runtime_local,不修改文件内容。打包allowlist添加固定cudart依赖;仅语法检查,未执行打包或发布。实际FRUC平移回放通过;通用test_av素材返回repeated=true的失败保留,不当有效生成。已发布旧包未更新。++EXE SHA256: 61618AF18F7B985BD4C1FECA06EBE7A07C30EAA01B2CC0682A217E89EAD3C372。原版NR固定SHA一致。已有控制面漂移保留,不改AGENTS/README/CONTROL_HASHES、不声称preflight通过。整体Phase7仍in_progress;下一条任务是用户实测本机新YUY2路径,再按同尺寸同配置证据继续性能优化。FRUC互通/重建等待、GPU临界区、自然运动效果和长期稳定性仍有边界。未push、未重新发布Release。++## 2026-09-09 原生 NR 性能反馈再排查++用户实测仍严重卡顿,授权读取最新日志继续排查。先只读保存 Magpie/Veyra 自然运行日志至 logs/native-nr-performance-20260909/,尚未重跑实卡/GPU。明确查到 Magpie 当前 NR1535x971→SR3840x2160→按最终显示FG2560x1440,与 Veyra post-SR 原生4KNR 不同;Veyra revision15 NR中位22.45ms。另有确实软件缺陷:运行中设置事务用旧cachedPacket建立新host锚点,引入额外相位延迟;FRUC drop触发每次新建worker约335ms且造成下一次drop。接下来最小修复缓存帧锚点和重复timer分配,评估SDK bSkipWarp用作明确不发布的重新播种,必须实际比较其后续像素再决定是否用于历史失效。保留NR真实4K模式与现有顺序,不擅自用降分辨率冒充原生,不改控制面,不占用户实卡。++## 2026-09-09 22:30 修复结果与停止试错++新帧设置/arrival/定时器/driver断点修复已构建并验证:CPU22、live DLSS12/FRUC12、delivery23 PASS45.671秒。FRUC恢复像素指纹连续尝试状态更新、冷重建恢复、相对时间与预热仍失败;停止该方向试错,撤下本轮FRUC生产候选,保存diff和全部失败日志。独立原实现`--reset-pixels`也失败,保留明确复现,不用既有短测放行FRUC质量。++用户纠正顺序可任意拖动且实测差异小。重新核对到先SR后NR2276x1440的Magpie片段;不以顺序解释全部性能差距,不推行未经确认的新路线。同尺寸Veyra1440p原生NR实测9.75ms,与Magpie同尺寸9.7–10.1ms接近。当前主问题仍须同负载完整管线等待/呈现诊断。详见docs/NATIVE_NR_PERFORMANCE_2026-09-09.md。无实卡占用、无远端或控制面修改;Phase7未完成。++## 2026-09-09 实时增强光流预算修复开工++用户再次确认 Magpie 的 SR/NR/FG 顺序可调,实际顺序变化对性能影响不大。本 cycle 不改效果顺序。已从现有源码确认:`ResolutionPlan` 的实时档只把 NR 降至 1080 级,`flow` 仍固定为 source;`EnhanceGraph` 同样把 NVOF 固定为原始输入尺寸,所以 4K 输入的实时 NR 仍执行完整 4K 光流。计划把实时档的 NVOF 内部尺寸明确限制到不超过 NR 内部尺寸,原生/导出保持 source 尺寸;使用既有 `FlowAdapt` 将 current-to-previous motion 换算到 NR 与 FG 工作尺寸,并修正状态栏和诊断尺寸。随后补契约测试、减少正常路径逐帧日志并运行每项小于 300 秒的 Release/RTX/delivery 验证。当前尚未修改产品代码,未占用实卡,未声称性能修复完成。++## 2026-09-09 性能开销消减与可观测性++用户确认 Magpie 可自由调整 SR/NR/FG 顺序且顺序变化对性能影响不大,因此本轮不再用调整顺序解释或掩盖性能差距。原子任务:对比关闭时停止每帧保留 source/base 参考纹理;正常运行默认关闭成功型逐帧格式化日志,仅由 `VEYRA_VERBOSE_FRAME_LOGS=1` 显式开启;为 `CommandSlotRing` 记录真实槽位复用等待次数/毫秒和提交数;把各 GPU stage、GPU ready、Present、显示提交与过期生成帧加入按 settings revision 隔离的每秒汇总。修改后运行 Release 构建、比较引用/实时呈现窄测、RTX 4K SR+实时 NR+FG 短测和 delivery,任何单次进程最多 300 秒。当前尚未宣称修复完成,不修改处理顺序、专有运行时或发布资产。diff --git a/loop/STATE.json b/loop/STATE.jsonindex 1b828b75..38fecb20 100644--- a/loop/STATE.json+++ b/loop/STATE.json@@ -1,5 +1,41 @@{"schemaVersion": 1,+ "captureFpsCheckpoint": {+ "report": "docs/HANDOFF_2026-09-10.md",+ "status": "implemented_software_verified_user_capture_pending",+ "changes": "One-second GPU-completed real FPS; explicit capture60to30 before graph; original PTS; no file/export decimation; prior native capture/performance changes documented.",+ "validation": "CPU41 worker11 preset PASS; RTX live half-rate19 PASS; UI3 layouts PASS; delivery23 PASS45.317s",+ "evidence": "logs/delivery/910fe667d2574babaa3b02a7aa9bb3e2/result.json",+ "next": "User PS5 fixed30 content over capture60 test, then matched-config pacing analysis. Prior natural FPS changes involved user quality adjustments, not proof of fixed-config FG fault.",+ "publication": "Local source/docs checkpoint only; no push, Runtime Pack or Release update. FRUC reset failure remains open."+ },+ "nativeNrPerformanceAudit": {+ "report": "docs/NATIVE_NR_PERFORMANCE_2026-09-09.md",+ "status": "capture_anchor_fixed_performance_and_fruc_unresolved",+ "userSteering": "Magpie supports arbitrary effect order; user sees little difference between orders. Do not infer order is the primary cause or silently change route.",+ "validation": "CPU22; DLSS/FRUC live replay12 each; delivery23 PASS45.671s; native1440 NR90/NVOF89 GPU median9.74784ms. No physical capture.",+ "failedEvidence": "logs/baseline-repair-20260909/nrperf-baseline-fruc-reset.log: original FRUC --reset-pixels exit1; candidate recovery changes withdrawn after failed pixels.",+ "exeHash": "8E1A694229257A66DA5F36DE439423632631B310E81258EA032C92CB5FFA159D"+ },+ "baselineQualityRepair": {+ "report": "docs/BASELINE_QUALITY_PERFORMANCE_REPAIR_2026-09-09.md",+ "status": "implemented_software_short_gate_passed_physical_comparison_not_run",+ "userSteering": "Skip physical YUY2 A/B per latest instruction; repair native conversion directly and retain offline validation.",+ "nextImplementation": "User verifies native YUY2 image; next performance changes require matched input/output and configuration timing evidence.",+ "evidence": "logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json",+ "validationScope": "CPU native sink26/worker11; RTX YUY2/RGB maxError<=1 with presentation0; native4K; NR8/NVOF7; DLSS and FRUC live replay10 each; delivery23 pass42.569s. Independent code/log review only; no physical capture.",+ "unresolved": "Physical driver connection/visual acceptance not run at user request; no matched Magpie performance proof; GPU critical section and FRUC reset/interop remain. Prior control hash drift retained.",+ "publicRelease": "Veyra-NRVideo v0.0.1 already public at 2026-09-09T11:00:36Z; no remote mutation this turn.",+ "implementationReport": "docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md"+ },+ "competitorImprovementPlan": {+ "supersededBy": "baselineQualityRepair: baseline color diagnosis precedes metrics optimization",+ "report": "docs/COMPETITOR_IMPROVEMENT_PLAN_2026-09-09.md",+ "status": "document_delivered_implementation_not_started",+ "userSteering": "Pause intermittent-stutter investigation; first write competitor-based improvement plan.",+ "nextImplementation": "P0-A: isolate metrics by applied settings revision; separate NR stage, valid generation and submission cadence.",+ "validationScope": "Documentation and existing evidence review only; no new build/GPU/capture execution."+ },"engineVersion": "veyra-loop-v1","objective": "User-started optimization Goal: remove arbitrary input dimension limits, professional preview wheel zoom, implement current verified quality repairs; retain export integrity checks; each test <=300 seconds.","status": "running",@@ -83,12 +119,13 @@"noProgressCycles": 0,"maximumNoProgressCycles": 5},- "currentTask": "Cycle86 live settings independently passed; local checkpoint and handoff ready",+ "currentTask": "Capture settings timeline repaired; native NR full-pipeline performance and FRUC reset pixel failure remain","lastGate": {- "name": "phase7",- "status": "passed",+ "name": "delivery",+ "status": "software_short_gate_passed","exitCode": 0,- "evidence": "logs/delivery/9f7468b334bc457db4b8bf125d4f5ddb/result.json; preflight69/phase773 PASS; Cycle86 independent scoped PASS"+ "evidence": "logs/delivery/d3b2dd62224a4df986941a8a4a1cb8a6/result.json",+ "note": "Unmodified software gate, system Utility import wrapper; not preflight or physical acceptance"},"lastFailureFingerprint": "","failureLedger": [@@ -102,16 +139,19 @@],"baselineCommit": "2086282478ae5d1e07e8162d47148633b59882fe","lastGoodCommit": "d681541a8fca77e3bfd5f496c8ee2dfe2d6a9031",- "openP0P1Findings": [],+ "openP0P1Findings": [+ "FRUC drop triggers repeated worker reconstruction ~335ms; candidate recovery withdrawn because reset pixel validation failed.",+ "Original FRUC returns some repeated/incorrect post-reset pixels with repeated=false; reproducible via --reset-pixels, not covered by existing delivery."+ ],"blockers": ["User real-card perceived latency/audio/FG display cadence and long stability acceptance pending; USB3Video1080p60 and4K18 short throughput measured.",- "Historical intermittent player-sync timing and mixed-configuration timing windows remain unresolved.",- "Public proprietary runtime distribution rights unresolved; local delivery only."+ "Public proprietary runtime distribution rights unresolved; local delivery only.",+ "Native capture physical connection/visual acceptance not run per user; mixed-revision statistics repaired but cadence/hardware performance not declared resolved."],- "nextAction": "Handoff: prioritize configuration-specific metric windows; user real-card acceptance; see docs/HANDOFF_2026-09-09.md. Do not restore intentionally removed GOAL_PROMPT.",- "updatedAt": "2026-09-09T01:52:39.336203+00:00",+ "nextAction": "Match actual stage extents/rates and instrument full pipeline waits/presentation; do not assume order is the main cause. FRUC reset pixels must pass before recovery changes ship. Do not resume cancelled physical color A/B.",+ "updatedAt": "2026-09-09T14:31:00+00:00","deliveryPlan": "docs/ACTIVE_DELIVERY_PLAN.md",- "captureAcceptance": "throughput_short_test_passed_user_latency_audio_pending",+ "captureAcceptance": "new_native_path_not_physically_tested_per_user_instruction","testInvocationLimitSeconds": 300,"currentEvidence": ["logs/f6-diag.json: diagnostic native1080 12frames exit0 (prior to statistics stride correction rebuild)",@@ -137,7 +177,8 @@"Cycle76 independent scopedPASS: docs/REVIEW_SR_FG_DEPTH_RESPONSE_2026-09-08.md; SR8bit negative depth response, FG tiny constructed benefit, no defaultmodel","Cycle77 independent scopedPASS: docs/REVIEW_SR_RECONSTRUCTION_2026-09-08.md; real4K SR spatialMAE lower, temporalerror/max higher; no natural/steady-state claim","Cycle85 scoped independent PASS: docs/SETTINGS_PAGE_SCOPE_REPAIR_2026-09-09.md; preflight71/phase775 and actual GPU double-direction settings regression passed",- "Cycle86 independent live-settings/master-off/focus/rollback/wheel/default PASS; delivery9f7468b334bc457db4b8bf125d4f5ddb; docs/HANDOFF_2026-09-09.md"+ "Cycle86 independent live-settings/master-off/focus/rollback/wheel/default PASS; delivery9f7468b334bc457db4b8bf125d4f5ddb; docs/HANDOFF_2026-09-09.md",+ "docs/BASELINE_REPAIR_IMPLEMENTATION_2026-09-09.md; logs/delivery/37bd4fedc5604642a2a2afeeca46c99e/result.json; final-live-fruc-pan10 PASS; native_capture independent scoped code/log review"],"reviewBaseCommit": "6f0ebaa687e3966d989bf138c86b6882380f20fb","localDelivery": "cycle86_live_settings_scoped_pass_handoff_ready",@@ -276,7 +317,7 @@"productModified": true,"consecutiveBlockedGoalTurns": 0,"previousGoalTurnClassification": "progress: SR/FG depth response and exact half-frame GT measured; incomplete-sample P2 fixed, independent18cases andgate PASS; default model not justified",- "currentGoalTurnClassification": "progress: optional shared RTX Video SR, actual playback/export and independent hot-switch/draft/legacy preset checks PASS; physical capture unavailable",+ "currentGoalTurnClassification": "progress: user FRUC short test accepted; GitHub source audit distinguishes GPU workload from scheduling/reset/metrics costs; no new code changes","controlSynchronizationAuthorization": "2026-09-08 user: 确认,给你全部权限; applies to previously proposed exact two-hash synchronization","diagnosticFindings": ["Q7 read-only dependency check: RTXVideoSDK not present in third_party_local; official1.1download redirects NVIDIA login. Localdepthfile vitl is Large, not permitted Small; no verified Small ONNX/provider. No dependency integrated or performance claimed."@@ -293,5 +334,15 @@"report": "docs/HANDOFF_2026-09-09.md","exeSha256": "3BD470D51AD43F7C461F23AB6F9F9B7234DC6F33D84C9DDEB35A463663264E2C","controlChangeAuthorization": "User explicitly deleted GOAL_PROMPT and requested removal of associated preflight checks; remaining10 hashes unchanged."+ },+ "frucIntegration": {+ "status": "independent_checks_passed_final_verdict_unavailable",+ "report": "docs/FRUC_INTEGRATION_2026-09-09.md",+ "highFpsActual": "256x144 2000frames 999.34processedfps enhancement-off",+ "backend": "optional FRUC 2/3/4X isolated GPU-sharing worker",+ "knownRisk": "capture-drop reset restarts worker; real-card quality/latency not yet accepted",+ "userFeedback": "User reports tested with no problems; unspecified configuration",+ "gate": "logs/delivery/1c195ef6d3684879b220fc8c13439e83/result.json",+ "reviewLimitation": "Reviewer hit usage limit after independent test reports; no final verdict"}}diff --git a/scripts/acceptance/ui-processing-fps.py b/scripts/acceptance/ui-processing-fps.pynew file mode 100644index 00000000..036ee4a8--- /dev/null+++ b/scripts/acceptance/ui-processing-fps.py@@ -0,0 +1,80 @@+"""Own-process regression: visible, bounded live GPU-completion FPS text."""+import ctypes as c+import ctypes.wintypes as w+import os+from pathlib import Path+import subprocess+import time+import uuid++root = Path.cwd()+user = c.WinDLL("user32")+user.SetProcessDPIAware()+user.GetAncestor.argtypes = [w.HWND, w.UINT]+user.GetAncestor.restype = w.HWND+callback = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM)+user.EnumWindows.argtypes = [callback, w.LPARAM]+user.EnumChildWindows.argtypes = [w.HWND, callback, w.LPARAM]+user.GetWindowThreadProcessId.argtypes = [w.HWND, c.POINTER(w.DWORD)]+user.GetWindowTextW.argtypes = [w.HWND, w.LPWSTR, c.c_int]+user.IsWindowVisible.argtypes = [w.HWND]+user.GetWindowRect.argtypes = [w.HWND, c.POINTER(w.RECT)]+user.GetClientRect.argtypes = [w.HWND, c.POINTER(w.RECT)]+user.ClientToScreen.argtypes = [w.HWND, c.POINTER(w.POINT)]+user.SendMessageTimeoutW.argtypes = [w.HWND, w.UINT, w.WPARAM, w.LPARAM,+ w.UINT, w.UINT, c.POINTER(c.c_size_t)]++for mode in ("daily", "professional", "small"):+ env = os.environ.copy()+ env["VEYRA_LOG_FILE"] = str(root / "logs" / ("fps-ui-" + uuid.uuid4().hex + ".log"))+ process = subprocess.Popen([str(root / "out/build/x64-release/veyra.exe"),+ str(root / "loop/local/fixed_clips/test_av_1080p.mp4"),+ "--no-nr", "--no-fg", "--no-sr", "--smoke-seconds", "8", "--smoke-view", mode], env=env)+ try:+ observed = {}++ @callback+ def child(handle, unused):+ text = c.create_unicode_buffer(512)+ user.GetWindowTextW(handle, text, len(text))+ if text.value.startswith("处理 ") and text.value.endswith(" fps"):+ observed["label"] = handle+ observed["text"] = text.value+ return True++ @callback+ def top(handle, unused):+ pid = w.DWORD()+ user.GetWindowThreadProcessId(handle, c.byref(pid))+ if pid.value == process.pid:+ observed["window"] = handle+ user.EnumChildWindows(handle, child, 0)+ return True++ deadline = time.monotonic() + 6+ while time.monotonic() < deadline:+ user.EnumWindows(top, 0)+ if "text" in observed and float(observed["text"].split()[1]) > 0:+ break+ time.sleep(.1)+ assert "label" in observed and float(observed["text"].split()[1]) > 0, observed+ label = observed["label"]+ observed["window"] = user.GetAncestor(label, 2)+ assert user.IsWindowVisible(label), (mode, "FPS hidden")+ rect, client, origin = w.RECT(), w.RECT(), w.POINT()+ user.GetWindowRect(label, c.byref(rect))+ user.GetClientRect(observed["window"], c.byref(client))+ user.ClientToScreen(observed["window"], c.byref(origin))+ assert origin.x <= rect.left < rect.right <= origin.x + client.right, (mode, rect.left, rect.right, origin.x, client.right)+ assert origin.y <= rect.top < rect.bottom <= origin.y + client.bottom, (mode, rect.top, rect.bottom, origin.y, client.bottom)+ result = c.c_size_t()+ assert user.SendMessageTimeoutW(observed["window"], 0x111, 102, 0, 2, 1000, c.byref(result))+ time.sleep(.3)+ user.EnumWindows(top, 0)+ assert observed["text"] == "处理 0.0 fps", observed+ assert process.wait(timeout=12) == 0+ print("PASS", mode, "visible bounded FPS, live value, pause zero", flush=True)+ finally:+ if process.poll() is None:+ process.terminate()+ process.wait(timeout=5)diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1index ca3aef79..93ec15e6 100644--- a/scripts/package-portable.ps1+++ b/scripts/package-portable.ps1@@ -24,7 +24,10 @@ $runtimeFiles = @(@{ Name = 'nvngx_dlssg.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_dlssg.dll'); Sha256 = '135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F'; Classification = 'community-experimental-runtime'; Experimental = $true },@{ Name = 'nvngx_dlssnr.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_dlssnr.dll'); Sha256 = 'E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E'; Classification = 'community-experimental-runtime'; Experimental = $true },@{ Name = 'nvngx_vsr.dll'; Source = (Join-Path $resolvedRoot 'runtime_local/nvidia/nvngx_vsr.dll'); Sha256 = 'C3D88EEA5FF7A548EDEFA66414CF6E77464D0947277C904F324DD23ABF58A1ED'; Classification = 'official-rtx-video-sdk-runtime'; Experimental = $false },- @{ Name = 'NvOFFRUC.dll'; Source = (Join-Path $resolvedRoot 'third_party_local/nvidia/Optical_Flow_SDK_5.0.7/NvOFFRUC/NvOFFRUCSample/bin/win64/NvOFFRUC.dll'); Sha256 = '5A0B6701D30709E25E7E5B92CA46B18AAB1459160CECD4F629872369D85C8B0A'; Classification = 'community-experimental-runtime'; Experimental = $true }+ @{ Name = 'NvOFFRUC.dll'; Source = (Join-Path $resolvedRoot 'third_party_local/nvidia/Optical_Flow_SDK_5.0.7/NvOFFRUC/NvOFFRUCSample/bin/win64/NvOFFRUC.dll'); Sha256 = '5A0B6701D30709E25E7E5B92CA46B18AAB1459160CECD4F629872369D85C8B0A'; Classification = 'community-experimental-runtime'; Experimental = $true },+ # Direct PE import of NvOFFRUC.dll. Keep the pinned dependency beside it;+ # do not assume a CUDA Toolkit or a globally installed cudart on user PCs.+ @{ Name = 'cudart64_110.dll'; Source = (Join-Path $resolvedRoot 'third_party_local/nvidia/Optical_Flow_SDK_5.0.7/NvOFFRUC/NvOFFRUCSample/bin/win64/cudart64_110.dll'); Sha256 = 'EDC35E7D0FA3F257BBEDFA7888911080C5696ACDD40B6187B6DD0173F20759AD'; Classification = 'cuda-runtime-dependency'; Experimental = $false })foreach ($item in $runtimeFiles) {if (-not (Test-Path -LiteralPath $item.Source)) { throw "Missing approved runtime: $($item.Name)" }diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlslindex 273c6594..8863a75f 100644--- a/shaders/RgbToLinear.hlsl+++ b/shaders/RgbToLinear.hlsl@@ -1,4 +1,4 @@-cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint reserved; };+cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; };Texture2D<float4> sourceRgb : register(t0);RWTexture2D<float4> linearRgb : register(u0);float decode(float v) {@@ -10,6 +10,7 @@ float decode(float v) {void main(uint3 p : SV_DispatchThreadID) {if (p.x >= width || p.y >= height) return;float4 c=sourceRgb[p.xy];+ if(limited!=0)c.rgb=saturate((c.rgb-16.0/255.0)*(255.0/219.0));// Present onto the player's opaque black canvas; never discard RGB chroma.linearRgb[p.xy]=float4(float3(decode(c.r),decode(c.g),decode(c.b))*c.a,1);}diff --git a/shaders/Yuy2ToLinear.hlsl b/shaders/Yuy2ToLinear.hlslnew file mode 100644index 00000000..80c5a68e--- /dev/null+++ b/shaders/Yuy2ToLinear.hlsl@@ -0,0 +1,27 @@+// Native 4:2:2 capture. One RGBA8 texel stores Y0 U Y1 V for two pixels.+// No CPU RGB expansion, intermediate 8-bit RGB rounding, or 4:2:0 conversion.+cbuffer Params : register(b0) {+ uint width; uint height; uint transfer; uint reserved;+ float limited; float matrix709; float2 padding;+};+Texture2D<float4> packedYuy2 : register(t0);+RWTexture2D<float4> linearRgb : register(u0);+float decode(float v) {+ if(transfer==0)return v;+ if(transfer==2)return v<0.081?v/4.5:pow((v+0.099)/1.099,1.0/0.45);+ return v<=0.04045?v/12.92:pow((v+0.055)/1.055,2.4);+}+[numthreads(16,16,1)]+void main(uint3 p : SV_DispatchThreadID) {+ if(p.x>=width||p.y>=height)return;+ const float4 pair=packedYuy2[uint2(p.x/2,p.y)];+ float y=(p.x&1)?pair.z:pair.x;+ float2 uv=pair.yw-128.0/255.0;+ if(limited>0.5){y=(y-16.0/255.0)*(255.0/219.0);uv*=255.0/224.0;}+ // Preserve head/footroom until the final RGB gamut clamp. Clipping Y+ // before the matrix changes saturated pixels with below-black luma.+ float3 rgb=matrix709>0.5?float3(y+1.5748*uv.y,y-0.187324*uv.x-0.468124*uv.y,y+1.8556*uv.x):+ float3(y+1.402*uv.y,y-0.344136*uv.x-0.714136*uv.y,y+1.772*uv.x);+ rgb=saturate(rgb);+ linearRgb[p.xy]=float4(decode(rgb.r),decode(rgb.g),decode(rgb.b),1);+}diff --git a/src/base/Log.cpp b/src/base/Log.cppindex 13b06df4..cd5f824a 100644--- a/src/base/Log.cpp+++ b/src/base/Log.cpp@@ -72,6 +72,8 @@ bool Logger::openFile(const std::wstring& path)if (file_ == nullptr) {return false;}+ std::setvbuf(file_,nullptr,_IOFBF,64*1024);+ bufferedLogBytes_=0;lastFileFlushTick_=GetTickCount64();return true;}@@ -110,7 +112,11 @@ void Logger::write(LogLevel level, const char* component, const std::string& mes}if (file_ != nullptr) {std::fprintf(file_, "%s\n", line.c_str());- std::fflush(file_);+ bufferedLogBytes_+=line.size()+1;+ const auto tick=GetTickCount64();+ // Keep every event, but avoid a write/flush syscall for every pass.+ // Errors and explicit crash/teardown flush() calls remain immediate.+ if(level==LogLevel::Warn||level==LogLevel::Error||bufferedLogBytes_>=64*1024||tick-lastFileFlushTick_>=250){std::fflush(file_);bufferedLogBytes_=0;lastFileFlushTick_=tick;}}}@@ -136,6 +142,15 @@ void error(const char* component, const std::string& message)Logger::instance().write(LogLevel::Error, component, message);}+bool verboseFrameLogs()+{+ static const bool enabled = [] {+ wchar_t value[2]{};+ return GetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS", value, 2) == 1 && value[0] == L'1';+ }();+ return enabled;+}+} // namespace log@@ -153,6 +168,7 @@ void Logger::flush()std::lock_guard<std::mutex> lock(mutex_);if (file_ != nullptr) {std::fflush(file_);+ bufferedLogBytes_=0;lastFileFlushTick_=GetTickCount64();}}} // namespace veyradiff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 02064582..168f7e8c 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -4,6 +4,10 @@#include "veyra/engine/LivePresentationTiming.h"#include "veyra/engine/PresentationScheduler.h"#include "veyra/engine/DeadlineWait.h"+#include "veyra/engine/PresentationWorker.h"+#include "veyra/engine/LivePresentationResetPolicy.h"+#include "veyra/engine/TimingWindow.h"+#include "veyra/engine/CaptureHalfRate.h"#include "veyra/source/MediaFileSource.h"#include "veyra/source/CaptureCardSource.h"#include "veyra/pipeline/EnhanceGraph.h"@@ -26,11 +30,8 @@ namespace veyra::engine {using Clock=std::chrono::steady_clock;namespace {double elapsedMs(Clock::time_point from){return std::chrono::duration<double,std::milli>(Clock::now()-from).count();}-struct TimingWindow {- std::deque<double> values;- void add(double v){values.push_back(v);if(values.size()>1200)values.pop_front();}- double p95()const{if(values.empty())return 0;std::vector<double> sorted(values.begin(),values.end());std::sort(sorted.begin(),sorted.end());return sorted[size_t((sorted.size()-1)*.95)];}-};+int64_t monotonic100ns(){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;}+struct OnExit {std::function<void()> action;~OnExit(){action();}};}EngineController::EngineController(){worker_=std::thread(&EngineController::dispatch,this);}EngineController::~EngineController(){ {std::lock_guard lock(mutex_);shutdown_=true;pending_={};stop_=true;}wake_.notify_one();if(worker_.joinable())worker_.join(); }@@ -43,11 +44,13 @@ void EngineController::dispatch(){void EngineController::post(std::function<void()> task){ {std::lock_guard lock(mutex_);stop_=true;pending_=std::move(task);}wake_.notify_one(); }bool EngineController::idle()const{std::lock_guard lock(mutex_);return !busy_&&!pending_;}void EngineController::open(HWND video,const std::wstring& path,PlayerOptions opts){- {std::lock_guard lock(mutex_);snapshot_={};previewView_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ const bool captureReplay=opts.captureReplayForTest;+ {std::lock_guard lock(mutex_);snapshot_={};processingRate_.reset(monotonic100ns());previewView_={};snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_);}+ opts.captureReplayForTest=captureReplay;post([this,video,path,opts]{paused_=false;seekSeconds_=-1;run(video,path,opts);});}void EngineController::stop(){std::lock_guard lock(mutex_);stop_=true;pending_={};snapshot_.transport=busy_?TransportState::Stopping:TransportState::Empty;}-void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);if(snapshot_.running)snapshot_.transport=p?TransportState::Paused:TransportState::Playing;}+void EngineController::pause(bool p){paused_=p;std::lock_guard lock(mutex_);processingRate_.reset(monotonic100ns());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;}@@ -57,7 +60,7 @@ 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_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;return copy;}+PlayerSnapshot EngineController::snapshot()const{std::lock_guard lock(mutex_);auto copy=snapshot_;copy.volume=volume_;copy.muted=muted_;copy.fps=copy.running&&!copy.image&©.transport==TransportState::Playing?processingRate_.rate(monotonic100ns()):0;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);@@ -65,8 +68,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;- source::CaptureCardSource captureSource;const bool isCapture=path.rfind(L"capture:",0)==0;- source::IFrameSource* activeSource=isCapture?static_cast<source::IFrameSource*>(&captureSource):&source;+ source::CaptureCardSource captureSource;const bool physicalCapture=path.rfind(L"capture:",0)==0;+ const bool isCapture=physicalCapture||options.captureReplayForTest;+ source::IFrameSource* activeSource=physicalCapture?static_cast<source::IFrameSource*>(&captureSource):&source;+ if(options.captureReplayForTest)veyra::log::info("capture-test","file replay exercises live scheduler; no physical capture device or latency measurement");bool audioStarted=false;bool failed=false;try {do {@@ -88,44 +93,67 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){{std::lock_guard lock(mutex_);desired_.multiplier=1;snapshot_.image=true;snapshot_.desired=desired_;}}else{source::SourceOpenDesc od;od.path=path;od.preferHardwareDecode=false;- if(!(isCapture?captureSource.configure(od):activeSource->open(od))){status(L"无法打开视频,请查看诊断",true);break;}+ if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(L"无法打开视频,请查看诊断",true);break;}width=activeSource->info().width;height=activeSource->info().height;duration=activeSource->info().duration.toDouble();}if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.rgbInput=isImage||isCapture;gd.stillImage=isImage;+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;+ gd.rgbInput=isImage||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);+ gd.yuy2Input=isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;gd.stillImage=isImage;const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,1);- gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;+ gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}- if(isCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}+ if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}{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(性能成本较高)"));+ status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false;std::deque<double> latenessSamples;- TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;auto nextTimingLog=Clock::now()+std::chrono::seconds(1);+ TimingWindow captureAges,scheduleWaits,processTimes,presentTimes,decodeTimes,gpuReadyTimes;+ std::array<TimingWindow,size_t(diagnostics::GpuStage::Count)> gpuStageTimes;+ std::array<uint64_t,size_t(diagnostics::GpuStage::Count)> lastGpuSampleEnd{};+ 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;+ CaptureHalfRate captureSampler;+ auto completedProcessing=[&](uint64_t revision){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==revision){processingRate_.complete(monotonic100ns());++snapshot_.processedCompleted;}};auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};+ // Only the live source may discard stale input. File playback keeps+ // its audio-clock scheduler and lossless source ordering.+ std::mutex gpuMutex,liveStatsMutex;+ struct LiveStats {uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};+ LiveStats liveStats;std::deque<int64_t> liveSubmissions;+ TimingWindow liveAges,liveWaits,livePresent,liveReady;+ std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;+ std::atomic<uint64_t> presentationGeneration{0};+ std::unique_ptr<PresentationWorker> liveWorker;+ if(isCapture)liveWorker=std::make_unique<PresentationWorker>([&]{return stop_.load()||paused_.load();});+ auto drainLivePresentation=[&]{if(liveWorker){++presentationDrains;liveWorker->cancelAndDrain();}};+ uint64_t metricsRevision=options.settings.revision,statsSourceBase=0,statsGeneratedBase=0;+ uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();while(!stop_){+ if(liveWorker&&liveWorker->failed()){status(L"采集画面呈现失败,请查看诊断",true);break;}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;}- // Save the currently displayed result before a settings transaction- // invalidates it. Keep a request queued until a frame exists.+ // Save the latest processed real frame before a settings transaction+ // invalidates it (live rendering can be one batch behind processing).std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();+ drainLivePresentation();if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}if(isImage)requested.multiplier=1;const auto previous=options.snapshot();const auto previousDesc=gd;bool transaction=false;if(requested.revision!=previous.revision){+ drainLivePresentation();auto next=PlayerOptions::from(requested);auto nextDesc=gd;const auto plan=pipeline::ResolutionPlan::make({width,height},next.sr,requested.nrPolicy,isImage,requested.revision);- nextDesc.workWidth=plan.base.width;nextDesc.workHeight=plan.base.height;nextDesc.nrWidth=plan.nr.width;nextDesc.nrHeight=plan.nr.height;+ nextDesc.workWidth=plan.base.width;nextDesc.workHeight=plan.base.height;nextDesc.nrWidth=plan.nr.width;nextDesc.nrHeight=plan.nr.height;nextDesc.flowWidth=plan.flow.width;nextDesc.flowHeight=plan.flow.height;nextDesc.enableSr=plan.srApplied;nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr;nextDesc.enableFg=next.fg;nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.frameGenerationBackend=next.settings.frameGenerationBackend;nextDesc.enableNvofStandalone=next.nr;nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;- const bool rebuild=gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||(nextDesc.frameGenerationBackend==FrameGenerationBackend::Fruc&&(gd.fgMultiplier!=nextDesc.fgMultiplier||gd.enableFg!=nextDesc.enableFg))||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight;+ const bool rebuild=gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||(nextDesc.frameGenerationBackend==FrameGenerationBackend::Fruc&&(gd.fgMultiplier!=nextDesc.fgMultiplier||gd.enableFg!=nextDesc.enableFg))||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;bool accepted=ring.drainQueue();out={};hasOutput=false;if(accepted&&rebuild){presenter.close();graph.shutdown();accepted=graph.initialize(nextDesc)&&presenter.open(ctx,window,graph)&&graph.createViews();if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}@@ -139,16 +167,44 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){discardBefore=seek*1000;reset=true;anchorMs=discardBefore;anchor=Clock::now();if(audioStarted)audioPipe.requestSeek(discardBefore);}if(!transaction&&((paused_&&seek<0)||(isImage&&hasOutput))){+ drainLivePresentation();if(audioStarted)audioPipe.setPaused(true);wasPaused=true;- if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){status(L"画面呈现失败",true);break;}+ const 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())){status(L"画面呈现失败",true);break;}std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;}if(wasPaused&&!paused_){if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}+ // Backpressure before reading the capacity-one source mailbox:+ // when a lease frees we consume the newest available sample.+ if(liveWorker&&!transaction&&!liveWorker->waitForSlot())continue;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;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;}if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}}+ if(transaction&&cachedFrame&&(!isCapture||paused_)){frame=cachedFrame;pkt=cachedPacket;}+ else if(!isImage){+ auto rs=activeSource->read(pkt,&frame);+ // Keep the accepted transaction and rollback state alive until+ // the next real capture sample arrives. Never bind old PTS to now.+ while(transaction&&isCapture&&rs==source::SourceReadStatus::Waiting&&!stop_){+ if(paused_&&cachedFrame){frame=cachedFrame;pkt=cachedPacket;rs=source::SourceReadStatus::Frame;break;}+ rs=activeSource->read(pkt,&frame);+ }+ if(stop_)break;+ 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;+ const bool halfRate=isCapture&&options.settings.content==ContentRate::Capture60To30&&+ CaptureHalfRate::supported(activeSource->info().averageFps);+ if(reset||pipeline::breaksHistory(pkt.flags))captureSampler.reset();+ if(halfRate&&!rereadCached){+ const auto interval=liveSourceInterval100ns(pipeline::Rational::unknown(),activeSource->info().averageFps);+ if(!pkt.pts.isUnknown()&&!captureSampler.accept(pkt.pts.to100ns(),interval,false)){+ std::lock_guard lock(mutex_);++snapshot_.captureRateSkipped;continue;+ }+ pkt.duration={interval*2,10000000};+ }+ if(!halfRate)captureSampler.reset();if(isImage)pkt.sequence=1;if(!rereadCached)++sourceFrames;const double decodeMs=elapsedMs(decodeStart);decodeTimes.add(decodeMs);@@ -157,37 +213,92 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(pts+0.1<discardBefore)continue;if(frame!=cachedFrame){av_frame_free(&cachedFrame);cachedFrame=av_frame_clone(frame);cachedPacket=pkt;}const auto processStart=Clock::now();+ const bool historyReset=reset||pipeline::breaksHistory(pkt.flags);+ if(historyReset){++historyResets;++presentationGeneration;}+ // A mailbox Drop must reset SR/NR/flow/FG history, but draining+ // the two-batch presenter here discarded completed real frames.+ if(liveWorker&&presentationDrainRequired(reset,pkt.flags))drainLivePresentation();const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");- if(injectedReject||!graph.process(frame,pts,reset||pipeline::breaksHistory(pkt.flags),out,pkt.sequence,&pkt.colorInfo)){+ bool processed=false;{std::lock_guard gpuLock(gpuMutex);processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0);}+ if(!processed){if(transaction){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,&pkt.colorInfo)){+ if(graph.initialize(gd)&&presenter.open(ctx,window,graph)&&graph.createViews()&&graph.process(frame,pts,true,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0)){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;}}- if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_.revision!=options.settings.revision;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,width,height,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时NR变化回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} backend={} multiplier={} (source kept open)",options.settings.revision,pts,options.settings.frameGenerationBackend==FrameGenerationBackend::Fruc?"FRUC":"DLSS",options.snapshot().multiplier));}- veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));+ if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_.revision!=options.settings.revision;snapshot_.status=std::format(L"输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} backend={} multiplier={} (source kept open)",options.settings.revision,pts,options.settings.frameGenerationBackend==FrameGenerationBackend::Fruc?"FRUC":"DLSS",options.snapshot().multiplier));}+ if(veyra::log::verboseFrameLogs())veyra::log::info("source-identity",std::format("source={} totalRead={} graphProcessed={} cached={} revision={} nvofStandalone={}",pkt.sequence,sourceFrames,frames+1,rereadCached,options.settings.revision,gd.enableNvofStandalone));reset=false;hasOutput=true;const auto processDone=Clock::now();processTimes.add(elapsedMs(processStart));- if(isCapture&&!liveTimeline.anchored(out.batch.identity.epoch)){+ if(metricsRevision!=options.settings.revision){+ metricsRevision=options.settings.revision;statsStart=Clock::now();statsSourceBase=sourceFrames;statsGeneratedBase=graph.metrics().fgGeneratedFrames;+ captureAges.clear();scheduleWaits.clear();processTimes.clear();presentTimes.clear();decodeTimes.clear();gpuReadyTimes.clear();for(auto& window:gpuStageTimes)window.clear();lastGpuSampleEnd={};latenessSamples.clear();submissionTimes.clear();submitted=expired=0;+ slotWaitBase=ring.cpuWaitCount();slotWaitMsBase=ring.cpuWaitMilliseconds();submitBase=ring.submitCount();+ if(liveWorker){std::lock_guard statsLock(liveStatsMutex);liveStats={};liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();historyResets=0;presentationDrains=0;presentationCompletedReal=0;presentationSkippedGenerated=0;presentationCancelledJobs=0;}+ veyra::log::info("metrics",std::format("reset appliedRevision={} sourceBase={}",metricsRevision,statsSourceBase));+ }+ if(transaction||frames==0){+ std::lock_guard lock(mutex_);processingRate_.reset(monotonic100ns());snapshot_.captureHalfRate=halfRate;+ veyra::log::info("capture-rate",std::format("revision={} requested60To30={} active={} transportFps={} originalPtsPreserved=true",options.settings.revision,options.settings.content==ContentRate::Capture60To30,halfRate,isCapture?activeSource->info().averageFps:0));+ }+ const auto captureArrival=pkt.arrivalHost100ns?pkt.arrivalHost100ns:+ std::chrono::duration_cast<std::chrono::nanoseconds>(processStart.time_since_epoch()).count()/100;+ if(isCapture&&!rereadCached&&!liveTimeline.anchored(out.batch.identity.epoch)){const auto duration100ns=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg));- 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);+ liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,captureArrival,options.fg?duration100ns:0);}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;+ double gpuWaitMs=0;+ if(liveWorker){+ const auto timeline=liveTimeline;+ const uint64_t jobGeneration=presentationGeneration.load();+ if(!liveWorker->push([&,batch=out,timeline,captureArrival,jobGeneration,rereadCached](const PresentationWorker::Cancelled& cancelled)mutable{+ auto& wait=deadlineWait;const auto readyStart=Clock::now();+ for(;;){if(cancelled()){++presentationCancelledJobs;return true;}bool ready;{std::lock_guard gpuLock(gpuMutex);ready=graph.resolveGeneration(batch);}if(ready)break;+ if(elapsedMs(readyStart)>2000){veyra::log::error("capture-present","GPU ready timeout");return false;}wait.slice(.2);}+ if(!rereadCached)completedProcessing(batch.batch.identity.settingsRevision);+ const double readyMs=elapsedMs(readyStart);double waitMs=0,presentMs=0,ageMs=0;uint64_t count=0,dropped=0;+ diagnostics::GpuSample blit;+ OnExit publish{[&]{if(!count&&!dropped)return;std::lock_guard statsLock(liveStatsMutex);liveStats.submitted+=count;liveStats.expired+=dropped;+ // Accumulate at completion, not at producer polling: two+ // completions between reads must not lose a timing sample.+ if(count){liveStats.waitMs=waitMs;liveStats.presentMs=presentMs;liveStats.readyMs=readyMs;liveStats.ageMs=ageMs;liveStats.blit=blit;+ liveAges.add(ageMs);liveWaits.add(waitMs);livePresent.add(presentMs);liveReady.add(readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}+ liveStats.fps=liveSubmissions.size()>1?double(liveSubmissions.size()-1)*1e7/(liveSubmissions.back()-liveSubmissions.front()):0;}};+ for(unsigned i=0;i<batch.batch.count;++i){auto& item=batch.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;+ if(generated&&(item.validity!=pipeline::GenerationValidity::Valid||comparisonMode_!=0))continue;+ if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}+ if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;continue;}+ const auto waitStart=Clock::now();while(!cancelled()&&host100ns()<timeline.deadline(item.pts100ns))wait.slice();waitMs+=elapsedMs(waitStart);if(cancelled()){++presentationCancelledJobs;return true;}+ if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}+ const auto begin=Clock::now();bool didPresent=false;+ {std::lock_guard gpuLock(gpuMutex);if(cancelled()){++presentationCancelledJobs;return true;}const auto before=presenter.submittedCount();+ if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView()))return false;+ item.lease->consumerFence=ring.lastSignaledValue();didPresent=presenter.submittedCount()>before;blit=presenter.blitTiming(ctx.fence());}+ presentMs+=elapsedMs(begin);+ if(didPresent){++count;if(!generated)++presentationCompletedReal;ageMs=double(host100ns()-captureArrival)/10000;std::lock_guard statsLock(liveStatsMutex);const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}+ }+ return true;+ })){status(L"采集呈现队列失败",true);break;}+ LiveStats completed;{std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}+ frameWaitMs=completed.waitMs;framePresentMs=completed.presentMs;gpuWaitMs=completed.readyMs;submitted=completed.submitted;expired=completed.expired;+ }else{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(.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);gpuReadyTimes.add(gpuWaitMs);+ if(paused_||seekSeconds_>=0){reset=true;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}+ if(!rereadCached&&!isImage)completedProcessing(out.batch.identity.settingsRevision);+ 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;@@ -198,29 +309,38 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){frameWaitMs+=elapsedMs(waitStart);if(stop_||paused_||seekSeconds_>=0){interrupted=true;break;}const auto begin=Clock::now();const auto before=presenter.submittedCount();- if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}+ if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}framePresentMs+=elapsedMs(begin);item.lease->consumerFence=ring.lastSignaledValue();- if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}+ if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}}if(presentFailed){status(L"画面提交失败",true);break;}if(interrupted){reset=true;continue;}- scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);+ }+ if(!liveWorker){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}const double lateness=isCapture?0:nowMs()-pts;if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());const auto captureStats=isCapture?captureSource.metrics():source::CaptureMetrics{};- if(isCapture)captureAges.add(captureStats.frameAgeMs);- auto measured=graph.gpuMetrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence());measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=elapsedMs(processStart)-elapsedMs(processDone);measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames;measured.validGenerated=graph.metrics().fgGeneratedFrames;measured.queueWatermark=out.batch.count;- ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;if(submissionTimes.size()>1)snapshot_.submissionFps=double(submissionTimes.size()-1)*1e7/(submissionTimes.back()-submissionTimes.front());snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graph.metrics().fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=sourceFrames/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());+ diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;+ {std::lock_guard gpuLock(gpuMutex);measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;}+ if(measured.identity.settingsRevision!=options.settings.revision){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}+ for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}+ measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.submitted=submitted;measured.expired=expired;measured.sourceFrames=sourceFrames-statsSourceBase;measured.validGenerated=graphStats.fgGeneratedFrames-statsGeneratedBase;measured.queueWatermark=out.batch.count;+ LiveStats completed;if(liveWorker){std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}+ const double ageP95=liveWorker?completed.ageP95:captureAges.p95(),waitP95=liveWorker?completed.waitP95:scheduleWaits.p95(),presentP95=liveWorker?completed.presentP95:presentTimes.p95();+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;if(liveWorker)snapshot_.submissionFps=completed.fps;else snapshot_.submissionFps=submissionTimes.size()>1?double(submissionTimes.size()-1)*1e7/(submissionTimes.back()-submissionTimes.front()):0;snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.fps=(sourceFrames-statsSourceBase)/std::max(0.001,std::chrono::duration<double>(Clock::now()-statsStart).count());snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;- snapshot_.nrEvaluated=graph.metrics().nrEvaluateCount;snapshot_.nvofExecuted=graph.metrics().nvofExecuteCount;- 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();+ snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;+ snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveWorker?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;+ snapshot_.schedulingWaitP95Ms=waitP95;snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentP95;}- 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);}+ const auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};+ if(!isCapture&&Clock::now()>=nextTimingLog){veyra::log::info("player-timing",std::format("revision={} decodeP95Ms={:.3f} graphSubmitP95Ms={:.3f} gpuReadyP95Ms={:.3f} presentP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} processed={}",options.settings.revision,decodeTimes.p95(),processTimes.p95(),gpuReadyTimes.p95(),presentTimes.p95(),gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,sourceFrames-statsSourceBase));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));+ const auto rates=snapshot();+ veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0)));+ veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} presentationWorker=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveWorker?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));nextTimingLog=Clock::now()+std::chrono::seconds(1);}}diff --git a/src/engine/EngineControllerImage.cpp b/src/engine/EngineControllerImage.cppindex 97b5da91..697eec46 100644--- a/src/engine/EngineControllerImage.cpp+++ b/src/engine/EngineControllerImage.cpp@@ -85,7 +85,7 @@ void EngineController::runLargeImage(HWND window,const sink::RgbaImage& originalout={};if(!preview.process(frame.get(),0,true,out,++previewRevision)){status(L"大图预览上传失败",true);break;}havePreview=true;lastComparison=comparison;lastSplit=split;lastView=view;lastClient=client;}- if(havePreview&&!presenter.present(ctx,ring,preview,out.videoSlot,false,0,false,.5f,{},PreviewView{0,.5f,.5f})){status(L"大图呈现失败",true);break;}+ if(havePreview&&!presenter.present(ctx,ring,preview,out.videoSlot,false,false,0,false,.5f,{},PreviewView{0,.5f,.5f})){status(L"大图呈现失败",true);break;}std::this_thread::sleep_for(std::chrono::milliseconds(16));}out={}; // Cleanup drains before either presenter or graph releases GPU objects.diff --git a/src/engine/TiledImageProcessor.cpp b/src/engine/TiledImageProcessor.cppindex 12d54247..f2728803 100644--- a/src/engine/TiledImageProcessor.cpp+++ b/src/engine/TiledImageProcessor.cpp@@ -62,7 +62,7 @@ bool TiledImageProcessor::process(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRtileSettings.revision=desc.settingsRevision;if(!graph.applySettings(tileSettings))return false;pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage tile;// Every tile is a new spatial image, never a temporal neighbour.- if(!graph.process(frame.get(),0,true,out,uint64_t(stats.tiles)+1)||+ if(!graph.process(frame.get(),0,true,out,uint64_t(stats.tiles)+1,nullptr,false)||!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),tile))return false;if(tile.width!=tileW||tile.height!=tileH)return false;out={};diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex d7f9a898..ec51bdae 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -42,7 +42,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpticonst AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den));const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision);- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();if(!graph.initialize(gd)||!graph.createViews())break;if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;@@ -80,7 +80,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiprogress(0,L"此文件时间戳不均匀,当前CFR导出不支持;已保留partial,未改写音画时间轴");veyra::log::error("export-timeline",std::format("CFR rejected source={} pts={} expected={}",sourceCount,packet.pts.toDouble(),expectedPts));error=true;break;}- pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo)){error=true;break;}+ pipeline::EnhanceGraph::FrameOutputs out;if(!graph.process(frame,packet.pts.toDouble()*1000,sourceCount==0||pipeline::breaksHistory(packet.flags),out,packet.sequence,&packet.colorInfo,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;}diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cppindex da0c9690..2f73f7a2 100644--- a/src/engine/VideoPresenter.cpp+++ b/src/engine/VideoPresenter.cpp@@ -18,7 +18,7 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enhreturn true;}void VideoPresenter::refresh(ID3D12Device* device){for(unsigned i=0;i<3;++i){Microsoft::WRL::ComPtr<ID3D12Resource> bb;if(SUCCEEDED(sink_.swapChain()->GetBuffer(i,IID_PPV_ARGS(&bb))))device->CreateRenderTargetView(bb.Get(),nullptr,{rtvs_->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*inc_});}}-bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {+bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,unsigned slot,bool generated,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {RECT rc{};GetClientRect(window_,&rc);if(rc.right<1||rc.bottom<1)return true;const auto now=std::chrono::steady_clock::now();const auto deferUntil=uint64_t(uintptr_t(GetPropW(window_,L"Veyra.ResizeDeferUntil")));@@ -46,13 +46,13 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&float dims[8]={float(graph.workWidth()),float(graph.workHeight()),0,view.zoom,float(rc.right),float(rc.bottom),view.centerX,view.centerY};list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(slot+(generated?2:0))*pass_.increment});list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);list->DrawInstanced(3,1,0,0);- if(comparison&&!generated){+ if(comparison&&!generated&&referencesValid){auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);dims[2]=1;list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(8+slot+(baseReference?2:0))*pass_.increment});if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*graph.workWidth()*scale*view.zoom)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);- veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));+ if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));}for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);diff --git a/src/gfx/CommandSlotRing.cpp b/src/gfx/CommandSlotRing.cppindex b4de7077..d2a2ed87 100644--- a/src/gfx/CommandSlotRing.cpp+++ b/src/gfx/CommandSlotRing.cpp@@ -1,5 +1,6 @@#include "veyra/gfx/CommandSlotRing.h"+#include <chrono>#include <format>#include "veyra/Log.h"@@ -28,6 +29,7 @@ bool CommandSlotRing::initialize(ID3D12Device* device,fenceEvent_ = fenceEvent;slotCount_ = slotCount;nextSlot_ = 0;+ cpuWaitCount_=0;cpuWaitMilliseconds_=0;submitCount_=0;if (device_ == nullptr || queue_ == nullptr || fence_ == nullptr || fenceEvent_ == nullptr || slotCount_ == 0) {status = Status::InvalidArgument;@@ -94,6 +96,7 @@ void CommandSlotRing::shutdown()slots_.clear();timestampHeap_.Reset();timingReadback_.Reset();+ cpuWaitCount_=0;cpuWaitMilliseconds_=0;submitCount_=0;initialized_ = false;veyra::log::info("gfx", "slot-ring: shutdown complete");}@@ -117,7 +120,9 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statureturn nullptr;}++cpuWaitCount_;+ const auto waitStart=std::chrono::steady_clock::now();const DWORD wait = WaitForSingleObject(fenceEvent_, 10000);+ cpuWaitMilliseconds_+=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-waitStart).count();if (wait != WAIT_OBJECT_0) {status = Status::DeviceFailure;veyra::log::error("gfx", std::format("slot-ring: fence wait slot={} waitResult={} fenceValue={}", slot, wait, target.fenceValue));@@ -130,7 +135,7 @@ ID3D12GraphicsCommandList* CommandSlotRing::acquire(uint32_t slot, Status& statuuint64_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];- if(end>=begin&&gpuCommandTimesMs_.size()<16384){const double ms=double(end-begin)*1000.0/timestampFrequency_;gpuCommandTimesMs_.push_back(ms);if(!target.label.empty())veyra::log::info("gpu-profile",std::format("{} {:.4f} ms",target.label,ms));}+ if(end>=begin&&gpuCommandTimesMs_.size()<16384){const double ms=double(end-begin)*1000.0/timestampFrequency_;gpuCommandTimesMs_.push_back(ms);if(!target.label.empty()&&veyra::log::verboseFrameLogs())veyra::log::info("gpu-profile",std::format("{} {:.4f} ms",target.label,ms));}D3D12_RANGE empty{0,0};timingReadback_->Unmap(0,&empty);}target.timed=false;target.label.clear();}@@ -176,6 +181,7 @@ bool CommandSlotRing::submitAndSignal(uint32_t slot)return false;}target.fenceValue = value;+ ++submitCount_;return true;}diff --git a/src/ngx/DlssFgBackend.cpp b/src/ngx/DlssFgBackend.cppindex 8f29aeb0..2e503c20 100644--- a/src/ngx/DlssFgBackend.cpp+++ b/src/ngx/DlssFgBackend.cpp@@ -285,9 +285,10 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,uint32_t sehCode = 0;const NVSDK_NGX_Result result = CallEvaluateDlssg(cmdList, handle_, params,&evalParams, &optParams, sehCode);- log::info("ngx", std::format("fg-backend: Evaluate #{} frameId={} reset={} generatedCount={} subframe={} result={} seh={}",- evaluateCount_ + 1, desc.frameId, desc.reset ? 1 : 0,desc.multiFrameCount,desc.multiFrameIndex,- ngxResultString(static_cast<uint64_t>(result)), sehCode));+ if(result != NVSDK_NGX_Result_Success || log::verboseFrameLogs())+ log::info("ngx", std::format("fg-backend: Evaluate #{} frameId={} reset={} generatedCount={} subframe={} result={} seh={}",+ evaluateCount_ + 1, desc.frameId, desc.reset ? 1 : 0,desc.multiFrameCount,desc.multiFrameIndex,+ ngxResultString(static_cast<uint64_t>(result)), sehCode));if (result != NVSDK_NGX_Result_Success) {log::error("ngx", std::format("fg-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));diff --git a/src/ngx/DlssSrBackend.cpp b/src/ngx/DlssSrBackend.cppindex cb988739..54fa6455 100644--- a/src/ngx/DlssSrBackend.cpp+++ b/src/ngx/DlssSrBackend.cpp@@ -167,8 +167,9 @@ bool DlssSrBackend::evaluate(ID3D12GraphicsCommandList* cmdList,uint32_t sehCode = 0;const NVSDK_NGX_Result result = CallEvaluateDlss(cmdList, handle_, params, &evalParams, sehCode);- log::info("ngx", std::format("sr-backend: Evaluate #{} result={} seh={}",- evaluateCount_ + 1, ngxResultString(static_cast<uint64_t>(result)), sehCode));+ if(result != NVSDK_NGX_Result_Success || log::verboseFrameLogs())+ log::info("ngx", std::format("sr-backend: Evaluate #{} result={} seh={}",+ evaluateCount_ + 1, ngxResultString(static_cast<uint64_t>(result)), sehCode));if (result != NVSDK_NGX_Result_Success) {log::error("ngx", std::format("sr-backend failed result=0x{:X} seh=0x{:X}", static_cast<unsigned>(result), sehCode));diff --git a/src/ngx/FrucWorker.cpp b/src/ngx/FrucWorker.cppindex 02c4fc3a..0bd10dff 100644--- a/src/ngx/FrucWorker.cpp+++ b/src/ngx/FrucWorker.cpp@@ -140,7 +140,7 @@ bool WorkerKernel::execute(FrucWorkerMessage& info) {out.uSyncSignal.FenceSignalValue.uiFenceValueToSignalOn=++wait;unsigned seh=0;auto result=callSafe(seh,process,handles[j],&in,&out);info.result=uint32_t(result);info.seh=seh;- log::info("fruc",std::format("Process inputMs={} outputMs={} sub={} result={} seh={} repeated={}",info.currentMs,out.stFrameDataOutput.nTimeStamp,j+1,int(result),seh,info.repeated[j]));+ if(result!=NvOFFRUC_SUCCESS||seh||log::verboseFrameLogs())log::info("fruc",std::format("Process inputMs={} outputMs={} sub={} result={} seh={} repeated={}",info.currentMs,out.stFrameDataOutput.nTimeStamp,j+1,int(result),seh,info.repeated[j]));if(result!=NvOFFRUC_SUCCESS||seh)return false;}info.outputFence=wait;return true;diff --git a/src/ngx/VideoSrBackend.cpp b/src/ngx/VideoSrBackend.cppindex acfcacb2..5cbfbf98 100644--- a/src/ngx/VideoSrBackend.cpp+++ b/src/ngx/VideoSrBackend.cpp@@ -13,8 +13,10 @@ NVSDK_NGX_Result invoke(int op,ID3D12GraphicsCommandList* list,NVSDK_NGX_Paramet} __except(EXCEPTION_EXECUTE_HANDLER){seh=GetExceptionCode();return NVSDK_NGX_Result_FAIL_PlatformError;}}bool result(int op,NVSDK_NGX_Result r,unsigned seh){- (NVSDK_NGX_SUCCEED(r)&&!seh?log::info:log::error)("video-sr",std::format("op={} result=0x{:X} seh=0x{:X}",op,unsigned(r),seh));- return NVSDK_NGX_SUCCEED(r)&&!seh;+ const bool ok=NVSDK_NGX_SUCCEED(r)&&!seh;+ if(!ok)log::error("video-sr",std::format("op={} result=0x{:X} seh=0x{:X}",op,unsigned(r),seh));+ else if(op!=1||log::verboseFrameLogs())log::info("video-sr",std::format("op={} result=0x{:X} seh=0x{:X}",op,unsigned(r),seh));+ return ok;}}bool VideoSrBackend::create(NgxCoreHost& core,ID3D12GraphicsCommandList* list){diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cppindex f782229a..990e0b94 100644--- a/src/pipeline/EnhanceGraph.cpp+++ b/src/pipeline/EnhanceGraph.cpp@@ -70,19 +70,21 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)veyra::log::info("graph","diagnostic SR motion override active; no product entry point enables this");}desc_ = desc;tracker_={};prevValid_=false;cadence_.reset();scene_.reset();previousLuma_.clear();- diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={desc.sourceWidth,desc.sourceHeight};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={desc.workWidth,desc.workHeight};initDiagnostic.resolution.nr={desc.nrWidth?desc.nrWidth:desc.workWidth,desc.nrHeight?desc.nrHeight:desc.workHeight};initDiagnostic.resolution.flow=initDiagnostic.resolution.source;initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";Logger::diagnosticContext(initDiagnostic);if(desc.videoSrQuality>4)return false;srcW_ = desc.sourceWidth;srcH_ = desc.sourceHeight;workW_ = desc.workWidth;workH_ = desc.workHeight;nrW_=desc.nrWidth?desc.nrWidth:workW_; nrH_=desc.nrHeight?desc.nrHeight:workH_;- nvofW_ = srcW_;- nvofH_ = srcH_;+ if((desc.flowWidth==0)!=(desc.flowHeight==0)){veyra::log::error("resolution","partial flow extent is invalid");return false;}+ nvofW_ = desc.flowWidth?desc.flowWidth:srcW_;+ nvofH_ = desc.flowHeight?desc.flowHeight:srcH_;if(!Extent{srcW_,srcH_}.valid()||!Extent{workW_,workH_}.valid()){veyra::log::error("resolution","source/output exceeds D3D12 texture dimensions or is empty");return false;}if(!Extent{nrW_,nrH_}.valid()||nrW_>workW_||nrH_>workH_){veyra::log::error("resolution","invalid NR extent");return false;}+ if(!Extent{nvofW_,nvofH_}.valid()||nvofW_>srcW_||nvofH_>srcH_){veyra::log::error("resolution","invalid source-space flow extent");return false;}+ diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={srcW_,srcH_};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={workW_,workH_};initDiagnostic.resolution.nr={nrW_,nrH_};initDiagnostic.resolution.flow={nvofW_,nvofH_};initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="E16BCF15E16E13F527491CDF7845B2FE6521A738D8F7C9C721866A8496E1FC8E";Logger::diagnosticContext(initDiagnostic);veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_);nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;@@ -141,9 +143,11 @@ bool EnhanceGraph::createResources()upZeroMotion_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);lumaTex_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R8_UNORM, true);chromaTex_ = makeTexture(context_.device(), (srcW_+1) / 2, (srcH_+1) / 2, DXGI_FORMAT_R8G8_UNORM, true);- if(desc_.rgbInput){- rgbPitch_=(size_t(srcW_)*4+255)&~size_t(255);- rgbTex_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,false);+ if(desc_.rgbInput||desc_.yuy2Input){+ if(desc_.yuy2Input&&(srcW_%2||desc_.rgbInput))return false;+ const unsigned packedWidth=desc_.yuy2Input?srcW_/2:srcW_;+ rgbPitch_=(size_t(packedWidth)*4+255)&~size_t(255);+ rgbTex_=makeTexture(context_.device(),packedWidth,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,false);if(!rgbTex_)return false;for(unsigned i=0;i<2;++i){upRgb_[i]=makeUploadBuffer(context_.device(),rgbPitch_*srcH_);if(!upRgb_[i]||FAILED(upRgb_[i]->Map(0,nullptr,reinterpret_cast<void**>(&mappedRgb_[i]))))return false;@@ -151,9 +155,10 @@ bool EnhanceGraph::createResources()}srcRgba_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);if(srEnabled_&&desc_.videoSrQuality){videoSrInput_=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);videoSrOutput_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R8G8B8A8_UNORM,true);if(!videoSrInput_||!videoSrOutput_)return false;}- workRgba_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);- for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}- nrInput_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ const bool directBase=!srEnabled_&&srcW_==workW_&&srcH_==workH_;+ workRgba_=directBase?srcRgba_:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);+ for(unsigned i=0;i<2;++i){sourceReferences_[i]=makeTexture(context_.device(),srcW_,srcH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);baseReferences_[i]=directBase?sourceReferences_[i]:makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,false);if(!sourceReferences_[i]||!baseReferences_[i])return false;}+ nrInput_=(nrW_==workW_&&nrH_==workH_)?workRgba_:makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);residualRgba_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16B16A16_FLOAT,true);nrFlow_=makeTexture(context_.device(),nrW_,nrH_,DXGI_FORMAT_R16G16_FLOAT,true);baseFlow_=makeTexture(context_.device(),workW_,workH_,DXGI_FORMAT_R16G16_FLOAT,true);@@ -493,7 +498,7 @@ bool EnhanceGraph::createComputePasses()if(!residualPass_.loadShader("NrResidualComposite.dxil",cs)||!residualPass_.create(context_.device(),cs,4,3,1,24))return false;if(!flowAdaptPass_.loadShader("FlowAdapt.dxil",cs)||!flowAdaptPass_.create(context_.device(),cs,3,1,1))return false;if (!yuvPass_.loadShader("YuvToLinearRgb.dxil", cs) || !yuvPass_.create(context_.device(), cs, 8, 2, 1)) return false;- if(desc_.rgbInput&&(!rgbPass_.loadShader("RgbToLinear.dxil",cs)||!rgbPass_.create(context_.device(),cs,4,1,1)))return false;+ if((desc_.rgbInput||desc_.yuy2Input)&&(!rgbPass_.loadShader(desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil",cs)||!rgbPass_.create(context_.device(),cs,desc_.yuy2Input?8:4,1,1)))return false;if (!encPass_.loadShader("ParityEncode.dxil", cs) || !encPass_.create(context_.device(), cs, 8, 1, 1)) return false;if (!decPass_.loadShader("ParityDecode.dxil", cs) || !decPass_.create(context_.device(), cs, 8)) return false;if (!blitPass_.loadShader("ScaleBlit.dxil", cs) || !blitPass_.create(context_.device(), cs, 18, 1, 1)) return false;@@ -555,7 +560,7 @@ bool EnhanceGraph::createViews()makeUav(context_.device(),nrFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,1));makeUav(context_.device(),baseFlow_.Get(),DXGI_FORMAT_R16G16_FLOAT,cpu(flowAdaptPass_,2));// Immutable per-resource views.- if(desc_.rgbInput){+ if(desc_.rgbInput||desc_.yuy2Input){stagedSrv(rgbTex_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,rgbPass_,0);makeUav(context_.device(),srcRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(rgbPass_,1));}@@ -632,7 +637,7 @@ bool EnhanceGraph::createViews()// ---------------------------------------------------------------------------// process: the per-frame chain (verbatim from the probe lambda).// ----------------------------------------------------------------------------bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color)+bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, bool retainReferences){out = FrameOutputs{};out.ptsMs = ptsMs;@@ -695,14 +700,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FramepreviousLuma_=std::move(sample);};- if(desc_.rgbInput){- if(frame->format!=AV_PIX_FMT_RGBA&&frame->format!=AV_PIX_FMT_BGRA&&frame->format!=AV_PIX_FMT_RGB0&&frame->format!=AV_PIX_FMT_BGR0){+ if(desc_.rgbInput||desc_.yuy2Input){+ if(desc_.yuy2Input?frame->format!=AV_PIX_FMT_YUYV422:(frame->format!=AV_PIX_FMT_RGBA&&frame->format!=AV_PIX_FMT_BGRA&&frame->format!=AV_PIX_FMT_RGB0&&frame->format!=AV_PIX_FMT_BGR0)){veyra::log::error("graph","direct RGB input contract requires packed RGBA/BGRA/RGB0/BGR0 frame");return false;}- if(frame->width!=int(srcW_)||frame->height!=int(srcH_))return false;+ if(frame->width!=int(srcW_)||frame->height!=int(srcH_)||!frame->data[0]||std::abs(int64_t(frame->linesize[0]))<int64_t(srcW_)*(desc_.yuy2Input?2:4))return false;for(uint32_t y=0;y<srcH_;++y){auto* dst=mappedRgb_[parity]+y*rgbPitch_;const auto* src=frame->data[0]+ptrdiff_t(y)*frame->linesize[0];- if(frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(srcW_)*4);+ if(desc_.yuy2Input||frame->format==AV_PIX_FMT_RGBA)std::memcpy(dst,src,size_t(srcW_)*(desc_.yuy2Input?2:4));else for(uint32_t x=0;x<srcW_;++x){const bool bgr=frame->format==AV_PIX_FMT_BGRA||frame->format==AV_PIX_FMT_BGR0;dst[x*4]=src[x*4+(bgr?2:0)];dst[x*4+1]=src[x*4+1];dst[x*4+2]=src[x*4+(bgr?0:2)];@@ -713,15 +718,15 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Framestd::vector<uint8_t> sample;sample.reserve(64*36);const bool bgr=frame->format==AV_PIX_FMT_BGRA||frame->format==AV_PIX_FMT_BGR0;for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){- const auto* p=frame->data[0]+ptrdiff_t(y*srcH_/36)*frame->linesize[0]+(x*srcW_/64)*4;- sample.push_back(uint8_t((54*unsigned(p[bgr?2:0])+183*unsigned(p[1])+19*unsigned(p[bgr?0:2])+128)>>8));+ const auto* p=frame->data[0]+ptrdiff_t(y*srcH_/36)*frame->linesize[0]+(x*srcW_/64)*(desc_.yuy2Input?2:4);+ sample.push_back(desc_.yuy2Input?p[0]:uint8_t((54*unsigned(p[bgr?2:0])+183*unsigned(p[1])+19*unsigned(p[bgr?0:2])+128)>>8));}analyzeLuma(std::move(sample));}tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);D3D12_TEXTURE_COPY_LOCATION dst{},src{};dst.pResource=rgbTex_.Get();dst.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;src.pResource=upRgb_[parity].Get();src.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;- src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,srcW_,srcH_,1,UINT(rgbPitch_)};+ src.PlacedFootprint.Footprint={DXGI_FORMAT_R8G8B8A8_UNORM,desc_.yuy2Input?srcW_/2:srcW_,srcH_,1,UINT(rgbPitch_)};list->CopyTextureRegion(&dst,0,0,0,&src,nullptr);tracker_.transition(list,rgbTex_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);} else if (frame->format == AV_PIX_FMT_D3D12) {@@ -827,8 +832,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame// 2. YUV -> RGBA16F.tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- if(desc_.rgbInput){- const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(transferCode(resolved.transfer)),0,0,0,0,0};+ if(desc_.rgbInput||desc_.yuy2Input){+ const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(transferCode(resolved.transfer)),uintBits(resolved.range==ColorRange::Limited?1u:0u),+ resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,0,0};rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);}else{@@ -861,7 +867,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list,nvofInA_.Get(),D3D12_RESOURCE_STATE_COMMON);}tracker_.transition(list,nvofInB_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);- const float encodedDims[8] = {uintBits(nvofW_),uintBits(nvofH_),uintBits(nvofW_),uintBits(nvofH_),1,0,0,0};+ const float encodedDims[8] = {uintBits(srcW_),uintBits(srcH_),uintBits(nvofW_),uintBits(nvofH_),1,0,0,0};blitPass_.bind(list,encodedDims,gpuHandleOf(blitPass_,15).ptr,gpuHandleOf(blitPass_,9).ptr);list->Dispatch((nvofW_+15)/16,(nvofH_+15)/16,1);tracker_.uavBarrier(list,nvofInB_.Get());@@ -941,7 +947,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame++metrics_.srEvaluateCount;gpuTimer_.mark(list,GpuStage::Sr,true);tracker_.uavBarrier(list, workRgba_.Get());tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);- } else {+ } else if(workRgba_.Get()!=srcRgba_.Get()) {tracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float constants[8] = {uintBits(srcW_), uintBits(srcH_),@@ -952,17 +958,23 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frametracker_.transition(list, workRgba_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);}if (desc_.stageMark) desc_.stageMark("sr");- // GPU copies retain exact pre-enhancement references under the real lease.- auto retain=[&](ID3D12Resource* src,ID3D12Resource* dst){tracker_.transition(list,src,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(dst,src);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,src,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};- retain(srcRgba_.Get(),sourceReferences_[parity].Get());retain(workRgba_.Get(),baseReferences_[parity].Get());+ if(retainReferences){+ // Comparison references belong to this real-frame lease. Avoid the two+ // full-frame copies when comparison is disabled.+ auto retain=[&](ID3D12Resource* src,ID3D12Resource* dst){tracker_.transition(list,src,D3D12_RESOURCE_STATE_COPY_SOURCE);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COPY_DEST);list->CopyResource(dst,src);tracker_.transition(list,dst,D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,src,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);};+ retain(srcRgba_.Get(),sourceReferences_[parity].Get());+ if(baseReferences_[parity].Get()!=sourceReferences_[parity].Get())retain(workRgba_.Get(),baseReferences_[parity].Get());+ }// 4a. Parity encode.if (nrEnabled_ && nrHandle_ != nullptr) {+ if(nrInput_.Get()!=workRgba_.Get()){tracker_.transition(list,nrInput_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float down[8]={uintBits(workW_),uintBits(workH_),uintBits(nrW_),uintBits(nrH_),0,0,0,0};downsamplePass_.bind(list,down,gpuHandleOf(downsamplePass_,0).ptr,gpuHandleOf(downsamplePass_,1).ptr);list->Dispatch((nrW_+15)/16,(nrH_+15)/16,1);tracker_.uavBarrier(list,nrInput_.Get());tracker_.transition(list,nrInput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ }tracker_.transition(list, proxyTex_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);const float constants[8] = { 1.0f, 1.0f, 1.0f, 0.0f,uintBits(nrW_), uintBits(nrH_), 0.0f, 0.0f };@@ -1144,13 +1156,18 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame++realFrameIndex_;out.realFrameIndex = realFrameIndex_;out.videoSlot = parity;- BatchFrame real;real.identity=out.batch.identity;real.pts100ns=out.batch.b100ns;real.lease=std::make_shared<FrameLease>();real.lease->texture=videoFrame_[parity];real.lease->sourceReference=sourceReferences_[parity];real.lease->baseReference=baseReferences_[parity];real.lease->slot=parity;real.lease->readyFence=out.videoFenceValue;realLeases_[parity]=real.lease;out.batch.append(std::move(real));- veyra::log::info("frame-batch",std::format("batch={} epoch={} revision={} source={} a={} b={} count={} realSlot={} realFence={} genSlot={} genFence={}",out.batch.batchId,epoch_,out.batch.identity.settingsRevision,out.batch.identity.sourceFrameId,out.batch.a100ns,out.batch.b100ns,out.batch.count,parity,out.videoFenceValue,out.genSlot,out.genFenceValue));+ BatchFrame real;real.identity=out.batch.identity;real.pts100ns=out.batch.b100ns;real.lease=std::make_shared<FrameLease>();real.lease->texture=videoFrame_[parity];real.lease->sourceReference=sourceReferences_[parity];real.lease->baseReference=baseReferences_[parity];real.lease->slot=parity;real.lease->readyFence=out.videoFenceValue;real.lease->referencesValid=retainReferences;realLeases_[parity]=real.lease;out.batch.append(std::move(real));+ if(veyra::log::verboseFrameLogs())veyra::log::info("frame-batch",std::format("batch={} epoch={} revision={} source={} a={} b={} count={} realSlot={} realFence={} genSlot={} genFence={}",out.batch.batchId,epoch_,out.batch.identity.settingsRevision,out.batch.identity.sourceFrameId,out.batch.a100ns,out.batch.b100ns,out.batch.count,parity,out.videoFenceValue,out.genSlot,out.genFenceValue));return true;}bool EnhanceGraph::resolveGeneration(FrameOutputs& out){+ // Real-only batches also need a completed GPU fence before a consumer+ // can report completed processing. This is a nonblocking poll.+ const auto completed=context_.fence()->GetCompletedValue();+ for(uint32_t i=0;i<out.batch.count;++i)+ if(out.batch.frames[i].lease&&completed<out.batch.frames[i].lease->readyFence)return false;if(!out.hasGenerated)return true;if(context_.fence()->GetCompletedValue()<out.genFenceValue)return false;bool anyValid=false;@@ -1168,7 +1185,7 @@ bool EnhanceGraph::resolveGeneration(FrameOutputs& out)const bool rejected=disabled||out.contentDuplicate;frame.validity=rejected?GenerationValidity::Disabled:GenerationValidity::Valid;anyValid|=!rejected;if(rejected)++metrics_.fgDisabledFrames;else ++metrics_.fgGeneratedFrames;- 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));+ 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));}out.hasGenerated=anyValid;return true;}diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex 273537dc..a30de541 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -1,5 +1,7 @@#include "veyra/source/CaptureCardSource.h"#include "veyra/source/CaptureTiming.h"+#include "veyra/source/CaptureMediaType.h"+#include "veyra/source/NativeCaptureSink.h"#include "veyra/pipeline/ColorMetadata.h"#include "veyra/Log.h"#include <windows.h>@@ -42,7 +44,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {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;+ SourceInfo info;CaptureMediaLayout layout;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;}HRESULT STDMETHODCALLTYPE SampleCB(double time,IMediaSample* sample)override{@@ -50,20 +52,21 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {REFERENCE_TIME sampleStart=0,sampleEnd=0;const bool sampleTime=sample&&sample->GetTime(&sampleStart,&sampleEnd)==S_OK;const bool valid=sample&&std::isfinite(time)&&SUCCEEDED(sample->GetPointer(&data))&&data&&- sample->GetActualDataLength()>=LONG(size_t(stride)*info.height);+ sample->GetActualDataLength()>=LONG(layout.sampleBytes);{std::lock_guard lock(mutex);if(!valid||!pendingFrame){callbackError=true;}else {// Copy directly into our bounded mailbox; read() swaps frames// under this lock, so the frame consumed by the GPU is untouched.- for(unsigned y=0;y<info.height;++y)- memcpy(pendingFrame->data[0]+size_t(y)*pendingFrame->linesize[0],- data+size_t(bottomUp?info.height-1-y:y)*stride,stride);+ if(!copyCaptureSample(layout,data,size_t(sample->GetActualDataLength()),*pendingFrame)){callbackError=true;wake.notify_one();return S_OK;}if(pending)++dropped;+ // Inspect consecutive callbacks, not consecutive mailbox reads.+ // Preserve a driver/clock break when its sample is overwritten.+ pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,+ sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);pending=true;pendingTime=time;pendingArrival=arrival;pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);- pendingDiscontinuity=sample->IsDiscontinuity()==S_OK;if(!received)firstArrival=arrival;++received;latestArrival=arrival;}@@ -92,23 +95,50 @@ bool CaptureCardSource::setAudioGain(float gain){bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}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);log::info("capture",std::format("SetFormat device={} nativeIndex={} subtype=0x{:08X} hr=0x{:08X}",index,format,native->subtype.Data1,uint32_t(hr)));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;- AM_MEDIA_TYPE want{};want.majortype=MEDIATYPE_Video;want.subtype=MEDIASUBTYPE_RGB32;want.formattype=FORMAT_VideoInfo;- if(FAILED(p.grab->SetMediaType(&want))||FAILED(CoCreateInstance(NullRendererClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.nullFilter)))||FAILED(p.graph->AddFilter(p.nullFilter.Get(),L"Video sink"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,p.device.Get(),p.grabFilter.Get(),p.nullFilter.Get())))return false;- AM_MEDIA_TYPE connected{};if(FAILED(p.grab->GetConnectedMediaType(&connected)))return false;- if(connected.formattype!=FORMAT_VideoInfo||connected.cbFormat<sizeof(VIDEOINFOHEADER)){freeType(&connected,false);return false;}auto vi=*reinterpret_cast<VIDEOINFOHEADER*>(connected.pbFormat);freeType(&connected,false);- if(vi.bmiHeader.biWidth<=0||vi.bmiHeader.biWidth>3840||abs(vi.bmiHeader.biHeight)>2160||vi.bmiHeader.biBitCount!=32)return false;- p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=vi.bmiHeader.biWidth;p.info.height=abs(vi.bmiHeader.biHeight);p.info.averageFps=vi.AvgTimePerFrame>0?1e7/vi.AvgTimePerFrame:0;p.info.duration=pipeline::Rational::unknown();p.bottomUp=vi.bmiHeader.biHeight>0;p.stride=p.info.width*4;- p.nominalDuration100ns=vi.AvgTimePerFrame;+ 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);const GUID requestedSubtype=native->subtype;+ log::info("capture",std::format("SetFormat device={} nativeIndex={} subtype=0x{:08X} hr=0x{:08X}",index,format,native->subtype.Data1,uint32_t(hr)));freeType(native);if(FAILED(hr))return false;+ // Read the driver-negotiated type back. Native YUY2/NV12/RGB32 connects+ // directly to our terminal filter: no intelligent-connect converter.+ native=nullptr;hr=p.config->GetFormat(&native);if(FAILED(hr)||!native){freeType(native);return false;}+ const bool nativeSupported=native->subtype==MEDIASUBTYPE_YUY2||native->subtype==MEDIASUBTYPE_NV12||native->subtype==MEDIASUBTYPE_RGB32;+ const bool direct=nativeSupported&&!desc.legacyCaptureRgbForDiagnostic;+ AM_MEDIA_TYPE connected{};+ if(direct){+ ComPtr<IPin> input,output;+ hr=createNativeCaptureSink(*native,[&p](IMediaSample* sample){REFERENCE_TIME a=0,b=0;const auto timeHr=sample->GetTime(&a,&b);if(FAILED(timeHr))return timeHr;return p.SampleCB(double(a)/1e7,sample);},p.grabFilter,input);+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.grabFilter.Get(),L"Native frame mailbox");+ if(SUCCEEDED(hr))hr=p.builder->FindPin(p.device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&output);+ if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(output.Get(),input.Get(),native);+ if(SUCCEEDED(hr))hr=input->ConnectionMediaType(&connected);+ log::info("capture",std::format("native ConnectDirect subtype=0x{:08X} hr=0x{:08X} converters=0",native->subtype.Data1,uint32_t(hr)));+ }else{+ log::warn("capture",std::format("explicit RGB32 compatibility path subtype=0x{:08X} diagnostic={} (decoder/color converter may be inserted)",requestedSubtype.Data1,desc.legacyCaptureRgbForDiagnostic));+ hr=CoCreateInstance(SampleGrabberClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.grabFilter));+ if(SUCCEEDED(hr))hr=p.grabFilter.As(&p.grab);+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.grabFilter.Get(),L"Decoded RGB compatibility mailbox");+ AM_MEDIA_TYPE want{};want.majortype=MEDIATYPE_Video;want.subtype=MEDIASUBTYPE_RGB32;want.formattype=FORMAT_VideoInfo;+ if(SUCCEEDED(hr))hr=p.grab->SetMediaType(&want);+ if(SUCCEEDED(hr))hr=CoCreateInstance(NullRendererClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.nullFilter));+ if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.nullFilter.Get(),L"Video sink");+ if(SUCCEEDED(hr))hr=p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,p.device.Get(),p.grabFilter.Get(),p.nullFilter.Get());+ if(SUCCEEDED(hr))hr=p.grab->GetConnectedMediaType(&connected);+ }+ freeType(native);const bool layoutValid=SUCCEEDED(hr)&&captureMediaLayout(connected,p.layout);freeType(&connected,false);+ if(!layoutValid){log::error("capture",std::format("unsupported negotiated layout/connect failure hr=0x{:08X}",uint32_t(hr)));return false;}+ p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=p.layout.width;p.info.height=p.layout.height;p.info.averageFps=p.layout.duration>0?1e7/p.layout.duration:0;p.info.duration=pipeline::Rational::unknown();p.info.color=p.layout.color;+ p.nominalDuration100ns=p.layout.duration;+ log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (SDR display-referred)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));if(audio>=0){if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio"))||FAILED(p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,p.audioFilter.Get(),nullptr,nullptr)))return false;}- if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events))||FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0)))return false;+ if(FAILED(p.graph.As(&p.control))||FAILED(p.graph.As(&p.events)))return false;+ if(p.grab&&(FAILED(p.grab->SetBufferSamples(FALSE))||FAILED(p.grab->SetCallback(&p,0))))return false;for(auto** f:{&p.frame,&p.pendingFrame}){*f=av_frame_alloc();if(!*f)return false;- (*f)->format=AV_PIX_FMT_BGR0;(*f)->width=p.info.width;(*f)->height=p.info.height;(*f)->color_range=AVCOL_RANGE_JPEG;+ (*f)->format=p.layout.format;(*f)->width=p.info.width;(*f)->height=p.info.height;if(av_frame_get_buffer(*f,32)<0)return false;}- p.info.color=pipeline::resolveFrameColor(*p.frame);p.configured=true;+ p.configured=true;// Log the upstream type after DirectShow has finished negotiation. The// RGB32 output's nominal FPS alone is not proof of actual callback cadence.AM_MEDIA_TYPE* actual=nullptr;const auto formatHr=p.config->GetFormat(&actual);@@ -139,11 +169,12 @@ SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFp.readAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();if(!p.sequence)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Open);if(p.dropped!=p.lastDrop)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Drop);- const double maxGap=p.info.averageFps>0?2.5/p.info.averageFps:0.1;- if(p.pendingDiscontinuity||(p.sequence&&(time<=p.lastPts||time-p.lastPts>maxGap)))flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);+ if(p.pendingDiscontinuity)flags|=static_cast<uint32_t>(pipeline::FrameFlagBits::Discontinuity);p.lastDrop=p.dropped;p.lastPts=time;sequence=++p.sequence;}- p.frame->pts=static_cast<int64_t>(time*10000000);p.frame->duration=duration.isUnknown()?0:duration.to100ns();p.frame->time_base={1,10000000};packet={};packet.pts={p.frame->pts,10000000};packet.duration=duration;packet.colorInfo=p.info.color;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;*frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;+ p.frame->pts=static_cast<int64_t>(time*10000000);p.frame->duration=duration.isUnknown()?0:duration.to100ns();p.frame->time_base={1,10000000};packet={};packet.pts={p.frame->pts,10000000};packet.duration=duration;packet.colorInfo=p.info.color;packet.sourceKind=pipeline::SourceKind::CaptureCard;packet.sequence=sequence;packet.flags=flags;packet.sourceEpoch=1;+ packet.arrivalHost100ns=std::chrono::duration_cast<std::chrono::nanoseconds>(p.readArrival.time_since_epoch()).count()/100;+ *frame=p.frame;p.lastFrame=Impl::Clock::now();return SourceReadStatus::Frame;}void CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);diff --git a/src/source/NativeCaptureSink.cpp b/src/source/NativeCaptureSink.cppnew file mode 100644index 00000000..5c1199d7--- /dev/null+++ b/src/source/NativeCaptureSink.cpp@@ -0,0 +1,119 @@+#include "veyra/source/NativeCaptureSink.h"+#include "veyra/source/CaptureMediaType.h"+#include "veyra/Log.h"+#include <format>+#include <atomic>+#include <mutex>+#include <string>++namespace veyra::source {+using Microsoft::WRL::ComPtr;+namespace {+void clearType(AM_MEDIA_TYPE& t){CoTaskMemFree(t.pbFormat);if(t.pUnk)t.pUnk->Release();t={};}+HRESULT copyType(AM_MEDIA_TYPE& dst,const AM_MEDIA_TYPE& src){+ dst=src;dst.pbFormat=nullptr;dst.pUnk=nullptr;+ if(src.cbFormat){if(!src.pbFormat)return E_INVALIDARG;dst.pbFormat=static_cast<BYTE*>(CoTaskMemAlloc(src.cbFormat));if(!dst.pbFormat)return E_OUTOFMEMORY;memcpy(dst.pbFormat,src.pbFormat,src.cbFormat);}+ dst.pUnk=src.pUnk;if(dst.pUnk)dst.pUnk->AddRef();return S_OK;+}+class PinEnum final:public IEnumPins {+ std::atomic<ULONG> refs_{1};ComPtr<IPin> pin_;bool used_=false;+public:+ explicit PinEnum(IPin* p,bool used=false):pin_(p),used_(used){}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IEnumPins)return E_NOINTERFACE;*p=static_cast<IEnumPins*>(this);AddRef();return S_OK;}+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs_;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs_;if(!n)delete this;return n;}+ HRESULT STDMETHODCALLTYPE Next(ULONG n,IPin** p,ULONG* fetched)override{if(!p||(!fetched&&n!=1))return E_POINTER;if(fetched)*fetched=0;if(!n)return S_OK;if(used_)return S_FALSE;*p=pin_.Get();(*p)->AddRef();used_=true;if(fetched)*fetched=1;return n==1?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE Skip(ULONG n)override{if(!n)return S_OK;const bool one=!used_&&n==1;used_=true;return one?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE Reset()override{used_=false;return S_OK;}+ HRESULT STDMETHODCALLTYPE Clone(IEnumPins** p)override{if(!p)return E_POINTER;*p=new PinEnum(pin_.Get(),used_);return S_OK;}+};+class TypeEnum final:public IEnumMediaTypes {+ std::atomic<ULONG> refs_{1};AM_MEDIA_TYPE type_{};bool used_=false;+public:+ TypeEnum(const AM_MEDIA_TYPE& type,bool used=false):used_(used){if(FAILED(copyType(type_,type)))throw std::bad_alloc();}+ ~TypeEnum(){clearType(type_);}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IEnumMediaTypes)return E_NOINTERFACE;*p=static_cast<IEnumMediaTypes*>(this);AddRef();return S_OK;}+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs_;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs_;if(!n)delete this;return n;}+ HRESULT STDMETHODCALLTYPE Next(ULONG n,AM_MEDIA_TYPE** p,ULONG* fetched)override{if(!p||(!fetched&&n!=1))return E_POINTER;if(fetched)*fetched=0;if(!n)return S_OK;if(used_)return S_FALSE;*p=static_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));if(!*p)return E_OUTOFMEMORY;const auto hr=copyType(**p,type_);if(FAILED(hr)){CoTaskMemFree(*p);*p=nullptr;return hr;}used_=true;if(fetched)*fetched=1;return n==1?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE Skip(ULONG n)override{if(!n)return S_OK;const bool one=!used_&&n==1;used_=true;return one?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE Reset()override{used_=false;return S_OK;}+ HRESULT STDMETHODCALLTYPE Clone(IEnumMediaTypes** p)override{if(!p)return E_POINTER;try{*p=new TypeEnum(type_,used_);return S_OK;}catch(...){*p=nullptr;return E_OUTOFMEMORY;}}+};+class NativeSink final:public IBaseFilter,public IPin,public IMemInputPin {+ std::atomic<ULONG> refs_{1};std::recursive_mutex mutex_;+ FILTER_STATE state_=State_Stopped;bool flushing_=false;+ AM_MEDIA_TYPE desired_{},connected_{};CaptureMediaLayout layout_;+ ComPtr<IPin> peer_;ComPtr<IMemAllocator> allocator_;ComPtr<IReferenceClock> clock_;+ IFilterGraph* graph_=nullptr;std::wstring name_=L"Native capture mailbox";+ std::function<HRESULT(IMediaSample*)> callback_;+public:+ NativeSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> cb):callback_(std::move(cb)){+ if(!captureMediaLayout(type,layout_)||FAILED(copyType(desired_,type)))throw std::bad_alloc();+ }+ ~NativeSink(){clearType(desired_);clearType(connected_);}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{+ if(!p)return E_POINTER;*p=nullptr;+ if(id==IID_IUnknown||id==IID_IPersist||id==IID_IMediaFilter||id==IID_IBaseFilter)*p=static_cast<IBaseFilter*>(this);+ else if(id==IID_IPin)*p=static_cast<IPin*>(this);else if(id==IID_IMemInputPin)*p=static_cast<IMemInputPin*>(this);else return E_NOINTERFACE;+ AddRef();return S_OK;+ }+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs_;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs_;if(!n)delete this;return n;}+ HRESULT STDMETHODCALLTYPE GetClassID(CLSID* p)override{if(!p)return E_POINTER;*p={0x02a47523,0x92af,0x4c6e,{0x97,0xe3,0x1a,0x14,0xf1,0x2d,0xab,0x5a}};return S_OK;}+ HRESULT STDMETHODCALLTYPE Stop()override{std::lock_guard lock(mutex_);state_=State_Stopped;return S_OK;}+ HRESULT STDMETHODCALLTYPE Pause()override{std::lock_guard lock(mutex_);state_=State_Paused;flushing_=false;return S_OK;}+ HRESULT STDMETHODCALLTYPE Run(REFERENCE_TIME)override{std::lock_guard lock(mutex_);state_=State_Running;flushing_=false;return S_OK;}+ HRESULT STDMETHODCALLTYPE GetState(DWORD,FILTER_STATE* p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p=state_;return S_OK;}+ HRESULT STDMETHODCALLTYPE SetSyncSource(IReferenceClock* p)override{std::lock_guard lock(mutex_);clock_=p;return S_OK;}+ HRESULT STDMETHODCALLTYPE GetSyncSource(IReferenceClock** p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);return clock_.CopyTo(p);}+ HRESULT STDMETHODCALLTYPE EnumPins(IEnumPins** p)override{if(!p)return E_POINTER;*p=new(std::nothrow) PinEnum(this);return *p?S_OK:E_OUTOFMEMORY;}+ HRESULT STDMETHODCALLTYPE FindPin(LPCWSTR id,IPin** p)override{if(!id||!p)return E_POINTER;*p=nullptr;if(wcscmp(id,L"Input"))return VFW_E_NOT_FOUND;*p=static_cast<IPin*>(this);AddRef();return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryFilterInfo(FILTER_INFO* p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p={};wcsncpy_s(p->achName,name_.c_str(),_TRUNCATE);p->pGraph=graph_;if(graph_)graph_->AddRef();return S_OK;}+ HRESULT STDMETHODCALLTYPE JoinFilterGraph(IFilterGraph* p,LPCWSTR name)override{std::lock_guard lock(mutex_);graph_=p;name_=name?name:L"Native capture mailbox";return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryVendorInfo(LPWSTR* p)override{if(p)*p=nullptr;return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE Connect(IPin*,const AM_MEDIA_TYPE*)override{return E_UNEXPECTED;}+ HRESULT STDMETHODCALLTYPE ReceiveConnection(IPin* peer,const AM_MEDIA_TYPE* type)override{+ if(!peer||!type)return E_POINTER;std::lock_guard lock(mutex_);if(state_!=State_Stopped)return VFW_E_NOT_STOPPED;if(peer_)return VFW_E_ALREADY_CONNECTED;+ PIN_DIRECTION direction;if(FAILED(peer->QueryDirection(&direction))||direction!=PINDIR_OUTPUT)return VFW_E_INVALID_DIRECTION;+ if(QueryAccept(type)!=S_OK)return VFW_E_TYPE_NOT_ACCEPTED;+ const auto hr=copyType(connected_,*type);if(FAILED(hr))return hr;peer_=peer;captureMediaLayout(*type,layout_);return S_OK;+ }+ HRESULT STDMETHODCALLTYPE Disconnect()override{std::lock_guard lock(mutex_);if(state_!=State_Stopped)return VFW_E_NOT_STOPPED;const bool connected=bool(peer_);peer_.Reset();allocator_.Reset();clearType(connected_);return connected?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE ConnectedTo(IPin** p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p=nullptr;return peer_?peer_.CopyTo(p):VFW_E_NOT_CONNECTED;}+ HRESULT STDMETHODCALLTYPE ConnectionMediaType(AM_MEDIA_TYPE* p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p={};return peer_?copyType(*p,connected_):VFW_E_NOT_CONNECTED;}+ HRESULT STDMETHODCALLTYPE QueryPinInfo(PIN_INFO* p)override{if(!p)return E_POINTER;*p={};p->pFilter=this;AddRef();p->dir=PINDIR_INPUT;wcscpy_s(p->achName,L"Input");return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* p)override{if(!p)return E_POINTER;*p=PINDIR_INPUT;return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryId(LPWSTR* p)override{if(!p)return E_POINTER;*p=static_cast<LPWSTR>(CoTaskMemAlloc(sizeof(L"Input")));if(!*p)return E_OUTOFMEMORY;memcpy(*p,L"Input",sizeof(L"Input"));return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE* p)override{+ if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(peer_)return equivalentCaptureTypes(*p,connected_)?S_OK:S_FALSE;CaptureMediaLayout candidate;+ return captureMediaLayout(*p,candidate)&&p->subtype==desired_.subtype&&candidate.width==layout_.width&&candidate.height==layout_.height?S_OK:S_FALSE;+ }+ HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes** p)override{if(!p)return E_POINTER;try{*p=new TypeEnum(desired_);return S_OK;}catch(...){*p=nullptr;return E_OUTOFMEMORY;}}+ HRESULT STDMETHODCALLTYPE QueryInternalConnections(IPin**,ULONG*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE EndOfStream()override{return S_OK;}+ HRESULT STDMETHODCALLTYPE BeginFlush()override{std::lock_guard lock(mutex_);flushing_=true;return S_OK;}+ HRESULT STDMETHODCALLTYPE EndFlush()override{std::lock_guard lock(mutex_);flushing_=false;return S_OK;}+ HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE GetAllocator(IMemAllocator** p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);if(!allocator_){const auto hr=CoCreateInstance(CLSID_MemoryAllocator,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&allocator_));if(FAILED(hr))return hr;}return allocator_.CopyTo(p);}+ HRESULT STDMETHODCALLTYPE NotifyAllocator(IMemAllocator* p,BOOL)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);allocator_=p;return S_OK;}+ HRESULT STDMETHODCALLTYPE GetAllocatorRequirements(ALLOCATOR_PROPERTIES* p)override{if(!p)return E_POINTER;std::lock_guard lock(mutex_);*p={3,LONG(layout_.sampleBytes),1,0};return S_OK;}+ HRESULT STDMETHODCALLTYPE Receive(IMediaSample* sample)override{+ if(!sample)return E_POINTER;std::lock_guard lock(mutex_);if(flushing_)return S_FALSE;if(state_==State_Stopped)return VFW_E_WRONG_STATE;+ // A device mode change needs full source/graph recreation, never a+ // silent reinterpretation using the previous frame's pitch/format.+ AM_MEDIA_TYPE* changed=nullptr;const auto typeHr=sample->GetMediaType(&changed);+ if(FAILED(typeHr)){if(changed){clearType(*changed);CoTaskMemFree(changed);}log::error("capture",std::format("sample GetMediaType hr=0x{:08X}",uint32_t(typeHr)));return typeHr;}+ if(typeHr==S_OK&&changed){+ const bool same=equivalentCaptureTypes(*changed,connected_);+ clearType(*changed);CoTaskMemFree(changed);if(!same){log::error("capture",std::format("dynamic capture contract changed; reopen required hr=0x{:08X}",uint32_t(VFW_E_INVALIDMEDIATYPE)));return VFW_E_INVALIDMEDIATYPE;}+ }+ if(sample->GetActualDataLength()<LONG(layout_.sampleBytes))return VFW_E_BUFFER_UNDERFLOW;+ try{return callback_(sample);}catch(...){return E_FAIL;}+ }+ HRESULT STDMETHODCALLTYPE ReceiveMultiple(IMediaSample** p,long n,long* done)override{if(!p||!done||n<0)return E_INVALIDARG;*done=0;while(*done<n){const auto hr=Receive(p[*done]);if(hr!=S_OK)return hr;++*done;}return S_OK;}+ HRESULT STDMETHODCALLTYPE ReceiveCanBlock()override{return S_OK;}+};+}+HRESULT createNativeCaptureSink(const AM_MEDIA_TYPE& type,std::function<HRESULT(IMediaSample*)> callback,ComPtr<IBaseFilter>& filter,ComPtr<IPin>& pin){+ filter.Reset();pin.Reset();CaptureMediaLayout layout;if(!captureMediaLayout(type,layout))return VFW_E_INVALIDMEDIATYPE;+ try{filter.Attach(new NativeSink(type,std::move(callback)));return filter.As(&pin);}catch(...){return E_OUTOFMEMORY;}+}+}diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cppindex 7c8975d9..ac7086d6 100644--- a/tests/integration/CaptureSourceTests.cpp+++ b/tests/integration/CaptureSourceTests.cpp@@ -29,7 +29,8 @@ int wmain(int argc,wchar_t** argv){auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame)return true;if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};if(!readFrame()){printf("FAIL first frame\n");return 5;}const auto initialPts=packet.pts.toDouble();const auto initialReceived=source.metrics().received;- std::vector<unsigned char> row(frame->data[0],frame->data[0]+frame->width*4);+ const int rowBytes=frame->width*(frame->format==AV_PIX_FMT_YUYV422?2:frame->format==AV_PIX_FMT_NV12?1:4);+ std::vector<unsigned char> row(frame->data[0],frame->data[0]+rowBytes);std::this_thread::sleep_for(std::chrono::milliseconds(300));auto stalled=source.metrics();check(stalled.received>=initialReceived+3,"callbacks continue while reader retains frame");diff --git a/tests/integration/FrucTests.cpp b/tests/integration/FrucTests.cppindex 97efbb53..a425d087 100644--- a/tests/integration/FrucTests.cpp+++ b/tests/integration/FrucTests.cpp@@ -7,6 +7,7 @@#include <fstream>#include <iostream>#include <cmath>+#include <string_view>extern "C" {#include <libavutil/frame.h>#include <libavutil/pixfmt.h>@@ -34,6 +35,29 @@ int main(int argc,char** argv){using namespace veyra;if(argc<3)return 2;const un// A second frame after reseeding must run successfully, even for static input.if(ok)ok=graph.process(f,epoch*2000.0+1000.0/15,false,out)&&ring.waitIdle()&&graph.resolveGeneration(out);}+ // Opt-in reproducer for the unresolved post-reset pixel error. The standard+ // smoke above never claimed pixel correctness after its static reseeds.+ if(argc>3&&std::string_view(argv[3])=="--reset-pixels"){+ bool pixelsOk=true;+ for(unsigned epoch=1;ok&&epoch<=6;++epoch){const double start=10000+epoch*1000;const bool invert=epoch%2!=0;+ for(unsigned i=0;ok&&i<3;++i){const int shift=int(epoch)*16+int(i)*8;+ for(unsigned y=0;y<H;++y)for(unsigned x=0;x<W;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c){const auto v=color(int(x)-shift,y,c);p[c]=static_cast<unsigned char>(invert?255-v:v);}p[3]=255;}+ pipeline::EnhanceGraph::FrameOutputs out;ok=graph.process(f,start+i*1000.0/15,i==0,out)&&ring.waitIdle()&&graph.resolveGeneration(out);+ if(i==0){ok=ok&&out.batch.count==1;continue;}+ ok=ok&&out.batch.count==mult;+ for(unsigned j=0;ok&&j<out.batch.count;++j){const auto& item=out.batch.frames[j];if(item.kind!=pipeline::FrameKind::Generated)continue;+ sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,item.lease->texture.Get(),image);if(!ok)break;+ double error=0,repeatError=0;size_t samples=0;const double target=shift-8+8.0*item.subframe/mult;+ for(unsigned y=32;y<H-32;++y)for(unsigned x=96;x<W-96;++x)for(unsigned c=0;c<3;++c){const double pos=x-target;const int left=int(std::floor(pos));const double t=pos-left;+ double expected=color(left,y,c)*(1-t)+color(left+1,y,c)*t;double repeated=color(int(x)-shift+8,y,c);if(invert){expected=255-expected;repeated=255-repeated;}+ error+=std::abs(image.pixels[(size_t(y)*W+x)*4+c]-expected);repeatError+=std::abs(repeated-expected);++samples;}+ const bool pass=item.validity==pipeline::GenerationValidity::Valid&&error<repeatError;+ pixelsOk=pixelsOk&&pass;std::cout<<"FRUC_RESET_GT epoch="<<epoch<<" frame="<<i<<" sub="<<item.subframe<<" mae="<<error/samples<<" repeatMae="<<repeatError/samples<<" pass="<<pass<<std::endl;+ }+ }+ }+ ok=ok&&pixelsOk;+ }ok=ok&&generated==5*(mult-1);std::cout<<"FRUC_RESULT multiplier="<<mult<<" generated="<<generated<<" worstMae="<<worst<<" pass="<<ok<<std::endl;ring.drainQueue();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:1;}diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cppnew file mode 100644index 00000000..b4b82760--- /dev/null+++ b/tests/integration/LivePresentationTests.cpp@@ -0,0 +1,57 @@+#include "veyra/engine/EngineController.h"+#include "veyra/Log.h"+#include <chrono>+#include <iostream>+#include <filesystem>+#include <fstream>+using namespace veyra;+using namespace std::chrono_literals;+int wmain(int argc,wchar_t**argv){+ SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);+ HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;+ const bool halfRate=argc==4&&wcscmp(argv[3],L"--half-rate")==0;+ if(argc==4&&!halfRate)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;+ if(halfRate)options.settings.content=engine::ContentRate::Capture60To30;+ int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<std::endl;if(!pass)++failures;};+ auto until=[&](auto predicate,int seconds=8){auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);while(std::chrono::steady_clock::now()<deadline){MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}auto s=engine.snapshot();if(s.failed){std::wcerr<<s.status<<'\n';return false;}if(predicate(s))return true;std::this_thread::sleep_for(5ms);}return false;};+ engine.open(window,argv[1],options);+ check(until([](const auto& s){return s.capture&&s.frames>=8&&s.metrics.submitted>=4;}),"file replay runs actual live worker and presents");+ if(halfRate){auto s=engine.snapshot();check(s.captureHalfRate&&s.captureRateSkipped>=s.frames-2,"60fps input is sampled before GPU processing");}+ check(engine.snapshot().processedCompleted>0,"real-only GPU completions are counted without FG");+ if(halfRate){+ check(until([](const auto& s){return s.processedCompleted>=80;}),"sampled capture sustains more than two seconds");+ const auto s=engine.snapshot();check(s.fps>=27&&s.fps<=33,"GPU completed throughput is about 30fps, not transport60");+ }+ auto state=engine.snapshot();auto settings=state.desired;settings.nr=true;settings.multiplier=2;engine.requestSettings(settings);+ check(until([](const auto& s){return s.applied.nr&&s.applied.multiplier==2&&!s.applying&&s.nrEvaluated>2&&s.generated>0;}),"NR and 2x transaction while two batches are in flight");+ state=engine.snapshot();const auto liveRevision=state.applied.revision;check(state.metrics.identity.settingsRevision==state.applied.revision,"GPU metrics belong to applied revision");+ engine.pause(true);check(until([](const auto& s){return s.transport==engine::TransportState::Paused;}),"pause returns without queue deadlock");+ check(engine.snapshot().fps==0,"paused FPS is zero rather than a retained session average");+ settings=engine.snapshot().desired;settings.model.style=1;engine.requestSettings(settings);+ check(until([](const auto& s){return s.applied.model.style==1&&!s.applying;}),"settings apply while paused");+ const auto pausedRevision=engine.snapshot().applied.revision;+ engine.pause(false);const auto before=engine.snapshot().frames;check(until([&](const auto& s){return s.frames>=before+8&&s.metrics.submitted>0;}),"resume resets history and restarts bounded presentation");+ settings=engine.snapshot().desired;settings.multiplier=4;engine.requestSettings(settings);+ check(until([](const auto& s){return s.applied.multiplier==4&&!s.applying&&s.metrics.submitted>8;}),"4x uses worker without lease overwrite");+ settings=engine.snapshot().desired;settings.nr=false;settings.multiplier=1;engine.requestSettings(settings);+ check(until([](const auto& s){return !s.applied.nr&&s.applied.multiplier==1&&!s.applying&&s.metrics.sourceFrames>4;}),"disable features and keep live source open");+ check(engine.snapshot().metrics.validGenerated==0,"disabled revision cannot retain prior generated-frame count");+ if(halfRate){+ settings=engine.snapshot().desired;settings.content=engine::ContentRate::Transport;engine.requestSettings(settings);+ check(until([](const auto& s){return !s.applying&&!s.captureHalfRate&&s.metrics.sourceFrames>=80;}),"switch back to original capture cadence live");+ const auto s=engine.snapshot();check(s.fps>=55&&s.fps<=65,"GPU completed throughput returns to about 60fps");+ }+ engine.stop();const auto stopLimit=std::chrono::steady_clock::now()+5s;while(!engine.idle()&&std::chrono::steady_clock::now()<stopLimit)std::this_thread::sleep_for(5ms);check(engine.idle(),"stop drains presenter before graph shutdown");+ Logger::instance().flush();std::ifstream log(std::filesystem::path(argv[2])/"engine.log");std::string line;bool liveFresh=false,pausedCached=false;+ while(std::getline(log,line))if(line.find("source-identity")!=std::string::npos){+ if(line.find("cached=false revision="+std::to_string(liveRevision)+" ")!=std::string::npos)liveFresh=true;+ if(line.find("cached=true revision="+std::to_string(pausedRevision)+" ")!=std::string::npos)pausedCached=true;+ if(line.find("cached=true revision="+std::to_string(liveRevision)+" ")!=std::string::npos)++failures;+ }+ check(liveFresh,"running capture settings process fresh source frame, never cached frame");+ check(pausedCached,"paused settings retain cached-frame preview");+ DestroyWindow(window);CoUninitialize();std::cout<<"failures="<<failures<<" (synthetic file replay, not physical capture)\n";return failures?1:0;+}diff --git a/tests/integration/PreviewGeometryTests.cpp b/tests/integration/PreviewGeometryTests.cppindex 8e695695..47b11322 100644--- a/tests/integration/PreviewGeometryTests.cpp+++ b/tests/integration/PreviewGeometryTests.cpp@@ -26,7 +26,8 @@ int wmain(int argc,wchar_t** argv){pipeline::EnhanceGraph::FrameOutputs out;ok=ok&&graph.process(f,0,true,out,1);struct Sample {int x,y,r,g,b;};auto test=[&](const char* name,engine::PreviewView view,int comparison,std::initializer_list<Sample> samples){- sink::RgbaImage image;bool pass=presenter.present(ctx,ring,graph,out.videoSlot,false,comparison,false,.5f,{},view)&&presenter.readPresentedFrameForTest(ctx,ring,image);+ const bool referencesValid=out.batch.count&&out.batch.frames[out.batch.count-1].lease&&out.batch.frames[out.batch.count-1].lease->referencesValid;+ sink::RgbaImage image;bool pass=presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparison,false,.5f,{},view)&&presenter.readPresentedFrameForTest(ctx,ring,image);pass=pass&&image.width==320&&image.height==240;if(pass)for(auto s:samples){auto* p=image.pixels.data()+(s.y*image.width+s.x)*4;pass=pass&&std::abs(int(p[0])-s.r)<=2&&std::abs(int(p[1])-s.g)<=2&&std::abs(int(p[2])-s.b)<=2;}if(pass)pass=sink::saveImage((dir/(std::string(name)+".png")).wstring(),image);@@ -37,5 +38,10 @@ int wmain(int argc,wchar_t** argv){if(ok)ok=test("pan",{2,.25f,.5f},0,{{280,60,255,0,0},{280,200,255,0,255}});if(ok)ok=test("reference",{2,.5f,.5f},1,{{40,10,255,0,0},{280,10,0,255,0}});if(ok)ok=test("reset",{},0,{{160,10,0,0,0},{280,80,0,255,0}});+ if(ok){+ for(int y=0;y<32;++y)for(int x=0;x<64;++x){auto* p=f->data[0]+y*f->linesize[0]+x*4;p[0]=0;p[1]=0;p[2]=255;p[3]=255;}+ pipeline::EnhanceGraph::FrameOutputs current;ok=graph.process(f,33.333,false,current,2,nullptr,false);+ if(ok){out=std::move(current);ok=test("invalid-reference",{},1,{{40,80,0,0,255},{280,160,0,0,255}});}+ }ring.drainQueue();out={};presenter.close();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok?0:1;}diff --git a/tests/integration/Yuy2ColorTests.cpp b/tests/integration/Yuy2ColorTests.cppnew file mode 100644index 00000000..72b2113b--- /dev/null+++ b/tests/integration/Yuy2ColorTests.cpp@@ -0,0 +1,56 @@+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/pipeline/ColorMetadata.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/engine/VideoPresenter.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/RuntimePaths.h"+#include <cmath>+#include <iostream>+extern "C" {+#include <libavutil/frame.h>+}+using namespace veyra;+int wmain(int argc,wchar_t**argv){+ bool nr=false,rgb=false,native4k=false,temporal=false,realtime=false;+ for(int i=1;i<argc;++i){nr|=wcscmp(argv[i],L"--nr")==0;rgb|=wcscmp(argv[i],L"--rgb")==0;native4k|=wcscmp(argv[i],L"--4k")==0;temporal|=wcscmp(argv[i],L"--temporal")==0;realtime|=wcscmp(argv[i],L"--realtime")==0;}+ nr|=temporal;+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 1;+ const unsigned w=native4k?3840:nr?1920:256,h=native4k?2160:nr?1080:64;+ HWND window=CreateWindowExW(0,L"STATIC",L"YUY2 contract",WS_POPUP,0,0,w,h,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ pipeline::EnhanceGraph graph(ctx,ring);engine::VideoPresenter presenter;pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.workWidth=w;gd.sourceHeight=gd.workHeight=h;gd.yuy2Input=!rgb;gd.rgbInput=rgb;gd.enableFg=false;gd.enableNr=nr;gd.enableNvofStandalone=nr;gd.noFeatures=!nr;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();+ if(realtime){+ if(!native4k||!nr)return 4;+ gd.nrWidth=gd.flowWidth=1920;gd.nrHeight=gd.flowHeight=1080;+ }+ if(!window||!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews())return 2;+ const unsigned expectedInternalWidth=realtime?1920:w,expectedInternalHeight=realtime?1080:h;+ if(graph.nrWidth()!=expectedInternalWidth||graph.nrHeight()!=expectedInternalHeight||graph.flowWidth()!=expectedInternalWidth||graph.flowHeight()!=expectedInternalHeight)return 4;+ AVFrame* f=av_frame_alloc();f->format=rgb?AV_PIX_FMT_BGRA:AV_PIX_FMT_YUYV422;f->width=w;f->height=h;if(av_frame_get_buffer(f,32)<0)return 3;+ int failures=0;unsigned frameId=0;+ for(unsigned index=0;index<(temporal?8u:nr?2u:4u);++index){+ const bool full=!temporal&&(nr?index>0:index>=2),hd=temporal||(!nr&&(index%2));+ for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;x+=2){auto* p=f->data[0]+ptrdiff_t(y)*f->linesize[0]+x*2;p[0]=uint8_t((x+(temporal?index*2:0))%256);p[2]=uint8_t((x+1+(temporal?index*2:0))%256);p[1]=y%4==0?128:y%4==1?16:y%4==2?240:90;p[3]=y%4==0?128:y%4==1?240:y%4==2?16:180;}+ if(rgb)for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){auto* p=f->data[0]+ptrdiff_t(y)*f->linesize[0]+x*4;p[0]=uint8_t(x%256);p[1]=uint8_t((x+37)%256);p[2]=uint8_t((x+129)%256);p[3]=255;}+ pipeline::ColorDescription color;color.pixelFormat=pipeline::SourcePixelFormat::Yuy2;color.range=full?pipeline::ColorRange::Full:pipeline::ColorRange::Limited;color.matrix=hd?pipeline::YuvMatrix::BT709:pipeline::YuvMatrix::BT601;color.transfer=pipeline::TransferFunction::SRGB;+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage image,display;+ if(rgb)color.pixelFormat=pipeline::SourcePixelFormat::Bgra8;+ const double ptsMs=frameId*100.0;++frameId;+ bool ok=graph.process(f,ptsMs,!temporal||index==0,out,frameId,&color)&&sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);+ int error=0,displayError=0;uint64_t sum=0;+ if(ok){for(unsigned y=0;y<h;++y)for(unsigned x=0;x<w;++x){auto* p=f->data[0]+ptrdiff_t(y)*f->linesize[0]+(x/2)*4;const double Y=(double(p[(x&1)?2:0])-(full?0:16))/(full?255:219);const double U=(double(p[1])-128)/(full?255:224),V=(double(p[3])-128)/(full?255:224);const double kr=hd?.2126:.299,kb=hd?.0722:.114;double expected[3]={Y+2*(1-kr)*V,0,Y+2*(1-kb)*U};expected[1]=(Y-kr*expected[0]-kb*expected[2])/(1-kr-kb);+ if(rgb){const auto* bgra=f->data[0]+ptrdiff_t(y)*f->linesize[0]+x*4;for(unsigned c=0;c<3;++c)expected[c]=(double(bgra[2-c])-(full?0:16))/(full?255:219);}+ for(unsigned c=0;c<3;++c){const int actual=image.pixels[(size_t(y)*w+x)*4+c];sum+=actual;error=std::max(error,std::abs(actual-int(std::lround(std::clamp(expected[c],0.0,1.0)*255))));}}+ ok=sum>0&&(nr?graph.metrics().nrEvaluateCount==frameId:error<=1);+ }+ if(ok)ok=presenter.present(ctx,ring,graph,out.videoSlot,false)&&presenter.readPresentedFrameForTest(ctx,ring,display);+ if(ok){ok=image.pixels.size()==display.pixels.size();if(ok)for(size_t i=0;i<image.pixels.size();++i)displayError=std::max(displayError,std::abs(int(image.pixels[i])-int(display.pixels[i])));ok=ok&&displayError<=1;}+ std::cout<<(rgb?"RGB_COLOR":"YUY2_COLOR")<<" extent="<<w<<"x"<<h<<" nrExtent="<<graph.nrWidth()<<"x"<<graph.nrHeight()<<" flowExtent="<<graph.flowWidth()<<"x"<<graph.flowHeight()<<" full="<<full<<" hd="<<hd<<" nr="<<nr<<" sourceError="<<error<<" displayError="<<displayError<<" pass="<<ok<<std::endl;+ if(!ok)++failures;out={};+ }+ if(temporal){const auto metrics=graph.metrics();const bool ok=metrics.nvofExecuteCount>0&&metrics.nrMotionFrames>0;std::cout<<"YUY2_TEMPORAL nvof="<<metrics.nvofExecuteCount<<" nrMotion="<<metrics.nrMotionFrames<<" pass="<<ok<<std::endl;if(!ok)++failures;}+ ring.drainQueue();presenter.close();graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return failures?1:0;+}diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cppnew file mode 100644index 00000000..401de592--- /dev/null+++ b/tests/unit/CaptureColorContractTests.cpp@@ -0,0 +1,76 @@+#include "veyra/source/CaptureMediaType.h"+#include "veyra/source/NativeCaptureSink.h"+#include <iostream>+#include <vector>+#include <atomic>+using namespace veyra;+using Microsoft::WRL::ComPtr;+// Minimal upstream peer: the production input pin must validate its direction.+struct OutputPin final:IPin {+ std::atomic<ULONG> refs{1};+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** p)override{if(!p)return E_POINTER;*p=nullptr;if(id!=IID_IUnknown&&id!=IID_IPin)return E_NOINTERFACE;*p=this;AddRef();return S_OK;}+ ULONG STDMETHODCALLTYPE AddRef()override{return ++refs;}ULONG STDMETHODCALLTYPE Release()override{auto n=--refs;if(!n)delete this;return n;}+ HRESULT STDMETHODCALLTYPE Connect(IPin*,const AM_MEDIA_TYPE*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE ReceiveConnection(IPin*,const AM_MEDIA_TYPE*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE Disconnect()override{return S_OK;}+ HRESULT STDMETHODCALLTYPE ConnectedTo(IPin**)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE ConnectionMediaType(AM_MEDIA_TYPE*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryPinInfo(PIN_INFO*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* p)override{if(!p)return E_POINTER;*p=PINDIR_OUTPUT;return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryId(LPWSTR*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE*)override{return S_OK;}+ HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes**)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryInternalConnections(IPin**,ULONG*)override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE EndOfStream()override{return S_OK;}+ HRESULT STDMETHODCALLTYPE BeginFlush()override{return S_OK;}+ HRESULT STDMETHODCALLTYPE EndFlush()override{return S_OK;}+ HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double)override{return S_OK;}+};+int main(){+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);int failures=0;+ auto check=[&](bool pass,const char* name){std::cout<<(pass?"PASS ":"FAIL ")<<name<<'\n';if(!pass)++failures;};+ VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=4;vi.bmiHeader.biHeight=2;vi.bmiHeader.biBitCount=16;vi.bmiHeader.biSizeImage=24;vi.AvgTimePerFrame=166667;+ AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;type.subtype=MEDIASUBTYPE_YUY2;type.formattype=FORMAT_VideoInfo2;type.pbFormat=reinterpret_cast<BYTE*>(&vi);type.cbFormat=sizeof(vi);+ source::CaptureMediaLayout layout;check(source::captureMediaLayout(type,layout)&&layout.stride==12&&layout.rowBytes==8&&!layout.bottomUp,"VideoInfo2 YUY2 padded row contract");+ check(layout.color.transfer==pipeline::TransferFunction::SRGB&&layout.color.transferAssumed,"display referred default remains explicit assumption");+ AVFrame* frame=av_frame_alloc();frame->format=AV_PIX_FMT_YUYV422;frame->width=4;frame->height=2;av_frame_get_buffer(frame,32);+ std::vector<uint8_t> raw(24,0xee);for(int y=0;y<2;++y)for(int x=0;x<8;++x)raw[y*12+x]=uint8_t(y*32+x);+ check(source::copyCaptureSample(layout,raw.data(),raw.size(),*frame)&&frame->data[0][0]==0&&frame->data[0][frame->linesize[0]]==32,"YUY2 positive height is top down; exclude padding");+ check(!source::copyCaptureSample(layout,raw.data(),23,*frame),"reject short sample before any copy");+ vi.bmiHeader.biHeight=-2;check(source::captureMediaLayout(type,layout)&&!layout.bottomUp,"negative YUY2 also top down");vi.bmiHeader.biHeight=2;+ DXVA2_ExtendedFormat ext{};ext.NominalRange=DXVA2_NominalRange_0_255;ext.VideoTransferMatrix=DXVA2_VideoTransferMatrix_BT709;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;+ check(source::captureMediaLayout(type,layout)&&layout.color.range==pipeline::ColorRange::Full&&!layout.color.rangeAssumed&&layout.color.matrix==pipeline::YuvMatrix::BT709&&!layout.color.matrixAssumed,"honor explicit matrix and range");+ auto resolved=pipeline::resolveFrameColor(*frame,layout.color);check(resolved.transfer==pipeline::TransferFunction::SRGB&&resolved.transferAssumed&&resolved.range==pipeline::ColorRange::Full,"source contract survives graph resolution");+ ext.NominalRange=DXVA2_NominalRange_48_208;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;check(!source::captureMediaLayout(type,layout),"unsupported range fails closed");vi.dwControlFlags=0;+ vi.bmiHeader.biWidth=3;check(!source::captureMediaLayout(type,layout),"odd YUY2 width rejected");vi.bmiHeader.biWidth=4;+ vi.bmiHeader.biSizeImage=23;check(!source::captureMediaLayout(type,layout),"ambiguous byte pitch rejected");vi.bmiHeader.biSizeImage=24;+ ComPtr<IBaseFilter> filter;ComPtr<IPin> input,output;ComPtr<IMemInputPin> memory;ComPtr<IMemAllocator> allocator;+ output.Attach(new OutputPin);unsigned delivered=0;+ check(SUCCEEDED(source::createNativeCaptureSink(type,[&](IMediaSample* sample){BYTE* bytes=nullptr;sample->GetPointer(&bytes);++delivered;return bytes?S_OK:E_FAIL;},filter,input)),"create native sink (no SampleGrabber dependency)");+ check(filter&&SUCCEEDED(filter.As(&memory))&&input->ReceiveConnection(output.Get(),&type)==S_OK,"native input directly accepts VideoInfo2");+ vi.bmiHeader.biSizeImage=32;check(input->QueryAccept(&type)==S_FALSE,"connected pin rejects same-size incompatible stride");vi.bmiHeader.biSizeImage=24;+ check(input->QueryAccept(&type)==S_OK,"connected pin accepts equivalent type");+ if(memory){+ ALLOCATOR_PROPERTIES wanted{},actual{};check(memory->GetAllocatorRequirements(&wanted)==S_OK&&wanted.cbBuffer==24,"allocator size includes negotiated padding");+ bool ready=memory->GetAllocator(&allocator)==S_OK&&allocator->SetProperties(&wanted,&actual)==S_OK&&allocator->Commit()==S_OK;+ check(ready,"owned sample allocator");+ if(ready){ComPtr<IMediaSample> sample;allocator->GetBuffer(&sample,nullptr,nullptr,0);BYTE* bytes=nullptr;sample->GetPointer(&bytes);memcpy(bytes,raw.data(),24);sample->SetActualDataLength(24);+ check(memory->Receive(sample.Get())==VFW_E_WRONG_STATE&&delivered==0,"stopped sink does not invoke callback");filter->Run(0);+ sample->SetMediaType(&type);check(memory->Receive(sample.Get())==S_OK&&delivered==1,"initial repeated media type accepted");sample->SetMediaType(nullptr);+ input->BeginFlush();check(memory->Receive(sample.Get())==S_FALSE&&delivered==1,"flush does not deliver");input->EndFlush();+ sample->SetActualDataLength(23);check(FAILED(memory->Receive(sample.Get()))&&delivered==1,"short native sample rejected");sample->SetActualDataLength(24);+ vi.bmiHeader.biWidth=8;sample->SetMediaType(&type);check(memory->Receive(sample.Get())==VFW_E_INVALIDMEDIATYPE&&delivered==1,"dynamic mode cannot reuse stale layout");sample->SetMediaType(nullptr);vi.bmiHeader.biWidth=4;+ check(memory->Receive(sample.Get())==S_OK&&delivered==2,"callback recovers for unchanged sample");+ filter->Stop();sample.Reset();allocator->Decommit();+ }+ check(input->Disconnect()==S_OK,"disconnect releases allocator and upstream peer");+ }+ memory.Reset();input.Reset();filter.Reset();output.Reset();allocator.Reset();av_frame_free(&frame);+ // NV12 uses separate planes; padding must not be copied into the UV plane.+ type.subtype=MEDIASUBTYPE_NV12;vi.bmiHeader.biHeight=4;vi.bmiHeader.biSizeImage=36;+ check(source::captureMediaLayout(type,layout)&&layout.stride==6&&layout.sampleBytes==36,"NV12 plane pitch derived without RGB conversion");+ frame=av_frame_alloc();frame->format=AV_PIX_FMT_NV12;frame->width=4;frame->height=4;av_frame_get_buffer(frame,32);raw.assign(36,0xee);for(int y=0;y<6;++y)for(int x=0;x<4;++x)raw[y*6+x]=uint8_t(y*10+x);+ check(source::copyCaptureSample(layout,raw.data(),raw.size(),*frame)&&frame->data[1][0]==40&&frame->data[1][frame->linesize[1]]==50,"NV12 UV offset respects input stride");av_frame_free(&frame);+ type.subtype=MEDIASUBTYPE_RGB32;vi.bmiHeader.biHeight=2;vi.bmiHeader.biSizeImage=32;check(source::captureMediaLayout(type,layout)&&layout.bottomUp&&layout.rowBytes==16,"RGB DIB keeps bottom-up compatibility");+ CoUninitialize();std::cout<<"failures="<<failures<<'\n';return failures?1:0;+}diff --git a/tests/unit/LivePresentationTimingTests.cpp b/tests/unit/LivePresentationTimingTests.cppindex 515ee1fd..867e809d 100644--- a/tests/unit/LivePresentationTimingTests.cpp+++ b/tests/unit/LivePresentationTimingTests.cpp@@ -1,5 +1,8 @@#include "veyra/engine/LivePresentationTiming.h"+#include "veyra/engine/LivePresentationResetPolicy.h"#include "veyra/source/CaptureTiming.h"+#include "veyra/engine/CaptureHalfRate.h"+#include "veyra/engine/FrameRateWindow.h"#include <cmath>#include <limits>#include <cstdio>@@ -7,7 +10,40 @@ int main(){using veyra::engine::livePairHoldMs;int failed=0;auto check=[&](bool ok,const char* label){printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failed;};+ using veyra::engine::CaptureHalfRate;+ for(double fps:{60.0,60000.0/1001.0}){+ CaptureHalfRate sampler;const auto dt=int64_t(std::llround(10000000.0/fps));int kept=0;bool ordered=true;+ for(int i=0;i<600;++i){const bool accepted=sampler.accept(i*dt+(i%3-1)*1000,dt,false);kept+=accepted;ordered&=accepted==(i%2==0);}+ check(kept==300&&ordered,"60/59.94 transport selects one original-PTS frame per pair despite jitter");+ check(sampler.accept(0,dt,false),"backward timestamp reanchors capture sampling");+ check(sampler.accept(dt,dt,true),"history boundary cannot be swallowed by sampling");+ sampler.reset();check(sampler.accept(dt,dt,false),"reset accepts first new frame immediately");+ }+ check(!CaptureHalfRate::supported(30)&&!CaptureHalfRate::supported(18)&&!CaptureHalfRate::supported(120)&&CaptureHalfRate::supported(59.94),"60-to-30 setting does not halve other transport modes");+ veyra::engine::FrameRateWindow rate;rate.reset(0);+ for(int i=1;i<=60;++i)rate.complete(i*166666);+ check(std::abs(rate.rate(10000000)-60)<.01,"one second counts 60 actual completion events");+ check(rate.rate(15000000)==30&&rate.rate(20000000)==0,"stalled GPU rate decays to zero without new events");+ rate.reset(20000000);check(rate.rate(21000000)==0,"revision reset discards old FPS");+ for(int i=1;i<=30;++i)rate.complete(20000000+i*333333);+ check(std::abs(rate.rate(30000000)-30)<.01,"30 real completions are not multiplied by FG");+ rate.reset(0);for(int i=1;i<=1000;++i)rate.complete(i*10000);+ check(rate.rate(10000000)==1000,"completion rate has no 60 or 120fps cap");using veyra::source::captureDuration;using veyra::engine::liveSourceInterval100ns;+ using veyra::source::captureDiscontinuity;+ check(!captureDiscontinuity(true,false,false,true,1,1+1.0/60,60),"continuous callbacks remain continuous while mailbox is overwritten");+ check(captureDiscontinuity(true,true,false,true,1,1+1.0/60,60),"driver discontinuity survives mailbox overwrite");+ check(!captureDiscontinuity(false,true,false,true,1,1+1.0/60,60),"consumed driver discontinuity does not leak to next packet");+ check(captureDiscontinuity(false,false,true,true,1,1+1.0/60,60),"driver discontinuity retained at normal cadence");+ check(captureDiscontinuity(false,false,false,true,1,0.5,60),"backwards callback clock remains hard discontinuity");+ check(captureDiscontinuity(false,false,false,true,1,1.2,60),"callback gap remains hard discontinuity");+ constexpr auto drop=static_cast<veyra::pipeline::FrameFlags>(veyra::pipeline::FrameFlagBits::Drop);+ constexpr auto resize=static_cast<veyra::pipeline::FrameFlags>(veyra::pipeline::FrameFlagBits::Resize);+ check(veyra::pipeline::breaksHistory(drop),"mailbox overwrite resets temporal history");+ check(!veyra::engine::presentationDrainRequired(false,drop),"mailbox overwrite retains queued real presentation");+ check(veyra::engine::presentationDrainRequired(false,resize),"resize drains resource-bound presentation");+ check(!veyra::engine::generatedPresentationCurrent(4,5),"history reset suppresses queued generated frame");+ check(veyra::engine::generatedPresentationCurrent(5,5),"current generation remains presentable");check(veyra::pipeline::FramePacket{}.duration.isUnknown(),"unset packet duration is unknown, not known zero");check(captureDuration(100,166767,true,333333).to100ns()==166667,"sample duration wins over nominal");check(captureDuration(100,100,false,333333).to100ns()==333333,"missing sample stop uses nominal30fps");diff --git a/tests/unit/PresentationWorkerTests.cpp b/tests/unit/PresentationWorkerTests.cppnew file mode 100644index 00000000..90c25b7b--- /dev/null+++ b/tests/unit/PresentationWorkerTests.cpp@@ -0,0 +1,22 @@+#include "veyra/engine/PresentationWorker.h"+#include "veyra/engine/TimingWindow.h"+#include <future>+#include <iostream>+using namespace std::chrono_literals;+int main(){+ int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<'\n';if(!pass)++failures;};+ std::promise<void> entered;auto enteredFuture=entered.get_future();std::atomic<unsigned> ran{0};std::atomic<bool> released{false};+ veyra::engine::PresentationWorker worker([]{return false;});+ check(worker.push([&](const auto& cancelled){entered.set_value();while(!cancelled())std::this_thread::sleep_for(1ms);released=true;return true;}),"queue active presentation");+ check(enteredFuture.wait_for(1s)==std::future_status::ready,"worker starts independently of producer");+ check(worker.push([&](const auto&){++ran;return true;}),"next batch can queue while active job sleeps");+ check(!worker.push([](const auto&){return true;}),"two-batch capacity includes active lease");+ worker.cancelAndDrain();check(released&&ran==0,"cancel waits for active callback and drops queued job");+ std::promise<void> next;auto nextFuture=next.get_future();check(worker.waitForSlot()&&worker.push([&](const auto&){next.set_value();return true;}),"producer resumes after cancellation");+ check(nextFuture.wait_for(1s)==std::future_status::ready,"new epoch job executes");worker.cancelAndDrain();+ check(worker.push([](const auto&){return false;}),"inject presentation failure");+ auto deadline=std::chrono::steady_clock::now()+1s;while(!worker.failed()&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(1ms);+ check(worker.failed()&&!worker.waitForSlot(),"failure propagates without blocking producer");+ veyra::engine::TimingWindow timing;for(unsigned i=0;i<100;++i)timing.add(i);check(timing.p95()==94,"percentile order statistic");timing.clear();timing.add(6);check(timing.p95()==6,"reset removes prior 94ms window immediately");+ return failures?1:0;+}diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex 785fa165..eb3d34fb 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -13,7 +13,11 @@ int main(){using namespace veyra;int failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};auto p=pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Realtime,false);- check(p.base==pipeline::Extent{3840,2160}&&p.nr==pipeline::Extent{1920,1080}&&p.output==p.base,"SR4K preserves base; NR1080");+ check(p.base==pipeline::Extent{3840,2160}&&p.nr==pipeline::Extent{1920,1080}&&p.flow==pipeline::Extent{1920,1080}&&p.output==p.base,"SR4K preserves base; NR and flow remain source1080");+ p=pipeline::ResolutionPlan::make({3840,2160},false,pipeline::NrSizePolicy::Realtime,false);+ check(p.nr==pipeline::Extent{1920,1080}&&p.flow==p.nr,"realtime native4K bounds NR and source-space flow to 1080");+ p=pipeline::ResolutionPlan::make({3840,2160},false,pipeline::NrSizePolicy::Native,false);+ check(p.nr==p.source&&p.flow==p.source,"native mode retains native4K NR and flow");p=pipeline::ResolutionPlan::make({3840,2160},true,pipeline::NrSizePolicy::Realtime,true);check(!p.srApplied&&p.nr==p.base,"native export and 1:1 SR bypass");engine::EnhancementSettings s;check(s.validate().empty(),"default settings valid");diff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex 7427a810..2da18138 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -4,6 +4,7 @@int main(int argc,char** argv){if(argc!=2)return 2;using namespace veyra::engine;const std::filesystem::path p=argv[1];PresetStore a(p);bool ok=a.load();EnhancementSettings s;s.videoSrQuality=2;s.frameGenerationBackend=FrameGenerationBackend::Fruc;s.protection.enabled=true;s.protection.featherPixels=3.5f;s.protection.regions[0]={.1f,.2f,.7f,.8f};s.protection.regions[3]={0,0,1,1};s.model.intensity=.375f;s.model.skin=1.5f;s.residual.darken=1.2f;s.multiplier=4;s.flow=FlowQuality::Quality;s.content=ContentRate::Fps50;s.nrPolicy=veyra::pipeline::NrSizePolicy::Native;ok=ok&&a.put(L"test",s)&&a.setDefault(0)&&!a.put(L"test",s);PresetStore b(p);ok=ok&&b.load()&&b.defaultSettings()==s&&b.rename(0,L"renamed")&&b.defaultSettings()==s;auto badBackend=s;badBackend.frameGenerationBackend=static_cast<FrameGenerationBackend>(2);ok=ok&&!b.put(L"invalid backend",badBackend);+ auto half=s;half.content=ContentRate::Capture60To30;ok=ok&&b.put(L"capture half rate",half);PresetStore halfReload(p);ok=ok&&halfReload.load()&&halfReload.entries().back().settings.content==ContentRate::Capture60To30&&b.erase(1);auto badSr=s;badSr.videoSrQuality=5;ok=ok&&!b.put(L"invalid video SR",badSr);auto invalid=s;invalid.model.tone=9;ok=ok&&!b.put(L"bad",invalid)&&b.entries().size()==1&&b.erase(0)&&b.entries().empty();auto badRegion=s;badRegion.protection.regions[0].left=2;ok=ok&&!b.put(L"invalid region",badRegion);diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cppindex b4c4eddc..54dc8af4 100644--- a/tests/unit/UiContractTests.cpp+++ b/tests/unit/UiContractTests.cpp@@ -29,6 +29,8 @@ int wmain(int argc,wchar_t** argv){try{require(ResolutionPlan::make({1080,1920},true,NrSizePolicy::Native,true).output==Extent{1214,2160},"portrait SR even dimensions");require(!ResolutionPlan::make({2880,2160},true,NrSizePolicy::Native,true).srApplied,"already maximum edge skips SR");require(ResolutionPlan::make({1920,1080},true,NrSizePolicy::Realtime,false).output==Extent{3840,2160},"16:9 SR unchanged");+ require(ResolutionPlan::make({3840,2160},false,NrSizePolicy::Realtime,false).flow==Extent{1920,1080},"realtime 4K uses bounded flow extent");+ require(ResolutionPlan::make({3840,2160},false,NrSizePolicy::Native,false).flow==Extent{3840,2160},"native 4K retains native flow extent");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");diff --git a/tools/capture_color_probe/main.cpp b/tools/capture_color_probe/main.cppnew file mode 100644index 00000000..1feda6ed--- /dev/null+++ b/tools/capture_color_probe/main.cpp@@ -0,0 +1,57 @@+// Explicit diagnostic readback. Never used by normal capture/playback.+#include "veyra/source/CaptureCardSource.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/engine/VideoPresenter.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/sink/ImageExportSink.h"+#include "veyra/Log.h"+#include <filesystem>+#include <fstream>+#include <iostream>+#include <chrono>+extern "C" {+#include <libavutil/frame.h>+}+using namespace veyra;+int wmain(int argc,wchar_t**argv){+ if(argc<3){std::cerr<<"capture:device:format:audio output-directory [--legacy-rgb]\n";return 2;}+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ const std::filesystem::path dir(argv[2]);std::filesystem::create_directories(dir);+ Logger::instance().openFile((dir/"probe.log").wstring());+ source::SourceOpenDesc desc;desc.path=argv[1];desc.legacyCaptureRgbForDiagnostic=argc>3&&wcscmp(argv[3],L"--legacy-rgb")==0;+ source::CaptureCardSource source;if(!source.configure(desc))return 3;+ const auto info=source.info();+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 4;+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;+ gd.sourceWidth=gd.workWidth=info.width;gd.sourceHeight=gd.workHeight=info.height;+ gd.rgbInput=info.color.pixelFormat==pipeline::SourcePixelFormat::Bgra8;+ gd.yuy2Input=info.color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;+ gd.enableNr=gd.enableFg=false;gd.noFeatures=true;+ const HWND window=CreateWindowExW(0,L"STATIC",L"Veyra color diagnostic",WS_POPUP,0,0,info.width,info.height,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);+ engine::VideoPresenter presenter;+ if(!window||!graph.initialize(gd)||!presenter.open(ctx,window,graph)||!graph.createViews()||!source.start())return 5;+ const AVFrame* frame=nullptr;pipeline::FramePacket packet;+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(8);+ unsigned frames=0;while(std::chrono::steady_clock::now()<deadline&&frames<20){+ const auto result=source.read(packet,&frame);+ if(result==source::SourceReadStatus::Error)return 6;+ if(result==source::SourceReadStatus::Frame)++frames;+ }+ if(frames<20||!frame)return 7;+ const unsigned rowBytes=info.width*(frame->format==AV_PIX_FMT_YUYV422?2:frame->format==AV_PIX_FMT_NV12?1:4);+ std::ofstream raw(dir/"source.raw",std::ios::binary);+ for(unsigned y=0;y<info.height;++y)raw.write(reinterpret_cast<const char*>(frame->data[0]+ptrdiff_t(y)*frame->linesize[0]),rowBytes);+ if(frame->format==AV_PIX_FMT_NV12)for(unsigned y=0;y<info.height/2;++y)raw.write(reinterpret_cast<const char*>(frame->data[1]+ptrdiff_t(y)*frame->linesize[1]),info.width);+ raw.close();+ pipeline::EnhanceGraph::FrameOutputs out;sink::RgbaImage gpu,display;+ const bool ok=graph.process(frame,packet.pts.toDouble()*1000,true,out,packet.sequence,&packet.colorInfo)&&+ sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),gpu)&&sink::saveImage((dir/"gpu.png").wstring(),gpu)&&+ presenter.present(ctx,ring,graph,out.videoSlot,false)&&presenter.readPresentedFrameForTest(ctx,ring,display)&&sink::saveImage((dir/"present.png").wstring(),display);+ int error=-1;if(ok&&gpu.pixels.size()==display.pixels.size()){error=0;for(size_t i=0;i<gpu.pixels.size();++i)error=std::max(error,std::abs(int(gpu.pixels[i])-int(display.pixels[i])));}+ const auto metrics=source.metrics();+ std::ofstream report(dir/"result.json");report<<"{\"success\":"<<(ok?"true":"false")<<",\"width\":"<<info.width<<",\"height\":"<<info.height<<",\"avPixelFormat\":"<<frame->format<<",\"rowBytes\":"<<rowBytes<<",\"matrix\":"<<int(info.color.matrix)<<",\"range\":"<<int(info.color.range)<<",\"transfer\":"<<int(info.color.transfer)<<",\"presentMaxError8\":"<<error<<",\"callbackFps\":"<<metrics.callbackFps<<",\"received\":"<<metrics.received<<",\"nrEvaluations\":"<<graph.metrics().nrEvaluateCount<<"}\n";report.close();+ std::cout<<"CAPTURE_COLOR success="<<ok<<" presentMaxError8="<<error<<" format="<<frame->format<<" size="<<info.width<<"x"<<info.height<<" fps="<<metrics.callbackFps<<"\n";+ source.close();out={};ring.drainQueue();presenter.close();graph.shutdown();ring.shutdown();ctx.shutdown();DestroyWindow(window);CoUninitialize();return ok?0:8;+}