Skip to content

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++

Repair user issue candidate and preserve SDR no-effects color values

Veyra Goal Agent8812e9419a5e
diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cpp
index fa9244bd..9274ab6c 100644
--- a/apps/veyra/SettingsWindow.cpp
+++ b/apps/veyra/SettingsWindow.cpp
@@ -167,7 +167,7 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.
body=CreateWindowExW(WS_EX_CONTROLPARENT,bodyClass.lpszClassName,L"滚动参数",WS_CHILD|WS_VISIBLE|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,88,300,300,h,nullptr,bodyClass.hInstance,nullptr);
add(L"BUTTON",L"实验性 NVIDIA NR 增强",200,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,12,-1,36);
add(L"BUTTON",L"超分辨率",201,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,56,-1,36);
- combo(203,0,104,{L"实时NR · 约1080内部处理",L"原生NR · 高性能成本"});
+ combo(203,0,104,{L"1080p NR · 实时默认",L"原生NR · 高性能成本",L"480p NR",L"720p NR",L"900p NR",L"1440p NR"});
add(L"STATIC",L"模型参数",1100,0,0,12,146,-1,24);
for(int i=0;i<12;++i){const int y=174+i*62+(i>=7?32:0);add(L"STATIC",labels[i],1000+i,0,0,12,y,176,28);
if(i>=4&&i<=6){const int group=i-4,count=group==0?3:2;for(int j=0;j<count;++j){const auto title=group==0?std::to_wstring(j):j==0?std::wstring(L"关闭"):std::wstring(L"开启");button(title.c_str(),700+group*10+j,0,12+j*88,y+28,80);}continue;}
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index f54de724..bdb39a7e 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -122,7 +122,12 @@ LRESULT CALLBACK interaction(HWND h,UINT m,WPARAM w,LPARAM l,UINT_PTR id,DWORD_P
if(id==VideoSurface&&(m==WM_MBUTTONUP||m==WM_CAPTURECHANGED)){panning=false;if(m==WM_MBUTTONUP&&GetCapture()==h)ReleaseCapture();}
if(id==VideoSurface&&m==WM_SETCURSOR&&full&&!fullControls){SetCursor(nullptr);return TRUE;}
if(id==VideoSurface&&m==WM_ERASEBKGND)return 1;
- if(id==VideoSurface&&m==WM_PAINT){veyra::ui::PaintBuffer paint(h);veyra::ui::opaqueBlack(paint.dc,paint.rect);return 0;}
+ if(id==VideoSurface&&m==WM_PAINT){
+ const auto state=engine.snapshot();
+ if(state.running&&state.frames){PAINTSTRUCT paint{};BeginPaint(h,&paint);EndPaint(h,&paint);}
+ else{veyra::ui::PaintBuffer paint(h);veyra::ui::opaqueBlack(paint.dc,paint.rect);}
+ return 0;
+ }
if(id==OriginalHold){if(m==WM_LBUTTONDOWN){holdOriginal=true;SetCapture(h);updateComparison();return 0;}if(m==WM_LBUTTONUP||m==WM_CAPTURECHANGED){holdOriginal=false;if(GetCapture()==h)ReleaseCapture();updateComparison();return 0;}}
if(id==VideoSurface&&compareMode==2&&(m==WM_LBUTTONDOWN||m==WM_MOUSEMOVE)&&(m==WM_LBUTTONDOWN||(w&MK_LBUTTON))){if(m==WM_LBUTTONDOWN)SetCapture(h);RECT r{};GetClientRect(h,&r);auto extent=engine.snapshot().metrics.resolution.output;auto view=engine.previewView();float contentWidth=float(r.right);if(extent.width&&extent.height)contentWidth=std::min(float(r.right),float(r.bottom)*extent.width/extent.height);contentWidth*=view.zoom;float left=r.right*.5f-contentWidth*view.centerX;compareSplit=std::clamp((float(GET_X_LPARAM(l))-left)/std::max(1.0f,contentWidth),0.0f,1.0f);updateComparison();return 0;}
if(id==VideoSurface&&m==WM_LBUTTONUP&&GetCapture()==h){ReleaseCapture();return 0;}
@@ -526,6 +531,16 @@ wc.hIconSm=static_cast<HICON>(LoadImageW(instance,MAKEINTRESOURCEW(IDI_VEYRA),IM
RegisterClassExW(&wc);
auto hwnd=CreateWindowExW(0,wc.lpszClassName,L"Veyra — 本地实验版",ShellStyle,CW_USEDEFAULT,CW_USEDEFAULT,std::min(MulDiv(uiPreferences.width,GetDpiForSystem(),96),GetSystemMetrics(SM_CXSCREEN)),std::min(MulDiv(uiPreferences.height,GetDpiForSystem(),96),GetSystemMetrics(SM_CYSCREEN)-40),nullptr,nullptr,instance,nullptr);if(!hwnd)return 1;if(uiPreferences.positioned&&smokeSeconds<=0){RECT target{uiPreferences.x,uiPreferences.y,uiPreferences.x+MulDiv(uiPreferences.width,GetDpiForSystem(),96),uiPreferences.y+MulDiv(uiPreferences.height,GetDpiForSystem(),96)};MONITORINFO mi{sizeof(mi)};GetMonitorInfoW(MonitorFromRect(&target,MONITOR_DEFAULTTONEAREST),&mi);int width=std::min(target.right-target.left,mi.rcWork.right-mi.rcWork.left),height=std::min(target.bottom-target.top,mi.rcWork.bottom-mi.rcWork.top);SetWindowPos(hwnd,nullptr,std::clamp(target.left,mi.rcWork.left,mi.rcWork.right-width),std::clamp(target.top,mi.rcWork.top,mi.rcWork.bottom-height),width,height,SWP_NOZORDER|SWP_NOACTIVATE);}CheckDlgButton(hwnd,Nr,initialOptions.nr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Sr,initialOptions.sr?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Fg,initialOptions.fg?BST_CHECKED:BST_UNCHECKED);CheckDlgButton(hwnd,Realtime,initialOptions.realtime?BST_CHECKED:BST_UNCHECKED);ShowWindow(hwnd,show);MSG msg{};while(GetMessageW(&msg,nullptr,0,0)>0){if(full&&GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&(msg.message==WM_MOUSEMOVE||msg.message==WM_LBUTTONDOWN||msg.message==WM_KEYDOWN)){static POINT previous{-9999,-9999};POINT now{};GetCursorPos(&now);if(msg.message!=WM_MOUSEMOVE||now.x!=previous.x||now.y!=previous.y)pointerActivity();previous=now;}if(GetAncestor(msg.hwnd,GA_ROOT)==hwnd&&(msg.message==WM_KEYDOWN||msg.message==WM_KEYUP||msg.message==WM_SYSKEYDOWN)){
wchar_t focusedClass[32]{};GetClassNameW(GetFocus(),focusedClass,32);const bool editing=_wcsicmp(focusedClass,L"Edit")==0||_wcsicmp(focusedClass,L"ComboBox")==0;
+const bool adjustingSlider=_wcsicmp(focusedClass,TRACKBAR_CLASSW)==0&&GetFocus()!=seekBar;
+if(!editing&&!adjustingSlider&&msg.message==WM_KEYDOWN&&(msg.wParam==VK_LEFT||msg.wParam==VK_RIGHT)&&
+ !(GetKeyState(VK_CONTROL)&0x8000)&&!(GetKeyState(VK_MENU)&0x8000)){
+ const auto state=engine.snapshot();
+ if(state.running&&!state.capture&&!state.image&&state.duration>0){
+ const double origin=state.seekPresented<state.seekRequested?state.seekTarget:state.position;
+ engine.seek(std::clamp(origin+(msg.wParam==VK_RIGHT?10.0:-10.0),0.0,state.duration));
+ if(full)pointerActivity();continue;
+ }
+}
if(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='O'){SendMessageW(hwnd,WM_COMMAND,Open,0);continue;}
if(!editing&&msg.message==WM_KEYDOWN&&(GetKeyState(VK_CONTROL)&0x8000)&&msg.wParam=='E'){if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspector(3);continue;}
const bool key=(!editing)&&(msg.wParam==VK_F11||msg.wParam==VK_ESCAPE||(msg.wParam==VK_SPACE&&(GetFocus()==hwnd||GetFocus()==video))||msg.wParam=='V'||(msg.wParam==VK_RETURN&&msg.message==WM_SYSKEYDOWN));if(key){SendMessageW(hwnd,msg.message,msg.wParam,msg.lParam);continue;}}
diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cpp
index 47241ab7..ae0136d6 100644
--- a/apps/veyra/ui/CapturePanel.cpp
+++ b/apps/veyra/ui/CapturePanel.cpp
@@ -1,6 +1,9 @@
#include "CapturePanel.h"
#include "Theme.h"
#include "SettingHelp.h"
+#include "CapturePreferenceStore.h"
+#include "veyra/RuntimePaths.h"
+#include "veyra/Log.h"
#include "veyra/source/CaptureCardSource.h"
#include <future>
#include <format>
@@ -8,16 +11,26 @@ namespace veyra::ui {
namespace {
HWND window=nullptr;HFONT font=nullptr;std::function<void(const std::wstring&)> start;
struct Query {int device=-1;std::vector<source::CaptureDevice> video,audio;std::vector<source::CaptureFormat> formats;};
-std::future<Query> pending;bool busy=false;int queriedDevice=-1;ULONGLONG queryStarted=0;
+std::future<Query> pending;bool busy=false,refreshAfterQuery=false;int queriedDevice=-1;ULONGLONG queryStarted=0;
std::vector<source::CaptureFormat> formats;
std::vector<source::CaptureDevice> videoDevices,audioDevices;
+CapturePreferences remembered;
std::function<bool()> readSdr;std::function<bool(bool)> setSdr;
void rebuildAudioList(HWND h,int device){
SendDlgItemMessageW(h,3,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(L"不监听音频"));
const bool videoSelected=device>=0&&size_t(device)<videoDevices.size();
if(videoSelected)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(videoDevices[size_t(device)].hasEmbeddedAudio?L"使用视频设备内置音频(已检测)":L"尝试视频设备内置音频"));
for(auto& audio:audioDevices){const auto label=std::format(L"[{}] {}",audio.wasapi?L"WASAPI":L"DirectShow",audio.name);SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(label.c_str()));}
- SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);
+ int restore=0;
+ if(videoSelected&&videoDevices[size_t(device)].path==remembered.videoPath){
+ if(remembered.audioMode==source::kCaptureAudioFromVideoDevice)restore=1;
+ else if(!remembered.audioPath.empty()){
+ restore=-1;
+ for(size_t i=0;i<audioDevices.size();++i)
+ if(audioDevices[i].path==remembered.audioPath&&audioDevices[i].wasapi==(remembered.audioMode==source::kCaptureAudioWasapi))restore=int(i)+2;
+ }
+ }
+ SendDlgItemMessageW(h,3,CB_SETCURSEL,restore,0);
}
int selectedAudio(HWND h,int device){
const int selection=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0));if(selection<=0)return source::kCaptureAudioDisabled;
@@ -32,6 +45,8 @@ void query(int device){if(busy)return;busy=true;queriedDevice=device;queryStarte
void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,412,412,14,84,344,154,254,224,294};for(int id=1;id<=12;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,(id<=3||id==10)?180:id==8?56:id==4||id==5?36:24),TRUE);}}
LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar_t* cls,const wchar_t* label,int id,DWORD style){auto c=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,0,0,1,1,h,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,WPARAM(font),TRUE);themeControl(c);};
+ remembered=CapturePreferenceStore(runtime::localDataDirectory()).load();
+ refreshAfterQuery=busy;
for(int i=1;i<=3;++i)add(L"COMBOBOX",L"",i,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);
add(L"COMBOBOX",L"",10,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);add(L"STATIC",L"输入颜色(变更需重连)",11,0);
for(auto name:{L"自动识别 SDR / HDR · 设备元数据",L"手动 HDR10 / PQ · BT.2020",L"手动 HLG · BT.2020 / 1000nit参考"})SendDlgItemMessageW(h,10,CB_ADDSTRING,0,LPARAM(name));SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);
@@ -44,20 +59,32 @@ case WM_TIMER:
SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
if(busy&&pending.wait_for(std::chrono::seconds(0))==std::future_status::ready){
auto result=pending.get();busy=false;EnableWindow(GetDlgItem(h,5),TRUE);EnableWindow(GetDlgItem(h,1),TRUE);
+ if(refreshAfterQuery){refreshAfterQuery=false;query(-1);return 0;}
if(result.device<0){
videoDevices=std::move(result.video);audioDevices=std::move(result.audio);
SendDlgItemMessageW(h,1,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);formats.clear();
for(auto& video:videoDevices)SendDlgItemMessageW(h,1,CB_ADDSTRING,0,LPARAM(video.name.c_str()));
if(!videoDevices.empty()){
- SendDlgItemMessageW(h,1,CB_SETCURSEL,0,0);rebuildAudioList(h,0);query(0);
+ int restore=remembered.videoPath.empty()?0:-1;
+ for(size_t i=0;i<videoDevices.size();++i)if(videoDevices[i].path==remembered.videoPath)restore=int(i);
+ SendDlgItemMessageW(h,1,CB_SETCURSEL,restore,0);rebuildAudioList(h,restore);
+ if(restore>=0)query(restore);else SetDlgItemTextW(h,8,L"上次采集设备未连接。插回后刷新,或手动选择其他设备。");
}else{
rebuildAudioList(h,-1);SetDlgItemTextW(h,8,L"未找到采集设备。连接后点击刷新。");
}
}else{
formats=std::move(result.formats);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);
for(auto& format:formats)SendDlgItemMessageW(h,2,CB_ADDSTRING,0,LPARAM(format.label.c_str()));
- if(!formats.empty())SendDlgItemMessageW(h,2,CB_SETCURSEL,0,0);EnableWindow(GetDlgItem(h,4),!formats.empty());
+ int restore=formats.empty()?-1:0;
+ const bool sameDevice=size_t(result.device)<videoDevices.size()&&videoDevices[size_t(result.device)].path==remembered.videoPath;
+ if(sameDevice&&!remembered.formatKey.empty()){
+ restore=-1;for(size_t i=0;i<formats.size();++i)if(formats[i].key==remembered.formatKey)restore=int(i);
+ SendDlgItemMessageW(h,10,CB_SETCURSEL,remembered.colorOverride,0);
+ }else SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);
+ SendDlgItemMessageW(h,2,CB_SETCURSEL,restore,0);EnableWindow(GetDlgItem(h,4),restore>=0);
SetDlgItemTextW(h,8,formats.empty()?L"未读到有效的4K以内采集格式,或设备正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");
+ if(!formats.empty()&&restore<0)SetDlgItemTextW(h,8,L"上次格式已不可用,请重新选择格式。");
+ if(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0)==CB_ERR){EnableWindow(GetDlgItem(h,4),FALSE);SetDlgItemTextW(h,8,L"上次音频设备未连接。请选择音频设备,或明确选择不监听音频。");}
}
}else if(busy&&GetTickCount64()-queryStarted>5000)SetDlgItemTextW(h,8,L"设备查询耗时较长。可以关闭此面板,当前播放不受影响。");
return 0;
@@ -68,17 +95,23 @@ case WM_COMMAND:
SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
}else if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE){
const int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0));rebuildAudioList(h,device);query(device);
+ }else if((LOWORD(wp)==2||LOWORD(wp)==3)&&HIWORD(wp)==CBN_SELCHANGE){
+ EnableWindow(GetDlgItem(h,4),!busy&&SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0)!=CB_ERR&&SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0)!=CB_ERR);
}else if(LOWORD(wp)==5){
query(-1);
}else if(LOWORD(wp)==4){
const int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0));
const int format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0));
const int audio=selectedAudio(h,device);
- const bool audioIndexValid=audio<0||size_t(audio)<audioDevices.size();
+ const bool audioIndexValid=SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0)!=CB_ERR&&(audio<0||size_t(audio)<audioDevices.size());
if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()&&device>=0&&size_t(device)<videoDevices.size()&&audioIndexValid){
const auto* audioDevice=audio>=0?&audioDevices[size_t(audio)]:nullptr;
const auto path=source::CaptureCardSource::makeCapturePath(unsigned(device),videoDevices[size_t(device)],formats[size_t(format)].index,audio,audioDevice,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)));
- if(!path.empty()){start(path);DestroyWindow(h);}
+ if(!path.empty()){
+ remembered={videoDevices[size_t(device)].path,formats[size_t(format)].key,audioDevice?audioDevice->path:L"",audioDevice?(audioDevice->wasapi?source::kCaptureAudioWasapi:0):audio,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0))};
+ if(!CapturePreferenceStore(runtime::localDataDirectory()).save(remembered))log::warn("capture","Failed to save capture selection");
+ start(path);DestroyWindow(h);
+ }
}
}
return 0;
diff --git a/apps/veyra/ui/CapturePreferenceStore.h b/apps/veyra/ui/CapturePreferenceStore.h
new file mode 100644
index 00000000..8e55345f
--- /dev/null
+++ b/apps/veyra/ui/CapturePreferenceStore.h
@@ -0,0 +1,44 @@
+#pragma once
+#include <windows.h>
+#include <filesystem>
+#include <fstream>
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+namespace veyra::ui {
+struct CapturePreferences {
+ std::wstring videoPath,formatKey,audioPath;
+ int audioMode=-1;
+ unsigned colorOverride=0;
+};
+class CapturePreferenceStore {
+ std::filesystem::path path_;
+public:
+ explicit CapturePreferenceStore(std::filesystem::path folder):path_(std::move(folder)/"capture-preferences.v1"){}
+ CapturePreferences load()const {
+ std::ifstream file(path_,std::ios::binary|std::ios::ate);
+ if(!file)return {};
+ const std::streamoff size=file.tellg();
+ if(size<=0||size>65536||size%sizeof(wchar_t))return {};
+ std::wstring data(size_t(size)/sizeof(wchar_t),0);file.seekg(0);
+ if(!file.read(reinterpret_cast<char*>(data.data()),size))return {};
+ std::wistringstream in(data);std::wstring magic;int version=0;CapturePreferences result;
+ if(!(in>>magic>>version>>std::quoted(result.videoPath)>>std::quoted(result.formatKey)>>result.audioMode>>std::quoted(result.audioPath)>>result.colorOverride)||
+ magic!=L"VEYRA_CAPTURE"||version!=1||result.audioMode< -3||result.audioMode>0||result.colorOverride>2)return {};
+ in>>std::ws;return in.eof()?result:CapturePreferences{};
+ }
+ bool save(const CapturePreferences& p)const {
+ if(p.audioMode< -3||p.audioMode>0||p.colorOverride>2)return false;
+ std::error_code ec;std::filesystem::create_directories(path_.parent_path(),ec);if(ec)return false;
+ std::wostringstream out;out<<L"VEYRA_CAPTURE 1\n"<<std::quoted(p.videoPath)<<L' '<<std::quoted(p.formatKey)<<L' '<<p.audioMode<<L' '<<std::quoted(p.audioPath)<<L' '<<p.colorOverride<<L'\n';
+ const auto data=out.str();if(data.size()>65536/sizeof(wchar_t))return false;const DWORD bytes=DWORD(data.size()*sizeof(wchar_t));
+ auto tmp=path_;tmp+=L".tmp-"+std::to_wstring(GetCurrentProcessId());
+ HANDLE file=CreateFileW(tmp.c_str(),GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;
+ DWORD written=0;bool ok=WriteFile(file,data.data(),bytes,&written,nullptr)&&written==bytes&&FlushFileBuffers(file);CloseHandle(file);
+ ok=ok&&MoveFileExW(tmp.c_str(),path_.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH);
+ if(!ok)DeleteFileW(tmp.c_str());
+ return ok;
+ }
+};
+}
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index 9c80cdcc..c0948ac5 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -147,6 +147,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"转换峰值 / 超满幅 / 异常",std::format(L"{:.4f} / {} / {}",s.captureAudio.inputPeak,s.captureAudio.overRangeSamples,s.captureAudio.nonFiniteSamples+s.captureAudio.invalidPaddingSamples));
}
if(!s.colorStatus.empty())rows.emplace_back(L"实际颜色链路",s.colorStatus);
+ if(!s.sourceNotice.empty())rows.emplace_back(L"片源兼容",s.sourceNotice);
if(!s.backendWarning.empty())rows.emplace_back(L"后端状态",s.backendWarning);
if(!s.captureAudio.error.empty())rows.emplace_back(L"采集音频异常",s.captureAudio.error);
}
diff --git a/apps/veyra/ui/SettingHelp.h b/apps/veyra/ui/SettingHelp.h
index 7aabe92f..8210c79c 100644
--- a/apps/veyra/ui/SettingHelp.h
+++ b/apps/veyra/ui/SettingHelp.h
@@ -30,7 +30,7 @@ inline const wchar_t* settingHelp(int id){
case 200:return L"这玩意就是我们接入的实验性DLSS5 NR:用神经网络重建画面细节。不是游戏原生集成,效果看素材,也看显卡。";
case 201:return L"把画面放大到所选目标尺寸。不是凭空找回所有细节,显卡也不是许愿池。";
case 202:return L"补帧倍率:2X插1张,3X插2张,4X插3张。目标帧率涨了,显卡不一定跟得上;拖影也可能来凑热闹。";
- case 203:return L"实时档约1080p内部做NR再回填;原生档按处理阶段的原尺寸做NR。原生更吃算力,不保证处处更好看。";
+ case 203:return L"选择NR内部处理上限,按画面比例缩放,再回填输出。低档省算力,高档留细节;原生档让显卡加班。视频导出仍用完整尺寸。";
case 204:return L"光流质量档:估计物体怎么移动。质量档更费工,运动估错了,补帧也可能跟着跑偏。";
case 205:return L"选择内容节奏。采集60→30适合60Hz信号里重复的30帧游戏内容;真60帧别硬砍半。时间戳仍保留。";
case 206:return L"让框选区域少受NR改动,最多4块。只管NR,不给超分和补帧当保镖。";
diff --git a/docs/SDR_CODE_VALUE_ROUNDTRIP_REPAIR_2026-09-15.md b/docs/SDR_CODE_VALUE_ROUNDTRIP_REPAIR_2026-09-15.md
new file mode 100644
index 00000000..94c71a76
--- /dev/null
+++ b/docs/SDR_CODE_VALUE_ROUNDTRIP_REPAIR_2026-09-15.md
@@ -0,0 +1,50 @@
+# SDR 效果全关颜色偏暗:端到端修复
+
+## 反馈与推翻的旧结论
+
+用户用同一视频对比其他播放器,Veyra 在关闭所有效果后仍偏暗。当前运行程序确认为 `out/build/audio-continuity-repair-20260915/veyra.exe`。上一批将文件 BT.709 工作解码改成 BT.1886 理想黑点(幂2.4),但 SDR 输出仍是 sRGB 编码,两者不互逆。这是代码值转换错误,不能作为“发灰已修复”的依据。
+
+上一批 `SourceFidelityTests::expectedGray` 同样计算 BT.1886→sRGB,属于错误预期:能够确认执行一致,无法证明无增强输出忠于原信号。撤回总修复方案中据此认定文件中灰修正正确的结论;旧通过日志只作历史证据。
+
+## 独立复现
+
+用户原文件 `C:/Users/123/Downloads/OpenAI-This_is_GPT-6_Astra__10368kbps-20260906113552.mp4` 为1920×1080 H.264/yuv420p,无range/matrix/transfer/primaries标记。生产解析推定limited/BT.709,假设写入日志。没有足够信息把该推定当成原作者确认的色彩空间。
+
+新检查直接从解码YUV按有限范围展开和BT.709矩阵计算RGB代码值,与关闭所有效果、同分辨率GPU输出逐像素比较。该预期不调用生产transfer函数,不计算任何对比度补偿。同时读取真正呈现缓冲,检验后段是否又修改颜色。硬解参考仅在诊断中回读解码平面,生产链没有增加回读。
+
+修复前:
+
+- 灰阶0至255端到端最大误差13.1233级,平面YUV与NV12均失败。
+- 原视频seek到60秒后的相同首帧,软/硬解PTS均513137900;RGB最大误差13.3126级,平均绝对误差6.74098级,平均带符号误差-6.74098,均失败。
+- 图输出至交换链缓冲最大误差0,说明本例不是显示blit再次变色。
+- 原视频检查退出码1:`logs/sdr-file-before-20260915.stdout.log`;灰阶首次红测 `logs/sdr-roundtrip-before-20260915.stdout.log`。
+
+## 修复合同
+
+普通桌面SDR播放默认保留范围展开和矩阵转换后的RGB代码值。仍使用统一线性工作图,输入采用与既有sRGB输出互逆的解码,不能把源BT.709标签直接改写成sRGB,不能在输出端加一条肉眼调参的补偿曲线。
+
+- `ColorDescription::preserveSdrCodeValues` 明确区分桌面代码值保留策略与源transfer元数据。
+- 文件启用该策略;采集保持已有未标记SDR行为,修正上一批新增显式BT.709时的错误2.4分支。
+- 本策略只影响BT.709 SDR工作解释;PQ/HLG、线性输入、BT.2020广色域路径不套用该规则。PS5现有参考显示策略保持独立,本例没有PS5同源实测,不能据本次结果宣称它正确或错误。
+- 输出、NR proxy、截图与导出仍复用原共享图。新日志同时记录源transfer、代码保留策略及实际工作transfer。
+
+修改文件包括 `FramePacket.h`、`ColorMetadata.h`、`MediaFileSource.cpp`、`CaptureMediaType.h`、`CaptureCardSource.cpp`、`EnhanceGraph.cpp`,以及源保真、SDR色块和采集颜色合同测试。新增 `tests/integration/FileSdrRoundTripCases.h` 执行真实媒体软硬解与呈现缓冲对照。
+
+## 验证命令与状态
+
+```powershell
+cmd.exe /c out\build\veyra-build-x64-release.cmd
+# run-short-test.ps1 包装,下列用例限90秒
+out/build/audio-continuity-repair-20260915/veyra_source_fidelity_tests.exe <用户原文件>
+```
+
+构建 `logs/sdr-roundtrip-build-20260915.log` exit0,75/75。用户关闭应用后实际替换了同一候选目录的EXE。
+
+- 修后同文件检查exit0:`logs/sdr-file-after-20260915.stdout.log`。软/硬解同PTS513137900,最大误差0.629614级,平均绝对误差0.256191级,平均偏差-0.0670757级;灰阶最大误差0.575342级;图输出至交换链误差0。误差包含FP16和8-bit输出量化,未冒称数学上的逐位无损。
+- HDR/SDR/采集GPU色块:`veyra_hdr_color_tests.exe`,90秒上限,exit0,`logs/sdr-repair-hdr-regression-20260915.stdout.log`。覆盖现有PQ/HLG、full/limited、平面/P010、原生HDR/SDR映射和四种SDR输入packing。
+- `veyra_repair_contract_tests.exe`:137项失败0,`logs/sdr-repair-contracts-20260915.log`。首次误用不存在的 `veyra_capture_color_contract_tests.exe` 名称,未实际执行该测试;随后按CMake真实目标 `veyra_capture_color_tests.exe` 重跑,不将先前PowerShell残留退出码作为成功。
+- `git diff --check` exit0,只有既存换行提示。
+
+候选EXE SHA256 `EFA748C7F7D64DF3E9ECE814CE56D2015BC976192F00195443C2B0E17A8EDA96`,入口仍为 `out/start-user-issues-candidate.cmd`。本轮未改版本、未发布或替换运行组件。
+
+尚未对其他播放器的显示设置/ICC/驱动视频处理逐项比对,因此不宣称屏幕最终像素与所有播放器完全一致;本次首先要求软件内部的无效果SDR链路不擅自改变代码值。实卡采集/PS5和反馈者屏幕复测未执行。
diff --git a/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md b/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md
index 348041c5..aca21c92 100644
--- a/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md
+++ b/docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md
@@ -1,6 +1,6 @@
# 用户集中反馈修复计划(2026-09-15)
-状态:方案建立,尚未开始本轮代码施工。
+状态:本地候选已构建并通过软件短测;硬件验收及受限功能仍见第 8 节。分支 `codex/user-issues-repair-20260915`,基线 `6206b5a`。
范围:视频播放器、采集卡、PS5 串流、增强管线、视频导出和颜色管理。
本计划不授权发布新版本、不替换运行组件、不修改显卡驱动。
@@ -46,7 +46,7 @@
1. 将交换链能力探测、请求模式和实际生效模式分开记录。
2. SDR、HDR、直播兼容和窗口 resize 使用明确的回退顺序;实际模式改变时重新绑定呈现资源,不直接终止串流。
-3. 把状态拆成“传输连接、视频解码、增强初始化、呈现初始化、运行中”五层。
+3. 利用已有传输/解码状态及增强/呈现日志分别定位失败阶段;本轮没有另建五层连接状态机。
4. NGX/NVOF/XeSS 失败只禁用对应后端,基础视频仍可显示。
5. 为每个阶段记录 HRESULT、NGX/XeSS 返回值、交换链格式、色彩空间和窗口尺寸。
@@ -56,13 +56,13 @@
现象:1.2.0 起使用 OBS 游戏采集,放大缩小窗口后进入错误状态;1.1.0 无此问题。
-实施:统一 resize 生命周期:暂停提交,等待旧资源 fence,重建交换链和尺寸相关纹理,原子 reset SR/NR/FG/flow/depth,再恢复提交。禁止旧 backbuffer 在 GPU 使用期间被释放或复用。
+实施:核查 resize 的实际资源所有权,等待相关旧资源 fence 后重建呈现缓冲;只有增强输入/工作尺寸改变才重建相应图和 reset 历史,纯窗口缩放不能一律重建全部增强。禁止旧 backbuffer 在 GPU 使用期间被释放或复用。
验收:连续拖动窗口、最大化/还原、全屏切换、DPI 改变、OBS 同时捕获;检查无黑帧、无错误状态、无旧尺寸资源访问。
#### A3. 采集卡断开自动重连
-实施:检测 DirectShow/WASAPI 设备失效、样本停止、端点错误和设备路径变化;进入 `reconnecting`,保留 UI/设置,暂停历史,按递增间隔重试原设备;成功后重新建视频格式、音频时钟和增强历史。多次失败后才进入可重试错误。
+实施:检测 DirectShow 设备失效事件、视频样本停止和 WASAPI 端点错误;保留 UI/设置,按 1 至 5 秒封顶退避持续重试原设备,停止可中断等待。成功后恢复原视频格式并重置历史。设备路径或格式合同改变需要重新选择。独立 WASAPI 音频自行恢复;DirectShow 音频启动失败时保留视频,本轮未实现独立音频 pin 热重建。
验收:拔线/插回、设备被 OBS 占用、设备格式改变、音频端点单独断开、连续断开重连;不切到其他设备,不丢失用户选择。
@@ -82,7 +82,7 @@
#### B2. 视频导出 BT.2020 转换失败
-实施:导出前按颜色合同分流 SDR 与 HDR。SDR 使用 BT.601/709 SDR 转换;HDR 使用 BT.2020 PQ/HLG 到 HDR10,或在用户选择 SDR 时执行明确 tone map。遇到不支持的组合要在导出前报错,不能进入错误转换函数。
+实施:导出前以首个实际解码帧确定颜色合同,保留首帧供导出。SDR 支持 BT.601/709 和 BT.2020 NCL 转换;HDR 使用 PQ/HLG 到 HEVC Main10 HDR10。当前未新增 HDR 转 SDR 导出选择器;预览强制 SDR 不改变导出合同。BT.2020 CL 仍明确拒绝。
验收:导出输出帧数、PTS、颜色元数据和解码回验一致;HDR 输入不得触发 `BT.2020 input is not supported by BT.601/709 SDR conversion`。
@@ -100,7 +100,7 @@
#### C1. Seek、全屏进度和快捷键
-实施:拖动过程中只更新目标位置,松开后执行一次精确 seek;新 seek 覆盖旧 seek。解码 worker 异步处理,UI 立即显示目标位置。全屏保留进度条、鼠标唤醒和键盘焦点;左右方向键默认前后10秒。
+实施:沿用拖动期间显示目标位置、松开提交与最新请求覆盖旧请求的机制;清理首帧缓存和过期 seek 结果。解码和 seek 在现有 EngineController 工作线程执行,UI 不等待;本轮没有增加独立预解码线程。全屏保留进度条、鼠标唤醒和键盘焦点;左右方向键默认前后10秒。
验收:4K 文件连续拖动、拖到末尾、反复前后跳、全屏/窗口切换、音频恢复;不出现先弹回旧位置再跳转的视觉回弹。
@@ -126,7 +126,7 @@
#### D2. 40 系过载
-先区分真实 GPU 超时、队列积压、显存不足和错误阈值。记录每阶段 GPU 时间、显存预算/占用、队列深度、后端和驱动版本。持续过载时按预设降级内部处理分辨率或关闭单个高成本效果,不能直接把目标帧率锁30并伪装成正常。
+先区分真实 GPU 超时、队列积压、显存不足和错误阈值。记录每阶段 GPU 时间、显存预算/占用、队列深度、后端和驱动版本。持续过载沿用有界实时预览调度,并提示用户选择较低内部尺寸;不擅自修改已选分辨率或效果,不能直接把目标帧率锁30并伪装成正常。
验收至少覆盖 RTX 4060、4070、4070 Ti;本机没有对应实卡时只做代码和日志验证,不宣称硬件通过。
@@ -136,13 +136,13 @@
#### D4. FG 后端失败
-按不可用、驱动不足、分辨率不支持、资源不足、初始化失败、运行时 Evaluate 失败分类。UI显示后端和真实错误码;失败只禁用该后端并保留基础播放,不能静默回滚成“已开启”。
+按 NR/SR/FG/光流/NGX 核心/基础资源标注失败归属,原始 SDK/HRESULT/SEH 在日志保留。UI 显示后端及失败恢复提示,错误码当前需查看日志。健康 GPU 上禁用失败后端及其依赖,保留基础播放;设备丢失等基础故障仍报错。XeSS 呈现失败需丢弃未提交命令、重建调度器和交换链,不能仅 cancel 后继续使用已失败调度器。
### 阶段 E:视频导出队列
#### E1. completed sample queue overflow
-导出路径使用独立有界队列和背压;接近上限时暂停生产或等待可复用 slot,不允许无限堆积。`flow=0 fallback=single-image` 只允许在首帧、seek、场景切换等无历史阶段,并在导出报告中统计。
+源码确认该告警来自 `include/veyra/diagnostics/GpuTimer.h` 的 GPU 计时样本队列(上限64),并非视频帧队列。先核对订阅者和消费路径,修复无消费者时的订阅及计时样本丢失,日志明确区分遥测与视频帧。另独立审计真实导出帧队列与背压,不能凭此告警断言导出帧堆积。`flow=0 fallback=single-image` 需按实际来源与是否有历史判断,不能与样本溢出合并归因。
验收:导出长视频、4K、FG 开关、场景切换和 HDR;检查队列峰值、最终归零、帧数、PTS 连续性、取消清理和输出可解码。
@@ -183,7 +183,7 @@
施工前优先收集:
-1. 用户提供的完整“串流异常.log”;
+1. 桌面“串流异常.log”已读取:呈现模式 requested=3 actual=4 被误拒绝,修复后还需反馈设备复测;
2. 视频导出失败的完整日志、输入文件信息和导出设置;
3. 4070/4070 Ti 过载日志,包含驱动版本、源分辨率、内部处理分辨率和所有效果开关;
4. HDR/SDR 发灰各一份源媒体或采集卡颜色日志;
@@ -192,6 +192,8 @@
在这些证据到齐前,可以先施工 A4、C1、C3 和日志/状态框架;不能声称已经解决用户设备上的 B1、D2、E1 或 A1。
+上述文字是最初证据收集顺序;截至本次候选,本机可执行的修复和检查已推进,以下记录为实际交付状态。
+
## 7. 明确不做的事情
- 不通过增加缓冲解决卡顿;这会把卡顿变成更高延迟。
@@ -201,3 +203,65 @@
- 不用0、未知或软件提交时间伪造 XeSS/FG GPU 耗时。
- 不把导出队列溢出、flow fallback 和颜色转换错误合并成一个笼统的“性能不足”。
+## 8. 逐项交付状态
+
+**颜色结论修订:**用户随后报告同视频、无增强时Veyra偏暗。第6项及第9节的BT.1886旧测试只能证明代码按错误预期执行,不能证明播放颜色正确。已用同一实际视频的软/硬解逐像素和呈现缓冲检查推翻并修复;最新证据与候选身份以 `SDR_CODE_VALUE_ROUNDTRIP_REPAIR_2026-09-15.md` 为准,旧候选hash及色彩通过记录保留作追溯。
+
+| 用户序号 | 本轮实现 | 当前证据与剩余验收 |
+| --- | --- | --- |
+| 1 采集卡记忆 | 原子保存稳定视频路径、格式语义键、音频端点及颜色选择;缺失时提示重新选择 | Unicode/配置往返测试通过;同名多卡、枚举变序待实卡 |
+| 2 播放器 seek/流畅性 | 清除过期首帧缓存、跳过已被替代目标、记录解码至首帧耗时;保留 UI 即时目标 | 用户 4K 文件 6 次远距跳转及暂停连续跳转通过,157 至339ms;没有修改前对照,不宣称达到 PotPlayer 速度 |
+| 3 UI 闪烁 | 正在播放的视频 surface 不再被 GDI WM_PAINT 涂黑;窗口 resize 不重建整条增强图 | UI 合同与 GUI 短测通过;尚未逐页视觉验收,不能认定所有闪烁消除 |
+| 4 采集断开重连 | DirectShow 事件/3秒断帧触发同设备重连,1至5秒退避,恢复原格式/颜色合同及新 epoch;WASAPI 原端点持续恢复 | WASAPI 无效端点超过旧3次限制及中止退避测试通过;物理拔插未执行;DirectShow 音频单独初始失败没有自动 pin 重建 |
+| 5 全屏进度/快进 | 沿用全屏自动隐藏/唤醒进度条;增加左右方向键前后10秒,不占用其他数值滑条或输入框 | 暂停 seek/resume 与 UI 合同通过;方向键实操待用户验收 |
+| 6 HDR/SDR 灰 | 修正BT.1886工作解码与sRGB输出不互逆导致的压暗;文件与显式BT.709采集保留SDR代码值;保留HDR及广色域合同 | 真实文件软/硬解同帧最大偏差从13.31降至0.63级,呈现新增偏差0;HDR回归通过。其他播放器设置及用户设备仍需复测 |
+| 7 NR 分辨率 | 480/720/900/1080/1440/native,保持宽高比,缩小内部 NR/flow,输出及导出尺寸不随档位缩水 | 设置往返、纵横比和导出尺寸合同通过;各档硬件性能曲线未测 |
+| 8 OBS resize | 接受合法 flip 模式替代;暂时 ResizeBuffers 失败时保留旧缓冲并延迟重试,检查设备状态 | 同一窗口1920/2560/3840反复 resize、普通/捕获兼容模式真实GPU读回一致;未加载 OBS hook 复现反馈设备 |
+| 9 Dolby Vision | 识别配置/RPU,P7及明确兼容的P8/P10走HDR10/HLG/SDR基础层;P5/未知兼容或颜色不匹配拒绝并说明 | 路由合同通过;真实DV媒体未验收。未实现 RPU/增强层重建或原生 DV 输出 |
+| 10 FG 后端失败 | 初始化/运行按失败组件降低效果,UI显示实际应用设置;XeSS呈现失败重建后继续播放,可手动重新启用 | 真实 NR/XeSS 启用、注入故障、恢复、同会话重开均通过;注入故障不是反馈者真实硬件错误复现 |
+| 11 XeSS计时/冗余 | 外层循环持续收取GPU计时,暂停/图像也消费;XeSS内部计时明确不可测,不填假0 | 合同与软件短测通过;SDK未提供内部GPU计时,不能声称实现精确XeSS耗时 |
+| 12 导出问题 | 确认旧overflow为遥测队列;修正订阅消费和日志;导出由实际首帧确定HDR/bitdepth,完整保留源帧 | H.264/HEVC原生4K 2X帧数、音轨、取消检查通过;PQ导出30帧Main10/2020/PQ+5.1通过;反馈者原文件/完整日志仍缺 |
+| 13 40系过载 | 用同帧GPU执行区间估算恢复预算,排除CPU迟轮询,把同帧FG成本从同帧总成本扣除,避免误锁补帧 | 本机NR+2X注入70ms阻塞后自动恢复,约13→46fps、生成约19fps;不是稳定60fps或40系实卡证明 |
+| 14 PS5初始化失败 | 修复 requested=3 actual=4 合法flip交换链被误拒绝,后端失败可保留基础播放 | 本地交换链/恢复测试通过;未重新连接用户PS5实测,不宣称网络或配对故障根治 |
+
+## 9. 实际验证与候选入口
+
+最终构建目录:`out/build/audio-continuity-repair-20260915`。依赖仍为带PS5 slice补丁及dav1d的FFmpeg,RemotePlay ON,原有运行组件未替换。
+
+命令均在项目根目录执行,单项限制不超过300秒:
+
+```powershell
+cmd.exe /c out\build\veyra-build-x64-release.cmd
+out/build/audio-continuity-repair-20260915/veyra_repair_contract_tests.exe
+out/build/audio-continuity-repair-20260915/veyra_ui_contract_tests.exe out/user-issues-ui-unique
+out/build/audio-continuity-repair-20260915/veyra_wasapi_input_tests.exe --invalid
+out/build/audio-continuity-repair-20260915/veyra_source_fidelity_tests.exe
+# 下列集成测试经 scripts/run-short-test.ps1 包装,最长180秒:
+# veyra_live_presentation_tests.exe <用户4K文件> <独立日志目录> --backend-recovery
+# 同上 --seek-stress / --file-fg-recovery
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915
+```
+
+- 最终构建 `logs/user-issues-build-20260915-k.log` exit0。
+- 合同137项失败0:`logs/user-issues-contract-i.log`;UI:`logs/user-issues-ui-j.log`;WASAPI:`logs/user-issues-wasapi-invalid-i.log`;重复resize:`logs/user-issues-resize-i.log`,均exit0。
+- NR及XeSS完整恢复:`logs/user-issues-backend-recovery-k.stdout.log` 与同名目录 `engine.log`,12项全部通过,exit0。实际NGX Init/CreateFeature18返回0x1(Success),NVOF Create状态0;故障注入均明确标注 `backend-test`。
+- seek:`logs/user-issues-seek-j/engine.log`,344.930/643.709/12/450/28/700秒目标首次呈现耗时266.533/157.017/284.033/339.187/236.143/288.996ms,解码96/48/112/150/92/106帧;暂停最新61秒目标221.771ms。关键帧至目标解码仍是主要等待来源。
+- 过载恢复:`logs/user-issues-fg-recovery-h.log`;无重开音频、无修改所选配置即恢复补帧。
+- HDR GPU:`logs/user-issues-hdr-color-20260915.log`;SDR/采集色块和源保真见对应 `user-issues-source-fidelity-20260915`、`user-issues-capture-color-20260915` 日志。
+- 最终delivery:`logs/delivery/23d9cf72ba7a463aacda42f56be591e3/result.json`,47.98秒,软件短测通过,明确标注采集实卡待验收。先前j版也通过,本次因补XeSS恢复重跑。
+- HDR导出:`scripts/run-short-test.ps1` 使用 `pq-tagged-51.mp4 --no-nr --no-sr --no-fg --hevc --export-out logs/user-issues-hdr-export-k.mp4`,60秒上限,exit0;外部ffprobe完整解码计数得到HEVC Main10/yuv420p10le/BT.2020 NCL/PQ/30帧、AAC 6声道5.1。
+- 中途失败:ResetReason枚举名与缺少标准头导致构建失败已修复;backend-recovery-i因测试参数白名单遗漏提前exit2,补白名单后j/k通过。一次ffprobe使用了不存在的依赖bin路径,改用已安装CLI后成功;这些失败不计为通过。
+
+本地入口:`out/start-user-issues-candidate.cmd`。根目录 `Veyra.cmd` 仍指向原x64-release,不能据此认定桌面旧入口已更新。最终候选EXE SHA256:`9DC754D09BB3835E605D32A8825040DFD25A24669D81789B8924D47351EEBAD3`。未push、未发布、未升版本、未关机。
+
+## 10. 实机验收顺序与回退
+
+1. 从候选入口启动,先不开增强,核对采集卡/格式/音频记忆、HDR/SDR颜色,再拔插同一设备。选WASAPI时另测音频端点恢复。
+2. 4070/4070Ti从900p NR+2X开始,记录实际处理率/生成率、错误码和30秒以上过载恢复;随后对比1080p,不能以显卡型号预测必然达标。
+3. OBS游戏捕获候选,连续最大化/还原、全屏/窗口;核对播放未进入错误状态。
+4. 文件全屏方向键、拖动、暂停跳转;用原问题媒体导出,保留对应日志和完整设置。
+5. PS5按已保存主机连接;失败时分别核对接收/解码/呈现,不要求重新配对掩盖显示错误。
+
+代码回退基线 `6206b5a`;本轮在独立分支提交,验证期间保留原应用目录。不要重置用户未提交改动,不把回退扩大成删除运行组件/配对/配置。
+
+下一步是以上问题设备的候选验收及按原始日志追踪剩余缺陷。原生Dolby Vision、XeSS内部计时、DirectShow音频pin独立热重建和PotPlayer级seek预解码仍未交付,不能将本轮报告称为14项全部实机修复完成。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 3564b599..b5c995e7 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2172,3 +2172,38 @@ WASAPI输入使用共享模式事件采集,按 `IAudioCaptureClient::GetBuffer
## 2026-09-15 用户集中反馈总修复方案
用户汇总14项问题:采集卡选择记忆、播放器seek/流畅性、UI闪烁、采集断连重连、全屏控制、HDR/SDR发灰、NR内部处理分辨率、OBS resize回归、Dolby Vision、FG后端失败、XeSS计时、同步/增强冗余、40系过载、视频导出队列与BT.2020错误、PS5串流增强初始化失败。已建立 `docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md`,按“不可用恢复→颜色→交互→性能→导出→Dolby Vision”分批施工,记录每项证据、验收合同和未验证边界。本轮仅建立方案,未修改代码、未构建、未发布;后续按批次逐项更新实际结果,不能把方案文档当作修复完成证明。
+
+## 2026-09-15 集中反馈修复本地候选
+
+用户授权目标模式、独立分支和全部修复;从 `6206b5a` 建立 `codex/user-issues-repair-20260915`。保留此前采集同步和音频连续性修复,本次交付为可回退的本地候选,不等同14项已在反馈者硬件全部验收。逐项实现、证据及剩余项见 `docs/USER_ISSUES_REPAIR_PLAN_2026-09-15.md` 第8至10节。
+
+修改范围:`CapturePanel`/新增 `CapturePreferenceStore` 保存稳定设备及格式选择;`CaptureCardSource` 和 `WasapiAudioInput` 同设备退避恢复;`AppShell` 修正视频GDI重绘及方向键seek;`EnhancementSettings`/`ResolutionPlan`/设置UI增加480/720/900/1440档。`MediaFileSource` 清理过期seek结果并记录首次呈现时间,新增 `DolbyVision.h` 区分配置及兼容基础层。颜色元数据和三个输入shader补显示参考BT.709及SDR BT.2020 NCL;`VideoExportJob` 使用实际首帧颜色合同。`PresentSink` 接受合法flip模式替代并保留暂时resize失败时的缓冲;`EngineController`/`EnhanceGraph`/新增 `BackendRecovery` 分组件恢复,XeSS呈现失败时重建调度器和交换链。GPU计时按外层循环消费,FG恢复预算使用同帧实际GPU执行区间。对应单元、UI、GPU颜色、呈现及输入测试一并更新。
+
+实际验证命令与结果:
+
+- `cmd.exe /c out\build\veyra-build-x64-release.cmd`,最终exit0,日志 `logs/user-issues-build-20260915-k.log`;构建目录 `out/build/audio-continuity-repair-20260915`,RemotePlay ON,FFmpeg仍为 `C:/veyra-deps/ffmpeg-ps5-dav1d-installed`,保留PS5 slice补丁。
+- 构建目录下 `veyra_repair_contract_tests.exe`:137项失败0;`veyra_ui_contract_tests.exe <独立输出目录>`、`veyra_wasapi_input_tests.exe --invalid`、`veyra_source_fidelity_tests.exe` 均exit0。证据为 `logs/user-issues-contract-i.log`、`user-issues-ui-j.log`、`user-issues-wasapi-invalid-i.log`、`user-issues-resize-i.log`。普通/捕获兼容模式下同窗口反复1920/2560/3840 resize有真实GPU读回检查。
+- 经 `scripts/run-short-test.ps1` 限制180秒执行 `veyra_live_presentation_tests.exe <用户4K文件> <独立日志目录> --backend-recovery`:12项通过,`logs/user-issues-backend-recovery-k.stdout.log` 和 `logs/user-issues-backend-recovery-k/engine.log`。真实NR/XeSS启用、注入初始化/运行/呈现故障、恢复基础播放、手动重启XeSS同会话成功。NGX Init/CreateFeature18返回 `0x1 Success`,NVOF Create状态0;注入故障不冒充用户实卡故障复现。
+- 同一呈现测试的 `--seek-stress`:用户4K视频6次远距跳转首次呈现157至339ms,暂停最新目标约222ms;`logs/user-issues-seek-j.log` 及同名目录。无修前对照,不宣称PotPlayer级速度。`--file-fg-recovery` 注入70ms主循环阻塞后恢复生成,约13→46fps,生成约19fps,`logs/user-issues-fg-recovery-h.log`;不是稳定60fps或RTX40实卡证明。
+- `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915`:最终exit0,47.98秒,`logs/delivery/23d9cf72ba7a463aacda42f56be591e3/result.json`。实际1080/原生4K NR/NVOF、GUI播放/暂停seek、图片、H.264/HEVC原生4K 2X完整帧数与音轨、取消检查通过;实卡采集明确待验收。
+- HDR GPU颜色检查见 `logs/user-issues-hdr-color-20260915.log`。另经短测脚本60秒上限执行 `veyra.exe out/hdr-audio-fixtures/pq-tagged-51.mp4 --no-nr --no-sr --no-fg --hevc --export-out logs/user-issues-hdr-export-k.mp4`:exit0;已安装外部ffprobe完整计数得到HEVC Main10/yuv420p10le/BT.2020 NCL/PQ/30帧、AAC 6声道5.1。日志 `logs/user-issues-hdr-export-k.stdout.log` 与 `logs/user-issues-hdr-export-k-app.log`。
+
+中途失败如实保留:ResetReason枚举及缺少标准头导致编译失败后修正;backend-recovery-i因测试参数白名单遗漏exit2,修正后j/k通过。首次ffprobe路径不存在,改用已安装Gyan CLI完成检查。修改后重新跑相关恢复及delivery,没有把失败当成功。
+
+候选入口 `out/start-user-issues-candidate.cmd`,实际EXE为 `out/build/audio-continuity-repair-20260915/veyra.exe`,SHA256 `9DC754D09BB3835E605D32A8825040DFD25A24669D81789B8924D47351EEBAD3`。根目录旧 `Veyra.cmd` 未改,不代表桌面原入口已更新。运行组件/SDK/配置/测试媒体/日志保持本地忽略,不加入提交;本轮不升版本、不push、不发布、不关机。
+
+尚未交付或验收:原生Dolby Vision RPU/增强层及输出、真实DV素材;XeSS SDK内部精确GPU时间;DirectShow音频pin单独初始化失败后的独立热重建;独立预解码worker及PotPlayer速度对照。物理采集卡拔插、4070/4070Ti、OBS真实hook、PS5重连和全屏方向键人工实操未执行。不能声称全部用户发灰、过载及导出异常已经根治;下一步为候选在问题设备上的复测和原始日志核对。
+
+## 2026-09-15 同视频无增强颜色偏暗:推翻旧预期并修复
+
+用户截图反馈普通播放器与Veyra无增强画面颜色不同,要求从链路定位而非提高对比度。确认用户运行本地候选,原媒体为Downloads内 `OpenAI-This_is_GPT-6_Astra__10368kbps-20260906113552.mp4`,1080p H.264/yuv420p、未标记颜色参数。生产推定limited/BT.709。发现上一批文件入口使用pow2.4(BT.1886理想黑点),输出仍sRGB,两曲线不互逆而压暗。原SourceFidelity期望值也执行同样曲线,错误地把算法一致性当成信号保真;撤回前文以该结果宣称文件中灰已正确修复的结论。
+
+先将灰阶测试预期改成独立的limited→full代码值恒等关系,旧版exit1;新增 `FileSdrRoundTripCases.h` 用生产MediaFileSource软/硬解同一文件60秒后的同帧,独立YUV矩阵计算RGB预期并读回图输出和真正呈现缓冲。修前软/硬解同PTS513137900:平均误差6.74098级、最大13.3126级且全部偏暗;图至呈现误差0。修后平均0.256191、最大0.629614、平均偏差-0.0670757级;灰阶最大0.575342级、呈现误差0,exit0。证据 `logs/sdr-file-before-20260915.stdout.log` 与 `logs/sdr-file-after-20260915.stdout.log`,不将诊断GPU回读加入生产路径。
+
+实现 `ColorDescription::preserveSdrCodeValues`,文件和采集用与现有sRGB输出互逆的工作解码,同时保留源transfer元数据。修正采集显式BT.709错误分支,设备格式匹配比较包含新策略;日志补充实际工作transfer。PS5旧参考显示策略及PQ/HLG路径未改,不拿本例判断它们是否正确。完整根因和边界见 `docs/SDR_CODE_VALUE_ROUNDTRIP_REPAIR_2026-09-15.md`。
+
+实际构建 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0(75/75),`logs/sdr-roundtrip-build-20260915.log`。用户明确关闭软件后替换候选EXE。`veyra_source_fidelity_tests.exe <用户文件>` 经90秒短测限制exit0;`veyra_hdr_color_tests.exe` 同样限90秒exit0,涵盖HDR/SDR/采集GPU色块;`veyra_repair_contract_tests.exe` 137项失败0;`veyra_capture_color_tests.exe` 限30秒exit0。首次误拼为capture_color_contract_tests导致命令未执行,之后按CMake真实名称纠正;不采用那次残留LASTEXITCODE。
+
+再执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915` exit0,结果 `logs/delivery/3c32cadc5f774f6eaae43efee5d02211/result.json`,真实NR/NVOF、4K导出等短测通过;不能替代问题设备实测。EXE SHA256 `EFA748C7F7D64DF3E9ECE814CE56D2015BC976192F00195443C2B0E17A8EDA96`,入口 `out/start-user-issues-candidate.cmd`。git diff --check通过;版本、runtime及发布状态不变。
+
+下一步唯一用户验收:同原视频、关闭所有效果对照新候选。未核对其他播放器ICC/驱动视频增强/显示设置,不能宣称所有播放器屏幕像素绝对相同,也不能将本次SDR修复扩大为全部HDR发灰根治。该修复与此前14项候选一并作为当前独立分支的本地可回退记录,原基线6206b5a保留,不push、不发布。
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index 453794a9..1509037b 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -1,4 +1,5 @@
#pragma once
+#include <algorithm>
#include <array>
#include <optional>
#include "veyra/pipeline/FrameBatch.h"
@@ -13,6 +14,19 @@ enum class ResetOutcome { InProgress, Completed, Failed, RolledBack, Cancelled }
struct TimingAggregate {std::optional<double> mean,p95;uint64_t samples=0;};
struct GpuSample {SampleState state=SampleState::NotExecuted;std::optional<double> milliseconds;uint64_t begin=0,end=0,frequency=0;};
struct GpuFrameTiming {pipeline::FrameIdentity identity;std::array<GpuSample,size_t(GpuStage::Count)> gpu{};};
+// All graph stage timestamps use the direct queue's clock. The envelope
+// includes its dependency waits but excludes a late CPU completion poll.
+inline std::optional<double> graphExecutionSpanMs(const GpuFrameTiming& frame){
+ uint64_t begin=UINT64_MAX,end=0,frequency=0;
+ for(size_t i=0;i<size_t(GpuStage::Blit);++i){
+ const auto& s=frame.gpu[i];
+ if(s.state!=SampleState::Measured)continue;
+ if(!s.frequency||s.end<s.begin||(frequency&&frequency!=s.frequency))return {};
+ frequency=s.frequency;begin=std::min(begin,s.begin);end=std::max(end,s.end);
+ }
+ if(!frequency||begin==UINT64_MAX||end<begin)return {};
+ return double(end-begin)*1000/frequency;
+}
// Live presentation is asynchronous. Keep the identity of the window that
// owns these counters so a finished job from a prior reset cannot be reported
// as work performed by the current settings or temporal epoch.
diff --git a/include/veyra/diagnostics/GpuTimer.h b/include/veyra/diagnostics/GpuTimer.h
index e9a7213e..ca5f2bff 100644
--- a/include/veyra/diagnostics/GpuTimer.h
+++ b/include/veyra/diagnostics/GpuTimer.h
@@ -32,7 +32,7 @@ public:
}
D3D12_RANGE written{0,0};readback_->Unmap(0,&written);if(p.fence>=lastCollectedFence_){last_=m;lastCollectedFence_=p.fence;}
if(recordCompleted_){
- if(completed_.size()==64){completed_.pop_front();++overflow_;if((overflow_&(overflow_-1))==0)log::warn("gpu-timestamp",std::format("completed sample queue overflow={}",overflow_));}
+ if(completed_.size()==64){completed_.pop_front();++overflow_;if((overflow_&(overflow_-1))==0)log::warn("gpu-timestamp",std::format("timing telemetry overflow={} (old timing samples dropped, not video frames)",overflow_));}
completed_.push_back({m.identity,m.gpu});
}p.fence=0;
}
diff --git a/include/veyra/engine/BackendRecovery.h b/include/veyra/engine/BackendRecovery.h
new file mode 100644
index 00000000..ab4b3d67
--- /dev/null
+++ b/include/veyra/engine/BackendRecovery.h
@@ -0,0 +1,36 @@
+#pragma once
+#include "veyra/engine/EnhancementSettings.h"
+
+namespace veyra::engine {
+enum class FailedBackend { None, Infrastructure, OpticalFlow, NgxCore, Nr, Sr, Fg };
+inline const wchar_t* backendFailureName(FailedBackend backend) {
+ switch(backend){
+ case FailedBackend::OpticalFlow:return L"光流";
+ case FailedBackend::NgxCore:return L"NGX 核心";
+ case FailedBackend::Nr:return L"NR";
+ case FailedBackend::Sr:return L"超分";
+ case FailedBackend::Fg:return L"帧生成";
+ default:return L"GPU / 输入 / 显示资源";
+ }
+}
+// Disable only the failed feature and its consumers. Never substitute zero
+// motion for a failed optical-flow backend while claiming normal enhancement.
+inline bool disableFailedBackend(EnhancementSettings& settings,FailedBackend backend){
+ const auto before=settings;
+ switch(backend){
+ case FailedBackend::Nr:settings.nr=false;break;
+ case FailedBackend::Sr:settings.sr=false;break;
+ case FailedBackend::Fg:settings.multiplier=1;break;
+ case FailedBackend::NgxCore:
+ settings.nr=settings.sr=false;
+ if(settings.frameGenerationBackend==FrameGenerationBackend::Dlss)settings.multiplier=1;
+ break;
+ case FailedBackend::OpticalFlow:
+ settings.nr=false;settings.multiplier=1;
+ if(!settings.videoSrQuality)settings.sr=false;
+ break;
+ default:return false;
+ }
+ return settings!=before;
+}
+}
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index b5363ef6..94ddee52 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -20,8 +20,8 @@ class FrameFlowWindow;
struct PlayerOptions { bool nr=false,sr=false,fg=false,realtime=true; uint32_t fgMultiplier=2; EnhancementSettings settings;
bool captureReplayForTest=false; // file-backed live scheduler test; never enabled by UI
bool captureReplayDisableFgAdmissionForTest=false; // controlled scheduler A/B only
- EnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native;return s;}
- 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;}
+ EnhancementSettings snapshot()const{auto s=settings;s.nr=nr;s.sr=sr;s.multiplier=fg?fgMultiplier:1;s.nrPolicy=realtime?(settings.nrPolicy==pipeline::NrSizePolicy::Native?pipeline::NrSizePolicy::Realtime:settings.nrPolicy):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::Native;o.settings=s;return o;}
};
enum class TransportState { Empty, Opening, Playing, Paused, Ended, Stopping, Failed };
struct PlayerSnapshot {
@@ -31,6 +31,7 @@ struct PlayerSnapshot {
EnhancementSettings desired,applied;bool applying=false;
bool nrActive=false,srActive=false,fgActive=false;
std::wstring backendWarning;
+ std::wstring sourceNotice;
std::wstring colorStatus;
sink::CaptureAudioState captureAudio;
unsigned audioInputChannels=0,audioOutputChannels=0;
@@ -47,6 +48,7 @@ struct PlayerSnapshot {
uint64_t captureReceived=0,captureDropped=0,nrEvaluated=0,nvofExecuted=0;
uint64_t captureRateSkipped=0,processedCompleted=0;
bool captureHalfRate=false;
+ bool captureRecovering=false;unsigned captureReconnectAttempts=0;
double captureFps=0,captureReadAgeMs=0,captureAgeMs=0,captureAgeP95Ms=0;
double schedulingWaitP95Ms=0,processCpuP95Ms=0,presentCpuP95Ms=0;
// Realtime file preview: dropped enhancement opportunities this metrics
diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.h
index 0b8f51ab..d6853ce7 100644
--- a/include/veyra/engine/EnhancementSettings.h
+++ b/include/veyra/engine/EnhancementSettings.h
@@ -115,7 +115,7 @@ struct EnhancementSettings {
if(!pipeline::validSrTarget(srTarget))return "invalid SR target";
if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";
if(multiplier<1||multiplier>4)return "unsupported multiplier";
- if(nrPolicy!=pipeline::NrSizePolicy::Realtime&&nrPolicy!=pipeline::NrSizePolicy::Native)return "invalid NR size policy";
+ if(!pipeline::validNrSizePolicy(nrPolicy))return "invalid NR size policy";
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/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.h
index d4c06f3b..e9e47708 100644
--- a/include/veyra/engine/FgRecoveryBudget.h
+++ b/include/veyra/engine/FgRecoveryBudget.h
@@ -30,9 +30,9 @@ class FgRecoveryBudget {
public:
void reset(){base_.clear();fg_.clear();warmup_.clear();limited_=false;recoveryPairs_=0;retryAt_=0;}
void fgCost(double ms,int64_t now){add(fg_,now,ms);}
- void complete(double ms,bool evaluated,bool warmup,int64_t now){
+ void complete(double ms,bool evaluated,bool warmup,int64_t now,std::optional<double> measuredFg={}){
if(warmup){add(warmup_,now,ms);return;}
- const auto extra=evaluated?p95(fg_,now,20000000):std::optional<double>(0);
+ const auto extra=evaluated?(measuredFg?measuredFg:p95(fg_,now,20000000)):std::optional<double>(0);
// If a generated batch lacks a GPU timing, retain its whole measured
// completion as conservative base cost; never assume free FG.
add(base_,now,std::max(0.0,ms-extra.value_or(0)));
diff --git a/include/veyra/engine/VideoPresenter.h b/include/veyra/engine/VideoPresenter.h
index 29732424..13e06878 100644
--- a/include/veyra/engine/VideoPresenter.h
+++ b/include/veyra/engine/VideoPresenter.h
@@ -19,6 +19,7 @@ public:
uint64_t xessGeneratedCount() const {return sink_.xess()?sink_.xess()->generatedCount():0;}
uint64_t xessPresentedCount() const {return sink_.xess()?sink_.xess()->presentedCount():0;}
bool xessActive() const {return sink_.xess()!=nullptr;}
+ bool xessFailed() const {return xessFailed_;}
// Sustained under-rate may suppress SDK-owned XeSS-FG generation over a
// stable interval (xefgSwapChainSetEnabled); re-enabling goes through the
// per-frame history reset, never a per-frame toggle.
@@ -39,6 +40,7 @@ private:
std::chrono::steady_clock::time_point lastXessFrame_{};
pipeline::FrameIdentity lastXessIdentity_{};
bool xessWasEnabled_=false;
+ bool xessFailed_=false;
bool xessGenerationSuppressed_=false;
void refresh(ID3D12Device*);
};
diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.h
index 93f05e5e..a08b808f 100644
--- a/include/veyra/gfx/PresentSink.h
+++ b/include/veyra/gfx/PresentSink.h
@@ -76,6 +76,7 @@ public:
HWND hwnd() const { return hwnd_; }
IDXGISwapChain3* swapChain() const { return swapChain_.Get(); }
XessPresenter* xess() const { return xess_.get(); }
+ bool xessFailed() const { return xessFailed_; }
void shutdown();
@@ -99,7 +100,9 @@ private:
uint32_t bufferExtentW_ = 0;
uint32_t bufferExtentH_ = 0;
bool tearingSupported_ = false;
+ UINT swapChainFlags_ = 0;
bool pendingResize_ = false;
+ bool xessFailed_ = false;
ID3D12Device* device_ = nullptr;
ID3D12CommandQueue* queue_ = nullptr;
ComPtr<IDXGIFactory2> factory_;
diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.h
index 92418b01..666d41ce 100644
--- a/include/veyra/pipeline/ColorMetadata.h
+++ b/include/veyra/pipeline/ColorMetadata.h
@@ -44,6 +44,10 @@ inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription
case AVCOL_PRI_BT2020:c.primaries=ColorPrimaries::BT2020;c.primariesAssumed=false;break;
default:break;
}
+ if(c.primaries==ColorPrimaries::Unknown||c.primariesAssumed){
+ c.primaries=c.matrix==YuvMatrix::BT2020NCL||c.matrix==YuvMatrix::BT2020CL?ColorPrimaries::BT2020:ColorPrimaries::BT709;
+ c.primariesAssumed=true;
+ }
switch(frame.color_trc){
case AVCOL_TRC_SMPTE2084:c.transfer=TransferFunction::PQ;c.transferAssumed=false;break;
case AVCOL_TRC_ARIB_STD_B67:c.transfer=TransferFunction::HLG;c.transferAssumed=false;break;
@@ -60,7 +64,15 @@ inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription
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;}
-inline uint32_t workingTransferCode(const ColorDescription& c){return c.displayReferred709&&c.transfer==TransferFunction::BT709?3u:transferCode(c.transfer);}
+// BT.2020 10/12-bit SDR uses the BT.709-compatible OETF. Keep it distinct in
+// metadata, but feed the same shader transfer branch rather than sRGB.
+inline uint32_t transferCode(TransferFunction t){return t==TransferFunction::Linear?0u:(t==TransferFunction::BT709||t==TransferFunction::BT2020_10)?2u:1u;}
+inline uint32_t workingTransferCode(const ColorDescription& c){
+ // Our SDR sink encodes sRGB. Decode that same curve for ordinary desktop
+ // BT.709 playback, preserving code values through the no-effects graph.
+ // A camera inverse OETF lifts midtones; BT.1886 -> sRGB darkens them.
+ if(c.preserveSdrCodeValues&&c.transfer==TransferFunction::BT709)return 1u;
+ return c.displayReferred709&&c.transfer==TransferFunction::BT709?3u:transferCode(c.transfer);
+}
}
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 625ec7d3..dd0f3be1 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -1,4 +1,5 @@
#pragma once
+#include "veyra/engine/BackendRecovery.h"
// EnhanceGraph - the real unified processing graph (Playbook R3.2).
// Chains, per real frame:
@@ -228,8 +229,10 @@ public:
void setNrEnabled(bool on);
void setFgEnabled(bool on) { fgEnabled_ = on && !desc_.stillImage; }
bool fgCreated() const;
+ engine::FailedBackend failedBackend() const { return failedBackend_; }
private:
+ engine::FailedBackend failedBackend_=engine::FailedBackend::None;
bool createResources();
bool initZeroAndDepthTextures();
bool initNvof();
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index fb968621..b8d769dc 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -93,6 +93,11 @@ struct ColorDescription {
// Display intent is separate from source VUI. PS5 SDR is displayed with
// BT.1886 (ideal black), not inverse camera OETF, before sRGB presentation.
bool displayReferred709 = false;
+ // Desktop SDR media uses a reversible sRGB working representation so
+ // no-effects output retains the post-matrix RGB code values. This is a
+ // display policy, not a rewrite of the source transfer metadata. Keep
+ // legacy PS5 reference-display intent separate until independently tested.
+ bool preserveSdrCodeValues = false;
bool rangeAssumed = false;
bool matrixAssumed = false;
bool transferAssumed = false;
diff --git a/include/veyra/pipeline/ResolutionPlan.h b/include/veyra/pipeline/ResolutionPlan.h
index 0b1de212..9e5dbd30 100644
--- a/include/veyra/pipeline/ResolutionPlan.h
+++ b/include/veyra/pipeline/ResolutionPlan.h
@@ -9,7 +9,11 @@ struct Extent {
// D3D12 texture extent, not a product aspect-ratio or video-format policy.
bool valid() const {return width>=1&&height>=1&&width<=16384&&height<=16384;}
};
-enum class NrSizePolicy { Realtime, Native };
+enum class NrSizePolicy { Realtime, Native, P480, P720, P900, P1440 };
+constexpr bool validNrSizePolicy(NrSizePolicy policy){return policy>=NrSizePolicy::Realtime&&policy<=NrSizePolicy::P1440;}
+constexpr unsigned nrHeightLimit(NrSizePolicy policy){
+ switch(policy){case NrSizePolicy::Realtime:return 1080;case NrSizePolicy::P480:return 480;case NrSizePolicy::P720:return 720;case NrSizePolicy::P900:return 900;case NrSizePolicy::P1440:return 1440;default:return 0;}
+}
enum class SrTarget : uint32_t { Qhd, Uhd4K, Uhd8K };
constexpr bool validSrTarget(SrTarget target) { return target<=SrTarget::Uhd8K; }
constexpr Extent srTargetExtent(SrTarget target) {
@@ -27,19 +31,21 @@ struct ResolutionPlan {
static ResolutionPlan make(Extent source,bool sr,NrSizePolicy policy,bool exporting,uint64_t revision=0,SrTarget target=SrTarget::Uhd4K,bool nrBeforeSr=false) {
if(!source.valid())throw std::invalid_argument("invalid SDR source extent");
if(!validSrTarget(target))throw std::invalid_argument("invalid SR target");
+ if(!validNrSizePolicy(policy))throw std::invalid_argument("invalid NR size policy");
ResolutionPlan p; p.source=source;p.base=source;
if(sr){const auto limit=srTargetExtent(target);const double scale=std::min(double(limit.width)/source.width,double(limit.height)/source.height);if(scale>1.0)p.base={std::max(2u,uint32_t(source.width*scale+1e-6)&~1u),std::max(2u,uint32_t(source.height*scale+1e-6)&~1u)};}
p.srApplied=sr&&p.base!=source;p.nr=p.base;
if(nrBeforeSr&&!exporting)p.nr=source;
- if(!exporting&&policy==NrSizePolicy::Realtime) {
- const double scale=std::min({1.0,1920.0/p.nr.width,1080.0/p.nr.height});
+ if(!exporting&&policy!=NrSizePolicy::Native) {
+ const double limit=nrHeightLimit(policy);
+ const double scale=std::min({1.0,(limit*16.0/9.0)/p.nr.width,limit/p.nr.height});
if(scale<1.0)p.nr={std::max(1u,uint32_t(p.nr.width*scale)&~1u),std::max(1u,uint32_t(p.nr.height*scale)&~1u)};
}
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&&
+ if(!exporting&&policy!=NrSizePolicy::Native&&
(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/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 19bebd75..94c710ad 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -5,7 +5,7 @@
#include <vector>
#include "veyra/sink/CaptureAudioSession.h"
namespace veyra::source {
-struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;};
+struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;std::wstring key;};
struct CaptureDevice {
std::wstring name;
// DirectShow moniker DevicePath/display name. This is stable across a
@@ -37,6 +37,7 @@ public:
// or start audio until the presenter and enhancement graph are ready.
bool configure(const SourceOpenDesc&);
bool start();
+ bool reconnect(float gain,unsigned syncMode,int offsetMs);
bool setAudioGain(float); // call on the graph owner thread; never system volume
CaptureMetrics metrics()const;
void videoPresented(double ptsMs,int64_t host100ns,int64_t arrival100ns);
@@ -51,5 +52,9 @@ public:
private:
SourceReadStatus readWithWait(pipeline::FramePacket&,const AVFrame**,unsigned milliseconds);
struct Impl;std::unique_ptr<Impl> p_;
+ SourceOpenDesc reconnectDesc_;
+ std::wstring reconnectFormat_;
+ SourceInfo reconnectInfo_;
+ uint64_t epoch_=1,receivedOffset_=0,deliveredOffset_=0,droppedOffset_=0;
};
}
diff --git a/include/veyra/source/CaptureMediaType.h b/include/veyra/source/CaptureMediaType.h
index 81eccbf2..d9669cf2 100644
--- a/include/veyra/source/CaptureMediaType.h
+++ b/include/veyra/source/CaptureMediaType.h
@@ -76,6 +76,7 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
// 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;
+ out.color.preserveSdrCodeValues=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;}
@@ -90,6 +91,7 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
if(ext.VideoPrimaries==9){out.color.primaries=pipeline::ColorPrimaries::BT2020;out.color.primariesAssumed=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_709){out.color.transfer=pipeline::TransferFunction::BT709;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction==15||ext.VideoTransferFunction==16){out.color.transfer=ext.VideoTransferFunction==15?pipeline::TransferFunction::PQ:pipeline::TransferFunction::HLG;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction!=DXVA2_VideoTransFunc_Unknown&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_709&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_22)return false;
}
@@ -121,6 +123,7 @@ 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.packing==y.packing&&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.primaries==y.color.primaries&&x.color.displayReferred709==y.color.displayReferred709&&x.color.preserveSdrCodeValues==y.color.preserveSdrCodeValues&&
x.color.rangeAssumed==y.color.rangeAssumed&&x.color.matrixAssumed==y.color.matrixAssumed&&x.color.transferAssumed==y.color.transferAssumed;
}
}
diff --git a/include/veyra/source/DolbyVision.h b/include/veyra/source/DolbyVision.h
new file mode 100644
index 00000000..ff1633be
--- /dev/null
+++ b/include/veyra/source/DolbyVision.h
@@ -0,0 +1,41 @@
+#pragma once
+#include "veyra/pipeline/FramePacket.h"
+#include <cstdint>
+#include <string>
+
+namespace veyra::source {
+enum class DolbyBaseLayer : uint8_t { None, Unsupported, Hdr10, Sdr, Hlg };
+struct DolbyVisionInfo {
+ bool present=false, baseLayer=false, enhancementLayer=false, rpuDeclared=false, rpuObserved=false;
+ uint8_t profile=0, level=0, compatibility=0;
+ DolbyBaseLayer route() const {
+ if(!present)return DolbyBaseLayer::None;
+ if(!baseLayer)return DolbyBaseLayer::Unsupported;
+ if(profile==7)return DolbyBaseLayer::Hdr10;
+ if(profile!=8&&profile!=10)return DolbyBaseLayer::Unsupported;
+ switch(compatibility){
+ case 1:return DolbyBaseLayer::Hdr10;
+ case 2:return DolbyBaseLayer::Sdr;
+ case 4:return DolbyBaseLayer::Hlg;
+ default:return DolbyBaseLayer::Unsupported;
+ }
+ }
+ std::wstring description() const {
+ if(!present)return {};
+ const auto layer=route();
+ const wchar_t* name=layer==DolbyBaseLayer::Hdr10?L"HDR10":layer==DolbyBaseLayer::Hlg?L"HLG":L"SDR";
+ if(layer==DolbyBaseLayer::Unsupported)return L"Dolby Vision P"+std::to_wstring(profile)+L":此类型需要 RPU 重建,当前不能正确显示";
+ return L"Dolby Vision P"+std::to_wstring(profile)+L" · "+name+L" 基础层兼容(不应用 RPU/增强层,不输出原生 DV)";
+ }
+ bool matches(const pipeline::ColorDescription& c) const {
+ using namespace pipeline;
+ switch(route()){
+ case DolbyBaseLayer::Hdr10:return c.transfer==TransferFunction::PQ&&c.matrix==YuvMatrix::BT2020NCL&&c.primaries==ColorPrimaries::BT2020;
+ case DolbyBaseLayer::Hlg:return c.transfer==TransferFunction::HLG&&c.matrix==YuvMatrix::BT2020NCL&&c.primaries==ColorPrimaries::BT2020;
+ case DolbyBaseLayer::Sdr:return !c.isHdrPath()&&c.matrix==YuvMatrix::BT709&&c.primaries==ColorPrimaries::BT709;
+ case DolbyBaseLayer::None:return true;
+ default:return false;
+ }
+ }
+};
+}
diff --git a/include/veyra/source/IFrameSource.h b/include/veyra/source/IFrameSource.h
index dd1b0a17..27f3f6de 100644
--- a/include/veyra/source/IFrameSource.h
+++ b/include/veyra/source/IFrameSource.h
@@ -8,6 +8,7 @@
#include <string>
#include "veyra/pipeline/FramePacket.h"
+#include "veyra/source/DolbyVision.h"
struct AVFrame;
@@ -38,6 +39,7 @@ struct SourceInfo {
std::string containerName;
std::string videoCodecName;
std::string videoPixelFormatName;
+ DolbyVisionInfo dolbyVision;
pipeline::ColorDescription color;
};
diff --git a/shaders/RgbToLinear.hlsl b/shaders/RgbToLinear.hlsl
index e8a39039..bae60e9c 100644
--- a/shaders/RgbToLinear.hlsl
+++ b/shaders/RgbToLinear.hlsl
@@ -1,4 +1,5 @@
-cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; };
+#include "HdrColor.hlsli"
+cbuffer RgbParams : register(b0) { uint width; uint height; uint transfer; uint limited; float2 reserved; float primaries2020; float padding; };
Texture2D<float4> sourceRgb : register(t0);
RWTexture2D<float4> linearRgb : register(u0);
float decode(float v) {
@@ -13,5 +14,7 @@ void main(uint3 p : SV_DispatchThreadID) {
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);
+ float3 decoded=float3(decode(c.r),decode(c.g),decode(c.b));
+ if(primaries2020>0.5)decoded=HdrTo709(decoded);
+ linearRgb[p.xy]=float4(decoded*c.a,1);
}
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index dde2a344..4ac1637f 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -2,12 +2,12 @@
// Reads plane 0 as R8/R16 UNORM and plane 1 as R8G8/R16G16 UNORM via two
// SRVs; the dispatch covers the full frame. Color metadata (range/matrix/
// transfer) arrives as root constants set per frame from FFmpeg stream data.
-// V1 supports BT.709 and BT.601, limited and full range, SDR transfer only.
+#include "HdrColor.hlsli"
cbuffer YuvParams : register(b0)
{
float4 colorParams0; // x=limitedRange y=matrix709 z=transferSRGB w=padding
- uint4 yuvDimensions; // x=width y=height z=nativeHDR w=chroma location (0=legacy)
+ uint4 yuvDimensions; // x=width y=height z=bit0 nativeHDR, bit1 BT2020 primaries; w=chroma location
};
Texture2D<float> lumaPlane : register(t0); // R8_UNORM or R16_UNORM
@@ -36,7 +36,10 @@ float3 YuvToRgb(float y, float2 uv)
float uu=(uv.x*scale-middle)/(colorParams0.x>0.5?span:maximum);
float vv=(uv.y*scale-middle)/(colorParams0.x>0.5?span:maximum);
- if(colorParams0.y>1.5)return float3(yy+1.4746*vv,yy-0.164553*uu-0.571353*vv,yy+1.8814*uu);
+ if(colorParams0.y>1.5){
+ // BT.2020 non-constant-luminance coefficients.
+ return float3(yy+1.4746*vv,yy-0.164553*uu-0.571353*vv,yy+1.8814*uu);
+ }
if (colorParams0.y > 0.5) {
// BT.709.
@@ -102,7 +105,7 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
nits=1000.0*scene*pow(max(dot(scene,float3(.2627,.6780,.0593)),0),.2);
}
float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);
- if(yuvDimensions.z!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
+ if((yuvDimensions.z&1)!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
else{
// Stable luminance shoulder, fixed 1000-nit reference peak.
// This is SDR mapping, never advertised as native HDR output.
@@ -119,5 +122,6 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
} else if (colorParams0.z > 0.5) {
rgb = float3(SrgbDecode(rgb.r), SrgbDecode(rgb.g), SrgbDecode(rgb.b));
}
+ if(colorParams0.z<3.5&&(yuvDimensions.z&2)!=0)rgb=HdrTo709(rgb);
linearRgb[dispatchThreadId.xy] = float4(rgb, 1.0);
}
diff --git a/shaders/Yuy2ToLinear.hlsl b/shaders/Yuy2ToLinear.hlsl
index 89216df7..e9951010 100644
--- a/shaders/Yuy2ToLinear.hlsl
+++ b/shaders/Yuy2ToLinear.hlsl
@@ -1,8 +1,9 @@
// 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.
+#include "HdrColor.hlsli"
cbuffer Params : register(b0) {
uint width; uint height; uint transfer; uint reserved;
- float limited; float matrix709; float2 padding;
+ float limited; float matrix709; float primaries2020; float padding;
};
Texture2D<float4> packedYuy2 : register(t0);
RWTexture2D<float4> linearRgb : register(u0);
@@ -23,6 +24,9 @@ void main(uint3 p : SV_DispatchThreadID) {
// 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);
+ if(matrix709>1.5)rgb=float3(y+1.4746*uv.y,y-.164553*uv.x-.571353*uv.y,y+1.8814*uv.x);
rgb=saturate(rgb);
- linearRgb[p.xy]=float4(decode(rgb.r),decode(rgb.g),decode(rgb.b),1);
+ float3 decoded=float3(decode(rgb.r),decode(rgb.g),decode(rgb.b));
+ if(primaries2020>0.5)decoded=HdrTo709(decoded);
+ linearRgb[p.xy]=float4(decoded,1);
}
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 0e1c9274..2ca71203 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -184,7 +184,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(stop_||!cachedFrame)break;
}else
#endif
- if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(L"无法打开视频,请查看诊断",true);break;}
+ if(!(physicalCapture?captureSource.configure(od):activeSource->open(od))){status(!isCapture&&!source.errorMessage().empty()?source.errorMessage():L"无法打开视频,请查看诊断",true);break;}
// A file's actual decoded pixel format and HDR VUI are only
// reliable on AVFrame. Prime one frame before constructing
// the graph so AV1/MOV 10-bit and HDR inputs do not get an
@@ -203,6 +203,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
cachedPacket=firstPacket;
}
width=activeSource->info().width;height=activeSource->info().height;duration=isCapture?0:activeSource->info().duration.toDouble();
+ {std::lock_guard lock(mutex_);snapshot_.sourceNotice=activeSource->info().dolbyVision.description();}
}
if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}
pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.hdrInput=!isImage&&activeSource->info().color.isHdrPath();
@@ -210,7 +211,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.rgbInput=isImage||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);
gd.captureBitDepth=activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P010?10:activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;
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,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);
+ const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);
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;
const bool nvidiaAdapter=ctx.adapter().isNvidia;
const bool xessFg=options.settings.frameGenerationBackend==FrameGenerationBackend::XeSS;
@@ -220,7 +221,37 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.hdrOutput=options.settings.useHdrPreview(gd.hdrInput,gfx::PresentSink::hdrDisplayActive(window));
veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));
gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
- if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}
+ std::wstring backendRecoveryWarning;
+ auto initializePreview=[&](pipeline::EnhanceGraphDesc& desc,PlayerOptions& selected){
+ backendRecoveryWarning.clear();
+ for(unsigned attempt=0;attempt<5;++attempt){
+ bool opened=graph.initialize(desc);
+ auto failure=graph.failedBackend();
+ if(opened){
+ opened=presenter.open(ctx,window,graph,selected.settings.captureCompatible)&&graph.createViews();
+ failure=FailedBackend::Infrastructure;
+ if(opened&&graph.xessEnabled()&&!presenter.xessActive()){opened=false;failure=FailedBackend::Fg;}
+ }
+ if(opened)return true;
+ auto reduced=selected.snapshot();
+ if(FAILED(ctx.device()->GetDeviceRemovedReason())||!disableFailedBackend(reduced,failure))return false;
+ veyra::log::warn("backend-recovery",std::format("initialization failed component={} attempt={} revision={} -> nr={} sr={} multiplier={}; original SDK error above",unsigned(failure),attempt+1,reduced.revision,reduced.nr,reduced.sr,reduced.multiplier));
+ if(!backendRecoveryWarning.empty())backendRecoveryWarning+=L";";
+ backendRecoveryWarning+=std::wstring(backendFailureName(failure))+L"初始化失败,已关闭依赖效果(错误码见日志)";
+ if(!ring.drainQueue()||!ring.discardRecording())return false;
+ presenter.close();graph.shutdown();selected=PlayerOptions::from(reduced);
+ const auto plan=pipeline::ResolutionPlan::make({width,height},selected.sr,reduced.nrPolicy,isImage,reduced.revision,reduced.srTarget,reduced.lowLatency&&selected.nr);
+ desc.workWidth=plan.base.width;desc.workHeight=plan.base.height;desc.nrWidth=plan.nr.width;desc.nrHeight=plan.nr.height;desc.flowWidth=plan.flow.width;desc.flowHeight=plan.flow.height;
+ desc.enableNr=selected.nr&&nvidiaAdapter;desc.enableSr=plan.srApplied&&nvidiaAdapter;desc.enableFg=selected.fg&&(nvidiaAdapter||reduced.frameGenerationBackend==FrameGenerationBackend::XeSS);desc.fgMultiplier=selected.fgMultiplier;
+ desc.enableNvofStandalone=desc.enableNr;desc.nrBeforeSr=!isImage&&reduced.lowLatency&&selected.nr&&desc.enableSr;
+ }
+ return false;
+ };
+ const auto initialRequested=options.snapshot();
+ if(!initializePreview(gd,options)){status(L"视频初始化失败,请查看对应组件的诊断日志",true);break;}
+ if(!backendRecoveryWarning.empty()){
+ std::lock_guard lock(mutex_);desired_.rejectVideoRequest(initialRequested,options.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;
+ }
if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg))){
veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested features: nr={} sr={} fgBackend={} flowBackend={}",options.nr,options.sr,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend)));
status(L"当前非 NVIDIA 适配器:NR、NVIDIA 超分与 DLSS 已禁用;可使用 XeSS 预览和 AMD 光流",false);
@@ -240,6 +271,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
bool initialRemoteFramePending=isRemote;
bool initialFileFramePending=!isImage&&!isCapture;
uint64_t activeSeekId=0;
+ Clock::time_point seekStarted{};
+ uint64_t seekDecoded=0;
bool fileAwaitingVideo=true,fileAudioAlignPending=true,fileInputEnded=false;double lastFilePresentedMs=0,lastFilePresentLateness=0;std::deque<double> latenessSamples;
if(!isImage&&!isCapture&&audioPipe.open(path)){
audioPipe.holdForVideo();audioPipe.startThread(&audio,true);audioStarted=true;
@@ -294,6 +327,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
pipeline::EnhanceGraph::FrameOutputs output;
std::shared_ptr<FrameFlowWindow> flow;
Clock::time_point processStart;
+ std::optional<double> gpuExecutionMs,fgExecutionMs;
bool real=false;
std::atomic<bool> ready=false;
Clock::time_point readyObserved{};
@@ -335,6 +369,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
auto collectTimings=[&]{
auto record=[&](const diagnostics::GpuFrameTiming& sample){
const auto& fgCost=sample.gpu[size_t(diagnostics::GpuStage::FgBatch)];
+ for(auto& watch:pendingCompletions){
+ const auto& id=watch->output.batch.identity;
+ if(id.epoch==sample.identity.epoch&&id.settingsRevision==sample.identity.settingsRevision&&id.sourceFrameId==sample.identity.sourceFrameId){
+ if(const auto span=diagnostics::graphExecutionSpanMs(sample))watch->gpuExecutionMs=span;
+ if(fgCost.state==diagnostics::SampleState::Measured)watch->fgExecutionMs=fgCost.milliseconds;
+ }
+ }
if(sample.identity.settingsRevision==fgBudgetRevision&&fgCost.state==diagnostics::SampleState::Measured&&fgCost.milliseconds)fgBudget.fgCost(*fgCost.milliseconds,host100ns());
if(frameFlow)frameFlow->gpuFrame(sample,host100ns());
for(size_t i=0;i<sample.gpu.size();++i){const auto& gpu=sample.gpu[i];
@@ -348,9 +389,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// Shared with the presenter: resolve each batch on this single
// object so SDK status and generated counts are consumed once.
auto pollCompletions=[&]{
+ collectTimings();
for(auto it=pendingCompletions.begin();it!=pendingCompletions.end();){
auto& watch=**it;auto& batch=watch.output;
if(!graph.resolveGeneration(batch)){++it;continue;}
+ // The GPU may finish between the first poll and resolve.
+ // Collect its timestamps before removing this watch.
+ if(!watch.gpuExecutionMs)collectTimings();
unsigned valid=0,invalid=0;
for(unsigned i=0;i<batch.batch.count;++i)if(batch.batch.frames[i].kind==pipeline::FrameKind::Generated){
if(batch.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;
@@ -358,7 +403,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
watch.flow->ready(batch.batch.batchId,watch.real,valid,invalid,host100ns());
traceFrame(diagnostics::TraceKind::Ready,batch.batch.identity,batch.batch.batchId,std::max(batch.videoFenceValue,batch.genFenceValue),batch.batch.b100ns,invalid,valid,elapsedMs(watch.processStart));
if(watch.real)completedProcessing(batch.batch.identity);
- if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(elapsedMs(watch.processStart),batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns());
+ if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(watch.gpuExecutionMs.value_or(elapsedMs(watch.processStart)),batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns(),watch.fgExecutionMs);
completeReset(batch.batch.identity);
watch.readyObserved=Clock::now();watch.ready=true;it=pendingCompletions.erase(it);
}
@@ -394,7 +439,47 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
return lastAudioClockMs;
};
uint64_t hdrDisplayCheck=0;
+ bool captureRecovering=false;unsigned captureRetries=0;
+ Clock::time_point captureRetryAt{};
+ bool xessPresentationRecovery=false;
+ auto recoverXessPresentation=[&]{
+ if(!presenter.xessFailed()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;
+ auto reduced=options.snapshot();
+ if(!disableFailedBackend(reduced,FailedBackend::Fg))return false;
+ holdFileAudio();fileAudioAlignPending=true;
+ drainLivePresentation();
+ if(!ring.drainQueue()||!ring.discardRecording())return false;
+ out={};hasOutput=false;
+ // A failed scheduler stays failed after cancel. Recreate it on
+ // its owner, then rebuild the SDK swapchain via settings below.
+ if(liveScheduler)liveScheduler=std::make_unique<LiveGpuScheduler>();
+ {
+ std::lock_guard lock(mutex_);
+ desired_.rejectVideoRequest(options.snapshot(),reduced);
+ desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;
+ snapshot_.backendWarning=L"XeSS 呈现失败,正在恢复基础播放;错误码见日志";
+ }
+ veyra::log::warn("backend-recovery","XeSS presentation failed; drained commands, requesting swapchain rebuild without FG");
+ xessPresentationRecovery=true;
+ reset=true;pendingResetCause=pipeline::ResetReason::Settings;
+ return true;
+ };
while(!stop_){
+ collectTimings();
+ if(captureRecovering){
+ if(Clock::now()<captureRetryAt){std::this_thread::sleep_for(std::chrono::milliseconds(20));continue;}
+ ++captureRetries;
+ {std::lock_guard lock(mutex_);snapshot_.captureReconnectAttempts=captureRetries;}
+ status(std::format(L"采集信号中断,正在重连原设备(第 {} 次)",captureRetries));
+ if(captureSource.reconnect(muted_?0.0f:volume_.load(),unsigned(options.settings.audioSync),options.settings.audioOffsetMs)){
+ captureRecovering=false;reset=true;pendingResetCause=pipeline::ResetReason::DeviceLost;captureSampler.reset();
+ {std::lock_guard lock(mutex_);snapshot_.captureRecovering=false;}
+ status(L"采集设备已重新连接,等待新画面");
+ }else{
+ captureRetryAt=Clock::now()+std::chrono::seconds(std::min(5u,captureRetries));
+ continue;
+ }
+ }
if(gd.hdrInput&&GetTickCount64()-hdrDisplayCheck>2000){
hdrDisplayCheck=GetTickCount64();
const bool native=options.settings.useHdrPreview(gd.hdrInput,gfx::PresentSink::hdrDisplayActive(window));
@@ -403,7 +488,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(audioStarted)publishAudioStatus();
if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}
advanceLive();
- if(liveScheduler&&liveScheduler->failed()){status(L"视频呈现失败,请查看诊断",true);break;}
+ if(liveScheduler&&liveScheduler->failed()){if(recoverXessPresentation())continue;status(L"视频呈现失败,请查看诊断",true);break;}
const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);
captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
if(physicalCapture){const bool available=captureSource.setAudioGain(gain);const auto audioState=captureSource.audioState();std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;snapshot_.captureAudio=audioState;snapshot_.audioInputChannels=audioState.inputChannels;snapshot_.audioOutputChannels=audioState.outputChannels;}
@@ -464,15 +549,16 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
resetRecord->rebuilt=rebuild;
markResetStage(diagnostics::ResetStage::Drain);
if(!accepted){finishReset(diagnostics::ResetOutcome::Failed);status(L"设置切换排空失败,已停止",true);break;}
- if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=graph.initialize(nextDesc)&&presenter.open(ctx,window,graph,requested.captureCompatible)&&graph.createViews();
+ backendRecoveryWarning.clear();
+ if(accepted&&rebuild){presenter.close();graph.shutdown();markResetStage(diagnostics::ResetStage::Destroy);accepted=initializePreview(nextDesc,next);
markResetStage(diagnostics::ResetStage::Create);
- if(accepted&&graph.xessEnabled()&&!presenter.xessActive()){
- veyra::log::warn("settings","requested XeSS presenter unavailable; rejecting transaction and restoring previous backend");
- accepted=false;
- }
if(!accepted){presenter.close();graph.shutdown();if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible)||!graph.createViews()){status(L"设置失败且旧资源恢复失败,已停止",true);break;}}
}else if(accepted)accepted=graph.applySettings(requested);
if(accepted){
+ if(xessPresentationRecovery){backendRecoveryWarning=L"XeSS 呈现失败,已关闭补帧并恢复播放;错误码见日志";xessPresentationRecovery=false;}
+ if(!backendRecoveryWarning.empty()){
+ std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,next.snapshot());snapshot_.desired=desired_;snapshot_.backendWarning=backendRecoveryWarning;
+ }
options=next;gd=nextDesc;transaction=true;reset=true;
resetRecord->epoch=0;
if(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested settings revision={} nr={} sr={} fgBackend={} flowBackend={}",requested.revision,next.nr,next.sr,frameGenerationBackendName(requested.frameGenerationBackend),opticalFlowBackendName(requested.opticalFlowBackend)));
@@ -484,9 +570,12 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(stop_)break;
double seek;{std::lock_guard lock(mutex_);seek=seekSeconds_.exchange(-1);if(seek>=0)activeSeekId=snapshot_.seekRequested;}
if(seek>=0&&!isImage&&!isCapture){
+ seekStarted=Clock::now();seekDecoded=0;
holdFileAudio();fileAudioAlignPending=true;
drainLivePresentation();
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
+ veyra::log::info("seek-latency",std::format("request={} targetSeconds={:.3f} drainAndDemuxMs={:.3f}",activeSeekId,seek,elapsedMs(seekStarted)));
+ initialFileFramePending=false;av_frame_free(&cachedFrame);out={};hasOutput=false;
discardBefore=seek*1000;seekPreviewPending=true;reset=true;pendingResetCause=pipeline::ResetReason::Seek;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
}
if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
@@ -498,7 +587,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
if(audioStarted)audioPipe.setPaused(true);wasPaused=true;
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;}
+ if(hasOutput&&!presenter.present(ctx,ring,graph,out.videoSlot,false,referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,out.batch.identity,previewView())){if(recoverXessPresentation())continue;status(L"画面呈现失败",true);break;}
if(hasOutput&&graph.resolveGeneration(out))completeReset(out.batch.identity);
std::this_thread::sleep_for(std::chrono::milliseconds(16));continue;
}
@@ -541,6 +630,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
collectTimings();seekPreviewPending=false;status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;
}
if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){
+ if(physicalCapture){
+ drainLivePresentation();if(!ring.drainQueue()){status(L"采集恢复时GPU排空失败",true);break;}
+ captureSource.videoReset();av_frame_free(&cachedFrame);hasOutput=false;out={};
+ captureRecovering=true;captureRetries=0;captureRetryAt=Clock::now()+std::chrono::milliseconds(500);
+ {std::lock_guard lock(mutex_);snapshot_.captureRecovering=true;snapshot_.captureFps=0;}
+ status(L"采集信号中断,等待原设备恢复");continue;
+ }
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}
#endif
@@ -557,6 +653,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
reset=true;pendingResetCause=pipeline::ResetReason::Resize;
}
const bool rereadCached=transaction&&frame==cachedFrame;
+ if(!isImage&&!isCapture&&seekSeconds_>=0)continue;
const bool halfRate=isCapture&&options.settings.content==ContentRate::Capture60To30&&
CaptureHalfRate::supported(activeSource->info().averageFps);
if(reset||pipeline::breaksHistory(pkt.flags))captureSampler.reset();
@@ -573,6 +670,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const double decodeMs=elapsedMs(decodeStart);decodeTimes.add(decodeMs);
double pts=isImage?0:pkt.pts.toDouble()*1000;
if(isCapture&&frames==0){anchor=Clock::now();anchorMs=pts;}
+ if(seekPreviewPending)++seekDecoded;
if(pts+0.1<discardBefore)continue;
auto retainCandidate=[&](){
if(frame==cachedFrame)return true;
@@ -677,6 +775,28 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
bool processed=false;{processWaitBase=ring.cpuWaitCount();processWaitMsBase=ring.cpuWaitMilliseconds();processSubmitBase=ring.submitCount();processed=!injectedReject&&graph.process(frame,pts,historyReset,out,pkt.sequence,&pkt.colorInfo,comparisonMode_!=0,admitFg);processSlotWaitMs=ring.cpuWaitMilliseconds()-processWaitMsBase;}
previewSkipSinceProcess=false;
if(!processed){
+ const auto failedComponent=graph.failedBackend();
+ if(!transaction){
+ auto reduced=options.snapshot();
+ if(SUCCEEDED(ctx.device()->GetDeviceRemovedReason())&&disableFailedBackend(reduced,failedComponent)){
+ const auto attempted=options.snapshot();
+ drainLivePresentation();
+ if(!ring.drainQueue()||!ring.discardRecording()){status(L"增强故障恢复排空失败",true);break;}
+ out={};hasOutput=false;presenter.close();graph.shutdown();
+ {std::lock_guard lock(mutex_);reduced.revision=++nextRevision_;}
+ options=PlayerOptions::from(reduced);
+ const auto plan=pipeline::ResolutionPlan::make({width,height},options.sr,reduced.nrPolicy,isImage,reduced.revision,reduced.srTarget,reduced.lowLatency&&reduced.nr);
+ gd.workWidth=plan.base.width;gd.workHeight=plan.base.height;gd.nrWidth=plan.nr.width;gd.nrHeight=plan.nr.height;gd.flowWidth=plan.flow.width;gd.flowHeight=plan.flow.height;
+ gd.enableNr=options.nr&&nvidiaAdapter;gd.enableSr=plan.srApplied&&nvidiaAdapter;gd.enableFg=options.fg&&(nvidiaAdapter||reduced.frameGenerationBackend==FrameGenerationBackend::XeSS);gd.fgMultiplier=options.fgMultiplier;gd.enableNvofStandalone=gd.enableNr;gd.settingsRevision=reduced.revision;gd.nrBeforeSr=!isImage&&reduced.lowLatency&&gd.enableNr&&gd.enableSr;
+ if(!initializePreview(gd,options)){status(L"增强故障后的基础图重建失败",true);break;}
+ backendRecoveryWarning=std::wstring(backendFailureName(failedComponent))+L"运行失败,已关闭对应效果;错误码见日志"+(backendRecoveryWarning.empty()?L"":L";"+backendRecoveryWarning);
+ {std::lock_guard lock(mutex_);desired_.rejectVideoRequest(attempted,options.snapshot());snapshot_.desired=desired_;snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;snapshot_.backendWarning=backendRecoveryWarning;}
+ veyra::log::warn("backend-recovery",std::format("runtime component={} disabled; rebuilt revision={} nr={} sr={} multiplier={}; retry next source frame",unsigned(failedComponent),options.settings.revision,options.nr,options.sr,options.snapshot().multiplier));
+ finishReset(diagnostics::ResetOutcome::Failed);reset=true;pendingResetCause=pipeline::ResetReason::Settings;
+ holdFileAudio();fileAudioAlignPending=true;
+ continue;
+ }
+ }
if(transaction){
ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);
gd=previousDesc;
@@ -684,7 +804,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
finishReset(diagnostics::ResetOutcome::RolledBack);
std::lock_guard lock(mutex_);desired_.rejectVideoRequest(requested,previous);snapshot_.desired=desired_;snapshot_.rejectedRevision=requested.revision;snapshot_.applying=desired_!=previous;snapshot_.status=L"参数执行失败,已整套回滚";transaction=false;
}else{status(L"参数回滚失败,已停止",true);break;}
- }else{status(L"增强执行失败;请查看日志",true);break;}
+ }else{status(std::wstring(backendFailureName(failedComponent))+L"执行失败;请查看日志",true);break;}
}
if(transaction){std::lock_guard lock(mutex_);snapshot_.applied=options.snapshot();snapshot_.applying=desired_!=snapshot_.applied;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.nrBeforeSr?L"低延迟 · NR先行后超分":gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)");veyra::log::info("display-color",std::format("hdrInput={} hdrOutput={} forceSdrPreview={}",gd.hdrInput,gd.hdrOutput,options.settings.forceSdrPreview));veyra::log::info("settings",std::format("Applied revision={} sourcePtsMs={} fgBackend={} flowBackend={} multiplier={} (source kept open)",options.settings.revision,pts,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend),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));
@@ -816,7 +936,9 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(xessPresented)flow->xessSubmitted(xessPresented,xessGenerated,host100ns());
if(didPresent&&!isCapture){
lastFilePresentedMs=itemPtsMs;lastFilePresentLateness=fileAwaitingVideo?0:nowMs()-itemPtsMs;
- {std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId&&snapshot_.applied.revision==item.identity.settingsRevision){snapshot_.position=itemPtsMs/1000;snapshot_.lateMs=lastFilePresentLateness;snapshot_.seekPresented=activeSeekId;}}
+ {std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId&&snapshot_.applied.revision==item.identity.settingsRevision){
+ if(activeSeekId&&snapshot_.seekPresented!=activeSeekId)veyra::log::info("seek-latency",std::format("request={} firstPresentMs={:.3f} decodedToTarget={} ptsMs={:.3f}",activeSeekId,elapsedMs(seekStarted),seekDecoded,itemPtsMs));
+ snapshot_.position=itemPtsMs/1000;snapshot_.lateMs=lastFilePresentLateness;snapshot_.seekPresented=activeSeekId;}}
double nextPts=itemPtsMs+sourceIntervalMs;
for(unsigned next=s.next+1;next<batch.batch.count;++next){const auto& candidate=batch.batch.frames[next];if(candidate.kind!=pipeline::FrameKind::Generated||(candidate.validity==pipeline::GenerationValidity::Valid&&comparisonMode_==0)){nextPts=double(candidate.pts100ns)/10000;break;}}
if(audioStarted){audioPipe.videoPresented(nextPts);audioPipe.setPaused(paused_);}
@@ -909,7 +1031,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();
}
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,options.settings.srTarget,options.settings.lowLatency&&options.nr);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;
+ measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.snapshot().nrPolicy,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;
LiveStats completed;if(liveScheduler)completed=liveStats;
uint64_t skipped=0;{std::lock_guard lock(mutex_);skipped=snapshot_.captureRateSkipped-rateSkippedBase;}
frameFlow->update([&](auto& m){m.counters.captureReceived=captureStats.received-captureFlowBase.received;m.counters.mailboxOverwritten=captureStats.dropped-captureFlowBase.dropped;m.counters.sourceSkippedBeforeGraph=skipped;m.slotReuseWaitCount=slotWaitCount;m.slotReuseWaitMs=slotWaitMilliseconds;m.counters.commandSlotsInFlight=slotsInFlight;m.counters.commandSlotHighWater=std::max(m.counters.commandSlotHighWater,slotsInFlight);});
@@ -937,7 +1059,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
snapshot_.audioVideoWaits=audioPipe.videoWaitCount();
snapshot_.srActive=gd.enableSr&&graphStats.srEvaluateCount>0;
snapshot_.fgActive=options.fg&&(graph.xessEnabled()?presenter.xessActive()&&graphStats.fgGeneratedFrames>0:graph.fgEnabled()&&measured.flow.counters.fgReadyValid>0);
- if(transaction&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();
+ if(transaction&&backendRecoveryWarning.empty()&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();
snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;
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=liveScheduler?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 7ae52803..79c797b8 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -42,8 +42,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
veyra::log::warn("export","export rejected: selected adapter has no NVIDIA NVENC; AMD AMF and Intel encoder backends are not implemented");
break;
}
- source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od))break;
- const auto info=source.info();if(!pipeline::Extent{info.width,info.height}.valid()){progress(0,L"输入尺寸超出GPU单纹理能力");break;}
+ source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od)){failureReason=source.errorMessage();break;}
+ auto info=source.info();if(!pipeline::Extent{info.width,info.height}.valid()){progress(0,L"输入尺寸超出GPU单纹理能力");break;}
// Bounded metadata scan; decoded pixels are not retained. Rewind the
// file source afterwards, preserving all source frames for the export.
std::vector<double> samples;bool scanError=false;
@@ -53,11 +53,18 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
CfrTimeline timeline(rateNum,rateDen,info.timestampQuantum,samples.front());
if(!timeline.valid()){progress(0,L"无法确认一致的恒定帧率,已停止导出");veyra::log::error("export-timeline","CFR rejected source=preflight; no timestamp-consistent rate candidate");break;}
source.close();if(!source.open(od))break; // reopen from the true beginning, including negative PTS
+ // The first decoded frame is authoritative when container headers omit
+ // transfer/range metadata. Do not build an SDR graph from stale header
+ // defaults after the preflight discovered HDR/BT.2020 pixels.
+ pipeline::FramePacket firstPacket;const AVFrame* firstFrame=nullptr;
+ if(source.read(firstPacket,&firstFrame)!=source::SourceReadStatus::Frame||!firstFrame){failureReason=L"导出预读首帧失败";break;}
+ info=source.info(); // retain this frame for the export, without decoding it again
const AVRational rate=av_mul_q({rateNum,rateDen},{int(options.fg?options.fgMultiplier:1),1});
outputRate=rate;
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,options.settings.srTarget);
pipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();hdrExport=gd.hdrOutput;
+ gd.captureBitDepth=info.color.pixelFormat==pipeline::SourcePixelFormat::P010?10:info.color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;
if(gd.hdrOutput&&!hevc){failureReason=L"HDR视频请使用HEVC Main10导出(选择HEVC)";break;}
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.nrRuntime=options.settings.nrRuntime;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.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
if(!graph.initialize(gd)||!graph.createViews())break;
@@ -92,7 +99,11 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());
if(avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE)<0||avformat_write_header(mux,nullptr)<0)break;headerWritten=true;
uint64_t sourceCount=0,generatedCount=0,holdCount=0;int64_t outputIndex=0;bool error=false;std::shared_ptr<pipeline::FrameLease> lastReal;
- while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;const auto rs=source.read(packet,&frame);if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){failureReason=source.errorMessage();error=true;break;}
+ while(!cancel){if(frameBoundary&&!frameBoundary()){error=true;break;}pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ source::SourceReadStatus rs;
+ if(sourceCount==0){packet=firstPacket;frame=firstFrame;rs=source::SourceReadStatus::Frame;}
+ else rs=source.read(packet,&frame);
+ if(rs==source::SourceReadStatus::Eos)break;if(rs!=source::SourceReadStatus::Frame||packet.pts.isUnknown()){failureReason=source.errorMessage();error=true;break;}
if(sourceCount==0)videoOriginSeconds=packet.pts.toDouble();
const double expectedPts=timeline.expected(sourceCount);
if(!timeline.accepts(sourceCount,packet.pts.toDouble())){
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index c807599c..221f2e94 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -20,15 +20,18 @@ bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::Enh
}
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,bool referencesValid,int comparison,bool baseReference,float split,pipeline::FrameIdentity identity,PreviewView view) {
+ xessFailed_=false;
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")));
if((unsigned(rc.right)!=sink_.width()||unsigned(rc.bottom)!=sink_.height())&&GetTickCount64()>=deferUntil&&now-lastResize_>=std::chrono::milliseconds(100)) {
if(!ring.drainQueue())return false;sink_.resize(rc.right,rc.bottom);
- if(sink_.bufferWidth()!=unsigned(rc.right)||sink_.bufferHeight()!=unsigned(rc.bottom))return false;
+ // A capture hook may temporarily retain a DXGI buffer. Keep the old
+ // valid buffers and let DXGI scale them until a later resize succeeds.
+ if(!sink_.currentBackBuffer()||FAILED(ctx.device()->GetDeviceRemovedReason()))return false;
refresh(ctx.device());lastResize_=now;xessWasEnabled_=false;
}
- if(sink_.xess()&&!sink_.xess()->beginFrame())return false;
+ if(sink_.xess()&&!sink_.xess()->beginFrame()){xessFailed_=true;return false;}
Status st=Status::Ok;uint32_t commandSlot=0;auto* list=ring.acquireNext(commandSlot,st);if(!list)return false;
gpuTimer_.frame(identity.sourceFrameId?identity:pipeline::FrameIdentity{0,0,submittedCount()+1},ctx.fence());gpuTimer_.mark(list,diagnostics::GpuStage::Blit);
auto* source=generated?graph.generatedFrameResource(slot):graph.videoFrameResource(slot);auto* bb=sink_.currentBackBuffer();if(!bb)return false;
@@ -59,6 +62,9 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
}
for(auto& b:barriers)std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(2,barriers);
if(auto* xess=sink_.xess()){
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",nullptr,0)>0){
+ veyra::log::warn("backend-test","Injected XeSS tagging failure with recorded commands");xessFailed_=true;return false;
+ }
const float fit=std::min(float(sink_.bufferWidth())/graph.workWidth(),float(sink_.bufferHeight())/graph.workHeight());
const LONG w=std::max(1L,LONG(std::lround(graph.workWidth()*fit))),h=std::max(1L,LONG(std::lround(graph.workHeight()*fit)));
const LONG left=(LONG(sink_.bufferWidth())-w)/2,top=(LONG(sink_.bufferHeight())-h)/2;
@@ -80,14 +86,15 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
toCopy[i].Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE;
}
list->ResourceBarrier(3,toCopy);
- if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},true,reset,elapsed))return false;
+ if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},true,reset,elapsed)){xessFailed_=true;return false;}
for(auto& barrier:toCopy)std::swap(barrier.Transition.StateBefore,barrier.Transition.StateAfter);
list->ResourceBarrier(3,toCopy);
- }else if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},false,reset,elapsed))return false;
+ }else if(!xess->tag(list,bb,motion,depth,{left,top,left+w,top+h},false,reset,elapsed)){xessFailed_=true;return false;}
lastXessFrame_=now;lastXessIdentity_=identity;xessWasEnabled_=enabled;
}
gpuTimer_.mark(list,diagnostics::GpuStage::Blit,true);gpuTimer_.resolve(list);
- if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=sink_.swapChain()->GetCurrentBackBufferIndex();hasPresented_=true;return sink_.present(st);
+ if(!ring.submitAndSignal(commandSlot))return false;gpuTimer_.submitted(ring.lastSignaledValue());lastBuffer_=sink_.swapChain()->GetCurrentBackBufferIndex();hasPresented_=true;
+ const bool presented=sink_.present(st);xessFailed_=sink_.xessFailed();return presented;
}
bool VideoPresenter::readPresentedFrameForTest(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,sink::RgbaImage& image){
if(!hasPresented_||!sink_.swapChain()||!ring.drainQueue())return false;
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index 26e47b6c..ef97c48a 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -163,12 +163,17 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
DXGI_SWAP_CHAIN_DESC1 actual{};
const HRESULT descResult=swapChain_->GetDesc1(&actual);
- if(FAILED(descResult)||actual.SwapEffect!=scd.SwapEffect){
- log::error("present",std::format("swapchain mode rejected hr=0x{:X} requested={} actual={}",unsigned(descResult),unsigned(scd.SwapEffect),unsigned(actual.SwapEffect)));
+ const bool flip=actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL||actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_DISCARD;
+ if(FAILED(descResult)||!flip||actual.Format!=scd.Format||actual.BufferCount!=3||
+ actual.Width!=scd.Width||actual.Height!=scd.Height||actual.SampleDesc.Count!=1||actual.SampleDesc.Quality!=0){
+ log::error("present",std::format("swapchain contract rejected hr=0x{:X} requestedMode={} actualMode={} format={} buffers={} extent={}x{} samples={}/{}",unsigned(descResult),unsigned(scd.SwapEffect),unsigned(actual.SwapEffect),unsigned(actual.Format),actual.BufferCount,actual.Width,actual.Height,actual.SampleDesc.Count,actual.SampleDesc.Quality));
status=Status::WindowFailure;return false;
}
+ if(actual.SwapEffect!=scd.SwapEffect)log::warn("present",std::format("swapchain mode negotiated requested={} actual={} (compatible flip model)",unsigned(scd.SwapEffect),unsigned(actual.SwapEffect)));
+ swapChainFlags_=actual.Flags;
+ tearingSupported_=tearingSupported_&&(actual.Flags&DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)!=0;
log::info("present", std::format("present-sink: window {}x{} swapEffect={} buffers=3 vsync={} tearing={} captureCompatible={} (capture not verified)",
- width_, height_, desc.captureCompatible?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, tearingSupported_ ? 1 : 0, desc.captureCompatible));
+ width_, height_, actual.SwapEffect==DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL?"flip-sequential":"flip-discard", desc_.vsync ? 1 : 0, tearingSupported_ ? 1 : 0, desc.captureCompatible));
return true;
}
@@ -215,15 +220,16 @@ ID3D12Resource* PresentSink::currentBackBuffer()
bool PresentSink::present(Status& status)
{
+ xessFailed_=false;
const UINT syncInterval = desc_.vsync ? 1 : 0;
const UINT flags = (!desc_.vsync && tearingSupported_) ? DXGI_PRESENT_ALLOW_TEARING : 0;
++attemptedPresentCount_;
- if(xess_&&!xess_->beforePresent()){status=Status::WindowFailure;return false;}
+ if(xess_&&!xess_->beforePresent()){xessFailed_=true;status=Status::WindowFailure;return false;}
const HRESULT hr = swapChain_->Present(syncInterval, flags);
if (SUCCEEDED(hr)) {
++presentCount_;
backBufferIndex_ = swapChain_->GetCurrentBackBufferIndex();
- if(xess_&&!xess_->afterPresent()){status=Status::WindowFailure;return false;}
+ if(xess_&&!xess_->afterPresent()){xessFailed_=true;status=Status::WindowFailure;return false;}
return true;
}
++failedPresentCount_;
@@ -293,7 +299,7 @@ void PresentSink::resize(uint32_t width, uint32_t height)
{
if (width == 0 || height == 0) return;
if (width == width_ && height == height_) return;
- const UINT flags = tearingSupported_ ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
+ const UINT flags = swapChainFlags_;
// DXGI spec compliance before ResizeBuffers: wait for outstanding GPU
// work on the presenting queue, then release ALL back-buffer references.
if (!waitForQueueIdle()) return;
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 41acd1d7..f9bf8eed 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -63,6 +63,7 @@ EnhanceGraph::~EnhanceGraph()
// ---------------------------------------------------------------------------
bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
{
+ failedBackend_=engine::FailedBackend::Infrastructure;
if(!desc.protection.validate().empty())return false;
if(desc.srMotionProbe){
const auto d=desc.srMotionProbe->GetDesc();ComPtr<ID3D12Device> device;
@@ -114,11 +115,17 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
if(!gpuTimer_.initialize(context_.device(),context_.directQueue()))veyra::log::warn("gpu-timestamp","GPU timing unavailable");
if (!createResources()) return false;
if (!initZeroAndDepthTextures()) return false;
- if (!initNvof()) return false;
+ if (!initNvof()) { failedBackend_=engine::FailedBackend::OpticalFlow; return false; }
+ if(nrEnabled_&&GetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",nullptr,0)){
+ failedBackend_=engine::FailedBackend::Nr;
+ veyra::log::error("backend-recovery-test","test-only NR initialization rejection before SDK call; not a hardware failure");return false;
+ }
if (!initNgxFeatures()) return false;
+ failedBackend_=engine::FailedBackend::Infrastructure;
if (!createComputePasses()) return false;
initialized_ = true;
+ failedBackend_=engine::FailedBackend::None;
veyra::log::info("graph", std::format("initialized src={}x{} work={}x{} sr={} nr={} fg={} nvof={}",
srcW_, srcH_, workW_, workH_, srEnabled_ ? 1 : 0, nrEnabled_ ? 1 : 0,
fgEnabled_ ? 1 : 0, (nvof_ && nvof_->initialized()) ? 1 : 0));
@@ -339,6 +346,7 @@ bool EnhanceGraph::initNvof()
bool EnhanceGraph::initNgxFeatures()
{
+ failedBackend_=engine::FailedBackend::NgxCore;
if (desc_.noNgx || desc_.noFeatures || (!nrEnabled_&&!srEnabled_&&!fgEnabled_)) {
veyra::log::info("graph", "NGX core/features skipped by disabled-feature configuration");
return true;
@@ -375,6 +383,7 @@ bool EnhanceGraph::initNgxFeatures()
fgCapsAvailable_ = false;
fgMultiFrameMax_ = 0;
if (fgEnabled_ && desc_.frameGenerationBackend==engine::FrameGenerationBackend::Dlss) {
+ failedBackend_=engine::FailedBackend::Fg;
fgBackend_ = std::make_unique<ngx::DlssFgBackend>();
ngx::DlssFgBackend::Capability fgCaps{};
const bool fgAvailable = fgBackend_->queryCapability(*coreHost_, fgCaps, st);
@@ -390,6 +399,7 @@ bool EnhanceGraph::initNgxFeatures()
}
if(nrEnabled_){
+ failedBackend_=engine::FailedBackend::Nr;
if(desc_.nrRuntime!=engine::NrRuntime::Original&&desc_.nrRuntime!=engine::NrRuntime::Community&&desc_.nrRuntime!=engine::NrRuntime::Ampere)return false;
auto nrDirectory=std::filesystem::path(desc_.runtimeAbsPath);if(desc_.nrRuntime==engine::NrRuntime::Community)nrDirectory/=L"nr-community";
if(desc_.nrRuntime==engine::NrRuntime::Ampere)nrDirectory/=L"nr-ampere";
@@ -404,6 +414,7 @@ bool EnhanceGraph::initNgxFeatures()
return false;
}
}
+ failedBackend_=engine::FailedBackend::NgxCore;
ngxParams_ = coreHost_->allocateParameters(st);
if (ngxParams_ == nullptr) return false;
@@ -426,14 +437,15 @@ bool EnhanceGraph::initNgxFeatures()
pb.setI32(p::kPerfQualityValue, 1);
pb.setU32(p::kCreationNodeMask, 1); pb.setU32(p::kVisibilityNodeMask, 1);
ID3D12GraphicsCommandList* list = ring_.acquire(0, st);
- if (list == nullptr) return false;
+ if (list == nullptr) { failedBackend_=engine::FailedBackend::Infrastructure; return false; }
+ failedBackend_=engine::FailedBackend::Nr;
if (!nrAdapter_->snippetCreateFeature(list, ngxParams_, &nrHandle_, nrResult_, nrSeh_) ||
nrResult_ != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
veyra::log::error("graph", std::format("NR create failed 0x{:X}", nrResult_));
return false;
}
- (void)ring_.submitAndSignal(0);
- (void)ring_.waitIdle();
+ failedBackend_=engine::FailedBackend::Infrastructure;
+ if(!ring_.submitAndSignal(0)||!ring_.waitIdle())return false;
}
if (srEnabled_ && !desc_.noFeatures) {
@@ -442,14 +454,15 @@ bool EnhanceGraph::initNgxFeatures()
sd.outputWidth = workW_; sd.outputHeight = workH_;
sd.perfQuality = 1; sd.enableOutputSubrects = false;
ID3D12GraphicsCommandList* list = ring_.acquire(0, st);
- if (list == nullptr) return false;
+ if (list == nullptr) { failedBackend_=engine::FailedBackend::Infrastructure; return false; }
+ failedBackend_=engine::FailedBackend::Sr;
if(desc_.videoSrQuality){videoSrBackend_=std::make_unique<ngx::VideoSrBackend>();if(!videoSrBackend_->create(*coreHost_,list))return false;veyra::log::info("video-sr",std::format("selected quality={} input={}x{} output={}x{}",desc_.videoSrQuality,srcW_,srcH_,workW_,workH_));}
else if (!srBackend_->create(*coreHost_, list, ngxParams_, sd, st) || !srBackend_->created()) {
veyra::log::error("graph", "SR create failed");
return false;
}
- (void)ring_.submitAndSignal(0);
- (void)ring_.waitIdle();
+ failedBackend_=engine::FailedBackend::Infrastructure;
+ if(!ring_.submitAndSignal(0)||!ring_.waitIdle())return false;
}
// Still images have no temporal pair and must not depend on FG support.
@@ -462,13 +475,14 @@ bool EnhanceGraph::initNgxFeatures()
fd.renderWidth = workW_; fd.renderHeight = workH_;
fd.backbufferFormat = outputFormat();
ID3D12GraphicsCommandList* list = ring_.acquire(0, st);
- if (list == nullptr) return false;
+ if (list == nullptr) { failedBackend_=engine::FailedBackend::Infrastructure; return false; }
+ failedBackend_=engine::FailedBackend::Fg;
if (!fgBackend_->create(*coreHost_, list, ngxParams_, fd, st) || !fgBackend_->created()) {
veyra::log::error("graph", std::format("FG create failed 0x{:X}", fgBackend_->createResult()));
return false;
}
- (void)ring_.submitAndSignal(0);
- (void)ring_.waitIdle();
+ failedBackend_=engine::FailedBackend::Infrastructure;
+ if(!ring_.submitAndSignal(0)||!ring_.waitIdle())return false;
ID3D12GraphicsCommandList* wlist = ring_.acquire(0, st);
if (wlist == nullptr) return false;
@@ -502,7 +516,7 @@ bool EnhanceGraph::initNgxFeatures()
warmOk=fgBackend_->evaluate(wlist,ngxParams_,fe,st)&&warmOk;
D3D12_RESOURCE_BARRIER u{};u.Type=D3D12_RESOURCE_BARRIER_TYPE_UAV;u.UAV.pResource=fe.outputInterpolated;wlist->ResourceBarrier(1,&u);
}
- if(!warmOk)return false;
+ if(!warmOk){failedBackend_=engine::FailedBackend::Fg;return false;}
for (int i = 0; i < 4; ++i) b[i].Transition.StateBefore = b[i].Transition.StateAfter;
b[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
b[1].Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
@@ -523,7 +537,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||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((desc_.rgbInput||desc_.yuy2Input)&&(!rgbPass_.loadShader(desc_.yuy2Input?"Yuy2ToLinear.dxil":"RgbToLinear.dxil",cs)||!rgbPass_.create(context_.device(),cs,8,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, 19, 1, 1)) return false;
@@ -676,6 +690,7 @@ bool EnhanceGraph::createViews()
// ---------------------------------------------------------------------------
bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, FrameOutputs& out, uint64_t sourceFrameId, const ColorDescription* color, bool retainReferences, const FgAdmission& admitFg)
{
+ failedBackend_=engine::FailedBackend::Infrastructure;
out = FrameOutputs{};
out.ptsMs = ptsMs;
if(!sourceFrameId)sourceFrameId=realFrameIndex_+1;
@@ -694,11 +709,11 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(desc_.hdrInput&&!resolved.isHdrPath()){
veyra::log::error("hdr","HDR source transfer changed to SDR; reopen/rebuild required");return false;
}
- if(resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10||(resolved.matrix==YuvMatrix::BT2020NCL&&!desc_.hdrInput)){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
+ if(resolved.matrix==YuvMatrix::BT2020CL){veyra::log::error("graph","BT.2020 constant-luminance requires a dedicated conversion; refusing NCL substitution");return false;}
if(resolved.isHdrPath()&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
veyra::log::error("hdr","Unsupported PQ/HLG colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
}
- if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709));
+ if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={} preserveSdrCodes={} workingTransfer={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709,resolved.preserveSdrCodeValues,workingTransferCode(resolved)));
if (resolved.isHdrPath()&&(!desc_.hdrInput||desc_.rgbInput||desc_.yuy2Input)) {
veyra::log::error("graph", "HDR input requires an explicit YUV HDR contract; RGB/YUY2 HDR ingress is unsupported"); return false;
}
@@ -894,14 +909,14 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list, srcRgba_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
if(desc_.rgbInput||desc_.yuy2Input){
const float c[8]={uintBits(srcW_),uintBits(srcH_),uintBits(workingTransferCode(resolved)),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};
+ resolved.range==ColorRange::Full?0.0f:1.0f,resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,resolved.primaries==ColorPrimaries::BT2020?1.0f:0.0f,0};
rgbPass_.bind(list,c,gpuHandleOf(rgbPass_,0).ptr,gpuHandleOf(rgbPass_,1).ptr);
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
const float constants[8] = { resolved.range==ColorRange::Full?0.0f:1.0f,
resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
resolved.transfer==TransferFunction::HLG?5.0f:resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?(nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?1.0f:0.0f):(desc_.captureBitDepth==16?2.0f:desc_.wideYuvInput()?1.0f:0.0f)),
- uintBits(srcW_), uintBits(srcH_), uintBits(desc_.hdrOutput?1u:0u),
+ uintBits(srcW_), uintBits(srcH_), uintBits((desc_.hdrOutput?1u:0u)|(resolved.primaries==ColorPrimaries::BT2020?2u:0u)),
uintBits(resolved.reconstructChroma?std::max(1u,unsigned(resolved.chromaLocation)):0u) };
yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
@@ -1010,7 +1025,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
const float enc[8]={uintBits(srcW_),uintBits(srcH_),uintBits(srcW_),uintBits(srcH_),desc_.hdrOutput?3.0f:1.0f,0,0,0};
blitPass_.bind(list,enc,gpuHandleOf(blitPass_,desc_.nrBeforeSr?18:0).ptr,gpuHandleOf(blitPass_,16).ptr);list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);tracker_.uavBarrier(list,videoSrInput_.Get());
tracker_.transition(list,videoSrInput_.Get(),D3D12_RESOURCE_STATE_COMMON);tracker_.transition(list,videoSrOutput_.Get(),D3D12_RESOURCE_STATE_COMMON);
- if(!videoSrBackend_->evaluate(list,videoSrInput_.Get(),videoSrOutput_.Get(),desc_.videoSrQuality))return false;
+ if(!videoSrBackend_->evaluate(list,videoSrInput_.Get(),videoSrOutput_.Get(),desc_.videoSrQuality)){failedBackend_=engine::FailedBackend::Sr;return false;}
tracker_.uavBarrier(list,videoSrOutput_.Get());tracker_.transition(list,videoSrOutput_.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);tracker_.transition(list,workRgba_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float dec[8]={uintBits(workW_),uintBits(workH_),uintBits(workW_),uintBits(workH_),-1,0,0,0};
if(desc_.hdrOutput){
@@ -1029,6 +1044,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(desc_.srMotionProbe)ed.motionVectors=desc_.srMotionProbe;
ed.reset = reset;
if (!srBackend_->evaluate(list, ngxParams_, ed, st)) {
+ failedBackend_=engine::FailedBackend::Sr;
veyra::log::error("graph", "sr evaluate failed");
return false;
}
@@ -1112,11 +1128,16 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
if(!injectedFailureConsumed&&desc_.model.style==2&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_STYLE2",nullptr,0)){
injectedFailureConsumed=true;veyra::log::error("settings-test","injected NR execution rejection before NGX; rollback exercise, not a hardware failure");return false;
}
+ if(GetEnvironmentVariableW(L"VEYRA_TEST_NR_RUNTIME_FAILURE",nullptr,0)){
+ failedBackend_=engine::FailedBackend::Nr;
+ veyra::log::error("backend-recovery-test","test-only NR runtime rejection before Evaluate; exercises partially recorded command cleanup, not a hardware failure");return false;
+ }
gpuTimer_.mark(nlist,GpuStage::Nr);
uint64_t er = 0; uint32_t es = 0;
if (!nrAdapter_->snippetEvaluateFeature(nlist, nrHandle_, ngxParams_, er, es) ||
er != static_cast<uint64_t>(NVSDK_NGX_Result_Success)) {
diagnostic.stage="NR Evaluate";diagnostic.ngx=er;diagnostic.seh=es;Logger::diagnosticContext(diagnostic);veyra::log::error("graph", std::format("NR evaluate failed 0x{:X} seh={}", er, es));
+ failedBackend_=engine::FailedBackend::Nr;
return false;
}
gpuTimer_.mark(nlist,GpuStage::Nr,true);
@@ -1221,7 +1242,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
fe.mvecScaleY=haveFlow?-1.0f/static_cast<float>(workH_):1.0f;
if(sub==1)gpuTimer_.mark(flist,GpuStage::FgBatch);
const auto timingStage=static_cast<GpuStage>(unsigned(GpuStage::Fg1)+sub-1);gpuTimer_.mark(flist,timingStage);
- if(!fgBackend_->evaluate(flist,ngxParams_,fe,st))return false;
+ if(!fgBackend_->evaluate(flist,ngxParams_,fe,st)){failedBackend_=engine::FailedBackend::Fg;return false;}
++out.fgEvaluated;
gpuTimer_.mark(flist,timingStage,true);if(sub==desc_.fgMultiplier-1)gpuTimer_.mark(flist,GpuStage::FgBatch,true);
tracker_.uavBarrier(flist,genFrame_[generatedSlot].Get());
@@ -1245,6 +1266,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
}
}
+ failedBackend_=engine::FailedBackend::None;
if(runFg)fgHistorySkipped_=false;
uploadFences_[parity]=ring_.lastSignaledValue();
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index ebef603e..622159c2 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -195,7 +195,9 @@ std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config){
if(bitmap&&bitmap->biWidth>0&&bitmap->biWidth<=3840&&std::abs(int64_t(bitmap->biHeight))>0&&std::abs(int64_t(bitmap->biHeight))<=2160&&duration>0){unsigned width=bitmap->biWidth,height=unsigned(std::abs(int64_t(bitmap->biHeight)));double fps=1e7/duration;
const auto pixel=capturePixelName(type->subtype);CaptureMediaLayout layout;const bool valid=captureMediaLayout(*type,layout);const bool knownRaw=capturePacking(type->subtype)!=CapturePacking::Unknown;
const wchar_t* support=valid?((layout.format==AV_PIX_FMT_P010||layout.format==AV_PIX_FMT_P016)?L"原生 · SDR":L"原生"):knownRaw?L"布局/颜色暂不支持":L"需系统解码/转换";
- out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.2f} fps · {} · {} [format {}]",width,height,fps,pixel,support,i)});
+ wchar_t subtype[40]{},formatType[40]{};StringFromGUID2(type->subtype,subtype,40);StringFromGUID2(type->formattype,formatType,40);
+ const auto key=std::format(L"{}:{}:{}:{}:{}:{}:{}",width,bitmap->biHeight,duration,subtype,formatType,bitmap->biBitCount,bitmap->biCompression);
+ out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.2f} fps · {} · {} [format {}]",width,height,fps,pixel,support,i),key});
}
freeType(type);
}
@@ -356,6 +358,8 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
if(av_frame_get_buffer(*f,32)<0)return false;
}
p.configured=true;
+ reconnectDesc_=desc;reconnectInfo_=p.info;reconnectFormat_.clear();
+ for(const auto& candidate:enumerateFormats(p.config.Get()))if(candidate.index==format){reconnectFormat_=candidate.key;break;}
// 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);
@@ -370,16 +374,42 @@ bool CaptureCardSource::start(){
if(p.info.opened&&p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";
veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} nominalFps={:.3f} mailbox=1 ownedBuffers=2",unsigned(hr),p.info.width,p.info.height,p.info.averageFps));return p.info.opened;
}
+bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){
+ CaptureSelection selection;
+ if(!parseCapturePath(reconnectDesc_.path,selection)||!selection.stable||reconnectFormat_.empty()){
+ log::warn("capture-reconnect","Stable device and format identity unavailable; manual selection required");return false;
+ }
+ const auto desc=reconnectDesc_;const auto key=reconnectFormat_;const auto expected=reconnectInfo_;
+ // Stop callbacks before carrying counters into the next device session.
+ // Never hold the mailbox lock while DirectShow Stop waits for a callback.
+ if(p_->control)p_->control->Stop();
+ {std::lock_guard lock(p_->mutex);
+ receivedOffset_+=p_->received;deliveredOffset_+=p_->sequence;droppedOffset_+=p_->dropped;}
+ close();
+ int format=-1;for(const auto& candidate:formatsByPath(selection.videoPath))if(candidate.key==key){format=candidate.index;break;}
+ if(format<0)return false;
+ auto reopen=desc;reopen.path=std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(selection.videoPath),format,selection.audio,encodePath(selection.audioPath),selection.colorOverride);
+ bool ok=configure(reopen);
+ if(ok){const auto& current=p_->info;
+ ok=current.width==expected.width&&current.height==expected.height&&current.color.pixelFormat==expected.color.pixelFormat&&
+ current.color.transfer==expected.color.transfer&&current.color.matrix==expected.color.matrix&&current.color.primaries==expected.color.primaries&&
+ current.color.range==expected.color.range&&current.color.displayReferred709==expected.color.displayReferred709&&current.color.preserveSdrCodeValues==expected.color.preserveSdrCodeValues;
+ if(!ok)log::warn("capture-reconnect","Negotiated input contract changed; explicit reselection required");
+ }
+ if(ok){setAudioGain(gain);setAudioSync(syncMode,offsetMs);ok=start();}
+ if(ok){++epoch_;log::info("capture-reconnect",std::format("reconnected epoch={} formatIndex={} history reset required",epoch_,format));return true;}
+ close();reconnectDesc_=desc;reconnectFormat_=key;reconnectInfo_=expected;return false;
+}
CaptureMetrics CaptureCardSource::metrics()const{
auto& p=*p_;std::lock_guard lock(p.mutex);CaptureMetrics m;
- m.received=p.received;m.delivered=p.sequence;m.dropped=p.dropped;m.readAgeMs=p.readAgeMs;
+ m.received=receivedOffset_+p.received;m.delivered=deliveredOffset_+p.sequence;m.dropped=droppedOffset_+p.dropped;m.readAgeMs=p.readAgeMs;
if(p.received>1){const double elapsed=std::chrono::duration<double>(p.latestArrival-p.firstArrival).count();if(elapsed>0)m.callbackFps=(p.received-1)/elapsed;}
if(p.sequence)m.frameAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();return m;
}
SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,30);}
SourceReadStatus CaptureCardSource::tryRead(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,0);}
SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,const AVFrame** frame,unsigned milliseconds){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;
- long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
+ long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)log::warn("capture-reconnect",std::format("DirectShow event={} detail=0x{:X}",code,uint64_t(a)));p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}
double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;
{
std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.callbackError;});
@@ -394,6 +424,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
p.lastDrop=p.dropped;p.lastPts=time;++p.sequence;sequence=p.received;
}
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.sequence+=receivedOffset_;packet.sourceEpoch=epoch_;
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;
}
diff --git a/src/source/MediaFileSource.cpp b/src/source/MediaFileSource.cpp
index d5dc0695..fbcdd721 100644
--- a/src/source/MediaFileSource.cpp
+++ b/src/source/MediaFileSource.cpp
@@ -2,6 +2,7 @@
#include "veyra/pipeline/ColorMetadata.h"
#include <climits>
+#include <cstddef>
#include <cmath>
#include <format>
#include <string_view>
@@ -11,6 +12,7 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/pixdesc.h>
+#include <libavutil/dovi_meta.h>
}
namespace veyra::source {
@@ -102,9 +104,13 @@ pipeline::ColorDescription MediaFileSource::parseColor(const AVCodecParameters*
}
if (cd.primaries == pipeline::ColorPrimaries::Unknown) {
- cd.primaries = pipeline::ColorPrimaries::BT709;
+ cd.primaries = cd.matrix==pipeline::YuvMatrix::BT2020NCL||cd.matrix==pipeline::YuvMatrix::BT2020CL?pipeline::ColorPrimaries::BT2020:pipeline::ColorPrimaries::BT709;
cd.primariesAssumed = true;
}
+ // Standard desktop SDR playback retains RGB signal levels after range
+ // expansion and YUV matrix conversion. Match the working decode to the
+ // sink encode; don't apply a reference-monitor gamma adjustment here.
+ cd.preserveSdrCodeValues = true;
AVFrame metadata{};metadata.format=params->format;metadata.height=info_.height;metadata.color_range=params->color_range;metadata.colorspace=params->color_space;metadata.color_trc=params->color_trc;
return pipeline::resolveFrameColor(metadata,cd);
}
@@ -167,6 +173,17 @@ bool MediaFileSource::open(const SourceOpenDesc& desc)
info_.videoPixelFormatName = params->format >= 0 && av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format))
? av_get_pix_fmt_name(static_cast<AVPixelFormat>(params->format)) : "unknown";
info_.color = parseColor(params);
+ if(const auto* side=av_packet_side_data_get(params->coded_side_data,params->nb_coded_side_data,AV_PKT_DATA_DOVI_CONF)){
+ if(side->size<offsetof(AVDOVIDecoderConfigurationRecord,dv_bl_signal_compatibility_id)+sizeof(uint8_t)){
+ errorMessage_=L"Dolby Vision 配置信息不完整";return false;
+ }
+ const auto& config=*reinterpret_cast<const AVDOVIDecoderConfigurationRecord*>(side->data);
+ auto& dv=info_.dolbyVision;dv.present=true;dv.profile=config.dv_profile;dv.level=config.dv_level;
+ dv.baseLayer=config.bl_present_flag!=0;dv.enhancementLayer=config.el_present_flag!=0;
+ dv.rpuDeclared=config.rpu_present_flag!=0;dv.compatibility=config.dv_bl_signal_compatibility_id;
+ log::info("source-dovi",std::format("profile={} level={} compatibility={} bl={} el={} rpuDeclared={} route={} nativeOutput=0 rpuApplied=0",dv.profile,dv.level,dv.compatibility,dv.baseLayer,dv.enhancementLayer,dv.rpuDeclared,int(dv.route())));
+ if(dv.route()==DolbyBaseLayer::Unsupported){errorMessage_=dv.description();return false;}
+ }
sequence_ = 0;
framesRead_ = 0;
@@ -274,6 +291,17 @@ SourceReadStatus MediaFileSource::read(pipeline::FramePacket& out, const AVFrame
}
out.sourceKind = pipeline::SourceKind::File;
out.colorInfo = pipeline::resolveFrameColor(*frame,info_.color);
+ auto& dv=info_.dolbyVision;
+ const bool hasRpu=av_frame_get_side_data(frame,AV_FRAME_DATA_DOVI_METADATA)||av_frame_get_side_data(frame,AV_FRAME_DATA_DOVI_RPU_BUFFER);
+ if(hasRpu&&!dv.present){
+ errorMessage_=L"检测到 Dolby Vision RPU,但缺少基础层兼容声明,无法确认颜色,已停止";
+ return SourceReadStatus::Error;
+ }
+ if(hasRpu&&!dv.rpuObserved){dv.rpuObserved=true;log::info("source-dovi","decoded RPU observed; compatibility playback does not apply dynamic metadata");}
+ if(!dv.matches(out.colorInfo)){
+ errorMessage_=L"Dolby Vision 基础层颜色与兼容声明不匹配,已停止以避免错误颜色";
+ return SourceReadStatus::Error;
+ }
// D3D12VA frames expose the underlying surface through AV_PIX_FMT_D3D12,
// so resolveFrameColor cannot infer NV12/P010 from frame->format. HDR
// hardware surfaces are P010 by contract; SDR surfaces are NV12. Software
diff --git a/src/source/WasapiAudioInput.cpp b/src/source/WasapiAudioInput.cpp
index 9cb7073d..8d922859 100644
--- a/src/source/WasapiAudioInput.cpp
+++ b/src/source/WasapiAudioInput.cpp
@@ -124,14 +124,15 @@ struct WasapiAudioInput::Impl {
void run(){
ComScope apartment;
if(!checked(apartment.hr,"capture thread COM")){std::lock_guard lock(mutex);error=L"WASAPI 输入线程初始化失败";return;}
- for(unsigned attempt=0;attempt<4&&!stopping;++attempt){
+ for(uint64_t attempt=0;!stopping;++attempt){
if(attempt){std::lock_guard lock(mutex);++metrics.retries;}
const HRESULT hr=stream();
{std::lock_guard lock(mutex);if(session)session->stop();session.reset();
- if(FAILED(hr))error=std::format(L"WASAPI 输入失败 0x{:08X};{}",uint32_t(hr),attempt<3?L"仅重试所选设备,视频继续":L"重试已用尽,请重新连接");}
+ if(FAILED(hr))error=std::format(L"WASAPI 输入失败 0x{:08X};等待原设备重新连接,视频继续",uint32_t(hr));}
if(SUCCEEDED(hr)||stopping)break;
- log::warn("wasapi-input",std::format("input attempt={} failed hr=0x{:08X} retriesRemaining={} defaultFallback=0",attempt+1,uint32_t(hr),3-attempt));
- if(attempt<3&&WaitForSingleObject(stopEvent.value,1000)==WAIT_OBJECT_0)break;
+ const DWORD backoff=DWORD(std::min<uint64_t>(attempt+1,5)*1000);
+ log::warn("wasapi-input",std::format("input attempt={} failed hr=0x{:08X} retryInMs={} defaultFallback=0",attempt+1,uint32_t(hr),backoff));
+ if(WaitForSingleObject(stopEvent.value,backoff)==WAIT_OBJECT_0)break;
}
}
};
diff --git a/tests/integration/FileSdrRoundTripCases.h b/tests/integration/FileSdrRoundTripCases.h
new file mode 100644
index 00000000..6751601b
--- /dev/null
+++ b/tests/integration/FileSdrRoundTripCases.h
@@ -0,0 +1,61 @@
+#pragma once
+#include "veyra/source/MediaFileSource.h"
+extern "C" {
+#include <libavutil/hwcontext.h>
+}
+
+// Diagnostic readbacks only. Expected RGB comes directly from decoded YUV
+// and legal-range/matrix equations, not from the graph's transfer functions.
+inline int fileSdrRoundTripCases(veyra::gfx::D3D12DeviceContext& ctx,
+ veyra::gfx::CommandSlotRing& ring,const wchar_t* path) {
+ using namespace veyra;int failures=0;
+ for(bool hardware:{false,true}) {
+ source::MediaFileSource source;source::SourceOpenDesc open;open.path=path;
+ open.preferHardwareDecode=hardware;open.d3d12Device=ctx.device();open.d3d12Queue=ctx.directQueue();
+ if(!source.open(open)||!source.seek({60,1}))return failures+1;
+ pipeline::FramePacket packet;const AVFrame* decoded=nullptr;
+ if(source.read(packet,&decoded)!=source::SourceReadStatus::Frame||!decoded)return failures+1;
+ AVFrame* transferred=av_frame_alloc();const AVFrame* reference=decoded;
+ if(decoded->hw_frames_ctx) {
+ if(av_hwframe_transfer_data(transferred,decoded,0)<0){av_frame_free(&transferred);return failures+1;}
+ reference=transferred;
+ }
+ const bool nv12=reference->format==AV_PIX_FMT_NV12;
+ if((!nv12&&reference->format!=AV_PIX_FMT_YUV420P)||packet.colorInfo.isHdrPath()||
+ packet.colorInfo.matrix!=pipeline::YuvMatrix::BT709){av_frame_free(&transferred);return failures+1;}
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
+ gd.sourceWidth=gd.workWidth=decoded->width;gd.sourceHeight=gd.workHeight=decoded->height;
+ gd.enableNr=gd.enableSr=gd.enableFg=false;gd.noFeatures=true;
+ pipeline::EnhanceGraph::FrameOutputs output;sink::RgbaImage image;
+ bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(decoded,60000,true,output,1,&packet.colorInfo)&&
+ sink::readRgba8(ctx,ring,graph.videoFrameResource(output.videoSlot),image);
+ double maximum=0,sum=0,bias=0;size_t samples=0;
+ const bool full=packet.colorInfo.range==pipeline::ColorRange::Full;
+ if(ok)for(unsigned y=0;y<image.height;++y)for(unsigned x=0;x<image.width;++x) {
+ const double yy=std::clamp((reference->data[0][size_t(y)*reference->linesize[0]+x]-(full?0.0:16.0))/(full?255.0:219.0),0.0,1.0);
+ const size_t offset=size_t(y/2)*reference->linesize[1]+(nv12?x/2*2:x/2);
+ const double u=(reference->data[1][offset]-128.0)/(full?255.0:224.0);
+ const double v=((nv12?reference->data[1][offset+1]:reference->data[2][size_t(y/2)*reference->linesize[2]+x/2])-128.0)/(full?255.0:224.0);
+ const double rgb[]={yy+1.5748*v,yy-.1873242729306488*u-.4681242729306488*v,yy+1.8556*u};
+ for(unsigned c=0;c<3;++c){double error=image.pixels[(size_t(y)*image.width+x)*4+c]-255*std::clamp(rgb[c],0.0,1.0);maximum=std::max(maximum,std::abs(error));sum+=std::abs(error);bias+=error;++samples;}
+ }
+ ok=ok&&samples&&maximum<2&&sum/samples<.6&&(!hardware||source.info().hardwareDecodeActive);
+ std::cout<<"FILE_SDR_ROUNDTRIP hardware="<<hardware<<" active="<<source.info().hardwareDecodeActive
+ <<" pts="<<decoded->pts<<" maxCodeError="<<maximum<<" meanCodeError="<<(samples?sum/samples:-1)
+ <<" signedBias="<<(samples?bias/samples:-1)<<" pass="<<ok<<std::endl;
+ failures+=!ok;
+ if(!image.pixels.empty()) {
+ HWND window=CreateWindowExW(0,L"STATIC",L"SDR file diagnostic",WS_POPUP,0,0,image.width,image.height,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ engine::VideoPresenter presenter;sink::RgbaImage shown;
+ bool presented=window&&presenter.open(ctx,window,graph)&&presenter.present(ctx,ring,graph,output.videoSlot,false)&&presenter.readPresentedFrameForTest(ctx,ring,shown);
+ unsigned maxPresent=0;
+ if(presented&&shown.pixels.size()==image.pixels.size())for(size_t i=0;i<shown.pixels.size();++i)maxPresent=std::max(maxPresent,unsigned(std::abs(int(shown.pixels[i])-int(image.pixels[i]))));
+ else presented=false;
+ presented=presented&&maxPresent<=1;
+ std::cout<<"FILE_SDR_PRESENT hardware="<<hardware<<" maxCodeError="<<maxPresent<<" pass="<<presented<<std::endl;
+ failures+=!presented;ring.drainQueue();presenter.close();if(window)DestroyWindow(window);
+ }
+ output={};ring.drainQueue();graph.shutdown();av_frame_free(&transferred);source.close();
+ }
+ return failures;
+}
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index 7398ab65..b054906e 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -8,6 +8,7 @@
#include "veyra/source/MediaFileSource.h"
#include "veyra/RuntimePaths.h"
#include "CaptureFormatGpuCases.h"
+#include "SdrColorGpuCases.h"
#include <iostream>
#include <cmath>
extern "C" {
@@ -18,7 +19,7 @@ int wmain(int argc,wchar_t** argv){
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 2;
- int failures=captureGpuCases(ctx,ring);
+ int failures=captureGpuCases(ctx,ring)+sdrColorGpuCases(ctx,ring);
for(bool hlg:{false,true})for(bool native:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=32;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.hdrInput=true;gd.hdrOutput=native;
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index 6e497211..cc608df6 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -98,13 +98,15 @@ int wmain(int argc,wchar_t**argv){
}
#endif
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--nr-first")==0||wcscmp(argv[3],L"--seek-stress")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--file-fg-recovery")==0||wcscmp(argv[3],L"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--backend-recovery")==0||wcscmp(argv[3],L"--nr-first")==0||wcscmp(argv[3],L"--seek-stress")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0||wcscmp(argv[3],L"--file-endpoint")==0||wcscmp(argv[3],L"--file-continuity")==0||wcscmp(argv[3],L"--file-fg-recovery")==0||wcscmp(argv[3],L"--reset-rollback")==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 nrFirst=argc==4&&wcscmp(argv[3],L"--nr-first")==0;
if(nrFirst){options.captureReplayForTest=false;options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=2;options.settings.lowLatency=true;options.settings.videoSrQuality=2;engine.setVolume(0,true);}
const bool seekStress=argc==4&&wcscmp(argv[3],L"--seek-stress")==0;
+ const bool backendRecovery=argc==4&&wcscmp(argv[3],L"--backend-recovery")==0;
+ if(backendRecovery){options.captureReplayForTest=false;options.nr=true;options.fg=false;engine.setVolume(0,true);SetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",L"1");}
if(seekStress){options.captureReplayForTest=false;options.nr=options.fg=true;options.realtime=false;options.fgMultiplier=3;engine.setVolume(0,true);}
const bool halfRate=argc==4&&wcscmp(argv[3],L"--half-rate")==0;
const bool sourceGap=argc==4&&wcscmp(argv[3],L"--source-gap")==0;
@@ -123,6 +125,31 @@ int wmain(int argc,wchar_t**argv){
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);
+ if(backendRecovery){
+ check(until([](const auto& s){return s.frames>20&&!s.applied.nr&&!s.backendWarning.empty();},25),"injected NR init failure retains real basic playback");
+ SetEnvironmentVariableW(L"VEYRA_TEST_NR_INIT_FAILURE",nullptr);
+ auto enabled=engine.snapshot().applied;enabled.nr=true;
+ check(engine.requestSettings(enabled),"retry NR explicitly after initialization failure");
+ check(until([](const auto& s){return !s.applying&&s.applied.nr&&s.nrActive;},25),"real NR runs after explicit retry");
+ const auto before=engine.snapshot();
+ SetEnvironmentVariableW(L"VEYRA_TEST_NR_RUNTIME_FAILURE",L"1");
+ check(until([&](const auto& s){return s.frames>before.frames+20&&!s.applied.nr&&!s.backendWarning.empty();},25),"injected NR Evaluate failure releases commands and keeps playback advancing");
+ SetEnvironmentVariableW(L"VEYRA_TEST_NR_RUNTIME_FAILURE",nullptr);
+ enabled=engine.snapshot().applied;enabled.nr=true;
+ check(engine.requestSettings(enabled),"retry NR after runtime recovery");
+ check(until([](const auto& s){return !s.applying&&s.applied.nr&&s.nrActive;},25),"real NR resumes in same session after runtime recovery");
+ enabled=engine.snapshot().applied;enabled.nr=false;enabled.multiplier=2;enabled.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;
+ check(engine.requestSettings(enabled),"enable real XeSS before presentation fault");
+ check(until([](const auto& s){return !s.applying&&s.fgActive&&s.generated>10;},25),"XeSS generates real frames before injected fault");
+ const auto xessBefore=engine.snapshot();
+ SetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",L"1");
+ check(until([&](const auto& s){return s.frames>xessBefore.frames+20&&s.applied.multiplier==1&&!s.applying&&!s.backendWarning.empty();},25),"XeSS presentation fault recovers through new scheduler and swapchain");
+ SetEnvironmentVariableW(L"VEYRA_TEST_XESS_PRESENT_FAILURE",nullptr);
+ enabled=engine.snapshot().applied;enabled.multiplier=2;
+ check(engine.requestSettings(enabled),"explicitly retry XeSS after presentation recovery");
+ check(until([](const auto& s){return !s.applying&&s.fgActive&&s.generated>10;},25),"XeSS generates again in the same session");
+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"recovered session drains");DestroyWindow(window);CoUninitialize();return failures?1:0;
+ }
if(nrFirst){
check(until([](const auto& s){return s.frames>30&&s.srActive&&s.nrActive&&s.fgActive;},25),"NR-first RTX Video SR and FG execute");
auto snapshot=engine.snapshot();check(snapshot.metrics.resolution.nr==snapshot.metrics.resolution.source,"NR processes source extent before SR");
diff --git a/tests/integration/SdrColorGpuCases.h b/tests/integration/SdrColorGpuCases.h
new file mode 100644
index 00000000..d790454e
--- /dev/null
+++ b/tests/integration/SdrColorGpuCases.h
@@ -0,0 +1,47 @@
+#pragma once
+#include "CaptureFormatGpuCases.h"
+#include <array>
+#include <cmath>
+
+inline int sdrColorGpuCases(veyra::gfx::D3D12DeviceContext& ctx,veyra::gfx::CommandSlotRing& ring){
+ using namespace veyra;int failures=0;
+ const std::array<std::array<double,3>,6> patches={{{0,0,0},{.5,.5,.5},{1,1,1},{.7,.2,.3},{.2,.7,.3},{.2,.3,.7}}};
+ for(bool wideGamut:{false,true})for(bool full:{false,true})for(int packing=0;packing<4;++packing){
+ const bool rgb=packing==0,yuy2=packing==1,ten=packing==3;
+ AVFrame* frame=av_frame_alloc();frame->width=48;frame->height=16;
+ frame->format=rgb?AV_PIX_FMT_BGRA:yuy2?AV_PIX_FMT_YUYV422:ten?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_YUV420P;
+ if(av_frame_get_buffer(frame,32)<0){av_frame_free(&frame);return failures+1;}
+ const double kr=wideGamut?.2627:.2126,kb=wideGamut?.0593:.0722,kg=1-kr-kb;
+ const double max=ten?1023:255,black=full?0:ten?64:16,span=full?max:ten?876:219,chroma=full?max:ten?896:224,mid=ten?512:128;
+ for(unsigned y=0;y<16;++y)for(unsigned x=0;x<48;++x){
+ const auto& c=patches[x/8];const double luma=kr*c[0]+kg*c[1]+kb*c[2];
+ const unsigned yy=unsigned(std::lround(black+span*luma));
+ const unsigned u=unsigned(std::lround(mid+chroma*(c[2]-luma)/(2*(1-kb))));
+ const unsigned v=unsigned(std::lround(mid+chroma*(c[0]-luma)/(2*(1-kr))));
+ if(rgb){auto* dst=frame->data[0]+y*frame->linesize[0]+x*4;for(unsigned k=0;k<3;++k)dst[k]=uint8_t(std::lround(black+span*c[2-k]));dst[3]=255;}
+ else if(yuy2){auto* dst=frame->data[0]+y*frame->linesize[0]+x*2;dst[0]=uint8_t(yy);dst[1]=uint8_t(x%2?v:u);}
+ else if(ten){reinterpret_cast<uint16_t*>(frame->data[0]+y*frame->linesize[0])[x]=uint16_t(yy);if(!(y%2)&&!(x%2)){reinterpret_cast<uint16_t*>(frame->data[1]+(y/2)*frame->linesize[1])[x/2]=uint16_t(u);reinterpret_cast<uint16_t*>(frame->data[2]+(y/2)*frame->linesize[2])[x/2]=uint16_t(v);}}
+ else{frame->data[0][y*frame->linesize[0]+x]=uint8_t(yy);if(!(y%2)&&!(x%2)){frame->data[1][(y/2)*frame->linesize[1]+x/2]=uint8_t(u);frame->data[2][(y/2)*frame->linesize[2]+x/2]=uint8_t(v);}}
+ }
+ pipeline::ColorDescription color;color.range=full?pipeline::ColorRange::Full:pipeline::ColorRange::Limited;
+ color.matrix=wideGamut?pipeline::YuvMatrix::BT2020NCL:pipeline::YuvMatrix::BT709;
+ color.primaries=wideGamut?pipeline::ColorPrimaries::BT2020:pipeline::ColorPrimaries::BT709;
+ color.transfer=wideGamut?pipeline::TransferFunction::BT2020_10:pipeline::TransferFunction::BT709;color.preserveSdrCodeValues=true;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
+ gd.sourceWidth=gd.workWidth=48;gd.sourceHeight=gd.workHeight=16;gd.enableNr=gd.enableSr=gd.enableFg=false;gd.noFeatures=true;
+ gd.rgbInput=rgb;gd.yuy2Input=yuy2;gd.captureBitDepth=ten?10:8;
+ pipeline::EnhanceGraph::FrameOutputs out;std::vector<float> actual;
+ bool ok=graph.initialize(gd)&&graph.createViews()&&graph.process(frame,0,true,out,1,&color)&&captureReadFp16(ctx,ring,graph.diagnosticLinearInput(),actual);
+ double error=0;
+ if(ok)for(unsigned patch=0;patch<patches.size();++patch){
+ std::array<double,3> linear{};
+ for(unsigned k=0;k<3;++k){const double c=patches[patch][k];linear[k]=wideGamut?(c<.081?c/4.5:std::pow((c+.099)/1.099,1/.45)):(c<=.04045?c/12.92:std::pow((c+.055)/1.055,2.4));}
+ const auto reference=wideGamut?std::array<double,3>{1.660491*linear[0]-.587641*linear[1]-.072850*linear[2],-.124550*linear[0]+1.132900*linear[1]-.008349*linear[2],-.018151*linear[0]-.100579*linear[1]+1.118730*linear[2]}:linear;
+ for(unsigned k=0;k<3;++k)error=std::max(error,std::abs(actual[(patch*8+4)*4+k]-reference[k]));
+ }
+ ok=ok&&error<(ten?.003:.015);
+ std::cout<<"SDR_COLOR bt2020="<<wideGamut<<" full="<<full<<" packing="<<packing<<" linearMaxError="<<error<<" pass="<<ok<<std::endl;
+ failures+=!ok;out={};ring.drainQueue();graph.shutdown();av_frame_free(&frame);
+ }
+ return failures;
+}
diff --git a/tests/integration/SourceFidelityTests.cpp b/tests/integration/SourceFidelityTests.cpp
index 42952728..8e9ae210 100644
--- a/tests/integration/SourceFidelityTests.cpp
+++ b/tests/integration/SourceFidelityTests.cpp
@@ -8,10 +8,12 @@
#include <cmath>
#include <iostream>
#include <memory>
+#include <thread>
extern "C" {
#include <libavutil/frame.h>
}
using namespace veyra;
+#include "FileSdrRoundTripCases.h"
namespace {
constexpr unsigned width=1920,height=1080;
// No game image, stream, credentials, enhancement, or visual judgement.
@@ -23,8 +25,9 @@ unsigned luma(unsigned x,unsigned y) {
return 16+x%220;
}
double expectedGray(unsigned code) {
- const double linear=std::pow((code-16)/219.0,2.4);
- return 255*(linear<=.0031308?12.92*linear:1.055*std::pow(linear,1/2.4)-.055);
+ // Independent no-effects contract: legal Y' codes become full-range RGB
+ // codes. Do not repeat the production transfer curve in the oracle.
+ return 255*(code-16)/219.0;
}
double sampled(const sink::RgbaImage& image,unsigned x,unsigned y,unsigned channel,unsigned w,unsigned h) {
const double sx=(x+.5)*image.width/w-.5,sy=(y+.5)*image.height/h-.5;
@@ -34,7 +37,7 @@ double sampled(const sink::RgbaImage& image,unsigned x,unsigned y,unsigned chann
return std::lerp(std::lerp(at(ix,iy),at(ix+1,iy),fx),std::lerp(at(ix,iy+1),at(ix+1,iy+1),fx),fy);
}
}
-int main() {
+int wmain(int argc,wchar_t** argv) {
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;
@@ -56,7 +59,7 @@ int main() {
desc.sourceWidth=desc.workWidth=width;desc.sourceHeight=desc.workHeight=height;
desc.enableNr=desc.enableSr=desc.enableFg=false;desc.noFeatures=true;
if(!graph.initialize(desc)||!graph.createViews())return 5;
- pipeline::ColorDescription fallback;fallback.displayReferred709=true;
+ pipeline::ColorDescription fallback;fallback.preserveSdrCodeValues=true;
auto color=pipeline::resolveFrameColor(*frame,fallback);
pipeline::EnhanceGraph::FrameOutputs output;
if(!graph.process(frame.get(),0,true,output,1,&color))return 6;
@@ -73,11 +76,15 @@ int main() {
const bool ingressOk=grayError<1.1&&clippedEdges==0&&identical;
std::cout<<"INGRESS_FIDELITY nv12="<<nv12<<" extent="<<image.width<<"x"<<image.height<<" grayMaxError="<<grayError<<" edgeErrors="<<clippedEdges<<" samePlanes="<<identical<<" pass="<<ingressOk<<std::endl;
failures+=!ingressOk;
- for(bool compatible:{false,true})for(unsigned w:{1920u,2560u,3840u}) {
- const unsigned h=w*9/16;
- HWND window=CreateWindowExW(0,L"STATIC",L"Source fidelity diagnostic",WS_POPUP,0,0,w,h,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ for(bool compatible:{false,true}) {
+ HWND window=CreateWindowExW(0,L"STATIC",L"Source fidelity diagnostic",WS_POPUP,0,0,1920,1080,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
engine::VideoPresenter presenter;
- if(!window||!presenter.open(ctx,window,graph,compatible)||!presenter.present(ctx,ring,graph,output.videoSlot,false))return 8;
+ if(!window||!presenter.open(ctx,window,graph,compatible))return 8;
+ for(unsigned w:{1920u,2560u,3840u,1920u,2560u,1920u}) {
+ const unsigned h=w*9/16;
+ if(!SetWindowPos(window,nullptr,0,0,w,h,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE))return 8;
+ std::this_thread::sleep_for(std::chrono::milliseconds(110));
+ if(!presenter.present(ctx,ring,graph,output.videoSlot,false))return 8;
sink::RgbaImage displayed;
if(!presenter.readPresentedFrameForTest(ctx,ring,displayed)||displayed.width!=w||displayed.height!=h)return 9;
double maxError=0,sum=0;
@@ -87,9 +94,12 @@ int main() {
}
const bool ok=maxError<2;
std::cout<<"PRESENT_FIDELITY nv12="<<nv12<<" compatible="<<compatible<<" extent="<<w<<"x"<<h<<" maxError="<<maxError<<" meanError="<<sum/(double(w)*h*3)<<" pass="<<ok<<std::endl;
- failures+=!ok;ring.drainQueue();presenter.close();DestroyWindow(window);
+ failures+=!ok;
+ }
+ ring.drainQueue();presenter.close();DestroyWindow(window);
}
output={};ring.drainQueue();graph.shutdown();
}
+ if(argc>1)failures+=fileSdrRoundTripCases(ctx,ring,argv[1]);
ring.shutdown();ctx.shutdown();CoUninitialize();return failures?1:0;
}
diff --git a/tests/integration/WasapiInputTests.cpp b/tests/integration/WasapiInputTests.cpp
index 1b278204..c9157232 100644
--- a/tests/integration/WasapiInputTests.cpp
+++ b/tests/integration/WasapiInputTests.cpp
@@ -19,9 +19,11 @@ int wmain(int argc,wchar_t** argv){
if(injected)SetEnvironmentVariableW(L"VEYRA_TEST_WASAPI_INPUT_LOSS",nullptr);
check(input.start(),"explicit same endpoint restart");std::this_thread::sleep_for(std::chrono::seconds(1));check(input.snapshot().inputBlocks>10,"restart delivers packets");input.stop();
}else if(argc==2&&wcscmp(argv[1],L"--invalid")==0){
- WasapiAudioInput input;input.configure(L"veyra-invalid-endpoint-no-fallback");input.setGain(0);check(input.start(),"invalid endpoint begins bounded attempts");
- std::this_thread::sleep_for(std::chrono::seconds(5));auto state=input.snapshot();check(!state.error.empty()&&!state.running&&state.inputBlocks==0,"invalid ID never falls back to microphone");input.stop();
- check(input.metrics().retries==3,"failed input retries are bounded to three");
+ WasapiAudioInput input;input.configure(L"veyra-invalid-endpoint-no-fallback");input.setGain(0);check(input.start(),"invalid endpoint begins paced retries");
+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(13);
+ while(input.metrics().retries<4&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ auto state=input.snapshot();check(!state.error.empty()&&!state.running&&state.inputBlocks==0,"invalid ID never falls back to microphone");input.stop();
+ check(input.metrics().retries>=4&&input.metrics().retries<=5,"selected endpoint keeps retrying beyond old limit with bounded backoff");
check(input.start(),"invalid endpoint can explicitly restart");std::this_thread::sleep_for(std::chrono::milliseconds(200));
const auto before=std::chrono::steady_clock::now();input.stop();check(std::chrono::steady_clock::now()-before<std::chrono::milliseconds(500),"stop interrupts reconnect backoff");
}else if(argc==2&&wcscmp(argv[1],L"--offline")==0){
diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cpp
index 9f291f4e..fb3f07ba 100644
--- a/tests/unit/CaptureColorContractTests.cpp
+++ b/tests/unit/CaptureColorContractTests.cpp
@@ -47,6 +47,9 @@ int main(){
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.VideoTransferFunction=DXVA2_VideoTransFunc_709;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;
+ check(source::captureMediaLayout(type,layout)&&layout.color.preserveSdrCodeValues&&!layout.color.transferAssumed&&pipeline::workingTransferCode(layout.color)==1,"explicit BT709 metadata retained; working decode reverses the SDR sink encode");
+ ext.VideoTransferFunction=DXVA2_VideoTransFunc_Unknown;
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;
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index 42a4f66c..9e64f90b 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -50,5 +50,7 @@ int main(){
check(*budget.predicted(24000000)<14,"old slow completion expires even when no FG succeeds");
check(!budget.admit(24000000,23800000,0,0),"recovery never admits an already expired deadline");
budget.reset();check(!budget.predicted(25000000),"settings revision reset clears prior backend costs");
+ budget.fgCost(20,25000000);budget.complete(12,true,false,25000000,3);
+ check(budget.predicted(25000000)==29,"subtract same-frame FG time instead of another frame's higher percentile");
return failures?1:0;
}
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index 9a0a85a0..c48d2590 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -1,4 +1,5 @@
#include "veyra/engine/EnhancementSettings.h"
+#include "veyra/engine/BackendRecovery.h"
#include "veyra/diagnostics/DiagnosticEvent.h"
#include "veyra/diagnostics/FrameMetrics.h"
#include "veyra/diagnostics/ResetCause.h"
@@ -19,9 +20,36 @@
#include "veyra/sink/AudioFrameTimeline.h"
#include "veyra/sink/ArrivalClockMapping.h"
#include "veyra/sink/CaptureSyncTarget.h"
+#include "veyra/source/DolbyVision.h"
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';};
+ {
+ engine::EnhancementSettings requested;requested.nr=requested.sr=true;requested.multiplier=2;requested.audioOffsetMs=37;
+ auto recovered=requested;
+ check(engine::disableFailedBackend(recovered,engine::FailedBackend::Fg)&&recovered.nr&&recovered.sr&&recovered.multiplier==1&&recovered.audioOffsetMs==37,"FG failure preserves NR, SR and independent audio settings");
+ recovered=requested;recovered.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;
+ check(engine::disableFailedBackend(recovered,engine::FailedBackend::NgxCore)&&!recovered.nr&&!recovered.sr&&recovered.multiplier==2,"NGX failure does not disable independent XeSS backend");
+ check(!engine::disableFailedBackend(recovered,engine::FailedBackend::Infrastructure),"device and color failures cannot silently degrade into success");
+ recovered=requested;recovered.videoSrQuality=2;
+ check(engine::disableFailedBackend(recovered,engine::FailedBackend::OpticalFlow)&&!recovered.nr&&recovered.sr&&recovered.multiplier==1,"flow failure disables dependent consumers while retaining spatial video SR");
+ check(!engine::disableFailedBackend(recovered,engine::FailedBackend::OpticalFlow),"repeated failure cannot create an unbounded recovery loop");
+ source::DolbyVisionInfo dv;dv.present=dv.baseLayer=true;dv.profile=5;dv.compatibility=1;
+ check(dv.route()==source::DolbyBaseLayer::Unsupported,"DV P5 cannot be relabelled as HDR10 even with a conflicting compatibility id");
+ dv.profile=8;
+ check(dv.route()==source::DolbyBaseLayer::Hdr10,"DV P8.1 selects HDR10 base-layer compatibility");
+ pipeline::ColorDescription color;color.transfer=pipeline::TransferFunction::PQ;color.matrix=pipeline::YuvMatrix::BT2020NCL;color.primaries=pipeline::ColorPrimaries::BT2020;
+ check(dv.matches(color),"DV HDR10 route requires matching decoded color contract");
+ color.transfer=pipeline::TransferFunction::SRGB;check(!dv.matches(color),"DV declaration cannot force SDR pixels into PQ");
+ dv.compatibility=4;check(dv.route()==source::DolbyBaseLayer::Hlg,"DV P8.4 selects HLG base layer");
+ dv.compatibility=2;check(dv.route()==source::DolbyBaseLayer::Sdr,"DV P8.2 selects SDR base layer");
+ dv.baseLayer=false;check(dv.route()==source::DolbyBaseLayer::Unsupported,"missing DV base layer fails closed");
+ diagnostics::GpuFrameTiming gpu;auto& first=gpu.gpu[size_t(diagnostics::GpuStage::Color)];first={diagnostics::SampleState::Measured,2,1000,3000,1000000};
+ auto& last=gpu.gpu[size_t(diagnostics::GpuStage::FgBatch)];last={diagnostics::SampleState::Measured,3,10000,13000,1000000};
+ gpu.gpu[size_t(diagnostics::GpuStage::Blit)]={diagnostics::SampleState::Measured,2,100000,102000,1000000};
+ check(diagnostics::graphExecutionSpanMs(gpu)==12,"GPU budget excludes delayed presentation and CPU completion observation");
+ last.frequency=1000;check(!diagnostics::graphExecutionSpanMs(gpu),"unrelated GPU clocks cannot form a processing envelope");
+ }
const auto logPath=std::filesystem::temp_directory_path()/(L"veyra-log-reopen-"+std::to_wstring(GetCurrentProcessId())+L".log");
{
auto logger=std::make_unique<Logger>();logger->setConsoleEnabled(false);
diff --git a/tests/unit/UiContractTests.cpp b/tests/unit/UiContractTests.cpp
index 24295a1d..61ab1eea 100644
--- a/tests/unit/UiContractTests.cpp
+++ b/tests/unit/UiContractTests.cpp
@@ -3,6 +3,8 @@
#include "../../apps/veyra/ui/WorkspaceTransition.h"
#include "../../apps/veyra/ui/TransportLayout.h"
#include "../../apps/veyra/ui/UiPreferenceStore.h"
+#include "../../apps/veyra/ui/CapturePreferenceStore.h"
+#include "veyra/engine/EngineController.h"
#include "veyra/sink/AudioGain.h"
#include "veyra/engine/PreviewView.h"
#include <iostream>
@@ -26,6 +28,21 @@ int wmain(int argc,wchar_t** argv){try{
for(int width:{290,400,480,508,700,1000}){ui::TransportLayout t(width,false);require(t.play.x+t.play.width<=t.mute.x&&t.stop.x+t.stop.width<=t.mute.x,"compact professional transport leaves room for audio and subtitle controls");}
ui::WorkspaceTransition animation;animation.start(true,1000);animation.sample(1120);const auto halfway=animation.value;require(halfway>.49&&halfway<.51,"visible intermediate expansion");animation.start(false,1120);require(animation.value==halfway,"reverse without jump");animation.sample(1240);require(animation.value>0&&animation.value<halfway,"panel collapses progressively");animation.sample(1360);require(!animation.running&&animation.value==0,"collapse ends exactly");
using pipeline::ResolutionPlan;using pipeline::NrSizePolicy;using pipeline::Extent;
+ for(auto policy:{NrSizePolicy::P480,NrSizePolicy::P720,NrSizePolicy::P900,NrSizePolicy::Realtime,NrSizePolicy::P1440}){
+ engine::EnhancementSettings s;s.nrPolicy=policy;
+ require(s.validate().empty()&&engine::PlayerOptions::from(s).snapshot().nrPolicy==policy,"NR policy survives controller round trip");
+ const auto p=ResolutionPlan::make({3840,2160},false,policy,false);
+ require(p.nr.height==pipeline::nrHeightLimit(policy)&&p.output==Extent{3840,2160}&&p.flow==p.nr,"NR tier reduces internal work only");
+ require(ResolutionPlan::make({3840,2160},false,policy,true).nr==Extent{3840,2160},"all export policies retain full extent");
+ require(ResolutionPlan::make({320,180},false,policy,false).nr==Extent{320,180},"NR tier never upscales smaller source");
+ auto portrait=ResolutionPlan::make({1080,1920},false,policy,false).nr;
+ require(std::abs(double(portrait.width)/portrait.height-1080.0/1920)<.005,"NR portrait aspect retained");
+ }
+ if(argc>1){
+ ui::CapturePreferenceStore store(argv[1]);ui::CapturePreferences p{L"\\\\?\\usb#video-\u91c7\u96c6",L"1920:1080:166833:{SUBTYPE}:RGB32",L"{audio-endpoint}",-3,2};
+ require(store.load().videoPath.empty(),"fresh capture preference empty");require(store.save(p),"capture preference atomic save");
+ const auto restored=store.load();require(restored.videoPath==p.videoPath&&restored.formatKey==p.formatKey&&restored.audioPath==p.audioPath&&restored.audioMode==p.audioMode&&restored.colorOverride==p.colorOverride,"capture stable identifiers and Unicode round trip");
+ }
require(ResolutionPlan::make({1448,1086},true,NrSizePolicy::Native,true).output==Extent{2880,2160},"4:3 SR preserves aspect");
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");