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

fix(remoteplay): add hardware decoding, stage telemetry and bounded FG recovery

Veyra Goal Agent7843d210b1de
diff --git a/apps/veyra/TelemetryWindow.cpp b/apps/veyra/TelemetryWindow.cpp
index f3d7a661..9578fdc5 100644
--- a/apps/veyra/TelemetryWindow.cpp
+++ b/apps/veyra/TelemetryWindow.cpp
@@ -17,6 +17,14 @@ void refresh(){auto s=engine->snapshot();const wchar_t* names[]={L"上传/颜色
o<<L"\r\nCPU与调度(毫秒,独立于GPU):取帧 "<<value(s.metrics.decodeCpuMs)<<L" / 图提交 "<<value(s.metrics.submitCpuMs)<<L" / GPU就绪等待 "<<value(s.metrics.gpuWaitCpuMs)<<L"\r\n截止时间等待 "<<value(s.metrics.deadlineWaitCpuMs)<<L" / Present调用 "<<value(s.metrics.presentCpuMs)<<L"\r\n源帧 "<<s.metrics.sourceFrames<<L" / 有效生成 "<<s.metrics.validGenerated<<L" / 实际提交 "<<s.metrics.submitted<<L" / 过期补帧 "<<s.metrics.expired<<L"\r\n当前批次容量 "<<s.metrics.queueWatermark<<L"(上限4);采集入口容量1;采集丢弃 "<<s.captureDropped<<L"\r\n实际提交频率(最近1秒观察):"<<value(s.submissionFps)<<L"fps;实际显示扫描率/光子延迟:未测\r\n";
const auto flowName=s.applied.flow==engine::FlowQuality::Performance?L"性能":s.applied.flow==engine::FlowQuality::Balanced?L"平衡":L"质量";
const auto& f=s.metrics.flow;const auto& c=f.counters;
+ if(s.remotePlay){const auto& r=s.remoteStream;
+ o<<L"\r\nPS5完整视频接收 "<<r.receivedFps<<L" fps / 实际解码 "<<r.decodedFps<<L" fps / 有效码率 "<<r.videoMbps<<L" Mbps"
+ <<L"\r\n实际解码路径:"<<(!r.decodeConfirmed?L"尚未确认":r.hardwareDecode?L"D3D12VA 硬解":r.decodeFallback?L"CPU软件(硬解回退)":L"CPU软件")
+ <<L"\r\n真实解码均值 / P95 "<<value(r.decodeMeanMs)<<L" / "<<value(r.decodeP95Ms)<<L" ms;接收后等待 "<<value(r.ingressWaitMeanMs)
+ <<L"\r\n原帧 / 生成呈现 "<<f.realPresentFps<<L" / "<<f.generatedPresentFps<<L" fps"
+ <<L"\r\n关键帧请求 "<<r.video.idrRequests<<L";压缩队列丢弃 "<<r.video.dropped<<L";解码邮箱覆盖 "<<s.remotePlaySkipped
+ <<L"\r\n延迟口径:完整视频收到→原帧Present返回,不含PS5渲染、编码、单程网络和显示扫描。实时RTT/端到端延迟未测。\r\n";
+ }
o<<L"\r\n最近一秒链路统计:均值 / P95 ms,n为样本数\r\n";
for(size_t i=0;i<f.gpuTiming.size();++i){const auto& a=f.gpuTiming[i];o<<names[i]<<L":"<<value(a.mean)<<L" / "<<value(a.p95)<<L" n="<<a.samples<<L"\r\n";}
o<<L"\r\n当前统计窗口:会话 "<<f.latest.sessionId<<L" / 设置 "<<f.latest.frame.settingsRevision<<L" / epoch "<<f.latest.frame.epoch
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index 4e0ec107..1083acab 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -1,9 +1,10 @@
#pragma once
#include "WorkspaceChrome.h"
+#include <chrono>
namespace veyra::ui {
namespace live_status {
-struct State {engine::EngineController* engine;int scroll=0,maxScroll=0;};
+struct State {engine::EngineController* engine;int scroll=0,maxScroll=0;bool advanced=false;};
inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
auto* state=reinterpret_cast<State*>(GetWindowLongPtrW(h,GWLP_USERDATA));
if(message==WM_NCCREATE){state=new State{static_cast<engine::EngineController*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams)};SetWindowLongPtrW(h,GWLP_USERDATA,LONG_PTR(state));}
@@ -12,6 +13,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
case WM_CREATE:SetTimer(h,1,250,nullptr);return 0;
case WM_TIMER:if(IsWindowVisible(h))InvalidateRect(h,nullptr,FALSE);return 0;
case WM_SIZE:InvalidateRect(h,nullptr,FALSE);return 0;
+ case WM_LBUTTONUP:if(GET_Y_LPARAM(lp)<dip(h,34)){state->advanced=!state->advanced;state->scroll=0;InvalidateRect(h,nullptr,FALSE);}return 0;
case WM_MOUSEWHEEL:state->scroll=std::clamp(state->scroll-GET_WHEEL_DELTA_WPARAM(wp)/WHEEL_DELTA*50,0,state->maxScroll);InvalidateRect(h,nullptr,FALSE);return 0;
case WM_ERASEBKGND:return 1;
case WM_PAINT:{
@@ -22,39 +24,82 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
const bool xess=s.applied.frameGenerationBackend==engine::FrameGenerationBackend::XeSS&&s.applied.multiplier>1;
auto write=[&](const std::wstring& value,int x,int y,int w,int ht,int size,COLORREF color){chromeText(paint.dc,h,value,x,y,w,ht,size,color);};
auto ms=[](std::optional<double> v){return v?std::format(L"{:.1f} ms",*v):std::wstring(L"未测");};
- auto timing=[&](const diagnostics::TimingAggregate& a){return playing&&a.mean&&a.p95?std::format(L"{:.1f} / {:.1f}",*a.mean,*a.p95):std::wstring(L"未测");};
+ auto timing=[&](const diagnostics::TimingAggregate& a){return playing&&a.mean&&a.p95?(state->advanced?std::format(L"{:.1f} / {:.1f}",*a.mean,*a.p95):ms(a.mean)):std::wstring(L"未测");};
auto fps=[&](double value){return playing&&!f.rateWindowReady?std::wstring(L"采样中"):std::format(L"{:.1f} fps",value);};
write(L"实时处理状态",12,8,width-24,24,13,textColor);
+ write(state->advanced?L"收起详情 −":L"展开详情 +",width-96,8,84,24,10,secondary);
const int half=(width-24)/2;
- write(xess?L"输出提交 · XeSS SDK":L"处理产出",12,36,half,20,10,secondary);
- write(s.capture?L"软件总延迟":L"软件驻留时间",12+half,36,half,20,10,secondary);
- write(fps(xess?f.xessSdkSubmitFps:f.outputCompletedFps),12,57,half,28,18,textColor);
+ write(xess?L"呈现提交 · XeSS SDK":L"实际呈现提交",12,36,half,20,10,secondary);
+ write(s.capture?L"软件延迟 · 平均":L"软件驻留 · 平均",12+half,36,half,20,10,secondary);
+ write(fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps),12,57,half,28,18,textColor);
write(playing?ms(f.softwareLatencyMs):L"未测",12+half,57,half,28,18,textColor);
std::vector<std::pair<std::wstring,std::wstring>> rows;
- rows.emplace_back(L"呈现提交",fps(xess?f.xessSdkSubmitFps:f.presentSubmitFps));
- rows.emplace_back(L"源帧处理",fps(f.sourceCompletedFps));
- rows.emplace_back(xess?L"补帧完成":L"有效补帧",xess?L"SDK内部不可测":fps(f.validGeneratedFps));
- rows.emplace_back(L"正常播放速度",playing?std::format(L"{:.2f} x",s.playbackSpeed):L"未测");
+ rows.emplace_back(L"同一延迟 · P95",playing?ms(f.softwareLatencyP95Ms):L"未测");
+ rows.emplace_back(L"请求目标(非实测)",s.nominalSourceFps>0?std::format(L"{:.1f} fps",s.nominalSourceFps*(s.captureHalfRate?.5:1)*s.applied.multiplier):L"未确定");
+ std::wstring progress=!playing?s.status:s.applying?L"正在应用设置":s.fgBudgetLimited?L"部分补帧未达截止时间":L"播放中";
+ if(playing&&!s.applying&&s.remotePlay){
+ const auto now=std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;
+ const auto old=[&](int64_t stamp){return stamp>0&&now-stamp>10000000;};const auto& r=s.remoteStream;
+ if(old(r.lastVideo100ns))progress=L"等待 PS5 视频输入";
+ else if(old(r.decodeStarted100ns))progress=L"解码调用尚未返回";
+ else if(old(r.lastDecoded100ns))progress=r.video.waitingForIdr?L"等待关键帧恢复":L"收到视频,等待解码输出";
+ else if(f.lastSubmit100ns>f.lastReady100ns&&old(f.lastSubmit100ns))progress=L"等待 GPU 完成观测";
+ else if(old(f.lastSubmit100ns))progress=L"已解码,增强提交停顿";
+ else if(old(f.lastPresent100ns))progress=L"GPU已就绪,等待呈现";
+ }
+ rows.emplace_back(L"状态",progress);
+ if(!s.capture)rows.emplace_back(L"媒体播放速度",playing?std::format(L"{:.2f} x",s.playbackSpeed):L"未测");
if(!s.capture&&!s.image){
rows.emplace_back(L"预览状态",!playing?L"未运行":s.previewSkipped?std::format(L"已跳帧 {}",s.previewSkipped):s.fgBudgetLimited?L"补帧预算不足":L"正常");
if(s.xessGenerationSuppressed)rows.emplace_back(L"XeSS补帧",L"欠速暂停生成 · 实验");
}
- rows.emplace_back(L"输入",s.capture?std::format(L"{:.1f} fps",s.captureFps):L"文件 / 图片");
- rows.emplace_back(L"总延迟 P95",playing?ms(f.softwareLatencyP95Ms):L"未测");
- rows.emplace_back(L"采集覆盖 / 补帧过期",std::format(L"{} / {}",f.counters.mailboxOverwritten,f.counters.generatedExpiredAfterEval));
- rows.emplace_back(L"链路耗时 · ms",L"均值 / P95");
- rows.emplace_back(L"取帧 / 解码",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Decode)]));
- rows.emplace_back(L"命令槽等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::SlotWait)]));
- rows.emplace_back(L"图提交",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Submit)]));
+ rows.emplace_back(L"输入",s.remotePlay?std::format(L"PS5 · {:.1f} fps",s.remoteStream.receivedFps):s.capture?std::format(L"采集 · {:.1f} fps",s.captureFps):L"文件 / 图片");
+ rows.emplace_back(L"链路耗时",state->advanced?L"均值 / P95 · ms":L"最近一秒平均");
+ rows.emplace_back(s.remotePlay?L"① PS5实际解码":L"① 文件取帧 / 解码",s.remotePlay?ms(s.remoteStream.decodeMeanMs):timing(f.cpuTiming[size_t(diagnostics::CpuStage::Decode)]));
+ if(s.remotePlay)rows.emplace_back(L"解码后等待增强",timing(f.cpuTiming[size_t(diagnostics::CpuStage::DecodedQueue)]));
const diagnostics::GpuStage stages[]={diagnostics::GpuStage::Color,diagnostics::GpuStage::Sr,diagnostics::GpuStage::Flow,diagnostics::GpuStage::Nr,diagnostics::GpuStage::Residual,diagnostics::GpuStage::FgBatch,diagnostics::GpuStage::Blit};
- const wchar_t* names[]={L"输入颜色",L"超分 SR",L"光流队列区间",L"NR",L"残差合成",L"补帧 FG",L"输出 blit"};
+ const wchar_t* names[]={L"② 输入颜色",L"③ 超分 SR",L"④ 光流队列区间",L"⑤ NR 增强",L"⑥ 残差合成",L"⑦ 补帧 FG",L"⑧ 输出合成"};
for(size_t i=0;i<std::size(stages);++i){const auto& sample=s.metrics.gpu[size_t(stages[i])];
const auto value=xess&&stages[i]==diagnostics::GpuStage::FgBatch?L"SDK内部不可测":sample.state==diagnostics::SampleState::NotExecuted?L"未执行":timing(f.gpuTiming[size_t(stages[i])]);
rows.emplace_back(names[i],value);
}
- rows.emplace_back(L"GPU就绪等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::ReadyWait)]));
- rows.emplace_back(L"呈现等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::DeadlineWait)]));
- rows.emplace_back(L"Present调用",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Present)]));
+ rows.emplace_back(L"⑨ 等待显示时间",timing(f.cpuTiming[size_t(diagnostics::CpuStage::DeadlineWait)]));
+ rows.emplace_back(L"⑩ Present提交",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Present)]));
+ rows.emplace_back(L"统计口径",L"并行阶段有重叠,不相加");
+ if(s.remotePlay){
+ const auto& r=s.remoteStream;
+ const auto now=std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;
+ auto age=[&](int64_t stamp){return stamp>0?ms(double(std::max<int64_t>(0,now-stamp))/10000):std::wstring(L"尚未收到");};
+ rows.emplace_back(L"PS5 串流",L"接收 → 解码 → 呈现");
+ rows.emplace_back(L"请求串流格式",std::format(L"{}x{} · {} fps · {}",r.requestedProfile.width,r.requestedProfile.height,r.requestedProfile.fps,r.requestedProfile.codec==remoteplay::Codec::H264?L"H.264":L"H.265"));
+ rows.emplace_back(L"请求码率",std::format(L"{:.1f} Mbps",r.requestedProfile.bitrateKbps/1000.0));
+ rows.emplace_back(L"实际解码方式",!r.decodeConfirmed?L"等待首帧":r.hardwareDecode?L"D3D12VA 硬解":r.decodeFallback?L"软件解码 · 硬解已回退":L"CPU 软件解码");
+ rows.emplace_back(L"接收 / 解码",std::format(L"{:.1f} / {:.1f} fps",r.receivedFps,r.decodedFps));
+ rows.emplace_back(L"增强完成",fps(f.sourceCompletedFps));
+ rows.emplace_back(L"原帧 / 生成帧呈现",xess?L"XeSS SDK 内部合计":std::format(L"{:.1f} / {:.1f} fps",f.realPresentFps,f.generatedPresentFps));
+ rows.emplace_back(L"视频有效码率",std::format(L"{:.2f} Mbps",r.videoMbps));
+ rows.emplace_back(L"接收后等待解码",ms(r.ingressWaitMeanMs));
+ rows.emplace_back(L"距上次视频接收",age(r.lastVideo100ns));
+ rows.emplace_back(L"距上次解码完成",age(r.lastDecoded100ns));
+ rows.emplace_back(L"距上次呈现",age(f.lastPresent100ns));
+ rows.emplace_back(L"串流端到端延迟",L"协议未提供,无法直接测量");
+ rows.emplace_back(L"关键帧恢复请求",std::to_wstring(r.video.idrRequests));
+ if(state->advanced){
+ rows.emplace_back(L"协议报告缺失源帧 · 累计",std::to_wstring(r.framesLost));
+ rows.emplace_back(L"参考恢复标记 · 累计",std::to_wstring(r.referenceRecoveryEvents));
+ rows.emplace_back(L"压缩队列丢弃 · 累计",std::to_wstring(r.video.dropped));
+ rows.emplace_back(L"解码邮箱覆盖 · 累计",std::to_wstring(s.remotePlaySkipped));
+ rows.emplace_back(L"FEC 成功 / 实时 RTT",L"当前接口未提供有效测量");
+ }
+ }
+ if(state->advanced){
+ rows.emplace_back(L"GPU完成产出",fps(f.outputCompletedFps));
+ rows.emplace_back(L"源帧处理完成",fps(f.sourceCompletedFps));
+ rows.emplace_back(L"有效生成(含过期)",xess?L"SDK内部不可测":fps(f.validGeneratedFps));
+ rows.emplace_back(L"采集覆盖 / 补帧过期",std::format(L"{} / {}",f.counters.mailboxOverwritten,f.counters.generatedExpiredAfterEval));
+ rows.emplace_back(L"命令槽等待",timing(f.cpuTiming[size_t(diagnostics::CpuStage::SlotWait)]));
+ rows.emplace_back(L"CPU图提交",timing(f.cpuTiming[size_t(diagnostics::CpuStage::Submit)]));
+ rows.emplace_back(L"GPU就绪等待(重叠)",timing(f.cpuTiming[size_t(diagnostics::CpuStage::ReadyWait)]));
rows.emplace_back(f.pairCaptureCallbacks?L"A/B采集到达间隔":L"A/B软件取帧间隔",xess?L"SDK内部不可测":timing(f.pairTiming[size_t(diagnostics::PairTiming::ArrivalInterval)]));
rows.emplace_back(L"生成呈现距A到达",xess?L"SDK内部不可测":timing(f.pairTiming[size_t(diagnostics::PairTiming::GeneratedFromA)]));
rows.emplace_back(L"生成呈现距B到达",xess?L"SDK内部不可测":timing(f.pairTiming[size_t(diagnostics::PairTiming::GeneratedFromB)]));
@@ -86,6 +131,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
}
if(!s.backendWarning.empty())rows.emplace_back(L"后端状态",s.backendWarning);
if(!s.captureAudio.error.empty())rows.emplace_back(L"采集音频异常",s.captureAudio.error);
+ }
std::vector<std::pair<std::wstring,std::wstring>> wrapped;
const auto rowFont=makeFont(h,11,FW_NORMAL);const auto oldFont=SelectObject(paint.dc,rowFont);
auto split=[&](std::wstring value,int room){
@@ -115,7 +161,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
}
RestoreDC(paint.dc,saved);
if(state->maxScroll&&available>0){const int thumb=std::max(18,available*available/(int(rows.size())*rowHeight));const int y=top+(available-thumb)*state->scroll/state->maxScroll;RECT r{dip(h,width-4),dip(h,y),dip(h,width-2),dip(h,y+thumb)};FillRect(paint.dc,&r,panelBrush());}
- write(xess?L"截止代理Present返回;屏幕扫描未测":L"源帧进入软件至Present返回;非光子延迟",12,height-28,width-24,24,9,secondary);
+ write(s.remotePlay?L"完整视频收到→Present;不含主机/屏幕":xess?L"截止代理Present返回;屏幕扫描未测":L"源帧进入软件至Present返回;非光子延迟",12,height-28,width-24,24,9,secondary);
return 0;
}
case WM_NCDESTROY:KillTimer(h,1);delete state;SetWindowLongPtrW(h,GWLP_USERDATA,0);break;
diff --git a/apps/veyra/ui/RemotePlayPanel.cpp b/apps/veyra/ui/RemotePlayPanel.cpp
index ddad62bb..eb172c78 100644
--- a/apps/veyra/ui/RemotePlayPanel.cpp
+++ b/apps/veyra/ui/RemotePlayPanel.cpp
@@ -11,7 +11,7 @@
namespace veyra::ui {
namespace {
HWND window=nullptr;HFONT font=nullptr;
-enum {Host=1,Account,PairPin,Quality,CodecChoice,Pair,Connect,Cancel,Scan,Wake,LoginPin,SendPin,StatusText,Help,Bitrate,Forget,ViewOnly,Calibrate};
+enum {Host=1,Account,PairPin,Quality,CodecChoice,Pair,Connect,Cancel,Scan,Wake,LoginPin,SendPin,StatusText,Help,Bitrate,Forget,ViewOnly,Calibrate,DecodeChoice};
std::function<bool()> calibrate;
std::function<void(source::RemotePlayConnectDesc)> connect;
std::function<void(std::string)> login;
@@ -78,7 +78,7 @@ void arrange(){
move(Quality,160,150,220,150);move(CodecChoice,392,150,160,150);
move(Connect,160,199,180,36);move(Wake,352,199,200,36);
move(LoginPin,160,250,180,28);move(SendPin,352,250,200,30);
- move(Bitrate,160,295,180,180);move(Forget,352,295,80,32);move(Cancel,440,295,112,32);move(StatusText,20,341,530,64);move(ViewOnly,20,408,400,28);move(Calibrate,432,408,120,28);move(Help,20,442,530,86);
+ move(Bitrate,160,295,180,180);move(Forget,352,295,80,32);move(Cancel,440,295,112,32);move(StatusText,20,341,530,64);move(ViewOnly,20,408,400,28);move(Calibrate,432,408,120,28);move(DecodeChoice,160,442,392,150);move(Help,20,485,530,86);
}
LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
@@ -88,6 +88,10 @@ case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
};
add(L"BUTTON",L"仅观看(手柄连接 PS5;更改后需重新连接)",ViewOnly,BS_AUTOCHECKBOX|WS_TABSTOP);
add(L"BUTTON",L"校准陀螺仪",Calibrate,BS_PUSHBUTTON|WS_TABSTOP);
+ add(L"STATIC",L"解码(重连生效)",106,0,20,445,138,25);
+ add(L"COMBOBOX",L"",DecodeChoice,CBS_DROPDOWNLIST|WS_TABSTOP);
+ for(auto label:{L"自动 · 优先硬解",L"CPU 软件解码",L"D3D12VA 硬件解码"})SendDlgItemMessageW(h,DecodeChoice,CB_ADDSTRING,0,LPARAM(label));
+ SendDlgItemMessageW(h,DecodeChoice,CB_SETCURSEL,std::min(2u,GetPrivateProfileIntW(L"RemotePlay",L"DecodeMode",0,(runtime::localDataDirectory()/"veyra.ini").c_str())),0);
add(L"STATIC",L"PS5 地址",100,0,20,21,130,25);add(L"STATIC",L"PSN Account ID",101,0,20,65,130,25);
add(L"STATIC",L"8 位配对码",102,0,20,109,130,25);add(L"STATIC",L"串流格式",103,0,20,153,130,25);add(L"STATIC",L"登录 PIN(可选)",104,0,20,253,135,25);
add(L"STATIC",L"码率",105,0,20,298,130,25);add(L"COMBOBOX",L"",Host,CBS_DROPDOWN|CBS_AUTOHSCROLL|WS_TABSTOP);SendDlgItemMessageW(h,Host,CB_LIMITTEXT,253,0);
@@ -115,7 +119,7 @@ case WM_COMMAND:switch(LOWORD(wp)){
auto result=remoteplay::pairLocalPs5(host,account,pin,stop);SecureZeroMemory(pin.data(),pin.size());Outcome out;
if(result.result.ok&&!stop.stop_requested()){remoteplay::NativeConnectRequest request;request.host=host;request.video=format;request.credentials=std::move(result.credentials);if(remoteplay::saveProfile(targetPath,request)){out.savedPath=targetPath;out.message=L"配对成功并已加密保存,可以连接。";}else out.message=L"配对成功,但保存失败。请检查目录权限后重试。";}
else out.message=result.canceled||stop.stop_requested()?L"已取消配对":std::format(L"配对失败({}),检查 PS5 配对码、Account ID 与网络。",result.result.code);return out;});break;}
- case Connect:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());auto host=ascii(Host);if(!saved||!remoteplay::validHost(host)){SetDlgItemTextW(h,StatusText,L"请先完成配对,并填写有效主机地址。");break;}saved->host=host;saved->video=video();if(!remoteplay::saveProfile(currentProfile,*saved)){SetDlgItemTextW(h,StatusText,L"保存连接设置失败,请检查目录权限。");break;}source::RemotePlayConnectDesc desc;saved->viewOnly=IsDlgButtonChecked(h,ViewOnly)==BST_CHECKED;desc.request=std::move(*saved);connect(std::move(desc));watching=true;EnableWindow(GetDlgItem(h,Cancel),TRUE);SetDlgItemTextW(h,StatusText,L"连接已开始。需要登录 PIN 时在下方提交。关闭面板不停止串流。");break;}
+ case Connect:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());auto host=ascii(Host);if(!saved||!remoteplay::validHost(host)){SetDlgItemTextW(h,StatusText,L"请先完成配对,并填写有效主机地址。");break;}saved->host=host;saved->video=video();if(!remoteplay::saveProfile(currentProfile,*saved)){SetDlgItemTextW(h,StatusText,L"保存连接设置失败,请检查目录权限。");break;}source::RemotePlayConnectDesc desc;saved->viewOnly=IsDlgButtonChecked(h,ViewOnly)==BST_CHECKED;desc.request=std::move(*saved);const auto decode=std::clamp<int>(int(SendDlgItemMessageW(h,DecodeChoice,CB_GETCURSEL,0,0)),0,2);desc.decodeMode=static_cast<source::RemotePlayConnectDesc::DecodeMode>(decode);WritePrivateProfileStringW(L"RemotePlay",L"DecodeMode",std::to_wstring(decode).c_str(),(runtime::localDataDirectory()/"veyra.ini").c_str());connect(std::move(desc));watching=true;EnableWindow(GetDlgItem(h,Cancel),TRUE);SetDlgItemTextW(h,StatusText,L"连接已开始。需要登录 PIN 时在下方提交。关闭面板不停止串流。");break;}
case Cancel:if(busy&&worker.joinable())worker.request_stop();else if(watching)disconnect();break;
case Scan:launch([](std::stop_token stop){Outcome out;auto report=remoteplay::discoverLocalPs5(stop);for(const auto& line:report.diagnostics)veyra::log::info("remoteplay-discovery",line);out.hosts=std::move(report.hosts);out.message=stop.stop_requested()?L"已取消查找":out.hosts.empty()?(report.error?std::format(L"主机搜索发生错误({}),详情见日志;可手填 IP。",report.error):L"搜索完成,未收到 PS5 回应;可手填 IP,检查主机开机和局域网。"):L"已填入发现的 PS5 地址。多台主机可手工输入目标 IP。";return out;});break;
case Wake:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());if(!saved){SetDlgItemTextW(h,StatusText,L"需要先配对才能唤醒。");break;}saved->host=ascii(Host);launch([request=std::move(*saved)](std::stop_token stop){Outcome out;if(stop.stop_requested()){out.message=L"已取消唤醒";return out;}auto r=remoteplay::wakeLocalPs5(request);out.message=r.ok?L"已发送唤醒请求,等待 PS5 启动后点击连接。":std::format(L"唤醒请求失败({})",r.code);return out;});break;}
@@ -131,6 +135,6 @@ void showRemotePlayPanel(HWND parent,std::function<void(source::RemotePlayConnec
calibrate=std::move(calibration);
connect=std::move(start);login=std::move(pin);connectionStatus=std::move(status);disconnect=std::move(stop);if(window){SetForegroundWindow(window);return;}
WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraRemotePlaySetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);
- CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"PS5 · Remote Play",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,590),dip(parent,580),parent,nullptr,wc.hInstance,nullptr);
+ CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"PS5 · Remote Play",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,590),dip(parent,625),parent,nullptr,wc.hInstance,nullptr);
}
}
diff --git a/docs/PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md b/docs/PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md
index fc9c1505..1b162d1f 100644
--- a/docs/PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md
+++ b/docs/PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md
@@ -19,3 +19,23 @@ FrameFlow记录最后GPU就绪、提交和Present;独立monitor每秒输出rem
真实原版 NR SHA256 符合 AGENTS。产品构建 build-product.cmd 成功(logs/ps5-p1-lookahead-build2.log)。使用 logs/audio-jitter-20260911/4k30fps.mp4(8秒)和实际 RTX5070/NVIDIA runtime,--native --nr --fg-multiplier 2 --no-sr:25秒 smoke 退出0,240源帧、238生成,稳态每秒约60次提交、expiredGenerated=0、播放1.000x。logs/ps5-p1-file4k30-runtime.log。与修前用户4K30样本不是相同媒体,不宣称全部媒体60fps保证。
15秒 --smoke-controls 同参数回归退出0:暂停→暂停seek到1秒→恢复完成,controlsStep=3,稳态提交约60fps,过期0,声音领先最终0.40ms、绝对偏差P95 0.88ms;logs/ps5-p1-controls-runtime.log。尚需长媒体、持续欠速、恢复、单帧EOF与XeSS回归,UI改动正在进行,硬解未实现。
+
+## P1追加:恢复预算、暂停跳转与清理
+
+加入FgRecoveryBudget:原帧耗时、FG追加GPU耗时、恢复预热分开;最近有效成本按墙钟过期并限制64样本,settings revision切换清空,普通时域重置不抹掉吞吐预测。欠速后250ms有界探测,连续两次可达截止时间的机会覆盖预热/有效生成,每次仍检查期限;不强制呈现过期帧。旧同步文件播放分支已删除,只有图片保留单次处理路径。取消原有陈旧混合预测字段。
+
+动态负载回归通过:生产Engine/实际NR+DLSS2X,测试专用owner工作延迟70ms(明确不是测量/伪造GPU耗时),约12呈现fps,56个源预览机会跳过,音频没有新增停机;移除延迟且不改settings revision,恢复至46呈现fps且19生成呈现fps时通过阈值,后续仍继续恢复。logs/ps5-dynamic-recovery.stdout.log,65秒watchdog,实际6.8秒exit0。FgRecoveryBudget确定性9项新增检查通过,logs/ps5-fg-budget-unit.log。
+
+文件欠速完整回归第一次有2项失败:4K输入的SR不执行(源/目标同4K,错误测试夹具),以及暂停seek显示位置未及时发布(产品问题)。改用1080p30→4K保证实际SR,并在Present成功时直接发布位置后,logs/ps5-final-file-overload2.stdout.log全部通过:NR/SR/FG实际执行、音频addedWaits=0、延迟有界、重建/播放seek/暂停seek/恢复/关闭通过。第一次失败保留于logs/ps5-final-file-overload.stdout.log,不能删除失败记录。XeSS原生4K文件音频连续性logs/ps5-final-xess-continuity.stdout.log退出0。
+
+## P2/P3:界面和真实硬解
+
+LiveStatusPanel首屏区分实际呈现、请求目标、软件平均/P95;默认阶段均值,详细产出/过期/等待/计数折叠。PS5输入取独立接收快照,不再用采集卡空计数。独立接收/解码/呈现年龄显示卡在哪一步,暂停和设置重建单独显示。TelemetryWindow也接PS5数据。
+
+PS5连接页新增自动(优先硬解)/CPU软件/D3D12VA硬件,重连生效,本地INI仅存解码选择、不写凭据。自动硬解失败在下一关键帧切CPU;明确选硬解失败报错,用户可改自动/软件,不伪装硬解。使用Engine同一D3D12设备,实际AV_PIX_FMT_D3D12输出进入现有图;每个硬件输入AVFrame由图双槽保留到消费fence完成,避免FFmpeg提前复用。正常路径无CPU像素下载。
+
+Native source H264/H265真实硬解、PTS重排通过;同片段软硬YUV逐像素对照max_error=0,颜色range/matrix/transfer与PTS一致,仅诊断测试允许readback。故意让FFmpeg格式选择失败,自动模式下一关键帧转软件与指定硬解报错分支都通过(预期日志-1094995529)。logs/ps5-p3-fallback-final.stdout.log,45秒上限,实际<1秒exit0。开发中颜色比较首次构建因Rational无operator==失败,改为to100ns比较,logs/ps5-p3-color-build.log保留;首次fallback夹具缺少独立config导致拒绝,补齐真实协议消息顺序后通过,logs/ps5-p3-fallback.stdout.log保留。
+
+生产图导入硬件纹理专项:VEYRA_TEST_FILE_HW_DECODE=1仅测试开关,4K30原生NR+DLSS2X文件,20秒smoke退出0,logs/ps5-p3-hardware-graph-runtime.log,稳态约60呈现/秒、过期0。此结果是本机解码+图验证,不是PS5网络实机硬解验收。旧probe中“descriptor后硬解约8fps”是历史诊断,不能覆盖本次实测。
+
+当前还有最后统一gate、UI快照、source gap/EOF等回归与最终文档存档。用户已追加授权:完成后正常关机,明天由用户实测PS5;不强杀游戏,不push/release。PS5原始冻结未重现,受限恢复与阶段诊断不能宣称彻底根因已确认。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index bcebf6b6..983f7478 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1666,3 +1666,7 @@ build-product/native-source/off-check成功;boundary默认与virtual、H264/H2
### 2026-09-12 文件FG提前增强节点
按PS5_TELEMETRY_STALL_FG_DECODE_REPAIR_PLAN实施文件预览容量2的提前增强。实际4K30原生NR+DLSS2X测试和暂停seek回归均退出0,短媒体稳态约60呈现提交/秒,生成过期0,音频约1倍速。详细命令、日志和未验证边界见PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md。仍未完成全部修复,不发布。
+
+### 2026-09-12 PS5硬解/遥测与欠速恢复节点
+实现PS5自动/软件/硬解选择、实际D3D12VA纹理输出与GPU消费引用保留,自动失败回退及强制硬解报错;重做实时状态分组与PS5独立接收/解码/呈现统计。实现FG分成本预算、限频连续恢复探测,移除旧同步文件分支。详见PS5_TELEMETRY_SCHEDULER_EXECUTION_2026-09-12.md。
+产品ON/OFF和native source构建通过。真实H264/H265软硬对比max_error=0,故障回退注入通过;NR/SR/FG欠速、动态负载恢复、XeSS连续音频、输入中断与EOF回归通过。45秒4K30原生NR2X:1286源帧、1253生成,absLatenessP95=0.79ms,非所有帧必达目标的承诺。统一gate、最后UI验证和最终用户说明待完成;不发布。用户要求修复结束后正常关机,明天实测PS5。
diff --git a/include/veyra/diagnostics/FrameMetrics.h b/include/veyra/diagnostics/FrameMetrics.h
index 21b87a48..30efcd32 100644
--- a/include/veyra/diagnostics/FrameMetrics.h
+++ b/include/veyra/diagnostics/FrameMetrics.h
@@ -6,7 +6,7 @@
namespace veyra::diagnostics {
enum class GpuStage { Color, Sr, Flow, Nr, Residual, Fg1, Fg2, Fg3, FgBatch, Blit, Count };
enum class SampleState { NotExecuted, Pending, Measured, Unavailable };
-enum class CpuStage { Decode, Submit, SlotWait, ReadyWait, DeadlineWait, Present, Count };
+enum class CpuStage { Decode, Submit, SlotWait, ReadyWait, DeadlineWait, Present, DecodedQueue, Count };
enum class PairTiming { ArrivalInterval, GeneratedFromA, GeneratedFromB, Count };
enum class ResetStage { Drain, Destroy, Create, Warmup, FirstValid, Count };
enum class ResetOutcome { InProgress, Completed, Failed, RolledBack, Cancelled };
@@ -43,6 +43,7 @@ struct FrameFlowMetrics {
std::optional<double> slotReuseWaitMs,captureArrivalToPresentReturnMs,gpuReadyWaitMs,deadlineWaitMs;
uint64_t slotReuseWaitCount=0;
double validGeneratedFps=0,presentSubmitFps=0,sourceCompletedFps=0,outputCompletedFps=0,xessSdkSubmitFps=0;
+ double realPresentFps=0,generatedPresentFps=0;
bool rateWindowReady=false;
std::optional<double> softwareLatencyMs,softwareLatencyP95Ms,slotWaitPerFrameMs;
uint64_t latencySamples=0;
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 4df1927c..e746aec1 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -36,6 +36,7 @@ struct PlayerSnapshot {
uint64_t audioVideoWaits=0;
bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;
double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
+ double nominalSourceFps=0;
diagnostics::FrameMetrics metrics;
std::optional<double> submissionFps;
uint32_t flowPerf=0;int contentFps=0;
diff --git a/include/veyra/engine/FgRecoveryBudget.h b/include/veyra/engine/FgRecoveryBudget.h
new file mode 100644
index 00000000..d4c06f3b
--- /dev/null
+++ b/include/veyra/engine/FgRecoveryBudget.h
@@ -0,0 +1,62 @@
+#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <deque>
+#include <optional>
+#include <vector>
+
+namespace veyra::engine {
+// Revision-scoped costs survive temporal-history resets. Old GPU pressure
+// expires by wall time, rather than requiring successful FG to replace it.
+class FgRecoveryBudget {
+ struct Sample {int64_t time;double ms;};
+ std::deque<Sample> base_,fg_,warmup_;
+ bool limited_=false;
+ unsigned recoveryPairs_=0;
+ int64_t retryAt_=0;
+ static void add(std::deque<Sample>& values,int64_t now,double ms){
+ if(!std::isfinite(ms)||ms<0)return;
+ while(!values.empty()&&(values.size()>=64||values.front().time<now-10000000))values.pop_front();
+ values.push_back({now,ms});
+ }
+ static std::optional<double> p95(const std::deque<Sample>& values,int64_t now,int64_t age){
+ std::vector<double> current;
+ for(const auto& sample:values)if(sample.time>=now-age)current.push_back(sample.ms);
+ if(current.empty())return {};
+ const auto index=(current.size()*95+99)/100-1;
+ std::nth_element(current.begin(),current.begin()+index,current.end());return current[index];
+ }
+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){
+ if(warmup){add(warmup_,now,ms);return;}
+ const auto extra=evaluated?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)));
+ }
+ std::optional<double> predicted(int64_t now)const{
+ const auto base=p95(base_,now,10000000);
+ if(!base)return {};
+ return *base+p95(fg_,now,20000000).value_or(0);
+ }
+ bool admit(int64_t now,int64_t deadline,double elapsed,double present){
+ const auto cost=predicted(now);
+ const bool fits=double(deadline-now)/10000+10>=std::max(0.0,cost.value_or(elapsed)-elapsed)+std::max(0.0,present);
+ if(!fits){
+ if(!limited_||recoveryPairs_){retryAt_=now+2500000;}
+ limited_=true;recoveryPairs_=0;return false;
+ }
+ if(limited_){
+ if(now<retryAt_)return false;
+ // A probe consists of consecutive admitted pairs, not an isolated
+ // warmup. Every pair still checks its actual deadline above.
+ if(++recoveryPairs_>=2){limited_=false;recoveryPairs_=0;}
+ }
+ return true;
+ }
+ bool recovering()const{return limited_&&recoveryPairs_>0;}
+};
+}
diff --git a/include/veyra/engine/FrameFlowWindow.h b/include/veyra/engine/FrameFlowWindow.h
index 57146a5e..6b2ad778 100644
--- a/include/veyra/engine/FrameFlowWindow.h
+++ b/include/veyra/engine/FrameFlowWindow.h
@@ -13,21 +13,24 @@ namespace veyra::engine {
class FrameCompletionRates {
mutable std::mutex mutex_;
FrameRateWindow generated_,presented_,source_,output_,xess_;
+ FrameRateWindow realPresented_,generatedPresented_;
int64_t start_;
public:
explicit FrameCompletionRates(int64_t now):start_(now){
generated_.reset(now);presented_.reset(now);source_.reset(now);output_.reset(now);xess_.reset(now);
+ realPresented_.reset(now);generatedPresented_.reset(now);
}
void ready(bool real,unsigned valid,int64_t now){
std::lock_guard lock(mutex_);
if(real){source_.complete(now);output_.complete(now);}
for(unsigned i=0;i<valid;++i){generated_.complete(now);output_.complete(now);}
}
- void presented(int64_t now){std::lock_guard lock(mutex_);presented_.complete(now);}
+ void presented(bool generated,int64_t now){std::lock_guard lock(mutex_);presented_.complete(now);(generated?generatedPresented_:realPresented_).complete(now);}
void xess(uint64_t count,int64_t now){std::lock_guard lock(mutex_);for(uint64_t i=0;i<count;++i)xess_.complete(now);}
void snapshot(diagnostics::FrameFlowMetrics& m,int64_t now)const{
std::lock_guard lock(mutex_);m.validGeneratedFps=generated_.rate(now);m.presentSubmitFps=presented_.rate(now);
m.sourceCompletedFps=source_.rate(now);m.outputCompletedFps=output_.rate(now);m.xessSdkSubmitFps=xess_.rate(now);m.rateWindowReady=now-start_>=10000000;
+ m.realPresentFps=realPresented_.rate(now);m.generatedPresentFps=generatedPresented_.rate(now);
}
};
// Each asynchronous job retains its own window. Replacing the current window
@@ -114,7 +117,7 @@ public:
void presented(bool generated,uint64_t fence,int64_t now){
std::lock_guard lock(mutex_);
if(generated)++metrics_.counters.generatedPresented;else ++metrics_.counters.realPresented;
- metrics_.latest.consumerFence=fence;rates_->presented(now);
+ metrics_.latest.consumerFence=fence;rates_->presented(generated,now);
metrics_.lastPresent100ns=now;
}
diagnostics::FrameFlowMetrics snapshot(int64_t now)const{
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index 3fa36e5b..95046b8e 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -298,6 +298,9 @@ private:
std::weak_ptr<FrameLease> realLeases_[2],generatedLeases_[6];
uint32_t nextListSlot_ = 0;
uint64_t uploadFences_[2] = {};
+ // FFmpeg may recycle a hardware surface as soon as its AVFrame is freed.
+ // Retain each imported surface until our last consumer fence completes.
+ std::shared_ptr<AVFrame> hardwareInputFrames_[2];
core::SceneCadenceAnalyzer scene_;
std::vector<uint8_t> previousLuma_;
double prevPtsMs_ = -1.0;
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index 9cc2f2a9..e4d9c572 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -161,6 +161,7 @@ struct FramePacket {
ColorDescription colorInfo;
uint64_t sourceEpoch = 1; // ResetCoordinator epoch at frame boundary
int64_t arrivalHost100ns = 0; // capture callback steady_clock; 0 when unavailable
+ int64_t decodedHost100ns = 0; // actual remote decoder output; same local clock
GpuTextureHandle color; // canonical linear RGBA16F working texture
diff --git a/include/veyra/remoteplay/SessionInbox.h b/include/veyra/remoteplay/SessionInbox.h
index ad5a74f0..bbf4c134 100644
--- a/include/veyra/remoteplay/SessionInbox.h
+++ b/include/veyra/remoteplay/SessionInbox.h
@@ -15,10 +15,12 @@ public:
std::uint64_t staleCallbacks=0;int errorCode=0;
VideoQueueStats video;AudioQueueStats audio;
HostTime lastVideo100ns=0,lastAudio100ns=0,decodeStarted100ns=0,lastDecoded100ns=0;
- uint64_t decodedFrames=0,receivedBytes=0,framesLost=0,framesRecovered=0;
+ uint64_t decodedFrames=0,receivedBytes=0,framesLost=0,referenceRecoveryEvents=0;
double receivedFps=0,decodedFps=0,videoMbps=0;
std::optional<double> decodeMeanMs,decodeP95Ms,ingressWaitMeanMs;
bool ratesReady=false;
+ bool hardwareDecode=false,decodeFallback=false,decodeConfirmed=false;
+ VideoProfile requestedProfile;
};
class Token {
public:
@@ -48,6 +50,8 @@ public:
void decodeStarted(HostTime now,HostTime arrival);
void decodeFinished(HostTime now);
void frameDecoded(HostTime now);
+ void decoderBackend(bool hardware,bool fallback);
+ void streamProfile(VideoProfile profile);
private:
std::shared_ptr<Shared> shared_;
};
diff --git a/include/veyra/source/RemotePlaySource.h b/include/veyra/source/RemotePlaySource.h
index 4f9cdbd7..74d51249 100644
--- a/include/veyra/source/RemotePlaySource.h
+++ b/include/veyra/source/RemotePlaySource.h
@@ -18,12 +18,18 @@
struct AVCodecContext;
struct AVFrame;
+struct ID3D12Device;
namespace veyra::source {
struct RemotePlayConnectDesc {
remoteplay::NativeConnectRequest request;
remoteplay::QueueLimits queueLimits{};
+ enum class DecodeMode { Automatic, Software, Hardware };
+ DecodeMode decodeMode=DecodeMode::Automatic;
+ // Set by the engine; shared ownership keeps the exact presentation adapter
+ // alive until the decoder owner has stopped, including failed connects.
+ std::shared_ptr<ID3D12Device> decodeDevice;
};
class RemotePlaySource final : public IFrameSource {
@@ -98,6 +104,9 @@ private:
bool decoderReady_ = false;
bool waitingForFirstFrame_ = true;
bool pendingOpenFlag_ = true;
+ RemotePlayConnectDesc::DecodeMode decodeMode_=RemotePlayConnectDesc::DecodeMode::Automatic;
+ std::shared_ptr<ID3D12Device> decodeDevice_;
+ bool hardwareFallback_=false;
};
class RemotePlayAudioSource final : public sink::AudioPcmSource {
diff --git a/services/remoteplay-probe/NativeChiaki.cmake b/services/remoteplay-probe/NativeChiaki.cmake
index d8c6b161..f201bb5d 100644
--- a/services/remoteplay-probe/NativeChiaki.cmake
+++ b/services/remoteplay-probe/NativeChiaki.cmake
@@ -15,7 +15,7 @@ if(VEYRA_RP_FFMPEG_ROOT)
target_compile_features(veyra_remoteplay_source_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_remoteplay_source_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
target_include_directories(veyra_remoteplay_source_tests SYSTEM PRIVATE "${VEYRA_RP_FFMPEG_ROOT}/include")
- target_link_libraries(veyra_remoteplay_source_tests PRIVATE veyra_remoteplay_chiaki
+ target_link_libraries(veyra_remoteplay_source_tests PRIVATE veyra_remoteplay_chiaki d3d12
"${VEYRA_RP_FFMPEG_ROOT}/lib/avcodec.lib"
"${VEYRA_RP_FFMPEG_ROOT}/lib/avutil.lib"
"${VEYRA_RP_FFMPEG_ROOT}/lib/avformat.lib")
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 22c10a12..94227eaa 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -9,6 +9,7 @@
#include "veyra/engine/TimingWindow.h"
#include "veyra/engine/FrameFlowWindow.h"
#include "veyra/engine/LiveFgAdmission.h"
+#include "veyra/engine/FgRecoveryBudget.h"
#include "veyra/engine/RealtimePreviewScheduling.h"
#include "veyra/engine/CaptureHalfRate.h"
#include "veyra/source/MediaFileSource.h"
@@ -151,9 +152,15 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{std::lock_guard lock(mutex_);desired_.multiplier=1;snapshot_.image=true;snapshot_.desired=desired_;}
}else{
source::SourceOpenDesc od;od.path=path;od.preferHardwareDecode=false;
+ // Diagnostic uses the production graph/presenter to validate
+ // D3D12VA imports without needing a paired PS5 or credentials.
+ if(!isCapture&&GetEnvironmentVariableW(L"VEYRA_TEST_FILE_HW_DECODE",nullptr,0)){
+ od.preferHardwareDecode=true;od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();
+ }
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){
status(L"正在连接 PS5…");
+ ctx.device()->AddRef();remoteRequest->decodeDevice=std::shared_ptr<ID3D12Device>(ctx.device(),[](ID3D12Device* device){device->Release();});
if(!remote->connect(std::move(*remoteRequest))){status(L"PS5 连接失败,请查看诊断",true);break;}
remoteRequest.reset();
while(!stop_){
@@ -196,7 +203,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
if(physicalCapture&&!captureSource.start()){status(L"无法启动采集,请查看诊断",true);break;}
- {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}
+ {std::lock_guard lock(mutex_);snapshot_.duration=duration;snapshot_.nominalSourceFps=isImage?0:activeSource->info().averageFps;snapshot_.running=true;snapshot_.transport=TransportState::Playing;snapshot_.image=isImage;snapshot_.capture=isCapture;snapshot_.applied=options.snapshot();snapshot_.desired=desired_;}
status(isImage?L"图片已增强,可保存PNG/JPEG":std::format(L"{} | 输入 {}×{} / 底图 {}×{} / NR {}×{} / 光流 {}×{} / FG与输出 {}×{} | {}",isRemote?L"PS5 串流":isCapture?L"实时采集":L"播放",width,height,gd.workWidth,gd.workHeight,gd.nrWidth,gd.nrHeight,gd.flowWidth,gd.flowHeight,gd.workWidth,gd.workHeight,gd.nrWidth<gd.workWidth?L"实时内部处理并回填":L"原生NR(性能成本较高)"));
pipeline::EnhanceGraph::FrameOutputs out;bool reset=true,hasOutput=false,audioRebuffering=false,seekPreviewPending=false;
bool initialRemoteFramePending=isRemote;
@@ -232,21 +239,20 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// late. Export/images/paused frames never enter these paths.
uint64_t previewSkippedTotal=0,previewSkippedSinceSubmit=0;
bool previewSkipSinceProcess=false;
- TimingWindow fileCompletion;uint64_t fileCompletionRevision=0;
XessGenerationGate xessGenerationGate;
double playbackSpeedLastPts=0;Clock::time_point playbackSpeedLastWall{};
CaptureHalfRate captureSampler;
FrameLineageTracker lineageTracker;
auto completedProcessing=[&](pipeline::FrameIdentity id){std::lock_guard lock(mutex_);if(snapshot_.applied.revision==id.settingsRevision)++snapshot_.processedCompleted;};
auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};
- // Only the live source may discard stale input. File playback keeps
- // its audio-clock scheduler and lossless source ordering.
+ // Live ingress stays latest-frame; file preview keeps the audio clock
+ // and may skip expired enhancement opportunities, never PCM.
// Graph, query collection and presentation remain on this owner.
graph.recordGpuTimings();presenter.recordGpuTimings();
struct LiveStats {pipeline::FrameIdentity identity;uint64_t submitted=0,expired=0;double waitMs=0,presentMs=0,readyMs=0,ageMs=0,fps=0,ageP95=0,waitP95=0,presentP95=0,readyP95=0;diagnostics::GpuSample blit;};
LiveStats liveStats;std::deque<int64_t> liveSubmissions;
- TimingWindow liveAges,liveWaits,livePresent,liveReady,liveCompletion;
- int64_t lastFgCompletion=0;
+ TimingWindow liveAges,liveWaits,livePresent,liveReady;
+ FgRecoveryBudget fgBudget;uint64_t fgBudgetRevision=options.settings.revision;
std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;
std::atomic<uint64_t> presentationGeneration{0};
std::unique_ptr<LiveGpuScheduler> liveScheduler;
@@ -294,6 +300,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
OnExit resetExit{[&]{finishReset(stop_?diagnostics::ResetOutcome::Cancelled:diagnostics::ResetOutcome::Failed);}};
auto collectTimings=[&]{
auto record=[&](const diagnostics::GpuFrameTiming& sample){
+ const auto& fgCost=sample.gpu[size_t(diagnostics::GpuStage::FgBatch)];
+ 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];
if(gpu.state==diagnostics::SampleState::Measured&&gpu.milliseconds)
@@ -316,13 +324,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(!isCapture&&!isImage&&batch.batch.identity.settingsRevision==options.settings.revision){
- if(fileCompletionRevision!=options.settings.revision){fileCompletion.clear();fileCompletionRevision=options.settings.revision;}
- if(!batch.historyReset&&!batch.fgRecovery)fileCompletion.add(elapsedMs(watch.processStart));
- }
- {
- if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision&&batch.fgEvaluated&&!batch.historyReset&&!batch.fgRecovery){liveCompletion.add(elapsedMs(watch.processStart));lastFgCompletion=host100ns();}
- }
+ if(batch.batch.identity.settingsRevision==fgBudgetRevision)fgBudget.complete(elapsedMs(watch.processStart),batch.fgEvaluated>0,batch.historyReset||batch.fgRecovery,host100ns());
completeReset(batch.batch.identity);
watch.readyObserved=Clock::now();watch.ready=true;it=pendingCompletions.erase(it);
}
@@ -361,7 +363,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()){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;}
@@ -486,7 +488,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
fileInputEnded=true;
while(liveScheduler&&liveScheduler->occupancy()&&!stop_&&(!paused_||seekPreviewPending)&&!liveScheduler->failed()){advanceLive();if(liveScheduler->occupancy())waitLive();}
if(stop_)break;
- if(liveScheduler&&liveScheduler->failed()){status(L"采集尾帧呈现失败,请查看诊断",true);break;}
+ if(liveScheduler&&liveScheduler->failed()){status(L"视频尾帧呈现失败,请查看诊断",true);break;}
if(paused_)continue;
collectTimings();seekPreviewPending=false;status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;
}
@@ -560,17 +562,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;
if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");
pipeline::EnhanceGraph::FgAdmission admitFg;
+ if(fgBudgetRevision!=options.settings.revision){fgBudget.reset();fgBudgetRevision=options.settings.revision;}
// DLSS can reseed after a skipped pair. XeSS
// owns generation inside its presenter and has no graph admission.
if(isCapture&&!rereadCached&&useLiveFgAdmission&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){
- std::optional<double> completionP95;double presentP95=0;uint64_t predictionEpoch=0;
- {if(host100ns()-lastFgCompletion>5000000)liveCompletion.clear();if(!historyReset&&liveStats.identity.settingsRevision==options.settings.revision&&liveCompletion.size()>=8){completionP95=liveCompletion.p95();presentP95=livePresent.p95();predictionEpoch=liveStats.identity.epoch;}}
- admitFg=[&,completionP95,presentP95,predictionEpoch](const pipeline::FrameBatch& batch){
+ const auto presentP95=livePresent.p95();
+ admitFg=[&,presentP95](const pipeline::FrameBatch& batch){
if(!liveTimeline.anchored(batch.identity.epoch))liveTimeline.reset(batch.identity.epoch,batch.b100ns,captureArrival,liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps));
const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;
const auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,options.fgMultiplier-1,options.fgMultiplier);
- return admitLiveFg(host100ns(),liveTimeline.deadline(lastGenerated),elapsedMs(processStart),predictionEpoch==batch.identity.epoch?completionP95:std::nullopt,presentP95);
+ return fgBudget.admit(host100ns(),liveTimeline.deadline(lastGenerated),elapsedMs(processStart),presentP95);
};
}
// File playback: same pair admission, but deadlines are PTS
@@ -578,19 +580,22 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// generated timestamp can no longer be reached spends no FG
// Evaluate; the real frame keeps its normal cadence (plan §4.1).
if(!isCapture&&!isImage&&!rereadCached&&!transaction&&options.fg&&options.settings.frameGenerationBackend!=FrameGenerationBackend::XeSS){
- const bool predictionValid=fileCompletionRevision==options.settings.revision&&fileCompletion.size()>=8;
- const std::optional<double> completionP95=predictionValid?std::optional<double>(fileCompletion.p95()):std::nullopt;
- const double presentP95=predictionValid?presentTimes.p95():0.0;
- admitFg=[&,historyReset,completionP95,presentP95](const pipeline::FrameBatch& batch){
+ admitFg=[&,historyReset](const pipeline::FrameBatch& batch){
if(fileAwaitingVideo)return true; // Bounded startup lookahead; audio has not started.
const auto interval=liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps);
const auto a=(historyReset||batch.b100ns<=batch.a100ns||batch.b100ns-batch.a100ns>10000000)?batch.b100ns-interval:batch.a100ns;
const auto lastGenerated=pipeline::FrameBatch::interpolate(a,batch.b100ns,options.fgMultiplier-1,options.fgMultiplier);
- return admitLiveFg(int64_t(nowMs()*10000.0),lastGenerated,elapsedMs(processStart),completionP95,presentP95);
+ const auto now=host100ns();
+ return fgBudget.admit(now,now+lastGenerated-int64_t(nowMs()*10000.0),elapsedMs(processStart),livePresent.p95());
};
}
uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=0;
if(resetRecord&&resetRecord->epoch==0)resetStageStart=Clock::now();
+ // Bounded integration-test delay on the owner thread. It
+ // exercises missed deadlines and recovery without changing
+ // settings/history or inventing GPU execution timestamps.
+ wchar_t testWork[16]{};
+ if(!isImage&&GetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",testWork,16))std::this_thread::sleep_for(std::chrono::milliseconds(std::clamp(_wtoi(testWork),0,150)));
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){
@@ -629,7 +634,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
// soft preview-skip history breaks do NOT reopen them.
if(settingsChanged){xessGenerationGate.reset();presenter.setXessGenerationSuppressed(false);}
playbackSpeedLastWall={};
- if(liveScheduler){liveStats={};liveStats.identity=out.batch.identity;liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();liveCompletion.clear();}
+ if(liveScheduler){liveStats={};liveStats.identity=out.batch.identity;liveSubmissions.clear();liveAges.clear();liveWaits.clear();livePresent.clear();liveReady.clear();}
if(settingsChanged||!completionRates)completionRates=std::make_shared<FrameCompletionRates>(host100ns());
frameFlow=std::shared_ptr<FrameFlowWindow>(new FrameFlowWindow(runSessionId,out.batch.identity,host100ns(),completionRates),[](FrameFlowWindow* window){logFrameFlow(window->snapshot(monotonic100ns()),"closed");delete window;});
if(resetRecord)frameFlow->resetLifecycle(*resetRecord);else if(lastResetRecord)frameFlow->resetLifecycle(*lastResetRecord);
@@ -647,6 +652,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
processTimes.add(processMs);
traceFrame(diagnostics::TraceKind::Submitted,out.batch.identity,out.batch.batchId,std::max(out.videoFenceValue,out.genFenceValue),out.batch.b100ns,out.fgSkippedBeforeEval,out.fgEvaluated,processMs);
frameFlow->cpu(diagnostics::CpuStage::Decode,decodeMs,host100ns());
+ if(isRemote&&pkt.decodedHost100ns>0&&!rereadCached)frameFlow->cpu(diagnostics::CpuStage::DecodedQueue,std::max(0.0,double(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100-pkt.decodedHost100ns)/10000),host100ns());
frameFlow->update([&](auto& m){m.lastSubmit100ns=host100ns();});
frameFlow->cpu(diagnostics::CpuStage::Submit,processMs,host100ns());
frameFlow->cpu(diagnostics::CpuStage::SlotWait,processSlotWaitMs,host100ns());
@@ -714,10 +720,14 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
const auto xessGenerated=presenter.xessGeneratedCount()-beforeXess,xessPresented=presenter.xessPresentedCount()-beforeXessPresented;
item.lease->consumerFence=ring.lastSignaledValue();const bool didPresent=presenter.submittedCount()>before;s.blit=presenter.blitTiming(ctx.fence());
const auto elapsed=elapsedMs(begin);s.presentMs+=elapsed;flow->cpu(diagnostics::CpuStage::Present,elapsed,host100ns());
- if(didPresent)traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
+ if(didPresent){
+ traceFrame(diagnostics::TraceKind::Present,item.identity,batch.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsed);
+ if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",batch.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));
+ }
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;}}
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_);}
@@ -749,103 +759,32 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(s.count){liveStats.waitMs=s.waitMs;liveStats.presentMs=s.presentMs;liveStats.readyMs=s.readyMs;liveStats.ageMs=s.ageMs;liveStats.blit=s.blit;
liveAges.add(s.ageMs);liveWaits.add(s.waitMs);livePresent.add(s.presentMs);liveReady.add(s.readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}
liveStats.fps=liveSubmissions.size()>1?double(liveSubmissions.size()-1)*1e7/(liveSubmissions.back()-liveSubmissions.front()):0;
- })){status(L"采集呈现队列失败",true);break;}
+ })){status(L"视频呈现队列失败",true);break;}
advanceLive();
const auto occupancy=liveScheduler->occupancy();frameFlow->update([&](auto& m){m.counters.presentationBatchHighWater=std::max(m.counters.presentationBatchHighWater,occupancy);});
const auto completed=liveStats;
frameWaitMs=completed.waitMs;framePresentMs=completed.presentMs;gpuWaitMs=completed.readyMs;submitted=completed.submitted;expired=completed.expired;
}else{
- unsigned handled=0;
- OnExit accountCancelled{[&]{frameFlow->update([&](auto& m){m.counters.cancelledBeforePresent+=out.batch.count-handled;});}};
- const auto readyStart=Clock::now();
- while(!stop_&&(!paused_||seekPreviewPending)&&seekSeconds_<0&&!graph.resolveGeneration(out)){
- if(elapsedMs(readyStart)>2000){status(L"补帧 GPU 就绪超时",true);stop_=true;break;}
- deadlineWait.slice(.2);
- }
- if(stop_)break;
- if((paused_&&!seekPreviewPending)||seekSeconds_>=0){reset=true;pendingResetCause=seekSeconds_>=0?pipeline::ResetReason::Seek:pipeline::ResetReason::PauseResume;if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} cancelled before submit (pause/seek)",out.batch.batchId));continue;}
- unsigned valid=0,invalid=0;for(unsigned i=0;i<out.batch.count;++i)if(out.batch.frames[i].kind==pipeline::FrameKind::Generated){if(out.batch.frames[i].validity==pipeline::GenerationValidity::Valid)++valid;else ++invalid;}
- frameFlow->ready(out.batch.batchId,!rereadCached&&!isImage,valid,invalid,host100ns());
- traceFrame(diagnostics::TraceKind::Ready,out.batch.identity,out.batch.batchId,std::max(out.videoFenceValue,out.genFenceValue),out.batch.b100ns,invalid,valid,elapsedMs(processStart));
- completeReset(out.batch.identity);
- if(!rereadCached&&!isImage)completedProcessing(out.batch.identity);
- gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
- frameFlow->cpu(diagnostics::CpuStage::ReadyWait,gpuWaitMs,host100ns());
- // Completion-time prediction for the NEXT pair's admission:
- // samples span submit -> GPU-ready. Cost depends on backend and
- // dimensions, so the window is keyed to the settings revision
- // only — not to seek/preview-skip temporal epochs.
- if(!isImage&&fileCompletionRevision!=options.settings.revision){
- fileCompletion.clear();fileCompletionRevision=options.settings.revision;
- }
- if(!isImage)fileCompletion.add(elapsedMs(processStart));
- // WASAPI prefill is allowed before video; device-clock playback
- // is not. Align only open/seek, never discard audio to catch up
- // with a slow graph during ordinary playback or settings edits.
- if(audioStarted&&fileAudioAlignPending){
- while(!stop_&&audioPipe.endpointRecovering()){publishAudioStatus();deadlineWait.slice();}
- const double media=audio.mediaTimeMs();
- if(std::isfinite(media)&&media+1.0<pts){
- const double aligned=audioPipe.requestSeek(pts);
- if(!std::isfinite(aligned)){status(L"音频时间线对齐失败",true);break;}
+ // Images have no media clock, audio or temporal batches.
+ const auto readyStart=Clock::now();
+ while(!stop_&&!graph.resolveGeneration(out)){
+ if(elapsedMs(readyStart)>2000){status(L"图片 GPU 就绪超时",true);stop_=true;break;}
+ deadlineWait.slice(.2);
}
- fileAudioAlignPending=false;
- }
- bool interrupted=false,presentFailed=false;
- for(uint32_t i=0;i<out.batch.count;++i){
- auto& item=out.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;
- if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}
- if(generated&&comparisonMode_!=0)continue;
- if(isCapture&&generated&&liveTimeline.expired(item.pts100ns,host100ns(),100000)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}
- // File preview: a generated result whose PTS the master
- // clock already passed by the shared 10ms grace replays
- // stale media; skip its present but still count it as
- // computed-but-not-shown GPU work (plan §4.1).
- if(!isCapture&&generated&&comparisonMode_==0&&previewGeneratedExpired(nowMs(),item.pts100ns/10000.0)){++expired;++handled;frameFlow->update([](auto& m){++m.counters.generatedExpiredAfterEval;});continue;}
- const double itemPtsMs=item.pts100ns/10000.0;
- if(audioStarted&&!fileAwaitingVideo)audioPipe.videoReady(itemPtsMs);
- const auto waitStart=Clock::now();
- while(!stop_&&!paused_&&seekSeconds_<0&&(isCapture?host100ns()<liveTimeline.deadline(item.pts100ns):!fileAwaitingVideo&&nowMs()+0.25<itemPtsMs))deadlineWait.slice();
- frameWaitMs+=elapsedMs(waitStart);
- frameFlow->cpu(diagnostics::CpuStage::DeadlineWait,elapsedMs(waitStart),host100ns());
- if(stop_||(paused_&&!seekPreviewPending)||seekSeconds_>=0){interrupted=true;break;}
- const auto begin=Clock::now();const auto before=presenter.submittedCount();const auto beforeXess=presenter.xessGeneratedCount(),beforeXessPresented=presenter.xessPresentedCount();
- if(!presenter.present(ctx,ring,graph,item.lease->slot,generated,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}
- framePresentMs+=elapsedMs(begin);
- frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
- frameFlow->xessSubmitted(presenter.xessPresentedCount()-beforeXessPresented,presenter.xessGeneratedCount()-beforeXess,host100ns());
- item.lease->consumerFence=ring.lastSignaledValue();
- if(presenter.submittedCount()>before)traceFrame(diagnostics::TraceKind::Present,item.identity,out.batch.batchId,item.lease->consumerFence,item.pts100ns,item.subframe,1,elapsedMs(begin));
- if(presenter.submittedCount()>before){++handled;frameFlow->presented(generated,item.lease->consumerFence,host100ns());}
- if(presenter.submittedCount()>before&&!isCapture&&!isImage){
- const double intervalMs=double(liveSourceInterval100ns(pkt.duration,activeSource->info().averageFps))/10000.0;
- // XeSS owns generated frames inside its swapchain. The
- // engine sees only real B frames, so its audio coverage
- // must last a SOURCE interval, never a hidden subframe.
- // A pair whose FG was not evaluated/generated covers
- // the whole source interval to the next real frame.
- const bool callerPresentsGenerated=options.fg&&!graph.xessEnabled()&&comparisonMode_==0&&out.hasGenerated;
- double nextPtsMs=itemPtsMs+intervalMs/(callerPresentsGenerated?options.fgMultiplier:1);
- for(uint32_t next=i+1;next<out.batch.count;++next){const auto& candidate=out.batch.frames[next];
- if(candidate.kind!=pipeline::FrameKind::Generated||(candidate.validity==pipeline::GenerationValidity::Valid&&comparisonMode_==0)){nextPtsMs=candidate.pts100ns/10000.0;break;}}
- if(audioStarted){audioPipe.videoPresented(nextPtsMs);audioPipe.setPaused(paused_);}
- if(fileAwaitingVideo)veyra::log::info("audio-sync",std::format("video anchor presented ptsMs={:.3f} audioPtsMs={:.3f} nextPtsMs={:.3f} paused={} (Present return, scanout unmeasured)",itemPtsMs,audio.mediaTimeMs(),nextPtsMs,paused_.load()));
- fileAwaitingVideo=false;anchor=Clock::now();anchorMs=itemPtsMs;
- // Sustained lateness suppresses SDK-owned XeSS-FG
- // generation over a stable interval; the presenter's
- // history reset covers the later re-enable.
- if(graph.xessEnabled()&&presenter.xessActive()&&xessGenerationGate.observe(nowMs()-itemPtsMs,intervalMs)){
- presenter.setXessGenerationSuppressed(xessGenerationGate.suppressed());
- veyra::log::info("xess-fg-gate",std::format("event={} revision={} lateMs={:.3f} intervalMs={:.3f}",xessGenerationGate.suppressed()?"suppress":"resume",options.settings.revision,nowMs()-itemPtsMs,intervalMs));
- }
+ if(stop_)break;
+ gpuWaitMs=elapsedMs(readyStart);gpuReadyTimes.add(gpuWaitMs);
+ frameFlow->cpu(diagnostics::CpuStage::ReadyWait,gpuWaitMs,host100ns());
+ frameFlow->ready(out.batch.batchId,false,0,0,host100ns());completeReset(out.batch.identity);
+ bool presentFailed=false;
+ for(auto& item:out.batch.frames){
+ if(!item.lease)continue;
+ const auto begin=Clock::now();const auto before=presenter.submittedCount();
+ if(!presenter.present(ctx,ring,graph,item.lease->slot,false,item.lease->referencesValid,comparisonMode_,comparisonBase_,comparisonSplit_,item.identity,previewView())){presentFailed=true;break;}
+ item.lease->consumerFence=ring.lastSignaledValue();framePresentMs+=elapsedMs(begin);
+ frameFlow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());
+ if(presenter.submittedCount()>before){++submitted;frameFlow->presented(false,item.lease->consumerFence,host100ns());}
}
- if(presenter.submittedCount()>before&&!generated&&!rereadCached)frameFlow->latency(std::chrono::duration_cast<std::chrono::nanoseconds>(decodeStart.time_since_epoch()).count()/100,host100ns());
- if(presenter.submittedCount()>before&&generated&&lineage)frameFlow->generatedLatency(*lineage,host100ns());
- if(presenter.submittedCount()>before){++submitted;const auto time=host100ns();submissionTimes.push_back(time);while(submissionTimes.size()>1&&time-submissionTimes.front()>10000000)submissionTimes.pop_front();if(veyra::log::verboseFrameLogs())veyra::log::info("submit",std::format("batch={} epoch={} revision={} subframe={} pts100ns={} host100ns={} fence={} (submission, display unmeasured)",out.batch.batchId,item.identity.epoch,item.identity.settingsRevision,item.subframe,item.pts100ns,host100ns(),item.lease->consumerFence));}
- }
- if(presentFailed){status(L"画面提交失败",true);break;}
- if(interrupted){reset=true;pendingResetCause=seekSeconds_>=0?pipeline::ResetReason::Seek:pipeline::ResetReason::PauseResume;continue;}
- seekPreviewPending=false;
+ if(presentFailed){status(L"图片呈现失败",true);break;}
}
if(!liveScheduler){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}
audioRebuffering=audioStarted&&audioPipe.waitingForVideo();
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index aff33c3f..784455c0 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -689,6 +689,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
uint32_t slot = 0;
if (uploadFences_[parity] && !context_.waitForFenceValue(uploadFences_[parity])) return false;
+ hardwareInputFrames_[parity].reset();
+ if(frame->format==AV_PIX_FMT_D3D12){
+ auto* retained=av_frame_clone(frame);
+ if(!retained)return false;
+ hardwareInputFrames_[parity]=std::shared_ptr<AVFrame>(retained,[](AVFrame* value){av_frame_free(&value);});
+ }
Status st = Status::Ok;
// 1. Source NV12: D3D12VA texture directly (GPU) or CPU upload.
@@ -1282,6 +1288,7 @@ void EnhanceGraph::shutdown()
{
if (!initialized_ && !nrAdapter_ && !nvof_ && !srcRgba_) return;
(void)ring_.drainQueue();(void)ring_.discardRecording();
+ for(auto& input:hardwareInputFrames_)input.reset();
Status st = Status::Ok;
if (nv12Ctx_ != nullptr) { sws_freeContext(nv12Ctx_); nv12Ctx_ = nullptr; }
diff --git a/src/remoteplay/SessionInbox.cpp b/src/remoteplay/SessionInbox.cpp
index 5f613192..2107c9fb 100644
--- a/src/remoteplay/SessionInbox.cpp
+++ b/src/remoteplay/SessionInbox.cpp
@@ -10,7 +10,9 @@ struct SessionInbox::Shared {
HostTime origin=0;bool accepting=false;std::uint64_t stale=0;int error=0;
VideoIngress video;AudioIngress audio;
HostTime lastVideo=0,lastAudio=0,decodeStart=0,lastDecoded=0;
- uint64_t decodedFrames=0,receivedBytes=0,framesLost=0,framesRecovered=0;
+ uint64_t decodedFrames=0,receivedBytes=0,framesLost=0,referenceRecoveryEvents=0;
+ bool hardwareDecode=false,decodeFallback=false,decodeConfirmed=false;
+ VideoProfile requestedProfile;
struct Sample {HostTime time;double value;};
std::deque<Sample> received,decoded,decodeTimes,ingressWait;
static void add(std::deque<Sample>& q,HostTime now,double value){
@@ -26,7 +28,8 @@ SessionInbox::Token SessionInbox::begin(HostTime origin){
if(s.state!=SessionState::Idle)throw std::logic_error("Stop and join previous backend before a new session");
if(s.generation==std::numeric_limits<Generation>::max())throw std::overflow_error("Session generation exhausted");
++s.generation;s.video.begin(s.generation);s.audio.begin(s.generation);s.origin=origin;s.state=SessionState::Connecting;s.accepting=true;s.error=0;
- s.lastVideo=s.lastAudio=s.decodeStart=s.lastDecoded=0;s.decodedFrames=s.receivedBytes=s.framesLost=s.framesRecovered=0;
+ s.lastVideo=s.lastAudio=s.decodeStart=s.lastDecoded=0;s.decodedFrames=s.receivedBytes=s.framesLost=s.referenceRecoveryEvents=0;
+ s.hardwareDecode=s.decodeFallback=s.decodeConfirmed=false;
s.received.clear();s.decoded.clear();s.decodeTimes.clear();s.ingressWait.clear();
return Token{shared_,s.generation};
}
@@ -46,7 +49,9 @@ SessionInbox::Snapshot SessionInbox::snapshot()const{
auto& s=*shared_;std::lock_guard l(s.mutex);Snapshot result{s.generation,s.state,s.origin,s.stale,s.error,s.video.stats(),s.audio.stats()};
const auto now=monotonic100ns();result.lastVideo100ns=s.lastVideo;result.lastAudio100ns=s.lastAudio;
result.decodeStarted100ns=s.decodeStart;result.lastDecoded100ns=s.lastDecoded;
- result.decodedFrames=s.decodedFrames;result.receivedBytes=s.receivedBytes;result.framesLost=s.framesLost;result.framesRecovered=s.framesRecovered;
+ result.decodedFrames=s.decodedFrames;result.receivedBytes=s.receivedBytes;result.framesLost=s.framesLost;result.referenceRecoveryEvents=s.referenceRecoveryEvents;
+ result.hardwareDecode=s.hardwareDecode;result.decodeFallback=s.decodeFallback;result.decodeConfirmed=s.decodeConfirmed;
+ result.requestedProfile=s.requestedProfile;
result.ratesReady=now-s.origin>=10000000;
for(const auto& v:s.received)if(v.time>now-10000000){++result.receivedFps;result.videoMbps+=v.value*8/1000000;}
for(const auto& v:s.decoded)if(v.time>now-10000000)++result.decodedFps;
@@ -62,7 +67,7 @@ void SessionInbox::frameDecoded(HostTime now){auto& s=*shared_;std::lock_guard l
bool SessionInbox::Token::video(VideoSample sample)const noexcept{
try{auto s=shared_.lock();if(!s)return false;std::lock_guard l(s->mutex);if(!s->current(generation_))return false;
if(sample.generation!=generation_)return false;
- if(sample.kind==SampleKind::AccessUnit){s->lastVideo=monotonic100ns();s->receivedBytes+=sample.payload.bytes().size();s->framesLost+=std::max(0,sample.framesLost);s->framesRecovered+=sample.referenceRecovered?1:0;Shared::add(s->received,s->lastVideo,double(sample.payload.bytes().size()));}
+ if(sample.kind==SampleKind::AccessUnit){s->lastVideo=monotonic100ns();s->receivedBytes+=sample.payload.bytes().size();s->framesLost+=std::max(0,sample.framesLost);s->referenceRecoveryEvents+=sample.referenceRecovered?1:0;Shared::add(s->received,s->lastVideo,double(sample.payload.bytes().size()));}
const auto r=s->video.push(std::move(sample),monotonic100ns());return r==PushStatus::Accepted||r==PushStatus::ConfigStored;
}catch(...){failed(-1001);return false;}
}
@@ -83,4 +88,8 @@ void SessionInbox::Token::failed(int code)const noexcept{
s->error=code;s->state=SessionState::Failed;s->accepting=false;s->video.close();s->audio.close();
}catch(...){}
}
+void SessionInbox::decoderBackend(bool hardware,bool fallback){
+ auto& s=*shared_;std::lock_guard lock(s.mutex);s.hardwareDecode=hardware;s.decodeFallback=fallback;s.decodeConfirmed=true;
+}
+void SessionInbox::streamProfile(VideoProfile profile){auto& s=*shared_;std::lock_guard lock(s.mutex);s.requestedProfile=profile;}
} // namespace veyra::remoteplay
diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cpp
index 19e9fe53..2137ad10 100644
--- a/src/source/RemotePlaySource.cpp
+++ b/src/source/RemotePlaySource.cpp
@@ -10,12 +10,19 @@
#include <format>
#include <limits>
#include <span>
+#ifdef _WIN32
+#include <d3d12.h>
+#endif
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/frame.h>
#include <libavutil/mem.h>
#include <libavutil/pixfmt.h>
+#include <libavutil/hwcontext.h>
+#ifdef _WIN32
+#include <libavutil/hwcontext_d3d12va.h>
+#endif
}
namespace veyra::source {
@@ -34,6 +41,10 @@ std::shared_ptr<AVFrame> cloneFrame(const AVFrame* frame)
pipeline::SourcePixelFormat pixelFormatFromFrame(const AVFrame& frame)
{
+ if(frame.format==AV_PIX_FMT_D3D12&&frame.hw_frames_ctx){
+ const auto* context=reinterpret_cast<const AVHWFramesContext*>(frame.hw_frames_ctx->data);
+ return context->sw_format==AV_PIX_FMT_NV12?pipeline::SourcePixelFormat::NV12:pipeline::SourcePixelFormat::Unknown;
+ }
switch (frame.format) {
case AV_PIX_FMT_NV12: return pipeline::SourcePixelFormat::NV12;
case AV_PIX_FMT_P010: return pipeline::SourcePixelFormat::P010;
@@ -80,6 +91,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
request_.credentials.accountId = desc.request.credentials.accountId;
request_.credentials.registrationKey = desc.request.credentials.registrationKey;
request_.credentials.sessionKey = desc.request.credentials.sessionKey;
+ decodeMode_=desc.decodeMode;decodeDevice_=desc.decodeDevice;hardwareFallback_=false;
origin100ns_ = static_cast<std::uint64_t>(remoteplay::monotonic100ns());
try {
@@ -90,6 +102,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
return false;
}
auto token = inbox_->begin(static_cast<remoteplay::HostTime>(origin100ns_));
+ inbox_->streamProfile(request_.video);
token_ = token; // Keep a second weak token; backend owns the moved copy.
const auto started = backend_.start(request_, token);
if (!started.ok) {
@@ -169,10 +182,38 @@ bool RemotePlaySource::openDecoder(remoteplay::Codec codec, std::uint32_t width,
codecContext_->max_pixels = 1920LL * 1088;
codecContext_->thread_count = 1;
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
+#ifdef _WIN32
+ if(decodeMode_!=RemotePlayConnectDesc::DecodeMode::Software&&!hardwareFallback_&&decodeDevice_){
+ AVBufferRef* device=av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D12VA);
+ int result=AVERROR(ENOMEM);
+ if(device){
+ auto* context=reinterpret_cast<AVHWDeviceContext*>(device->data);
+ auto* native=reinterpret_cast<AVD3D12VADeviceContext*>(context->hwctx);
+ native->device=decodeDevice_.get();native->device->AddRef();
+ result=av_hwdevice_ctx_init(device);
+ }
+ if(result>=0){
+ codecContext_->hw_device_ctx=device;
+ codecContext_->get_format=[](AVCodecContext*,const AVPixelFormat* formats){
+ for(auto p=formats;*p!=AV_PIX_FMT_NONE;++p)if(*p==AV_PIX_FMT_D3D12)return *p;
+ return AV_PIX_FMT_NONE;
+ };
+ }else{
+ av_buffer_unref(&device);hardwareFallback_=true;
+ if(decodeMode_==RemotePlayConnectDesc::DecodeMode::Hardware){
+ veyra::log::error("remoteplay-decode",std::format("requested hardware unavailable code={}; choose automatic or software",result));
+ avcodec_free_context(&codecContext_);return false;
+ }
+ veyra::log::warn("remoteplay-decode",std::format("D3D12VA device init failed code={}; falling back to software",result));
+ }
+ }
+#endif
const int opened = avcodec_open2(codecContext_, decoder, nullptr);
if (opened < 0) {
veyra::log::error("remoteplay", std::format("FFmpeg remote decoder open failed code={}", opened));
+ const bool retrySoftware=codecContext_->hw_device_ctx&&!hardwareFallback_&&decodeMode_==RemotePlayConnectDesc::DecodeMode::Automatic;
avcodec_free_context(&codecContext_);
+ if(retrySoftware){hardwareFallback_=true;return openDecoder(codec,width,height);}
return false;
}
decoderFrame_ = av_frame_alloc();
@@ -183,7 +224,7 @@ bool RemotePlaySource::openDecoder(remoteplay::Codec codec, std::uint32_t width,
decoderReady_ = true;
info_.width = width;
info_.height = height;
- veyra::log::info("remoteplay", std::format("software decoder opened codec={} {}x{}", decoder->name, width, height));
+ veyra::log::info("remoteplay", std::format("{} decoder opened codec={} {}x{} (active format confirmed on first output)",codecContext_->hw_device_ctx?"D3D12VA":"software", decoder->name, width, height));
return true;
}
@@ -248,12 +289,17 @@ bool RemotePlaySource::drainDecoder(std::uint64_t sourceIndex, const pipeline::F
packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Resize);
}
info_.color = packet.colorInfo;
+ const bool hardware=decoderFrame_->format==AV_PIX_FMT_D3D12;
+ if(sequence_==1||info_.hardwareDecodeActive!=hardware)veyra::log::info("remoteplay-decode",std::format("actual={} pixelFormat={} {}x{} fallback={}",hardware?"D3D12VA":"software",decoderFrame_->format,decoderFrame_->width,decoderFrame_->height,hardwareFallback_));
+ info_.hardwareDecodeActive=hardware;
+ inbox_->decoderBackend(hardware,hardwareFallback_);
packet.color.resource = nullptr;
// The AU contract is one picture per input. Unknown/reused timestamps
// are rejected above instead of fabricating timing for extra pictures.
(void)sourcePacket;
(void)sourceIndex;
if (ready_.size() >= 4) return false;
+ packet.decodedHost100ns=remoteplay::monotonic100ns();
ready_.push_back({std::move(clone), packet});
inbox_->frameDecoded(remoteplay::monotonic100ns());
}
@@ -351,6 +397,15 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
}
if (!submitPacket(payload, sourceIndex, sourcePacket)) {
flushDecoder();
+ if(codecContext_&&codecContext_->hw_device_ctx&&!hardwareFallback_){
+ if(decodeMode_==RemotePlayConnectDesc::DecodeMode::Hardware){
+ veyra::log::error("remoteplay-decode","requested hardware decode failed; choose automatic or software");
+ inbox_->decodeFailed(sample.generation);return SourceReadStatus::Error;
+ }
+ hardwareFallback_=true;avcodec_free_context(&codecContext_);decoderReady_=false;
+ info_.hardwareDecodeActive=false;
+ veyra::log::warn("remoteplay-decode","hardware decode failed; switching to software at next keyframe");
+ }
inbox_->decodeFailed(sample.generation);
return SourceReadStatus::Waiting;
}
@@ -437,6 +492,7 @@ void RemotePlaySource::close() noexcept
av_frame_free(&decoderFrame_);
avcodec_free_context(&codecContext_);
decoderReady_ = false;
+ decodeDevice_.reset();
audioBlock_.reset(); audioAnchorSample_.reset(); audioOffset_ = 0;
audioNextSample_ = 0; audioRate_ = 0; wireSequence_.reset();
request_.credentials = remoteplay::PairingCredentials{};
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index 81b611a9..93d33799 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -11,7 +11,7 @@ using namespace veyra;
using namespace std::chrono_literals;
int wmain(int argc,wchar_t**argv){
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--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"--reset-rollback")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ if(argc!=3&&!(argc==4&&(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;
@@ -21,6 +21,8 @@ int wmain(int argc,wchar_t**argv){
const bool overload=(argc==4&&std::wstring(argv[3]).find(L"--overload")==0);
const bool fileOverload=argc==4&&wcscmp(argv[3],L"--file-overload")==0;
const bool fileEndpoint=argc==4&&wcscmp(argv[3],L"--file-endpoint")==0;
+ const bool fileRecovery=argc==4&&wcscmp(argv[3],L"--file-fg-recovery")==0;
+ if(fileRecovery){options.captureReplayForTest=false;options.nr=options.fg=true;options.fgMultiplier=2;engine.setVolume(0,true);}
const bool fileContinuity=argc==4&&wcscmp(argv[3],L"--file-continuity")==0;
if(fileContinuity){options.captureReplayForTest=false;options.nr=options.fg=true;options.realtime=false;options.settings.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;engine.setVolume(0,true);}
if(fileEndpoint){options.captureReplayForTest=false;SetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",L"1");engine.setVolume(0,true);}
@@ -30,6 +32,21 @@ 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(fileRecovery){
+ check(until([](const auto& s){return s.metrics.flow.generatedPresentFps>15&&s.metrics.flow.presentSubmitFps>45;},15),"NR plus 2X starts with real generated presentation");
+ const auto before=engine.snapshot();const auto wallStart=std::chrono::steady_clock::now();
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",L"70");
+ check(until([&](const auto& s){return s.processedCompleted>=before.processedCompleted+40;},15),"slow owner still advances source output");
+ const auto slow=engine.snapshot();const auto seconds=std::chrono::duration<double>(std::chrono::steady_clock::now()-wallStart).count();
+ check(slow.audioVideoWaits==before.audioVideoWaits,"insufficient output rate never stops steady audio");
+ check(std::abs(slow.position-before.position-seconds)<.3,"slow preview follows one-times media timeline");
+ check(slow.previewSkipped>0&&slow.lateMs<250,"overload skips distributed source opportunities and bounds latency");
+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);
+ check(until([&](const auto& s){return s.applied.revision==before.applied.revision&&s.metrics.flow.generatedPresentFps>15&&s.metrics.flow.presentSubmitFps>45;},12),"FG recovers without changing settings or restarting audio");
+ const auto recovered=engine.snapshot();check(recovered.audioVideoWaits==before.audioVideoWaits,"recovery retains continuous audio");
+ std::cout<<"FILE_RECOVERY slowPresent="<<slow.metrics.flow.presentSubmitFps<<" recoveredPresent="<<recovered.metrics.flow.presentSubmitFps<<" generatedPresent="<<recovered.metrics.flow.generatedPresentFps<<" skipped="<<slow.previewSkipped<<"\n";
+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"recovery session drains");DestroyWindow(window);CoUninitialize();return failures?1:0;
+ }
if(fileContinuity){
check(until([](const auto& s){return s.frames>=20;}),"XeSS/NR file starts with actual audio");
const auto before=engine.snapshot();const auto begin=std::chrono::steady_clock::now();
diff --git a/tests/remoteplay/SourceTests.cpp b/tests/remoteplay/SourceTests.cpp
index c82913ef..a0827ec6 100644
--- a/tests/remoteplay/SourceTests.cpp
+++ b/tests/remoteplay/SourceTests.cpp
@@ -3,8 +3,10 @@
#include <algorithm>
#include <stdexcept>
#include <cmath>
+#include <d3d12.h>
extern "C" {
#include <libavcodec/avcodec.h>
+#include <libavutil/hwcontext.h>
}
extern "C" {
#include <libavformat/avformat.h>
@@ -15,6 +17,7 @@ extern "C" {
using namespace veyra;
using namespace veyra::remoteplay;
using namespace veyra::source;
+static bool testHardware=false;
namespace veyra::source {
struct RemotePlaySourceTestAccess {
static void check(bool ok) { if(!ok) throw std::runtime_error("RemotePlay source regression failed"); }
@@ -22,6 +25,12 @@ static std::vector<uint8_t> bytes(const char* path) {
std::ifstream f(path,std::ios::binary); return {std::istreambuf_iterator<char>(f),{}};
}
static void setup(RemotePlaySource& s) {
+ if(testHardware){
+ ID3D12Device* device=nullptr;
+ check(SUCCEEDED(D3D12CreateDevice(nullptr,D3D_FEATURE_LEVEL_11_0,IID_PPV_ARGS(&device))));
+ s.decodeDevice_=std::shared_ptr<ID3D12Device>(device,[](auto* value){value->Release();});
+ s.decodeMode_=RemotePlayConnectDesc::DecodeMode::Hardware;
+ }
s.origin100ns_=monotonic100ns();
s.token_=s.inbox_->begin(static_cast<HostTime>(s.origin100ns_));
s.token_->connected(); s.connected_=true;
@@ -65,6 +74,7 @@ static void splitTest(const char* prefix, Codec codec=Codec::H264) {
std::cout<<(codec==Codec::H264?"SPLIT_H264":"SPLIT_H265")<<" config_accepted="<<ca<<" au_accepted="<<fa<<" read_status="<<int(r)
<<" frame="<<bool(frame)<<" session_state="<<int(s.sessionSnapshot().state)<<"\n";
check(ca && fa && r==SourceReadStatus::Frame && frame && s.sessionSnapshot().state==SessionState::Streaming);
+ if(testHardware){check(frame->format==AV_PIX_FMT_D3D12&&s.info().hardwareDecodeActive);std::cout<<"REAL_D3D12_DECODE_PASS codec="<<int(codec)<<"\n";}
// Decode across the real 16-bit wrap, retaining a valid increasing PTS.
const auto firstPts=p.pts.to100ns();
VideoSample wrapped;wrapped.generation=s.token_->generation();wrapped.width=1280;wrapped.height=720;wrapped.codec=codec;
@@ -105,12 +115,56 @@ static void reorder(const char* path) {
check(n==12 && outputs==10 && mismatches==0);
std::cout<<"REORDER input="<<n<<" output_before_eof="<<outputs<<" wrong_pts="<<mismatches<<"\n";
}
+static void compareDecode(const char* prefix,Codec codec){
+ RemotePlaySource software,hardware;
+ testHardware=false;setup(software);testHardware=true;setup(hardware);
+ const auto config=bytes((std::string(prefix)+"-config.bin").c_str());
+ auto data=config;const auto au=bytes((std::string(prefix)+"-au.bin").c_str());data.insert(data.end(),au.begin(),au.end());
+ pipeline::FramePacket stamp;stamp.pts={0,60};
+ for(auto* source:{&software,&hardware}){
+ check(source->openDecoder(codec,1280,720));stamp.colorInfo=source->info_.color;
+ check(source->submitPacket(data,0,stamp)&&source->ready_.size()==1);
+ }
+ auto* cpu=software.ready_.front().frame.get();auto* gpu=hardware.ready_.front().frame.get();
+ AVFrame* downloaded=av_frame_alloc();check(downloaded&&av_hwframe_transfer_data(downloaded,gpu,0)>=0);
+ // Diagnostic-only readback: compare identical coded YUV before the common
+ // colour shader. Product hardware playback never performs this transfer.
+ check(cpu->width==downloaded->width&&cpu->height==downloaded->height&&downloaded->format==AV_PIX_FMT_NV12&&cpu->format==AV_PIX_FMT_YUV420P);
+ int maxError=0;
+ for(int y=0;y<cpu->height;++y)for(int x=0;x<cpu->width;++x)maxError=std::max(maxError,std::abs(int(cpu->data[0][y*cpu->linesize[0]+x])-int(downloaded->data[0][y*downloaded->linesize[0]+x])));
+ for(int y=0;y<cpu->height/2;++y)for(int x=0;x<cpu->width/2;++x)for(int c=0;c<2;++c)maxError=std::max(maxError,std::abs(int(cpu->data[c+1][y*cpu->linesize[c+1]+x])-int(downloaded->data[1][y*downloaded->linesize[1]+2*x+c])));
+ av_frame_free(&downloaded);check(maxError<=2);
+ check(software.ready_.front().packet.pts.to100ns()==hardware.ready_.front().packet.pts.to100ns());
+ check(software.info_.color.matrix==hardware.info_.color.matrix&&software.info_.color.range==hardware.info_.color.range&&software.info_.color.transfer==hardware.info_.color.transfer);
+ std::cout<<"SOFT_HARD_YUV_COMPARE_PASS codec="<<int(codec)<<" max_error="<<maxError<<" diagnostic_readback_only=1\n";
+}
+static void fallback(const char* prefix){
+ auto data=bytes((std::string(prefix)+"-config.bin").c_str());const auto au=bytes((std::string(prefix)+"-au.bin").c_str());data.insert(data.end(),au.begin(),au.end());
+ for(bool automatic:{true,false}){
+ RemotePlaySource s;testHardware=true;setup(s);s.decodeMode_=automatic?RemotePlayConnectDesc::DecodeMode::Automatic:RemotePlayConnectDesc::DecodeMode::Hardware;
+ check(s.openDecoder(Codec::H264,1280,720));
+ // Force FFmpeg format negotiation to fail, without changing runtime
+ // binaries or adding a product-only fake hardware-success path.
+ s.codecContext_->get_format=[](AVCodecContext*,const AVPixelFormat*){return AV_PIX_FMT_NONE;};
+ VideoSample config;config.generation=s.token_->generation();config.width=1280;config.height=720;config.codec=Codec::H264;config.arrival100ns=monotonic100ns();config.kind=SampleKind::CodecConfig;config.payload=PaddedBytes::copy(bytes((std::string(prefix)+"-config.bin").c_str()));check(s.token_->video(std::move(config)));
+ VideoSample sample;sample.generation=s.token_->generation();sample.width=1280;sample.height=720;sample.codec=Codec::H264;sample.arrival100ns=monotonic100ns();sample.wireFrameIndex=1;sample.payload=PaddedBytes::copy(au);
+ check(s.token_->video(std::move(sample)));pipeline::FramePacket packet;const AVFrame* frame=nullptr;
+ const auto result=s.read(packet,&frame);
+ if(automatic){
+ check(result==SourceReadStatus::Waiting&&s.hardwareFallback_&&!s.codecContext_);
+ check(s.openDecoder(Codec::H264,1280,720)&&!s.codecContext_->hw_device_ctx);
+ packet.pts={1,60};check(s.submitPacket(data,2,packet)&&s.ready_.size()==1&&!s.info_.hardwareDecodeActive);
+ }else check(result==SourceReadStatus::Error);
+ std::cout<<"HARDWARE_FAILURE_POLICY_PASS automatic="<<automatic<<"\n";
+ }
+}
};
}
int main(int argc,char**argv) {
- if(argc!=3&&argc!=4)return 2;
- std::cout<<"SOURCE_TEST: real FFmpeg, direct inbox injection; NO PS5/WASAPI/GPU validation\n";
- try{RemotePlaySourceTestAccess::pcm();RemotePlaySourceTestAccess::splitTest(argv[1]);RemotePlaySourceTestAccess::reorder(argv[2]);if(argc==4)RemotePlaySourceTestAccess::splitTest(argv[3],Codec::H265);}
+ if(argc!=3&&argc!=4&&argc!=5)return 2;
+ testHardware=argc==5&&std::string_view(argv[4])=="--hardware";
+ std::cout<<"SOURCE_TEST: real FFmpeg, direct inbox injection; no PS5/WASAPI/presentation validation; hardware="<<testHardware<<"\n";
+ try{RemotePlaySourceTestAccess::pcm();RemotePlaySourceTestAccess::splitTest(argv[1]);RemotePlaySourceTestAccess::reorder(argv[2]);if(argc>=4)RemotePlaySourceTestAccess::splitTest(argv[3],Codec::H265);if(testHardware){RemotePlaySourceTestAccess::compareDecode(argv[1],Codec::H264);RemotePlaySourceTestAccess::compareDecode(argv[3],Codec::H265);RemotePlaySourceTestAccess::fallback(argv[1]);}}
catch(const std::exception& e){std::cerr<<e.what()<<"\n";return 2;}
std::cout<<"REMOTEPLAY_SOURCE_REGRESSIONS_PASS\n"; return 0;
}
diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cpp
index f73ad8dc..42a4f66c 100644
--- a/tests/unit/LiveGpuSchedulerTests.cpp
+++ b/tests/unit/LiveGpuSchedulerTests.cpp
@@ -1,5 +1,6 @@
#include "veyra/engine/LiveGpuScheduler.h"
#include "veyra/engine/TimingWindow.h"
+#include "veyra/engine/FgRecoveryBudget.h"
#include <iostream>
#include <memory>
#include <atomic>
@@ -36,5 +37,18 @@ int main(){
check(scheduler.failed()&&failedFinished==2&&scheduler.occupancy()==0,"failure propagates and finalizes queued work");
check(!scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[]{}),"failed scheduler rejects new work");
veyra::engine::TimingWindow timing;for(unsigned i=0;i<100;++i)timing.add(i);check(timing.p95()==94,"percentile order statistic");timing.clear();timing.add(6);check(timing.p95()==6,"reset removes old timing window");
+ veyra::engine::FgRecoveryBudget budget;
+ budget.fgCost(3,10000000);budget.complete(31,true,false,10000000);
+ check(budget.predicted(10000000)&&std::abs(*budget.predicted(10000000)-31)<.001,"base and FG cost do not double count additional generation");
+ check(!budget.admit(10000000,10100000,0,0),"insufficient pair deadline enters limited state");
+ check(!budget.admit(10100000,10600000,0,0),"recovery does not oscillate every input frame");
+ check(budget.admit(12600000,13100000,0,0)&&budget.recovering(),"bounded recovery admits first warmup opportunity");
+ check(budget.admit(12900000,13400000,0,0)&&!budget.recovering(),"second consecutive opportunity exits recovery and can produce a frame");
+ budget.complete(200,true,true,13000000);
+ check(*budget.predicted(13000000)<32,"expensive reset warmup does not poison steady cost");
+ budget.complete(10,false,false,24000000);
+ 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");
return failures?1:0;
}
diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cpp
index b3c3fea4..20edd50e 100644
--- a/tests/unit/RepairContractTests.cpp
+++ b/tests/unit/RepairContractTests.cpp
@@ -102,6 +102,7 @@ int main(){
rates.ready(60,true,3,0,7000000);
const auto counted=rates.snapshot(10000000);
check(counted.sourceCompletedFps==60&&counted.outputCompletedFps==100&&counted.validGeneratedFps==40&&counted.presentSubmitFps==90,"real60 plus valid40 yields output100 but present90; duplicate completion ignored");
+ check(counted.realPresentFps==60&&counted.generatedPresentFps==30,"source and generated presentation counts are independently measured");
check(counted.counters.realReady==60&&counted.counters.fgReadyValid==40,"GPU-ready counts are independent of requested multiplier");
rates.xessSubmitted(2,1,10000000);rates.xessSubmitted(1,0,10000000);
check(rates.snapshot(10000000).xessSdkSubmitFps==3&&rates.snapshot(10000000).outputCompletedFps==100,"XeSS SDK submissions never enter measured GPU completions");