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: correct capture audio drift and map real PCM playback time
Veyra Goal Agent18211208ec98
diff --git a/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.md b/docs/CONTINUATION_REPAIR_IMPLEMENTATION_2026-09-10.mdindex b7b7bd31..23b1371a 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 续接实证(优先于下面历史进度)+### 最新续接:采集时钟漂移与真实PCM播放位置++基线本地提交`ed5aed3`。本轮仅合成PCM/PTS与静音WASAPI测试,没有打开实体采集卡、修改系统默认音频设备或发布。++- 增加有界`AudioFrameTimeline`,分别记录重采样输出样本对应的源媒体起止PTS,以及写入WASAPI的位置。播放时钟从实际IAudioClock位置查找媒体时间,不能继续把每个48k输出样本当作固定长度源媒体样本。未写入区域、设备断粮后及reset后没有虚构的有效媒体时钟;恢复时越过设备实际消耗的静音区间。+- 自动模式每250ms低通观测音画误差,`swr_set_compensation`最多正负5000ppm、每次变化最多250ppm;突变大于60ms保留重锚。模式/端点重置清除补偿。PCM持续转换保留swr前后delay并建立分段媒体映射,软件总队列预算仍500ms。+- 候选回归确实失败:`continuation-audio-drift-prefill-normal`关闭/零补偿误差约53.8ms。事件等待在PCM转换后,等待期间到达的PCM不能参与此次填充;采集路径又把所有剩余设备空位补成静音,插入额外延迟。修正为先等事件再收集PCM、避免启动后立即重复填充、采集仅提交已有真实PCM,文件路径保留原欠载策略。初始只改预填和等待并未解决,相关失败日志完整保留。+- 测试端普通`std::this_thread::sleep_until`的10ms回调受Windows定时粒度影响;改为独立高精度waitable timer,不改系统定时器或验收阈值。设备时钟QPC采样年龄诊断约0.001ms以内,排除读取旧时钟假设,临时逐次诊断已移除。+- `continuation-audio-drift-final-normal`11.112秒PASS:自动80/160、手动100、关闭、负值钳制、350ms断流与重开;最终关闭/零补偿误差23.36/23.41ms,自动/手动误差18.10至22.67ms。突发high-water500ms、overflow11,普通模式0overflow。关闭同步不代表消除声卡/系统固有延迟。+- `continuation-audio-drift-final-loss`3.573秒PASS:释放测试自有端点后恢复,retries2、平均软件偏差12.22ms、0overflow。`continuation-audio-drift-final-timeline`1.082秒PASS:44.1/48k文件各36000输出样本、seek/pause、真实WASAPI半速媒体映射、断粮clock失效与恢复新PCM。`continuation-audio-drift-final-contract`70项PASS、0.069秒。+- 最终同一EXE `continuation-audio-drift-final-fast`119.757秒、`continuation-audio-drift-final-slow`119.998秒均PASS:源时钟正负1000ppm,P95偏差分别4.242/4.302ms,两项missing0、仅首次reset1、overflow0、high-water89.65ms。中间候选`continuation-audio-gap-slow`120.002秒P95为4.297ms(EXE `3D334D7A9BC81726676B25BA8ED58A46608018B2886259238C9A4ECF741C5DE2`),仅保留追溯,以最终同EXE结果为准。+- 最新构建`build-audio-drift-final.log`exit0。采集测试EXE `7D9FEF157E2EE871544A6B312CDC4CBBD9EF9A340322B4B6B44FC7C7DF8DA1AB`,worker仍`EC8150FF88C7C84FACDF92B920DED2D6CEC5F682990C375A92550AFD5E818695`。所有短测由`scripts/acceptance/scheduler-short-test.ps1 -Name <以上名称> -Exe out/build/x64-release/<test>.exe -TestArgs <参数>`执行;普通无参数,设备恢复`--endpoint-loss`,漂移`--drift-slow`/`--drift-fast`。完整result/stdout/stderr在`logs/scheduler-repair-20260910/`,构建在`logs/continuation-repair-20260910/`。++最终联合命令`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root <root>`23项PASS、42.484秒,`logs/delivery/c41ad55982e6448190d1bc4ed239a415/result.json`;应用EXE SHA `FDA98B226562C55B44A8139E1A4D7F3F35A7458109AC8ED4F72FD6ACE755D6BE`。实际执行RTX NR/NVOF、原生4K正确性、播放器、图片、NVENC H264/HEVC及取消;未改导出检查。NR runtime固定SHA再次核对一致、签名Valid。`git diff --check`通过,SDK/runtime/日志没有加入源码。++本轮音频软件回归通过,整体目标仍active。下一条任务为逐帧GPU时间戳交付:已确认`GpuTimer::collect`可能一次收回多帧而上层`last()`只消费最新一帧,需逐帧交付完成样本并保持revision/epoch隔离;随后继续单GPU所有者调度。AMD NR依赖/provider、UI完整DPI、实体采集验收仍未完成。旧Loop不启用、无push/发布。音频只证明本机合成输入的软件估算同步,不是实卡听觉/屏幕扫描验收;手动/关闭模式未启用漂移补偿、突变短淡出和文件设备自动恢复仍有限制。+### 最新续接:采集音频总预算与输出设备恢复基线`8b36b4c`,工作树原先干净。本轮仍未打开实体采集设备,不修改默认系统音频设备、不发布。diff --git a/docs/HANDOFF_2026-09-10.md b/docs/HANDOFF_2026-09-10.mdindex 761ca126..8458c3a1 100644--- a/docs/HANDOFF_2026-09-10.md+++ b/docs/HANDOFF_2026-09-10.md@@ -4,6 +4,8 @@## 2026-09-11 当前可续接状态+当前优先续接:`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漂移失败是本轮修复前基线。+最新音频续接:raw/转换中/PCM统一500ms上限,突发与正常/断流回归通过;WASAPI错误真实记录、有限频率重连及自有端点故障测试通过,设备padding单列。最终联合delivery `0325b097b61a42b0becf6dc71a900175`23项42.43秒通过,EXE `1136543C02604020F877BAA8BE0F67442671DFC7805FBB28310CD57B2D3E8FC6`。新增120秒源时钟-1000ppm测试失败P95 31.73ms,仍靠间歇reset;下一任务必须实现平滑漂移校正和重采样后正确媒体时钟,不能拿联合短测覆盖此失败。详见实施记录最新音频段,目标active,未实卡/未发布。最新续接覆盖下方旧计数/哈希:前序已本地存档`6316376`;音频-only设置隔离、重复请求消除、排空后合并最新设置已修;生成帧A/B真实到达关系与三项独立延迟加入状态。FRUC跳过恢复新GT暴露source parity覆盖旧CUDA输入,已改按实际SDK调用轮转,2/3/4X通过并重新启用采集admission。同源原生4K NR+VSR4+FRUC4过载:450无收益Evaluate→450提交前skip,源处理12→33fps,两组均0有效生成呈现,非4X实时或内核提速。合同66/live29/FRUC24和最终delivery23通过,run `f024e12327b5429593e762943abb2eca`,EXE `D3E8736F9D0ADD088B0CEA5FE8C979B99820745467CA7743654A93687EF24823`。详细失败/命令/worker哈希见实施记录最新段。下一条任务为音频漂移与PCM总容量/端点恢复;单GPU所有者和AMD网络仍待做,未实卡/未发布。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 581877c5..7ac3e1df 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,7 @@# 2026-09-11 继续修复目标模式执行中+最新漂移续接(覆盖下面旧结论):在`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完整验收仍未完成。+最新音频续接(优先于下方):统一raw+转换中+PCM总预算500ms,突发600块high-water500ms通过;WASAPI实际HRESULT诊断、500ms重连、自有端点释放恢复及首缓冲淡入接入,正常11.12秒/故障3.59秒/文件时钟0.523秒测试通过。联合delivery `0325b097b61a42b0becf6dc71a900175`23项42.43秒PASS,应用SHA `1136543C02604020F877BAA8BE0F67442671DFC7805FBB28310CD57B2D3E8FC6`。但新增120秒-1000ppm漂移测试exit1,P95偏差31.73ms、3次额外重锚;长期平滑同步未完成,失败完整保留。下一任务为漂移重采样及播放PTS映射,详见实施记录最新段。没有打开实卡或操作系统默认音频设备,未push/发布。## 最新续接:设置隔离、生成帧关系与FRUC过载筛选diff --git a/include/veyra/sink/AudioFrameTimeline.h b/include/veyra/sink/AudioFrameTimeline.hnew file mode 100644index 00000000..5d909133--- /dev/null+++ b/include/veyra/sink/AudioFrameTimeline.h@@ -0,0 +1,28 @@+#pragma once+#include <algorithm>+#include <cmath>+#include <cstdint>+#include <deque>+#include <optional>++namespace veyra::sink {+// Piecewise media time for resampled PCM. Frame positions refer to output+// samples, while endpoints retain the original source timeline.+class AudioFrameTimeline {+ struct Span {uint64_t first,count;double begin,end;};+ std::deque<Span> spans_;+public:+ void clear(){spans_.clear();}+ void append(uint64_t first,uint64_t count,double begin,double end){+ if(!count||!std::isfinite(begin)||!std::isfinite(end)||end<begin)return;+ spans_.push_back({first,count,begin,end});+ while(spans_.size()>1024)spans_.pop_front();+ }+ std::optional<double> at(double frame)const{+ for(const auto& s:spans_)if(frame>=s.first&&frame<=s.first+s.count)+ return s.begin+(s.end-s.begin)*(frame-s.first)/s.count;+ return {};+ }+ void discardBefore(uint64_t frame){while(!spans_.empty()&&spans_.front().first+spans_.front().count<frame)spans_.pop_front();}+};+}diff --git a/include/veyra/sink/AudioPcmSource.h b/include/veyra/sink/AudioPcmSource.hindex 1fca53cb..19b720d0 100644--- a/include/veyra/sink/AudioPcmSource.h+++ b/include/veyra/sink/AudioPcmSource.h@@ -1,9 +1,12 @@#pragma once#include <cstddef>+#include <optional>namespace veyra::sink {class AudioPcmSource {public:virtual ~AudioPcmSource() = default;virtual size_t pull(float* stereo, size_t frames, double* firstPtsMs) = 0;+ virtual std::optional<double> lastPullEndPtsMs()const{return {};}+ virtual bool padUnderruns()const{return true;}};}diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.hindex b9bc4df8..b63236c4 100644--- a/include/veyra/sink/CaptureAudioSession.h+++ b/include/veyra/sink/CaptureAudioSession.h@@ -9,6 +9,7 @@ namespace veyra::sink {struct CaptureAudioState {bool available=false,running=false,clockEstimated=true,limited=false;double compensationMs=0,bufferedMs=0,bufferHighWaterMs=0,endpointBufferedMs=0;+ double driftCorrectionPpm=0;std::optional<double> skewMs;uint64_t resets=0,overflows=0,underruns=0,endpointRetries=0;std::wstring error;diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex 81201675..c0d7597a 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -21,6 +21,7 @@#include "veyra/Log.h"#include "veyra/sink/AudioPcmSource.h"+#include "veyra/sink/AudioFrameTimeline.h"struct AVFormatContext;struct AVCodecContext;@@ -137,7 +138,8 @@ public:// Event-driven pump for ONE event cycle. Writes real data when the ring// has it, silence otherwise (underrun counted). Returns false on hard// failure.- bool pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs);+ bool waitForEvent();+ bool pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs, bool wait = true);// Master clock, or NaN when unstarted/reset or the device clock failed.double mediaTimeMs() const;@@ -151,6 +153,7 @@ 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_;}void shutdown();@@ -158,6 +161,10 @@ 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};std::atomic<double> bufferedMs_{0};+ mutable std::mutex timelineMutex_;+ AudioFrameTimeline outputTimeline_;+ bool timedPcm_=false;+ std::atomic<uint64_t> timelineWriteFrame_{0};std::atomic<float> gain_{1};float smoothedGain_=1,loggedGain_=-1;IMMDeviceEnumerator* enum_ = nullptr;IMMDevice* device_ = nullptr;diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cppindex 1c2f1536..c1017836 100644--- a/src/sink/CaptureAudioSession.cpp+++ b/src/sink/CaptureAudioSession.cpp@@ -20,6 +20,9 @@ struct CaptureAudioSession::Impl : AudioPcmSource {size_t inputBytes=0,convertingBytes=0;std::deque<float> pcm;double headPts=0;+ AudioFrameTimeline pcmTimeline;+ uint64_t pcmHead=0,pcmTail=0;+ std::optional<double> pullEnd;bool haveHead=false,pendingReset=false;std::atomic<bool> stop{false};std::atomic<float> gain{1};@@ -32,17 +35,24 @@ struct CaptureAudioSession::Impl : AudioPcmSource {static constexpr double maxQueuedMs=500;double queuedMs()const{return 1000.0*(pcm.size()/2)/kAudioRate+1000.0*(inputBytes+convertingBytes)/format.nAvgBytesPerSec;}void queueChanged(){state.bufferedMs=queuedMs();state.bufferHighWaterMs=std::max(state.bufferHighWaterMs,state.bufferedMs);}- void clearPcm(){std::lock_guard lock(mutex);pcm.clear();haveHead=false;queueChanged();}+ void clearPcmLocked(){pcm.clear();haveHead=false;pcmTimeline.clear();pcmHead=pcmTail=0;pullEnd.reset();}+ void clearPcm(){std::lock_guard lock(mutex);clearPcmLocked();queueChanged();}+ void discardPcm(size_t frames){+ for(size_t i=0;i<frames*2;++i)pcm.pop_front();pcmHead+=frames;+ headPts=pcmTimeline.at(double(pcmHead)).value_or(headPts);+ pcmTimeline.discardBefore(pcmHead);queueChanged();+ }void fail(const wchar_t* reason){std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.error=reason;}size_t pull(float* dst,size_t frames,double* pts)override{std::lock_guard lock(mutex);const size_t take=std::min(frames,pcm.size()/2);*pts=haveHead?headPts:-1;- for(size_t i=0;i<take*2;++i){dst[i]=pcm.front();pcm.pop_front();}- headPts+=1000.0*take/kAudioRate;- queueChanged();+ for(size_t i=0;i<take*2;++i)dst[i]=pcm[i];+ discardPcm(take);pullEnd=take?std::optional<double>(headPts):std::nullopt;return take;}+ std::optional<double> lastPullEndPtsMs()const override{return pullEnd;}+ bool padUnderruns()const override{return false;}void run(){AudioRenderer renderer;bool endpointReady=false;int64_t retryAt=0;@@ -56,13 +66,23 @@ struct CaptureAudioSession::Impl : AudioPcmSource {if(configured<0||!swr||swr_init(swr)<0){log::error("capture-audio","resampler initialization failed");swr_free(&swr);renderer.shutdown();fail(L"音频重采样初始化失败");return;}const auto releaseSwr=[](SwrContext* value){swr_free(&value);};std::unique_ptr<SwrContext,decltype(releaseSwr)> resampler(swr,releaseSwr);- double anchorHostMinusPts=0;+ double filteredError=0,correctionPpm=0;+ int64_t nextCorrection=0;int64_t lastReset=0;unsigned appliedMode=mode.load();int appliedOffset=offset.load();uint64_t lastUnderruns=0;+ bool endpointEventReady=false;+ auto clearCorrection=[&]{+ filteredError=correctionPpm=0;nextCorrection=hostTime()+2500000;+ const int result=swr_set_compensation(swr,0,0);+ if(result<0){log::error("capture-audio",std::format("clear drift compensation failed code={}",result));return false;}+ std::lock_guard lock(mutex);state.driftCorrectionPpm=0;return true;+ };auto recoverEndpoint=[&]{const auto error=renderer.lastError();renderer.shutdown();endpointReady=false;retryAt=hostTime()+5000000;clearPcm();swr_close(swr);if(swr_init(swr)<0){fail(L"音频重采样重置失败");return false;}+ if(!clearCorrection())return false;+ endpointEventReady=false;std::lock_guard lock(mutex);input.clear();inputBytes=convertingBytes=0;pendingReset=false;haveVideo=false;state.available=false;state.running=false;state.skewMs.reset();state.endpointBufferedMs=0;state.error=L"音频输出断开,正在重连("+std::to_wstring(unsigned(error))+L")";queueChanged();return true;@@ -77,6 +97,9 @@ struct CaptureAudioSession::Impl : AudioPcmSource {{std::lock_guard lock(mutex);state.error.clear();pendingReset=true;}}renderer.setGain(gain);+ // Wait before collecting callbacks, so PCM arriving during the+ // endpoint wait is available for this fill instead of padded silence.+ if(renderer.started()&&!endpointEventReady){if(!renderer.waitForEvent()){if(!recoverEndpoint())break;continue;}endpointEventReady=true;}Chunk chunk;bool reset=false;double vPts=0,vHost=0,ingress=0;bool video=false;int64_t arrival=0;{std::unique_lock lock(mutex);@@ -90,6 +113,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {if(reset||chunk.discontinuity){renderer.stopAndReset();clearPcm();swr_close(swr);if(swr_init(swr)<0){fail(L"音频重采样重置失败");break;}+ if(!clearCorrection()){fail(L"音频漂移校正重置失败");break;}std::lock_guard lock(mutex);++state.resets;}if(!chunk.bytes.empty()){@@ -102,7 +126,9 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const int count=swr_convert(swr,dst,capacity,src,inputFrames);if(count<0){log::error("capture-audio",std::format("convert failed code={}",count));fail(L"音频转换失败");break;}const double start=chunk.pts-1000.0*delay/format.nSamplesPerSec;- if(haveHead&&std::abs(start-(headPts+1000.0*(pcm.size()/2)/kAudioRate))>50){+ const double end=chunk.pts+1000.0*(inputFrames-swr_get_delay(swr,format.nSamplesPerSec))/format.nSamplesPerSec;+ if(reset||chunk.discontinuity)log::info("capture-audio-reset",std::format("mode={} pts={} delayBefore={} delayAfter={} input={} output={}",appliedMode,chunk.pts,delay,swr_get_delay(swr,format.nSamplesPerSec),inputFrames,count));+ if(haveHead&&std::abs(start-pcmTimeline.at(double(pcmTail)).value_or(start))>50){renderer.stopAndReset();clearPcm();std::lock_guard lock(mutex);++state.resets;}@@ -110,14 +136,21 @@ struct CaptureAudioSession::Impl : AudioPcmSource {std::lock_guard lock(mutex);convertingBytes=0;if(pendingReset){queueChanged();continue;}if(queuedMs()+1000.0*count/kAudioRate>maxQueuedMs){- input.clear();inputBytes=0;pcm.clear();haveHead=false;pendingReset=true;++state.overflows;+ input.clear();inputBytes=0;clearPcmLocked();pendingReset=true;++state.overflows;}else{if(!haveHead){headPts=start;haveHead=true;}+ pcmTimeline.append(pcmTail,count,start,end);pcmTail+=count;pcm.insert(pcm.end(),converted.begin(),converted.begin()+size_t(count)*2);}queueChanged();}}+ {+ std::lock_guard lock(mutex);+ // Drain callback blocks already available before waiting for+ // another endpoint event; otherwise silence can build a backlog.+ if(!input.empty()&&1000.0*(pcm.size()/2)/kAudioRate<renderer.capacityMs()+10)continue;+ }// Both streams use graph PTS. Relate the latest displayed video PTS// to host time; the endpoint's own queued frames are not added again.const double now=double(hostTime())/10000;@@ -126,22 +159,27 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const double target=std::clamp(requested,0.0,250.0);const double mapping=ingress+target;const bool limited=requested<0||requested>250;- if(!renderer.started()&&haveHead&&!pcm.empty()&&(appliedMode!=0||fresh)){+ bool justStarted=false;+ const double startupPrefillMs=std::min(renderer.capacityMs(),10.0);+ if(!renderer.started()&&haveHead&&1000.0*(pcm.size()/2)/kAudioRate>=startupPrefillMs&&(appliedMode!=0||fresh)){// Live recovery discards expired sound rather than replaying// an obsolete half-second after a GPU stall or graph reset.- const size_t expired=std::min(pcm.size()/2,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));- {std::lock_guard lock(mutex);for(size_t i=0;i<expired*2;++i)pcm.pop_front();headPts+=1000.0*expired/kAudioRate;queueChanged();}+ const size_t prefill=size_t(std::ceil(startupPrefillMs*kAudioRate/1000));+ const size_t expired=std::min(pcm.size()/2-prefill,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));+ {std::lock_guard lock(mutex);discardPcm(expired);}const bool due=now>=mapping+headPts;if(due&&!pcm.empty()){if(!renderer.startAnchored(*this)){if(!recoverEndpoint())break;continue;}- anchorHostMinusPts=now-renderer.mediaTimeMs();lastReset=hostTime();+ justStarted=true;endpointEventReady=false;+ lastReset=hostTime();filteredError=correctionPpm=0;nextCorrection=lastReset+2500000;}}- if(renderer.started()){+ if(renderer.started()&&!justStarted){// Test only: release this session's endpoint, never change a// system device or interfere with another application's audio.if(injectEndpointLoss&&!injected&&++endpointPumps==60){injected=true;log::warn("capture-audio-test","inject owned endpoint loss");if(!recoverEndpoint())break;continue;}- double pts=-1;if(!renderer.pumpOnce(*this,&pts)){if(!recoverEndpoint())break;continue;}+ double pts=-1;if(!renderer.pumpOnce(*this,&pts,false)){if(!recoverEndpoint())break;continue;}+ endpointEventReady=false;const auto underruns=renderer.underruns();if(underruns>lastUnderruns&&hostTime()-arrival>1000000){// Silence advances IAudioClock without consuming media.@@ -152,9 +190,21 @@ struct CaptureAudioSession::Impl : AudioPcmSource {lastUnderruns=underruns;// Large video-delay changes need a bounded re-anchor. Never// chase every jitter sample by stopping the audio endpoint.- if(appliedMode==0&&fresh&&hostTime()-lastReset>10000000&&std::abs(mapping-anchorHostMinusPts)>40){- renderer.stopAndReset();lastReset=hostTime();- std::lock_guard lock(mutex);++state.resets;+ const auto observed=hostTime();const double audioPts=renderer.mediaTimeMs();+ if(appliedMode==0&&fresh&&std::isfinite(audioPts)&&observed>=nextCorrection){+ const double error=audioPts-(double(observed)/10000-mapping);+ filteredError=.75*filteredError+.25*error;nextCorrection=observed+2500000;+ if(observed-lastReset>10000000&&std::abs(error)>60){+ renderer.stopAndReset();lastReset=observed;filteredError=correctionPpm=0;+ std::lock_guard lock(mutex);++state.resets;+ }else{+ const double targetPpm=std::clamp(filteredError*250.0,-5000.0,5000.0);+ correctionPpm+=std::clamp(targetPpm-correctionPpm,-250.0,250.0);+ const int delta=int(std::llround(correctionPpm*kAudioRate/1000000));+ const int result=swr_set_compensation(swr,delta,kAudioRate);+ if(result<0){log::error("capture-audio",std::format("drift compensation failed code={}",result));fail(L"音频漂移校正失败");break;}+ std::lock_guard lock(mutex);state.driftCorrectionPpm=correctionPpm;+ }}}{@@ -163,7 +213,8 @@ struct CaptureAudioSession::Impl : AudioPcmSource {state.compensationMs=target;state.underruns=renderer.underruns();state.endpointBufferedMs=renderer.bufferedMs();const auto audioPts=renderer.mediaTimeMs();- state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+now-vHost)):std::nullopt;+ const double observedNow=double(hostTime())/10000;+ state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+observedNow-vHost)):std::nullopt;}}renderer.shutdown();std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.endpointBufferedMs=0;@@ -180,13 +231,13 @@ bool CaptureAudioSession::configure(const WAVEFORMATEX& f){}bool CaptureAudioSession::start(){if(!p_->format.nBlockAlign||p_->thread.joinable())return false;- {std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=p_->convertingBytes=0;p_->pcm.clear();p_->haveHead=p_->haveVideo=p_->haveIngress=p_->pendingReset=false;p_->state={};}+ {std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=p_->convertingBytes=0;p_->clearPcmLocked();p_->haveHead=p_->haveVideo=p_->haveIngress=p_->pendingReset=false;p_->state={};}p_->stop=false;try{p_->thread=std::thread([this]{try{p_->run();}catch(const std::exception& e){log::error("capture-audio",std::format("audio thread failed: {}",e.what()));p_->fail(L"音频线程异常,请重新打开采集");}});}catch(const std::exception& e){log::error("capture-audio",std::format("audio thread start failed: {}",e.what()));p_->fail(L"无法创建音频线程");return false;}return true;}-void CaptureAudioSession::stop(){p_->stop=true;p_->wake.notify_all();if(p_->thread.joinable())p_->thread.join();std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=p_->convertingBytes=0;p_->pcm.clear();p_->state.bufferedMs=0;}+void CaptureAudioSession::stop(){p_->stop=true;p_->wake.notify_all();if(p_->thread.joinable())p_->thread.join();std::lock_guard lock(p_->mutex);p_->input.clear();p_->inputBytes=p_->convertingBytes=0;p_->clearPcmLocked();p_->state.bufferedMs=0;p_->state.driftCorrectionPpm=0;}bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool discontinuity){auto& p=*p_;if(!data||!p.format.nBlockAlign||bytes%p.format.nBlockAlign||bytes>p.format.nAvgBytesPerSec/2||!std::isfinite(pts))return false;if(!bytes)return true;std::lock_guard lock(p.mutex);diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex 35be6b3f..9368d7d9 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -322,39 +322,62 @@ bool AudioRenderer::startAnchored(AudioPcmSource& pipeline)return true;}-bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs)+bool AudioRenderer::waitForEvent(){- if (!running_) return false;+ if(!running_)return false;if(started_){const auto wait=WaitForSingleObject(event_,50);if(wait==WAIT_FAILED)return checked(HRESULT_FROM_WIN32(GetLastError()),"Wait audio event");}+ return true;+}++bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs, bool wait)+{+ if (!running_) return false;+ if(wait&&!waitForEvent())return false;UINT32 padding = 0;if (!checked(client_->GetCurrentPadding(&padding),"GetCurrentPadding")) return false;if(padding>bufferFrames_)return checked(E_UNEXPECTED,"Invalid endpoint padding");bufferedMs_=1000.0*padding/sampleRate_;const UINT32 avail = bufferFrames_ - padding;if (avail == 0) return true;+ // The endpoint can play silence after a live source runs dry. Its device+ // clock may then pass our last write; leave that gap unmapped.+ if(started_&&!padding&&!pipeline.padUnderruns()){+ UINT64 pos=0,qpc=0;+ if(!checked(clock_->GetPosition(&pos,&qpc),"Live write GetPosition"))return false;+ const auto consumed=static_cast<uint64_t>(std::ceil(double(pos-anchorPos_)*sampleRate_/clockFrequency_));+ timelineWriteFrame_=std::max(timelineWriteFrame_.load(),consumed);+ }chunk_.resize(static_cast<size_t>(avail) * 2);BYTE* dest = nullptr;if (!checked(render_->GetBuffer(avail, &dest),"GetBuffer")) return false;double firstPts = -1.0;const size_t got = pipeline.pull(chunk_.data(), avail, &firstPts);+ const auto endPts=pipeline.lastPullEndPtsMs();if (firstWrittenPtsMs) *firstWrittenPtsMs = firstPts;if (!started_ && !got) return checked(render_->ReleaseBuffer(0, 0),"Release empty prefill");+ const UINT32 written=started_&&pipeline.padUnderruns()?avail:static_cast<UINT32>(got);if (got > 0) {const float target=std::clamp(gain_.load(),0.0f,1.0f);applyStereoGain(chunk_.data(),got,target,smoothedGain_);if(target!=loggedGain_&&std::abs(smoothedGain_-target)<.00001f){loggedGain_=target;log::info("audio-gain",std::format("target={} reached={} framesWritten={} clockPreserved=true applicationPCM=true",target,smoothedGain_,framesWritten_.load()));}std::memcpy(dest, chunk_.data(), got * 8);- if (got < avail) {- std::memset(dest + got * 8, 0, (avail - got) * 8);+ if (got < written) {+ std::memset(dest + got * 8, 0, (written - got) * 8);underruns_.fetch_add(1);}} else {std::memset(dest, 0, static_cast<size_t>(avail) * 8);underruns_.fetch_add(1);}- if (!checked(render_->ReleaseBuffer(avail, 0),"ReleaseBuffer")) return false;- bufferedMs_=1000.0*(padding+avail)/sampleRate_;- framesWritten_ += avail;+ if (!checked(render_->ReleaseBuffer(written, 0),"ReleaseBuffer")) return false;+ {+ std::lock_guard lock(timelineMutex_);+ if(got&&endPts){timedPcm_=true;outputTimeline_.append(timelineWriteFrame_,got,firstPts,*endPts);}+ outputTimeline_.discardBefore(timelineWriteFrame_>sampleRate_?timelineWriteFrame_-sampleRate_:0);+ timelineWriteFrame_+=written;+ }+ bufferedMs_=1000.0*(padding+written)/sampleRate_;+ framesWritten_ += written;return true;}@@ -367,6 +390,11 @@ double AudioRenderer::mediaTimeMs() const}const double consumedMs = 1000.0 * static_cast<double>(pos - anchorPos_) /static_cast<double>(clockFrequency_);+ {std::lock_guard lock(timelineMutex_);if(timedPcm_){+ const double frame=consumedMs*sampleRate_/1000;+ if(frame>=timelineWriteFrame_)return std::numeric_limits<double>::quiet_NaN();+ return outputTimeline_.at(frame).value_or(std::numeric_limits<double>::quiet_NaN());+ }}return anchorPtsMs_.load() + consumedMs;}@@ -375,7 +403,9 @@ void AudioRenderer::stopAndReset()started_ = false;if (client_) { checked(client_->Stop(),"Stop for reset");checked(client_->Reset(),"Reset"); }framesWritten_ = 0;+ timelineWriteFrame_=0;bufferedMs_=0;smoothedGain_=0;+ {std::lock_guard lock(timelineMutex_);outputTimeline_.clear();timedPcm_=false;}}bool AudioRenderer::started() const { return started_; }@@ -392,6 +422,8 @@ void AudioRenderer::shutdown()running_ = false;started_ = false;bufferedMs_=0;framesWritten_=0;clockFrequency_=0;+ timelineWriteFrame_=0;+ {std::lock_guard lock(timelineMutex_);outputTimeline_.clear();timedPcm_=false;}if (comInited_) { CoUninitialize(); comInited_ = false; }}diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cppindex 74765891..fd05cf65 100644--- a/tests/integration/AudioTimelineTests.cpp+++ b/tests/integration/AudioTimelineTests.cpp@@ -68,5 +68,34 @@ int wmain(int argc, wchar_t** argv) {check(std::abs(seek-250)<0.05 && std::abs(renderer.mediaTimeMs()-250)<20,"paused seek reanchors actual PCM");pipe.stopThread(); renderer.stopAndReset();check(!std::isfinite(renderer.mediaTimeMs()),"reset invalidates clock");+ renderer.shutdown();+ struct StretchedPcm final:AudioPcmSource {+ size_t frames=0;+ size_t pull(float* samples,size_t count,double* pts)override{*pts=100+frames*500.0/kAudioRate;std::fill_n(samples,count*2,0.0f);frames+=count;return count;}+ std::optional<double> lastPullEndPtsMs()const override{return 100+frames*500.0/kAudioRate;}+ } stretched;+ check(renderer.start()&&renderer.startAnchored(stretched),"start mapped resampled PCM");+ const auto wall=std::chrono::steady_clock::now();+ while(std::chrono::steady_clock::now()-wall<300ms){double pts=0;if(!renderer.pumpOnce(stretched,&pts))break;}+ const double elapsed=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-wall).count();+ check(std::abs(renderer.mediaTimeMs()-(100+elapsed*.5))<12,"device clock follows media span at half speed, not output sample duration");+ renderer.stopAndReset();check(!std::isfinite(renderer.mediaTimeMs()),"reset clears mapped resampler timeline");+ renderer.shutdown();+ struct LivePcm final:AudioPcmSource {+ bool dry=false;double pts=100;+ size_t pull(float* samples,size_t count,double* first)override{*first=pts;if(dry)return 0;std::fill_n(samples,count*2,0.0f);pts+=count*1000.0/kAudioRate;return count;}+ std::optional<double> lastPullEndPtsMs()const override{return dry?std::nullopt:std::optional<double>(pts);}+ bool padUnderruns()const override{return false;}+ } live;+ check(renderer.start()&&renderer.startAnchored(live),"start live PCM timeline");+ live.dry=true;+ const auto stall=std::chrono::steady_clock::now();+ while(std::chrono::steady_clock::now()-stall<100ms){double pts=0;if(!renderer.pumpOnce(live,&pts))break;}+ check(!std::isfinite(renderer.mediaTimeMs()),"starved live endpoint has no invented media timestamp");+ live.dry=false;live.pts=500;+ const auto recovery=std::chrono::steady_clock::now();+ 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;}diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cppindex 0d19b60b..fe451771 100644--- a/tests/integration/CaptureAudioTests.cpp+++ b/tests/integration/CaptureAudioTests.cpp@@ -8,31 +8,43 @@#include <string_view>int main(int argc,char** argv){using namespace veyra::sink;using Clock=std::chrono::steady_clock;+ struct Pacer {+ HANDLE timer=CreateWaitableTimerExW(nullptr,nullptr,CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,TIMER_ALL_ACCESS);+ ~Pacer(){if(timer)CloseHandle(timer);}+ void until(Clock::time_point due){+ const auto ticks=std::chrono::duration_cast<std::chrono::nanoseconds>(due-Clock::now()).count()/100;+ if(ticks<=0)return;+ LARGE_INTEGER when{};when.QuadPart=-ticks;+ if(timer&&SetWaitableTimer(timer,&when,0,nullptr,nullptr,FALSE))WaitForSingleObject(timer,100);+ else std::this_thread::sleep_until(due);+ }+ } pacer;const bool endpointTest=argc==2&&std::string_view(argv[1])=="--endpoint-loss";- const bool driftTest=argc==2&&std::string_view(argv[1])=="--drift-slow";+ const bool fastDrift=argc==2&&std::string_view(argv[1])=="--drift-fast";+ const bool driftTest=fastDrift||(argc==2&&std::string_view(argv[1])=="--drift-slow");if(endpointTest)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",L"1");CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=192000;if(!audio.configure(f)||!audio.start())return 2;audio.setGain(0);std::vector<int16_t> pcm(960,0);const auto start=Clock::now();if(driftTest){std::vector<double> errors;unsigned missing=0;- constexpr double speed=.999;+ const double speed=fastDrift?1.001:.999;for(unsigned i=0;i<11980;++i){- std::this_thread::sleep_until(start+std::chrono::microseconds(int64_t(i*10000/speed)));+ pacer.until(start+std::chrono::microseconds(int64_t(i*10000/speed)));const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 6;if(i>=8)audio.videoPresented(i*10.0-80,host);const auto s=audio.snapshot();if(i>1000){if(s.running&&s.skewMs)errors.push_back(std::abs(*s.skewMs));else ++missing;}- if(i&&i%2000==0)std::cout<<"DRIFT seconds="<<i/100<<" skewMs="<<s.skewMs.value_or(-999)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<std::endl;+ if(i&&i%2000==0)std::cout<<"DRIFT seconds="<<i/100<<" skewMs="<<s.skewMs.value_or(-999)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" correctionPpm="<<s.driftCorrectionPpm<<std::endl;}const auto state=audio.snapshot();audio.stop();std::sort(errors.begin(),errors.end());const double p95=errors.empty()?999:errors[(errors.size()*95+99)/100-1];- const bool pass=p95<=30&&missing<100&&state.overflows==0&&state.bufferHighWaterMs<=500;- std::cout<<(pass?"PASS ":"FAIL ")<<"120s capture clock -1000ppm p95SkewMs="<<p95<<" missing="<<missing<<" resets="<<state.resets<<" highWaterMs="<<state.bufferHighWaterMs<<'\n';return pass?0:1;+ const bool pass=p95<=30&&missing<100&&state.resets==1&&state.overflows==0&&state.bufferHighWaterMs<=500;+ std::cout<<(pass?"PASS ":"FAIL ")<<"120s capture clock speed="<<speed<<" p95SkewMs="<<p95<<" missing="<<missing<<" resets="<<state.resets<<" highWaterMs="<<state.bufferHighWaterMs<<'\n';return pass?0:1;}double sum=0;unsigned count=0;bool bounded=true,sawReconnecting=false;for(unsigned i=0;i<(endpointTest?350u:160u);++i){- const auto due=start+std::chrono::milliseconds(i*10);std::this_thread::sleep_until(due);+ const auto due=start+std::chrono::milliseconds(i*10);pacer.until(due);const auto time=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;if(!audio.push(pcm.data(),pcm.size()*2,i*10.0,i==0))return 3;if(i>=8)audio.videoPresented(i*10.0-80,time);@@ -49,7 +61,7 @@ int main(int argc,char** argv){auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew){audio.setSync(mode,offset);double error=0;unsigned samples=0;bool boundedPhase=true;for(unsigned j=0;j<150;++j,++sequence){- std::this_thread::sleep_until(start+std::chrono::milliseconds(sequence*10));+ pacer.until(start+std::chrono::milliseconds(sequence*10));const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,false))return false;audio.videoPresented(sequence*10.0-delay,host);const auto s=audio.snapshot();@@ -57,7 +69,7 @@ int main(int argc,char** argv){if(j>70&&s.running&&s.skewMs){error+=std::abs(*s.skewMs-expectedSkew);++samples;}}const auto s=audio.snapshot();const bool pass=samples>=60&&error/samples<28&&std::abs(s.compensationMs-expectedComp)<15&&boundedPhase&&s.overflows==0;- std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<'\n';return pass;+ std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" compensation="<<s.compensationMs<<" meanSkewError="<<(samples?error/samples:-1)<<" resets="<<s.resets<<" queueMs="<<s.bufferedMs<<" endpointMs="<<s.endpointBufferedMs<<" underruns="<<s.underruns<<" correctionPpm="<<s.driftCorrectionPpm<<'\n';return pass;};ok=phase(0,0,160,160,0)&&ok;ok=phase(1,100,80,100,-20)&&ok;diff --git a/tests/unit/RepairContractTests.cpp b/tests/unit/RepairContractTests.cppindex 8dfe5ab4..8a02887c 100644--- a/tests/unit/RepairContractTests.cpp+++ b/tests/unit/RepairContractTests.cpp@@ -11,9 +11,16 @@#include <vector>#include "veyra/engine/CfrTimeline.h"#include "veyra/Log.h"+#include "veyra/sink/AudioFrameTimeline.h"int main(){using namespace veyra;int failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};+ sink::AudioFrameTimeline pcmTime;+ pcmTime.append(0,480,100,105);pcmTime.append(480,480,105,120);+ check(pcmTime.at(240)==102.5&&pcmTime.at(720)==112.5,"resampled PCM maps each span at its actual media rate");+ check(!pcmTime.at(1000),"unwritten or silent output has no invented media clock");+ pcmTime.discardBefore(481);check(!pcmTime.at(100)&&pcmTime.at(720)==112.5,"consumed PCM mapping prunes without losing queued audio");+ pcmTime.clear();check(!pcmTime.at(720),"audio reset clears old media anchors");auto p=pipeline::ResolutionPlan::make({1920,1080},true,pipeline::NrSizePolicy::Realtime,false);check(p.base==pipeline::Extent{3840,2160}&&p.nr==pipeline::Extent{1920,1080}&&p.flow==pipeline::Extent{1920,1080}&&p.output==p.base,"SR4K preserves base; NR and flow remain source1080");p=pipeline::ResolutionPlan::make({3840,2160},false,pipeline::NrSizePolicy::Realtime,false);