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): recover stalled streams with bounded reconnects
Veyra Goal Agent5c3fad097c07
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 0ca811b0..8146468e 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -342,7 +342,7 @@ case Settings:if(uiState.mode==veyra::ui::Mode::Daily)switchMode();selectInspect#ifdef VEYRA_ENABLE_REMOTEPLAYcase RemotePlay:veyra::ui::showRemotePlayPanel(hwnd,[](veyra::source::RemotePlayConnectDesc desc){cancelProtection();remoteViewOnly=desc.request.viewOnly;if(!desc.request.viewOnly){if(!remoteController.start())veyra::log::warn("remoteplay-input","SDL gamepad initialization failed");startShellTimer(mainWindow,ControllerTimer,8);}else{KillTimer(mainWindow,ControllerTimer);remoteController.stop();}currentFile=L"remoteplay:";subtitles.clear();paused=false;engine.previewView({});engine.openRemotePlay(video,std::move(desc),options());SetWindowTextW(mainWindow,L"Veyra — PS5 Remote Play");layout();},[](std::string pin){engine.remotePlayLoginPin(std::move(pin));},[]{auto s=engine.snapshot();veyra::ui::RemotePlayPanelStatus result;result.active=s.remotePlay&&(s.running||s.transport==veyra::engine::TransportState::Opening||s.transport==veyra::engine::TransportState::Stopping);- result.message=s.failed?s.status:s.remotePlay&&s.running?L"PS5 画面已进入播放;关闭此面板不停止串流。":result.active?s.status:L"PS5 串流已停止,可以重新连接。";+ result.message=s.failed?s.status:s.remoteRecovering?s.remoteRecoveryMessage:s.remotePlay&&s.running?L"PS5 画面已进入播放;关闭此面板不停止串流。":result.active?s.status:L"PS5 串流已停止,可以重新连接。";if(s.remotePlay&&s.running){const auto c=remoteController.capabilities();if(remoteViewOnly)result.message+=L"\n仅观看:电脑输入已关闭,手柄由 PS5 处理。";diff --git a/apps/veyra/ui/LiveStatusDashboard.h b/apps/veyra/ui/LiveStatusDashboard.hindex b5592a76..0ac0a8d4 100644--- a/apps/veyra/ui/LiveStatusDashboard.h+++ b/apps/veyra/ui/LiveStatusDashboard.h@@ -65,6 +65,7 @@ inline void paintDashboard(HWND h,HDC dc,int w,int height,const engine::PlayerSntext(std::format(L"{} 帧{}",active?f.pendingOutputFrames:0,xess?L" *":L""),20,bottom+27,bw-20,23,17,textColor);std::wstring status=L"待机";COLORREF color=RGB(145,151,149);if(s.failed){status=L"错误";color=RGB(245,86,86);}+ else if(s.remoteRecovering){status=L"恢复中";color=RGB(242,185,65);}else if(active&&!s.applying&&f.rateWindowReady){status=history.overloaded?L"过载":L"正常";color=history.overloaded?RGB(242,185,65):RGB(111,211,127);}else if(s.applying&&s.running)status=L"调整中";else if(active)status=L"采样中";else if(s.transport==engine::TransportState::Paused)status=L"已暂停";text(L"当前状态",26+bw,bottom+6,bw-20,18,10,secondary);diff --git a/docs/PS5_STREAM_RECOVERY_2026-09-13.md b/docs/PS5_STREAM_RECOVERY_2026-09-13.mdnew file mode 100644index 00000000..301a6e99--- /dev/null+++ b/docs/PS5_STREAM_RECOVERY_2026-09-13.md@@ -0,0 +1,42 @@+# PS5 断流恢复施工记录++## 任务与基线++用户游玩中画面停住,接收和解码均为 0,要求修复。基线 `b5cb1b5`,施工分支 `codex/ps5-stream-recovery`。不发布、不更换运行 DLL、不修改配对文件。++## 已确认事实++现场日志副本 `logs/ps5-stall-20260913-before.log`(本地忽略,不提交):2026-09-12 19:42:05 UTC(本地 9 月 13 日 03:42:05)之后完整视频输入与解码计数都停在 7053,队列为 0,decodeBusy 为 -1。此前 NR 约 6.23 ms、SR 约 2.12 ms、FG 约 2.65 ms,未见 GPU 超时。旧逻辑请求关键帧三次未恢复,30 秒后报错;手动重连后恢复。++这是解码前没有新的完整视频输入,不足以判断是网络收包、Chiaki 组帧还是适配器拒绝。部分音频回调继续到达,不能称为整条连接完全断开。现有解码错误计数为零也不等于底层无错误。++## 修复设计及代码++- `StreamRecovery.h`:有画面后断流 1 秒、3 秒请求关键帧,6 秒仍未恢复则重建串流会话。初次连接未出画面仍保留 30 秒等待;登录 PIN 保留 120 秒等待。最多自动重连 3 次,等待间隔 1、2、4 秒;偶发恢复一帧不会刷新次数预算。+- `RemotePlaySessionSource`:同一个 owner 重用 source,先停止监测、PCM feeder、WASAPI,再 stop/join/fini Chiaki 和解码器,旧会话退出后才创建新会话。主动断开可取消退避。凭据只保留在本次连接请求的内存中,销毁时清零,不重新配对或写盘。+- 重连后的应用帧序号连续,源 epoch 分开,首帧携带 Discontinuity;即使首帧被 latest mailbox 覆盖,重置标记也传递至下一帧。继续共享 EngineController/EnhanceGraph/Presenter;不另建播放循环。+- `ChiakiBackend` 新增固定字段日志:完整回调数、拒绝数、底层包统计窗口、上游警告/错误分类及终止码。底层包窗口可能被上游重置,不能当累计 UDP 或相邻窗口差速率。原始上游字符串/密钥不输出。+- 已知主机关闭、明确终止或认证拒绝不自动重连。可重试的上游终止码限 CTRL_UNKNOWN、CTRL_CONNECT_FAILED、STREAM_CONNECTION_UNKNOWN、SESSION_REQUEST_RP_IN_USE,无终止码的无画面超时也可重试。RP_IN_USE 是实测旧会话退出后主机尚未释放时出现的状态,只能消耗原有 3 次预算;初次连接从未收到画面时不自动重试,不强制抢占其他会话。+- UI 面板与状态卡显示“恢复中”,最终失败显示串流原因,不再通用显示为采集卡断开。++## 验证状态++构建与离线:`cmd /c out/remoteplay/build-extra-delay.cmd` 构建主程序、实际播放测试和现有产品测试成功。MSVC 有既存 FFmpeg 头文件 C4244 警告。`cmd /c out/remoteplay/build-clock-tests.cmd` 最终核心 73/73(`logs/ps5-stream-core-result.log`)。`cmd /c out/remoteplay/build-boundary-clock.cmd` 后执行 `veyra_remoteplay_boundary_tests.exe` 通过,包含重连序号连续及首帧重置标记跨 mailbox 覆盖;`veyra_repair_contract_tests.exe` 103 checks / 0 failures。++新增实机测试选项:`out/remoteplay/product-repair/veyra_live_presentation_tests.exe --last-paired-ps5 <日志目录> --reconnect`,显式环境变量在第 600 个解码帧停止测试自己持有的传输,不发送 PS5 关机命令。验证断流前实际播放、恢复后 NR/SR/DLSS 补帧和音频持续推进。`--cancel-reconnect` 在第 120 个解码帧注入,验证重连退避阶段主动停止。此注入是可控断流,不能冒充已复现最初网络故障。++### 实机结果与失败记录++均在 RTX 5070、PS5 H.264 1080p60 硬解、80 Mbps 请求、视频 SR 到 4K、实时 NR、DLSS 2X 下运行;每轮不超过 50 秒加停止等待,单次低于 300 秒。测试使用静音 WASAPI 实际输出,不代表主观听感或手柄已验收。++1. `logs/ps5-stream-reconnect-result.log` / `logs/ps5-stream-reconnect/engine.log`:自动重连一次、FG 与音频恢复。但初版在第 120 解码帧、增强初始化尚未完成时就断流,且最后一秒 FG 从 60 降到 5 导致单点性能断言失败。这轮不算整体通过。后续改为第 600 帧,并检查断流前已呈现和生成、恢复后至少 300 新帧/100 生成帧及至少 250 次健康采样,不修改产品性能准入逻辑。+2. `logs/ps5-stream-reconnect2-result.log` / `logs/ps5-stream-reconnect2/engine.log`:初始播放成功,重连被 PS5 返回 quitReason=4 / error=2004(RP_IN_USE),旧策略直接失败。由此增加有上限的占用状态重试,保留失败日志。+3. `logs/ps5-stream-reconnect3-result.log` / `logs/ps5-stream-reconnect3/engine.log`:PASS。断流前已有画面和补帧;第一次重连主机占用,第二次恢复;730 次恢复后健康采样,退出 idle=1。45 秒采样呈现提交 110 fps、生成累计 1000,音频补偿 103.945 ms。NR Feature18 Create=0x1、DLSSG Create 3840×2160=0x1,SEH=0;关闭时 DLSSG evaluates=1276,Release=0x1。不是固定 120 fps 或屏幕 scanout 测量。++4. `logs/ps5-stream-cancel-result.log` / `logs/ps5-stream-cancel/engine.log`:`--cancel-reconnect` PASS。恢复阶段主动 Stop,manualCancel=1、idle=1,额外观察 2 秒未再次启动会话;该测试只验证取消,不声称恢复输出成功。++`git diff --check` 通过。只提交源码、测试和文档,无 SDK/DLL/配对/日志进入 Git;没有推送或发布。产品 EXE 为 `out/remoteplay/product-repair/veyra.exe`,原桌面 PS5 测试版快捷方式路径不变。下一步由用户重新打开测试版长时游玩;若再次自然断流,保留新 `remoteplay-transport` 与 `remoteplay-recovery` 日志继续定位最初原因。++## 边界++不保证断流期间声音画面连续,也不掩盖新会话的时间轴断点。若底层 decode/驱动调用或 join 本身永久阻塞,本次 owner 上的恢复不能安全强杀线程;不得 detach 后释放回调资源。最初自然断流根因仍待新日志区分。未验证小时级网络波动、休眠/恢复和断线时的真实手柄触觉状态。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 36704c8e..b6009da4 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1764,3 +1764,11 @@ apps/veyra/SettingsWindow.cpp调整布局;apps/veyra/ui/AppShell.cpp新增音基线 c68b4b0,分支 codex/ps5-fg-overload-audio。日志证实 DLSS 候选大量被截止时间判定跳过、实际串流约 59.9314 fps 而视频时钟固定除以60、decoded mailbox 覆盖误标 Discontinuity 导致统计窗口不断重开。修正本地估计时钟渐进校准、音频 ingress 映射有限老化、Drop 分类与同配置软历史重置的异步计时保留;PS5 每对新解码输入在增强前确定补帧预算,不用增强完成延后截止时间。UI 不再把已开启但等待执行的 FG 写成未开启。构建 cmd /c out/remoteplay/build-clock-product.cmd 成功;离线核心68/68,合同103/103,调度与RemotePlay边界通过。真实WASAPI基础回归及120秒慢钟差通过,P95音画偏差4.254ms、仅启动reset1次、无溢出。前三轮实机回归失败均保留:逐步定位覆盖事件分类、压缩AU锚点和硬解交付抖动。第四轮120秒PS5 H264硬解+4K视频SR+实时NR+DLSS2X通过;115秒有效生成累计5251,末期有效补帧53fps,过载163/163保留计时,音频等待早期64.587/末期57.892ms。NR/DLSSG Create与预热Evaluate=0x1,SEH=0。不能宣称固定120fps或小时级验收。证据 logs/ps5-clock-live4-result.log、logs/ps5-clock-live4/engine.log、logs/ps5-clock-audio-drift.log;其余命令、失败边界和修改文件见 docs/PS5_FG_CLOCK_METRICS_REPAIR_2026-09-13.md。运行中的旧EXE重命名保留,最新主程序已构建到原快捷方式路径,用户重开才生效。未改运行DLL,未提交SDK/二进制/凭据/日志,未推送发布。下一步由用户长时游戏体验验收。++## 2026-09-13 PS5 断流自动恢复++基线 b5cb1b5,分支 codex/ps5-stream-recovery。现场日志完整输入/解码停在 7053,队列0、decoder非忙碌,旧三次IDR及30秒等待未恢复。新增1秒/3秒关键帧恢复、6秒后旧会话顺序退出并复用本次内存凭据重连,最多3次且1/2/4秒退避;主动断开可取消。重连首帧重置历史和音频时钟、应用序号连续;界面显示恢复中。增加底层包窗口、回调拒绝、组帧/传输分类与终止码日志,不输出上游原始字符串/密钥。++构建 cmd /c out/remoteplay/build-extra-delay.cmd 成功;cmd /c out/remoteplay/build-clock-tests.cmd 核心73/73;cmd /c out/remoteplay/build-boundary-clock.cmd 后边界通过,合同103/103。实机使用 veyra_live_presentation_tests.exe --last-paired-ps5 <目录> --reconnect:第一轮恢复成功但单点FG性能断言失败;第二轮暴露PS5旧会话短暂RP_IN_USE导致放弃,修成已有恢复预算内继续退避。第三轮50秒PASS:断流前已播放、第二次重连成功、730次恢复后健康采样,NR/SR4K/DLSS2X及WASAPI音频恢复。NR与DLSSG Create=0x1/SEH=0,DLSSG evaluates=1276/Release=0x1。另 --cancel-reconnect PASS,主动停止后idle且不重连。证据 logs/ps5-stream-reconnect3-result.log、对应engine.log及logs/ps5-stream-cancel-result.log;详细失败、命令及修改文件见 docs/PS5_STREAM_RECOVERY_2026-09-13.md。++这是可控断流与自动恢复验证,不是最初自然断流根因已查明,也不等于长时PS5/HDR/手柄触觉验收。没有更换运行DLL、没有提交SDK/配对/日志、未推送发布。下一步用户重开桌面PS5测试版长时游玩,如再断流带新诊断定位上游原因。diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 3b73d389..d986aa99 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -55,6 +55,7 @@ struct PlayerSnapshot {bool fgBudgetLimited=false,xessGenerationSuppressed=false;bool running=false,failed=false,image=false,capture=false,remotePlay=false;int remotePlayState=0; uint64_t remotePlaySkipped=0;+ bool remoteRecovering=false;unsigned remoteReconnectAttempts=0;std::wstring remoteRecoveryMessage;remoteplay::SessionInbox::Snapshot remoteStream;double remoteReceivedFps=0,remoteDecodedFps=0;bool remoteRatesReady=false;uint64_t remoteReceived=0,remoteDecoded=0,remoteIngressDropped=0;};diff --git a/include/veyra/remoteplay/ChiakiBackend.h b/include/veyra/remoteplay/ChiakiBackend.hindex 5a3c51ac..ed50479c 100644--- a/include/veyra/remoteplay/ChiakiBackend.h+++ b/include/veyra/remoteplay/ChiakiBackend.h@@ -38,6 +38,9 @@ struct NativeSnapshot {bool started=false,connected=false;std::uint64_t warnings=0,errors=0,videoCallbacks=0,audioCallbacks=0;int lastQuitReason=0,lastApiError=0;+ uint64_t callbackRejected=0,packetReceived=0,packetLost=0;+ uint64_t transportErrors=0,assemblyErrors=0;+ bool automaticRetryAllowed=true;};BackendResult initializeChiaki();class ChiakiBackend {diff --git a/include/veyra/remoteplay/StreamRecovery.h b/include/veyra/remoteplay/StreamRecovery.hnew file mode 100644index 00000000..7f98408d--- /dev/null+++ b/include/veyra/remoteplay/StreamRecovery.h@@ -0,0 +1,27 @@+#pragma once+#include <cstdint>+namespace veyra::remoteplay {+// Local monotonic milliseconds. Bounded for the entire user-started session;+// one recovered frame does not replenish reconnects and create a retry loop.+class StreamRecovery {+public:+ enum class Action {Wait,Keyframe,Reconnect,Fail};+ void beginAttempt(int64_t now){lastProgress_=now;keyframes_=0;currentVideo_=false;}+ void frame(int64_t now){lastProgress_=now;keyframes_=0;everVideo_=currentVideo_=true;}+ Action poll(int64_t now,bool loginPin,bool failed,bool retryAllowed=true){+ const auto silent=now-lastProgress_;+ if(loginPin)return silent>=120000?Action::Fail:Action::Wait;+ if(failed&&!retryAllowed)return Action::Fail;+ if(failed||silent>=(everVideo_?6000:30000)){+ if(!everVideo_||reconnects_>=3)return Action::Fail;+ ++reconnects_;return Action::Reconnect;+ }+ if(currentVideo_&&keyframes_<2&&silent>=1000+int64_t(keyframes_)*2000){++keyframes_;return Action::Keyframe;}+ return Action::Wait;+ }+ unsigned reconnects()const{return reconnects_;}+private:+ int64_t lastProgress_=0;unsigned keyframes_=0,reconnects_=0;+ bool everVideo_=false,currentVideo_=false;+};+}diff --git a/include/veyra/source/RemotePlaySessionSource.h b/include/veyra/source/RemotePlaySessionSource.hindex 801b8987..301d4d83 100644--- a/include/veyra/source/RemotePlaySessionSource.h+++ b/include/veyra/source/RemotePlaySessionSource.h@@ -25,6 +25,8 @@ public:uint64_t skipped() const;struct Rates {uint64_t received=0,decoded=0,ingressDropped=0;double receivedFps=0,decodedFps=0;bool ready=false;};Rates rates() const;+ struct RecoveryStatus {bool active=false;unsigned attempts=0;std::wstring message;};+ RecoveryStatus recoveryStatus()const {std::lock_guard lock(mutex_);return recovery_;}sink::CaptureAudioState audioState() const { return audio_.snapshot(); }void setAudioGain(float value) { audio_.setGain(value); }void setAudioSync(unsigned mode, int offset) { audio_.setSync(mode, offset); }@@ -51,6 +53,8 @@ private:std::string pin_;uint64_t skipped_=0;Rates rates_;+ RecoveryStatus recovery_;+ uint64_t publishedSequence_=0;remoteplay::ControllerFeedback feedback_;sink::CaptureAudioSession audio_;};diff --git a/include/veyra/source/RemotePlaySource.h b/include/veyra/source/RemotePlaySource.hindex 74d51249..6557f24d 100644--- a/include/veyra/source/RemotePlaySource.h+++ b/include/veyra/source/RemotePlaySource.h@@ -47,6 +47,8 @@ public:remoteplay::BackendResult submitController(const remoteplay::ControllerState& state) { return backend_.submitController(state); }remoteplay::BackendResult submitLoginPin(std::string_view pin) { return backend_.submitLoginPin(pin); }remoteplay::ControllerFeedback takeFeedback(){return backend_.takeFeedback();}+ remoteplay::NativeSnapshot nativeSnapshot()const{return backend_.snapshot();} // session owner only+ remoteplay::BackendResult disconnectTransportForTest(){return backend_.stop();}bool connected() const noexcept { return connected_; }remoteplay::SessionInbox::Snapshot sessionSnapshot() const;std::shared_ptr<const remoteplay::SessionInbox> telemetryInbox()const{return inbox_;}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 3f31658f..15cdeda6 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -100,6 +100,7 @@ PlayerSnapshot EngineController::snapshot()const{#ifdef VEYRA_ENABLE_REMOTEPLAYif(copy.remotePlay&&activeRemote_){const auto s=activeRemote_->sessionSnapshot();copy.remoteStream=s;copy.remotePlayState=int(s.state);+ const auto recovery=activeRemote_->recoveryStatus();copy.remoteRecovering=recovery.active;copy.remoteReconnectAttempts=recovery.attempts;copy.remoteRecoveryMessage=recovery.message;copy.remoteReceivedFps=s.receivedFps;copy.remoteDecodedFps=s.decodedFps;copy.remoteRatesReady=s.ratesReady;copy.remoteReceived=s.video.accessUnits;copy.remoteDecoded=s.decodedFrames;copy.remoteIngressDropped=s.video.dropped;copy.remotePlaySkipped=activeRemote_->skipped();copy.captureAudio=activeRemote_->audioState();copy.audioAvailable=copy.captureAudio.available;@@ -509,7 +510,11 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sif(paused_)continue;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()){status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}+ if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if(remote){const auto recovery=remote->recoveryStatus();status(recovery.message.empty()?L"PS5 串流异常,请检查主机状态后重新连接。":recovery.message,true);break;}+#endif+ status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}}if(isRemote&&frame&&(uint32_t(frame->width)!=width||uint32_t(frame->height)!=height)){drainLivePresentation();if(!ring.drainQueue()){status(L"串流尺寸切换排空失败",true);break;}diff --git a/src/remoteplay/ChiakiBackend.cpp b/src/remoteplay/ChiakiBackend.cppindex cd40a699..7acf6302 100644--- a/src/remoteplay/ChiakiBackend.cpp+++ b/src/remoteplay/ChiakiBackend.cpp@@ -57,6 +57,7 @@ struct ChiakiBackend::Impl {std::atomic<bool> active=false,started=false,connected=false;std::atomic<std::uint64_t> warnings=0,errors=0,videoCallbacks=0,audioCallbacks=0;std::atomic<int> quitReason=0,apiError=0;+ std::atomic<uint64_t> callbackRejected=0,transportErrors=0,assemblyErrors=0;// Only the upstream audio/Opus callback thread reads/writes these fields.std::uint32_t channels=0,rate=0;std::uint64_t sampleIndex=0;@@ -65,11 +66,17 @@ struct ChiakiBackend::Impl {uint64_t lastMotion=0;std::mutex feedbackMutex;ControllerFeedback feedback;- static void logCallback(ChiakiLogLevel level,const char*,void* user) noexcept {+ static void logCallback(ChiakiLogLevel level,const char* message,void* user) noexcept {auto& self=*static_cast<Impl*>(user);// Raw upstream log strings/hexdumps may contain keys. Do not forward them.if(level==CHIAKI_LOG_ERROR)++self.errors;if(level==CHIAKI_LOG_WARNING)++self.warnings;+ // Classify in memory; no upstream strings or hexdumps leave this callback.+ if(message&&(level==CHIAKI_LOG_ERROR||level==CHIAKI_LOG_WARNING)){+ const std::string_view text=message;+ if(text.find("Takion")!=text.npos||text.find("timeout")!=text.npos)++self.transportErrors;+ if(text.find("Video")!=text.npos||text.find("video")!=text.npos||text.find("frame")!=text.npos||text.find("FEC")!=text.npos)++self.assemblyErrors;+ }}static void eventCallback(ChiakiEvent* event,void* user) noexcept {auto& self=*static_cast<Impl*>(user);@@ -102,18 +109,18 @@ struct ChiakiBackend::Impl {if(!self.active.load()||!data||!size||!info)return false;try{const auto nal=inspectAnnexB({data,size},self.profile.codec);- if(!nal.valid || (!nal.hasConfig&&!nal.hasPicture))return false;+ if(!nal.valid || (!nal.hasConfig&&!nal.hasPicture)){++self.callbackRejected;return false;}VideoSample sample;sample.generation=self.token.generation();sample.arrival100ns=monotonic100ns();sample.codec=self.profile.codec;sample.kind=info->kind==CHIAKI_VEYRA_SAMPLE_FRAME?SampleKind::AccessUnit:SampleKind::CodecConfig;if((sample.kind==SampleKind::AccessUnit && !nal.hasPicture) ||- (sample.kind==SampleKind::CodecConfig && (!nal.hasConfig || nal.hasPicture)))return false;+ (sample.kind==SampleKind::CodecConfig && (!nal.hasConfig || nal.hasPicture))){++self.callbackRejected;return false;}if(info->frame_index_valid)sample.wireFrameIndex=info->frame_index;sample.width=info->width;sample.height=info->height;sample.framesLost=info->frames_lost;sample.referenceRecovered=info->reference_recovered;sample.payload=PaddedBytes::copy({data,size});++self.videoCallbacks;- return self.token.video(std::move(sample));+ const bool accepted=self.token.video(std::move(sample));if(!accepted)++self.callbackRejected;return accepted;}catch(...){self.apiError=-1001;self.token.failed(-1001);return false;}}static void opusSettings(std::uint32_t channels,std::uint32_t rate,void* user) noexcept {@@ -255,7 +262,15 @@ NativeSnapshot ChiakiBackend::snapshot()const{// Like start/stop, pointer ownership requires the owner; the atomic counters// themselves may be updated by callbacks. Do not call concurrently with reset.if(!p_)return {};- const auto& s=*p_;- return {s.started.load(),s.connected.load(),s.warnings.load(),s.errors.load(),s.videoCallbacks.load(),s.audioCallbacks.load(),s.quitReason.load(),s.apiError.load()};+ auto& s=*p_;+ NativeSnapshot out{s.started.load(),s.connected.load(),s.warnings.load(),s.errors.load(),s.videoCallbacks.load(),s.audioCallbacks.load(),s.quitReason.load(),s.apiError.load()};+ out.callbackRejected=s.callbackRejected;out.transportErrors=s.transportErrors;out.assemblyErrors=s.assemblyErrors;+ // Upstream packet window may reset itself; do not label this cumulative UDP.+ if(s.initialized)chiaki_packet_stats_get(&s.session.stream_connection.packet_stats,false,&out.packetReceived,&out.packetLost);+ // After a stopped session the PS5 may briefly still report RP_IN_USE.+ // Retrying this request cannot evict it; the console remains authoritative.+ // StreamRecovery retries only after this user-started run had real video.+ out.automaticRetryAllowed=out.lastQuitReason==CHIAKI_QUIT_REASON_NONE||out.lastQuitReason==CHIAKI_QUIT_REASON_CTRL_UNKNOWN||out.lastQuitReason==CHIAKI_QUIT_REASON_CTRL_CONNECT_FAILED||out.lastQuitReason==CHIAKI_QUIT_REASON_STREAM_CONNECTION_UNKNOWN||out.lastQuitReason==CHIAKI_QUIT_REASON_SESSION_REQUEST_RP_IN_USE;+ return out;}} // namespace veyra::remoteplaydiff --git a/src/source/RemotePlaySessionSource.cpp b/src/source/RemotePlaySessionSource.cppindex 7d4d2b57..cef56c57 100644--- a/src/source/RemotePlaySessionSource.cpp+++ b/src/source/RemotePlaySessionSource.cpp@@ -1,5 +1,6 @@#include "veyra/source/RemotePlaySessionSource.h"#include "veyra/Log.h"+#include "veyra/remoteplay/StreamRecovery.h"#include <cmath>#include <format>extern "C" {@@ -8,7 +9,7 @@ extern "C" {namespace veyra::source {bool RemotePlaySessionSource::connect(RemotePlayConnectDesc desc) {close();- { std::lock_guard lock(mutex_); initialized_=started_=failed_=false; skipped_=0; rates_={}; feedback_={}; controller_={}; pendingControllers_.clear(); snapshot_={}; }+ { std::lock_guard lock(mutex_); initialized_=started_=failed_=false; skipped_=publishedSequence_=0; recovery_={}; rates_={}; feedback_={}; controller_={}; pendingControllers_.clear(); snapshot_={}; }owner_=std::jthread([this, request=std::move(desc)](std::stop_token stop) mutable { run(stop,std::move(request)); });std::unique_lock lock(mutex_);ready_.wait(lock,[&]{return initialized_;});@@ -17,12 +18,22 @@ bool RemotePlaySessionSource::connect(RemotePlayConnectDesc desc) {}void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc desc) {RemotePlaySource source;+ remoteplay::StreamRecovery recovery;+ const auto milliseconds=[] {return remoteplay::monotonic100ns()/10000;};+ // Keep the existing in-memory credentials only for this user-started run.+ // Their move-only destructor wipes them; never reread another saved profile.+ for(;;){+ recovery.beginAttempt(milliseconds());+ bool retry=false;+ uint64_t receivedBase=0,droppedBase=0;+ {std::lock_guard lock(mutex_);receivedBase=rates_.received;droppedBase=rates_.ingressDropped;}std::jthread feeder;std::jthread monitor;try {const bool ok=source.connect(desc);- desc.request.credentials=remoteplay::PairingCredentials{};- {std::lock_guard lock(mutex_);publishedInfo_=source.info();started_=ok;failed_=!ok;initialized_=true;telemetryInbox_=source.telemetryInbox();}+ if(!ok)retry=recovery.poll(milliseconds(),false,true)==remoteplay::StreamRecovery::Action::Reconnect;+ {std::lock_guard lock(mutex_);publishedInfo_=source.info();if(!initialized_)started_=ok;failed_=!ok&&!retry;initialized_=true;telemetryInbox_=source.telemetryInbox();+ if(failed_)recovery_.message=L"PS5 串流连接失败,请检查主机及网络;已保存的配对无需重输。";}ready_.notify_all();if(ok) {monitor=std::jthread([inbox=source.telemetryInbox()](std::stop_token cancel){@@ -55,9 +66,13 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc de} else log::error("remoteplay-audio","output initialization failed; video remains available");auto lastFrame=std::chrono::steady_clock::now();auto nextController=lastFrame;- auto rateStart=lastFrame;uint64_t previousReceived=0,previousDecoded=0;- unsigned recoveryAttempts=0;- auto nextRecovery=lastFrame+std::chrono::seconds(1);+ auto rateStart=lastFrame;uint64_t previousReceived=receivedBase,previousDecoded=0;+ {std::lock_guard lock(mutex_);previousDecoded=rates_.decoded;}+ auto nextNativeLog=lastFrame;+ remoteplay::NativeSnapshot native;+ bool firstFrame=true;+ wchar_t disconnectAfter[24]{};uint64_t testDisconnectFrames=0;bool testDisconnected=false;+ if(!recovery.reconnects()&&GetEnvironmentVariableW(L"VEYRA_TEST_REMOTEPLAY_DISCONNECT_AFTER_FRAMES",disconnectAfter,24))testDisconnectFrames=std::clamp<uint64_t>(_wtoi64(disconnectAfter),60,3600);while(!stop.stop_requested()) {std::string pin;{std::lock_guard lock(mutex_);pin.swap(pin_);}@@ -77,29 +92,38 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc deconst auto result=source.read(packet,&frame);auto feedback=source.takeFeedback();const auto snapshot=source.sessionSnapshot();+ if(now>=nextNativeLog||result==SourceReadStatus::Error){native=source.nativeSnapshot();nextNativeLog=now+std::chrono::seconds(1);+ log::info("remoteplay-transport",std::format("attempt={} connected={} videoCallbacks={} audioCallbacks={} callbackRejected={} packetWindowReceived={} packetWindowLost={} upstreamWarnings={} upstreamErrors={} transportErrors={} assemblyErrors={} quitReason={} apiError={} (upstream resetting packet window; not cumulative UDP)",recovery.reconnects(),native.connected,native.videoCallbacks,native.audioCallbacks,native.callbackRejected,native.packetReceived,native.packetLost,native.warnings,native.errors,native.transportErrors,native.assemblyErrors,native.lastQuitReason,native.lastApiError));}{std::lock_guard lock(mutex_);snapshot_=snapshot;feedback_.merge(std::move(feedback));- rates_.received=snapshot.video.accessUnits;rates_.ingressDropped=snapshot.video.dropped;+ rates_.received=receivedBase+snapshot.video.accessUnits;rates_.ingressDropped=droppedBase+snapshot.video.dropped;const double elapsed=std::chrono::duration<double>(now-rateStart).count();if(elapsed>=1){rates_.receivedFps=double(rates_.received-previousReceived)/elapsed;rates_.decodedFps=double(rates_.decoded-previousDecoded)/elapsed;rates_.ready=true;previousReceived=rates_.received;previousDecoded=rates_.decoded;rateStart=now;}}- if(result==SourceReadStatus::Error) {std::lock_guard lock(mutex_);failed_=true;break;}if(result==SourceReadStatus::Frame && frame) {+ packet.sourceEpoch+=uint64_t(recovery.reconnects())<<32;+ if(firstFrame&&recovery.reconnects())packet.flags|=static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);+ if(firstFrame&&recovery.reconnects())log::info("remoteplay-recovery",std::format("reconnected attempt={} first decoded frame; reset video history and audio clock",recovery.reconnects()));+ firstFrame=false;publishDecoded(frame,packet,source.info());lastFrame=now;- recoveryAttempts=0;nextRecovery=now+std::chrono::seconds(1);- } else {- if(snapshot.state==remoteplay::SessionState::Streaming&&now>=nextRecovery&&recoveryAttempts<3){- ++recoveryAttempts;source.recoverVideo();nextRecovery=now+std::chrono::seconds(2);- log::warn("remoteplay-recovery",std::format("no decoded progress; request keyframe attempt={} received={} decoded={} lastReceiveAgeMs={:.1f}",recoveryAttempts,snapshot.video.accessUnits,snapshot.decodedFrames,snapshot.lastVideo100ns?double(remoteplay::monotonic100ns()-snapshot.lastVideo100ns)/10000:-1));+ recovery.frame(milliseconds());+ {std::lock_guard lock(mutex_);recovery_.active=false;recovery_.message.clear();}+ if(testDisconnectFrames&&!testDisconnected&&snapshot.decodedFrames>=testDisconnectFrames){+ testDisconnected=true;const auto r=source.disconnectTransportForTest();+ log::warn("remoteplay-recovery-test",std::format("injected owned transport stop ok={} code={} (no console power command)",r.ok,r.code));}- // A missing console or unrecoverable stream must not leave- // a perpetual opening spinner. Login PIN allows more time.- const auto deadline=snapshot.state==remoteplay::SessionState::LoginPinRequired?std::chrono::seconds(120):std::chrono::seconds(30);- if(now-lastFrame>deadline) {- log::error("remoteplay","no decoded frame before recovery deadline");- std::lock_guard lock(mutex_);failed_=true;break;+ } else {+ const auto action=recovery.poll(milliseconds(),snapshot.state==remoteplay::SessionState::LoginPinRequired,result==SourceReadStatus::Error,native.automaticRetryAllowed);+ if(action==remoteplay::StreamRecovery::Action::Keyframe){+ source.recoverVideo();log::warn("remoteplay-recovery",std::format("request keyframe; received={} decoded={} videoCallbacks={} rejected={} packetReceived={} packetLost={}",snapshot.video.accessUnits,snapshot.decodedFrames,native.videoCallbacks,native.callbackRejected,native.packetReceived,native.packetLost));+ std::lock_guard lock(mutex_);recovery_.active=true;recovery_.message=L"画面中断,正在请求关键帧恢复…";+ }else if(action==remoteplay::StreamRecovery::Action::Reconnect){retry=true;break;}+ else if(action==remoteplay::StreamRecovery::Action::Fail){+ log::error("remoteplay-recovery",std::format("recovery stopped attempts={} quitReason={} error={}",recovery.reconnects(),native.lastQuitReason,snapshot.errorCode));+ std::lock_guard lock(mutex_);failed_=true;recovery_.active=false;+ recovery_.message=snapshot.state==remoteplay::SessionState::LoginPinRequired?L"等待 PS5 登录 PIN 超时,请重新连接。":!native.automaticRetryAllowed?L"PS5 已结束或拒绝串流,请检查主机状态后重新连接。":L"PS5 串流未恢复,请检查主机及网络后点击连接;无需重新配对。";break;}std::this_thread::sleep_for(std::chrono::milliseconds(1));}@@ -107,18 +131,31 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc de}} catch(const std::exception& e) {log::error("remoteplay",e.what());- {std::lock_guard lock(mutex_);failed_=true;initialized_=true;}+ retry=false;+ {std::lock_guard lock(mutex_);failed_=true;initialized_=true;recovery_.message=L"PS5 串流处理异常,已停止自动恢复,请查看日志。";}ready_.notify_all();}+ if(retry&&!stop.stop_requested()){+ std::lock_guard lock(mutex_);recovery_={true,recovery.reconnects(),std::format(L"串流中断,正在重新连接({}/3)…",recovery.reconnects())};+ latest_.reset();pendingControllers_.clear();controller_={};feedback_={};+ }if(monitor.joinable()){monitor.request_stop();monitor.join();}if(feeder.joinable()){feeder.request_stop();feeder.join();}audio_.stop();source.close();+ if(!retry||stop.stop_requested())break;+ log::warn("remoteplay-recovery",std::format("old session joined; reconnect={} using existing in-memory pairing",recovery.reconnects()));+ // Interruptible 1/2/4 second backoff; manual Stop prevents the next start.+ for(unsigned i=0;i<(1u<<(recovery.reconnects()-1))*20&&!stop.stop_requested();++i)std::this_thread::sleep_for(std::chrono::milliseconds(50));+ if(stop.stop_requested())break;+ }+ {std::lock_guard lock(mutex_);recovery_.active=false;}}void RemotePlaySessionSource::publishDecoded(const AVFrame* frame,pipeline::FramePacket packet,const SourceInfo& info){auto* cloned=av_frame_clone(frame);if(!cloned)throw std::bad_alloc();Frame item{std::shared_ptr<AVFrame>(cloned,[](AVFrame* p){av_frame_free(&p);}),packet,info};std::lock_guard lock(mutex_);+ item.packet.sequence=++publishedSequence_;++rates_.decoded;if(latest_){++skipped_;item.packet.flags|=latest_->packet.flags;item.packet.flags|=static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Drop);}diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cppindex bd8c6cbd..706f415a 100644--- a/tests/integration/LivePresentationTests.cpp+++ b/tests/integration/LivePresentationTests.cpp@@ -17,7 +17,8 @@ int wmain(int argc,wchar_t**argv){#ifdef VEYRA_ENABLE_REMOTEPLAY// Explicit opt-in; uses existing local pairing without changing it. Runs// the actual shared engine, audio endpoint, GPU admission and presenter.- if(argc==3&&std::wstring_view(argv[1])==L"--last-paired-ps5"){+ if((argc==3||(argc==4&&(std::wstring_view(argv[3])==L"--reconnect"||std::wstring_view(argv[3])==L"--cancel-reconnect")))&&std::wstring_view(argv[1])==L"--last-paired-ps5"){+ const bool reconnect=argc==4,cancelReconnect=reconnect&&std::wstring_view(argv[3])==L"--cancel-reconnect";const auto dir=remoteplay::profileDirectory();wchar_t name[80]{};GetPrivateProfileStringW(L"RemotePlay",L"LastProfile",L"",name,80,(dir/L"settings.ini").c_str());const std::wstring profile=name;if(profile.empty()||profile.find_first_of(L"/\\:")!=profile.npos)return 3;@@ -28,23 +29,39 @@ int wmain(int argc,wchar_t**argv){engine::EngineController engine;engine.setVolume(0,true);engine::PlayerOptions options;options.nr=options.sr=options.fg=true;options.fgMultiplier=2;options.settings.videoSrQuality=2;source::RemotePlayConnectDesc request;request.request=std::move(*saved);request.request.video={1920,1080,60,80000,remoteplay::Codec::H264};request.decodeMode=source::RemotePlayConnectDesc::DecodeMode::Hardware;+ if(reconnect)SetEnvironmentVariableW(L"VEYRA_TEST_REMOTEPLAY_DISCONNECT_AFTER_FRAMES",cancelReconnect?L"120":L"600");engine.openRemotePlay(window,std::move(request),options);const auto start=std::chrono::steady_clock::now();unsigned overloadSamples=0,overloadTimings=0;double early=-1,late=-1;uint64_t maxGenerated=0;bool failed=false;int lastSecond=-1;- while(std::chrono::steady_clock::now()-start<120s){+ bool sawRecovery=false,resumed=false,cancelled=false,playedBefore=false;uint64_t recoveryFrames=0,recoveryGenerated=0;unsigned attempts=0,postHealthySamples=0;+ while(std::chrono::steady_clock::now()-start<(reconnect?50s:120s)){const int second=int(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now()-start).count());- SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",second>=30&&second<38?L"35":nullptr);+ SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",!reconnect&&second>=30&&second<38?L"35":nullptr);MSG msg;while(PeekMessageW(&msg,nullptr,0,0,PM_REMOVE)){TranslateMessage(&msg);DispatchMessageW(&msg);}const auto s=engine.snapshot();if(s.failed){failed=true;char message[1024]{};WideCharToMultiByte(CP_UTF8,0,s.status.c_str(),-1,message,sizeof(message),nullptr,nullptr);std::cout<<"ENGINE_FAILED "<<message<<std::endl;break;}maxGenerated=std::max(maxGenerated,s.generated);+ attempts=std::max(attempts,s.remoteReconnectAttempts);+ if(!sawRecovery&&s.frames>30&&s.generated>20)playedBefore=true;+ if(s.remoteRecovering){sawRecovery=true;recoveryFrames=s.frames;recoveryGenerated=s.generated;}+ if(sawRecovery&&!s.remoteRecovering&&attempts>=1&&attempts<=3&&s.frames>recoveryFrames+60&&s.metrics.flow.validGeneratedFps>10&&s.captureAudio.bufferedMs>0)resumed=true;+ if(resumed&&s.frames>recoveryFrames+300&&s.generated>recoveryGenerated+100&&s.nrActive&&s.srActive&&s.captureAudio.running&&s.captureAudio.error.empty())++postHealthySamples;+ if(cancelReconnect&&s.remoteRecovering&&attempts==1){cancelled=true;break;}if(second>=33&&second<38){++overloadSamples;overloadTimings+=s.metrics.flow.gpuTiming[size_t(diagnostics::GpuStage::Nr)].mean.has_value();}if(second==25)early=s.captureAudio.compensationMs;if(second>=110)late=s.captureAudio.compensationMs;- if(second!=lastSecond&&second%5==0){lastSecond=second;std::cout<<"PS5 t="<<second<<" presented="<<s.metrics.flow.presentSubmitFps<<" generated="<<s.generated<<" nrMs="<<s.metrics.flow.gpuTiming[size_t(diagnostics::GpuStage::Nr)].mean.value_or(-1)<<" audioDelay="<<s.captureAudio.compensationMs<<" pcm="<<s.captureAudio.bufferedMs<<" resets="<<s.captureAudio.resets<<std::endl;}+ if(second!=lastSecond&&second%5==0){lastSecond=second;std::cout<<"PS5 t="<<second<<" presented="<<s.metrics.flow.presentSubmitFps<<" generated="<<s.generated<<" nrMs="<<s.metrics.flow.gpuTiming[size_t(diagnostics::GpuStage::Nr)].mean.value_or(-1)<<" audioDelay="<<s.captureAudio.compensationMs<<" pcm="<<s.captureAudio.bufferedMs<<" resets="<<s.captureAudio.resets<<" recovering="<<s.remoteRecovering<<" attempts="<<attempts<<std::endl;}std::this_thread::sleep_for(20ms);}SetEnvironmentVariableW(L"VEYRA_TEST_VIDEO_WORK_MS",nullptr);+ SetEnvironmentVariableW(L"VEYRA_TEST_REMOTEPLAY_DISCONNECT_AFTER_FRAMES",nullptr);const auto final=engine.snapshot();engine.stop();const auto stopDeadline=std::chrono::steady_clock::now()+10s;while(!engine.idle()&&std::chrono::steady_clock::now()<stopDeadline)std::this_thread::sleep_for(10ms);+ if(reconnect){+ // Observe beyond the first retry backoff: Stop must not reopen the session.+ if(cancelReconnect)std::this_thread::sleep_for(2s);+ const bool ok=!failed&&engine.idle()&&sawRecovery&&attempts>=1&&attempts<=3&&(cancelReconnect?cancelled:playedBefore&&resumed&&postHealthySamples>=250&&final.captureAudio.compensationMs<150);+ std::cout<<(ok?"PASS ":"FAIL ")<<"PS5 owned transport interruption playedBefore="<<playedBefore<<" recovery="<<sawRecovery<<" attempts="<<attempts<<" resumedWithFgAndAudio="<<resumed<<" postHealthySamples="<<postHealthySamples<<" manualCancel="<<cancelled<<" idle="<<engine.idle()<<std::endl;+ DestroyWindow(window);CoUninitialize();return ok?0:1;+ }const bool ok=!failed&&engine.idle()&&maxGenerated>100&&final.metrics.flow.validGeneratedFps>10&&overloadSamples>0&&overloadTimings*100>=overloadSamples*95&&early>=0&&late>=0&&late<150&&std::abs(late-early)<40;std::cout<<(ok?"PASS ":"FAIL ")<<"PS5 actual NR/SR/DLSS 2X, overload timings="<<overloadTimings<<'/'<<overloadSamples<<" earlyAudio="<<early<<" lateAudio="<<late<<" finalValidFgFps="<<final.metrics.flow.validGeneratedFps<<std::endl;DestroyWindow(window);CoUninitialize();return ok?0:1;diff --git a/tests/remoteplay/CoreTests.cpp b/tests/remoteplay/CoreTests.cppindex 756e742c..b4f9bc57 100644--- a/tests/remoteplay/CoreTests.cpp+++ b/tests/remoteplay/CoreTests.cpp@@ -6,6 +6,7 @@#include "veyra/remoteplay/PacketPump.h"#include "veyra/remoteplay/InputGate.h"#include "veyra/remoteplay/SessionInbox.h"+#include "veyra/remoteplay/StreamRecovery.h"#include "veyra/engine/PresentationScheduler.h"#include "veyra/engine/FgRecoveryBudget.h"#include <atomic>@@ -131,6 +132,36 @@ TEST(inbox_failed_requires_backend_join){SessionInbox q;auto t=q.begin(monotonicTEST(input_and_mailbox_zero_generation){InputGate g;THROWS(g.begin(0));LatestMailbox<int> m;THROWS(m.begin(0));VideoIngress v;THROWS(v.begin(0));AudioIngress a;THROWS(a.begin(0));}TEST(inbox_real_sample_vs_config_counts){SessionInbox q;auto t=q.begin(monotonic100ns());auto now=monotonic100ns();CHECK(t.video(config(t.generation(),now)));CHECK(q.snapshot().video.accessUnits==0);CHECK(t.video(frame(0,true,monotonic100ns(),t.generation())));CHECK(q.snapshot().video.accessUnits==1);auto v=q.tryVideo(monotonic100ns());CHECK(v&&v->sample.generation==t.generation());}}+TEST(recovery_keyframes_before_reconnect){+ StreamRecovery r;using A=StreamRecovery::Action;r.beginAttempt(100);r.frame(200);+ CHECK(r.poll(1199,false,false)==A::Wait);CHECK(r.poll(1200,false,false)==A::Keyframe);+ CHECK(r.poll(3199,false,false)==A::Wait);CHECK(r.poll(3200,false,false)==A::Keyframe);+ CHECK(r.poll(6199,false,false)==A::Wait);CHECK(r.poll(6200,false,false)==A::Reconnect);CHECK(r.reconnects()==1);+}+TEST(recovery_initial_and_login_deadlines){+ StreamRecovery r;using A=StreamRecovery::Action;r.beginAttempt(100);+ CHECK(r.poll(30099,false,false)==A::Wait);CHECK(r.poll(30100,false,false)==A::Fail);CHECK(r.reconnects()==0);+ r.frame(50000);CHECK(r.poll(169999,true,true,false)==A::Wait);CHECK(r.poll(170000,true,true,false)==A::Fail);+ CHECK(r.reconnects()==0);+}+TEST(recovery_budget_survives_brief_recovery){+ StreamRecovery r;using A=StreamRecovery::Action;+ for(int i=0;i<3;++i){r.beginAttempt(i*10000);r.frame(i*10000+100);CHECK(r.poll(i*10000+6100,false,false)==A::Reconnect);CHECK(r.reconnects()==unsigned(i+1));}+ r.beginAttempt(30000);r.frame(30100);CHECK(r.poll(36100,false,false)==A::Fail);CHECK(r.reconnects()==3);+}+TEST(recovery_progress_and_terminal_quit){+ StreamRecovery r;using A=StreamRecovery::Action;r.beginAttempt(0);r.frame(100);+ CHECK(r.poll(1100,false,false)==A::Keyframe);r.frame(1500);CHECK(r.poll(2000,false,false)==A::Wait);+ CHECK(r.poll(2200,false,true,false)==A::Fail);CHECK(r.reconnects()==0);+ CHECK(r.poll(2200,false,true,true)==A::Reconnect);r.beginAttempt(5000);+ CHECK(r.poll(10999,false,false)==A::Wait);CHECK(r.poll(11000,false,false)==A::Reconnect);+}+TEST(recovery_retryable_busy_requires_prior_video){+ StreamRecovery r;using A=StreamRecovery::Action;r.beginAttempt(0);+ CHECK(r.poll(500,false,true,true)==A::Fail);CHECK(r.reconnects()==0);+ r.frame(1000);CHECK(r.poll(7000,false,false)==A::Reconnect);r.beginAttempt(8000);+ CHECK(r.poll(8500,false,true,true)==A::Reconnect);CHECK(r.reconnects()==2);+}int main(int argc,char**argv){std::string filter;if(argc==2&&std::string_view(argv[1])=="--list"){for(auto [name,f]:tests()){(void)f;std::cout<<name<<'\n';}return 0;}diff --git a/tests/remoteplay/ProductBoundaryTests.cpp b/tests/remoteplay/ProductBoundaryTests.cppindex e42e84ec..10ef6f8f 100644--- a/tests/remoteplay/ProductBoundaryTests.cpp+++ b/tests/remoteplay/ProductBoundaryTests.cpp@@ -39,6 +39,12 @@ static void mailbox(){if(s.read(out,&frame)!=SourceReadStatus::Frame||!frame||out.sequence!=2||s.skipped()!=1||!pipeline::breaksHistory(out.flags))throw std::runtime_error("latest decoded mailbox");if(!pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Drop)||pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Discontinuity))throw std::runtime_error("decoded overwrite must be a soft Drop, not a clock discontinuity");if(s.read(out,&frame)!=SourceReadStatus::Waiting)throw std::runtime_error("mailbox replay");+ raw=av_frame_alloc();raw->width=16;raw->height=16;raw->format=AV_PIX_FMT_YUV420P;+ if(av_frame_get_buffer(raw,32)<0)throw std::bad_alloc();+ packet.sequence=1;packet.sourceEpoch=uint64_t(1)<<32;+ packet.flags=static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);+ s.publishDecoded(raw,packet,info);packet.sequence=2;packet.flags=0;s.publishDecoded(raw,packet,info);av_frame_free(&raw);+ if(s.read(out,&frame)!=SourceReadStatus::Frame||out.sequence!=4||out.sourceEpoch!=(uint64_t(1)<<32)||!pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Discontinuity))throw std::runtime_error("reconnect keeps application sequence and pending clock reset across mailbox overwrite");}};}