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: run live GPU scheduling on one owner with nonblocking presentation steps
Veyra Goal Agentdb98af783690
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 2d9ce8ed..1015204d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -128,10 +128,10 @@ target_compile_definitions(veyra_runtime_probe PRIVATEUNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)target_link_libraries(veyra_runtime_probe PRIVATE veyra_gfx)+veyra_add_compute_shader(veyra_shader_parity_encode ParityEncode)+veyra_add_compute_shader(veyra_shader_parity_decode ParityDecode)if(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR)veyra_add_compute_shader(veyra_shader_test_pattern GenerateTestPattern)- veyra_add_compute_shader(veyra_shader_parity_encode ParityEncode)- veyra_add_compute_shader(veyra_shader_parity_decode ParityDecode)add_executable(veyra_nr_harnesstools/nr_harness/main.cpptools/nr_harness/frame_loop.cpp@@ -283,9 +283,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_definitions(veyra_scene_analyzer PRIVATEUNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)target_include_directories(veyra_scene_analyzer PRIVATE- ${CMAKE_CURRENT_SOURCE_DIR}/include ${FFMPEG_INCLUDE_DIRS})- target_link_directories(veyra_scene_analyzer PRIVATE ${FFMPEG_LIBRARY_DIRS})- target_link_libraries(veyra_scene_analyzer PRIVATE ${FFMPEG_LIBRARIES} veyra_base)+ ${CMAKE_CURRENT_SOURCE_DIR}/include)+ target_link_libraries(veyra_scene_analyzer PRIVATE veyra_media veyra_base)endif()# NVOF probe tool (phase5 gate expects veyra_nvof_probe.exe).@@ -446,7 +445,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_executable(veyra_image_dimension_tests tests/integration/ImageDimensionTests.cpp)add_executable(veyra_capture_color_probe tools/capture_color_probe/main.cpp)add_executable(veyra_capture_color_tests tests/unit/CaptureColorContractTests.cpp)- add_executable(veyra_presentation_worker_tests tests/unit/PresentationWorkerTests.cpp)+ add_executable(veyra_presentation_worker_tests tests/unit/LiveGpuSchedulerTests.cpp)target_compile_features(veyra_presentation_worker_tests PRIVATE cxx_std_20)target_include_directories(veyra_presentation_worker_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)add_executable(veyra_live_presentation_tests tests/integration/LivePresentationTests.cpp)diff --git a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.mdindex dea7d190..20aa86d4 100644--- a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md+++ b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md@@ -4,6 +4,24 @@## 2026-09-11 续接实证(优先于下面历史进度)+### 最新续接:单GPU所有者调度、断流与末帧++基线`e25585e`工作树干净;上一目标轮是有效进展(音频与逐帧GPU计时两个已验证本地提交)。本轮按原计划推进S3,没有开启旧Loop或发布。++- `LiveGpuScheduler`取代旧`PresentationWorker`线程。增强提交、完成检查、deadline和Present在现有引擎线程推进;任务返回Pending/Complete/Failed,未来播放时间只作为截止时间返回,不在任务内等待。最多两批包含当前租约。跨线程调用拒绝、失败/取消逐项finalize、先释放旧租约再接下一批。删除旧worker实现与旧线程测试,保留测试target名称以兼容现有命令。+- 移除EngineController的`gpuMutex/liveStatsMutex`。UI仍只提交设置/控制请求,采集回调仍只更新容量1 mailbox;`CaptureCardSource::tryRead`立即检查输入,原`read`保留30ms等待供其它调用者。主循环遇到Waiting或两批占满时继续推进完成、呈现和GPU时间戳,使用局部高精度timer等待,未加入正常像素回读/逐pass CPU fence等待。+- GPU-ready时长改用完成观测时刻,不能把前一批的呈现排队时间计入GPU-ready。EOF先完成剩余呈现再报Ended;失败不能被Ended覆盖,批处理中发现暂停/停止就取消剩余工作。状态统计仍区分完成与Present,不声称scanout。+- `continuation-single-owner-state`15项0.074秒PASS:同一owner、Pending立即返回、提交可推进、两批上限、lease释放、取消一次、错误传播和外部线程拒绝。最终`continuation-single-owner-cancel-live`30项8.723秒PASS,30/60、NR/2X/4X、设置/音频隔离、暂停/恢复/停止;source30fps对应Color30样本。最终live EXE SHA `6B0D1EDF5D3FF1750E1E06088D3A372149CE7C98B22489E01E49D7ADE4AA1BE1`。+- 输入空档与EOF:在仅测试回放模式下注入400ms Waiting,未读取新输入时12帧全部完成/呈现;恢复后处理完62帧。最终`continuation-single-owner-cancel-eof`6项3.325秒PASS,所有epoch累计真实提交/呈现均62。初版`continuation-single-owner-gap`用长素材等20秒没有到EOF,不能当产品EOF失败;`continuation-single-owner-short-eof`错误用当前epoch计数与整段总数比较(末尾epoch1帧、前epoch61帧),修正为累计closed窗口,失败日志保留。+- 短素材由`ffmpeg -hide_banner -loglevel error -i loop/local/fixed_clips/test_av_1080p.mp4 -t 1 -c copy logs/continuation-repair-20260910/owner-eof-1s.mp4`生成,SHA `9CF8AEE99AB10E1B476616A9677A329687E4E7D4AE235A18BF119AB5544EBE25`。流复制尾部含62帧,测试按实际输出,不假设恰60。原素材SHA `7952AD2904C8FED78402BC299EA2A04D1D869663EBCE17BBAC0C297F84FA2A91`。+- FRUC回放`continuation-single-owner-fruc`24项6.644秒PASS,known-pan15 SHA `EB05452E25325D9882DDD9E975051A010459FDD2432305F61E3820D85689D05B`;worker固定`EC8150FF88C7C84FACDF92B920DED2D6CEC5F682990C375A92550AFD5E818695`。UI `python scripts/acceptance/ui-fg-backends.py`正常与`--reject-xess`分别`ui-fg-1789064098272439200`/`ui-fg-1789064215917318600`通过,FRUC->XeSS->DLSS->关闭及XeSS失败保留FRUC。它们早于最终退出边界补丁,非全DPI验收。+- **性能对照无显著提升**:在`out/owner-baseline`单独checkout`e25585e`并构建,源码干净;仅在ignored输出目录补同版FFmpeg5个DLL及与当前相同FRUC worker。`continuation-owner-ab-old-runtime`7.708秒与`continuation-owner-ab-new`7.646秒,同素材、原生4K NR+VSR4+FRUC4+admission,均150源帧、33源fps、148真实呈现、0有效生成呈现、skip450/evaluate0,帧年龄P95 59.659/59.645ms。旧EXE `AAF6EF3DA6D331B40AB3B44DEDA589BA8B9F301D6BB53099A487B21C6C041510`,新对照EXE `2F425BE7F77B704397A58526B0C797E8C70F3E5DED4F0769AA0556297B9E0F97`。本轮解决所有权/等待推进,不声称NR内核提速或4X实时。基线第一次启动缺FFmpeg返回0xC0000135,记录`continuation-owner-ab-old`,未把启动失败拿来比较性能。+- 干净构建发现旧CMake先读FFmpeg变量、后find_package导致scene_analyzer首次缺头文件;改用`veyra_media`传递依赖。无实验NR配置还缺自有parity shader target,现将两个通用着色器target移到功能开关外。基线首构建失败`build-owner-baseline.log`,第二次配置成功`build-owner-baseline-configured.log`。最终全新VS生成目录`out/scene-no-nr-first-config`首次configure与scene_analyzer Release构建通过,日志`configure-scene-no-nr-final.log`/`build-scene-no-nr-final.log`;也验证带实验runtime的全新目录。先前无NR失败保留在`configure-scene-fresh.log`,不能说那次configure成功。++命令统一`scripts/build.ps1 -Root <root> -Preset x64-release`,最新`build-single-owner-cancel.log`exit0;短测`scripts/acceptance/scheduler-short-test.ps1 -Name <名称> -Exe <test> -TestArgs <result.args>`,result/stdout/stderr在`logs/scheduler-repair-20260910/`。最终`scripts/gates/delivery.ps1 -Root <root>`23项42.380秒PASS,`logs/delivery/3462b28549ed4982a99799adc5a3071e/result.json`,EXE SHA `1B0DF186574B552E349EBB9502AF89A001430B89407B3D15635862E668279CE6`。前置退出边界补丁前gate `7ce879edc9094d70b9febd31cd2cba1b`23项42.279秒也通过,不能与最终EXE混用。实际RTX NR/NVOF和NVENC已运行;NR CreateFeature18返回0x1、handle非空,例证`owner-fruc/engine.log`。没有改变导出检查、SDK/runtime没有入Git。++以上单次<300秒,未打开实体采集卡、未执行AMD NR。单所有者主循环和对应短测已落地;下一任务为专业页全DPI/最小窗口/展开滚动验收与修复,再推进AMD NR依赖/provider。GPU driver/NGX/FRUC调用仍可能阻塞当前线程,此状态机不是可抢占GPU内核,也不是所有成本消除。整体目标仍active。+### 最新续接:逐帧GPU时间戳交付音频修复已本地存档`1821120`,随后修复阶段时间戳漏样,不改NR/SR/FG处理顺序。diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.mdindex a445c798..14628991 100644--- a/docs/HANDOFF_2026-09-10.md+++ b/docs/HANDOFF_2026-09-10.md@@ -4,6 +4,8 @@## 2026-09-11 当前可续接状态+当前最新:`e25585e`之后单GPU所有者主循环已落地,`LiveGpuScheduler`取代并删除旧呈现线程,所有图/完成/Present由引擎线程推进;采集tryRead不阻塞,源Waiting仍推进帧,EOF完整交付62真实帧。状态机15/live30/EOF6/FRUC24/正常与失败XeSS UI通过,最终delivery `3462b28549ed4982a99799adc5a3071e`23项42.380秒PASS,EXE `1B0DF186574B552E349EBB9502AF89A001430B89407B3D15635862E668279CE6`。旧`e25585e`独立构建在`out/owner-baseline`(干净源码、ignored SDK/runtime junction),同源原生4K重载A/B均33fps、P95约59.66ms,没有性能提升结论。下一条唯一任务全DPI/最小窗/专业展开滚动与选择器验收;AMD NR provider/依赖和实卡仍未完成。完整命令、失败、限制见实施记录最上方,下面“下一步单GPU所有者”是历史快照。无发布,目标active。+最新:音频修复本地提交`1821120`。其后GPU阶段计时的完成记录逐帧交付、同源补帧空闲查询槽选择已修;RTX6项/CPU71/live30项通过,源30fps对应Color30样本。联合delivery `88753f608465497dba0c2660bf7755dd`23项42.146秒PASS,EXE `F6B5F0E96B81B223FE856E888221CFF51ABBE706C9898A6609A49B7EF90413A2`。下一任务完整单GPU所有者状态机,继续解决阻塞观测与末帧计时;尚非S3完成。详见实施记录最上方,下面“下一步逐帧交付”已由本段覆盖。AMD NR/全DPI/实卡仍未完成,目标active。当前优先续接:`ed5aed3`之后漂移补偿/真实PCM时间映射的软件回归通过,关闭/零补偿53.8ms回归经采集静音填充/事件顺序修复。最终普通/端点丢失/文件与断粮时钟/70项CPU通过;同一EXE正负120秒漂移P95为4.242/4.302ms,均仅首个reset。delivery `c41ad55982e6448190d1bc4ed239a415`23项42.484秒通过,应用SHA `FDA98B226562C55B44A8139E1A4D7F3F35A7458109AC8ED4F72FD6ACE755D6BE`,本轮建立本地checkpoint。实施记录最新“采集时钟漂移与真实PCM播放位置”段包含命令、失败和EXE身份。下一条任务:修`GpuTimer::collect`多帧收回却只通过`last()`上报最后一帧的问题,保持epoch/revision隔离,再继续完整GPU所有者。目标active,AMD NR、完整DPI和实卡尚未验收;下方31.73ms漂移失败是本轮修复前基线。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 20c86a11..e591e985 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,7 @@# 2026-09-11 继续修复目标模式执行中+最新单GPU所有者续接:以`e25585e`为基线,用`LiveGpuScheduler`取代呈现线程并删除旧worker;提交/完成检查/deadline/Present由引擎线程推进,容量仍2,实卡tryRead立即返回。空档仍完成已有帧,EOF先呈现尾批,退出边界不覆盖失败;时间戳在源Waiting时也采集。状态机15项、最终live30项、400ms输入空档/62帧EOF6项、FRUC24项及正常/拒绝XeSS界面通过。独立旧Git构建同源原生4K NR+VSR4+FRUC4对照,新旧均33源fps、P95约59.66ms、0有效生成,不声称性能加速。首次CMake依赖顺序/无NR缺shader目标一起修复并全新配置验证。最终delivery `3462b28549ed4982a99799adc5a3071e`23项42.380秒PASS,EXE `1B0DF186574B552E349EBB9502AF89A001430B89407B3D15635862E668279CE6`。细节、失败与完整命令见实施记录最新段。下一条全DPI/窗口交互验收,AMD NR/实卡仍未完成;本地存档,不push/发布。+最新GPU计时续接:音频已提交`1821120`。修复`GpuTimer::collect`多帧完成只保留latest及同源补帧查询槽冲突,启用64条有界完成记录、逐帧/epoch/revision统计,满槽与溢出显式记录。真实RTX时间戳6项、CPU71项、最终live30项通过,30fps时Color一秒样本30。最终delivery `88753f608465497dba0c2660bf7755dd`23项42.146秒PASS,应用SHA `F6B5F0E96B81B223FE856E888221CFF51ABBE706C9898A6609A49B7EF90413A2`。命令/身份/边界见实施记录最新段。下一任务完整单GPU所有者调度;仍未实卡/AMD NR/全DPI验收,不push/发布。最新漂移续接(覆盖下面旧结论):在`ed5aed3`之后接入有界swr补偿和重采样PCM到IAudioClock的分段PTS映射。候选关闭/零补偿出现53.8ms回归,已定位并修复采集填充静音及等待顺序;最终普通模式11.112秒、端点恢复3.573秒、文件/半速/断粮时钟1.082秒和70项CPU合同通过。同一最终EXE正负1000ppm各120秒,P95为4.242/4.302ms,均missing0/仅首次reset1。联合delivery `c41ad55982e6448190d1bc4ed239a415`23项42.484秒PASS,应用SHA `FDA98B226562C55B44A8139E1A4D7F3F35A7458109AC8ED4F72FD6ACE755D6BE`。详细失败、命令、哈希见实施记录“采集时钟漂移与真实PCM播放位置”。本轮建立本地存档,无实卡/发布;下一任务逐帧GPU时间戳交付,随后单GPU所有者,AMD NR与UI完整验收仍未完成。diff --git a/include/veyra/engine/LiveGpuScheduler.h b/include/veyra/engine/LiveGpuScheduler.hnew file mode 100644index 00000000..0bc9edaa--- /dev/null+++ b/include/veyra/engine/LiveGpuScheduler.h@@ -0,0 +1,43 @@+#pragma once+#include <cstdint>+#include <deque>+#include <functional>+#include <thread>+#include <stdexcept>++namespace veyra::engine {+// All steps execute on the graph owner. Waiting is represented as a deadline,+// never a sleeping callback; each queued entry retains one batch lease.+class LiveGpuScheduler {+public:+ enum class State { Pending, Complete, Failed };+ struct Step {State state=State::Pending;int64_t wakeAt=0;};+ using Job=std::function<Step(int64_t)>;+ explicit LiveGpuScheduler():owner_(std::this_thread::get_id()){}+ LiveGpuScheduler(const LiveGpuScheduler&)=delete;+ LiveGpuScheduler& operator=(const LiveGpuScheduler&)=delete;+ ~LiveGpuScheduler(){cancel();}+ bool push(Job job,std::function<void()> finish){+ requireOwner();if(failed_||queue_.size()>=2)return false;+ queue_.push_back({std::move(job),std::move(finish)});return true;+ }+ void advance(int64_t now){+ requireOwner();wakeAt_=0;+ while(!queue_.empty()&&!failed_){+ Step result;+ try{result=queue_.front().job(now);}catch(...){result.state=State::Failed;}+ if(result.state==State::Pending){wakeAt_=result.wakeAt;break;}+ auto entry=std::move(queue_.front());queue_.pop_front();entry.finish();entry.job={};+ if(result.state==State::Failed){failed_=true;cancel();}+ }+ }+ void cancel(){requireOwner();while(!queue_.empty()){auto entry=std::move(queue_.front());queue_.pop_front();entry.finish();}wakeAt_=0;}+ uint32_t occupancy()const{return static_cast<uint32_t>(queue_.size());}+ bool failed()const{return failed_;}+ int64_t wakeAt()const{return wakeAt_;}+private:+ struct Entry {Job job;std::function<void()> finish;};+ void requireOwner()const{if(std::this_thread::get_id()!=owner_)throw std::logic_error("GPU scheduler called outside owner thread");}+ std::thread::id owner_;std::deque<Entry> queue_;bool failed_=false;int64_t wakeAt_=0;+};+}diff --git a/include/veyra/engine/PresentationWorker.h b/include/veyra/engine/PresentationWorker.hdeleted file mode 100644index 1fa7d69f..00000000--- a/include/veyra/engine/PresentationWorker.h+++ /dev/null@@ -1,51 +0,0 @@-#pragma once-#include <atomic>-#include <chrono>-#include <condition_variable>-#include <deque>-#include <functional>-#include <mutex>-#include <string>-#include <thread>-namespace veyra::engine {-// Two leased batches including the active batch. Sleeping for presentation-// deadlines must not stop the source/graph thread from submitting the next one.-class PresentationWorker {-public:- using Cancelled=std::function<bool()>;- using Job=std::function<bool(const Cancelled&)>;- explicit PresentationWorker(Cancelled interrupt):interrupt_(std::move(interrupt)),thread_([this]{run();}){}- ~PresentationWorker(){stopping_=true;++epoch_;wake_.notify_all();if(thread_.joinable())thread_.join();}- PresentationWorker(const PresentationWorker&)=delete;- bool waitForSlot(const std::function<void()>& progress={}){- std::unique_lock lock(mutex_);- while(queue_.size()+unsigned(active_)>=2&&!failed_&&!stopping_&&!interrupt_()){- lock.unlock();if(progress)progress();lock.lock();- if(queue_.size()+unsigned(active_)>=2)wake_.wait_for(lock,std::chrono::milliseconds(1));- }- return !failed_&&!stopping_&&!interrupt_();- }- bool push(Job job,std::function<void()> discarded={}){std::lock_guard lock(mutex_);if(failed_||stopping_||queue_.size()+unsigned(active_)>=2)return false;queue_.push_back({epoch_.load(),std::move(job),std::move(discarded)});wake_.notify_all();return true;}- uint32_t occupancy()const{std::lock_guard lock(mutex_);return uint32_t(queue_.size()+unsigned(active_));}- void cancelAndDrain(){- ++epoch_;std::unique_lock lock(mutex_);discardQueued();wake_.notify_all();wake_.wait(lock,[&]{return !active_;});- }- bool failed()const{std::lock_guard lock(mutex_);return failed_;}-private:- struct Entry{uint64_t epoch;Job job;std::function<void()> discarded;};- Cancelled interrupt_;mutable std::mutex mutex_;std::condition_variable wake_;std::deque<Entry> queue_;- bool active_=false,failed_=false;std::atomic<bool> stopping_{false};std::atomic<uint64_t> epoch_{0};std::thread thread_;- void discardQueued(){for(auto& entry:queue_)if(entry.discarded)entry.discarded();queue_.clear();}- void run(){- for(;;){Entry entry;{- std::unique_lock lock(mutex_);wake_.wait(lock,[&]{return stopping_||!queue_.empty();});if(stopping_){discardQueued();break;}- entry=std::move(queue_.front());queue_.pop_front();active_=true;- }- bool ok=true;try{ok=entry.job([&,generation=entry.epoch]{return stopping_||epoch_!=generation||interrupt_();});}catch(...){ok=false;}- // Drop captured FrameOutputs/leases before advertising a reusable slot.- entry.job={};{- std::lock_guard lock(mutex_);active_=false;if(!ok){failed_=true;discardQueued();}wake_.notify_all();- }}- }-};-}diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.hindex b65f4012..fd7bb65e 100644--- a/include/veyra/source/CaptureCardSource.h+++ b/include/veyra/source/CaptureCardSource.h@@ -26,8 +26,11 @@ public:sink::CaptureAudioState audioState()const;const SourceInfo& info()const override;SourceReadStatus read(pipeline::FramePacket&,const AVFrame**)override;+ SourceReadStatus tryRead(pipeline::FramePacket&,const AVFrame**);bool seek(const pipeline::Rational&)override{return false;}void close()noexcept override;-private:struct Impl;std::unique_ptr<Impl> p_;+private:+ SourceReadStatus readWithWait(pipeline::FramePacket&,const AVFrame**,unsigned milliseconds);+ struct Impl;std::unique_ptr<Impl> p_;};}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 47006288..63246f91 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -4,7 +4,7 @@#include "veyra/engine/LivePresentationTiming.h"#include "veyra/engine/PresentationScheduler.h"#include "veyra/engine/DeadlineWait.h"-#include "veyra/engine/PresentationWorker.h"+#include "veyra/engine/LiveGpuScheduler.h"#include "veyra/engine/LivePresentationResetPolicy.h"#include "veyra/engine/TimingWindow.h"#include "veyra/engine/FrameFlowWindow.h"@@ -159,7 +159,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){auto host100ns=[](){return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;};// Only the live source may discard stale input. File playback keeps// its audio-clock scheduler and lossless source ordering.- std::mutex gpuMutex,liveStatsMutex;+ // 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;@@ -167,20 +167,24 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){int64_t lastFgCompletion=0;std::atomic<uint64_t> historyResets=0,presentationDrains=0,presentationCompletedReal=0,presentationSkippedGenerated=0,presentationCancelledJobs=0;std::atomic<uint64_t> presentationGeneration{0};- std::unique_ptr<PresentationWorker> liveWorker;+ std::unique_ptr<LiveGpuScheduler> liveScheduler;struct CompletionWatch {pipeline::EnhanceGraph::FrameOutputs output;std::shared_ptr<FrameFlowWindow> flow;Clock::time_point processStart;bool real=false;std::atomic<bool> ready=false;+ Clock::time_point readyObserved{};};std::vector<std::shared_ptr<CompletionWatch>> pendingCompletions;+ std::shared_ptr<FrameFlowWindow> frameFlow;+ auto collectTimings=[&]{+ for(const auto& sample:graph.takeGpuTimings())if(frameFlow)frameFlow->gpuFrame(sample,host100ns());+ for(const auto& sample:presenter.takeGpuTimings(ctx.fence()))if(frameFlow)frameFlow->gpuFrame(sample,host100ns());+ };// Shared with the presenter: resolve each batch on this single// object so SDK status and generated counts are consumed once.auto pollCompletions=[&]{- std::unique_lock gpuLock(gpuMutex,std::try_to_lock);- if(!gpuLock.owns_lock())return;for(auto it=pendingCompletions.begin();it!=pendingCompletions.end();){auto& watch=**it;auto& batch=watch.output;if(!graph.resolveGeneration(batch)){++it;continue;}@@ -190,26 +194,30 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){}watch.flow->ready(batch.batch.batchId,watch.real,valid,invalid,host100ns());if(watch.real)completedProcessing(batch.batch.identity);- {std::lock_guard statsLock(liveStatsMutex);+ {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();}}- watch.ready=true;it=pendingCompletions.erase(it);+ watch.readyObserved=Clock::now();watch.ready=true;it=pendingCompletions.erase(it);}+ collectTimings();};- if(isCapture)liveWorker=std::make_unique<PresentationWorker>([&]{return stop_.load()||paused_.load();});- auto drainLivePresentation=[&]{if(liveWorker){++presentationDrains;liveWorker->cancelAndDrain();pollCompletions();std::lock_guard gpuLock(gpuMutex);pendingCompletions.clear();}};+ if(isCapture){liveScheduler=std::make_unique<LiveGpuScheduler>();veyra::log::info("scheduler",std::format("single GPU owner thread={} capacity=2",GetCurrentThreadId()));}+ auto drainLivePresentation=[&]{if(liveScheduler){++presentationDrains;liveScheduler->cancel();pollCompletions();pendingCompletions.clear();}};+ auto advanceLive=[&]{if(liveScheduler){pollCompletions();if(stop_||paused_)liveScheduler->cancel();else liveScheduler->advance(host100ns());}};+ auto waitLive=[&]{const auto due=liveScheduler?liveScheduler->wakeAt():0;deadlineWait.slice(due>host100ns()?std::min(1.0,double(due-host100ns())/10000):1.0);};uint64_t metricsRevision=options.settings.revision,metricsEpoch=0,statsSourceBase=0;uint64_t slotWaitBase=ring.cpuWaitCount(),submitBase=ring.submitCount();double slotWaitMsBase=ring.cpuWaitMilliseconds();const uint64_t runSessionId=[&]{std::lock_guard lock(mutex_);return snapshot_.sessionId;}();- std::shared_ptr<FrameFlowWindow> frameFlow;std::shared_ptr<FrameCompletionRates> completionRates;source::CaptureMetrics captureFlowBase{},captureFlowLast{};uint64_t rateSkippedBase=0;- // The worker captures these locals; join before their destruction.- OnExit stopPresentation{[&]{liveWorker.reset();std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId){if(frameFlow)snapshot_.metrics.flow=frameFlow->snapshot(host100ns());activeFlow_.reset();}}};+ // Queued steps capture these locals; cancel before their destruction.+ OnExit stopPresentation{[&]{liveScheduler.reset();std::lock_guard lock(mutex_);if(snapshot_.sessionId==runSessionId){if(frameFlow)snapshot_.metrics.flow=frameFlow->snapshot(host100ns());activeFlow_.reset();}}};+ const bool injectSourceGap=options.captureReplayForTest&&GetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_SOURCE_GAP",nullptr,0)>0;+ std::optional<Clock::time_point> sourceGapUntil;while(!stop_){- if(liveWorker)pollCompletions();- if(liveWorker&&liveWorker->failed()){status(L"采集画面呈现失败,请查看诊断",true);break;}+ advanceLive();+ 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(isCapture){const bool available=captureSource.setAudioGain(gain);const auto audioState=captureSource.audioState();std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;snapshot_.captureAudio=audioState;}@@ -272,21 +280,37 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(wasPaused&&!paused_){audioRebuffering=false;if(audioStarted)audioPipe.setPaused(false);anchor=Clock::now();anchorMs=out.ptsMs;reset=true;wasPaused=false;}// Backpressure before reading the capacity-one source mailbox:// when a lease frees we consume the newest available sample.- if(liveWorker&&!transaction&&!liveWorker->waitForSlot(pollCompletions))continue;+ if(liveScheduler&&!transaction){+ while(liveScheduler->occupancy()>=2&&!stop_&&!paused_&&!liveScheduler->failed()){+ advanceLive();if(liveScheduler->occupancy()>=2)waitLive();+ std::lock_guard lock(mutex_);if(desired_.revision!=options.settings.revision)break;+ }+ if(stop_||paused_||liveScheduler->failed()||liveScheduler->occupancy()>=2)continue;+ }const auto decodeStart=Clock::now();+ if(injectSourceGap&&frames>=12){+ if(!sourceGapUntil){sourceGapUntil=Clock::now()+std::chrono::milliseconds(400);veyra::log::info("capture-test","inject 400ms Waiting before next source read");}+ if(Clock::now()<*sourceGapUntil){advanceLive();waitLive();continue;}+ }pipeline::FramePacket pkt;const AVFrame* frame=imageFrame;if(transaction&&cachedFrame&&(!isCapture||paused_)){frame=cachedFrame;pkt=cachedPacket;}else if(!isImage){- auto rs=activeSource->read(pkt,&frame);+ auto rs=physicalCapture?captureSource.tryRead(pkt,&frame):activeSource->read(pkt,&frame);// Keep the accepted transaction and rollback state alive until// the next real capture sample arrives. Never bind old PTS to now.while(transaction&&isCapture&&rs==source::SourceReadStatus::Waiting&&!stop_){if(paused_&&cachedFrame){frame=cachedFrame;pkt=cachedPacket;rs=source::SourceReadStatus::Frame;break;}- rs=activeSource->read(pkt,&frame);+ advanceLive();waitLive();rs=physicalCapture?captureSource.tryRead(pkt,&frame):activeSource->read(pkt,&frame);}if(stop_)break;- if(rs==source::SourceReadStatus::Waiting)continue;- if(rs==source::SourceReadStatus::Eos){seekPreviewPending=false;status(L"视频已播放完毕");paused_=true;{std::lock_guard lock(mutex_);snapshot_.transport=TransportState::Ended;}continue;}+ if(rs==source::SourceReadStatus::Waiting){advanceLive();waitLive();continue;}+ if(rs==source::SourceReadStatus::Eos){+ while(liveScheduler&&liveScheduler->occupancy()&&!stop_&&!paused_&&!liveScheduler->failed()){advanceLive();if(liveScheduler->occupancy())waitLive();}+ if(stop_)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;+ }if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()){status(isCapture?L"采集信号中断,请检查设备连接或格式":L"视频解码或时间戳错误",true);break;}}const bool rereadCached=transaction&&frame==cachedFrame;@@ -315,7 +339,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(historyReset){++historyResets;++presentationGeneration;}// A mailbox Drop must reset SR/NR/flow/FG history, but draining// the two-batch presenter here discarded completed real frames.- if(liveWorker&&presentationDrainRequired(reset,pkt.flags))drainLivePresentation();+ if(liveScheduler&&presentationDrainRequired(reset,pkt.flags))drainLivePresentation();const bool injectedReject=transaction&&!options.nr&&GetEnvironmentVariableW(L"VEYRA_TEST_REJECT_NR_DISABLE",nullptr,0)>0;if(injectedReject)veyra::log::error("settings-test","test-only reject NR-disable transaction before graph process; no driver failure");pipeline::EnhanceGraph::FgAdmission admitFg;@@ -323,7 +347,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){// 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;- {std::lock_guard statsLock(liveStatsMutex);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;}}+ {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){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);@@ -333,7 +357,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){};}uint64_t processWaitBase=0,processSubmitBase=0;double processWaitMsBase=0,processSlotWaitMs=0;- bool processed=false;{std::lock_guard gpuLock(gpuMutex);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;}+ 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;}if(!processed){if(transaction){ring.drainQueue();out={};presenter.close();graph.shutdown();options=PlayerOptions::from(previous);@@ -352,7 +376,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){metricsRevision=options.settings.revision;metricsEpoch=out.batch.identity.epoch;statsStart=Clock::now();statsSourceBase=sourceFrames-uint64_t(!rereadCached);slotWaitBase=processWaitBase;slotWaitMsBase=processWaitMsBase;submitBase=processSubmitBase;captureAges.clear();scheduleWaits.clear();processTimes.clear();presentTimes.clear();decodeTimes.clear();gpuReadyTimes.clear();for(auto& window:gpuStageTimes)window.clear();lastGpuSampleEnd={};latenessSamples.clear();submissionTimes.clear();submitted=expired=0;- if(liveWorker){std::lock_guard statsLock(liveStatsMutex);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();liveCompletion.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;});frameFlow->update([&](auto& m){m.counters.historyResets=out.historyReset;m.counters.settingsResets=settingsChanged;m.counters.captureDropResets=pipeline::hasFrameFlag(pkt.flags,pipeline::FrameFlagBits::Drop);});@@ -384,53 +408,61 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){auto nowMs=[&](){const double a=audioStarted?audio.mediaTimeMs():-1;return a>=0?a:anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();};double frameWaitMs=0,framePresentMs=0;double gpuWaitMs=0;- if(liveWorker){+ if(liveScheduler){const auto timeline=liveTimeline;const uint64_t jobGeneration=presentationGeneration.load();auto watch=std::make_shared<CompletionWatch>();watch->output=out;watch->flow=frameFlow;watch->processStart=processStart;watch->real=!rereadCached;- {std::lock_guard gpuLock(gpuMutex);pendingCompletions.push_back(watch);}- if(!liveWorker->push([&,watch,timeline,captureArrival,lineage,jobGeneration,rereadCached,flow=frameFlow](const PresentationWorker::Cancelled& cancelled){- auto& batch=watch->output;- unsigned handled=0;- OnExit accountCancelled{[&]{flow->update([&](auto& m){m.counters.cancelledBeforePresent+=batch.batch.count-handled;});}};- auto& wait=deadlineWait;const auto readyStart=Clock::now();- for(;;){if(cancelled()){++presentationCancelledJobs;return true;}pollCompletions();if(watch->ready)break;- if(elapsedMs(readyStart)>2000){veyra::log::error("capture-present","GPU ready timeout");return false;}wait.slice(.2);}- const double readyMs=elapsedMs(readyStart);double waitMs=0,presentMs=0,ageMs=0;uint64_t count=0,dropped=0;- flow->cpu(diagnostics::CpuStage::ReadyWait,readyMs,host100ns());+ pendingCompletions.push_back(watch);+ struct LiveStepState {+ unsigned next=0,handled=0;bool readyReported=false;+ Clock::time_point readyStart=Clock::now();std::optional<Clock::time_point> deadlineStart;+ double readyMs=0,waitMs=0,presentMs=0,ageMs=0;uint64_t count=0,dropped=0;diagnostics::GpuSample blit;- OnExit publish{[&]{flow->update([&](auto& m){m.gpuReadyWaitMs=readyMs;m.deadlineWaitMs=waitMs;if(count)m.captureArrivalToPresentReturnMs=ageMs;m.counters.generatedExpiredAfterEval+=dropped;});if(!count&&!dropped)return;std::lock_guard statsLock(liveStatsMutex);if(liveStats.identity.epoch!=batch.batch.identity.epoch||liveStats.identity.settingsRevision!=batch.batch.identity.settingsRevision)return;liveStats.submitted+=count;liveStats.expired+=dropped;- // Accumulate at completion, not at producer polling: two- // completions between reads must not lose a timing sample.- if(count){liveStats.waitMs=waitMs;liveStats.presentMs=presentMs;liveStats.readyMs=readyMs;liveStats.ageMs=ageMs;liveStats.blit=blit;- liveAges.add(ageMs);liveWaits.add(waitMs);livePresent.add(presentMs);liveReady.add(readyMs);liveStats.ageP95=liveAges.p95();liveStats.waitP95=liveWaits.p95();liveStats.presentP95=livePresent.p95();liveStats.readyP95=liveReady.p95();}- liveStats.fps=liveSubmissions.size()>1?double(liveSubmissions.size()-1)*1e7/(liveSubmissions.back()-liveSubmissions.front()):0;}};- for(unsigned i=0;i<batch.batch.count;++i){auto& item=batch.batch.frames[i];const bool generated=item.kind==pipeline::FrameKind::Generated;- if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++handled;continue;}- if(generated&&comparisonMode_!=0)continue;- if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}- if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;++handled;continue;}- const auto waitStart=Clock::now();while(!cancelled()&&host100ns()<timeline.deadline(item.pts100ns)){pollCompletions();wait.slice();}const auto waited=elapsedMs(waitStart);waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());if(cancelled()){++presentationCancelledJobs;return true;}- if(generated&&!generatedPresentationCurrent(jobGeneration,presentationGeneration.load())){++presentationSkippedGenerated;continue;}- const auto begin=Clock::now();bool didPresent=false;uint64_t xessGenerated=0,xessPresented=0;- {std::lock_guard gpuLock(gpuMutex);if(cancelled()){++presentationCancelledJobs;return true;}if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++dropped;++handled;continue;}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()))return false;- xessGenerated=presenter.xessGeneratedCount()-beforeXess;- xessPresented=presenter.xessPresentedCount()-beforeXessPresented;- item.lease->consumerFence=ring.lastSignaledValue();didPresent=presenter.submittedCount()>before;blit=presenter.blitTiming(ctx.fence());}- presentMs+=elapsedMs(begin);- flow->cpu(diagnostics::CpuStage::Present,elapsedMs(begin),host100ns());+ };+ auto step=std::make_shared<LiveStepState>();+ if(!liveScheduler->push([&,watch,step,timeline,captureArrival,lineage,jobGeneration,rereadCached,flow=frameFlow](int64_t now)->LiveGpuScheduler::Step{+ using State=LiveGpuScheduler::State;auto& batch=watch->output;auto& s=*step;+ if(!watch->ready){+ if(elapsedMs(s.readyStart)>2000){veyra::log::error("capture-present","GPU ready timeout");return {State::Failed};}+ return {State::Pending,now+2000};+ }+ if(!s.readyReported){s.readyMs=std::max(0.0,std::chrono::duration<double,std::milli>(watch->readyObserved-s.readyStart).count());s.readyReported=true;flow->cpu(diagnostics::CpuStage::ReadyWait,s.readyMs,host100ns());}+ while(s.next<batch.batch.count){auto& item=batch.batch.frames[s.next];const bool generated=item.kind==pipeline::FrameKind::Generated;+ if(stop_||paused_)return {State::Complete};+ if(generated&&item.validity!=pipeline::GenerationValidity::Valid){++s.handled;++s.next;continue;}+ if(generated&&(comparisonMode_!=0||!generatedPresentationCurrent(jobGeneration,presentationGeneration.load()))){++presentationSkippedGenerated;++s.next;continue;}+ if(generated&&timeline.expired(item.pts100ns,host100ns(),100000)){++s.dropped;++s.handled;++s.next;s.deadlineStart.reset();continue;}+ if(!s.deadlineStart)s.deadlineStart=Clock::now();+ if(host100ns()<timeline.deadline(item.pts100ns))return {State::Pending,timeline.deadline(item.pts100ns)};+ const auto waited=elapsedMs(*s.deadlineStart);s.deadlineStart.reset();s.waitMs+=waited;flow->cpu(diagnostics::CpuStage::DeadlineWait,waited,host100ns());+ 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()))return {State::Failed};+ 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(xessPresented)flow->xessSubmitted(xessPresented,xessGenerated,host100ns());if(didPresent&&physicalCapture)captureSource.videoPresented(double(item.pts100ns)/10000,host100ns());if(didPresent&&!generated&&!rereadCached)flow->latency(captureArrival,host100ns());if(didPresent&&generated&&lineage)flow->generatedLatency(*lineage,host100ns());- if(didPresent){++handled;++count;flow->presented(generated,item.lease->consumerFence,host100ns());if(!generated)++presentationCompletedReal;ageMs=double(host100ns()-captureArrival)/10000;std::lock_guard statsLock(liveStatsMutex);if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision){const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}}+ if(didPresent){++s.handled;++s.count;flow->presented(generated,item.lease->consumerFence,host100ns());if(!generated)++presentationCompletedReal;s.ageMs=double(host100ns()-captureArrival)/10000;+ if(liveStats.identity.epoch==batch.batch.identity.epoch&&liveStats.identity.settingsRevision==batch.batch.identity.settingsRevision){const auto time=host100ns();liveSubmissions.push_back(time);while(liveSubmissions.size()>1&&time-liveSubmissions.front()>10000000)liveSubmissions.pop_front();}}+ ++s.next;}- return true;- },[flow=frameFlow,count=out.batch.count]{flow->update([&](auto& m){m.counters.cancelledBeforePresent+=count;});})){status(L"采集呈现队列失败",true);break;}- const auto occupancy=liveWorker->occupancy();frameFlow->update([&](auto& m){m.counters.presentationBatchHighWater=std::max(m.counters.presentationBatchHighWater,occupancy);});- LiveStats completed;{std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}+ return {State::Complete};+ },[&,watch,step,flow=frameFlow]{+ const auto& batch=watch->output;const auto& s=*step;+ if(s.handled<batch.batch.count)++presentationCancelledJobs;+ flow->update([&](auto& m){m.counters.cancelledBeforePresent+=batch.batch.count-s.handled;m.gpuReadyWaitMs=s.readyMs;m.deadlineWaitMs=s.waitMs;if(s.count)m.captureArrivalToPresentReturnMs=s.ageMs;m.counters.generatedExpiredAfterEval+=s.dropped;});+ if(liveStats.identity.epoch!=batch.batch.identity.epoch||liveStats.identity.settingsRevision!=batch.batch.identity.settingsRevision)return;+ liveStats.submitted+=s.count;liveStats.expired+=s.dropped;+ 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;}+ 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;@@ -481,31 +513,29 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(interrupted){reset=true;continue;}seekPreviewPending=false;}- if(!liveWorker){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}+ if(!liveScheduler){scheduleWaits.add(frameWaitMs);presentTimes.add(framePresentMs);}const double lateness=isCapture?0:nowMs()-pts;if(!paused_&&!isCapture){latenessSamples.push_back(std::abs(lateness));if(latenessSamples.size()>1200)latenessSamples.pop_front();}std::vector<double> sorted(latenessSamples.begin(),latenessSamples.end());std::sort(sorted.begin(),sorted.end());const auto captureStats=isCapture?captureSource.metrics():source::CaptureMetrics{};diagnostics::FrameMetrics measured;pipeline::EnhanceGraph::Metrics graphStats;uint64_t slotWaitCount=0,commandSubmits=0;double slotWaitMilliseconds=0;uint32_t slotsInFlight=0;- {std::lock_guard gpuLock(gpuMutex);measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;slotsInFlight=ring.inFlightCount();- for(const auto& sample:graph.takeGpuTimings())frameFlow->gpuFrame(sample,host100ns());- for(const auto& sample:presenter.takeGpuTimings(ctx.fence()))frameFlow->gpuFrame(sample,host100ns());+ {measured=graph.gpuMetrics();graphStats=graph.metrics();measured.gpu[size_t(diagnostics::GpuStage::Blit)]=presenter.blitTiming(ctx.fence(),options.settings.revision,out.batch.identity.epoch);slotWaitCount=ring.cpuWaitCount()-slotWaitBase;slotWaitMilliseconds=ring.cpuWaitMilliseconds()-slotWaitMsBase;commandSubmits=ring.submitCount()-submitBase;slotsInFlight=ring.inFlightCount();+ collectTimings();}if(measured.identity.settingsRevision!=options.settings.revision||measured.identity.epoch!=out.batch.identity.epoch){measured={};measured.identity=out.batch.identity;for(auto& sample:measured.gpu)sample.state=diagnostics::SampleState::Pending;}if(graph.xessEnabled()){- std::lock_guard gpuLock(gpuMutex);graphStats.fgGeneratedFrames=presenter.xessGeneratedCount();}for(size_t stage=0;stage<measured.gpu.size();++stage){const auto& sample=measured.gpu[stage];if(sample.state==diagnostics::SampleState::Measured&&sample.milliseconds&&sample.end&&sample.end!=lastGpuSampleEnd[stage]){gpuStageTimes[stage].add(*sample.milliseconds);lastGpuSampleEnd[stage]=sample.end;}}measured.resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget);measured.decodeCpuMs=decodeMs;measured.submitCpuMs=std::chrono::duration<double,std::milli>(processDone-processStart).count();measured.gpuWaitCpuMs=gpuWaitMs;measured.deadlineWaitCpuMs=frameWaitMs;measured.presentCpuMs=framePresentMs;measured.queueWatermark=out.batch.count;- LiveStats completed;if(liveWorker){std::lock_guard statsLock(liveStatsMutex);completed=liveStats;}+ LiveStats completed;if(liveScheduler)completed=liveStats;uint64_t skipped=0;{std::lock_guard lock(mutex_);skipped=snapshot_.captureRateSkipped-rateSkippedBase;}frameFlow->update([&](auto& m){m.counters.captureReceived=captureStats.received-captureFlowBase.received;m.counters.mailboxOverwritten=captureStats.dropped-captureFlowBase.dropped;m.counters.sourceSkippedBeforeGraph=skipped;m.slotReuseWaitCount=slotWaitCount;m.slotReuseWaitMs=slotWaitMilliseconds;m.counters.commandSlotsInFlight=slotsInFlight;m.counters.commandSlotHighWater=std::max(m.counters.commandSlotHighWater,slotsInFlight);});frameFlow->update([&](auto& m){m.slotWaitPerFrameMs=processSlotWaitMs;});captureFlowLast=captureStats;measured.flow=frameFlow->snapshot(host100ns());measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;- const double ageP95=liveWorker?completed.ageP95:captureAges.p95(),waitP95=liveWorker?completed.waitP95:scheduleWaits.p95(),presentP95=liveWorker?completed.presentP95:presentTimes.p95();+ const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.position=pts/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];snapshot_.nrActive=graph.nrEnabled()&&graphStats.nrEvaluateCount>0;snapshot_.audioRebuffering=audioRebuffering;@@ -514,7 +544,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){if(transaction&&nvidiaAdapter&&(!graph.xessEnabled()||presenter.xessActive()))snapshot_.backendWarning.clear();snapshot_.flowPerf=graph.actualFlowPerf();snapshot_.contentFps=out.measuredContentRate;snapshot_.nrEvaluated=graphStats.nrEvaluateCount;snapshot_.nvofExecuted=graphStats.nvofExecuteCount;- snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveWorker?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;+ snapshot_.captureReceived=captureStats.received;snapshot_.captureDropped=captureStats.dropped;snapshot_.captureFps=captureStats.callbackFps;snapshot_.captureReadAgeMs=captureStats.readAgeMs;snapshot_.captureAgeMs=liveScheduler?completed.ageMs:captureStats.frameAgeMs;snapshot_.captureAgeP95Ms=ageP95;snapshot_.schedulingWaitP95Ms=waitP95;snapshot_.processCpuP95Ms=processTimes.p95();snapshot_.presentCpuP95Ms=presentP95;}const auto gpuP95=[&](diagnostics::GpuStage stage){return gpuStageTimes[size_t(stage)].p95();};@@ -523,7 +553,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){logFrameFlow(measured.flow,"active");const auto rates=snapshot();veyra::log::info("frame-rate",std::format("revision={} gpuCompletedFps={:.2f} completedReal={} capture60To30={} rateSkipped={} presentSubmitFps={:.2f} windowMs=1000 (not scanout FPS)",options.settings.revision,rates.fps,rates.processedCompleted,rates.captureHalfRate,rates.captureRateSkipped,rates.submissionFps.value_or(0)));- veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} presentationWorker=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveWorker?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));+ veyra::log::info("capture-timing",std::format("revision={} received={} processed={} dropped={} callbackFps={:.2f} readAgeMs={:.3f} callbackToPresentReturnP95Ms={:.3f} processCpuP95Ms={:.3f} gpuReadyP95Ms={:.3f} schedulingWaitP95Ms={:.3f} presentCpuP95Ms={:.3f} gpuColorP95Ms={:.3f} gpuSrP95Ms={:.3f} gpuFlowP95Ms={:.3f} gpuNrP95Ms={:.3f} gpuResidualP95Ms={:.3f} gpuFgBatchP95Ms={:.3f} gpuBlitP95Ms={:.3f} slotWaits={} slotWaitMs={:.3f} commandSubmits={} displaySubmits={} expiredGenerated={} nr={} nvof={} generated={} historyResets={} presentationDrains={} presentationCompletedReal={} presentationSkippedGenerated={} presentationCancelledJobs={} singleGpuOwner=1 batchCapacity=2 (not HDMI-to-display latency)",options.settings.revision,captureStats.received,sourceFrames-statsSourceBase,captureStats.dropped,captureStats.callbackFps,captureStats.readAgeMs,ageP95,processTimes.p95(),liveScheduler?completed.readyP95:gpuReadyTimes.p95(),waitP95,presentP95,gpuP95(diagnostics::GpuStage::Color),gpuP95(diagnostics::GpuStage::Sr),gpuP95(diagnostics::GpuStage::Flow),gpuP95(diagnostics::GpuStage::Nr),gpuP95(diagnostics::GpuStage::Residual),gpuP95(diagnostics::GpuStage::FgBatch),gpuP95(diagnostics::GpuStage::Blit),slotWaitCount,slotWaitMilliseconds,commandSubmits,submitted,expired,graphStats.nrEvaluateCount,graphStats.nvofExecuteCount,graphStats.fgGeneratedFrames,historyResets.load(),presentationDrains.load(),presentationCompletedReal.load(),presentationSkippedGenerated.load(),presentationCancelledJobs.load()));nextTimingLog=Clock::now()+std::chrono::seconds(1);}}diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex e636f806..7244213a 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -202,11 +202,13 @@ CaptureMetrics CaptureCardSource::metrics()const{if(p.received>1){const double elapsed=std::chrono::duration<double>(p.latestArrival-p.firstArrival).count();if(elapsed>0)m.callbackFps=(p.received-1)/elapsed;}if(p.sequence)m.frameAgeMs=std::chrono::duration<double,std::milli>(Impl::Clock::now()-p.readArrival).count();return m;}-SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;+SourceReadStatus CaptureCardSource::read(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,30);}+SourceReadStatus CaptureCardSource::tryRead(pipeline::FramePacket& packet,const AVFrame** frame){return readWithWait(packet,frame,0);}+SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,const AVFrame** frame,unsigned milliseconds){auto& p=*p_;*frame=nullptr;if(!p.info.opened)return SourceReadStatus::Error;long code=0;LONG_PTR a=0,b=0;while(p.events&&p.events->GetEvent(&code,&a,&b,0)==S_OK){p.events->FreeEventParams(code,a,b);if(code==EC_DEVICE_LOST||code==EC_ERRORABORT)return SourceReadStatus::Error;}double time=0;uint32_t flags=0;uint64_t sequence=0;pipeline::Rational duration;{- std::unique_lock lock(p.mutex);p.wake.wait_for(lock,std::chrono::milliseconds(30),[&]{return p.pending||p.callbackError;});+ std::unique_lock lock(p.mutex);if(milliseconds)p.wake.wait_for(lock,std::chrono::milliseconds(milliseconds),[&]{return p.pending||p.callbackError;});if(p.callbackError)return SourceReadStatus::Error;if(!p.pending)return Impl::Clock::now()-p.lastFrame>std::chrono::seconds(3)?SourceReadStatus::Error:SourceReadStatus::Waiting;std::swap(p.frame,p.pendingFrame);p.pending=false;time=p.pendingTime;p.readArrival=p.pendingArrival;diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cppindex ad9141f4..cdd5613a 100644--- a/tests/integration/LivePresentationTests.cpp+++ b/tests/integration/LivePresentationTests.cpp@@ -4,15 +4,18 @@#include <iostream>#include <filesystem>#include <fstream>+#include <regex>using namespace veyra;using namespace std::chrono_literals;int wmain(int argc,wchar_t**argv){SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--fruc-overload")==0||wcscmp(argv[3],L"--fruc-overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);+ if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--fruc")==0||wcscmp(argv[3],L"--half-rate")==0||wcscmp(argv[3],L"--overload")==0||wcscmp(argv[3],L"--overload-baseline")==0||wcscmp(argv[3],L"--fruc-overload")==0||wcscmp(argv[3],L"--fruc-overload-baseline")==0||wcscmp(argv[3],L"--file-overload")==0||wcscmp(argv[3],L"--source-gap")==0)))return 2;SetProcessDPIAware();CoInitializeEx(nullptr,COINIT_MULTITHREADED);std::filesystem::create_directories(argv[2]);Logger::instance().openFile((std::filesystem::path(argv[2])/"engine.log").wstring());Logger::instance().setConsoleEnabled(false);HWND window=CreateWindowExW(0,L"STATIC",L"Live scheduler replay",WS_POPUP,0,0,960,540,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);if(!window)return 3;engine::EngineController engine;engine::PlayerOptions options;options.nr=false;options.fg=false;options.captureReplayForTest=true;const bool halfRate=argc==4&&wcscmp(argv[3],L"--half-rate")==0;+ const bool sourceGap=argc==4&&wcscmp(argv[3],L"--source-gap")==0;+ if(sourceGap){SetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_SOURCE_GAP",L"1");options.nr=options.fg=true;options.fgMultiplier=2;}const bool frucOverload=argc==4&&std::wstring(argv[3]).find(L"--fruc-overload")==0;const bool overload=frucOverload||(argc==4&&std::wstring(argv[3]).find(L"--overload")==0);const bool fileOverload=argc==4&&wcscmp(argv[3],L"--file-overload")==0;@@ -24,6 +27,20 @@ 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(sourceGap){+ check(until([](const auto& s){return s.frames==12&&s.metrics.flow.counters.realPresented==12&&s.processedCompleted==12;}),"source Waiting still completes and presents all outstanding real frames");+ check(until([](const auto& s){return s.frames>=20;}),"source resumes after gap without deadlock");+ check(until([](const auto& s){return s.transport==engine::TransportState::Ended;},20),"EOF drains final live batch before marking ended");+ const auto s=engine.snapshot();const auto& c=s.metrics.flow.counters;+ std::cout<<"EOS frames="<<s.frames<<" ready="<<s.processedCompleted<<" presented="<<c.realPresented<<" cancelled="<<c.cancelledBeforePresent<<'\n';+ check(s.frames>20&&s.processedCompleted==s.frames&&c.realPresented==c.realSubmitted,"last real source frame is completed and current epoch fully presented");+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"source-gap session stops cleanly");+ Logger::instance().flush();std::ifstream log(std::filesystem::path(argv[2])/"engine.log");std::string line;uint64_t totalPresented=0,totalSubmitted=0;+ const std::regex submittedPattern("realSubmitted=([0-9]+)"),presentedPattern("realPresented=([0-9]+)");+ while(std::getline(log,line))if(line.find("[frame-flow] state=closed ")!=std::string::npos){std::smatch match;if(std::regex_search(line,match,submittedPattern))totalSubmitted+=std::stoull(match[1]);if(std::regex_search(line,match,presentedPattern))totalPresented+=std::stoull(match[1]);}+ check(totalPresented==s.frames&&totalSubmitted==s.frames,"all source frames across EOF discontinuity epochs present exactly once");+ DestroyWindow(window);CoUninitialize();return failures?1:0;+ }if(fileOverload){engine.setVolume(0,true);bool held=false,resumed=false;double maxLead=0;check(until([&](const auto& s){held|=s.audioRebuffering;resumed|=held&&!s.audioRebuffering&&s.frames>10;maxLead=std::max(maxLead,s.lateMs);return s.frames>=100;},35),"overloaded file keeps advancing without dropping source frames or deadlocking");diff --git a/tests/unit/LiveGpuSchedulerTests.cpp b/tests/unit/LiveGpuSchedulerTests.cppnew file mode 100644index 00000000..f73ad8dc--- /dev/null+++ b/tests/unit/LiveGpuSchedulerTests.cpp@@ -0,0 +1,40 @@+#include "veyra/engine/LiveGpuScheduler.h"+#include "veyra/engine/TimingWindow.h"+#include <iostream>+#include <memory>+#include <atomic>+int main(){+ using Scheduler=veyra::engine::LiveGpuScheduler;using State=Scheduler::State;+ int failures=0;auto check=[&](bool pass,const char* text){std::cout<<(pass?"PASS ":"FAIL ")<<text<<'\n';failures+=!pass;};+ Scheduler scheduler;unsigned finished=0,secondRan=0,firstSteps=0;bool gpuReady=false;+ const auto owner=std::this_thread::get_id();bool sameOwner=true;+ auto lease=std::make_shared<int>(1);std::weak_ptr<int> weak=lease;+ check(scheduler.push([&,lease](int64_t now){++firstSteps;sameOwner&=std::this_thread::get_id()==owner;if(!gpuReady)return Scheduler::Step{State::Pending,now+2};return Scheduler::Step{now<100?State::Pending:State::Complete,100};},[&]{++finished;}),"accept first leased GPU batch");+ lease.reset();scheduler.advance(0);+ check(firstSteps==1&&scheduler.wakeAt()==2&&!weak.expired(),"GPU-pending step yields immediately and retains lease");+ check(scheduler.push([&](int64_t){++secondRan;return Scheduler::Step{State::Complete};},[&]{++finished;}),"next batch accepted while current batch awaits GPU");+ check(!scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[]{})&&scheduler.occupancy()==2,"capacity includes both current and next batch");+ gpuReady=true;scheduler.advance(20);+ check(scheduler.wakeAt()==100&&secondRan==0,"deadline wait yields without presenting early or reordering batches");+ unsigned submission=0;++submission;+ check(submission==1&&finished==0,"owner remains available to submit work during future presentation deadline");+ scheduler.advance(100);+ check(finished==2&&secondRan==1&&weak.expired()&&scheduler.occupancy()==0&&sameOwner,"due work finishes on owner and releases leases exactly once");+ scheduler.advance(200);check(finished==2,"completed jobs cannot execute or finalize twice");+ unsigned cancelled=0;+ scheduler.push([](int64_t){return Scheduler::Step{State::Pending,1000};},[&]{++cancelled;});+ scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[&]{++cancelled;});+ scheduler.advance(300);scheduler.cancel();scheduler.cancel();+ check(cancelled==2&&scheduler.occupancy()==0&&scheduler.wakeAt()==0,"cancellation finalizes pending and queued batches exactly once without waiting");+ scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[&]{++finished;});scheduler.advance(400);+ check(finished==3,"new work accepted after cancellation");+ std::atomic<bool> rejected=false;std::thread foreign([&]{try{scheduler.advance(500);}catch(const std::logic_error&){rejected=true;}});foreign.join();+ check(rejected,"foreign thread cannot advance GPU owner state");+ unsigned failedFinished=0;+ scheduler.push([](int64_t){return Scheduler::Step{State::Failed};},[&]{++failedFinished;});+ scheduler.push([](int64_t){return Scheduler::Step{State::Complete};},[&]{++failedFinished;});scheduler.advance(600);+ 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");+ return failures?1:0;+}diff --git a/tests/unit/PresentationWorkerTests.cpp b/tests/unit/PresentationWorkerTests.cppdeleted file mode 100644index 57d58c57..00000000--- a/tests/unit/PresentationWorkerTests.cpp+++ /dev/null@@ -1,29 +0,0 @@-#include "veyra/engine/PresentationWorker.h"-#include "veyra/engine/TimingWindow.h"-#include <future>-#include <iostream>-using namespace std::chrono_literals;-int main(){- int failures=0;auto check=[&](bool pass,const char* s){std::cout<<(pass?"PASS ":"FAIL ")<<s<<'\n';if(!pass)++failures;};- std::promise<void> entered;auto enteredFuture=entered.get_future();std::atomic<unsigned> ran{0};std::atomic<bool> released{false};- veyra::engine::PresentationWorker worker([]{return false;});- check(worker.push([&](const auto& cancelled){entered.set_value();while(!cancelled())std::this_thread::sleep_for(1ms);released=true;return true;}),"queue active presentation");- check(enteredFuture.wait_for(1s)==std::future_status::ready,"worker starts independently of producer");- std::atomic<unsigned> discarded=0;- check(worker.push([&](const auto&){++ran;return true;},[&]{++discarded;}),"next batch can queue while active job sleeps");- check(!worker.push([](const auto&){return true;}),"two-batch capacity includes active lease");- worker.cancelAndDrain();check(released&&ran==0,"cancel waits for active callback and drops queued job");- check(discarded==1&&worker.occupancy()==0,"queued cancellation counted exactly once and occupancy drains");- std::promise<void> next;auto nextFuture=next.get_future();check(worker.waitForSlot()&&worker.push([&](const auto&){next.set_value();return true;}),"producer resumes after cancellation");- check(nextFuture.wait_for(1s)==std::future_status::ready,"new epoch job executes");worker.cancelAndDrain();- std::atomic<bool> observed=false;std::promise<void> waiting;auto waitingFuture=waiting.get_future();- check(worker.push([&](const auto& cancelled){waiting.set_value();while(!observed&&!cancelled())std::this_thread::sleep_for(1ms);return true;}),"hold presenter behind independently completed work");- check(waitingFuture.wait_for(1s)==std::future_status::ready&&worker.push([](const auto&){return true;}),"fill bounded queue during presentation deadline");- check(worker.waitForSlot([&]{check(worker.occupancy()==2,"completion polling runs outside queue mutex");observed=true;})&&observed,"backpressure observes completion before presenter releases slot");- worker.cancelAndDrain();- check(worker.push([](const auto&){return false;}),"inject presentation failure");- auto deadline=std::chrono::steady_clock::now()+1s;while(!worker.failed()&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(1ms);- check(worker.failed()&&!worker.waitForSlot(),"failure propagates without blocking producer");- veyra::engine::TimingWindow timing;for(unsigned i=0;i<100;++i)timing.add(i);check(timing.p95()==94,"percentile order statistic");timing.clear();timing.add(6);check(timing.p95()==6,"reset removes prior 94ms window immediately");- return failures?1:0;-}