From 53378c64950f7d192e10084c042a5769786f6e8d Mon Sep 17 00:00:00 2001 From: "Mark.lin" Date: Tue, 9 Jun 2026 10:02:10 +0800 Subject: [PATCH] Initial standalone GVFG SDK --- .gitignore | 15 + CMakeLists.txt | 29 + README.md | 55 + docs/GVFG_CUSTOMER_API.md | 1271 +++++++++ docs/GVFG_DIRECT_SDK_PLAN.md | 44 + samples/gvfg_qt_preview/CMakeLists.txt | 54 + samples/gvfg_qt_preview/main.cpp | 13 + samples/gvfg_qt_preview/mainwindow.cpp | 459 +++ samples/gvfg_qt_preview/mainwindow.h | 61 + samples/gvfg_qt_preview/mainwindow.ui | 84 + samples/gvfg_qt_preview/previewwindow.cpp | 47 + samples/gvfg_qt_preview/previewwindow.h | 32 + samples/gvfg_qt_preview/previewwindow.ui | 31 + sdk/gcapture/include/gcap_audio.h | 97 + sdk/gcapture/include/gcapture.h | 871 ++++++ sdk/gcapture/src/core/logging.h | 19 + .../src/pipeline/shared_scene_pipeline.cpp | 2519 +++++++++++++++++ .../src/pipeline/shared_scene_pipeline.h | 129 + sdk/gdriver_shared/include/gdriver_abi.h | 197 ++ .../include/gdriver_control_codes.h | 41 + sdk/gvfg/CMakeLists.txt | 54 + sdk/gvfg/include/gvfg_capture.h | 458 +++ .../src/backend/xdma/xdma_backend_types.h | 118 + .../src/backend/xdma/xdma_capture_session.cpp | 1699 +++++++++++ .../src/backend/xdma/xdma_capture_session.h | 128 + sdk/gvfg/src/backend/xdma/xdma_public.h | 34 + sdk/gvfg/src/gcapture_log_bridge.cpp | 62 + sdk/gvfg/src/gvfg_capture.cpp | 1145 ++++++++ 28 files changed, 9766 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 docs/GVFG_CUSTOMER_API.md create mode 100644 docs/GVFG_DIRECT_SDK_PLAN.md create mode 100644 samples/gvfg_qt_preview/CMakeLists.txt create mode 100644 samples/gvfg_qt_preview/main.cpp create mode 100644 samples/gvfg_qt_preview/mainwindow.cpp create mode 100644 samples/gvfg_qt_preview/mainwindow.h create mode 100644 samples/gvfg_qt_preview/mainwindow.ui create mode 100644 samples/gvfg_qt_preview/previewwindow.cpp create mode 100644 samples/gvfg_qt_preview/previewwindow.h create mode 100644 samples/gvfg_qt_preview/previewwindow.ui create mode 100644 sdk/gcapture/include/gcap_audio.h create mode 100644 sdk/gcapture/include/gcapture.h create mode 100644 sdk/gcapture/src/core/logging.h create mode 100644 sdk/gcapture/src/pipeline/shared_scene_pipeline.cpp create mode 100644 sdk/gcapture/src/pipeline/shared_scene_pipeline.h create mode 100644 sdk/gdriver_shared/include/gdriver_abi.h create mode 100644 sdk/gdriver_shared/include/gdriver_control_codes.h create mode 100644 sdk/gvfg/CMakeLists.txt create mode 100644 sdk/gvfg/include/gvfg_capture.h create mode 100644 sdk/gvfg/src/backend/xdma/xdma_backend_types.h create mode 100644 sdk/gvfg/src/backend/xdma/xdma_capture_session.cpp create mode 100644 sdk/gvfg/src/backend/xdma/xdma_capture_session.h create mode 100644 sdk/gvfg/src/backend/xdma/xdma_public.h create mode 100644 sdk/gvfg/src/gcapture_log_bridge.cpp create mode 100644 sdk/gvfg/src/gvfg_capture.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..520be7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +build*/ +out/ +.vs/ +.vscode/ +.qtcreator/ +CMakeUserPresets.json +*.user +*.suo +*.obj +*.pdb +*.ilk +*.exp +*.lib +*.dll +*.exe diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..a0bf797 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,29 @@ +cmake_minimum_required(VERSION 3.16) + +project(gvfg_standalone VERSION 0.1.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(GVFG_SDK_VERSION "${PROJECT_VERSION}" CACHE STRING "GVFG SDK version") + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTORCC ON) + +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") + +option(BUILD_GVFG_SAMPLES "Build GVFG customer samples" ON) +option(GVFG_XDMA_DEBUG_LOG "Enable verbose XDMA flow debug logging in GVFG internal XDMA backend" OFF) + +if (NOT WIN32) + message(FATAL_ERROR "GVFG currently supports Windows only.") +endif() + +add_subdirectory(sdk/gvfg) + +if (BUILD_GVFG_SAMPLES) + add_subdirectory(samples/gvfg_qt_preview) +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..45a5cf6 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# GVFG Standalone SDK + +This is the standalone source tree for the GVFG capture SDK. + +GVFG is the source of truth here. Other projects should consume GVFG through +the exported public header, import library, and runtime DLL instead of compiling +the GVFG source directly. + +## Contents + +- `sdk/gvfg`: GVFG public C API and internal XDMA backend. +- `sdk/gdriver_shared/include`: shared driver ABI headers required by the backend. +- `sdk/gcapture`: minimal shared render/logging code currently required by GVFG preview. +- `samples/gvfg_qt_preview`: customer-facing Qt preview sample. +- `docs`: API and integration notes. + +## Build + +Open this folder's `CMakeLists.txt` in Qt Creator with a Windows MSVC Qt kit, or +configure from a Visual Studio developer shell. + +Example: + +```bat +cmake -S . -B build -DBUILD_GVFG_SAMPLES=ON -DCMAKE_PREFIX_PATH=C:\Qt\6.10.2\msvc2022_64 +cmake --build build --target gvfg_qt_preview --config Release +``` + +Useful CMake options: + +```text +BUILD_GVFG_SAMPLES=ON +GVFG_XDMA_DEBUG_LOG=OFF +``` + +Build outputs: + +```text +build/.../bin/gvfg.dll +build/.../lib/gvfg.lib +build/.../bin/gvfg_qt_preview.exe +``` + +## Consumer Layout + +Applications should consume the SDK with: + +```text +include/gvfg_capture.h +lib/gvfg.lib +bin/gvfg.dll +``` + +The XDMA backend and driver ABI headers are implementation details and should not +be included by customer applications. diff --git a/docs/GVFG_CUSTOMER_API.md b/docs/GVFG_CUSTOMER_API.md new file mode 100644 index 0000000..d80b80b --- /dev/null +++ b/docs/GVFG_CUSTOMER_API.md @@ -0,0 +1,1271 @@ +# GVFG 客戶 API 使用說明 + +這份文件說明 VFG100 / GVFG capture SDK 對外給客戶使用的 C API。API 名稱統一使用 `gvfg_` prefix;`XDMA` 只代表目前底層 driver/backend。 + +目前 API 定義在: + +```text +sdk/gvfg/include/gvfg_capture.h +``` + +`gvfg` 是獨立的 GVFG capture SDK。它和 `gcapture` 分開,所以只需要 VFG100 / GVFG 功能的客戶,不需要看到或使用 DirectShow / Media Foundation 那一批 API。 + +後續 XDMA driver/backend 還會持續開發,所以這份文件先以中文維護。等 API 和流程穩定後,再整理英文版給客戶。 + +## 要提供給客戶的檔案 + +Windows app 使用 GVFG capture 時,執行檔旁邊需要放: + +```text +gvfg.dll +``` + +開發時需要 include: + +```text +sdk/gvfg/include +``` + +客戶端只需要 include: + +```c +#include +``` + +下面這些是 SDK 內部檔案,不是客戶 API: + +```text +None. Internal XDMA backend/gdriver headers are not distributed. +``` + +link: + +```text +gvfg.lib +``` + +最小 Qt UI 範例: + +```text +samples/gvfg_qt_preview +``` + +這個 sample 只示範 GVFG API,不依賴原本 `apps/qt6_viewer`。 + +CMake build option: + +```text +BUILD_GVFG_SDK=ON +``` + +如果要開 XDMA flow debug log: + +```text +GVFG_XDMA_DEBUG_LOG=ON +``` + +debug log 目前會走 `OutputDebugStringA`,viewer 也會把部分 log 顯示到 debug panel / log file。 + +## 整體架構 + +目前 XDMA 分成兩層: + +```text +客戶 App + | + | include gvfg_capture.h + | link gvfg.lib + v +gvfg.dll + | + | 對外提供簡單 XDMA capture API + | 管理 preview、callback、runtime info + v +gvfg.dll + | + | 低階 XDMA driver access + | enumerate / open / c2h read / event / signal + v +XDMA Windows driver +``` + +目前 preview path: + +```text +XDMA C2H 讀到 YUY2 frame +-> GVFG internal XDMA backend 收 driver buffer +-> gvfg 拿 frame +-> D3D SharedScenePipeline +-> GPU shader 做 YUY2 -> RGB +-> D3D swapchain present 到客戶提供的 HWND +``` + +重點: + +- 主要 preview 是 D3D swapchain 直接畫到 `HWND`。 +- frame callback 目前主要給 snapshot、UI 狀態、或 fallback preview 用。 +- callback 不是主要零拷貝 preview path。 + +## 建議使用流程 + +一般客戶程式照這個順序: + +```text +gvfg_enumerate_devices +-> gvfg_create +-> gvfg_set_callbacks +-> gvfg_set_frame_callback_interval (optional) +-> gvfg_set_event_callback (optional) +-> gvfg_open +-> gvfg_start +-> capture running +-> gvfg_get_signal_status / gvfg_get_runtime_info +-> gvfg_stop +-> gvfg_destroy +``` + +簡單說: + +1. 先列出 XDMA 裝置。 +2. 建立一個 `gvfg_handle`。 +3. 設 callback。 +4. 視需求設定 callback 速率。 +5. 視需求設定 event callback。 +6. open device。 +7. start stream。 +8. stop / destroy。 + +如果客戶想使用 SDK 內建 D3D preview helper,才需要多呼叫: + +```text +gvfg_set_preview +gvfg_get_preview_info +``` + +如果客戶要自己畫畫面,就不要呼叫 `gvfg_set_preview()`,直接使用 frame callback 或未來的 GPU texture API。 + +## 型別說明 + +### gvfg_handle + +```c +typedef struct gvfg_handle_t *gvfg_handle; +``` + +這是 SDK session handle。 + +客戶不要直接存取裡面的內容,只能透過 API 操作。 + +生命週期: + +```text +gvfg_create +-> 使用 handle +-> gvfg_destroy +``` + +## gvfg_status_t + +大部分 API 都會回傳這個 status。 + +```c +typedef enum +{ + GVFG_OK = 0, + GVFG_EINVAL = -1, + GVFG_ENODEV = -2, + GVFG_ESTATE = -3, + GVFG_EIO = -4, + GVFG_ENOTSUP = -5, + GVFG_ETIMEOUT = -6 +} gvfg_status_t; +``` + +| 值 | 意義 | +| --- | --- | +| `GVFG_OK` | 成功 | +| `GVFG_EINVAL` | 參數錯誤,例如傳入 null pointer | +| `GVFG_ENODEV` | 找不到裝置,或目前沒有有效 signal | +| `GVFG_ESTATE` | 狀態錯誤,例如還沒 open 就 start | +| `GVFG_EIO` | driver I/O 錯誤 | +| `GVFG_ENOTSUP` | 功能尚未支援,或 preview pipeline 無法建立 | +| `GVFG_ETIMEOUT` | 等待 frame / event timeout | + +如果要把錯誤碼轉成人能看的字串,用: + +```c +gvfg_strerror(status) +``` + +## gvfg_preview_bitdepth_t + +preview swapchain bit-depth 設定。 + +```c +typedef enum +{ + GVFG_PREVIEW_BITDEPTH_AUTO = 0, + GVFG_PREVIEW_BITDEPTH_10BIT = 10, + GVFG_PREVIEW_BITDEPTH_8BIT = 8 +} gvfg_preview_bitdepth_t; +``` + +| 值 | 意義 | +| --- | --- | +| `GVFG_PREVIEW_BITDEPTH_AUTO` | 讓 SDK 自己判斷 | +| `GVFG_PREVIEW_BITDEPTH_10BIT` | 要求 10-bit swapchain,如果環境支援 | +| `GVFG_PREVIEW_BITDEPTH_8BIT` | 強制 8-bit swapchain | + +目前 XDMA input 是 8-bit YUY2,所以通常會建立 8-bit BGRA swapchain。 + +## gvfg_device_info_t + +列舉裝置時回傳的裝置資料。 + +```c +typedef struct +{ + int index; + char name[128]; +} gvfg_device_info_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `index` | 裝置 index,之後給 `gvfg_open()` 使用 | +| `name` | 顯示名稱,例如 `XDMA Capture Device 0` | + +## gvfg_preview_desc_t + +preview 設定。 + +```c +typedef struct +{ + void *hwnd; + int enable_preview; + int swapchain_bitdepth; +} gvfg_preview_desc_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `hwnd` | 要讓 SDK 畫 preview 的 Win32 `HWND` | +| `enable_preview` | `1` 啟用 preview,`0` 關閉 preview | +| `swapchain_bitdepth` | `gvfg_preview_bitdepth_t` 的值 | + +注意: + +- `hwnd` 必須是 native Win32 window handle。 +- capture running 的時候,這個 window 必須還活著。 +- 如果 app 是 Qt / WinForms / WPF,要拿到真正可用的 native HWND。 + +## gvfg_signal_status_t + +目前 input signal 狀態。 + +```c +typedef struct +{ + int width; + int height; + double fps; + int bit_depth; + char pixel_format[32]; +} gvfg_signal_status_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `width` | input 寬度 | +| `height` | input 高度 | +| `fps` | Legacy field;GVFG 固定回 `0`,請使用 `fpga.frame_rate_*` | +| `bit_depth` | Legacy SDK source-buffer bit depth;FPGA bit depth 請使用 `fpga.bit_depth` | +| `pixel_format` | Legacy SDK source-buffer format;callback buffer format 請使用 `gvfg_runtime_info_t::delivered_frame` | + + +### Customer buffer vs FPGA signal + +The customer API separates the delivered buffer format from the FPGA signal +register values. + +```c +typedef struct +{ + uint32_t valid_mask; /* FPGA register read-valid mask: bit0=0x0c, bit1=0x18, bit2=0x1c, bit3=0x180. */ + int width_valid; /* Non-zero when FPGA 0x10 read succeeded. */ + int height_valid; /* Non-zero when FPGA 0x14 read succeeded. */ + uint32_t width_raw; /* Raw FPGA 0x10 width register. */ + uint32_t height_raw; /* Raw FPGA 0x14 height register. */ + uint32_t video_format_raw; /* Raw FPGA 0x0c value. */ + int video_format_valid; + int video_format_code; /* 0=yuv422, 1=rgb, 2=yuv444, 3=yuv420 */ + char video_format[16]; + + uint32_t frame_rate_raw; /* Raw FPGA 0x18 value. */ + int frame_rate_valid; + int frame_rate_code; /* FPGA 0x18 low nibble. */ + char frame_rate_bits[5]; /* 4-bit binary text, for example "0110". */ + char frame_rate_name[16]; /* None, 23.98, 24, 47.95, ..., or "--" for unsupported codes. */ + + uint32_t bit_depth_raw; /* Raw FPGA 0x1c value. */ + int bit_depth_valid; + int bit_depth; /* FPGA signal bit depth: 8 or 10 when valid. */ + + uint32_t status_raw; /* Raw FPGA 0x180 value. */ + int status_valid; + int sdi_locked; /* FPGA 0x180 bit0 */ + int sdi_ddr_ok; /* FPGA 0x180 bit1 */ + int hdmi_locked; /* FPGA 0x180 bit2 */ + int hdmi_ddr_ok; /* FPGA 0x180 bit3 */ +} gvfg_fpga_signal_status_t; + +typedef struct +{ + int width; /* Signal width in pixels, from FPGA when available. */ + int height; /* Signal height in pixels, from FPGA when available. */ + double fps; /* Legacy field; GVFG leaves this 0. Use fpga.frame_rate_* instead. */ + int bit_depth; /* Legacy SDK source-buffer field. Prefer fpga.* and runtime delivered_frame. */ + char pixel_format[32]; /* Legacy SDK source-buffer field. Prefer fpga.* and runtime delivered_frame. */ + gvfg_fpga_signal_status_t fpga; /* Raw/decoded FPGA signal metadata. */ +} gvfg_signal_status_t; +``` + +Use `gvfg_signal_status_t::fpga` for FPGA-reported raw/decoded signal data. +For delivered frame format, prefer `gvfg_runtime_info_t::delivered_frame`. + +For example, if FPGA reports `video_format=YUV422` and `bit_depth=10`, the +hardware signal should be treated as YUV422 10-bit. The current GVFG callback +buffer is a rendered BGRA8 frame, reported through +`gvfg_runtime_info_t::delivered_frame`. + +FPGA frame-rate code table: + +| Bits | Name | +| --- | --- | +| `0000` | None | +| `0010` | 23.98 | +| `0011` | 24 | +| `0100` | 47.95 | +| `0101` | 25 | +| `0110` | 29.97 | +| `0111` | 30 | +| `1000` | 48 | +| `1001` | 50 | +| `1010` | 59.94 | +| `1011` | 60 | + +All other codes, including `0001`, are reported as `--`. + +## gvfg_runtime_info_t + +runtime debug/status 資訊。 + +```c +typedef struct +{ + int width; + int height; + int bit_depth; + char pixel_format[32]; + int valid; +} gvfg_delivered_frame_info_t; + +typedef struct +{ + gvfg_signal_status_t input_signal; + gvfg_delivered_frame_info_t delivered_frame; + double capture_fps; + uint64_t delivered_frames; +} gvfg_runtime_info_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `input_signal` | 目前 input signal 狀態 | +| `delivered_frame` | Frame buffer delivered by gvfg.dll to the app callback: valid, width, height, pixel format, bit depth | +| `capture_fps` | SDK capture thread 從 backend frame 測到的 FPS | +| `delivered_frames` | SDK 已送到 app callback 的 frame 數 | + +Source ownership: + +- FPGA reported signal: use `input_signal.fpga.*`. +- Delivered callback buffer: use `delivered_frame.*`. `valid=0` means no callback frame is currently available/reported. +- App/SDK runtime counters: use `capture_fps` and `delivered_frames`. + +這個 struct 適合顯示在: + +- status bar +- debug panel +- support log +- 客戶回報問題時的診斷資訊 + +注意: + +`gvfg_runtime_info_t` 是 core capture runtime 狀態,不描述 preview/render。 +如果要查 SDK 內建 D3D preview helper 的 render/swapchain 狀態,請用 `gvfg_get_preview_info()`。 + +## gvfg_preview_info_t + +optional preview helper 的狀態。 + +如果客戶自己畫畫面,不使用 `gvfg_set_preview()`,這個 struct 通常不需要使用。 + +```c +typedef struct +{ + int enabled; + int active; + int width; + int height; + int swapchain_bitdepth; + int swapchain_10bit; + char render_path[128]; + char backbuffer_format[64]; +} gvfg_preview_info_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `enabled` | app 是否有啟用 SDK preview helper | +| `active` | preview pipeline / swapchain 是否已建立 | +| `width` | preview swapchain 寬度 | +| `height` | preview swapchain 高度 | +| `swapchain_bitdepth` | 目前/要求的 swapchain bit depth | +| `swapchain_10bit` | 目前 swapchain 是否是 10-bit | +| `render_path` | SDK preview helper 的 render path | +| `backbuffer_format` | D3D swapchain backbuffer format | + +這些資訊只描述 SDK 內建 preview helper,不代表客戶 app 自己的 rendering pipeline。 + +## gvfg_frame_t + +frame callback 的 payload。 + +```c +typedef struct +{ + const void *data; + int stride; + int width; + int height; + uint64_t pts_ns; + uint64_t frame_id; +} gvfg_frame_t; +``` + +| 欄位 | 意義 | +| --- | --- | +| `data` | pixel data pointer | +| `stride` | 每一列 bytes | +| `width` | frame 寬度 | +| `height` | frame 高度 | +| `pts_ns` | timestamp,單位 ns | +| `frame_id` | frame counter | + +重要: + +- `data` 只在 callback 當下有效。 +- callback return 後不能再使用這個 pointer。 +- 如果客戶要存圖、做 snapshot、或丟給其他 thread,要自己 copy 一份。 +- 目前 callback 輸出是 8-bit BGRA-compatible 格式,在 Windows/Qt 可用 `QImage::Format_ARGB32` 接。 +- callback 由 SDK worker thread 呼叫,不是在 UI thread。 + +UI 程式要注意: + +```text +callback thread +-> copy frame +-> post / invoke 到 UI thread +-> UI thread 更新畫面 +``` + +不要直接在 callback 裡操作 UI control。 + +## Callback 型別 + +```c +typedef void (*gvfg_on_frame_cb)(const gvfg_frame_t *frame, void *user); +typedef void (*gvfg_on_error_cb)(gvfg_status_t status, const char *message, void *user); +``` + +### gvfg_on_frame_cb + +SDK 有 frame readback / fallback frame 時呼叫。 + +用途: + +- snapshot +- UI preview fallback +- 確認 XDMA frame 有進來 +- 客戶自己後處理 + +目前不建議把它當作主要高效 preview path。主要 preview 仍然是 D3D swapchain。 + +### gvfg_on_error_cb + +SDK 有錯誤或警告訊息時呼叫。 + +用途: + +- 顯示錯誤訊息 +- 寫 log +- debug / support + +## Function 說明 + +## gvfg_enumerate_devices + +```c +enum { GVFG_MAX_DEVICES = 16 }; + +int gvfg_enumerate_devices(gvfg_device_info_t *out_devices, int max_devices); +``` + +列出目前系統上的 GVFG capture device。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `out_devices` | 輸出 array。如果只想取得數量,可傳 `NULL` | +| `max_devices` | `out_devices` 最多可寫入幾個;SDK 上限是 `GVFG_MAX_DEVICES` / 16 | + +### 回傳值 + +| 回傳 | 意義 | +| --- | --- | +| `> 0` | 找到的裝置數量,或實際寫入數量 | +| `0` | 沒找到裝置 | +| `< 0` | enumerate 失敗 | + +### 範例 + +```c +gvfg_device_info_t devices[GVFG_MAX_DEVICES] = {0}; +int count = gvfg_enumerate_devices(devices, GVFG_MAX_DEVICES); + +for (int i = 0; i < count; ++i) { + printf("device %d: %s\n", devices[i].index, devices[i].name); +} +``` + +## gvfg_create + +```c +gvfg_status_t gvfg_create(gvfg_handle *out_handle); +``` + +建立一個 GVFG capture session。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `out_handle` | 輸出 handle,不可為 `NULL` | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 注意 + +這時候只是建立 session,還沒有 open device,也還沒有 start stream。 + +用完必須呼叫: + +```c +gvfg_destroy(handle); +``` + +## gvfg_destroy + +```c +gvfg_status_t gvfg_destroy(gvfg_handle handle); +``` + +釋放 GVFG capture session。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | `gvfg_create()` 回傳的 handle | + +### 回傳值 + +目前固定回傳 `GVFG_OK`。 + +### 注意 + +如果 capture 還在跑,destroy 時會自動 stop / close。 + +建議正常流程還是明確呼叫: + +```c +gvfg_stop(handle); +gvfg_destroy(handle); +``` + +## gvfg_set_callbacks + +```c +gvfg_status_t gvfg_set_callbacks(gvfg_handle handle, + gvfg_on_frame_cb on_frame, + gvfg_on_error_cb on_error, + void *user); +``` + +設定 frame callback 和 error callback。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `on_frame` | frame callback,可為 `NULL` | +| `on_error` | error callback,可為 `NULL` | +| `user` | 客戶自訂 pointer,callback 時會原樣帶回 | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 注意 + +callback 是從 SDK worker thread 呼叫。 + +如果是 GUI app,不要在 callback 裡直接更新 UI,請 marshal 到 UI thread。 + +## gvfg_set_frame_callback_interval + +```c +gvfg_status_t gvfg_set_frame_callback_interval(gvfg_handle handle, + uint32_t frame_interval); +``` + +設定 frame callback 的輸出頻率。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `frame_interval` | `0` 或 `1` 代表每張 frame 都 callback;`N > 1` 代表每 N 張 backend frame callback 一張 | + +### 行為 + +- 只影響 `on_frame` callback。 +- 不影響 SDK 內建 preview render。 +- 不影響實際採集速率。 +- 不影響 `gvfg_get_runtime_info()` 的 delivered frame 統計。 + +如果客戶要自己靠 callback 畫 preview,建議設 `1`。如果 callback 只拿來做 snapshot、log、或低頻 UI 狀態,可設 `6`、`30` 等較大的值。 + +## gvfg_set_event_callback + +```c +typedef enum +{ + GVFG_EVENT_VIDEO_IRQ = 1, + GVFG_EVENT_PLUG_IN = 2, + GVFG_EVENT_PLUG_OUT = 3, + GVFG_EVENT_CAPTURE_PAUSED = 4, + GVFG_EVENT_CAPTURE_RESUMED = 5 +} gvfg_event_type_t; + +typedef struct +{ + gvfg_event_type_t type; + uint32_t irq_bit; + uint32_t irq_mask; + uint64_t timestamp_ns; +} gvfg_event_t; + +typedef void (*gvfg_on_event_cb)(const gvfg_event_t *event, void *user); + +gvfg_status_t gvfg_set_event_callback(gvfg_handle handle, + gvfg_on_event_cb on_event, + void *user, + uint32_t event_mask); +``` + +註冊 capture event callback,用來通知上層 plug in/out 或 SDK 自動 pause/resume 狀態。 + +### event mask + +| mask | 說明 | +| --- | --- | +| `GVFG_EVENT_MASK_PLUG_IN` | 收到 FPGA PLUG_IN IRQ | +| `GVFG_EVENT_MASK_PLUG_OUT` | 收到 FPGA PLUG_OUT IRQ | +| `GVFG_EVENT_MASK_CAPTURE_PAUSED` | SDK 已因 plug out 完成自動 pause | +| `GVFG_EVENT_MASK_CAPTURE_RESUMED` | SDK 已因 plug in 完成自動 resume | +| `GVFG_EVENT_MASK_VIDEO_IRQ` | 收到 video IRQ,通常每張 frame 一次 | +| `GVFG_EVENT_MASK_DEFAULT` | 預設 hotplug/capture state,不包含 video IRQ | +| `GVFG_EVENT_MASK_ALL` | 全部事件,包含 video IRQ | + +`event_mask` 傳 `0` 時使用 `GVFG_EVENT_MASK_DEFAULT`。一般客戶建議用 default;`VIDEO_IRQ` 頻率高,建議只在 debug 或明確需要時打開。 + +### 範例 + +```c +static void on_event(const gvfg_event_t *event, void *user) +{ + switch (event->type) { + case GVFG_EVENT_PLUG_OUT: + /* UI 顯示 signal disconnected */ + break; + case GVFG_EVENT_PLUG_IN: + /* UI 顯示 signal connected */ + break; + case GVFG_EVENT_CAPTURE_PAUSED: + /* SDK 已自動 pause capture */ + break; + case GVFG_EVENT_CAPTURE_RESUMED: + /* SDK 已自動 resume capture */ + break; + default: + break; + } +} + +gvfg_set_event_callback(handle, on_event, user, GVFG_EVENT_MASK_DEFAULT); +``` + +注意:event callback 是通知用途。熱插拔時的 stop/start/pause/resume 邏輯仍由 SDK 自己處理,客戶不需要在 event callback 裡重啟 capture。 + +## gvfg_set_preview + +```c +gvfg_status_t gvfg_set_preview(gvfg_handle handle, const gvfg_preview_desc_t *desc); +``` + +設定 optional D3D preview helper 要畫到哪個 window。 + +這個 API 不是 core capture 必要流程。 +如果客戶自己處理顯示,就不需要呼叫這個 function。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `desc` | preview 設定,不可為 `NULL` | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 範例 + +```c +gvfg_preview_desc_t preview = {0}; +preview.hwnd = (void *)hwnd; +preview.enable_preview = 1; +preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO; + +gvfg_set_preview(handle, &preview); +``` + +### 注意 + +一般建議在 `gvfg_start()` 前呼叫。 + +目前也可在 running 中呼叫,用來更新 preview target 或 bit-depth request。 + +## gvfg_open + +```c +gvfg_status_t gvfg_open(gvfg_handle handle, int device_index); +``` + +開啟指定的 GVFG device。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `device_index` | `gvfg_enumerate_devices()` 得到的 device index | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 目前行為 + +`gvfg_open()` 目前會: + +1. open XDMA device。 +2. 設定 SDI input。 +3. 讀取目前 signal width / height / fps。 + +stream 的解析度會依照 signal 自動調整。 +例如 log 看到: + +```text +signal: width=1280 height=720 configured=1920x1080 +configure: effective ... 1280x720 +``` + +代表一開始預設可能是 1920x1080,但 driver 讀到實際 signal 是 1280x720,所以最後 stream 會用 1280x720。 + +## gvfg_start + +```c +gvfg_status_t gvfg_start(gvfg_handle handle); +``` + +開始 GVFG streaming。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | 已經 open 的 session handle | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 目前行為 + +`gvfg_start()` 會: + +1. configure stream。 +2. 建立 D3D preview pipeline。 +3. start XDMA event thread。 +4. start XDMA data thread。 +5. 從 C2H 讀 frame。 +6. 把 YUY2 frame 丟給 GPU shader 轉 RGB。 +7. present 到 preview HWND。 + +正常 log 會看到: + +```text +[GVFG][XDMA] start: threads launched +[GVFG][XDMA] publish_frame: id=1 ... +[GVFG][XDMA] wait_frame: deliver id=1 ... +[SharedScene] preview render path ... +``` + +## gvfg_stop + +```c +gvfg_status_t gvfg_stop(gvfg_handle handle); +``` + +停止 GVFG streaming。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 注意 + +即使目前沒有 running,也可以呼叫。 +SDK 會做安全檢查。 + +## gvfg_get_signal_status + +```c +gvfg_status_t gvfg_get_signal_status(gvfg_handle handle, + gvfg_signal_status_t *out_status); +``` + +取得目前 input signal 狀態。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `out_status` | 輸出 signal status,不可為 `NULL` | + +### 回傳值 + +如果有有效 width / height,回傳 `GVFG_OK`。 +否則回傳錯誤狀態。 + +### 範例 + +```c +gvfg_signal_status_t sig = {0}; +gvfg_status_t st = gvfg_get_signal_status(handle, &sig); + +if (st == GVFG_OK) { + printf("Signal legacy: %dx%d\n", + sig.width, + sig.height); + + printf("FPGA raw\n" + " valid_mask=0x%08x\n" + " width_valid=%d width_raw=%u\n" + " height_valid=%d height_raw=%u\n" + " video_format_raw=0x%08x\n" + " frame_rate_raw=0x%08x\n" + " bit_depth_raw=0x%08x\n" + " status_raw=0x%08x\n", + sig.fpga.valid_mask, + sig.fpga.width_valid, + sig.fpga.width_raw, + sig.fpga.height_valid, + sig.fpga.height_raw, + sig.fpga.video_format_raw, + sig.fpga.frame_rate_raw, + sig.fpga.bit_depth_raw, + sig.fpga.status_raw); + + if (sig.fpga.video_format_valid) { + printf("FPGA format=%d (%s) bitdepth=%d\n", + sig.fpga.video_format_code, + sig.fpga.video_format, + sig.fpga.bit_depth); + } + + if (sig.fpga.frame_rate_valid) { + printf("FPGA fps code=%s (%s)\n", + sig.fpga.frame_rate_bits, + sig.fpga.frame_rate_name); + } +} +``` + +## gvfg_get_runtime_info + +```c +gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, + gvfg_runtime_info_t *out_info); +``` + +取得 core capture runtime 診斷資訊。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `out_info` | 輸出 runtime info,不可為 `NULL` | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 建議用途 + +可以用來顯示: + +- 目前解析度 +- runtime FPS +- source format +- backend / frame source +- delivered frame count + +例如 viewer status bar 可以顯示: + +```text +Backend: GVFG | FPGA reported 1280x720 29.97fps | Delivered frame 1280x720 BGRA8 8bit | App runtime 29.97fps frames=120 +``` + +## gvfg_get_preview_info + +```c +gvfg_status_t gvfg_get_preview_info(gvfg_handle handle, + gvfg_preview_info_t *out_info); +``` + +取得 optional D3D preview helper 狀態。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `handle` | session handle | +| `out_info` | 輸出 preview info,不可為 `NULL` | + +### 回傳值 + +成功回傳 `GVFG_OK`。 + +### 建議用途 + +只有在客戶使用 `gvfg_set_preview()` 時才需要呼叫。 + +可以用來顯示: + +- SDK preview 是否啟用 +- swapchain 是否建立 +- preview size +- backbuffer format +- SDK preview shader/render path + +如果客戶自己畫畫面,render 狀態應該由客戶自己的 app 顯示,不應該依賴這個 function。 + +## gvfg_strerror + +```c +const char *gvfg_strerror(gvfg_status_t status); +``` + +把 `gvfg_status_t` 轉成字串。 + +### 參數 + +| 參數 | 說明 | +| --- | --- | +| `status` | API 回傳的 status | + +### 回傳值 + +回傳 static string pointer。 +客戶不需要也不能 free。 + +### 範例 + +```c +gvfg_status_t st = gvfg_start(handle); +if (st != GVFG_OK) { + printf("gvfg_start failed: %s\n", gvfg_strerror(st)); +} +``` + +## 最小使用範例 + +```c +#include "gvfg_capture.h" +#include + +static void on_frame(const gvfg_frame_t *frame, void *user) +{ + (void)user; + + if (!frame || !frame->data) + return; + + printf("frame %llu: %dx%d stride=%d\n", + (unsigned long long)frame->frame_id, + frame->width, + frame->height, + frame->stride); + + /* + 如果要存圖或交給其他 thread,這裡要 copy frame->data。 + callback return 後 frame->data 就不能再使用。 + */ +} + +static void on_error(gvfg_status_t status, const char *message, void *user) +{ + (void)user; + printf("gvfg message %d: %s\n", + (int)status, + message ? message : ""); +} + +int start_xdma_preview(void *hwnd) +{ + gvfg_device_info_t devices[GVFG_MAX_DEVICES] = {0}; + int device_count = gvfg_enumerate_devices(devices, GVFG_MAX_DEVICES); + + if (device_count <= 0) { + printf("No GVFG device found\n"); + return -1; + } + + gvfg_handle handle = NULL; + gvfg_status_t st = gvfg_create(&handle); + + if (st != GVFG_OK) { + printf("gvfg_create failed: %s\n", gvfg_strerror(st)); + return -1; + } + + gvfg_set_callbacks(handle, on_frame, on_error, NULL); + + /* + Optional: + 如果客戶要使用 SDK 內建 D3D preview helper,才需要設定 preview HWND。 + 如果客戶自己畫畫面,可以整段省略。 + */ + if (hwnd) { + gvfg_preview_desc_t preview = {0}; + preview.hwnd = hwnd; + preview.enable_preview = 1; + preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO; + gvfg_set_preview(handle, &preview); + } + + st = gvfg_open(handle, devices[0].index); + if (st != GVFG_OK) { + printf("gvfg_open failed: %s\n", gvfg_strerror(st)); + gvfg_destroy(handle); + return -1; + } + + st = gvfg_start(handle); + if (st != GVFG_OK) { + printf("gvfg_start failed: %s\n", gvfg_strerror(st)); + gvfg_destroy(handle); + return -1; + } + + /* + 注意:handle 必須保存起來。 + capture running 期間不能 destroy。 + + 停止時: + + gvfg_stop(handle); + gvfg_destroy(handle); + */ + + return 0; +} +``` + +## Qt 使用注意 + +Qt viewer 目前使用 optional preview helper: + +```text +previewWindow_->previewHwnd() +-> 傳給 gvfg_set_preview() +-> gvfg 用 D3D swapchain 畫到 previewHost +``` + +Qt callback: + +```text +gvfg worker thread +-> emit frameReady(QImage copy) +-> Qt queued connection +-> UI thread 更新 snapshot/狀態 +``` + +XDMA 模式下,Qt 不應該再用 QLabel overlay 蓋住 D3D preview。 +frame callback 可以保留給 snapshot、初始解析度調整、debug。 + +如果客戶不用 SDK preview helper,Qt app 可以自己用 callback frame 或自家的 GPU pipeline 畫畫面。 + +## 目前限制 + +目前版本限制: + +- input format 目前固定走 YUY2。 +- `gvfg` 還沒有對外提供 recording API。 +- 目前沒有 expose 手動選 input source 的 API,內部先固定 SDI。 +- `gvfg_set_preview()` 是 optional helper,不是 core capture 必要 API。 +- frame callback 不是主要 SDK preview path。 +- callback data pointer 只在 callback 期間有效。 +- callback thread 不是 UI thread。 + +## 正常 log 範例 + +啟動成功時,大致會看到: + +```text +[GVFG][XDMA] enumerate: done count=1 +[GVFG][XDMA] open_device: done +[GVFG][XDMA] signal: width=1280 height=720 +[GVFG][XDMA] configure: effective ... 1280x720 ... frame_bytes=1843200 +[SharedScene] preview swapchain created ... +[GVFG][XDMA] start: threads launched +[GVFG][XDMA] publish_frame: id=1 ... +[GVFG][XDMA] wait_frame: deliver id=1 ... +[SharedScene] preview render path ... +``` + +代表: + +```text +device 找到 +-> device open 成功 +-> signal 讀到解析度 +-> stream configure 成功 +-> D3D preview 建立成功 +-> XDMA frame 有進來 +-> preview shader path 有跑 +``` + +## 問題判斷 + +### 有 enumerate,但 start 失敗 + +可能原因: + +- device 被其他程式占用 +- driver subdevice open 失敗 +- event subdevice open 失敗 +- stream configure 失敗 + +### 有 start,但沒有 frame + +log 如果沒有: + +```text +publish_frame +wait_frame: deliver +``` + +可能原因: + +- XDMA interrupt event 沒來 +- c2h read 沒資料 +- FPGA/driver capture enable 沒生效 +- input signal 或 DMA path 有問題 + +### 有 frame,但 preview 黑畫面 + +如果有: + +```text +publish_frame +wait_frame: deliver +``` + +但沒有: + +```text +[SharedScene] preview swapchain created +[SharedScene] preview render path +``` + +可能是: + +- 傳進來的 `HWND` 無效 +- preview window 還沒建立 native handle +- D3D device / swapchain 建立失敗 + +如果兩者都有,但畫面仍異常,要查: + +- YUY2 shader 轉換 +- source stride +- swapchain present +- window 被 UI overlay 蓋住 + +## 後續可能會新增的 API + +目前先保留未來擴充方向: + +- 選 input source,例如 SDI / HDMI +- 手動指定解析度 / fps / pixel format +- recording API +- snapshot / raw export API +- 取得 driver / firmware / card info +- 設定 debug log callback +- expose GPU adapter selection +- expose zero-copy / GPU texture callback + +## Current XDMA Notes + +- The current XDMA path exposes decoded FPGA signal metadata through `sig.fpga`. +- `sig.pixel_format` and `sig.bit_depth` are legacy SDK source-buffer fields. +- The delivered customer callback buffer is reported by `gvfg_runtime_info_t::delivered_frame`. +- `sig.fpga.bit_depth=10` does not by itself mean the delivered callback buffer is `Y210`; the current callback path reports BGRA8. +- `sig.fpga.frame_rate_bits=0001` is not in the supported table, so the UI/API reports it as `--`. diff --git a/docs/GVFG_DIRECT_SDK_PLAN.md b/docs/GVFG_DIRECT_SDK_PLAN.md new file mode 100644 index 0000000..6f927c3 --- /dev/null +++ b/docs/GVFG_DIRECT_SDK_PLAN.md @@ -0,0 +1,44 @@ +# GVFG Direct SDK Plan + +## Current Direction + +GVFG Direct 目前改成使用獨立的 GVFG SDK: + +- 對外 facade:`sdk/gvfg` +- 低階 driver access:`sdk/gvfg/src/backend/xdma` +- Viewer 整合:`apps/qt6_viewer` 的 `GVFG Direct` + +GVFG 是客戶看到的 SDK/API 名稱。XDMA 只保留為底層 driver/backend 說明。 + +## Build Options + +```text +BUILD_GVFG_SDK=ON +BUILD_GVFG_SAMPLES=ON +GVFG_XDMA_DEBUG_LOG=ON +``` + +`BUILD_GVFG_SDK` 會 build `gvfg.dll`,並把 `gvfg.dll` 複製到 viewer 輸出資料夾。XDMA backend 會編進 `gvfg.dll`,不再另外產生 backend DLL。 + +`GVFG_XDMA_DEBUG_LOG` 會開啟底層 XDMA flow log。 + +## Active Components + +- `sdk/gvfg`: customer-facing GVFG capture SDK。 +- `sdk/gvfg/src/backend/xdma`: internal low-level XDMA driver access。 +- `apps/qt6_viewer`: viewer demo,`GVFG Direct` 透過 GVFG SDK 啟動。 +- `samples/gvfg_qt_preview`: 最小客戶 sample。 + +## Customer API + +請看: + +```text +docs/GVFG_CUSTOMER_API.md +``` + +## Removed Components + +- old standalone XDMA probe app +- KS capture session implementation +- KS device enumerator implementation diff --git a/samples/gvfg_qt_preview/CMakeLists.txt b/samples/gvfg_qt_preview/CMakeLists.txt new file mode 100644 index 0000000..e077318 --- /dev/null +++ b/samples/gvfg_qt_preview/CMakeLists.txt @@ -0,0 +1,54 @@ +cmake_minimum_required(VERSION 3.16) + +project(gvfg_qt_preview LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets) +find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets) + +if (QT_VERSION_MAJOR GREATER_EQUAL 6) + qt_add_executable(gvfg_qt_preview + main.cpp + mainwindow.cpp + mainwindow.h + mainwindow.ui + previewwindow.cpp + previewwindow.h + previewwindow.ui + ) +else() + add_executable(gvfg_qt_preview + main.cpp + mainwindow.cpp + mainwindow.h + mainwindow.ui + previewwindow.cpp + previewwindow.h + previewwindow.ui + ) +endif() + +target_link_libraries(gvfg_qt_preview PRIVATE + Qt${QT_VERSION_MAJOR}::Widgets + gvfg +) + +target_include_directories(gvfg_qt_preview PRIVATE + ${CMAKE_SOURCE_DIR}/sdk/gvfg/include +) + +if (MSVC) + target_compile_options(gvfg_qt_preview PRIVATE /utf-8) +endif() + +add_custom_command(TARGET gvfg_qt_preview POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + $ + $ +) + +set_target_properties(gvfg_qt_preview PROPERTIES + WIN32_EXECUTABLE TRUE +) diff --git a/samples/gvfg_qt_preview/main.cpp b/samples/gvfg_qt_preview/main.cpp new file mode 100644 index 0000000..2494e39 --- /dev/null +++ b/samples/gvfg_qt_preview/main.cpp @@ -0,0 +1,13 @@ +#include "mainwindow.h" + +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + MainWindow window; + window.show(); + + return app.exec(); +} diff --git a/samples/gvfg_qt_preview/mainwindow.cpp b/samples/gvfg_qt_preview/mainwindow.cpp new file mode 100644 index 0000000..f076232 --- /dev/null +++ b/samples/gvfg_qt_preview/mainwindow.cpp @@ -0,0 +1,459 @@ +#include "mainwindow.h" +#include "previewwindow.h" +#include "ui_mainwindow.h" + +#include +#include +#include +#include + +namespace +{ + QString fpgaFieldText(bool valid, const QString &text) + { + return valid ? text : QStringLiteral("--"); + } + + QString hex32(uint32_t value) + { + return QStringLiteral("0x") + QString::number(value, 16).rightJustified(8, QLatin1Char('0')).toUpper(); + } + + QString eventTypeText(gvfg_event_type_t type) + { + switch (type) + { + case GVFG_EVENT_VIDEO_IRQ: + return QStringLiteral("VIDEO_IRQ"); + case GVFG_EVENT_PLUG_IN: + return QStringLiteral("PLUG_IN"); + case GVFG_EVENT_PLUG_OUT: + return QStringLiteral("PLUG_OUT"); + case GVFG_EVENT_CAPTURE_PAUSED: + return QStringLiteral("CAPTURE_PAUSED"); + case GVFG_EVENT_CAPTURE_RESUMED: + return QStringLiteral("CAPTURE_RESUMED"); + default: + return QStringLiteral("UNKNOWN"); + } + } + + QString fpgaRawLogLine(const gvfg_runtime_info_t &info) + { + const auto &fpga = info.input_signal.fpga; + return QStringLiteral("fpga_raw\n" + " valid_mask=%1\n" + " resolution: width_valid=%2 width_raw=%3 height_valid=%4 height_raw=%5\n" + " video_format: valid=%6 raw=%7 code=%8 name=%9\n" + " frame_rate: valid=%10 raw=%11 code=%12 bits=%13 name=%14\n" + " bit_depth: valid=%15 raw=%16 value=%17\n" + " status: valid=%18 raw=%19 sdi_lock=%20 sdi_ddr=%21 hdmi_lock=%22 hdmi_ddr=%23") + .arg(hex32(fpga.valid_mask)) + .arg(fpga.width_valid) + .arg(fpga.width_raw) + .arg(fpga.height_valid) + .arg(fpga.height_raw) + .arg(fpga.video_format_valid) + .arg(hex32(fpga.video_format_raw)) + .arg(fpga.video_format_code) + .arg(QString::fromLatin1(fpga.video_format)) + .arg(fpga.frame_rate_valid) + .arg(hex32(fpga.frame_rate_raw)) + .arg(fpga.frame_rate_code) + .arg(QString::fromLatin1(fpga.frame_rate_bits)) + .arg(QString::fromLatin1(fpga.frame_rate_name)) + .arg(fpga.bit_depth_valid) + .arg(hex32(fpga.bit_depth_raw)) + .arg(fpga.bit_depth) + .arg(fpga.status_valid) + .arg(hex32(fpga.status_raw)) + .arg(fpga.sdi_locked) + .arg(fpga.sdi_ddr_ok) + .arg(fpga.hdmi_locked) + .arg(fpga.hdmi_ddr_ok); + } + + QString fpgaRawStateKey(const gvfg_runtime_info_t &info) + { + const auto &fpga = info.input_signal.fpga; + return QStringLiteral("%1|%2|%3|%4|%5|%6|%7|%8|%9|%10|%11|%12|%13|%14|%15|%16|%17|%18|%19|%20|%21|%22|%23") + .arg(fpga.valid_mask) + .arg(fpga.width_valid) + .arg(fpga.width_raw) + .arg(fpga.height_valid) + .arg(fpga.height_raw) + .arg(fpga.video_format_valid) + .arg(fpga.video_format_raw) + .arg(fpga.video_format_code) + .arg(QString::fromLatin1(fpga.video_format)) + .arg(fpga.frame_rate_valid) + .arg(fpga.frame_rate_raw) + .arg(fpga.frame_rate_code) + .arg(QString::fromLatin1(fpga.frame_rate_bits)) + .arg(QString::fromLatin1(fpga.frame_rate_name)) + .arg(fpga.bit_depth_valid) + .arg(fpga.bit_depth_raw) + .arg(fpga.bit_depth) + .arg(fpga.status_valid) + .arg(fpga.status_raw) + .arg(fpga.sdi_locked) + .arg(fpga.sdi_ddr_ok) + .arg(fpga.hdmi_locked) + .arg(fpga.hdmi_ddr_ok); + } +} + +MainWindow::MainWindow(QWidget *parent) + : QWidget(parent), ui_(new Ui::MainWindow) +{ + ui_->setupUi(this); + + previewWindow_ = new PreviewWindow(); + ui_->logEdit->setMaximumBlockCount(300); + ui_->statusLabel->setWordWrap(true); + signalStatusTimer_ = new QTimer(this); + signalStatusTimer_->setInterval(1000); + + connect(ui_->refreshButton, &QPushButton::clicked, this, [this]() { refreshDevices(); }); + connect(ui_->openButton, &QPushButton::clicked, this, [this]() + { + if (handle_) + closeDevice(); + else + openDevice(); + }); + connect(ui_->showPreviewButton, &QPushButton::clicked, this, [this]() { showPreviewWindow(); }); + connect(ui_->startButton, &QPushButton::clicked, this, [this]() { startCapture(); }); + connect(ui_->stopButton, &QPushButton::clicked, this, [this]() { stopCapture(); }); + connect(signalStatusTimer_, &QTimer::timeout, this, [this]() { updateSignalStatus(true); }); + + updateUiState(); + refreshDevices(); +} + +MainWindow::~MainWindow() +{ + closeDevice(); + delete previewWindow_; + delete ui_; +} + +void MainWindow::closeEvent(QCloseEvent *event) +{ + closeDevice(); + if (previewWindow_) + previewWindow_->closePreview(); + + QWidget::closeEvent(event); +} + +void MainWindow::refreshDevices() +{ + if (handle_) + closeDevice(); + + ui_->deviceCombo->clear(); + devices_ = {}; + + const int count = gvfg_enumerate_devices(devices_.data(), GVFG_MAX_DEVICES); + deviceCount_ = count > 0 ? count : 0; + + for (int i = 0; i < deviceCount_; ++i) + { + const QString name = QString::fromUtf8(devices_[i].name); + ui_->deviceCombo->addItem(name.isEmpty() ? QStringLiteral("GVFG Capture") : name, devices_[i].index); + } + + if (deviceCount_ <= 0) + { + ui_->deviceCombo->addItem(QStringLiteral("No GVFG device found"), -1); + appendLog(QStringLiteral("No GVFG device found")); + } + else + { + appendLog(QStringLiteral("Found %1 XDMA device(s)").arg(deviceCount_)); + } +} + +void MainWindow::showPreviewWindow() +{ + previewWindow_->showPreview(); + + if (handle_ && !applyPreview()) + appendLog(QStringLiteral("Show Preview failed: unable to update preview window")); +} + +bool MainWindow::openDevice() +{ + if (handle_) + return true; + + if (ui_->deviceCombo->currentData().toInt() < 0) + { + appendLog(QStringLiteral("Open skipped: no device selected")); + return false; + } + + gvfg_status_t st = gvfg_create(&handle_); + if (st != GVFG_OK || !handle_) + { + showError(QStringLiteral("gvfg_create"), st); + handle_ = nullptr; + updateUiState(); + return false; + } + + gvfg_set_callbacks(handle_, &MainWindow::onFrame, &MainWindow::onError, this); + gvfg_set_event_callback(handle_, &MainWindow::onEvent, this, GVFG_EVENT_MASK_DEFAULT); + + const int deviceIndex = ui_->deviceCombo->currentData().toInt(); + st = gvfg_open(handle_, deviceIndex); + if (st != GVFG_OK) + { + showError(QStringLiteral("gvfg_open"), st); + closeDevice(); + return false; + } + + lastSignalStatusText_.clear(); + lastFpgaRawStateKey_.clear(); + appendLog(QStringLiteral("Opened device index %1").arg(deviceIndex)); + appendLog(QStringLiteral("FPGA signal monitor active")); + updateSignalStatus(true); + signalStatusTimer_->start(); + updateUiState(); + return true; +} + +void MainWindow::closeDevice() +{ + stopCapture(); + + if (signalStatusTimer_) + signalStatusTimer_->stop(); + + if (handle_) + { + gvfg_destroy(handle_); + handle_ = nullptr; + appendLog(QStringLiteral("Closed device")); + } + + ui_->statusLabel->setText(QStringLiteral("Idle")); + lastSignalStatusText_.clear(); + lastFpgaRawStateKey_.clear(); + updateUiState(); +} + +void MainWindow::startCapture() +{ + if (captureRunning_) + return; + + if (!handle_ && !openDevice()) + return; + + previewWindow_->showPreview(); + if (!applyPreview()) + return; + + appendLog(QStringLiteral("FPGA signal before stream start")); + updateSignalStatus(true); + + const gvfg_status_t st = gvfg_start(handle_); + if (st != GVFG_OK) + { + showError(QStringLiteral("gvfg_start"), st); + updateSignalStatus(true); + updateUiState(); + return; + } + + frameCount_ = 0; + captureRunning_ = true; + updateUiState(); + appendLog(QStringLiteral("Started capture")); + updateSignalStatus(true); +} + +void MainWindow::stopCapture() +{ + if (handle_ && captureRunning_) + { + gvfg_stop(handle_); + captureRunning_ = false; + appendLog(QStringLiteral("Stopped capture")); + updateSignalStatus(true); + } + + updateUiState(); +} + +bool MainWindow::applyPreview() +{ + if (!handle_) + return false; + + gvfg_preview_desc_t preview{}; + preview.hwnd = previewWindow_->nativePreviewHandle(); + preview.enable_preview = 1; + preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO; + + const gvfg_status_t st = gvfg_set_preview(handle_, &preview); + if (st != GVFG_OK) + { + showError(QStringLiteral("gvfg_set_preview"), st); + return false; + } + return true; +} + +void MainWindow::updateSignalStatus(bool writeLog) +{ + if (!handle_) + return; + + gvfg_runtime_info_t info{}; + if (gvfg_get_runtime_info(handle_, &info) != GVFG_OK) + return; + + const auto &fpga = info.input_signal.fpga; + const auto &delivered = info.delivered_frame; + + const QString fpgaResolution = (fpga.width_valid && fpga.height_valid) + ? QStringLiteral("%1x%2").arg(fpga.width_raw).arg(fpga.height_raw) + : QStringLiteral("--"); + const QString line0 = QStringLiteral("FPGA reported | signal=%1 fps=%2 format=%3 bitdepth=%4") + .arg(fpgaResolution) + .arg(fpgaFieldText(fpga.frame_rate_valid != 0, + QStringLiteral("%1 (%2)") + .arg(QString::fromLatin1(fpga.frame_rate_bits)) + .arg(QString::fromLatin1(fpga.frame_rate_name)))) + .arg(fpgaFieldText(fpga.video_format_valid != 0, + QStringLiteral("%1 (%2)") + .arg(fpga.video_format_code) + .arg(QString::fromLatin1(fpga.video_format)))) + .arg(fpgaFieldText(fpga.bit_depth_valid != 0, + QStringLiteral("%1").arg(fpga.bit_depth))); + const QString line2 = QStringLiteral("FPGA status | SDI lock=%1 SDI DDR=%2 HDMI lock=%3 HDMI DDR=%4") + .arg(fpgaFieldText(fpga.status_valid != 0, QString::number(fpga.sdi_locked))) + .arg(fpgaFieldText(fpga.status_valid != 0, QString::number(fpga.sdi_ddr_ok))) + .arg(fpgaFieldText(fpga.status_valid != 0, QString::number(fpga.hdmi_locked))) + .arg(fpgaFieldText(fpga.status_valid != 0, QString::number(fpga.hdmi_ddr_ok))); + const QString line3 = delivered.valid + ? QStringLiteral("Delivered frame | frame=%1x%2 format=%3 bitdepth=%4") + .arg(delivered.width) + .arg(delivered.height) + .arg(QString::fromUtf8(delivered.pixel_format)) + .arg(delivered.bit_depth) + : QStringLiteral("Delivered frame | --"); + const QString line4 = QStringLiteral("App runtime | capture=%1 fps delivered=%2") + .arg(info.capture_fps > 0.0 ? QString::number(info.capture_fps, 'f', 2) + : QStringLiteral("--")) + .arg(static_cast(info.delivered_frames)); + + const QString statusText = line0 + QLatin1Char('\n') + line2 + QLatin1Char('\n') + line3 + QLatin1Char('\n') + line4; + if (lastSignalStatusText_ != statusText) + { + ui_->statusLabel->setText(statusText); + lastSignalStatusText_ = statusText; + } + + const QString stateKey = fpgaRawStateKey(info); + if (writeLog && lastFpgaRawStateKey_ != stateKey) + { + appendLog(fpgaRawLogLine(info)); + lastFpgaRawStateKey_ = stateKey; + } +} + +void MainWindow::updateUiState() +{ + const bool deviceOpen = handle_ != nullptr; + ui_->openButton->setText(deviceOpen ? QStringLiteral("Close Device") : QStringLiteral("Open Device")); + ui_->openButton->setEnabled(!captureRunning_); + ui_->startButton->setEnabled(deviceOpen && !captureRunning_); + ui_->stopButton->setEnabled(captureRunning_); + ui_->refreshButton->setEnabled(!deviceOpen && !captureRunning_); + ui_->deviceCombo->setEnabled(!deviceOpen && !captureRunning_); +} + +void MainWindow::showError(const QString &apiName, gvfg_status_t status) +{ + appendLog(QStringLiteral("%1 failed: %2").arg(apiName, QString::fromUtf8(gvfg_strerror(status)))); +} + +void MainWindow::appendLog(const QString &message) +{ + const QString line = QStringLiteral("[%1] %2") + .arg(QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"))) + .arg(message); + ui_->logEdit->appendPlainText(line); +} + +void MainWindow::onFrame(const gvfg_frame_t *frame, void *user) +{ + MainWindow *self = static_cast(user); + if (!self || !frame) + return; + + const uint64_t count = ++self->frameCount_; + if (count <= 5 || (count % 60) == 0) + { + const int width = frame->width; + const int height = frame->height; + const uint64_t frameId = frame->frame_id; + QMetaObject::invokeMethod(self, + [self, count, frameId, width, height]() + { + self->appendLog(QStringLiteral("callback #%1 source id=%2 %3x%4") + .arg(static_cast(count)) + .arg(static_cast(frameId)) + .arg(width) + .arg(height)); + }, + Qt::QueuedConnection); + } +} + +void MainWindow::onEvent(const gvfg_event_t *event, void *user) +{ + MainWindow *self = static_cast(user); + if (!self || !event) + return; + + const QString type = eventTypeText(event->type); + const uint32_t irqBit = event->irq_bit; + const uint32_t irqMask = event->irq_mask; + const uint64_t timestampNs = event->timestamp_ns; + QMetaObject::invokeMethod(self, + [self, type, irqBit, irqMask, timestampNs]() + { + self->appendLog(QStringLiteral("event %1 irq=%2 mask=%3 ts=%4") + .arg(type) + .arg(irqBit) + .arg(hex32(irqMask)) + .arg(static_cast(timestampNs))); + }, + Qt::QueuedConnection); +} + +void MainWindow::onError(gvfg_status_t status, const char *message, void *user) +{ + MainWindow *self = static_cast(user); + if (!self) + return; + + const QString text = message && message[0] + ? QString::fromUtf8(message) + : QString::fromUtf8(gvfg_strerror(status)); + + QMetaObject::invokeMethod(self, + [self, status, text]() + { + self->appendLog(QStringLiteral("message %1: %2") + .arg(static_cast(status)) + .arg(text)); + }, + Qt::QueuedConnection); +} diff --git a/samples/gvfg_qt_preview/mainwindow.h b/samples/gvfg_qt_preview/mainwindow.h new file mode 100644 index 0000000..74229c3 --- /dev/null +++ b/samples/gvfg_qt_preview/mainwindow.h @@ -0,0 +1,61 @@ +#pragma once + +#include + +#include +#include + +#include +#include +#include + +class QCloseEvent; +class PreviewWindow; +class QTimer; + +QT_BEGIN_NAMESPACE +namespace Ui +{ +class MainWindow; +} +QT_END_NAMESPACE + +class MainWindow final : public QWidget +{ + Q_OBJECT + +public: + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; + +protected: + void closeEvent(QCloseEvent *event) override; + +private: + void refreshDevices(); + void showPreviewWindow(); + bool openDevice(); + void closeDevice(); + void startCapture(); + void stopCapture(); + bool applyPreview(); + void updateSignalStatus(bool writeLog); + void updateUiState(); + void showError(const QString &apiName, gvfg_status_t status); + void appendLog(const QString &message); + + static void onFrame(const gvfg_frame_t *frame, void *user); + static void onEvent(const gvfg_event_t *event, void *user); + static void onError(gvfg_status_t status, const char *message, void *user); + + Ui::MainWindow *ui_ = nullptr; + PreviewWindow *previewWindow_ = nullptr; + std::array devices_{}; + int deviceCount_ = 0; + gvfg_handle handle_ = nullptr; + bool captureRunning_ = false; + std::atomic frameCount_{0}; + QTimer *signalStatusTimer_ = nullptr; + QString lastSignalStatusText_; + QString lastFpgaRawStateKey_; +}; diff --git a/samples/gvfg_qt_preview/mainwindow.ui b/samples/gvfg_qt_preview/mainwindow.ui new file mode 100644 index 0000000..64c51bc --- /dev/null +++ b/samples/gvfg_qt_preview/mainwindow.ui @@ -0,0 +1,84 @@ + + + MainWindow + + + + 0 + 0 + 960 + 640 + + + + GVFG Qt Preview Sample + + + + + + + + Device: + + + + + + + + + + Refresh + + + + + + + Open Device + + + + + + + Show Preview + + + + + + + Start + + + + + + + Stop + + + + + + + + + Idle + + + + + + + true + + + + + + + + diff --git a/samples/gvfg_qt_preview/previewwindow.cpp b/samples/gvfg_qt_preview/previewwindow.cpp new file mode 100644 index 0000000..99e2fc4 --- /dev/null +++ b/samples/gvfg_qt_preview/previewwindow.cpp @@ -0,0 +1,47 @@ +#include "previewwindow.h" +#include "ui_previewwindow.h" + +#include + +PreviewWindow::PreviewWindow(QWidget *parent) + : QWidget(parent), ui_(new Ui::PreviewWindow) +{ + ui_->setupUi(this); + ui_->previewHost->setAttribute(Qt::WA_NativeWindow, true); + ui_->previewHost->setStyleSheet(QStringLiteral("background: black;")); +} + +PreviewWindow::~PreviewWindow() +{ + delete ui_; +} + +void *PreviewWindow::nativePreviewHandle() const +{ + return reinterpret_cast(ui_->previewHost->winId()); +} + +void PreviewWindow::closePreview() +{ + closeAllowed_ = true; + close(); +} + +void PreviewWindow::showPreview() +{ + show(); + raise(); + activateWindow(); +} + +void PreviewWindow::closeEvent(QCloseEvent *event) +{ + if (closeAllowed_) + { + event->accept(); + return; + } + + hide(); + event->ignore(); +} diff --git a/samples/gvfg_qt_preview/previewwindow.h b/samples/gvfg_qt_preview/previewwindow.h new file mode 100644 index 0000000..9fdd907 --- /dev/null +++ b/samples/gvfg_qt_preview/previewwindow.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +QT_BEGIN_NAMESPACE +namespace Ui +{ +class PreviewWindow; +} +QT_END_NAMESPACE + +class PreviewWindow final : public QWidget +{ + Q_OBJECT + +public: + explicit PreviewWindow(QWidget *parent = nullptr); + ~PreviewWindow() override; + + void *nativePreviewHandle() const; + void closePreview(); + +public slots: + void showPreview(); + +protected: + void closeEvent(QCloseEvent *event) override; + +private: + Ui::PreviewWindow *ui_ = nullptr; + bool closeAllowed_ = false; +}; diff --git a/samples/gvfg_qt_preview/previewwindow.ui b/samples/gvfg_qt_preview/previewwindow.ui new file mode 100644 index 0000000..4038aab --- /dev/null +++ b/samples/gvfg_qt_preview/previewwindow.ui @@ -0,0 +1,31 @@ + + + PreviewWindow + + + + 0 + 0 + 960 + 540 + + + + GVFG Preview + + + + + + + 640 + 360 + + + + + + + + + diff --git a/sdk/gcapture/include/gcap_audio.h b/sdk/gcapture/include/gcap_audio.h new file mode 100644 index 0000000..b8c1d03 --- /dev/null +++ b/sdk/gcapture/include/gcap_audio.h @@ -0,0 +1,97 @@ +#pragma once + +/* + gcapture audio helper API + + Normal recording users should use: + - gcap_audio_device_count() + - gcap_audio_enum_devices() + - gcap_set_recording_audio_device() from gcapture.h + + The low-level gcap_start_audio_capture()/gcap_stop_audio_capture() APIs run + a simple WASAPI preview monitor from a capture endpoint to the default + speaker. They are independent from the recording path. +*/ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef _WIN32 +#ifdef GCAPTURE_BUILD +#define GCAP_API __declspec(dllexport) +#else +#define GCAP_API __declspec(dllimport) +#endif +#else +#define GCAP_API +#endif + +#define GCAP_AUDIO_ID_MAX 256 +#define GCAP_AUDIO_NAME_MAX 256 + + /** WASAPI capture endpoint information. */ + typedef struct gcap_audio_device_t + { + char id[GCAP_AUDIO_ID_MAX]; /** Opaque WASAPI endpoint id, UTF-8. Use with gcap_set_recording_audio_device(). */ + char name[GCAP_AUDIO_NAME_MAX]; /** Friendly endpoint name, UTF-8. */ + + int channels; /** Channel count when known: 1, 2, 6, etc. 0 means unknown. */ + int sample_rate; /** Preferred/current sample rate when known, e.g. 48000. 0 means unknown. */ + int bits_per_sample; /** 16 / 24 / 32 when known. 0 means unknown. */ + int is_float; /** 1 = IEEE float, 0 = PCM or unknown. */ + int is_default; /** 1 = system default capture endpoint. */ + } gcap_audio_device_t; + + /** Return number of active WASAPI capture endpoints. */ + GCAP_API int gcap_audio_device_count(void); + + /** + * Enumerate active WASAPI capture endpoints. + * + * Parameters: + * out - Output array. If null, the function returns total count. + * max_count - Number of entries available in out. + * + * Return: + * Number of entries written, or total count when out is null/max_count <= 0. + */ + GCAP_API int gcap_audio_enum_devices( + gcap_audio_device_t *out, + int max_count); + + /** Legacy alias for gcap_audio_device_count(). Kept for source/binary compatibility. */ + GCAP_API int gcap_get_audio_device_count(void); + + /** Legacy alias for gcap_audio_enum_devices(). Kept for source/binary compatibility. */ + GCAP_API int gcap_enum_audio_devices( + gcap_audio_device_t *out, + int max_count); + + /** + * Best-effort match from a video capture device friendly name to a WASAPI + * capture endpoint. Returns 1 and writes out when a likely endpoint is found. + */ + GCAP_API int gcap_audio_find_device_for_capture( + const char *capture_device_name_utf8, + gcap_audio_device_t *out); + + /** Experimental low-level audio capture configuration. Prefer gcap_set_recording_audio_device() for recording. */ + typedef struct gcap_audio_capture_config_t + { + const char *device_id; /** Endpoint id from gcap_audio_enum_devices(). null/empty may mean default. */ + int sample_rate; /** Requested sample rate, commonly 48000. */ + int channels; /** Requested channels, commonly 1 or 2. */ + } gcap_audio_capture_config_t; + + /** Start low-level WASAPI audio preview/capture from cfg->device_id to the default speaker. */ + GCAP_API int gcap_start_audio_capture( + const gcap_audio_capture_config_t *cfg); + + /** Stop low-level WASAPI audio preview/capture if it was started. */ + GCAP_API void gcap_stop_audio_capture(void); + +#ifdef __cplusplus +} +#endif diff --git a/sdk/gcapture/include/gcapture.h b/sdk/gcapture/include/gcapture.h new file mode 100644 index 0000000..7ad46bb --- /dev/null +++ b/sdk/gcapture/include/gcapture.h @@ -0,0 +1,871 @@ +#pragma once +#include +#include +#include "gcap_audio.h" + +/* + gcapture public C API + + This header is the SDK boundary. It intentionally uses C-compatible types, + fixed-size UTF-8 strings, and opaque handles so applications can use the SDK + from Qt, Win32/MFC, C#, Python wrappers, or other UI frameworks. + + Typical lifecycle: + 1. gcap_enumerate() + 2. gcap_create() + gcap_open2(), or gcap_open() + 3. Optional: gcap_set_backend(), gcap_set_profile(), gcap_set_processing() + 4. Optional preview: gcap_set_preview() + 5. Optional callbacks: gcap_set_callbacks(), gcap_set_frame_packet_callback() + 6. gcap_start() + 7. Optional runtime operations: snapshot, recording, signal/runtime queries + 8. gcap_stop() + 9. gcap_close() + + Thread-safety notes: + - A single gcap_handle should normally be controlled from one application + thread, except frame/error callbacks which are invoked from SDK/backend + worker threads. + - Callback pointers are only valid during the callback call. Copy data you + need before returning. + - Do not call blocking UI code directly inside callbacks. Marshal to your + UI thread. + - Unless a function explicitly says otherwise, do not call it concurrently + with gcap_close() on the same handle. + + String notes: + - Public string parameters and string fields are UTF-8 unless documented + otherwise. + - Fixed-size output buffers are always intended to be NUL-terminated by the + SDK on success. +*/ + +#ifdef _WIN32 +#ifdef GCAPTURE_BUILD +#define GCAP_API __declspec(dllexport) +#else +#define GCAP_API __declspec(dllimport) +#endif +#else +#define GCAP_API +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** Capture backend selection. */ + typedef enum + { + /** Media Foundation CPU readback path. */ + GCAP_BACKEND_WINMF_CPU = 0, + /** Media Foundation GPU/DXGI path. Recommended for WinMF preview when supported. */ + GCAP_BACKEND_WINMF_GPU = 1, + /** DirectShow raw-sink path. Recommended for DShow capture devices. */ + GCAP_BACKEND_DSHOW = 2, + /** SDK chooses an available backend. Actual backend can be queried by gcap_get_active_backend(). */ + GCAP_BACKEND_AUTO = 3 + } gcap_backend_t; + + /** Profile negotiation mode. */ + enum gcap_profile_mode_t + { + /** Let the device/backend choose its default format. */ + GCAP_PROFILE_DEVICE_DEFAULT = 0, + /** Use width/height/fps/format from gcap_profile_t where supported. */ + GCAP_PROFILE_CUSTOM + }; + + + /** SDK log level passed to gcap_log_callback_t. */ + typedef enum + { + GCAP_LOG_TRACE = 0, + GCAP_LOG_DEBUG = 1, + GCAP_LOG_INFO = 2, + GCAP_LOG_WARN = 3, + GCAP_LOG_ERROR = 4 + } gcap_log_level_t; + + /** + * SDK log callback. + * + * The callback may be invoked from SDK/backend worker threads. Do not touch + * UI objects directly; marshal the message to your UI/log thread. + * message_utf8 is valid only during the callback call. Copy it if needed. + */ + typedef void (*gcap_log_callback_t)(gcap_log_level_t level, const char *message_utf8, void *user); + + /** SDK status code returned by most high-level APIs. */ + typedef enum + { + GCAP_OK = 0, + /** Invalid argument, null pointer, invalid state-independent parameter, or insufficient buffer. */ + GCAP_EINVAL, + /** Device not found, removed, or unavailable. */ + GCAP_ENODEV, + /** Operation is not valid in the current handle state. */ + GCAP_ESTATE, + /** I/O, backend, driver, media, or file operation failed. */ + GCAP_EIO, + /** Requested backend/format/operation is not supported. */ + GCAP_ENOTSUP + } gcap_status_t; + + /** Pixel format used by capability, negotiated status, callbacks, and recording helpers. */ + typedef enum + { + GCAP_FMT_NV12, /** 8-bit YUV 4:2:0, two planes: Y + interleaved UV. */ + GCAP_FMT_YUY2, /** 8-bit YUV 4:2:2 packed. */ + GCAP_FMT_ARGB, /** 8-bit packed 32-bit RGB-like surface. In callbacks it is treated as BGRA/ARGB-compatible 4 bytes per pixel. */ + GCAP_FMT_P010, /** 10-bit YUV 4:2:0 in 16-bit containers, two planes. */ + GCAP_FMT_Y210, /** 10-bit YUV 4:2:2 packed in 16-bit containers. */ + GCAP_FMT_V210, /** 10-bit packed 4:2:2. Capability placeholder; conversion support may be limited. */ + GCAP_FMT_R210 /** 10-bit packed RGB. Capability placeholder; conversion support may be limited. */ + } gcap_pixfmt_t; + + /** Device enumeration result. */ + typedef struct + { + int index; /** Device index accepted by gcap_open() / gcap_open2(). */ + char name[128]; /** Friendly device name, UTF-8. */ + char symbolic_link[256]; /** Backend/device symbolic link when available, UTF-8. */ + unsigned caps; /** Reserved bitmask. Current convention: 1<<0 HDMI, 1<<1 SDI, 1<<2 10-bit capable. */ + } gcap_device_info_t; + + typedef enum + { + GCAP_INPUT_UNKNOWN = 0, + GCAP_INPUT_HDMI = 1, + GCAP_INPUT_SDI = 2 + } gcap_input_t; + + typedef enum + { + GCAP_RANGE_UNKNOWN = 0, + GCAP_RANGE_LIMITED = 1, + GCAP_RANGE_FULL = 2 + } gcap_range_t; + + typedef enum + { + GCAP_CSP_UNKNOWN = 0, + GCAP_CSP_BT601 = 1, + GCAP_CSP_BT709 = 2, + GCAP_CSP_BT2020 = 3 + } gcap_colorspace_t; + + /** Best-effort static device properties. Empty/zero/-1 fields mean unknown or not reported by the driver. */ + typedef struct + { + char driver_version[64]; + char firmware_version[64]; + char serial_number[64]; + gcap_input_t input; + int pcie_gen; /** 2/3/4/5, or 0 if unknown. */ + int pcie_lanes; /** 1/4/8/16, or 0 if unknown. */ + int hdcp; /** 0 = no, 1 = yes, -1 = unknown. */ + } gcap_device_props_t; + + /** Signal/media-type status. Used for input probe, negotiated format, and runtime info. */ + typedef struct + { + int width, height; + int fps_num, fps_den; /** FPS numerator/denominator. 0 means unknown. */ + gcap_pixfmt_t pixfmt; + int bit_depth; /** 8/10/12, or 0 if unknown. */ + gcap_colorspace_t csp; + gcap_range_t range; + int hdr; /** 0 = SDR/unknown-not-HDR, 1 = HDR, -1 = unknown. */ + } gcap_signal_status_t; + + /** One video capability entry reported or inferred for a device/backend. */ + typedef struct + { + int width; + int height; + int fps_num; + int fps_den; + gcap_pixfmt_t pixfmt; + int bit_depth; + char subtype_name[32]; /** Backend/native media subtype name, e.g. HDYC/UYVY/v210/ARGB32. May be empty. */ + } gcap_video_cap_t; + + /** DirectShow property page descriptor. */ + typedef struct + { + char page_name[128]; /** Vendor/driver page name, UTF-8 when conversion succeeds. */ + int capture_pin; /** 0 = filter property page, 1 = capture-pin property page. */ + } gcap_property_page_t; + + /** Runtime information for UI/status display and diagnostics. */ + typedef struct + { + gcap_signal_status_t signal; /** Best-effort input signal shown to UI. */ + gcap_signal_status_t signal_probe; /** Raw probe/fallback result, for example DShow IAMStreamConfig::GetFormat(). */ + gcap_signal_status_t negotiated; /** Media type actually negotiated/delivered by the backend. */ + double runtime_fps; /** Measured delivered-frame FPS. 0 means unknown/not running yet. */ + int active_backend; /** gcap_backend_t value actually in use. */ + char backend_name[32]; /** Display string, e.g. WinMF GPU / WinMF CPU / DShow Raw. */ + char frame_source[32]; /** Display string, e.g. DXGI / CPU / RawSink. */ + char path_name[64]; /** Display string describing active preview/capture path. */ + char source_format[32]; /** Legacy display field: negotiated media subtype name. */ + char render_format[32]; /** Display field: canvas / scene processing format. */ + char input_signal_desc[64]; /** Display field: RGB/YUV, color space, bit depth, may be inferred. */ + char input_signal_note[32]; /** Display field: Inferred / Driver / Unknown. */ + char negotiated_desc[32]; /** Display field: RGB24 / NV12 / YUY2 / ARGB32 / etc. */ + char selectable_caps_inline[512]; /** Active open-graph selectable modes summary after SDK filtering/policy. */ + char selectable_caps_tooltip[2048];/** Full active open-graph selectable modes after SDK filtering/policy. */ + } gcap_runtime_info_t; + + /** Human-readable recording configuration currently selected by the SDK. */ + typedef struct + { + char mode_name[64]; /** e.g. DShow + FFmpeg MP4 / Media Foundation Sink Writer. */ + char encoder_name[160]; /** e.g. FFmpeg HEVC / H.265 Main10. */ + char input_format[32]; /** SDK pixel format name. */ + char output_format[32]; /** Encoder/muxer output pixel/codec description. */ + int input_bit_depth; + int output_bit_depth; + int output_fps_num; + int output_fps_den; + int video_only; /** 1 = current recorder writes video only; 0 = audio may be included when configured/supported. */ + } gcap_recording_info_t; + + /** Snapshot export flags. If desc->flags is 0, SDK exports RAW_ALL + TIFF + STATS + PNG. */ + typedef enum + { + GCAP_EXPORT_RAW_NATIVE = 1 << 0, /** Native readback RAW: 10-bit source -> *_abgr2101010.raw; 8-bit source -> *_bgra8.raw. */ + GCAP_EXPORT_RAW_RGB10_U16 = 1 << 1, /** 10-bit RGB values stored in uint16 containers: *_rgb10.raw. */ + GCAP_EXPORT_RAW_RGBA16 = 1 << 2, /** 10-bit values expanded to 16-bit RGBA: *_rgba16_expanded.raw. */ + GCAP_EXPORT_TIFF = 1 << 3, /** WIC TIFF export: *.tiff. */ + GCAP_EXPORT_STATS = 1 << 4, /** Text statistics: *.stats.txt. */ + GCAP_EXPORT_PNG = 1 << 5, /** WIC PNG preview/export image: *.png. */ + GCAP_EXPORT_RAW_GIGABYTE_HEADER = 1 << 6, /** Additional RAW copies with 128-byte GIGABYTE RAW header: *_gigabyte_*.raw. */ + GCAP_EXPORT_RAW_RGBA8 = 1 << 7, /** 8-bit hex-editor-friendly RGBA dump: *_rgba8.raw, bytes are R G B A per pixel. */ + GCAP_EXPORT_RAW_ALL = GCAP_EXPORT_RAW_NATIVE | GCAP_EXPORT_RAW_RGB10_U16 | GCAP_EXPORT_RAW_RGBA16 + } gcap_export_flags_t; + +#define GCAP_GIGABYTE_RAW_HEADER_SIZE 128 + + /* + * GIGABYTE RAW header is a 128-byte ASCII header before the RAW payload: + * GIGABYTE_RAW + * header_size=128 + * Width= + * Height= + * Format= + * SourceBitDepth= + */ + + /** Snapshot export request. */ + typedef struct + { + const char *base_path_utf8; /** Base path without SDK suffix. Must not be null/empty. UTF-8. */ + int flags; /** Bitwise OR of gcap_export_flags_t. 0 means default full export. */ + } gcap_snapshot_export_desc_t; + + /** Snapshot export result. Empty path means that file type was not requested or not generated for the source format. */ + typedef struct + { + char native_raw_path[512]; /** *_abgr2101010.raw for 10-bit sources, or *_bgra8.raw for 8-bit sources. */ + char fp16_raw_path[512]; /** *_fp16_rgba16f.raw, generated for 10-bit/FP16 scene readback when RAW export is requested. */ + char rgb10_u16_path[512]; /** *_rgb10.raw, generated for 10-bit sources when RGB10 RAW export is requested. */ + char rgba16_path[512]; /** *_rgba16_expanded.raw, generated for 10-bit sources when RAW export is requested. */ + char rgba8_path[512]; /** *_rgba8.raw, generated for 8-bit hex-editor-friendly R8 G8 B8 A8 inspection. */ + char gigabyte_native_raw_path[512]; /** Headered mirror: *_gigabyte_abgr2101010.raw or *_gigabyte_bgra8.raw. */ + char gigabyte_fp16_raw_path[512]; /** Reserved legacy field. Current snapshot export leaves this empty. */ + char gigabyte_rgb10_u16_path[512]; /** Reserved legacy field. Current snapshot export leaves this empty. */ + char gigabyte_rgba16_path[512]; /** Reserved legacy field. Current snapshot export leaves this empty. */ + char tiff_path[512]; /** *.tiff when TIFF export is requested. */ + char stats_path[512]; /** *.stats.txt when STATS export is requested. */ + char png_path[512]; /** *.png when PNG export is requested. */ + int width; + int height; + gcap_pixfmt_t source_format; + int source_bit_depth; + int generated_flags; /** Bitwise OR of actually generated gcap_export_flags_t values. */ + } gcap_snapshot_export_result_t; + + /** Recording statistics collected by the active recorder/backend. Unsupported fields remain 0. */ + typedef struct + { + uint64_t frames_written; + uint64_t frames_dropped; + uint64_t frames_duplicated; + uint64_t input_frames; + uint64_t unsupported_frames; + uint64_t overwritten_frames; + int width; + int height; + int fps_num; + int fps_den; + gcap_pixfmt_t input_pixfmt; + int output_bit_depth; + char encoder_name[128]; + char muxer_name[64]; + double avg_encode_fps; + double avg_bitrate_kbps; + } gcap_recording_stats_t; + + + /** + * Ramp-pattern validation status for gcap_tiff_analysis_t. + * + * Important: ramp validation is only meaningful for generated monotonic ramp test + * images. A real camera/HDMI frame usually returns GCAP_TIFF_RAMP_NOT_APPLICABLE; + * that does not mean the TIFF is 8-bit or invalid. Use likely_ten_bit_content, + * min/max, unique_value_count, and effective_bit_depth as the general bit-depth + * evidence for arbitrary images. + */ + typedef enum + { + GCAP_TIFF_RAMP_NOT_CHECKED = 0, + GCAP_TIFF_RAMP_NOT_APPLICABLE = 1, + GCAP_TIFF_RAMP_DETECTED_VALID = 2, + GCAP_TIFF_RAMP_DETECTED_INVALID = 3 + } gcap_tiff_ramp_status_t; + + /** TIFF bit-depth / optional ramp-pattern analysis result. Fixed-size C struct for SDK clients. */ + typedef struct + { + int ok; /** 1 = analysis succeeded, 0 = failed. */ + char path[512]; /** Input TIFF path, UTF-8 when available. */ + char error[512]; /** Failure reason, UTF-8. Empty on success. */ + + int width; + int height; + int channels; + int bits_per_sample; + int samples_per_pixel; + int stored_bit_depth; + int effective_bit_depth; + + char pixel_format_name[96]; + char photometric[64]; + + uint64_t min_value; + uint64_t max_value; + uint64_t unique_value_count; + + int likely_ten_bit_ramp; /** Backward-compatible alias: 1 only when ramp_status == GCAP_TIFF_RAMP_DETECTED_VALID. */ + int strict_ten_bit_ramp; /** Strict monotonic ramp and likely 10-bit content. */ + int visual_ten_bit_ramp_candidate; /** A monotonic visual ramp pattern was detected, regardless of bit-depth validity. */ + int likely_ten_bit_content; /** General bit-depth evidence for arbitrary images; does not require a ramp pattern. */ + int values_look_shifted_10bit; + int values_look_8bit_expanded; + int ramp_status; /** gcap_tiff_ramp_status_t. Non-ramp images should be NOT_APPLICABLE, not failed. */ + + char ramp_reason[512]; + char strict_ramp_reason[512]; + char visual_ramp_reason[512]; + char ramp_note[512]; /** Human-readable explanation of ramp_status. */ + + int sampled_row_y; + char sampled_row_source[96]; + char sampled_row_logical10_rule[192]; + char sampled_row_raw16_csv[4096]; + char sampled_row_logical10_csv[4096]; + + int preview_stride_bytes; /** RGBA64 preview stride. Use gcap_read_tiff_preview_rgba64() to read data. */ + size_t preview_size_bytes; /** Required RGBA64 preview buffer size. */ + } gcap_tiff_analysis_t; + + typedef enum + { + GCAP_DEINT_AUTO = 0, + GCAP_DEINT_OFF, + GCAP_DEINT_WEAVE, + GCAP_DEINT_BOB + } gcap_deinterlace_t; + + /** Optional processing preferences. Unsupported options are ignored or return GCAP_ENOTSUP depending on backend. */ + typedef struct + { + gcap_pixfmt_t preferred_pixfmt; /** Preferred capture format. Use backend capability APIs to discover support. */ + gcap_deinterlace_t deinterlace; + gcap_range_t force_range; /** GCAP_RANGE_UNKNOWN = auto. */ + } gcap_processing_opts_t; + + /** ProcAmp settings. SDK UI scale is 0..255, where 128 is neutral. */ + typedef struct + { + int brightness; + int contrast; + int hue; + int saturation; + int sharpness; + } gcap_procamp_t; + + /** One ProcAmp control range in SDK UI units. */ + typedef struct + { + int supported; /** Non-zero if this control is supported by the active backend/path. */ + int min_value; /** Minimum accepted value. */ + int max_value; /** Maximum accepted value. */ + int step; /** Recommended slider step. */ + int default_value; /** Recommended neutral/default value. */ + int current_value; /** Current value if available; otherwise default_value. */ + } gcap_procamp_range_t; + + /** ProcAmp capability block for Brightness/Contrast/Hue/Saturation/Sharpness. */ + typedef struct + { + gcap_procamp_range_t brightness; + gcap_procamp_range_t contrast; + gcap_procamp_range_t hue; + gcap_procamp_range_t saturation; + gcap_procamp_range_t sharpness; + } gcap_procamp_caps_t; + + /** Requested capture profile. For GCAP_PROFILE_CUSTOM, set width/height/fps/format. */ + typedef struct + { + int width, height; + int fps_num, fps_den; + gcap_pixfmt_t format; + gcap_profile_mode_t mode; + } gcap_profile_t; + + /** Legacy frame callback payload. Prefer gcap_frame_packet_t for SDK clients that need backend/source metadata. */ + typedef struct + { + const void *data[3]; /** Plane pointers. Valid only during callback. */ + int stride[3]; /** Bytes per row for each plane. */ + int plane_count; + int width, height; + gcap_pixfmt_t format; + uint64_t pts_ns; + uint64_t frame_id; + } gcap_frame_t; + + typedef enum + { + GCAP_SOURCE_UNKNOWN = 0, + GCAP_SOURCE_WINMF_GPU = 1, + GCAP_SOURCE_WINMF_CPU = 2, + GCAP_SOURCE_DSHOW_RAWSINK = 3, + GCAP_SOURCE_DSHOW_RENDERER = 4 /** Legacy/debug renderer path. Prefer GCAP_SOURCE_DSHOW_RAWSINK for SDK clients. */ + } gcap_frame_source_kind_t; + + /** Preferred raw frame callback payload. Plane pointers are valid only during callback. */ + typedef struct + { + int width, height; + gcap_pixfmt_t format; + int plane_count; + const void *data[3]; /** Plane pointers. Do not retain after callback returns. */ + int stride[3]; /** Bytes per row for each plane. */ + uint64_t pts_ns; + uint64_t frame_id; + int backend; /** gcap_backend_t value. */ + int source_kind; /** gcap_frame_source_kind_t value. */ + int gpu_backed; /** 1 when frame originated from GPU-backed path; callback data is still CPU-readable. */ + } gcap_frame_packet_t; + + typedef enum + { + GCAP_PREVIEW_BITDEPTH_8BIT = 0, + GCAP_PREVIEW_BITDEPTH_10BIT = 1, + GCAP_PREVIEW_BITDEPTH_AUTO = 2 + } gcap_preview_bitdepth_t; + + /** Native preview target. The SDK renders into the supplied HWND. */ + typedef struct + { + void *hwnd; /** Native HWND. Required when enable_preview is non-zero. */ + int enable_preview; /** 0 = disable preview, 1 = enable preview. */ + int use_fp16_pipeline; /** 1 = use FP16 scene pipeline when available. Recommended for 10-bit/HDR-oriented paths. */ + int swapchain_10bit; /** 0 = force 8-bit BGRA, 1 = prefer/force 10-bit RGB10A2, 2 = auto try 10-bit then fallback 8-bit. */ + } gcap_preview_desc_t; + + typedef void (*gcap_on_video_cb)(const gcap_frame_t *frame, void *user); + typedef void (*gcap_on_frame_packet_cb)(const gcap_frame_packet_t *pkt, void *user); + typedef void (*gcap_on_error_cb)(gcap_status_t code, const char *msg, void *user); + + typedef struct gcap_handle_t *gcap_handle; + + /** + * Installs a process-wide SDK log callback. + * + * This is intended for SDK clients to receive WinMF/DShow/snapshot/recording + * diagnostics in their own logging system. Passing cb = NULL disables the + * callback. The callback may be invoked from SDK/backend worker threads. + * The SDK may still also send messages to OutputDebugString on Windows as + * a fallback. + */ + GCAP_API void gcap_set_log_callback(gcap_log_callback_t cb, void *user); + + /** + * Enumerate capture devices. + * + * Parameters: + * out - Output array. Must not be null in the current implementation. + * max - Number of entries available in out. + * count - Receives total/actual count when non-null. + * + * Return: + * GCAP_OK on success. GCAP_EINVAL for invalid output array/max. + * + * Thread-safety: + * Safe to call before any handle is created. Avoid calling repeatedly from + * a real-time callback thread because device enumeration can touch OS/driver APIs. + */ + GCAP_API gcap_status_t gcap_enumerate(gcap_device_info_t *out, int max, int *count); + + /** Create an unopened handle. Use gcap_open2() before gcap_start(). */ + GCAP_API gcap_status_t gcap_create(gcap_handle *out); + + /** Convenience API: create and open a device in one call. Close with gcap_close(). */ + GCAP_API gcap_status_t gcap_open(int device_index, gcap_handle *out); + + /** Open an existing handle created by gcap_create(). Must be called before gcap_start(). */ + GCAP_API gcap_status_t gcap_open2(gcap_handle h, int device_index); + + /** + * Set requested capture profile. + * + * Call state: + * Recommended after open and before start. Changing profile while running + * may return GCAP_ESTATE or may require stop/start depending on backend. + * + * Notes: + * Use gcap_enum_video_caps_ex() / gcap_get_recommended_profile() to find + * supported values. The driver may still negotiate a different final format; + * query gcap_get_runtime_info() after start to verify. + */ + GCAP_API gcap_status_t gcap_set_profile(gcap_handle h, const gcap_profile_t *prof); + + /** Configure SDK buffering hints. Call before gcap_start(). Backend may ignore unsupported hints. */ + GCAP_API gcap_status_t gcap_set_buffers(gcap_handle h, int count, size_t bytes_hint); + + /** + * Set legacy video/error callbacks. + * + * Callback lifetime: + * Frame data is valid only during the callback. Copy before returning. + * Passing null callbacks disables that callback type. + */ + GCAP_API gcap_status_t gcap_set_callbacks(gcap_handle h, gcap_on_video_cb vcb, gcap_on_error_cb ecb, void *user); + + /** + * Set preferred frame packet callback. + * + * Call state: + * Usually configured before gcap_start(); can be cleared before/after stop. + * + * Thread-safety: + * Invoked from SDK/backend worker thread. Do not block for long periods. + */ + GCAP_API gcap_status_t gcap_set_frame_packet_callback(gcap_handle h, gcap_on_frame_packet_cb cb, void *user); + + /** Start capture/preview/callback delivery. Requires an opened handle. */ + GCAP_API gcap_status_t gcap_start(gcap_handle h); + + /** + * Start recording to an output path. + * + * Call state: + * Requires an opened and normally running capture session. If called before + * capture is started, backend support is not guaranteed. + * + * Parameters: + * path_utf8 - Output file path, UTF-8. MP4 is the intended container for + * current FFmpeg/MF recorder paths. + * + * Notes: + * Use gcap_get_recording_info() after profile/backend selection to show the + * selected encoder/mode to the user. Use gcap_get_recording_stats() after or + * during recording to inspect counters supported by the active backend. + */ + GCAP_API gcap_status_t gcap_start_recording(gcap_handle h, const char *path_utf8); + + /** Stop active recording. Safe to call when recording is not active; backend may return GCAP_ESTATE. */ + GCAP_API gcap_status_t gcap_stop_recording(gcap_handle h); + + /** Stop capture/preview/callback delivery. Recording should be stopped first. */ + GCAP_API gcap_status_t gcap_stop(gcap_handle h); + + /** + * Enumerate WASAPI capture endpoints. + * + * Legacy status-code API. New clients may prefer gcap_audio_device_count() + * and gcap_audio_enum_devices(). + */ + GCAP_API gcap_status_t gcap_enumerate_audio_devices(gcap_audio_device_t *out, int max, int *count); + + /** + * Select WASAPI capture endpoint for recording. + * + * Call state: + * Call before gcap_start_recording(). If changed while recording, behavior is + * backend-dependent and not recommended. + * + * Parameters: + * device_id_utf8 - Endpoint id from audio enumeration. null or empty string + * means system default capture endpoint. + */ + GCAP_API gcap_status_t gcap_set_recording_audio_device(gcap_handle h, const char *device_id_utf8); + + /** Close and destroy a handle. Do not use the handle after this call. */ + GCAP_API gcap_status_t gcap_close(gcap_handle h); + + /** Set global preferred backend for subsequently opened sessions. Not per-handle. */ + GCAP_API void gcap_set_backend(int backend); + + /** Select D3D11 adapter index for GPU/DXGI processing. -1 means system default adapter. */ + GCAP_API void gcap_set_d3d_adapter(int adapter_index); + + /** Query actual backend currently used by an opened/running handle. Returns -1 for invalid handle. */ + GCAP_API int gcap_get_active_backend(gcap_handle h); + + /** + * Legacy snapshot helper. + * + * Prefer gcap_export_snapshot() for new SDK clients because it returns the + * generated paths and flags. This helper uses base_path_utf8 plus SDK-defined + * suffixes and writes requested RAW/TIFF/STATS outputs. + */ + GCAP_API gcap_status_t gcap_export_preview_scene_rgb10(gcap_handle h, const char *base_path_utf8, + int export_raw, int export_tiff, int export_stats); + + /** + * Export a snapshot from the current preview scene/readback path. + * + * Call state: + * Requires a valid opened handle and a capture/preview scene that has already + * produced at least one frame. In normal use, call after gcap_start() and + * after frames are visible/delivered. It does not require the caller to have + * a frame callback. A preview HWND is strongly recommended because the export + * currently reads from the SDK preview/scene pipeline. + * + * Recording interaction: + * Intended to be callable while recording, but it may briefly contend with + * GPU/readback/file I/O. Avoid calling it from frame callbacks or timing- + * critical threads. + * + * Output naming: + * Given base_path_utf8 = "C:/cap/snapshot_001", generated paths are: + * 10-bit source RAW: + * C:/cap/snapshot_001_abgr2101010.raw + * C:/cap/snapshot_001_fp16_rgba16f.raw + * C:/cap/snapshot_001_rgb10.raw + * C:/cap/snapshot_001_rgba16_expanded.raw + * 8-bit source RAW: + * C:/cap/snapshot_001_bgra8.raw + * TIFF: + * C:/cap/snapshot_001.tiff + * STATS: + * C:/cap/snapshot_001.stats.txt + * PNG: + * C:/cap/snapshot_001.png + * + * Parameters: + * h - Opened capture handle. + * desc - Export request. desc->base_path_utf8 must not be null/empty. + * desc->flags == 0 means RAW_ALL | TIFF | STATS | PNG. + * out - Optional result. If non-null, SDK clears it to zero before writing. + * + * Return: + * GCAP_OK on success. On failure, no guarantee is made that partial files were + * not written; callers may delete files using the expected suffixes if needed. + */ + GCAP_API gcap_status_t gcap_export_snapshot(gcap_handle h, const gcap_snapshot_export_desc_t *desc, + gcap_snapshot_export_result_t *out); + + /** Query best-effort static device properties. Can be called after open; values may be unknown. */ + GCAP_API gcap_status_t gcap_get_device_props(gcap_handle h, gcap_device_props_t *out); + + /** Query current/best-effort input signal. Can be called after open/start. */ + GCAP_API gcap_status_t gcap_get_signal_status(gcap_handle h, gcap_signal_status_t *out); + + /** Query combined runtime status. Most useful after gcap_start(). */ + GCAP_API gcap_status_t gcap_get_runtime_info(gcap_handle h, gcap_runtime_info_t *out); + + /** Set processing preferences such as preferred format, deinterlace, or forced range. Prefer calling before start. */ + GCAP_API gcap_status_t gcap_set_processing(gcap_handle h, const gcap_processing_opts_t *opts); + + /** + * Query current ProcAmp values from the active backend/path. + * + * Can be called after gcap_open(). If the active backend/path does not + * support SDK ProcAmp, returns GCAP_ENOTSUP. + */ + GCAP_API gcap_status_t gcap_get_procamp(gcap_handle h, gcap_procamp_t *out); + + /** + * Query ProcAmp control ranges/capabilities. + * + * The current implementation exposes SDK-side preview/conversion ProcAmp + * controls in 0..255 units, default 128. These are not necessarily the + * hardware driver's IAMVideoProcAmp ranges. Unsupported controls are marked + * supported = 0. + */ + GCAP_API gcap_status_t gcap_get_procamp_caps(gcap_handle h, gcap_procamp_caps_t *out); + + /** Apply ProcAmp settings on supported CPU/GPU preview/conversion paths. Passing null resets to neutral. */ + GCAP_API gcap_status_t gcap_set_procamp(gcap_handle h, const gcap_procamp_t *p); + + /** Reset ProcAmp settings to backend defaults/neutral values. */ + GCAP_API gcap_status_t gcap_reset_procamp(gcap_handle h); + + /** Legacy audio count helper. Prefer gcap_audio_device_count() for new code. */ + GCAP_API int gcap_get_audio_device_count(void); + + /** Legacy audio enumeration helper. Prefer gcap_audio_enum_devices() for new code. Returns number written, or total if out_devices is null. */ + GCAP_API int gcap_enum_audio_devices(gcap_audio_device_t *out_devices, int max_devices); + + /** Return number of active WASAPI capture devices. */ + GCAP_API int gcap_audio_device_count(void); + + /** Enumerate active WASAPI capture devices. Returns number written, or total if out_devices is null or max_devices <= 0. */ + GCAP_API int gcap_audio_enum_devices(gcap_audio_device_t *out_devices, int max_devices); + + /** Best-effort match from the selected video capture device name to a WASAPI capture endpoint. */ + GCAP_API int gcap_audio_find_device_for_capture(const char *capture_device_name_utf8, gcap_audio_device_t *out_device); + + /** Return stable SDK pixel format display name. Never returns null. */ + GCAP_API const char *gcap_pixfmt_name(gcap_pixfmt_t fmt); + + /** Return gcapture SDK version string, for example "1.0.0". Never returns null. */ + GCAP_API const char *gcap_version_string(void); + + /** Return nominal bit depth for a pixel format, or 0 if unknown/unsupported. */ + GCAP_API int gcap_pixfmt_bit_depth(gcap_pixfmt_t fmt); + + /** Return non-zero if the pixel format is treated as 10-bit by SDK helpers. */ + GCAP_API int gcap_pixfmt_is_10bit(gcap_pixfmt_t fmt); + + /** Return non-zero if the pixel format is YUV-family. */ + GCAP_API int gcap_pixfmt_is_yuv(gcap_pixfmt_t fmt); + + /** Return default stride in bytes for a single row/primary plane at the given width, or 0 if unknown. */ + GCAP_API int gcap_pixfmt_default_stride(int width, gcap_pixfmt_t fmt); + + /** Return stable backend display name. Never returns null. */ + GCAP_API const char *gcap_backend_name(int backend); + + /** Return stable frame source display name. Never returns null. */ + GCAP_API const char *gcap_source_kind_name(int source_kind); + + /** Return non-zero when the recording helper would choose HEVC/H.265 Main10 for the input format. */ + GCAP_API int gcap_recording_uses_hevc_main10(gcap_pixfmt_t fmt); + + /** Return human-readable recording mode name for a backend. Never returns null. */ + GCAP_API const char *gcap_recording_mode_name(int backend); + + /** + * Query current recording mode/encoder information. + * + * Call state: + * Can be called after open/profile selection, before or during recording. + * The result is based on current backend and negotiated/requested format; + * after gcap_start(), it is more accurate. + */ + GCAP_API gcap_status_t gcap_get_recording_info(gcap_handle h, gcap_recording_info_t *out); + + /** + * Query recording counters/statistics. + * + * Call state: + * Can be called during recording or after gcap_stop_recording() while the + * handle is still valid. Unsupported counters remain 0. + */ + GCAP_API gcap_status_t gcap_get_recording_stats(gcap_handle h, gcap_recording_stats_t *out); + + /** + * Convert callback frame packet to packed BGRA8. + * + * Parameters: + * src - Frame packet received from gcap_on_frame_packet_cb. + * dst - Destination buffer. + * dst_stride - Destination bytes per row. Must be >= src->width * 4. + * + * Supported input formats: + * GCAP_FMT_ARGB, GCAP_FMT_NV12, GCAP_FMT_YUY2, GCAP_FMT_Y210. + * + * Thread-safety: + * Stateless helper. It may be called from inside the frame callback if the + * destination buffer is caller-owned and conversion cost is acceptable. + */ + GCAP_API gcap_status_t gcap_frame_to_bgra8(const gcap_frame_packet_t *src, void *dst, int dst_stride); + + + /** + * Analyze a TIFF file written by SDK snapshot export or any WIC-readable TIFF. + * + * The analysis uses Windows Imaging Component on Windows and reports stored + * bit depth, effective bit depth heuristics, min/max/unique values, and + * optional ramp-pattern validation. Ramp validation is only meaningful for + * generated monotonic ramp test images; normal camera/HDMI content commonly + * reports GCAP_TIFF_RAMP_NOT_APPLICABLE. That is not a failure and does not + * imply 8-bit content. Use likely_ten_bit_content and the value statistics + * as the general bit-depth evidence for arbitrary images. + * + * It does not allocate memory for the caller. + */ + GCAP_API gcap_status_t gcap_analyze_tiff(const char *path_utf8, gcap_tiff_analysis_t *out); + + /** + * Decode the first TIFF frame into RGBA64 little-endian pixels for preview. + * + * Pass dst = NULL or dst_size = 0 to query required_size/width/height/stride. + * The destination buffer must be at least required_size bytes. + */ + GCAP_API gcap_status_t gcap_read_tiff_preview_rgba64(const char *path_utf8, + void *dst, + size_t dst_size, + int *width, + int *height, + int *stride_bytes, + size_t *required_size); + + /** Return human-readable status string. Never returns null. */ + GCAP_API const char *gcap_strerror(gcap_status_t); + + /** + * Configure native HWND preview. + * + * Call state: + * Recommended after open and before start. Some backends may allow changing + * preview target while stopped only. To disable preview, pass enable_preview=0. + * + * Notes: + * The SDK does not own the HWND. The application must keep it valid while + * preview is enabled/running. + */ + GCAP_API gcap_status_t gcap_set_preview(gcap_handle h, const gcap_preview_desc_t *desc); + + /** + * Enumerate DirectShow video format capabilities for a device index. + * + * Return: + * Number of entries written. Passing null or max_caps <= 0 returns supported + * count when available. + * + * Notes: + * DShow-specific legacy helper. New code can use gcap_enum_video_caps_ex(). + */ + GCAP_API int gcap_enum_video_caps(int device_index, gcap_video_cap_t *out_caps, int max_caps); + + /** Backend-aware capability enumeration helper. Returns number written, or count when out_caps is null/max_caps <= 0. */ + GCAP_API int gcap_enum_video_caps_ex(int backend, int device_index, gcap_video_cap_t *out_caps, int max_caps); + + /** Return SDK-recommended profile for backend/device based on current format priority and capabilities. */ + GCAP_API gcap_status_t gcap_get_recommended_profile(int backend, int device_index, gcap_profile_t *out_profile); + + /** Enumerate unique pixel formats supported by a device/backend. Returns number written, or count when out_formats is null/max_formats <= 0. */ + GCAP_API int gcap_enum_supported_pixel_formats(int backend, int device_index, gcap_pixfmt_t *out_formats, int max_formats); + + /** Enumerate available DirectShow property pages for a device. Returns number written, or count when out_pages is null/max_pages <= 0. */ + GCAP_API int gcap_enum_property_pages(int device_index, gcap_property_page_t *out_pages, int max_pages); + + /** Open a device-specific vendor DShow property page. Debug/test helper; not required for generic capture flow. */ + GCAP_API int gcap_open_vendor_property_page(int device_index); + + /** Open a named DirectShow property page. page_name_utf8 must match a name returned by gcap_enum_property_pages(). */ + GCAP_API int gcap_open_named_property_page(int device_index, const char *page_name_utf8, int capture_pin); + +#ifdef __cplusplus +} +#endif diff --git a/sdk/gcapture/src/core/logging.h b/sdk/gcapture/src/core/logging.h new file mode 100644 index 0000000..e93cea9 --- /dev/null +++ b/sdk/gcapture/src/core/logging.h @@ -0,0 +1,19 @@ +#pragma once + +#include "gcapture.h" +#include + + +namespace gcap +{ + void log_message(gcap_log_level_t level, const char *message_utf8); + void log_message_w(gcap_log_level_t level, const wchar_t *message_wide); + void log_printf(gcap_log_level_t level, const char *fmt, ...); +} + +inline void gcap_log_trace(const char *message_utf8) { gcap::log_message(GCAP_LOG_TRACE, message_utf8); } +inline void gcap_log_debug(const char *message_utf8) { gcap::log_message(GCAP_LOG_DEBUG, message_utf8); } +inline void gcap_log_info(const char *message_utf8) { gcap::log_message(GCAP_LOG_INFO, message_utf8); } +inline void gcap_log_warn(const char *message_utf8) { gcap::log_message(GCAP_LOG_WARN, message_utf8); } +inline void gcap_log_error(const char *message_utf8) { gcap::log_message(GCAP_LOG_ERROR, message_utf8); } +inline void gcap_log_debug_w(const wchar_t *message_wide) { gcap::log_message_w(GCAP_LOG_DEBUG, message_wide); } diff --git a/sdk/gcapture/src/pipeline/shared_scene_pipeline.cpp b/sdk/gcapture/src/pipeline/shared_scene_pipeline.cpp new file mode 100644 index 0000000..85bcaad --- /dev/null +++ b/sdk/gcapture/src/pipeline/shared_scene_pipeline.cpp @@ -0,0 +1,2519 @@ +#include +#include "../core/logging.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include "shared_scene_pipeline.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void SSP_DBG(const char *stage, HRESULT hr) +{ + char buf[256] = {}; + std::snprintf(buf, sizeof(buf), "[SharedScene] %s : hr=0x%lx\n", + stage ? stage : "(null)", (unsigned long)hr); + gcap_log_debug(buf); +} + +using Microsoft::WRL::ComPtr; + +static inline uint16_t normalize_y210_word_for_upload(uint16_t v) +{ + // Y210 stores each 10-bit component left-aligned in a 16-bit WORD. + // Bits [15:6] are valid, bits [5:0] are padding. + return static_cast((v >> 6) & 0x03FFu); +} + +static inline uint16_t v210_component_for_upload(uint32_t word, int shift) +{ + return static_cast((word >> shift) & 0x03FFu); +} + +static const char *ss_dxgi_format_name(DXGI_FORMAT fmt) +{ + switch (fmt) + { + case DXGI_FORMAT_UNKNOWN: + return "UNKNOWN"; + case DXGI_FORMAT_B8G8R8A8_UNORM: + return "B8G8R8A8_UNORM"; + case DXGI_FORMAT_R10G10B10A2_UNORM: + return "R10G10B10A2_UNORM"; + case DXGI_FORMAT_R16G16B16A16_FLOAT: + return "R16G16B16A16_FLOAT"; + case DXGI_FORMAT_NV12: + return "NV12"; + case DXGI_FORMAT_P010: + return "P010"; + default: + return "OTHER"; + } +} + +static void ssp_log_text(const char *msg) +{ + if (!msg) + return; + gcap_log_debug(msg); + gcap_log_debug("\n"); +} + +static ComPtr createSRV_NV12(ID3D11Device *dev, ID3D11Texture2D *tex, bool uv) +{ + if (!dev || !tex) + return {}; + + D3D11_SHADER_RESOURCE_VIEW_DESC d{}; + d.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + d.Texture2D.MipLevels = 1; + d.Format = uv ? DXGI_FORMAT_R8G8_UNORM : DXGI_FORMAT_R8_UNORM; + + ComPtr s; + if (FAILED(dev->CreateShaderResourceView(tex, &d, &s))) + return {}; + return s; +} + +static ComPtr createSRV_P010(ID3D11Device *dev, ID3D11Texture2D *tex, bool uv) +{ + if (!dev || !tex) + return {}; + + D3D11_SHADER_RESOURCE_VIEW_DESC d{}; + d.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + d.Texture2D.MipLevels = 1; + d.Format = uv ? DXGI_FORMAT_R16G16_UNORM : DXGI_FORMAT_R16_UNORM; + + ComPtr s; + if (FAILED(dev->CreateShaderResourceView(tex, &d, &s))) + return {}; + return s; +} + +static const char *g_vs_src = R"( +struct VSIn { float2 pos:POSITION; float2 uv:TEXCOORD0; }; +struct VSOut { float4 pos:SV_Position; float2 uv:TEXCOORD0; }; +VSOut main(VSIn i){ + VSOut o; o.pos=float4(i.pos,0,1); o.uv=i.uv; return o; +} +)"; + +static const char *g_ps_nv12 = R"( +Texture2D texY : register(t0); +Texture2D texUV : register(t1); +SamplerState samL: register(s0); + + +cbuffer ProcAmp : register(b0) +{ + uint width; + uint height; + float invW; + float invH; + + float br; // brightness offset (normalized, about [-0.5..0.5]) + float ct; // contrast factor (1.0 = neutral) + float sat; // saturation factor (1.0 = neutral) + float hueSin; // sin(hue) + + float hueCos; // cos(hue) + float sharpAmt; // [-1..+1], 0 = neutral + float pad0; + float pad1; +}; + +static float3 apply_rgb_procamp(float3 rgb) +{ + // contrast + brightness + rgb = (rgb - 0.5) * ct + 0.5 + br; + + // saturation + float l = dot(rgb, float3(0.299, 0.587, 0.114)); + rgb = lerp(float3(l, l, l), rgb, sat); + + return saturate(rgb); +} + +static float2 rotate_uv(float2 uv01) +{ + // uv01 is 0..1, convert to signed around 0 + float2 uv = uv01 - 0.5; + float u = uv.x; + float v = uv.y; + float u2 = u * hueCos - v * hueSin; + float v2 = u * hueSin + v * hueCos; + return float2(u2, v2) + 0.5; +} + + +float3 yuv_to_rgb709(float y, float u, float v) +{ + // y,u,v are normalized 0..1, assume limited->full & BT.709 + y = y * 255.0; + u = (u - 0.5) * 255.0; + v = (v - 0.5) * 255.0; + float c = y - 16.0; + float d = u; + float e = v; + float r = 1.164383 * c + 1.792741 * e; + float g = 1.164383 * c - 0.213249 * d - 0.532909 * e; + float b = 1.164383 * c + 2.112402 * d; + return float3(r,g,b)/255.0; +} + +float sampleY(float2 uv) +{ + return texY.Sample(samL, uv).r; +} + +float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target +{ + // ---- Sharpness on luma (Y) via small unsharp mask ---- + float yC = sampleY(uv); + float yL = sampleY(uv + float2(-invW, 0)); + float yR = sampleY(uv + float2( invW, 0)); + float yU = sampleY(uv + float2(0, -invH)); + float yD = sampleY(uv + float2(0, invH)); + + float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0; + float y = saturate(yC + sharpAmt * (yC - blur)); + + float2 uv2 = texUV.Sample(samL, uv).rg; + uv2 = rotate_uv(uv2); + + float3 rgb = yuv_to_rgb709(y, uv2.x, uv2.y); + rgb = apply_rgb_procamp(rgb); + return float4(rgb, 1.0); +} +)"; + +static const char *g_ps_p010 = R"( +Texture2D texY16 : register(t0); +Texture2D texUV16 : register(t1); +SamplerState samL: register(s0); + + +cbuffer ProcAmp : register(b0) +{ + uint width; + uint height; + float invW; + float invH; + + float br; // brightness offset (normalized, about [-0.5..0.5]) + float ct; // contrast factor (1.0 = neutral) + float sat; // saturation factor (1.0 = neutral) + float hueSin; // sin(hue) + + float hueCos; // cos(hue) + float sharpAmt; // [-1..+1], 0 = neutral + float pad0; + float pad1; +}; + +static float3 apply_rgb_procamp(float3 rgb) +{ + // contrast + brightness + rgb = (rgb - 0.5) * ct + 0.5 + br; + + // saturation + float l = dot(rgb, float3(0.299, 0.587, 0.114)); + rgb = lerp(float3(l, l, l), rgb, sat); + + return saturate(rgb); +} + +static float2 rotate_uv(float2 uv01) +{ + // uv01 is 0..1, convert to signed around 0 + float2 uv = uv01 - 0.5; + float u = uv.x; + float v = uv.y; + float u2 = u * hueCos - v * hueSin; + float v2 = u * hueSin + v * hueCos; + return float2(u2, v2) + 0.5; +} + + +float3 yuv_to_rgb709(float y, float u, float v) +{ + y = y * 255.0; + u = (u - 0.5) * 255.0; + v = (v - 0.5) * 255.0; + float c = y - 16.0; + float d = u; + float e = v; + float r = 1.164383 * c + 1.792741 * e; + float g = 1.164383 * c - 0.213249 * d - 0.532909 * e; + float b = 1.164383 * c + 2.112402 * d; + return float3(r,g,b)/255.0; +} + +float loadY(int2 ip) +{ + ip.x = clamp(ip.x, 0, (int)width - 1); + ip.y = clamp(ip.y, 0, (int)height - 1); + return saturate(texY16.Load(int3(ip, 0)).r); +} + +float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target +{ + int2 ip = int2(pos.xy); + + // Sharpness on luma + float yC = loadY(ip); + float yL = loadY(ip + int2(-1, 0)); + float yR = loadY(ip + int2( 1, 0)); + float yU = loadY(ip + int2( 0,-1)); + float yD = loadY(ip + int2( 0, 1)); + float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0; + float y = saturate(yC + sharpAmt * (yC - blur)); + + int2 uvp = int2(ip.x / 2, ip.y / 2); + float2 uvv = saturate(texUV16.Load(int3(uvp, 0)).rg); + float u = uvv.x; + float v = uvv.y; + + float2 uv2 = rotate_uv(float2(u, v)); + + float3 rgb = yuv_to_rgb709(y, uv2.x, uv2.y); + rgb = apply_rgb_procamp(rgb); + return float4(rgb, 1.0); +} +)"; + +// YUY2(4:2:2 packed): +// 我們把每兩個像素打包成一個 RGBA8_UINT texel: +// R=Y0, G=U, B=Y1, A=V +// texture width = ceil(w/2) +static const char *g_ps_yuy2 = R"( +// YUY2 (4:2:2 packed): +// Each texel packs 2 pixels: R=Y0, G=U, B=Y1, A=V +// texture width = ceil(w/2) +Texture2D texP : register(t0); + + +cbuffer ProcAmp : register(b0) +{ + uint width; + uint height; + float invW; + float invH; + + float br; // brightness offset (normalized, about [-0.5..0.5]) + float ct; // contrast factor (1.0 = neutral) + float sat; // saturation factor (1.0 = neutral) + float hueSin; // sin(hue) + + float hueCos; // cos(hue) + float sharpAmt; // [-1..+1], 0 = neutral + float pad0; + float pad1; +}; + +static float3 apply_rgb_procamp(float3 rgb) +{ + // contrast + brightness + rgb = (rgb - 0.5) * ct + 0.5 + br; + + // saturation + float l = dot(rgb, float3(0.299, 0.587, 0.114)); + rgb = lerp(float3(l, l, l), rgb, sat); + + return saturate(rgb); +} + +static float2 rotate_uv(float2 uv01) +{ + // uv01 is 0..1, convert to signed around 0 + float2 uv = uv01 - 0.5; + float u = uv.x; + float v = uv.y; + float u2 = u * hueCos - v * hueSin; + float v2 = u * hueSin + v * hueCos; + return float2(u2, v2) + 0.5; +} + + +float3 yuv_to_rgb709(float y, float u, float v) +{ + y = y * 255.0; + u = (u - 0.5) * 255.0; + v = (v - 0.5) * 255.0; + float c = y - 16.0; + float d = u; + float e = v; + float r = 1.164383 * c + 1.792741 * e; + float g = 1.164383 * c - 0.213249 * d - 0.532909 * e; + float b = 1.164383 * c + 2.112402 * d; + return float3(r,g,b)/255.0; +} + +float loadY(int x, int y) +{ + x = clamp(x, 0, (int)width - 1); + y = clamp(y, 0, (int)height - 1); + uint4 p = texP.Load(int3(x >> 1, y, 0)); + uint yy = ((x & 1) != 0) ? p.b : p.r; + return (float)yy / 255.0; +} + +float2 loadUV01(int x, int y) +{ + x = clamp(x, 0, (int)width - 1); + y = clamp(y, 0, (int)height - 1); + uint4 p = texP.Load(int3(x >> 1, y, 0)); + float u = (float)p.g / 255.0; + float v = (float)p.a / 255.0; + return float2(u, v); +} + +float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target +{ + int2 ip = int2(pos.xy); + int px = ip.x; + int py = ip.y; + + // Sharpness on luma + float yC = loadY(px, py); + float yL = loadY(px - 1, py); + float yR = loadY(px + 1, py); + float yU = loadY(px, py - 1); + float yD = loadY(px, py + 1); + float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0; + float y = saturate(yC + sharpAmt * (yC - blur)); + + float2 uv01 = loadUV01(px, py); + uv01 = rotate_uv(uv01); + + float3 rgb = yuv_to_rgb709(y, uv01.x, uv01.y); + rgb = apply_rgb_procamp(rgb); + return float4(rgb, 1.0); +} +)"; + +// NV12 → RGBA 的 Compute Shader 版本 + +// Y210(4:2:2 packed, 10-bit in 16-bit container): +// 每個 texel 打包 2 個像素:R=Y0, G=U, B=Y1, A=V +// texture width = ceil(w/2), format = R16G16B16A16_UINT +static const char *g_ps_y210 = R"( +Texture2D texP : register(t0); + +cbuffer ProcAmp : register(b0) +{ + uint width; + uint height; + float invW; + float invH; + + float br; + float ct; + float sat; + float hueSin; + + float hueCos; + float sharpAmt; + float pad0; + float pad1; +}; + +static float3 apply_rgb_procamp(float3 rgb) +{ + rgb = (rgb - 0.5) * ct + 0.5 + br; + float l = dot(rgb, float3(0.299, 0.587, 0.114)); + rgb = lerp(float3(l, l, l), rgb, sat); + return saturate(rgb); +} + +static float2 rotate_uv(float2 uv01) +{ + float2 uv = uv01 - 0.5; + float u = uv.x; + float v = uv.y; + float u2 = u * hueCos - v * hueSin; + float v2 = u * hueSin + v * hueCos; + return float2(u2, v2) + 0.5; +} + +float3 yuv_to_rgb709(float y, float u, float v) +{ + y = y * 255.0; + u = (u - 0.5) * 255.0; + v = (v - 0.5) * 255.0; + float c = y - 16.0; + float d = u; + float e = v; + float r = 1.164383 * c + 1.792741 * e; + float g = 1.164383 * c - 0.213249 * d - 0.532909 * e; + float b = 1.164383 * c + 2.112402 * d; + return float3(r,g,b)/255.0; +} + +float loadY(int x, int y) +{ + x = clamp(x, 0, (int)width - 1); + y = clamp(y, 0, (int)height - 1); + uint4 p = texP.Load(int3(x >> 1, y, 0)); + uint yy = ((x & 1) != 0) ? p.b : p.r; + return (float)(yy & 1023) / 1023.0; +} + +float2 loadUV01(int x, int y) +{ + x = clamp(x, 0, (int)width - 1); + y = clamp(y, 0, (int)height - 1); + uint4 p = texP.Load(int3(x >> 1, y, 0)); + float u = (float)(p.g & 1023) / 1023.0; + float v = (float)(p.a & 1023) / 1023.0; + return float2(u, v); +} + +float4 main(float4 pos:SV_Position, float2 uv:TEXCOORD0) : SV_Target +{ + int2 ip = int2(pos.xy); + int px = ip.x; + int py = ip.y; + + float yC = loadY(px, py); + float yL = loadY(px - 1, py); + float yR = loadY(px + 1, py); + float yU = loadY(px, py - 1); + float yD = loadY(px, py + 1); + float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0; + float y = saturate(yC + sharpAmt * (yC - blur)); + + float2 uv01 = loadUV01(px, py); + uv01 = rotate_uv(uv01); + + float3 rgb = yuv_to_rgb709(y, uv01.x, uv01.y); + rgb = apply_rgb_procamp(rgb); + return float4(rgb, 1.0); +} +)"; + +static const char *g_cs_nv12 = R"( +Texture2D texY : register(t0); +Texture2D texUV : register(t1); +RWTexture2D texOut : register(u0); + +cbuffer ProcAmp : register(b0) +{ + uint width; + uint height; + float invW; + float invH; + + float br; + float ct; + float sat; + float hueSin; + + float hueCos; + float sharpAmt; + float pad0; + float pad1; +}; + +static float3 apply_rgb_procamp(float3 rgb) +{ + rgb = (rgb - 0.5) * ct + 0.5 + br; + float l = dot(rgb, float3(0.299, 0.587, 0.114)); + rgb = lerp(float3(l,l,l), rgb, sat); + return saturate(rgb); +} + +static float2 rotate_uv(float2 uv01) +{ + float2 uv = uv01 - 0.5; + float u = uv.x; + float v = uv.y; + float u2 = u * hueCos - v * hueSin; + float v2 = u * hueSin + v * hueCos; + return float2(u2, v2) + 0.5; +} + +[numthreads(16, 16, 1)] +void main(uint3 tid : SV_DispatchThreadID) +{ + uint x = tid.x; + uint y = tid.y; + if (x >= width || y >= height) return; + + float yC = texY.Load(int3(x, y, 0)); + float yL = texY.Load(int3((int)max((int)x - 1, 0), (int)y, 0)); + float yR = texY.Load(int3((int)min((int)x + 1, (int)width - 1), (int)y, 0)); + float yU = texY.Load(int3((int)x, (int)max((int)y - 1, 0), 0)); + float yD = texY.Load(int3((int)x, (int)min((int)y + 1, (int)height - 1), 0)); + float blur = (yC*4.0 + yL + yR + yU + yD) / 8.0; + float yNorm = saturate(yC + sharpAmt * (yC - blur)); + + float2 uvNorm = texUV.Load(int3(x / 2, y / 2, 0)); + uvNorm = rotate_uv(uvNorm); + + // Convert to RGB (BT.709 limited->full) + float Y = yNorm * 255.0; + float U = (uvNorm.x - 0.5) * 255.0; + float V = (uvNorm.y - 0.5) * 255.0; + + float c = Y - 16.0; + float d = U; + float e = V; + + float r = 1.164383 * c + 1.792741 * e; + float g = 1.164383 * c - 0.213249 * d - 0.532909 * e; + float b = 1.164383 * c + 2.112402 * d; + + float3 rgb = float3(r, g, b) / 255.0; + rgb = apply_rgb_procamp(rgb); + + texOut[uint2(x, y)] = float4(rgb, 1.0); +} +)"; + +static const char *g_ps_fp16_to_rgba8 = R"( +Texture2D tex0 : register(t0); +SamplerState samL : register(s0); + +struct PSIn +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +float4 main(PSIn i) : SV_Target +{ + float4 c = tex0.Sample(samL, i.uv); + return saturate(c); +} +)"; + +static const char *g_ps_fp16_to_preview = R"( +Texture2D tex0 : register(t0); +SamplerState samL : register(s0); + +struct PSIn +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +float4 main(PSIn i) : SV_Target +{ + float4 c = tex0.Sample(samL, i.uv); + return float4(saturate(c.rgb), 1.0); +} +)"; + +static const char *g_ps_composite_overlay_fp16 = R"( +Texture2D texBase : register(t0); +Texture2D texOverlay : register(t1); +SamplerState samL : register(s0); + +struct PSIn +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +float4 main(PSIn i) : SV_Target +{ + float4 base = texBase.Sample(samL, i.uv); + float4 ov = texOverlay.Sample(samL, i.uv); + float a = saturate(ov.a); + float3 rgb = ov.rgb + base.rgb * (1.0 - a); + return float4(rgb, 1.0); +} +)"; + +static const char *g_ps_rgba8_to_preview = R"( +Texture2D tex0 : register(t0); +SamplerState samL : register(s0); + +struct PSIn +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +float4 main(PSIn i) : SV_Target +{ + float4 c = tex0.Sample(samL, i.uv); + c.rgb = saturate(c.rgb); + return c; +} +)"; + +bool SharedScenePipeline::initialize(ID3D11Device *d3d, + ID3D11DeviceContext *ctx, + ID2D1DeviceContext *d2d_ctx, + IDWriteFactory *dwrite, + ID2D1SolidColorBrush *white, + ID2D1SolidColorBrush *black) +{ + d3d_ = d3d; + ctx_ = ctx; + d2d_ctx_ = d2d_ctx; + dwrite_ = dwrite; + d2d_white_ = white; + d2d_black_ = black; + return d3d_ && ctx_ && d2d_ctx_; +} + +void SharedScenePipeline::shutdown() +{ + release_preview_swapchain(); + d2d_bitmap_rt_.Reset(); + d2d_white_.Reset(); + d2d_black_.Reset(); + dwrite_.Reset(); + overlay_srv_.Reset(); + overlay_rtv_.Reset(); + overlay_rgba_.Reset(); + srv_scene_fp16_.Reset(); + rtv_scene_fp16_.Reset(); + rt_scene_fp16_.Reset(); + srv_fp16_.Reset(); + rtv_fp16_.Reset(); + rt_fp16_.Reset(); + srv_rgba_.Reset(); + rtv_rgba_.Reset(); + rt_rgba_.Reset(); + rt_stage_.Reset(); + rt_scene_stage_fp16_.Reset(); + samp_.Reset(); + vb_.Reset(); + il_.Reset(); + vs_.Reset(); + ps_nv12_.Reset(); + ps_p010_.Reset(); + ps_yuy2_.Reset(); + ps_y210_.Reset(); + ps_fp16_to_rgba8_.Reset(); + ps_fp16_to_preview_.Reset(); + ps_rgba8_to_preview_.Reset(); + ps_composite_overlay_fp16_.Reset(); + cs_params_.Reset(); + rt_uav_.Reset(); + d3d_ = nullptr; + ctx_ = nullptr; + d2d_ctx_ = nullptr; +} + +bool SharedScenePipeline::configurePreview(const gcap_preview_desc_t &desc) +{ + int requestedMode = desc.swapchain_10bit; + if (requestedMode != GCAP_PREVIEW_BITDEPTH_8BIT && + requestedMode != GCAP_PREVIEW_BITDEPTH_10BIT && + requestedMode != GCAP_PREVIEW_BITDEPTH_AUTO) + { + requestedMode = GCAP_PREVIEW_BITDEPTH_AUTO; + } + + const bool modeChanged = (preview_swapchain_mode_ != requestedMode); + const bool hwndChanged = (preview_hwnd_ != desc.hwnd); + const bool enabledChanged = (preview_enabled_ != (desc.enable_preview != 0)); + + preview_hwnd_ = desc.hwnd; + preview_enabled_ = (desc.enable_preview != 0); + preview_use_fp16_ = (desc.use_fp16_pipeline != 0); + preview_swapchain_mode_ = requestedMode; + + if (modeChanged || hwndChanged || enabledChanged) + release_preview_swapchain(); + + return true; +} + +void SharedScenePipeline::set_source_bit_depth(int bits) +{ + if (bits != 8 && bits != 10 && bits != 12 && bits != 16) + bits = 0; + + const int oldEffectiveMode = (preview_swapchain_mode_ == GCAP_PREVIEW_BITDEPTH_AUTO) + ? ((preview_source_bit_depth_ >= 10) ? GCAP_PREVIEW_BITDEPTH_10BIT : GCAP_PREVIEW_BITDEPTH_8BIT) + : preview_swapchain_mode_; + const int newEffectiveMode = (preview_swapchain_mode_ == GCAP_PREVIEW_BITDEPTH_AUTO) + ? ((bits >= 10) ? GCAP_PREVIEW_BITDEPTH_10BIT : GCAP_PREVIEW_BITDEPTH_8BIT) + : preview_swapchain_mode_; + + preview_source_bit_depth_ = bits; + if (oldEffectiveMode != newEffectiveMode) + release_preview_swapchain(); +} + +bool SharedScenePipeline::create_shaders_and_states() +{ + // Compile shaders + ComPtr vsb, psb1, psb2, psb3, psb4, psb5, psb6, psb7, err; + if (FAILED(D3DCompile(g_vs_src, strlen(g_vs_src), nullptr, nullptr, nullptr, + "main", "vs_5_0", 0, 0, &vsb, &err))) + return false; + if (FAILED(d3d_->CreateVertexShader(vsb->GetBufferPointer(), vsb->GetBufferSize(), nullptr, &vs_))) + return false; + + D3D11_INPUT_ELEMENT_DESC ied[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0}, + }; + if (FAILED(d3d_->CreateInputLayout(ied, 2, vsb->GetBufferPointer(), vsb->GetBufferSize(), &il_))) + return false; + + if (FAILED(D3DCompile(g_ps_nv12, strlen(g_ps_nv12), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb1, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb1->GetBufferPointer(), psb1->GetBufferSize(), nullptr, &ps_nv12_))) + return false; + + if (FAILED(D3DCompile(g_ps_p010, strlen(g_ps_p010), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb2, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb2->GetBufferPointer(), psb2->GetBufferSize(), nullptr, &ps_p010_))) + return false; + + if (FAILED(D3DCompile(g_ps_yuy2, strlen(g_ps_yuy2), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb3, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb3->GetBufferPointer(), psb3->GetBufferSize(), nullptr, &ps_yuy2_))) + return false; + + ComPtr psbY210; + if (FAILED(D3DCompile(g_ps_y210, strlen(g_ps_y210), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psbY210, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psbY210->GetBufferPointer(), psbY210->GetBufferSize(), nullptr, &ps_y210_))) + return false; + + if (FAILED(D3DCompile(g_ps_fp16_to_rgba8, strlen(g_ps_fp16_to_rgba8), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb4, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb4->GetBufferPointer(), psb4->GetBufferSize(), nullptr, &ps_fp16_to_rgba8_))) + return false; + + if (FAILED(D3DCompile(g_ps_fp16_to_preview, strlen(g_ps_fp16_to_preview), nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb5, &err))) + return false; + if (FAILED(D3DCompile(g_ps_rgba8_to_preview, strlen(g_ps_rgba8_to_preview), + nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb6, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb5->GetBufferPointer(), psb5->GetBufferSize(), nullptr, &ps_fp16_to_preview_))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb6->GetBufferPointer(), + psb6->GetBufferSize(), + nullptr, + &ps_rgba8_to_preview_))) + return false; + if (FAILED(D3DCompile(g_ps_composite_overlay_fp16, strlen(g_ps_composite_overlay_fp16), + nullptr, nullptr, nullptr, + "main", "ps_5_0", 0, 0, &psb7, &err))) + return false; + if (FAILED(d3d_->CreatePixelShader(psb7->GetBufferPointer(), + psb7->GetBufferSize(), + nullptr, + &ps_composite_overlay_fp16_))) + return false; + + // Fullscreen quad (two triangles) + struct V + { + float x, y, u, v; + }; + V quad[6] = { + {-1.f, -1.f, 0.f, 1.f}, {-1.f, 1.f, 0.f, 0.f}, {1.f, 1.f, 1.f, 0.f}, {-1.f, -1.f, 0.f, 1.f}, {1.f, 1.f, 1.f, 0.f}, {1.f, -1.f, 1.f, 1.f}}; + D3D11_BUFFER_DESC bd{}; + bd.ByteWidth = sizeof(quad); + bd.Usage = D3D11_USAGE_IMMUTABLE; + bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; + D3D11_SUBRESOURCE_DATA sd{}; + sd.pSysMem = quad; + if (FAILED(d3d_->CreateBuffer(&bd, &sd, &vb_))) + return false; + + D3D11_SAMPLER_DESC ss{}; + ss.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + ss.AddressU = ss.AddressV = ss.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + if (FAILED(d3d_->CreateSamplerState(&ss, &samp_))) + return false; + + // ProcAmp constant buffer (shared by PS/CS). Layout must match shader cbuffer Params. + if (!cs_params_) + { + D3D11_BUFFER_DESC cbd{}; + cbd.ByteWidth = 64; // 48 bytes used, round up to 64 + cbd.Usage = D3D11_USAGE_DYNAMIC; + cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateBuffer(&cbd, nullptr, &cs_params_))) + return false; + } + + return true; +} + +bool SharedScenePipeline::ensure_rt_and_pipeline(int w, int h) +{ + const auto t0 = std::chrono::steady_clock::now(); + lastEnsureRtRebuilt_ = false; + lastEnsureRtReason_ = "reuse"; + + const bool hasAllTargets = rt_fp16_ && rtv_fp16_ && srv_fp16_ && + rt_scene_fp16_ && rtv_scene_fp16_ && srv_scene_fp16_ && + rt_rgba_ && rtv_rgba_ && srv_rgba_ && + overlay_rgba_ && overlay_rtv_ && overlay_srv_ && + rt_stage_ && rt_scene_stage_fp16_ && d2d_bitmap_rt_; + + if (hasAllTargets && rt_w_ == w && rt_h_ == h) + { + const auto t1 = std::chrono::steady_clock::now(); + lastEnsureRtNs_ = (uint64_t)std::chrono::duration_cast(t1 - t0).count(); + totalEnsureRtNs_ += lastEnsureRtNs_; + ++ensureRtCalls_; + return true; + } + + lastEnsureRtRebuilt_ = true; + if (!hasAllTargets) + lastEnsureRtReason_ = "missing-targets"; + else if (rt_w_ != w || rt_h_ != h) + lastEnsureRtReason_ = "size-change"; + else + lastEnsureRtReason_ = "unknown"; + + rt_fp16_.Reset(); + rtv_fp16_.Reset(); + srv_fp16_.Reset(); + rt_scene_fp16_.Reset(); + rtv_scene_fp16_.Reset(); + srv_scene_fp16_.Reset(); + rt_rgba_.Reset(); + rtv_rgba_.Reset(); + srv_rgba_.Reset(); + overlay_rgba_.Reset(); + overlay_rtv_.Reset(); + overlay_srv_.Reset(); + rt_stage_.Reset(); + rt_scene_stage_fp16_.Reset(); + d2d_bitmap_rt_.Reset(); + + // 1) High precision intermediate target + D3D11_TEXTURE2D_DESC td{}; + td.Width = w; + td.Height = h; + td.MipLevels = 1; + td.ArraySize = 1; + td.SampleDesc = {1, 0}; + td.Usage = D3D11_USAGE_DEFAULT; + td.CPUAccessFlags = 0; + td.MiscFlags = 0; + td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; + td.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &rt_fp16_))) + return false; + if (FAILED(d3d_->CreateRenderTargetView(rt_fp16_.Get(), nullptr, &rtv_fp16_))) + return false; + if (FAILED(d3d_->CreateShaderResourceView(rt_fp16_.Get(), nullptr, &srv_fp16_))) + return false; + + // rt 尺寸/格式若重建,compute path 的 UAV 也要跟著重建 + rt_uav_.Reset(); + + // 2) Composited FP16 scene target (base FP16 + overlay) + td.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &rt_scene_fp16_))) + return false; + if (FAILED(d3d_->CreateRenderTargetView(rt_scene_fp16_.Get(), nullptr, &rtv_scene_fp16_))) + return false; + if (FAILED(d3d_->CreateShaderResourceView(rt_scene_fp16_.Get(), nullptr, &srv_scene_fp16_))) + return false; + + // 3) RGBA8 target for CPU readback / compatibility output + td.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &rt_rgba_))) + return false; + if (FAILED(d3d_->CreateRenderTargetView(rt_rgba_.Get(), nullptr, &rtv_rgba_))) + return false; + if (FAILED(d3d_->CreateShaderResourceView(rt_rgba_.Get(), nullptr, &srv_rgba_))) + return false; + + // 4) Overlay texture for D2D/DWrite (premultiplied BGRA8) + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &overlay_rgba_))) + return false; + if (FAILED(d3d_->CreateRenderTargetView(overlay_rgba_.Get(), nullptr, &overlay_rtv_))) + return false; + if (FAILED(d3d_->CreateShaderResourceView(overlay_rgba_.Get(), nullptr, &overlay_srv_))) + return false; + + // 5) staging for readback + td.BindFlags = 0; + td.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + td.Usage = D3D11_USAGE_STAGING; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &rt_stage_))) + return false; + + td.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &rt_scene_stage_fp16_))) + return false; + + // 6) D2D target now stays on dedicated overlay texture, not the final preview/readback surface + ComPtr surf; + if (FAILED(overlay_rgba_->QueryInterface(IID_PPV_ARGS(&surf))) || !surf) + return false; + D2D1_BITMAP_PROPERTIES1 bp = {}; + bp.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; + bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; + bp.dpiX = 96.f; + bp.dpiY = 96.f; + bp.bitmapOptions = (D2D1_BITMAP_OPTIONS)(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW); + bp.colorContext = nullptr; + + if (FAILED(d2d_ctx_->CreateBitmapFromDxgiSurface(surf.Get(), &bp, &d2d_bitmap_rt_))) + { + SSP_DBG("D2D CreateBitmapFromDxgiSurface", E_FAIL); + return false; + } + + d2d_ctx_->SetTarget(d2d_bitmap_rt_.Get()); + + const bool ok = create_shaders_and_states(); + if (ok) + { + rt_w_ = w; + rt_h_ = h; + } + const auto t1 = std::chrono::steady_clock::now(); + lastEnsureRtNs_ = (uint64_t)std::chrono::duration_cast(t1 - t0).count(); + totalEnsureRtNs_ += lastEnsureRtNs_; + ++ensureRtCalls_; + return ok; +} + +bool SharedScenePipeline::gpu_overlay_text(const wchar_t *text, int frame_w, int frame_h) +{ + if (!text || !*text || !d2d_ctx_ || !dwrite_) + return true; + + d2d_ctx_->BeginDraw(); + d2d_ctx_->SetTransform(D2D1::Matrix3x2F::Identity()); + d2d_ctx_->Clear(D2D1::ColorF(0, 0, 0, 0)); + + ComPtr fmt; + HRESULT hr = dwrite_->CreateTextFormat( + L"Segoe UI", + nullptr, + DWRITE_FONT_WEIGHT_SEMI_BOLD, + DWRITE_FONT_STYLE_NORMAL, + DWRITE_FONT_STRETCH_NORMAL, + 16.0f, + L"en-us", + &fmt); + if (FAILED(hr)) + { + d2d_ctx_->EndDraw(); + return false; + } + + fmt->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); + fmt->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); + + float layoutWidth = static_cast(frame_w) - 32.0f; + if (layoutWidth < 100.0f) + layoutWidth = 100.0f; + float layoutHeight = 100.0f; + + ComPtr layout; + hr = dwrite_->CreateTextLayout( + text, + (UINT32)wcslen(text), + fmt.Get(), + layoutWidth, + layoutHeight, + &layout); + if (FAILED(hr)) + { + d2d_ctx_->EndDraw(); + return false; + } + + DWRITE_TEXT_METRICS metrics{}; + hr = layout->GetMetrics(&metrics); + if (FAILED(hr)) + { + d2d_ctx_->EndDraw(); + return false; + } + + float textWidth = metrics.width; + float textHeight = metrics.height; + const float padX = 12.0f; + const float padY = 6.0f; + + D2D1_RECT_F bg = D2D1::RectF( + 8.0f, + 8.0f, + 8.0f + textWidth + padX * 2.0f, + 8.0f + textHeight + padY * 2.0f); + + if (d2d_black_) + d2d_ctx_->FillRectangle(bg, d2d_black_.Get()); + + D2D1_RECT_F rc = D2D1::RectF( + bg.left + padX, + bg.top + padY, + bg.right - padX, + bg.bottom - padY); + + if (d2d_white_) + d2d_ctx_->DrawText( + text, + (UINT32)wcslen(text), + fmt.Get(), + rc, + d2d_white_.Get()); + + hr = d2d_ctx_->EndDraw(); + return SUCCEEDED(hr); +} + +bool SharedScenePipeline::composite_overlay_to_scene_fp16(int frame_w, int frame_h) +{ + if (!rtv_scene_fp16_ || !srv_fp16_ || !overlay_srv_ || !vs_ || !ps_composite_overlay_fp16_ || !ctx_) + return false; + + UINT stride = sizeof(float) * 4, offset = 0; + ID3D11Buffer *pVB = vb_.Get(); + ctx_->IASetVertexBuffers(0, 1, &pVB, &stride, &offset); + ctx_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx_->IASetInputLayout(il_.Get()); + + ID3D11RenderTargetView *rtv = rtv_scene_fp16_.Get(); + ctx_->OMSetRenderTargets(1, &rtv, nullptr); + + D3D11_VIEWPORT vp{}; + vp.TopLeftX = 0.0f; + vp.TopLeftY = 0.0f; + vp.Width = static_cast(frame_w); + vp.Height = static_cast(frame_h); + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + ctx_->RSSetViewports(1, &vp); + + const float clear[4] = {0, 0, 0, 1}; + ctx_->ClearRenderTargetView(rtv_scene_fp16_.Get(), clear); + + ctx_->VSSetShader(vs_.Get(), nullptr, 0); + ctx_->PSSetShader(ps_composite_overlay_fp16_.Get(), nullptr, 0); + + ID3D11ShaderResourceView *srvs[2] = {srv_fp16_.Get(), overlay_srv_.Get()}; + ctx_->PSSetShaderResources(0, 2, srvs); + + ID3D11SamplerState *ss = samp_.Get(); + ctx_->PSSetSamplers(0, 1, &ss); + + ctx_->Draw(6, 0); + + ID3D11ShaderResourceView *nullSrv[2] = {nullptr, nullptr}; + ctx_->PSSetShaderResources(0, 2, nullSrv); + + return true; +} + +bool SharedScenePipeline::blit_fp16_to_rgba8(int frame_w, int frame_h) +{ + if (!rtv_rgba_ || !srv_scene_fp16_ || !vs_ || !ps_fp16_to_rgba8_ || !ctx_) + return false; + + UINT stride = sizeof(float) * 4, offset = 0; + ID3D11Buffer *pVB = vb_.Get(); + ctx_->IASetVertexBuffers(0, 1, &pVB, &stride, &offset); + ctx_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx_->IASetInputLayout(il_.Get()); + + ID3D11RenderTargetView *rtv = rtv_rgba_.Get(); + ctx_->OMSetRenderTargets(1, &rtv, nullptr); + + D3D11_VIEWPORT vp{}; + vp.TopLeftX = 0.0f; + vp.TopLeftY = 0.0f; + vp.Width = static_cast(frame_w); + vp.Height = static_cast(frame_h); + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + ctx_->RSSetViewports(1, &vp); + + const float clear[4] = {0, 0, 0, 1}; + ctx_->ClearRenderTargetView(rtv_rgba_.Get(), clear); + + ctx_->VSSetShader(vs_.Get(), nullptr, 0); + ctx_->PSSetShader(ps_fp16_to_rgba8_.Get(), nullptr, 0); + + ID3D11ShaderResourceView *srvs[1] = {srv_scene_fp16_.Get()}; + ctx_->PSSetShaderResources(0, 1, srvs); + + ID3D11SamplerState *ss = samp_.Get(); + ctx_->PSSetSamplers(0, 1, &ss); + + ctx_->Draw(6, 0); + + ID3D11ShaderResourceView *nullSrv[1] = {nullptr}; + ctx_->PSSetShaderResources(0, 1, nullSrv); + + return true; +} + +bool SharedScenePipeline::upload_argb_frame(const void *data, int frame_w, int frame_h, int src_stride) +{ + if (!data || !ctx_ || !rt_rgba_ || frame_w <= 0 || frame_h <= 0 || src_stride <= 0) + return false; + + D3D11_BOX box{}; + box.left = 0; + box.top = 0; + box.front = 0; + box.right = (UINT)frame_w; + box.bottom = (UINT)frame_h; + box.back = 1; + + ctx_->UpdateSubresource(rt_rgba_.Get(), 0, &box, data, (UINT)src_stride, 0); + return true; +} + +bool SharedScenePipeline::render_uploaded_argb_to_fp16(int frame_w, int frame_h) +{ + if (!ctx_ || !vs_ || !il_ || !vb_ || !rtv_fp16_ || !srv_rgba_ || !ps_rgba8_to_preview_ || frame_w <= 0 || frame_h <= 0) + return false; + + UINT stride = sizeof(float) * 4, offset = 0; + ID3D11Buffer *pVB = vb_.Get(); + ctx_->IASetVertexBuffers(0, 1, &pVB, &stride, &offset); + ctx_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx_->IASetInputLayout(il_.Get()); + + ctx_->VSSetShader(vs_.Get(), nullptr, 0); + ctx_->PSSetShader(ps_rgba8_to_preview_.Get(), nullptr, 0); + + D3D11_VIEWPORT vp{}; + vp.TopLeftX = 0.0f; + vp.TopLeftY = 0.0f; + vp.Width = static_cast(frame_w); + vp.Height = static_cast(frame_h); + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + ctx_->RSSetViewports(1, &vp); + + ID3D11RenderTargetView *rtv = rtv_fp16_.Get(); + ctx_->OMSetRenderTargets(1, &rtv, nullptr); + const float clear[4] = {0, 0, 0, 1}; + ctx_->ClearRenderTargetView(rtv_fp16_.Get(), clear); + + ID3D11ShaderResourceView *srv = srv_rgba_.Get(); + ctx_->PSSetShaderResources(0, 1, &srv); + ID3D11SamplerState *ss = samp_.Get(); + ctx_->PSSetSamplers(0, 1, &ss); + ctx_->Draw(6, 0); + + ID3D11ShaderResourceView *nullSrv = nullptr; + ctx_->PSSetShaderResources(0, 1, &nullSrv); + return true; +} + +bool SharedScenePipeline::upload_nv12_frame(const uint8_t *y, int stride_y, const uint8_t *uv, int stride_uv, int frame_w, int frame_h) +{ + if (!d3d_ || !ctx_ || !y || !uv || frame_w <= 0 || frame_h <= 0 || stride_y <= 0 || stride_uv <= 0) + return false; + + if (!upload_nv12_) + { + D3D11_TEXTURE2D_DESC td{}; + td.Width = (UINT)frame_w; + td.Height = (UINT)frame_h; + td.MipLevels = 1; + td.ArraySize = 1; + td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_NV12; + td.Usage = D3D11_USAGE_DYNAMIC; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &upload_nv12_))) + return false; + } + else + { + D3D11_TEXTURE2D_DESC td{}; + upload_nv12_->GetDesc(&td); + if ((int)td.Width != frame_w || (int)td.Height != frame_h || td.Format != DXGI_FORMAT_NV12) + { + upload_nv12_.Reset(); + return upload_nv12_frame(y, stride_y, uv, stride_uv, frame_w, frame_h); + } + } + + D3D11_MAPPED_SUBRESOURCE m{}; + HRESULT hr = ctx_->Map(upload_nv12_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m); + if (FAILED(hr)) + return false; + + uint8_t *dst = static_cast(m.pData); + for (int row = 0; row < frame_h; ++row) + std::memcpy(dst + (size_t)row * m.RowPitch, y + (size_t)row * stride_y, (size_t)frame_w); + + uint8_t *dst_uv = dst + (size_t)m.RowPitch * (size_t)frame_h; + for (int row = 0; row < frame_h / 2; ++row) + std::memcpy(dst_uv + (size_t)row * m.RowPitch, uv + (size_t)row * stride_uv, (size_t)frame_w); + + ctx_->Unmap(upload_nv12_.Get(), 0); + return true; +} + +bool SharedScenePipeline::upload_p010_frame(const uint8_t *y, int stride_y, const uint8_t *uv, int stride_uv, int frame_w, int frame_h) +{ + if (!ctx_ || !d3d_ || !y || !uv || frame_w <= 0 || frame_h <= 0) + return false; + + if (!upload_nv12_) + { + D3D11_TEXTURE2D_DESC td{}; + td.Width = (UINT)frame_w; + td.Height = (UINT)frame_h; + td.MipLevels = 1; + td.ArraySize = 1; + td.Format = DXGI_FORMAT_P010; + td.SampleDesc = {1, 0}; + td.Usage = D3D11_USAGE_DYNAMIC; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &upload_nv12_))) + return false; + } + else + { + D3D11_TEXTURE2D_DESC td{}; + upload_nv12_->GetDesc(&td); + if ((int)td.Width != frame_w || (int)td.Height != frame_h || td.Format != DXGI_FORMAT_P010) + { + upload_nv12_.Reset(); + return upload_p010_frame(y, stride_y, uv, stride_uv, frame_w, frame_h); + } + } + + D3D11_MAPPED_SUBRESOURCE m{}; + HRESULT hr = ctx_->Map(upload_nv12_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m); + if (FAILED(hr)) + return false; + + uint8_t *dstY = reinterpret_cast(m.pData); + for (int r = 0; r < frame_h; ++r) + std::memcpy(dstY + (size_t)r * m.RowPitch, y + (size_t)r * stride_y, (size_t)frame_w * 2u); + + uint8_t *dstUV = dstY + (size_t)m.RowPitch * (size_t)frame_h; + for (int r = 0; r < frame_h / 2; ++r) + std::memcpy(dstUV + (size_t)r * m.RowPitch, uv + (size_t)r * stride_uv, (size_t)frame_w * 2u); + + ctx_->Unmap(upload_nv12_.Get(), 0); + return true; +} + +bool SharedScenePipeline::upload_yuy2_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h) +{ + if (!d3d_ || !ctx_ || !data || frame_w <= 0 || frame_h <= 0 || src_stride <= 0) + return false; + + const int w2 = (frame_w + 1) / 2; + if (!upload_yuy2_packed_) + { + D3D11_TEXTURE2D_DESC td{}; + td.Width = (UINT)w2; + td.Height = (UINT)frame_h; + td.MipLevels = 1; + td.ArraySize = 1; + td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UINT; + td.Usage = D3D11_USAGE_DYNAMIC; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &upload_yuy2_packed_))) + return false; + } + else + { + D3D11_TEXTURE2D_DESC td{}; + upload_yuy2_packed_->GetDesc(&td); + if ((int)td.Width != w2 || (int)td.Height != frame_h || td.Format != DXGI_FORMAT_R8G8B8A8_UINT) + { + upload_yuy2_packed_.Reset(); + return upload_yuy2_frame(data, src_stride, frame_w, frame_h); + } + } + + D3D11_MAPPED_SUBRESOURCE m{}; + HRESULT hr = ctx_->Map(upload_yuy2_packed_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m); + if (FAILED(hr)) + return false; + + for (int row = 0; row < frame_h; ++row) + { + const uint8_t *srcRow = data + (size_t)row * src_stride; + uint8_t *dstRow = static_cast(m.pData) + (size_t)row * m.RowPitch; + std::memcpy(dstRow, srcRow, (size_t)w2 * 4); + } + + ctx_->Unmap(upload_yuy2_packed_.Get(), 0); + return true; +} + +bool SharedScenePipeline::upload_y210_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h) +{ + if (!ctx_ || !d3d_ || !data || frame_w <= 0 || frame_h <= 0) + return false; + + const int effectiveStride = (src_stride > 0) ? src_stride : (frame_w * 4); + const int minStride = frame_w * 4; + if (effectiveStride < minStride) + return false; + + const int w2 = (frame_w + 1) / 2; + if (upload_y210_packed_) + { + D3D11_TEXTURE2D_DESC desc{}; + upload_y210_packed_->GetDesc(&desc); + if ((int)desc.Width != w2 || (int)desc.Height != frame_h || desc.Format != DXGI_FORMAT_R16G16B16A16_UINT) + upload_y210_packed_.Reset(); + } + + if (!upload_y210_packed_) + { + D3D11_TEXTURE2D_DESC td{}; + td.Width = (UINT)w2; + td.Height = (UINT)frame_h; + td.MipLevels = 1; + td.ArraySize = 1; + td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R16G16B16A16_UINT; + td.Usage = D3D11_USAGE_DYNAMIC; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &upload_y210_packed_))) + return false; + } + + D3D11_MAPPED_SUBRESOURCE m{}; + if (FAILED(ctx_->Map(upload_y210_packed_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m))) + return false; + + const size_t rowBytes = (size_t)frame_w * 4u; + for (int row = 0; row < frame_h; ++row) + { + const uint8_t *srcRow = data + (size_t)row * (size_t)effectiveStride; + uint8_t *dstRow = static_cast(m.pData) + (size_t)row * (size_t)m.RowPitch; + const uint16_t *src16 = reinterpret_cast(srcRow); + uint16_t *dst16 = reinterpret_cast(dstRow); + const int rowWords = (int)(rowBytes / 2u); + + for (int x = 0; x < w2; ++x) + { + const int srcX = x * 4; + const uint16_t Y0 = normalize_y210_word_for_upload(src16[srcX + 0]); + const uint16_t U = normalize_y210_word_for_upload(src16[srcX + 1]); + const uint16_t Y1 = (srcX + 2 < rowWords) ? normalize_y210_word_for_upload(src16[srcX + 2]) : Y0; + const uint16_t V = (srcX + 3 < rowWords) ? normalize_y210_word_for_upload(src16[srcX + 3]) : U; + + uint16_t *d4 = dst16 + x * 4; + d4[0] = Y0; + d4[1] = U; + d4[2] = Y1; + d4[3] = V; + } + } + + ctx_->Unmap(upload_y210_packed_.Get(), 0); + return true; +} + +bool SharedScenePipeline::upload_v210_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h) +{ + if (!ctx_ || !d3d_ || !data || frame_w <= 0 || frame_h <= 0) + return false; + + const int packedStride = ((frame_w + 5) / 6) * 16; + const int effectiveStride = (src_stride > 0) ? src_stride : packedStride; + if (effectiveStride < packedStride) + return false; + + const int w2 = (frame_w + 1) / 2; + if (upload_y210_packed_) + { + D3D11_TEXTURE2D_DESC desc{}; + upload_y210_packed_->GetDesc(&desc); + if ((int)desc.Width != w2 || (int)desc.Height != frame_h || desc.Format != DXGI_FORMAT_R16G16B16A16_UINT) + upload_y210_packed_.Reset(); + } + + if (!upload_y210_packed_) + { + D3D11_TEXTURE2D_DESC td{}; + td.Width = (UINT)w2; + td.Height = (UINT)frame_h; + td.MipLevels = 1; + td.ArraySize = 1; + td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R16G16B16A16_UINT; + td.Usage = D3D11_USAGE_DYNAMIC; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE; + td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(d3d_->CreateTexture2D(&td, nullptr, &upload_y210_packed_))) + return false; + } + + D3D11_MAPPED_SUBRESOURCE m{}; + if (FAILED(ctx_->Map(upload_y210_packed_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m))) + return false; + + for (int row = 0; row < frame_h; ++row) + { + const uint8_t *srcRow = data + (size_t)row * (size_t)effectiveStride; + uint8_t *dstRow = static_cast(m.pData) + (size_t)row * (size_t)m.RowPitch; + uint16_t *dst16 = reinterpret_cast(dstRow); + + for (int x = 0; x < frame_w; x += 6) + { + uint32_t words[4] = {}; + std::memcpy(words, srcRow + (size_t)(x / 6) * 16u, sizeof(words)); + + const uint16_t u0 = v210_component_for_upload(words[0], 0); + const uint16_t y0 = v210_component_for_upload(words[0], 10); + const uint16_t v0 = v210_component_for_upload(words[0], 20); + const uint16_t y1 = v210_component_for_upload(words[1], 0); + const uint16_t u2 = v210_component_for_upload(words[1], 10); + const uint16_t y2 = v210_component_for_upload(words[1], 20); + const uint16_t v2 = v210_component_for_upload(words[2], 0); + const uint16_t y3 = v210_component_for_upload(words[2], 10); + const uint16_t u4 = v210_component_for_upload(words[2], 20); + const uint16_t y4 = v210_component_for_upload(words[3], 0); + const uint16_t v4 = v210_component_for_upload(words[3], 10); + const uint16_t y5 = v210_component_for_upload(words[3], 20); + + uint16_t *d0 = dst16 + (size_t)(x / 2) * 4u; + d0[0] = y0; + d0[1] = u0; + d0[2] = (x + 1 < frame_w) ? y1 : y0; + d0[3] = v0; + + if (x + 2 < frame_w) + { + uint16_t *d1 = dst16 + (size_t)((x + 2) / 2) * 4u; + d1[0] = y2; + d1[1] = u2; + d1[2] = (x + 3 < frame_w) ? y3 : y2; + d1[3] = v2; + } + + if (x + 4 < frame_w) + { + uint16_t *d2 = dst16 + (size_t)((x + 4) / 2) * 4u; + d2[0] = y4; + d2[1] = u4; + d2[2] = (x + 5 < frame_w) ? y5 : y4; + d2[3] = v4; + } + } + } + + ctx_->Unmap(upload_y210_packed_.Get(), 0); + return true; +} + +bool SharedScenePipeline::render_uploaded_yuv_to_fp16(gcap_pixfmt_t fmt, int frame_w, int frame_h) +{ + if (!ctx_ || !vs_ || !il_ || !vb_ || !rtv_fp16_ || !rt_fp16_ || frame_w <= 0 || frame_h <= 0) + return false; + + ID3D11PixelShader *ps = nullptr; + ComPtr srv0, srv1; + if (fmt == GCAP_FMT_NV12) + { + if (!upload_nv12_) + return false; + srv0 = createSRV_NV12(d3d_, upload_nv12_.Get(), false); + srv1 = createSRV_NV12(d3d_, upload_nv12_.Get(), true); + ps = ps_nv12_.Get(); + if (!srv0 || !srv1 || !ps) + return false; + } + else if (fmt == GCAP_FMT_P010) + { + if (!upload_nv12_) + return false; + srv0 = createSRV_P010(d3d_, upload_nv12_.Get(), false); + srv1 = createSRV_P010(d3d_, upload_nv12_.Get(), true); + ps = ps_p010_.Get(); + if (!srv0 || !srv1 || !ps) + return false; + } + else if (fmt == GCAP_FMT_YUY2) + { + if (!upload_yuy2_packed_) + return false; + D3D11_SHADER_RESOURCE_VIEW_DESC sd{}; + sd.Format = DXGI_FORMAT_R8G8B8A8_UINT; + sd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + sd.Texture2D.MipLevels = 1; + if (FAILED(d3d_->CreateShaderResourceView(upload_yuy2_packed_.Get(), &sd, &srv0)) || !srv0) + return false; + ps = ps_yuy2_.Get(); + if (!ps) + return false; + } + else if (fmt == GCAP_FMT_Y210) + { + if (!upload_y210_packed_) + return false; + D3D11_SHADER_RESOURCE_VIEW_DESC sd{}; + sd.Format = DXGI_FORMAT_R16G16B16A16_UINT; + sd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + sd.Texture2D.MipLevels = 1; + if (FAILED(d3d_->CreateShaderResourceView(upload_y210_packed_.Get(), &sd, &srv0)) || !srv0) + return false; + ps = ps_y210_.Get(); + if (!ps) + return false; + } + else + { + return false; + } + + struct CB + { + uint32_t width; + uint32_t height; + float invW; + float invH; + float brightness; + float contrast; + float saturation; + float hueSin; + float hueCos; + float sharpAmount; + float pad0; + float pad1; + } cb{}; + cb.width = (uint32_t)frame_w; + cb.height = (uint32_t)frame_h; + cb.invW = frame_w > 0 ? 1.0f / (float)frame_w : 0.0f; + cb.invH = frame_h > 0 ? 1.0f / (float)frame_h : 0.0f; + cb.brightness = 0.0f; + cb.contrast = 1.0f; + cb.saturation = 1.0f; + cb.hueSin = 0.0f; + cb.hueCos = 1.0f; + cb.sharpAmount = 0.0f; + + if (cs_params_) + { + D3D11_MAPPED_SUBRESOURCE mapped{}; + if (SUCCEEDED(ctx_->Map(cs_params_.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) + { + std::memcpy(mapped.pData, &cb, sizeof(cb)); + ctx_->Unmap(cs_params_.Get(), 0); + ID3D11Buffer *cb0[1] = {cs_params_.Get()}; + ctx_->PSSetConstantBuffers(0, 1, cb0); + } + } + + UINT stride = sizeof(float) * 4, offset = 0; + ID3D11Buffer *pVB = vb_.Get(); + ctx_->IASetVertexBuffers(0, 1, &pVB, &stride, &offset); + ctx_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx_->IASetInputLayout(il_.Get()); + ctx_->VSSetShader(vs_.Get(), nullptr, 0); + ctx_->PSSetShader(ps, nullptr, 0); + + D3D11_VIEWPORT vp{}; + vp.TopLeftX = 0.0f; + vp.TopLeftY = 0.0f; + vp.Width = static_cast(frame_w); + vp.Height = static_cast(frame_h); + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + ctx_->RSSetViewports(1, &vp); + + ID3D11RenderTargetView *rtv = rtv_fp16_.Get(); + ctx_->OMSetRenderTargets(1, &rtv, nullptr); + const float clear[4] = {0, 0, 0, 1}; + ctx_->ClearRenderTargetView(rtv_fp16_.Get(), clear); + + if (fmt == GCAP_FMT_NV12 || fmt == GCAP_FMT_P010) + { + ID3D11ShaderResourceView *srvs[2] = {srv0.Get(), srv1.Get()}; + ctx_->PSSetShaderResources(0, 2, srvs); + } + else + { + ID3D11ShaderResourceView *srvs[1] = {srv0.Get()}; + ctx_->PSSetShaderResources(0, 1, srvs); + ID3D11ShaderResourceView *null1[1] = {nullptr}; + ctx_->PSSetShaderResources(1, 1, null1); + } + + ID3D11SamplerState *ss = samp_.Get(); + ctx_->PSSetSamplers(0, 1, &ss); + ctx_->Draw(6, 0); + + if (fmt == GCAP_FMT_NV12 || fmt == GCAP_FMT_P010) + { + ID3D11ShaderResourceView *nulls[2] = {nullptr, nullptr}; + ctx_->PSSetShaderResources(0, 2, nulls); + } + else + { + ID3D11ShaderResourceView *nulls[1] = {nullptr}; + ctx_->PSSetShaderResources(0, 1, nulls); + } + + return true; +} + +namespace +{ + + static inline uint16_t ssp_float_to_10bit(float v) + { + if (v < 0.0f) + v = 0.0f; + if (v > 1.0f) + v = 1.0f; + return static_cast(std::lround(v * 1023.0f)); + } + + static inline uint16_t ssp_expand_10_to_16(uint16_t v10) + { + v10 = static_cast(std::min(v10, 1023u)); + return static_cast((v10 << 6) | (v10 >> 4)); + } + + static inline uint8_t ssp_float_to_8bit(float v) + { + if (v < 0.0f) + v = 0.0f; + if (v > 1.0f) + v = 1.0f; + return static_cast(std::lround(v * 255.0f)); + } + + static bool ssp_write_gigabyte_raw_file(const std::wstring &path, + int w, + int h, + const char *format, + int sourceBitDepth, + const void *payload, + size_t payloadBytes) + { + if (path.empty() || !format || !*format || !payload || payloadBytes == 0) + return false; + + char header[GCAP_GIGABYTE_RAW_HEADER_SIZE] = {}; + std::snprintf(header, sizeof(header), + "GIGABYTE_RAW\n" + "header_size=%d\n" + "Width=%d\n" + "Height=%d\n" + "Format=%s\n" + "SourceBitDepth=%d\n", + GCAP_GIGABYTE_RAW_HEADER_SIZE, + w, + h, + format, + sourceBitDepth); + + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(header, static_cast(sizeof(header))); + ofs.write(reinterpret_cast(payload), static_cast(payloadBytes)); + return ofs.good(); + } + + static bool ssp_write_fp16_gigabyte_raw(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &rgba16f) + { + if (w <= 0 || h <= 0 || rgba16f.size() < static_cast(w) * static_cast(h) * 4u) + return false; + const size_t payloadBytes = rgba16f.size() * sizeof(uint16_t); + return ssp_write_gigabyte_raw_file(path, w, h, "RGBA16F", sourceBitDepth, rgba16f.data(), payloadBytes); + } + + static bool ssp_write_rgb10_gigabyte_raw(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &rgb10) + { + if (w <= 0 || h <= 0 || rgb10.size() < static_cast(w) * static_cast(h) * 3u) + return false; + const size_t payloadBytes = rgb10.size() * sizeof(uint16_t); + return ssp_write_gigabyte_raw_file(path, w, h, "RGB10_U16", sourceBitDepth, rgb10.data(), payloadBytes); + } + + static bool ssp_write_bgra8_gigabyte_raw(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &bgra8) + { + if (w <= 0 || h <= 0 || bgra8.size() < static_cast(w) * static_cast(h) * 4u) + return false; + return ssp_write_gigabyte_raw_file(path, w, h, "BGRA8", sourceBitDepth, bgra8.data(), bgra8.size()); + } + + static bool ssp_write_abgr2101010_gigabyte_raw(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &abgr2101010) + { + if (w <= 0 || h <= 0 || abgr2101010.size() < static_cast(w) * static_cast(h)) + return false; + const size_t payloadBytes = abgr2101010.size() * sizeof(uint32_t); + return ssp_write_gigabyte_raw_file(path, w, h, "ABGR2101010", sourceBitDepth, abgr2101010.data(), payloadBytes); + } + + static bool ssp_write_rgba16_expanded_gigabyte_raw(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &rgb10) + { + if (w <= 0 || h <= 0 || rgb10.size() < static_cast(w) * static_cast(h) * 3u) + return false; + + std::vector rgba; + const size_t pixelCount = static_cast(w) * static_cast(h); + rgba.resize(pixelCount * 4u); + for (size_t i = 0; i < pixelCount; ++i) + { + rgba[i * 4u + 0u] = ssp_expand_10_to_16(rgb10[i * 3u + 0u]); + rgba[i * 4u + 1u] = ssp_expand_10_to_16(rgb10[i * 3u + 1u]); + rgba[i * 4u + 2u] = ssp_expand_10_to_16(rgb10[i * 3u + 2u]); + rgba[i * 4u + 3u] = 0xFFFFu; + } + + const size_t payloadBytes = rgba.size() * sizeof(uint16_t); + return ssp_write_gigabyte_raw_file(path, w, h, "RGBA16", sourceBitDepth, rgba.data(), payloadBytes); + } + + static bool ssp_write_fp16_raw(const std::wstring &path, int w, int h, const std::vector &rgba16f) + { + if (w <= 0 || h <= 0 || rgba16f.size() < static_cast(w) * static_cast(h) * 4u) + return false; + + // No header. Payload: R16F G16F B16F A16F, little-endian. + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(rgba16f.data()), static_cast(rgba16f.size() * sizeof(uint16_t))); + return ofs.good(); + } + + static bool ssp_write_rgb10_raw_value(const std::wstring &path, int w, int h, const std::vector &rgb10) + { + if (w <= 0 || h <= 0 || rgb10.size() < static_cast(w) * static_cast(h) * 3u) + return false; + + // No header. Payload: R16 G16 B16, little-endian, valid value 0..1023. + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(rgb10.data()), static_cast(rgb10.size() * sizeof(uint16_t))); + return ofs.good(); + } + + static bool ssp_write_bgra8_raw_value(const std::wstring &path, int w, int h, const std::vector &bgra8) + { + if (w <= 0 || h <= 0 || bgra8.size() < static_cast(w) * static_cast(h) * 4u) + return false; + + // No header. Payload: B8 G8 R8 A8, 4 bytes per pixel. + // This matches DXGI_FORMAT_B8G8R8A8_UNORM preview backbuffer layout. + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(bgra8.data()), static_cast(bgra8.size())); + return ofs.good(); + } + + static bool ssp_write_rgba8_raw_value(const std::wstring &path, int w, int h, const std::vector &bgra8) + { + if (w <= 0 || h <= 0 || bgra8.size() < static_cast(w) * static_cast(h) * 4u) + return false; + + std::vector rgba8; + const size_t pixelCount = static_cast(w) * static_cast(h); + rgba8.resize(pixelCount * 4u); + for (size_t i = 0; i < pixelCount; ++i) + { + rgba8[i * 4u + 0u] = bgra8[i * 4u + 2u]; + rgba8[i * 4u + 1u] = bgra8[i * 4u + 1u]; + rgba8[i * 4u + 2u] = bgra8[i * 4u + 0u]; + rgba8[i * 4u + 3u] = bgra8[i * 4u + 3u]; + } + + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(rgba8.data()), static_cast(rgba8.size())); + return ofs.good(); + } + + static bool ssp_write_abgr2101010_raw_value(const std::wstring &path, int w, int h, const std::vector &abgr2101010) + { + if (w <= 0 || h <= 0 || abgr2101010.size() < static_cast(w) * static_cast(h)) + return false; + + // No header. Payload: 4 bytes per pixel, little-endian packed 10-bit RGB. + // This matches the preview backbuffer DXGI_FORMAT_R10G10B10A2_UNORM bit layout: + // bits 0.. 9 = R, bits 10..19 = G, bits 20..29 = B, bits 30..31 = A. + // PixelViewer names the same low-to-high layout as ABGR_2101010 because + // reading the 32-bit word from high bits to low bits is A2 B10 G10 R10. + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(abgr2101010.data()), static_cast(abgr2101010.size() * sizeof(uint32_t))); + return ofs.good(); + } + + static bool ssp_write_rgba16_expanded_raw(const std::wstring &path, int w, int h, const std::vector &rgb10) + { + if (w <= 0 || h <= 0 || rgb10.size() < static_cast(w) * static_cast(h) * 3u) + return false; + + // No header. Payload: R16 G16 B16 A16, little-endian. + // RGB is expanded from 10-bit 0..1023 to 16-bit 0..65535 for RAW viewers. + std::vector rgba; + const size_t pixelCount = static_cast(w) * static_cast(h); + rgba.resize(pixelCount * 4u); + for (size_t i = 0; i < pixelCount; ++i) + { + rgba[i * 4u + 0u] = ssp_expand_10_to_16(rgb10[i * 3u + 0u]); + rgba[i * 4u + 1u] = ssp_expand_10_to_16(rgb10[i * 3u + 1u]); + rgba[i * 4u + 2u] = ssp_expand_10_to_16(rgb10[i * 3u + 2u]); + rgba[i * 4u + 3u] = 0xFFFFu; + } + + std::ofstream ofs(std::filesystem::path(path), std::ios::binary); + if (!ofs) + return false; + ofs.write(reinterpret_cast(rgba.data()), static_cast(rgba.size() * sizeof(uint16_t))); + return ofs.good(); + } + + static bool ssp_write_rgb10_stats(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &rgb10) + { + if (rgb10.empty()) + return false; + uint16_t minV[3] = {1023, 1023, 1023}; + uint16_t maxV[3] = {0, 0, 0}; + bool anyGt255 = false; + bool bins[3][1024] = {}; + for (size_t i = 0; i + 2 < rgb10.size(); i += 3) + { + for (int c = 0; c < 3; ++c) + { + uint16_t v = rgb10[i + c]; + minV[c] = (std::min)(minV[c], v); + maxV[c] = (std::max)(maxV[c], v); + if (v > 255) + anyGt255 = true; + bins[c][v] = true; + } + } + int unique[3] = {0, 0, 0}; + for (int c = 0; c < 3; ++c) + for (bool hit : bins[c]) + if (hit) + ++unique[c]; + std::ofstream ofs{std::filesystem::path(path)}; + if (!ofs) + return false; + ofs << "Width=" << w << "\n"; + ofs << "Height=" << h << "\n"; + ofs << "SourceBitDepth=" << sourceBitDepth << "\n"; + ofs << "Files=_abgr2101010.raw, _gigabyte_abgr2101010.raw, _rgb10.raw, .tiff, .png, .stats.txt\n"; + ofs << "NativeRAW=_abgr2101010.raw, DXGI R10G10B10A2 layout, little-endian uint32 per pixel\n"; + ofs << "GigabyteRAW=_gigabyte_abgr2101010.raw, 128-byte ASCII GIGABYTE_RAW header + same native payload\n"; + ofs << "HexRGB10=_rgb10.raw, little-endian uint16 R G B values per pixel, valid range 0..1023, no header\n"; + ofs << "R min=" << minV[0] << " max=" << maxV[0] << " unique=" << unique[0] << "\n"; + ofs << "G min=" << minV[1] << " max=" << maxV[1] << " unique=" << unique[1] << "\n"; + ofs << "B min=" << minV[2] << " max=" << maxV[2] << " unique=" << unique[2] << "\n"; + ofs << "Any value > 255=" << (anyGt255 ? "YES" : "NO") << "\n"; + ofs << "MatchesPreviewSwapchain=DXGI_FORMAT_R10G10B10A2_UNORM via _abgr2101010.raw\n"; + ofs << "ABGR2101010 raw is for PixelViewer: choose ABGR_2101010 + Little-Endian\n"; + ofs << "DXGI bit layout=bits 0-9 R, 10-19 G, 20-29 B, 30-31 A; alpha fixed to 3\n"; + return ofs.good(); + } + + static bool ssp_write_bgra8_stats(const std::wstring &path, int w, int h, int sourceBitDepth, const std::vector &bgra8) + { + if (bgra8.empty()) + return false; + uint8_t minV[3] = {255, 255, 255}; + uint8_t maxV[3] = {0, 0, 0}; + bool bins[3][256] = {}; + for (size_t i = 0; i + 3 < bgra8.size(); i += 4) + { + const uint8_t r = bgra8[i + 2u]; + const uint8_t g = bgra8[i + 1u]; + const uint8_t b = bgra8[i + 0u]; + const uint8_t v[3] = {r, g, b}; + for (int c = 0; c < 3; ++c) + { + minV[c] = (std::min)(minV[c], v[c]); + maxV[c] = (std::max)(maxV[c], v[c]); + bins[c][v[c]] = true; + } + } + int unique[3] = {0, 0, 0}; + for (int c = 0; c < 3; ++c) + for (bool hit : bins[c]) + if (hit) + ++unique[c]; + std::ofstream ofs{std::filesystem::path(path)}; + if (!ofs) + return false; + ofs << "Width=" << w << "\n"; + ofs << "Height=" << h << "\n"; + ofs << "SourceBitDepth=" << sourceBitDepth << "\n"; + ofs << "Files=_bgra8.raw, _gigabyte_bgra8.raw, _rgba8.raw, .tiff, .png, .stats.txt\n"; + ofs << "NativeRAW=_bgra8.raw, B8 G8 R8 A8 byte order, 4 bytes per pixel, no header\n"; + ofs << "GigabyteRAW=_gigabyte_bgra8.raw, 128-byte ASCII GIGABYTE_RAW header + same native payload\n"; + ofs << "HexRGBA=_rgba8.raw, R8 G8 B8 A8 byte order, 4 bytes per pixel, no header\n"; + ofs << "MatchesPreviewSwapchain=DXGI_FORMAT_B8G8R8A8_UNORM\n"; + ofs << "R min=" << static_cast(minV[0]) << " max=" << static_cast(maxV[0]) << " unique=" << unique[0] << "\n"; + ofs << "G min=" << static_cast(minV[1]) << " max=" << static_cast(maxV[1]) << " unique=" << unique[1] << "\n"; + ofs << "B min=" << static_cast(minV[2]) << " max=" << static_cast(maxV[2]) << " unique=" << unique[2] << "\n"; + ofs << "Any value > 255=NO\n"; + return ofs.good(); + } + + static bool ssp_write_rgb16_tiff(const std::wstring &path, int w, int h, const std::vector &rgb10) + { + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + const bool needUninit = SUCCEEDED(hr); + IWICImagingFactory *factory = nullptr; + IWICBitmapEncoder *encoder = nullptr; + IWICStream *stream = nullptr; + IWICBitmapFrameEncode *frame = nullptr; + IPropertyBag2 *bag = nullptr; + bool ok = false; + do + { + hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory)); + if (FAILED(hr) || !factory) + break; + hr = factory->CreateStream(&stream); + if (FAILED(hr) || !stream) + break; + hr = stream->InitializeFromFilename(path.c_str(), GENERIC_WRITE); + if (FAILED(hr)) + break; + hr = factory->CreateEncoder(GUID_ContainerFormatTiff, nullptr, &encoder); + if (FAILED(hr) || !encoder) + break; + hr = encoder->Initialize(stream, WICBitmapEncoderNoCache); + if (FAILED(hr)) + break; + hr = encoder->CreateNewFrame(&frame, &bag); + if (FAILED(hr) || !frame) + break; + hr = frame->Initialize(bag); + if (FAILED(hr)) + break; + hr = frame->SetSize(static_cast(w), static_cast(h)); + if (FAILED(hr)) + break; + WICPixelFormatGUID pf = GUID_WICPixelFormat48bppRGB; + hr = frame->SetPixelFormat(&pf); + if (FAILED(hr) || !IsEqualGUID(pf, GUID_WICPixelFormat48bppRGB)) + break; + std::vector rgb16(rgb10.size()); + for (size_t i = 0; i < rgb10.size(); ++i) + rgb16[i] = static_cast((static_cast(rgb10[i]) * 65535u + 511u) / 1023u); + const UINT stride = static_cast(w * 3 * sizeof(uint16_t)); + const UINT imageSize = static_cast(rgb16.size() * sizeof(uint16_t)); + hr = frame->WritePixels(static_cast(h), stride, imageSize, reinterpret_cast(rgb16.data())); + if (FAILED(hr)) + break; + hr = frame->Commit(); + if (FAILED(hr)) + break; + hr = encoder->Commit(); + if (FAILED(hr)) + break; + ok = true; + } while (false); + if (bag) + bag->Release(); + if (frame) + frame->Release(); + if (encoder) + encoder->Release(); + if (stream) + stream->Release(); + if (factory) + factory->Release(); + if (needUninit) + CoUninitialize(); + return ok; + } +} + +bool SharedScenePipeline::copy_fp16_to_scene() +{ + if (!ctx_ || !rt_fp16_ || !rt_scene_fp16_) + return false; + ctx_->CopyResource(rt_scene_fp16_.Get(), rt_fp16_.Get()); + return true; +} + +bool SharedScenePipeline::readback_to_frame(int frame_w, int frame_h, uint64_t pts_ns, uint64_t frame_id, + gcap_frame_t *out) +{ + if (!out || !ctx_ || !rt_stage_ || !rt_rgba_) + return false; + + ctx_->CopyResource(rt_stage_.Get(), rt_rgba_.Get()); + D3D11_MAPPED_SUBRESOURCE m{}; + if (FAILED(ctx_->Map(rt_stage_.Get(), 0, D3D11_MAP_READ, 0, &m))) + return false; + + std::memset(out, 0, sizeof(*out)); + out->data[0] = m.pData; + out->stride[0] = (int)m.RowPitch; + out->plane_count = 1; + out->width = frame_w; + out->height = frame_h; + out->format = GCAP_FMT_ARGB; + out->pts_ns = pts_ns; + out->frame_id = frame_id; + return true; +} + +bool SharedScenePipeline::export_scene_rgb10(const wchar_t *base_path, int raw_flags, bool export_tiff, bool export_stats, bool export_gigabyte_raw) +{ + if (!base_path || !*base_path || !ctx_ || !rt_scene_stage_fp16_ || !rt_scene_fp16_ || rt_w_ <= 0 || rt_h_ <= 0) + return false; + + ctx_->CopyResource(rt_scene_stage_fp16_.Get(), rt_scene_fp16_.Get()); + D3D11_MAPPED_SUBRESOURCE m{}; + if (FAILED(ctx_->Map(rt_scene_stage_fp16_.Get(), 0, D3D11_MAP_READ, 0, &m))) + return false; + + const size_t pixelCount = static_cast(rt_w_) * static_cast(rt_h_); + std::vector rgba16f; + std::vector rgb10; + std::vector bgra8; + std::vector abgr2101010; + const bool sourceIs10Bit = (preview_source_bit_depth_ >= 10); + rgba16f.resize(pixelCount * 4u); + rgb10.resize(pixelCount * 3u); + bgra8.resize(pixelCount * 4u); + abgr2101010.resize(pixelCount); + for (int y = 0; y < rt_h_; ++y) + { + const uint8_t *srcRow = static_cast(m.pData) + static_cast(y) * static_cast(m.RowPitch); + const uint16_t *src = reinterpret_cast(srcRow); + for (int x = 0; x < rt_w_; ++x) + { + const size_t pixelIndex = static_cast(y) * static_cast(rt_w_) + static_cast(x); + const size_t si = static_cast(x) * 4u; + const size_t fpi = pixelIndex * 4u; + const size_t di = pixelIndex * 3u; + const size_t bi = pixelIndex * 4u; + + rgba16f[fpi + 0u] = src[si + 0u]; + rgba16f[fpi + 1u] = src[si + 1u]; + rgba16f[fpi + 2u] = src[si + 2u]; + rgba16f[fpi + 3u] = src[si + 3u]; + + const float r = DirectX::PackedVector::XMConvertHalfToFloat(src[si + 0u]); + const float g = DirectX::PackedVector::XMConvertHalfToFloat(src[si + 1u]); + const float b = DirectX::PackedVector::XMConvertHalfToFloat(src[si + 2u]); + const uint16_t r10 = ssp_float_to_10bit(r); + const uint16_t g10 = ssp_float_to_10bit(g); + const uint16_t b10 = ssp_float_to_10bit(b); + rgb10[di + 0u] = r10; + rgb10[di + 1u] = g10; + rgb10[di + 2u] = b10; + + bgra8[bi + 0u] = ssp_float_to_8bit(b); + bgra8[bi + 1u] = ssp_float_to_8bit(g); + bgra8[bi + 2u] = ssp_float_to_8bit(r); + bgra8[bi + 3u] = 255u; + + abgr2101010[pixelIndex] = + ((static_cast(r10) & 0x3FFu) << 0u) | + ((static_cast(g10) & 0x3FFu) << 10u) | + ((static_cast(b10) & 0x3FFu) << 20u) | + (3u << 30u); + } + } + ctx_->Unmap(rt_scene_stage_fp16_.Get(), 0); + + const bool exportNativeRaw = (raw_flags & GCAP_EXPORT_RAW_NATIVE) != 0; + const bool exportRgb10Raw = (raw_flags & GCAP_EXPORT_RAW_RGB10_U16) != 0; + const bool exportRgba16Raw = (raw_flags & GCAP_EXPORT_RAW_RGBA16) != 0; + const bool exportRgba8Raw = (raw_flags & GCAP_EXPORT_RAW_RGBA8) != 0; + const bool exportFp16Raw = sourceIs10Bit && (raw_flags & GCAP_EXPORT_RAW_ALL) == GCAP_EXPORT_RAW_ALL; + const std::wstring base(base_path); + bool ok = true; + if (raw_flags != 0) + { + if (sourceIs10Bit) + { + if (exportFp16Raw) + ok = ssp_write_fp16_raw(base + L"_fp16_rgba16f.raw", rt_w_, rt_h_, rgba16f) && ok; + if (exportRgb10Raw) + ok = ssp_write_rgb10_raw_value(base + L"_rgb10.raw", rt_w_, rt_h_, rgb10) && ok; + if (exportNativeRaw) + ok = ssp_write_abgr2101010_raw_value(base + L"_abgr2101010.raw", rt_w_, rt_h_, abgr2101010) && ok; + if (exportRgba16Raw) + ok = ssp_write_rgba16_expanded_raw(base + L"_rgba16_expanded.raw", rt_w_, rt_h_, rgb10) && ok; + } + else + { + if (exportNativeRaw) + ok = ssp_write_bgra8_raw_value(base + L"_bgra8.raw", rt_w_, rt_h_, bgra8) && ok; + if (exportRgba8Raw) + ok = ssp_write_rgba8_raw_value(base + L"_rgba8.raw", rt_w_, rt_h_, bgra8) && ok; + } + } + if (export_gigabyte_raw) + { + const int sourceBitDepth = preview_source_bit_depth_ > 0 ? preview_source_bit_depth_ : (sourceIs10Bit ? 10 : 8); + if (sourceIs10Bit) + { + ok = ssp_write_abgr2101010_gigabyte_raw(base + L"_gigabyte_abgr2101010.raw", rt_w_, rt_h_, sourceBitDepth, abgr2101010) && ok; + } + else + { + ok = ssp_write_bgra8_gigabyte_raw(base + L"_gigabyte_bgra8.raw", rt_w_, rt_h_, sourceBitDepth, bgra8) && ok; + } + } + if (export_tiff) + ok = ssp_write_rgb16_tiff(base + L".tiff", rt_w_, rt_h_, rgb10) && ok; + if (export_stats) + { + const int sourceBitDepth = preview_source_bit_depth_ > 0 ? preview_source_bit_depth_ : (sourceIs10Bit ? 10 : 8); + ok = sourceIs10Bit + ? (ssp_write_rgb10_stats(base + L".stats.txt", rt_w_, rt_h_, sourceBitDepth, rgb10) && ok) + : (ssp_write_bgra8_stats(base + L".stats.txt", rt_w_, rt_h_, sourceBitDepth, bgra8) && ok); + } + + char msg[512] = {}; + std::snprintf(msg, sizeof(msg), + "[SharedScene] export_scene_rgb10 base=%ls size=%dx%d sourceBitDepth=%d exportAs=%s rawFlags=0x%x gigabyteRaw=%d tiff=%d stats=%d ok=%d", + base_path, rt_w_, rt_h_, preview_source_bit_depth_, sourceIs10Bit ? "abgr2101010" : "bgra8", raw_flags, export_gigabyte_raw ? 1 : 0, export_tiff ? 1 : 0, export_stats ? 1 : 0, ok ? 1 : 0); + ssp_log_text(msg); + return ok; +} + +void SharedScenePipeline::release_preview_swapchain() +{ + preview_rtv_.Reset(); + preview_backbuf_.Reset(); + preview_swapchain_.Reset(); + preview_w_ = 0; + preview_h_ = 0; + preview_swapchain_10bit_ = false; + preview_swapchain_format_ = DXGI_FORMAT_UNKNOWN; +} + +bool SharedScenePipeline::ensure_preview_swapchain(int w, int h) +{ + if (!preview_enabled_ || !preview_hwnd_ || !d3d_) + return false; + + if (w <= 0 || h <= 0) + return false; + + RECT rc{}; + if (!GetClientRect((HWND)preview_hwnd_, &rc)) + return false; + + int clientW = rc.right - rc.left; + int clientH = rc.bottom - rc.top; + + if (clientW <= 0 || clientH <= 0) + { + clientW = w; + clientH = h; + } + + ComPtr dxgiDev; + if (!d3d_ || FAILED(d3d_->QueryInterface(IID_PPV_ARGS(&dxgiDev))) || !dxgiDev) + return false; + + ComPtr adapter; + if (FAILED(dxgiDev->GetAdapter(&adapter)) || !adapter) + return false; + + ComPtr factory; + if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory2), + reinterpret_cast(factory.GetAddressOf()))) || + !factory) + return false; + + const int effectiveMode = (preview_swapchain_mode_ == GCAP_PREVIEW_BITDEPTH_AUTO) + ? ((preview_source_bit_depth_ >= 10) ? GCAP_PREVIEW_BITDEPTH_10BIT : GCAP_PREVIEW_BITDEPTH_8BIT) + : preview_swapchain_mode_; + const DXGI_FORMAT desiredFormat = (effectiveMode == GCAP_PREVIEW_BITDEPTH_8BIT) + ? DXGI_FORMAT_B8G8R8A8_UNORM + : DXGI_FORMAT_R10G10B10A2_UNORM; + + if (preview_swapchain_ && preview_swapchain_format_ != DXGI_FORMAT_UNKNOWN && preview_swapchain_format_ != desiredFormat) + { + char msg[320] = {}; + std::snprintf(msg, sizeof(msg), + "[SharedScene] preview swapchain format change: mode=%d sourceBitDepth=%d old=%s desired=%s", + preview_swapchain_mode_, preview_source_bit_depth_, ss_dxgi_format_name(preview_swapchain_format_), ss_dxgi_format_name(desiredFormat)); + ssp_log_text(msg); + release_preview_swapchain(); + } + + if (!preview_swapchain_) + { + DXGI_SWAP_CHAIN_DESC1 sd{}; + sd.Width = (UINT)clientW; + sd.Height = (UINT)clientH; + sd.Format = desiredFormat; + sd.SampleDesc.Count = 1; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.BufferCount = 2; + sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; + sd.Scaling = DXGI_SCALING_STRETCH; + sd.AlphaMode = DXGI_ALPHA_MODE_IGNORE; + + HRESULT hr = factory->CreateSwapChainForHwnd( + d3d_, + (HWND)preview_hwnd_, + &sd, + nullptr, + nullptr, + &preview_swapchain_); + + if ((FAILED(hr) || !preview_swapchain_) && sd.Format == DXGI_FORMAT_R10G10B10A2_UNORM) + { + char warn[320] = {}; + std::snprintf(warn, sizeof(warn), + "[SharedScene] 10-bit preview swapchain failed hr=0x%08X, fallback to 8-bit BGRA", + static_cast(hr)); + ssp_log_text(warn); + + preview_swapchain_.Reset(); + sd.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + hr = factory->CreateSwapChainForHwnd( + d3d_, + (HWND)preview_hwnd_, + &sd, + nullptr, + nullptr, + &preview_swapchain_); + } + + if (FAILED(hr) || !preview_swapchain_) + return false; + + preview_swapchain_format_ = sd.Format; + preview_swapchain_10bit_ = (sd.Format == DXGI_FORMAT_R10G10B10A2_UNORM); + + { + char msg[320] = {}; + std::snprintf(msg, sizeof(msg), + "[SharedScene] preview swapchain created: %dx%d requestedMode=%d sourceBitDepth=%d effectiveMode=%d actualFormat=%s actual10bit=%d", + clientW, clientH, preview_swapchain_mode_, preview_source_bit_depth_, effectiveMode, ss_dxgi_format_name(sd.Format), preview_swapchain_10bit_ ? 1 : 0); + ssp_log_text(msg); + } + + factory->MakeWindowAssociation((HWND)preview_hwnd_, DXGI_MWA_NO_ALT_ENTER); + } + else if (preview_w_ != clientW || preview_h_ != clientH) + { + preview_rtv_.Reset(); + preview_backbuf_.Reset(); + + HRESULT hr = preview_swapchain_->ResizeBuffers( + 0, + (UINT)clientW, + (UINT)clientH, + DXGI_FORMAT_UNKNOWN, + 0); + + if (FAILED(hr)) + return false; + + { + char msg[256] = {}; + std::snprintf(msg, sizeof(msg), + "[SharedScene] preview swapchain resized: %dx%d", + clientW, clientH); + ssp_log_text(msg); + } + } + + if (!preview_backbuf_) + { + if (FAILED(preview_swapchain_->GetBuffer(0, IID_PPV_ARGS(&preview_backbuf_))) || !preview_backbuf_) + return false; + } + + if (!preview_rtv_) + { + if (FAILED(d3d_->CreateRenderTargetView(preview_backbuf_.Get(), nullptr, &preview_rtv_)) || !preview_rtv_) + return false; + } + + preview_w_ = clientW; + preview_h_ = clientH; + return true; +} + +bool SharedScenePipeline::present_preview(int src_w, int src_h) +{ + static bool s_loggedPresentPath = false; + if (!preview_enabled_ || !preview_swapchain_ || !preview_backbuf_ || !ctx_) + return false; + + ID3D11RenderTargetView *nullRTV = nullptr; + ctx_->OMSetRenderTargets(1, &nullRTV, nullptr); + + if (!preview_rtv_ || !vs_) + return false; + + const float srcW = static_cast(src_w); + const float srcH = static_cast(src_h); + const float dstW = static_cast(preview_w_); + const float dstH = static_cast(preview_h_); + + if (srcW <= 0.0f || srcH <= 0.0f || dstW <= 0.0f || dstH <= 0.0f) + return false; + + float drawW = dstW; + float drawH = dstH; + float offsetX = 0.0f; + float offsetY = 0.0f; + + const float srcAspect = srcW / srcH; + const float dstAspect = dstW / dstH; + + if (srcAspect > dstAspect) + { + drawW = dstW; + drawH = dstW / srcAspect; + offsetX = 0.0f; + offsetY = (dstH - drawH) * 0.5f; + } + else + { + drawH = dstH; + drawW = dstH * srcAspect; + offsetX = (dstW - drawW) * 0.5f; + offsetY = 0.0f; + } + + UINT stride = sizeof(float) * 4; + UINT offset = 0; + ID3D11Buffer *pVB = vb_.Get(); + ctx_->IASetVertexBuffers(0, 1, &pVB, &stride, &offset); + ctx_->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx_->IASetInputLayout(il_.Get()); + + ID3D11RenderTargetView *rtv = preview_rtv_.Get(); + ctx_->OMSetRenderTargets(1, &rtv, nullptr); + + const float clear[4] = {0, 0, 0, 1}; + ctx_->ClearRenderTargetView(preview_rtv_.Get(), clear); + + D3D11_VIEWPORT vp{}; + vp.TopLeftX = offsetX; + vp.TopLeftY = offsetY; + vp.Width = drawW; + vp.Height = drawH; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + ctx_->RSSetViewports(1, &vp); + + ctx_->VSSetShader(vs_.Get(), nullptr, 0); + + ID3D11ShaderResourceView *srv = nullptr; + if (preview_swapchain_10bit_) + { + if (!srv_scene_fp16_ || !ps_fp16_to_preview_) + return false; + + ctx_->PSSetShader(ps_fp16_to_preview_.Get(), nullptr, 0); + srv = srv_scene_fp16_.Get(); + } + else + { + if (!srv_rgba_ || !ps_rgba8_to_preview_) + return false; + + ctx_->PSSetShader(ps_rgba8_to_preview_.Get(), nullptr, 0); + srv = srv_rgba_.Get(); + } + + if (!s_loggedPresentPath) + { + char msg[320] = {}; + std::snprintf(msg, sizeof(msg), + "[SharedScene] preview render path: scene=%s linear=%s backbuffer=%s present_shader=%s", + ss_dxgi_format_name(scene_texture_format()), + ss_dxgi_format_name(linear_fp16_texture_format()), + ss_dxgi_format_name(preview_backbuffer_format()), + preview_swapchain_10bit_ ? "FP16->R10G10B10A2" : "RGBA8->BGRA8"); + ssp_log_text(msg); + s_loggedPresentPath = true; + } + + ID3D11ShaderResourceView *srvs[1] = {srv}; + ctx_->PSSetShaderResources(0, 1, srvs); + + ID3D11SamplerState *ss = samp_.Get(); + ctx_->PSSetSamplers(0, 1, &ss); + + ctx_->Draw(6, 0); + + ID3D11ShaderResourceView *nullSrv[1] = {nullptr}; + ctx_->PSSetShaderResources(0, 1, nullSrv); + + HRESULT hr = preview_swapchain_->Present(1, 0); + return SUCCEEDED(hr); +} + +DXGI_FORMAT SharedScenePipeline::preview_backbuffer_format() const +{ + if (preview_swapchain_format_ != DXGI_FORMAT_UNKNOWN) + return preview_swapchain_format_; + if (!preview_backbuf_) + return DXGI_FORMAT_UNKNOWN; + D3D11_TEXTURE2D_DESC d{}; + preview_backbuf_->GetDesc(&d); + return d.Format; +} + +DXGI_FORMAT SharedScenePipeline::scene_texture_format() const +{ + if (!rt_scene_fp16_) + return DXGI_FORMAT_UNKNOWN; + D3D11_TEXTURE2D_DESC d{}; + rt_scene_fp16_->GetDesc(&d); + return d.Format; +} + +DXGI_FORMAT SharedScenePipeline::linear_fp16_texture_format() const +{ + if (!rt_fp16_) + return DXGI_FORMAT_UNKNOWN; + D3D11_TEXTURE2D_DESC d{}; + rt_fp16_->GetDesc(&d); + return d.Format; +} diff --git a/sdk/gcapture/src/pipeline/shared_scene_pipeline.h b/sdk/gcapture/src/pipeline/shared_scene_pipeline.h new file mode 100644 index 0000000..9dc84c7 --- /dev/null +++ b/sdk/gcapture/src/pipeline/shared_scene_pipeline.h @@ -0,0 +1,129 @@ +#pragma once + +#include "gcapture.h" + +#include +#include +#include +#include +#include + +class SharedScenePipeline +{ +public: + SharedScenePipeline() = default; + ~SharedScenePipeline() = default; + + bool initialize(ID3D11Device *d3d, + ID3D11DeviceContext *ctx, + ID2D1DeviceContext *d2d_ctx, + IDWriteFactory *dwrite = nullptr, + ID2D1SolidColorBrush *white = nullptr, + ID2D1SolidColorBrush *black = nullptr); + void shutdown(); + + bool configurePreview(const gcap_preview_desc_t &desc); + void set_source_bit_depth(int bits); + int source_bit_depth() const { return preview_source_bit_depth_; } + void release_preview_swapchain(); + + bool create_shaders_and_states(); + bool ensure_rt_and_pipeline(int w, int h); + uint64_t last_ensure_rt_ns() const { return lastEnsureRtNs_; } + uint64_t total_ensure_rt_ns() const { return totalEnsureRtNs_; } + uint64_t ensure_rt_calls() const { return ensureRtCalls_; } + bool last_ensure_rt_rebuilt() const { return lastEnsureRtRebuilt_; } + const char *last_ensure_rt_rebuild_reason() const { return lastEnsureRtReason_; } + bool ensure_preview_swapchain(int w, int h); + bool preview_swapchain_10bit() const { return preview_swapchain_10bit_; } + int preview_swapchain_mode() const { return preview_swapchain_mode_; } + bool present_preview(int src_w, int src_h); + DXGI_FORMAT preview_backbuffer_format() const; + DXGI_FORMAT scene_texture_format() const; + DXGI_FORMAT linear_fp16_texture_format() const; + bool gpu_overlay_text(const wchar_t *text, int frame_w, int frame_h); + bool composite_overlay_to_scene_fp16(int frame_w, int frame_h); + bool blit_fp16_to_rgba8(int frame_w, int frame_h); + bool upload_argb_frame(const void *data, int frame_w, int frame_h, int src_stride); + bool render_uploaded_argb_to_fp16(int frame_w, int frame_h); + bool upload_nv12_frame(const uint8_t *y, int stride_y, const uint8_t *uv, int stride_uv, int frame_w, int frame_h); + bool upload_p010_frame(const uint8_t *y, int stride_y, const uint8_t *uv, int stride_uv, int frame_w, int frame_h); + bool upload_yuy2_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h); + bool upload_y210_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h); + bool upload_v210_frame(const uint8_t *data, int src_stride, int frame_w, int frame_h); + bool render_uploaded_yuv_to_fp16(gcap_pixfmt_t fmt, int frame_w, int frame_h); + bool copy_fp16_to_scene(); + bool readback_to_frame(int frame_w, int frame_h, uint64_t pts_ns, uint64_t frame_id, + gcap_frame_t *out); + bool export_scene_rgb10(const wchar_t *base_path, int raw_flags, bool export_tiff, bool export_stats, bool export_gigabyte_raw); + + ID3D11Device *d3d_ = nullptr; + ID3D11DeviceContext *ctx_ = nullptr; + ID2D1DeviceContext *d2d_ctx_ = nullptr; + + Microsoft::WRL::ComPtr rt_fp16_; + Microsoft::WRL::ComPtr rtv_fp16_; + Microsoft::WRL::ComPtr srv_fp16_; + + Microsoft::WRL::ComPtr rt_scene_fp16_; + Microsoft::WRL::ComPtr rtv_scene_fp16_; + Microsoft::WRL::ComPtr srv_scene_fp16_; + + Microsoft::WRL::ComPtr srv_rgba_; + Microsoft::WRL::ComPtr ps_rgba8_to_preview_; + + Microsoft::WRL::ComPtr rt_rgba_; + Microsoft::WRL::ComPtr upload_nv12_; + Microsoft::WRL::ComPtr upload_yuy2_packed_; + Microsoft::WRL::ComPtr upload_y210_packed_; + Microsoft::WRL::ComPtr rtv_rgba_; + Microsoft::WRL::ComPtr rt_stage_; + Microsoft::WRL::ComPtr rt_scene_stage_fp16_; + + Microsoft::WRL::ComPtr cs_params_; + Microsoft::WRL::ComPtr rt_uav_; + + Microsoft::WRL::ComPtr vs_; + Microsoft::WRL::ComPtr ps_nv12_; + Microsoft::WRL::ComPtr ps_p010_; + Microsoft::WRL::ComPtr ps_yuy2_; + Microsoft::WRL::ComPtr ps_y210_; + Microsoft::WRL::ComPtr ps_fp16_to_rgba8_; + Microsoft::WRL::ComPtr ps_fp16_to_preview_; + Microsoft::WRL::ComPtr ps_composite_overlay_fp16_; + Microsoft::WRL::ComPtr il_; + Microsoft::WRL::ComPtr vb_; + Microsoft::WRL::ComPtr samp_; + + Microsoft::WRL::ComPtr d2d_bitmap_rt_; + + Microsoft::WRL::ComPtr dwrite_; + Microsoft::WRL::ComPtr d2d_white_; + Microsoft::WRL::ComPtr d2d_black_; + Microsoft::WRL::ComPtr overlay_rgba_; + Microsoft::WRL::ComPtr overlay_rtv_; + Microsoft::WRL::ComPtr overlay_srv_; + + void *preview_hwnd_ = nullptr; + bool preview_enabled_ = false; + bool preview_use_fp16_ = false; + int preview_swapchain_mode_ = GCAP_PREVIEW_BITDEPTH_10BIT; + int preview_source_bit_depth_ = 0; + bool preview_swapchain_10bit_ = false; + DXGI_FORMAT preview_swapchain_format_ = DXGI_FORMAT_UNKNOWN; + int preview_w_ = 0; + int preview_h_ = 0; + + + int rt_w_ = 0; + int rt_h_ = 0; + uint64_t lastEnsureRtNs_ = 0; + uint64_t totalEnsureRtNs_ = 0; + uint64_t ensureRtCalls_ = 0; + bool lastEnsureRtRebuilt_ = false; + const char *lastEnsureRtReason_ = "never"; + + Microsoft::WRL::ComPtr preview_swapchain_; + Microsoft::WRL::ComPtr preview_backbuf_; + Microsoft::WRL::ComPtr preview_rtv_; +}; diff --git a/sdk/gdriver_shared/include/gdriver_abi.h b/sdk/gdriver_shared/include/gdriver_abi.h new file mode 100644 index 0000000..fdec79c --- /dev/null +++ b/sdk/gdriver_shared/include/gdriver_abi.h @@ -0,0 +1,197 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define GDRIVER_ABI_VERSION_MAJOR 0u +#define GDRIVER_ABI_VERSION_MINOR 1u +#define GDRIVER_ABI_VERSION_PATCH 0u + +#define GDRIVER_ABI_MAKE_VERSION(major, minor, patch) \ + ((((uint32_t)(major) & 0xffu) << 24) | (((uint32_t)(minor) & 0xffu) << 16) | ((uint32_t)(patch) & 0xffffu)) + +#define GDRIVER_ABI_VERSION \ + GDRIVER_ABI_MAKE_VERSION(GDRIVER_ABI_VERSION_MAJOR, GDRIVER_ABI_VERSION_MINOR, GDRIVER_ABI_VERSION_PATCH) + +#define GDRIVER_MAX_FRIENDLY_NAME 128 +#define GDRIVER_MAX_SERIAL_NUMBER 64 +#define GDRIVER_MAX_FIRMWARE_VERSION 64 +#define GDRIVER_MAX_DRIVER_VERSION 64 +#define GDRIVER_MAX_PLANES 3 + +typedef enum gdriver_status_t +{ + GDRIVER_STATUS_OK = 0, + GDRIVER_STATUS_INVALID_ARGUMENT = 1, + GDRIVER_STATUS_UNSUPPORTED = 2, + GDRIVER_STATUS_INVALID_STATE = 3, + GDRIVER_STATUS_NO_DEVICE = 4, + GDRIVER_STATUS_TIMEOUT = 5, + GDRIVER_STATUS_BUFFER_TOO_SMALL = 6, + GDRIVER_STATUS_IO_ERROR = 7 +} gdriver_status_t; + +typedef enum gdriver_input_t +{ + GDRIVER_INPUT_UNKNOWN = 0, + GDRIVER_INPUT_SDI = 1, + GDRIVER_INPUT_HDMI = 2 +} gdriver_input_t; + +typedef enum gdriver_pixel_format_t +{ + GDRIVER_PIXFMT_UNKNOWN = 0, + GDRIVER_PIXFMT_YUY2 = 1, + GDRIVER_PIXFMT_UYVY = 2, + GDRIVER_PIXFMT_RGB24 = 3, + GDRIVER_PIXFMT_BGRX32 = 4, + GDRIVER_PIXFMT_NV12 = 5, + GDRIVER_PIXFMT_P010 = 6, + GDRIVER_PIXFMT_Y210 = 7, + GDRIVER_PIXFMT_YUV444 = 8 +} gdriver_pixel_format_t; + +typedef enum gdriver_memory_kind_t +{ + GDRIVER_MEMORY_DRIVER_COPY = 0, + GDRIVER_MEMORY_SHARED_SECTION = 1, + GDRIVER_MEMORY_DMA_RING = 2 +} gdriver_memory_kind_t; + +typedef enum gdriver_stream_state_t +{ + GDRIVER_STREAM_STOPPED = 0, + GDRIVER_STREAM_CONFIGURED = 1, + GDRIVER_STREAM_RUNNING = 2 +} gdriver_stream_state_t; + +typedef struct gdriver_abi_version_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint32_t driver_build; + uint32_t reserved0; +} gdriver_abi_version_t; + +typedef struct gdriver_device_info_t +{ + uint32_t struct_size; + uint32_t abi_version; + char friendly_name[GDRIVER_MAX_FRIENDLY_NAME]; + char serial_number[GDRIVER_MAX_SERIAL_NUMBER]; + char firmware_version[GDRIVER_MAX_FIRMWARE_VERSION]; + char driver_version[GDRIVER_MAX_DRIVER_VERSION]; + uint32_t supported_inputs_mask; + uint32_t supported_pixel_formats_mask; +} gdriver_device_info_t; + +typedef struct gdriver_capability_t +{ + uint32_t width; + uint32_t height; + uint32_t fps_num; + uint32_t fps_den; + gdriver_pixel_format_t pixel_format; + uint32_t bit_depth; +} gdriver_capability_t; + +typedef struct gdriver_capabilities_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint32_t capability_count; + uint32_t capability_capacity; + gdriver_capability_t capabilities[1]; +} gdriver_capabilities_t; + +typedef struct gdriver_set_input_t +{ + uint32_t struct_size; + uint32_t abi_version; + gdriver_input_t input; +} gdriver_set_input_t; + +typedef struct gdriver_stream_config_t +{ + uint32_t struct_size; + uint32_t abi_version; + gdriver_input_t input; + uint32_t width; + uint32_t height; + uint32_t fps_num; + uint32_t fps_den; + gdriver_pixel_format_t pixel_format; + uint32_t buffer_count; + gdriver_memory_kind_t memory_kind; + uint32_t flags; +} gdriver_stream_config_t; + +typedef struct gdriver_signal_status_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint32_t signal_locked; + gdriver_input_t input; + uint32_t width; + uint32_t height; + uint32_t fps_num; + uint32_t fps_den; + gdriver_pixel_format_t pixel_format; + uint32_t bit_depth; +} gdriver_signal_status_t; + +typedef struct gdriver_wait_frame_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint32_t timeout_ms; + uint32_t reserved0; +} gdriver_wait_frame_t; + +typedef struct gdriver_frame_desc_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint64_t frame_id; + uint64_t timestamp_ns; + uint32_t width; + uint32_t height; + gdriver_pixel_format_t pixel_format; + uint32_t bit_depth; + uint32_t plane_count; + uint32_t data_size_bytes; + uint32_t plane_offset_bytes[GDRIVER_MAX_PLANES]; + uint32_t plane_stride_bytes[GDRIVER_MAX_PLANES]; + uint32_t driver_buffer_index; + uint32_t flags; +} gdriver_frame_desc_t; + +typedef struct gdriver_release_frame_t +{ + uint32_t struct_size; + uint32_t abi_version; + uint64_t frame_id; + uint32_t driver_buffer_index; + uint32_t reserved0; +} gdriver_release_frame_t; + +typedef struct gdriver_stream_stats_t +{ + uint32_t struct_size; + uint32_t abi_version; + gdriver_stream_state_t state; + uint32_t reserved0; + uint64_t frames_captured; + uint64_t frames_delivered; + uint64_t frames_dropped; + uint64_t dma_errors; + uint64_t interrupt_count; +} gdriver_stream_stats_t; + +#ifdef __cplusplus +} +#endif diff --git a/sdk/gdriver_shared/include/gdriver_control_codes.h b/sdk/gdriver_shared/include/gdriver_control_codes.h new file mode 100644 index 0000000..3c89c4a --- /dev/null +++ b/sdk/gdriver_shared/include/gdriver_control_codes.h @@ -0,0 +1,41 @@ +#pragma once + +#ifdef _WIN32 +#include +#include +#include + +/* 5a09f9e5-7d62-4a65-bce8-d0d9830eb27c */ +DEFINE_GUID(GUID_DEVINTERFACE_GDRIVER_CAPTURE, + 0x5a09f9e5, 0x7d62, 0x4a65, 0xbc, 0xe8, 0xd0, 0xd9, 0x83, 0x0e, 0xb2, 0x7c); + +#ifndef FILE_DEVICE_GDRIVER_CAPTURE +#define FILE_DEVICE_GDRIVER_CAPTURE 0x8337u +#endif + +#define GDRIVER_IOCTL(index, method, access) \ + CTL_CODE(FILE_DEVICE_GDRIVER_CAPTURE, (index), (method), (access)) + +#define IOCTL_GDRIVER_GET_ABI_VERSION \ + GDRIVER_IOCTL(0x800u, METHOD_BUFFERED, FILE_READ_ACCESS) +#define IOCTL_GDRIVER_GET_DEVICE_INFO \ + GDRIVER_IOCTL(0x801u, METHOD_BUFFERED, FILE_READ_ACCESS) +#define IOCTL_GDRIVER_GET_CAPABILITIES \ + GDRIVER_IOCTL(0x802u, METHOD_BUFFERED, FILE_READ_ACCESS) +#define IOCTL_GDRIVER_SET_INPUT \ + GDRIVER_IOCTL(0x803u, METHOD_BUFFERED, FILE_WRITE_ACCESS) +#define IOCTL_GDRIVER_CONFIGURE_STREAM \ + GDRIVER_IOCTL(0x804u, METHOD_BUFFERED, FILE_WRITE_ACCESS) +#define IOCTL_GDRIVER_START_STREAM \ + GDRIVER_IOCTL(0x805u, METHOD_BUFFERED, FILE_WRITE_ACCESS) +#define IOCTL_GDRIVER_STOP_STREAM \ + GDRIVER_IOCTL(0x806u, METHOD_BUFFERED, FILE_WRITE_ACCESS) +#define IOCTL_GDRIVER_WAIT_FRAME \ + GDRIVER_IOCTL(0x807u, METHOD_BUFFERED, FILE_READ_ACCESS) +#define IOCTL_GDRIVER_RELEASE_FRAME \ + GDRIVER_IOCTL(0x808u, METHOD_BUFFERED, FILE_WRITE_ACCESS) +#define IOCTL_GDRIVER_GET_SIGNAL_STATUS \ + GDRIVER_IOCTL(0x809u, METHOD_BUFFERED, FILE_READ_ACCESS) +#define IOCTL_GDRIVER_GET_STATS \ + GDRIVER_IOCTL(0x80au, METHOD_BUFFERED, FILE_READ_ACCESS) +#endif diff --git a/sdk/gvfg/CMakeLists.txt b/sdk/gvfg/CMakeLists.txt new file mode 100644 index 0000000..020cee9 --- /dev/null +++ b/sdk/gvfg/CMakeLists.txt @@ -0,0 +1,54 @@ +if (NOT DEFINED GVFG_SDK_VERSION) + set(GVFG_SDK_VERSION "0.1.0" CACHE STRING "GVFG SDK version") +endif() + +option(GVFG_XDMA_DEBUG_LOG "Enable verbose XDMA flow debug logging in GVFG internal XDMA backend" OFF) + +project(gvfg VERSION ${GVFG_SDK_VERSION} LANGUAGES CXX) + +add_library(gvfg SHARED + include/gvfg_capture.h + src/backend/xdma/xdma_backend_types.h + src/backend/xdma/xdma_capture_session.cpp + src/backend/xdma/xdma_capture_session.h + src/backend/xdma/xdma_public.h + src/gvfg_capture.cpp + src/gcapture_log_bridge.cpp + ${CMAKE_SOURCE_DIR}/sdk/gcapture/src/pipeline/shared_scene_pipeline.cpp +) + +set_target_properties(gvfg PROPERTIES + AUTOMOC OFF + AUTOUIC OFF + AUTORCC OFF +) + +target_include_directories(gvfg + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backend/xdma + ${CMAKE_SOURCE_DIR}/sdk/gdriver_shared/include + ${CMAKE_SOURCE_DIR}/sdk/gcapture/include + ${CMAKE_SOURCE_DIR}/sdk/gcapture/src + ${CMAKE_SOURCE_DIR}/sdk/gcapture/src/pipeline +) + +target_compile_definitions(gvfg PRIVATE + GVFG_BUILD + GVFG_SDK_VERSION="${GVFG_SDK_VERSION}" +) + +if (GVFG_XDMA_DEBUG_LOG) + target_compile_definitions(gvfg PRIVATE GVFG_XDMA_DEBUG_LOG=1) +endif() + +target_link_libraries(gvfg PRIVATE + setupapi + ole32 user32 windowscodecs + dxgi d3d11 d2d1 dwrite D3DCompiler +) + +if (MSVC) + target_compile_options(gvfg PRIVATE /utf-8 /EHsc) +endif() diff --git a/sdk/gvfg/include/gvfg_capture.h b/sdk/gvfg/include/gvfg_capture.h new file mode 100644 index 0000000..6dabe72 --- /dev/null +++ b/sdk/gvfg/include/gvfg_capture.h @@ -0,0 +1,458 @@ +#pragma once + +/* + * Customer-facing GVFG capture API. + * + * Include only this header in customer applications. Do not include internal + * backend/gdriver headers; those layers are implementation details behind + * gvfg.dll. + * + * Minimal capture flow: + * + * gvfg_device_info_t devices[GVFG_MAX_DEVICES] = {}; + * int count = gvfg_enumerate_devices(devices, GVFG_MAX_DEVICES); + * + * gvfg_handle h = NULL; + * gvfg_create(&h); + * gvfg_set_callbacks(h, on_frame, on_error, user); + * // Optional: gvfg_set_frame_callback_interval(h, 6); // one callback per 6 frames + * + * // Optional: let the SDK render preview directly into a native HWND. + * gvfg_preview_desc_t preview = {}; + * preview.hwnd = hwnd; + * preview.enable_preview = 1; + * preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO; + * gvfg_set_preview(h, &preview); + * + * gvfg_open(h, devices[0].index); + * gvfg_start(h); + * + * // Capture is now running. Use callbacks for frames/messages and + * // gvfg_get_runtime_info() for status. + * + * gvfg_stop(h); + * gvfg_destroy(h); + * + * Threading notes: + * - Frame and error callbacks are called from an SDK worker thread, not from + * the UI thread. UI applications should marshal callback work back to their + * UI thread. + * - The frame data pointer is valid only during the callback. Copy the data if + * it must be used after the callback returns. + */ + +#include + +#ifdef _WIN32 +#ifdef GVFG_BUILD +#define GVFG_API __declspec(dllexport) +#else +#define GVFG_API __declspec(dllimport) +#endif +#else +#define GVFG_API +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + GVFG_MAX_DEVICES = 16 +}; + +typedef enum +{ + GVFG_OK = 0, + GVFG_EINVAL = -1, /* Invalid argument, such as NULL handle/output pointer. */ + GVFG_ENODEV = -2, /* No GVFG device, no signal, or device open failed. */ + GVFG_ESTATE = -3, /* API was called in the wrong state. */ + GVFG_EIO = -4, /* Driver/backend I/O failure. */ + GVFG_ENOTSUP = -5, /* Requested feature or format is not supported. */ + GVFG_ETIMEOUT = -6 /* Timed out waiting for driver/backend work. */ +} gvfg_status_t; + +typedef enum +{ + GVFG_PREVIEW_BITDEPTH_AUTO = 0, /* Let the SDK choose the best swapchain format. */ + GVFG_PREVIEW_BITDEPTH_10BIT = 10, /* Prefer a 10-bit preview swapchain when available. */ + GVFG_PREVIEW_BITDEPTH_8BIT = 8 /* Force an 8-bit preview swapchain. */ +} gvfg_preview_bitdepth_t; + +typedef struct +{ + int index; /* Device index to pass to gvfg_open(). */ + char name[128]; /* Display name for UI/logging. UTF-8, null-terminated. */ +} gvfg_device_info_t; + +typedef struct +{ + void *hwnd; /* Native Windows HWND that stays alive while capture runs. */ + int enable_preview; /* Non-zero enables SDK-managed preview rendering. */ + int swapchain_bitdepth; /* gvfg_preview_bitdepth_t value. */ +} gvfg_preview_desc_t; + +typedef struct +{ + uint32_t valid_mask; /* FPGA register read-valid mask: bit0=0x0c, bit1=0x18, bit2=0x1c, bit3=0x180. */ + int width_valid; /* Non-zero when FPGA 0x10 read succeeded. */ + int height_valid; /* Non-zero when FPGA 0x14 read succeeded. */ + uint32_t width_raw; /* Raw FPGA 0x10 width register. */ + uint32_t height_raw; /* Raw FPGA 0x14 height register. */ + uint32_t video_format_raw; /* Raw FPGA 0x0c value. */ + int video_format_valid; + int video_format_code; /* 0=yuv422, 1=rgb, 2=yuv444, 3=yuv420 */ + char video_format[16]; + + uint32_t frame_rate_raw; /* Raw FPGA 0x18 value. */ + int frame_rate_valid; + int frame_rate_code; /* FPGA frame-rate code from 0x18 low nibble. */ + char frame_rate_bits[5]; /* 4-bit binary text, for example "0110". */ + char frame_rate_name[16]; /* None, 23.98, 24, 47.95, ..., or "--" for unsupported codes. */ + + uint32_t bit_depth_raw; /* Raw FPGA 0x1c value. */ + int bit_depth_valid; + int bit_depth; /* 8 or 10 when valid. */ + + uint32_t status_raw; /* Raw FPGA 0x180 value. */ + int status_valid; + int sdi_locked; /* FPGA 0x180 bit0 */ + int sdi_ddr_ok; /* FPGA 0x180 bit1 */ + int hdmi_locked; /* FPGA 0x180 bit2 */ + int hdmi_ddr_ok; /* FPGA 0x180 bit3 */ +} gvfg_fpga_signal_status_t; + +typedef struct +{ + int width; /* Signal width in pixels, from FPGA when available. */ + int height; /* Signal height in pixels, from FPGA when available. */ + double fps; /* Legacy field; GVFG leaves this 0. Use fpga.frame_rate_* instead. */ + int bit_depth; /* Legacy SDK source-buffer bit depth. Prefer fpga.* and runtime delivered_frame. */ + char pixel_format[32]; /* Legacy SDK source-buffer format. Prefer fpga.* and runtime delivered_frame. */ + gvfg_fpga_signal_status_t fpga; /* Raw/decoded FPGA signal metadata. */ +} gvfg_signal_status_t; + +typedef struct +{ + int width; /* Width of frames delivered to the customer callback. */ + int height; /* Height of frames delivered to the customer callback. */ + int bit_depth; /* Bit depth of the delivered callback buffer. */ + char pixel_format[32]; /* Delivered callback buffer format, for example BGRA8. */ + int valid; /* Non-zero while capture is running after at least one callback frame. */ +} gvfg_delivered_frame_info_t; + +typedef struct +{ + gvfg_signal_status_t input_signal; /* FPGA-reported signal metadata plus legacy buffer fields. */ + gvfg_delivered_frame_info_t delivered_frame; /* Frame buffer delivered by gvfg.dll to the app. */ + double capture_fps; /* Runtime FPS measured from backend frames seen by the SDK worker. */ + uint64_t delivered_frames; /* Number of frames delivered to the app callback. */ +} gvfg_runtime_info_t; + +typedef struct +{ + int enabled; /* Non-zero when preview was requested. */ + int active; /* Non-zero when the preview pipeline is currently active. */ + int width; /* Preview render width. */ + int height; /* Preview render height. */ + int swapchain_bitdepth; /* Actual preview swapchain bit depth, usually 8 or 10. */ + int swapchain_10bit; /* Non-zero when the active swapchain is 10-bit. */ + char render_path[128]; /* Human-readable preview pipeline description. */ + char backbuffer_format[64]; /* DXGI backbuffer format name. */ +} gvfg_preview_info_t; + +typedef struct +{ + const void *data; /* Frame pixels. Valid only during the frame callback. */ + int stride; /* Bytes per row for data. */ + int width; /* Frame width in pixels. */ + int height; /* Frame height in pixels. */ + uint64_t pts_ns; /* Presentation timestamp in nanoseconds. */ + uint64_t frame_id; /* Monotonic frame identifier from the backend. */ +} gvfg_frame_t; + +typedef enum +{ + GVFG_EVENT_VIDEO_IRQ = 1, + GVFG_EVENT_PLUG_IN = 2, + GVFG_EVENT_PLUG_OUT = 3, + GVFG_EVENT_CAPTURE_PAUSED = 4, + GVFG_EVENT_CAPTURE_RESUMED = 5 +} gvfg_event_type_t; + +enum +{ + GVFG_EVENT_MASK_VIDEO_IRQ = 1u << 0, + GVFG_EVENT_MASK_PLUG_IN = 1u << 1, + GVFG_EVENT_MASK_PLUG_OUT = 1u << 2, + GVFG_EVENT_MASK_CAPTURE_PAUSED = 1u << 3, + GVFG_EVENT_MASK_CAPTURE_RESUMED = 1u << 4, + GVFG_EVENT_MASK_HOTPLUG = GVFG_EVENT_MASK_PLUG_IN | + GVFG_EVENT_MASK_PLUG_OUT | + GVFG_EVENT_MASK_CAPTURE_PAUSED | + GVFG_EVENT_MASK_CAPTURE_RESUMED, + GVFG_EVENT_MASK_DEFAULT = GVFG_EVENT_MASK_HOTPLUG, + GVFG_EVENT_MASK_ALL = GVFG_EVENT_MASK_VIDEO_IRQ | GVFG_EVENT_MASK_HOTPLUG +}; + +typedef struct +{ + gvfg_event_type_t type; + uint32_t irq_bit; + uint32_t irq_mask; + uint64_t timestamp_ns; +} gvfg_event_t; + +/* Opaque session handle created by gvfg_create() and released by gvfg_destroy(). */ +typedef struct gvfg_handle_t *gvfg_handle; + +/* Called when the SDK provides a frame for application use. + * This callback is not required for SDK-managed preview rendering. + */ +typedef void (*gvfg_on_frame_cb)(const gvfg_frame_t *frame, void *user); + +/* Called for capture events such as PLUG_IN / PLUG_OUT. */ +typedef void (*gvfg_on_event_cb)(const gvfg_event_t *event, void *user); + +/* Called for asynchronous SDK messages or errors. */ +typedef void (*gvfg_on_error_cb)(gvfg_status_t status, const char *message, void *user); + +/* + * Enumerate GVFG capture devices. + * + * Parameters: + * - out_devices: Output array that receives device entries. Pass NULL to query + * the device count only. + * - max_devices: Number of entries available in out_devices. Values larger + * than GVFG_MAX_DEVICES are clamped. Pass 0 when out_devices is NULL. + * + * Returns: + * - When out_devices is non-NULL, returns the number of entries written. + * - When out_devices is NULL or max_devices is 0, returns the number of + * available devices. + * - Returns <= 0 when no device is available. + */ +GVFG_API int gvfg_enumerate_devices(gvfg_device_info_t *out_devices, int max_devices); + +/* + * Create a GVFG capture session. + * + * Parameters: + * - out_handle: Receives the new session handle. Must not be NULL. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if out_handle is NULL. + * + * The returned handle starts in the closed state. Release it with + * gvfg_destroy(). + */ +GVFG_API gvfg_status_t gvfg_create(gvfg_handle *out_handle); + +/* + * Destroy a GVFG capture session. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * + * Returns: + * - GVFG_OK. + * + * If capture is still running, it is stopped first. After this call, the handle + * must not be used again. + */ +GVFG_API gvfg_status_t gvfg_destroy(gvfg_handle handle); + +/* + * Register frame and error callbacks. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - on_frame: Function called when a frame is available. Pass NULL if frame + * callbacks are not needed. + * - on_error: Function called for asynchronous SDK messages/errors. Pass NULL + * if error callbacks are not needed. + * - user: Application-defined pointer passed back to both callbacks. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle is NULL. + * + * Callbacks are called from an SDK worker thread. The application must marshal + * UI work to its UI thread. + */ +GVFG_API gvfg_status_t gvfg_set_callbacks(gvfg_handle handle, + gvfg_on_frame_cb on_frame, + gvfg_on_error_cb on_error, + void *user); + +/* + * Configure frame callback rate. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - frame_interval: 0 or 1 calls on_frame for every delivered frame. N > 1 + * calls on_frame once for every N delivered backend frames. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle is NULL. + * + * This only affects the application frame callback. SDK-managed preview + * rendering, gvfg_get_runtime_info(), and capture itself continue at full rate. + */ +GVFG_API gvfg_status_t gvfg_set_frame_callback_interval(gvfg_handle handle, + uint32_t frame_interval); + +/* + * Register capture event callback. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - on_event: Function called when an enabled capture event occurs. Pass NULL + * to disable event callbacks. + * - user: Application-defined pointer passed back to the callback. + * - event_mask: GVFG_EVENT_MASK_* bits. Pass 0 to use GVFG_EVENT_MASK_DEFAULT. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle is NULL. + * + * VIDEO_IRQ is not included in the default mask because it can occur once per + * video frame. Enable GVFG_EVENT_MASK_VIDEO_IRQ only for debug or when the + * application explicitly needs it. + */ +GVFG_API gvfg_status_t gvfg_set_event_callback(gvfg_handle handle, + gvfg_on_event_cb on_event, + void *user, + uint32_t event_mask); + +/* + * Configure SDK-managed preview rendering. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - desc: Preview configuration. Must not be NULL. When preview is enabled, + * desc->hwnd must be a valid native Windows HWND. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle or desc is NULL. + * + * This API is optional. If enabled, call it before gvfg_start() and keep the + * HWND alive while capture is running. Applications that render frames + * themselves can skip this API and use the frame callback instead. + */ +GVFG_API gvfg_status_t gvfg_set_preview(gvfg_handle handle, const gvfg_preview_desc_t *desc); + +/* + * Open a device by index from gvfg_enumerate_devices(). + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - device_index: Device index from gvfg_device_info_t::index. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle is NULL. + * - GVFG_ENODEV if the device cannot be opened. + * - GVFG_EIO for driver/backend failures. + * + * The current implementation selects the SDI input internally. + */ +GVFG_API gvfg_status_t gvfg_open(gvfg_handle handle, int device_index); + +/* + * Configure and start capture on an opened device. + * + * Parameters: + * - handle: Opened session handle. + * + * Returns: + * - GVFG_OK on success, including when capture is already running. + * - GVFG_EINVAL if handle is NULL. + * - GVFG_ESTATE if no device is open. + * - GVFG_EIO or another status code if stream configuration/start fails. + * + * After success, frames and asynchronous messages are delivered through the + * callbacks registered by gvfg_set_callbacks(). + */ +GVFG_API gvfg_status_t gvfg_start(gvfg_handle handle); + +/* + * Stop capture. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * + * Returns: + * - GVFG_OK on success, including when capture is already stopped. + * - GVFG_EINVAL if handle is NULL. + * + * This waits for the SDK capture worker thread to exit. + */ +GVFG_API gvfg_status_t gvfg_stop(gvfg_handle handle); + +/* + * Query current signal information and delivered buffer format. + * + * Parameters: + * - handle: Opened session handle. + * - out_status: Receives signal status. Must not be NULL. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle or out_status is NULL. + * - GVFG_ENODEV if no valid signal information is available. + * + * The FPGA metadata describes the hardware signal. The pixel_format and + * bit_depth fields describe the buffer format delivered by the customer API. + */ +GVFG_API gvfg_status_t gvfg_get_signal_status(gvfg_handle handle, gvfg_signal_status_t *out_status); + +/* + * Query runtime capture diagnostics. + * + * Parameters: + * - handle: Opened or running session handle. + * - out_info: Receives runtime information. Must not be NULL. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle or out_info is NULL. + * + * The result includes current signal status, SDK-measured capture FPS, and the + * number of frames delivered by the SDK. + */ +GVFG_API gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, gvfg_runtime_info_t *out_info); + +/* + * Query SDK-managed preview diagnostics. + * + * Parameters: + * - handle: Session handle returned by gvfg_create(). + * - out_info: Receives preview information. Must not be NULL. + * + * Returns: + * - GVFG_OK on success. + * - GVFG_EINVAL if handle or out_info is NULL. + * + * This is useful only when the application uses gvfg_set_preview(). + */ +GVFG_API gvfg_status_t gvfg_get_preview_info(gvfg_handle handle, gvfg_preview_info_t *out_info); + +/* + * Convert a GVFG status code to a static English error string. + * + * Parameters: + * - status: Status code returned by a GVFG API. + * + * Returns: + * - Static null-terminated English string. The caller must not free it. + */ +GVFG_API const char *gvfg_strerror(gvfg_status_t status); + +#ifdef __cplusplus +} +#endif diff --git a/sdk/gvfg/src/backend/xdma/xdma_backend_types.h b/sdk/gvfg/src/backend/xdma/xdma_backend_types.h new file mode 100644 index 0000000..752be22 --- /dev/null +++ b/sdk/gvfg/src/backend/xdma/xdma_backend_types.h @@ -0,0 +1,118 @@ +#pragma once + +#include +#include +#include "gdriver_abi.h" + +typedef enum xdma_status_t +{ + XDMA_OK = 0, + XDMA_EINVAL, + XDMA_ENODEV, + XDMA_ESTATE, + XDMA_ENOTSUP, + XDMA_ETIMEOUT, + XDMA_EIO, + XDMA_EABI +} xdma_status_t; + +typedef struct xdma_device_info_t +{ + char friendly_name[GDRIVER_MAX_FRIENDLY_NAME]; + char serial_number[GDRIVER_MAX_SERIAL_NUMBER]; + char firmware_version[GDRIVER_MAX_FIRMWARE_VERSION]; + char driver_version[GDRIVER_MAX_DRIVER_VERSION]; + uint32_t supported_inputs_mask; + uint32_t supported_pixel_formats_mask; +} xdma_device_info_t; + +typedef struct xdma_stream_desc_t +{ + gdriver_input_t input; + uint32_t width; + uint32_t height; + gdriver_pixel_format_t pixel_format; + uint32_t buffer_count; + gdriver_memory_kind_t memory_kind; + uint32_t flags; +} xdma_stream_desc_t; + +typedef struct xdma_signal_status_t +{ + int signal_locked; + gdriver_input_t input; + uint32_t width; + uint32_t height; + gdriver_pixel_format_t pixel_format; + uint32_t bit_depth; + uint32_t fpga_valid_mask; /* bit0:0x0c, bit1:0x18, bit2:0x1c, bit3:0x180 */ + uint32_t fpga_width_valid; /* Non-zero when FPGA 0x10 read succeeded. */ + uint32_t fpga_height_valid; /* Non-zero when FPGA 0x14 read succeeded. */ + uint32_t fpga_width_raw; /* Raw FPGA 0x10 width register. */ + uint32_t fpga_height_raw; /* Raw FPGA 0x14 height register. */ + uint32_t fpga_video_format_raw; /* 0x0c: 0=yuv422, 1=rgb, 2=yuv444, 3=yuv420 */ + uint32_t fpga_frame_rate_raw; /* 0x18 low nibble: frame-rate code */ + uint32_t fpga_bit_depth_raw; /* 0x1c: 8 or 10 */ + uint32_t fpga_status_raw; /* 0x180: bit0 SDI lock, bit1 SDI DDR, bit2 HDMI lock, bit3 HDMI DDR */ +} xdma_signal_status_t; + +typedef struct xdma_frame_t +{ + const void *data; /* Valid until the next XdmaCaptureSession::wait_frame() or close(). */ + size_t data_size_bytes; + uint64_t frame_id; + uint64_t timestamp_ns; + uint32_t width; + uint32_t height; + gdriver_pixel_format_t pixel_format; + uint32_t bit_depth; + uint32_t plane_count; + uint32_t plane_offset_bytes[GDRIVER_MAX_PLANES]; + uint32_t plane_stride_bytes[GDRIVER_MAX_PLANES]; + uint32_t driver_buffer_index; + uint32_t flags; +} xdma_frame_t; + +typedef struct xdma_stream_stats_t +{ + gdriver_stream_state_t state; + uint64_t frames_captured; + uint64_t frames_delivered; + uint64_t frames_dropped; + uint64_t dma_errors; + uint64_t interrupt_count; +} xdma_stream_stats_t; + +typedef enum xdma_event_type_t +{ + XDMA_EVENT_VIDEO_IRQ = 1, + XDMA_EVENT_PLUG_IN = 2, + XDMA_EVENT_PLUG_OUT = 3, + XDMA_EVENT_CAPTURE_PAUSED = 4, + XDMA_EVENT_CAPTURE_RESUMED = 5 +} xdma_event_type_t; + +enum +{ + XDMA_EVENT_MASK_VIDEO_IRQ = 1u << 0, + XDMA_EVENT_MASK_PLUG_IN = 1u << 1, + XDMA_EVENT_MASK_PLUG_OUT = 1u << 2, + XDMA_EVENT_MASK_CAPTURE_PAUSED = 1u << 3, + XDMA_EVENT_MASK_CAPTURE_RESUMED = 1u << 4, + XDMA_EVENT_MASK_HOTPLUG = XDMA_EVENT_MASK_PLUG_IN | + XDMA_EVENT_MASK_PLUG_OUT | + XDMA_EVENT_MASK_CAPTURE_PAUSED | + XDMA_EVENT_MASK_CAPTURE_RESUMED, + XDMA_EVENT_MASK_DEFAULT = XDMA_EVENT_MASK_HOTPLUG, + XDMA_EVENT_MASK_ALL = XDMA_EVENT_MASK_VIDEO_IRQ | XDMA_EVENT_MASK_HOTPLUG +}; + +typedef struct xdma_event_t +{ + xdma_event_type_t type; + uint32_t irq_bit; + uint32_t irq_mask; + uint64_t timestamp_ns; +} xdma_event_t; + +typedef void (*xdma_event_callback_t)(const xdma_event_t *event, void *user); diff --git a/sdk/gvfg/src/backend/xdma/xdma_capture_session.cpp b/sdk/gvfg/src/backend/xdma/xdma_capture_session.cpp new file mode 100644 index 0000000..9d5e482 --- /dev/null +++ b/sdk/gvfg/src/backend/xdma/xdma_capture_session.cpp @@ -0,0 +1,1699 @@ +#include "xdma_capture_session.h" + +#include "xdma_public.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma comment(lib, "SetupAPI.lib") + +DEFINE_GUID(GUID_DEVINTERFACE_XDMA, + 0x74c7e4a9, 0x6d5d, 0x4a70, 0xbc, 0x0d, 0x20, 0x69, 0x1d, 0xff, 0x9e, 0x9d); + +namespace +{ + constexpr uint32_t kInputPathCount = 2; + constexpr uint32_t kIrqRolesPerInput = 4; + constexpr uint32_t kVideoIrqRole = 0; + constexpr uint32_t kPlugInIrqRole = 2; + constexpr uint32_t kPlugOutIrqRole = 3; + constexpr int kPlugInScanFrames = 5; + constexpr uint32_t kDefaultWidth = 1920; + constexpr uint32_t kDefaultHeight = 1080; + constexpr DWORD kMaxBytesPerTransfer = 0x800000; + + // FPGA user BAR register offsets. These match the old CaptureDemo + // register map: write capture-enable to start/stop DMA, read width/height + // to infer the current input signal, and pulse INT_CLR after an IRQ. + constexpr long kInterruptClearReg = 0x500; + constexpr long kVideo0CaptureEnableReg = 0x004; + constexpr long kVideo1CaptureEnableReg = 0x304; + constexpr long kVideoFormatReg = 0x0c; + constexpr long kVideoWidthReg = 0x10; + constexpr long kVideoHeightReg = 0x14; + constexpr long kVideoFrameRateReg = 0x18; + constexpr long kVideoBitDepthReg = 0x1c; + constexpr long kFpgaStatusReg = 0x180; + constexpr long kPlugInFrameFixReg = 0x200; + + static uint32_t bit_n(uint32_t n) + { + return n < 32 ? (1u << n) : 0u; + } + + static bool should_log_counter(uint64_t count) + { + return count <= 5 || (count % 60) == 0; + } + + static bool is_stream_event_role(uint32_t role) + { + return role == kVideoIrqRole || role == kPlugInIrqRole || role == kPlugOutIrqRole; + } + + static uint32_t event_mask_for_type(xdma_event_type_t type) + { + switch (type) + { + case XDMA_EVENT_VIDEO_IRQ: + return XDMA_EVENT_MASK_VIDEO_IRQ; + case XDMA_EVENT_PLUG_IN: + return XDMA_EVENT_MASK_PLUG_IN; + case XDMA_EVENT_PLUG_OUT: + return XDMA_EVENT_MASK_PLUG_OUT; + case XDMA_EVENT_CAPTURE_PAUSED: + return XDMA_EVENT_MASK_CAPTURE_PAUSED; + case XDMA_EVENT_CAPTURE_RESUMED: + return XDMA_EVENT_MASK_CAPTURE_RESUMED; + default: + return 0; + } + } + + static uint64_t steady_now_ns() + { + const auto now = std::chrono::steady_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(now).count()); + } + + static size_t find_frame_marker_offset(const uint8_t *data, size_t bytes) + { + if (!data || bytes < 2) + return bytes; + for (size_t i = 0; i + 1 < bytes; ++i) + { + if (data[i] == 0xff && data[i + 1] == 0xff) + return i; + } + return bytes; + } + + static uint32_t decode_bit_depth(uint32_t raw, uint32_t fallback) + { + const uint32_t value = raw & 0xffu; + return (value == 8u || value == 10u) ? value : fallback; + } + + static gdriver_pixel_format_t decode_pixel_format(uint32_t rawFormat, uint32_t bitDepth) + { + (void)bitDepth; + switch (rawFormat & 0x3u) + { + case 0: + return GDRIVER_PIXFMT_YUY2; + case 1: + return GDRIVER_PIXFMT_RGB24; + case 2: + return GDRIVER_PIXFMT_YUV444; + case 3: + return GDRIVER_PIXFMT_NV12; + default: + return GDRIVER_PIXFMT_UNKNOWN; + } + } + + static uint32_t bit_depth_for_pixfmt(gdriver_pixel_format_t fmt) + { + switch (fmt) + { + case GDRIVER_PIXFMT_P010: + case GDRIVER_PIXFMT_Y210: + return 10; + default: + return 8; + } + } + + static size_t bytes_per_frame(uint32_t width, uint32_t height, gdriver_pixel_format_t fmt, uint32_t bitDepth) + { + const size_t pixels = static_cast(width) * static_cast(height); + switch (fmt) + { + case GDRIVER_PIXFMT_NV12: + return pixels * 3u / 2u; + case GDRIVER_PIXFMT_P010: + return pixels * 3u; + case GDRIVER_PIXFMT_RGB24: + case GDRIVER_PIXFMT_YUV444: + return bitDepth > 8u ? pixels * 6u : pixels * 3u; + case GDRIVER_PIXFMT_Y210: + return pixels * 4u; + case GDRIVER_PIXFMT_YUY2: + case GDRIVER_PIXFMT_UYVY: + default: + return pixels * 2u; + } + } + + static uint32_t plane_count_for_pixfmt(gdriver_pixel_format_t fmt) + { + return (fmt == GDRIVER_PIXFMT_NV12 || fmt == GDRIVER_PIXFMT_P010) ? 2u : 1u; + } + + static uint32_t plane_stride_for_pixfmt(uint32_t width, gdriver_pixel_format_t fmt, uint32_t bitDepth) + { + switch (fmt) + { + case GDRIVER_PIXFMT_NV12: + return width; + case GDRIVER_PIXFMT_P010: + return width * 2u; + case GDRIVER_PIXFMT_RGB24: + case GDRIVER_PIXFMT_YUV444: + return bitDepth > 8u ? width * 6u : width * 3u; + case GDRIVER_PIXFMT_Y210: + return width * 4u; + case GDRIVER_PIXFMT_YUY2: + case GDRIVER_PIXFMT_UYVY: + default: + return width * 2u; + } + } + +#if defined(GVFG_XDMA_DEBUG_LOG) + static void xdma_debug_log(const char *fmt, ...) + { + char msg[1024] = {}; + va_list args; + va_start(args, fmt); + vsnprintf(msg, sizeof(msg), fmt, args); + va_end(args); + + char line[1152] = {}; + snprintf(line, sizeof(line), "[GVFG][XDMA] %s\n", msg); + OutputDebugStringA(line); + } +#define XDMA_LOG(...) xdma_debug_log(__VA_ARGS__) +#else +#define XDMA_LOG(...) ((void)0) +#endif + + static void xdma_hotplug_log(const char *fmt, ...) + { + char msg[1024] = {}; + va_list args; + va_start(args, fmt); + vsnprintf(msg, sizeof(msg), fmt, args); + va_end(args); + + char line[1152] = {}; + snprintf(line, sizeof(line), "[GVFG][XDMA][hotplug] %s\n", msg); + OutputDebugStringA(line); + } +#define XDMA_HOTPLUG_LOG(...) xdma_hotplug_log(__VA_ARGS__) + + static std::string wide_to_utf8(const std::wstring &s) + { + if (s.empty()) + return std::string(); + const int needed = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, nullptr, 0, nullptr, nullptr); + if (needed <= 0) + return std::string(); + std::string out(static_cast(needed), '\0'); + WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, &out[0], needed, nullptr, nullptr); + if (!out.empty() && out.back() == '\0') + out.pop_back(); + return out; + } + + static std::string summarize_device_path(const std::wstring &path) + { + std::string s = wide_to_utf8(path); + std::string lower = s; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) + { return static_cast(std::tolower(c)); }); + + const auto pciPos = lower.find("pci#"); + const auto guidPos = lower.find("#{"); + if (pciPos == std::string::npos) + return s; + + const std::string pci = s.substr(pciPos, guidPos == std::string::npos ? std::string::npos : guidPos - pciPos); + const auto venPos = lower.find("ven_", pciPos); + const auto devPos = lower.find("dev_", pciPos); + const auto subsysPos = lower.find("subsys_", pciPos); + const auto revPos = lower.find("rev_", pciPos); + if (venPos == std::string::npos || devPos == std::string::npos) + return pci; + + std::ostringstream oss; + oss << "pci ven=" << s.substr(venPos + 4, 4) + << " dev=" << s.substr(devPos + 4, 4); + if (subsysPos != std::string::npos) + oss << " subsys=" << s.substr(subsysPos + 7, 8); + if (revPos != std::string::npos) + oss << " rev=" << s.substr(revPos + 4, 2); + return oss.str(); + } + + static void copy_string(const std::string &src, char *dst, size_t dstSize) + { + if (!dst || dstSize == 0) + return; + dst[0] = '\0'; + if (src.empty()) + return; + const size_t n = (std::min)(src.size(), dstSize - 1); + std::memcpy(dst, src.data(), n); + dst[n] = '\0'; + } + + static void reset_stats(xdma_stream_stats_t &stats, gdriver_stream_state_t state) + { + std::memset(&stats, 0, sizeof(stats)); + stats.state = state; + } + + static std::string win32_error(DWORD err) + { + char *msg = nullptr; + const DWORD len = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&msg), + 0, + nullptr); + std::string out; + if (len && msg) + { + out.assign(msg, msg + len); + while (!out.empty() && (out.back() == '\r' || out.back() == '\n' || out.back() == ' ')) + out.pop_back(); + } + if (msg) + LocalFree(msg); + if (out.empty()) + { + std::ostringstream oss; + oss << "win32=" << err; + out = oss.str(); + } + return out; + } +} + +namespace gvfg::internal +{ + // Enumerate XDMA device interface paths with Windows SetupAPI. + std::vector enumerate_xdma_devices() + { + std::vector devices; + XDMA_LOG("enumerate: begin guid=74c7e4a9-6d5d-4a70-bc0d-20691dff9e9d"); + + // Find installed XDMA device interfaces. This is the SDK version of + // CaptureDemo::getDevices(): keep the Windows SetupAPI detail hidden + // inside the XDMA backend so customer code only calls gvfg_enumerate_devices(). + HDEVINFO info = SetupDiGetClassDevsW(&GUID_DEVINTERFACE_XDMA, nullptr, nullptr, + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + if (info == INVALID_HANDLE_VALUE) + { + XDMA_LOG("enumerate: SetupDiGetClassDevsW failed gle=%lu", GetLastError()); + return devices; + } + + SP_DEVICE_INTERFACE_DATA iface = {}; + iface.cbSize = sizeof(iface); + for (DWORD index = 0; SetupDiEnumDeviceInterfaces(info, nullptr, &GUID_DEVINTERFACE_XDMA, index, &iface); ++index) + { + DWORD required = 0; + SetupDiGetDeviceInterfaceDetailW(info, &iface, nullptr, 0, &required, nullptr); + if (required == 0) + continue; + + std::vector detailBytes(required); + auto *detail = reinterpret_cast(detailBytes.data()); + detail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W); + if (!SetupDiGetDeviceInterfaceDetailW(info, &iface, detail, required, nullptr, nullptr)) + continue; + + XdmaDevice device; + device.interface_path = detail->DevicePath; + device.friendly_name = L"XDMA Capture Device " + std::to_wstring(devices.size()); + XDMA_LOG("enumerate: device[%zu] %s", + devices.size(), + summarize_device_path(device.interface_path).c_str()); + devices.push_back(device); + } + + SetupDiDestroyDeviceInfoList(info); + XDMA_LOG("enumerate: done count=%zu", devices.size()); + return devices; + } + + XdmaCaptureSession::XdmaCaptureSession() + { + stream_desc_.input = GDRIVER_INPUT_SDI; + stream_desc_.width = kDefaultWidth; + stream_desc_.height = kDefaultHeight; + stream_desc_.pixel_format = GDRIVER_PIXFMT_YUY2; + stream_bit_depth_ = 8; + stream_desc_.buffer_count = 1; + stream_desc_.memory_kind = GDRIVER_MEMORY_DRIVER_COPY; + reset_stats(stats_, GDRIVER_STREAM_STOPPED); + } + + XdmaCaptureSession::~XdmaCaptureSession() + { + close(); + } + + xdma_status_t XdmaCaptureSession::open_default() + { + const auto devices = enumerate_xdma_devices(); + XDMA_LOG("open_default: device_count=%zu", devices.size()); + if (devices.empty()) + return fail(XDMA_ENODEV, "enumerate_xdma_devices", ERROR_NOT_FOUND); + return open_device(devices.front()); + } + + xdma_status_t XdmaCaptureSession::open_device_index(size_t deviceIndex) + { + const auto devices = enumerate_xdma_devices(); + XDMA_LOG("open_device_index: requested=%zu device_count=%zu", deviceIndex, devices.size()); + if (deviceIndex >= devices.size()) + return fail(XDMA_ENODEV, "enumerate_xdma_devices", ERROR_NOT_FOUND); + return open_device(devices[deviceIndex]); + } + + xdma_status_t XdmaCaptureSession::open_device(const XdmaDevice &device) + { + XDMA_LOG("open_device: begin friendly=%s %s", + wide_to_utf8(device.friendly_name).c_str(), + summarize_device_path(device.interface_path).c_str()); + close(); + base_path_ = device.interface_path; + friendly_name_ = device.friendly_name.empty() ? L"XDMA Capture Device" : device.friendly_name; + + // XDMA exposes several subdevices under the same base path: + // user : FPGA register access through ReadFile/WriteFile + // c2h_0 / c2h_1 : card-to-host DMA data paths for SDI / HDMI + // event_N is opened later in start_stream(), only for the active IRQ. + user_device_ = open_subdevice(L"user"); + if (user_device_ == INVALID_HANDLE_VALUE) + { + close_handles(); + return fail(XDMA_EIO, "CreateFile(user)"); + } + + for (uint32_t path = 0; path < kInputPathCount; ++path) + { + const std::wstring name = L"c2h_" + std::to_wstring(path); + c2h_device_[path] = open_subdevice(name.c_str()); + if (c2h_device_[path] == INVALID_HANDLE_VALUE) + { + close_handles(); + return fail(XDMA_EIO, "CreateFile(c2h)"); + } + XDMA_LOG("open_device: c2h_%u ready", path); + } + + opened_ = true; + configured_ = false; + clear_last_error(); + XDMA_LOG("open_device: done"); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::close() + { + XDMA_LOG("close: begin opened=%d configured=%d running=%d", + opened_ ? 1 : 0, + configured_ ? 1 : 0, + running_ ? 1 : 0); + stop_stream(); + close_handles(); + opened_ = false; + configured_ = false; + base_path_.clear(); + friendly_name_.clear(); + XDMA_LOG("close: done"); + return XDMA_OK; + } + + void XdmaCaptureSession::close_handles() + { + for (uint32_t role = 0; role < kIrqRolesPerInput; ++role) + { + if (event_device_[role] != INVALID_HANDLE_VALUE) + { + CloseHandle(event_device_[role]); + event_device_[role] = INVALID_HANDLE_VALUE; + XDMA_LOG("close_handles: event_%u closed", role); + } + } + if (user_device_ != INVALID_HANDLE_VALUE) + { + CloseHandle(user_device_); + user_device_ = INVALID_HANDLE_VALUE; + XDMA_LOG("close_handles: user closed"); + } + for (HANDLE &h : c2h_device_) + { + if (h != INVALID_HANDLE_VALUE) + { + CloseHandle(h); + h = INVALID_HANDLE_VALUE; + XDMA_LOG("close_handles: c2h closed"); + } + } + } + + HANDLE XdmaCaptureSession::open_subdevice(const wchar_t *name) const + { + if (base_path_.empty() || !name || !*name) + return INVALID_HANDLE_VALUE; + + // Full path example: + // \user + // \c2h_0 + // \event_0 + const std::wstring path = base_path_ + L"\\" + name; + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) + { + XDMA_LOG("open_subdevice: %s failed gle=%lu path=%s", + wide_to_utf8(name).c_str(), + GetLastError(), + wide_to_utf8(path).c_str()); + } + else + { + XDMA_LOG("open_subdevice: %s ready", wide_to_utf8(name).c_str()); + } + return h; + } + + xdma_status_t XdmaCaptureSession::set_input(gdriver_input_t input) + { + if (!opened_) + return XDMA_EINVAL; + input_ = input == GDRIVER_INPUT_UNKNOWN ? GDRIVER_INPUT_SDI : input; + stream_desc_.input = input_; + XDMA_LOG("set_input: input=%u", static_cast(input_)); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::get_device_info(xdma_device_info_t &out) const + { + if (!opened_) + return XDMA_ESTATE; + std::memset(&out, 0, sizeof(out)); + copy_string(wide_to_utf8(friendly_name_), out.friendly_name, sizeof(out.friendly_name)); + copy_string("XDMA", out.driver_version, sizeof(out.driver_version)); + out.supported_inputs_mask = (1u << GDRIVER_INPUT_SDI) | (1u << GDRIVER_INPUT_HDMI); + out.supported_pixel_formats_mask = (1u << GDRIVER_PIXFMT_YUY2) | + (1u << GDRIVER_PIXFMT_Y210) | + (1u << GDRIVER_PIXFMT_RGB24) | + (1u << GDRIVER_PIXFMT_NV12) | + (1u << GDRIVER_PIXFMT_P010) | + (1u << GDRIVER_PIXFMT_YUV444); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::get_signal_status(xdma_signal_status_t &out) const + { + if (!opened_) + return XDMA_ESTATE; + std::memset(&out, 0, sizeof(out)); + uint32_t width = 0; + uint32_t height = 0; + uint32_t rawFormat = 0; + uint32_t rawFrameRate = 0; + uint32_t rawBitDepth = 0; + uint32_t rawStatus = 0; + + // The current XDMA backend has no high-level signal IOCTL yet, so we + // read the FPGA signal registers directly. Empty width/height means + // the FPGA is not reporting a usable signal. + const bool formatOk = read_user_reg(kVideoFormatReg, rawFormat); + const bool widthOk = read_user_reg(kVideoWidthReg, width); + const bool heightOk = read_user_reg(kVideoHeightReg, height); + const bool frameRateOk = read_user_reg(kVideoFrameRateReg, rawFrameRate); + const bool bitDepthOk = read_user_reg(kVideoBitDepthReg, rawBitDepth); + const bool statusOk = read_user_reg(kFpgaStatusReg, rawStatus); + + const uint32_t signalBitDepth = bitDepthOk ? decode_bit_depth(rawBitDepth, 8) : 0; + const gdriver_pixel_format_t pixelFormat = formatOk ? decode_pixel_format(rawFormat, signalBitDepth) : stream_desc_.pixel_format; + const uint32_t bufferBitDepth = bit_depth_for_pixfmt(pixelFormat); + + XDMA_LOG("signal: fmt_ok=%d fmt_raw=0x%x fps_ok=%d fps_raw=0x%x bit_ok=%d bit_raw=%u status_ok=%d status=0x%08x width_ok=%d width=%u height_ok=%d height=%u configured=%ux%u fmt=%u", + formatOk ? 1 : 0, + rawFormat, + frameRateOk ? 1 : 0, + rawFrameRate, + bitDepthOk ? 1 : 0, + rawBitDepth, + statusOk ? 1 : 0, + rawStatus, + widthOk ? 1 : 0, + width, + heightOk ? 1 : 0, + height, + stream_desc_.width, + stream_desc_.height, + static_cast(stream_desc_.pixel_format)); + + const bool haveSignalSize = widthOk && heightOk && width != 0 && height != 0; + const bool sdiLocked = statusOk ? ((rawStatus & bit_n(0)) != 0) : haveSignalSize; + const bool hdmiLocked = statusOk ? ((rawStatus & bit_n(2)) != 0) : haveSignalSize; + out.signal_locked = (input_ == GDRIVER_INPUT_HDMI ? hdmiLocked : sdiLocked) ? 1 : 0; + out.input = input_; + out.width = haveSignalSize ? width : 0; + out.height = haveSignalSize ? height : 0; + out.pixel_format = pixelFormat; + out.bit_depth = bufferBitDepth; + out.fpga_valid_mask = (formatOk ? bit_n(0) : 0u) | + (frameRateOk ? bit_n(1) : 0u) | + (bitDepthOk ? bit_n(2) : 0u) | + (statusOk ? bit_n(3) : 0u); + out.fpga_width_valid = widthOk ? 1u : 0u; + out.fpga_height_valid = heightOk ? 1u : 0u; + out.fpga_width_raw = width; + out.fpga_height_raw = height; + out.fpga_video_format_raw = rawFormat; + out.fpga_frame_rate_raw = rawFrameRate; + out.fpga_bit_depth_raw = rawBitDepth; + out.fpga_status_raw = rawStatus; + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::get_stream_stats(xdma_stream_stats_t &out) const + { + std::lock_guard lock(mutex_); + out = stats_; + out.state = running_ ? GDRIVER_STREAM_RUNNING : (configured_ ? GDRIVER_STREAM_CONFIGURED : GDRIVER_STREAM_STOPPED); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::set_event_callback(xdma_event_callback_t callback, void *user, uint32_t eventMask) + { + std::lock_guard lock(event_callback_mutex_); + event_callback_ = callback; + event_callback_user_ = user; + event_mask_filter_ = eventMask ? eventMask : XDMA_EVENT_MASK_DEFAULT; + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::configure_stream(const xdma_stream_desc_t &desc) + { + if (!opened_) + return XDMA_ESTATE; + if (running_) + return XDMA_ESTATE; + if (desc.pixel_format != GDRIVER_PIXFMT_YUY2 && + desc.pixel_format != GDRIVER_PIXFMT_Y210 && + desc.pixel_format != GDRIVER_PIXFMT_RGB24 && + desc.pixel_format != GDRIVER_PIXFMT_NV12 && + desc.pixel_format != GDRIVER_PIXFMT_P010 && + desc.pixel_format != GDRIVER_PIXFMT_YUV444 && + desc.pixel_format != GDRIVER_PIXFMT_UNKNOWN) + return fail(XDMA_ENOTSUP, "configure_stream(pixel_format)", ERROR_NOT_SUPPORTED); + + XDMA_LOG("configure: request input=%u %ux%u fmt=%u buffers=%u mem=%u flags=0x%x", + static_cast(desc.input), + desc.width, + desc.height, + static_cast(desc.pixel_format), + desc.buffer_count, + static_cast(desc.memory_kind), + desc.flags); + + // Normalize the requested stream. The render path may support fewer + // formats than the FPGA, but the DMA frame size must follow the signal. + stream_desc_ = desc; + stream_desc_.input = desc.input == GDRIVER_INPUT_UNKNOWN ? input_ : desc.input; + stream_desc_.width = desc.width ? desc.width : kDefaultWidth; + stream_desc_.height = desc.height ? desc.height : kDefaultHeight; + stream_desc_.pixel_format = desc.pixel_format == GDRIVER_PIXFMT_UNKNOWN ? GDRIVER_PIXFMT_YUY2 : desc.pixel_format; + uint32_t rawBitDepth = 0; + stream_bit_depth_ = bit_depth_for_pixfmt(stream_desc_.pixel_format); + stream_desc_.buffer_count = desc.buffer_count ? desc.buffer_count : 1; + stream_desc_.memory_kind = GDRIVER_MEMORY_DRIVER_COPY; + configured_ = true; + + { + std::lock_guard lock(mutex_); + reset_stats(stats_, GDRIVER_STREAM_CONFIGURED); + latest_frame_.clear(); + delivery_frame_.clear(); + latest_sequence_ = 0; + delivered_sequence_ = 0; + wait_timeout_count_ = 0; + } + + XDMA_LOG("configure: effective input=%u path=%u %ux%u fmt=%u frame_bytes=%zu", + static_cast(stream_desc_.input), + active_input_path(), + stream_desc_.width, + stream_desc_.height, + static_cast(stream_desc_.pixel_format), + frame_size_bytes()); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::start_stream() + { + XDMA_LOG("start: begin opened=%d configured=%d running=%d", + opened_ ? 1 : 0, + configured_ ? 1 : 0, + running_ ? 1 : 0); + if (!opened_ || !configured_) + return XDMA_ESTATE; + if (running_) + return XDMA_OK; + + const uint32_t path = active_input_path(); + if (c2h_device_[path] == INVALID_HANDLE_VALUE) + return fail(XDMA_EIO, "c2h handle", ERROR_INVALID_HANDLE); + + for (uint32_t role = 0; role < kIrqRolesPerInput; ++role) + { + if (event_device_[role] != INVALID_HANDLE_VALUE) + { + CloseHandle(event_device_[role]); + event_device_[role] = INVALID_HANDLE_VALUE; + } + } + + // IRQ layout follows CaptureDemo: each input path owns four event + // bits: VIDEO_INT, AUDIO_INT, PLUG_IN, PLUG_OUT. + for (uint32_t role = 0; role < kIrqRolesPerInput; ++role) + { + if (!is_stream_event_role(role)) + continue; + + const std::wstring eventName = L"event_" + std::to_wstring(path * kIrqRolesPerInput + role); + event_device_[role] = open_subdevice(eventName.c_str()); + if (event_device_[role] == INVALID_HANDLE_VALUE) + { + for (uint32_t openedRole = 0; openedRole < kIrqRolesPerInput; ++openedRole) + { + if (event_device_[openedRole] != INVALID_HANDLE_VALUE) + { + CloseHandle(event_device_[openedRole]); + event_device_[openedRole] = INVALID_HANDLE_VALUE; + } + } + return fail(XDMA_EIO, "CreateFile(event)"); + } + } + + const size_t bytes = frame_size_bytes(); + if (bytes == 0) + return fail(XDMA_EINVAL, "frame_size_bytes", ERROR_INVALID_PARAMETER); + XDMA_LOG("start: input=%u path=%u event_mask=0x%08x capture_reg=0x%lx frame_bytes=%zu", + static_cast(stream_desc_.input), + path, + active_event_mask(), + capture_enable_reg(), + bytes); + + { + std::lock_guard lock(mutex_); + dma_buffer_.assign(bytes, 0); + latest_frame_.clear(); + delivery_frame_.clear(); + pending_events_ = 0; + latest_sequence_ = 0; + delivered_sequence_ = 0; + wait_timeout_count_ = 0; + stream_error_ = false; + reset_stats(stats_, GDRIVER_STREAM_RUNNING); + } + save_frames_after_plug_in_.store(0); + fix_pulsed_after_plug_in_.store(false); + + // Match CaptureDemo's hot-plug-safe startup order: make the event/data + // workers ready first, then clear stale IRQs, toggle capture, and only + // then enable user interrupt delivery. + running_ = true; + capture_active_ = true; + try + { + for (uint32_t role = 0; role < kIrqRolesPerInput; ++role) + { + if (!is_stream_event_role(role)) + continue; + + const uint32_t irqBit = path * kIrqRolesPerInput + role; + event_thread_[role] = std::thread([this, role, irqBit]() + { + try + { + event_thread_proc(role, irqBit); + } + catch (...) + { + running_ = false; + capture_active_ = false; + data_cv_.notify_all(); + frame_cv_.notify_all(); + } + }); + } + if (!start_data_worker()) + throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); + + Sleep(10); + XDMA_LOG("start: clear event mask=0x%08x", active_event_mask()); + write_user_reg(kInterruptClearReg, active_event_mask()); + write_user_reg(kInterruptClearReg, 0); + XDMA_LOG("start: capture disable reg=0x%lx", capture_enable_reg()); + write_user_reg(capture_enable_reg(), 0); + XDMA_LOG("start: capture enable reg=0x%lx", capture_enable_reg()); + write_user_reg(capture_enable_reg(), 1); + if (!enable_user_event(active_event_mask())) + throw std::system_error(std::make_error_code(std::errc::io_error)); + XDMA_LOG("start: user event enabled mask=0x%08x", active_event_mask()); + } + catch (const std::system_error &) + { + running_ = false; + capture_active_ = false; + disable_user_event(active_event_mask()); + write_user_reg(capture_enable_reg(), 0); + for (HANDLE h : event_device_) + { + if (h != INVALID_HANDLE_VALUE) + CancelIoEx(h, nullptr); + } + if (c2h_device_[path] != INVALID_HANDLE_VALUE) + CancelIoEx(c2h_device_[path], nullptr); + data_cv_.notify_all(); + frame_cv_.notify_all(); + for (std::thread &thread : event_thread_) + { + if (thread.joinable()) + thread.join(); + } + stop_data_worker(); + return fail(XDMA_EIO, "start worker thread", ERROR_NOT_ENOUGH_MEMORY); + } + XDMA_LOG("start: threads launched"); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::stop_stream() + { + const bool wasRunning = running_.exchange(false); + capture_active_ = false; + XDMA_LOG("stop: begin was_running=%d", wasRunning ? 1 : 0); + if (!wasRunning) + { + std::lock_guard lock(mutex_); + stats_.state = configured_ ? GDRIVER_STREAM_CONFIGURED : GDRIVER_STREAM_STOPPED; + XDMA_LOG("stop: no active stream state=%u", static_cast(stats_.state)); + return XDMA_OK; + } + + // Stop in the reverse direction: disable IRQ/capture first, then cancel + // blocking ReadFile calls so worker threads can exit and join cleanly. + XDMA_LOG("stop: disable event mask=0x%08x capture_reg=0x%lx", active_event_mask(), capture_enable_reg()); + disable_user_event(active_event_mask()); + write_user_reg(capture_enable_reg(), 0); + + for (HANDLE h : event_device_) + { + if (h != INVALID_HANDLE_VALUE) + CancelIoEx(h, nullptr); + } + const uint32_t path = active_input_path(); + if (c2h_device_[path] != INVALID_HANDLE_VALUE) + CancelIoEx(c2h_device_[path], nullptr); + + { + std::lock_guard lock(mutex_); + pending_events_ = 0; + } + data_cv_.notify_all(); + frame_cv_.notify_all(); + + for (std::thread &thread : event_thread_) + { + if (thread.joinable()) + thread.join(); + } + stop_data_worker(); + + std::lock_guard lock(mutex_); + stats_.state = configured_ ? GDRIVER_STREAM_CONFIGURED : GDRIVER_STREAM_STOPPED; + XDMA_LOG("stop: done captured=%llu delivered=%llu interrupts=%llu dma_errors=%llu", + static_cast(stats_.frames_captured), + static_cast(stats_.frames_delivered), + static_cast(stats_.interrupt_count), + static_cast(stats_.dma_errors)); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::wait_frame(uint32_t timeoutMs, xdma_frame_t &out) + { + std::unique_lock lock(mutex_); + std::memset(&out, 0, sizeof(out)); + if (!running_) + return XDMA_ESTATE; + + const auto hasFrame = [this]() + { + return latest_sequence_ > delivered_sequence_ || stream_error_ || !running_; + }; + + if (timeoutMs == 0) + { + frame_cv_.wait(lock, hasFrame); + } + else if (!frame_cv_.wait_for(lock, std::chrono::milliseconds(timeoutMs), hasFrame)) + { + ++wait_timeout_count_; + if (should_log_counter(wait_timeout_count_)) + XDMA_LOG("wait_frame: timeout count=%llu timeout_ms=%u latest=%llu delivered=%llu running=%d stream_error=%d", + static_cast(wait_timeout_count_), + timeoutMs, + static_cast(latest_sequence_), + static_cast(delivered_sequence_), + running_ ? 1 : 0, + stream_error_ ? 1 : 0); + return XDMA_ETIMEOUT; + } + + if (!running_ && latest_sequence_ <= delivered_sequence_) + { + XDMA_LOG("wait_frame: stopped without pending frame"); + return XDMA_ESTATE; + } + if (stream_error_ && latest_sequence_ <= delivered_sequence_) + { + XDMA_LOG("wait_frame: stream error latest=%llu delivered=%llu", + static_cast(latest_sequence_), + static_cast(delivered_sequence_)); + return XDMA_EIO; + } + if (latest_sequence_ <= delivered_sequence_) + return XDMA_ETIMEOUT; + + // Return a stable pointer to delivery_frame_. The pointer is valid + // until the next wait_frame() on this same session or close(). + delivery_frame_ = latest_frame_; + delivered_sequence_ = latest_sequence_; + ++stats_.frames_delivered; + + out.data = delivery_frame_.data(); + out.data_size_bytes = delivery_frame_.size(); + out.frame_id = delivered_sequence_; + out.timestamp_ns = static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count()); + out.width = stream_desc_.width; + out.height = stream_desc_.height; + out.pixel_format = stream_desc_.pixel_format; + out.bit_depth = stream_bit_depth_; + out.plane_count = plane_count_for_pixfmt(stream_desc_.pixel_format); + out.plane_offset_bytes[0] = 0; + out.plane_stride_bytes[0] = plane_stride_for_pixfmt(stream_desc_.width, stream_desc_.pixel_format, stream_bit_depth_); + if (out.plane_count > 1) + { + out.plane_offset_bytes[1] = out.plane_stride_bytes[0] * stream_desc_.height; + out.plane_stride_bytes[1] = out.plane_stride_bytes[0]; + } + out.driver_buffer_index = 0; + out.flags = 0; + if (should_log_counter(out.frame_id)) + XDMA_LOG("wait_frame: deliver id=%llu bytes=%zu %ux%u stride=%u captured=%llu delivered=%llu", + static_cast(out.frame_id), + out.data_size_bytes, + out.width, + out.height, + out.plane_stride_bytes[0], + static_cast(stats_.frames_captured), + static_cast(stats_.frames_delivered)); + return XDMA_OK; + } + + xdma_status_t XdmaCaptureSession::release_frame(const xdma_frame_t &) + { + return XDMA_OK; + } + + void XdmaCaptureSession::emit_event(xdma_event_type_t type, uint32_t irqBit, uint32_t irqMask) const + { + xdma_event_callback_t callback = nullptr; + void *user = nullptr; + { + std::lock_guard lock(event_callback_mutex_); + const uint32_t typeMask = event_mask_for_type(type); + if (!event_callback_ || typeMask == 0 || (event_mask_filter_ & typeMask) == 0) + return; + callback = event_callback_; + user = event_callback_user_; + } + + xdma_event_t event{}; + event.type = type; + event.irq_bit = irqBit; + event.irq_mask = irqMask; + event.timestamp_ns = steady_now_ns(); + callback(&event, user); + } + + void XdmaCaptureSession::event_thread_proc(uint32_t role, uint32_t irqBit) + { + const uint32_t mask = bit_n(irqBit); + XDMA_LOG("event_thread: start role=%u irq=%u mask=0x%08x", role, irqBit, mask); + while (running_) + { + uint8_t value = 0; + + // Blocking read from event_N. The XDMA driver completes this read + // when the FPGA raises the selected user interrupt. + const int ret = read_device(event_device_[role], 0, 1, &value); + if (!running_) + break; + if (ret < 0) + { + fail(XDMA_EIO, "ReadFile(event)"); + std::lock_guard lock(mutex_); + stream_error_ = true; + ++stats_.dma_errors; + frame_cv_.notify_all(); + break; + } + + uint64_t interruptCount = 0; + { + std::lock_guard lock(mutex_); + ++stats_.interrupt_count; + interruptCount = stats_.interrupt_count; + } + + if (role == kPlugOutIrqRole) + { + XDMA_HOTPLUG_LOG("PLUG_OUT IRQ input=%u path=%u irq=%u mask=0x%08x value=%u interrupt_count=%llu active=%d running=%d", + static_cast(stream_desc_.input), + active_input_path(), + irqBit, + mask, + static_cast(value), + static_cast(interruptCount), + capture_active_.load() ? 1 : 0, + running_.load() ? 1 : 0); + XDMA_LOG("event_thread: PLUG_OUT irq=%u value=%u", irqBit, static_cast(value)); + emit_event(XDMA_EVENT_PLUG_OUT, irqBit, mask); + pause_capture_for_plug_out(); + continue; + } + + if (role == kPlugInIrqRole) + { + XDMA_HOTPLUG_LOG("PLUG_IN IRQ input=%u path=%u irq=%u mask=0x%08x value=%u interrupt_count=%llu active=%d running=%d", + static_cast(stream_desc_.input), + active_input_path(), + irqBit, + mask, + static_cast(value), + static_cast(interruptCount), + capture_active_.load() ? 1 : 0, + running_.load() ? 1 : 0); + XDMA_LOG("event_thread: PLUG_IN irq=%u value=%u", irqBit, static_cast(value)); + emit_event(XDMA_EVENT_PLUG_IN, irqBit, mask); + resume_capture_after_plug_in(); + continue; + } + + if (role != kVideoIrqRole) + { + write_user_reg(kInterruptClearReg, mask); + write_user_reg(kInterruptClearReg, 0); + if (capture_active_) + enable_user_event(mask); + else + enable_user_event(plug_in_event_mask()); + continue; + } + + uint32_t pending = 0; + if (capture_active_) + { + std::lock_guard lock(mutex_); + ++pending_events_; + pending = pending_events_; + } + else + { + write_user_reg(kInterruptClearReg, mask); + write_user_reg(kInterruptClearReg, 0); + enable_user_event(plug_in_event_mask()); + continue; + } + + if (should_log_counter(interruptCount)) + XDMA_LOG("event_thread: irq=%llu role=%u value=%u pending=%u", + static_cast(interruptCount), + role, + static_cast(value), + pending); + emit_event(XDMA_EVENT_VIDEO_IRQ, irqBit, mask); + data_cv_.notify_one(); + } + XDMA_LOG("event_thread: exit role=%u running=%d", role, running_ ? 1 : 0); + } + + void XdmaCaptureSession::data_thread_proc() + { + XDMA_LOG("data_thread: start input=%u path=%u frame_bytes=%zu", + static_cast(stream_desc_.input), + active_input_path(), + frame_size_bytes()); + uint64_t readCount = 0; + while (running_ && !data_worker_stop_) + { + uint32_t pendingAfterPop = 0; + { + std::unique_lock lock(mutex_); + data_cv_.wait(lock, [this]() + { return (capture_active_ && pending_events_ > 0) || !running_ || data_worker_stop_; }); + if (!running_ || data_worker_stop_) + break; + if (!capture_active_) + continue; + --pending_events_; + pendingAfterPop = pending_events_; + } + + ++readCount; + if (should_log_counter(readCount)) + XDMA_LOG("data_thread: event consumed read=%llu pending=%u clear_reg=0x%lx mask=0x%08x", + static_cast(readCount), + pendingAfterPop, + kInterruptClearReg, + video_event_mask()); + // A VIDEO_INT means one frame is ready in C2H. Acknowledge the FPGA + // interrupt, re-enable XDMA user interrupt delivery, then read the + // full video frame from c2h_N. + write_user_reg(kInterruptClearReg, video_event_mask()); + write_user_reg(kInterruptClearReg, 0); + enable_user_event(video_event_mask()); + + if (!capture_active_) + continue; + + const DWORD bytes = static_cast(frame_size_bytes()); + if (dma_buffer_.size() < bytes) + { + std::lock_guard lock(mutex_); + if (dma_buffer_.size() < bytes) + dma_buffer_.resize(bytes); + } + const int ret = read_device(c2h_device_[active_input_path()], 0, bytes, dma_buffer_.data()); + + if (!running_) + break; + if (!capture_active_) + continue; + if (ret < 0 || static_cast(ret) != bytes) + { + fail(XDMA_EIO, "ReadFile(c2h)"); + std::lock_guard lock(mutex_); + stream_error_ = true; + ++stats_.dma_errors; + frame_cv_.notify_all(); + break; + } + + handle_plug_in_frame_fix(dma_buffer_.data(), static_cast(ret)); + + std::lock_guard lock(mutex_); + publish_frame(dma_buffer_.data(), static_cast(ret)); + } + XDMA_LOG("data_thread: exit running=%d", running_ ? 1 : 0); + } + + bool XdmaCaptureSession::start_data_worker() + { + std::lock_guard lock(worker_mutex_); + if (data_thread_.joinable()) + return true; + + data_worker_stop_ = false; + try + { + data_thread_ = std::thread([this]() + { + try + { + data_thread_proc(); + } + catch (...) + { + running_ = false; + capture_active_ = false; + frame_cv_.notify_all(); + } + }); + return true; + } + catch (const std::system_error &) + { + return false; + } + } + + void XdmaCaptureSession::stop_data_worker() + { + data_worker_stop_ = true; + const uint32_t path = active_input_path(); + if (c2h_device_[path] != INVALID_HANDLE_VALUE) + CancelIoEx(c2h_device_[path], nullptr); + data_cv_.notify_all(); + + std::thread thread; + { + std::lock_guard lock(worker_mutex_); + if (!data_thread_.joinable()) + return; + thread = std::move(data_thread_); + } + + if (thread.joinable()) + thread.join(); + } + + void XdmaCaptureSession::pause_capture_for_plug_out() + { + if (!capture_active_.exchange(false)) + { + const bool clearHighOk = write_user_reg(kInterruptClearReg, plug_out_event_mask()); + const bool clearLowOk = write_user_reg(kInterruptClearReg, 0); + const bool enablePlugInOk = enable_user_event(plug_in_event_mask()); + XDMA_HOTPLUG_LOG("PLUG_OUT pause skipped input=%u path=%u already_inactive clear_out=%d/%d enable_plug_in=%d", + static_cast(stream_desc_.input), + active_input_path(), + clearHighOk ? 1 : 0, + clearLowOk ? 1 : 0, + enablePlugInOk ? 1 : 0); + return; + } + + XDMA_HOTPLUG_LOG("PLUG_OUT pause begin input=%u path=%u active_mask=0x%08x video_mask=0x%08x plug_in_mask=0x%08x plug_out_mask=0x%08x capture_reg=0x%lx", + static_cast(stream_desc_.input), + active_input_path(), + active_event_mask(), + video_event_mask(), + plug_in_event_mask(), + plug_out_event_mask(), + capture_enable_reg()); + XDMA_LOG("hotplug: plug-out pause input=%u path=%u active_mask=0x%08x plug_in_mask=0x%08x", + static_cast(stream_desc_.input), + active_input_path(), + active_event_mask(), + plug_in_event_mask()); + + const bool captureOffOk = write_user_reg(capture_enable_reg(), 0); + const bool disableActiveOk = disable_user_event(active_event_mask()); + const bool clearActiveHighOk = write_user_reg(kInterruptClearReg, active_event_mask()); + const bool clearActiveLowOk = write_user_reg(kInterruptClearReg, 0); + const bool enablePlugInOk = enable_user_event(plug_in_event_mask()); + + // Firmware raises the next PLUG_IN IRQ only while capture-enable is high. + const bool captureArmedOk = write_user_reg(capture_enable_reg(), running_ ? 1u : 0u); + XDMA_HOTPLUG_LOG("PLUG_OUT pause regs input=%u path=%u capture_off=%d disable_active=%d clear_active=%d/%d enable_plug_in=%d capture_armed=%d armed_value=%u", + static_cast(stream_desc_.input), + active_input_path(), + captureOffOk ? 1 : 0, + disableActiveOk ? 1 : 0, + clearActiveHighOk ? 1 : 0, + clearActiveLowOk ? 1 : 0, + enablePlugInOk ? 1 : 0, + captureArmedOk ? 1 : 0, + running_.load() ? 1u : 0u); + + { + std::lock_guard lock(mutex_); + pending_events_ = 0; + } + stop_data_worker(); + uint64_t latestAfterPause = 0; + uint64_t deliveredAfterPause = 0; + { + std::lock_guard lock(mutex_); + dma_buffer_.clear(); + latest_frame_.clear(); + delivery_frame_.clear(); + latest_sequence_ = delivered_sequence_; + latestAfterPause = latest_sequence_; + deliveredAfterPause = delivered_sequence_; + } + frame_cv_.notify_all(); + emit_event(XDMA_EVENT_CAPTURE_PAUSED, + active_input_path() * kIrqRolesPerInput + kPlugOutIrqRole, + plug_out_event_mask()); + XDMA_HOTPLUG_LOG("PLUG_OUT pause done input=%u path=%u active=%d data_worker_stop=%d latest_sequence=%llu delivered_sequence=%llu", + static_cast(stream_desc_.input), + active_input_path(), + capture_active_.load() ? 1 : 0, + data_worker_stop_.load() ? 1 : 0, + static_cast(latestAfterPause), + static_cast(deliveredAfterPause)); + } + + void XdmaCaptureSession::resume_capture_after_plug_in() + { + if (capture_active_.load()) + { + const bool clearHighOk = write_user_reg(kInterruptClearReg, plug_in_event_mask()); + const bool clearLowOk = write_user_reg(kInterruptClearReg, 0); + bool enableActiveOk = true; + if (running_) + enableActiveOk = enable_user_event(active_event_mask()); + XDMA_HOTPLUG_LOG("PLUG_IN resume skipped input=%u path=%u already_active clear_in=%d/%d enable_active=%d active_mask=0x%08x", + static_cast(stream_desc_.input), + active_input_path(), + clearHighOk ? 1 : 0, + clearLowOk ? 1 : 0, + enableActiveOk ? 1 : 0, + active_event_mask()); + return; + } + + save_frames_after_plug_in_.store(kPlugInScanFrames); + fix_pulsed_after_plug_in_.store(false); + + XDMA_HOTPLUG_LOG("PLUG_IN resume begin input=%u path=%u active_mask=0x%08x video_mask=0x%08x plug_in_mask=0x%08x plug_out_mask=0x%08x capture_reg=0x%lx scan_frames=%d", + static_cast(stream_desc_.input), + active_input_path(), + active_event_mask(), + video_event_mask(), + plug_in_event_mask(), + plug_out_event_mask(), + capture_enable_reg(), + kPlugInScanFrames); + XDMA_LOG("hotplug: plug-in resume input=%u path=%u active_mask=0x%08x", + static_cast(stream_desc_.input), + active_input_path(), + active_event_mask()); + + size_t allocatedBytes = 0; + { + std::lock_guard lock(mutex_); + const size_t bytes = frame_size_bytes(); + dma_buffer_.assign(bytes, 0); + allocatedBytes = bytes; + pending_events_ = 0; + stream_error_ = false; + stats_.state = GDRIVER_STREAM_RUNNING; + } + XDMA_HOTPLUG_LOG("PLUG_IN resume buffer input=%u path=%u frame_bytes=%zu", + static_cast(stream_desc_.input), + active_input_path(), + allocatedBytes); + + capture_active_ = true; + if (!start_data_worker()) + { + capture_active_ = false; + std::lock_guard lock(mutex_); + stream_error_ = true; + ++stats_.dma_errors; + frame_cv_.notify_all(); + XDMA_HOTPLUG_LOG("PLUG_IN resume failed input=%u path=%u start_data_worker=0", + static_cast(stream_desc_.input), + active_input_path()); + return; + } + Sleep(10); + + const bool captureOffOk = write_user_reg(capture_enable_reg(), 0); + const bool clearActiveHighOk = write_user_reg(kInterruptClearReg, active_event_mask()); + const bool clearActiveLowOk = write_user_reg(kInterruptClearReg, 0); + if (!running_) + { + XDMA_HOTPLUG_LOG("PLUG_IN resume aborted input=%u path=%u running=0 capture_off=%d clear_active=%d/%d", + static_cast(stream_desc_.input), + active_input_path(), + captureOffOk ? 1 : 0, + clearActiveHighOk ? 1 : 0, + clearActiveLowOk ? 1 : 0); + return; + } + const bool captureOnOk = write_user_reg(capture_enable_reg(), 1); + const bool enableActiveOk = enable_user_event(active_event_mask()); + data_cv_.notify_all(); + frame_cv_.notify_all(); + emit_event(XDMA_EVENT_CAPTURE_RESUMED, + active_input_path() * kIrqRolesPerInput + kPlugInIrqRole, + plug_in_event_mask()); + XDMA_HOTPLUG_LOG("PLUG_IN resume done input=%u path=%u capture_off=%d clear_active=%d/%d capture_on=%d enable_active=%d active=%d active_mask=0x%08x", + static_cast(stream_desc_.input), + active_input_path(), + captureOffOk ? 1 : 0, + clearActiveHighOk ? 1 : 0, + clearActiveLowOk ? 1 : 0, + captureOnOk ? 1 : 0, + enableActiveOk ? 1 : 0, + capture_active_.load() ? 1 : 0, + active_event_mask()); + } + + void XdmaCaptureSession::handle_plug_in_frame_fix(const uint8_t *data, size_t bytes) + { + int remaining = save_frames_after_plug_in_.load(); + if (remaining <= 0 || fix_pulsed_after_plug_in_.load()) + return; + + while (remaining > 0 && !save_frames_after_plug_in_.compare_exchange_weak(remaining, remaining - 1)) + { + } + if (remaining <= 0) + return; + + const size_t markerOffset = find_frame_marker_offset(data, bytes); + if (markerOffset >= bytes) + { + XDMA_HOTPLUG_LOG("PLUG_IN frame scan input=%u path=%u marker_not_found remaining_before=%d bytes=%zu", + static_cast(stream_desc_.input), + active_input_path(), + remaining, + bytes); + return; + } + + XDMA_HOTPLUG_LOG("PLUG_IN frame marker found input=%u path=%u offset=%zu remaining_before=%d bytes=%zu", + static_cast(stream_desc_.input), + active_input_path(), + markerOffset, + remaining, + bytes); + XDMA_LOG("hotplug: plug-in frame marker found offset=%zu remaining=%d", markerOffset, remaining); + pulse_plug_in_frame_fix(); + } + + void XdmaCaptureSession::pulse_plug_in_frame_fix() + { + bool expected = false; + if (!fix_pulsed_after_plug_in_.compare_exchange_strong(expected, true)) + return; + + uint32_t statusAfterHigh = 0; + uint32_t statusAfterLow = 0; + XDMA_LOG("hotplug: pulse PLUG_IN_FRAME_FIX reg=0x%lx", kPlugInFrameFixReg); + const bool highOk = write_user_reg(kPlugInFrameFixReg, 1); + std::atomic_thread_fence(std::memory_order_seq_cst); + const bool readHighOk = read_user_reg(kFpgaStatusReg, statusAfterHigh); + const bool lowOk = write_user_reg(kPlugInFrameFixReg, 0); + std::atomic_thread_fence(std::memory_order_seq_cst); + const bool readLowOk = read_user_reg(kFpgaStatusReg, statusAfterLow); + XDMA_HOTPLUG_LOG("PLUG_IN_FRAME_FIX pulse input=%u path=%u reg=0x%lx high=%d status_high=%d/0x%08x low=%d status_low=%d/0x%08x", + static_cast(stream_desc_.input), + active_input_path(), + kPlugInFrameFixReg, + highOk ? 1 : 0, + readHighOk ? 1 : 0, + statusAfterHigh, + lowOk ? 1 : 0, + readLowOk ? 1 : 0, + statusAfterLow); + } + + void XdmaCaptureSession::publish_frame(const uint8_t *data, size_t bytes) + { + // Keep only the newest frame. This makes wait_frame() simple and avoids + // unbounded queue growth if the consumer is slower than the device. + latest_frame_.assign(data, data + bytes); + ++latest_sequence_; + ++stats_.frames_captured; + stats_.state = GDRIVER_STREAM_RUNNING; + if (should_log_counter(latest_sequence_)) + XDMA_LOG("publish_frame: id=%llu bytes=%zu captured=%llu", + static_cast(latest_sequence_), + bytes, + static_cast(stats_.frames_captured)); + frame_cv_.notify_one(); + } + + int XdmaCaptureSession::read_device(HANDLE device, long address, DWORD size, uint8_t *buffer) const + { + if (device == INVALID_HANDLE_VALUE || !buffer) + return -1; + if (SetFilePointer(device, address, nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) + { + XDMA_LOG("read_device: SetFilePointer failed handle=%p addr=0x%lx size=%lu gle=%lu", + device, + address, + size, + GetLastError()); + return -3; + } + + // XDMA reads/writes are file operations at a BAR/DMA offset. Large + // transfers are split so a full HD/4K frame does not exceed the + // driver's per-request size limit. + DWORD done = 0; + DWORD offset = 0; + while (offset + kMaxBytesPerTransfer <= size) + { + if (!ReadFile(device, buffer + offset, kMaxBytesPerTransfer, &done, nullptr)) + { + XDMA_LOG("read_device: ReadFile chunk failed handle=%p addr=0x%lx offset=%lu size=%lu gle=%lu", + device, + address, + offset, + kMaxBytesPerTransfer, + GetLastError()); + return -1; + } + if (done != kMaxBytesPerTransfer) + { + XDMA_LOG("read_device: short chunk handle=%p addr=0x%lx offset=%lu got=%lu expected=%lu", + device, + address, + offset, + done, + kMaxBytesPerTransfer); + return -2; + } + offset += kMaxBytesPerTransfer; + } + + const DWORD remaining = size - offset; + if (remaining) + { + if (!ReadFile(device, buffer + offset, remaining, &done, nullptr)) + { + XDMA_LOG("read_device: ReadFile tail failed handle=%p addr=0x%lx offset=%lu size=%lu gle=%lu", + device, + address, + offset, + remaining, + GetLastError()); + return -1; + } + if (done != remaining) + { + XDMA_LOG("read_device: short tail handle=%p addr=0x%lx offset=%lu got=%lu expected=%lu", + device, + address, + offset, + done, + remaining); + return -2; + } + } + return static_cast(size); + } + + int XdmaCaptureSession::write_device(HANDLE device, long address, DWORD size, const uint8_t *buffer) const + { + if (device == INVALID_HANDLE_VALUE || !buffer) + return -1; + if (SetFilePointer(device, address, nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) + { + XDMA_LOG("write_device: SetFilePointer failed handle=%p addr=0x%lx size=%lu gle=%lu", + device, + address, + size, + GetLastError()); + return -3; + } + + DWORD done = 0; + DWORD offset = 0; + while (offset + kMaxBytesPerTransfer <= size) + { + if (!WriteFile(device, buffer + offset, kMaxBytesPerTransfer, &done, nullptr)) + { + XDMA_LOG("write_device: WriteFile chunk failed handle=%p addr=0x%lx offset=%lu size=%lu gle=%lu", + device, + address, + offset, + kMaxBytesPerTransfer, + GetLastError()); + return -1; + } + if (done != kMaxBytesPerTransfer) + { + XDMA_LOG("write_device: short chunk handle=%p addr=0x%lx offset=%lu got=%lu expected=%lu", + device, + address, + offset, + done, + kMaxBytesPerTransfer); + return -2; + } + offset += kMaxBytesPerTransfer; + } + + const DWORD remaining = size - offset; + if (remaining) + { + if (!WriteFile(device, buffer + offset, remaining, &done, nullptr)) + { + XDMA_LOG("write_device: WriteFile tail failed handle=%p addr=0x%lx offset=%lu size=%lu gle=%lu", + device, + address, + offset, + remaining, + GetLastError()); + return -1; + } + if (done != remaining) + { + XDMA_LOG("write_device: short tail handle=%p addr=0x%lx offset=%lu got=%lu expected=%lu", + device, + address, + offset, + done, + remaining); + return -2; + } + } + return static_cast(size); + } + + bool XdmaCaptureSession::read_user_reg(long address, uint32_t &out) const + { + out = 0; + // User BAR register read: SetFilePointer(user, address) + ReadFile(4). + const bool ok = read_device(user_device_, address, sizeof(out), reinterpret_cast(&out)) == sizeof(out); + if (!ok) + XDMA_LOG("read_user_reg: addr=0x%lx failed", address); + return ok; + } + + bool XdmaCaptureSession::write_user_reg(long address, uint32_t value) const + { + // User BAR register write: SetFilePointer(user, address) + WriteFile(4). + const bool ok = write_device(user_device_, address, sizeof(value), reinterpret_cast(&value)) == sizeof(value); + if (!ok) + XDMA_LOG("write_user_reg: addr=0x%lx value=0x%08x failed", address, value); + return ok; + } + + bool XdmaCaptureSession::enable_user_event(uint32_t mask) + { + static std::atomic enableLogCount{0}; + DWORD returned = 0; + // This is one of the few DeviceIoControl calls in the direct XDMA path: + // it tells the XDMA driver which user interrupt bits should wake event_N. + const bool ok = DeviceIoControl(user_device_, IOCTL_XDMA_USER_INT_ENABLE, + &mask, sizeof(mask), nullptr, 0, &returned, nullptr) != FALSE; + const uint64_t count = ++enableLogCount; + if (!ok || should_log_counter(count)) + XDMA_LOG("enable_user_event: count=%llu mask=0x%08x ok=%d gle=%lu", + static_cast(count), + mask, + ok ? 1 : 0, + ok ? 0 : GetLastError()); + return ok; + } + + bool XdmaCaptureSession::disable_user_event(uint32_t mask) + { + DWORD returned = 0; + const bool ok = DeviceIoControl(user_device_, IOCTL_XDMA_USER_INT_DISABLE, + &mask, sizeof(mask), nullptr, 0, &returned, nullptr) != FALSE; + XDMA_LOG("disable_user_event: mask=0x%08x ok=%d gle=%lu", mask, ok ? 1 : 0, ok ? 0 : GetLastError()); + return ok; + } + + xdma_status_t XdmaCaptureSession::fail(xdma_status_t status, const char *where, DWORD winerr) const + { + std::ostringstream oss; + oss << (where ? where : "XDMA") << " failed"; + if (winerr != NO_ERROR) + oss << ": " << win32_error(winerr) << " (" << winerr << ")"; + set_last_error(oss.str()); + XDMA_LOG("error: status=%u %s", static_cast(status), oss.str().c_str()); + return status; + } + + void XdmaCaptureSession::set_last_error(const std::string &message) const + { + std::lock_guard lock(mutex_); + last_error_ = message; + } + + void XdmaCaptureSession::clear_last_error() const + { + std::lock_guard lock(mutex_); + last_error_.clear(); + } + + const char *XdmaCaptureSession::last_error() const + { + std::lock_guard lock(mutex_); + return last_error_.c_str(); + } + + uint32_t XdmaCaptureSession::active_input_path() const + { + return stream_desc_.input == GDRIVER_INPUT_HDMI ? 1u : 0u; + } + + uint32_t XdmaCaptureSession::event_mask(uint32_t role) const + { + return bit_n(active_input_path() * kIrqRolesPerInput + role); + } + + uint32_t XdmaCaptureSession::video_event_mask() const + { + return event_mask(kVideoIrqRole); + } + + uint32_t XdmaCaptureSession::plug_in_event_mask() const + { + return event_mask(kPlugInIrqRole); + } + + uint32_t XdmaCaptureSession::plug_out_event_mask() const + { + return event_mask(kPlugOutIrqRole); + } + + uint32_t XdmaCaptureSession::active_event_mask() const + { + return video_event_mask() | plug_in_event_mask() | plug_out_event_mask(); + } + + long XdmaCaptureSession::capture_enable_reg() const + { + return active_input_path() == 0 ? kVideo0CaptureEnableReg : kVideo1CaptureEnableReg; + } + + size_t XdmaCaptureSession::frame_size_bytes() const + { + return bytes_per_frame(stream_desc_.width, stream_desc_.height, stream_desc_.pixel_format, stream_bit_depth_); + } +} diff --git a/sdk/gvfg/src/backend/xdma/xdma_capture_session.h b/sdk/gvfg/src/backend/xdma/xdma_capture_session.h new file mode 100644 index 0000000..52c4d1a --- /dev/null +++ b/sdk/gvfg/src/backend/xdma/xdma_capture_session.h @@ -0,0 +1,128 @@ +#pragma once + +#include "xdma_backend_types.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace gvfg::internal +{ + struct XdmaDevice + { + std::wstring interface_path; + std::wstring friendly_name; + }; + + std::vector enumerate_xdma_devices(); + + class XdmaCaptureSession + { + public: + XdmaCaptureSession(); + XdmaCaptureSession(const XdmaCaptureSession &) = delete; + XdmaCaptureSession &operator=(const XdmaCaptureSession &) = delete; + ~XdmaCaptureSession(); + + xdma_status_t open_default(); + xdma_status_t open_device_index(size_t deviceIndex); + xdma_status_t close(); + + xdma_status_t set_input(gdriver_input_t input); + xdma_status_t get_device_info(xdma_device_info_t &out) const; + xdma_status_t get_signal_status(xdma_signal_status_t &out) const; + xdma_status_t get_stream_stats(xdma_stream_stats_t &out) const; + + xdma_status_t set_event_callback(xdma_event_callback_t callback, void *user, uint32_t eventMask); + xdma_status_t configure_stream(const xdma_stream_desc_t &desc); + xdma_status_t start_stream(); + xdma_status_t stop_stream(); + xdma_status_t wait_frame(uint32_t timeoutMs, xdma_frame_t &out); + xdma_status_t release_frame(const xdma_frame_t &frame); + + const char *last_error() const; + + private: + xdma_status_t open_device(const XdmaDevice &device); + void close_handles(); + + HANDLE open_subdevice(const wchar_t *name) const; + int read_device(HANDLE device, long address, DWORD size, uint8_t *buffer) const; + int write_device(HANDLE device, long address, DWORD size, const uint8_t *buffer) const; + bool read_user_reg(long address, uint32_t &out) const; + bool write_user_reg(long address, uint32_t value) const; + bool enable_user_event(uint32_t mask); + bool disable_user_event(uint32_t mask); + + void event_thread_proc(uint32_t role, uint32_t irqBit); + void data_thread_proc(); + bool start_data_worker(); + void stop_data_worker(); + void publish_frame(const uint8_t *data, size_t bytes); + void pause_capture_for_plug_out(); + void resume_capture_after_plug_in(); + void handle_plug_in_frame_fix(const uint8_t *data, size_t bytes); + void pulse_plug_in_frame_fix(); + void emit_event(xdma_event_type_t type, uint32_t irqBit, uint32_t irqMask) const; + + xdma_status_t fail(xdma_status_t status, const char *where, DWORD winerr = GetLastError()) const; + void set_last_error(const std::string &message) const; + void clear_last_error() const; + + uint32_t active_input_path() const; + uint32_t event_mask(uint32_t role) const; + uint32_t video_event_mask() const; + uint32_t plug_in_event_mask() const; + uint32_t plug_out_event_mask() const; + uint32_t active_event_mask() const; + long capture_enable_reg() const; + size_t frame_size_bytes() const; + + std::wstring base_path_; + std::wstring friendly_name_; + + HANDLE user_device_ = INVALID_HANDLE_VALUE; + HANDLE c2h_device_[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE}; + HANDLE event_device_[4] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE}; + + xdma_stream_desc_t stream_desc_{}; + uint32_t stream_bit_depth_ = 8; + gdriver_input_t input_ = GDRIVER_INPUT_SDI; + bool opened_ = false; + bool configured_ = false; + + std::atomic running_{false}; + std::atomic capture_active_{false}; + std::atomic data_worker_stop_{false}; + std::atomic save_frames_after_plug_in_{0}; + std::atomic fix_pulsed_after_plug_in_{false}; + std::thread event_thread_[4]; + std::thread data_thread_; + + mutable std::mutex mutex_; + std::mutex worker_mutex_; + mutable std::mutex event_callback_mutex_; + std::condition_variable frame_cv_; + std::condition_variable data_cv_; + xdma_event_callback_t event_callback_ = nullptr; + void *event_callback_user_ = nullptr; + uint32_t event_mask_filter_ = XDMA_EVENT_MASK_DEFAULT; + uint32_t pending_events_ = 0; + std::vector dma_buffer_; + std::vector latest_frame_; + std::vector delivery_frame_; + uint64_t latest_sequence_ = 0; + uint64_t delivered_sequence_ = 0; + uint64_t wait_timeout_count_ = 0; + bool stream_error_ = false; + xdma_stream_stats_t stats_{}; + mutable std::string last_error_; + }; +} diff --git a/sdk/gvfg/src/backend/xdma/xdma_public.h b/sdk/gvfg/src/backend/xdma/xdma_public.h new file mode 100644 index 0000000..4f93fdd --- /dev/null +++ b/sdk/gvfg/src/backend/xdma/xdma_public.h @@ -0,0 +1,34 @@ +/* + * XDMA Driver public API + * + * This header mirrors the public IOCTL values exposed by the Xilinx XDMA + * Windows driver. The values are consumed by the GVFG internal XDMA backend. + */ + +#pragma once + +#include +#include + +#define XDMA_MAKE_VERSION(major, minor, patch) (((major) << 24) | ((minor) << 16) | (patch)) +#define XDMA_VERSION_MAJOR(version) (((uint32_t)(version) >> 24) & 0xff) +#define XDMA_VERSION_MINOR(version) (((uint32_t)(version) >> 16) & 0xff) +#define XDMA_VERSION_PATCH(version) ((uint32_t)(version) & 0xffff) + +#define XDMA_DRIVER_VERSION XDMA_MAKE_VERSION(1, 0, 0) + +#define XDMA_IOCTL(index) CTL_CODE(FILE_DEVICE_UNKNOWN, index, METHOD_BUFFERED, FILE_ANY_ACCESS) + +#define IOCTL_XDMA_GET_VERSION XDMA_IOCTL(0x0) +#define IOCTL_XDMA_PERF_START XDMA_IOCTL(0x1) +#define IOCTL_XDMA_PERF_STOP XDMA_IOCTL(0x2) +#define IOCTL_XDMA_PERF_GET XDMA_IOCTL(0x3) +#define IOCTL_XDMA_USER_INT_ENABLE XDMA_IOCTL(0x4) +#define IOCTL_XDMA_USER_INT_DISABLE XDMA_IOCTL(0x5) + +typedef struct XDMA_PERF_DATA +{ + UINT64 clockCycleCount; + UINT64 dataCycleCount; + UINT64 pendingCount; +} XDMA_PERF_DATA; diff --git a/sdk/gvfg/src/gcapture_log_bridge.cpp b/sdk/gvfg/src/gcapture_log_bridge.cpp new file mode 100644 index 0000000..d659419 --- /dev/null +++ b/sdk/gvfg/src/gcapture_log_bridge.cpp @@ -0,0 +1,62 @@ +#include "gcapture.h" + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +namespace gcap +{ + void log_message(gcap_log_level_t, const char *message_utf8) + { +#ifdef _WIN32 + const char *msg = message_utf8 ? message_utf8 : ""; + OutputDebugStringA(msg); + const size_t len = std::strlen(msg); + if (len == 0 || msg[len - 1] != '\n') + OutputDebugStringA("\n"); +#else + (void)message_utf8; +#endif + } + + void log_message_w(gcap_log_level_t level, const wchar_t *message_wide) + { +#ifdef _WIN32 + if (!message_wide) + { + log_message(level, ""); + return; + } + const int needed = WideCharToMultiByte(CP_UTF8, 0, message_wide, -1, nullptr, 0, nullptr, nullptr); + if (needed <= 0) + return; + std::string utf8(static_cast(needed - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, message_wide, -1, utf8.data(), needed, nullptr, nullptr); + log_message(level, utf8.c_str()); +#else + (void)level; + (void)message_wide; +#endif + } + + void log_printf(gcap_log_level_t level, const char *fmt, ...) + { + if (!fmt) + { + log_message(level, ""); + return; + } + + char buf[1024]; + va_list args; + va_start(args, fmt); + std::vsnprintf(buf, sizeof(buf), fmt, args); + va_end(args); + log_message(level, buf); + } +} diff --git a/sdk/gvfg/src/gvfg_capture.cpp b/sdk/gvfg/src/gvfg_capture.cpp new file mode 100644 index 0000000..1230e46 --- /dev/null +++ b/sdk/gvfg/src/gvfg_capture.cpp @@ -0,0 +1,1145 @@ +#include "gvfg_capture.h" + +#include "gcapture.h" +#include "pipeline/shared_scene_pipeline.h" +#include "xdma_capture_session.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace +{ + void copy_cstr(char *dst, size_t dstSize, const char *src) + { + if (!dst || dstSize == 0) + return; + dst[0] = 0; + if (src) + strncpy_s(dst, dstSize, src, _TRUNCATE); + } + + uint64_t now_ns() + { + const auto now = std::chrono::steady_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(now).count()); + } + + gvfg_status_t map_status(xdma_status_t st) + { + switch (st) + { + case XDMA_OK: + return GVFG_OK; + case XDMA_EINVAL: + return GVFG_EINVAL; + case XDMA_ENODEV: + return GVFG_ENODEV; + case XDMA_ESTATE: + return GVFG_ESTATE; + case XDMA_ETIMEOUT: + return GVFG_ETIMEOUT; + case XDMA_ENOTSUP: + return GVFG_ENOTSUP; + case XDMA_EIO: + default: + return GVFG_EIO; + } + } + + const char *xdma_status_text(xdma_status_t st) + { + switch (st) + { + case XDMA_OK: + return "ok"; + case XDMA_EINVAL: + return "invalid argument"; + case XDMA_ENODEV: + return "device not found"; + case XDMA_ESTATE: + return "invalid state"; + case XDMA_ENOTSUP: + return "not supported"; + case XDMA_ETIMEOUT: + return "timeout"; + case XDMA_EIO: + return "i/o error"; + case XDMA_EABI: + return "abi mismatch"; + default: + return "unknown"; + } + } + + const char *xdma_error_text(xdma_status_t st, const gvfg::internal::XdmaCaptureSession *session) + { + const char *detail = session ? session->last_error() : nullptr; + if (detail && detail[0]) + return detail; + return xdma_status_text(st); + } + + void copy_wide_to_utf8(const std::wstring &src, char *dst, size_t dstSize) + { + if (!dst || dstSize == 0) + return; + dst[0] = '\0'; + if (src.empty()) + return; + WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, dst, static_cast(dstSize), nullptr, nullptr); + dst[dstSize - 1] = '\0'; + } + + gvfg_event_type_t map_event_type(xdma_event_type_t type) + { + switch (type) + { + case XDMA_EVENT_VIDEO_IRQ: + return GVFG_EVENT_VIDEO_IRQ; + case XDMA_EVENT_PLUG_IN: + return GVFG_EVENT_PLUG_IN; + case XDMA_EVENT_PLUG_OUT: + return GVFG_EVENT_PLUG_OUT; + case XDMA_EVENT_CAPTURE_PAUSED: + return GVFG_EVENT_CAPTURE_PAUSED; + case XDMA_EVENT_CAPTURE_RESUMED: + return GVFG_EVENT_CAPTURE_RESUMED; + default: + return GVFG_EVENT_VIDEO_IRQ; + } + } + + uint32_t map_event_mask_to_xdma(uint32_t mask) + { + const uint32_t effective = mask ? mask : GVFG_EVENT_MASK_DEFAULT; + uint32_t out = 0; + if (effective & GVFG_EVENT_MASK_VIDEO_IRQ) + out |= XDMA_EVENT_MASK_VIDEO_IRQ; + if (effective & GVFG_EVENT_MASK_PLUG_IN) + out |= XDMA_EVENT_MASK_PLUG_IN; + if (effective & GVFG_EVENT_MASK_PLUG_OUT) + out |= XDMA_EVENT_MASK_PLUG_OUT; + if (effective & GVFG_EVENT_MASK_CAPTURE_PAUSED) + out |= XDMA_EVENT_MASK_CAPTURE_PAUSED; + if (effective & GVFG_EVENT_MASK_CAPTURE_RESUMED) + out |= XDMA_EVENT_MASK_CAPTURE_RESUMED; + return out ? out : XDMA_EVENT_MASK_DEFAULT; + } + + const char *dxgi_format_name(DXGI_FORMAT fmt) + { + switch (fmt) + { + case DXGI_FORMAT_UNKNOWN: + return "UNKNOWN"; + case DXGI_FORMAT_B8G8R8A8_UNORM: + return "B8G8R8A8_UNORM"; + case DXGI_FORMAT_R10G10B10A2_UNORM: + return "R10G10B10A2_UNORM"; + case DXGI_FORMAT_R16G16B16A16_FLOAT: + return "R16G16B16A16_FLOAT"; + default: + return "DXGI_FORMAT_OTHER"; + } + } + + const char *gdriver_pixel_format_name(gdriver_pixel_format_t fmt) + { + switch (fmt) + { + case GDRIVER_PIXFMT_YUY2: + return "YUY2"; + case GDRIVER_PIXFMT_Y210: + return "Y210"; + case GDRIVER_PIXFMT_RGB24: + return "RGB24"; + case GDRIVER_PIXFMT_NV12: + return "NV12"; + case GDRIVER_PIXFMT_P010: + return "P010"; + case GDRIVER_PIXFMT_YUV444: + return "YUV444"; + default: + return "UNKNOWN"; + } + } + + bool fpga_field_valid(uint32_t mask, int bit) + { + return (mask & (1u << bit)) != 0; + } + + const char *fpga_video_format_name(uint32_t value) + { + switch (value & 0x3u) + { + case 0: + return "YUV422"; + case 1: + return "RGB"; + case 2: + return "YUV444"; + case 3: + return "YUV420"; + default: + return "UNKNOWN"; + } + } + + const char *fpga_frame_rate_name(uint32_t value) + { + switch (value & 0x0fu) + { + case 0x0: + return "None"; + case 0x2: + return "23.98"; + case 0x3: + return "24"; + case 0x4: + return "47.95"; + case 0x5: + return "25"; + case 0x6: + return "29.97"; + case 0x7: + return "30"; + case 0x8: + return "48"; + case 0x9: + return "50"; + case 0xa: + return "59.94"; + case 0xb: + return "60"; + default: + return "--"; + } + } + + void copy_binary4(char *dst, size_t dstSize, uint32_t value) + { + if (!dst || dstSize == 0) + return; + const uint32_t code = value & 0x0fu; + char bits[5] = {}; + for (int i = 0; i < 4; ++i) + bits[i] = (code & (1u << (3 - i))) ? '1' : '0'; + bits[4] = '\0'; + copy_cstr(dst, dstSize, bits); + } + + int clamp_u8(int v) + { + return (std::max)(0, (std::min)(255, v)); + } + + void yuv_to_rgb(int y, int u, int v, uint8_t &r, uint8_t &g, uint8_t &b) + { + const int c = y - 16; + const int d = u - 128; + const int e = v - 128; + r = static_cast(clamp_u8((298 * c + 409 * e + 128) >> 8)); + g = static_cast(clamp_u8((298 * c - 100 * d - 208 * e + 128) >> 8)); + b = static_cast(clamp_u8((298 * c + 516 * d + 128) >> 8)); + } +} + +struct gvfg_handle_t +{ + ~gvfg_handle_t() + { + close(); + } + + gvfg_status_t open(int index) + { + if (index < 0) + return GVFG_EINVAL; + + close(); + + backend = std::make_unique(); + const xdma_status_t stOpen = backend->open_device_index(static_cast(index)); + if (stOpen != XDMA_OK) + { + emitError(map_status(stOpen), xdma_error_text(stOpen, backend.get())); + backend.reset(); + return map_status(stOpen); + } + + currentIndex = index; + syncBackendEventCallback(); + selectedInput = GDRIVER_INPUT_SDI; + resetRuntimeCounters(); + const xdma_status_t stInput = backend->set_input(selectedInput); + if (stInput != XDMA_OK) + { + emitError(map_status(stInput), xdma_error_text(stInput, backend.get())); + close(); + return map_status(stInput); + } + + querySignal(); + return GVFG_OK; + } + + gvfg_status_t start() + { + if (!backend) + return GVFG_ESTATE; + if (running) + return GVFG_OK; + + const gvfg_status_t cfg = configureStream(); + if (cfg != GVFG_OK) + return cfg; + + if (previewHwnd && !createRenderPipeline()) + emitError(GVFG_ENOTSUP, "GVFG preview pipeline unavailable"); + + resetRuntimeCounters(); + const xdma_status_t st = backend->start_stream(); + if (st != XDMA_OK) + { + emitError(map_status(st), xdma_error_text(st, backend.get())); + return map_status(st); + } + + running = true; + captureThread = std::thread([this]() + { captureLoop(); }); + return GVFG_OK; + } + + gvfg_status_t stop() + { + running = false; + if (captureThread.joinable()) + captureThread.join(); + if (backend) + backend->stop_stream(); + return GVFG_OK; + } + + void close() + { + stop(); + releaseRenderPipeline(); + if (backend) + { + backend->set_event_callback(nullptr, nullptr, 0); + backend->close(); + backend.reset(); + } + currentIndex = -1; + } + + gvfg_status_t setEventCallback(gvfg_on_event_cb callback, void *user, uint32_t mask) + { + onEvent = callback; + eventCallbackUser = user; + eventMask = mask ? mask : GVFG_EVENT_MASK_DEFAULT; + syncBackendEventCallback(); + return GVFG_OK; + } + + gvfg_status_t setPreview(const gvfg_preview_desc_t &desc) + { + previewDesc = desc; + previewHwnd = desc.enable_preview ? desc.hwnd : nullptr; + if (pipeline) + pipeline->configurePreview(toGcapPreviewDesc()); + if (previewHwnd && width > 0 && height > 0) + createRenderPipeline(); + return GVFG_OK; + } + + gvfg_status_t getSignalStatus(gvfg_signal_status_t &out) + { + std::memset(&out, 0, sizeof(out)); + querySignal(); + bool haveSignalSize = false; + { + std::lock_guard lock(stateMutex); + haveSignalSize = fpgaWidthValid && fpgaHeightValid && fpgaWidthRaw != 0 && fpgaHeightRaw != 0; + out.width = haveSignalSize ? static_cast(fpgaWidthRaw) : 0; + out.height = haveSignalSize ? static_cast(fpgaHeightRaw) : 0; + out.fps = 0.0; + out.bit_depth = static_cast(bitDepth ? bitDepth : 8); + copy_cstr(out.pixel_format, sizeof(out.pixel_format), gdriver_pixel_format_name(pixelFormat)); + out.fpga.valid_mask = fpgaValidMask; + out.fpga.width_valid = fpgaWidthValid ? 1 : 0; + out.fpga.height_valid = fpgaHeightValid ? 1 : 0; + out.fpga.width_raw = fpgaWidthRaw; + out.fpga.height_raw = fpgaHeightRaw; + out.fpga.video_format_raw = fpgaVideoFormatRaw; + out.fpga.video_format_valid = fpga_field_valid(fpgaValidMask, 0) ? 1 : 0; + out.fpga.video_format_code = static_cast(fpgaVideoFormatRaw & 0x3u); + copy_cstr(out.fpga.video_format, sizeof(out.fpga.video_format), fpga_video_format_name(fpgaVideoFormatRaw)); + out.fpga.frame_rate_raw = fpgaFrameRateRaw; + out.fpga.frame_rate_valid = fpga_field_valid(fpgaValidMask, 1) ? 1 : 0; + out.fpga.frame_rate_code = static_cast(fpgaFrameRateRaw & 0x0fu); + copy_binary4(out.fpga.frame_rate_bits, sizeof(out.fpga.frame_rate_bits), fpgaFrameRateRaw); + copy_cstr(out.fpga.frame_rate_name, sizeof(out.fpga.frame_rate_name), fpga_frame_rate_name(fpgaFrameRateRaw)); + out.fpga.bit_depth_raw = fpgaBitDepthRaw; + out.fpga.bit_depth_valid = fpga_field_valid(fpgaValidMask, 2) ? 1 : 0; + out.fpga.bit_depth = static_cast(fpgaBitDepthRaw); + out.fpga.status_raw = fpgaStatusRaw; + out.fpga.status_valid = fpga_field_valid(fpgaValidMask, 3) ? 1 : 0; + out.fpga.sdi_locked = (fpgaStatusRaw & (1u << 0)) ? 1 : 0; + out.fpga.sdi_ddr_ok = (fpgaStatusRaw & (1u << 1)) ? 1 : 0; + out.fpga.hdmi_locked = (fpgaStatusRaw & (1u << 2)) ? 1 : 0; + out.fpga.hdmi_ddr_ok = (fpgaStatusRaw & (1u << 3)) ? 1 : 0; + } + return haveSignalSize ? GVFG_OK : GVFG_ENODEV; + } + + gvfg_status_t getRuntimeInfo(gvfg_runtime_info_t &out) + { + std::memset(&out, 0, sizeof(out)); + getSignalStatus(out.input_signal); + const uint64_t frames = deliveredFrames.load(std::memory_order_relaxed); + const bool deliveredValid = running.load(std::memory_order_relaxed) && frames > 0; + out.delivered_frame.valid = deliveredValid ? 1 : 0; + if (deliveredValid) + { + out.delivered_frame.width = static_cast(deliveredWidth.load(std::memory_order_relaxed)); + out.delivered_frame.height = static_cast(deliveredHeight.load(std::memory_order_relaxed)); + out.delivered_frame.bit_depth = 8; + copy_cstr(out.delivered_frame.pixel_format, sizeof(out.delivered_frame.pixel_format), "BGRA8"); + } + out.capture_fps = runtimeFps.load(std::memory_order_relaxed); + out.delivered_frames = frames; + return GVFG_OK; + } + + gvfg_status_t getPreviewInfo(gvfg_preview_info_t &out) + { + std::memset(&out, 0, sizeof(out)); + out.enabled = previewHwnd ? 1 : 0; + out.active = (pipeline && previewHwnd) ? 1 : 0; + out.width = pipeline ? pipeline->preview_w_ : 0; + out.height = pipeline ? pipeline->preview_h_ : 0; + out.swapchain_bitdepth = pipeline ? (pipeline->preview_swapchain_10bit() ? 10 : 8) + : previewDesc.swapchain_bitdepth; + out.swapchain_10bit = pipeline && pipeline->preview_swapchain_10bit() ? 1 : 0; + copy_cstr(out.render_path, sizeof(out.render_path), + pipeline ? (pipeline->preview_swapchain_10bit() + ? "YUY2 Shader -> FP16 Scene -> 10bit Swapchain" + : "YUY2 Shader -> FP16 Scene -> 8bit Swapchain") + : (previewHwnd ? "Preview helper configured, pipeline inactive" + : "Preview helper disabled")); + copy_cstr(out.backbuffer_format, sizeof(out.backbuffer_format), + pipeline ? dxgi_format_name(pipeline->preview_backbuffer_format()) : "N/A"); + return GVFG_OK; + } + + void syncBackendEventCallback() + { + if (!backend) + return; + backend->set_event_callback(onEvent ? &gvfg_handle_t::onBackendEvent : nullptr, + this, + map_event_mask_to_xdma(eventMask)); + } + + static void onBackendEvent(const xdma_event_t *event, void *user) + { + auto *self = static_cast(user); + if (!self || !event) + return; + self->emitEvent(*event); + } + + void emitEvent(const xdma_event_t &event) + { + if (!onEvent) + return; + + gvfg_event_t out{}; + out.type = map_event_type(event.type); + out.irq_bit = event.irq_bit; + out.irq_mask = event.irq_mask; + out.timestamp_ns = event.timestamp_ns; + onEvent(&out, eventCallbackUser); + } + + void querySignal() + { + if (!backend) + return; + + xdma_signal_status_t sig{}; + if (backend->get_signal_status(sig) != XDMA_OK) + return; + + std::lock_guard lock(stateMutex); + if (sig.width > 0) + width = sig.width; + if (sig.height > 0) + height = sig.height; + if (sig.bit_depth > 0) + bitDepth = sig.bit_depth; + pixelFormat = sig.pixel_format != GDRIVER_PIXFMT_UNKNOWN ? sig.pixel_format : GDRIVER_PIXFMT_YUY2; + fpgaValidMask = sig.fpga_valid_mask; + fpgaWidthValid = sig.fpga_width_valid != 0; + fpgaHeightValid = sig.fpga_height_valid != 0; + fpgaWidthRaw = sig.fpga_width_raw; + fpgaHeightRaw = sig.fpga_height_raw; + fpgaVideoFormatRaw = sig.fpga_video_format_raw; + fpgaFrameRateRaw = sig.fpga_frame_rate_raw; + fpgaBitDepthRaw = sig.fpga_bit_depth_raw; + fpgaStatusRaw = sig.fpga_status_raw; + } + + static const char *inputName(gdriver_input_t input) + { + switch (input) + { + case GDRIVER_INPUT_HDMI: + return "HDMI"; + case GDRIVER_INPUT_SDI: + return "SDI"; + default: + return "unknown"; + } + } + + gvfg_status_t validateSelectedInputReady() + { + const bool statusValid = fpga_field_valid(fpgaValidMask, 3); + const bool sdiLocked = (fpgaStatusRaw & (1u << 0)) != 0; + const bool sdiDdrOk = (fpgaStatusRaw & (1u << 1)) != 0; + const bool hdmiLocked = (fpgaStatusRaw & (1u << 2)) != 0; + const bool hdmiDdrOk = (fpgaStatusRaw & (1u << 3)) != 0; + const bool selectedReady = (selectedInput == GDRIVER_INPUT_HDMI) ? (hdmiLocked && hdmiDdrOk) + : (sdiLocked && sdiDdrOk); + + if (!statusValid || !selectedReady) + { + char msg[256] = {}; + std::snprintf(msg, + sizeof(msg), + "%s input not ready; FPGA status valid=%d raw=0x%08x sdi_lock=%d sdi_ddr=%d hdmi_lock=%d hdmi_ddr=%d", + inputName(selectedInput), + statusValid ? 1 : 0, + fpgaStatusRaw, + sdiLocked ? 1 : 0, + sdiDdrOk ? 1 : 0, + hdmiLocked ? 1 : 0, + hdmiDdrOk ? 1 : 0); + emitError(GVFG_ENODEV, msg); + return GVFG_ENODEV; + } + + if (!fpgaWidthValid || !fpgaHeightValid || fpgaWidthRaw == 0 || fpgaHeightRaw == 0) + { + char msg[192] = {}; + std::snprintf(msg, + sizeof(msg), + "%s input has no valid FPGA resolution; width_valid=%d width=%u height_valid=%d height=%u", + inputName(selectedInput), + fpgaWidthValid ? 1 : 0, + fpgaWidthRaw, + fpgaHeightValid ? 1 : 0, + fpgaHeightRaw); + emitError(GVFG_ENODEV, msg); + return GVFG_ENODEV; + } + + return GVFG_OK; + } + + gvfg_status_t configureStream() + { + if (!backend) + return GVFG_ESTATE; + + querySignal(); + const gvfg_status_t inputReady = validateSelectedInputReady(); + if (inputReady != GVFG_OK) + return inputReady; + + if (width == 0) + width = 1920; + if (height == 0) + height = 1080; + + xdma_stream_desc_t desc{}; + desc.input = selectedInput; + desc.width = width; + desc.height = height; + desc.pixel_format = pixelFormat; + desc.buffer_count = 1; + desc.memory_kind = GDRIVER_MEMORY_DRIVER_COPY; + + const xdma_status_t st = backend->configure_stream(desc); + if (st != XDMA_OK) + { + emitError(map_status(st), xdma_error_text(st, backend.get())); + return map_status(st); + } + return GVFG_OK; + } + + gcap_preview_desc_t toGcapPreviewDesc() const + { + gcap_preview_desc_t desc{}; + desc.hwnd = previewHwnd; + desc.enable_preview = previewHwnd ? 1 : 0; + desc.use_fp16_pipeline = 1; + switch (previewDesc.swapchain_bitdepth) + { + case GVFG_PREVIEW_BITDEPTH_8BIT: + desc.swapchain_10bit = GCAP_PREVIEW_BITDEPTH_8BIT; + break; + case GVFG_PREVIEW_BITDEPTH_10BIT: + desc.swapchain_10bit = GCAP_PREVIEW_BITDEPTH_10BIT; + break; + case GVFG_PREVIEW_BITDEPTH_AUTO: + default: + desc.swapchain_10bit = GCAP_PREVIEW_BITDEPTH_AUTO; + break; + } + return desc; + } + + bool createRenderPipeline() + { + if (!previewHwnd || width == 0 || height == 0) + return false; + + if (!pipeline) + pipeline = std::make_unique(); + + if (!d3d) + { + UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; +#ifdef _DEBUG + flags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0}; + D3D_FEATURE_LEVEL got{}; + HRESULT hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, + flags, levels, _countof(levels), D3D11_SDK_VERSION, + &d3d, &got, &ctx); +#ifdef _DEBUG + if (FAILED(hr)) + { + flags &= ~D3D11_CREATE_DEVICE_DEBUG; + hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, + flags, levels, _countof(levels), D3D11_SDK_VERSION, + &d3d, &got, &ctx); + } +#endif + if (FAILED(hr) || !d3d || !ctx) + return false; + + ComPtr mt; + if (SUCCEEDED(d3d.As(&mt)) && mt) + mt->SetMultithreadProtected(TRUE); + + if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, d2dFactory.ReleaseAndGetAddressOf())) || !d2dFactory) + return false; + + ComPtr dxgiDev; + if (FAILED(d3d.As(&dxgiDev)) || !dxgiDev) + return false; + if (FAILED(d2dFactory->CreateDevice(dxgiDev.Get(), &d2dDevice)) || !d2dDevice) + return false; + if (FAILED(d2dDevice->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2dCtx)) || !d2dCtx) + return false; + if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &dwrite)) || !dwrite) + return false; + d2dCtx->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1, 1), &d2dWhite); + d2dCtx->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0, 0.55f), &d2dBlack); + } + + if (!pipeline->initialize(d3d.Get(), ctx.Get(), d2dCtx.Get(), dwrite.Get(), d2dWhite.Get(), d2dBlack.Get())) + return false; + + pipeline->configurePreview(toGcapPreviewDesc()); + pipeline->set_source_bit_depth(static_cast(bitDepth ? bitDepth : 8)); + return pipeline->ensure_rt_and_pipeline(static_cast(width), static_cast(height)) && + pipeline->ensure_preview_swapchain(static_cast(width), static_cast(height)); + } + + void releaseRenderPipeline() + { + if (pipeline) + { + pipeline->release_preview_swapchain(); + pipeline.reset(); + } + d2dBlack.Reset(); + d2dWhite.Reset(); + dwrite.Reset(); + d2dCtx.Reset(); + d2dDevice.Reset(); + d2dFactory.Reset(); + ctx.Reset(); + d3d.Reset(); + } + + void captureLoop() + { + while (running) + { + xdma_frame_t frame{}; + const xdma_status_t st = backend->wait_frame(1000, frame); + if (!running) + break; + if (st == XDMA_ETIMEOUT) + continue; + if (st != XDMA_OK) + { + emitError(map_status(st), xdma_error_text(st, backend.get())); + break; + } + + updateRuntimeFps(frame.timestamp_ns ? frame.timestamp_ns : now_ns()); + const bool rendered = renderGpuFrame(frame); + if (rendered) + emitReadbackFrame(frame); + else + emitCpuFallbackFrame(frame); + backend->release_frame(frame); + } + } + + bool renderGpuFrame(const xdma_frame_t &frame) + { + if (!pipeline || !previewHwnd || !frame.data) + return false; + + const int w = static_cast(frame.width); + const int h = static_cast(frame.height); + if (w <= 0 || h <= 0) + return false; + + if (!pipeline->ensure_rt_and_pipeline(w, h) || !pipeline->ensure_preview_swapchain(w, h)) + return false; + uint32_t fallbackBitDepth = 8; + { + std::lock_guard lock(stateMutex); + fallbackBitDepth = bitDepth ? bitDepth : 8; + } + pipeline->set_source_bit_depth(static_cast(frame.bit_depth ? frame.bit_depth : fallbackBitDepth)); + + const auto *base = static_cast(frame.data); + gcap_pixfmt_t renderFmt = GCAP_FMT_YUY2; + bool uploaded = false; + + switch (frame.pixel_format) + { + case GDRIVER_PIXFMT_YUY2: + { + const int stride = frame.plane_stride_bytes[0] ? static_cast(frame.plane_stride_bytes[0]) : w * 2; + if (stride < w * 2) + return false; + renderFmt = GCAP_FMT_YUY2; + uploaded = pipeline->upload_yuy2_frame(base + frame.plane_offset_bytes[0], stride, w, h); + break; + } + case GDRIVER_PIXFMT_Y210: + { + const int stride = frame.plane_stride_bytes[0] ? static_cast(frame.plane_stride_bytes[0]) : w * 4; + if (stride < w * 4) + return false; + renderFmt = GCAP_FMT_Y210; + uploaded = pipeline->upload_y210_frame(base + frame.plane_offset_bytes[0], stride, w, h); + break; + } + case GDRIVER_PIXFMT_NV12: + { + if (frame.plane_count < 2) + return false; + const int strideY = frame.plane_stride_bytes[0] ? static_cast(frame.plane_stride_bytes[0]) : w; + const int strideUV = frame.plane_stride_bytes[1] ? static_cast(frame.plane_stride_bytes[1]) : strideY; + renderFmt = GCAP_FMT_NV12; + uploaded = pipeline->upload_nv12_frame(base + frame.plane_offset_bytes[0], strideY, + base + frame.plane_offset_bytes[1], strideUV, w, h); + break; + } + case GDRIVER_PIXFMT_P010: + { + if (frame.plane_count < 2) + return false; + const int strideY = frame.plane_stride_bytes[0] ? static_cast(frame.plane_stride_bytes[0]) : w * 2; + const int strideUV = frame.plane_stride_bytes[1] ? static_cast(frame.plane_stride_bytes[1]) : strideY; + renderFmt = GCAP_FMT_P010; + uploaded = pipeline->upload_p010_frame(base + frame.plane_offset_bytes[0], strideY, + base + frame.plane_offset_bytes[1], strideUV, w, h); + break; + } + default: + return false; + } + + if (!uploaded || + !pipeline->render_uploaded_yuv_to_fp16(renderFmt, w, h) || + !pipeline->copy_fp16_to_scene()) + return false; + + bool ok = true; + if (!pipeline->preview_swapchain_10bit()) + ok = pipeline->blit_fp16_to_rgba8(w, h); + if (ok) + pipeline->present_preview(w, h); + return ok; + } + + void emitReadbackFrame(const xdma_frame_t &frame) + { + if (!onFrame || !pipeline || !ctx) + return; + if (!shouldEmitFrameCallback(frame.frame_id)) + return; + + const int w = static_cast(frame.width); + const int h = static_cast(frame.height); + if (!pipeline->blit_fp16_to_rgba8(w, h)) + return; + + gcap_frame_t readback{}; + if (pipeline->readback_to_frame(w, h, frame.timestamp_ns ? frame.timestamp_ns : now_ns(), frame.frame_id, &readback)) + { + gvfg_frame_t out{}; + out.data = readback.data[0]; + out.stride = readback.stride[0]; + out.width = readback.width; + out.height = readback.height; + out.pts_ns = readback.pts_ns; + out.frame_id = readback.frame_id; + onFrame(&out, callbackUser); + noteDeliveredFrame(out.width, out.height); + ctx->Unmap(pipeline->rt_stage_.Get(), 0); + } + } + + void emitCpuFallbackFrame(const xdma_frame_t &frame) + { + if (frame.pixel_format != GDRIVER_PIXFMT_YUY2) + { + if (!fallbackLogged) + { + emitError(GVFG_ENOTSUP, "GVFG preview currently supports YUV422/YUV420 GPU paths only; RGB/YUV444 input is not rendered"); + fallbackLogged = true; + } + return; + } + if (!onFrame || !frame.data) + return; + if (!shouldEmitFrameCallback(frame.frame_id)) + return; + + const int w = static_cast(frame.width); + const int h = static_cast(frame.height); + const int srcStride = frame.plane_stride_bytes[0] ? static_cast(frame.plane_stride_bytes[0]) : w * 2; + if (w <= 0 || h <= 0 || srcStride < w * 2) + return; + + if (!fallbackLogged) + { + emitError(GVFG_ENOTSUP, "GPU preview/readback unavailable; using CPU YUY2 preview fallback"); + fallbackLogged = true; + } + + fallbackBgra.resize(static_cast(w) * static_cast(h) * 4u); + const auto *srcBase = static_cast(frame.data); + for (int y = 0; y < h; ++y) + { + const uint8_t *src = srcBase + static_cast(y) * static_cast(srcStride); + uint8_t *dst = fallbackBgra.data() + static_cast(y) * static_cast(w) * 4u; + for (int x = 0; x + 1 < w; x += 2) + { + const int y0 = src[x * 2 + 0]; + const int u = src[x * 2 + 1]; + const int y1 = src[x * 2 + 2]; + const int v = src[x * 2 + 3]; + + uint8_t r0 = 0, g0 = 0, b0 = 0; + uint8_t r1 = 0, g1 = 0, b1 = 0; + yuv_to_rgb(y0, u, v, r0, g0, b0); + yuv_to_rgb(y1, u, v, r1, g1, b1); + + dst[x * 4 + 0] = b0; + dst[x * 4 + 1] = g0; + dst[x * 4 + 2] = r0; + dst[x * 4 + 3] = 255; + dst[(x + 1) * 4 + 0] = b1; + dst[(x + 1) * 4 + 1] = g1; + dst[(x + 1) * 4 + 2] = r1; + dst[(x + 1) * 4 + 3] = 255; + } + } + + gvfg_frame_t out{}; + out.data = fallbackBgra.data(); + out.stride = w * 4; + out.width = w; + out.height = h; + out.pts_ns = frame.timestamp_ns ? frame.timestamp_ns : now_ns(); + out.frame_id = frame.frame_id; + onFrame(&out, callbackUser); + noteDeliveredFrame(out.width, out.height); + } + + bool shouldEmitFrameCallback(uint64_t frameId) const + { + const uint32_t interval = callbackFrameInterval.load(std::memory_order_relaxed); + if (interval <= 1) + return true; + return (frameId % interval) == 1; + } + + void emitError(gvfg_status_t code, const char *msg) + { + if (onError) + onError(code, msg ? msg : "", callbackUser); + } + + void updateRuntimeFps(uint64_t ptsNs) + { + const uint64_t prevPtsNs = lastPtsNs.exchange(ptsNs, std::memory_order_relaxed); + if (prevPtsNs != 0 && ptsNs > prevPtsNs) + { + const double fps = 1e9 / static_cast(ptsNs - prevPtsNs); + if (fps > 0.0 && fps < 1000.0) + { + const double current = runtimeFps.load(std::memory_order_relaxed); + runtimeFps.store((current <= 0.0) ? fps : current * 0.9 + fps * 0.1, + std::memory_order_relaxed); + } + } + } + + void resetRuntimeCounters() + { + lastPtsNs.store(0, std::memory_order_relaxed); + deliveredFrames.store(0, std::memory_order_relaxed); + deliveredWidth.store(0, std::memory_order_relaxed); + deliveredHeight.store(0, std::memory_order_relaxed); + runtimeFps.store(0.0, std::memory_order_relaxed); + } + + void noteDeliveredFrame(int frameWidth, int frameHeight) + { + deliveredWidth.store(frameWidth > 0 ? static_cast(frameWidth) : 0, std::memory_order_relaxed); + deliveredHeight.store(frameHeight > 0 ? static_cast(frameHeight) : 0, std::memory_order_relaxed); + deliveredFrames.fetch_add(1, std::memory_order_relaxed); + } + + std::unique_ptr backend; + int currentIndex = -1; + gdriver_input_t selectedInput = GDRIVER_INPUT_SDI; + gvfg_preview_desc_t previewDesc{}; + void *previewHwnd = nullptr; + + uint32_t width = 0; + uint32_t height = 0; + uint32_t bitDepth = 8; + gdriver_pixel_format_t pixelFormat = GDRIVER_PIXFMT_YUY2; + mutable std::mutex stateMutex; + uint32_t fpgaValidMask = 0; + bool fpgaWidthValid = false; + bool fpgaHeightValid = false; + uint32_t fpgaWidthRaw = 0; + uint32_t fpgaHeightRaw = 0; + uint32_t fpgaVideoFormatRaw = 0; + uint32_t fpgaFrameRateRaw = 0; + uint32_t fpgaBitDepthRaw = 0; + uint32_t fpgaStatusRaw = 0; + std::atomic lastPtsNs{0}; + std::atomic deliveredFrames{0}; + std::atomic deliveredWidth{0}; + std::atomic deliveredHeight{0}; + std::atomic runtimeFps{0.0}; + + gvfg_on_frame_cb onFrame = nullptr; + gvfg_on_error_cb onError = nullptr; + void *callbackUser = nullptr; + std::atomic callbackFrameInterval{1}; + gvfg_on_event_cb onEvent = nullptr; + void *eventCallbackUser = nullptr; + uint32_t eventMask = GVFG_EVENT_MASK_DEFAULT; + bool fallbackLogged = false; + std::vector fallbackBgra; + + std::atomic running{false}; + std::thread captureThread; + + ComPtr d3d; + ComPtr ctx; + ComPtr d2dFactory; + ComPtr d2dDevice; + ComPtr d2dCtx; + ComPtr dwrite; + ComPtr d2dWhite; + ComPtr d2dBlack; + std::unique_ptr pipeline; +}; + +extern "C" +{ + int gvfg_enumerate_devices(gvfg_device_info_t *out_devices, int max_devices) + { + const std::vector devices = gvfg::internal::enumerate_xdma_devices(); + const int n = static_cast(devices.size()); + if (n <= 0) + return n; + + if (!out_devices || max_devices <= 0) + return n; + + const int written = (std::min)(n, max_devices); + for (int i = 0; i < written; ++i) + { + out_devices[i] = {}; + out_devices[i].index = i; + copy_cstr(out_devices[i].name, sizeof(out_devices[i].name), + "GVFG Capture"); + copy_wide_to_utf8(devices[static_cast(i)].friendly_name, + out_devices[i].name, + sizeof(out_devices[i].name)); + if (!out_devices[i].name[0]) + copy_cstr(out_devices[i].name, sizeof(out_devices[i].name), "GVFG Capture"); + } + return written; + } + + gvfg_status_t gvfg_create(gvfg_handle *out_handle) + { + if (!out_handle) + return GVFG_EINVAL; + auto h = std::make_unique(); + *out_handle = h.release(); + return GVFG_OK; + } + + gvfg_status_t gvfg_destroy(gvfg_handle handle) + { + delete handle; + return GVFG_OK; + } + + gvfg_status_t gvfg_set_callbacks(gvfg_handle handle, + gvfg_on_frame_cb on_frame, + gvfg_on_error_cb on_error, + void *user) + { + if (!handle) + return GVFG_EINVAL; + handle->onFrame = on_frame; + handle->onError = on_error; + handle->callbackUser = user; + return GVFG_OK; + } + + gvfg_status_t gvfg_set_frame_callback_interval(gvfg_handle handle, uint32_t frame_interval) + { + if (!handle) + return GVFG_EINVAL; + handle->callbackFrameInterval.store(frame_interval <= 1 ? 1u : frame_interval, + std::memory_order_relaxed); + return GVFG_OK; + } + + gvfg_status_t gvfg_set_event_callback(gvfg_handle handle, + gvfg_on_event_cb on_event, + void *user, + uint32_t event_mask) + { + if (!handle) + return GVFG_EINVAL; + return handle->setEventCallback(on_event, user, event_mask); + } + + gvfg_status_t gvfg_set_preview(gvfg_handle handle, const gvfg_preview_desc_t *desc) + { + if (!handle || !desc) + return GVFG_EINVAL; + return handle->setPreview(*desc); + } + + gvfg_status_t gvfg_open(gvfg_handle handle, int device_index) + { + if (!handle) + return GVFG_EINVAL; + return handle->open(device_index); + } + + gvfg_status_t gvfg_start(gvfg_handle handle) + { + if (!handle) + return GVFG_EINVAL; + return handle->start(); + } + + gvfg_status_t gvfg_stop(gvfg_handle handle) + { + if (!handle) + return GVFG_EINVAL; + return handle->stop(); + } + + gvfg_status_t gvfg_get_signal_status(gvfg_handle handle, gvfg_signal_status_t *out_status) + { + if (!handle || !out_status) + return GVFG_EINVAL; + return handle->getSignalStatus(*out_status); + } + + gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, gvfg_runtime_info_t *out_info) + { + if (!handle || !out_info) + return GVFG_EINVAL; + return handle->getRuntimeInfo(*out_info); + } + + gvfg_status_t gvfg_get_preview_info(gvfg_handle handle, gvfg_preview_info_t *out_info) + { + if (!handle || !out_info) + return GVFG_EINVAL; + return handle->getPreviewInfo(*out_info); + } + + const char *gvfg_strerror(gvfg_status_t status) + { + switch (status) + { + case GVFG_OK: + return "OK"; + case GVFG_EINVAL: + return "Invalid argument"; + case GVFG_ENODEV: + return "No GVFG device"; + case GVFG_ESTATE: + return "Invalid state"; + case GVFG_EIO: + return "I/O error"; + case GVFG_ENOTSUP: + return "Not supported"; + case GVFG_ETIMEOUT: + return "Timeout"; + default: + return "Unknown"; + } + } +}