Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
Fix capture capability discovery and restore legacy format picker
golem Z09ac54bd31ce
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e3e30a8d..3d73abd9 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1104,6 +1104,16 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)add_executable(veyra_qml_data_tests tests/unit/QmlDataDirectoryTests.cpp src/ui/QmlDataDirectory.cpp)add_executable(veyra_game_passthrough_tests tests/integration/GamePassthroughTests.cpp)add_executable(veyra_game_mode_policy_tests tests/unit/GameModePolicyTests.cpp)+ add_executable(veyra_capture_capability_tests tests/unit/CaptureCapabilityTests.cpp)+ add_executable(veyra_dshow_format_discovery_tests tests/unit/DirectShowFormatDiscoveryTests.cpp)+ target_compile_features(veyra_dshow_format_discovery_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_dshow_format_discovery_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_compile_options(veyra_dshow_format_discovery_tests PRIVATE /utf-8)+ target_include_directories(veyra_dshow_format_discovery_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ target_link_libraries(veyra_dshow_format_discovery_tests PRIVATE ole32 oleaut32 strmiids uuid)+ target_compile_features(veyra_capture_capability_tests PRIVATE cxx_std_20)+ target_compile_options(veyra_capture_capability_tests PRIVATE /utf-8)+ target_include_directories(veyra_capture_capability_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)target_compile_features(veyra_game_mode_policy_tests PRIVATE cxx_std_20)target_include_directories(veyra_game_mode_policy_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)target_compile_features(veyra_game_passthrough_tests PRIVATE cxx_std_20)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex f77eaeb9..799e2846 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -22,6 +22,19 @@ licenses/notices are retained, and this local authorization grants no newpublic redistribution permission. See `docs/NR_SF_310916_PLAN_2026-10-17.md`and the corresponding report for measured conditions and untested hardware.+## Capture format capability discovery (2026-10-17)++The format compatibility review used OBS Studio 32.2.2 at+`ba2f32bdf791005443988a4955e963663e16b1ed` and its libdshowcapture submodule+at `8878638324393815512f802640b0d5ce940161f1`, especially+`src/dshow-enum.cpp` and `src/dshow-base.cpp` (LGPL-2.1-or-later).+Veyra independently implements the capability fallback, range candidates,+pin selection and exact media-type validation in+`include/veyra/source/DirectShowFormatDiscovery.h` and+`CaptureCapabilityRange.h`. No OBS runtime, capture loop, buffering,+decoder or renderer is imported by this change. This is separate from the+existing attributed libdshowcapture adaptations below.+## Compressed Matroska subtitles (2026-10-09)The subtitle candidate rebuilds the existing LGPL FFmpeg n9.0.1 with zlibdiff --git a/docs/CAPTURE_FORMAT_FIXES_2026-10-17.md b/docs/CAPTURE_FORMAT_FIXES_2026-10-17.mdnew file mode 100644index 00000000..68629c04--- /dev/null+++ b/docs/CAPTURE_FORMAT_FIXES_2026-10-17.md@@ -0,0 +1,46 @@+# 采集格式识别与旧版入口修复++日期:2026-10-17。用户授权:修复前次 OBS 对比发现的问题,并在采集页面增加旧版格式选择入口。++基线:公开 main `d68d6be9c37127350698a1d4d47fc01b36b29475`,继承窗口游戏模式修复 `1295d6b`;本任务在隔离分支 `codex/capture-format-fixes-20261017` 实施。没有修改原 main、运行库、模型、驱动或真实用户配置,没有发布或生成用户安装包。++## 改动与结果++1. `GetNumberOfCapabilities` 未实现、列表为空或全部格式块不可解析时,使用采集 pin 的 `EnumMediaTypes`。明确的设备访问错误不会伪装成成功。部分能力读取失败保留可用项,并显示阶段、HRESULT 和列表可能不完整的提示。未知帧率保持未知,不填造 59.94/60。+2. 读取 `VIDEO_STREAM_CONFIG_CAPS` 的尺寸上下限、步进和帧间隔范围,保留原始离散类型及 `IAMVideoControl` 帧率。范围派生项明确标为“范围候选(连接时验证)”,不是声称这些模式已实卡验证。列出常用合法尺寸/帧率及边界,额外尺寸可用“自定义分辨率 → 检查并选择”请求;不枚举范围中的无穷组合。+3. 帧率菜单仅在标准帧率附近吸收 1 个 100ns 整数取整误差。同一组收集全部像素格式,而持久化和实际连接仍使用各自精确 interval、subtype、format type、尺寸和扫描标识。59.94 与 60、逐行与隔行不合并,移除旧菜单二次按显示值去重造成的丢项。+4. 配置时重新发现能力,用精确 key 找回原生模板,构造具体媒体类型,核对 `SetFormat`、`GetFormat` 和实际连接。尺寸、帧率、像素格式或扫描方式被驱动替换会失败并说明原因,不使用最近似模式冒充成功。`SetFormat=E_NOTIMPL` 允许尝试精确连接,但必须通过实际连接验证。+5. 优先明确的 video capture pin;只有一个未分类视频输出时允许兼容;预览 pin、输入 pin、多个未分类输出不会被盲选。连接沿用选中的 pin。保留 VideoInfo/VideoInfo2 和隔行信息。+6. 采集页面增加 **旧版格式选择 → 打开旧版格式列表**,在一个可搜索、虚拟化列表中组合显示分辨率、帧率和像素格式,包括常用帧率开关隐藏的项。两个入口共用同一个精确 key、保存和恢复逻辑;不支持的布局仍不能连接。查询或设备切换时关闭旧列表,避免选择过时数据。++范围候选由所属 COM 线程持有的原始模板克隆,不修改驱动返回的模板;重建 sample size、stride 对应字节数、裁剪框和 VideoInfo2 宽高比。原始模板不穿过 UI 线程或存入配置。失败的自定义尺寸请求保留原有效选择。能力数、格式块和总内存有界,达到上限明确标记列表不完整。++没有引入 OBS 的采集运行时、排队、缓冲、解码、音频或渲染实现。现有 DirectShow 低延迟 native/compressed 路径、BMD 原生后端、回调、增强、调度和 UI 33ms/250ms 节奏保持。旧 RGB 兼容路径也核对上游实际类型。没有延迟性能改善的测量结论。++## OBS 对照来源++- OBS 32.2.2:`ba2f32bdf791005443988a4955e963663e16b1ed`。+- 对应 libdshowcapture:`8878638324393815512f802640b0d5ce940161f1`;`src/dshow-enum.cpp`、`src/dshow-base.cpp`。+- 不照搬 OBS 回退时填 59.94、静默最近似模式替换等行为;维持 Veyra 的精确身份和 VideoInfo2 扫描区分。+- 首次对比的复现:166667 与 166666 两种帧间隔分别提供 NV12/YUY2,旧版三联默认菜单只能访问一个像素格式;现在同一显示组内两者均可访问,各自精确 key 不变。++## 验证及限制++- 原生 Linux C++20:`CaptureCapabilityTests`,25 个检查;尺寸范围/步进、保存 key、未知帧率、59.94/60/p/i 分离、精确像素选择,以及 16,000 条记录的菜单生成。+- Windows 目标编译、链接并在 Wine 10 运行:`DirectShowFormatDiscoveryTests`,24 个检查;未实现/空能力回退、权限失败、部分失败及其诊断阶段、VideoInfo2 范围构造、实际类型替换拒绝、capture/preview/未分类 pin。驱动为 COM 测试替身,未访问真实设备。+- 同样编译、链接并在 Wine 运行现有 `CaptureFormatSelectionTests`,0 failures。+- Qt Quick Test / Qt 6.8.3 software/offscreen:新增 `tst_capture_legacy.qml` 4 项通过,搜索、精确选择、关闭/重开、禁用布局和空结果;16,000 行只实例化可见委托,独立 UI 探针看到 17 个列表子项。现有 `tst_menu_layout.qml` 9 项通过。+- `CaptureCardSource.cpp` 与 `QmlPlayerBridge.cpp` 的 Windows x86-64 COFF 对象编译通过。使用 MinGW 14、真实 Win32/DirectShow、Qt 与 FFmpeg 公开头文件;NGX 公开头文件仅作桥接语法检查的外部依赖。MinGW 对原有 MSVC `__declspec(uuid)` 声明有已记录警告;此检查不代替 MSVC 链接。+- `DialogHost.qml`、`CaptureLegacyPicker.qml` 和新增 QML 测试的 qmlcachegen 字节码/basic-block 检查;三语 i18n 占位符与缺失检查;`git diff --check`。++本机为 Linux,无 Windows GPU/真实采集卡和项目完整的 MSVC/厂商运行环境,因此**未完成完整 Windows 程序构建或实卡端到端验证**,不能宣称反馈用户的硬件已恢复。上述 Wine 运行属于程序逻辑测试。临时工具、公开 SDK 头文件和 Wine 全在仓库外,不进入产品源码或发布包。原始回执保存在 `/workspace/scratch/capture-format-fix-checks/`。++## Windows 后续验收++在项目原有 Windows 构建环境构建 `veyra_qml_ui`、`veyra_capture_format_selection_tests`、`veyra_capture_capability_tests`、`veyra_dshow_format_discovery_tests`、`veyra_qml_quick_tests`,运行相关测试后,用反馈采集卡核对:++1. 关闭 OBS,刷新 Veyra,比较同一驱动在 OBS 中的分辨率、59.94/60、像素格式与隔行项;旧版列表应可找到被常用帧率过滤的精确模式。+2. 三联菜单和旧列表分别选择 NV12/YUY2/MJPEG/其他实际支持项,连接后对照日志的 requested 与 connected;驱动不接受的范围候选必须明确失败,不能变成另一个模式。+3. 保存/重启/继续上次/断线重连,确认按 key 恢复;合法自定义尺寸可验证,非法步进保留原选择。+4. 设备被占用、部分枚举失败、查询中切换设备或关闭对话框时,不出现旧列表覆盖新设备或静默空列表。+5. 正常预览、音频、NR/SR/FG 及已有低延迟链路做定向回归。格式枚举仅在打开/刷新/配置时进行,没有每帧增加枚举操作。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex e42ea3bc..a61303ef 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,11 @@# WORKLOG+## 2026-10-17 采集格式与旧版入口(Linux 源码候选)++按用户“全部修复掉,再添加老版本采集格式选择入口”,在窗口修复 1295d6b 之上隔离实施 `codex/capture-format-fixes-20261017`。修复 DirectShow 能力回退、尺寸/帧率范围候选、±1 tick 显示分组漏掉像素项、精确媒体类型恢复与连接校验;增加可搜索虚拟化旧版组合列表、自定义尺寸检查和查询错误诊断。原低延迟回调/队列、BMD 原生、增强/音频/渲染/运行库与配置保持。详见 docs/CAPTURE_FORMAT_FIXES_2026-10-17.md。++原生能力测试、Windows/Wine 枚举及原格式测试、Qt 旧列表回归、QML 字节码与翻译检查,另做采集源和桥接的 Windows 对象编译。完整 MSVC 程序构建与真实采集卡端到端仍需 Windows 环境,不能用 Wine/模拟驱动结果代替实卡验收。没有合并 main、推送、打包或发布。+## 2026-10-17 窗口捕获游戏模式修正(Linux 源码候选)按用户最新要求取消进入穿透的初始化/动画等待,修正退出热键接收和先释放后退出、全屏拉伸/填满与源窗口 resize 元数据;任务栏问题暂缓。以 origin/main d68d6be 在隔离 codex/window-game-fixes-20261017、/workspace/veyra-window-fixes 实施,原 main/用户文件/运行组件保持。源码、输入边界和验收记录见 docs/WINDOW_GAME_FIXES_2026-10-17.md。diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex 096023a4..2a6e2f10 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -287,6 +287,13 @@"en": " · node","ja": " · ノード"},+ {+ "zh": " · 范围候选(连接时验证)",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": " · 範圍候選(連線時驗證)",+ "en": " · Range candidate (verified on connection)",+ "ja": " · 範囲内の候補(接続時に検証)"+ },{"zh": " · 质量 ","src": "qml/DialogHost.qml",@@ -413,6 +420,13 @@"en": " items","ja": " 件"},+ {+ "zh": "%1 / %2 个格式",+ "src": "qml/CaptureLegacyPicker.qml",+ "zh-TW": "%1 / %2 個格式",+ "en": "%1 / %2 formats",+ "ja": "%1 / %2 形式"+ },{"zh": "%1 · 去重后约 %2 fps","src": "src/ui/QmlPlayerBridge.cpp",@@ -3094,6 +3108,13 @@"en": "Keys are captured only in game mode; Ctrl, Alt and Shift combinations are supported","ja": "ゲームモード中のみキーを使用します。Ctrl、Alt、Shift の組み合わせに対応"},+ {+ "zh": "仅接受驱动尺寸范围与步进支持的值;连接时核对实际格式",+ "src": "qml/DialogHost.qml",+ "zh-TW": "僅接受驅動尺寸範圍與步進支援的值;連線時核對實際格式",+ "en": "Only sizes within driver bounds and granularity are accepted; the actual format is checked on connection",+ "ja": "ドライバーのサイズ範囲と刻みに合う値のみ使用できます。実際の形式は接続時に確認します"+ },{"zh": "仅清空列表,不删除硬盘文件","src": "qml/PlaylistWindow.qml",@@ -3628,7 +3649,7 @@},{"zh": "关闭",- "src": "qml/DialogHost.qml",+ "src": "qml/CaptureLegacyPicker.qml","zh-TW": "關閉","en": "Close","ja": "閉じる"@@ -3984,6 +4005,13 @@"en": "Resolution","ja": "解像度"},+ {+ "zh": "分辨率、帧率和像素格式合并显示;包含非常用帧率,与主界面共用同一个精确选择。范围候选将在连接时验证。",+ "src": "qml/CaptureLegacyPicker.qml",+ "zh-TW": "解析度、影格率和像素格式合併顯示;包含非常用影格率,與主介面共用同一個精確選擇。範圍候選將在連線時驗證。",+ "en": "Resolution, frame rate and pixel format in one list, including uncommon rates. Both views share the same exact selection. Range candidates are verified on connection.",+ "ja": "解像度・フレームレート・ピクセル形式をまとめて表示します。一般的でないレートも含み、通常画面と同じ正確な選択を使用します。範囲内の候補は接続時に検証します。"+ },{"zh": "分辨率与帧率","src": "qml/DialogHost.qml",@@ -4061,6 +4089,13 @@"en": "Toggle Minimal / Pro","ja": "シンプル / プロを切り替え"},+ {+ "zh": "列出离散帧率及驱动范围内的候选;设备帧率填 0 时沿用此选择,连接时验证实际值",+ "src": "qml/DialogHost.qml",+ "zh-TW": "列出離散影格率及驅動範圍內的候選;裝置影格率填 0 時沿用此選擇,連線時驗證實際值",+ "en": "Lists discrete rates and candidates within driver bounds; device FPS 0 uses this selection, verified on connection",+ "ja": "個別のレートとドライバー範囲内の候補を表示します。デバイスFPSが0の場合はこの選択を使い、接続時に実際の値を検証します"+ },{"zh": "列表","src": "qml/DialogHost.qml",@@ -4684,13 +4719,6 @@"en": "One frame in flight; adds Reflex without frame generation","ja": "処理中は 1 フレームのみ、フレーム生成なしでは Reflex を追加"},- {- "zh": "只列出当前分辨率下设备上报的帧率。设备帧率填 0 时,连接使用这里选中的帧率",- "src": "qml/DialogHost.qml",- "zh-TW": "只列出目前解析度下裝置回報的幀率。裝置幀率填 0 時,連接使用這裡選中的幀率",- "en": "Only frame rates the device reports for the current resolution. A device frame rate of 0 uses the rate selected here",- "ja": "現在の解像度でデバイスが報告するフレームレートだけを表示します。デバイスのフレームレートが 0 のときは、ここで選んだ値で接続します"- },{"zh": "只列出当前分辨率和帧率下的像素格式","src": "qml/DialogHost.qml",@@ -6021,6 +6049,13 @@"en": "Actually running: FSR %1 · 2X","ja": "実際の動作:FSR %1 · 2X"},+ {+ "zh": "实际连接的采集格式与所选模式不同,请刷新并重新选择。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "實際連線的擷取格式與所選模式不同,請重新整理並重新選擇。",+ "en": "The connected capture format differs from the selected mode. Refresh and select again.",+ "ja": "接続されたキャプチャ形式が選択したモードと異なります。更新して選び直してください。"+ },{"zh": "实验","src": "qml/ChainNodeCard.qml",@@ -8093,6 +8128,13 @@"en": "Pick the second available subtitle track automatically when opening a new file","ja": "新しいファイルを開くと 2 番目の字幕を自動で選択"},+ {+ "zh": "打开旧版格式列表",+ "src": "qml/DialogHost.qml",+ "zh-TW": "開啟舊版格式清單",+ "en": "Open legacy format list",+ "ja": "従来の形式一覧を開く"+ },{"zh": "打开时的默认页面","src": "qml/SettingsPage.qml",@@ -8457,6 +8499,13 @@"en": "Search finished; no PS5 found. Make sure it is on the same LAN, or enter the IP by hand.","ja": "検索が完了しましたが、PS5 は見つかりませんでした。同じ LAN にあるか確認するか、IP を手入力してください。"},+ {+ "zh": "搜索,例如:1920 60 NV12",+ "src": "qml/CaptureLegacyPicker.qml",+ "zh-TW": "搜尋,例如:1920 60 NV12",+ "en": "Search, e.g. 1920 60 NV12",+ "ja": "検索例:1920 60 NV12"+ },{"zh": "撤销","src": "qml/ColourPanel.qml",@@ -9074,6 +9123,13 @@"en": "Could not map the export communication resources","ja": "書き出し用の通信リソースをマップできませんでした"},+ {+ "zh": "无法构造所选采集格式,请检查分辨率、帧率与驱动能力。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "無法建立所選擷取格式,請檢查解析度、影格率與驅動能力。",+ "en": "Cannot construct the selected capture format. Check resolution, frame rate and driver capabilities.",+ "ja": "選択したキャプチャ形式を作成できません。解像度、レート、ドライバーの対応能力を確認してください。"+ },{"zh": "无法检测屏幕是否支持(目前只支持 NVIDIA 显卡)","src": "src/ui/QmlPlayerBridge.cpp",@@ -9165,6 +9221,20 @@"en": "日本語","ja": "日本語"},+ {+ "zh": "旧版格式列表",+ "src": "qml/CaptureLegacyPicker.qml",+ "zh-TW": "舊版格式清單",+ "en": "Legacy format list",+ "ja": "従来の形式一覧"+ },+ {+ "zh": "旧版格式选择",+ "src": "qml/DialogHost.qml",+ "zh-TW": "舊版格式選擇",+ "en": "Legacy format selection",+ "ja": "従来の形式選択"+ },{"zh": "旧节点配置的 NR 保护区域已移除;列表保护及其他节点参数保留,后续保存到 .p3-node 文件,原文件不覆盖","src": "src/engine/PresetLibrary.cpp",@@ -9963,13 +10033,6 @@"en": "No cap","ja": "上限なし"},- {- "zh": "未读到设备上报的采集格式,或设备正被其他应用占用。",- "src": "src/ui/QmlPlayerBridge.cpp",- "zh-TW": "未讀到裝置回報的擷取格式,或裝置正被其他應用程式佔用。",- "en": "No capture formats were reported, or the device is in use by another application.",- "ja": "キャプチャ形式が取得できないか、他のアプリがデバイスを使用しています。"- },{"zh": "未输出","src": "qml/NodePage.qml",@@ -10138,6 +10201,13 @@"en": "Checking…","ja": "確認中…"},+ {+ "zh": "检查并选择",+ "src": "qml/DialogHost.qml",+ "zh-TW": "檢查並選擇",+ "en": "Check and select",+ "ja": "確認して選択"+ },{"zh": "检查更新","src": "qml/SettingsPage.qml",@@ -10768,20 +10838,6 @@"en": "This capture card does not offer this format. Choose a supported resolution, frame rate and pixel format.","ja": "このキャプチャカードにこの形式はありません。対応する解像度、フレームレート、ピクセル形式を選び直してください。"},- {- "zh": "此采集卡无此格式,驱动拒绝所选格式(0x{:08X}),请重新选择。",- "src": "src/source/CaptureCardSource.cpp",- "zh-TW": "此擷取卡無此格式,驅動拒絕所選格式(0x{:08X}),請重新選擇。",- "en": "This capture card rejected the selected format (0x{:08X}). Choose another supported format.",- "ja": "キャプチャカードのドライバーが選択形式を拒否しました(0x{:08X})。対応する形式を選び直してください。"- },- {- "zh": "此采集卡无此格式:拒绝 {:.3f} FPS(0x{:08X}),请改用设备支持的帧率,或填 0 沿用所选格式。",- "src": "src/source/CaptureCardSource.cpp",- "zh-TW": "此擷取卡無此格式:拒絕 {:.3f} FPS(0x{:08X}),請改用裝置支援的幀率,或填 0 沿用所選格式。",- "en": "This capture card rejected the requested format at {:.3f} FPS (0x{:08X}). Choose a supported rate, or enter 0 to use the selected format rate.",- "ja": "キャプチャカードが {:.3f} FPS の指定形式を拒否しました(0x{:08X})。対応するレートを選ぶか、0 を入力して選択形式のレートを使用してください。"- },{"zh": "残差","src": "src/ui/QmlPlayerBridge.cpp",@@ -10810,6 +10866,13 @@"en": "Compares the source with the previous frame: pixels without a clear change reuse the previous output; clearly changed areas take the new result directly.","ja": "ソースを前のフレームと比較し、目立った変化のないピクセルは前の出力を使い、変化した部分は新しい結果をそのまま使います。"},+ {+ "zh": "没有匹配的格式",+ "src": "qml/CaptureLegacyPicker.qml",+ "zh-TW": "沒有相符的格式",+ "en": "No matching formats",+ "ja": "一致する形式がありません"+ },{"zh": "没有可保存的画面","src": "src/ui/QmlPlayerBridge.cpp",@@ -11748,6 +11811,13 @@"en": "Open an HTTP, HTTPS or RTSP media stream, such as IPTV or a camera feed.","ja": "IPTV やカメラなどの HTTP、HTTPS、RTSP メディアストリームを開きます。"},+ {+ "zh": "直接查看完整格式列表,包含被常用帧率筛选隐藏的模式",+ "src": "qml/DialogHost.qml",+ "zh-TW": "直接查看完整格式清單,包含被常用影格率篩選隱藏的模式",+ "en": "View the full list, including modes hidden by the common frame rate filter",+ "ja": "一般的なレートのフィルターで隠れるモードも含め、形式の全一覧を表示します"+ },{"zh": "直播兼容模式未能启用,已恢复","src": "src/engine/EngineControllerImage.cpp",@@ -12595,6 +12665,13 @@"en": "Custom cap (FPS)","ja": "カスタム上限(FPS)"},+ {+ "zh": "自定义分辨率",+ "src": "qml/DialogHost.qml",+ "zh-TW": "自訂解析度",+ "en": "Custom resolution",+ "ja": "カスタム解像度"+ },{"zh": "自定义播放速度","src": "qml/PlaybackRateDialog.qml",@@ -13547,13 +13624,6 @@"en": "This node type has reached its limit (including disabled and unconnected nodes)","ja": "この種類のノードは上限に達しています(無効・未接続のノードを含む)"},- {- "zh": "该采集格式不支持设备帧率协商,请将采集帧率设为 0。",- "src": "src/source/CaptureCardSource.cpp",- "zh-TW": "該擷取格式不支援裝置幀率協商,請將擷取幀率設為 0。",- "en": "This capture format does not support frame rate negotiation; set the capture frame rate to 0.",- "ja": "このキャプチャーフォーマットはフレームレートの調整に対応していません。キャプチャーのフレームレートを 0 にしてください。"- },{"zh": "请先切换到要保存的编辑模式","src": "src/ui/QmlPlayerBridge.cpp",@@ -13813,6 +13883,13 @@"en": "Choose an input port to finish the link · Esc to cancel","ja": "入力ポートを選んで接続を完了 · Esc でキャンセル"},+ {+ "zh": "读取协商后的采集格式失败(0x{:08X})。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "讀取協商後的擷取格式失敗(0x{:08X})。",+ "en": "Failed to read the negotiated capture format (0x{:08X}).",+ "ja": "合意されたキャプチャ形式を読み取れませんでした(0x{:08X})。"+ },{"zh": "读取媒体信息失败","src": "src/engine/ExportQueue.cpp",@@ -13834,6 +13911,13 @@"en": "Read source tracks","ja": "ソーストラックの読み取り"},+ {+ "zh": "读取采集格式失败:%1(0x%2)。请检查设备占用与驱动后重试。",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "讀取擷取格式失敗:%1(0x%2)。請檢查裝置占用與驅動後重試。",+ "en": "Failed to read capture formats: %1 (0x%2). Check whether the device is in use and check its driver, then retry.",+ "ja": "キャプチャ形式を読み取れません:%1(0x%2)。デバイスの使用状況とドライバーを確認して再試行してください。"+ },{"zh": "读取附属轨道","src": "src/engine/ExportStreams.cpp",@@ -15010,6 +15094,13 @@"en": "Some tracks do not fit the current container and were not kept (see the queue notes)","ja": "現在のコンテナーに保持できないトラックがあり、保持していません(キューの説明を参照)"},+ {+ "zh": "部分采集能力读取失败(%1,0x%2);当前列表可能不完整,请刷新重试。",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "部分擷取能力讀取失敗(%1,0x%2);目前清單可能不完整,請重新整理再試。",+ "en": "Some capture capabilities could not be read (%1, 0x%2). The list may be incomplete; refresh to retry.",+ "ja": "一部のキャプチャ能力を読み取れませんでした(%1、0x%2)。一覧が不完全な可能性があります。更新して再試行してください。"+ },{"zh": "配对","src": "qml/DialogHost.qml",@@ -15290,6 +15381,13 @@"en": "Capture method","ja": "キャプチャー方式"},+ {+ "zh": "采集格式内存分配失败",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "擷取格式記憶體配置失敗",+ "en": "Capture format memory allocation failed",+ "ja": "キャプチャ形式のメモリを確保できませんでした"+ },{"zh": "采集格式无效","src": "src/source/MagewellCapture.cpp",@@ -15297,6 +15395,20 @@"en": "Invalid capture format","ja": "キャプチャーフォーマットが不正です"},+ {+ "zh": "采集格式无法恢复:{}(0x{:08X}),请刷新并重新选择。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "擷取格式無法還原:{}(0x{:08X}),請重新整理並重新選擇。",+ "en": "Cannot restore capture format: {} (0x{:08X}). Refresh and select again.",+ "ja": "キャプチャ形式を復元できません:{}(0x{:08X})。更新して選び直してください。"+ },+ {+ "zh": "采集格式的能力记录已失效,请刷新后重试。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "擷取格式的能力記錄已失效,請重新整理後再試。",+ "en": "The capture capability record is no longer valid. Refresh and retry.",+ "ja": "キャプチャ能力の記録が無効です。更新して再試行してください。"+ },{"zh": "采集没有开始","src": "src/ui/QmlPlayerBridge.cpp",@@ -16557,6 +16669,27 @@"en": "Home = the page for choosing a source (clicking the logo at the top also returns here)","ja": "ホーム = ソースを選ぶ画面(上部のロゴをクリックしても戻れます)"},+ {+ "zh": "驱动拒绝所选采集格式(0x{:08X}),请重新选择。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "驅動拒絕所選擷取格式(0x{:08X}),請重新選擇。",+ "en": "The driver rejected the selected capture format (0x{:08X}). Select another mode.",+ "ja": "ドライバーが選択したキャプチャ形式を拒否しました(0x{:08X})。選び直してください。"+ },+ {+ "zh": "驱动未提供可解析的视频格式,请检查设备与驱动后刷新。",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "驅動未提供可解析的視訊格式,請檢查裝置與驅動後重新整理。",+ "en": "The driver provided no readable video formats. Check the device and driver, then refresh.",+ "ja": "ドライバーから読み取れる映像形式が取得できません。デバイスとドライバーを確認して更新してください。"+ },+ {+ "zh": "驱动未提供该分辨率,或尺寸不符合步进要求;原选择已保留。",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "驅動未提供該解析度,或尺寸不符合步進要求;原選擇已保留。",+ "en": "The driver does not offer this resolution, or its size violates granularity. The previous selection was kept.",+ "ja": "ドライバーがこの解像度に対応していないか、サイズが刻みに合いません。以前の選択を保持しました。"+ },{"zh": "驱动没有公开此设置页。Blackmagic 请用 Desktop Video Setup 选择 HDMI/SDI,并在采集面板匹配分辨率、帧率和逐行/隔行制式。","src": "src/source/CaptureCardSource.cpp",@@ -16585,6 +16718,13 @@"en": "Cannot open driver settings (0x{:08X}).","ja": "ドライバー設定を開けません(0x{:08X})。"},+ {+ "zh": "驱动返回的分辨率、帧率、像素格式或扫描方式与所选模式不同,请重新选择。",+ "src": "src/source/CaptureCardSource.cpp",+ "zh-TW": "驅動傳回的解析度、影格率、像素格式或掃描方式與所選模式不同,請重新選擇。",+ "en": "The driver returned a different resolution, frame rate, pixel format or scan mode. Select again.",+ "ja": "ドライバーが返した解像度、レート、ピクセル形式、または走査方式が選択と異なります。選び直してください。"+ },{"zh": "驱动默认","src": "qml/DialogHost.qml",diff --git a/include/veyra/source/CaptureCapabilityRange.h b/include/veyra/source/CaptureCapabilityRange.hnew file mode 100644index 00000000..015a8bdb--- /dev/null+++ b/include/veyra/source/CaptureCapabilityRange.h@@ -0,0 +1,87 @@+#pragma once+#include "veyra/source/CaptureFrameRate.h"+#include <algorithm>+#include <charconv>+#include <limits>+#include <span>+#include <string_view>+#include <utility>+#include <vector>++namespace veyra::source {+struct CaptureModeHint { unsigned width=0,height=0;int64_t interval=0; };+inline bool captureUnsigned(std::wstring_view text,unsigned& value){+ if(text.empty()||text.size()>6)return false;+ unsigned result=0;+ for(wchar_t c:text){if(c<L'0'||c>L'9')return false;result=result*10+unsigned(c-L'0');}+ value=result;return result>0&&result<=16384;+}+inline CaptureModeHint captureResolutionHint(std::wstring_view text){+ CaptureModeHint hint;const auto separator=text.find_first_of(L"xX×");+ if(separator==text.npos||!captureUnsigned(text.substr(0,separator),hint.width)||+ !captureUnsigned(text.substr(separator+1),hint.height))return {};+ return hint;+}+inline CaptureModeHint captureKeyHint(std::wstring_view key){+ const auto first=key.find(L':');if(first==key.npos)return {};+ const auto second=key.find(L':',first+1);if(second==key.npos)return {};+ auto height=key.substr(first+1,second-first-1);if(height.starts_with(L"-"))height.remove_prefix(1);+ CaptureModeHint hint;+ if(!captureUnsigned(key.substr(0,first),hint.width)||!captureUnsigned(height,hint.height))return {};+ const auto end=key.find(L':',second+1);if(end==key.npos||end-second>15)return {};+ for(wchar_t c:key.substr(second+1,end-second-1)){+ if(c<L'0'||c>L'9')return {};+ hint.interval=hint.interval*10+(c-L'0');+ }+ if(hint.interval>10000000000LL)return {};+ return hint;+}+struct CaptureCapabilityRange {+ unsigned minWidth=0,maxWidth=0,minHeight=0,maxHeight=0,stepX=1,stepY=1;+ int64_t minInterval=0,maxInterval=0;+ bool validSize()const{return minWidth&&minHeight&&maxWidth>=minWidth&&maxHeight>=minHeight&&maxWidth<=16384&&maxHeight<=16384;}+ bool acceptsSize(unsigned width,unsigned height)const{+ return validSize()&&width>=minWidth&&width<=maxWidth&&height>=minHeight&&height<=maxHeight&&+ (width-minWidth)%std::max(1u,stepX)==0&&(height-minHeight)%std::max(1u,stepY)==0;+ }+ bool validRate()const{return minInterval>0&&maxInterval>=minInterval;}+ bool acceptsInterval(int64_t value)const{return validRate()&&value>=minInterval&&value<=maxInterval;}+};+inline std::vector<std::pair<unsigned,unsigned>> captureCandidateSizes(const CaptureCapabilityRange& range,+ unsigned width,unsigned height,std::span<const CaptureModeHint> hints={}){+ std::vector<std::pair<unsigned,unsigned>> out;+ const auto add=[&](unsigned w,unsigned h){const auto size=std::pair{w,h};+ if(w&&h&&w<=16384&&h<=16384&&std::find(out.begin(),out.end(),size)==out.end())out.push_back(size);};+ add(width,height); // the original advertised type always remains a candidate+ if(range.validSize()){+ add(range.minWidth,range.minHeight);+ const auto maxWidth=range.minWidth+(range.maxWidth-range.minWidth)/std::max(1u,range.stepX)*std::max(1u,range.stepX);+ const auto maxHeight=range.minHeight+(range.maxHeight-range.minHeight)/std::max(1u,range.stepY)*std::max(1u,range.stepY);+ add(maxWidth,maxHeight);+ static constexpr std::pair<unsigned,unsigned> common[]={{640,480},{720,480},{720,576},{1280,720},{1920,1080},{2560,1440},{3840,2160},{4096,2160}};+ for(auto [w,h]:common)if(range.acceptsSize(w,h))add(w,h);+ for(const auto& hint:hints)if(range.acceptsSize(hint.width,hint.height))add(hint.width,hint.height);+ }+ return out;+}+inline std::vector<int64_t> captureCandidateIntervals(int64_t advertised,std::span<const int64_t> discrete,+ const CaptureCapabilityRange& range,std::span<const CaptureModeHint> hints={}){+ std::vector<int64_t> out;+ const auto add=[&](int64_t value){if(value>=0&&std::find(out.begin(),out.end(),value)==out.end())out.push_back(value);};+ add(advertised);+ for(auto value:discrete)if(value>0)add(value);+ if(range.validRate()){+ add(range.minInterval);add(range.maxInterval);+ static constexpr double common[]{1,2,3,4,5,10,15,20,24,25,30,40,48,50,60,90,100,120,144,165,180,200,240,360,480,960};+ for(double fps:common)for(double divisor:{1.,1001./1000.}){+ auto value=captureFrameInterval(fps/divisor);+ // Integer endpoint rounding, never a percentage-based NTSC merge.+ if(value+1==range.minInterval)value=range.minInterval;+ if(value-1==range.maxInterval)value=range.maxInterval;+ if(range.acceptsInterval(value))add(value);+ }+ for(const auto& hint:hints)if(range.acceptsInterval(hint.interval))add(hint.interval);+ }+ return out;+}+}diff --git a/include/veyra/source/CaptureCardSource.h b/include/veyra/source/CaptureCardSource.hindex fe39c7cc..d5f40e64 100644--- a/include/veyra/source/CaptureCardSource.h+++ b/include/veyra/source/CaptureCardSource.h@@ -26,6 +26,12 @@ struct CaptureMetrics {double callbackFps=0, readAgeMs=0, frameAgeMs=0;bool sampledBlack=false; // Sparse source pixels, not input signal detection.};+struct CaptureFormatQueryInfo {+ long code=0;+ std::wstring stage;+ size_t advertised=0,rejected=0;+ bool partial=false,fallback=false;+};class CaptureCardSource final:public IFrameSource {public:CaptureCardSource();~CaptureCardSource()override;@@ -34,7 +40,8 @@ public:static std::wstring makeCapturePath(unsigned videoIndex,const CaptureDevice& video,int format,int audioMode,const CaptureDevice* audio,unsigned colorOverride=0,double requestedFps=0,std::wstring_view formatKey={});static std::vector<CaptureFormat> formats(unsigned device);- static std::vector<CaptureFormat> formatsByPath(std::wstring_view devicePath);+ static std::vector<CaptureFormat> formatsByPath(std::wstring_view devicePath,CaptureFormatQueryInfo* query=nullptr,+ std::wstring_view preferredKey={},std::wstring_view requestedResolution={});// Explicit user action on the UI COM apartment; no Run or auto-routing.static bool showDeviceProperties(std::wstring_view devicePath,uintptr_t owner,bool inputSelector,std::wstring& error,std::wstring* changedFormatKey=nullptr);bool open(const SourceOpenDesc&)override;diff --git a/include/veyra/source/CaptureFormatSelection.h b/include/veyra/source/CaptureFormatSelection.hindex 4d5c91a1..1e2c581a 100644--- a/include/veyra/source/CaptureFormatSelection.h+++ b/include/veyra/source/CaptureFormatSelection.h@@ -6,13 +6,15 @@#include <format>#include <iterator>#include <span>+#include <unordered_map>+#include <unordered_set>#include <vector>namespace veyra::source {// `pixel` / `scan` / `interlaced` describe the same media type as `key`.// The capture dialog offers them as three linked choices; `key` stays the// persisted identity so an old combined selection still restores one type.-struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;std::wstring key;int rank=0;int tier=0;bool driverCurrent=false;std::wstring pixel;std::wstring scan;bool interlaced=false;int64_t interval100ns=0;bool supported=true;bool automatic=false;};+struct CaptureFormat {int index=0;unsigned width=0,height=0;double fps=0;std::wstring label;std::wstring key;int rank=0;int tier=0;bool driverCurrent=false;std::wstring pixel;std::wstring scan;bool interlaced=false;int64_t interval100ns=0;bool supported=true;bool automatic=false;int capability=-1;bool rangeCandidate=false;};enum class CaptureFormatAxis { Resolution, FrameRate };// Frame-rate rows also carry the rate itself and whether it is a common one (see// captureVisibleFrameRates); the other menus leave those fields at their defaults.@@ -52,15 +54,30 @@ inline std::wstring captureFrameRateId(const CaptureFormat& format){// Field order stays on the pixel list, so it does not create two identical fps rows.return std::format(L"{}|{}",format.interval100ns>0?format.interval100ns:format.fps>0?captureFrameInterval(format.fps):0,format.interlaced?1:0);}+// Display groups absorb only integer 100ns rounding around standard rates.+// The exact interval and media key above remain untouched for negotiation.+inline std::wstring captureFrameRateGroupId(const CaptureFormat& format){+ if(format.automatic)return L"auto";+ const auto interval=format.interval100ns>0?format.interval100ns:captureFrameInterval(format.fps);+ static constexpr double rates[]{1,2,3,4,5,10,15,20,24,25,30,40,48,50,60,90,100,120,144,165,180,200,240,360,480,960};+ for(double rate:rates)for(double divisor:{1.,1001./1000.}){+ const auto standard=captureFrameInterval(rate/divisor);+ if(interval>0&&std::abs(interval-standard)<=1)+ return std::format(L"{}|{}",standard,format.interlaced?1:0);+ }+ return captureFrameRateId(format);+}inline const CaptureFormat* captureRateSample(std::span<const CaptureFormat> formats,std::wstring_view resolution,std::wstring_view rate){if(resolution.empty()||rate.empty())return nullptr;for(const auto& f:formats)if(captureResolutionId(f)==resolution&&captureFrameRateId(f)==rate)return &f;+ for(const auto& f:formats)if(captureResolutionId(f)==resolution&&captureFrameRateGroupId(f)==rate)return &f;return nullptr;}inline const CaptureFormat* selectCapturePixelFormat(std::span<const CaptureFormat> formats,std::wstring_view resolution,std::wstring_view rate,std::wstring_view key){if(key.empty())return nullptr;const auto* f=selectCaptureFormat(formats,-1,key);- return f&&!resolution.empty()&&!rate.empty()&&captureResolutionId(*f)==resolution&&captureFrameRateId(*f)==rate?f:nullptr;+ const auto* sample=captureRateSample(formats,resolution,rate);+ return f&&sample&&captureResolutionId(*f)==resolution&&captureFrameRateGroupId(*f)==captureFrameRateGroupId(*sample)?f:nullptr;}inline bool captureMjpegFormat(const CaptureFormat& format){std::wstring pixel=format.pixel;@@ -89,7 +106,7 @@ inline std::wstring capturePixelLabel(const CaptureFormat& format,bool ambiguousstd::wstring label=format.pixel.empty()?L"未知格式":format.pixel;if(ambiguous){if(!format.scan.empty())label+=L" · "+format.scan;- label+=std::format(L" [format {}]",format.index);+ label+=std::format(L" [format {}] · {} x100ns",format.index,format.interval100ns);}if(format.driverCurrent)label+=L" · 驱动默认";if(!format.supported)label+=L" · 当前播放器不支持";@@ -97,21 +114,23 @@ inline std::wstring capturePixelLabel(const CaptureFormat& format,bool ambiguous}inline std::vector<CaptureFormatOption> captureResolutionOptions(std::span<const CaptureFormat> formats){std::vector<CaptureFormatOption> out;+ std::unordered_set<std::wstring> seen;for(const auto& format:formats){const auto id=captureResolutionId(format);- if(std::any_of(out.begin(),out.end(),[&](const CaptureFormatOption& option){return option.id==id;}))continue;+ if(!seen.insert(id).second)continue;out.push_back({id,captureResolutionLabel(format)});}return out;}inline std::vector<CaptureFormatOption> captureFrameRateOptions(std::span<const CaptureFormat> formats,const CaptureFormat* current){std::vector<CaptureFormatOption> out;+ std::unordered_set<std::wstring> seen;if(!current)return out;const auto resolution=captureResolutionId(*current);for(const auto& format:formats){if(captureResolutionId(format)!=resolution)continue;- const auto id=captureFrameRateId(format);- if(std::any_of(out.begin(),out.end(),[&](const CaptureFormatOption& option){return option.id==id;}))continue;+ const auto id=captureFrameRateGroupId(format);+ if(!seen.insert(id).second)continue;auto label=captureFrameRateLabel(format);if(std::any_of(out.begin(),out.end(),[&](const CaptureFormatOption& option){return option.label==label;}))label+=std::format(L" [format {}]",format.index);@@ -129,12 +148,9 @@ inline std::vector<CaptureFormatOption> captureVisibleFrameRates(const std::vectstd::vector<CaptureFormatOption> shown;if(std::none_of(all.begin(),all.end(),[](const CaptureFormatOption& option){return option.common;}))shown=all;else{- std::vector<std::pair<long long,bool>> rates;for(const auto& option:all){- const std::pair<long long,bool> rate{std::llround(option.fps*1000),option.interlaced};- const bool repeat=std::find(rates.begin(),rates.end(),rate)!=rates.end();- if(option.id!=selected&&(!option.common||repeat))continue;- shown.push_back(option);if(option.common)rates.push_back(rate);+ if(option.id!=selected&&!option.common)continue;+ shown.push_back(option);}if(hidden)*hidden=all.size()-shown.size();if(showAll)shown=all;@@ -161,15 +177,15 @@ inline std::vector<CaptureFormatOption> capturePixelOptions(std::span<const Captstd::vector<CaptureFormatOption> out;if(!current)return out;const auto resolution=captureResolutionId(*current);- const auto rate=captureFrameRateId(*current);+ const auto rate=captureFrameRateGroupId(*current);std::vector<const CaptureFormat*> matched;+ std::unordered_map<std::wstring,int> copies;+ std::unordered_set<std::wstring> seen;for(const auto& format:formats)- if(captureResolutionId(format)==resolution&&captureFrameRateId(format)==rate)matched.push_back(&format);+ if(captureResolutionId(format)==resolution&&captureFrameRateGroupId(format)==rate){matched.push_back(&format);++copies[format.pixel];}for(const auto* format:matched){- int copies=0;- for(const auto* other:matched)if(other->pixel==format->pixel)++copies;- if(std::any_of(out.begin(),out.end(),[&](const CaptureFormatOption& option){return option.id==format->key;}))continue;- out.push_back({format->key,capturePixelLabel(*format,copies>1),!format->supported,captureMjpegFormat(*format)});+ if(!seen.insert(format->key).second)continue;+ out.push_back({format->key,capturePixelLabel(*format,copies[format->pixel]>1),!format->supported,captureMjpegFormat(*format)});}return out;}@@ -180,18 +196,18 @@ inline std::vector<CaptureFormatOption> capturePixelOptions(std::span<const Captinline const CaptureFormat* retargetCaptureFormat(std::span<const CaptureFormat> formats,const CaptureFormat* current,CaptureFormatAxis axis,std::wstring_view id){if(id.empty()||(axis==CaptureFormatAxis::FrameRate&&!current))return nullptr;const auto resolution=current?captureResolutionId(*current):std::wstring{};- const auto rate=current?captureFrameRateId(*current):std::wstring{};+ const auto rate=current?captureFrameRateGroupId(*current):std::wstring{};const auto pixel=current?current->pixel:std::wstring{};const CaptureFormat* fallback=nullptr;const CaptureFormat* samePixel=nullptr;const CaptureFormat* sameBoth=nullptr;for(const auto& format:formats){const bool match=axis==CaptureFormatAxis::Resolution?captureResolutionId(format)==id- :captureResolutionId(format)==resolution&&captureFrameRateId(format)==id;+ :captureResolutionId(format)==resolution&&(captureFrameRateId(format)==id||captureFrameRateGroupId(format)==id);if(!match)continue;if(!fallback)fallback=&format;if(!current)continue;- const bool rateMatch=captureFrameRateId(format)==rate;+ const bool rateMatch=captureFrameRateGroupId(format)==rate;const bool pixelMatch=!pixel.empty()&&format.pixel==pixel;if(rateMatch&&pixelMatch){if(!sameBoth)sameBoth=&format;}else if(pixelMatch){if(!samePixel)samePixel=&format;}diff --git a/include/veyra/source/CaptureFrameIntervals.h b/include/veyra/source/CaptureFrameIntervals.hindex 4349e79b..156c54bb 100644--- a/include/veyra/source/CaptureFrameIntervals.h+++ b/include/veyra/source/CaptureFrameIntervals.h@@ -5,8 +5,9 @@#include <vector>namespace veyra::source {-// The driver owns this discrete list. A min/max interval range is not a list-// of supported standard frame rates; never expand it using a preset table.+// This function reads only the driver's discrete list. Range-derived rates+// live separately in CaptureCapabilityRange, are labelled as candidates,+// and require exact connection validation; they are not discrete guarantees.inline std::vector<REFERENCE_TIME> captureFrameIntervals(IAMVideoControl* control, IPin* pin,int index, SIZE dimensions, REFERENCE_TIME advertised, HRESULT* queryResult=nullptr) {std::vector<REFERENCE_TIME> out{advertised};diff --git a/include/veyra/source/DirectShowFormatDiscovery.h b/include/veyra/source/DirectShowFormatDiscovery.hnew file mode 100644index 00000000..232bf518--- /dev/null+++ b/include/veyra/source/DirectShowFormatDiscovery.h@@ -0,0 +1,175 @@+#pragma once+// Capability-only compatibility informed by OBS 32.2.2's libdshowcapture+// 8878638324393815512f802640b0d5ce940161f1, dshow-enum.cpp / dshow-base.cpp.+// Independent implementation: no OBS capture, buffering or rendering code.+#include "veyra/source/CaptureCapabilityRange.h"+#include "veyra/source/CapturePixelFormat.h"+#include <dvdmedia.h>+#include <ks.h>+#include <ksproxy.h>+#include <wrl/client.h>+#include <cstring>+#include <memory>++namespace veyra::source::dshow {+using Microsoft::WRL::ComPtr;+using OwnedCaptureType=std::shared_ptr<AM_MEDIA_TYPE>;+inline void destroyCaptureType(AM_MEDIA_TYPE* type){+ if(!type)return;+ CoTaskMemFree(type->pbFormat);if(type->pUnk)type->pUnk->Release();CoTaskMemFree(type);+}+inline OwnedCaptureType ownCaptureType(AM_MEDIA_TYPE* type){return {type,destroyCaptureType};}+inline OwnedCaptureType cloneCaptureType(const AM_MEDIA_TYPE& type){+ if(type.cbFormat>1024*1024||(type.cbFormat&&!type.pbFormat))return {};+ auto* copy=static_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));if(!copy)return {};+ *copy=type;copy->pbFormat=nullptr;copy->pUnk=nullptr;+ if(type.cbFormat){copy->pbFormat=static_cast<BYTE*>(CoTaskMemAlloc(type.cbFormat));+ if(!copy->pbFormat){CoTaskMemFree(copy);return {};}std::memcpy(copy->pbFormat,type.pbFormat,type.cbFormat);}+ copy->pUnk=type.pUnk;if(copy->pUnk)copy->pUnk->AddRef();return ownCaptureType(copy);+}+struct CaptureVideoHeader {BITMAPINFOHEADER* bitmap=nullptr;REFERENCE_TIME* interval=nullptr;DWORD scan=0;};+inline CaptureVideoHeader captureVideoHeader(AM_MEDIA_TYPE& type){+ if(type.majortype!=MEDIATYPE_Video||!type.pbFormat||type.cbFormat>1024*1024)return {};+ if(type.formattype==FORMAT_VideoInfo&&type.cbFormat>=sizeof(VIDEOINFOHEADER)){+ auto* header=reinterpret_cast<VIDEOINFOHEADER*>(type.pbFormat);return {&header->bmiHeader,&header->AvgTimePerFrame,0};}+ if(type.formattype==FORMAT_VideoInfo2&&type.cbFormat>=sizeof(VIDEOINFOHEADER2)){+ auto* header=reinterpret_cast<VIDEOINFOHEADER2*>(type.pbFormat);return {&header->bmiHeader,&header->AvgTimePerFrame,header->dwInterlaceFlags};}+ return {};+}+inline bool capturePinHasVideo(IPin* pin){+ ComPtr<IAMStreamConfig> config;+ if(SUCCEEDED(pin->QueryInterface(IID_PPV_ARGS(&config)))){+ AM_MEDIA_TYPE* raw=nullptr;const auto hr=config->GetFormat(&raw);auto current=ownCaptureType(raw);+ if(SUCCEEDED(hr)&¤t&¤t->majortype==MEDIATYPE_Video)return true;+ int count=0,size=0;+ if(SUCCEEDED(config->GetNumberOfCapabilities(&count,&size))&&count>0&&count<=65536&&size>0&&size<=65536){+ std::vector<BYTE> bytes(size);+ for(int i=0;i<count;++i){raw=nullptr;const auto result=config->GetStreamCaps(i,&raw,bytes.data());auto type=ownCaptureType(raw);+ if(SUCCEEDED(result)&&type&&type->majortype==MEDIATYPE_Video)return true;}+ }+ }+ ComPtr<IEnumMediaTypes> types;+ if(FAILED(pin->EnumMediaTypes(&types)))return false;+ for(unsigned i=0;i<65536;++i){AM_MEDIA_TYPE* raw=nullptr;const auto hr=types->Next(1,&raw,nullptr);auto type=ownCaptureType(raw);+ if(hr!=S_OK)return false;if(type&&type->majortype==MEDIATYPE_Video)return true;}+ return false;+}+inline HRESULT findCaptureVideoPin(IBaseFilter* filter,ComPtr<IPin>& result){+ result.Reset();if(!filter)return E_POINTER;ComPtr<IEnumPins> pins;auto hr=filter->EnumPins(&pins);if(FAILED(hr))return hr;+ ComPtr<IPin> fallback;unsigned fallbackCount=0;+ for(unsigned i=0;i<65536;++i){ComPtr<IPin> pin;hr=pins->Next(1,&pin,nullptr);if(hr!=S_OK)break;+ PIN_DIRECTION direction{};if(FAILED(pin->QueryDirection(&direction))||direction!=PINDIR_OUTPUT||!capturePinHasVideo(pin.Get()))continue;+ ComPtr<IKsPropertySet> properties;GUID category{};DWORD bytes=0;+ hr=pin.As(&properties);+ if(SUCCEEDED(hr))hr=properties->Get(AMPROPSETID_Pin,AMPROPERTY_PIN_CATEGORY,nullptr,0,&category,sizeof(category),&bytes);+ if(SUCCEEDED(hr)&&bytes==sizeof(category)){if(category==PIN_CATEGORY_CAPTURE){result=pin;return S_OK;}continue;}+ if(hr==E_NOINTERFACE||hr==E_NOTIMPL||hr==HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)||+ hr==E_PROP_ID_UNSUPPORTED||hr==E_PROP_SET_UNSUPPORTED){+ fallback=pin;++fallbackCount;+ }+ }+ if(fallbackCount==1){result=fallback;return S_OK;}+ return fallbackCount>1?E_UNEXPECTED:VFW_E_NOT_FOUND;+}+enum class CaptureTypeOrigin { StreamCaps, MediaTypes };+struct CaptureNativeCapability {+ OwnedCaptureType media;+ CaptureCapabilityRange range;+ int nativeIndex=0;+ CaptureTypeOrigin origin=CaptureTypeOrigin::StreamCaps;+};+struct CaptureNativeCapabilities {+ std::vector<CaptureNativeCapability> types;+ HRESULT result=S_OK;+ const wchar_t* stage=L"GetStreamCaps";+ unsigned advertised=0,rejected=0,failed=0;+ bool fallback=false;+};+inline CaptureNativeCapabilities discoverCaptureTypes(IAMStreamConfig* config,IPin* pin){+ CaptureNativeCapabilities found;+ if(!config){found.result=E_NOINTERFACE;found.stage=L"IAMStreamConfig";return found;}+ int count=0,size=0;auto hr=config->GetNumberOfCapabilities(&count,&size);+ if(SUCCEEDED(hr)&&(count<0||count>65536||size<0||size>65536||(count>0&&size<1))){found.result=E_INVALIDARG;found.stage=L"GetNumberOfCapabilities";return found;}+ if(FAILED(hr)&&hr!=E_NOTIMPL&&hr!=E_NOINTERFACE){found.result=hr;found.stage=L"GetNumberOfCapabilities";return found;}+ if(SUCCEEDED(hr)){+ std::vector<BYTE> bytes(size);size_t allocated=0;+ for(int i=0;i<count;++i){+ AM_MEDIA_TYPE* raw=nullptr;std::fill(bytes.begin(),bytes.end(),0);+ const auto result=config->GetStreamCaps(i,&raw,bytes.data());auto media=ownCaptureType(raw);++found.advertised;+ if(FAILED(result)||!media){++found.failed;found.result=FAILED(result)?result:E_POINTER;continue;}+ const auto header=captureVideoHeader(*media);+ if(!header.bitmap){++found.rejected;continue;}+ allocated+=media->cbFormat;+ if(allocated>64*1024*1024){found.result=E_OUTOFMEMORY;++found.failed;break;}+ CaptureCapabilityRange range;+ if(bytes.size()>=sizeof(VIDEO_STREAM_CONFIG_CAPS)){+ VIDEO_STREAM_CONFIG_CAPS caps{};std::memcpy(&caps,bytes.data(),sizeof(caps));+ if(caps.MinOutputSize.cx>0&&caps.MaxOutputSize.cx>0&&caps.MinOutputSize.cy>0&&caps.MaxOutputSize.cy>0){+ range.minWidth=unsigned(caps.MinOutputSize.cx);range.maxWidth=unsigned(caps.MaxOutputSize.cx);+ range.minHeight=unsigned(caps.MinOutputSize.cy);range.maxHeight=unsigned(caps.MaxOutputSize.cy);+ range.stepX=unsigned(std::max(1,caps.OutputGranularityX));range.stepY=unsigned(std::max(1,caps.OutputGranularityY));+ }+ range.minInterval=caps.MinFrameInterval;range.maxInterval=caps.MaxFrameInterval;+ }+ found.types.push_back({std::move(media),range,i,CaptureTypeOrigin::StreamCaps});+ }+ }+ // Explicitly unsupported/empty capability lists and entirely unusable lists.+ // Access denied/device-busy failures above do not become fictitious success.+ if(found.types.empty()&&pin){+ const auto previousStage=found.stage;const auto previousFailures=found.failed;+ found.fallback=true;found.stage=L"EnumMediaTypes";ComPtr<IEnumMediaTypes> enumerator;+ hr=pin->EnumMediaTypes(&enumerator);+ if(FAILED(hr)){found.result=hr;return found;}+ size_t allocated=0;+ int i=0;+ for(;i<65536;++i){AM_MEDIA_TYPE* raw=nullptr;hr=enumerator->Next(1,&raw,nullptr);auto media=ownCaptureType(raw);+ if(hr==S_FALSE)break;+ if(FAILED(hr)||!media){found.result=FAILED(hr)?hr:E_POINTER;++found.failed;break;}+ ++found.advertised;+ if(!captureVideoHeader(*media).bitmap){++found.rejected;continue;}+ allocated+=media->cbFormat;if(allocated>64*1024*1024){found.result=E_OUTOFMEMORY;++found.failed;break;}+ found.types.push_back({std::move(media),{},i,CaptureTypeOrigin::MediaTypes});+ }+ if(i==65536){found.result=HRESULT_FROM_WIN32(ERROR_MORE_DATA);++found.failed;}+ if(previousFailures&&found.failed==previousFailures)found.stage=previousStage;+ }+ if(!found.failed)found.result=S_OK;+ return found;+}+inline OwnedCaptureType captureTypeForMode(const CaptureNativeCapability& capability,unsigned width,unsigned height,int64_t interval){+ auto result=cloneCaptureType(*capability.media);if(!result)return {};+ auto header=captureVideoHeader(*result);if(!header.bitmap||!width||!height||width>16384||height>16384||interval<0)return {};+ auto& bitmap=*header.bitmap;+ const auto oldHeight=std::abs(int64_t(bitmap.biHeight));+ if(unsigned(bitmap.biWidth)!=width||oldHeight!=height){+ if(!capability.range.acceptsSize(width,height))return {};+ bitmap.biWidth=LONG(width);bitmap.biHeight=bitmap.biHeight<0?-LONG(height):LONG(height);+ const auto packing=capturePacking(result->subtype);uint64_t bytes=0;+ switch(packing){+ case CapturePacking::Nv12:case CapturePacking::Nv21:case CapturePacking::I420:case CapturePacking::Yv12:+ if(width%2||height%2)return {};bytes=uint64_t(width)*height*3/2;break;+ case CapturePacking::P010:case CapturePacking::P016:+ if(width%2||height%2)return {};bytes=uint64_t(width)*height*3;break;+ case CapturePacking::Yuy2:case CapturePacking::Uyvy:case CapturePacking::Yvyu:+ if(width%2)return {};bytes=uint64_t(width)*height*2;break;+ case CapturePacking::V210:bytes=uint64_t((width+47)/48)*128*height;break;+ case CapturePacking::Rgb10xLE:bytes=uint64_t(width)*height*4;break;+ case CapturePacking::Unknown:bytes=0;break;+ default:bytes=((uint64_t(width)*bitmap.biBitCount+31)/32)*4*height;break;+ }+ if(bytes>std::numeric_limits<DWORD>::max())return {};+ bitmap.biSizeImage=DWORD(bytes);result->lSampleSize=ULONG(bytes);+ if(result->formattype==FORMAT_VideoInfo){auto* info=reinterpret_cast<VIDEOINFOHEADER*>(result->pbFormat);info->rcSource={};info->rcTarget={};}+ else {auto* info=reinterpret_cast<VIDEOINFOHEADER2*>(result->pbFormat);info->rcSource={};info->rcTarget={};info->dwPictAspectRatioX=width;info->dwPictAspectRatioY=height;}+ }+ *header.interval=interval;return result;+}+inline bool captureTypesMatch(const AM_MEDIA_TYPE& requested,const AM_MEDIA_TYPE& actual){+ auto wanted=captureVideoHeader(const_cast<AM_MEDIA_TYPE&>(requested));+ auto got=captureVideoHeader(const_cast<AM_MEDIA_TYPE&>(actual));+ return wanted.bitmap&&got.bitmap&&requested.subtype==actual.subtype&&+ wanted.bitmap->biWidth==got.bitmap->biWidth&&std::abs(int64_t(wanted.bitmap->biHeight))==std::abs(int64_t(got.bitmap->biHeight))&&+ wanted.scan==got.scan&&(*wanted.interval<=0||(*got.interval>0&&std::abs(*wanted.interval-*got.interval)<=1));+}+}diff --git a/qml/Veyra/CaptureLegacyPicker.qml b/qml/Veyra/CaptureLegacyPicker.qmlnew file mode 100644index 00000000..d78eeea8--- /dev/null+++ b/qml/Veyra/CaptureLegacyPicker.qml@@ -0,0 +1,87 @@+import QtQuick+import QtQuick.Controls+import QtQuick.Layouts++Popup {+ id: picker+ objectName: "capture-legacy-picker"+ property var formats: []+ property string selectedKey: ""+ property var filtered: []+ signal selected(string key)+ parent: Overlay.overlay+ modal: true+ focus: true+ width: Math.min(760, Math.max(1, parent ? parent.width - 32 : 640))+ height: Math.min(560, Math.max(1, parent ? parent.height - 32 : 480))+ x: parent ? Math.round((parent.width - width) / 2) : 0+ y: parent ? Math.round((parent.height - height) / 2) : 0+ padding: 18+ closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside+ background: Rectangle { readonly property bool videoCover: picker.visible; readonly property real coverRadius: 14; color: Theme.bgOuter; radius: 14; border.color: Theme.stroke }++ function applySearch() {+ const words = search.text.toLowerCase().trim().split(/\s+/).filter(w => w.length)+ const snapshot = formats+ filtered = words.length ? snapshot.filter(f => {+ const label = f.label.toLowerCase()+ return words.every(w => label.indexOf(w) >= 0)+ }) : snapshot+ }+ onFormatsChanged: if (visible) applySearch()+ onOpened: { search.text = ""; applySearch(); search.forceActiveFocus() }+ onClosed: filtered = []+ Timer { id: searchDelay; interval: 150; onTriggered: picker.applySearch() }++ contentItem: ColumnLayout {+ spacing: 10+ RowLayout {+ Layout.fillWidth: true+ Text { Layout.fillWidth: true; text: qsTr("旧版格式列表"); color: Theme.t1; font.family: Theme.fontUi; font.pixelSize: 16; font.bold: true }+ VButton { text: qsTr("关闭"); ghost: true; onClicked: picker.close() }+ }+ Text {+ Layout.fillWidth: true+ text: qsTr("分辨率、帧率和像素格式合并显示;包含非常用帧率,与主界面共用同一个精确选择。范围候选将在连接时验证。")+ color: Theme.t3; font.family: Theme.fontUi; font.pixelSize: 11; wrapMode: Text.WordWrap+ }+ TextField {+ id: search+ objectName: "capture-legacy-search"+ Layout.fillWidth: true+ placeholderText: qsTr("搜索,例如:1920 60 NV12")+ color: Theme.t1; placeholderTextColor: Theme.t3+ font.family: Theme.fontUi; font.pixelSize: 12+ background: Rectangle { color: Qt.rgba(1,1,1,.05); radius: 8; border.color: Theme.stroke }+ onTextEdited: searchDelay.restart()+ }+ Text { text: qsTr("%1 / %2 个格式").arg(picker.filtered.length).arg(picker.formats.length); color: Theme.t3; font.pixelSize: 11 }+ ListView {+ id: list+ objectName: "capture-legacy-list"+ Layout.fillWidth: true; Layout.fillHeight: true+ clip: true+ model: picker.filtered+ reuseItems: true+ ScrollBar.vertical: ScrollBar {}+ delegate: ItemDelegate {+ required property var modelData+ width: list.width+ height: 46+ enabled: modelData.disabled !== true+ highlighted: modelData.id === picker.selectedKey+ contentItem: Text {+ text: modelData.label+ color: modelData.disabled ? Theme.t3 : modelData.costHint ? Theme.warn : Theme.t1+ font.family: Theme.fontMono; font.pixelSize: 11+ elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter+ }+ background: Rectangle { radius: 6; color: parent.highlighted ? Qt.rgba(1,1,1,.1) : parent.hovered ? Qt.rgba(1,1,1,.05) : "transparent" }+ ToolTip.visible: hovered+ ToolTip.text: modelData.label+ onClicked: { picker.selected(modelData.id); picker.close() }+ }+ Text { anchors.centerIn: parent; visible: list.count === 0; text: qsTr("没有匹配的格式"); color: Theme.t3; font.pixelSize: 12 }+ }+ }+}diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex 928a2a00..9c2eba04 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -20,6 +20,7 @@ Item {// Which dialog is showing: "" | capture | ps5 | moonlight | xbox | screen | subtitle | audioproperty string dialog: ""+ onDialogChanged: if (dialog !== "capture") legacyCapturePicker.close()function open(key) {if (key === "save") saveDialog.resetForOpen()@@ -38,6 +39,17 @@ Item {signal startXbox()signal startScreen()+ CaptureLegacyPicker {+ id: legacyCapturePicker+ formats: visible ? veyra.captureFormats : []+ selectedKey: veyra.captureFormatKey+ onSelected: key => { if (!veyra.captureQueryBusy) veyra.captureFormatKey = key }+ }+ Connections {+ target: veyra+ function onCaptureChanged() { if (veyra.captureQueryBusy) legacyCapturePicker.close() }+ }+// Scrim (M16): the design dims the page behind the dialog, opacity .2s linear.// The native video window cannot be dimmed from QML; only the dialog panel is cut// out of it (videoCover below), so the picture beside the dialog stays undimmed.@@ -385,6 +397,17 @@ Item {}}}+ VRow {+ objectName: "capture-legacy-entry"+ label: qsTr("旧版格式选择")+ hint: qsTr("直接查看完整格式列表,包含被常用帧率筛选隐藏的模式")+ VButton {+ objectName: "capture-legacy-open"+ text: qsTr("打开旧版格式列表")+ enabled: !veyra.captureQueryBusy && veyra.captureDeviceId.length > 0+ onClicked: legacyCapturePicker.open()+ }+ }VRow {label: qsTr("分辨率")hint: qsTr("先选择分辨率,再选择该分辨率支持的帧率和像素格式")@@ -398,9 +421,19 @@ Item {onPicked: id => veyra.captureResolutionId = id}}+ VRow {+ label: qsTr("自定义分辨率")+ hint: qsTr("仅接受驱动尺寸范围与步进支持的值;连接时核对实际格式")+ RowLayout {+ spacing: 6+ enabled: !veyra.captureQueryBusy && veyra.captureDeviceId.length > 0+ VTextField { id: customCaptureResolution; objectName: "capture-custom-resolution"; implicitWidth: 140; text: "1920x1080" }+ VButton { text: qsTr("检查并选择"); onClicked: veyra.captureResolutionId = customCaptureResolution.text }+ }+ }VRow {label: qsTr("帧率")- hint: qsTr("只列出当前分辨率下设备上报的帧率。设备帧率填 0 时,连接使用这里选中的帧率")+ hint: qsTr("列出离散帧率及驱动范围内的候选;设备帧率填 0 时沿用此选择,连接时验证实际值")VSelect {objectName: "capture-frame-rate"enabled: !veyra.captureQueryBusy && veyra.captureResolutionId.length > 0diff --git a/qml/Veyra/qmldir b/qml/Veyra/qmldirindex 53fd949e..744e7e59 100644--- a/qml/Veyra/qmldir+++ b/qml/Veyra/qmldir@@ -1,4 +1,5 @@module Veyra+CaptureLegacyPicker 1.0 CaptureLegacyPicker.qmlUpdateBanner 1.0 UpdateBanner.qmlPlaylistWindow 1.0 PlaylistWindow.qmlPlaybackRateButton 1.0 PlaybackRateButton.qmldiff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex ff5366ac..bd41c220 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -13,6 +13,7 @@#include "veyra/source/CaptureBuffer.h"#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureFrameIntervals.h"+#include "veyra/source/DirectShowFormatDiscovery.h"#include "veyra/source/CaptureCodec.h"#include "veyra/source/CaptureCompressedDecoder.h"#include "veyra/source/AverMediaAudioSwitch.h"@@ -212,9 +213,34 @@ std::wstring captureDeviceName(std::wstring_view path){for(auto& moniker:monikers(false))if(monikerPath(moniker.Get())==path)return propertyString(moniker.Get(),L"FriendlyName");return {};}-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)));}+bool createConfiguration(ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,HRESULT* status=nullptr){+ HRESULT hr=CoCreateInstance(CLSID_FilterGraph,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g));+ if(SUCCEEDED(hr))hr=CoCreateInstance(CLSID_CaptureGraphBuilder2,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&b));+ if(SUCCEEDED(hr))hr=b->SetFiltergraph(g.Get());if(status)*status=hr;return SUCCEEDED(hr);+}+bool videoConfiguration(ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c,HRESULT* status){+ HRESULT hr=g->AddFilter(f.Get(),L"Capture card");+ ComPtr<IPin> pin;+ if(SUCCEEDED(hr))hr=dshow::findCaptureVideoPin(f.Get(),pin);+ if(SUCCEEDED(hr))hr=pin.As(&c);+ if(status)*status=hr;+ log::info("capture-formats",std::format("video configuration hr=0x{:08X}",uint32_t(hr)));+ return SUCCEEDED(hr);+}+bool configuration(unsigned device,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c,HRESULT* status=nullptr){+ if(!createConfiguration(g,b,status))return false;+ const auto list=monikers(false);+ const HRESULT hr=device<list.size()?list[device]->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&f)):VFW_E_NOT_FOUND;+ if(FAILED(hr)){if(status)*status=hr;return false;}+ return videoConfiguration(g,b,f,c,status);+}+bool configuration(std::wstring_view path,ComPtr<IGraphBuilder>& g,ComPtr<ICaptureGraphBuilder2>& b,ComPtr<IBaseFilter>& f,ComPtr<IAMStreamConfig>& c,HRESULT* status=nullptr){+ if(!createConfiguration(g,b,status))return false;+ HRESULT hr=VFW_E_NOT_FOUND;+ for(auto& moniker:monikers(false))if(monikerPath(moniker.Get())==path){hr=moniker->BindToObject(nullptr,nullptr,IID_PPV_ARGS(&f));break;}+ if(FAILED(hr)){if(status)*status=hr;return false;}+ return videoConfiguration(g,b,f,c,status);+}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;@@ -764,64 +790,85 @@ std::wstring CaptureCardSource::makeCapturePath(unsigned videoIndex,const Capturif(video.path.empty()||(audioMode>=0&&(!audio||audio->path.empty())))return std::format(L"capture:{}:{}:{}:{}{}",videoIndex,format,audioMode,colorOverride,suffix);return std::format(L"capture2:{}:{}:{}:{}:{}{}",encodePath(video.path),format,audioMode,audioMode>=0?encodePath(audio->path):L"",colorOverride,suffix);}-std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config,bool preferDriverCurrent=false,IBaseFilter* device=nullptr,IPin* capturePin=nullptr){- std::vector<CaptureFormat> out;if(!config)return out;int count=0,size=0;- std::unordered_set<std::wstring> keys; // a driver may list 100+ rates per capability (logs(18): 32759 types)- ComPtr<IPin> pin=capturePin;if(!pin)config->QueryInterface(IID_PPV_ARGS(&pin));+std::vector<CaptureFormat> enumerateFormats(IAMStreamConfig* config,bool preferDriverCurrent=false,IBaseFilter* device=nullptr,IPin* capturePin=nullptr,+ std::span<const CaptureModeHint> hints={},dshow::CaptureNativeCapabilities* saved=nullptr,CaptureFormatQueryInfo* query=nullptr){+ std::vector<CaptureFormat> out;+ ComPtr<IPin> pin=capturePin;if(!pin&&config)config->QueryInterface(IID_PPV_ARGS(&pin));+ auto discovered=dshow::discoverCaptureTypes(config,pin.Get());+ if(query){query->code=discovered.result;query->stage=discovered.stage;query->advertised=discovered.advertised;+ query->rejected=discovered.rejected;query->partial=discovered.failed>0;query->fallback=discovered.fallback;}ComPtr<IAMVideoControl> control;if(device)device->QueryInterface(IID_PPV_ARGS(&control));if(!control&&pin)pin->QueryInterface(IID_PPV_ARGS(&control));std::wstring currentKey;- if(preferDriverCurrent){AM_MEDIA_TYPE* current=nullptr;const HRESULT hr=config->GetFormat(¤t);+ if(preferDriverCurrent&&config){AM_MEDIA_TYPE* raw=nullptr;const auto hr=config->GetFormat(&raw);auto current=dshow::ownCaptureType(raw);if(SUCCEEDED(hr)&¤t)currentKey=captureFormatIdentity(*current);- log::info("capture-default-format",std::format("GetFormat hr=0x{:08X} key={} configurationOnly=1 notSignalDetection=1",uint32_t(hr),narrowForLog(currentKey)));freeType(current);}- const HRESULT capsHr=config->GetNumberOfCapabilities(&count,&size);- log::info("capture-formats",std::format("GetNumberOfCapabilities hr=0x{:08X} count={} bytes={} discreteRates={}",uint32_t(capsHr),count,size,bool(control&&pin)));- if(FAILED(capsHr)||count<0||size<1||size>65536)return out;- std::vector<BYTE> caps(size);- for(int i=0;i<count;++i){AM_MEDIA_TYPE* type=nullptr;const HRESULT typeHr=config->GetStreamCaps(i,&type,caps.data());- if(FAILED(typeHr)){log::warn("capture-formats",std::format("GetStreamCaps index={} hr=0x{:08X}",i,uint32_t(typeHr)));freeType(type);continue;}BITMAPINFOHEADER* bitmap=nullptr;REFERENCE_TIME duration=0;- if(type&&type->pbFormat&&type->formattype==FORMAT_VideoInfo&&type->cbFormat>=sizeof(VIDEOINFOHEADER)){auto* info=reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat);bitmap=&info->bmiHeader;duration=info->AvgTimePerFrame;}- else if(type&&type->pbFormat&&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(bitmap&&bitmap->biWidth>0&&bitmap->biHeight!=0&&bitmap->biHeight!=LONG_MIN&&duration>=0){unsigned width=bitmap->biWidth,height=unsigned(std::abs(int64_t(bitmap->biHeight)));- HRESULT ratesHr=E_NOINTERFACE;- const auto intervals=captureFrameIntervals(control.Get(),pin.Get(),i,{LONG(width),LONG(height)},duration,&ratesHr);- if(control&&pin)log::info("capture-formats",std::format("GetFrameRateList index={} size={}x{} hr=0x{:08X} intervals={}",i,width,height,uint32_t(ratesHr),intervals.size()));+ log::info("capture-default-format",std::format("GetFormat hr=0x{:08X} key={} configurationOnly=1 notSignalDetection=1",uint32_t(hr),narrowForLog(currentKey)));}+ std::unordered_set<std::wstring> keys;+ for(size_t capabilityIndex=0;capabilityIndex<discovered.types.size();++capabilityIndex){+ const auto& capability=discovered.types[capabilityIndex];+ const auto header=dshow::captureVideoHeader(*capability.media);+ const auto originalWidth=header.bitmap->biWidth>0?unsigned(header.bitmap->biWidth):0;+ const auto originalHeight=std::abs(int64_t(header.bitmap->biHeight));+ const auto sizes=captureCandidateSizes(capability.range,originalWidth,originalHeight<=16384?unsigned(originalHeight):0,hints);+ log::info("capture-formats",std::format("cap={} origin={} template={}x{} interval={} range={}x{}..{}x{} step={},{} intervals={}..{} sizeCandidates={}",+ capability.nativeIndex,capability.origin==dshow::CaptureTypeOrigin::StreamCaps?"StreamCaps":"EnumMediaTypes",header.bitmap->biWidth,header.bitmap->biHeight,*header.interval,+ capability.range.minWidth,capability.range.minHeight,capability.range.maxWidth,capability.range.maxHeight,capability.range.stepX,capability.range.stepY,+ capability.range.minInterval,capability.range.maxInterval,sizes.size()));+ for(auto [width,height]:sizes){+ std::vector<int64_t> discrete;+ if(capability.origin==dshow::CaptureTypeOrigin::StreamCaps){+ HRESULT ratesHr=E_NOINTERFACE;+ const auto rates=captureFrameIntervals(control.Get(),pin.Get(),capability.nativeIndex,{LONG(width),LONG(height)},*header.interval,&ratesHr);+ discrete.assign(rates.begin(),rates.end());+ }+ const auto intervals=captureCandidateIntervals(*header.interval,discrete,capability.range,hints);for(const auto interval:intervals){- if(type->formattype==FORMAT_VideoInfo)reinterpret_cast<VIDEOINFOHEADER*>(type->pbFormat)->AvgTimePerFrame=interval;- else reinterpret_cast<VIDEOINFOHEADER2*>(type->pbFormat)->AvgTimePerFrame=interval;- const double fps=interval>0?1e7/interval:0;- 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"需系统解码/转换";- // N3: latency tier + recommended rank; compressed/unknown sorts last.- const auto tier=valid?captureFormatTier(layout.packing):CaptureFormatTier::Decoded;- const int rank=valid?captureFormatRank(layout.packing):captureFormatRank(CapturePacking::Unknown);- const auto key=captureFormatIdentity(*type);const bool current=!currentKey.empty()&&key==currentKey;- std::wstring scan;bool interlaced=false;- if(type->formattype==FORMAT_VideoInfo2){const auto flags=reinterpret_cast<const VIDEOINFOHEADER2*>(type->pbFormat)->dwInterlaceFlags;- interlaced=(flags&AMINTERLACE_IsInterlaced)!=0;- scan=interlaced?std::format(L"隔行({:.2f} 场/秒)",fps*((flags&AMINTERLACE_1FieldPerSample)?1:2)):L"逐行";}- const std::wstring scanMark=scan.empty()?std::wstring{}:L" · "+scan;- const bool supported=width<=3840&&height<=2160&&(!knownRaw||valid);- if(keys.insert(key).second)- out.push_back({i,width,height,fps,std::format(L"{} x {} @ {:.3f} fps{} · {} · {} · {}{}{} [format {}]",width,height,fps,scanMark,pixel,support,captureFormatTierLabel(tier),current?L" · 驱动默认":L"",supported?L"":L" · 当前播放器不支持",i),key,rank,int(tier),current,pixel,scan,interlaced,interval,supported});+ auto type=dshow::captureTypeForMode(capability,width,height,interval);if(!type){if(query)++query->rejected;continue;}+ const auto key=captureFormatIdentity(*type);if(key.empty()||!keys.insert(key).second)continue;+ const auto pixel=capturePixelName(type->subtype);CaptureMediaLayout layout;+ const bool valid=captureMediaLayout(*type,layout),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"需系统解码/转换";+ const auto tier=valid?captureFormatTier(layout.packing):CaptureFormatTier::Decoded;+ const int rank=valid?captureFormatRank(layout.packing):captureFormatRank(CapturePacking::Unknown);+ const double fps=interval>0?1e7/interval:0;+ const auto rateLabel=interval>0?std::format(L"{:.3f} fps",fps):L"设备默认帧率";+ const auto candidateHeader=dshow::captureVideoHeader(*type);+ const bool interlaced=(candidateHeader.scan&AMINTERLACE_IsInterlaced)!=0;+ std::wstring scan;+ if(type->formattype==FORMAT_VideoInfo2)scan=interlaced?std::format(L"隔行({:.2f} 场/秒)",fps*((candidateHeader.scan&AMINTERLACE_1FieldPerSample)?1:2)):L"逐行";+ const auto scanMark=scan.empty()?std::wstring{}:L" · "+scan;+ const bool supported=width<=3840&&height<=2160&&(!knownRaw||valid);+ const bool current=!currentKey.empty()&¤tKey==key;+ const bool rangeCandidate=width!=originalWidth||height!=originalHeight||+ (interval!=*header.interval&&std::find(discrete.begin(),discrete.end(),interval)==discrete.end());+ const auto rangeMark=rangeCandidate?L" · 范围候选(连接时验证)":L"";+ CaptureFormat format{capability.nativeIndex,width,height,fps,+ std::format(L"{} x {} @ {}{} · {} · {} · {}{}{}{} [format {}]",width,height,rateLabel,scanMark,pixel,support,captureFormatTierLabel(tier),+ current?L" · 驱动默认":L"",supported?L"":L" · 当前播放器不支持",rangeMark,capability.nativeIndex),key,rank,int(tier),current,pixel,scan,interlaced,interval,supported};+ format.capability=int(capabilityIndex);format.rangeCandidate=rangeCandidate;out.push_back(std::move(format));+ if(out.size()>=131072){if(query){query->partial=true;query->code=E_OUTOFMEMORY;query->stage=L"Capability candidate limit";}break;}}+ if(out.size()>=131072)break;}- freeType(type);+ if(out.size()>=131072)break;}- // Recommended order first; equal ranks keep the driver's enumeration order.+ log::info("capture-formats",std::format("discovery hr=0x{:08X} raw={} failed={} rejected={} fallback={} concrete={}",+ uint32_t(discovered.result),discovered.advertised,discovered.failed,query?query->rejected:discovered.rejected,discovered.fallback,out.size()));+ if(query&&out.empty()&&SUCCEEDED(query->code)&&query->advertised){query->code=VFW_E_INVALIDMEDIATYPE;query->stage=L"Parse video capabilities";}std::stable_sort(out.begin(),out.end(),[](const CaptureFormat& a,const CaptureFormat& b){return a.driverCurrent!=b.driverCurrent?a.driverCurrent:a.rank<b.rank;});+ if(saved)*saved=std::move(discovered);return out;}std::vector<CaptureFormat> CaptureCardSource::formats(unsigned device){const auto details=deviceDetails();if(device<details.size()&&decklink::isPath(details[device].path))return formatsByPath(details[device].path);ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(device,g,b,f,c))return {};const auto list=monikers(false);const auto name=device<list.size()?propertyString(list[device].Get(),L"FriendlyName"):L"";- ComPtr<IPin> pin;b->FindPin(f.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&pin);+ ComPtr<IPin> pin;dshow::findCaptureVideoPin(f.Get(),pin);return enumerateFormats(c.Get(),isBlackmagicCaptureDevice(name),f.Get(),pin.Get());}-std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view devicePath){+std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view devicePath,CaptureFormatQueryInfo* query,+ std::wstring_view preferredKey,std::wstring_view requestedResolution){+ if(query)*query={};if(decklink::isPath(devicePath)){std::vector<CaptureFormat> out;for(const auto& device:decklink::devices())if(device.path==devicePath&&device.autoDetection)@@ -830,9 +877,14 @@ std::vector<CaptureFormat> CaptureCardSource::formatsByPath(std::wstring_view destd::format(L"{} · {} x {} @ {:.3f} fps · {} · BMD 原生",mode.name,mode.width,mode.height,double(mode.scale)/mode.duration,mode.interlaced?L"隔行":L"逐行"),decklink::modeKey(mode.id),1,0,false,L"自动选择像素格式",mode.interlaced?L"隔行":L"逐行",mode.interlaced,int64_t(1e7*mode.duration/mode.scale),mode.width<=3840&&mode.height<=2160});return out;}- ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;if(!configuration(devicePath,g,b,f,c))return {};- ComPtr<IPin> pin;b->FindPin(f.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&pin);- return enumerateFormats(c.Get(),isBlackmagicCaptureDevice(captureDeviceName(devicePath),devicePath),f.Get(),pin.Get());+ ComPtr<IGraphBuilder> g;ComPtr<ICaptureGraphBuilder2>b;ComPtr<IBaseFilter>f;ComPtr<IAMStreamConfig>c;HRESULT status=S_OK;+ if(!configuration(devicePath,g,b,f,c,&status)){+ if(query){query->code=status;query->stage=L"Bind device / video capture pin";}+ return {};+ }+ ComPtr<IPin> pin;dshow::findCaptureVideoPin(f.Get(),pin);+ const CaptureModeHint hints[]{captureKeyHint(preferredKey),captureResolutionHint(requestedResolution)};+ return enumerateFormats(c.Get(),isBlackmagicCaptureDevice(captureDeviceName(devicePath),devicePath),f.Get(),pin.Get(),hints,nullptr,query);}bool CaptureCardSource::showDeviceProperties(std::wstring_view devicePath,uintptr_t owner,bool inputSelector,std::wstring& error,std::wstring* changedFormatKey){error.clear();if(changedFormatKey)changedFormatKey->clear();@@ -961,26 +1013,28 @@ bool CaptureCardSource::configureDeckLink(const SourceOpenDesc& desc){bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.clear();p_->lastAudioGain=-1;auto& p=*p_;CaptureSelection selection;if(!parseCapturePath(desc.path,selection))return false;const unsigned index=selection.videoIndex;int format=selection.format;const int audio=selection.audio;if(selection.stable&&decklink::isPath(selection.videoPath))return configureDeckLink(desc);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;- ComPtr<IPin> formatPin;p.builder->FindPin(p.device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&formatPin);- const auto available=enumerateFormats(p.config.Get(),false,p.device.Get(),formatPin.Get());+ ComPtr<IPin> formatPin;dshow::findCaptureVideoPin(p.device.Get(),formatPin);+ dshow::CaptureNativeCapabilities capabilities;+ CaptureFormatQueryInfo query;+ const CaptureModeHint hint[]{captureKeyHint(selection.formatKey)};+ const auto available=enumerateFormats(p.config.Get(),false,p.device.Get(),formatPin.Get(),hint,&capabilities,&query);const auto* chosen=selectCaptureFormat(available,format,selection.formatKey);- if(!chosen){error_=L"此采集卡无此格式,请重新选择分辨率、帧率和像素格式。";return false;}- if(chosen)format=chosen->index;- if(chosen&&!chosen->supported){error_=L"设备提供此格式,但当前播放器不支持其尺寸或像素布局,请选择其他格式";return false;}- // Capture the advertised identity before SetFormat: some drivers mutate- // their capability list to reflect the last negotiated rate/orientation.- const std::wstring selectedKey=chosen?chosen->key:L"";- const double expectedFps=selection.requestedFps>0?selection.requestedFps:chosen?chosen->fps:0;- 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;- if(selection.requestedFps>0||(chosen&&chosen->interval100ns>0)){- REFERENCE_TIME* interval=nullptr;- if(native->formattype==FORMAT_VideoInfo&&native->cbFormat>=sizeof(VIDEOINFOHEADER))interval=&reinterpret_cast<VIDEOINFOHEADER*>(native->pbFormat)->AvgTimePerFrame;- else if(native->formattype==FORMAT_VideoInfo2&&native->cbFormat>=sizeof(VIDEOINFOHEADER2))interval=&reinterpret_cast<VIDEOINFOHEADER2*>(native->pbFormat)->AvgTimePerFrame;- if(!interval){error_=L"该采集格式不支持设备帧率协商,请将采集帧率设为 0。";freeType(native);return false;}- *interval=selection.requestedFps>0?captureFrameInterval(selection.requestedFps):chosen->interval100ns;- log::info("capture-rate",std::format("requestFps={:.6f} interval100ns={} deviceNegotiation=1 softwareLimiter=0",expectedFps,*interval));- }+ if(!chosen){error_=std::format(L"采集格式无法恢复:{}(0x{:08X}),请刷新并重新选择。",query.stage,uint32_t(query.code));return false;}+ format=chosen->index;+ if(!chosen->supported){error_=L"设备提供此格式,但当前播放器不支持其尺寸或像素布局,请选择其他格式";return false;}+ if(chosen->capability<0||size_t(chosen->capability)>=capabilities.types.size()){error_=L"采集格式的能力记录已失效,请刷新后重试。";return false;}+ const std::wstring selectedKey=chosen->key;+ const double expectedFps=selection.requestedFps>0?selection.requestedFps:chosen->fps;+ const auto interval=selection.requestedFps>0?captureFrameInterval(selection.requestedFps):chosen->interval100ns;+ auto requested=dshow::captureTypeForMode(capabilities.types[size_t(chosen->capability)],chosen->width,chosen->height,interval);+ if(!requested){error_=L"无法构造所选采集格式,请检查分辨率、帧率与驱动能力。";return false;}+ auto nativeOwner=dshow::cloneCaptureType(*requested);+ if(!nativeOwner){error_=L"采集格式内存分配失败";return false;}+ // Existing connection code owns this pointer through freeType().+ AM_MEDIA_TYPE* native=static_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));+ if(!native)return false;+ *native=*nativeOwner;nativeOwner->pbFormat=nullptr;nativeOwner->cbFormat=0;nativeOwner->pUnk=nullptr;+ log::info("capture-rate",std::format("requestFps={:.6f} interval100ns={} deviceNegotiation=1 softwareLimiter=0",expectedFps,interval));std::wstring devicePath=selection.videoPath;if(devicePath.empty()){const auto devices=monikers(false);if(index<devices.size())devicePath=monikerPath(devices[index].Get());}const auto deviceName=captureDeviceName(devicePath);p.signalProbeEnabled=isBlackmagicCaptureDevice(deviceName,devicePath);@@ -994,10 +1048,23 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleconfigureAverToneMap(p.device.Get(),devicePath,native->subtype.Data1==MAKEFOURCC('P','0','1','0')||native->subtype.Data1==MAKEFOURCC('P','0','1','6'));log::info("capture-device",std::format("path={} selectedFormat={} requestedFps={} nativeSubtype=0x{:X}",narrowForLog(devicePath),format,expectedFps,native->subtype.Data1));HRESULT hr=p.config->SetFormat(native);const GUID requestedSubtype=native->subtype;- log::info("capture",std::format("SetFormat device={} nativeIndex={} subtype=0x{:08X} hr=0x{:08X}",index,format,native->subtype.Data1,uint32_t(hr)));freeType(native);if(FAILED(hr)){error_=selection.requestedFps>0?std::format(L"此采集卡无此格式:拒绝 {:.3f} FPS(0x{:08X}),请改用设备支持的帧率,或填 0 沿用所选格式。",selection.requestedFps,uint32_t(hr)):std::format(L"此采集卡无此格式,驱动拒绝所选格式(0x{:08X}),请重新选择。",uint32_t(hr));return false;}- // Read the driver-negotiated type back. Native YUY2/NV12/RGB32 connects- // directly to our terminal filter: no intelligent-connect converter.- native=nullptr;hr=p.config->GetFormat(&native);if(FAILED(hr)||!native){freeType(native);return false;}+ const bool connectionNegotiation=hr==E_NOTIMPL;+ log::info("capture",std::format("SetFormat device={} nativeIndex={} subtype=0x{:08X} hr=0x{:08X} verifyConnection={}",index,format,native->subtype.Data1,uint32_t(hr),connectionNegotiation));+ freeType(native);native=nullptr;+ if(FAILED(hr)&&!connectionNegotiation){error_=std::format(L"驱动拒绝所选采集格式(0x{:08X}),请重新选择。",uint32_t(hr));return false;}+ hr=p.config->GetFormat(&native);+ if(FAILED(hr)&&hr!=E_NOTIMPL&&hr!=E_NOINTERFACE){error_=std::format(L"读取协商后的采集格式失败(0x{:08X})。",uint32_t(hr));freeType(native);return false;}+ if(SUCCEEDED(hr)&&native&&!connectionNegotiation&&!dshow::captureTypesMatch(*requested,*native)){+ error_=L"驱动返回的分辨率、帧率、像素格式或扫描方式与所选模式不同,请重新选择。";freeType(native);return false;+ }+ // Drivers with unimplemented configuration methods must still accept the+ // exact type in ConnectDirect, whose actual media type is checked below.+ if(connectionNegotiation||FAILED(hr)||!native){+ freeType(native);auto copy=dshow::cloneCaptureType(*requested);if(!copy)return false;+ native=static_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));if(!native)return false;+ *native=*copy;copy->pbFormat=nullptr;copy->cbFormat=0;copy->pUnk=nullptr;+ }+ hr=S_OK;CaptureMediaLayout nativeLayout;const bool nativeSupported=captureMediaLayout(*native,nativeLayout);if(!nativeSupported&&capturePacking(native->subtype)!=CapturePacking::Unknown){log::error("capture","Known raw format has unsupported layout/color metadata; refusing implicit RGB conversion");freeType(native);return false;}if(nativeSupported&&(nativeLayout.format==AV_PIX_FMT_P010||nativeLayout.format==AV_PIX_FMT_P016)&&desc.legacyCaptureRgbForDiagnostic){log::error("capture","10/16-bit capture cannot use the legacy 8-bit RGB diagnostic converter");freeType(native);return false;}@@ -1042,7 +1109,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleComPtr<IPin> input,output;hr=createCompressedCaptureSink(*native,[&p](IMediaSample* sample){REFERENCE_TIME a=0,b=0;const auto timeHr=sample->GetTime(&a,&b);if(FAILED(timeHr))return timeHr;return p.SampleCB(double(a)/1e7,sample);},p.grabFilter,input);if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.grabFilter.Get(),L"Compressed frame mailbox");- if(SUCCEEDED(hr))hr=p.builder->FindPin(p.device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&output);+ if(SUCCEEDED(hr))output=formatPin;if(SUCCEEDED(hr))suggestCaptureVideoBuffering(output.Get(),4,512*1024);if(SUCCEEDED(hr))hr=p.graph->ConnectDirect(output.Get(),input.Get(),native);if(SUCCEEDED(hr))hr=input->ConnectionMediaType(&connected);@@ -1078,7 +1145,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleComPtr<IPin> input,output;hr=createNativeCaptureSink(*native,[&p](IMediaSample* sample){REFERENCE_TIME a=0,b=0;const auto timeHr=sample->GetTime(&a,&b);if(FAILED(timeHr))return timeHr;return p.SampleCB(double(a)/1e7,sample);},p.grabFilter,input,bmdCompat?CaptureAllocatorMode::Upstream:CaptureAllocatorMode::SinkDefault);if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.grabFilter.Get(),L"Native frame mailbox");- if(SUCCEEDED(hr))hr=p.builder->FindPin(p.device.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,FALSE,0,&output);+ if(SUCCEEDED(hr))output=formatPin;if(SUCCEEDED(hr)&&suggestedBuffers>0)suggestCaptureVideoBuffering(output.Get(),suggestedBuffers,LONG(nativeLayout.sampleBytes));// OBS HDevice::ConnectPins (fixed commit/license in NativeCaptureSink.cpp)// lets the output pin supply its configured media type. Check the actual@@ -1108,8 +1175,22 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleif(SUCCEEDED(hr))hr=p.grab->SetMediaType(&want);if(SUCCEEDED(hr))hr=CoCreateInstance(NullRendererClass,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&p.nullFilter));if(SUCCEEDED(hr))hr=p.graph->AddFilter(p.nullFilter.Get(),L"Video sink");- if(SUCCEEDED(hr))hr=p.builder->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,p.device.Get(),p.grabFilter.Get(),p.nullFilter.Get());+ if(SUCCEEDED(hr))hr=p.builder->RenderStream(nullptr,&MEDIATYPE_Video,formatPin.Get(),p.grabFilter.Get(),p.nullFilter.Get());if(SUCCEEDED(hr))hr=p.grab->GetConnectedMediaType(&connected);+ if(SUCCEEDED(hr)){+ AM_MEDIA_TYPE sourceConnected{};hr=formatPin->ConnectionMediaType(&sourceConnected);+ if(SUCCEEDED(hr)&&!dshow::captureTypesMatch(*requested,sourceConnected))hr=VFW_E_INVALIDMEDIATYPE;+ freeType(&sourceConnected,false);+ }+ }+ if(FAILED(hr)){+ error_=std::format(L"采集卡无法连接所选格式(0x{:08X}),请检查设备占用并重新选择。",uint32_t(hr));+ freeType(native);freeType(&connected,false);return false;+ }+ if(SUCCEEDED(hr)&&(direct||compressedPath)&&!dshow::captureTypesMatch(*requested,connected)){+ error_=L"实际连接的采集格式与所选模式不同,请刷新并重新选择。";+ log::error("capture-formats","connected media type differs from exact selection; refusing implicit mode substitution");+ freeType(native);freeType(&connected,false);return false;}bool layoutValid=false;if(compressedPath){@@ -1698,7 +1779,7 @@ bool CaptureCardSource::reconnect(float gain,unsigned syncMode,int offsetMs){{std::lock_guard lock(p_->mutex);receivedOffset_+=p_->received;deliveredOffset_+=p_->sequence;droppedOffset_+=p_->dropped;}close();- int format=-1;for(const auto& candidate:formatsByPath(selection.videoPath))if(candidate.key==key){format=candidate.index;break;}+ int format=-1;for(const auto& candidate:formatsByPath(selection.videoPath,nullptr,key))if(candidate.key==key){format=candidate.index;break;}if(format<0)return false;auto reopen=desc;reopen.path=std::format(L"capture2:{}:{}:{}:{}:{}",encodePath(selection.videoPath),format,selection.audio,encodePath(selection.audioPath),selection.colorOverride);reopen.path+=capturePathOptions(selection.requestedFps,encodePath(key));diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 1e3b23b0..284769d9 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -70,6 +70,7 @@#include "veyra/engine/PlaybackRate.h"#include "veyra/sink/WasapiAudioSink.h"#include "veyra/source/CaptureFormatSelection.h"+#include "veyra/source/CaptureCapabilityRange.h"#include "veyra/source/CaptureFormatRank.h"#include "veyra/source/CaptureColorOverride.h"#include "veyra/source/CaptureFrameRate.h"@@ -359,7 +360,7 @@ struct QmlPlayerBridge::Impl {double resumeAt = 0;std::vector<sink::RenderEndpoint> audioEndpoints;// --- capture connection (P4-e) ---- struct CaptureQuery { int kind = 0; std::wstring device; std::vector<source::CaptureDevice> video, audio; std::vector<source::CaptureFormat> formats; };+ struct CaptureQuery { int kind = 0; std::wstring device,requestedResolution; std::vector<source::CaptureDevice> video, audio; std::vector<source::CaptureFormat> formats;source::CaptureFormatQueryInfo info; };std::future<CaptureQuery> captureQuery;std::optional<std::pair<int,std::wstring>> captureNextQuery;bool captureBusy = false, captureListed = false, captureResumePending = false;@@ -398,6 +399,7 @@ struct QmlPlayerBridge::Impl {}std::wstring captureFormatKey;std::wstring captureResolutionChoice, captureRateChoice;+ std::wstring captureRequestedResolution;int captureAudioChoice = source::kCaptureAudioDisabled;bool captureAudioMissing = false;unsigned captureColor = 0;@@ -2297,6 +2299,7 @@ void QmlPlayerBridge::setCaptureDeviceId(const QString& value) {impl_->captureDevice = wideOf(value);impl_->captureFormatList.clear();++impl_->captureFormatGeneration;impl_->captureResolutionChoice.clear();impl_->captureRateChoice.clear();+ impl_->captureRequestedResolution.clear();impl_->captureFormatKey=impl_->captureDevice==impl_->capturePrefs.videoPath?impl_->capturePrefs.formatKey:std::wstring{};impl_->captureDriverFormatKey.clear();// Colour follows the device, as in 1.4.4; audio returns to "none" unless it@@ -2325,7 +2328,7 @@ QVariantList QmlPlayerBridge::captureFormats() const {out << QVariantMap{{"id", utf8Of(f.key)}, {"label", captureFormatUiLabel(f, impl_->captureDevice)}, {"tier", f.tier},{"costHint", source::captureFormatNeedsCostHint(static_cast<source::CaptureFormatTier>(f.tier))}, {"driverCurrent", f.driverCurrent},{"width", int(f.width)}, {"height", int(f.height)}, {"fps", f.fps}, {"pixel", uiText(f.pixel)},- {"scan", uiText(f.scan)}, {"interlaced", f.interlaced}};+ {"scan", uiText(f.scan)}, {"interlaced", f.interlaced}, {"disabled", !f.supported}, {"rangeCandidate", f.rangeCandidate}};}return out;});@@ -2352,9 +2355,9 @@ void QmlPlayerBridge::setCaptureFormatKey(const QString& key) {impl_->captureStatus=tr("此采集卡无此格式,请重新选择分辨率、帧率和像素格式。");emit notice(impl_->captureStatus,true);emit captureChanged();return;}- if (impl_->captureFormatKey == format->key && impl_->captureResolutionChoice == source::captureResolutionId(*format) && impl_->captureRateChoice == source::captureFrameRateId(*format)) return;+ if (impl_->captureFormatKey == format->key && impl_->captureResolutionChoice == source::captureResolutionId(*format) && impl_->captureRateChoice == source::captureFrameRateGroupId(*format)) return;impl_->captureResolutionChoice=source::captureResolutionId(*format);- impl_->captureRateChoice=source::captureFrameRateId(*format);+ impl_->captureRateChoice=source::captureFrameRateGroupId(*format);impl_->captureFormatKey = format->key;impl_->captureStatus.clear();if(!impl_->persistCaptureSelection(true))emit notice(tr("采集设置保存失败,请检查配置目录是否可写"),true);@@ -2378,14 +2381,21 @@ QString QmlPlayerBridge::captureResolutionId() const {return utf8Of(impl_->captureResolutionChoice);}void QmlPlayerBridge::setCaptureResolutionId(const QString& id) {- const auto wide = wideOf(id);+ QString normalized=id.trimmed().toLower();normalized.remove(QLatin1Char(' '));+ normalized.replace(QChar(0x00D7),QLatin1Char('x'));+ const auto wide = wideOf(normalized);if(impl_->captureResolutionChoice==wide)return;const auto* sample=source::captureResolutionSample(impl_->captureFormatList,wide);- if(!sample){emit notice(tr("此采集卡无此格式,请重新选择分辨率、帧率和像素格式。"),true);return;}+ if(!sample){+ const auto hint=source::captureResolutionHint(wide);+ if(hint.width&&hint.height&&!impl_->captureDevice.empty()&&!source::decklink::isPath(impl_->captureDevice)){+ impl_->captureRequestedResolution=wide;queryCapture(4,impl_->captureDevice);return;+ }+ emit notice(tr("此采集卡无此格式,请重新选择分辨率、帧率和像素格式。"),true);return;+ }impl_->captureResolutionChoice=wide;- // A rate the new resolution lacks becomes its first common rate, not the driver's first row.if(!source::captureRateSample(impl_->captureFormatList,wide,impl_->captureRateChoice))- if(const auto* rate=source::captureDefaultFrameRate(impl_->captureFormatList,wide))impl_->captureRateChoice=source::captureFrameRateId(*rate);+ if(const auto* rate=source::captureDefaultFrameRate(impl_->captureFormatList,wide))impl_->captureRateChoice=source::captureFrameRateGroupId(*rate);impl_->captureFormatKey.clear();if(!impl_->persistCaptureSelection(true))emit notice(tr("采集设置保存失败,请检查配置目录是否可写"),true);emit captureChanged();@@ -2415,7 +2425,8 @@ void QmlPlayerBridge::setCaptureFrameRateId(const QString& id) {if(!source::captureRateSample(impl_->captureFormatList,impl_->captureResolutionChoice,wide)){emit notice(tr("此采集卡无此格式,请重新选择分辨率、帧率和像素格式。"),true);return;}- impl_->captureRateChoice=wide;impl_->captureFormatKey.clear();+ const auto* sample=source::captureRateSample(impl_->captureFormatList,impl_->captureResolutionChoice,wide);+ impl_->captureRateChoice=source::captureFrameRateGroupId(*sample);impl_->captureFormatKey.clear();if(!impl_->persistCaptureSelection(true))emit notice(tr("采集设置保存失败,请检查配置目录是否可写"),true);emit captureChanged();}@@ -2538,16 +2549,22 @@ void QmlPlayerBridge::queryCapture(int kind, std::wstring device) {if (captureQueryBusy()) { i.captureNextQuery=std::pair{kind,std::move(device)};return; }i.captureBusy = true; i.captureQueryKind = kind;i.captureStatus = kind == 0 ? tr("正在查询采集设备…当前播放继续") : tr("正在读取设备支持的格式…");- i.captureQuery = std::async(std::launch::async, [kind, device] {- CoInitializeEx(nullptr, COINIT_MULTITHREADED);- Impl::CaptureQuery q; q.kind = kind; q.device = device;+ const auto preferred=kind==2?i.capturePrefs.formatKey:+ kind==3&&!i.captureDriverFormatKey.empty()?i.captureDriverFormatKey:i.captureFormatKey;+ const auto requested=kind==4?i.captureRequestedResolution:+ preferred.empty()&&wideOf(i.prefs.value("captureDraftDevice").toString())==device?+ wideOf(i.prefs.value("captureDraftResolution").toString()):std::wstring{};+ i.captureQuery = std::async(std::launch::async, [kind, device, preferred, requested] {+ Impl::CaptureQuery q; q.kind = kind; q.device = device;q.requestedResolution=requested;+ const auto initialized=CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ if(FAILED(initialized)){q.info.code=initialized;q.info.stage=L"COM initialization";return q;}try {if (kind == 0) { q.video = source::CaptureCardSource::deviceDetails(); q.audio = source::CaptureCardSource::deviceDetails(true); }else {if (kind == 2) { q.video = source::CaptureCardSource::deviceDetails(); q.audio = source::CaptureCardSource::deviceDetails(true); }- q.formats = source::CaptureCardSource::formatsByPath(device);+ q.formats = source::CaptureCardSource::formatsByPath(device,&q.info,preferred,requested);}- } catch (...) {}+ } catch (...) {q.info.code=E_FAIL;q.info.stage=L"Capture capability exception";}CoUninitialize();return q;});@@ -2559,6 +2576,13 @@ void QmlPlayerBridge::tickCapture() {auto q = i.captureQuery.get();i.captureBusy = false;if(i.captureNextQuery){auto next=std::move(*i.captureNextQuery);i.captureNextQuery.reset();queryCapture(next.first,std::move(next.second));return;}+ if(FAILED(q.info.code)&&q.formats.empty()){+ if(q.kind!=0&&q.device!=i.captureDevice){emit captureChanged();return;}+ if(q.kind!=0&&q.kind!=4){i.captureFormatList.clear();++i.captureFormatGeneration;i.captureResolutionChoice.clear();i.captureRateChoice.clear();}+ i.captureStatus=tr("读取采集格式失败:%1(0x%2)。请检查设备占用与驱动后重试。")+ .arg(utf8Of(q.info.stage),QString::number(quint32(q.info.code),16).rightJustified(8,QLatin1Char('0')));+ emit notice(i.captureStatus,true);emit captureChanged();return;+ }if (q.kind == 0 || q.kind == 2) { i.captureVideo = std::move(q.video); i.captureAudio = std::move(q.audio); i.captureListed = true; }// The remembered rate and audio input, matched against the inputs listed now. Both the// panel (kind 0) and 继续上次 (kind 2) need it: the resume path skipped it and connected@@ -2592,6 +2616,10 @@ void QmlPlayerBridge::tickCapture() {return;}if (q.device != i.captureDevice) { emit captureChanged(); return; } // stale answer+ if(q.kind==4&&!source::captureResolutionSample(q.formats,q.requestedResolution)){+ i.captureStatus=tr("驱动未提供该分辨率,或尺寸不符合步进要求;原选择已保留。");+ emit notice(i.captureStatus,true);emit captureChanged();return;+ }i.captureFormatList = std::move(q.formats);++i.captureFormatGeneration;const bool remembered = i.captureDevice == i.capturePrefs.videoPath;@@ -2605,23 +2633,30 @@ void QmlPlayerBridge::tickCapture() {}i.captureResolutionChoice.clear();i.captureRateChoice.clear();if(const auto* f=selectedCaptureFormat(i.captureFormatList,i.captureFormatKey)){- i.captureResolutionChoice=source::captureResolutionId(*f);i.captureRateChoice=source::captureFrameRateId(*f);+ i.captureResolutionChoice=source::captureResolutionId(*f);i.captureRateChoice=source::captureFrameRateGroupId(*f);}else if(remembered&&i.capturePrefs.formatKey.empty()&&wideOf(i.prefs.value("captureDraftDevice").toString())==i.captureDevice){const auto resolution=wideOf(i.prefs.value("captureDraftResolution").toString());const auto rate=wideOf(i.prefs.value("captureDraftRate").toString());if(source::captureResolutionSample(i.captureFormatList,resolution)){i.captureResolutionChoice=resolution;- if(source::captureRateSample(i.captureFormatList,resolution,rate))i.captureRateChoice=rate;+ if(const auto* sample=source::captureRateSample(i.captureFormatList,resolution,rate))i.captureRateChoice=source::captureFrameRateGroupId(*sample);}}+ if(q.kind==4){+ i.captureResolutionChoice=q.requestedResolution;i.captureFormatKey.clear();+ if(const auto* rate=source::captureDefaultFrameRate(i.captureFormatList,i.captureResolutionChoice))i.captureRateChoice=source::captureFrameRateGroupId(*rate);+ if(!i.persistCaptureSelection(true))emit notice(tr("采集设置保存失败,请检查配置目录是否可写"),true);+ }if(!i.captureFormatKey.empty()&&!i.persistCaptureSelection())emit notice(tr("采集设置保存失败,请检查配置目录是否可写"),true);- i.captureStatus = i.captureFormatList.empty() ? tr("未读到设备上报的采集格式,或设备正被其他应用占用。")+ i.captureStatus = i.captureFormatList.empty() ? tr("驱动未提供可解析的视频格式,请检查设备与驱动后刷新。"): i.captureFormatKey.empty() ? (!i.capturePrefs.formatKey.empty()?tr("此采集卡无此格式,请重新选择分辨率、帧率和像素格式。"):tr("先选择分辨率,再选择该分辨率支持的帧率和像素格式")): q.kind == 3 ? tr("驱动设置已关闭。请核对所选格式与设备帧率,再连接。"): source::decklink::isPath(i.captureDevice) ? tr("原生采集先确认有效信号;请在设备列表选择对应的 HDMI/SDI 输入,支持自动检测的卡建议选择自动。Driver 保留驱动当前输入。"): captureBlackmagicDevice() ? tr("请选择与输入信号一致的格式。驱动默认格式不代表检测到的信号。"): tr("连接后使用当前增强设置。格式与音频变更需要重新连接。");- veyra::log::info("capture-ui", std::format("formats={} selected={}", i.captureFormatList.size(), !i.captureFormatKey.empty()));+ if(q.info.partial)i.captureStatus=tr("部分采集能力读取失败(%1,0x%2);当前列表可能不完整,请刷新重试。")+ .arg(utf8Of(q.info.stage),QString::number(quint32(q.info.code),16).rightJustified(8,QLatin1Char('0')));+ veyra::log::info("capture-ui", std::format("formats={} selected={} raw={} rejected={} partial={} fallback={}", i.captureFormatList.size(), !i.captureFormatKey.empty(),q.info.advertised,q.info.rejected,q.info.partial,q.info.fallback));emit captureChanged();if (q.kind == 2) {if (i.captureFormatKey.empty()) emit notice(tr("上次的采集格式不可用,请在采集卡面板重新选择"), true);diff --git a/tests/qml/quick/tst_capture_legacy.qml b/tests/qml/quick/tst_capture_legacy.qmlnew file mode 100644index 00000000..6079ff80--- /dev/null+++ b/tests/qml/quick/tst_capture_legacy.qml@@ -0,0 +1,50 @@+import QtQuick+import QtQuick.Controls+import QtTest+import Veyra++Item {+ width: 900; height: 650+ CaptureLegacyPicker { id: picker }+ SignalSpy { id: chosen; target: picker; signalName: "selected" }+ TestCase {+ name: "CaptureLegacyPicker"+ when: windowShown+ function cleanup() { picker.close(); chosen.clear() }+ function test_full_list_search_and_selection() {+ let entries = []+ for (let i = 0; i < 16000; ++i)+ entries.push({id: "exact:" + i, label: "1920 x 1080 @ 60 fps · " + (i % 2 ? "NV12" : "YUY2") + " [format " + i + "]"})+ picker.formats = entries+ picker.open()+ tryCompare(picker, "opened", true)+ const list = findChild(picker.contentItem, "capture-legacy-list")+ const search = findChild(picker.contentItem, "capture-legacy-search")+ tryCompare(list, "count", 16000)+ verify(list.contentItem.children.length < 100, "Rows must stay virtualized")+ search.text = "1920 60 NV12"+ picker.applySearch()+ tryCompare(list, "count", 8000)+ tryVerify(() => list.itemAtIndex(0) !== null)+ list.itemAtIndex(0).clicked()+ compare(chosen.count, 1)+ compare(chosen.signalArguments[0][0], "exact:1")+ tryCompare(picker, "visible", false)+ picker.open()+ tryCompare(picker, "opened", true)+ tryCompare(list, "count", 16000)+ }+ function test_unsupported_rows_and_empty_search() {+ picker.formats = [{id:"unsupported",label:"Unsupported",disabled:true}]+ picker.open()+ tryCompare(picker, "opened", true)+ const list = findChild(picker.contentItem, "capture-legacy-list")+ tryVerify(() => list.itemAtIndex(0) !== null)+ compare(list.itemAtIndex(0).enabled, false)+ findChild(picker.contentItem, "capture-legacy-search").text = "not-found"+ picker.applySearch()+ compare(list.count, 0)+ compare(chosen.count, 0)+ }+ }+}diff --git a/tests/unit/CaptureCapabilityTests.cpp b/tests/unit/CaptureCapabilityTests.cppnew file mode 100644index 00000000..0e44d288--- /dev/null+++ b/tests/unit/CaptureCapabilityTests.cpp@@ -0,0 +1,59 @@+#include "veyra/source/CaptureCapabilityRange.h"+#include "veyra/source/CaptureFormatSelection.h"+#include <chrono>+#include <iostream>+#include <set>++using namespace veyra::source;+int main(){+ unsigned checks=0,failures=0;+ const auto check=[&](bool ok,const char* text){++checks;if(!ok){++failures;std::cerr<<"FAIL "<<text<<'\n';}};+ CaptureCapabilityRange range{640,1920,480,1080,16,2,166666,333667};+ check(range.acceptsSize(1280,720)&&range.acceptsSize(1920,1080),"range accepts aligned intermediate and endpoint dimensions");+ check(!range.acceptsSize(1279,720)&&!range.acceptsSize(1280,721)&&!range.acceptsSize(3840,2160),"step and bounds reject unsupported dimensions");+ const CaptureModeHint hint[]{captureResolutionHint(L"1440x900")};+ const auto sizes=captureCandidateSizes(range,0,0,hint);+ check(std::find(sizes.begin(),sizes.end(),std::pair{1440u,900u})!=sizes.end(),"custom dimensions work with an invalid template size and valid range");+ check(std::find(sizes.begin(),sizes.end(),std::pair{1920u,1080u})!=sizes.end(),"maximum capability is not lost behind template dimensions");+ auto unaligned=range;unaligned.maxWidth=1919;unaligned.maxHeight=1079;+ const auto alignedSizes=captureCandidateSizes(unaligned,0,0);+ check(std::find(alignedSizes.begin(),alignedSizes.end(),std::pair{1904u,1078u})!=alignedSizes.end(),"highest aligned size is retained when the maximum endpoint is off-step");+ check(!captureResolutionHint(L"1920x1080garbage").width&&!captureResolutionHint(L"99999999999x1080").width,"malformed and overflowing sizes rejected");+ const auto restored=captureKeyHint(L"1440:-900:333667:{subtype}:{format}:16:1:scan=5");+ check(restored.width==1440&&restored.height==900&&restored.interval==333667,"stable signed-height media key restores a range hint");+ check(!captureKeyHint(L"-1:1080:333667:bad").width&&!captureKeyHint(L"1920:1080:-1:bad").width,"invalid persisted keys cannot construct media types");+ const std::vector<int64_t> discrete{166666,166667,333667};+ const auto intervals=captureCandidateIntervals(333667,discrete,range);+ check(std::find(intervals.begin(),intervals.end(),166833)!=intervals.end(),"59.94 can be offered from an explicit driver interval range");+ check(std::find(intervals.begin(),intervals.end(),166666)!=intervals.end()&&std::find(intervals.begin(),intervals.end(),166667)!=intervals.end(),"native integer intervals are preserved exactly");+ check(std::find(intervals.begin(),intervals.end(),666667)==intervals.end(),"range does not invent 15fps outside its bounds");+ const auto fallback=captureCandidateIntervals(0,{},{});+ check(fallback==std::vector<int64_t>{0},"fallback with unknown rate stays unknown instead of fabricating 59.94");+ CaptureFormat nv12;nv12.index=0;nv12.width=1920;nv12.height=1080;nv12.interval100ns=166667;nv12.fps=1e7/166667;nv12.pixel=L"NV12";nv12.key=L"nv12";+ auto yuy2=nv12;yuy2.index=1;yuy2.interval100ns=166666;yuy2.fps=1e7/166666;yuy2.pixel=L"YUY2";yuy2.key=L"yuy2";+ std::vector<CaptureFormat> formats{nv12,yuy2};+ const auto all=captureFrameRateOptions(formats,&formats.front());+ check(all.size()==1,"rounding variants form one display group");+ check(captureFrameRateId(nv12)!=captureFrameRateId(yuy2),"display grouping never changes exact interval identity");+ for(bool showAll:{false,true}){+ const auto rows=captureVisibleFrameRates(all,all.front().id,showAll);+ check(rows.size()==1,"common and complete lists retain the same valid 60fps group");+ const auto* sample=captureRateSample(formats,L"1920x1080",rows.front().id);+ const auto pixels=capturePixelOptions(formats,sample);+ check(pixels.size()==2,"both NV12 and YUY2 remain reachable through the grouped menu");+ check(selectCapturePixelFormat(formats,L"1920x1080",rows.front().id,yuy2.key)==&formats[1],"pixel selection resolves the exact original YUY2 record");+ }+ auto ntsc=nv12;ntsc.key=L"ntsc";ntsc.interval100ns=166833;ntsc.fps=1e7/166833;formats.push_back(ntsc);+ auto interlaced=nv12;interlaced.key=L"interlaced";interlaced.interlaced=true;formats.push_back(interlaced);+ check(captureFrameRateOptions(formats,&formats.front()).size()==3,"60, 59.94 and interlaced groups remain separate");+ check(!selectCapturePixelFormat(formats,L"1920x1080",all.front().id,L"ntsc"),"60fps selection cannot silently open 59.94");+ check(!selectCapturePixelFormat(formats,L"1920x1080",all.front().id,L"interlaced"),"progressive selection cannot open interlaced media");+ const auto start=std::chrono::steady_clock::now();+ formats.clear();+ for(int i=0;i<16000;++i){auto f=nv12;f.index=i;f.key=std::format(L"mode{}",i);formats.push_back(std::move(f));}+ check(captureResolutionOptions(formats).size()==1&&captureFrameRateOptions(formats,&formats.front()).size()==1,"large capability sets keep compact linked menus");+ check(capturePixelOptions(formats,&formats.front()).size()==16000,"large exact-mode lists remain available without quadratic duplicate counting");+ const auto elapsed=std::chrono::duration<double>(std::chrono::steady_clock::now()-start).count();+ std::cout<<"Capture capability tests: "<<checks<<" checks, "<<failures<<" failures; 16000-mode case "<<elapsed<<" s\n";+ return failures?1:0;+}diff --git a/tests/unit/DirectShowFormatDiscoveryTests.cpp b/tests/unit/DirectShowFormatDiscoveryTests.cppnew file mode 100644index 00000000..14354d86--- /dev/null+++ b/tests/unit/DirectShowFormatDiscoveryTests.cpp@@ -0,0 +1,170 @@+#include "veyra/source/DirectShowFormatDiscovery.h"+#include <array>+#include <iostream>++using namespace veyra::source;+using namespace veyra::source::dshow;+namespace {+unsigned checks=0,failures=0;+void check(bool ok,const char* text){++checks;if(!ok){++failures;std::cerr<<"FAIL "<<text<<'\n';}}+OwnedCaptureType media(bool info2=false,LONG width=1920,LONG height=1080,REFERENCE_TIME interval=166667){+ AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;+ type.subtype={captureFourcc('N','V','1','2'),0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};+ type.formattype=info2?FORMAT_VideoInfo2:FORMAT_VideoInfo;+ type.bFixedSizeSamples=TRUE;+ VIDEOINFOHEADER v1{};VIDEOINFOHEADER2 v2{};+ auto& bitmap=info2?v2.bmiHeader:v1.bmiHeader;+ bitmap.biSize=sizeof(BITMAPINFOHEADER);bitmap.biWidth=width;bitmap.biHeight=height;bitmap.biBitCount=12;bitmap.biCompression=type.subtype.Data1;bitmap.biPlanes=1;+ v1.AvgTimePerFrame=v2.AvgTimePerFrame=interval;+ type.cbFormat=info2?sizeof(v2):sizeof(v1);type.pbFormat=reinterpret_cast<BYTE*>(info2?static_cast<void*>(&v2):static_cast<void*>(&v1));+ return cloneCaptureType(type);+}+AM_MEDIA_TYPE* detached(const AM_MEDIA_TYPE& type){+ auto owned=cloneCaptureType(type);if(!owned)return nullptr;+ auto* copy=static_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));+ if(!copy)return nullptr;*copy=*owned;owned->pbFormat=nullptr;owned->pUnk=nullptr;owned->cbFormat=0;return copy;+}+struct MediaEnum final:IEnumMediaTypes {+ std::vector<OwnedCaptureType> types;size_t index=0;+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID,void**) override{return E_NOINTERFACE;}+ ULONG STDMETHODCALLTYPE AddRef() override{return 1;}ULONG STDMETHODCALLTYPE Release() override{return 1;}+ HRESULT STDMETHODCALLTYPE Next(ULONG count,AM_MEDIA_TYPE** out,ULONG* fetched) override{+ if(fetched)*fetched=0;if(count!=1)return E_INVALIDARG;if(index>=types.size())return S_FALSE;+ *out=detached(*types[index++]);if(fetched)*fetched=1;return *out?S_OK:E_OUTOFMEMORY;+ }+ HRESULT STDMETHODCALLTYPE Skip(ULONG count) override{index+=count;return index<=types.size()?S_OK:S_FALSE;}+ HRESULT STDMETHODCALLTYPE Reset() override{index=0;return S_OK;}+ HRESULT STDMETHODCALLTYPE Clone(IEnumMediaTypes**) override{return E_NOTIMPL;}+};+struct Driver final:IAMStreamConfig {+ HRESULT capsResult=S_OK;int failIndex=-1,bytes=sizeof(VIDEO_STREAM_CONFIG_CAPS);+ std::vector<OwnedCaptureType> types;+ VIDEO_STREAM_CONFIG_CAPS range{};+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID,void**) override{return E_NOINTERFACE;}+ ULONG STDMETHODCALLTYPE AddRef() override{return 1;}ULONG STDMETHODCALLTYPE Release() override{return 1;}+ HRESULT STDMETHODCALLTYPE SetFormat(AM_MEDIA_TYPE*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE GetFormat(AM_MEDIA_TYPE** out) override{if(types.empty())return E_NOTIMPL;*out=detached(*types.front());return S_OK;}+ HRESULT STDMETHODCALLTYPE GetNumberOfCapabilities(int* count,int* size) override{*count=int(types.size());*size=bytes;return capsResult;}+ HRESULT STDMETHODCALLTYPE GetStreamCaps(int index,AM_MEDIA_TYPE** out,BYTE* caps) override{+ if(index==failIndex)return E_FAIL;if(index<0||size_t(index)>=types.size())return E_INVALIDARG;+ if(bytes>=int(sizeof(range)))std::memcpy(caps,&range,sizeof(range));*out=detached(*types[size_t(index)]);return *out?S_OK:E_OUTOFMEMORY;+ }+};+struct Pin final:IPin,IKsPropertySet {+ Driver* driver=nullptr;MediaEnum enumerator;+ PIN_DIRECTION direction=PINDIR_OUTPUT;bool categorized=false;GUID category=PIN_CATEGORY_CAPTURE;unsigned enumCalls=0;HRESULT categoryResult=S_OK;+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** out) override{+ *out=nullptr;+ if(id==IID_IAMStreamConfig&&driver)*out=static_cast<IAMStreamConfig*>(driver);+ else if(id==IID_IKsPropertySet&&categorized)*out=static_cast<IKsPropertySet*>(this);+ else if(id==IID_IPin||id==IID_IUnknown)*out=static_cast<IPin*>(this);+ else return E_NOINTERFACE;+ return S_OK;+ }+ ULONG STDMETHODCALLTYPE AddRef() override{return 1;}ULONG STDMETHODCALLTYPE Release() override{return 1;}+ HRESULT STDMETHODCALLTYPE Connect(IPin*,const AM_MEDIA_TYPE*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE ReceiveConnection(IPin*,const AM_MEDIA_TYPE*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE Disconnect() override{return S_OK;}+ HRESULT STDMETHODCALLTYPE ConnectedTo(IPin**) override{return VFW_E_NOT_CONNECTED;}+ HRESULT STDMETHODCALLTYPE ConnectionMediaType(AM_MEDIA_TYPE*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryPinInfo(PIN_INFO*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* out) override{*out=direction;return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryId(LPWSTR*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE*) override{return S_OK;}+ HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes** out) override{++enumCalls;enumerator.index=0;*out=&enumerator;return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryInternalConnections(IPin**,ULONG*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE EndOfStream() override{return S_OK;}HRESULT STDMETHODCALLTYPE BeginFlush() override{return S_OK;}+ HRESULT STDMETHODCALLTYPE EndFlush() override{return S_OK;}HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME,REFERENCE_TIME,double) override{return S_OK;}+ HRESULT STDMETHODCALLTYPE Set(REFGUID,DWORD,LPVOID,DWORD,LPVOID,DWORD) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE Get(REFGUID,DWORD,LPVOID,DWORD,LPVOID out,DWORD size,DWORD* bytes) override{+ if(FAILED(categoryResult))return categoryResult;+ if(size<sizeof(GUID))return E_INVALIDARG;std::memcpy(out,&category,sizeof(category));*bytes=sizeof(category);return S_OK;+ }+ HRESULT STDMETHODCALLTYPE QuerySupported(REFGUID,DWORD,DWORD*) override{return E_NOTIMPL;}+};+struct PinEnum final:IEnumPins {+ std::vector<Pin*> pins;size_t index=0;+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID,void**) override{return E_NOINTERFACE;}+ ULONG STDMETHODCALLTYPE AddRef() override{return 1;}ULONG STDMETHODCALLTYPE Release() override{return 1;}+ HRESULT STDMETHODCALLTYPE Next(ULONG count,IPin** out,ULONG* fetched) override{+ if(fetched)*fetched=0;if(count!=1)return E_INVALIDARG;if(index>=pins.size())return S_FALSE;+ *out=static_cast<IPin*>(pins[index++]);if(fetched)*fetched=1;return S_OK;+ }+ HRESULT STDMETHODCALLTYPE Skip(ULONG count) override{index+=count;return S_OK;}+ HRESULT STDMETHODCALLTYPE Reset() override{index=0;return S_OK;}+ HRESULT STDMETHODCALLTYPE Clone(IEnumPins**) override{return E_NOTIMPL;}+};+struct Filter final:IBaseFilter {+ PinEnum enumerator;+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID,void**) override{return E_NOINTERFACE;}+ ULONG STDMETHODCALLTYPE AddRef() override{return 1;}ULONG STDMETHODCALLTYPE Release() override{return 1;}+ HRESULT STDMETHODCALLTYPE GetClassID(CLSID*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE Stop() override{return S_OK;}HRESULT STDMETHODCALLTYPE Pause() override{return S_OK;}+ HRESULT STDMETHODCALLTYPE Run(REFERENCE_TIME) override{return S_OK;}+ HRESULT STDMETHODCALLTYPE GetState(DWORD,FILTER_STATE*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE SetSyncSource(IReferenceClock*) override{return S_OK;}+ HRESULT STDMETHODCALLTYPE GetSyncSource(IReferenceClock**) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE EnumPins(IEnumPins** out) override{enumerator.index=0;*out=&enumerator;return S_OK;}+ HRESULT STDMETHODCALLTYPE FindPin(LPCWSTR,IPin**) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE QueryFilterInfo(FILTER_INFO*) override{return E_NOTIMPL;}+ HRESULT STDMETHODCALLTYPE JoinFilterGraph(IFilterGraph*,LPCWSTR) override{return S_OK;}+ HRESULT STDMETHODCALLTYPE QueryVendorInfo(LPWSTR*) override{return E_NOTIMPL;}+};+}+int main(){+ Driver driver;Pin pin;pin.driver=&driver;pin.enumerator.types={media(false,1920,1080,0)};+ driver.capsResult=E_NOTIMPL;+ auto fallback=discoverCaptureTypes(&driver,&pin);+ check(fallback.types.size()==1&&fallback.fallback&&SUCCEEDED(fallback.result),"unimplemented caps use EnumMediaTypes");+ check(*captureVideoHeader(*fallback.types.front().media).interval==0,"unknown fallback rate is preserved");+ driver.capsResult=E_ACCESSDENIED;pin.enumCalls=0;+ const auto denied=discoverCaptureTypes(&driver,&pin);+ check(denied.types.empty()&&denied.result==E_ACCESSDENIED&&pin.enumCalls==0,"access denied is not concealed by fallback");+ driver.capsResult=S_OK;driver.bytes=0;+ check(discoverCaptureTypes(&driver,&pin).types.size()==1,"empty size-zero capability list can fall back");+ driver.bytes=sizeof(VIDEO_STREAM_CONFIG_CAPS);driver.types={media(true,0,0,333667)};+ driver.range.MinOutputSize={640,480};driver.range.MaxOutputSize={1920,1080};driver.range.OutputGranularityX=16;driver.range.OutputGranularityY=2;+ driver.range.MinFrameInterval=166666;driver.range.MaxFrameInterval=333667;+ auto ranged=discoverCaptureTypes(&driver,&pin);+ check(ranged.types.size()==1&&ranged.types.front().range.acceptsSize(1280,720),"range remains usable with an empty template size");+ auto resized=captureTypeForMode(ranged.types.front(),1280,720,166667);+ check(resized&&resized->lSampleSize==1280*720*3/2,"NV12 range request rebuilds image sample size");+ auto resizedHeader=captureVideoHeader(*resized);+ check(resizedHeader.bitmap->biWidth==1280&&resizedHeader.bitmap->biHeight==720&&*resizedHeader.interval==166667,"concrete type has selected dimensions and exact interval");+ check(captureVideoHeader(*ranged.types.front().media).bitmap->biWidth==0,"template is never mutated by a selection");+ check(!captureTypeForMode(ranged.types.front(),1279,720,166667),"out-of-step dimensions are rejected");+ auto same=cloneCaptureType(*resized);check(captureTypesMatch(*resized,*same),"exact connected contract accepted");+ ++*captureVideoHeader(*same).interval;check(captureTypesMatch(*resized,*same),"one 100ns integer rounding tick accepted");+ *captureVideoHeader(*same).interval=166833;check(!captureTypesMatch(*resized,*same),"59.94 cannot replace selected 60fps");+ same=cloneCaptureType(*resized);captureVideoHeader(*same).bitmap->biWidth=1920;check(!captureTypesMatch(*resized,*same),"size substitution rejected");+ same=cloneCaptureType(*resized);same->subtype=MEDIASUBTYPE_YUY2;check(!captureTypesMatch(*resized,*same),"pixel substitution rejected");+ same=cloneCaptureType(*resized);reinterpret_cast<VIDEOINFOHEADER2*>(same->pbFormat)->dwInterlaceFlags=AMINTERLACE_IsInterlaced;+ check(!captureTypesMatch(*resized,*same),"interlaced substitution rejected");+ driver.types.push_back(media());driver.failIndex=1;+ const auto partial=discoverCaptureTypes(&driver,&pin);+ check(partial.types.size()==1&&partial.failed==1&&FAILED(partial.result),"partial caps failure retains good types and an explicit error");+ driver.types.resize(1);driver.failIndex=0;+ const auto failedCapsFallback=discoverCaptureTypes(&driver,&pin);+ check(failedCapsFallback.types.size()==1&&failedCapsFallback.fallback&&failedCapsFallback.result==E_FAIL&&+ std::wstring_view(failedCapsFallback.stage)==L"GetStreamCaps","successful fallback preserves the real earlier failure stage");+ auto malformed=media();malformed->cbFormat=1;driver.types={malformed};driver.failIndex=-1;+ check(discoverCaptureTypes(&driver,&pin).fallback,"malformed format block is rejected before fallback");+ Driver normal;normal.types={media()};Pin preview,capture,unknown,other,input;+ for(auto* p:{&preview,&capture,&unknown,&other,&input}){p->driver=&normal;p->enumerator.types=normal.types;}+ preview.categorized=true;preview.category=PIN_CATEGORY_PREVIEW;capture.categorized=true;input.direction=PINDIR_INPUT;+ Filter filter;filter.enumerator.pins={&preview,&unknown,&capture};ComPtr<IPin> selected;+ check(SUCCEEDED(findCaptureVideoPin(&filter,selected))&&selected.Get()==static_cast<IPin*>(&capture),"explicit capture pin wins over preview and uncategorized video");+ filter.enumerator.pins={&preview,&input,&unknown};+ check(SUCCEEDED(findCaptureVideoPin(&filter,selected))&&selected.Get()==static_cast<IPin*>(&unknown),"unique uncategorized video output is compatible");+ unknown.categorized=true;unknown.categoryResult=E_PROP_ID_UNSUPPORTED;+ check(SUCCEEDED(findCaptureVideoPin(&filter,selected))&&selected.Get()==static_cast<IPin*>(&unknown),"missing category property is compatible");+ unknown.categoryResult=E_PROP_SET_UNSUPPORTED;+ check(SUCCEEDED(findCaptureVideoPin(&filter,selected))&&selected.Get()==static_cast<IPin*>(&unknown),"missing category property set is compatible");+ unknown.categoryResult=E_ACCESSDENIED;+ check(FAILED(findCaptureVideoPin(&filter,selected)),"category access failure is not treated as missing metadata");+ unknown.categorized=false;+ filter.enumerator.pins={&unknown,&other};+ check(FAILED(findCaptureVideoPin(&filter,selected))&&!selected,"ambiguous uncategorized outputs cannot be silently guessed");+ std::cout<<"DirectShow format discovery: "<<checks<<" checks, "<<failures<<" failures\n";+ return failures?1:0;+}