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++

chore: checkpoint before capture FG clock repair

Veyra Goal Agentd9a94ebf76a2
diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cpp
index de0b3682..f14718e4 100644
--- a/apps/veyra/ui/CapturePanel.cpp
+++ b/apps/veyra/ui/CapturePanel.cpp
@@ -7,12 +7,27 @@
namespace veyra::ui {
namespace {
HWND window=nullptr;HFONT font=nullptr;std::function<void(const std::wstring&)> start;
-struct Query {int device=-1;std::vector<std::wstring> video,audio;std::vector<source::CaptureFormat> formats;};
+struct Query {int device=-1;std::vector<source::CaptureDevice> video,audio;std::vector<source::CaptureFormat> formats;};
std::future<Query> pending;bool busy=false;int queriedDevice=-1;ULONGLONG queryStarted=0;
std::vector<source::CaptureFormat> formats;
+std::vector<source::CaptureDevice> videoDevices,audioDevices;
std::function<bool()> readSdr;std::function<bool(bool)> setSdr;
+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()));
+ SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);
+}
+int selectedAudio(HWND h,int device){
+ const int selection=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0));if(selection<=0)return source::kCaptureAudioDisabled;
+ const bool videoSelected=device>=0&&size_t(device)<videoDevices.size();
+ if(videoSelected&&selection==1)return source::kCaptureAudioFromVideoDevice;
+ return selection-1-(videoSelected?1:0);
+}
void query(int device){if(busy)return;busy=true;queriedDevice=device;queryStarted=GetTickCount64();SetDlgItemTextW(window,8,L"正在查询设备能力…当前播放继续");EnableWindow(GetDlgItem(window,4),FALSE);EnableWindow(GetDlgItem(window,5),FALSE);EnableWindow(GetDlgItem(window,1),FALSE);
- pending=std::async(std::launch::async,[device]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);Query result;result.device=device;try{if(device<0){result.video=source::CaptureCardSource::devices();result.audio=source::CaptureCardSource::devices(true);}else result.formats=source::CaptureCardSource::formats(unsigned(device));}catch(...){}CoUninitialize();return result;});
+ const std::wstring videoPath=device>=0&&size_t(device)<videoDevices.size()?videoDevices[size_t(device)].path:L"";
+ pending=std::async(std::launch::async,[device,videoPath]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);Query result;result.device=device;try{if(device<0){result.video=source::CaptureCardSource::deviceDetails();result.audio=source::CaptureCardSource::deviceDetails(true);}else result.formats=videoPath.empty()?source::CaptureCardSource::formats(unsigned(device)):source::CaptureCardSource::formatsByPath(videoPath);}catch(...){}CoUninitialize();return result;});
}
void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,412,412,14,84,344,154,254,224,294};for(int id=1;id<=12;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,(id<=3||id==10)?180:id==8?56:id==4||id==5?36:24),TRUE);}}
LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
@@ -23,12 +38,50 @@ case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar
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);
- installDialogHelp(h,{{12,L"收到HDR也转成SDR显示,不用改PS5或Windows。增强照常用;只改预览,视频导出不受影响。切换会短暂停顿,截图跟随当前画面。关闭后跟随显示器。"},{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"选择对应的采集音频设备,也可不采声音。画面和声音要认对门。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});
+ 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:SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);if(busy&&pending.wait_for(std::chrono::seconds(0))==std::future_status::ready){auto result=pending.get();busy=false;EnableWindow(GetDlgItem(h,5),TRUE);EnableWindow(GetDlgItem(h,1),TRUE);if(result.device<0){SendDlgItemMessageW(h,1,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,3,CB_RESETCONTENT,0,0);formats.clear();for(auto& name:result.video)SendDlgItemMessageW(h,1,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(L"不监听音频"));for(auto& name:result.audio)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);SetDlgItemTextW(h,8,result.video.empty()?L"未找到采集设备。连接后点击刷新。":L"请选择设备以查询实际格式;点击连接前不会中断当前视频。");}
- else{formats=std::move(result.formats);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);for(auto& format:formats)SendDlgItemMessageW(h,2,CB_ADDSTRING,0,LPARAM(format.label.c_str()));if(!formats.empty())SendDlgItemMessageW(h,2,CB_SETCURSEL,0,0);EnableWindow(GetDlgItem(h,4),!formats.empty());SetDlgItemTextW(h,8,formats.empty()?L"未读到有效的4K以内采集格式,或设备正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");}}
- else if(busy&&GetTickCount64()-queryStarted>5000)SetDlgItemTextW(h,8,L"设备查询耗时较长。可以关闭此面板,当前播放不受影响。");return 0;
-case WM_COMMAND:if(LOWORD(wp)==12&&HIWORD(wp)==BN_CLICKED){const bool enabled=SendDlgItemMessageW(h,12,BM_GETCHECK,0,0)==BST_CHECKED;if(!setSdr(enabled))SetDlgItemTextW(h,8,L"当前正在切换增强,请稍后再试。");SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);}else if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)query(int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)));else if(LOWORD(wp)==5)query(-1);else if(LOWORD(wp)==4){int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)),format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0)),audio=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0))-1;if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()){start(std::format(L"capture:{}:{}:{}:{}",device,formats[format].index,audio,int(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0))));DestroyWindow(h);}}return 0;
+case WM_TIMER:
+ SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
+ if(busy&&pending.wait_for(std::chrono::seconds(0))==std::future_status::ready){
+ auto result=pending.get();busy=false;EnableWindow(GetDlgItem(h,5),TRUE);EnableWindow(GetDlgItem(h,1),TRUE);
+ if(result.device<0){
+ videoDevices=std::move(result.video);audioDevices=std::move(result.audio);
+ SendDlgItemMessageW(h,1,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);formats.clear();
+ for(auto& video:videoDevices)SendDlgItemMessageW(h,1,CB_ADDSTRING,0,LPARAM(video.name.c_str()));
+ if(!videoDevices.empty()){
+ SendDlgItemMessageW(h,1,CB_SETCURSEL,0,0);rebuildAudioList(h,0);query(0);
+ }else{
+ rebuildAudioList(h,-1);SetDlgItemTextW(h,8,L"未找到采集设备。连接后点击刷新。");
+ }
+ }else{
+ formats=std::move(result.formats);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);
+ for(auto& format:formats)SendDlgItemMessageW(h,2,CB_ADDSTRING,0,LPARAM(format.label.c_str()));
+ if(!formats.empty())SendDlgItemMessageW(h,2,CB_SETCURSEL,0,0);EnableWindow(GetDlgItem(h,4),!formats.empty());
+ SetDlgItemTextW(h,8,formats.empty()?L"未读到有效的4K以内采集格式,或设备正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");
+ }
+ }else if(busy&&GetTickCount64()-queryStarted>5000)SetDlgItemTextW(h,8,L"设备查询耗时较长。可以关闭此面板,当前播放不受影响。");
+ return 0;
+case WM_COMMAND:
+ if(LOWORD(wp)==12&&HIWORD(wp)==BN_CLICKED){
+ const bool enabled=SendDlgItemMessageW(h,12,BM_GETCHECK,0,0)==BST_CHECKED;
+ if(!setSdr(enabled))SetDlgItemTextW(h,8,L"当前正在切换增强,请稍后再试。");
+ SendDlgItemMessageW(h,12,BM_SETCHECK,readSdr()?BST_CHECKED:BST_UNCHECKED,0);
+ }else if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE){
+ const int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0));rebuildAudioList(h,device);query(device);
+ }else if(LOWORD(wp)==5){
+ query(-1);
+ }else if(LOWORD(wp)==4){
+ const int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0));
+ const int format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0));
+ const int audio=selectedAudio(h,device);
+ const bool audioIndexValid=audio<0||size_t(audio)<audioDevices.size();
+ if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()&&device>=0&&size_t(device)<videoDevices.size()&&audioIndexValid){
+ const auto* audioDevice=audio>=0?&audioDevices[size_t(audio)]:nullptr;
+ const auto path=source::CaptureCardSource::makeCapturePath(unsigned(device),videoDevices[size_t(device)],formats[size_t(format)].index,audio,audioDevice,unsigned(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0)));
+ if(!path.empty()){start(path);DestroyWindow(h);}
+ }
+ }
+ return 0;
case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);
case WM_SIZE:arrange();return 0;
case WM_DPICHANGED:{auto r=reinterpret_cast<RECT*>(lp);SetWindowPos(h,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER|SWP_NOACTIVATE);auto old=font;font=makeFont(h);EnumChildWindows(h,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(old);arrange();return 0;}
diff --git a/docs/CAPTURE_AUDIO_DEVICE_SELECTION_REPAIR_2026-09-14.md b/docs/CAPTURE_AUDIO_DEVICE_SELECTION_REPAIR_2026-09-14.md
new file mode 100644
index 00000000..875ff846
--- /dev/null
+++ b/docs/CAPTURE_AUDIO_DEVICE_SELECTION_REPAIR_2026-09-14.md
@@ -0,0 +1,41 @@
+# 采集卡音频设备选择修复(2026-09-14)
+
+## 结论
+
+Veyra 原先只枚举 `CLSID_AudioInputDeviceCategory` 下的独立音频 filter,连接时也强制绑定独立音频 filter;没有尝试从用户选中的视频 filter 查找内置音频 pin。部分采集卡把 HDMI 音频作为视频 filter 的输出 pin 暴露,OBS 可以通过“使用视频设备音频”打开,Veyra 因此不会在音频列表中出现对应项。
+
+## 本次修复
+
+- 新增视频/音频设备详细枚举,保留 FriendlyName,并读取 DirectShow DevicePath。
+- 视频设备枚举时探测其音频输出 pin;UI 对每个已选视频设备都提供“尝试视频设备内置音频”,预扫描成功时标为“已检测”,避免驱动延迟暴露 pin 时被预扫描结果误拒绝。
+- 内置音频直接复用已加入 graph 的视频 filter;没有把同一个 filter 重复 AddFilter 或失败时误 RemoveFilter。
+- 独立音频设备继续支持,但新 UI 通过 DevicePath 绑定,不再依赖刷新后的全局整数序号。
+- 新 UI 使用 `capture2:` 连接串保存视频/音频 DevicePath;旧 `capture:` 连接串继续兼容。
+- 音频 pin 查找优先 `PIN_CATEGORY_CAPTURE`,再回退到未提供 pin category 但确实是音频输出的驱动 pin。
+- 记录音频绑定模式、pin/media type、PCM 可解析性和 ConnectDirect HRESULT,便于区分“未枚举”和“连接失败”。
+- `veyra_capture_tests --list` 现在同时输出视频内置音频标记、视频 DevicePath 和独立音频设备。
+
+## 实际验证
+
+构建命令:
+
+```powershell
+.\scripts\build.ps1 -Root (Get-Location).Path -Preset x64-release -BuildDirectory (Join-Path (Get-Location).Path 'out\build\audio-device-fix') -FfmpegRoot 'C:\veyra-deps\ffmpeg-ps5-dav1d-installed'
+```
+
+结果:exit 0,`veyra.exe`、`veyra_capture_tests.exe` 及相关库均完成链接。
+
+针对性测试:
+
+- `veyra_capture_tests.exe --list`:exit 0;本机输出 `USB3 Video embeddedAudio=0`,并输出独立 `USB3 Digital Audio`。
+- `veyra_capture_audio_tests.exe --jitter`:PASS,500 个 10ms PCM 输入块,追加 reset/underrun 均为 0。
+- `veyra_capture_audio_tests.exe --jitter --5.1`:PASS,6 声道输入路径通过。
+- `veyra_ui_contract_tests.exe`:PASS。
+- `veyra_capture_color_tests.exe`:PASS,failures=0。
+
+## 未验证与边界
+
+- 反馈者的具体采集卡、驱动和 OBS 选择路径尚未在本机复现;不能据此宣称该实卡已经验收。
+- 本机设备是“独立 USB3 Digital Audio”路径,没有可供 Agent 实际启动的内置音频卡用于端到端验证;内置路径已编译并由同一 pin 查找/连接逻辑接入。
+- Veyra 当前仍只接收可解析的 PCM;Dolby/DTS/其他压缩音频不会因本修复自动获得支持,失败会保留视频并写出详细日志。
+- 未修改驱动、SDK、运行时 DLL、模型或发布资产;未 push、未发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 9e996423..09f815ae 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,11 @@
# 2026-09-11 继续修复目标模式执行中
+## 2026-09-14 采集卡音频设备选择修复
+
+用户反馈“采集卡对应音频在 Veyra 中选不到、OBS 可以选择”。静态排查确认原实现只枚举全局独立 DirectShow 音频 filter,未使用选中视频 filter 的内置音频 pin,也用易变整数序号重新绑定设备。本轮已修复内置音频路径、独立音频 DevicePath 绑定、`capture2:` 连接串和音频 pin/media type 诊断;旧 `capture:` 路径兼容。详细范围、命令、结果和未测边界见 [采集卡音频设备选择修复](CAPTURE_AUDIO_DEVICE_SELECTION_REPAIR_2026-09-14.md)。
+
+最终 `x64-release` 构建 exit 0;`veyra_capture_tests --list`、普通/5.1 音频 jitter、UI contract、capture color 均通过。本机只枚举到独立 `USB3 Digital Audio`,没有反馈者实卡,未宣称实卡验收;未 push/发布。
+
## 2026-09-14 用户实卡反馈:RTX 3060 XeSS-FG 2X 可用
用户确认在 RTX 3060 实机上,Veyra 选择 `Intel XeSS · 实验显示补帧 2X` 后可以正常使用帧生成。该结论指向 XeSS-FG 预览路径,不等同于 NVIDIA 官方 DLSS Frame Generation 对 RTX 30 的支持,也不证明社区 `dlssg_for_sm86` 已接入或必要。
diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.h
index 88ab53a7..783cd451 100644
--- a/include/veyra/source/CaptureCardSource.h
+++ b/include/veyra/source/CaptureCardSource.h
@@ -1,10 +1,22 @@
#pragma once
#include "veyra/source/IFrameSource.h"
#include <memory>
+#include <string_view>
#include <vector>
#include "veyra/sink/CaptureAudioSession.h"
namespace veyra::source {
struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;};
+struct CaptureDevice {
+ std::wstring name;
+ // DirectShow moniker DevicePath/display name. This is stable across a
+ // fresh enumeration, unlike the ordinal exposed by ICreateDevEnum.
+ std::wstring path;
+ // 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;
+};
+constexpr int kCaptureAudioDisabled=-1;
+constexpr int kCaptureAudioFromVideoDevice=-2;
struct CaptureMetrics {
uint64_t received=0, delivered=0, dropped=0;
double callbackFps=0, readAgeMs=0, frameAgeMs=0;
@@ -12,8 +24,12 @@ struct CaptureMetrics {
class CaptureCardSource final:public IFrameSource {
public:
CaptureCardSource();~CaptureCardSource()override;
+ static std::vector<CaptureDevice> deviceDetails(bool audio=false);
static std::vector<std::wstring> devices(bool audio=false);
+ static std::wstring makeCapturePath(unsigned videoIndex,const CaptureDevice& video,
+ int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride=0);
static std::vector<CaptureFormat> formats(unsigned device);
+ static std::vector<CaptureFormat> formatsByPath(std::wstring_view devicePath);
bool open(const SourceOpenDesc&)override;
// Negotiate/allocate before GPU initialization, but do not queue frames
// or start audio until the presenter and enhancement graph are ready.
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 93b66da2..5a2afcad 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -118,7 +118,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;
sink::AudioPipeline audioPipe;sink::AudioRenderer audio;VideoPresenter presenter;
pipeline::EnhanceGraph graph(ctx,ring);AVFrame* imageFrame=nullptr;AVFrame* cachedFrame=nullptr;pipeline::FramePacket cachedPacket;
- source::CaptureCardSource captureSource;const bool physicalCapture=path.rfind(L"capture:",0)==0;
+ source::CaptureCardSource captureSource;const bool physicalCapture=path.starts_with(L"capture:")||path.starts_with(L"capture2:");
#ifdef VEYRA_ENABLE_REMOTEPLAY
auto remote=remoteRequest?std::make_shared<source::RemotePlaySessionSource>():nullptr;
const bool isRemote=bool(remote);
diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cpp
index 4cdadf06..93fc8c44 100644
--- a/src/engine/ExportJobManager.cpp
+++ b/src/engine/ExportJobManager.cpp
@@ -33,7 +33,7 @@ ExportJobManager::~ExportJobManager(){cancel();if(p_->process)WaitForSingleObjec
bool ExportJobManager::start(const std::wstring& input,const std::wstring& output,EnhancementSettings settings,bool hevc,unsigned maxFrames){
if(poll().active())return false;p_->clear();p_->snapshot={};
auto fail=[&](const wchar_t* message){const DWORD error=GetLastError();p_->clear();p_->snapshot.state=ExportState::Failed;p_->snapshot.message=message;log::error("export-worker",std::format("launch failed error={}",error));return false;};
- if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.rfind(L"capture:",0)==0)return fail(L"请选择本地视频与有效导出设置");
+ if(input.empty()||output.empty()||input.size()>=32768||output.size()>=32768||!settings.validate().empty()||input.starts_with(L"capture:")||input.starts_with(L"capture2:"))return fail(L"请选择本地视频与有效导出设置");
if(std::filesystem::exists(output)||std::filesystem::exists(output+L".partial"))return fail(L"输出或partial文件已存在,请选择新文件名");
SECURITY_ATTRIBUTES sa{sizeof(sa),nullptr,TRUE};
p_->mapping=CreateFileMappingW(INVALID_HANDLE_VALUE,&sa,PAGE_READWRITE,0,sizeof(Shared),nullptr);
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 8ad64bec..cd3d8b43 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -9,12 +9,16 @@
#include <dshow.h>
#include <dvdmedia.h>
#include <wrl/client.h>
+#include <algorithm>
+#include <array>
+#include <cstdint>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <format>
#include <chrono>
#include <cmath>
+#include <string_view>
extern "C" {
#include <libavutil/frame.h>
#include <libavutil/pixfmt.h>
@@ -29,9 +33,82 @@ struct __declspec(uuid("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F")) ISampleGrabber:I
const CLSID SampleGrabberClass={0xc1f400a0,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};
const CLSID NullRendererClass={0xc1f400a4,0x3f08,0x11d3,{0x9f,0x0b,0x00,0x60,0x08,0x03,0x9e,0x37}};
void freeType(AM_MEDIA_TYPE* t,bool pointer=true){if(!t)return;CoTaskMemFree(t->pbFormat);if(t->pUnk)t->pUnk->Release();if(pointer)CoTaskMemFree(t);}
+std::wstring propertyString(IMoniker* moniker,LPCOLESTR property){
+ if(!moniker)return {};
+ ComPtr<IPropertyBag> bag;VARIANT value;VariantInit(&value);std::wstring result;
+ if(SUCCEEDED(moniker->BindToStorage(nullptr,nullptr,IID_PPV_ARGS(&bag)))&&
+ SUCCEEDED(bag->Read(property,&value,nullptr))&&value.vt==VT_BSTR&&value.bstrVal)result=value.bstrVal;
+ VariantClear(&value);return result;
+}
+std::wstring monikerPath(IMoniker* moniker){
+ if(auto path=propertyString(moniker,L"DevicePath");!path.empty())return path;
+ ComPtr<IBindCtx> context;LPOLESTR display=nullptr;
+ if(SUCCEEDED(CreateBindCtx(0,&context))&&SUCCEEDED(moniker->GetDisplayName(context.Get(),nullptr,&display))&&display){
+ std::wstring path(display);CoTaskMemFree(display);return path;
+ }
+ return {};
+}
+bool audioOutputPin(IPin* pin){
+ if(!pin)return false;PIN_DIRECTION direction{};if(FAILED(pin->QueryDirection(&direction))||direction!=PINDIR_OUTPUT)return false;
+ ComPtr<IEnumMediaTypes> types;if(FAILED(pin->EnumMediaTypes(&types)))return false;
+ for(;;){AM_MEDIA_TYPE* type=nullptr;const HRESULT hr=types->Next(1,&type,nullptr);if(hr!=S_OK||!type)break;const bool audio=type->majortype==MEDIATYPE_Audio;freeType(type);if(audio)return true;}
+ return false;
+}
+HRESULT findAudioOutputPin(IBaseFilter* filter,ComPtr<IPin>& result){
+ result.Reset();if(!filter)return E_POINTER;ComPtr<IEnumPins> pins;HRESULT hr=filter->EnumPins(&pins);if(FAILED(hr))return hr;
+ ComPtr<IPin> fallback;
+ for(;;){ComPtr<IPin> pin;hr=pins->Next(1,&pin,nullptr);if(hr!=S_OK)break;if(!audioOutputPin(pin.Get()))continue;
+ if(!fallback)fallback=pin;
+ // Prefer a pin explicitly classified as capture, but accept a driver
+ // that omits the category and exposes only an audio output pin.
+ ComPtr<IKsPropertySet> properties;if(SUCCEEDED(pin.As(&properties))){GUID category{};DWORD returned=0;
+ if(SUCCEEDED(properties->Get(AMPROPSETID_Pin,AMPROPERTY_PIN_CATEGORY,nullptr,0,&category,sizeof(category),&returned))&&category==PIN_CATEGORY_CAPTURE){result=pin;return S_OK;}}
+ }
+ if(fallback){result=fallback;return S_OK;}return VFW_E_NOT_FOUND;
+}
std::vector<ComPtr<IMoniker>> monikers(bool audio){std::vector<ComPtr<IMoniker>> out;ComPtr<ICreateDevEnum> de;ComPtr<IEnumMoniker> en;if(FAILED(CoCreateInstance(CLSID_SystemDeviceEnum,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&de)))||de->CreateClassEnumerator(audio?CLSID_AudioInputDeviceCategory:CLSID_VideoInputDeviceCategory,&en,0)!=S_OK)return out;for(;;){ComPtr<IMoniker> m;if(en->Next(1,&m,nullptr)!=S_OK)break;out.push_back(m);}return out;}
bool bind(unsigned index,bool audio,ComPtr<IBaseFilter>& filter){auto list=monikers(audio);return index<list.size()&&SUCCEEDED(list[index]->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&filter)));}
-bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b)))&&SUCCEEDED(b->SetFiltergraph(g.Get()))&&bind(device,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
+bool bindPath(std::wstring_view wanted,bool audio,ComPtr<IBaseFilter>& filter){
+ if(wanted.empty())return false;for(auto& moniker:monikers(audio))if(monikerPath(moniker.Get())==wanted)return SUCCEEDED(moniker->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&filter)));return false;
+}
+bool createConfiguration(ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b){return SUCCEEDED(CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g)))&&SUCCEEDED(CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b)))&&SUCCEEDED(b->SetFiltergraph(g.Get()));}
+bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return createConfiguration(g,b)&&bind(device,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
+bool configuration(std::wstring_view path,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c){return createConfiguration(g,b)&&bindPath(path,false,f)&&SUCCEEDED(g->AddFilter(f.Get(),L"Capture card"))&&SUCCEEDED(b->FindInterface(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,f.Get(),IID_PPV_ARGS(&c)));}
+HRESULT audioPinFor(ICaptureGraphBuilder2* builder,IBaseFilter* filter,ComPtr<IPin>& pin){
+ if(!builder||!filter)return E_POINTER;const HRESULT categorized=builder->FindPin(filter,PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,FALSE,0,&pin);
+ if(SUCCEEDED(categorized))return categorized;
+ pin.Reset();return findAudioOutputPin(filter,pin);
+}
+std::wstring encodePath(std::wstring_view value){
+ static constexpr wchar_t digits[]=L"0123456789ABCDEF";std::wstring encoded;encoded.reserve(value.size()*4);
+ for(const wchar_t character:value){const uint16_t unit=static_cast<uint16_t>(character);for(int shift=12;shift>=0;shift-=4)encoded.push_back(digits[(unit>>shift)&0xF]);}return encoded;
+}
+std::string pathTag(std::wstring_view value){const auto encoded=encodePath(value);std::string tag;tag.reserve(encoded.size());for(const wchar_t character:encoded)tag.push_back(static_cast<char>(character));return tag;}
+int hexValue(wchar_t character){if(character>=L'0'&&character<=L'9')return character-L'0';if(character>=L'A'&&character<=L'F')return character-L'A'+10;if(character>=L'a'&&character<=L'f')return character-L'a'+10;return -1;}
+bool decodePath(std::wstring_view encoded,std::wstring& value){
+ if(encoded.size()%4!=0)return false;value.clear();value.reserve(encoded.size()/4);
+ for(size_t i=0;i<encoded.size();i+=4){int unit=0;for(size_t j=0;j<4;++j){const int nibble=hexValue(encoded[i+j]);if(nibble<0)return false;unit=(unit<<4)|nibble;}value.push_back(static_cast<wchar_t>(unit));}return true;
+}
+bool parseInt(std::wstring_view text,int& value){
+ if(text.empty())return false;const std::wstring copy(text);size_t consumed=0;try{value=std::stoi(copy,&consumed);}catch(...){return false;}return consumed==copy.size();
+}
+bool parseUnsigned(std::wstring_view text,unsigned& value){int parsed=0;if(!parseInt(text,parsed)||parsed<0)return false;value=static_cast<unsigned>(parsed);return true;}
+struct CaptureSelection {unsigned videoIndex=0;int format=0;int audio=kCaptureAudioDisabled;unsigned colorOverride=0;bool stable=false;std::wstring videoPath,audioPath;};
+bool parseCapturePath(std::wstring_view path,CaptureSelection& selection){
+ selection={};
+ constexpr std::wstring_view prefix=L"capture2:";
+ if(path.starts_with(prefix)){
+ 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;
+ }
+ 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);
+ if(fields<3||format<0||audio<kCaptureAudioFromVideoDevice||colorOverride>2)return false;
+ selection.videoIndex=videoIndex;selection.format=format;selection.audio=audio;selection.colorOverride=fields>=4?colorOverride:0;return true;
+}
}
struct CaptureCardSource::Impl:ISampleGrabberCB {
using Clock=std::chrono::steady_clock;
@@ -81,14 +158,44 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {
};
CaptureCardSource::CaptureCardSource():p_(std::make_unique<Impl>()){}
CaptureCardSource::~CaptureCardSource(){close();}
-std::vector<std::wstring> CaptureCardSource::devices(bool audio){std::vector<std::wstring> result;for(auto& m:monikers(audio)){ComPtr<IPropertyBag> bag;VARIANT v;VariantInit(&v);std::wstring name=L"Unknown capture device";if(SUCCEEDED(m->BindToStorage(nullptr,nullptr,IID_PPV_ARGS(&bag)))&&SUCCEEDED(bag->Read(L"FriendlyName",&v,nullptr))&&v.vt==VT_BSTR)name=v.bstrVal;VariantClear(&v);result.push_back(name);}return result;}
-std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;std::vector<CaptureFormat> out;if(!configuration(device,g,b,f,c))return out;int count=0,size=0;if(FAILED(c->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;std::vector<BYTE> caps(size);for(int i=0;i<count;++i){AM_MEDIA_TYPE* t=nullptr;if(FAILED(c->GetStreamCaps(i,&t,caps.data())))continue;BITMAPINFOHEADER* bm=nullptr;REFERENCE_TIME duration=0;if(t->formattype==FORMAT_VideoInfo&&t->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* vi=reinterpret_cast<VIDEOINFOHEADER*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}else if(t->formattype==FORMAT_VideoInfo2&&t->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* vi=reinterpret_cast<VIDEOINFOHEADER2*>(t->pbFormat);bm=&vi->bmiHeader;duration=vi->AvgTimePerFrame;}
+std::vector<CaptureDevice> CaptureCardSource::deviceDetails(bool audio){
+ std::vector<CaptureDevice> result;
+ for(auto& moniker:monikers(audio)){
+ CaptureDevice device;device.name=propertyString(moniker.Get(),L"FriendlyName");
+ if(device.name.empty())device.name=L"Unknown capture device";
+ device.path=monikerPath(moniker.Get());
+ if(!audio){ComPtr<IBaseFilter> filter;ComPtr<IPin> audioPin;
+ if(SUCCEEDED(moniker->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&filter)))&&SUCCEEDED(findAudioOutputPin(filter.Get(),audioPin)))device.hasEmbeddedAudio=true;
+ }
+ result.push_back(std::move(device));
+ }
+ 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(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);
+}
+std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config){
+ std::vector<CaptureFormat> out;if(!config)return out;int count=0,size=0;
+ if(FAILED(config->GetNumberOfCapabilities(&count,&size))||size<1||size>65536)return out;
+ std::vector<BYTE> caps(size);
+ for(int i=0;i<count;++i){AM_MEDIA_TYPE* type=nullptr;if(FAILED(config->GetStreamCaps(i,&type,caps.data())))continue;BITMAPINFOHEADER* bitmap=nullptr;REFERENCE_TIME duration=0;
+ if(type->formattype==FORMAT_VideoInfo&&type->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* info=reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
+ else if(type->formattype==FORMAT_VideoInfo2&&type->cbFormat>=sizeof(VIDEOINFOHEADER2)){auto* info=reinterpret_cast<VIDEOINFOHEADER2*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}
// Device capabilities, not a 1080p/2160p 30/60 preset list. Keep native
// indices so the selected row opens the exact driver media type.
- if(bm&&bm->biWidth>0&&bm->biWidth<=3840&&std::abs(int64_t(bm->biHeight))>0&&std::abs(int64_t(bm->biHeight))<=2160&&duration>0){unsigned w=bm->biWidth,h=unsigned(std::abs(int64_t(bm->biHeight)));double fps=1e7/duration;
- const auto pixel=capturePixelName(t->subtype);CaptureMediaLayout layout;const bool valid=captureMediaLayout(*t,layout);const bool knownRaw=capturePacking(t->subtype)!=CapturePacking::Unknown;
+ if(bitmap&&bitmap->biWidth>0&&bitmap->biWidth<=3840&&std::abs(int64_t(bitmap->biHeight))>0&&std::abs(int64_t(bitmap->biHeight))<=2160&&duration>0){unsigned width=bitmap->biWidth,height=unsigned(std::abs(int64_t(bitmap->biHeight)));double fps=1e7/duration;
+ const auto pixel=capturePixelName(type->subtype);CaptureMediaLayout layout;const bool valid=captureMediaLayout(*type,layout);const bool knownRaw=capturePacking(type->subtype)!=CapturePacking::Unknown;
const wchar_t* support=valid?((layout.format==AV_PIX_FMT_P010||layout.format==AV_PIX_FMT_P016)?L"原生 · SDR":L"原生"):knownRaw?L"布局/颜色暂不支持":L"需系统解码/转换";
- out.push_back({i,w,h,fps,std::format(L"{} x {} @ {:.2f} fps · {} · {} [format {}]",w,h,fps,pixel,support,i)});}freeType(t);}return out;}
+ out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.2f} fps · {} · {} [format {}]",width,height,fps,pixel,support,i)});
+ }
+ freeType(type);
+ }
+ return out;
+}
+std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(device,g,b,f,c))return {};return enumerateFormats(c.Get());}
+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){
auto& p=*p_;if(p.audioSession){p.audioSession->setGain(gain);return p.audioSession->snapshot().available;}if(!p.graph||!p.audioFilter)return false;
@@ -102,8 +209,8 @@ void CaptureCardSource::videoReset(){if(p_->audioSession)p_->audioSession->video
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();}
-bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAudioGain=-1;auto& p=*p_;unsigned index=0;int format=0,audio=-1;if(swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d",&index,&format,&audio)!=3)return false;
- if(!configuration(index,p.graph,p.builder,p.device,p.config))return false;
+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;
int count=0,size=0;if(FAILED(p.config->GetNumberOfCapabilities(&count,&size))||format<0||format>=count||size<=0||size>65536)return false;
std::vector<BYTE> caps(size);AM_MEDIA_TYPE* native=nullptr;if(FAILED(p.config->GetStreamCaps(format,&native,caps.data())))return false;
HRESULT hr=p.config->SetFormat(native);const GUID requestedSubtype=native->subtype;
@@ -138,7 +245,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
}
freeType(native);const bool layoutValid=SUCCEEDED(hr)&&captureMediaLayout(connected,p.layout);freeType(&connected,false);
if(!layoutValid){log::error("capture",std::format("unsupported negotiated layout/connect failure hr=0x{:08X}",uint32_t(hr)));return false;}
- unsigned colorOverride=0;swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d:%u",&index,&format,&audio,&colorOverride);
+ const unsigned colorOverride=selection.colorOverride;
if(colorOverride>2)return false;
if(colorOverride){
if(p.layout.format!=AV_PIX_FMT_P010&&p.layout.format!=AV_PIX_FMT_P016){log::error("capture-color","Explicit HDR requires P010/P016; select a 10/16-bit capture format");return false;}
@@ -150,21 +257,39 @@ 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>=0){
- const bool connected=[&]{
- if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio")))return false;
- ComPtr<IPin> audioPin;
- if(FAILED(p.builder->FindPin(p.audioFilter.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,FALSE,0,&audioPin)))return false;
- ComPtr<IEnumMediaTypes> types;if(FAILED(audioPin->EnumMediaTypes(&types)))return false;
+ if(audio!=kCaptureAudioDisabled){
+ const bool audioReady=[&]{
+ ComPtr<IBaseFilter> audioFilter;const bool embedded=audio==kCaptureAudioFromVideoDevice;
+ if(embedded){
+ // Some capture cards expose video and HDMI audio on one
+ // DirectShow filter. OBS calls this "use video device". Do not
+ // AddFilter/RemoveFilter here: p.device owns the graph filter.
+ audioFilter=p.device;log::info("capture-audio",std::format("binding=video-filter embedded=1 videoPathTag={}",pathTag(selection.videoPath)));
+ }else{
+ const bool bound=selection.stable?bindPath(selection.audioPath,true,audioFilter):bind(unsigned(audio),true,audioFilter);
+ if(!bound){log::warn("capture-audio",std::format("binding=separate failed mode={} audioIndex={} audioPathTag={}",audio,audio,pathTag(selection.audioPath)));return false;}
+ hr=p.graph->AddFilter(audioFilter.Get(),L"Capture audio");
+ if(FAILED(hr)){log::warn("capture-audio",std::format("binding=separate AddFilter hr=0x{:08X}",uint32_t(hr)));return false;}
+ p.audioFilter=audioFilter;log::info("capture-audio",std::format("binding=separate embedded=0 audioIndex={} audioPathTag={}",audio,audio,pathTag(selection.audioPath)));
+ }
+ ComPtr<IPin> audioPin;hr=audioPinFor(p.builder.Get(),audioFilter.Get(),audioPin);
+ if(FAILED(hr)){log::warn("capture-audio",std::format("audio output pin not found embedded={} hr=0x{:08X}",embedded?1:0,uint32_t(hr)));return false;}
+ ComPtr<IEnumMediaTypes> types;hr=audioPin->EnumMediaTypes(&types);if(FAILED(hr)){log::warn("capture-audio",std::format("EnumMediaTypes hr=0x{:08X}",uint32_t(hr)));return false;}
// Preserve the device's actual speaker layout. Enumeration order is
// commonly stereo first even when native 5.1 is available.
auto releaseType=[](AM_MEDIA_TYPE* type){freeType(type);};
using AudioType=std::unique_ptr<AM_MEDIA_TYPE,decltype(releaseType)>;
- std::vector<AudioType> audioTypes;
- for(;;){AM_MEDIA_TYPE* type=nullptr;if(types->Next(1,&type,nullptr)!=S_OK)break;
- AudioType owned(type,releaseType);sink::WavePcmFormat pcm;
- if(type->formattype==FORMAT_WaveFormatEx&&sink::parseWavePcm(type->pbFormat,type->cbFormat,pcm))audioTypes.push_back(std::move(owned));
+ std::vector<AudioType> audioTypes;unsigned typeIndex=0;
+ for(;;){AM_MEDIA_TYPE* type=nullptr;if(types->Next(1,&type,nullptr)!=S_OK||!type)break;
+ AudioType owned(type,releaseType);sink::WavePcmFormat pcm;bool supported=false;
+ if(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));
+ }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;
});
@@ -193,7 +318,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
}
return connectedAudio;
}();
- if(!connected){
+ if(!audioReady){
p.audioError=L"采集音频设备或 PCM 格式不可用;视频继续运行";
log::warn("capture-audio","audio connection unavailable; retaining video capture");
if(p.audioFilter)p.graph->RemoveFilter(p.audioFilter.Get());
diff --git a/tests/integration/CaptureSourceTests.cpp b/tests/integration/CaptureSourceTests.cpp
index ab6d2c22..1ec7f42f 100644
--- a/tests/integration/CaptureSourceTests.cpp
+++ b/tests/integration/CaptureSourceTests.cpp
@@ -13,9 +13,10 @@ extern "C" {
}
int wmain(int argc,wchar_t** argv){
if(argc==2&&wcscmp(argv[1],L"--list")==0){
- CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto devices=veyra::source::CaptureCardSource::devices();
- for(unsigned d=0;d<devices.size();++d){wprintf(L"DEVICE %u %ls\n",d,devices[d].c_str());for(const auto& f:veyra::source::CaptureCardSource::formats(d))wprintf(L"FORMAT %u:%d %ls\n",d,f.index,f.label.c_str());}
- CoUninitialize();return devices.empty()?1: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());
+ CoUninitialize();return videos.empty()?1:0;
}
if(argc!=2){printf("Specify capture:device:format:audio; real hardware required\n");return 2;}
CoInitializeEx(nullptr,COINIT_MULTITHREADED);