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 capture audio crackle by preserving playback reserve during sync

Veyra Goal Agentaa40381f8879
diff --git a/docs/CAPTURE_AUDIO_BUZZ_REPAIR_2026-09-15.md b/docs/CAPTURE_AUDIO_BUZZ_REPAIR_2026-09-15.md
new file mode 100644
index 00000000..a1462414
--- /dev/null
+++ b/docs/CAPTURE_AUDIO_BUZZ_REPAIR_2026-09-15.md
@@ -0,0 +1,51 @@
+# 采集卡随音乐出现滋滋声:实录定位与修复
+
+## 范围与现状
+
+用户明确授权连接当前 USB3 Video / USB3 Digital Audio 采集卡录音,PS5 保持音乐开启。串流未报告相同噪声。本轮优先处理采集音频,暂停 HDR→SDR 后续工作;不操作游戏、不发布。分支 `codex/user-issues-repair-20260915`,前置提交 `f7bc4eb`。
+
+## 根因证据
+
+1. DirectShow 实际协商 48000 Hz / 16-bit / 双声道,10 ms(480 frame)回调。分别记录原始 PCM、连续 SWR 输出、队列 pull 和送给 WASAPI 的 PCM;最后用 Windows **指定进程** loopback 回录当前测试 Veyra,未记录其他程序/麦克风。
+2. 无效果录音:转换后与 pull 对齐 463 frame 后逐样本一致。增强录音中,pull 与送入 WASAPI 的 PCM 在启动 240 frame 音量渐入后逐样本一致。输入没有过幅削波;不能因该证据宣称用户没有听到噪声。
+3. 原控制器只按音频 PTS 与视频目标偏差调整 `swr_set_compensation`,负补偿不断缩短音频。目标低于实时播放所需的调度缓冲时,原有 20 ms 安全余量被耗尽,每个 10 ms 周期只有约 478~479 frame 可提交。驱动 `IAudioClock` 可在微小耗尽时停住,旧 underrun 计数仍为 0;连续 PCM 文件看不出 Windows 实际插入的间隙。
+4. 修复前独立回录 `logs/audio-buzz-loopback-before-20260915.loopback.f32`:5~20 秒共 96 处前一 frame 幅值超过 0.002、随后双声道突然同时为零的断口;129 个双声道零 frame。断口集中在同一 480-frame 周期边界。启动 1 秒后的 1902 次写入全部观察到 padding=0。
+
+这说明当前实机的一条确切软件缺陷是**同步控制耗尽播放缓冲造成周期性间隙**,不是把音乐振幅限制一下可以解决,也不能靠 swresample 单独离线测试排除。不同录音的音乐内容并不完全相同,不将峰值/RMS 差异当作音质改善量。
+
+## 修改
+
+- `include/veyra/sink/CaptureAudioDsp.h`:`captureSafeCorrectionPpm` 将时钟请求与实际音频储备约束结合;储备包含未转换输入、软件 PCM 和端点实际排队,沿用已有启动安全窗(本机 20 ms)。储备不足时限制负补偿并平滑补足;有富余仍允许追赶。安全限制可及时覆盖向下速度斜率,不重建 FIR、不丢 PCM、不加逐块 AGC。
+- `src/sink/CaptureAudioSession.cpp`:接入储备约束,记录 `capture-audio-reserve` 的真实队列值、最低储备、限制状态和 ppm。不把这个调度储备冒充额外视频处理耗时。
+- `tests/integration/AudioWaveformTests.cpp`:增加持续不可能的提前目标、低储备恢复、富余时追赶和正向斜率测试;原实际 FFmpeg 波形连续性测试保留。
+- `include/veyra/diagnostics/CapturePcmRecording.h`、`AudioPcmSource.h`、`WasapiAudioSink.cpp`:显式环境变量 `VEYRA_DIAGNOSTIC_CAPTURE_PCM_PREFIX`(绝对路径)才开启采集源分段诊断;内存上限 20 秒,关闭后落盘,默认不录音。输出 tap 在成功 ReleaseBuffer 后使用自有 staging 内存,绝不访问已释放的 WASAPI 指针。记录保存失败单独警告,不冒充已保存。
+
+## 已执行验证
+
+- `cmd.exe /c out\build\veyra-build-x64-release.cmd`:录音版、修复版构建成功。日志 `logs/audio-buzz-record-build-b-20260915.log`、`logs/audio-buzz-fix-build-20260915.log`。末次仅诊断保存检查的构建见后续记录。
+- `scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_audio_waveform_tests.exe -TimeoutSeconds 60`:`logs/audio-buzz-waveform-20260915.stdout.log`,51 checks / 0 failures。
+- 同 wrapper 运行 `veyra_capture_audio_tests.exe`,60 秒上限:`logs/audio-buzz-sync-regression-20260915.stdout.log`,exit 0。实际静音 WASAPI,含同步模式切换、80/160/400/900 ms 目标、同源时间偏移、视频重建、真实输入停顿恢复和容量上限;不冒充物理 VRR 验收。
+- 实机增强前后:Veyra 参数 `capture:0:0:0 --nr --no-sr --fg --smoke-seconds 32`;单独进程 loopback 28 秒,上层在进程超时后只终止自有测试进程。实际 NR/NVOF/FG 日志保留。
+- 修复后成功样本 `logs/audio-buzz-loopback-after-b-20260915.*`:5~20 秒的上述断口 **0**、双声道零 frame **0**;启动 1 秒后 1899 次写入 padding=0 次数 **0**,最低 padding 168 frame,中位 486 frame。gain 渐入后 pull/render PCM 仍逐样本一致。日志中实际储备约 20 ms,没有通过停止声音或关闭增强通过测试。
+
+## 失败与边界
+
+- 第一轮修复后测试 `audio-buzz-loopback-after-20260915` 被用户另一份 Veyra 占用设备,DirectShow Run 返回 `0x800705AA`,录音为空;**不计通过**。用户关闭后独立重跑 after-b 成功,未强制关闭用户程序。
+- 初始工具误用旧测试名/FFmpeg DirectShow 替代名、cmd 正斜杠路径,均已纠正;失败日志保留。
+- 本机已证实和消除周期性间隙,仍需用户听感确认是否覆盖全部杂音。Windows 进程 loopback 不是耳机/扬声器的声学测量,也不代表其他型号采集卡已全部验收。
+- 旧 underrun 计数无法可靠衡量极短的驱动停钟间隙,本轮不伪造缺失 frame 计数。用独立回录与实际 padding 做证据,新增储备日志供定位。
+- 指定进程回录使用 Windows 官方公开 API,依据:https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/ 。本地工具 `out/audio-process-loopback.cpp` 只用于诊断,不进入应用或便携包。
+
+## 最终构建与交付
+
+最终构建 `logs/audio-buzz-final-build-20260915.log` exit 0。执行 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915`,46.48 秒 exit 0:`logs/delivery/3c3099c2022d4272a439d63b3062363b/result.json`。覆盖实际 NR/NVOF、原生 4K、播放/控制/图片、H.264/HEVC 4K 2X 导出及音轨;该 gate 的通用采集标签不替代本轮独立实卡录音证据。
+
+可重复录音分析:`python scripts/diagnostics/capture-pcm-audit.py logs/audio-buzz-loopback-before-20260915`,after-b 同命令替换前缀。JSON 结果分别为 `logs/audio-buzz-before-audit-20260915.json`、`logs/audio-buzz-after-audit-20260915.json`。
+
+候选 `out/build/audio-continuity-repair-20260915/veyra.exe`,SHA256 `912FECDF30FE385BC33F1A6272EF8DF8E695B43F1D76F650AC2B521422CEBF93`。启动入口 `out/start-user-issues-candidate.cmd`,不修改其他桌面入口。运行组件、用户配置、版本号不变;未发布。
+
+持续漂移:`scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_capture_audio_tests.exe -Arguments @('--drift-slow') -TimeoutSeconds 150`,`logs/audio-buzz-drift-slow-20260915.stdout.log` exit 0。120 秒合成输入时钟慢 0.1%,实际静音 WASAPI;时差绝对值 P95=4.279 ms、missing=0、仅启动 reset=1、队列高水位89.646 ms,稳态 underrun=0。该数值是软件时钟差,不是声学端到端延迟。
+
+## 后续唯一任务
+
+交用户听感验收。本轮不继续扩展颜色或导出功能。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 9b053029..54b7d511 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2251,3 +2251,17 @@ VideoExportJob修正视频包失败仍计数、检查关闭刷新、细分编码
实际构建脚本scrub-nr-export-build系列exit0;shader45秒上限exit0、真实NR参数120秒上限exit0、最终GUI24秒/55秒上限exit0;前两次GUI测试失败及修正原因保留在对应文档。真实3600帧文件锁测试export-lock-final在全部解码通过后得到Windows32,并正确报告保存失败;export-corrupt-output破坏尾包后正确拒绝成功,两项各120秒上限exit0。computer-use实际点击导出按钮,观察另存为窗口及默认名字,取消未导出。
完整 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root . -BuildDirectory out/build/audio-continuity-repair-20260915` exit0:`logs/delivery/582eaf50540a4f2f82abf2b7b82b3cfc/result.json`。实际NR/NVOF、原生4K、GUI/图片、H264/HEVC4K2X导出/音轨/取消通过,采集待实卡。候选EXE SHA256 `E0FE742B3EC7B83BEA18390EA7E61472D5CBB925F8DC0A6809F925EE92DB86E9`,入口保持 `out/start-user-issues-candidate.cmd`。未改运行组件、SDK、版本或发布。反馈者99%根因尚缺原文件/日志,不能拿注入文件锁替代真实复现。后续继续独立的HDR转SDR曲线/色域修复。
+
+## 2026-09-15 采集卡音乐滋滋声:真实播放间隙修复
+
+用户将采集音频严重杂音提为最高优先级,并明确开启PS5音乐授权实卡录音;暂缓HDR色调映射。前置提交f7bc4eb,仍在codex/user-issues-repair-20260915。完整根因、修改清单与命令见 `docs/CAPTURE_AUDIO_BUZZ_REPAIR_2026-09-15.md`。
+
+物理USB3 Digital Audio输入48k/16bit/2ch/10ms。原始、SWR、pull、WASAPI提交四阶段录音表明转换和队列没有引入块断裂,但自动同步负ppm耗尽20ms播放储备;实际每周期少量缺样被Windows插入短静音,驱动时钟停顿使旧underrun计数仍为0。仅指定测试Veyra进程的Windows loopback,修复前5~20秒96处明显双声道归零断口、129零frame,1902次稳态写入padding全为0;修复后同长度0断口/0零frame,1899次稳态写入无padding=0。两段音乐非逐帧相同,不以RMS或峰值作音质分数。
+
+CaptureAudioDsp增加调度储备约束,CaptureAudioSession将输入/PCM/端点真实储备纳入速度校正,不让不可达到的更早画面目标饿死播放;保留连续SWR、原有20ms安全窗、有储备时的正常追赶。新增显式环境变量才开启的20秒有界诊断和capture-pcm-audit.py;默认不录音,不记录其他应用。WaveformTests增加反例测试。
+
+最终构建 `cmd.exe /c out\build\veyra-build-x64-release.cmd` exit0,`logs/audio-buzz-final-build-20260915.log`。waveform测试51/0,真实静音WASAPI capture_audio全模式/延迟/重建/恢复/容量回归exit0(各60秒上限)。实卡NR+FG运行32秒、进程回录28秒;一次修复后测试因用户另一份Veyra占用,Run=0x800705AA且录音为空,明确失败,用户关闭后after-b通过,失败记录保留。独立录音分析JSON见audio-buzz-before/after-audit-20260915,实际SDK返回值在录音应用日志及delivery原始日志。
+
+完整delivery同上命令exit0,`logs/delivery/3c3099c2022d4272a439d63b3062363b/result.json`,46.48秒,实际NR/NVOF/原生4K/播放控制/图片/导出音轨通过。候选EXE SHA256 `912FECDF30FE385BC33F1A6272EF8DF8E695B43F1D76F650AC2B521422CEBF93`,`out/start-user-issues-candidate.cmd`。运行组件/SDK/配置/录音不提交Git,没有push或发布。本机回录消除了已复现的间隙,用户最终听感及其他卡型号尚未验收。
+
+持续漂移 `veyra_capture_audio_tests.exe --drift-slow` 经run-short-test、150秒上限,日志 `logs/audio-buzz-drift-slow-20260915.stdout.log` exit0。实际120秒/输入慢0.1%/静音WASAPI,软件时差绝对值P95=4.279ms,missing=0、resets=1(启动)、队列高水位89.646ms、稳态underrun=0,未出现累计多秒延迟。不是声学延迟证明。下一步仅交用户试听确认本次采集杂音,不据此宣称所有卡已修好。
diff --git a/include/veyra/diagnostics/CapturePcmRecording.h b/include/veyra/diagnostics/CapturePcmRecording.h
new file mode 100644
index 00000000..7752b159
--- /dev/null
+++ b/include/veyra/diagnostics/CapturePcmRecording.h
@@ -0,0 +1,57 @@
+#pragma once
+#include <windows.h>
+#include <vector>
+#include <filesystem>
+#include <fstream>
+#include <algorithm>
+#include <string>
+#include <cstdint>
+#include "veyra/Log.h"
+namespace veyra::diagnostics {
+// Explicit diagnostic opt-in only. Keep at most 20 seconds per stage in
+// memory; write after capture stops, never perform disk I/O in a callback.
+class CapturePcmRecording {
+ std::wstring prefix_;
+ size_t rawLimit_=0,floatLimit_=0;
+ unsigned rate_=0,channels_=0,bits_=0,valid_=0;bool floating_=false;
+ std::vector<uint8_t> raw_;
+ std::vector<float> converted_,pulled_,rendered_;
+ struct Write {uint64_t frame;unsigned count,padding;int64_t qpc;};
+ std::vector<Write> writes_;unsigned renderedChannels_=0;
+public:
+ void configure(unsigned rate,unsigned channels,unsigned bits,unsigned valid,bool floating){
+ wchar_t path[32768]{};const DWORD n=GetEnvironmentVariableW(L"VEYRA_DIAGNOSTIC_CAPTURE_PCM_PREFIX",path,DWORD(std::size(path)));
+ if(!n||n>=std::size(path)||!std::filesystem::path(path).is_absolute())return;
+ prefix_=path;rate_=rate;channels_=channels;bits_=bits;valid_=valid;floating_=floating;
+ rawLimit_=size_t(rate)*channels*(bits/8)*20;floatLimit_=size_t(48000)*channels*20;
+ raw_.reserve(rawLimit_);converted_.reserve(floatLimit_);pulled_.reserve(floatLimit_);rendered_.reserve(size_t(48000)*8*20);writes_.reserve(20000);
+ }
+ void raw(const void* bytes,size_t count){if(prefix_.empty())return;const auto* p=static_cast<const uint8_t*>(bytes);count=std::min(count,rawLimit_-raw_.size());raw_.insert(raw_.end(),p,p+count);}
+ void converted(const float* samples,size_t count){if(prefix_.empty())return;count=std::min(count,floatLimit_-converted_.size());converted_.insert(converted_.end(),samples,samples+count);}
+ void pulled(const float* samples,size_t count){if(prefix_.empty())return;count=std::min(count,floatLimit_-pulled_.size());pulled_.insert(pulled_.end(),samples,samples+count);}
+ void rendered(const float* samples,size_t frames,unsigned channels,unsigned padding){
+ if(prefix_.empty()||!channels||channels>8)return;
+ if(renderedChannels_&&renderedChannels_!=channels)return;
+ renderedChannels_=channels;const size_t limit=size_t(48000)*channels*20;
+ const size_t count=std::min(frames*channels,limit-rendered_.size());if(!count)return;
+ LARGE_INTEGER qpc;QueryPerformanceCounter(&qpc);
+ if(writes_.size()<20000)writes_.push_back({rendered_.size()/channels,unsigned(count/channels),padding,qpc.QuadPart});
+ rendered_.insert(rendered_.end(),samples,samples+count);
+ }
+ void finish(){
+ if(prefix_.empty())return;
+ try{
+ bool saved=true;
+ auto write=[&](const wchar_t* suffix,const void* data,size_t bytes){std::ofstream file(std::filesystem::path(prefix_+suffix),std::ios::binary);if(bytes)file.write(static_cast<const char*>(data),std::streamsize(bytes));file.close();saved=saved&&bool(file);};
+ write(L".raw.pcm",raw_.data(),raw_.size());write(L".converted.f32",converted_.data(),converted_.size()*sizeof(float));write(L".pulled.f32",pulled_.data(),pulled_.size()*sizeof(float));
+ write(L".rendered.f32",rendered_.data(),rendered_.size()*sizeof(float));
+ std::ofstream events(std::filesystem::path(prefix_+L".writes.csv"));LARGE_INTEGER frequency;QueryPerformanceFrequency(&frequency);
+ events<<"frame,count,padding,qpc,frequency,channels\n";for(const auto& w:writes_)events<<w.frame<<','<<w.count<<','<<w.padding<<','<<w.qpc<<','<<frequency.QuadPart<<','<<renderedChannels_<<'\n';
+ std::ofstream meta(std::filesystem::path(prefix_+L".json"));meta<<"{\"inputRate\":"<<rate_<<",\"channels\":"<<channels_<<",\"containerBits\":"<<bits_<<",\"validBits\":"<<valid_<<",\"floating\":"<<(floating_?"true":"false")<<",\"outputRate\":48000,\"rawBytes\":"<<raw_.size()<<",\"convertedSamples\":"<<converted_.size()<<",\"pulledSamples\":"<<pulled_.size()<<"}";
+ events.close();meta.close();
+ if(!saved||!events||!meta)log::warn("capture-pcm-recording","Diagnostic recording write failed; capture state is unaffected");
+ }catch(const std::exception&){log::warn("capture-pcm-recording","Diagnostic recording could not be saved");}
+ prefix_.clear();raw_.clear();converted_.clear();pulled_.clear();rendered_.clear();writes_.clear();renderedChannels_=0;
+ }
+};
+}
diff --git a/include/veyra/sink/AudioPcmSource.h b/include/veyra/sink/AudioPcmSource.h
index eb248b46..ce5fc414 100644
--- a/include/veyra/sink/AudioPcmSource.h
+++ b/include/veyra/sink/AudioPcmSource.h
@@ -10,5 +10,8 @@ public:
virtual size_t pull(float* interleaved, size_t frames, double* firstPtsMs) = 0;
virtual std::optional<double> lastPullEndPtsMs()const{return {};}
virtual bool padUnderruns()const{return true;}
+ // Optional diagnostic observer, invoked on the audio owner after a successful
+ // endpoint write. Never enabled by ordinary playback sources.
+ virtual void observeRenderedPcm(const float*,size_t,unsigned,unsigned){}
};
}
diff --git a/include/veyra/sink/CaptureAudioDsp.h b/include/veyra/sink/CaptureAudioDsp.h
index c20b247c..3aa5d68e 100644
--- a/include/veyra/sink/CaptureAudioDsp.h
+++ b/include/veyra/sink/CaptureAudioDsp.h
@@ -16,6 +16,15 @@ private:
bool prepared_=false;
};
struct CaptureSampleStats {float peak=0;uint64_t nonFinite=0,overRange=0;};
+// Clock alignment cannot consume the live renderer's scheduling reserve.
+// Negative SWR compensation makes fewer output samples. At the latency floor,
+// chasing an unachievable earlier PTS otherwise causes periodic endpoint gaps.
+inline double captureSafeCorrectionPpm(double requested,double current,double queuedMs,double reserveMs){
+ const double slewed=current+std::clamp(requested-current,-250.0,250.0);
+ const double reservoirLimit=std::clamp((reserveMs-queuedMs)*500.0,-5000.0,5000.0);
+ // Safety overrides the downward slew immediately; keep the FIR history.
+ return std::clamp(std::max(slewed,reservoirLimit),-5000.0,5000.0);
+}
// Float PCM can legitimately exceed unity before final user gain/downmix.
// Do not introduce block AGC or clamp finite samples in the conversion stage.
inline CaptureSampleStats inspectCapturePcm(float* samples,size_t count){
diff --git a/scripts/diagnostics/capture-pcm-audit.py b/scripts/diagnostics/capture-pcm-audit.py
new file mode 100644
index 00000000..02591a02
--- /dev/null
+++ b/scripts/diagnostics/capture-pcm-audit.py
@@ -0,0 +1,52 @@
+"""Inspect explicitly recorded capture PCM and per-process Windows loopback.
+
+Requires numpy. This diagnoses exact-zero discontinuities and endpoint padding;
+it is not a perceptual score or proof about an acoustic output device.
+"""
+import argparse
+import json
+from pathlib import Path
+import numpy as np
+
+parser = argparse.ArgumentParser()
+parser.add_argument("prefix", type=Path)
+parser.add_argument("--start-seconds", type=float, default=5)
+parser.add_argument("--end-seconds", type=float, default=20)
+args = parser.parse_args()
+prefix = str(args.prefix)
+meta = json.loads(Path(prefix + ".json").read_text())
+writes = np.atleast_1d(np.genfromtxt(prefix + ".writes.csv", delimiter=",", names=True))
+if not len(writes) or not np.isfinite(writes["channels"]).all():
+ raise ValueError("No endpoint writes: this recording cannot verify playback")
+channels = int(writes["channels"][0])
+if channels != meta["channels"] or channels != 2:
+ raise ValueError("This comparison requires unchanged stereo mapping")
+pulled = np.fromfile(prefix + ".pulled.f32", dtype="<f4").reshape(-1, channels)
+rendered = np.fromfile(prefix + ".rendered.f32", dtype="<f4").reshape(-1, channels)
+loopback = np.fromfile(prefix + ".loopback.f32", dtype="<f4").reshape(-1, 2)
+start = int(args.start_seconds * 48000)
+end = int(args.end_seconds * 48000)
+if not 0 <= start < end <= len(loopback):
+ raise ValueError("Requested loopback interval is unavailable")
+zero = np.all(loopback == 0, axis=1)
+# Reject naturally quiet quantized samples: only count a sudden exact stereo
+# zero immediately after a sample whose peak amplitude exceeds 0.002.
+edge = zero[1:-1] & ~zero[:-2] & (np.max(abs(loopback[:-2]), axis=1) > .002)
+positions = np.flatnonzero(edge) + 1
+positions = positions[(positions >= start) & (positions < end)]
+residues, counts = np.unique(positions % 480, return_counts=True)
+steady = writes[writes["frame"] > 48000]
+print(json.dumps({
+ "prefix": prefix,
+ "loopback_interval_seconds": [args.start_seconds, args.end_seconds],
+ "hard_zero_edges": len(positions),
+ "stereo_zero_frames": int(zero[start:end].sum()),
+ "edge_residues_in_10ms": dict(zip(map(str, residues), map(int, counts))),
+ "steady_writes": len(steady),
+ "steady_empty_padding_writes": int((steady["padding"] == 0).sum()),
+ "steady_padding_min_median_max_frames": np.quantile(steady["padding"], [0, .5, 1]).tolist(),
+ "pull_render_equal_after_240_frame_gain_ramp": bool(
+ len(pulled) == len(rendered) and len(rendered) > 240 and
+ np.array_equal(pulled[240:], rendered[240:])),
+ "limitations": "Different music segments; no perceptual/acoustic quality claim. Empty padding alone does not prove an audible gap."
+}, ensure_ascii=False, indent=2))
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
index 302a74ed..62c637da 100644
--- a/src/sink/CaptureAudioSession.cpp
+++ b/src/sink/CaptureAudioSession.cpp
@@ -3,6 +3,7 @@
#include "veyra/sink/ArrivalClockMapping.h"
#include "veyra/sink/CaptureAudioDsp.h"
#include "veyra/sink/CaptureSyncTarget.h"
+#include "veyra/diagnostics/CapturePcmRecording.h"
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -15,6 +16,7 @@ namespace {
int64_t hostTime(){return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100;}
}
struct CaptureAudioSession::Impl : AudioPcmSource {
+ diagnostics::CapturePcmRecording recording;
struct Chunk {std::vector<uint8_t> bytes;double pts=0;bool discontinuity=false;};
WAVEFORMATEX format{};
AudioFormat layout;unsigned validBits=0;bool floating=false;
@@ -56,11 +58,13 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const size_t take=std::min(frames,pcm.size()/layout.channels);
*pts=haveHead?headPts:-1;
for(size_t i=0;i<take*layout.channels;++i)dst[i]=pcm[i];
+ recording.pulled(dst,take*layout.channels);
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 observeRenderedPcm(const float* samples,size_t frames,unsigned channels,unsigned padding)override{recording.rendered(samples,frames,channels,padding);}
void run(){
AudioRenderer renderer;
bool endpointReady=false;int64_t retryAt=0;
@@ -84,6 +88,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const auto releaseSwr=[](SwrContext* value){swr_free(&value);};
std::unique_ptr<SwrContext,decltype(releaseSwr)> resampler(swr,releaseSwr);
double filteredError=0,correctionPpm=0;
+ double correctionQueuedMs=0;bool correctionReserveLimited=false;
CaptureRateCorrection rateCorrection;
int64_t nextCorrection=0;
int64_t lastReset=0;
@@ -202,6 +207,7 @@ 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 auto stats=inspectCapturePcm(converted.data(),size_t(count)*layout.channels);
+ recording.converted(converted.data(),size_t(count)*layout.channels);
{
std::lock_guard lock(mutex);
state.invalidPaddingSamples+=invalidPadding;state.nonFiniteSamples+=stats.nonFinite;
@@ -330,7 +336,14 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
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);
+ // Include all pending source PCM plus the endpoint's
+ // real padding after this write. A presentation target
+ // below this reserve is physically unattainable without
+ // starving playback; do not squeeze out those samples.
+ {std::lock_guard lock(mutex);correctionQueuedMs=queuedMs()+renderer.bufferedMs();}
+ const double requestedPpm=correctionPpm+std::clamp(targetPpm-correctionPpm,-250.0,250.0);
+ correctionPpm=captureSafeCorrectionPpm(targetPpm,correctionPpm,correctionQueuedMs,startupPrefillMs);
+ correctionReserveLimited=correctionPpm>requestedPpm+.01;
const int delta=int(std::llround(correctionPpm*kAudioRate/1000000));
{
const int result=rateCorrection.set(swr,delta,kAudioRate);
@@ -355,6 +368,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(state.syncClockFallback?observedNow-mapping:vPts+observedNow-vHost)):std::nullopt;
if(hostTime()>=nextSyncLog){
nextSyncLog=hostTime()+20000000;
+ if(appliedMode==0)log::info("capture-audio-reserve",std::format("queuedAtCorrectionMs={:.3f} minimumMs={:.3f} rateLimited={} correctionPpm={:.1f} (real scheduling reserve, not extra video delay)",correctionQueuedMs,startupPrefillMs,correctionReserveLimited,correctionPpm));
if(vArrival)log::info("capture-audio-target",std::format("mode={} rawMs={:.3f} localVideoMs={:.3f} acceptedMs={:.3f} fallback={} fresh={} rawSkewMs={:.3f} presentation=original inputArrival100ns={}",appliedMode,syncEstimate.rawMs,syncEstimate.localMs,target,state.syncClockFallback,fresh,fresh&&std::isfinite(audioPts)?audioPts-(vPts+observedNow-vHost):-999,*vArrival));
log::info("live-audio-sync",std::format("videoPtsMs={:.3f} videoHostMs={:.3f} audioIngressMapMs={:.3f} compensationMs={:.3f} pcmMs={:.3f} endpointMs={:.3f} skewMs={:.3f} correctionPpm={:.1f} resets={} underruns={} underrunFrames={} silenceFrames={} emptyPulls={} recoveryFades={} inputBlockMs={:.3f} inputIntervalMs={:.3f} inputBlocks={} format={}Hz/{}bit validBits={} convertedPeak={:.5f} overRange={} clipped={} (local clock alignment, not GPU execution time)",vPts,vHost,ingress,target,state.bufferedMs,state.endpointBufferedMs,state.skewMs.value_or(-999),state.driftCorrectionPpm,state.resets,state.underruns,state.underrunFrames,state.silenceFrames,state.emptyPulls,state.recoveryFades,state.inputBlockMs,state.inputIntervalMs,state.inputBlocks,state.inputSampleRate,state.inputContainerBits,state.inputValidBits,state.inputPeak,state.overRangeSamples,state.clippedSamples));
}
@@ -368,6 +382,7 @@ CaptureAudioSession::~CaptureAudioSession(){stop();}
bool CaptureAudioSession::configure(const WavePcmFormat& parsed){
if(p_->thread.joinable()||!parsed.layout.valid()||!parsed.validBits)return false;
p_->format=parsed.wave;p_->layout=parsed.layout;p_->validBits=parsed.validBits;p_->floating=parsed.floating;
+ p_->recording.configure(parsed.wave.nSamplesPerSec,parsed.layout.channels,parsed.wave.wBitsPerSample,parsed.validBits,parsed.floating);
{
std::lock_guard lock(p_->mutex);
p_->state.inputChannels=parsed.layout.channels;p_->state.inputChannelMask=parsed.layout.mask;
@@ -390,11 +405,12 @@ bool CaptureAudioSession::start(){
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_->clearPcmLocked();p_->state.bufferedMs=0;p_->state.driftCorrectionPpm=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_->recording.finish();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);
if(p.stop||!p.state.error.empty())return true;
+ p.recording.raw(data,bytes);
if(discontinuity){p.input.clear();p.inputBytes=0;p.pendingReset=true;p.haveVideo=false;}
const auto arrival=hostTime();
p.state.inputIntervalMs=p.state.inputBlocks&&!discontinuity?double(arrival-p.lastArrival)/10000:0;
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index c2d87328..b3130af3 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -475,7 +475,10 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs
silenceFrames_.fetch_add(written);
}
}
+ // ReleaseBuffer invalidates dest. The same gain/mapped samples remain in
+ // our owned staging storage for the source-specific diagnostic observer.
if (!checked(render_->ReleaseBuffer(written, 0),"ReleaseBuffer")) return false;
+ if(got)pipeline.observeRenderedPcm(channelMix_?mixed_.data():chunk_.data(),got,outputFormat_.channels,padding);
liveGap_.submitted(got);
if(written>got)std::fill(lastRaw_.begin(),lastRaw_.end(),0);
{
diff --git a/tests/integration/AudioWaveformTests.cpp b/tests/integration/AudioWaveformTests.cpp
index c2608019..dbcc52d7 100644
--- a/tests/integration/AudioWaveformTests.cpp
+++ b/tests/integration/AudioWaveformTests.cpp
@@ -99,6 +99,20 @@ int main(int argc,char** argv){
unsigned checks=0,failures=0;
auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};
try{
+ // Adversarial model: the video target asks to consume 0.5% faster
+ // forever, while the physical input arrives at the endpoint rate.
+ // A clock-only controller drains 20 ms to zero; the production guard
+ // retains the reserve without resetting/dropping waveform samples.
+ double reserve=20,ppm=0,minimum=reserve,unguarded=20;
+ for(unsigned i=0;i<2400;++i){
+ ppm=captureSafeCorrectionPpm(-5000,ppm,reserve,20);
+ reserve+=250*ppm/1000000;minimum=std::min(minimum,reserve);
+ unguarded+=250*(-5000.0)/1000000;
+ }
+ check(minimum>=19.99&&unguarded<0,"unattainable early video target cannot consume live scheduling reserve");
+ check(captureSafeCorrectionPpm(-5000,-5000,12,20)>0,"low reservoir overrides negative slew before another underrun");
+ check(captureSafeCorrectionPpm(-3000,-3000,40,20)==-3000,"healthy queued audio can still catch up smoothly");
+ check(captureSafeCorrectionPpm(3000,0,20,20)==250,"positive correction retains bounded slew with healthy reserve");
for(unsigned rate:{44100u,48000u})for(unsigned channels:{2u,6u})for(double hz:{1000.,4000.,8000.,16000.}){
const auto reference=render(rate,channels,hz,480,false);
const auto product=render(rate,channels,hz,480,true);