Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

fix: recover file audio endpoints without advancing a disconnected media clock

Veyra Goal Agent78675f2c5c57
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index 0b323831..c0bf63ff 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -56,7 +56,11 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"延迟样本 / 统计溢出",std::format(L"{} / {}",f.latencySamples,f.timingOverflow));
rows.emplace_back(L"补帧方式",s.applied.multiplier<=1?L"关闭":std::format(L"{} {}X",xess?L"XeSS":s.applied.frameGenerationBackend==engine::FrameGenerationBackend::Fruc?L"FRUC":L"DLSS",s.applied.multiplier));
rows.emplace_back(L"NR内部尺寸",s.applied.nr?std::format(L"{} x {}",s.metrics.resolution.nr.width,s.metrics.resolution.nr.height):L"关闭");
- rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioRebuffering?L"视频过载 · 同步缓冲":L"音频主时钟")):L"无音频");
+ rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioEndpointRecovering?L"音频设备恢复中 · 时间线保持":s.audioRebuffering?L"视频过载 · 同步缓冲":L"音频主时钟")):L"无音频");
+ if(!s.capture&&s.audioAvailable){
+ rows.emplace_back(L"音频设备恢复次数",std::to_wstring(s.audioEndpointRecoveries));
+ if(FAILED(s.audioEndpointError))rows.emplace_back(L"最近音频设备错误",std::format(L"0x{:08X}",unsigned(s.audioEndpointError)));
+ }
if(!s.capture&&s.audioAvailable)rows.emplace_back(L"声音领先 · 软件估算",std::format(L"{:.1f} ms",s.lateMs));
if(s.capture&&s.audioAvailable){
rows.emplace_back(L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));
diff --git a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
index 9f2648a1..de9f32f5 100644
--- a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
+++ b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md
@@ -4,6 +4,23 @@
## 2026-09-11 续接实证(优先于下面历史进度)
+### 最新续接:文件音频端点恢复与共同时间线
+
+基线 `bba7283` 工作树干净,上一轮UI修复/AMD loader定因属于有效进展。本轮完成文件WASAPI端点错误后的自动恢复,不改SR -> NR -> FG、导出检查或实体采集设置。
+
+- 原因:`AudioPipeline::runOnAudioThread`在pump失败直接退出;引擎在音频clock变NaN时切换到墙钟,设备断开后视频继续走。现在文件路径由音频线程创建/释放/重建端点和COM,500ms重试;旧诊断调用可保留外部初始化。端点释放与anchor更新受短生命周期互斥保护,引擎clock读取不会访问已释放的COM;正常pump仍由单音频owner执行。
+- 设备失效、clock失败、暂停/恢复失败都进入恢复;保留HRESULT及恢复次数。视频在音频失效期间保持最后有效媒体时间,不用墙钟冒充仍在播音;只有已确认音频尾部耗尽才允许无音频尾段继续。恢复清理旧PCM/重采样,seek到最后有效播放PTS后预填,不能从已经预解码约一秒的队首直接跳过去。用户在断开期间seek会更新恢复目标。seek失败返回NaN并保留恢复状态,不能记录成功。
+- 暂停时重建只预填/锚定,不调用IAudioClient::Start,恢复后仍暂停;音量/静音保留。状态面板新增设备恢复状态、次数和最近错误,停止清除恢复中标记。测试注入只在音频owner上释放自己的端点,不操作系统默认设备、不关闭其它软件。
+- 最终 `continuation-file-endpoint-final2-timeline` 47项、2.628秒PASS:既有44.1/48k PCM、sample精度seek、真实WASAPI、半速映射、断粮及恢复,加播放中设备丢失/重开、暂停丢失、断开中seek到1234.25ms、暂停重建不播放、恢复后resume、重试期间stop、并发clock读取。恢复前111.979ms,重新锚定127.438ms,差来自故障命令被音频线程接收前已播放部分;未跳到预解码队首。97/98次并发读取有实证。首轮 `continuation-file-endpoint-recovery` 只因测试要求读取次数>100失败(Windows线程sleep调度),修正为实际多次跨恢复读取/最终clock失效检查,失败日志保留;功能门槛未放宽。
+- 最终 `continuation-file-endpoint-final2-player` 7项、2.297秒PASS,真实EngineController文件路径:端点断开300ms期间最多两帧边界变化,时间线不前进;恢复后继续50帧、软件A/V偏差<30ms、暂停seek/resume/关闭均通过。测试EXE `3075E01896ED72899C675FE40A89C69BADDA01F97F378B57BBF707E232FB0204`;音频测试EXE `5060691745A1DC6F15891179EA28DC501855AFCD42541C5C1B872829B9A5FAC2`。
+- `continuation-file-endpoint-overload` 5项、7.067秒PASS:实际原生4K NR+VSR4+FG4过载仍保持音频并在视频追上后恢复、暂停seek/关闭通过;最大观测lead123.333ms是过载捕获瞬间,不是稳态同步达标值。最终异常边界补丁前执行,EXE `BB6E1BBC49FA77F7D76BB38B7F71F294A7C7A050360E06C444ACB4014243F3FF`。`continuation-file-endpoint-capture` 11.118秒PASS,合成PCM/真实WASAPI自动80/160、手动/关闭/负值钳制/断流/重开,普通偏差13.2至18.3ms、突发预算500ms,非实体采集验收。
+
+实际构建 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root <root> -Preset x64-release`,最终 `logs/continuation-repair-20260910/audio-file-recovery-final-build.log` exit0。全部针对性测试经 `scripts/acceptance/scheduler-short-test.ps1 -Name <上述名称> -Exe out/build/x64-release/<test>.exe -TestArgs <result.args>`,stdout/stderr/result在 `logs/scheduler-repair-20260910/`。文件输入 `loop/local/fixed_clips/test_av_1080p.mp4` SHA `7952AD2904C8FED78402BC299EA2A04D1D869663EBCE17BBAC0C297F84FA2A91`;这只是历史目录内素材,不启用旧Loop。
+
+最终 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root <root>` 23项42.420秒PASS,`logs/delivery/5c80d299087b4f2482706bf2a24df9c9/result.json`。当前应用SHA `E2EA9CB93CB290E6B13683647835B3E7F54EA21810FC358D69DB803AA9168866`,worker不变 `EC8150FF88C7C84FACDF92B920DED2D6CEC5F682990C375A92550AFD5E818695`。实际RTX NR/NVOF、原生4K正确性、播放器、图片、NVENC H264/HEVC及取消已执行;例如overload日志CreateFeature18 `0x1`、handle非空,DLSSG Create `0x1`。不是AMD或实卡验证。未添加SDK/runtime/日志到Git,未push/发布。
+
+剩余边界:未在真实拔插/系统默认设备切换上测试,当前自动恢复针对已打开端点报告失效;仍可用的旧设备不会因默认设备变化主动切换。声卡突然消失时无法为已丢失设备播放淡出;可控设置/PTS突变前的短淡出仍需补齐。下一条唯一任务:处理可控音频重锚的短淡出与恢复边界,并对原方案逐项核对计时/重建覆盖。AMD完整网络/provider仍未实现,缺Developer Mode预览加载、权重与目标硬件实证;真实系统150%/200%DPI、实卡验收未完成。整体目标active。
+
### 最新续接:AMD预览运行时失败已定因
UI批次已本地存档 `ee46c5f`。继续AMD诊断:原隔离探针源码/EXE在 `logs/amd-nr-research-20260910/capability.*`,不是continuation日志目录。新增ignored `debug-capability.cpp` 只以 `DEBUG_ONLY_THIS_PROCESS` 启动该探针,读取其调试字符串,最长20秒;不附加其它进程、不装驱动、不改系统设置。编译命令 `cmd.exe /c logs\amd-nr-research-20260910\build-debug-capability.cmd` exit0。
diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.md
index 6bf8ea2a..805decf1 100644
--- a/docs/HANDOFF_2026-09-10.md
+++ b/docs/HANDOFF_2026-09-10.md
@@ -4,6 +4,10 @@
## 2026-09-11 当前可续接状态
+**当前优先读本段及实施记录最上方,后面的“下一条文件音频恢复”已完成软件闭环。** 基线`bba7283`后实现文件WASAPI owner线程重建、500ms重试、共享clock生命周期保护、断开时共同媒体时钟保持、最后有效PTS重锚、断开期间seek和暂停恢复。最终47项音频/7项真实player通过,原生4K过载/合成采集回归通过;delivery `5c80d299087b4f2482706bf2a24df9c9`23项42.420秒PASS,当前EXE `E2EA9CB93CB290E6B13683647835B3E7F54EA21810FC358D69DB803AA9168866`。具体命令、失败与身份见[实施记录](CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md)。未改系统默认设备、未实卡/AMD、未发布。
+
+下一条唯一任务:可控音频重锚的短淡出与边界(现有淡入已保留,突然拔掉硬件本身无法淡出),随后逐项审计原方案计时/reset覆盖。当前自动重连针对已打开端点失效,默认设备切换但旧端点仍可用时未主动迁移。AMD provider/权重/预览环境仍缺,150%/200%只是应用注入、真实系统高DPI与实卡未测。全目标保持active。
+
最新续接:UI批次已提交`ee46c5f`。AMD隔离probe已抓到准确loader原因:`Preview releases of D3D12Core require Developer Mode.`,测试`continuation-amd-debug-loader`exit1/0.088秒;这是运行时加载限制,尚未查询显卡能力。本轮未开Developer Mode,网络权重/provider/目标硬件依然欠缺。下一条独立任务改为文件音频设备恢复:`src/sink/WasapiAudioSink.cpp`的`runOnAudioThread`在pump失败直接退出;先处理renderer由引擎读clock与音频线程使用的所有权关系,再恢复,不能盲目shutdown造成竞态。AMD留为未完成,下面“下一步AMD”是本次诊断前状态;目标active。
**以本段为当前状态,下方“下一条全DPI”等是历史快照。** 在`db98af7`之后修复最小窗口状态区没有明细、设置滚轮跳过选择器、DPI字体变化与窄标题范围。新增真实进程UI脚本`python scripts/acceptance/ui-layout-dpi.py`,最终`ui-layout-1789065295999940200`PASS,96/144/192应用缩放、最小窗、展开/滚动/弹窗/连续resize/最大化/全屏/空视频黑色;真实Windows只测DPI96,不能宣称跨显示器150%/200%完成。绘制21项/popup14种/布局合同及真实FRUC->XeSS->DLSS->关闭通过。当前EXE SHA `27910DEDB2855334C45A0B92F4694542AB8631FB9AA17FED819E65585CC35C55`,构建`ui-dpi-build2.log`exit0;本轮未重跑联合delivery、NR或实卡。具体失败与证据见[实施记录最上方](CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md)。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index c0e2b0f9..8c7c89ea 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,7 @@
# 2026-09-11 继续修复目标模式执行中
+最新文件音频恢复:基线`bba7283`。修复pump失败退出音频线程和clock失效后视频转墙钟继续播放;文件端点改由音频owner创建/500ms重连/释放,clock读取与COM生命周期互斥,最后有效PTS重锚、断开期间seek更新目标、暂停预填不Start,状态区显示恢复/HRESULT/次数。最终音频47项2.628秒、真实player7项2.297秒PASS;原生4K过载5项及合成采集回归通过。首轮任意并发读取次数门槛失败已保留并改成验证实际并发生命周期,详见实施记录最上方。最终build `audio-file-recovery-final-build.log`exit0,delivery `5c80d299087b4f2482706bf2a24df9c9`23项42.420秒PASS,应用SHA `E2EA9CB93CB290E6B13683647835B3E7F54EA21810FC358D69DB803AA9168866`。RTX NR/NVOF/NVENC已实跑,未实卡/AMD/真实系统设备拔插。下一任务可控音频重锚短淡出与原方案剩余计时覆盖审计;AMD依赖/provider、高DPI实机和实卡未完成。整体目标active,本地存档,不发布。
+
最新AMD诊断(UI已经提交`ee46c5f`):隔离探针调试输出明确`Preview releases of D3D12Core require Developer Mode.`,随后CLSID_D3D12CoreModule获取失败;已解释先前0x887E0003,尚未到GPU能力查询。`continuation-amd-debug-loader`0.088秒exit1,完整stdout/result在`logs/scheduler-repair-20260910/`,只调试自有进程。未开开发者模式、未改主程序runtime、未提取权重。AMD完整网络/provider仍未实现。下一条独立任务转文件音频端点失败恢复,避免共享renderer shutdown与引擎clock读取竞态;详见实施记录最新段。整体目标active,不发布。
最新UI续接(优先于下方历史):基线`db98af7`。修复最小高度状态区无明细空间、90像素滚动跳过选择器、DPI切换字体14变15、窄标题绘制区域重叠;统一应用DPI,并只给smoke进程提供96/144/192注入。最终`ui-layout-1789065295999940200`三档布局/字体、最小窗口滚动、popup、滑条滚轮不变值、展开中间帧、resize、最大化/全屏进出/自动隐藏、黑色视频区PASS;实机系统DPI96,150%/200%仅应用注入,真实跨屏未测。首轮因FG选择器被滚动步长越过失败,证据保留。绘制21项、popup14种、UI合同通过;实际RTX后端UI`ui-fg-1789065217190095800`完成FRUC/XeSS/DLSS/关闭,DLSSG Create/Evaluate0x1。构建`ui-dpi-build2.log`exit0,EXE SHA `27910DEDB2855334C45A0B92F4694542AB8631FB9AA17FED819E65585CC35C55`。详见实施记录最新段的命令/日志/限制。本轮未跑NR、实卡、AMD或新的联合delivery;未改导出检查。下一任务AMD NR依赖/provider,整体目标active,本地存档不发布。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 58dcdab3..b70cb3d7 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -30,6 +30,7 @@ struct PlayerSnapshot {
std::wstring backendWarning;
sink::CaptureAudioState captureAudio;
bool audioRebuffering=false;
+ bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;
double position=0,duration=0,fps=0,lateMs=0,lateP95Ms=0;
diagnostics::FrameMetrics metrics;
std::optional<double> submissionFps;
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index c0d7597a..046221cd 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -72,8 +72,14 @@ public:
// Returns the PTS of the first buffered sample after seek.
double requestSeek(double targetMs);
- void runOnAudioThread(AudioRenderer* renderer);
- void startThread(AudioRenderer* renderer);
+ void runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint = false);
+ void startThread(AudioRenderer* renderer, bool ownEndpoint = false);
+ bool endpointRecovering()const{return endpointRecovering_.load();}
+ HRESULT endpointError()const{return endpointError_.load();}
+ uint64_t endpointRecoveries()const{return endpointRecoveries_.load();}
+ bool clockExhausted()const{return clockExhausted_.load();}
+ // Fault injection is consumed by the audio owner; never release COM on a caller thread.
+ void requestEndpointLossForTest(){endpointLossForTest_=true;}
private:
struct Segment {
@@ -123,6 +129,9 @@ private:
std::vector<float> converted_{std::vector<float>(kAudioRate)};
std::thread thread_;
+ std::atomic<bool> endpointRecovering_{false},clockExhausted_{false},endpointLossForTest_{false};
+ std::atomic<HRESULT> endpointError_{S_OK};
+ std::atomic<uint64_t> endpointRecoveries_{0};
};
class AudioRenderer {
@@ -132,7 +141,7 @@ public:
void setGain(float value){gain_.store(value);}
// Write actual PCM before starting the endpoint and its media clock.
- bool startAnchored(AudioPcmSource& pipeline);
+ bool startAnchored(AudioPcmSource& pipeline, bool paused = false);
void setPaused(bool value);
// Event-driven pump for ONE event cycle. Writes real data when the ring
@@ -153,13 +162,15 @@ public:
uint64_t framesWritten() const;
HRESULT lastError()const{return lastError_.load();}
double bufferedMs()const{return bufferedMs_.load();}
- double capacityMs()const{return 1000.0*bufferFrames_/sampleRate_;}
+ double capacityMs()const{std::lock_guard lock(endpointMutex_);return 1000.0*bufferFrames_/sampleRate_;}
void shutdown();
private:
- bool checked(HRESULT hr,const char* operation){if(SUCCEEDED(hr))return true;lastError_=hr;log::error("audio",std::format("{} hr=0x{:08X}",operation,unsigned(hr)));return false;}
- std::atomic<HRESULT> lastError_{S_OK};
+ bool checked(HRESULT hr,const char* operation)const{if(SUCCEEDED(hr))return true;if(lastError_.exchange(hr)!=hr)log::error("audio",std::format("{} hr=0x{:08X}",operation,unsigned(hr)));return false;}
+ mutable std::atomic<HRESULT> lastError_{S_OK};
+ // Protect endpoint lifetime/anchor from readers; pump remains audio-owner only.
+ mutable std::mutex endpointMutex_;
std::atomic<double> bufferedMs_{0};
mutable std::mutex timelineMutex_;
AudioFrameTimeline outputTimeline_;
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 63246f91..af2fe3f4 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -151,6 +151,17 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
std::array<uint64_t,size_t(diagnostics::GpuStage::Count)> lastGpuSampleEnd{};
auto nextTimingLog=Clock::now()+std::chrono::seconds(1);
auto anchor=Clock::now(),statsStart=anchor;double anchorMs=0;uint64_t frames=0,sourceFrames=0;bool wasPaused=false;double discardBefore=0;
+ double lastAudioClockMs=0;bool audioClockExhausted=false;auto audioTailAnchor=anchor;
+ bool publishedAudioRecovery=false;HRESULT publishedAudioError=S_OK;uint64_t publishedAudioRecoveries=0;
+ const bool injectFileEndpointLoss=GetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",nullptr,0)>0;
+ bool fileEndpointLossInjected=false;
+ auto publishAudioStatus=[&]{
+ const bool recovering=audioPipe.endpointRecovering();const auto error=audioPipe.endpointError();const auto count=audioPipe.endpointRecoveries();
+ if(recovering!=publishedAudioRecovery||error!=publishedAudioError||count!=publishedAudioRecoveries){
+ publishedAudioRecovery=recovering;publishedAudioError=error;publishedAudioRecoveries=count;
+ std::lock_guard lock(mutex_);snapshot_.audioEndpointRecovering=recovering;snapshot_.audioEndpointError=error;snapshot_.audioEndpointRecoveries=count;
+ }
+ };
PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;
DeadlineWait deadlineWait;
CaptureHalfRate captureSampler;
@@ -216,6 +227,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const bool injectSourceGap=options.captureReplayForTest&&GetEnvironmentVariableW(L"VEYRA_TEST_REPLAY_SOURCE_GAP",nullptr,0)>0;
std::optional<Clock::time_point> sourceGapUntil;
while(!stop_){
+ if(audioStarted)publishAudioStatus();
+ if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}
advanceLive();
if(liveScheduler&&liveScheduler->failed()){status(L"采集画面呈现失败,请查看诊断",true);break;}
const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);
@@ -268,7 +281,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
const double seek=seekSeconds_.exchange(-1);
if(seek>=0&&!isImage&&!isCapture){
if(!ring.drainQueue()||!activeSource->seek({static_cast<int64_t>(seek*1000000),1000000})){status(L"跳转失败",true);break;}
- discardBefore=seek*1000;seekPreviewPending=true;reset=true;anchorMs=discardBefore;anchor=Clock::now();audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
+ discardBefore=seek*1000;seekPreviewPending=true;reset=true;anchorMs=discardBefore;anchor=Clock::now();lastAudioClockMs=discardBefore;audioClockExhausted=false;audioRebuffering=false;if(audioStarted){audioPipe.setPaused(paused_);audioPipe.requestSeek(discardBefore);}
}
if(!transaction&&((paused_&&!seekPreviewPending)||(isImage&&hasOutput))){
drainLivePresentation();
@@ -404,8 +417,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
veyra::log::info("capture-timeline",std::format("interval100ns={} packetDurationKnown={} packetDurationPositive={} nominalFps={} FG={}",duration100ns,!pkt.duration.isUnknown(),pkt.duration.num>0,activeSource->info().averageFps,options.fg));
liveTimeline.reset(out.batch.identity.epoch,out.batch.b100ns,captureArrival,options.fg?duration100ns:0);
}
- if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)&&audio.start()){audioPipe.startThread(&audio);audioStarted=true;{std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;}}anchor=Clock::now();anchorMs=pts;}
- auto nowMs=[&](){const double a=audioStarted?audio.mediaTimeMs():-1;return a>=0?a:anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();};
+ if(!audioStarted&&!isImage&&!isCapture&&frames==0){if(audioPipe.open(path)){audioPipe.startThread(&audio,true);audioStarted=true;{std::lock_guard lock(mutex_);snapshot_.audioAvailable=true;}}anchor=Clock::now();anchorMs=lastAudioClockMs=pts;}
+ auto nowMs=[&](){
+ if(!audioStarted)return anchorMs+std::chrono::duration<double,std::milli>(Clock::now()-anchor).count();
+ publishAudioStatus();const double a=audio.mediaTimeMs();
+ if(std::isfinite(a)){lastAudioClockMs=a;audioClockExhausted=false;return a;}
+ // A disconnected endpoint freezes the shared media clock. Only a
+ // fully exhausted audio stream may hand its tail to the wall clock.
+ if(audioPipe.clockExhausted()){
+ if(!audioClockExhausted){audioClockExhausted=true;audioTailAnchor=Clock::now();}
+ return lastAudioClockMs+std::chrono::duration<double,std::milli>(Clock::now()-audioTailAnchor).count();
+ }
+ return lastAudioClockMs;
+ };
double frameWaitMs=0,framePresentMs=0;
double gpuWaitMs=0;
if(liveScheduler){
@@ -561,7 +585,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options){
}catch(const std::exception& e){veyra::log::error("engine",e.what());status(L"引擎异常,请查看诊断",true);failed=true;}
(void)failed;
audioPipe.stopThread();audio.shutdown();ring.drainQueue();presenter.close();graph.shutdown();captureSource.close();source.close();av_frame_free(&cachedFrame);av_frame_free(&imageFrame);ring.shutdown();ctx.shutdown();
- {std::lock_guard lock(mutex_);snapshot_.running=false;}
+ {std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.audioEndpointRecovering=false;snapshot_.audioRebuffering=false;}
CoUninitialize();
}
}
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index 9368d7d9..ef4572b1 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -264,10 +264,12 @@ void AudioPipeline::closeAll()
bool AudioRenderer::start()
{
+ std::lock_guard endpointLock(endpointMutex_);
if(client_||enum_)return checked(E_UNEXPECTED,"Endpoint already initialized");
lastError_=S_OK;bufferedMs_=0;smoothedGain_=0;
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
comInited_ = SUCCEEDED(hr);
+ if(FAILED(hr)&&hr!=RPC_E_CHANGED_MODE)return checked(hr,"Initialize COM");
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&enum_));
if (!checked(hr,"Create MMDeviceEnumerator")) return false;
@@ -307,18 +309,19 @@ bool AudioRenderer::start()
return true;
}
-bool AudioRenderer::startAnchored(AudioPcmSource& pipeline)
+bool AudioRenderer::startAnchored(AudioPcmSource& pipeline, bool paused)
{
+ std::lock_guard endpointLock(endpointMutex_);
double firstBufferPtsMs = -1;
if (!pumpOnce(pipeline, &firstBufferPtsMs) || framesWritten_ == 0) return false;
UINT64 pos = 0, qpc = 0;
if (!checked(clock_->GetPosition(&pos, &qpc),"Anchor GetPosition") || !clockFrequency_) return false;
anchorPos_ = pos;
anchorPtsMs_.store(firstBufferPtsMs);
- if (!checked(client_->Start(),"Start")) return false;
+ if (!paused && !checked(client_->Start(),"Start")) return false;
started_ = true;
- veyra::log::info("audio", std::format("renderer STARTED anchored ptsMs={:.1f} devicePos={} freq={}",
- firstBufferPtsMs, pos, clockFrequency_));
+ veyra::log::info("audio", std::format("renderer ANCHORED ptsMs={:.1f} devicePos={} freq={} paused={}",
+ firstBufferPtsMs, pos, clockFrequency_,paused));
return true;
}
@@ -383,9 +386,10 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs
double AudioRenderer::mediaTimeMs() const
{
+ std::lock_guard endpointLock(endpointMutex_);
if (!running_ || !started_) return std::numeric_limits<double>::quiet_NaN();
UINT64 pos = 0, qpc = 0;
- if (FAILED(clock_->GetPosition(&pos, &qpc)) || clockFrequency_ == 0) {
+ if (!checked(clock_->GetPosition(&pos, &qpc),"Clock GetPosition") || clockFrequency_ == 0) {
return std::numeric_limits<double>::quiet_NaN();
}
const double consumedMs = 1000.0 * static_cast<double>(pos - anchorPos_) /
@@ -400,6 +404,7 @@ double AudioRenderer::mediaTimeMs() const
void AudioRenderer::stopAndReset()
{
+ std::lock_guard endpointLock(endpointMutex_);
started_ = false;
if (client_) { checked(client_->Stop(),"Stop for reset");checked(client_->Reset(),"Reset"); }
framesWritten_ = 0;
@@ -414,6 +419,7 @@ uint64_t AudioRenderer::framesWritten() const { return framesWritten_; }
void AudioRenderer::shutdown()
{
+ std::lock_guard endpointLock(endpointMutex_);
if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
#define REL(x) if (x) { x->Release(); x = nullptr; }
REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);
@@ -429,14 +435,45 @@ void AudioRenderer::shutdown()
void AudioRenderer::setPaused(bool value)
{
+ std::lock_guard endpointLock(endpointMutex_);
if (!client_ || !started_) return;
- const HRESULT hr = value ? client_->Stop() : client_->Start();
- if (FAILED(hr)) veyra::log::error("audio", std::format("pause/resume failed hr=0x{:X}", static_cast<unsigned>(hr)));
+ checked(value ? client_->Stop() : client_->Start(),"Pause/resume");
}
-void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
+void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
{
const auto t0 = std::chrono::steady_clock::now();
+ bool endpointReady = renderer && (!ownEndpoint || renderer->start());
+ double lastClockMs = 0, recoveryTargetMs = 0;
+ auto retryAt = t0;
+ auto recovering = [&](HRESULT error) {
+ endpointError_ = FAILED(error) ? error : E_FAIL;
+ endpointRecovering_ = true;
+ recoveryTargetMs = lastClockMs;
+ endpointReady = false;
+ if (ownEndpoint) renderer->shutdown();
+ retryAt = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
+ log::warn("audio-recovery",std::format("endpoint unavailable hr=0x{:08X} holdPtsMs={:.3f}",unsigned(endpointError_.load()),recoveryTargetMs));
+ };
+ auto rewind = [&](double target) {
+ {
+ std::lock_guard lock(mutex_);
+ ring_.clear();ringFrames_=0;segments_.clear();
+ if(havePacket_){av_packet_unref(packet_);havePacket_=false;}
+ avcodec_flush_buffers(codecCtx_);
+ if(swr_)swr_free(&swr_);
+ const int64_t tbTarget=static_cast<int64_t>(target*stream_->time_base.den/1000/stream_->time_base.num);
+ const int result=avformat_seek_file(fmt_,streamIndex_,INT64_MIN,tbTarget,INT64_MAX,0);
+ if(result<0){log::error("audio",std::format("seek failed code={}",result));clockExhausted_=false;return false;}
+ demuxEof_=drainSent_=false;decodedEof_=false;
+ nextPtsMs_=target;discardUntilPtsMs_=target;
+ }
+ decodeBlock();
+ discardUntilPtsMs_=-1;
+ clockExhausted_=decodedEof_&&headPtsMs()<0;
+ return true;
+ };
+ if(renderer&&ownEndpoint&&!endpointReady)recovering(renderer->lastError());
// Initial prefill (open case).
{
std::unique_lock<std::mutex> lock(mutex_);
@@ -451,18 +488,28 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
}
}
const double firstPts = headPtsMs();
- if (renderer != nullptr && firstPts >= 0.0) {
- if (!renderer->startAnchored(*this)) log::error("audio", "initial endpoint prefill/start failed");
+ clockExhausted_=decodedEof_&&firstPts<0;
+ if (endpointReady && firstPts >= 0.0) {
+ if (!renderer->startAnchored(*this,paused_)) recovering(renderer->lastError());
+ else endpointRecovering_=false;
}
lastPrefillMs_.store(std::chrono::duration<double>(
std::chrono::steady_clock::now() - t0).count() * 1000.0);
veyra::log::info("audio", std::format("startup prefill done in {:.0f}ms firstPtsMs={:.1f} bufferedMs={:.0f}",
lastPrefillMs_.load(), firstPts, bufferedMs()));
- bool pauseApplied = false;
+ bool pauseApplied = paused_;
while (!stopFlag_.load()) {
const bool pauseNow = paused_.load();
- if (pauseNow != pauseApplied && renderer) renderer->setPaused(pauseNow);
+ if(endpointReady){
+ const double current=renderer->mediaTimeMs();
+ if(std::isfinite(current))lastClockMs=current;
+ if(ownEndpoint&&endpointLossForTest_.exchange(false)){
+ log::info("audio-recovery-test","release own endpoint on its audio thread; no system device change");
+ recovering(AUDCLNT_E_DEVICE_INVALIDATED);
+ }else if(ownEndpoint&&FAILED(renderer->lastError()))recovering(renderer->lastError());
+ }
+ if (pauseNow != pauseApplied && endpointReady) renderer->setPaused(pauseNow);
pauseApplied = pauseNow;
// Seek request? Atomic re-sequence.
{
@@ -472,32 +519,15 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
const double target = seekTargetMs_;
seekCount_.fetch_add(1);
lock.unlock();
- if (renderer != nullptr) renderer->stopAndReset();
- {
- std::lock_guard<std::mutex> l2(mutex_);
- ring_.clear();
- ringFrames_ = 0;
- segments_.clear();
- if (havePacket_) { av_packet_unref(packet_); havePacket_ = false; }
- avcodec_flush_buffers(codecCtx_);
- if (swr_) swr_free(&swr_);
- const int64_t tbTarget = static_cast<int64_t>(
- target * stream_->time_base.den / 1000 / stream_->time_base.num);
- const int seekResult = avformat_seek_file(fmt_, streamIndex_, INT64_MIN, tbTarget, INT64_MAX, 0);
- if (seekResult < 0) log::error("audio", std::format("seek failed code={}", seekResult));
- demuxEof_ = false;
- drainSent_ = false;
- decodedEof_ = false;
- nextPtsMs_ = target;
- discardUntilPtsMs_ = target;
- }
- decodeBlock(); // drops pts < target, fills to high watermark
- double startPts = headPtsMs();
- if (startPts < 0.0) startPts = target;
+ if (endpointReady) renderer->stopAndReset();
+ lastClockMs=recoveryTargetMs=target;
+ const bool seekOk=rewind(target);
+ double startPts = seekOk?headPtsMs():std::numeric_limits<double>::quiet_NaN();
+ if (seekOk&&startPts < 0.0) startPts = target;
firstPtsAfterSeek_.store(startPts);
- if (renderer != nullptr) {
- if (!renderer->startAnchored(*this)) log::error("audio", "seek endpoint prefill/start failed");
- if (pauseNow) renderer->setPaused(true);
+ if(!seekOk&&renderer)recovering(E_FAIL);
+ if (seekOk&&endpointReady && !clockExhausted_) {
+ if (!renderer->startAnchored(*this,pauseNow)) recovering(renderer->lastError());
}
{
std::lock_guard<std::mutex> l2(mutex_);
@@ -510,13 +540,29 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
continue;
}
}
+ if(renderer&&ownEndpoint&&!endpointReady){
+ if(clockExhausted_){endpointRecovering_=false;}
+ else if(std::chrono::steady_clock::now()>=retryAt){
+ if(renderer->start()){
+ endpointReady=true;
+ const bool rewound=rewind(recoveryTargetMs);
+ if(rewound&&(clockExhausted_||renderer->startAnchored(*this,pauseNow))){
+ endpointRecovering_=false;++endpointRecoveries_;
+ log::info("audio-recovery",std::format("restored mediaPtsMs={:.3f} paused={} recoveries={}",recoveryTargetMs,pauseNow,endpointRecoveries_.load()));
+ }else recovering(renderer->lastError());
+ }else recovering(renderer->lastError());
+ }
+ std::unique_lock lock(mutex_);
+ wake_.wait_for(lock,std::chrono::milliseconds(5),[&]{return stopFlag_||seekRequested_;});
+ continue;
+ }
if (pauseNow) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; }
// Regular cycle: pump the endpoint, then top up below high watermark.
if (renderer != nullptr) {
double firstPts = -1.0;
if (!renderer->pumpOnce(*this, &firstPts)) {
- veyra::log::error("audio", "pumpOnce failed");
- break;
+ if(!ownEndpoint){log::error("audio","pumpOnce failed");break;}
+ recovering(renderer->lastError());continue;
}
}
if (bufferedMs() < kAudioHighWatermarkMs) {
@@ -529,11 +575,13 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
+ if(renderer&&ownEndpoint)renderer->shutdown();
}
-void AudioPipeline::startThread(AudioRenderer* renderer)
+void AudioPipeline::startThread(AudioRenderer* renderer, bool ownEndpoint)
{
- thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer);
+ endpointRecovering_=renderer&&ownEndpoint;endpointError_=S_OK;endpointRecoveries_=0;clockExhausted_=false;
+ thread_ = std::thread(&AudioPipeline::runOnAudioThread, this, renderer, ownEndpoint);
}
} // namespace veyra::sink
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
index fd05cf65..c30931cb 100644
--- a/tests/integration/AudioTimelineTests.cpp
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -18,10 +18,10 @@ bool until(const std::function<bool()>& ready) {
while (!ready() && std::chrono::steady_clock::now() < limit) std::this_thread::sleep_for(2ms);
return ready();
}
-void fixture(const std::filesystem::path& file, uint32_t rate) {
+void fixture(const std::filesystem::path& file, uint32_t rate, unsigned durationMs=750) {
std::ofstream out(file, std::ios::binary);
auto word = [&](uint32_t v, unsigned bytes) { for (unsigned i=0;i<bytes;++i) out.put(char(v >> (8*i))); };
- const uint32_t frames = rate * 3 / 4;
+ const uint32_t frames = rate * durationMs / 1000;
out.write("RIFF",4); word(36+frames*2,4); out.write("WAVEfmt ",8); word(16,4);
word(1,2); word(1,2); word(rate,4); word(rate*2,4); word(2,2); word(16,2);
out.write("data",4); word(frames*2,4);
@@ -97,5 +97,42 @@ int wmain(int argc, wchar_t** argv) {
while(std::chrono::steady_clock::now()-recovery<100ms){double pts=0;if(!renderer.pumpOnce(live,&pts))break;}
const double recovered=renderer.mediaTimeMs();
check(std::isfinite(recovered)&&recovered>=500&&recovered<=live.pts,"recovered live clock references new PCM after device silence");
- renderer.shutdown(); return failures ? 1 : 0;
+ renderer.shutdown();
+ const auto longFile=dir/"recovery.wav";fixture(longFile,48000,4000);
+ AudioPipeline recoveryPipe;AudioRenderer recoveryRenderer;recoveryRenderer.setGain(0);
+ check(recoveryPipe.open(longFile.wstring()),"open recovery PCM fixture");
+ recoveryPipe.startThread(&recoveryRenderer,true);
+ check(until([&]{return recoveryRenderer.started()&&!recoveryPipe.endpointRecovering();}),"audio thread owns endpoint initialization");
+ std::atomic<bool> reading=true;std::atomic<uint64_t> reads=0;
+ std::thread reader([&]{while(reading){(void)recoveryRenderer.mediaTimeMs();++reads;std::this_thread::sleep_for(1ms);}});
+ std::this_thread::sleep_for(100ms);
+ const double beforeLoss=recoveryRenderer.mediaTimeMs();
+ recoveryPipe.requestEndpointLossForTest();
+ check(until([&]{return recoveryPipe.endpointRecovering();}),"endpoint loss publishes recovery state");
+ check(!std::isfinite(recoveryRenderer.mediaTimeMs()),"released endpoint clock is invalid during retry");
+ check(recoveryPipe.endpointError()==AUDCLNT_E_DEVICE_INVALIDATED,"endpoint HRESULT remains available");
+ check(until([&]{return recoveryPipe.endpointRecoveries()==1&&!recoveryPipe.endpointRecovering();}),"endpoint reopens without exiting audio thread");
+ const double restored=recoveryRenderer.mediaTimeMs();
+ std::cout<<"recovery before="<<beforeLoss<<" restored="<<restored<<'\n';
+ check(restored>=beforeLoss-30&&restored<=beforeLoss+50,"recovery replays from last clock, not decoded-ahead head");
+ recoveryPipe.setPaused(true);std::this_thread::sleep_for(70ms);
+ recoveryPipe.requestEndpointLossForTest();
+ check(until([&]{return recoveryPipe.endpointRecovering();}),"paused endpoint loss is detected");
+ const double seekRecovered=recoveryPipe.requestSeek(1234.25);
+ check(std::abs(seekRecovered-1234.25)<.05,"seek while disconnected updates recovery PTS");
+ check(until([&]{return recoveryPipe.endpointRecoveries()==2&&!recoveryPipe.endpointRecovering();}),"paused endpoint reconnects");
+ const double pausedRecovered=recoveryRenderer.mediaTimeMs();std::this_thread::sleep_for(100ms);
+ check(std::abs(pausedRecovered-1234.25)<.1&&std::abs(recoveryRenderer.mediaTimeMs()-pausedRecovered)<.1,"reconnect does not start paused PCM");
+ recoveryPipe.setPaused(false);
+ check(until([&]{return recoveryRenderer.mediaTimeMs()>pausedRecovered+50;}),"resume after reconnect advances real endpoint clock");
+ recoveryPipe.requestEndpointLossForTest();
+ check(until([&]{return recoveryPipe.endpointRecovering();}),"third loss enters retry");
+ const auto stopping=std::chrono::steady_clock::now();recoveryPipe.stopThread();
+ check(std::chrono::steady_clock::now()-stopping<300ms,"stop interrupts endpoint retry promptly");
+ reading=false;reader.join();
+ std::cout<<"concurrentClockReads="<<reads.load()<<'\n';
+ check(reads>10&&!std::isfinite(recoveryRenderer.mediaTimeMs()),"concurrent clock readers survive endpoint releases and shutdown");
+ check(recoveryPipe.overruns()==0,"endpoint outages preserve bounded file PCM queue");
+ recoveryRenderer.shutdown();
+ return failures ? 1 : 0;
}
diff --git a/tests/integration/LivePresentationTests.cpp b/tests/integration/LivePresentationTests.cpp
index cdd5613a..9d0a551b 100644
--- a/tests/integration/LivePresentationTests.cpp
+++ b/tests/integration/LivePresentationTests.cpp
@@ -9,7 +9,7 @@ using namespace veyra;
using namespace std::chrono_literals;
int wmain(int argc,wchar_t**argv){
SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",L"1");
- if(argc!=3&&!(argc==4&&(wcscmp(argv[3],L"--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);
+ 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||wcscmp(argv[3],L"--file-endpoint")==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;
@@ -19,6 +19,8 @@ int wmain(int argc,wchar_t**argv){
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;
+ const bool fileEndpoint=argc==4&&wcscmp(argv[3],L"--file-endpoint")==0;
+ if(fileEndpoint){options.captureReplayForTest=false;SetEnvironmentVariableW(L"VEYRA_TEST_FILE_ENDPOINT_LOSS",L"1");engine.setVolume(0,true);}
if(argc==4&&wcscmp(argv[3],L"--fruc")==0)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;
if(overload){options.nr=options.sr=options.fg=true;options.realtime=false;options.fgMultiplier=4;options.settings.videoSrQuality=4;options.captureReplayDisableFgAdmissionForTest=std::wstring(argv[3]).ends_with(L"-baseline");SetEnvironmentVariableW(L"VEYRA_VERBOSE_FRAME_LOGS",nullptr);}
if(frucOverload)options.settings.frameGenerationBackend=engine::FrameGenerationBackend::Fruc;
@@ -27,6 +29,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(fileEndpoint){
+ check(until([](const auto& s){return s.frames>=20&&s.audioEndpointRecovering;}),"actual player exposes endpoint recovery");
+ const auto held=engine.snapshot();
+ std::this_thread::sleep_for(300ms);const auto stillHeld=engine.snapshot();
+ check(stillHeld.frames<=held.frames+2&&stillHeld.position<=held.position+.04,"video timeline stays held during audio endpoint outage");
+ check(until([](const auto& s){return s.audioEndpointRecoveries==1&&!s.audioEndpointRecovering&&s.frames>=50;}),"player resumes after endpoint reanchor");
+ check(std::abs(engine.snapshot().lateMs)<30,"restored software A/V skew under 30ms");
+ engine.pause(true);engine.seek(.5);
+ check(until([](const auto& s){return s.transport==engine::TransportState::Paused&&s.position>=.49&&s.position<.6;}),"paused seek after endpoint recovery");
+ const auto pausedFrames=engine.snapshot().frames;engine.pause(false);
+ check(until([&](const auto& s){return s.frames>=pausedFrames+10;}),"resume after recovered paused seek");
+ engine.stop();check(until([&](const auto&){return engine.idle();},5),"recovered file closes without audio thread deadlock");
+ DestroyWindow(window);CoUninitialize();return failures?1:0;
+ }
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");