feat: harden capture API and preview diagnostics

This commit is contained in:
Mark.lin
2026-07-27 11:10:59 +08:00
parent 2b2eeb7302
commit 747209fa87
12 changed files with 530 additions and 142 deletions
+60 -5
View File
@@ -43,6 +43,13 @@ console/service app:
Backend 在 capture running 時可以有自己的 internal driver I/O workers,但那是 Backend 在 capture running 時可以有自己的 internal driver I/O workers,但那是
`gvfg.dll` 背後的 implementation detail。 `gvfg.dll` 背後的 implementation detail。
同一個 handle 允許一條 frame-reading thread;query API 與 `gvfg_poll_event()`
可以和它同時執行。Application 必須自行 serialize lifecycle API。`gvfg_stop()` 可以
喚醒 blocked read/poll,但 stop/destroy 讓 frame 失效時,其他 thread 不得繼續存取它。
所有等待 API 使用一致的 timeout:`0` 表示 non-blocking,
`GVFG_TIMEOUT_INFINITE` 表示無限等待,其他值是 milliseconds。
## Frame 所有權 ## Frame 所有權
`gvfg_read_frame()` 會回傳一個 SDK-owned frame buffer。 `gvfg_read_frame()` 會回傳一個 SDK-owned frame buffer。
@@ -97,6 +104,15 @@ Customer-readable input signal status:
新 driver 未提供 frame-rate、SDI/HDMI lock、DDR status 或舊 FPGA validity 新 driver 未提供 frame-rate、SDI/HDMI lock、DDR status 或舊 FPGA validity
register,因此 SDK 不再合成或公開這些欄位。 register,因此 SDK 不再合成或公開這些欄位。
這是可擴充的 query output,呼叫前必須設定 `struct_size`。沒有 input signal 是正常
狀態:API 回傳 `GVFG_OK`,同時 `connected == 0`。
```c
gvfg_signal_status_t signal = {};
signal.struct_size = sizeof(signal);
gvfg_get_signal_status(h, &signal);
```
### `gvfg_frame_t` ### `gvfg_frame_t`
`gvfg_read_frame()` 回傳的 frame descriptor。 `gvfg_read_frame()` 回傳的 frame descriptor。
@@ -114,6 +130,10 @@ typedef struct
} gvfg_frame_t; } gvfg_frame_t;
``` ```
`gvfg_frame_t` 只保存每張 frame 必定存在的核心欄位;stable release 後凍結此 ABI。
Memory layout、color metadata 與 timestamp metadata 不會繼續塞進這個 struct,而是
分別透過 query API 取得。
### `gvfg_frame_layout_t` ### `gvfg_frame_layout_t`
由 `gvfg_get_frame_layout()` 回傳的 optional per-plane layout。 由 `gvfg_get_frame_layout()` 回傳的 optional per-plane layout。
@@ -129,7 +149,6 @@ typedef struct
int plane_stride[GVFG_MAX_PLANES]; int plane_stride[GVFG_MAX_PLANES];
uint64_t plane_size[GVFG_MAX_PLANES]; uint64_t plane_size[GVFG_MAX_PLANES];
uint64_t plane_offset[GVFG_MAX_PLANES]; uint64_t plane_offset[GVFG_MAX_PLANES];
uint64_t reserved[8];
} gvfg_frame_layout_t; } gvfg_frame_layout_t;
``` ```
@@ -144,7 +163,18 @@ DMA layout,也可以在不改 `gvfg_frame_t` 的情況下支援。
`layout_flags` 是 `gvfg_frame_layout_flags_t` bitmask。目前 backend 會設 `layout_flags` 是 `gvfg_frame_layout_flags_t` bitmask。目前 backend 會設
`GVFG_FRAME_LAYOUT_CONTIGUOUS` 和 `GVFG_FRAME_LAYOUT_SDK_DERIVED`,表示 planes `GVFG_FRAME_LAYOUT_CONTIGUOUS` 和 `GVFG_FRAME_LAYOUT_SDK_DERIVED`,表示 planes
位在同一個 native DMA buffer 裡,而且 pitch 是 SDK 依照 known native format 位在同一個 native DMA buffer 裡,而且 pitch 是 SDK 依照 known native format
推導出來的。Application 必須忽略 `reserved[]`。 推導出來的。
### ABI 與 metadata 擴充規則
- `gvfg_handle` 永遠保持 opaque。
- `gvfg_frame_t` 保持極小,stable release 後凍結。
- 真正可擴充的 query output 使用 `struct_size`。
- Layout 使用 `gvfg_get_frame_layout()`。
- 未來 color metadata 使用獨立的 `gvfg_get_frame_color_info()`。
- 未來 timestamp metadata 使用獨立的 `gvfg_get_frame_timestamp_info()`。
- Metadata 類型真的大量增加時,才考慮 side data。
- 只有 major version 可以破壞既有 ABI。
板子只提供兩種 native capture layout: 板子只提供兩種 native capture layout:
@@ -268,7 +298,8 @@ gvfg_status_t gvfg_read_frame(gvfg_handle handle,
uint32_t timeout_ms); uint32_t timeout_ms);
``` ```
讀取一個 frame。`timeout_ms == 0` 表示 indefinite wait。 讀取一個 frame。`timeout_ms == 0` 表示 non-blocking;
`timeout_ms == GVFG_TIMEOUT_INFINITE` 表示 indefinite wait。
回傳值: 回傳值:
@@ -375,7 +406,10 @@ gvfg_status_t gvfg_poll_event(gvfg_handle handle,
uint32_t timeout_ms); uint32_t timeout_ms);
``` ```
Poll 一個 event。`timeout_ms == 0` 表示 non-blocking poll。 Poll 一個 event。`timeout_ms == 0` 表示 non-blocking poll;
`timeout_ms == GVFG_TIMEOUT_INFINITE` 表示 indefinite wait。
只有 running session 可以 poll;`gvfg_stop()` 會喚醒 blocked poll 並使它回傳
`GVFG_ESTATE`。
### `gvfg_get_signal_status` ### `gvfg_get_signal_status`
@@ -386,6 +420,14 @@ gvfg_status_t gvfg_get_signal_status(gvfg_handle handle,
查詢目前 input signal metadata。 查詢目前 input signal metadata。
```c
gvfg_signal_status_t status = {};
status.struct_size = sizeof(status);
gvfg_get_signal_status(h, &status);
```
沒有 input signal 時仍回傳 `GVFG_OK`,並設定 `status.connected = 0`。
### `gvfg_get_runtime_info` ### `gvfg_get_runtime_info`
```c ```c
@@ -393,7 +435,15 @@ gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle,
gvfg_runtime_info_t *out_info); gvfg_runtime_info_t *out_info);
``` ```
查詢目前 signal status、last read frame format、FPS、delivered frame count。 查詢 last read frame format、FPS、delivered frame count。Input signal metadata 請另外
呼叫 `gvfg_get_signal_status()`;不要把可擴充的 signal struct 內嵌進 runtime struct,
避免未來欄位位移破壞 ABI。
```c
gvfg_runtime_info_t info = {};
info.struct_size = sizeof(info);
gvfg_get_runtime_info(h, &info);
```
## Preview 邊界 ## Preview 邊界
@@ -411,3 +461,8 @@ gvfg_read_frame
Customer demo source 需要簡單 display path 時,可以 include `gvfg_preview.h` Customer demo source 需要簡單 display path 時,可以 include `gvfg_preview.h`
並 link `gvfg_preview.dll`。Preview helper source 保持 private;customer code 並 link `gvfg_preview.dll`。Preview helper source 保持 private;customer code
只看到 helper API 和 binary。 只看到 helper API 和 binary。
`gvfg_preview_get_stats()` 可查詢 preview 顯示速率。`present_fps` 只計算
DXGI `Present` 成功接受的畫面;使用 `DXGI_PRESENT_DO_NOT_WAIT` 時因
swapchain busy 而跳過的畫面不列入。速率以最近五秒的 successful Present
時間戳計算,開始顯示前至少收集兩秒,停止顯示超過一秒後回到 `0`。
+17 -4
View File
@@ -124,20 +124,30 @@ gvfg_enumerate_devices
Pull mode 下,`gvfg.dll` 不擁有 application 的 public read thread。UI app 應該 Pull mode 下,`gvfg.dll` 不擁有 application 的 public read thread。UI app 應該
自己建立 worker thread,並在那個 thread 呼叫 `gvfg_read_frame()`。 自己建立 worker thread,並在那個 thread 呼叫 `gvfg_read_frame()`。
`gvfg_start()` 在沒有 input signal 時仍會註冊 driver events 並啟動單一 backend `gvfg_start()` 在尚未確認 input signal 時仍會註冊 driver events 並啟動單一 backend
wait thread,但不 enable DMA。`gvfg_read_frame()` 此時 timeout;收到 signal-connected wait thread。`gvfg_read_frame()` 此時 timeout;收到 signal-connected event 後,backend
event 後,backend 在相同 thread 重讀 width/height/payload format、resize ring,然後 在相同 thread 重讀 width/height/payload format、resize ring,然後 enable DMA 並送出
enable DMA 並送出 capture-resumed event。 capture-resumed event。
FPGA H/V/format registers 可能在拔除來源後保留 last-known values,因此它們只能用來
準備 DMA probe layout,不能當作 signal-present 判斷。啟動時 backend 可以在內部 enable
probe DMA,以涵蓋來源早於 event registration 就已接上的情況;只有收到 driver plug-in
event 或成功取得第一張完整 frame 後,public signal status 才能回報 connected。
## Frame 所有權 ## Frame 所有權
- `gvfg_read_frame()` 回傳一個 SDK-owned frame buffer。 - `gvfg_read_frame()` 回傳一個 SDK-owned frame buffer。
- `frame.data` 在 `gvfg_release_frame()` 前有效。 - `frame.data` 在 `gvfg_release_frame()` 前有效。
- `gvfg_frame_t` 要保持 ABI-stable;不要為了 layout 直接 append fields。 - `gvfg_frame_t` 要保持 ABI-stable;不要為了 layout 直接 append fields。
- `gvfg_handle` 永遠 opaque;stable release 後 `gvfg_frame_t` 凍結,只有 major
version 可以破壞既有 ABI。
- `gvfg_get_frame_layout()` 回傳 SDK-filled layout metadata:`plane_data`、 - `gvfg_get_frame_layout()` 回傳 SDK-filled layout metadata:`plane_data`、
`plane_stride`、`plane_size`、`plane_offset`。目前 PCIES2MM backend 先用 `plane_stride`、`plane_size`、`plane_offset`。目前 PCIES2MM backend 先用
width/height/format 推導 tightly packed layout;未來 driver 如果能回報真實 width/height/format 推導 tightly packed layout;未來 driver 如果能回報真實
pitch 或 plane offsets,應該更新 layout query path,而不是改既有 frame struct。 pitch 或 plane offsets,應該更新 layout query path,而不是改既有 frame struct。
- 未來 color/timestamp metadata 應新增各自帶 `struct_size` 的 query output,例如
`gvfg_get_frame_color_info()` 與 `gvfg_get_frame_timestamp_info()`。不要預先在每個
struct 放大型 reserved array;等 metadata 類型真的很多再考慮 side data。
- `gvfg_preview.dll` 應優先吃 `gvfg_get_frame_layout()`;layout query 不可用時才 - `gvfg_preview.dll` 應優先吃 `gvfg_get_frame_layout()`;layout query 不可用時才
fallback 到 width-derived stride。 fallback 到 width-derived stride。
- `gvfg_convert.dll` 負責 explicit snapshot/export conversion。不要把 color - `gvfg_convert.dll` 負責 explicit snapshot/export conversion。不要把 color
@@ -145,6 +155,9 @@ enable DMA 並送出 capture-resumed event。
- 同一個 handle 一次最多 hold 一個 frame。 - 同一個 handle 一次最多 hold 一個 frame。
- Application 如果 release 後還要用 data,必須自己 copy frame。 - Application 如果 release 後還要用 data,必須自己 copy frame。
- `gvfg_preview_render_frame()` 是 synchronous,應該在 `gvfg_release_frame()` 前呼叫。 - `gvfg_preview_render_frame()` 是 synchronous,應該在 `gvfg_release_frame()` 前呼叫。
- Qt sample 狀態列只顯示 Preview FPS,不顯示 reader/capture FPS。Preview FPS
由 `gvfg_preview_get_stats()` 提供,只計算 DXGI 接受的 Present;swapchain
busy skip 不計入,採最近五秒滑動時間窗。
Typical two-way use: Typical two-way use:
@@ -65,6 +65,21 @@ typedef struct
int adapter_index; int adapter_index;
} gvfg_preview_info_t; } gvfg_preview_info_t;
/*
* Preview presentation statistics.
*
* present_fps counts only frames accepted by DXGI Present. A frame skipped
* because the non-blocking swapchain is busy is excluded. The rate uses
* successful presents from the most recent five seconds.
*/
typedef struct
{
uint32_t struct_size; /* Set to sizeof(gvfg_preview_stats_t). */
double present_fps;
uint64_t presented_frames;
uint64_t skipped_presents;
} gvfg_preview_stats_t;
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_create( GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_create(
gvfg_preview_handle *out_handle); gvfg_preview_handle *out_handle);
@@ -94,6 +109,10 @@ GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_info(
gvfg_preview_handle handle, gvfg_preview_handle handle,
gvfg_preview_info_t *out_info); gvfg_preview_info_t *out_info);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_get_stats(
gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats);
GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_shutdown( GVFG_PREVIEW_API gvfg_preview_status_t gvfg_preview_shutdown(
gvfg_preview_handle handle); gvfg_preview_handle handle);
@@ -984,17 +984,17 @@ bool D3DPreviewPipeline::ensure_preview_swapchain(int w, int h)
return true; return true;
} }
bool D3DPreviewPipeline::present_preview(int src_w, int src_h) gvfg_preview_present_result_t D3DPreviewPipeline::present_preview(int src_w, int src_h)
{ {
static bool s_loggedPresentPath = false; static bool s_loggedPresentPath = false;
if (!preview_enabled_ || !preview_swapchain_ || !preview_backbuf_ || !ctx_) if (!preview_enabled_ || !preview_swapchain_ || !preview_backbuf_ || !ctx_)
return false; return GVFG_PREVIEW_PRESENT_FAILED;
ID3D11RenderTargetView *nullRTV = nullptr; ID3D11RenderTargetView *nullRTV = nullptr;
ctx_->OMSetRenderTargets(1, &nullRTV, nullptr); ctx_->OMSetRenderTargets(1, &nullRTV, nullptr);
if (!preview_rtv_ || !vs_) if (!preview_rtv_ || !vs_)
return false; return GVFG_PREVIEW_PRESENT_FAILED;
const float srcW = static_cast<float>(src_w); const float srcW = static_cast<float>(src_w);
const float srcH = static_cast<float>(src_h); const float srcH = static_cast<float>(src_h);
@@ -1002,7 +1002,7 @@ bool D3DPreviewPipeline::present_preview(int src_w, int src_h)
const float dstH = static_cast<float>(preview_h_); const float dstH = static_cast<float>(preview_h_);
if (srcW <= 0.0f || srcH <= 0.0f || dstW <= 0.0f || dstH <= 0.0f) if (srcW <= 0.0f || srcH <= 0.0f || dstW <= 0.0f || dstH <= 0.0f)
return false; return GVFG_PREVIEW_PRESENT_FAILED;
float drawW = dstW; float drawW = dstW;
float drawH = dstH; float drawH = dstH;
@@ -1055,7 +1055,7 @@ bool D3DPreviewPipeline::present_preview(int src_w, int src_h)
if (preview_swapchain_10bit_) if (preview_swapchain_10bit_)
{ {
if (!srv_scene_fp16_ || !ps_fp16_to_preview_) if (!srv_scene_fp16_ || !ps_fp16_to_preview_)
return false; return GVFG_PREVIEW_PRESENT_FAILED;
ctx_->PSSetShader(ps_fp16_to_preview_.Get(), nullptr, 0); ctx_->PSSetShader(ps_fp16_to_preview_.Get(), nullptr, 0);
srv = srv_scene_fp16_.Get(); srv = srv_scene_fp16_.Get();
@@ -1063,7 +1063,7 @@ bool D3DPreviewPipeline::present_preview(int src_w, int src_h)
else else
{ {
if (!srv_rgba_ || !ps_rgba8_to_preview_) if (!srv_rgba_ || !ps_rgba8_to_preview_)
return false; return GVFG_PREVIEW_PRESENT_FAILED;
ctx_->PSSetShader(ps_rgba8_to_preview_.Get(), nullptr, 0); ctx_->PSSetShader(ps_rgba8_to_preview_.Get(), nullptr, 0);
srv = srv_rgba_.Get(); srv = srv_rgba_.Get();
@@ -1106,7 +1106,7 @@ bool D3DPreviewPipeline::present_preview(int src_w, int src_h)
static_cast<unsigned long long>(s_presentBusyCount)); static_cast<unsigned long long>(s_presentBusyCount));
ssp_log_text(warn); ssp_log_text(warn);
} }
return true; return GVFG_PREVIEW_PRESENT_SKIPPED;
} }
if (FAILED(hr)) if (FAILED(hr))
{ {
@@ -1116,9 +1116,9 @@ bool D3DPreviewPipeline::present_preview(int src_w, int src_h)
static_cast<unsigned>(hr)); static_cast<unsigned>(hr));
ssp_log_text(err); ssp_log_text(err);
release_preview_swapchain(); release_preview_swapchain();
return false; return GVFG_PREVIEW_PRESENT_FAILED;
} }
return true; return GVFG_PREVIEW_PRESENTED;
} }
DXGI_FORMAT D3DPreviewPipeline::preview_backbuffer_format() const DXGI_FORMAT D3DPreviewPipeline::preview_backbuffer_format() const
@@ -21,6 +21,13 @@ typedef enum
GVFG_RENDER_PREVIEW_BITDEPTH_AUTO = 2 GVFG_RENDER_PREVIEW_BITDEPTH_AUTO = 2
} gvfg_render_preview_bitdepth_t; } gvfg_render_preview_bitdepth_t;
typedef enum
{
GVFG_PREVIEW_PRESENT_FAILED = 0,
GVFG_PREVIEW_PRESENTED = 1,
GVFG_PREVIEW_PRESENT_SKIPPED = 2
} gvfg_preview_present_result_t;
typedef struct typedef struct
{ {
void *hwnd; void *hwnd;
@@ -45,7 +52,7 @@ public:
bool ensure_rt_and_pipeline(int w, int h); bool ensure_rt_and_pipeline(int w, int h);
bool ensure_preview_swapchain(int w, int h); bool ensure_preview_swapchain(int w, int h);
bool preview_swapchain_10bit() const { return preview_swapchain_10bit_; } bool preview_swapchain_10bit() const { return preview_swapchain_10bit_; }
bool present_preview(int src_w, int src_h); gvfg_preview_present_result_t present_preview(int src_w, int src_h);
DXGI_FORMAT preview_backbuffer_format() const; DXGI_FORMAT preview_backbuffer_format() const;
DXGI_FORMAT scene_texture_format() const; DXGI_FORMAT scene_texture_format() const;
DXGI_FORMAT linear_fp16_texture_format() const; DXGI_FORMAT linear_fp16_texture_format() const;
+80 -1
View File
@@ -5,7 +5,10 @@
#include <d3d11_4.h> #include <d3d11_4.h>
#include <dxgi1_2.h> #include <dxgi1_2.h>
#include <atomic> #include <atomic>
#include <chrono>
#include <cstddef>
#include <cstring> #include <cstring>
#include <deque>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <wrl/client.h> #include <wrl/client.h>
@@ -21,6 +24,7 @@ public:
bool configure(void *hwnd) bool configure(void *hwnd)
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
resetPresentStats();
hwnd_ = hwnd; hwnd_ = hwnd;
configured_ = hwnd_ != nullptr; configured_ = hwnd_ != nullptr;
if (pipeline_) if (pipeline_)
@@ -103,11 +107,14 @@ public:
return false; return false;
} }
if (!pipeline_->present_preview(frame.width, frame.height)) const gvfg::internal::gvfg_preview_present_result_t presentResult =
pipeline_->present_preview(frame.width, frame.height);
if (presentResult == gvfg::internal::GVFG_PREVIEW_PRESENT_FAILED)
{ {
clearActiveInfo(); clearActiveInfo();
return false; return false;
} }
recordPresentResult(presentResult);
width_.store(pipeline_->preview_w_, std::memory_order_relaxed); width_.store(pipeline_->preview_w_, std::memory_order_relaxed);
height_.store(pipeline_->preview_h_, std::memory_order_relaxed); height_.store(pipeline_->preview_h_, std::memory_order_relaxed);
@@ -127,6 +134,7 @@ public:
configured_ = false; configured_ = false;
hwnd_ = nullptr; hwnd_ = nullptr;
clearActiveInfo(); clearActiveInfo();
resetPresentStats();
} }
bool active() const bool active() const
@@ -164,6 +172,16 @@ public:
return adapterIndex_; return adapterIndex_;
} }
void getStats(gvfg_preview_stats_t &stats) const
{
std::lock_guard<std::mutex> lock(mutex_);
stats.presented_frames = presentedFrames_;
stats.skipped_presents = skippedPresents_;
stats.present_fps = active_.load(std::memory_order_relaxed)
? calculatePresentFps(std::chrono::steady_clock::now())
: 0.0;
}
private: private:
struct D3DState struct D3DState
{ {
@@ -180,6 +198,46 @@ private:
active_.store(false, std::memory_order_relaxed); active_.store(false, std::memory_order_relaxed);
} }
using PresentClock = std::chrono::steady_clock;
void resetPresentStats()
{
presentTimes_.clear();
presentedFrames_ = 0;
skippedPresents_ = 0;
}
void recordPresentResult(gvfg::internal::gvfg_preview_present_result_t result)
{
if (result == gvfg::internal::GVFG_PREVIEW_PRESENT_SKIPPED)
{
++skippedPresents_;
return;
}
if (result != gvfg::internal::GVFG_PREVIEW_PRESENTED)
return;
++presentedFrames_;
const PresentClock::time_point now = PresentClock::now();
presentTimes_.push_back(now);
const auto windowStart = now - std::chrono::seconds(5);
while (presentTimes_.size() > 2 && presentTimes_.front() < windowStart)
presentTimes_.pop_front();
}
double calculatePresentFps(PresentClock::time_point now) const
{
if (presentTimes_.size() < 2 ||
now - presentTimes_.back() > std::chrono::seconds(1))
return 0.0;
const double elapsed =
std::chrono::duration<double>(presentTimes_.back() - presentTimes_.front()).count();
if (elapsed < 2.0)
return 0.0;
return static_cast<double>(presentTimes_.size() - 1) / elapsed;
}
static bool sameLuid(const LUID &a, const LUID &b) static bool sameLuid(const LUID &a, const LUID &b)
{ {
return a.LowPart == b.LowPart && a.HighPart == b.HighPart; return a.LowPart == b.LowPart && a.HighPart == b.HighPart;
@@ -309,6 +367,9 @@ private:
std::atomic<bool> active_{false}; std::atomic<bool> active_{false};
char adapterName_[160] = {}; char adapterName_[160] = {};
int adapterIndex_ = -1; int adapterIndex_ = -1;
std::deque<PresentClock::time_point> presentTimes_;
uint64_t presentedFrames_ = 0;
uint64_t skippedPresents_ = 0;
std::unique_ptr<D3DState> d3d_; std::unique_ptr<D3DState> d3d_;
std::unique_ptr<gvfg::internal::D3DPreviewPipeline> pipeline_; std::unique_ptr<gvfg::internal::D3DPreviewPipeline> pipeline_;
}; };
@@ -417,6 +478,24 @@ extern "C"
return GVFG_PREVIEW_OK; return GVFG_PREVIEW_OK;
} }
gvfg_preview_status_t gvfg_preview_get_stats(gvfg_preview_handle handle,
gvfg_preview_stats_t *out_stats)
{
constexpr size_t kMinimumSize =
offsetof(gvfg_preview_stats_t, skipped_presents) +
sizeof(uint64_t);
if (!handle || !out_stats || out_stats->struct_size < kMinimumSize)
return GVFG_PREVIEW_EINVAL;
const uint32_t callerSize = out_stats->struct_size;
gvfg_preview_stats_t stats{};
stats.struct_size = sizeof(stats);
handle->renderer.getStats(stats);
std::memcpy(out_stats, &stats, (callerSize < sizeof(stats)) ? callerSize : sizeof(stats));
out_stats->struct_size = callerSize;
return GVFG_PREVIEW_OK;
}
gvfg_preview_status_t gvfg_preview_shutdown(gvfg_preview_handle handle) gvfg_preview_status_t gvfg_preview_shutdown(gvfg_preview_handle handle)
{ {
if (!handle) if (!handle)
+106 -36
View File
@@ -10,11 +10,48 @@
#include <QDir> #include <QDir>
#include <QIODevice> #include <QIODevice>
#include <QMetaObject> #include <QMetaObject>
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
#include <QStringList> #include <QStringList>
#include <QTimer> #include <QTimer>
namespace namespace
{ {
class LogHighlighter final : public QSyntaxHighlighter
{
public:
explicit LogHighlighter(QTextDocument *document)
: QSyntaxHighlighter(document)
{
errorFormat_.setForeground(QColor(200, 0, 0));
errorFormat_.setFontWeight(QFont::Bold);
recoveryFormat_.setForeground(QColor(0, 128, 0));
recoveryFormat_.setFontWeight(QFont::Bold);
}
protected:
void highlightBlock(const QString &text) override
{
if (text.contains(QStringLiteral("SIGNAL_DISCONNECTED")) ||
text.contains(QStringLiteral("CAPTURE_PAUSED")) ||
text.contains(QStringLiteral("failed"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("error"), Qt::CaseInsensitive))
{
setFormat(0, text.size(), errorFormat_);
return;
}
if (text.contains(QStringLiteral("SIGNAL_CONNECTED")) ||
text.contains(QStringLiteral("CAPTURE_RESUMED")) ||
text.contains(QStringLiteral("recovered"), Qt::CaseInsensitive))
setFormat(0, text.size(), recoveryFormat_);
}
private:
QTextCharFormat errorFormat_;
QTextCharFormat recoveryFormat_;
};
QString boolText(int value) QString boolText(int value)
{ {
return value ? QStringLiteral("yes") : QStringLiteral("no"); return value ? QStringLiteral("yes") : QStringLiteral("no");
@@ -25,10 +62,12 @@ namespace
return QString::number(static_cast<qulonglong>(value)); return QString::number(static_cast<qulonglong>(value));
} }
QString captureStatusText(const gvfg_debug_backend_stats_t &stats) QString captureStatusText(const gvfg_debug_backend_stats_t &stats, bool signalConnected)
{ {
if (!stats.backend_running) if (!stats.backend_running)
return QStringLiteral("stopped"); return QStringLiteral("stopped");
if (!signalConnected)
return QStringLiteral("waiting_signal");
if (!stats.backend_capture_active) if (!stats.backend_capture_active)
return QStringLiteral("paused"); return QStringLiteral("paused");
return QStringLiteral("streaming"); return QStringLiteral("streaming");
@@ -56,8 +95,8 @@ namespace
const QString resolution = (signal.width > 0 && signal.height > 0) const QString resolution = (signal.width > 0 && signal.height > 0)
? QStringLiteral("%1x%2").arg(signal.width).arg(signal.height) ? QStringLiteral("%1x%2").arg(signal.width).arg(signal.height)
: QStringLiteral("--"); : QStringLiteral("--");
const QString format = signal.pixel_format[0] != '\0' const QString format = signal.pixel_format != GVFG_PIXFMT_UNKNOWN
? QString::fromLatin1(signal.pixel_format) ? QString::fromLatin1(gvfg_pixel_format_name(signal.pixel_format))
: QStringLiteral("--"); : QStringLiteral("--");
const QString bit = signal.bit_depth > 0 ? QString::number(signal.bit_depth) : QStringLiteral("--"); const QString bit = signal.bit_depth > 0 ? QString::number(signal.bit_depth) : QStringLiteral("--");
return QStringLiteral("%1 %2 %3-bit").arg(resolution, format, bit); return QStringLiteral("%1 %2 %3-bit").arg(resolution, format, bit);
@@ -96,9 +135,11 @@ MainWindow::MainWindow(QWidget *parent)
previewWindow_ = new PreviewWindow(); previewWindow_ = new PreviewWindow();
ui_->logEdit->setMaximumBlockCount(300); ui_->logEdit->setMaximumBlockCount(300);
new LogHighlighter(ui_->logEdit->document());
ui_->statusLabel->setWordWrap(true); ui_->statusLabel->setWordWrap(true);
signalStatusTimer_ = new QTimer(this); signalStatusTimer_ = new QTimer(this);
signalStatusTimer_->setInterval(1000); signalStatusTimer_->setInterval(1000);
diagnosticSnapshotTimer_.start();
openLogFile(); openLogFile();
connect(ui_->refreshButton, &QPushButton::clicked, this, [this]() connect(ui_->refreshButton, &QPushButton::clicked, this, [this]()
@@ -118,7 +159,7 @@ MainWindow::MainWindow(QWidget *parent)
connect(ui_->stopButton, &QPushButton::clicked, this, [this]() connect(ui_->stopButton, &QPushButton::clicked, this, [this]()
{ stopCapture(); }); { stopCapture(); });
connect(signalStatusTimer_, &QTimer::timeout, this, [this]() connect(signalStatusTimer_, &QTimer::timeout, this, [this]()
{ updateSignalStatus(true); }); { updateSignalStatus(); });
updateUiState(); updateUiState();
appendLog(logFile_.isOpen() appendLog(logFile_.isOpen()
@@ -233,7 +274,7 @@ bool MainWindow::openDevice()
lastSignalStatusText_.clear(); lastSignalStatusText_.clear();
appendLog(QStringLiteral("Opened device index %1 CH%2").arg(deviceIndex).arg(channelIndex)); appendLog(QStringLiteral("Opened device index %1 CH%2").arg(deviceIndex).arg(channelIndex));
appendLog(QStringLiteral("FPGA signal monitor active")); appendLog(QStringLiteral("FPGA signal monitor active"));
updateSignalStatus(true); updateSignalStatus();
signalStatusTimer_->start(); signalStatusTimer_->start();
updateUiState(); updateUiState();
return true; return true;
@@ -277,18 +318,17 @@ void MainWindow::startCapture()
return; return;
appendLog(QStringLiteral("FPGA signal before stream start")); appendLog(QStringLiteral("FPGA signal before stream start"));
updateSignalStatus(true); updateSignalStatus();
const gvfg_status_t st = gvfg_start(handle_); const gvfg_status_t st = gvfg_start(handle_);
if (st != GVFG_OK) if (st != GVFG_OK)
{ {
showError(QStringLiteral("gvfg_start"), st); showError(QStringLiteral("gvfg_start"), st);
updateSignalStatus(true); updateSignalStatus();
updateUiState(); updateUiState();
return; return;
} }
frameCount_ = 0;
previewFailureCount_ = 0; previewFailureCount_ = 0;
captureStop_.store(false, std::memory_order_release); captureStop_.store(false, std::memory_order_release);
captureRunning_ = true; captureRunning_ = true;
@@ -296,7 +336,7 @@ void MainWindow::startCapture()
{ captureReadLoop(); }); { captureReadLoop(); });
updateUiState(); updateUiState();
appendLog(QStringLiteral("Started capture")); appendLog(QStringLiteral("Started capture"));
updateSignalStatus(true); updateSignalStatus();
} }
void MainWindow::stopCapture() void MainWindow::stopCapture()
@@ -308,7 +348,7 @@ void MainWindow::stopCapture()
gvfg_stop(handle_); gvfg_stop(handle_);
captureRunning_ = false; captureRunning_ = false;
appendLog(QStringLiteral("Stopped capture")); appendLog(QStringLiteral("Stopped capture"));
updateSignalStatus(true); updateSignalStatus();
} }
updateUiState(); updateUiState();
@@ -338,9 +378,9 @@ bool MainWindow::applyPreview()
return true; return true;
} }
void MainWindow::updatePreviewSourceSize(const gvfg_runtime_info_t &info) void MainWindow::updatePreviewSourceSize(const gvfg_runtime_info_t &info,
const gvfg_signal_status_t &signal)
{ {
const auto &signal = info.input_signal;
const auto &readFrame = info.last_frame; const auto &readFrame = info.last_frame;
if (signal.width > 0 && signal.height > 0) if (signal.width > 0 && signal.height > 0)
@@ -359,31 +399,47 @@ void MainWindow::updatePreviewSourceSize()
return; return;
gvfg_runtime_info_t info{}; gvfg_runtime_info_t info{};
if (gvfg_get_runtime_info(handle_, &info) == GVFG_OK) info.struct_size = sizeof(info);
updatePreviewSourceSize(info); gvfg_signal_status_t signal{};
signal.struct_size = sizeof(signal);
if (gvfg_get_runtime_info(handle_, &info) == GVFG_OK &&
gvfg_get_signal_status(handle_, &signal) == GVFG_OK)
updatePreviewSourceSize(info, signal);
} }
void MainWindow::updateSignalStatus(bool writeLog) void MainWindow::updateSignalStatus()
{ {
if (!handle_) if (!handle_)
return; return;
gvfg_runtime_info_t info{}; gvfg_runtime_info_t info{};
info.struct_size = sizeof(info);
if (gvfg_get_runtime_info(handle_, &info) != GVFG_OK) if (gvfg_get_runtime_info(handle_, &info) != GVFG_OK)
return; return;
const auto &signal = info.input_signal; gvfg_signal_status_t signal{};
signal.struct_size = sizeof(signal);
if (gvfg_get_signal_status(handle_, &signal) != GVFG_OK)
return;
const auto &readFrame = info.last_frame; const auto &readFrame = info.last_frame;
gvfg_debug_backend_stats_t backendStats{}; gvfg_debug_backend_stats_t backendStats{};
backendStats.struct_size = sizeof(backendStats); backendStats.struct_size = sizeof(backendStats);
const bool haveBackendStats = gvfg_debug_get_backend_stats(handle_, &backendStats) == GVFG_OK; const bool haveBackendStats = gvfg_debug_get_backend_stats(handle_, &backendStats) == GVFG_OK;
if (previewWindow_->isVisible()) if (previewWindow_->isVisible())
updatePreviewSourceSize(info); updatePreviewSourceSize(info, signal);
gvfg_preview_info_t previewInfo{}; gvfg_preview_info_t previewInfo{};
const bool previewInfoOk = previewHandle_ && const bool previewInfoOk = previewHandle_ &&
gvfg_preview_get_info(previewHandle_, &previewInfo) == GVFG_PREVIEW_OK && gvfg_preview_get_info(previewHandle_, &previewInfo) == GVFG_PREVIEW_OK &&
previewInfo.active; previewInfo.active;
gvfg_preview_stats_t previewStats{};
previewStats.struct_size = sizeof(previewStats);
const bool previewStatsOk = previewHandle_ &&
gvfg_preview_get_stats(previewHandle_, &previewStats) == GVFG_PREVIEW_OK;
const QString previewFps = previewStatsOk && previewStats.present_fps > 0.0
? QString::number(previewStats.present_fps, 'f', 2)
: QStringLiteral("--");
const QString previewFrame = previewInfoOk const QString previewFrame = previewInfoOk
? frameText(true, ? frameText(true,
previewInfo.width, previewInfo.width,
@@ -394,21 +450,21 @@ void MainWindow::updateSignalStatus(bool writeLog)
const QString lastFrame = frameText(readFrame.valid != 0, const QString lastFrame = frameText(readFrame.valid != 0,
readFrame.width, readFrame.width,
readFrame.height, readFrame.height,
readFrame.pixel_format, gvfg_pixel_format_name(readFrame.pixel_format),
readFrame.bit_depth); readFrame.bit_depth);
QStringList statusLines; QStringList statusLines;
statusLines << QStringLiteral("Input | CH%1 connected=%2 signal=%3") statusLines << QStringLiteral("Input | CH%1 connected=%2 signal=%3")
.arg(signal.channel) .arg(signal.channel)
.arg(boolText(signal.connected), signalFrameText(signal)); .arg(boolText(signal.connected), signalFrameText(signal));
statusLines << QStringLiteral("App | reader_fps=%1 last_frame=%2 preview_active=%3 preview_output=%4") statusLines << QStringLiteral("Preview | fps=%1 last_frame=%2 active=%3 output=%4")
.arg(info.capture_fps > 0.0 ? QString::number(info.capture_fps, 'f', 2) : QStringLiteral("--")) .arg(previewFps)
.arg(lastFrame) .arg(lastFrame)
.arg(boolText(previewInfoOk ? 1 : 0)) .arg(boolText(previewInfoOk ? 1 : 0))
.arg(previewFrame); .arg(previewFrame);
statusLines << (haveBackendStats statusLines << (haveBackendStats
? QStringLiteral("Capture| status=%1 pending_irqs=%2 dma_errors=%3 no_frame_waits=%4") ? QStringLiteral("Capture| status=%1 pending_irqs=%2 dma_errors=%3 no_frame_waits=%4")
.arg(captureStatusText(backendStats)) .arg(captureStatusText(backendStats, signal.connected != 0))
.arg(backendStats.backend_pending_events) .arg(backendStats.backend_pending_events)
.arg(static_cast<qulonglong>(backendStats.backend_dma_errors)) .arg(static_cast<qulonglong>(backendStats.backend_dma_errors))
.arg(static_cast<qulonglong>(backendStats.backend_wait_timeouts)) .arg(static_cast<qulonglong>(backendStats.backend_wait_timeouts))
@@ -431,6 +487,16 @@ void MainWindow::updateSignalStatus(bool writeLog)
if (!lastError.isEmpty()) if (!lastError.isEmpty())
statusLines << QStringLiteral("Error | %1").arg(lastError); statusLines << QStringLiteral("Error | %1").arg(lastError);
if (!lastError.isEmpty() && lastError != lastLoggedBackendError_)
{
lastLoggedBackendError_ = lastError;
appendLog(QStringLiteral("Backend error | %1").arg(lastError));
}
else if (lastError.isEmpty())
{
lastLoggedBackendError_.clear();
}
const QString statusText = statusLines.join(QLatin1Char('\n')); const QString statusText = statusLines.join(QLatin1Char('\n'));
const bool changed = lastSignalStatusText_ != statusText; const bool changed = lastSignalStatusText_ != statusText;
if (changed) if (changed)
@@ -439,8 +505,11 @@ void MainWindow::updateSignalStatus(bool writeLog)
lastSignalStatusText_ = statusText; lastSignalStatusText_ = statusText;
} }
if (writeLog && changed) if (diagnosticSnapshotTimer_.elapsed() >= 10000)
appendLog(statusText); {
writeDiagnosticSnapshot(statusText);
diagnosticSnapshotTimer_.restart();
}
} }
void MainWindow::updateUiState() void MainWindow::updateUiState()
@@ -544,6 +613,20 @@ void MainWindow::writeLogFileLine(const QString &line)
logFile_.flush(); logFile_.flush();
} }
void MainWindow::writeDiagnosticSnapshot(const QString &statusText)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = statusText.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
{
const QString line = QStringLiteral("[%1] %2%3")
.arg(timestamp,
i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "),
lines.at(i));
writeLogFileLine(line);
}
}
void MainWindow::appendLog(const QString &message) void MainWindow::appendLog(const QString &message)
{ {
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz")); const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
@@ -578,10 +661,6 @@ void MainWindow::captureReadLoop()
const gvfg_status_t st = gvfg_read_frame(handle_, &frame, 200); const gvfg_status_t st = gvfg_read_frame(handle_, &frame, 200);
if (st == GVFG_OK) if (st == GVFG_OK)
{ {
const uint64_t count = ++frameCount_;
const int width = frame.width;
const int height = frame.height;
const uint64_t frameId = frame.frame_id;
if (previewHandle_) if (previewHandle_)
{ {
gvfg_preview_frame_t previewFrame{}; gvfg_preview_frame_t previewFrame{};
@@ -643,15 +722,6 @@ void MainWindow::captureReadLoop()
} }
gvfg_release_frame(handle_, &frame); gvfg_release_frame(handle_, &frame);
if (count <= 5 || (count % 60) == 0)
{
QMetaObject::invokeMethod(this, [this, count, frameId, width, height]()
{ appendLog(QStringLiteral("read_frame #%1 source id=%2 %3x%4")
.arg(static_cast<qulonglong>(count))
.arg(static_cast<qulonglong>(frameId))
.arg(width)
.arg(height)); }, Qt::QueuedConnection);
}
continue; continue;
} }
+7 -3
View File
@@ -4,6 +4,7 @@
#include <gvfg_preview.h> #include <gvfg_preview.h>
#include <QFile> #include <QFile>
#include <QElapsedTimer>
#include <QString> #include <QString>
#include <QWidget> #include <QWidget>
@@ -44,15 +45,17 @@ private:
void startCapture(); void startCapture();
void stopCapture(); void stopCapture();
bool applyPreview(); bool applyPreview();
void updatePreviewSourceSize(const gvfg_runtime_info_t &info); void updatePreviewSourceSize(const gvfg_runtime_info_t &info,
const gvfg_signal_status_t &signal);
void updatePreviewSourceSize(); void updatePreviewSourceSize();
void updateSignalStatus(bool writeLog); void updateSignalStatus();
void updateUiState(); void updateUiState();
void showError(const QString &apiName, gvfg_status_t status); void showError(const QString &apiName, gvfg_status_t status);
void openLogFile(); void openLogFile();
bool openLogFilePart(); bool openLogFilePart();
void rotateLogFileIfNeeded(); void rotateLogFileIfNeeded();
void writeLogFileLine(const QString &line); void writeLogFileLine(const QString &line);
void writeDiagnosticSnapshot(const QString &statusText);
void appendLog(const QString &message); void appendLog(const QString &message);
void captureReadLoop(); void captureReadLoop();
void joinCaptureThread(); void joinCaptureThread();
@@ -68,10 +71,11 @@ private:
std::atomic<bool> captureRunning_{false}; std::atomic<bool> captureRunning_{false};
std::atomic<bool> captureStop_{false}; std::atomic<bool> captureStop_{false};
std::thread captureThread_; std::thread captureThread_;
std::atomic<uint64_t> frameCount_{0};
uint64_t previewFailureCount_ = 0; uint64_t previewFailureCount_ = 0;
QTimer *signalStatusTimer_ = nullptr; QTimer *signalStatusTimer_ = nullptr;
QString lastSignalStatusText_; QString lastSignalStatusText_;
QString lastLoggedBackendError_;
QElapsedTimer diagnosticSnapshotTimer_;
QFile logFile_; QFile logFile_;
std::mutex logFileMutex_; std::mutex logFileMutex_;
QString logDirPath_; QString logDirPath_;
+54 -21
View File
@@ -9,12 +9,18 @@
* Minimal capture flow: * Minimal capture flow:
* *
* gvfg_device_info_t devices[GVFG_MAX_DEVICES] = {}; * gvfg_device_info_t devices[GVFG_MAX_DEVICES] = {};
* int count = gvfg_enumerate_devices(devices, GVFG_MAX_DEVICES); * const int count = gvfg_enumerate_devices(devices, GVFG_MAX_DEVICES);
* if (count <= 0)
* return;
* *
* gvfg_handle h = NULL; * gvfg_handle h = NULL;
* gvfg_create(&h); * if (gvfg_create(&h) != GVFG_OK)
* gvfg_open(h, devices[0].index); * return;
* gvfg_start(h); * if (gvfg_open(h, devices[0].index) != GVFG_OK ||
* gvfg_start(h) != GVFG_OK) {
* gvfg_destroy(h);
* return;
* }
* *
* while (running) { * while (running) {
* gvfg_frame_t frame = {}; * gvfg_frame_t frame = {};
@@ -33,6 +39,18 @@
* - The frame data pointer remains valid until gvfg_release_frame() is called. * - The frame data pointer remains valid until gvfg_release_frame() is called.
* Copy the data if it must outlive that call. * Copy the data if it must outlive that call.
* - At most one frame may be held by a handle at a time. * - At most one frame may be held by a handle at a time.
* - Query functions and gvfg_poll_event() may run concurrently with the single
* frame-reading thread. Lifecycle calls must be serialized by the application.
* gvfg_stop() may cancel a blocked read/poll, but no thread may access a held
* frame while stop/destroy invalidates it.
*
* ABI policy:
* - gvfg_handle remains opaque.
* - gvfg_frame_t contains only mandatory per-frame fields and is frozen after
* the first stable SDK release.
* - Extensible metadata is returned by dedicated query APIs whose output
* structures begin with struct_size.
* - Breaking existing ABI requires a new major SDK version.
*/ */
#ifdef _WIN32 #ifdef _WIN32
@@ -69,6 +87,9 @@
#include <stdint.h> #include <stdint.h>
/* Consistent timeout value for an indefinite wait. A timeout of 0 never waits. */
#define GVFG_TIMEOUT_INFINITE UINT32_MAX
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@@ -83,7 +104,7 @@ typedef enum
{ {
GVFG_OK = 0, GVFG_OK = 0,
GVFG_EINVAL = -1, /* Invalid argument, such as NULL handle/output pointer. */ GVFG_EINVAL = -1, /* Invalid argument, such as NULL handle/output pointer. */
GVFG_ENODEV = -2, /* No GVFG device, no signal, or device open failed. */ GVFG_ENODEV = -2, /* No GVFG capture device, or the device cannot be opened. */
GVFG_ESTATE = -3, /* API was called in the wrong state. */ GVFG_ESTATE = -3, /* API was called in the wrong state. */
GVFG_EIO = -4, /* Driver/backend I/O failure. */ GVFG_EIO = -4, /* Driver/backend I/O failure. */
GVFG_ENOTSUP = -5, /* Requested feature or format is not supported. */ GVFG_ENOTSUP = -5, /* Requested feature or format is not supported. */
@@ -117,11 +138,12 @@ typedef struct
typedef struct typedef struct
{ {
uint32_t struct_size; /* Set to sizeof(gvfg_signal_status_t) before calling. */
int connected; /* Non-zero while the selected channel has a valid input signal. */ int connected; /* Non-zero while the selected channel has a valid input signal. */
int channel; /* gvfg_channel_t selected when the device was opened. */ int channel; /* gvfg_channel_t selected when the device was opened. */
int width; /* Signal width in pixels when connected. */ int width; /* Signal width in pixels when connected. */
int height; /* Signal height in pixels when connected. */ int height; /* Signal height in pixels when connected. */
char pixel_format[16]; /* Actual DMA payload format, for example Y210. */ int pixel_format; /* gvfg_pixel_format_t value for the actual DMA payload. */
int bit_depth; /* Signal bit depth derived from the payload format. */ int bit_depth; /* Signal bit depth derived from the payload format. */
} gvfg_signal_status_t; } gvfg_signal_status_t;
@@ -130,13 +152,13 @@ typedef struct
int width; /* Width of the most recent frame returned by gvfg_read_frame(). */ int width; /* Width of the most recent frame returned by gvfg_read_frame(). */
int height; /* Height of the most recent frame returned by gvfg_read_frame(). */ int height; /* Height of the most recent frame returned by gvfg_read_frame(). */
int bit_depth; /* Bits per color channel of the frame buffer. */ int bit_depth; /* Bits per color channel of the frame buffer. */
char pixel_format[32]; /* Native frame buffer format: YUY2 or Y210. */ int pixel_format; /* gvfg_pixel_format_t value: YUY2 or Y210. */
int valid; /* Non-zero while capture is running after at least one frame read. */ int valid; /* Non-zero while capture is running after at least one frame read. */
} gvfg_last_frame_info_t; } gvfg_last_frame_info_t;
typedef struct typedef struct
{ {
gvfg_signal_status_t input_signal; /* Decoded input signal metadata. */ uint32_t struct_size; /* Set to sizeof(gvfg_runtime_info_t) before calling. */
gvfg_last_frame_info_t last_frame; /* Last frame returned by gvfg_read_frame(). */ gvfg_last_frame_info_t last_frame; /* Last frame returned by gvfg_read_frame(). */
double capture_fps; /* Runtime FPS measured from frames returned by gvfg_read_frame(). */ double capture_fps; /* Runtime FPS measured from frames returned by gvfg_read_frame(). */
uint64_t delivered_frames; /* Number of frames returned by gvfg_read_frame(). */ uint64_t delivered_frames; /* Number of frames returned by gvfg_read_frame(). */
@@ -150,7 +172,7 @@ typedef struct
int height; /* Frame height in pixels. */ int height; /* Frame height in pixels. */
int pixel_format; /* gvfg_pixel_format_t value. */ int pixel_format; /* gvfg_pixel_format_t value. */
int bit_depth; /* Bits per color channel of the native frame. */ int bit_depth; /* Bits per color channel of the native frame. */
uint64_t frame_id; /* Monotonic frame identifier from the backend. */ uint64_t frame_id; /* Monotonic identifier within the current gvfg_start()/stop() run. */
} gvfg_frame_t; } gvfg_frame_t;
typedef struct typedef struct
@@ -163,7 +185,6 @@ typedef struct
int plane_stride[GVFG_MAX_PLANES]; /* Bytes from one row to the next for each plane. */ int plane_stride[GVFG_MAX_PLANES]; /* Bytes from one row to the next for each plane. */
uint64_t plane_size[GVFG_MAX_PLANES]; /* Bytes available in each plane. */ uint64_t plane_size[GVFG_MAX_PLANES]; /* Bytes available in each plane. */
uint64_t plane_offset[GVFG_MAX_PLANES]; /* Byte offset from frame.data to each plane. */ uint64_t plane_offset[GVFG_MAX_PLANES]; /* Byte offset from frame.data to each plane. */
uint64_t reserved[8]; /* Reserved for future SDK/driver layout metadata. Must be ignored. */
} gvfg_frame_layout_t; } gvfg_frame_layout_t;
typedef enum typedef enum
@@ -183,7 +204,7 @@ typedef enum
typedef struct typedef struct
{ {
gvfg_event_type_t type; gvfg_event_type_t type;
uint64_t timestamp_ns; uint64_t timestamp_ns; /* Monotonic timestamp for ordering; not Unix/wall-clock time. */
} gvfg_event_t; } gvfg_event_t;
/* Opaque session handle created by gvfg_create() and released by gvfg_destroy(). */ /* Opaque session handle created by gvfg_create() and released by gvfg_destroy(). */
@@ -268,7 +289,7 @@ GVFG_API gvfg_status_t gvfg_open_channel(
* Configure and start capture on an opened device. * Configure and start capture on an opened device.
* *
* Parameters: * Parameters:
* - handle: Opened session handle. * - handle: Running session handle.
* *
* Returns: * Returns:
* - GVFG_OK on success, including when capture is already running or the SDK * - GVFG_OK on success, including when capture is already running or the SDK
@@ -290,7 +311,8 @@ GVFG_API gvfg_status_t gvfg_start(
* Parameters: * Parameters:
* - handle: Running capture session. * - handle: Running capture session.
* - out_frame: Receives a frame descriptor. Must not be NULL. * - out_frame: Receives a frame descriptor. Must not be NULL.
* - timeout_ms: Maximum time to wait. Use 0 to wait indefinitely. * - timeout_ms: Maximum time to wait. Use 0 for a non-blocking read or
* GVFG_TIMEOUT_INFINITE to wait indefinitely.
* *
* Returns: * Returns:
* - GVFG_OK on success. * - GVFG_OK on success.
@@ -352,11 +374,13 @@ GVFG_API gvfg_status_t gvfg_release_frame(
* Parameters: * Parameters:
* - handle: Opened session handle. * - handle: Opened session handle.
* - out_event: Receives the event. Must not be NULL. * - out_event: Receives the event. Must not be NULL.
* - timeout_ms: Maximum time to wait. Use 0 to return immediately. * - timeout_ms: Maximum time to wait. Use 0 to return immediately or
* GVFG_TIMEOUT_INFINITE to wait indefinitely.
* *
* Returns: * Returns:
* - GVFG_OK on success. * - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_event is NULL. * - GVFG_EINVAL if handle or out_event is NULL.
* - GVFG_ESTATE if capture is not running or is stopped while waiting.
* - GVFG_ETIMEOUT if no event is available before timeout_ms expires. * - GVFG_ETIMEOUT if no event is available before timeout_ms expires.
*/ */
GVFG_API gvfg_status_t gvfg_poll_event( GVFG_API gvfg_status_t gvfg_poll_event(
@@ -389,16 +413,18 @@ GVFG_API gvfg_status_t gvfg_stop(
* Returns: * Returns:
* - GVFG_OK on success. * - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_status is NULL. * - GVFG_EINVAL if handle or out_status is NULL.
* - GVFG_ENODEV if no valid signal information is available. * - GVFG_EINVAL if out_status->struct_size is too small.
* - GVFG_ESTATE if no capture device is open.
* *
* Use gvfg_runtime_info_t::last_frame for the frame buffer format. * No input signal is a normal state: the function returns GVFG_OK with
* out_status->connected set to 0. Set out_status->struct_size before calling.
*/ */
GVFG_API gvfg_status_t gvfg_get_signal_status( GVFG_API gvfg_status_t gvfg_get_signal_status(
_In_ gvfg_handle handle, _In_ gvfg_handle handle,
_Out_ gvfg_signal_status_t *out_status); _Inout_ gvfg_signal_status_t *out_status);
/* /*
* Query runtime capture diagnostics. * Query runtime frame-delivery diagnostics.
* *
* Parameters: * Parameters:
* - handle: Opened or running session handle. * - handle: Opened or running session handle.
@@ -407,13 +433,20 @@ GVFG_API gvfg_status_t gvfg_get_signal_status(
* Returns: * Returns:
* - GVFG_OK on success. * - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_info is NULL. * - GVFG_EINVAL if handle or out_info is NULL.
* - GVFG_EINVAL if out_info->struct_size is too small.
* *
* The result includes current signal status, SDK-measured capture FPS, and the * The result includes the latest delivered frame, SDK-measured capture FPS,
* number of frames delivered by the SDK. * and the number of frames delivered by the SDK. Query current input signal
* metadata separately with gvfg_get_signal_status(). Set out_info->struct_size
* before calling.
*/ */
GVFG_API gvfg_status_t gvfg_get_runtime_info( GVFG_API gvfg_status_t gvfg_get_runtime_info(
_In_ gvfg_handle handle, _In_ gvfg_handle handle,
_Out_ gvfg_runtime_info_t *out_info); _Inout_ gvfg_runtime_info_t *out_info);
/* Convert a gvfg_pixel_format_t value to a static English format name. */
GVFG_API const char *gvfg_pixel_format_name(
_In_ int pixel_format);
/* /*
* Convert a GVFG status code to a static English error string. * Convert a GVFG status code to a static English error string.
@@ -177,6 +177,7 @@ namespace gvfg::internal
configured_ = false; configured_ = false;
signal_presence_known_.store(false, std::memory_order_release); signal_presence_known_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release);
signal_probe_active_.store(false, std::memory_order_release);
clear_last_error(); clear_last_error();
PCIES2MM_LOG("open_device: %s", wide_to_utf8(base_path_).c_str()); PCIES2MM_LOG("open_device: %s", wide_to_utf8(base_path_).c_str());
return PCIES2MM_OK; return PCIES2MM_OK;
@@ -190,6 +191,7 @@ namespace gvfg::internal
configured_ = false; configured_ = false;
signal_presence_known_.store(false, std::memory_order_release); signal_presence_known_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release);
signal_probe_active_.store(false, std::memory_order_release);
base_path_.clear(); base_path_.clear();
friendly_name_.clear(); friendly_name_.clear();
reset_stats(stats_, PCIES2MM_STREAM_STOPPED); reset_stats(stats_, PCIES2MM_STREAM_STOPPED);
@@ -232,16 +234,10 @@ namespace gvfg::internal
const bool haveRawSize = widthOk && heightOk && rawWidth != 0 && rawHeight != 0; const bool haveRawSize = widthOk && heightOk && rawWidth != 0 && rawHeight != 0;
const bool presenceKnown = signal_presence_known_.load(std::memory_order_acquire); const bool presenceKnown = signal_presence_known_.load(std::memory_order_acquire);
if (!presenceKnown) // H/V/format registers can retain their previous values after signal
signal_present_.store(haveRawSize, std::memory_order_release); // loss. They describe a candidate DMA layout, never signal presence.
const bool signalPresent = presenceKnown &&
// Before the driver reports an explicit plug/unplug event, raw H/V is signal_present_.load(std::memory_order_acquire);
// only a probe result, not a permanent disconnected state. This matters
// when the cable was already connected before the SDK registered its
// event handles and the first register read happened too early.
const bool signalPresent = presenceKnown
? signal_present_.load(std::memory_order_acquire)
: haveRawSize;
pcies2mm_pixel_format_t fmt = formatOk ? decode_pixel_format(rawFormat) : PCIES2MM_PIXFMT_UNKNOWN; pcies2mm_pixel_format_t fmt = formatOk ? decode_pixel_format(rawFormat) : PCIES2MM_PIXFMT_UNKNOWN;
const uint32_t width = signalPresent && haveRawSize ? rawWidth : 0; const uint32_t width = signalPresent && haveRawSize ? rawWidth : 0;
@@ -338,8 +334,13 @@ namespace gvfg::internal
return fail(PCIES2MM_EIO, "REGISTER_EVENT", err); return fail(PCIES2MM_EIO, "REGISTER_EVENT", err);
} }
const bool startCaptureNow = signal_present_.load(std::memory_order_acquire); // Events are edge-triggered, so a source connected before registration
if (startCaptureNow) // may not produce a plug-in event. Probe DMA using the register layout,
// but do not report connected until a full frame is received.
signal_presence_known_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release);
const bool startProbeNow = refresh_stream_from_registers(true);
if (startProbeNow)
{ {
// Match the proven CaptureDemo sequence: register events first, // Match the proven CaptureDemo sequence: register events first,
// enable DMA/video second, then start the single wait thread. // enable DMA/video second, then start the single wait thread.
@@ -357,7 +358,8 @@ namespace gvfg::internal
} }
running_ = true; running_ = true;
capture_active_ = startCaptureNow; capture_active_ = startProbeNow;
signal_probe_active_ = startProbeNow;
try try
{ {
capture_thread_ = std::thread(&PcieS2mmCaptureSession::capture_thread_proc, this); capture_thread_ = std::thread(&PcieS2mmCaptureSession::capture_thread_proc, this);
@@ -366,7 +368,8 @@ namespace gvfg::internal
{ {
running_ = false; running_ = false;
capture_active_ = false; capture_active_ = false;
if (startCaptureNow) signal_probe_active_ = false;
if (startProbeNow)
{ {
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0); write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
write_reg(video_base() + VIDEO_EN_OFFSET, 0); write_reg(video_base() + VIDEO_EN_OFFSET, 0);
@@ -376,17 +379,11 @@ namespace gvfg::internal
return fail(PCIES2MM_EIO, "capture_thread", ERROR_NOT_ENOUGH_MEMORY); return fail(PCIES2MM_EIO, "capture_thread", ERROR_NOT_ENOUGH_MEMORY);
} }
if (startCaptureNow) PCIES2MM_LOG("start: channel=%u base=0x%x bytes=%zu probe_active=%d",
{
std::lock_guard<std::mutex> lock(mutex_);
stats_.state = PCIES2MM_STREAM_RUNNING;
}
PCIES2MM_LOG("start: channel=%u base=0x%x bytes=%zu capture_active=%d",
channel, channel,
video_base(), video_base(),
bytes, frame_size_bytes(),
startCaptureNow ? 1 : 0); startProbeNow ? 1 : 0);
return PCIES2MM_OK; return PCIES2MM_OK;
} }
@@ -398,6 +395,7 @@ namespace gvfg::internal
const uint32_t channel = active_channel(); const uint32_t channel = active_channel();
running_ = false; running_ = false;
capture_active_ = false; capture_active_ = false;
signal_probe_active_ = false;
if (device_ != INVALID_HANDLE_VALUE) if (device_ != INVALID_HANDLE_VALUE)
{ {
@@ -450,6 +448,14 @@ namespace gvfg::internal
}; };
if (timeoutMs == 0) if (timeoutMs == 0)
{
if (!hasFrame())
{
++wait_timeout_count_;
return PCIES2MM_ETIMEOUT;
}
}
else if (timeoutMs == UINT32_MAX)
{ {
frame_cv_.wait(lock, hasFrame); frame_cv_.wait(lock, hasFrame);
} }
@@ -722,10 +728,22 @@ namespace gvfg::internal
break; break;
if (waitResult == WAIT_TIMEOUT) if (waitResult == WAIT_TIMEOUT)
{ {
if (!signal_presence_known_.load(std::memory_order_acquire)) if (!signal_presence_known_.load(std::memory_order_acquire) &&
!capture_active_.load(std::memory_order_acquire) &&
refresh_stream_from_registers(true))
{ {
pcies2mm_signal_status_t probe{}; const bool dmaEnableOk = write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 1);
get_signal_status(probe); const bool videoEnableOk = write_reg(video_base() + VIDEO_EN_OFFSET, 1);
if (dmaEnableOk && videoEnableOk)
{
signal_probe_active_.store(true, std::memory_order_release);
capture_active_.store(true, std::memory_order_release);
}
else
{
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
write_reg(video_base() + VIDEO_EN_OFFSET, 0);
}
} }
if (signal_present_.load(std::memory_order_acquire) && if (signal_present_.load(std::memory_order_acquire) &&
!capture_active_.load(std::memory_order_acquire)) !capture_active_.load(std::memory_order_acquire))
@@ -847,6 +865,14 @@ namespace gvfg::internal
return; return;
} }
if (signal_probe_active_.exchange(false, std::memory_order_acq_rel))
{
signal_present_.store(true, std::memory_order_release);
signal_presence_known_.store(true, std::memory_order_release);
emit_event(PCIES2MM_EVENT_PLUG_IN, channel == 0 ? 0 : 4, video_irq_mask_bit());
emit_event(PCIES2MM_EVENT_CAPTURE_RESUMED, channel == 0 ? 0 : 4, video_irq_mask_bit());
}
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (pending_events_ > 0) if (pending_events_ > 0)
@@ -870,6 +896,16 @@ namespace gvfg::internal
void PcieS2mmCaptureSession::handle_plugin_event(uint32_t channel) void PcieS2mmCaptureSession::handle_plugin_event(uint32_t channel)
{ {
if (signal_presence_known_.load(std::memory_order_acquire) &&
signal_present_.load(std::memory_order_acquire))
return;
if (capture_active_.exchange(false, std::memory_order_acq_rel))
{
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
write_reg(video_base() + VIDEO_EN_OFFSET, 0);
}
signal_probe_active_.store(false, std::memory_order_release);
signal_present_.store(true, std::memory_order_release); signal_present_.store(true, std::memory_order_release);
signal_presence_known_.store(true, std::memory_order_release); signal_presence_known_.store(true, std::memory_order_release);
emit_event(PCIES2MM_EVENT_PLUG_IN, channel == 0 ? 0 : 4, video_irq_mask_bit()); emit_event(PCIES2MM_EVENT_PLUG_IN, channel == 0 ? 0 : 4, video_irq_mask_bit());
@@ -880,6 +916,7 @@ namespace gvfg::internal
void PcieS2mmCaptureSession::handle_unplug_event(uint32_t channel) void PcieS2mmCaptureSession::handle_unplug_event(uint32_t channel)
{ {
signal_probe_active_.store(false, std::memory_order_release);
signal_present_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release);
signal_presence_known_.store(true, std::memory_order_release); signal_presence_known_.store(true, std::memory_order_release);
write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0); write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 0);
@@ -906,7 +943,7 @@ namespace gvfg::internal
{ {
if (!running_.load(std::memory_order_acquire) || if (!running_.load(std::memory_order_acquire) ||
!signal_present_.load(std::memory_order_acquire) || !signal_present_.load(std::memory_order_acquire) ||
!refresh_stream_from_signal(true)) !refresh_stream_from_registers(true))
return false; return false;
const bool dmaEnableOk = write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 1); const bool dmaEnableOk = write_reg(video_base() + VIDEO_DMA_EN_OFFSET, 1);
@@ -930,6 +967,7 @@ namespace gvfg::internal
} }
capture_active_.store(true, std::memory_order_release); capture_active_.store(true, std::memory_order_release);
signal_probe_active_.store(false, std::memory_order_release);
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
stream_error_ = false; stream_error_ = false;
@@ -941,31 +979,35 @@ namespace gvfg::internal
return true; return true;
} }
bool PcieS2mmCaptureSession::refresh_stream_from_signal(bool resizeRing) bool PcieS2mmCaptureSession::refresh_stream_from_registers(bool resizeRing)
{ {
pcies2mm_signal_status_t signal{}; uint32_t width = 0;
if (get_signal_status(signal) != PCIES2MM_OK || uint32_t height = 0;
signal.width == 0 || uint32_t rawFormat = 0;
signal.height == 0 || if (!read_reg(video_base() + VIDEO_HSIZE_OFFSET, width) ||
signal.pixel_format == PCIES2MM_PIXFMT_UNKNOWN) !read_reg(video_base() + VIDEO_VSIZE_OFFSET, height) ||
{ !read_reg(video_base() + VIDEO_FORMAT_OFFSET, rawFormat) ||
PCIES2MM_ERROR_LOG("refresh_stream_from_signal failed"); width == 0 || height == 0)
return false; return false;
}
const uint32_t bitDepth = bit_depth_for_pixfmt(signal.pixel_format); const pcies2mm_pixel_format_t pixelFormat = decode_pixel_format(rawFormat);
const size_t bytes = bytes_per_frame(signal.width, signal.height, signal.pixel_format); if (pixelFormat == PCIES2MM_PIXFMT_UNKNOWN)
return false;
const uint32_t bitDepth = bit_depth_for_pixfmt(pixelFormat);
const size_t bytes = bytes_per_frame(width, height, pixelFormat);
if (bytes == 0 || bytes > (std::numeric_limits<DWORD>::max)()) if (bytes == 0 || bytes > (std::numeric_limits<DWORD>::max)())
{ {
PCIES2MM_ERROR_LOG("refresh_stream_from_signal invalid frame size width=%u height=%u bytes=%zu", PCIES2MM_ERROR_LOG("refresh_stream_from_registers invalid frame size width=%u height=%u bytes=%zu",
signal.width, width,
signal.height, height,
bytes); bytes);
return false; return false;
} }
std::unique_lock<std::mutex> lock(mutex_); std::unique_lock<std::mutex> lock(mutex_);
if (resizeRing) const bool wasRunning = running_.load(std::memory_order_acquire);
if (resizeRing && wasRunning)
{ {
data_cv_.wait(lock, [this]() data_cv_.wait(lock, [this]()
{ return !running_.load(std::memory_order_acquire) || { return !running_.load(std::memory_order_acquire) ||
@@ -973,9 +1015,9 @@ namespace gvfg::internal
if (!running_.load(std::memory_order_acquire)) if (!running_.load(std::memory_order_acquire))
return false; return false;
} }
stream_desc_.width = signal.width; stream_desc_.width = width;
stream_desc_.height = signal.height; stream_desc_.height = height;
stream_desc_.pixel_format = signal.pixel_format; stream_desc_.pixel_format = pixelFormat;
stream_bit_depth_ = bitDepth; stream_bit_depth_ = bitDepth;
if (resizeRing) if (resizeRing)
{ {
@@ -62,7 +62,7 @@ namespace gvfg::internal
void handle_plugin_event(uint32_t channel); void handle_plugin_event(uint32_t channel);
void handle_unplug_event(uint32_t channel); void handle_unplug_event(uint32_t channel);
bool resume_capture_from_signal(uint32_t channel); bool resume_capture_from_signal(uint32_t channel);
bool refresh_stream_from_signal(bool resizeRing); bool refresh_stream_from_registers(bool resizeRing);
void publish_frame(size_t slotIndex, size_t bytes); void publish_frame(size_t slotIndex, size_t bytes);
void emit_event(pcies2mm_event_type_t type, uint32_t irqBit, uint32_t irqMask) const; void emit_event(pcies2mm_event_type_t type, uint32_t irqBit, uint32_t irqMask) const;
@@ -102,6 +102,7 @@ namespace gvfg::internal
std::atomic<bool> running_{false}; std::atomic<bool> running_{false};
std::atomic<bool> capture_active_{false}; std::atomic<bool> capture_active_{false};
std::atomic<bool> signal_probe_active_{false};
mutable std::atomic<bool> signal_presence_known_{false}; mutable std::atomic<bool> signal_presence_known_{false};
mutable std::atomic<bool> signal_present_{false}; mutable std::atomic<bool> signal_present_{false};
std::thread capture_thread_; std::thread capture_thread_;
+81 -16
View File
@@ -8,18 +8,32 @@
#include <chrono> #include <chrono>
#include <climits> #include <climits>
#include <condition_variable> #include <condition_variable>
#include <cstddef>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <deque> #include <deque>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <type_traits>
#include <vector> #include <vector>
using namespace gvfg::internal; using namespace gvfg::internal;
namespace namespace
{ {
#if INTPTR_MAX == INT64_MAX
static_assert(std::is_standard_layout_v<gvfg_frame_t>);
static_assert(sizeof(gvfg_frame_t) == 40, "gvfg_frame_t x64 ABI must remain frozen");
static_assert(offsetof(gvfg_frame_t, data) == 0);
static_assert(offsetof(gvfg_frame_t, data_size) == 8);
static_assert(offsetof(gvfg_frame_t, width) == 16);
static_assert(offsetof(gvfg_frame_t, height) == 20);
static_assert(offsetof(gvfg_frame_t, pixel_format) == 24);
static_assert(offsetof(gvfg_frame_t, bit_depth) == 28);
static_assert(offsetof(gvfg_frame_t, frame_id) == 32);
#endif
void copy_cstr(char *dst, size_t dstSize, const char *src) void copy_cstr(char *dst, size_t dstSize, const char *src)
{ {
if (!dst || dstSize == 0) if (!dst || dstSize == 0)
@@ -129,7 +143,7 @@ namespace
} }
} }
const char *gvfg_pixel_format_name(int fmt) const char *pixel_format_name(int fmt)
{ {
switch (fmt) switch (fmt)
{ {
@@ -159,8 +173,6 @@ namespace
std::memset(layout.plane_stride, 0, sizeof(layout.plane_stride)); std::memset(layout.plane_stride, 0, sizeof(layout.plane_stride));
std::memset(layout.plane_size, 0, sizeof(layout.plane_size)); std::memset(layout.plane_size, 0, sizeof(layout.plane_size));
std::memset(layout.plane_offset, 0, sizeof(layout.plane_offset)); std::memset(layout.plane_offset, 0, sizeof(layout.plane_offset));
std::memset(layout.reserved, 0, sizeof(layout.reserved));
if (!frame.data || frame.data_size == 0 || frame.width <= 0 || frame.height <= 0) if (!frame.data || frame.data_size == 0 || frame.width <= 0 || frame.height <= 0)
return GVFG_EINVAL; return GVFG_EINVAL;
@@ -263,6 +275,7 @@ struct gvfg_handle_t
gvfg_status_t stop() gvfg_status_t stop()
{ {
running = false; running = false;
eventCv.notify_all();
releaseHeldFrameForStop(); releaseHeldFrameForStop();
if (backend) if (backend)
backend->stop_stream(); backend->stop_stream();
@@ -284,6 +297,7 @@ struct gvfg_handle_t
gvfg_status_t getSignalStatus(gvfg_signal_status_t &out) gvfg_status_t getSignalStatus(gvfg_signal_status_t &out)
{ {
std::memset(&out, 0, sizeof(out)); std::memset(&out, 0, sizeof(out));
out.struct_size = sizeof(out);
const pcies2mm_status_t status = querySignal(); const pcies2mm_status_t status = querySignal();
{ {
std::lock_guard<std::mutex> lock(stateMutex); std::lock_guard<std::mutex> lock(stateMutex);
@@ -291,16 +305,18 @@ struct gvfg_handle_t
out.channel = static_cast<int>(selectedChannel); out.channel = static_cast<int>(selectedChannel);
out.width = static_cast<int>(width); out.width = static_cast<int>(width);
out.height = static_cast<int>(height); out.height = static_cast<int>(height);
copy_cstr(out.pixel_format, sizeof(out.pixel_format), gvfg_pixel_format_name(to_gvfg_pixel_format(pixelFormat))); out.pixel_format = to_gvfg_pixel_format(pixelFormat);
out.bit_depth = static_cast<int>(bitDepth); out.bit_depth = static_cast<int>(bitDepth);
} }
return map_status(status); // A disconnected input is a normal query result, not a missing-device
// error. The opened device remains usable for plug-in monitoring.
return status == PCIES2MM_ENODEV ? GVFG_OK : map_status(status);
} }
gvfg_status_t getRuntimeInfo(gvfg_runtime_info_t &out) gvfg_status_t getRuntimeInfo(gvfg_runtime_info_t &out)
{ {
std::memset(&out, 0, sizeof(out)); std::memset(&out, 0, sizeof(out));
getSignalStatus(out.input_signal); out.struct_size = sizeof(out);
const uint64_t frames = deliveredFrames.load(std::memory_order_relaxed); const uint64_t frames = deliveredFrames.load(std::memory_order_relaxed);
const bool deliveredValid = running.load(std::memory_order_relaxed) && frames > 0; const bool deliveredValid = running.load(std::memory_order_relaxed) && frames > 0;
@@ -310,9 +326,7 @@ struct gvfg_handle_t
out.last_frame.width = static_cast<int>(deliveredWidth.load(std::memory_order_relaxed)); out.last_frame.width = static_cast<int>(deliveredWidth.load(std::memory_order_relaxed));
out.last_frame.height = static_cast<int>(deliveredHeight.load(std::memory_order_relaxed)); out.last_frame.height = static_cast<int>(deliveredHeight.load(std::memory_order_relaxed));
out.last_frame.bit_depth = static_cast<int>(deliveredBitDepth.load(std::memory_order_relaxed)); out.last_frame.bit_depth = static_cast<int>(deliveredBitDepth.load(std::memory_order_relaxed));
copy_cstr(out.last_frame.pixel_format, out.last_frame.pixel_format = deliveredPixelFormat.load(std::memory_order_relaxed);
sizeof(out.last_frame.pixel_format),
gvfg_pixel_format_name(deliveredPixelFormat.load(std::memory_order_relaxed)));
} }
out.capture_fps = runtimeFps.load(std::memory_order_relaxed); out.capture_fps = runtimeFps.load(std::memory_order_relaxed);
out.delivered_frames = frames; out.delivered_frames = frames;
@@ -509,10 +523,13 @@ struct gvfg_handle_t
gvfg_status_t pollEvent(gvfg_event_t &out, uint32_t timeoutMs) gvfg_status_t pollEvent(gvfg_event_t &out, uint32_t timeoutMs)
{ {
if (!backend || !running.load(std::memory_order_acquire))
return GVFG_ESTATE;
std::unique_lock<std::mutex> lock(eventMutex); std::unique_lock<std::mutex> lock(eventMutex);
const auto hasEvent = [this]() const auto hasEvent = [this]()
{ {
return !eventQueue.empty(); return !eventQueue.empty() || !running.load(std::memory_order_acquire);
}; };
if (timeoutMs == 0) if (timeoutMs == 0)
@@ -520,11 +537,18 @@ struct gvfg_handle_t
if (!hasEvent()) if (!hasEvent())
return GVFG_ETIMEOUT; return GVFG_ETIMEOUT;
} }
else if (timeoutMs == GVFG_TIMEOUT_INFINITE)
{
eventCv.wait(lock, hasEvent);
}
else if (!eventCv.wait_for(lock, std::chrono::milliseconds(timeoutMs), hasEvent)) else if (!eventCv.wait_for(lock, std::chrono::milliseconds(timeoutMs), hasEvent))
{ {
return GVFG_ETIMEOUT; return GVFG_ETIMEOUT;
} }
if (eventQueue.empty())
return GVFG_ESTATE;
out = eventQueue.front(); out = eventQueue.front();
eventQueue.pop_front(); eventQueue.pop_front();
return GVFG_OK; return GVFG_OK;
@@ -734,13 +758,21 @@ extern "C"
{ {
if (!frame || !out_layout) if (!frame || !out_layout)
return GVFG_EINVAL; return GVFG_EINVAL;
if (out_layout->struct_size < sizeof(gvfg_frame_layout_t)) constexpr uint32_t kFrameLayoutV1Size =
static_cast<uint32_t>(offsetof(gvfg_frame_layout_t, plane_offset) + sizeof(out_layout->plane_offset));
const uint32_t callerSize = out_layout->struct_size;
if (callerSize < kFrameLayoutV1Size)
return GVFG_EINVAL; return GVFG_EINVAL;
const uint32_t callerSize = out_layout->struct_size; gvfg_frame_layout_t layout{};
std::memset(out_layout, 0, sizeof(*out_layout)); layout.struct_size = sizeof(layout);
const gvfg_status_t status = populate_frame_layout(*frame, layout);
if (status != GVFG_OK)
return status;
std::memcpy(out_layout, &layout, std::min<size_t>(callerSize, sizeof(layout)));
out_layout->struct_size = callerSize; out_layout->struct_size = callerSize;
return populate_frame_layout(*frame, *out_layout); return GVFG_OK;
} }
gvfg_status_t gvfg_release_frame(gvfg_handle handle, const gvfg_frame_t *frame) gvfg_status_t gvfg_release_frame(gvfg_handle handle, const gvfg_frame_t *frame)
@@ -768,14 +800,47 @@ extern "C"
{ {
if (!handle || !out_status) if (!handle || !out_status)
return GVFG_EINVAL; return GVFG_EINVAL;
return handle->getSignalStatus(*out_status); constexpr uint32_t kSignalStatusV1Size =
static_cast<uint32_t>(offsetof(gvfg_signal_status_t, bit_depth) + sizeof(out_status->bit_depth));
const uint32_t callerSize = out_status->struct_size;
if (callerSize < kSignalStatusV1Size)
return GVFG_EINVAL;
gvfg_signal_status_t statusInfo{};
statusInfo.struct_size = sizeof(statusInfo);
const gvfg_status_t status = handle->getSignalStatus(statusInfo);
if (status != GVFG_OK)
return status;
std::memcpy(out_status, &statusInfo, std::min<size_t>(callerSize, sizeof(statusInfo)));
out_status->struct_size = callerSize;
return GVFG_OK;
} }
gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, gvfg_runtime_info_t *out_info) gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, gvfg_runtime_info_t *out_info)
{ {
if (!handle || !out_info) if (!handle || !out_info)
return GVFG_EINVAL; return GVFG_EINVAL;
return handle->getRuntimeInfo(*out_info); constexpr uint32_t kRuntimeInfoV1Size =
static_cast<uint32_t>(offsetof(gvfg_runtime_info_t, delivered_frames) + sizeof(out_info->delivered_frames));
const uint32_t callerSize = out_info->struct_size;
if (callerSize < kRuntimeInfoV1Size)
return GVFG_EINVAL;
gvfg_runtime_info_t runtimeInfo{};
runtimeInfo.struct_size = sizeof(runtimeInfo);
const gvfg_status_t status = handle->getRuntimeInfo(runtimeInfo);
if (status != GVFG_OK)
return status;
std::memcpy(out_info, &runtimeInfo, std::min<size_t>(callerSize, sizeof(runtimeInfo)));
out_info->struct_size = callerSize;
return GVFG_OK;
}
const char *gvfg_pixel_format_name(int pixel_format)
{
return pixel_format_name(pixel_format);
} }
const char *gvfg_strerror(gvfg_status_t status) const char *gvfg_strerror(gvfg_status_t status)