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(audio): preserve capture waveform continuity and endpoint recovery
Veyra Goal Agentdc44c483f720
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 0350d70e..d20339ea 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -392,6 +392,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformadd_library(veyra_sinks STATICsrc/sink/WasapiAudioSink.cppsrc/sink/CaptureAudioSession.cpp+ src/sink/CaptureAudioDsp.cppsrc/sink/ImageExportSink.cppsrc/sink/NvencD3D12Encoder.cpp)@@ -484,6 +485,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_features(veyra_audio_timeline_tests PRIVATE cxx_std_20)target_link_libraries(veyra_audio_timeline_tests PRIVATE veyra_sinks)add_executable(veyra_capture_audio_tests tests/integration/CaptureAudioTests.cpp)+ add_executable(veyra_audio_waveform_tests tests/integration/AudioWaveformTests.cpp)+ target_compile_features(veyra_audio_waveform_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_audio_waveform_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_include_directories(veyra_audio_waveform_tests PRIVATE ${FFMPEG_INCLUDE_DIRS})+ target_link_libraries(veyra_audio_waveform_tests PRIVATE veyra_sinks ${FFMPEG_LIBRARIES})target_compile_features(veyra_capture_audio_tests PRIVATE cxx_std_20)target_link_libraries(veyra_capture_audio_tests PRIVATE veyra_sinks)target_compile_features(veyra_live_presentation_tests PRIVATE cxx_std_20)diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.hindex 7363b886..a1482eba 100644--- a/apps/veyra/ui/LiveStatusPanel.h+++ b/apps/veyra/ui/LiveStatusPanel.h@@ -134,11 +134,15 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){}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"音频格式",std::format(L"{} Hz · {} bit / {} valid{}",s.captureAudio.inputSampleRate,s.captureAudio.inputContainerBits,s.captureAudio.inputValidBits,s.captureAudio.inputFloating?L" · Float":L""));rows.emplace_back(L"音画偏差 · 声音领先",ms(s.captureAudio.skewMs));rows.emplace_back(L"声音补偿",std::format(L"{:.1f} ms{}",s.captureAudio.compensationMs,s.captureAudio.limited?L" · 已达边界":L""));rows.emplace_back(L"PCM队列",std::format(L"{:.1f} ms",s.captureAudio.bufferedMs));rows.emplace_back(L"音频设备队列",std::format(L"{:.1f} ms",s.captureAudio.endpointBufferedMs));rows.emplace_back(L"音频重锚 / 溢出",std::format(L"{} / {}",s.captureAudio.resets,s.captureAudio.overflows));+ rows.emplace_back(L"欠载 / 可测缺口 / 插入静音",std::format(L"{} / {:.1f} / {:.1f} ms",s.captureAudio.underruns,s.captureAudio.underrunFrames/48.0,s.captureAudio.silenceFrames/48.0));+ if(s.captureAudio.clockStalledGaps)rows.emplace_back(L"时钟未量出时长的断流",std::to_wstring(s.captureAudio.clockStalledGaps));+ rows.emplace_back(L"转换峰值 / 超满幅 / 异常",std::format(L"{:.4f} / {} / {}",s.captureAudio.inputPeak,s.captureAudio.overRangeSamples,s.captureAudio.nonFiniteSamples+s.captureAudio.invalidPaddingSamples));}if(!s.colorStatus.empty())rows.emplace_back(L"实际颜色链路",s.colorStatus);if(!s.backendWarning.empty())rows.emplace_back(L"后端状态",s.backendWarning);diff --git a/docs/CAPTURE_AUDIO_ARTIFACT_REPAIR_2026-09-14.md b/docs/CAPTURE_AUDIO_ARTIFACT_REPAIR_2026-09-14.mdnew file mode 100644index 00000000..5d5b5d89--- /dev/null+++ b/docs/CAPTURE_AUDIO_ARTIFACT_REPAIR_2026-09-14.md@@ -0,0 +1,153 @@+# 采集音频爆音与沙沙声修复记录(2026-09-14)++> 2026-09-15 重新审查:用户明确否定当前候选的听感。下文阶跃过冲、cubic与块级峰值保护的历史结论不能作为用户沙沙声根因或修复成功的证明。新审查已复现补偿归零重建导致丢样,并发现峰值保护释放错误、空拉误淡入;但最新约15分钟会话保护/削波/欠载计数均为0,原始持续噪声仍须生产链波形定位。以 `CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md` 为当前方案;本轮未修改产品或交付新EXE。++## 结论++本次问题不是单一的“音量太大”。采集音频链路同时存在三个内部风险:采集卡媒体类型按枚举顺序选择,可能先选到 44.1 kHz;WASAPI 端点实际约 22 ms,而采集启动只预填约 10 ms;实时欠载时旧逻辑会直接停止并重置 renderer。另有部分设备可能使用有效位数小于容器位数的 PCM,旧路径没有保留 `validBits`。++本地 USB3 采集卡实际枚举顺序是 44.1 kHz、32 kHz、22.05 kHz、11.025 kHz、8 kHz,48 kHz 在后面。修复后选择 48 kHz/16-bit,而不是依赖枚举顺序。对于 `WAVEFORMATEXTENSIBLE`,有效 PCM 位在容器中可能是左对齐的;Microsoft 的结构说明见[官方文档](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ksmedia/ns-ksmedia-waveformatextensible)。++## 修改内容++- `AudioFormat.h` 增加采集格式排序:优先原生 48 kHz,再按临近采样率、声道布局、标准整数 PCM、完整有效位数排序。+- `CaptureCardSource` 保留并记录声道 mask、采样率、容器位数、有效位数、浮点标记,连接成功后输出最终选择的媒体类型。+- `CaptureAudioSession` 保留 `validBits`,对 16/32-bit PCM 清除容器低位填充,对 packed 24-bit 按左对齐规则扩展到 S32;转换后检查非有限值、削波和异常填充并纳入诊断状态。+- 采集 WASAPI 请求约 20 ms 端点缓冲,并将启动/重锚预填提高到最多 20 ms。该数值是抗调度抖动的安全窗口,不是端到端延迟承诺。+- 实时路径的短暂欠载不再写入伪造的媒体静音帧,也不立即 `stopAndReset`;端点保持静音、媒体时间线不被合成帧推进。连续约 30 ms 且输入也持续缺失时,先提交有限淡出,再清空 PCM、重置重采样/漂移校正并重新锚定。+- 状态面板区分欠载次数、缺口时长和实际插入的静音时长;欠载日志按首个/周期/持续故障限频。+- 集成测试改用非零低幅 PCM,新增 5.1、24-in-32 有效位数和真实采集卡音频状态检查;物理测试将应用增益设为 0,避免改变用户扬声器听感。++## 实际验证++构建目录:`out/build/audio-artifact-repair-20260914`。++构建命令:++```powershell+& '.\scripts\build.ps1' -Root (Get-Location).Path -Preset x64-release `+ -BuildDirectory (Join-Path (Get-Location).Path 'out\build\audio-artifact-repair-20260914') `+ -FfmpegRoot 'C:\veyra-deps\ffmpeg-ps5-dav1d-installed'+```++结果:完整增量构建 29/29、后续物理测试变更增量 2/2,均 exit 0。初次构建曾因 `CaptureAudioSession.h` 直接引入 `ks.h` 与工程 `GUID_NULL` 宏发生 include 顺序冲突而失败,改为前置声明 `WavePcmFormat` 后恢复;只有已有 FFmpeg/工程编译警告,没有新的编译错误。++针对性结果:++- `veyra_capture_audio_tests.exe`:exit 0;完整同步、模式切换、图 reset、持续欠载恢复和停止清理通过。持续输入故障在约 31 ms 后执行淡出/重锚,恢复后收到真实 PCM。+- `veyra_capture_audio_tests.exe --jitter`:exit 0;500 个 10 ms 输入块,追加 reset/underrun 为 0,p95 skew 26.29 ms,peak 0.0687,非有限/削波均为 0。+- `veyra_capture_audio_tests.exe --jitter --5.1`:exit 0;500 个 10 ms 5.1 输入块,追加 reset/underrun 为 0,p95 skew 23.74 ms,peak 0.0644,非有限/削波均为 0。+- `veyra_multichannel_tests.exe logs/audio-artifact-repair-20260914-prefill20`:exit 0,`MULTICHANNEL checks=31 failures=0`;24-in-32 转换峰值约 0.25,异常填充和非有限值为 0。+- `veyra_audio_timeline_tests.exe logs/audio-artifact-repair-20260914-prefill20 --jitter`:exit 0;1x/2x/4x 抖动倍率均为 0 underrun,文件音频连续播放通过。+- `veyra_capture_tests.exe capture:0:0:0:0`:exit 0;本机 USB3 Video + USB3 Digital Audio 静音物理回归通过。最终选择 48 kHz/16-bit/16 valid bits,2 秒收到 31 个音频块,输入 peak 0.01043,欠载 1 次/576 帧,插入静音 0,重锚 2 次。该结果证明本机真实链路运行,不证明反馈者采集卡或所有驱动均无欠载。++中间回归失败也已修正:第一次实时欠载方案把合成静音帧推进了媒体时间线,导致两个旧时序阶段失败;改为实时 `ReleaseBuffer(0)` 后完整采集音频测试恢复 exit 0。第一次物理音频断言因 source-only 测试没有视频呈现锚点而误判 renderer 未运行,实际已有 32 个音频块;测试改用显式音频时钟模式后复跑通过。++## 边界与未完成事项++- 物理回归使用的是本机 USB3 采集卡,不是反馈用户的具体型号;尚未取得反馈者新版日志和未静音听测,不能宣称所有采集卡的爆音/沙沙声已根治。+- 当前短暂实时欠载会产生真实的静音缺口,但不再把缺口伪造成媒体帧或用硬停止制造 click;若上游持续不发数据,产品只能淡出并重锚,不能凭空恢复丢失的音频。+- 本次没有修改 NVIDIA/NGX/DLSS 运行时,也没有执行 RTX runtime 的 Create/Evaluate;这是音频链路修复,不能用本机 GPU 结果替代音频验收。+- 未发布、未 push、未替换正式便携包或运行时文件。++## 二次排查:实测仍有声音后的复核++### 已确认的旧版内部触发点++重新逐行对齐 `logs/veyra-app.log` 后,确认旧版有一条与采集卡原始噪声无关的 click/爆音触发链:++```text+14:11:49.858 UI selector committed=true changed=true+14:11:49.859 video graph shutdown/rebuild+14:11:49.859 audio-fade submitted frames=240 realPcm=0+14:11:49.859 capture-audio-reset mode=0+```++也就是说,用户修改视频设置时,旧 `EngineController` 会调用采集源的 `videoReset()`;旧实现把仍然健康的音频 renderer 一起淡出、停止、清空 PCM 并重新锚定。同期长时间日志的 `underruns=0`,因此这条路径不能解释持续沙沙声,但足以解释设置切换瞬间的爆音。此前把这条旧日志误判成“自动时钟偏差重锚”是不准确的,已在本节纠正。++### 二次实现++- 视频图因设置重建时调用 `videoReset(false)`,保留没有断流的音频时钟、PCM 队列和 renderer;暂停/真正的音频断流仍可使用完整 reset。+- 用户主动修改音频同步模式或偏移时,记录 `capture-audio-sync ... reanchor=explicit-audio-setting`,执行有边界的淡出/重锚,使音频设置不会因为隔离视频 reset 而失效。+- 实时端点从短暂空拉恢复时,首段真实 PCM 增加约 5 ms 淡入,避免从任意非零采样硬切回来。+- 保留 5.1/24-in-32/非有限值和削波诊断;没有把测试容差变化当成音质修复。++### 二次验证结果++当前构建仍为 `out/build/audio-artifact-repair-20260914`。最终增量构建 29/29,测试夹具变更增量 2/2,均 exit 0。最新回归结果:++- `veyra_capture_audio_tests.exe`:exit 0;视频图 reset 保持音频时钟、显式音频同步设置、持续输入故障后的真实 PCM 恢复均通过。+- `veyra_capture_audio_tests.exe --jitter`:exit 0;500 个 10 ms 块,追加 reset/underrun 均为 0,p95 skew 20.4108 ms,非有限值/削波为 0。+- `veyra_capture_audio_tests.exe --jitter --5.1`:exit 0;追加 reset/underrun 均为 0,p95 skew 20.8171 ms,非有限值/削波为 0。+- `veyra_multichannel_tests.exe logs/audio-artifact-repair-20260914-second-pass`:exit 0,31 项检查、0 失败。+- `veyra_audio_timeline_tests.exe logs/audio-artifact-repair-20260914-second-pass --jitter`:exit 0;1x/2x/4x 文件音频均未发生 underrun,视频抖动没有停止连续音频。+- 本机真实 USB3 采集卡 `veyra_capture_tests.exe capture:0:0:0:0`:exit 0;最终选择 48 kHz/16-bit/16 valid bits,2 秒收到 31 个音频块,增益为 0,输入 peak 0.05127,记录 2 次/1632 帧欠载、0 帧软件插入静音、2 次重锚。它证明本机 DirectShow→音频会话→WASAPI 路径可运行,但不证明反馈者设备的听感已经正常;这次短测仍有调度边界风险。+- 同一台本机采集卡绕过 Veyra 的 DirectShow 原始录音约 10 秒:左右声道 peak 约 -41.27/-44.29 dBFS、RMS 约 -55.95/-60.99 dBFS,无满幅削波,但存在可测的低电平源噪声。该结果只说明本机输入源有噪声底,不能外推到反馈者的采集卡,也不能替代 Veyra 输出端的 loopback 对照。++### 当前结论与剩余闭环++“视频设置切换导致音频被硬重启”的内部 bug 已定位并隔离;但用户实测仍听到沙沙声,当前证据还不足以宣称沙沙声已经修复。因为尚未拿到反馈者在新版程序中的具体时间点、`capture-audio-format`/`live-audio-sync`/`capture-audio-underrun` 日志和输出录音,仍需区分:采集卡本底噪声、驱动/USB 调度欠载、Veyra 输出波形处理,还是扬声器/线路增益问题。未执行 RTX/NVIDIA runtime Create/Evaluate;未发布、未 push、未替换正式包。++## 三次排查:OBS 对照与尖锐瞬态复现++用户补充“同一采集卡在 OBS 没有沙沙声,Veyra 只在尖锐声音上出现”。这改变了判断:本底噪声不再是主假设,必须对比 Veyra 独有的波形处理。新增了阶跃/尖脉冲回归,不再只用低幅正弦覆盖音频链路。++### 复现到的真实内部机制++`CaptureAudioSession` 将采集 PCM 统一送入 48 kHz `SwrContext`。libswresample 默认 Kaiser 窗化 sinc 在瞬态边缘会产生过冲,旧代码随后把大于 1.0 的 float 硬裁剪到 [-1, 1]:++- 44.1 kHz 输入重采样到 48 kHz:修复前阶跃测试出现 30 个裁剪样本,峰值 1.05091。+- 即使输入已经是 48 kHz,只要音画自动同步调用 `swr_set_compensation`,同一个 context 也会进入有效变速重采样;修复前 48 kHz 补偿瞬态测试出现 32 个裁剪样本,峰值 1.13351。++这与“OBS 正常、Veyra 在尖锐声音上出现沙沙/砂砾声”高度吻合:稳态正弦和低电平声音不触发过冲,尖锐边沿会触发硬裁剪。当前证据是软件内部合成波形的可重复复现,不是凭用户描述猜测。++### 三次施工++实时采集的所有 `SwrContext` 统一设置 `SWR_FILTER_TYPE_CUBIC`,不只对非 48 kHz 输入设置;即使当前输入是 48 kHz,后续漂移补偿也仍然使用瞬态安全的滤波器。失败时不静默退回未知滤波器,日志增加 `capture-audio-resampler inputRate/outputRate/filter/compensationSafe`。++新增 `veyra_capture_audio_tests.exe --transient` 和 `--transient-comp`:分别覆盖 44.1→48 kHz 瞬态,以及 48 kHz + 自动漂移补偿瞬态。++### 最终复核++- 构建命令仍为 `scripts/build.ps1 -Preset x64-release -BuildDirectory out/build/audio-artifact-repair-20260914 -FfmpegRoot C:\veyra-deps\ffmpeg-ps5-dav1d-installed`;最终 29/29 exit 0。+- `--transient`:exit 0,峰值 0.999969,clipped=0,nonFinite=0。+- `--transient-comp`:exit 0,48 kHz 自动补偿期间峰值 0.999969,clipped=0,nonFinite=0。+- 完整 `veyra_capture_audio_tests.exe`:exit 0;图 reset 保持音频时钟、显式同步设置、持续欠载重锚和停止清理通过。+- `--jitter`:exit 0,追加 reset/underrun=0,p95 skew 20.6725 ms,clipped=0。+- `--jitter --5.1`:exit 0,追加 reset/underrun=0,p95 skew 20.7548 ms,clipped=0。+- `veyra_multichannel_tests.exe logs/audio-artifact-repair-20260914-final`:exit 0,31 checks/0 failures;`veyra_audio_timeline_tests.exe ... --jitter`:exit 0,1x/2x/4x 连续音频通过。+- 本机 USB3 实卡:exit 0,实际选择 48 kHz/16-bit/16 valid bits,收到 32 个音频块,增益为 0,peak 0.05359,欠载 1 次/576 帧,软件插入静音 0,重锚 2 次。它验证了当前本机链路,没有验证反馈者设备的最终听感。+- 独立 WASAPI 4 秒 harness:mix 48 kHz/2ch/32-bit,0 underrun,时钟漂移 0.01 ms,Stop+Reset padding=0,exit 0。++### 结论++“漂移补偿启动默认 Kaiser 过冲,再被 Veyra 硬裁剪”的瞬态失真已经在代码中复现并修复;这比此前仅看到欠载计数为 0 的证据强得多。但仍需反馈者用当前构建实测确认,因为用户设备可能还有独立的 USB 欠载、输入位宽或线路问题。当前程序路径和剩余验收边界不变;未执行 RTX/NVIDIA runtime Create/Evaluate,未发布、未 push、未替换正式包。++## 2026-09-15 用户复测否定 cubic:撤回低通方向并改为峰值保护++用户实际听测确认上一轮 cubic 方案使声音发闷,且沙沙声更明显。这个反馈否定了“换成 cubic 就是修复”的结论:上一轮 `clipped=0` 只证明 cubic 压住了过冲计数,不证明音频保真,也不能作为交付依据。上一节保留为历史排查证据,但 cubic 不再是当前实现。++本轮已从 `src/sink/CaptureAudioSession.cpp` 移除强制 `SWR_FILTER_TYPE_CUBIC` 及对应 `libavutil/opt.h` 依赖,恢复 libswresample 默认 Kaiser 窗化 sinc;当输入和输出同为 48 kHz 时保持原本的 identity 路径,只有实际发生采样率转换或时钟补偿时才进入重采样。针对 Kaiser/补偿在尖锐满幅边缘产生的 1.0 以上样本,改为转换块级共享增益保护:以 0.995 为上限,对整块 PCM 做线性缩放并带释放,不对样本逐点硬裁剪,不引入低通;`CaptureAudioState.peakProtectedSamples` 与限频日志记录保护是否实际触发,`clippedSamples` 只代表保护之后仍发生的硬裁剪。++实际构建命令:++`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -Preset x64-release -BuildDirectory "out/build/audio-artifact-repair-20260914" -FfmpegRoot "C:\veyra-deps\ffmpeg-ps5-dav1d-installed"`++最终代码构建 exit 0;随后测试目标增量构建 exit 0。串行回归结果:++- `veyra_capture_audio_tests.exe --transient`:exit 0;44.1→48 kHz 尖锐阶跃 `peak=1.05091`,`peakProtected=9582`,`clipped=0`,`nonFinite=0`。+- `veyra_capture_audio_tests.exe --transient-comp`:exit 0;48 kHz 自动补偿尖锐阶跃,实际日志 `peak=1.04561`、保护增益约 `0.951596`、`peakProtected=9570`,`clipped=0`。+- `veyra_capture_audio_tests.exe --jitter`:exit 0;p95 skew `20.4106 ms`,`clipped=0`。+- `veyra_capture_audio_tests.exe --jitter --5.1`:exit 0;p95 skew `20.3669 ms`,`clipped=0`。+- `veyra_multichannel_tests.exe logs/audio-artifact-repair-20260914-corrected`:exit 0,`checks=31 failures=0`。+- `veyra_capture_tests.exe capture:0:0:0:0`:exit 0;本机真实 USB3 采集卡实际选择 48 kHz/16-bit/16 valid bits,音频块 31,欠载 1 次/576 帧,测试增益为 0。它验证真实 DirectShow→音频会话→WASAPI 链路,不等于扬声器听感验收。++当前版本仍需用户用未静音的真实尖锐声做 A/B 听测;本轮没有执行反馈者设备,也没有执行 RTX runtime Create/Evaluate。只有在用户确认高频未变闷、尖锐声沙沙声消失后,才能把这条候选修复标记为听感通过。++## 2026-09-15 进一步修正:无补偿时真正恢复 identity,并修复重建生命周期++继续审查后发现,旧的 `clearCorrection()` 即使传入 `swr_set_compensation(swr,0,0)`,也会让 48 kHz 同速 `SwrContext` 进入强制 resample 标志;因此“48 kHz identity”在此前代码里并不完全成立。当前改为记录 `compensationActive`:无补偿时不调用该 API;补偿结束、欠载重锚、同步重置或大幅偏差重锚时,创建新的默认 context,并通过同一个 RAII owner 接管,恢复真正的 native-rate identity。此前一次重建测试发现旧智能指针仍持有已释放 context,已修正后才收口。++最终构建命令同上,完整 29/29、exit 0。最终串行证据:`--transient` exit 0(peak 1.05091、peakProtected 9582、clipped 0);`--transient-comp` exit 0(peak 1.13518、peakProtected 9570、clipped 0,重锚日志明确 `native-rate path restored`);`--jitter` exit 0(p95 20.7114 ms);`--jitter --5.1` exit 0(p95 20.4901 ms);`veyra_multichannel_tests.exe` `checks=31 failures=0`;`veyra_audio_timeline_tests.exe --jitter` 的 1x/2x/4x 均通过;本机 `capture:0:0:0:0` exit 0,实际 48 kHz/16-bit/16 valid bits,31 音频块,欠载 1 次/576 帧,增益0,peak0.13455。++这次才是当前候选构建,路径仍为 `out/build/audio-artifact-repair-20260914/veyra.exe`,文件大小 3,375,616 bytes,SHA-256 `A98B657FA5F66F5C2A3CD26ADBFE0051DDB7C8EA7DCFC7F5D8907909D57EA7FA`。自动化和本机链路均通过,但反馈者的未静音听感仍未完成,不能把“沙沙声已消失”写成事实。diff --git a/docs/CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md b/docs/CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.mdnew file mode 100644index 00000000..3a4a581b--- /dev/null+++ b/docs/CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md@@ -0,0 +1,199 @@+# 采集音频沙沙声:重新审查与波形闭环方案++日期:2026-09-15。状态:**已实施已知缺陷修复,最终专项回归通过;真实火堆/口哨听感未验收**。++> 下文§1–5保留首次审查时状态。当前实施与验证以文末§6为准,不将已知缺陷修复泛化为持续沙沙声已根治。++本轮用户报告火堆、吹口哨呼唤马匹时仍有沙沙声,OBS 对照正常,要求重新审查前序 Luna 改动并给出方案。不能将旧“开始修复”扩展为这次未请求的盲改。当前只新增离线诊断脚本、方案和工作记录;不替换 EXE、不发布、不改运行时。++## 1. 结论及证据等级++1. 前序将“合成满幅阶跃会过冲”直接认定为用户沙沙声根因,证据不成立。尖锐的音高不等于接近数字满幅;满幅阶跃可触发削波,不证明真实口哨/火堆触发了同一机制。+2. cubic 已撤回,当前默认 Kaiser 路径仍被用户否定。不能继续低通、按块自动压音量,也不能把 `clipped=0` 当保真验收。+3. 当前代码有三个可确认的缺陷/风险:峰值保护增益跳变和释放错误;补偿归零时销毁有延迟历史的重采样器;把软件空拉等同设备断音并触发淡入。前两个有离线数值反例,第三个有代码与 WASAPI 合同依据。**这些不是对全部持续沙沙声的已证实解释。**+4. 固定补偿的实际 libswresample 离线测试未发现明显高频杂散失真。当前重点应是动态时钟控制、块拼接/端点提交及采集协商与 OBS 的差异,不是换一种滤波器赌听感。+5. 缺失的决定性证据是:同一次问题声音在原始输入、转换后、最终提交和系统回录四个位置的波形。拿到首次出现额外失真的阶段,再修改该阶段。++## 2. 当前构建和真实使用日志++审查构建:`out/build/audio-artifact-repair-20260914/veyra.exe`。++SHA256:`A98B657FA5F66F5C2A3CD26ADBFE0051DDB7C8EA7DCFC7F5D8907909D57EA7FA`。本轮未重编译/替换。已有未提交改动全部保留,包括 MOV 负 AAC PTS 修复与采集设备枚举改动。++`logs/veyra-app.log` 最新完整采集会话从第26036行开始,2026-09-14 16:09:11Z 至16:24:13Z,即本地9月15日00:09–00:24:++- 配置48 kHz / S16 / stereo,有效位16,音量1;明确记录 `default-kaiser-or-identity` 和 `native-rate path restored`。可证明使用了当前修复路径,但旧日志没记录完整 EXE hash,不冒充逐字节匹配证明。+- 448条 `live-audio-sync`,全程累计 `peakProtected=0 clipped=0 underruns=0`,最终转换后峰值0.95073;`resets=1`。+- `native-rate path restored` 共5次,最后在16:10:18.894Z。它们未计入 `resets`,所以旧 `resets=1` 不能证明重采样器没被重建。+- 后段持续非零 `correctionPpm`,例如末条-1243.0,软件补偿时长0ms不等于关闭变速。最终块间隔10.019ms、块时长10ms。+- 日志没有用户标记的口哨/火堆精确时刻,也没有输出PCM。因此不能把该会话某条状态强行绑定到某一次听感。++这段日志对候选原因有反证价值:新增峰值保护和空拉淡入未在这段会话触发,不能拿这两个问题解释这段会话全程持续噪声;5次早期重建也不能解释十多分钟后仍出现的问题。++## 3. 前序代码审查++### 3.1 块级峰值保护不是“保持波形与频谱”++位置:`src/sink/CaptureAudioSession.cpp:204–215`。++- 攻击时整块增益瞬变,块边界没有连续包络。+- 释放分支用 `min(1, gain+0.05)`,而非受当前安全目标约束。同样峰值1.05的连续块,增益在0.947619与0.997619间来回切换;第二块保护后峰值仍1.0475,随后真实硬裁剪。+- 下一块峰值低于0.995时完全不乘保留的 `peakGuardGain`,立即回到1;所谓释放状态没有实际应用。+- 注释“never hard-clips”与紧接的 `std::clamp(sample,-1,1)` 矛盾。局部常数缩放不等于整个时变信号频谱不变。+- 指标 `inputPeak` 位于 `swr_convert` 后、保护前,不是采集原始输入峰值,UI与诊断命名要纠正。++### 3.2 补偿归零不能直接换 context++位置:`src/sink/CaptureAudioSession.cpp:102–110, 332–338`。++`delta==0` 且曾进入补偿时,`clearCorrection()` 不 drain、不衔接,直接释放旧 `SwrContext`,丢掉滤波历史和待输出内容。它还将滤波误差和增益状态清零,混淆“暂时零校正”与“会话断点”。++本轮直接调用应用目录 FFmpeg 9.0.1 的 DLL,用-1250ppm、0.5幅值连续4kHz正弦,1秒处将补偿置零,对比“保留context,仅取消补偿”和“销毁重建”:++- 旧 context 仍有16输入帧延迟;最终 drain 后,重建分支少17输出帧。+- 边界后的第一个样本:保留为-0.496447,重建为+0.325928。+- 边界后48帧最大差0.871988。++这是实际库的离线波形反例,不是完整播放器或实卡听测。相位偏差和丢样比0.35ms时长本身更重要。++FFmpeg 的 `swr_set_compensation(s,0,0)` 在**未创建 resampler**时会强制初始化重采样,这个前序发现成立。但正确边界是“首次启动选择好策略,活跃后保留历史”,不是每次补偿归零切回直通。[FFmpeg API说明](https://ffmpeg.org/doxygen/trunk/group__lswr.html)。本机源代码另核对 `C:/veyra-deps/ffmpeg-ps5-slices-source/libswresample/swresample.c:909` 与 `resample.c` 的补偿实现;实际执行证据以应用DLL为准。++### 3.3 空拉不等于设备已经断音++位置:`src/sink/WasapiAudioSink.cpp:401–460`;`include/veyra/sink/AudioGain.h:25`。++当前 `got==0` 就累计欠载并把下次PCM套5ms淡入;没有确认设备队列是否耗尽。`padding` 是尚待播放的有效帧,不是无声帧,见[Microsoft合同](https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getcurrentpadding)。++例如空拉时还有480帧/10ms,下一次回调在耗尽前到达,完全可以连续播放,却会在新块开头把增益变为1/240(约-47.6dB)再升回去。它能人为制造音量缺口。只检查 `padding==0` 也不够:应结合实际设备时钟、最后提交终点与实际写入时刻,分辨无缝接续和真实空洞;记录不足时注明未知。++此外,把可写容量 `avail` 累加为“缺失帧”会重复计算未填的空位,不能把此计数直接解释为声学丢失时长。++### 3.4 动态同步仍是待验证候选,不能直接判死刑++位置:`src/sink/CaptureAudioSession.cpp:252–258, 321–339`;`ArrivalClockMapping.h`。++当前每250ms由音画相位差更新变速,误差平滑为0.75/0.25,最大±5000ppm,每次变化最多250ppm,没有稳定死区;音频输入映射取2秒窗口最小值,视频延迟则取最新呈现值。它可能将呈现抖动、固定安全缓冲偏差混入真实设备频差。非零补偿本身并不是错误,独立采集/播放时钟本来就可能需要校正。++本輪固定-1250ppm、1/4/8/16kHz、0.5幅值S16测试:原生同速转换与S16/32768逐样本误差0;固定补偿拟合实际输出频率后,残差分别约-100.53/-100.96/-105.82/-112.71dBFS,幅值约0.5。未包含动态控制器、WASAPI、系统APO或真实输入。**因此没有证据说默认 Kaiser 本身必然造成可闻沙沙声。**++初次分析只用理论频率拟合,出现较高残差;复核发现是FFmpeg整数步长导致微小频差,已改为拟合实际频率,不能将频偏误报为噪声。++上游OBS的[FFmpeg重采样封装](https://github.com/obsproject/obs-studio/blob/master/libobs/media-io/audio-resampler-ffmpeg.c)也调用libswresample。仅作接口/行为参考,未复制代码;没有审计用户安装的OBS版本,也不将OBS全部监听策略直接搬入Veyra。++### 3.5 旧测试为什么漏检++- `--transient` 给44100Hz满幅矩形脉冲,仅检查计数;没有视频锚点,默认auto模式不启动播放端点。+- `--transient-comp` 是满幅平台,结束前断供150ms,最终补偿状态可能已经重置;不检查输出频谱、块边界或累计丢帧。+- 两者及物理回归设置增益0。静音本身可以用于安全自动测试,但必须在静音前截取输出验证,现有测试没有这样做。+- `--jitter` 循环重复同一小块正弦,非连续相位;只检查时间偏差/计数,不检查波形,不能验收高频保真。+- 已通过的格式、5.1、恢复、同步检查仍有价值,但覆盖范围必须如实收窄。++## 4. 实施顺序(待用户要求开始修复)++### P0:先固定失败与可观察证据++1. 固定当前代码/EXE身份,保留原包;仅本地新建候选构建目录,不覆盖用户正在测试的文件。+2. 在共享生产链上增加默认关闭的有界诊断tap:A原始回调PCM(格式/帧数/PTS),B重采样后,C音量/声道映射后、WASAPI提交前;同步记录每次补偿值、context epoch、延迟样本、pull数量、padding、设备时钟和写入帧序号。音频线程只写预分配内存环,后台限时落盘,满了明确标记diagnostic drop,不阻塞播放。仅记录用户选择的采集来源,不后台录麦克风或保存其他程序声音。+3. 同一次捕获的连续PCM在自动夹具中重放,分别跑当前生产链、固定补偿链和短时同速基线。不能依赖两次游戏随机火焰具有相同波形;原始录音及输出保持gitignore。+4. 必要时由用户显式启动回录,比较D系统输出。记录OBS比较的是监听还是录制、输出设备、采样率、声道/滤镜/增益,避免拿OBS录制文件与Veyra不同输出设备混比。一次只监听一路,避免双路叠加,但不预设用户犯了这个错误。++分流标准:A已异常→检查协商/回调/动态格式,和OBS同输入交叉验证;A干净B异常→转换/补偿;B干净C异常→增益/降混/缓冲;C干净D异常→端点提交、系统格式转换/APO/时钟。任何阶段不能凭峰值一个数代替波形。++### P1:去除已证实的新增失真,单变量验证++1. 撤销块级peak guard;保持默认高质量重采样,不换cubic、不加降噪/低通。有限浮点样本保留内部余量,异常NaN/Inf防护保留;若真实输出证明存在过载,单独设计最终音量/降混后的可验证输出余量策略,不通过无标注AGC掩盖问题。+2. 一个连续音频epoch保持同一重采样历史。自动模式在预填阶段准备连续重采样路径,避免播放中首次切入或归零切出;已激活的context归零只更新校正,不重建、不drain中断、不偷偷丢PCM。真正设备重连/PTS断点才明确reset和重锚;手动模式切换仍保留显式语义。+3. 空拉且端点仍有可连续播放数据时,不改后续音量,不记为已发生声学缺口。将 `emptyPull`、实际/可确认的设备gap、软件填零帧分开。真实中断的恢复才做有限淡入,不能为“去爆音”制造每块音量洞。+4. 保留独立的设备音频枚举、validBits解析、20ms预填、视频图重建不重启健康音频、MOV合法负PTS修复,不整文件回退。++### P2:按证据修动态同步,而不是永久关闭同步++1. 分离“固定软件延迟目标”和“采集—输出硬件频差”。固定延迟由预填与稳定锚点处理;频差用较长窗的累计实际音频帧、有效PTS和输出时钟趋势估计,不能用单次GPU/Present毛刺直接调音高。+2. 仅在P0对照证实后调整控制器:延迟目标去毛刺/稳定死区、频差估计平滑、变速比例连续且有界,记录每次实际请求。窗口/死区/上限必须通过波形和±1000ppm测试确定,不能拍脑袋把5000改成100就交付。+3. 不把“关闭自动同步”作为最终修复:短时同速基线只做因果对照,长时保持独立时钟校正、队列上限、真实PTS;不得靠丢PCM、插伪静音、无限缓冲或视频欠速拖慢声音通过。++### P3:新的交付门槛++| 场景 | 必须验证 |+| --- | --- |+| 连续相位1/4/8/16kHz,多个低于满幅的电平 | 同速转换逐样本正确;扣除真实必要变速后,不出现额外明显杂散/频响下陷;不能靠低通过关 |+| 补偿正→零→负、零附近往返、长时间固定补偿 | 有界且连续的历史、帧数/延迟闭合;无context切换丢样,无块边界尖峰 |+| 5/10/20ms块及不同边界相位 | 相同PCM换分块不改变结果(允许正确重采样舍入),无块级增益调制 |+| 空pull但padding未耗尽;真实延迟回调与断流 | 前者无淡入/静音/声学gap;后者准确计数、受控恢复,不伪报缺口时长 |+| 真实口哨、火堆与宽带噪声/多音/瞬态 | A/B/C/D确定首次失真位置;同一素材、同输出设备、匹配音量与OBS听测一致性验证 |+| ±1000ppm各120秒,视频30/35ms抖动与大延迟阶跃 | 同步误差和队列有界,无普通抖动触发reset;现有同步门槛不放宽,单次不超过300秒 |+| 立体声/5.1、packed24/24-in32、44.1→48、输出44.1/48/96(设备可用时) | 格式及声道位置正确,降混后也不过载;不可用设备标未执行 |+| 文件音轨含合法负PTS、PS5共享renderer、暂停/重连 | 不回归首帧死锁、已知恢复或其他入口声音;RTX增强测试单独报告 |++具体保真基准:对固定比率正弦排除启动/尾部后拟合实际频率,残差相对同库连续参考不劣化超过3dB,1–16kHz稳态幅度相对参考偏差≤0.1dB;同速无补偿的整数到浮点转换与直接归一化一致。动态变速须按实际采样轨迹比较,不能用固定正弦频率误判正常频偏。补偿归零丢弃待输出帧必须为0;无真实断流时新增淡入必须为0。以上是待执行门槛,不是这次已验收结果。++## 5. 本轮实际命令和产物++环境Python3.11、numpy2.4.3。执行(退出码0):++```powershell+python scripts/diagnostics/audio-waveform-audit.py --dll-dir out/build/audio-artifact-repair-20260914 > logs/audio-waveform-audit-20260915/offline-dsp.json+```++脚本调用实际应用目录的 `avutil-61.dll`、`swresample-7.dll`,hash匹配所选patched FFmpeg prefix;只做内存内合成数据测试,不打开扬声器或采集设备。峰值保护/淡入案例显式标为代码算术模型,不冒充生产库集成。++FFmpeg DLL SHA256分别为 `C46EE9C04E8DADA7BEB4AEEE12F93A5D147D758E990F204141AA163D427B9688`、`A6A6876291DFA42E5609261DF2212038A2C7536EFCA0372E3899E12F8073B339`。++尚未执行:本轮产品构建、生产链tap/loopback、用户火堆/口哨录音比对、实卡听测、新同步控制器、RTX Create/Evaluate。未改任何DLL、SDK、版本号、发布资产。没有外部Reviewer验收。++下一条唯一任务:P0——在当前失败生产链增加受控波形证据与重放回归,先找到额外失真首次产生的位置,再逐项实施P1/P2并按P3验收。++## 6. 用户要求先修已知缺陷后的实施(2026-09-15)++本轮按“先把当前的问题修复”实施已确认的三处缺陷,不根据未验证假设调整动态同步控制器。未自动记录用户音频,完整原始/转换/提交三处tap及真实游戏素材同源对照尚未实施;通过共享生产DSP的离线波形对照、实际WASAPI受控空拉、现有产品集成回归先闭合P1。++### 实际修改++- 新增共享 `CaptureAudioDsp.h/.cpp`。`CaptureRateCorrection` 在自动模式新epoch预填前准备重采样;整个连续epoch内正/零/负补偿只更新同一context。归零不销毁、不清空滤波历史,不重置控制器误差。仅真正输入断点/端点恢复/显式同步重设仍走原有重置路径。+- `CaptureAudioSession` 移除块级peak guard及转换阶段的有限值硬裁剪。`inspectCapturePcm` 只清理NaN/Inf,记录转换后峰值与超过unity的样本;最终增益/声道处理仍在renderer。有限浮点超满幅不再错误等同已发生削波。保留旧状态字段兼容调用,`peakProtectedSamples/clippedSamples` 在此转换路径不再增加,不以它们为保真验收。+- `LiveAudioGapTracker` 依据padding为零且设备已消费位置超过已提交终点确认可观察缺口;按新增的时钟帧差计数,不重复累加可写容量。一段持续缺口只计一次事件;会话恢复判断同时看新增缺口帧,以保持30ms持续断流恢复。空pull仍有设备排队PCM时不触发淡入。+- 新增 `emptyPulls` 与 `recoveryFades`,同步日志明确列出 `convertedPeak`、`overRange`;UI将“输入峰值/保护”改为“转换峰值/超满幅”。设备时钟采样仍非物理声学测量,不能据零计数承诺驱动层零glitch。+- 保留设备音频枚举、validBits/packed24解析、20ms预填、视频图reset隔离、MOV负AAC起点修复;未调整现有同步上限/测试容差、未改DLL或SDK。++### 已执行验证和构建++新增 `tests/integration/AudioWaveformTests.cpp`,链接与产品相同的DSP实现及应用FFmpeg。覆盖44.1/48kHz、2/6声道、1/4/8/16kHz、正零负补偿、480/127帧分块;全部与保留历史参考的输出数量一致,逐样本最大误差0。反向故障控制重新引入滤波历史reset时,参考96001帧,错误分支95935帧,测试能检出。有限超unity、NaN/Inf、正确应用后续音量以及缺口状态检查合计43项通过。++另一个真实WASAPI用例在暂停端点中预填PCM,然后制造空pull:实际 `emptyPulls=1 gaps=0 fades=0`,再提交PCM仍无误淡入。端点暂停且音量0,不播放扬声器,也不将此测试当作声学验收。++首轮新构建因新增测试缺少 `<string>` 编译失败(C2039/to_string);补齐后构建成功。随后沿用现有PS5依赖配置重新启用RemotePlay,完整326/326构建成功,避免沿用前序音频候选 `VEYRA_ENABLE_REMOTEPLAY=OFF`;最终新增实际端点用例增量2/2成功。原候选目录未覆盖。++构建目录:`out/build/audio-continuity-repair-20260915`。完整命令:++```powershell+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root 'C:\Users\123\Desktop\Veyra DLSS Video Player' -Preset x64-release -BuildDirectory 'C:\Users\123\Desktop\Veyra DLSS Video Player\out\build\audio-continuity-repair-20260915' -FfmpegRoot C:\veyra-deps\ffmpeg-ps5-dav1d-installed -RemotePlay -ChiakiCheckout C:\veyra-deps\chiaki-source -ChiakiStage 'C:\Users\123\Desktop\Veyra DLSS Video Player\out\remoteplay\chiaki-msvc-stage' -RemotePlayPrefixPath C:\veyra-deps\remoteplay-installed\x64-windows-static -ProtocPath C:\veyra-deps\remoteplay-installed\x64-windows\tools\protobuf\protoc.exe -PkgConfigPath C:\veyra-deps\vcpkg\downloads\tools\msys2\3e71d1f8e22ab23f\mingw64\bin\pkg-config.exe+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915+powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -DriftOnly+```++首套11个独立进程均exit0:离线波形、实际排队空拉、采集基线同步/模式切换/恢复、立体声抖动、5.1抖动、44.1k和补偿瞬态浮点余量、端点故障注入恢复、多声道31项、完整文件音频时间线、文件抖动。每个用例独立限时,最长120秒;漂移用例各限150秒,不并发争用端点。瞬态仍只验证转换余量,不冒充实卡听感。++构建和回归日志:`logs/audio-continuity-repair-20260915/`,首套汇总 `results.json`,波形证据 `waveform.stdout.log`,实际端点证据 `queued-empty-pull.stdout.log`。本地原版NR hash复核仍为批准的E16BCF…FC8E;运行组件未修改。漂移与最终交付状态待下文收口。++### 对抗复核发现并修正的第二个断流边界++首套测试虽然全部返回0,但复核输入断供日志发现emptyPulls增加、设备时钟没有越过最后提交帧,未触发恢复;旧基线测试在恢复时同时切换了同步模式,显式模式reset掩盖了这个漏检。本轮未将这组通过直接作为最终验收。++新增 `--endpoint-gap`:真实WASAPI预填240帧、音量0,播放端点连续80ms无输入、8次pump,再恢复PCM。只依赖时钟帧差的第一版真实失败:`emptyPulls=8 gaps=0 fades=0`,证据 `true-gap-before.stdout.log`。++修正为双证据策略:设备时钟能量出缺口时仍按真实帧差计数;对时钟停在队列尾部的设备,连续两次确认端点为空且间隔至少一个实际 `GetDevicePeriod` 后才判持续断流。排队PCM仍在、短暂空观察或显式暂停不触发;不把墙钟等待伪造成已测设备缺失帧,单列 `clockStalledGaps`,日志 `clockMeasuredMissingFrames=unknown`,UI明确这类断流时长未量出。持续空pull仍可推进30ms恢复观察,避免缺口只记一次事件后失去恢复资格。++修后真实用例 `emptyPulls=8 gaps=1 fades=1`,且排队空拉仍 `emptyPulls=1 gaps=0 fades=0`。新增4项状态断言后离线波形47/47通过。基线测试改为断流前后保持相同auto模式,并在恢复输入之前断言已完成重锚;最终日志明确 `PASS persistent dry input recovers without a sync setting change`。++最终行为构建为 `build-verified.log`,增量34/34成功;所有回归在 `logs/audio-continuity-repair-20260915/final/` 重新执行,不用前一版结果代替。初次 `cmd /c` 使用正斜杠路径被cmd拒绝,改为反斜杠后正常,未改变构建参数。++### 最终收口++- 最终12组短回归全部exit0;生产DSP47/47、实际WASAPI有队列空pull与真实断供用例均通过。+- 最终 `-DriftOnly` 两组各120秒的合成输入时钟+真实WASAPI回归均exit0:1.001倍输入P95软件偏差4.24594ms,0.999倍4.30137ms;missing=0、resets=1(仅启动)、队列高水位均89.6458ms。同期同步日志无欠载或误恢复淡入。证据 `final/drift-results.json` 和两份stdout日志。不冒充物理采集卡晶振或端到端声学测量。+- 最终完整GUI空界面2秒启动检查exit0,日志 `final/gui-smoke.log`;没有播放媒体、没有执行NR/NVOF,不将零帧视为播放通过。+- 当前EXE:`out/build/audio-continuity-repair-20260915/veyra.exe`,11,442,688字节,SHA256 `F26C655DDF7D9CF07FBA35AEA323059B9F65708139AB580015CF788B23D1D552`。原测试EXE仍保留,hash未变。+- `git diff --check`通过(现有CRLF提示);源码Git无新增DLL/SDK/模型。旧审查Python生成的单个PYC缓存已清理,仅移除本次工具产物,没有删除用户源文件。+- 未做RTX Create/Evaluate、全GPU delivery gate、真实火堆/口哨听测或分段PCM录音;没有push/Release,未替换任何运行组件。++下一条唯一任务:用这个明确路径的新构建复测同一火堆/口哨场景。若仍有噪声,直接做原始PCM→转换后→最终输出前的同源波形定位;已通过的自动检查不代替用户听感,也不作为再次盲改滤波器的理由。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 354194c2..a8f7e2f6 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -2042,6 +2042,16 @@ GitHub Release https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.0.0 于本地 `package-portable.ps1` 已成功生成带 `dav1d.dll`、DAV1D 版权/SPDX 和 FFMPEG provenance 的1.2.0测试包。`portable-smoke.ps1` 的基础、社区NR、DLSS NR/FG场景产生了有效输出;最后的既有 VideoSR 断言因当前驱动未加载脚本要求的 `_nvngx.dll` 失败,日志保留在 `out/media-codec-dav1d-portable-smoke/video-sr-nr-fg.stdout.log`,不归因于AV1/MOV。新 FFmpeg 仍未替换1.2.0 GitHub Release,未制作/上传包含 dav1d 对应源码/port 的正式对应源码包;用户原始文件、长时播放、10/12-bit、4:2:2/4:4:4 和其他显卡尚未验收,不能宣称所有格式和设备均已支持。+## 2026-09-14 采集音频爆音与沙沙声修复(本地)++用户反馈采集卡音频偶发爆音、沙沙声,且已有多名用户反馈。排查确认采集音频格式可能按 DirectShow 枚举顺序先选 44.1 kHz;本机 USB3 卡实际 48 kHz 在后面。旧实时 renderer 在欠载时会直接停止/重置,WASAPI 实际共享缓冲约 22ms 而采集回调按10ms协商、启动只预填约10ms;另外 `validBits` 未贯穿,24-in-32/packed 24-bit 存在解释风险。++本地施工增加48kHz优先的媒体类型选择、格式/validBits诊断及PCM归一化(16/32/packed24)、非有限值/削波/填充检查;采集端点请求20ms并预填20ms。短暂实时欠载改为不写伪造媒体静音帧、不推进媒体时间线,持续约30ms且输入同时缺失时先淡出,再重置PCM/重采样/漂移校正并重锚,避免硬停止造成 click。UI 分开展示欠载次数、缺口和真正插入的静音;欠载日志限频。物理回归测试增益固定0,避免听感干扰。++实际构建:`scripts/build.ps1 -Preset x64-release -BuildDirectory out/build/audio-artifact-repair-20260914 -FfmpegRoot C:\veyra-deps\ffmpeg-ps5-dav1d-installed`,完整增量29/29、物理测试变更增量2/2,均 exit0。初次构建曾因 `CaptureAudioSession.h` 直接引入 `ks.h` 与工程 `GUID_NULL` 宏发生 include 顺序冲突,改为前置声明后恢复。`veyra_capture_audio_tests.exe` exit0;`--jitter` 与 `--jitter --5.1` 均 exit0(500×10ms,追加reset/underrun=0);`veyra_multichannel_tests.exe` `checks=31 failures=0`;`veyra_audio_timeline_tests.exe --jitter` 1x/2x/4x均0 underrun。真实本机 `veyra_capture_tests.exe capture:0:0:0:0` exit0:选择48k/16-bit/16 valid bits,收到31个音频块,peak0.01043,欠载1次/576帧、插入静音0、重锚2次;测试全程应用增益0。首次实时欠载方案把合成静音推进媒体时间线导致时序阶段失败,改为不伪造实时媒体帧后复测通过;首次物理音频断言因测试没有视频锚点误判renderer未运行,改用显式音频时钟后通过。日志/证据目录为`logs/audio-artifact-repair-20260914*`,完整记录见`docs/CAPTURE_AUDIO_ARTIFACT_REPAIR_2026-09-14.md`。++未修改NVIDIA/NGX运行时,未执行RTX runtime Create/Evaluate;未发布、未push、未替换正式包。真实反馈者采集卡型号、驱动与未静音听测仍待验收,不能宣称所有设备零欠载或问题已根治。下一步唯一任务:让反馈者使用本地修复版复现并回传`capture-audio-format`、`live-audio-sync`和`capture-audio-underrun`日志及听感时间点。+## 2026-09-14 用户 MOV 黑屏:负 AAC 起始 PTS 修复(本地)用户提供 `C:/Users/123/Videos/2026-08-11 21-29-44.mov`,反馈打开黑屏。文件 SHA256 为 `4D826CE4487F19A43375DC2BD8C4A0221926B5A9C29CD224E55FA9B6BFFEAC0A`,容器为 QuickTime/MOV,视频 H.264 High 2940x1912 60fps yuv420p,音频 AAC-LC 2ch 48kHz。视频-only 无损去音轨副本可以正常呈现,原文件软件解码和 D3D12VA 探针也分别 PASS,故排除 MOV/H.264 解码、硬解纹理导入和颜色初始化;原文件全播放器复现的黑屏只在带 AAC 音轨路径出现。@@ -2049,3 +2059,63 @@ GitHub Release https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.0.0 于根因是 `AudioPipeline::runOnAudioThread` 将 `headPtsMs()` 的所有负值都当成“没有可用音频”,而该 MOV 的 AAC 编码首帧合法起始 PTS 为 `-1.3ms`(编码器 priming)。音频 endpoint 因此只打开未锚定,音频主时钟没有启动,文件调度一直没有进入首帧呈现。`src/sink/WasapiAudioSink.cpp` 现在以实际预填充时长区分“空队列”与合法负 PTS,仅在 `prefetchedMs>0` 且 PTS 有限时锚定 renderer;`clockExhausted` 同步按预填充是否为空判断。未改变音频时间线、补偿、重采样或无音频文件路径。修复后重建 `out/media-codec-dav1d`(`scripts/build.ps1 ... -FfmpegRoot C:/veyra-deps/ffmpeg-ps5-dav1d-installed`,44/44 增量步骤成功,最终 build exit 0)。原始 MOV 全播放器无增强 10 秒测试 exit 0,`renderer ANCHORED ptsMs=-1.3` 后释放保持,`smoke frames=542 generated=0 failed=false`,`realPresented=540`、`presentSubmitFps=60.00`;证据 `out/mov-audio-fix.stdout.log`,FFmpeg 的 `UDTA parsing failed retrying raw` 仍为可恢复元数据警告,AAC 仍有 skipped-samples 时间戳警告但不再阻止播放。软件 H.264 30帧媒体探针、D3D12VA/共享设备 12帧探针、NGX NR Create/Evaluate/Release(0x1、SEH0)、`veyra_source_tests` 及 `veyra_audio_timeline_tests`(完整实时/WASAPI/恢复/欠速用例)均 exit 0。未改 GitHub Release、未替换正式包、未执行用户肉眼画质验收。++## 2026-09-14 采集音频尖锐瞬态砂砾声:重采样过冲修复(二次施工)++用户补充同一设备在 OBS 无沙沙声、Veyra 只在尖锐声音上出现。新增尖锐阶跃与自动补偿瞬态夹具后复现了内部原因:libswresample 默认 Kaiser 在 44.1→48 kHz 瞬态中产生峰值 1.05091,Veyra 的硬裁剪记录30个 clipped;输入本来就是48 kHz时,`swr_set_compensation` 启动有效变速后同样产生峰值1.13351、32个 clipped。故不是继续泛化为“采集卡本底噪声”。++`src/sink/CaptureAudioSession.cpp` 现在为实时采集的所有 `SwrContext` 设置 `SWR_FILTER_TYPE_CUBIC`,包括48 kHz后续进入漂移补偿的路径,并记录 `capture-audio-resampler` 的输入/输出采样率、滤波器和 `compensationSafe=1`。测试 `veyra_capture_audio_tests.exe --transient` 与 `--transient-comp` 均 exit0:峰值0.999969、clipped=0、nonFinite=0。新增这一轮不是把诊断计数清零,而是先在真实转换输出上消除触发过冲的滤波器。++最终构建命令:`scripts/build.ps1 -Preset x64-release -BuildDirectory out/build/audio-artifact-repair-20260914 -FfmpegRoot C:\veyra-deps\ffmpeg-ps5-dav1d-installed`,29/29、exit0。最终 `veyra_capture_audio_tests.exe`、`--jitter`(p95 skew 20.6725ms、clipped0)、`--jitter --5.1`(p95 skew 20.7548ms、clipped0)、`veyra_multichannel_tests.exe`(31/31)、`veyra_audio_timeline_tests.exe --jitter`(1x/2x/4x)均 exit0。最终本机 USB3 实卡选择48k/16-bit/16 valid bits,收到32块,peak0.05359,欠载1次/576帧,软件插入静音0,重锚2次;增益为0,未作扬声器听感宣称。独立WASAPI harness为48k/2ch/32-bit,4秒0 underrun、drift0.01ms、Stop+Reset padding=0,exit0。++本轮修改与证据详见 `docs/CAPTURE_AUDIO_ARTIFACT_REPAIR_2026-09-14.md`。当前构建路径为 `out/build/audio-artifact-repair-20260914/veyra.exe`;未修改NVIDIA/NGX运行时,未执行RTX runtime Create/Evaluate,未发布、未push、未替换正式包。仍需反馈者在该构建上复测并回传听感时间点及 `capture-audio-resampler`、`capture-audio-samples`、`live-audio-sync` 日志;若新版仍有声音,再按实际采样率/补偿/欠载数据排查第二条路径。++## 2026-09-15 用户复测否定 cubic:撤回并改为无低通的峰值保护++用户明确反馈 cubic 版声音变闷、沙沙声反而更明显。上一条“cubic 已修复”结论撤回:测试中的 `clipped=0` 仅证明过冲被滤波器压掉,不能证明保真或听感正确。++已从 `src/sink/CaptureAudioSession.cpp` 移除强制 cubic 和 `libavutil/opt.h`,恢复默认 Kaiser/48 kHz identity 路径;对重采样转换块只做共享线性增益峰值保护(ceiling 0.995、释放过程),不再逐样本硬裁剪、不用低通。新增 `peakProtectedSamples`,并对保护日志限频;UI 显示“输入峰值 / 保护 / 异常”。这条实现的意图是保留高频与瞬态,只处理过滤器过冲造成的满幅削波。++实际命令 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1 -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -Preset x64-release -BuildDirectory "out/build/audio-artifact-repair-20260914" -FfmpegRoot "C:\veyra-deps\ffmpeg-ps5-dav1d-installed"` exit 0;串行 `--transient`、`--transient-comp`、`--jitter`、`--jitter --5.1` 均 exit 0,分别确认过冲块实际触发保护而 `clipped=0`,抖动 p95 为 20.4106/20.3669ms;`veyra_multichannel_tests.exe` 为 `checks=31 failures=0`;本机 `capture:0:0:0:0` exit 0,实际选择 48k/16/16,测试增益0。`git diff --check` 仅有既存 CRLF 转换提示,无空白错误。++当前仍未完成用户反馈者设备的未静音听感验收,不能宣称沙沙声已根治;未修改 NVIDIA/NGX runtime,未执行 RTX runtime Create/Evaluate,未发布或 push。++## 2026-09-15 进一步修正:48 kHz 无补偿真正走 identity,修复 SwrContext 重建所有权++继续审查发现旧 `clearCorrection()` 调用 `swr_set_compensation(swr,0,0)` 会把同速 48 kHz context 变成强制 resample;当前以 `compensationActive` 区分无补偿与补偿,补偿结束/重锚时新建默认 context,通过原 RAII owner 接管,避免无必要的高频处理。一次复测发现新 context 替换后旧智能指针悬挂,已修复后再测。++完整构建 `scripts/build.ps1 -Root "C:\Users\123\Desktop\Veyra DLSS Video Player" -Preset x64-release -BuildDirectory "out/build/audio-artifact-repair-20260914" -FfmpegRoot "C:\veyra-deps\ffmpeg-ps5-dav1d-installed"` 为 29/29、exit0。最终串行回归:`--transient` peak1.05091/protected9582/clipped0;`--transient-comp` peak1.13518/protected9570/clipped0,重锚日志为 `native-rate path restored`;`--jitter` p95 20.7114ms;`--jitter --5.1` p95 20.4901ms;多声道31/31;音频时间线抖动1x/2x/4x;本机 `capture:0:0:0:0` exit0,48k/16/16、31块、欠载1/576帧、增益0。当前 EXE SHA256 `A98B657FA5F66F5C2A3CD26ADBFE0051DDB7C8EA7DCFC7F5D8907909D57EA7FA`,大小 3,375,616 bytes。未执行 RTX runtime Create/Evaluate,未发布或 push,用户反馈设备未静音听感待验收。++## 2026-09-15 火堆/口哨持续沙沙声:重新审查(诊断与方案,非新修复交付)++用户继续否定当前候选听感并要求审查Luna改动、给出解决方案。本轮保留全部已有产品改动和EXE,未构建/替换产品;新增 `scripts/diagnostics/audio-waveform-audit.py`、`docs/CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md`,在旧修复文档顶部标明历史结论的证据限制。++最新真实使用会话 `logs/veyra-app.log` 第26036行起,00:09–00:24本地时间共448条同步状态,保护/削波/欠载计数均为0,最终转换后峰值0.95073;只有5次早期native context重建,之后仍持续非零时钟补偿。故过载、误淡入和少数重建不能直接解释持续噪声,不能再次强行认定根因。代码确有三项缺陷:块增益跳变且释放可再次削波、补偿归零销毁待输出滤波历史、空pull不看有效端点padding就触发5ms淡入。另有测试未检查波形、transient无视频锚点未启动输出、inputPeak其实为转换后峰值等证据缺口。++实际执行 `python scripts/diagnostics/audio-waveform-audit.py --dll-dir out/build/audio-artifact-repair-20260914 > logs/audio-waveform-audit-20260915/offline-dsp.json`,exit0。使用该应用真实FFmpeg9.0.1 DLL,hash与patched prefix匹配。0.5幅值4kHz、-1250ppm补偿归零时,对比保留context与销毁重建,后者最终少17输出帧,边界后48帧最大差0.871988;固定补偿1/4/8/16kHz拟合实际频率后残差约-100.53/-100.96/-105.82/-112.71dBFS,同速归一化误差0。最初按理论频率拟合误将整数步长频偏计为较高残差,已修正分析;不能据此说库有高频噪声。峰值保护的算术模型中,相同1.05峰值的第二块保护后仍1.0475再触发裁剪;淡入模型展示无真实断音也可能令首样本增益下降约47.6dB。这两个为明确标注的算术模型,不冒充生产集成。++完整实施/回归方案见新PLAN:先在原始PCM、重采样后、最终WASAPI提交前做有界受控tap和同源重放;去除新增失真、保持连续重采样历史,再按证据分离固定音画延迟与设备频差,不永久关闭同步或低通压噪。保留设备枚举、validBits、预填、视频reset隔离和MOV负PTS修复。下一条唯一任务P0生产波形定位。未执行产品构建/实卡听测/loopback/RTX Create或Evaluate;未修改运行组件,未push、未发布,沙沙声仍未通过用户验收。++## 2026-09-15 用户要求先修已知音频缺陷:连续历史、浮点余量与空拉恢复++本轮实施前述已确认缺陷,不盲改动态同步控制器、不加低通或降噪。修改 `CaptureAudioSession.cpp`、`WasapiAudioSink.cpp`及相应头文件、`LiveStatusPanel.h`、`CMakeLists.txt`;新增共享 `CaptureAudioDsp.h/.cpp`、生产DSP波形/真实WASAPI用例 `AudioWaveformTests.cpp`、串行限时回归脚本 `scripts/diagnostics/test-audio-continuity.ps1`;更新 `CaptureAudioTests.cpp` 的瞬态余量断言,并修复“模式切换掩盖断流恢复”的旧测试。方案完整记录为 `docs/CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md` §6。其他原有未提交改动全部保留。++核心修改:移除块级峰值保护及转换阶段的有限浮点硬裁剪,NaN/Inf防护保留,转换后峰值和超unity计数分别记录;auto在预填前准备重采样,同一epoch归零只更新补偿,不换context或丢滤波历史;空pull仍有设备排队PCM时不触发淡入。第一次实现只以设备时钟超过提交尾部判gap,首套11组和两组120秒测试虽通过,但审查真实断供日志发现本机时钟在无数据时会停在尾部;新增真实80ms断供负向用例,明确复现 `emptyPulls=8 gaps=0 fades=0` 失败。后增加持续空端点观测满实际device period的保守路径,断流时长未知单列clockStalledGaps而不伪造missingFrames,持续恢复观察同时考虑空pull;修后同用例 `gaps=1 fades=1`,已有队列用例仍 `gaps=0 fades=0`。捕获基线现在在不改同步模式、尚未恢复输入时就验证已重锚,通过。++构建到全新 `out/build/audio-continuity-repair-20260915`,未覆盖旧 `audio-artifact-repair-20260914/veyra.exe`(原SHA仍A98B657F…EA7FA)。先完成本地音频配置,再沿用现有RemotePlay依赖配置完整构建326/326、最终行为增量34/34成功,最终 `VEYRA_ENABLE_REMOTEPLAY=ON`,避免前序音频候选关闭PS5模块;FFmpeg仍 `C:/veyra-deps/ffmpeg-ps5-dav1d-installed`。完整 `scripts/build.ps1` 参数在PLAN §6,最终 `cmd.exe /c out\build\veyra-build-x64-release.cmd` 日志 `logs/audio-continuity-repair-20260915/build-verified.log`。首轮测试缺 `<string>` 导致C2039,补齐后成功;一次cmd正斜杠路径被拒绝,改反斜杠后正常。未隐藏失败日志。++最终短套命令:`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -LogDirectory logs/audio-continuity-repair-20260915/final`,12组进程均exit0,结果 `final/results.json`。其中生产DSP47/47,44.1/48kHz、2/6声道、1/4/8/16kHz、补偿正零负和480/127帧分块均与连续参考逐样本误差0、帧数一致;故障对照重置历史后由96001帧变为95935,能检出。其余包括真实WASAPI排队空拉和持续断流、捕获完整生命周期、立体声/5.1抖动、两类瞬态余量、端点失效恢复、多声道31/31、文件完整音频时间线与抖动。全部扬声器测试静音;无用户声学验收宣称。++最终EXE空界面启动短测:`scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra.exe -Arguments @('--smoke-empty','--smoke-seconds','2','--no-nr','--no-sr','--no-fg') -TimeoutSeconds 30 -LogPrefix logs/audio-continuity-repair-20260915/final/gui-smoke`,独立 `VEYRA_LOG_FILE`,exit0;`frames=0 failed=false nrEvaluated=0 nvofExecuted=0`,只证明启动,未伪报播放/增强成功。git diff --check通过(已有CRLF警告);没有SDK/DLL/模型/PYC被Git跟踪。最终两组各120秒快慢输入时钟漂移回归进行中,收口结果随后补充。++未做:真实火堆/口哨输入与输出分段录音、用户实卡听感、RTX Create/Evaluate、全GPU delivery gate。没有修改增强算法/导出路径,故本轮以音频专项与GUI启动检查为主;不拿这些替代RTX/导出验收。未改运行组件、未push、未发布。持续沙沙声是否完全消失仍待新构建实测;若仍出现,下一条唯一任务是同源PCM逐阶段定位,不再凭音高猜过载。++最终收口:`test-audio-continuity.ps1 ... -LogDirectory logs/audio-continuity-repair-20260915/final -DriftOnly` 两组exit0(最终目录12个短用例也全0)。1.001输入120秒P95偏差4.24594ms,0.999输入120秒4.30137ms,均missing0、resets1(仅启动)、队列高水位89.6458ms,无欠载/误淡入;证据 `final/drift-results.json`、`drift-fast.stdout.log`、`drift-slow.stdout.log`。这是合成采集节奏与真实WASAPI的专项回归,不是实卡听感。最终EXE 11,442,688字节,SHA256 `F26C655DDF7D9CF07FBA35AEA323059B9F65708139AB580015CF788B23D1D552`,路径 `out/build/audio-continuity-repair-20260915/veyra.exe`;旧候选hash未变。最终GUI空界面启动exit0、47项DSP检查通过、git diff --check通过;旧审查产生的单个PYC缓存已移除,未删用户数据。下一步用户复测新构建的真实火堆/口哨;未验收前不宣称沙沙声已根治。++## 2026-09-15 用户授权本地合并与工作区收口++用户要求“先合并一下,我需要一个干净的工作区”。确认本地 main(edabd3c)是当前修复分支(ebba6f1)的祖先;当前分支已包含媒体兼容、MOV负PTS、采集音频设备选择、FG时钟及此前HDR/多声道等改动。执行范围为提交现有23个源码/测试/诊断脚本/文档文件,然后以 `git switch main`、`git merge --ff-only codex/capture-fg-clock-repair-20260914` 收口,不另造冲突合并,不推送或发布。旧源码归档及已被取代的Smooth Motion实验分支不合入,所有原分支保留。++合并前重新执行 `cmd.exe /c out\build\veyra-build-x64-release.cmd`:exit0,配置生成成功,ninja no work to do;保留RemotePlay ON与patched FFmpeg/dav1d路径。裸 `cmake --version` 因当前PATH未配置失败,改用已有脚本中的VS CMake绝对路径,实际版本3.31.6-msvc6;可选依赖与CMake策略警告不影响构建。`out/build/audio-continuity-repair-20260915/veyra_audio_waveform_tests.exe --offline`:exit0,checks=47 failures=0,输出位于本任务命令记录;前轮完整日志继续保留在 `logs/audio-continuity-repair-20260915/final/`,不冒充本轮重新执行。EXE hash仍为F26C655D…D1D552。`git diff --check` 无空白错误,仅已有CRLF转换提示。++仅将审查过的源码、文档及脚本加入暂存;EXE、运行组件、日志与测试媒体仍被忽略且保留,不以删除本地文件制造干净工作区。当前验收目标是本地main包含修复提交、Git未提交/未跟踪状态为空;不改变真实沙沙声尚未听感验收的结论。本轮未执行RTX Create/Evaluate、GPU delivery或实卡测试,未重新跑120秒漂移用例。下一步仍是取得真实问题场景同源波形证据,用户当前远程不便测试,不要求立即验收。diff --git a/include/veyra/sink/AudioFormat.h b/include/veyra/sink/AudioFormat.hindex dd2ecca8..e596bbb5 100644--- a/include/veyra/sink/AudioFormat.h+++ b/include/veyra/sink/AudioFormat.h@@ -46,6 +46,27 @@ inline bool parseWavePcm(const void* bytes,size_t size,WavePcmFormat& out){(result.floating&&(w.wBitsPerSample!=32||result.validBits!=32)))return false;out=result;return true;}+// Capture devices frequently enumerate a low-rate compatibility format before+// their native 48 kHz format. Do not let DirectShow enumeration order choose+// the format: the whole live path and the WASAPI renderer use 48 kHz PCM.+inline bool preferCaptureAudioFormat(const WavePcmFormat& lhs,const WavePcmFormat& rhs){+ const auto rateDistance=[](const WAVEFORMATEX& f)->uint32_t{+ const auto rate=f.nSamplesPerSec;return rate>48000?rate-48000:48000-rate;+ };+ const bool lhs48=lhs.wave.nSamplesPerSec==48000,rhs48=rhs.wave.nSamplesPerSec==48000;+ if(lhs48!=rhs48)return lhs48;+ if(const auto l=rateDistance(lhs.wave),r=rateDistance(rhs.wave);l!=r)return l<r;+ if(lhs.layout.channels!=rhs.layout.channels)return lhs.layout.channels>rhs.layout.channels;+ const bool lhs16=!lhs.floating&&lhs.wave.wBitsPerSample==16&&lhs.validBits==16;+ const bool rhs16=!rhs.floating&&rhs.wave.wBitsPerSample==16&&rhs.validBits==16;+ if(lhs16!=rhs16)return lhs16;+ const bool lhsFull=lhs.validBits==lhs.wave.wBitsPerSample;+ const bool rhsFull=rhs.validBits==rhs.wave.wBitsPerSample;+ if(lhsFull!=rhsFull)return lhsFull;+ if(lhs.validBits!=rhs.validBits)return lhs.validBits>rhs.validBits;+ if(lhs.floating!=rhs.floating)return !lhs.floating;+ return lhs.wave.wBitsPerSample<rhs.wave.wBitsPerSample;+}inline WAVEFORMATEXTENSIBLE floatWave(AudioFormat layout){WAVEFORMATEXTENSIBLE out{};out.Format={WAVE_FORMAT_EXTENSIBLE,WORD(layout.channels),48000,48000*layout.channels*4,WORD(layout.channels*4),32,22};out.Samples.wValidBitsPerSample=32;out.dwChannelMask=layout.mask;out.SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;return out;diff --git a/include/veyra/sink/AudioGain.h b/include/veyra/sink/AudioGain.hindex 18d5a12f..d6c7fa41 100644--- a/include/veyra/sink/AudioGain.h+++ b/include/veyra/sink/AudioGain.h@@ -15,6 +15,18 @@ inline void fadePcmTail(float* samples,size_t frames,unsigned channels,float gaifor(size_t i=0;i<frames;++i){const float envelope=frames>1?gain*float(frames-1-i)/float(frames-1):0;for(unsigned c=0;c<channels;++c)samples[channels*i+c]*=envelope;}}+// Restart the waveform at zero after a live endpoint gap. This is applied+// after the user gain, so it only changes the short edge envelope and never+// changes the requested volume.+inline void fadePcmHead(float* samples,size_t frames,unsigned channels,size_t& remaining){+ constexpr size_t total=240; // 5 ms at 48 kHz+ for(size_t i=0;i<frames&&remaining;++i){+ const size_t consumed=total-remaining;+ const float envelope=float(consumed+1)/float(total);+ for(unsigned c=0;c<channels;++c)samples[i*channels+c]*=envelope;+ --remaining;+ }+}inline void applyStereoGain(float* p,size_t n,float target,float& current){applyPcmGain(p,n,2,target,current);}inline void fadeStereoTail(float* p,size_t n,float gain){fadePcmTail(p,n,2,gain);}}diff --git a/include/veyra/sink/CaptureAudioDsp.h b/include/veyra/sink/CaptureAudioDsp.hnew file mode 100644index 00000000..c20b247c--- /dev/null+++ b/include/veyra/sink/CaptureAudioDsp.h@@ -0,0 +1,58 @@+#pragma once+#include <algorithm>+#include <cmath>+#include <cstddef>+#include <cstdint>+#include <optional>+struct SwrContext;+namespace veyra::sink {+// Prepare on a fresh epoch BEFORE consuming PCM. Once active, zero correction+// preserves the same FIR history and delay; it is not a stream reset.+class CaptureRateCorrection {+public:+ int prepare(SwrContext* context,bool automatic);+ int set(SwrContext* context,int delta,int distance=48000);+private:+ bool prepared_=false;+};+struct CaptureSampleStats {float peak=0;uint64_t nonFinite=0,overRange=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){+ CaptureSampleStats stats;+ for(size_t i=0;i<count;++i){+ auto& sample=samples[i];+ if(!std::isfinite(sample)){sample=0;++stats.nonFinite;continue;}+ stats.peak=std::max(stats.peak,std::abs(sample));+ if(std::abs(sample)>1.0f)++stats.overRange;+ }+ return stats;+}+// Device-clock evidence, not unfilled writable capacity. An empty software+// pull with queued endpoint PCM does not alter the following waveform.+class LiveAudioGapTracker {+public:+ struct Observation {uint64_t frames=0;bool began=false;};+ Observation observe(uint32_t padding,uint64_t consumed,uint64_t submittedEnd){+ if(padding||consumed<=submittedEnd)return {};+ const bool began=!open_;open_=true;+ return {consumed-submittedEnd,began};+ }+ // Some WASAPI drivers stop advancing IAudioClock when the queue empties.+ // Require TWO empty observations spanning a full endpoint period before+ // treating this as starvation. Do not invent device-clock missing frames.+ bool observeEmpty(uint32_t padding,size_t got,double nowMs,double periodMs){+ const bool confirmed=!padding&&emptySince_&&nowMs-*emptySince_>=periodMs;+ const bool began=confirmed&&!open_;+ if(confirmed)open_=true;+ if(padding||got)emptySince_.reset();+ else if(!emptySince_)emptySince_=nowMs;+ return began;+ }+ void submitted(size_t frames){if(frames){open_=false;emptySince_.reset();}}+ void reset(){open_=false;emptySince_.reset();}+private:+ bool open_=false;+ std::optional<double> emptySince_;+};+}diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.hindex 7af482d4..46cfe4f8 100644--- a/include/veyra/sink/CaptureAudioSession.h+++ b/include/veyra/sink/CaptureAudioSession.h@@ -6,28 +6,36 @@#include <optional>#include <string>namespace veyra::sink {+struct WavePcmFormat;struct CaptureAudioState {bool available=false,running=false,clockEstimated=true,limited=false;unsigned inputChannels=0,outputChannels=0;uint32_t inputChannelMask=0,outputChannelMask=0;+ uint32_t inputSampleRate=0;unsigned inputContainerBits=0,inputValidBits=0;bool inputFloating=false;double compensationMs=0,bufferedMs=0,bufferHighWaterMs=0,endpointBufferedMs=0;double driftCorrectionPpm=0;double inputBlockMs=0,inputIntervalMs=0;+ double inputPeak=0; // Historical API name: peak AFTER sample conversion.uint64_t inputBlocks=0;std::optional<double> skewMs;- uint64_t resets=0,overflows=0,underruns=0,endpointRetries=0;+ uint64_t resets=0,overflows=0,underruns=0,underrunFrames=0,silenceFrames=0,+ invalidPaddingSamples=0,nonFiniteSamples=0,clippedSamples=0,peakProtectedSamples=0,endpointRetries=0,+ overRangeSamples=0,emptyPulls=0,recoveryFades=0,clockStalledGaps=0;std::wstring error;};class CaptureAudioSession {public:CaptureAudioSession();~CaptureAudioSession();+ bool configure(const WavePcmFormat&);bool configure(const WAVEFORMATEX&,size_t formatBytes=sizeof(WAVEFORMATEX));bool start();void stop();bool push(const void* data,size_t bytes,double ptsMs,bool discontinuity);void videoPresented(double ptsMs,int64_t host100ns);- // Invalidate only software presentation; preserve the shared input mapping.- void videoReset();+ // Invalidate software presentation. A video graph rebuild can preserve+ // the audio clock; callers that are actually pausing the transport may+ // request the old audio reset explicitly.+ void videoReset(bool resetAudio=true);void setGain(float);// 0 automatic, 1 manual, 2 off. Positive offset delays sound.void setSync(unsigned mode,int offsetMs);diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.hindex 7e15c002..da825c56 100644--- a/include/veyra/sink/WasapiAudioSink.h+++ b/include/veyra/sink/WasapiAudioSink.h@@ -23,6 +23,7 @@#include "veyra/Log.h"#include "veyra/sink/AudioPcmSource.h"#include "veyra/sink/AudioFrameTimeline.h"+#include "veyra/sink/CaptureAudioDsp.h"struct AVFormatContext;struct AVCodecContext;@@ -63,8 +64,9 @@ public:bool decodingComplete() const { return decodedEof_.load(); }// Pull up to maxFrames source-layout frames; sets the PTS of the first pulled- // frame. Returns frames pulled (0 legal; caller writes silence and it is- // counted as an underrun by the pump only when the endpoint had space).+ // frame. Returns frames pulled. A file source pads an empty endpoint with+ // explicit silence; a live source may return 0 so the owner can preserve+ // its media timeline and apply its bounded recovery policy.size_t pull(float* dst, size_t maxFrames, double* firstPtsMs) override;void stopThread();@@ -156,7 +158,7 @@ private:class AudioRenderer {public:~AudioRenderer(){shutdown();}- bool start(AudioFormat input = {});+ bool start(AudioFormat input = {},double requestedBufferMs=10.0);AudioFormat outputFormat()const{std::lock_guard lock(endpointMutex_);return outputFormat_;}void setGain(float value){gain_.store(value);}@@ -164,9 +166,9 @@ public:bool startAnchored(AudioPcmSource& pipeline, bool paused = false);void setPaused(bool value);- // Event-driven pump for ONE event cycle. Writes real data when the ring- // has it, silence otherwise (underrun counted). Returns false on hard- // failure.+ // Event-driven pump for ONE event cycle. Writes real data when available;+ // file sources pad with silence, while live sources release zero frames+ // on an isolated gap so synthetic PCM cannot advance their timeline.bool waitForEvent();bool pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs, bool wait = true);@@ -181,6 +183,11 @@ public:bool started() const;uint64_t underruns() const;+ uint64_t underrunFrames() const;+ uint64_t silenceFrames() const;+ uint64_t emptyPulls() const{return emptyPulls_.load();}+ uint64_t recoveryFades() const{return recoveryFades_.load();}+ uint64_t clockStalledGaps() const{return clockStalledGaps_.load();}uint64_t framesWritten() const;HRESULT lastError()const{return lastError_.load();}double bufferedMs()const{return bufferedMs_.load();}@@ -207,12 +214,15 @@ private:HANDLE event_ = nullptr;UINT32 bufferFrames_ = 0;uint32_t sampleRate_ = kAudioRate;+ double devicePeriodMs_=10;UINT64 clockFrequency_ = 0;std::atomic<UINT64> anchorPos_{0};std::atomic<double> anchorPtsMs_{0.0};std::atomic<bool> started_{false};std::atomic<bool> running_{false};std::atomic<bool> fading_{false};bool pausedEndpoint_=false;+ size_t fadeInRemaining_=0;+ LiveAudioGapTracker liveGap_;std::vector<float> lastRaw_=std::vector<float>(2,0);AudioFormat inputFormat_,outputFormat_;SwrContext* channelMix_=nullptr;@@ -220,6 +230,9 @@ private:bool copyPcm(BYTE* destination,const float* input,size_t frames);bool comInited_ = false;std::atomic<uint64_t> underruns_{0};+ std::atomic<uint64_t> underrunFrames_{0},silenceFrames_{0};+ std::atomic<uint64_t> emptyPulls_{0},recoveryFades_{0};+ std::atomic<uint64_t> clockStalledGaps_{0};std::atomic<uint64_t> framesWritten_{0};std::vector<float> chunk_;};diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.hindex 783cd451..a61d9ff7 100644--- a/include/veyra/source/CaptureCardSource.h+++ b/include/veyra/source/CaptureCardSource.h@@ -38,7 +38,7 @@ public:bool setAudioGain(float); // call on the graph owner thread; never system volumeCaptureMetrics metrics()const;void videoPresented(double ptsMs,int64_t host100ns);- void videoReset();+ void videoReset(bool resetAudio=true);void setAudioSync(unsigned mode,int offsetMs);sink::CaptureAudioState audioState()const;const SourceInfo& info()const override;diff --git a/include/veyra/source/RemotePlaySessionSource.h b/include/veyra/source/RemotePlaySessionSource.hindex 301d4d83..ff3e12b8 100644--- a/include/veyra/source/RemotePlaySessionSource.h+++ b/include/veyra/source/RemotePlaySessionSource.h@@ -31,7 +31,7 @@ public:void setAudioGain(float value) { audio_.setGain(value); }void setAudioSync(unsigned mode, int offset) { audio_.setSync(mode, offset); }void videoPresented(double pts, int64_t host) { audio_.videoPresented(pts, host); }- void videoReset() { audio_.videoReset(); }+ void videoReset(bool resetAudio=true) { audio_.videoReset(resetAudio); }private:friend struct RemotePlaySessionSourceTestAccess;void publishDecoded(const AVFrame*,pipeline::FramePacket,const SourceInfo&);diff --git a/scripts/diagnostics/audio-waveform-audit.py b/scripts/diagnostics/audio-waveform-audit.pynew file mode 100644index 00000000..8935556f--- /dev/null+++ b/scripts/diagnostics/audio-waveform-audit.py@@ -0,0 +1,189 @@+"""Read-only/offline DSP audit; no device capture/playback or product changes.++SWResample tests call the supplied application's actual DLLs. Guard/fade cases+are explicitly arithmetic models of the audited C++ (not product integration).+Requires numpy. Prints JSON evidence; redirect stdout to an ignored log path.+"""+import argparse+import ctypes as C+import hashlib+import json+import os+from pathlib import Path++import numpy as np+++class Layout(C.Structure):+ _fields_ = [("order", C.c_int), ("channels", C.c_int),+ ("mask", C.c_uint64), ("opaque", C.c_void_p)]+++parser = argparse.ArgumentParser()+parser.add_argument("--dll-dir", type=Path, required=True)+args = parser.parse_args()+directory = args.dll_dir.resolve()+search = os.add_dll_directory(str(directory))+av = C.CDLL(str(directory / "avutil-61.dll"))+sw = C.CDLL(str(directory / "swresample-7.dll"))+ptr = C.c_void_p+sw.swr_alloc_set_opts2.argtypes = [C.POINTER(ptr), C.POINTER(Layout), C.c_int,+ C.c_int, C.POINTER(Layout), C.c_int,+ C.c_int, C.c_int, ptr]+sw.swr_alloc_set_opts2.restype = C.c_int+sw.swr_init.argtypes = [ptr]+sw.swr_init.restype = C.c_int+sw.swr_free.argtypes = [C.POINTER(ptr)]+sw.swr_get_delay.argtypes = [ptr, C.c_int64]+sw.swr_get_delay.restype = C.c_int64+sw.swr_set_compensation.argtypes = [ptr, C.c_int, C.c_int]+sw.swr_set_compensation.restype = C.c_int+sw.swr_convert.argtypes = [ptr, C.POINTER(ptr), C.c_int,+ C.POINTER(ptr), C.c_int]+sw.swr_convert.restype = C.c_int+av.av_version_info.restype = C.c_char_p+++def checked(code):+ if code < 0:+ raise RuntimeError(f"FFmpeg error {code}")+++class Resampler:+ def __init__(self):+ self.ctx = ptr()+ layout = Layout(1, 2, 3, None)+ # Packed S16 -> packed float, stereo 48 kHz: actual capture format.+ checked(sw.swr_alloc_set_opts2(C.byref(self.ctx), C.byref(layout), 3,+ 48000, C.byref(layout), 1, 48000, 0, None))+ checked(sw.swr_init(self.ctx))++ def convert(self, block):+ out = np.empty((2048, 2), dtype=np.float32)+ output = (ptr * 1)(out.ctypes.data)+ source = None if block is None else (ptr * 1)(block.ctypes.data)+ count = sw.swr_convert(self.ctx, output, len(out), source,+ 0 if block is None else len(block))+ checked(count)+ return out[:count].copy()++ def compensation(self, delta):+ checked(sw.swr_set_compensation(self.ctx, delta, 48000 if delta else 0))++ def delay(self):+ return sw.swr_get_delay(self.ctx, 48000)++ def close(self):+ sw.swr_free(C.byref(self.ctx))+++def signal(frequency, blocks=200):+ t = np.arange(blocks * 480) / 48000+ mono = np.round(0.5 * 32768 * np.sin(2 * np.pi * frequency * t + 0.71)).astype(np.int16)+ return np.repeat(mono[:, None], 2, axis=1)+++def run(data, reset_at=None, zero_at=None, compensated=True):+ s = Resampler()+ chunks = []+ events = []+ for i, block in enumerate(data.reshape(-1, 480, 2)):+ if compensated and i % 25 == 0 and (zero_at is None or i < zero_at):+ s.compensation(-60) # -1250 ppm; near latest user's log.+ if i == zero_at:+ events.append({"block": i, "pending_input_frames": s.delay(),+ "output_frame": sum(len(c) for c in chunks)})+ if reset_at == i:+ s.close()+ s = Resampler()+ else:+ s.compensation(0)+ chunks.append(s.convert(block))+ pending = s.delay()+ chunks.append(s.convert(None))+ s.close()+ return np.concatenate(chunks), events, pending+++def sine_residual(samples, frequency, refine=False):+ requested_frequency = frequency+ if refine:+ # Compensation increments are integers in FFmpeg. Fitting the nominal+ # frequency alone mistakes fractional-rate rounding for broadband noise.+ small = samples[::4]+ times = np.arange(len(small)) * 4 / 48000+ def cost(f):+ basis = np.stack([np.sin(2*np.pi*f*times),+ np.cos(2*np.pi*f*times), np.ones(len(times))], axis=1)+ weights = np.linalg.lstsq(basis, small, rcond=None)[0]+ return float(np.mean((small-basis@weights)**2))+ lo, hi = frequency-.1, frequency+.1+ for _ in range(38):+ left, right = lo+(hi-lo)/3, hi-(hi-lo)/3+ if cost(left) < cost(right):+ hi = right+ else:+ lo = left+ frequency = (lo+hi)/2+ t = np.arange(len(samples)) / 48000+ basis = np.stack([np.sin(2*np.pi*frequency*t),+ np.cos(2*np.pi*frequency*t), np.ones(len(t))], axis=1)+ weights = np.linalg.lstsq(basis, samples, rcond=None)[0]+ error = samples - basis @ weights+ rms = float(np.sqrt(np.mean(error**2)))+ return {"nominal_frequency_hz": requested_frequency, "fitted_frequency_hz": frequency,+ "fitted_amplitude": float(np.hypot(*weights[:2])),+ "residual_dbfs": float(20*np.log10(max(rms, 1e-20)))}+++def model_guard(block_peaks):+ gain = 1.0+ rows = []+ for peak in block_peaks:+ target = .995/peak if peak > .995 else 1.0+ gain = target if target < gain else min(1.0, gain+.05)+ applied = gain if target < .99999 else 1.0+ raw = peak * applied+ rows.append({"input_peak": peak, "state_gain": gain, "applied_gain": applied,+ "pre_clamp_peak": raw, "hard_clip": raw > 1.0})+ return rows+++results = {"kind": "offline audit, NOT acoustic or full-player acceptance",+ "ffmpeg_version": av.av_version_info().decode(),+ "dlls": {name: hashlib.file_digest(open(directory/name, "rb"), "sha256").hexdigest()+ for name in ["avutil-61.dll", "swresample-7.dll"]}}+stable = []+for f in [1000, 4000, 8000, 16000]:+ data = signal(f)+ identity, _, _ = run(data, compensated=False)+ compensated, _, _ = run(data)+ stable.append({"input_hz": f,+ "identity_max_abs_error": float(np.max(np.abs(identity-data/32768))),+ # Omit startup/end transients; expected step = 1.00125.+ "fixed_compensation": sine_residual(compensated[2000:-2000, 0], f*1.00125, refine=True)})+results["stable_actual_swr"] = stable+data = signal(4000)+kept, events, _ = run(data, zero_at=100)+replaced, _, _ = run(data, zero_at=100, reset_at=100)+edge = events[0]["output_frame"]+results["zero_crossing_actual_swr"] = {+ "event": events[0], "kept_frames_with_drain": len(kept),+ "replaced_frames_with_drain": len(replaced),+ "lost_output_frames": len(kept)-len(replaced),+ "first_post_boundary_reference": float(kept[edge, 0]),+ "first_post_boundary_replaced": float(replaced[edge, 0]),+ "max_difference_first_48_frames": float(np.max(np.abs(kept[edge:edge+48]-replaced[edge:edge+48])))}+results["guard_arithmetic_model_constant_peak"] = model_guard([1.05]*4)+results["guard_arithmetic_model_release"] = model_guard([1.1, .9, .9])+results["fade_arithmetic_model_false_empty_pull"] = {+ "queued_endpoint_frames_at_empty_pull": 480,+ "next_callback_before_queue_drain": True,+ "actual_playback_gap_frames": 0,+ "input_next_sample": .5, "new_fade_first_sample": .5/240,+ "gain_drop_db": float(20*np.log10(1/240)),+ "note": "Model of C++ trigger/envelope, not device loopback."}+assert all(row["identity_max_abs_error"] == 0 for row in stable)+assert results["zero_crossing_actual_swr"]["lost_output_frames"] > 0+assert results["guard_arithmetic_model_constant_peak"][1]["hard_clip"]+print(json.dumps(results, indent=2))diff --git a/scripts/diagnostics/test-audio-continuity.ps1 b/scripts/diagnostics/test-audio-continuity.ps1new file mode 100644index 00000000..8201c15c--- /dev/null+++ b/scripts/diagnostics/test-audio-continuity.ps1@@ -0,0 +1,45 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory=$true)][string]$BuildDirectory,+ [string]$LogDirectory='logs/audio-continuity-repair-20260915',+ [switch]$DriftOnly+)+$ErrorActionPreference='Stop'+$audioBin=(Resolve-Path -LiteralPath $BuildDirectory).Path+$audioLogs=[IO.Path]::GetFullPath($LogDirectory)+[IO.Directory]::CreateDirectory($audioLogs) | Out-Null+$cases=@(+ @{Name='waveform';Exe='veyra_audio_waveform_tests.exe';Args=@('--offline');Seconds=30},+ @{Name='queued-empty-pull';Exe='veyra_audio_waveform_tests.exe';Args=@('--endpoint');Seconds=30},+ @{Name='true-endpoint-gap';Exe='veyra_audio_waveform_tests.exe';Args=@('--endpoint-gap');Seconds=30},+ @{Name='capture-baseline';Exe='veyra_capture_audio_tests.exe';Args=@('--baseline');Seconds=90},+ @{Name='jitter-stereo';Exe='veyra_capture_audio_tests.exe';Args=@('--jitter');Seconds=30},+ @{Name='jitter-51';Exe='veyra_capture_audio_tests.exe';Args=@('--jitter','--5.1');Seconds=30},+ @{Name='transient';Exe='veyra_capture_audio_tests.exe';Args=@('--transient');Seconds=30},+ @{Name='transient-comp';Exe='veyra_capture_audio_tests.exe';Args=@('--transient-comp');Seconds=30},+ @{Name='endpoint-loss';Exe='veyra_capture_audio_tests.exe';Args=@('--endpoint-loss');Seconds=30},+ @{Name='multichannel';Exe='veyra_multichannel_tests.exe';Args=@("$audioLogs/multichannel-fixtures");Seconds=60},+ @{Name='timeline';Exe='veyra_audio_timeline_tests.exe';Args=@("$audioLogs/timeline-fixtures");Seconds=120},+ @{Name='timeline-jitter';Exe='veyra_audio_timeline_tests.exe';Args=@("$audioLogs/timeline-jitter-fixtures",'--jitter');Seconds=60}+)+if($DriftOnly){$cases=@(+ @{Name='drift-fast';Exe='veyra_capture_audio_tests.exe';Args=@('--drift-fast');Seconds=150},+ @{Name='drift-slow';Exe='veyra_capture_audio_tests.exe';Args=@('--drift-slow');Seconds=150}+)}+$results=@()+foreach($case in $cases){+ Write-Host ('START '+$case.Name)+ $quoted=@($case.Args | ForEach-Object {'"'+$_.Replace('"','\"')+'"'})+ $process=Start-Process -FilePath (Join-Path $audioBin $case.Exe) -ArgumentList $quoted -PassThru -WindowStyle Hidden -RedirectStandardOutput "$audioLogs/$($case.Name).stdout.log" -RedirectStandardError "$audioLogs/$($case.Name).stderr.log"+ $processHandle=$process.Handle+ if(-not $process.WaitForExit($case.Seconds*1000)){+ Stop-Process -Id $process.Id -Force+ $code=124+ }else{$process.Refresh();$code=$process.ExitCode}+ $results+=@{name=$case.Name;exitCode=$code;timeoutSeconds=$case.Seconds}+ Write-Host ('END '+$case.Name+' exit='+$code)+}+$name=if($DriftOnly){'drift-results.json'}else{'results.json'}+$results | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $audioLogs $name) -Encoding UTF8+if(@($results | Where-Object {$null -eq $_.exitCode -or $_.exitCode -ne 0}).Count){exit 1}+exit 0diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 51239c2a..ae2d4e25 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -436,9 +436,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sresetRecord->reason=static_cast<uint8_t>(pipeline::ResetReason::Settings);if(frameFlow)frameFlow->resetLifecycle(*resetRecord);drainLivePresentation();- if(physicalCapture)captureSource.videoReset();+ // Rebuilding the video graph must not tear down a healthy+ // capture audio endpoint; only the new video mapping is+ // invalidated here. Audio transport reset is reserved for+ // an actual pause/stop or input discontinuity.+ if(physicalCapture)captureSource.videoReset(false);#ifdef VEYRA_ENABLE_REMOTEPLAY- if(remote)remote->videoReset();+ if(remote)remote->videoReset(false);#endif// A drain may outlive several slider notifications. Builddiff --git a/src/sink/CaptureAudioDsp.cpp b/src/sink/CaptureAudioDsp.cppnew file mode 100644index 00000000..bc60f1fa--- /dev/null+++ b/src/sink/CaptureAudioDsp.cpp@@ -0,0 +1,18 @@+#include "veyra/sink/CaptureAudioDsp.h"+extern "C" {+#include <libswresample/swresample.h>+}+namespace veyra::sink {+int CaptureRateCorrection::prepare(SwrContext* context,bool automatic){+ if(!automatic&&!prepared_)return 0;+ const int result=swr_set_compensation(context,0,0);+ if(result>=0)prepared_=true;+ return result;+}+int CaptureRateCorrection::set(SwrContext* context,int delta,int distance){+ // A newly enabled auto mode must prepare before playback, not hot-switch+ // from identity halfway through a continuous PCM stream.+ if(!prepared_)return delta?AVERROR(EINVAL):0;+ return swr_set_compensation(context,delta,delta?distance:0);+}+}diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cppindex f0579ee6..bfed74c9 100644--- a/src/sink/CaptureAudioSession.cpp+++ b/src/sink/CaptureAudioSession.cpp@@ -1,6 +1,7 @@#include "veyra/sink/CaptureAudioSession.h"#include "veyra/sink/WasapiAudioSink.h"#include "veyra/sink/ArrivalClockMapping.h"+#include "veyra/sink/CaptureAudioDsp.h"#include <algorithm>#include <cmath>#include <cstring>@@ -15,7 +16,7 @@ int64_t hostTime(){return std::chrono::duration_cast<std::chrono::nanoseconds>(sstruct CaptureAudioSession::Impl : AudioPcmSource {struct Chunk {std::vector<uint8_t> bytes;double pts=0;bool discontinuity=false;};WAVEFORMATEX format{};- AudioFormat layout;bool floating=false;+ AudioFormat layout;unsigned validBits=0;bool floating=false;AudioFormat pcmFormat()const override{return layout;}mutable std::mutex mutex;std::condition_variable wake;@@ -63,24 +64,37 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const bool injectEndpointLoss=GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",nullptr,0)>0;bool injected=false;uint64_t endpointPumps=0;SwrContext* swr=nullptr;- AVChannelLayout out{},in{};av_channel_layout_from_mask(&out,layout.mask);av_channel_layout_from_mask(&in,layout.mask);const auto inputFormat=floating?AV_SAMPLE_FMT_FLT:format.wBitsPerSample==16?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_S32;- const int configured=swr_alloc_set_opts2(&swr,&out,AV_SAMPLE_FMT_FLT,kAudioRate,&in,inputFormat,format.nSamplesPerSec,0,nullptr);- av_channel_layout_uninit(&in);- if(configured<0||!swr||swr_init(swr)<0){log::error("capture-audio","resampler initialization failed");swr_free(&swr);renderer.shutdown();fail(L"音频重采样初始化失败");return;}+ auto makeResampler=[&](SwrContext*& result)->bool{+ AVChannelLayout out{},in{};+ const int outResult=av_channel_layout_from_mask(&out,layout.mask);+ const int inResult=av_channel_layout_from_mask(&in,layout.mask);+ const int configured=outResult<0||inResult<0?-1:swr_alloc_set_opts2(&result,&out,AV_SAMPLE_FMT_FLT,kAudioRate,&in,inputFormat,format.nSamplesPerSec,0,nullptr);+ av_channel_layout_uninit(&in);av_channel_layout_uninit(&out);+ if(configured<0||!result||swr_init(result)<0){swr_free(&result);return false;}+ return true;+ };+ if(!makeResampler(swr)){log::error("capture-audio","resampler initialization failed");renderer.shutdown();fail(L"音频重采样初始化失败");return;}+ log::info("capture-audio-resampler",std::format("inputRate={} outputRate={} filter=default-kaiser continuousHistory=1 blockAgc=0 floatHeadroom=1",format.nSamplesPerSec,kAudioRate));const auto releaseSwr=[](SwrContext* value){swr_free(&value);};std::unique_ptr<SwrContext,decltype(releaseSwr)> resampler(swr,releaseSwr);double filteredError=0,correctionPpm=0;+ CaptureRateCorrection rateCorrection;int64_t nextCorrection=0;int64_t lastReset=0;int64_t nextSyncLog=0;+ int64_t nextPeakLog=0;unsigned appliedMode=mode.load();int appliedOffset=offset.load();uint64_t lastUnderruns=0;+ uint64_t lastUnderrunFrames=0,lastSilenceFrames=0;+ uint64_t lastEmptyPulls=0;+ int64_t starvationSince=0;+ static constexpr int64_t liveUnderrunGrace100ns=300000; // 30 msbool 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;}+ const int result=rateCorrection.set(swr,0);+ if(result<0){log::error("capture-audio",std::format("clear compensation failed code={}",result));return false;}std::lock_guard lock(mutex);state.driftCorrectionPpm=0;return true;};auto recoverEndpoint=[&]{@@ -97,15 +111,16 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const auto time=hostTime();if(time<retryAt){std::unique_lock lock(mutex);wake.wait_for(lock,std::chrono::milliseconds(20),[&]{return stop.load();});continue;}{std::lock_guard lock(mutex);++state.endpointRetries;}- if(!renderer.start(layout)){if(!recoverEndpoint())break;continue;}+ if(!renderer.start(layout,20.0)){if(!recoverEndpoint())break;continue;}endpointReady=true;lastUnderruns=renderer.underruns();+ lastUnderrunFrames=renderer.underrunFrames();lastSilenceFrames=renderer.silenceFrames();starvationSince=0;{std::lock_guard lock(mutex);state.error.clear();state.inputChannels=layout.channels;state.inputChannelMask=layout.mask;const auto output=renderer.outputFormat();state.outputChannels=output.channels;state.outputChannelMask=output.mask;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;+ Chunk chunk;bool reset=false,syncChanged=false;double vPts=0,vHost=0,ingress=0;bool video=false;int64_t arrival=0;{std::unique_lock lock(mutex);if(input.empty())wake.wait_for(lock,std::chrono::milliseconds(2));@@ -114,10 +129,16 @@ struct CaptureAudioSession::Impl : AudioPcmSource {ingress=ingressMapping;arrival=lastArrival;}- if(mode!=appliedMode||offset!=appliedOffset){reset=true;appliedMode=mode;appliedOffset=offset;}+ if(mode!=appliedMode||offset!=appliedOffset){+ syncChanged=true;reset=true;appliedMode=mode;appliedOffset=offset;+ log::info("capture-audio-sync",std::format("mode={} offsetMs={} reanchor=explicit-audio-setting",appliedMode,appliedOffset));+ }+ if(syncChanged&&!clearCorrection()){fail(L"音频同步补偿重置失败");break;}if(reset||chunk.discontinuity){renderer.fadeAndReset(*this,stop);clearPcm();swr_close(swr);if(swr_init(swr)<0){fail(L"音频重采样重置失败");break;}+ const int prepared=rateCorrection.prepare(swr,appliedMode==0);+ if(prepared<0){log::error("capture-audio",std::format("prepare compensation failed code={}",prepared));fail(L"音频补偿初始化失败");break;}if(!clearCorrection()){fail(L"音频漂移校正重置失败");break;}std::lock_guard lock(mutex);++state.resets;}@@ -128,14 +149,53 @@ struct CaptureAudioSession::Impl : AudioPcmSource {if(capacity<=0||capacity>int(kAudioRate)){log::error("capture-audio","invalid converted block capacity");fail(L"音频转换块大小无效");break;}std::vector<float> converted(size_t(capacity)*layout.channels);uint8_t* dst[]={reinterpret_cast<uint8_t*>(converted.data())};const uint8_t* src[]={chunk.bytes.data()};+ std::vector<int16_t> normalized16;+ std::vector<int32_t> normalized32;std::vector<int32_t> packed24;- if(format.wBitsPerSample==24){+ uint64_t invalidPadding=0;+ const unsigned paddingBits=format.wBitsPerSample-validBits;+ const uint32_t paddingMask=paddingBits?((uint32_t(1)<<paddingBits)-1u):0u;+ if(!floating&&validBits<format.wBitsPerSample&&format.wBitsPerSample==16){+ normalized16.resize(size_t(inputFrames)*layout.channels);+ for(size_t i=0;i<normalized16.size();++i){+ uint16_t raw=0;memcpy(&raw,chunk.bytes.data()+i*2,sizeof(raw));+ if(raw&paddingMask)++invalidPadding;raw=static_cast<uint16_t>(raw&~paddingMask);+ memcpy(&normalized16[i],&raw,sizeof(raw));+ }+ src[0]=reinterpret_cast<const uint8_t*>(normalized16.data());+ }else if(!floating&&validBits<format.wBitsPerSample&&format.wBitsPerSample==32){+ normalized32.resize(size_t(inputFrames)*layout.channels);+ for(size_t i=0;i<normalized32.size();++i){+ uint32_t raw=0;memcpy(&raw,chunk.bytes.data()+i*4,sizeof(raw));+ if(raw&paddingMask)++invalidPadding;raw&=~paddingMask;+ memcpy(&normalized32[i],&raw,sizeof(raw));+ }+ src[0]=reinterpret_cast<const uint8_t*>(normalized32.data());+ }else if(!floating&&format.wBitsPerSample==24){+ // WAVEFORMATEXTENSIBLE PCM stores valid bits left-aligned+ // in the byte container. Expand the signed 24-bit sample+ // to the high 24 bits of S32 for libswresample.packed24.resize(size_t(inputFrames)*layout.channels);- for(size_t i=0;i<packed24.size();++i){const auto* p=chunk.bytes.data()+i*3;const uint32_t v=(uint32_t(p[0])<<8)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<24);memcpy(&packed24[i],&v,4);}+ for(size_t i=0;i<packed24.size();++i){+ const auto* p=chunk.bytes.data()+i*3;uint32_t raw=uint32_t(p[0])|uint32_t(p[1])<<8|uint32_t(p[2])<<16;+ if(paddingMask&&((raw&0xFFFFFFu)&paddingMask))++invalidPadding;raw&=0xFFFFFFu&~paddingMask;+ const uint32_t expanded=raw<<8;memcpy(&packed24[i],&expanded,sizeof(expanded));+ }src[0]=reinterpret_cast<const uint8_t*>(packed24.data());}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);+ {+ std::lock_guard lock(mutex);+ state.invalidPaddingSamples+=invalidPadding;state.nonFiniteSamples+=stats.nonFinite;+ state.overRangeSamples+=stats.overRange;state.inputPeak=std::max<double>(state.inputPeak,stats.peak);+ }+ const auto sampleLogTime=hostTime();+ if((invalidPadding||stats.nonFinite||stats.overRange)&&sampleLogTime>=nextPeakLog){+ nextPeakLog=sampleLogTime+5000000;+ log::warn("capture-audio-samples",std::format("invalidPadding={} nonFinite={} overRange={} convertedPeak={:.6f} blockAgc=0 format={}Hz/{}bit validBits={}",invalidPadding,stats.nonFinite,stats.overRange,stats.peak,format.nSamplesPerSec,format.wBitsPerSample,validBits));+ }const double start=chunk.pts-1000.0*delay/format.nSamplesPerSec;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));@@ -171,12 +231,17 @@ struct CaptureAudioSession::Impl : AudioPcmSource {const double target=std::clamp(requested,0.0,maxDelay);const double mapping=ingress+target;const bool limited=requested<0||requested>maxDelay;- if(appliedMode==0&&!fresh&&renderer.started()){- renderer.fadeAndReset(*this,stop);endpointEventReady=false;- std::lock_guard lock(mutex);++state.resets;- }+ // A temporary video rebuild must not stop a healthy capture audio+ // clock. The next presented video sample will refresh the+ // mapping; a real PCM discontinuity is handled above instead.bool justStarted=false;- const double startupPrefillMs=std::min(renderer.capacityMs(),10.0);+ // The capture callback is negotiated at 10ms, while shared-mode+ // WASAPI commonly returns a ~22ms endpoint buffer. Starting with+ // only one callback leaves half of that endpoint exposed to+ // scheduler jitter. Keep one full 20ms safety window for capture;+ // this is startup/re-anchor buffering, not a claimed end-to-end+ // latency measurement.+ const double startupPrefillMs=std::min(renderer.capacityMs(),20.0);if(!renderer.started()&&haveHead&&1000.0*(pcm.size()/layout.channels)/kAudioRate>=startupPrefillMs&&(appliedMode!=0||fresh)){// Live recovery discards expired sound rather than replaying// an obsolete half-second after a GPU stall or graph reset.@@ -197,13 +262,35 @@ struct CaptureAudioSession::Impl : AudioPcmSource {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.- // Re-anchor the next real block instead of retaining that drift.- renderer.stopAndReset();lastReset=hostTime();- std::lock_guard lock(mutex);++state.resets;+ const auto underrunFrames=renderer.underrunFrames();+ const auto silenceFrames=renderer.silenceFrames();+ if(underruns>lastUnderruns||underrunFrames>lastUnderrunFrames||+ (starvationSince&&renderer.bufferedMs()==0&&renderer.emptyPulls()>lastEmptyPulls)){+ const auto underrunNow=hostTime();+ if(!starvationSince)starvationSince=underrunNow;+ const double starvationMs=double(underrunNow-starvationSince)/10000.0;+ if(underruns==1||(underruns%16)==0||starvationMs>=30.0)+ log::warn("capture-audio-underrun",std::format("events={} deltaEvents={} missingFrames={} silenceFrames={} starvationMs={:.3f} inputAgeMs={:.3f} endpointMs={:.3f}",underruns,underruns-lastUnderruns,underrunFrames-lastUnderrunFrames,silenceFrames-lastSilenceFrames,starvationMs,double(underrunNow-arrival)/10000.0,renderer.bufferedMs()));+ if(underrunNow-starvationSince>=liveUnderrunGrace100ns&&underrunNow-arrival>=liveUnderrunGrace100ns){+ // A single missed callback is kept as controlled+ // silence. Persistent starvation gets a bounded fade+ // and a fresh PCM/PTS anchor instead of a hard click.+ const auto fade=renderer.fadeAndReset(*this,stop);+ clearPcm();swr_close(swr);+ if(swr_init(swr)<0){fail(L"音频欠载恢复失败");break;}+ if(!clearCorrection()){fail(L"音频漂移校正重置失败");break;}+ lastReset=hostTime();starvationSince=0;endpointEventReady=false;+ std::lock_guard lock(mutex);++state.resets;+ log::warn("capture-audio-underrun",std::format("reanchor result={} afterMs={:.3f} underruns={} missingFrames={}",int(fade),starvationMs,underruns,underrunFrames));+ }+ }else if(starvationSince){+ const double recoveredMs=double(hostTime()-starvationSince)/10000.0;+ if(recoveredMs>=5.0)+ log::info("capture-audio-underrun",std::format("recovered before reanchor starvationMs={:.3f}",recoveredMs));+ starvationSince=0;}- lastUnderruns=underruns;+ lastUnderruns=underruns;lastUnderrunFrames=underrunFrames;lastSilenceFrames=silenceFrames;+ lastEmptyPulls=renderer.emptyPulls();// Large video-delay changes need a bounded re-anchor. Never// chase every jitter sample by stopping the audio endpoint.const auto observed=hostTime();const double audioPts=renderer.mediaTimeMs();@@ -212,13 +299,16 @@ struct CaptureAudioSession::Impl : AudioPcmSource {filteredError=.75*filteredError+.25*error;nextCorrection=observed+2500000;if(observed-lastReset>10000000&&std::abs(error)>60){renderer.fadeAndReset(*this,stop);lastReset=hostTime();filteredError=correctionPpm=0;+ if(!clearCorrection()){fail(L"音频漂移校正重置失败");break;}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;}+ {+ const int result=rateCorrection.set(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;}}@@ -227,13 +317,16 @@ struct CaptureAudioSession::Impl : AudioPcmSource {std::lock_guard lock(mutex);state.available=true;state.running=renderer.started();state.limited=limited;queueChanged();state.compensationMs=target;state.underruns=renderer.underruns();+ state.underrunFrames=renderer.underrunFrames();state.silenceFrames=renderer.silenceFrames();+ state.emptyPulls=renderer.emptyPulls();state.recoveryFades=renderer.recoveryFades();+ state.clockStalledGaps=renderer.clockStalledGaps();state.endpointBufferedMs=renderer.bufferedMs();const auto audioPts=renderer.mediaTimeMs();const double observedNow=double(hostTime())/10000;state.skewMs=fresh&&std::isfinite(audioPts)?std::optional<double>(audioPts-(vPts+observedNow-vHost)):std::nullopt;if(hostTime()>=nextSyncLog){nextSyncLog=hostTime()+20000000;- log::info("live-audio-sync",std::format("videoPtsMs={:.3f} videoHostMs={:.3f} audioIngressMapMs={:.3f} compensationMs={:.3f} pcmMs={:.3f} endpointMs={:.3f} skewMs={:.3f} correctionPpm={:.1f} resets={} inputBlockMs={:.3f} inputIntervalMs={:.3f} inputBlocks={} (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.inputBlockMs,state.inputIntervalMs,state.inputBlocks));+ 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));}}}@@ -242,14 +335,26 @@ struct CaptureAudioSession::Impl : AudioPcmSource {};CaptureAudioSession::CaptureAudioSession():p_(std::make_unique<Impl>()){}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;+ {+ std::lock_guard lock(p_->mutex);+ p_->state.inputChannels=parsed.layout.channels;p_->state.inputChannelMask=parsed.layout.mask;+ p_->state.inputSampleRate=parsed.wave.nSamplesPerSec;p_->state.inputContainerBits=parsed.wave.wBitsPerSample;+ p_->state.inputValidBits=parsed.validBits;p_->state.inputFloating=parsed.floating;+ }+ log::info("capture-audio-format",std::format("selected channels={} mask=0x{:X} rate={} containerBits={} validBits={} floating={} blockAlign={} avgBytesPerSec={}",parsed.layout.channels,parsed.layout.mask,parsed.wave.nSamplesPerSec,parsed.wave.wBitsPerSample,parsed.validBits,parsed.floating?1:0,parsed.wave.nBlockAlign,parsed.wave.nAvgBytesPerSec));+ return true;+}bool CaptureAudioSession::configure(const WAVEFORMATEX& f,size_t bytes){WavePcmFormat parsed;- if(p_->thread.joinable()||!parseWavePcm(&f,bytes,parsed))return false;- p_->format=parsed.wave;p_->layout=parsed.layout;p_->floating=parsed.floating;return true;+ if(!parseWavePcm(&f,bytes,parsed))return false;+ return configure(parsed);}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_->clearPcmLocked();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_->lastArrival=0;p_->state={};p_->state.inputChannels=p_->layout.channels;p_->state.inputChannelMask=p_->layout.mask;p_->state.inputSampleRate=p_->format.nSamplesPerSec;p_->state.inputContainerBits=p_->format.wBitsPerSample;p_->state.inputValidBits=p_->validBits;p_->state.inputFloating=p_->floating;}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;}@@ -278,7 +383,7 @@ bool CaptureAudioSession::push(const void* data,size_t bytes,double pts,bool disp.inputBytes+=bytes;p.input.push_back(std::move(c));p.queueChanged();p.wake.notify_one();return true;}void CaptureAudioSession::videoPresented(double pts,int64_t time){std::lock_guard lock(p_->mutex);p_->videoPts=pts;p_->videoHost=double(time)/10000;p_->haveVideo=true;}-void CaptureAudioSession::videoReset(){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(p_->mode==0)p_->pendingReset=true;p_->wake.notify_all();}+void CaptureAudioSession::videoReset(bool resetAudio){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(resetAudio&&p_->mode==0)p_->pendingReset=true;p_->wake.notify_all();}void CaptureAudioSession::setGain(float value){p_->gain=std::clamp(value,0.0f,1.0f);}void CaptureAudioSession::setSync(unsigned mode,int offset){p_->mode=std::min(mode,2u);p_->offset=std::clamp(offset,-250,250);}CaptureAudioState CaptureAudioSession::snapshot()const{std::lock_guard lock(p_->mutex);return p_->state;}diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cppindex 3d5e3a59..c2d87328 100644--- a/src/sink/WasapiAudioSink.cpp+++ b/src/sink/WasapiAudioSink.cpp@@ -315,11 +315,14 @@ bool AudioRenderer::copyPcm(BYTE* destination,const float* input,size_t frames){std::memcpy(destination,mixed_.data(),frames*outputFormat_.channels*sizeof(float));return true;}-bool AudioRenderer::start(AudioFormat input)+bool AudioRenderer::start(AudioFormat input,double requestedBufferMs){std::lock_guard endpointLock(endpointMutex_);if(client_||enum_)return checked(E_UNEXPECTED,"Endpoint already initialized");- lastError_=S_OK;bufferedMs_=0;smoothedGain_=0;+ lastError_=S_OK;bufferedMs_=0;smoothedGain_=0;fadeInRemaining_=0;underruns_=0;underrunFrames_=0;silenceFrames_=0;+ liveGap_.reset();+ emptyPulls_=0;recoveryFades_=0;+ clockStalledGaps_=0;if(!input.valid())return checked(E_INVALIDARG,"Invalid input channel layout");inputFormat_=input;lastRaw_.assign(input.channels,0);HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);@@ -349,12 +352,17 @@ bool AudioRenderer::start(AudioFormat input)}log::info("audio-format",std::format("input={} mask=0x{:X} output={} mask=0x{:X} downmix={} deviceLayoutKnown={}",input.channels,input.mask,outputFormat_.channels,outputFormat_.mask,outputFormat_.channels<input.channels,known));sampleRate_ = kAudioRate;+ requestedBufferMs=std::clamp(requestedBufferMs,5.0,50.0);+ const REFERENCE_TIME requestedBufferHns=static_cast<REFERENCE_TIME>(std::llround(requestedBufferMs*10000.0));hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK |AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,- 10 * 10000, 0, &mix.Format, nullptr);+ requestedBufferHns, 0, &mix.Format, nullptr);const bool initOk = checked(hr,"Initialize AudioClient");if (!initOk) return false;if (!checked(client_->GetBufferSize(&bufferFrames_),"GetBufferSize")) return false;+ REFERENCE_TIME devicePeriod=0;+ if(!checked(client_->GetDevicePeriod(&devicePeriod,nullptr),"GetDevicePeriod"))return false;+ devicePeriodMs_=std::max(.1,double(devicePeriod)/10000.0);event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);if(event_==nullptr)return checked(HRESULT_FROM_WIN32(GetLastError()),"CreateEvent");if(!checked(client_->SetEventHandle(event_),"SetEventHandle"))return false;@@ -367,8 +375,8 @@ bool AudioRenderer::start(AudioFormat input)if(!freq)return checked(E_UNEXPECTED,"Zero audio clock frequency");clockFrequency_=freq;running_ = true;- veyra::log::info("audio", std::format("renderer opened {}Hz event-mode buffer={} frames (not started; prefill first)",- sampleRate_, bufferFrames_));+ veyra::log::info("audio", std::format("renderer opened {}Hz event-mode requestedBufferMs={:.1f} actualBufferMs={:.3f} buffer={} frames (not started; prefill first)",+ sampleRate_,requestedBufferMs,1000.0*bufferFrames_/sampleRate_,bufferFrames_));return true;}@@ -411,7 +419,12 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMsif(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_));+ const auto consumed=static_cast<uint64_t>(double(pos-anchorPos_)*sampleRate_/clockFrequency_);+ const auto gap=liveGap_.observe(padding,consumed,timelineWriteFrame_.load());+ if(gap.frames){+ underrunFrames_.fetch_add(gap.frames);+ if(gap.began){underruns_.fetch_add(1);fadeInRemaining_=240;recoveryFades_.fetch_add(1);}+ }timelineWriteFrame_=std::max(timelineWriteFrame_.load(),consumed);}if(pipeline.pcmFormat()!=inputFormat_)return checked(E_INVALIDARG,"PCM source channel layout changed without reset");@@ -423,22 +436,47 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMsconst 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);+ // File playback owns a continuous media timeline, so it may explicitly+ // fill an empty read with silence. Live capture must not invent media+ // frames for a short gap: doing so advances the timeline with synthetic+ // audio and creates a clock jump when the next real block arrives. The+ // endpoint remains silent when ReleaseBuffer(0) is used; the capture+ // owner applies the bounded fade/re-anchor policy only for a persistent+ // starvation.+ const bool padSilence=started_&&pipeline.padUnderruns();+ const UINT32 written=padSilence?avail:static_cast<UINT32>(got);+ if(started_&&!pausedEndpoint_&&!padSilence){+ const double nowMs=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();+ if(liveGap_.observeEmpty(padding,got,nowMs,devicePeriodMs_)){+ underruns_.fetch_add(1);clockStalledGaps_.fetch_add(1);+ fadeInRemaining_=240;recoveryFades_.fetch_add(1);+ log::warn("audio-gap",std::format("persistent empty endpoint periodMs={:.3f} clockMeasuredMissingFrames=unknown recoveryFadeArmed=true",devicePeriodMs_));+ }+ }if (got > 0) {for(unsigned c=0;c<inputFormat_.channels;++c)lastRaw_[c]=chunk_[(got-1)*inputFormat_.channels+c];const float target=std::clamp(gain_.load(),0.0f,1.0f);applyPcmGain(chunk_.data(),got,inputFormat_.channels,target,smoothedGain_);+ if(fadeInRemaining_)fadePcmHead(chunk_.data(),got,inputFormat_.channels,fadeInRemaining_);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()));}if(!copyPcm(dest,chunk_.data(),got)){render_->ReleaseBuffer(0,0);return false;}if (got < written) {std::memset(dest + got * outputFormat_.channels*4, 0, (written - got) * outputFormat_.channels*4);underruns_.fetch_add(1);+ underrunFrames_.fetch_add(written-got);+ silenceFrames_.fetch_add(written-got);}} else {- std::memset(dest, 0, static_cast<size_t>(avail) * outputFormat_.channels*4);- underruns_.fetch_add(1);+ std::memset(dest, 0, static_cast<size_t>(written) * outputFormat_.channels*4);+ if(started_&&!padSilence)emptyPulls_.fetch_add(1);+ if(padSilence){+ underruns_.fetch_add(1);+ underrunFrames_.fetch_add(written);+ silenceFrames_.fetch_add(written);+ }}if (!checked(render_->ReleaseBuffer(written, 0),"ReleaseBuffer")) return false;+ liveGap_.submitted(got);if(written>got)std::fill(lastRaw_.begin(),lastRaw_.end(),0);{std::lock_guard lock(timelineMutex_);@@ -478,7 +516,7 @@ void AudioRenderer::stopAndReset()timelineWriteFrame_=0;bufferedMs_=0;smoothedGain_=0;{std::lock_guard lock(timelineMutex_);outputTimeline_.clear();timedPcm_=false;}- fading_=false;pausedEndpoint_=false;std::fill(lastRaw_.begin(),lastRaw_.end(),0);+ fading_=false;pausedEndpoint_=false;fadeInRemaining_=0;liveGap_.reset();std::fill(lastRaw_.begin(),lastRaw_.end(),0);}AudioFadeResult AudioRenderer::fadeAndReset(AudioPcmSource& source,const std::atomic<bool>& cancel)@@ -516,6 +554,8 @@ AudioFadeResult AudioRenderer::fadeAndReset(AudioPcmSource& source,const std::atbool AudioRenderer::started() const { return started_; }uint64_t AudioRenderer::underruns() const { return underruns_.load(); }+uint64_t AudioRenderer::underrunFrames() const { return underrunFrames_.load(); }+uint64_t AudioRenderer::silenceFrames() const { return silenceFrames_.load(); }uint64_t AudioRenderer::framesWritten() const { return framesWritten_; }void AudioRenderer::shutdown()@@ -529,7 +569,7 @@ void AudioRenderer::shutdown()if (event_ != nullptr) { CloseHandle(event_); event_ = nullptr; }running_ = false;started_ = false;- fading_=false;pausedEndpoint_=false;+ fading_=false;pausedEndpoint_=false;fadeInRemaining_=0;liveGap_.reset();bufferedMs_=0;framesWritten_=0;clockFrequency_=0;timelineWriteFrame_=0;{std::lock_guard lock(timelineMutex_);outputTimeline_.clear();timedPcm_=false;}@@ -540,7 +580,7 @@ void AudioRenderer::setPaused(bool value){std::lock_guard endpointLock(endpointMutex_);if (!client_ || !started_) return;- if(checked(value ? client_->Stop() : client_->Start(),"Pause/resume"))pausedEndpoint_=value;+ if(checked(value ? client_->Stop() : client_->Start(),"Pause/resume")){pausedEndpoint_=value;liveGap_.reset();}}void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex cd3d8b43..38965215 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -205,7 +205,7 @@ bool CaptureCardSource::setAudioGain(float gain){p.lastAudioGain=gain;p.audioGainSupported=SUCCEEDED(hr);log::info("capture-audio",std::format("application gain={} hr=0x{:X}",gain,unsigned(hr)));return p.audioGainSupported;}void CaptureCardSource::videoPresented(double pts,int64_t time){if(p_->audioSession)p_->audioSession->videoPresented(pts,time);}-void CaptureCardSource::videoReset(){if(p_->audioSession)p_->audioSession->videoReset();}+void CaptureCardSource::videoReset(bool resetAudio){if(p_->audioSession)p_->audioSession->videoReset(resetAudio);}void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->audioSession)p_->audioSession->setSync(mode,offset);}sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->audioSession?p_->audioSession->snapshot():sink::CaptureAudioState{};if(!p_->audioError.empty())state.error=p_->audioError;return state;}bool CaptureCardSource::open(const SourceOpenDesc& desc){return configure(desc)&&start();}@@ -285,19 +285,22 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAuif(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat)supported=sink::parseWavePcm(type->pbFormat,type->cbFormat,pcm);if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)){const auto* wave=reinterpret_cast<const WAVEFORMATEX*>(type->pbFormat);- log::info("capture-audio",std::format("mediaType={} major=0x{:08X} subtype=0x{:08X} tag={} channels={} rate={} bits={} pcm={}",typeIndex++,type->majortype.Data1,type->subtype.Data1,wave->wFormatTag,wave->nChannels,wave->nSamplesPerSec,wave->wBitsPerSample,supported?1:0));+ log::info("capture-audio",std::format("mediaType={} major=0x{:08X} subtype=0x{:08X} tag={} channels={} mask=0x{:X} rate={} containerBits={} validBits={} floating={} pcm={}",typeIndex++,type->majortype.Data1,type->subtype.Data1,wave->wFormatTag,wave->nChannels,supported?pcm.layout.mask:0,wave->nSamplesPerSec,wave->wBitsPerSample,supported?pcm.validBits:0,supported&&pcm.floating?1:0,supported?1:0));}else log::info("capture-audio",std::format("mediaType={} major=0x{:08X} subtype=0x{:08X} format=0x{:08X} pcm=0",typeIndex++,type->majortype.Data1,type->subtype.Data1,type->formattype.Data1));if(supported)audioTypes.push_back(std::move(owned));}if(audioTypes.empty()){log::warn("capture-audio","audio pin has no supported PCM media type");return false;}std::stable_sort(audioTypes.begin(),audioTypes.end(),[](const auto& a,const auto& b){- return reinterpret_cast<const WAVEFORMATEX*>(a->pbFormat)->nChannels>reinterpret_cast<const WAVEFORMATEX*>(b->pbFormat)->nChannels;+ sink::WavePcmFormat lhs{},rhs{};+ if(!sink::parseWavePcm(a->pbFormat,a->cbFormat,lhs)||!sink::parseWavePcm(b->pbFormat,b->cbFormat,rhs))return false;+ return sink::preferCaptureAudioFormat(lhs,rhs);});bool connectedAudio=false;for(const auto& owned:audioTypes){auto* type=owned.get();auto session=std::make_unique<sink::CaptureAudioSession>();ComPtr<IBaseFilter> candidate;ComPtr<IPin> terminal;- if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)&&session->configure(*reinterpret_cast<WAVEFORMATEX*>(type->pbFormat),type->cbFormat)){+ sink::WavePcmFormat parsed{};+ if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)&&sink::parseWavePcm(type->pbFormat,type->cbFormat,parsed)&&session->configure(parsed)){auto* target=session.get();hr=createNativeAudioSink(*type,[target](IMediaSample* sample){BYTE* bytes=nullptr;REFERENCE_TIME begin=0,end=0;@@ -310,7 +313,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu// Some devices reject this advisory API, so do not fail capture.if(SUCCEEDED(hr))suggestCaptureAudioBuffering(audioPin.Get(),*reinterpret_cast<const WAVEFORMATEX*>(type->pbFormat));if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(audioPin.Get(),terminal.Get(),type);- if(SUCCEEDED(hr)){p.audioSink=candidate;p.audioSession=std::move(session);connectedAudio=true;}+ if(SUCCEEDED(hr)){p.audioSink=candidate;p.audioSession=std::move(session);connectedAudio=true;log::info("capture-audio",std::format("selected media type channels={} mask=0x{:X} rate={} containerBits={} validBits={} floating={}",parsed.layout.channels,parsed.layout.mask,parsed.wave.nSamplesPerSec,parsed.wave.wBitsPerSample,parsed.validBits,parsed.floating?1:0));}else if(candidate)p.graph->RemoveFilter(candidate.Get());log::info("capture-audio",std::format("PCM ConnectDirect hr=0x{:X}",unsigned(hr)));}diff --git a/tests/integration/AudioWaveformTests.cpp b/tests/integration/AudioWaveformTests.cppnew file mode 100644index 00000000..c2608019--- /dev/null+++ b/tests/integration/AudioWaveformTests.cpp@@ -0,0 +1,145 @@+#include "veyra/sink/CaptureAudioDsp.h"+#include "veyra/sink/AudioGain.h"+#include "veyra/sink/WasapiAudioSink.h"+#include <iostream>+#include <vector>+#include <array>+#include <limits>+#include <stdexcept>+#include <string>+#include <numbers>+extern "C" {+#include <libswresample/swresample.h>+}+using namespace veyra::sink;+namespace {+void checked(int result){if(result<0)throw std::runtime_error("FFmpeg error "+std::to_string(result));}+struct Swr {+ SwrContext* ctx=nullptr;+ Swr(unsigned rate,unsigned channels){+ AVChannelLayout layout{};av_channel_layout_default(&layout,int(channels));+ const int result=swr_alloc_set_opts2(&ctx,&layout,AV_SAMPLE_FMT_FLT,48000,&layout,AV_SAMPLE_FMT_FLT,int(rate),0,nullptr);+ av_channel_layout_uninit(&layout);checked(result);checked(swr_init(ctx));+ }+ ~Swr(){swr_free(&ctx);}+};+// Uses the same correction/sanitization implementation as CaptureAudioSession.+// Reference explicitly holds FFmpeg history; never re-creates on zero crossing.+std::vector<float> render(unsigned rate,unsigned channels,double frequency,unsigned blockFrames,bool production,bool broken=false){+ Swr swr(rate,channels);CaptureRateCorrection correction;+ if(production)checked(correction.prepare(swr.ctx,true));else checked(swr_set_compensation(swr.ctx,0,0));+ const unsigned total=rate*2,period=rate/4;+ const std::array<int,8> deltas={-60,0,60,0,-12,0,12,0};+ std::vector<float> output;+ auto convert=[&](const float* pcm,unsigned frames){+ const int capacity=swr_get_out_samples(swr.ctx,int(frames));checked(capacity);+ std::vector<float> converted(size_t(capacity)*channels);+ uint8_t* dst[]={reinterpret_cast<uint8_t*>(converted.data())};+ const uint8_t* src[]={reinterpret_cast<const uint8_t*>(pcm)};+ const int count=swr_convert(swr.ctx,dst,capacity,pcm?src:nullptr,int(frames));checked(count);+ if(production)inspectCapturePcm(converted.data(),size_t(count)*channels);+ output.insert(output.end(),converted.begin(),converted.begin()+size_t(count)*channels);+ return count;+ };+ for(unsigned at=0;at<total;){+ if(at%period==0){+ const int delta=deltas[(at/period)%deltas.size()];+ if(broken&&!delta){swr_close(swr.ctx);checked(swr_init(swr.ctx));}+ if(production)checked(correction.set(swr.ctx,delta));+ else checked(swr_set_compensation(swr.ctx,delta,delta?48000:0));+ }+ const unsigned frames=std::min({blockFrames,total-at,period-at%period});+ std::vector<float> input(size_t(frames)*channels);+ for(unsigned i=0;i<frames;++i)for(unsigned c=0;c<channels;++c)+ input[size_t(i)*channels+c]=float(.5*std::sin(2*std::numbers::pi*frequency*(at+i)/rate+.71+c*.2));+ convert(input.data(),frames);at+=frames;+ }+ while(convert(nullptr,0)>0){}+ return output;+}+double difference(const std::vector<float>& a,const std::vector<float>& b){+ if(a.size()!=b.size())return 999;+ double error=0;for(size_t i=0;i<a.size();++i)error=std::max(error,std::abs(double(a[i])-b[i]));return error;+}+}+int main(int argc,char** argv){+ if(argc>1&&(std::string(argv[1])=="--endpoint"||std::string(argv[1])=="--endpoint-gap")){+ const bool gapTest=std::string(argv[1])=="--endpoint-gap";+ struct PausedLiveSource:AudioPcmSource {+ size_t remaining=240;+ bool padUnderruns()const override{return false;}+ size_t pull(float* out,size_t requested,double* pts)override{+ const auto count=std::min(remaining,requested);remaining-=count;*pts=0;+ std::fill(out,out+count*2,.25f);return count;+ }+ } source;+ AudioRenderer renderer;renderer.setGain(0);+ // The endpoint is paused after prefill: queued PCM provably cannot+ // have run out, even if this test is descheduled. No audible playback.+ bool ok=renderer.start({},20)&&renderer.startAnchored(source,!gapTest);+ double pts=0;+ if(gapTest){+ // Keep the source dry over multiple endpoint periods. Some drivers+ // freeze IAudioClock at the last submitted frame during starvation.+ for(unsigned i=0;ok&&i<8;++i){Sleep(10);ok=renderer.pumpOnce(source,&pts,false);}+ source.remaining=240;+ if(ok)ok=renderer.pumpOnce(source,&pts,false)&&renderer.underruns()>0&&renderer.recoveryFades()>0;+ std::cout<<(ok?"PASS ":"FAIL ")<<"REAL_WASAPI true starvation emptyPulls="<<renderer.emptyPulls()+ <<" gaps="<<renderer.underruns()<<" fades="<<renderer.recoveryFades()<<" muted=true\n";+ renderer.shutdown();return ok?0:1;+ }+ if(ok)ok=renderer.pumpOnce(source,&pts,false)&&renderer.emptyPulls()==1&&+ renderer.underruns()==0&&renderer.underrunFrames()==0&&renderer.recoveryFades()==0;+ source.remaining=240;+ if(ok)ok=renderer.pumpOnce(source,&pts,false)&&renderer.recoveryFades()==0;+ std::cout<<(ok?"PASS ":"FAIL ")<<"REAL_WASAPI queued empty pull emptyPulls="<<renderer.emptyPulls()+ <<" gaps="<<renderer.underruns()<<" fades="<<renderer.recoveryFades()<<" paused=true muted=true\n";+ renderer.shutdown();return ok?0:1;+ }+ unsigned checks=0,failures=0;+ auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<'\n';};+ try{+ 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);+ const auto repartitioned=render(rate,channels,hz,127,true);+ const double error=difference(product,reference),blockError=difference(product,repartitioned);+ std::cout<<"rate="<<rate<<" channels="<<channels<<" hz="<<hz<<" frames="<<product.size()/channels<<" referenceError="<<error<<" blockError="<<blockError<<'\n';+ check(error<1e-6,"production correction matches continuous reference across positive/zero/negative ratios");+ check(blockError<1e-6,"changing callback partitions preserves waveform and frame count");+ }+ const auto reference=render(48000,2,4000,480,false);+ const auto broken=render(48000,2,4000,480,false,true);+ std::cout<<"referenceFrames="<<reference.size()/2<<" brokenResetFrames="<<broken.size()/2<<'\n';+ check(difference(reference,broken)>.1,"negative control: resetting FIR history fails waveform/frame test");+ std::vector<float> samples={1.05f,1.05f,-1.1f,.9f,.5f};const auto original=samples;+ const auto stats=inspectCapturePcm(samples.data(),samples.size());+ check(samples==original&&stats.overRange==3&&stats.nonFinite==0,"finite over-unity samples survive without clipping or AGC");+ float gain=0.5f;applyPcmGain(samples.data(),samples.size(),1,.5f,gain);+ check(std::abs(samples[0]-.525f)<1e-6,"user attenuation applies after preserving float headroom");+ samples={std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::infinity(),-.5f};+ const auto invalid=inspectCapturePcm(samples.data(),samples.size());+ check(invalid.nonFinite==2&&samples[0]==0&&samples[1]==0&&samples[2]==-.5f,"non-finite values sanitized without changing finite PCM");+ LiveAudioGapTracker gaps;+ auto observation=gaps.observe(480,480,960);+ check(!observation.frames&&!observation.began,"empty pull with queued PCM does not trigger recovery fade");+ observation=gaps.observe(0,960,960);+ check(!observation.frames&&!observation.began,"exact endpoint boundary is not evidence of a gap");+ observation=gaps.observe(0,1000,960);+ check(observation.frames==40&&observation.began,"actual device clock gap starts one event");+ observation=gaps.observe(0,1020,1000);+ check(observation.frames==20&&!observation.began,"ongoing gap counts only new frames, not writable capacity");+ gaps.submitted(480);observation=gaps.observe(0,1600,1500);+ check(observation.frames==100&&observation.began,"real PCM closes a gap before a new interruption");+ gaps.reset();observation=gaps.observe(480,0,480);+ check(!observation.frames,"reset clears previous gap state");+ check(!gaps.observeEmpty(480,0,0,10),"queued empty observation never starts a starvation timer");+ check(!gaps.observeEmpty(0,0,10,10)&&!gaps.observeEmpty(0,480,15,10),"short empty observation does not arm a fade");+ check(!gaps.observeEmpty(0,0,20,10)&&gaps.observeEmpty(0,0,31,10),"sustained empty endpoint detected even when device clock freezes");+ check(!gaps.observeEmpty(0,0,50,10),"frozen-clock starvation is counted once");+ Swr native(48000,2);CaptureRateCorrection manual;checked(manual.prepare(native.ctx,false));+ check(manual.set(native.ctx,60)<0,"unprepared live identity cannot hot-switch into compensation");+ }catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 2;}+ std::cout<<"AUDIO_WAVEFORM checks="<<checks<<" failures="<<failures<<" (offline production DSP; no speaker claim)\n";+ return failures?1:0;+}diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cppindex 4ccbafe6..ceffb4b1 100644--- a/tests/integration/CaptureAudioTests.cpp+++ b/tests/integration/CaptureAudioTests.cpp@@ -22,14 +22,46 @@ int main(int argc,char** argv){} pacer;const bool endpointTest=argc>=2&&std::string_view(argv[1])=="--endpoint-loss";const bool jitterTest=argc>=2&&std::string_view(argv[1])=="--jitter";+ const bool transientTest=argc>=2&&std::string_view(argv[1])=="--transient";+ const bool compensatedTransientTest=argc>=2&&std::string_view(argv[1])=="--transient-comp";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");const bool multichannel=argc>=3&&std::string_view(argv[2])=="--5.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;+ CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=transientTest?44100:48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=f.nSamplesPerSec*f.nBlockAlign;auto extended=floatWave({6,0x60f});extended.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;extended.Format.wBitsPerSample=16;extended.Samples.wValidBitsPerSample=16;extended.Format.nBlockAlign=12;extended.Format.nAvgBytesPerSec=576000;if(!(multichannel?audio.configure(extended.Format,sizeof(extended)):audio.configure(f))||!audio.start())return 2;audio.setGain(0);- std::vector<int16_t> pcm(480*(multichannel?6:2),0);const auto start=Clock::now();+ const unsigned channels=multichannel?6:2;std::vector<int16_t> pcm(480*channels);+ for(size_t i=0;i<pcm.size()/channels;++i)for(unsigned c=0;c<channels;++c)pcm[i*channels+c]=int16_t(2000*std::sin((i*channels+c)*0.031));+ const auto start=Clock::now();+ if(transientTest){+ const size_t frames=441;std::vector<int16_t> block(frames*2);+ for(unsigned blockIndex=0;blockIndex<30;++blockIndex){+ pacer.until(start+std::chrono::milliseconds(blockIndex*10));+ std::fill(block.begin(),block.end(),blockIndex>=10&&blockIndex<20?int16_t(32767):int16_t(0));+ if(!audio.push(block.data(),block.size()*sizeof(int16_t),blockIndex*10.0,blockIndex==0))return 10;+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ const auto state=audio.snapshot();audio.stop();+ const bool pass=state.inputSampleRate==44100&&state.inputBlocks==30&&state.nonFiniteSamples==0&&state.clippedSamples==0&&state.overRangeSamples>0&&state.inputPeak>1.0;+ std::cout<<(pass?"PASS ":"FAIL ")<<"44.1k sharp transient conversion clipped="<<state.clippedSamples<<" peakProtected="<<state.peakProtectedSamples<<" nonFinite="<<state.nonFiniteSamples<<" peak="<<state.inputPeak<<" blocks="<<state.inputBlocks<<'\n';+ return pass?0:1;+ }+ if(compensatedTransientTest){+ const size_t frames=480;std::vector<int16_t> block(frames*2);+ for(unsigned blockIndex=0;blockIndex<500;++blockIndex){+ pacer.until(start+std::chrono::milliseconds(blockIndex*10));+ std::fill(block.begin(),block.end(),blockIndex>=300&&blockIndex<310?int16_t(32767):int16_t(0));+ if(!audio.push(block.data(),block.size()*sizeof(int16_t),blockIndex*10.0,blockIndex==0))return 11;+ const auto host=std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count()/100;+ audio.videoPresented(blockIndex*10.0-80,host);+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ const auto state=audio.snapshot();audio.stop();+ const bool pass=state.inputSampleRate==48000&&state.inputBlocks==500&&state.nonFiniteSamples==0&&state.clippedSamples==0&&state.overRangeSamples>0&&state.inputPeak>1.0;+ std::cout<<(pass?"PASS ":"FAIL ")<<"48k compensated sharp transient conversion clipped="<<state.clippedSamples<<" peakProtected="<<state.peakProtectedSamples<<" nonFinite="<<state.nonFiniteSamples<<" peak="<<state.inputPeak<<" correctionPpm="<<state.driftCorrectionPpm<<" blocks="<<state.inputBlocks<<'\n';+ return pass?0:1;+ }if(jitterTest){uint64_t settledResets=0,settledUnderruns=0;unsigned missing=0;std::vector<double> errors;for(unsigned i=0;i<500;++i){@@ -45,9 +77,9 @@ int main(int argc,char** argv){}const auto s=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 inputTelemetry=s.inputBlocks==500&&std::abs(s.inputBlockMs-10)<.001&&s.inputIntervalMs>=0&&s.inputIntervalMs<100;+ const bool inputTelemetry=s.inputBlocks==500&&std::abs(s.inputBlockMs-10)<.001&&s.inputIntervalMs>=0&&s.inputIntervalMs<100&&s.inputPeak>.01&&s.nonFiniteSamples==0&&s.clippedSamples==0;const bool pass=inputTelemetry&&missing==0&&s.resets==settledResets&&s.underruns==settledUnderruns&&s.overflows==0&&p95<35;- std::cout<<(pass?"PASS ":"FAIL ")<<"CAPTURE_JITTER additionalResets="<<s.resets-settledResets<<" additionalUnderruns="<<s.underruns-settledUnderruns<<" missing="<<missing<<" p95SkewMs="<<p95<<" inputBlocks="<<s.inputBlocks<<" inputBlockMs="<<s.inputBlockMs<<" inputIntervalMs="<<s.inputIntervalMs<<'\n';+ std::cout<<(pass?"PASS ":"FAIL ")<<"CAPTURE_JITTER additionalResets="<<s.resets-settledResets<<" additionalUnderruns="<<s.underruns-settledUnderruns<<" missing="<<missing<<" p95SkewMs="<<p95<<" inputBlocks="<<s.inputBlocks<<" inputBlockMs="<<s.inputBlockMs<<" inputIntervalMs="<<s.inputIntervalMs<<" peak="<<s.inputPeak<<" nonFinite="<<s.nonFiniteSamples<<" clipped="<<s.clippedSamples<<'\n';return pass?0:1;}if(driftTest){@@ -82,7 +114,7 @@ int main(int argc,char** argv){if(endpointTest){ok=ok&&sawReconnecting&&state.error.empty()&&state.endpointRetries>=2&&state.running;audio.stop();std::cout<<(ok?"PASS ":"FAIL ")<<"owned WASAPI endpoint recovered without reopening capture retries="<<state.endpointRetries<<'\n';return ok?0:1;}std::cout<<(ok?"PASS":"FAIL")<<" synthetic capture PTS with 80ms video delay; real WASAPI, no physical capture\n";unsigned sequence=160;- auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew,double commonInputMs=0){+ auto phase=[&](unsigned mode,int offset,double delay,double expectedComp,double expectedSkew,double commonInputMs=0,double maxSkewError=28){audio.setSync(mode,offset);double error=0;unsigned samples=0;bool boundedPhase=true;const unsigned steps=delay>500?300:150;for(unsigned j=0;j<steps;++j,++sequence){@@ -93,7 +125,7 @@ int main(int argc,char** argv){boundedPhase&=s.bufferedMs<=2000;if(j>steps-80&&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;+ const auto s=audio.snapshot();const bool pass=samples>=60&&error/samples<maxSkewError&&std::abs(s.compensationMs-expectedComp)<15&&boundedPhase&&s.overflows==0;std::cout<<(pass?"PASS ":"FAIL ")<<"capture phase mode="<<mode<<" delay="<<delay<<" commonInputMs="<<commonInputMs<<" 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;@@ -103,19 +135,33 @@ int main(int argc,char** argv){// Start a fresh ingress epoch after the shared-input offset fixture.audio.stop();if(!audio.start())return 7;ok=phase(0,0,80,80,0)&&ok;- audio.videoReset();+ const auto beforeGraphReset=audio.snapshot();+ audio.videoReset(false);for(unsigned i=0;i<35;++i,++sequence){pacer.until(start+std::chrono::milliseconds(sequence*10));- if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,i==0))return 8;+ // This models a video graph rebuild only. The audio callback remains+ // on the same DirectShow epoch; a true audio discontinuity is tested+ // separately through the normal reset/re-anchor paths.+ if(!audio.push(pcm.data(),pcm.size()*2,sequence*10.0,false))return 8;}- const bool heldForGraph=!audio.snapshot().running;- std::cout<<(heldForGraph?"PASS ":"FAIL ")<<"graph reset waits for new video while input PCM continues\n";ok=heldForGraph&&ok;+ const auto afterGraphReset=audio.snapshot();+ const bool heldForGraph=afterGraphReset.running&&afterGraphReset.resets==beforeGraphReset.resets;+ std::cout<<(heldForGraph?"PASS ":"FAIL ")<<"video graph reset preserves running audio clock\n";ok=heldForGraph&&ok;ok=phase(0,0,80,80,0)&&ok;ok=phase(1,100,80,100,-20)&&ok;- ok=phase(2,0,80,0,80)&&ok;- ok=phase(1,-100,80,0,80)&&ok;+ // With the shared endpoint's 20 ms safety window and no requested+ // compensation, the observed software skew has a wider scheduling+ // envelope than the auto/manual-delay phases. This is timing tolerance,+ // not permission to insert or drop PCM.+ ok=phase(2,0,80,0,80,0,45)&&ok;+ ok=phase(1,-100,80,0,80,0,45)&&ok;+ // Keep the SAME sync mode before and after the stall. Otherwise the+ // explicit mode-switch reset can falsely satisfy this recovery assertion.+ ok=phase(0,0,80,80,0)&&ok;const auto beforeStall=audio.snapshot().resets;std::this_thread::sleep_for(std::chrono::milliseconds(350));sequence+=35;+ const bool reanchoredWhileDry=audio.snapshot().resets>beforeStall;+ std::cout<<(reanchoredWhileDry?"PASS ":"FAIL ")<<"persistent dry input recovers without a sync setting change\n";ok=reanchoredWhileDry&&ok;ok=phase(0,0,80,80,0)&&ok;const bool recovered=audio.snapshot().resets>beforeStall;std::cout<<(recovered?"PASS ":"FAIL ")<<"audio reanchors real PCM after ingress stall\n";ok=recovered&&ok;diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cppindex 1ec7f42f..faa07f19 100644--- a/tests/integration/CaptureSourceTests.cpp+++ b/tests/integration/CaptureSourceTests.cpp@@ -26,6 +26,13 @@ int wmain(int argc,wchar_t** argv){std::this_thread::sleep_for(std::chrono::milliseconds(150));check(!source.info().opened&&source.metrics().received==0,"configure does not start capture/audio");if(!source.start()){printf("FAIL start\n");return 4;}+ // Keep the physical regression silent while still exercising the real+ // capture-card audio renderer and its format negotiation.+ source.setAudioGain(0.0f);+ // This source-only test has no presenter to provide video host/PTS+ // anchors. Use the explicit audio-clock mode so the renderer remains+ // running while the test validates actual audio callbacks.+ source.setAudioSync(2,0);const AVFrame* frame=nullptr;veyra::pipeline::FramePacket packet;auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame)return true;if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};@@ -41,9 +48,15 @@ int wmain(int argc,wchar_t** argv){deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);check(readFrame(),"read after consumer stall");auto recovered=source.metrics();+ const auto audio=source.audioState();+ check(audio.running&&audio.error.empty()&&audio.inputSampleRate==48000&&audio.inputBlocks>=20,+ "real capture-card audio renderer runs at selected 48 kHz format");check(packet.pts.toDouble()>initialPts+.15,"read skips stale frames rather than draining FIFO");check(veyra::pipeline::hasFrameFlag(packet.flags,veyra::pipeline::FrameFlagBits::Drop),"drop invalidates temporal history");check(recovered.readAgeMs<100,"latest frame callback age below 100ms");printf("received=%llu dropped=%llu callbackFps=%.3f readAgeMs=%.3f\n",recovered.received,recovered.dropped,recovered.callbackFps,recovered.readAgeMs);+ printf("audioBlocks=%llu format=%uHz/%ubit validBits=%u underruns=%llu underrunFrames=%llu peak=%.5f resets=%llu\n",+ audio.inputBlocks,audio.inputSampleRate,audio.inputContainerBits,audio.inputValidBits,audio.underruns,+ audio.underrunFrames,audio.inputPeak,audio.resets);source.close();CoUninitialize();return failures?1:0;}diff --git a/tests/integration/MultichannelTests.cpp b/tests/integration/MultichannelTests.cppindex 969e95aa..098e25c8 100644--- a/tests/integration/MultichannelTests.cpp+++ b/tests/integration/MultichannelTests.cpp@@ -5,6 +5,8 @@#include <filesystem>#include <iostream>#include <cmath>+#include <chrono>+#include <thread>using namespace veyra::sink;static void wave(const std::filesystem::path& path,unsigned rate,uint32_t mask,bool isolated=false){auto w=floatWave({6,mask});w.Format.nSamplesPerSec=rate;w.Format.nAvgBytesPerSec=rate*24;@@ -21,6 +23,14 @@ int wmain(int argc,wchar_t** argv){check(!parseWavePcm(&w,sizeof(WAVEFORMATEX),parsed),"truncated extended format rejected");w.dwChannelMask=3;check(!parseWavePcm(&w,sizeof(w),parsed),"six channels with stereo mask rejected");}+ {+ auto w=floatWave({2,0x3});w.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;w.Format.wBitsPerSample=32;w.Format.nBlockAlign=8;w.Format.nAvgBytesPerSec=48000*8;w.Samples.wValidBitsPerSample=24;+ WavePcmFormat parsed;check(parseWavePcm(&w,sizeof(w),parsed)&&parsed.validBits==24&&parsed.wave.wBitsPerSample==32,"24 valid bits in 32-bit PCM container accepted");+ WAVEFORMATEX low{};low.wFormatTag=WAVE_FORMAT_PCM;low.nChannels=2;low.nSamplesPerSec=44100;low.wBitsPerSample=16;low.nBlockAlign=4;low.nAvgBytesPerSec=44100*4;+ WAVEFORMATEX native=low;native.nSamplesPerSec=48000;native.nAvgBytesPerSec=48000*4;+ WavePcmFormat lowParsed{},nativeParsed{};parseWavePcm(&low,sizeof(low),lowParsed);parseWavePcm(&native,sizeof(native),nativeParsed);+ check(preferCaptureAudioFormat(nativeParsed,lowParsed)&&!preferCaptureAudioFormat(lowParsed,nativeParsed),"capture format preference chooses native 48 kHz over enumeration order");+ }for(auto mask:{0x3fu,0x60fu})for(unsigned rate:{44100u,48000u,96000u}){const auto path=root/(std::to_wstring(mask)+L"-"+std::to_wstring(rate)+L".wav");wave(path,rate,mask);AudioPipeline pipe;bool ok=pipe.open(path.wstring())&&pipe.pcmFormat()==AudioFormat{6,mask};@@ -55,6 +65,14 @@ int wmain(int argc,wchar_t** argv){for(unsigned i=0;started&&i<80;++i){std::this_thread::sleep_until(begin+std::chrono::milliseconds(i*10));started=capture.push(silence.data(),silence.size()*4,i*10.0,i==0);}const auto state=capture.snapshot();capture.stop();std::cout<<"capture input="<<state.inputChannels<<" output="<<state.outputChannels<<" mask="<<state.outputChannelMask<<" blocks="<<state.inputBlocks<<std::endl;- check(started&&state.available&&state.running&&state.inputChannels==6&&state.outputChannels>0&&state.overflows==0,"5.1 capture to actual WASAPI endpoint (muted; no speaker claim)");+ check(started&&state.available&&state.running&&state.inputChannels==6&&state.outputChannels>0&&state.overflows==0&&state.inputValidBits==32,"5.1 capture to actual WASAPI endpoint (muted; no speaker claim)");+ {+ auto format24=floatWave({2,0x3});format24.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;format24.Format.wBitsPerSample=32;format24.Format.nBlockAlign=8;format24.Format.nAvgBytesPerSec=48000*8;format24.Samples.wValidBitsPerSample=24;+ CaptureAudioSession capture24;bool ok=capture24.configure(format24.Format,sizeof(format24))&&capture24.start();capture24.setGain(0);capture24.setSync(2,0);+ std::vector<int32_t> samples(480*2);for(size_t i=0;i<samples.size();++i){const int32_t value=int32_t(0.25*2147483647.0);samples[i]=value&~0xFF;}+ const auto begin24=std::chrono::steady_clock::now();for(unsigned i=0;ok&&i<80;++i){std::this_thread::sleep_until(begin24+std::chrono::milliseconds(i*10));ok=capture24.push(samples.data(),samples.size()*sizeof(int32_t),i*10.0,i==0);}+ const auto state24=capture24.snapshot();capture24.stop();+ check(ok&&state24.inputContainerBits==32&&state24.inputValidBits==24&&state24.nonFiniteSamples==0&&state24.inputPeak>.20&&state24.inputPeak<.30&&state24.invalidPaddingSamples==0,"24-in-32 PCM is left-aligned and finite after conversion");+ }std::cout<<"MULTICHANNEL checks="<<checks<<" failures="<<failures<<std::endl;return failures?1:0;}