Skip to content

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

C++

feat(capture): add explicit WASAPI audio input

Veyra Goal Agent89751cdbc9ea
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d20339ea..622b2351 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -416,6 +416,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
src/source/CaptureCardSource.cpp
+ src/source/WasapiAudioInput.cpp
)
veyra_apply_warnings(veyra_sources)
target_compile_options(veyra_sources PRIVATE /WX-)
@@ -447,6 +448,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_source_tests PRIVATE veyra_sources)
add_executable(veyra_capture_tests tests/integration/CaptureSourceTests.cpp)
+ add_executable(veyra_wasapi_input_tests tests/integration/WasapiInputTests.cpp)
+ target_compile_features(veyra_wasapi_input_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_wasapi_input_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
+ target_link_libraries(veyra_wasapi_input_tests PRIVATE veyra_sources)
target_compile_features(veyra_capture_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_capture_tests PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX)
target_link_libraries(veyra_capture_tests PRIVATE veyra_sources)
diff --git a/README.md b/README.md
index 537f4aaf..5f3873cc 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,7 @@ Windows 视频播放器与采集卡增强工具。支持视频、图片、采集
- 音频已修复连续重采样历史、浮点余量和空拉恢复等已确认缺陷,撤回造成声音发闷的处理。**火堆、口哨场景的沙沙声尚未完成真实听感验收,不能宣称已根治。**
- 媒体兼容改进有 AV1 MP4、ProRes MOV 等样本证据;MOV 是容器,不承诺所有编码组合可播放。AV1 / ProRes 导出仍不支持。
+- 采集音频现在可在“音频监听”中选择 DirectShow 音频或明确的 WASAPI 录音端点;WASAPI 使用共享模式、稳定端点 ID 和现有 PCM 音频处理链,不自动选择麦克风,也不做系统回录。
- 分支整合、逐项验证与候选程序位置见 [当前修复汇总](docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md)。已发布功能说明与未发布修复应分别阅读。
## 功能
@@ -71,8 +72,9 @@ BUG反馈与新功能
1. 连接设备,关闭其他软件对同一采集卡的占用。
2. 点击“采集”,选择设备、分辨率、帧率、像素格式及音频设备。
-3. 先关闭增强确认基础画面,再按需打开 NR、超分和补帧。同一模式下可优先试 YUY2 / NV12。
-4. 若主机游戏为30fps、采集卡输出60fps,在专业模式的内容节奏中选择60转30;真正60fps内容使用原始采集节奏。
+3. 在“音频监听”中按来源选择 `[DirectShow]` 或 `[WASAPI]`;默认是不监听音频。WASAPI 端点用 Windows 设备 ID 保存,只连接你明确选中的输入,不会自动切到麦克风或系统回录。
+4. 先关闭增强确认基础画面,再按需打开 NR、超分和补帧。同一模式下可优先试 YUY2 / NV12。
+5. 若主机游戏为30fps、采集卡输出60fps,在专业模式的内容节奏中选择60转30;真正60fps内容使用原始采集节奏。
### PS5 串流
diff --git a/README_EN.md b/README_EN.md
index 8069b49e..788b9a62 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -22,6 +22,7 @@ Local `main` includes repair commit `dc44c48`. The download above is still the *
- Confirmed audio defects in resampler history, float headroom and empty-pull recovery have been addressed; the processing that muffled audio was withdrawn. **The reported fire/whistle hiss has not passed real listening acceptance and is not claimed resolved.**
- Media improvements have sample evidence for AV1 MP4 and ProRes MOV, not every codec/container combination. AV1 / ProRes export remains unsupported.
+- Capture audio can now be selected as DirectShow audio or an explicit WASAPI recording endpoint. WASAPI uses shared mode, a stable endpoint ID, and the existing PCM audio path; it never auto-selects a microphone or performs system loopback.
- See the [local integration status](docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md) for included repairs, verification limits and the candidate executable. Keep released capabilities separate from unreleased fixes.
## Features
@@ -76,8 +77,9 @@ Choose Open on the bottom bar. Playback, seeking, volume, subtitles, and fullscr
1. Connect the device and close other applications using the same capture card.
2. Choose Capture, then select the device, resolution, frame rate, pixel format, and audio input.
-3. Confirm the picture with enhancement disabled, then enable NR, upscaling, or frame generation. Try YUY2 / NV12 when the device offers the same desired mode.
-4. For a 30fps console game carried over 60fps capture, select the 60-to-30 content cadence setting in Professional mode. Keep the original cadence for actual 60fps content.
+3. In Audio monitoring, choose a `[DirectShow]` device or an explicit `[WASAPI]` endpoint; the default is no audio monitoring. WASAPI stores the Windows endpoint ID and connects only to the selected input; it does not fall back to a microphone or system loopback.
+4. Confirm the picture with enhancement disabled, then enable NR, upscaling, or frame generation. Try YUY2 / NV12 when the device offers the same desired mode.
+5. For a 30fps console game carried over 60fps capture, select the 60-to-30 content cadence setting in Professional mode. Keep the original cadence for actual 60fps content.
### Enhancement and Frame Generation
diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cpp
index f14718e4..47241ab7 100644
--- a/apps/veyra/ui/CapturePanel.cpp
+++ b/apps/veyra/ui/CapturePanel.cpp
@@ -16,7 +16,7 @@ void rebuildAudioList(HWND h,int device){
SendDlgItemMessageW(h,3,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(L"不监听音频"));
const bool videoSelected=device>=0&&size_t(device)<videoDevices.size();
if(videoSelected)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(videoDevices[size_t(device)].hasEmbeddedAudio?L"使用视频设备内置音频(已检测)":L"尝试视频设备内置音频"));
- for(auto& audio:audioDevices)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(audio.name.c_str()));
+ for(auto& audio:audioDevices){const auto label=std::format(L"[{}] {}",audio.wasapi?L"WASAPI":L"DirectShow",audio.name);SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(label.c_str()));}
SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);
}
int selectedAudio(HWND h,int device){
@@ -37,7 +37,7 @@ case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar
for(auto name:{L"自动识别 SDR / HDR · 设备元数据",L"手动 HDR10 / PQ · BT.2020",L"手动 HLG · BT.2020 / 1000nit参考"})SendDlgItemMessageW(h,10,CB_ADDSTRING,0,LPARAM(name));SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);
add(L"BUTTON",L"转为 SDR 显示(所有预览,立即生效)",12,BS_AUTOCHECKBOX|WS_TABSTOP);SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
add(L"BUTTON",L"连接并开始观看",4,BS_PUSHBUTTON|WS_TABSTOP);marked(GetDlgItem(h,4));add(L"BUTTON",L"刷新设备",5,BS_PUSHBUTTON|WS_TABSTOP);
- add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"HDMI 音频监听",9,0);
+ add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"音频监听(仅采集所选输入,默认关闭)",9,0);
installDialogHelp(h,{{12,L"收到HDR也转成SDR显示,不用改PS5或Windows。增强照常用;只改预览,视频导出不受影响。切换会短暂停顿,截图跟随当前画面。关闭后跟随显示器。"},{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"如果设备自带 HDMI 音频,会显示“使用视频设备内置音频”;否则选择独立音频设备,也可不采声音。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});
EnableWindow(GetDlgItem(h,4),FALSE);arrange();SetTimer(h,1,100,nullptr);if(!busy)query(-1);return 0;}
case WM_TIMER:
diff --git a/docs/BUILD.md b/docs/BUILD.md
index 4a0008eb..84ee3cbd 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -12,11 +12,23 @@ Targeted audio verification from the repository root:
```powershell
& ./out/build/audio-continuity-repair-20260915/veyra_audio_waveform_tests.exe --offline
+& ./out/build/audio-continuity-repair-20260915/veyra_wasapi_input_tests.exe --offline
powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -LogDirectory logs/audio-continuity-local-check
powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/diagnostics/test-audio-continuity.ps1 -BuildDirectory out/build/audio-continuity-repair-20260915 -LogDirectory logs/audio-continuity-local-check -DriftOnly
```
-The first command is offline DSP only. The script additionally uses the real Windows audio endpoint with muted synthetic tests; each drift case runs for 120 seconds. Neither proves capture-card listening quality or replaces GPU / export verification. Do not run endpoint suites concurrently.
+The first two commands are offline DSP/timebase checks. The script additionally uses the real Windows audio endpoint with muted synthetic tests; each drift case runs for 120 seconds. Neither proves capture-card listening quality or replaces GPU / export verification. Do not run endpoint suites concurrently.
+
+WASAPI input-specific checks:
+
+```powershell
+& ./out/build/audio-continuity-repair-20260915/veyra_wasapi_input_tests.exe --list
+& ./out/build/audio-continuity-repair-20260915/veyra_wasapi_input_tests.exe --invalid
+& ./scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_wasapi_input_tests.exe -Arguments @('--endpoint','<explicit endpoint ID>') -TimeoutSeconds 20 -LogPrefix logs/wasapi-input-20260915/endpoint
+& ./scripts/run-short-test.ps1 -Exe out/build/audio-continuity-repair-20260915/veyra_capture_tests.exe -Arguments @('--wasapi','<explicit endpoint ID>') -TimeoutSeconds 20 -LogPrefix logs/wasapi-input-20260915/video-wasapi
+```
+
+`--endpoint` and `--wasapi` require a user-selected active recording endpoint ID from `--list`; the placeholder must not be replaced with a default device. These tests use muted input/output and do not save PCM. A successful local endpoint test proves enumeration, PCM delivery and lifecycle only; it does not prove the reported hiss is gone.
## Requirements
diff --git a/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md b/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
index d8275946..a3fd2586 100644
--- a/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
+++ b/docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md
@@ -20,6 +20,7 @@
| 采集卡内置音频无法选择 | `d9a94eb` | 增加视频filter内置音频pin绑定、稳定DevicePath及旧连接串兼容;本机独立音频枚举和专项通过,反馈者内置音频实卡未验收。此提交标题为checkpoint,但确实包含该修复。 |
| 长时间实时补帧截止时间漂移 | `ebba6f1` | live帧对重新锚定,源PTS仍保持真实;五分钟漂移模拟、DLSS 2/3/4 Create/Evaluate等通过。未完成反馈者显卡/采集卡同源实测。 |
| 音频连续性、格式与恢复 | `dc44c48` | 保留连续重采样历史、有限浮点余量,区分软件空拉与设备断流;包含validBits/packed24、预填及视频reset隔离修复。撤销cubic和块级AGC方向;真实沙沙声未验收。 |
+| WASAPI录音端点输入 | 本轮本地整合 | UI同时显示`[WASAPI]`与`[DirectShow]`;共享模式、稳定endpoint ID、QPC时间轴、静音包和有界重连接入现有PCM链。本机USB3端点和视频+WASAPI组合通过静音回归;用户设备与听感未验收。 |
详细记录:[媒体兼容](MEDIA_FILE_COMPATIBILITY_PLAN_2026-09-14.md)、[音频设备选择](CAPTURE_AUDIO_DEVICE_SELECTION_REPAIR_2026-09-14.md)、[FG时钟](CAPTURE_FG_CLOCK_REPAIR_2026-09-14.md)、[当前音频修复§6](CAPTURE_AUDIO_WAVEFORM_REPAIR_PLAN_2026-09-15.md)。旧音频施工结论仅作追溯,以新方案§6为准。
@@ -50,3 +51,5 @@
用户当前远程无法测试,不要求立即实卡验收。后续唯一诊断主线是取得问题场景同源PCM,在原始输入、转换后、最终输出前定位首次额外失真,再与系统输出/OBS进行条件匹配对照。完整生产链分段tap尚未实现,不能写成已有功能。不再凭音高猜过载,不盲加低通或块级自动增益。
后续发布需要另行授权、完整候选包回归和依赖对应源码审计;不能直接把当前本地EXE标为已发布1.2.0修复包。
+
+WASAPI专项记录见 [WASAPI接入方案与证据](WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md)。
diff --git a/docs/WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md b/docs/WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md
new file mode 100644
index 00000000..bf7ae0b8
--- /dev/null
+++ b/docs/WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md
@@ -0,0 +1,31 @@
+# WASAPI录音端点接入(2026-09-15)
+
+状态:**已实现本地候选,未发布;本机USB3采集卡端点已通过静音回归,反馈者设备与听感未验收。**
+
+用户授权“把这个加入”。在DirectShow视频采集旁新增WASAPI共享模式录音输入,保留原独立DirectShow与内置音频路径。仅本地开发,不发布、不改运行组件、不自动选择麦克风、不提供系统回录。
+
+## 实施合同
+
+- 枚举active eCapture端点,显示来源标签,用endpoint ID精确绑定;默认不监听,不使用GetDefaultAudioEndpoint。已保存DirectShow连接串继续兼容。
+- 独立产品输入类拥有MTA采集线程、事件和COM资源;PCM交给共享CaptureAudioSession,复用重采样、音量、声道及输出。采用设备mix format,不声称原始bit-perfect或绕过Windows APO。
+- GetBuffer设备时间/QPC为样本起点,不把回调到达时间冒充采样时刻;SILENT补足真实静音包,TIMESTAMP_ERROR按连续帧位置估计并明确计数,断点重置历史。GetBuffer/ReleaseBuffer同线程配对;队列、单包和重连有界。
+- WASAPI源PTS映射到本进程steady-clock轴,视频在采集回调处建立PTS→host映射供呈现通知转换。只估计软件链延迟,不宣称消除HDMI音视频固有延迟;原DirectShow共图同步不变。
+- 输入故障保留视频,显示HRESULT/错误;只重连同一ID,最多3次,停止可中断等待。输入重新打开时重新协商格式、创建音频epoch,不留悬空回调。切换设备仍通过关闭旧会话再打开。
+- 当前媒体/音频修复继续保留,不能用新增输入路径宣称火堆/口哨沙沙声根治。
+
+## 验证与交付门槛
+
+离线覆盖连接串、时间戳/帧连续性、静音及异常包;枚举不启动录音;仅明确指定USB采集卡端点才做短时静音输入测试,不保存PCM。构建RemotePlay ON且保留patched FFmpeg/dav1d;重跑既有音频专项。实卡拔插、用户设备和同源听感未执行时必须标明。文档和WORKLOG记录结果,提交本地main保持工作区干净。
+
+API依据:[GetBuffer](https://learn.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer)、[Device Formats](https://learn.microsoft.com/en-us/windows/win32/coreaudio/device-formats)。独立实现,不复制第三方源码。
+
+## 本轮实际实现与证据
+
+- 新增 `WasapiAudioInput`:枚举活动 `eCapture` 端点,绑定用户选择的 endpoint ID,使用共享模式事件采集;没有 loopback flag、默认端点选择或设备替换回退。
+- 采集卡连接串仍为 `capture2:`,WASAPI 音频模式使用 `-3` 和编码后的端点 ID;DirectShow 内置/独立音频以及旧 `capture:` 均保留。UI 标签明确 `[WASAPI]` / `[DirectShow]` 来源。
+- `IAudioCaptureClient::GetBuffer` 的QPC时间转换到进程steady-clock轴;设备位置跳变、数据断点和坏时间戳分别处理。静音包按帧数补零,空包、超界包和非静音空指针拒绝;`GetBuffer` 与 `ReleaseBuffer` 同线程配对。
+- 设备失效只重试所选 endpoint,最多三次;不会切换到默认麦克风。停止事件可中断重试等待,恢复后重新建立PCM epoch和共享 `CaptureAudioSession`。
+- 代码构建:`cmd.exe /c out\build\veyra-build-x64-release.cmd` exit 0,最终 `[30/30] Linking CXX executable veyra.exe`;首次构建的 `cguid.h` 头文件顺序错误已修正,失败日志保留在 `logs/wasapi-input-20260915/build-first.log`。
+- `veyra_wasapi_input_tests.exe --offline`:时间轴、连接串、静音包和异常包 **18项通过**;`--invalid`:无效ID不回退、三次重试、停止可中断 **exit 0**。
+- 本机 `USB3 Digital Audio` WASAPI endpoint(`{0.0.1.00000000}.{73a0923c-3eaf-4f12-945e-c8a0271e60b7}`)3秒静音输入收到超过20个PCM块,48kHz/32-bit float,停止并重开通过;DirectShow视频+WASAPI音频组合测试 exit 0;DirectShow原路径回归 exit 0。
+- 旧音频连续性专项仍保留;本轮未重跑完整GPU delivery、RTX Create/Evaluate或用户反馈者设备。所有本机端点测试均静音,不能把通过结果写成沙沙声已根治。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 4554f790..8b061445 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -2125,3 +2125,22 @@ GitHub Release https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.0.0 于
本地快进合并已完成,代码基线 `dc44c48`,合并后工作区干净。用户要求更新项目文档;本轮更新中英文README开发状态、`docs/BUILD.md`候选构建与专项命令,新增 `docs/LOCAL_INTEGRATION_STATUS_2026-09-15.md` 汇总分支、提交、已发布/未发布边界、候选身份与测试证据。未修改历史1.2.0发布说明、版本号、代码或运行组件。音频沙沙声仍未听感验收、生产链完整分段tap尚未实现,均明确保留,不将旧cubic/AGC施工记录误报为成功修复。
检查:PowerShell扫描上述4份文档的Markdown本地文件链接,全部目标存在(不校验外部URL或页内锚点);`git diff --check`通过,仅既存CRLF提示。新增文档引用的构建与DSP/端点/漂移结果均标明为前轮证据,本轮未重新构建或运行音频/GPU/实卡测试,未执行RTX Create/Evaluate。文档在本地main提交以保持用户要求的干净工作区,不push、不发布;下一步仍为真实问题场景同源PCM定位,用户远程期间不要求立即测试。
+
+## 2026-09-15 用户授权加入WASAPI采集输入
+
+用户要求把WASAPI加入采集卡音频选择。实现保持DirectShow视频路径和已有视频filter内置音频/独立DirectShow音频不变,在采集面板的同一音频列表新增 `[WASAPI]` 端点。枚举Windows活动 `eCapture` 端点,使用FriendlyName展示、endpoint ID稳定保存;默认仍为“不监听音频”,不调用默认端点、不做loopback、不自动切到麦克风。
+
+WASAPI输入使用共享模式事件采集,按 `IAudioCaptureClient::GetBuffer` 返回的设备位置和QPC时间将PCM转换到进程steady-clock轴;静音包按帧数补零,坏时间戳继续连续帧时间线并记估计,设备位置跳变/数据断点触发音频epoch reset。PCM进入既有 `CaptureAudioSession`,复用采样率、声道、重采样、音量、补偿和输出。设备失效只重试原endpoint三次,停止可中断等待;失败保留视频并写HRESULT,不回退默认设备。
+
+连接串:稳定 `capture2:` 的音频模式 `-3` 加编码endpoint ID;旧 `capture:`、内置音频和DirectShow独立音频保持兼容。新增 `WasapiAudioInput.h/.cpp`、WASAPI输入测试和 `CaptureSourceTests --wasapi`;UI标签及 `--list`输出注明来源。计划/边界见 `docs/WASAPI_CAPTURE_INPUT_PLAN_2026-09-15.md`。
+
+实际验证:
+
+- `cmd.exe /c out\build\veyra-build-x64-release.cmd`:最终exit0,`[30/30] Linking CXX executable veyra.exe`。首次因Windows `cguid.h`包含顺序失败(C2059 `__uuidof`),调整头文件顺序后重建通过;失败日志保留。
+- `veyra_wasapi_input_tests.exe --offline`:最终连接串、QPC时间轴、坏时间戳、静音/异常包等 **18项**通过。
+- `veyra_wasapi_input_tests.exe --invalid`:无效endpoint不回退、重试上限3次、停止打断退避,exit0。
+- 本机显式USB3 Digital Audio endpoint 3秒输入:共享48kHz/32-bit float,超过20个PCM块,停止/重开通过;日志/输出在 `logs/wasapi-input-20260915/`。注入设备失效后只重连同endpoint的测试通过。
+- `veyra_capture_tests.exe --wasapi <本机显式endpoint ID>`:视频+WASAPI音频组合通过;同一设备的原DirectShow路径也通过。测试增益为0且不保存PCM,不能替代用户听感。
+- 旧 `test-audio-continuity.ps1` 12组音频专项此前已通过;本轮补充脚本中的WASAPI离线时钟项,未重复声学/GPU验收。
+
+候选仍是本地 `out/build/audio-continuity-repair-20260915/veyra.exe`,未更新版本号、未修改运行组件、未push、未发布。WASAPI接入已具备本机候选证据,但反馈者设备的端点是否提供正确采集音频、以及火堆/口哨沙沙声是否改善,均未验收。
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index a61d9ff7..06e51d1a 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -14,9 +14,11 @@ struct CaptureDevice {
// Only populated for video devices: the selected video filter exposes an
// audio output pin that can be used without a second audio filter.
bool hasEmbeddedAudio=false;
+ bool wasapi=false; // Audio only: path is a Windows recording endpoint ID.
};
constexpr int kCaptureAudioDisabled=-1;
constexpr int kCaptureAudioFromVideoDevice=-2;
+constexpr int kCaptureAudioWasapi=-3; // capture2 only; requires explicit endpoint ID
struct CaptureMetrics {
uint64_t received=0, delivered=0, dropped=0;
double callbackFps=0, readAgeMs=0, frameAgeMs=0;
diff --git a/include/veyra/source/WasapiAudioInput.h b/include/veyra/source/WasapiAudioInput.h
new file mode 100644
index 00000000..3ad43863
--- /dev/null
+++ b/include/veyra/source/WasapiAudioInput.h
@@ -0,0 +1,46 @@
+#pragma once
+#include "veyra/sink/CaptureAudioSession.h"
+#include <memory>
+#include <span>
+#include <vector>
+
+namespace veyra::source {
+struct WasapiInputDevice {std::wstring name,id;};
+struct WasapiInputMetrics {uint64_t packets=0,retries=0,timestampErrors=0,discontinuities=0;};
+// SILENT packets may have a null driver pointer; the preallocated zero buffer
+// preserves their actual frame count. Reject malformed/oversized packets.
+inline const void* wasapiPacketData(const void* data,size_t bytes,bool silent,std::span<const uint8_t> zeros){
+ if(!bytes||bytes>zeros.size())return nullptr;
+ return silent?zeros.data():data;
+}
+// Packet time in the process steady-clock domain; never compare raw device
+// positions with DirectShow stream-relative PTS.
+class WasapiPacketClock {
+public:
+ struct Stamp {double ptsMs;bool discontinuity,estimated;};
+ void reset(unsigned rate,double qpcToHostMs){rate_=rate;offset_=qpcToHostMs;have_=false;}
+ Stamp stamp(uint64_t position,uint64_t qpc100ns,unsigned frames,bool discontinuity,bool timestampError,double nowMs){
+ const bool gap=have_&&!timestampError&&position!=nextPosition_;
+ const double pts=timestampError?(have_?nextPts_:nowMs-1000.0*frames/rate_):double(qpc100ns)/10000.0+offset_;
+ const bool reset=!have_||discontinuity||gap||(have_&&pts<lastPts_);
+ lastPts_=pts;nextPts_=pts+1000.0*frames/rate_;nextPosition_=(timestampError&&have_?nextPosition_:position)+frames;have_=true;
+ return {pts,reset,timestampError};
+ }
+private:
+ unsigned rate_=48000;double offset_=0,nextPts_=0,lastPts_=0;uint64_t nextPosition_=0;bool have_=false;
+};
+class WasapiAudioInput {
+public:
+ WasapiAudioInput();~WasapiAudioInput();
+ static std::vector<WasapiInputDevice> devices(); // enumerate only, never capture
+ bool configure(std::wstring endpointId);
+ bool start();void stop();
+ void setGain(float);void setSync(unsigned,int);
+ void videoPresented(double hostAxisPtsMs,int64_t host100ns);
+ void videoReset(bool resetAudio);
+ sink::CaptureAudioState snapshot()const;
+ WasapiInputMetrics metrics()const;
+private:
+ struct Impl;std::unique_ptr<Impl> p_;
+};
+}
diff --git a/scripts/diagnostics/test-audio-continuity.ps1 b/scripts/diagnostics/test-audio-continuity.ps1
index 8201c15c..2374100e 100644
--- a/scripts/diagnostics/test-audio-continuity.ps1
+++ b/scripts/diagnostics/test-audio-continuity.ps1
@@ -10,6 +10,7 @@ $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='wasapi-clock';Exe='veyra_wasapi_input_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},
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 38965215..3b5a3bff 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -1,4 +1,6 @@
#include "veyra/source/CaptureCardSource.h"
+#include "veyra/source/WasapiAudioInput.h"
+#include "veyra/sink/ArrivalClockMapping.h"
#include "veyra/source/CaptureTiming.h"
#include "veyra/source/CaptureMediaType.h"
#include "veyra/source/NativeCaptureSink.h"
@@ -101,8 +103,8 @@ bool parseCapturePath(std::wstring_view path,CaptureSelection& selection){
std::array<std::wstring_view,5> fields{};size_t cursor=prefix.size();
for(size_t i=0;i<fields.size();++i){const size_t end=path.find(L':',cursor);if(i+1<fields.size()){if(end==std::wstring_view::npos)return false;fields[i]=path.substr(cursor,end-cursor);cursor=end+1;}else{if(end!=std::wstring_view::npos)return false;fields[i]=path.substr(cursor);}}
if(fields[0].empty()||!decodePath(fields[0],selection.videoPath)||!parseInt(fields[1],selection.format)||!parseInt(fields[2],selection.audio)||!decodePath(fields[3],selection.audioPath)||!parseUnsigned(fields[4],selection.colorOverride)||selection.format<0||selection.colorOverride>2)return false;
- if(selection.audio!=kCaptureAudioDisabled&&selection.audio!=kCaptureAudioFromVideoDevice&&selection.audio<0)return false;
- if(selection.audio>=0&&selection.audioPath.empty())return false;selection.stable=true;return true;
+ if(selection.audio!=kCaptureAudioDisabled&&selection.audio!=kCaptureAudioFromVideoDevice&&selection.audio!=kCaptureAudioWasapi&&selection.audio<0)return false;
+ if((selection.audio>=0||selection.audio==kCaptureAudioWasapi)&&selection.audioPath.empty())return false;selection.stable=true;return true;
}
unsigned videoIndex=0,colorOverride=0;int format=0,audio=kCaptureAudioDisabled;const std::wstring legacy(path);
const int fields=swscanf_s(legacy.c_str(),L"capture:%u:%d:%d:%u",&videoIndex,&format,&audio,&colorOverride);
@@ -124,6 +126,8 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
float lastAudioGain=-1;bool audioGainSupported=false;
ComPtr<IBaseFilter> audioSink;ComPtr<IReferenceClock> referenceClock;
std::unique_ptr<sink::CaptureAudioSession> audioSession;
+ std::unique_ptr<WasapiAudioInput> wasapi;
+ sink::ArrivalClockMapping videoIngressClock;double videoIngressMs=0;bool haveVideoIngress=false;
std::wstring audioError;
SourceInfo info;CaptureMediaLayout layout;Clock::time_point lastFrame;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** pp)override{if(!pp)return E_POINTER;*pp=nullptr;if(id==IID_IUnknown||id==__uuidof(ISampleGrabberCB)){*pp=static_cast<ISampleGrabberCB*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
@@ -147,6 +151,11 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
pendingDiscontinuity=captureDiscontinuity(pending,pendingDiscontinuity,
sample->IsDiscontinuity()==S_OK,received>0,pendingTime,time,info.averageFps);
pending=true;pendingTime=time;pendingArrival=arrival;
+ if(wasapi){
+ if(sample->IsDiscontinuity()==S_OK)videoIngressClock.reset();
+ videoIngressMs=videoIngressClock.observe(std::chrono::duration<double,std::milli>(arrival.time_since_epoch()).count(),time*1000);
+ haveVideoIngress=true;
+ }
pendingDuration=captureDuration(sampleStart,sampleEnd,sampleTime,nominalDuration100ns);
if(!received)firstArrival=arrival;
++received;latestArrival=arrival;
@@ -169,10 +178,15 @@ std::vector<CaptureDevice> CaptureCardSource::deviceDetails(bool audio){
}
result.push_back(std::move(device));
}
+ if(audio)for(auto& endpoint:WasapiAudioInput::devices())result.push_back({std::move(endpoint.name),std::move(endpoint.id),false,true});
return result;
}
std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<std::wstring> result;for(auto& device:deviceDetails(audio))result.push_back(std::move(device.name));return result;}
std::wstring CaptureCardSource::makeCapturePath(unsigned videoIndex,const CaptureDevice& video,int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride){
+ if(audio&&audio->wasapi){
+ if(video.path.empty()||audio->path.empty())return {};
+ return std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(video.path),format,kCaptureAudioWasapi,encodePath(audio->path),colorOverride);
+ }
if(video.path.empty()||(audioMode>=0&&(!audio||audio->path.empty())))return std::format(L"capture:{}:{}:{}:{}",videoIndex,format,audioMode,colorOverride);
return std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(video.path),format,audioMode,audioMode>=0?encodePath(audio->path):L"",colorOverride);
}
@@ -198,16 +212,20 @@ std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IG
std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view devicePath){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(devicePath,g,b,f,c))return {};return enumerateFormats(c.Get());}
const SourceInfo& CaptureCardSource::info()const{return p_->info;}
bool CaptureCardSource::setAudioGain(float gain){
+ if(p_->wasapi){p_->wasapi->setGain(gain);return p_->wasapi->snapshot().available;}
auto& p=*p_;if(p.audioSession){p.audioSession->setGain(gain);return p.audioSession->snapshot().available;}if(!p.graph||!p.audioFilter)return false;
if(gain==p.lastAudioGain)return p.audioGainSupported;
ComPtr<IBasicAudio> audio;HRESULT hr=p.graph.As(&audio);
if(SUCCEEDED(hr)){long attenuation=gain<=0?-10000:long(std::clamp(2000.0*std::log10(double(gain)),-10000.0,0.0));hr=audio->put_Volume(attenuation);}
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(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;}
+void CaptureCardSource::videoPresented(double pts,int64_t time){
+ if(p_->wasapi){double mapping=0;{std::lock_guard lock(p_->mutex);if(!p_->haveVideoIngress)return;mapping=p_->videoIngressMs;}p_->wasapi->videoPresented(pts+mapping,time);}
+ else if(p_->audioSession)p_->audioSession->videoPresented(pts,time);
+}
+void CaptureCardSource::videoReset(bool resetAudio){if(p_->wasapi)p_->wasapi->videoReset(resetAudio);else if(p_->audioSession)p_->audioSession->videoReset(resetAudio);}
+void CaptureCardSource::setAudioSync(unsigned mode,int offset){if(p_->wasapi)p_->wasapi->setSync(mode,offset);else if(p_->audioSession)p_->audioSession->setSync(mode,offset);}
+sink::CaptureAudioState CaptureCardSource::audioState()const{auto state=p_->wasapi?p_->wasapi->snapshot():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();}
bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAudioGain=-1;auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const unsigned index=selection.videoIndex;const int format=selection.format;const int audio=selection.audio;
if(selection.stable?!configuration(selection.videoPath,p.graph,p.builder,p.device,p.config):!configuration(index,p.graph,p.builder,p.device,p.config))return false;
@@ -257,7 +275,11 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=p.layout.width;p.info.height=p.layout.height;p.info.averageFps=p.layout.duration>0?1e7/p.layout.duration:0;p.info.duration=pipeline::Rational::unknown();p.info.color=p.layout.color;
p.nominalDuration100ns=p.layout.duration;
log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (explicit transfer contract)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));
- if(audio!=kCaptureAudioDisabled){
+ if(audio==kCaptureAudioWasapi){
+ p.wasapi=std::make_unique<WasapiAudioInput>();
+ if(!p.wasapi->configure(selection.audioPath)){p.wasapi.reset();p.audioError=L"WASAPI 音频端点ID无效;视频继续运行";}
+ log::info("capture-audio","binding=wasapi shared=1 explicitEndpoint=1 videoClock=ingress-host-estimate");
+ }else if(audio!=kCaptureAudioDisabled){
const bool audioReady=[&]{
ComPtr<IBaseFilter> audioFilter;const bool embedded=audio==kCaptureAudioFromVideoDevice;
if(embedded){
@@ -352,6 +374,7 @@ bool CaptureCardSource::start(){
auto& p=*p_;if(p.info.opened)return true;if(!p.configured||!p.control)return false;
if(p.audioSession&&!p.audioSession->start())log::warn("capture-audio","audio start failed; retaining video capture");
p.lastFrame=Impl::Clock::now();const auto hr=p.control->Run();p.info.opened=SUCCEEDED(hr);
+ if(p.info.opened&&p.wasapi&&!p.wasapi->start())p.audioError=L"WASAPI 音频启动失败;视频继续运行";
veyra::log::info("capture",std::format("Run hr=0x{:X} actual={}x{} nominalFps={:.3f} mailbox=1 ownedBuffers=2",unsigned(hr),p.info.width,p.info.height,p.info.averageFps));return p.info.opened;
}
CaptureMetrics CaptureCardSource::metrics()const{
@@ -383,6 +406,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,c
}
void CaptureCardSource::close()noexcept{
auto& p=*p_;if(p.control)p.control->Stop();if(p.grab)p.grab->SetCallback(nullptr,0);
+ if(p.wasapi)p.wasapi->stop();p.wasapi.reset();p.videoIngressClock.reset();p.haveVideoIngress=false;p.videoIngressMs=0;
if(p.audioSession)p.audioSession->stop();p.audioError.clear();
p.events.Reset();p.control.Reset();p.grab.Reset();p.nullFilter.Reset();p.grabFilter.Reset();p.audioSink.Reset();p.audioFilter.Reset();p.config.Reset();p.device.Reset();p.builder.Reset();p.graph.Reset();p.referenceClock.Reset();p.audioSession.reset();
av_frame_free(&p.frame);av_frame_free(&p.pendingFrame);p.info={};
diff --git a/src/source/WasapiAudioInput.cpp b/src/source/WasapiAudioInput.cpp
new file mode 100644
index 00000000..ac4f3ec2
--- /dev/null
+++ b/src/source/WasapiAudioInput.cpp
@@ -0,0 +1,156 @@
+#include "veyra/source/WasapiAudioInput.h"
+#include "veyra/Log.h"
+#include <audioclient.h>
+#include <mmdeviceapi.h>
+#include <functiondiscoverykeys_devpkey.h>
+#include <wrl/client.h>
+#include "veyra/sink/AudioFormat.h"
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <format>
+#include <mutex>
+#include <thread>
+
+namespace veyra::source {
+using Microsoft::WRL::ComPtr;
+namespace {
+double hostMs(){return std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();}
+struct ComScope {HRESULT hr=CoInitializeEx(nullptr,COINIT_MULTITHREADED);~ComScope(){if(SUCCEEDED(hr))CoUninitialize();}};
+struct Handle {HANDLE value=nullptr;~Handle(){if(value)CloseHandle(value);} };
+bool checked(HRESULT hr,const char* operation){
+ if(FAILED(hr))log::error("wasapi-input",std::format("{} hr=0x{:08X}",operation,uint32_t(hr)));
+ return SUCCEEDED(hr);
+}
+}
+std::vector<WasapiInputDevice> WasapiAudioInput::devices(){
+ ComScope apartment;std::vector<WasapiInputDevice> result;
+ if(FAILED(apartment.hr)&&apartment.hr!=RPC_E_CHANGED_MODE){checked(apartment.hr,"enumeration COM");return result;}
+ ComPtr<IMMDeviceEnumerator> enumerator;ComPtr<IMMDeviceCollection> collection;
+ if(!checked(CoCreateInstance(__uuidof(MMDeviceEnumerator),nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&enumerator)),"enumerator")||
+ !checked(enumerator->EnumAudioEndpoints(eCapture,DEVICE_STATE_ACTIVE,&collection),"EnumAudioEndpoints capture"))return result;
+ UINT count=0;if(!checked(collection->GetCount(&count),"GetCount"))return result;
+ for(UINT i=0;i<count;++i){
+ ComPtr<IMMDevice> device;ComPtr<IPropertyStore> properties;LPWSTR raw=nullptr;
+ if(!checked(collection->Item(i,&device),"Item")||!checked(device->GetId(&raw),"GetId"))continue;
+ WasapiInputDevice input{L"WASAPI recording endpoint",raw};CoTaskMemFree(raw);
+ PROPVARIANT name;PropVariantInit(&name);
+ if(SUCCEEDED(device->OpenPropertyStore(STGM_READ,&properties))&&SUCCEEDED(properties->GetValue(PKEY_Device_FriendlyName,&name))&&name.vt==VT_LPWSTR&&name.pwszVal)input.name=name.pwszVal;
+ PropVariantClear(&name);result.push_back(std::move(input));
+ }
+ return result;
+}
+struct WasapiAudioInput::Impl {
+ mutable std::mutex mutex;std::unique_ptr<sink::CaptureAudioSession> session;
+ std::wstring id,error;std::thread worker;Handle stopEvent;std::atomic<bool> stopping{true};
+ float gain=1;unsigned mode=0;int offset=0;double videoPts=0;int64_t videoHost=0;bool haveVideo=false;
+ WasapiInputMetrics metrics;bool injectedLoss=false;
+ HRESULT stream(){
+ ComPtr<IMMDeviceEnumerator> enumerator;ComPtr<IMMDevice> device;ComPtr<IMMEndpoint> endpoint;
+ ComPtr<IAudioClient> client;ComPtr<IAudioCaptureClient> capture;Handle ready;
+ HRESULT hr=CoCreateInstance(__uuidof(MMDeviceEnumerator),nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&enumerator));
+ if(!checked(hr,"create enumerator"))return hr;
+ hr=enumerator->GetDevice(id.c_str(),&device);if(!checked(hr,"selected endpoint GetDevice"))return hr;
+ hr=device.As(&endpoint);if(!checked(hr,"IMMEndpoint"))return hr;
+ EDataFlow flow=eAll;hr=endpoint->GetDataFlow(&flow);if(!checked(hr,"GetDataFlow"))return hr;
+ if(flow!=eCapture){checked(E_INVALIDARG,"render/loopback endpoint rejected");return E_INVALIDARG;}
+ hr=device->Activate(__uuidof(IAudioClient),CLSCTX_INPROC_SERVER,nullptr,reinterpret_cast<void**>(client.GetAddressOf()));
+ if(!checked(hr,"Activate capture client"))return hr;
+ WAVEFORMATEX* raw=nullptr;hr=client->GetMixFormat(&raw);
+ if(!checked(hr,"GetMixFormat"))return hr;
+ auto freeWave=[](WAVEFORMATEX* value){CoTaskMemFree(value);};std::unique_ptr<WAVEFORMATEX,decltype(freeWave)> wave(raw,freeWave);
+ sink::WavePcmFormat format;
+ if(!raw||!sink::parseWavePcm(raw,sizeof(WAVEFORMATEX)+raw->cbSize,format)){checked(AUDCLNT_E_UNSUPPORTED_FORMAT,"mix PCM format");return AUDCLNT_E_UNSUPPORTED_FORMAT;}
+ hr=client->Initialize(AUDCLNT_SHAREMODE_SHARED,AUDCLNT_STREAMFLAGS_EVENTCALLBACK,200000,0,raw,nullptr);
+ if(!checked(hr,"Initialize shared capture"))return hr;
+ ready.value=CreateEventW(nullptr,FALSE,FALSE,nullptr);
+ if(!ready.value)return HRESULT_FROM_WIN32(GetLastError());
+ hr=client->SetEventHandle(ready.value);if(!checked(hr,"SetEventHandle"))return hr;
+ hr=client->GetService(IID_PPV_ARGS(&capture));if(!checked(hr,"GetService capture"))return hr;
+ UINT capacity=0;hr=client->GetBufferSize(&capacity);if(!checked(hr,"GetBufferSize"))return hr;
+ // A single input packet is bounded to the shared session's 500ms limit.
+ const size_t maxFrames=std::min<size_t>(capacity,raw->nSamplesPerSec/2);
+ if(!maxFrames)return E_INVALIDARG;
+ std::vector<BYTE> silent(maxFrames*raw->nBlockAlign,0);
+ LARGE_INTEGER frequency{},qpc{};
+ if(!QueryPerformanceFrequency(&frequency)||!QueryPerformanceCounter(&qpc)||frequency.QuadPart<=0)return E_FAIL;
+ WasapiPacketClock clock;clock.reset(raw->nSamplesPerSec,hostMs()-1000.0*double(qpc.QuadPart)/double(frequency.QuadPart));
+ {
+ std::lock_guard lock(mutex);session=std::make_unique<sink::CaptureAudioSession>();
+ if(!session->configure(format)){session.reset();return AUDCLNT_E_UNSUPPORTED_FORMAT;}
+ session->setGain(gain);session->setSync(mode,offset);
+ if(!session->start()){session.reset();return E_FAIL;}
+ if(haveVideo)session->videoPresented(videoPts,videoHost);
+ }
+ hr=client->Start();if(!checked(hr,"Start capture"))return hr;
+ struct StopClient {IAudioClient* client;~StopClient(){checked(client->Stop(),"Stop capture");}} stopClient{client.Get()};
+ {std::lock_guard lock(mutex);error.clear();}
+ log::info("wasapi-input",std::format("capture started shared=1 loopback=0 rate={} channels={} bits={} validBits={} capacity={} timestamp=QPC-host-axis",raw->nSamplesPerSec,raw->nChannels,raw->wBitsPerSample,format.validBits,capacity));
+ HANDLE events[]={stopEvent.value,ready.value};uint64_t packets=0,estimated=0,gaps=0;double lastPacket=hostMs();
+ const bool injectLoss=GetEnvironmentVariableW(L"VEYRA_TEST_WASAPI_INPUT_LOSS",nullptr,0)>0;
+ while(!stopping){
+ const DWORD wait=WaitForMultipleObjects(2,events,FALSE,1000);
+ if(wait==WAIT_OBJECT_0)break;
+ if(wait==WAIT_FAILED)return HRESULT_FROM_WIN32(GetLastError());
+ // Also inspect on timeout: some drivers lose notifications.
+ UINT next=0;hr=capture->GetNextPacketSize(&next);if(!checked(hr,"GetNextPacketSize"))return hr;
+ if(!next&&hostMs()-lastPacket>3000){checked(HRESULT_FROM_WIN32(ERROR_TIMEOUT),"no input packets for 3s");return HRESULT_FROM_WIN32(ERROR_TIMEOUT);}
+ while(next&&!stopping){
+ BYTE* data=nullptr;UINT frames=0;DWORD flags=0;UINT64 position=0,timestamp=0;
+ hr=capture->GetBuffer(&data,&frames,&flags,&position,&timestamp);if(!checked(hr,"GetBuffer"))return hr;
+ if(hr==AUDCLNT_S_BUFFER_EMPTY)break;
+ struct PacketLease {IAudioCaptureClient* capture;UINT frames;bool held=true;~PacketLease(){if(held)checked(capture->ReleaseBuffer(frames),"ReleaseBuffer unwind");}} lease{capture.Get(),frames};
+ const auto bytes=size_t(frames)*raw->nBlockAlign;
+ const void* packet=wasapiPacketData(data,bytes,(flags&AUDCLNT_BUFFERFLAGS_SILENT)!=0,silent);
+ if(!packet){checked(E_INVALIDARG,"invalid packet size/data");return E_INVALIDARG;}
+ const auto stamp=clock.stamp(position,timestamp,frames,(flags&AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)!=0,(flags&AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR)!=0,hostMs());
+ bool accepted=false;
+ {
+ std::lock_guard lock(mutex);
+ accepted=session->push(packet,bytes,stamp.ptsMs,stamp.discontinuity);
+ }
+ hr=capture->ReleaseBuffer(frames);lease.held=false;if(!checked(hr,"ReleaseBuffer"))return hr;
+ if(!accepted){checked(E_FAIL,"shared PCM queue rejected packet");return E_FAIL;}
+ ++packets;lastPacket=hostMs();estimated+=stamp.estimated;gaps+=stamp.discontinuity;
+ {std::lock_guard lock(mutex);++metrics.packets;metrics.timestampErrors+=stamp.estimated;metrics.discontinuities+=stamp.discontinuity;}
+ if(packets==1||packets%500==0)log::info("wasapi-input",std::format("packets={} timestampEstimated={} discontinuities={} position={} frames={}",packets,estimated,gaps,position,frames));
+ if(injectLoss&&!injectedLoss&&packets>=25){injectedLoss=true;log::warn("wasapi-input","test-only injected input invalidation after actual PCM");return AUDCLNT_E_DEVICE_INVALIDATED;}
+ hr=capture->GetNextPacketSize(&next);if(!checked(hr,"GetNextPacketSize"))return hr;
+ }
+ }
+ return S_OK;
+ }
+ void run(){
+ ComScope apartment;
+ if(!checked(apartment.hr,"capture thread COM")){std::lock_guard lock(mutex);error=L"WASAPI 输入线程初始化失败";return;}
+ for(unsigned attempt=0;attempt<4&&!stopping;++attempt){
+ if(attempt){std::lock_guard lock(mutex);++metrics.retries;}
+ const HRESULT hr=stream();
+ {std::lock_guard lock(mutex);if(session)session->stop();session.reset();
+ if(FAILED(hr))error=std::format(L"WASAPI 输入失败 0x{:08X};{}",uint32_t(hr),attempt<3?L"仅重试所选设备,视频继续":L"重试已用尽,请重新连接");}
+ if(SUCCEEDED(hr)||stopping)break;
+ log::warn("wasapi-input",std::format("input attempt={} failed hr=0x{:08X} retriesRemaining={} defaultFallback=0",attempt+1,uint32_t(hr),3-attempt));
+ if(attempt<3&&WaitForSingleObject(stopEvent.value,1000)==WAIT_OBJECT_0)break;
+ }
+ }
+};
+WasapiAudioInput::WasapiAudioInput():p_(std::make_unique<Impl>()){}
+WasapiAudioInput::~WasapiAudioInput(){stop();}
+bool WasapiAudioInput::configure(std::wstring id){if(p_->worker.joinable()||id.empty())return false;p_->id=std::move(id);return true;}
+bool WasapiAudioInput::start(){
+ if(p_->worker.joinable()||p_->id.empty())return false;
+ if(p_->stopEvent.value)CloseHandle(p_->stopEvent.value);
+ p_->stopEvent.value=CreateEventW(nullptr,TRUE,FALSE,nullptr);if(!p_->stopEvent.value)return false;
+ p_->stopping=false;
+ {std::lock_guard lock(p_->mutex);p_->error.clear();p_->metrics={};p_->injectedLoss=false;}
+ try{p_->worker=std::thread([this]{try{p_->run();}catch(const std::exception& e){log::error("wasapi-input",e.what());std::lock_guard lock(p_->mutex);if(p_->session)p_->session->stop();p_->session.reset();p_->error=L"WASAPI 输入线程异常,请重新连接";}});}
+ catch(...){p_->stopping=true;return false;}return true;
+}
+void WasapiAudioInput::stop(){p_->stopping=true;if(p_->stopEvent.value)SetEvent(p_->stopEvent.value);if(p_->worker.joinable())p_->worker.join();}
+void WasapiAudioInput::setGain(float value){std::lock_guard lock(p_->mutex);p_->gain=std::clamp(value,0.f,1.f);if(p_->session)p_->session->setGain(p_->gain);}
+void WasapiAudioInput::setSync(unsigned mode,int offset){std::lock_guard lock(p_->mutex);p_->mode=std::min(mode,2u);p_->offset=std::clamp(offset,-250,250);if(p_->session)p_->session->setSync(p_->mode,p_->offset);}
+void WasapiAudioInput::videoPresented(double pts,int64_t host){std::lock_guard lock(p_->mutex);p_->haveVideo=true;p_->videoPts=pts;p_->videoHost=host;if(p_->session)p_->session->videoPresented(pts,host);}
+void WasapiAudioInput::videoReset(bool resetAudio){std::lock_guard lock(p_->mutex);p_->haveVideo=false;if(p_->session)p_->session->videoReset(resetAudio);}
+sink::CaptureAudioState WasapiAudioInput::snapshot()const{std::lock_guard lock(p_->mutex);auto state=p_->session?p_->session->snapshot():sink::CaptureAudioState{};if(!p_->error.empty())state.error=p_->error;return state;}
+WasapiInputMetrics WasapiAudioInput::metrics()const{std::lock_guard lock(p_->mutex);return p_->metrics;}
+}
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
index faa07f19..30da088a 100644
--- a/tests/integration/CaptureSourceTests.cpp
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -6,6 +6,7 @@
#include <thread>
#include <cstdio>
#include <vector>
+#include <algorithm>
#include <cstring>
extern "C" {
#include <libavutil/frame.h>
@@ -15,12 +16,20 @@ int wmain(int argc,wchar_t** argv){
if(argc==2&&wcscmp(argv[1],L"--list")==0){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto videos=veyra::source::CaptureCardSource::deviceDetails();auto audios=veyra::source::CaptureCardSource::deviceDetails(true);
for(unsigned d=0;d<videos.size();++d){wprintf(L"VIDEO %u %ls embeddedAudio=%d path=%ls\n",d,videos[d].name.c_str(),videos[d].hasEmbeddedAudio?1:0,videos[d].path.c_str());const auto formats=videos[d].path.empty()?veyra::source::CaptureCardSource::formats(d):veyra::source::CaptureCardSource::formatsByPath(videos[d].path);for(const auto& f:formats)wprintf(L"FORMAT %u:%d %ls\n",d,f.index,f.label.c_str());}
- for(unsigned a=0;a<audios.size();++a)wprintf(L"AUDIO %u %ls path=%ls\n",a,audios[a].name.c_str(),audios[a].path.c_str());
+ for(unsigned a=0;a<audios.size();++a)wprintf(L"AUDIO %u [%ls] %ls path=%ls\n",a,audios[a].wasapi?L"WASAPI":L"DirectShow",audios[a].name.c_str(),audios[a].path.c_str());
CoUninitialize();return videos.empty()?1:0;
}
- if(argc!=2){printf("Specify capture:device:format:audio; real hardware required\n");return 2;}
+ const bool wasapiTest=argc==3&&wcscmp(argv[1],L"--wasapi")==0;
+ if(argc!=2&&!wasapiTest){printf("Specify capture:device:format:audio or --wasapi <explicit endpoint ID>; real hardware required\n");return 2;}
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
veyra::source::CaptureCardSource source;veyra::source::SourceOpenDesc d;d.path=argv[1];
+ if(wasapiTest){
+ const auto videos=veyra::source::CaptureCardSource::deviceDetails();
+ const auto video=std::find_if(videos.begin(),videos.end(),[](const auto& v){return v.name==L"USB3 Video";});
+ if(video==videos.end()){printf("FAIL explicit USB3 Video fixture unavailable\n");return 3;}
+ const veyra::source::CaptureDevice audio{L"Explicit WASAPI test",argv[2],false,true};
+ d.path=veyra::source::CaptureCardSource::makeCapturePath(unsigned(video-videos.begin()),*video,0,0,&audio);
+ }
int failures=0;auto check=[&](bool ok,const char* label){printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failures;};
if(!source.configure(d)){printf("FAIL configure\n");return 3;}
std::this_thread::sleep_for(std::chrono::milliseconds(150));
@@ -32,10 +41,10 @@ int wmain(int argc,wchar_t** argv){
// 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);
+ source.setAudioSync(wasapiTest?0: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;};
+ auto readFrame=[&](){while(std::chrono::steady_clock::now()<deadline){auto r=source.read(packet,&frame);if(r==veyra::source::SourceReadStatus::Frame){if(wasapiTest)source.videoPresented(packet.pts.toDouble()*1000,std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()/100);return true;}if(r==veyra::source::SourceReadStatus::Error)return false;}return false;};
if(!readFrame()){printf("FAIL first frame\n");return 5;}
const auto initialPts=packet.pts.toDouble();const auto initialReceived=source.metrics().received;
const int rowBytes=av_image_get_linesize(AVPixelFormat(frame->format),frame->width,0);
@@ -48,11 +57,16 @@ 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 bool recoveryDrop=veyra::pipeline::hasFrameFlag(packet.flags,veyra::pipeline::FrameFlagBits::Drop);
+ if(wasapiTest){
+ const auto until=std::chrono::steady_clock::now()+std::chrono::seconds(2);
+ while(std::chrono::steady_clock::now()<until){deadline=until;if(!readFrame())break;}
+ }
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(recoveryDrop,"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",
diff --git a/tests/integration/WasapiInputTests.cpp b/tests/integration/WasapiInputTests.cpp
new file mode 100644
index 00000000..1b278204
--- /dev/null
+++ b/tests/integration/WasapiInputTests.cpp
@@ -0,0 +1,52 @@
+#include "veyra/source/WasapiAudioInput.h"
+#include "veyra/source/CaptureCardSource.h"
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <thread>
+using namespace veyra::source;
+int wmain(int argc,wchar_t** argv){
+ int failures=0,checks=0;auto check=[&](bool ok,const char* label){++checks;printf("%s %s\n",ok?"PASS":"FAIL",label);if(!ok)++failures;};
+ if(argc==2&&wcscmp(argv[1],L"--list")==0){for(const auto& d:WasapiAudioInput::devices())wprintf(L"WASAPI %ls ID=%ls\n",d.name.c_str(),d.id.c_str());return 0;}
+ if(argc==3&&wcscmp(argv[1],L"--endpoint")==0){
+ WasapiAudioInput input;check(input.configure(argv[2]),"explicit endpoint configured");input.setGain(0);input.setSync(2,0);
+ check(input.start(),"capture thread started");std::this_thread::sleep_for(std::chrono::seconds(3));
+ const auto state=input.snapshot();check(state.running&&state.inputBlocks>20&&state.error.empty(),"real selected input packets reach shared audio session");
+ const bool injected=GetEnvironmentVariableW(L"VEYRA_TEST_WASAPI_INPUT_LOSS",nullptr,0)>0;
+ check(input.metrics().retries==(injected?1u:0u),"only injected loss reconnects exactly the selected endpoint");
+ printf("packets=%llu rate=%u channels=%u peak=%f errors=%zu\n",state.inputBlocks,state.inputSampleRate,state.inputChannels,state.inputPeak,state.error.size());
+ input.stop();check(!input.snapshot().running,"stop joins input and output");
+ if(injected)SetEnvironmentVariableW(L"VEYRA_TEST_WASAPI_INPUT_LOSS",nullptr);
+ check(input.start(),"explicit same endpoint restart");std::this_thread::sleep_for(std::chrono::seconds(1));check(input.snapshot().inputBlocks>10,"restart delivers packets");input.stop();
+ }else if(argc==2&&wcscmp(argv[1],L"--invalid")==0){
+ WasapiAudioInput input;input.configure(L"veyra-invalid-endpoint-no-fallback");input.setGain(0);check(input.start(),"invalid endpoint begins bounded attempts");
+ std::this_thread::sleep_for(std::chrono::seconds(5));auto state=input.snapshot();check(!state.error.empty()&&!state.running&&state.inputBlocks==0,"invalid ID never falls back to microphone");input.stop();
+ check(input.metrics().retries==3,"failed input retries are bounded to three");
+ check(input.start(),"invalid endpoint can explicitly restart");std::this_thread::sleep_for(std::chrono::milliseconds(200));
+ const auto before=std::chrono::steady_clock::now();input.stop();check(std::chrono::steady_clock::now()-before<std::chrono::milliseconds(500),"stop interrupts reconnect backoff");
+ }else if(argc==2&&wcscmp(argv[1],L"--offline")==0){
+ WasapiPacketClock clock;clock.reset(48000,50);
+ auto a=clock.stamp(0,10000000,480,false,false,2000);check(a.ptsMs==1050&&a.discontinuity&&!a.estimated,"QPC 100ns maps to host axis; first epoch resets");
+ auto b=clock.stamp(480,10100000,480,false,false,3000);check(b.ptsMs==1060&&!b.discontinuity,"arrival delay does not change sample PTS");
+ auto c=clock.stamp(960,0,480,false,true,4000);check(c.ptsMs==1070&&c.estimated&&!c.discontinuity,"bad timestamp continues frame timeline");
+ auto d=clock.stamp(1920,10400000,480,false,false,5000);check(d.discontinuity,"missing device frames reset epoch");
+ check(clock.stamp(2400,10500000,480,true,false,5000).discontinuity,"explicit device discontinuity retained");
+ check(clock.stamp(2880,10000000,480,false,false,5000).discontinuity,"backwards timestamp resets");
+ clock.reset(48000,0);clock.stamp(0,10000000,480,false,false,1000);
+ auto bad=clock.stamp(999999,0,480,false,true,3000);check(!bad.discontinuity&&bad.ptsMs==1010,"unreliable device position does not fabricate a gap");
+ check(!clock.stamp(960,10200000,480,false,false,3000).discontinuity,"valid timestamp resumes after estimated packet");
+ clock.reset(44100,0);auto e=clock.stamp(0,0,441,false,true,1000);check(e.ptsMs==990&&e.estimated&&e.discontinuity,"first invalid timestamp estimated from packet duration");
+ CaptureDevice video{L"Video",L"video:path"},audio{L"Audio",L"endpoint:id",false,true};
+ auto path=CaptureCardSource::makeCapturePath(0,video,0,0,&audio);check(path.starts_with(L"capture2:")&&path.find(L":-3:")!=std::wstring::npos,"WASAPI provider encoded with explicit stable ID");
+ audio.path.clear();check(CaptureCardSource::makeCapturePath(0,video,0,0,&audio).empty(),"no endpoint ID cannot become default input");
+ audio={L"DShow",L"ds:audio"};check(CaptureCardSource::makeCapturePath(0,video,0,0,&audio).find(L":0:")!=std::wstring::npos,"DirectShow connection retained");
+ video.path.clear();check(CaptureCardSource::makeCapturePath(0,video,0,-2,nullptr)==L"capture:0:0:-2:0","legacy embedded path retained");
+ std::vector<uint8_t> zeros(3840,0);const uint8_t data[]={1,2,3,4};
+ check(wasapiPacketData(data,4,false,zeros)==data,"non-silent PCM preserved without modification");
+ check(wasapiPacketData(nullptr,3840,true,zeros)==zeros.data()&&zeros.back()==0,"silent null packet uses bounded zero PCM");
+ check(!wasapiPacketData(nullptr,4,false,zeros),"null non-silent packet rejected");
+ check(!wasapiPacketData(data,3841,false,zeros),"oversized packet rejected");
+ check(!wasapiPacketData(data,0,false,zeros),"empty packet rejected");
+ }else {printf("Use --offline, --list, --invalid, or --endpoint <explicit capture ID>. No default recording.\n");return 2;}
+ printf("WASAPI_INPUT checks=%d failures=%d\n",checks,failures);return failures?1:0;
+}