diff --git a/README.md b/README.md index 10ae25e..d1d5ad9 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,11 @@ 這個 repo 以 GVFG 為 source of truth。其他專案應該透過 public header、 import library、runtime DLL 來使用 GVFG,不要直接把 GVFG source 編進去。 +## Driver compatibility + +此開發版本僅支援新 driver `vfg100_0821c`。舊版 driver、舊 IOCTL、 +done-index 與舊 SDK frame-ring 流程不在相容範圍內。 + ## 內容 - `sdk/gvfg`:GVFG customer C API、internal debug API、PCIES2MM backend。 @@ -85,7 +90,7 @@ gvfg_open_channel(handle, device_index, GVFG_CHANNEL_0); ```c uint32_t events = GVFG_EVENT_MASK_SIGNAL_CONNECTED | GVFG_EVENT_MASK_SIGNAL_DISCONNECTED | - GVFG_EVENT_MASK_FRAME_LOSS; + GVFG_EVENT_MASK_FORMAT_CHANGE_BEGIN; gvfg_set_channel_event_mask(handle, GVFG_CHANNEL_0, events); gvfg_open_channel(handle, device_index, GVFG_CHANNEL_0); ``` @@ -101,7 +106,7 @@ SDK 會在 open 時 enable zero-copy,並在 close/destroy 時 disable。 ### 同一裝置雙 channel 同一個 `gvfg_handle` 可對同一個 device index 開啟 CH0、CH1。SDK 只建立一個 -Windows device handle;兩個 channel 各自保有 capture thread、event、frame ring +Windows device handle;兩個 channel 各自保有 event、單一 frame buffer 以及 held-frame/zero-copy ownership: ```c @@ -121,7 +126,7 @@ gvfg_stop(handle); /* stop both channels */ runtime API 都明確要求 `channel_index`;不再保留隱含 selected-channel 的舊 API。 `gvfg_qt_preview.exe` 只使用 public API,主畫面只顯示 input 與 Preview -狀態;IRQ、DMA、ring slot 等資訊只存在 internal diagnostic tool。 +狀態;IRQ、DMA 等資訊只存在 internal diagnostic tool。 ## Consumer Layout diff --git a/docs/GVFG_ARCHITECTURE_OVERVIEW.drawio b/docs/GVFG_ARCHITECTURE_OVERVIEW.drawio index 6f3833d..08d204b 100644 --- a/docs/GVFG_ARCHITECTURE_OVERVIEW.drawio +++ b/docs/GVFG_ARCHITECTURE_OVERVIEW.drawio @@ -36,7 +36,7 @@ - + @@ -56,7 +56,7 @@ - + diff --git a/docs/GVFG_CUSTOMER_API.md b/docs/GVFG_CUSTOMER_API.md index e3ec9fe..c6e4942 100644 --- a/docs/GVFG_CUSTOMER_API.md +++ b/docs/GVFG_CUSTOMER_API.md @@ -183,8 +183,8 @@ Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,每次成 - `gvfg_get_channel_signal_status(handle, channel, &status)`:查詢指定 channel 的連線、尺寸、 原生格式與 bit depth。沒有輸入訊號是正常狀態:回傳 `GVFG_OK` 且 `connected == 0`。 -- `gvfg_get_channel_runtime_info(handle, channel, &info)`:取得指定 channel 已交付 frame 數、SDK 能確定的 - `lost_frames` 與依 read 間隔估算的 `capture_fps`。start 時統計值重設。 +- `gvfg_get_channel_runtime_info(handle, channel, &info)`:取得指定 channel 已交付 frame 數與 + 依 read 間隔估算的 `capture_fps`。start 時統計值重設。 ### Event @@ -197,7 +197,6 @@ Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,每次成 | `GVFG_EVENT_SIGNAL_DISCONNECTED` | 停止使用目前影像內容 | | `GVFG_EVENT_FORMAT_CHANGE_BEGIN` | 暫停使用依賴舊尺寸/格式的資源 | | `GVFG_EVENT_STREAM_READY` | 第一個完整 frame 已就緒,可依新格式重建資源 | -| `GVFG_EVENT_FRAME_LOSS` | 記錄錄影內容可能不完整;`event.count` 是本次已知 loss 數量 | 呼叫前應將 `gvfg_event_t` 清零並設定 `struct_size = sizeof(gvfg_event_t)`。 事件是狀態通知,不取代 `gvfg_get_channel_signal_status()`;需要完整 metadata 時應重新查詢。 diff --git a/docs/GVFG_CUSTOMER_API_REFERENCE.md b/docs/GVFG_CUSTOMER_API_REFERENCE.md index 853e6fc..18714c5 100644 --- a/docs/GVFG_CUSTOMER_API_REFERENCE.md +++ b/docs/GVFG_CUSTOMER_API_REFERENCE.md @@ -77,7 +77,6 @@ register 與 DMA 實作不屬於本文件。 | ------------------ | ---------- | ------------------------------------------------------- | | `capture_fps` | `double` | 依 `gvfg_read_channel_frame()` 成功交付時間估算並平滑化的 FPS;尚無足夠 frame 時為 0 | | `delivered_frames` | `uint64_t` | 此次 running session 中成功交付給 caller 的 frame 數 | -| `lost_frames` | `uint64_t` | SDK 能確定在交付前遺失的 frame 數;目前包含 capture FIFO 覆蓋 | ### 1.8 `gvfg_frame_t` @@ -124,11 +123,9 @@ Caller 不得修改任何欄位再 release。SDK 會將完整 token 與目前 he | `GVFG_EVENT_SIGNAL_DISCONNECTED` | 2 | 輸入訊號中斷 | | `GVFG_EVENT_STREAM_READY` | 3 | 啟動、重新接線或格式恢復後,第一個完整 frame 已就緒 | | `GVFG_EVENT_FORMAT_CHANGE_BEGIN` | 4 | 輸入格式正在改變,應暫停使用舊格式資源 | -| `GVFG_EVENT_FRAME_LOSS` | 5 | SDK 確定一個或多個 frame 在交付前遺失 | `gvfg_event_t` 是 `gvfg_poll_channel_event()` 的輸出。呼叫前將結構清零並把 -`struct_size` 設為 `sizeof(gvfg_event_t)`。`type` 是上述事件型別;只有 -`GVFG_EVENT_FRAME_LOSS` 使用 `count`,表示這筆事件合併的已知 loss 數量。 +`struct_size` 設為 `sizeof(gvfg_event_t)`。`type` 是上述事件型別。 `gvfg_event_mask_t` 提供對應的 `GVFG_EVENT_MASK_*` bit,可在 channel open 前用 `gvfg_set_channel_event_mask()` 組合。預設為 `GVFG_EVENT_MASK_ALL`;mask 為 0 @@ -252,7 +249,7 @@ gvfg_status_t gvfg_read_channel_frame(gvfg_handle handle, - `GVFG_ETIMEOUT`:期限內沒有 frame。 - `GVFG_EIO`/`GVFG_ENOTSUP`:frame/backend 無效或格式不支援。 -Copy mode 回傳 SDK ring buffer;zero-copy mode 回傳 driver-owned buffer。兩者的 +Copy mode 回傳 SDK 的單一 frame buffer;zero-copy mode 回傳 driver-owned buffer。兩者的 pointer 都只保證有效到對應的 `gvfg_release_channel_frame()`。 ### 1.19 `gvfg_release_channel_frame` @@ -265,7 +262,7 @@ gvfg_status_t gvfg_release_channel_frame(gvfg_handle handle, - `handle`:取得該 frame 的同一個 handle。 - `frame`:`gvfg_read_channel_frame()` 原封不動回傳的完整 descriptor。 -- `GVFG_OK`:成功歸還 frame;copy slot 可再次使用,或 zero-copy frame 已歸還 driver。 +- `GVFG_OK`:成功歸還 frame;copy buffer 可再次使用,或 zero-copy frame 已歸還 driver。 - `GVFG_EINVAL`:NULL 或 token 內容與 held frame 不符。 - `GVFG_ESTATE`:沒有 backend、目前沒有 held frame,或 backend release 狀態不正確。 diff --git a/docs/GVFG_DMA_RING_DATA_FLOW.drawio b/docs/GVFG_DMA_RING_DATA_FLOW.drawio deleted file mode 100644 index c091dce..0000000 --- a/docs/GVFG_DMA_RING_DATA_FLOW.drawio +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/GVFG_INTERNAL_NOTES.md b/docs/GVFG_INTERNAL_NOTES.md index fc26ca4..512316b 100644 --- a/docs/GVFG_INTERNAL_NOTES.md +++ b/docs/GVFG_INTERNAL_NOTES.md @@ -3,7 +3,7 @@ ## Driver IOCTL DLL 邊界 `gvfg.dll` 保留裝置列舉、`CreateFile`/`CloseHandle`、channel session、event、 -thread 與 frame ring。Driver IOCTL code、request layout 及所有 +event thread 與單一 frame buffer。Driver IOCTL code、request layout 及所有 `DeviceIoControl` 呼叫集中在內部 `giga_ioctl.dll`;GVFG 僅呼叫其具名 C API, 失敗時沿用 `GetLastError()`。`giga_ioctl.h` 是內部相依,不屬於客戶公開 API。 @@ -70,7 +70,7 @@ Created/Closed -> Opened -> Running -> Opened -> Destroyed 由 caller 序列化;若日後要宣告完整 thread-safe,必須先補足 open/start/stop/destroy 彼此的同步與 handle lifetime 保護。 -## 4. DMA 與 frame ring +## 4. DMA 與單一 frame buffer Copy mode 資料路徑: @@ -78,28 +78,17 @@ Copy mode 資料路徑: source frame -> hardware/driver DMA buffer -> DMA complete event --> capture worker 收到 DMA complete event --> IOCTL_GET_FRAME(frameIndex=0xFFFFFFFF) 複製到 SDK ring free slot --> slot ready + sequence 更新 + frame_cv notify --> wait_frame 選取 ready frame --> facade 回傳指向 slot.data 的 gvfg_frame_t +-> 呼叫 gvfg_read_channel_frame() 的 thread 等待 DMA complete event +-> IOCTL_GET_FRAME(frameIndex=0xFFFFFFFF) 直接複製到 SDK 的單一 buffer +-> facade 回傳指向該 buffer 的 gvfg_frame_t -> customer/preview/conversion -> release_frame --> slot 回到 free +-> buffer 可供下一次 read 使用 ``` -Backend stream descriptor 目前配置 3 個 SDK slots。Slot 邏輯狀態: - -```text -Free ready=false, in_use=false -Writing ready=false, in_use=true -Ready ready=true, in_use=false -Delivered ready=false, in_use=true -``` - -ring 滿時的行為是即時擷取的 drop/backpressure policy,不是 lossless queue;應透過 -internal stats 觀察 `frames_dropped`。不要將 slot 數、driver DMA buffer 數或 done-index -演算法暴露為客戶契約。 +Backend 不做 frame queue、slot 切換或 done-index 查詢。每個 channel 同一時間只允許 +一個 read,且成功取得的 frame 必須 release 後才能讀下一張。SDK 不把 driver DMA +buffer 數或 done-index 演算法暴露為客戶契約。 Zero-copy mode 資料路徑: @@ -116,10 +105,9 @@ gvfg_create -> close/destroy 時 IOCTL_GIGA_DISABLE_FRAME_ZEROCOPY(channel) ``` -Zero-copy 同時只允許一張 outstanding frame。若下一個 DMA event 到達時 caller 尚未 -release,backend 只會跳過該次 acquire,不會覆寫仍由 caller 使用的 driver pointer。 -這種情況不計入 `frames_dropped`,也不送出 `GVFG_EVENT_FRAME_LOSS`;driver 目前沒有 -提供可用來確認實際遺失 frame 的 sequence/drop counter。 +Zero-copy 同時只允許一張 outstanding frame。Caller 必須 release 目前的 +driver pointer,才能再次 read。SDK 不根據 read 間隔推算 frame loss;driver 目前也 +沒有提供可用來確認實際遺失 frame 的 sequence/drop counter。 ## 5. Frame token 與 ABI diff --git a/samples/gvfg_qt_preview/mainwindow.cpp b/samples/gvfg_qt_preview/mainwindow.cpp index bac9067..9e04b28 100644 --- a/samples/gvfg_qt_preview/mainwindow.cpp +++ b/samples/gvfg_qt_preview/mainwindow.cpp @@ -93,10 +93,6 @@ namespace return QStringLiteral("streaming"); } - QString appHoldingText(uint64_t value) - { - return value == UINT64_MAX ? QStringLiteral("none") : QStringLiteral("slot %1").arg(valueOrDash(value)); - } #endif QString frameText(bool valid, int width, int height, const char *pixelFormat, int bitDepth) @@ -148,8 +144,6 @@ namespace return QStringLiteral("STREAM_READY"); case GVFG_EVENT_FORMAT_CHANGE_BEGIN: return QStringLiteral("FORMAT_CHANGE_BEGIN"); - case GVFG_EVENT_FRAME_LOSS: - return QStringLiteral("FRAME_LOSS"); default: return QStringLiteral("UNKNOWN"); } @@ -451,12 +445,13 @@ void MainWindow::startCapture() previewCallMaximumMs_.store(0.0, std::memory_order_relaxed); previewCallWindowMaximumMs_.store(0.0, std::memory_order_relaxed); previewCallSamples_.store(0, std::memory_order_relaxed); + getFrameAverageMs_.store(0.0, std::memory_order_relaxed); + getFrameMaximumMs_.store(0.0, std::memory_order_relaxed); + getFrameWindowMaximumMs_.store(0.0, std::memory_order_relaxed); + getFrameSamples_.store(0, std::memory_order_relaxed); #if GVFG_INTERNAL_DIAGNOSTICS haveDebugBaseline_ = false; lastDebugDmaErrors_ = 0; - lastDebugDroppedFrames_ = 0; - pendingDroppedFrames_ = 0; - lastDroppedWarningMs_ = 0; #endif captureStop_.store(false, std::memory_order_release); captureRunning_ = true; @@ -536,10 +531,7 @@ void MainWindow::processPendingEvents() while (gvfg_poll_channel_event(handle_, selectedChannel_, &event, 0) == GVFG_OK) { const auto eventType = static_cast(event.type); - if (eventType == GVFG_EVENT_FRAME_LOSS) - appendLog(QStringLiteral("WARNING dropped frames +%1").arg(event.count)); - else - appendLog(QStringLiteral("EVENT %1").arg(eventTypeText(eventType))); + appendLog(QStringLiteral("EVENT %1").arg(eventTypeText(eventType))); if (eventType == GVFG_EVENT_SIGNAL_CONNECTED || eventType == GVFG_EVENT_SIGNAL_DISCONNECTED || @@ -618,6 +610,10 @@ void MainWindow::updateSignalStatus(bool queryHardware) const double previewCallMaximumMs = previewCallMaximumMs_.load(std::memory_order_relaxed); const double previewCallWindowMaximumMs = previewCallWindowMaximumMs_.load(std::memory_order_relaxed); const uint64_t previewCallSamples = previewCallSamples_.load(std::memory_order_relaxed); + const double getFrameAverageMs = getFrameAverageMs_.load(std::memory_order_relaxed); + const double getFrameMaximumMs = getFrameMaximumMs_.load(std::memory_order_relaxed); + const double getFrameWindowMaximumMs = getFrameWindowMaximumMs_.load(std::memory_order_relaxed); + const uint64_t getFrameSamples = getFrameSamples_.load(std::memory_order_relaxed); QStringList statusLines; statusLines << (signal.connected ? QStringLiteral("Input | CH%1 | Connected | %2") @@ -650,26 +646,42 @@ void MainWindow::updateSignalStatus(bool queryHardware) .arg(backendStats.get_frame_timing_max_us, 0, 'f', 3) .arg(static_cast(backendStats.get_frame_timing_samples)) : QStringLiteral("Driver GetFrame | measuring")); + statusLines << (getFrameSamples > 0 + ? QStringLiteral("GetFrame total | avg=%1 max300=%2 max=%3 ms/frame samples=%4") + .arg(getFrameAverageMs, 0, 'f', 3) + .arg(getFrameWindowMaximumMs, 0, 'f', 3) + .arg(getFrameMaximumMs, 0, 'f', 3) + .arg(static_cast(getFrameSamples)) + : QStringLiteral("GetFrame total | measuring")); + statusLines << (haveBackendStats && backendStats.event_wait_timing_samples >= 300 + ? QStringLiteral("Event Wait | avg=%1 max300=%2 max=%3 ms/frame samples=%4") + .arg(backendStats.event_wait_timing_average_us / 1000.0, 0, 'f', 3) + .arg(backendStats.event_wait_timing_max300_us / 1000.0, 0, 'f', 3) + .arg(backendStats.event_wait_timing_max_us / 1000.0, 0, 'f', 3) + .arg(static_cast(backendStats.event_wait_timing_samples)) + : QStringLiteral("Event Wait | measuring")); + statusLines << (haveBackendStats && backendStats.sdk_processing_timing_samples >= 300 + ? QStringLiteral("SDK Processing | avg=%1 max300=%2 max=%3 us/frame samples=%4") + .arg(backendStats.sdk_processing_timing_average_us, 0, 'f', 3) + .arg(backendStats.sdk_processing_timing_max300_us, 0, 'f', 3) + .arg(backendStats.sdk_processing_timing_max_us, 0, 'f', 3) + .arg(static_cast(backendStats.sdk_processing_timing_samples)) + : QStringLiteral("SDK Processing | measuring")); #if GVFG_INTERNAL_DIAGNOSTICS statusLines << (haveBackendStats - ? QStringLiteral("Capture| status=%1 pending_irqs=%2 dma_errors=%3 no_frame_waits=%4") + ? QStringLiteral("Capture| status=%1 dma_errors=%2 no_frame_waits=%3") .arg(captureStatusText(backendStats, signal.connected != 0)) - .arg(backendStats.backend_pending_events) .arg(static_cast(backendStats.backend_dma_errors)) .arg(static_cast(backendStats.backend_wait_timeouts)) : QStringLiteral("Capture| unavailable")); if (haveBackendStats) { - statusLines << QStringLiteral("Flow | irqs=%1 captured=%2 app_read=%3 dropped=%4") + statusLines << QStringLiteral("Flow | irqs=%1 captured=%2 app_read=%3") .arg(static_cast(backendStats.backend_interrupt_count)) .arg(valueOrDash(backendStats.backend_frames_captured)) - .arg(valueOrDash(backendStats.backend_frames_delivered)) - .arg(valueOrDash(backendStats.backend_frames_dropped)); - statusLines << QStringLiteral("Buffer | app_holding=%1 slots=%2 next_write=%3 frame_id newest/read=%4/%5") - .arg(appHoldingText(backendStats.backend_active_delivery_slot), - valueOrDash(backendStats.backend_ring_size), - valueOrDash(backendStats.backend_next_write_slot), - valueOrDash(backendStats.backend_latest_sequence), + .arg(valueOrDash(backendStats.backend_frames_delivered)); + statusLines << QStringLiteral("Frame | newest/read=%1/%2") + .arg(valueOrDash(backendStats.backend_latest_sequence), valueOrDash(backendStats.backend_delivered_sequence)); } @@ -689,7 +701,6 @@ void MainWindow::updateSignalStatus(bool queryHardware) } lastDebugDmaErrors_ = backendStats.backend_dma_errors; - lastDebugDroppedFrames_ = backendStats.backend_frames_dropped; haveDebugBaseline_ = true; } @@ -866,6 +877,7 @@ void MainWindow::appendLog(const QString &message) void MainWindow::captureReadLoop() { + constexpr uint64_t kGetFrameTimingSampleFrames = 300; constexpr uint64_t kPreviewTimingWarmupFrames = 30; constexpr uint64_t kPreviewTimingSampleFrames = 300; @@ -875,12 +887,39 @@ void MainWindow::captureReadLoop() uint64_t previewTimingSampleCount = 0; double previewTimingTotalMs = 0.0; double previewTimingMaximumMs = 0.0; + uint64_t getFrameTimingSampleCount = 0; + double getFrameTimingMaximumMs = 0.0; while (!captureStop_.load(std::memory_order_acquire)) { gvfg_frame_t frame{}; + const auto getFrameStart = std::chrono::steady_clock::now(); const gvfg_status_t st = gvfg_read_channel_frame(handle_, selectedChannel_, &frame, 200); + const double getFrameElapsedMs = + std::chrono::duration( + std::chrono::steady_clock::now() - getFrameStart).count(); if (st == GVFG_OK) { + ++getFrameTimingSampleCount; + getFrameTimingMaximumMs = (std::max)(getFrameTimingMaximumMs, getFrameElapsedMs); + const uint64_t totalSamples = getFrameSamples_.fetch_add(1, std::memory_order_relaxed) + 1; + const double previousAverage = getFrameAverageMs_.load(std::memory_order_relaxed); + getFrameAverageMs_.store( + previousAverage + (getFrameElapsedMs - previousAverage) / static_cast(totalSamples), + std::memory_order_relaxed); + double observedMaximum = getFrameMaximumMs_.load(std::memory_order_relaxed); + while (getFrameElapsedMs > observedMaximum && + !getFrameMaximumMs_.compare_exchange_weak( + observedMaximum, getFrameElapsedMs, std::memory_order_relaxed)) + { + } + if (totalSamples <= kGetFrameTimingSampleFrames) + getFrameWindowMaximumMs_.store(getFrameTimingMaximumMs, std::memory_order_relaxed); + if (getFrameTimingSampleCount >= kGetFrameTimingSampleFrames) + { + getFrameWindowMaximumMs_.store(getFrameTimingMaximumMs, std::memory_order_relaxed); + getFrameTimingSampleCount = 0; + getFrameTimingMaximumMs = 0.0; + } consecutiveTimeouts = 0; if (!frameAvailable_.exchange(true, std::memory_order_acq_rel)) { diff --git a/samples/gvfg_qt_preview/mainwindow.h b/samples/gvfg_qt_preview/mainwindow.h index 4493010..4055090 100644 --- a/samples/gvfg_qt_preview/mainwindow.h +++ b/samples/gvfg_qt_preview/mainwindow.h @@ -75,6 +75,10 @@ private: std::atomic captureStop_{false}; std::atomic frameAvailable_{false}; std::thread captureThread_; + std::atomic getFrameAverageMs_{0.0}; + std::atomic getFrameMaximumMs_{0.0}; + std::atomic getFrameWindowMaximumMs_{0.0}; + std::atomic getFrameSamples_{0}; uint64_t previewFailureCount_ = 0; std::atomic previewCallAverageMs_{0.0}; std::atomic previewCallMaximumMs_{0.0}; @@ -88,9 +92,6 @@ private: #if GVFG_INTERNAL_DIAGNOSTICS QString lastLoggedBackendError_; uint64_t lastDebugDmaErrors_ = 0; - uint64_t lastDebugDroppedFrames_ = 0; - uint64_t pendingDroppedFrames_ = 0; - qint64 lastDroppedWarningMs_ = 0; bool haveDebugBaseline_ = false; #endif QFile logFile_; diff --git a/sdk/gvfg/include/gvfg_capture.h b/sdk/gvfg/include/gvfg_capture.h index 24ab225..19e3a55 100644 --- a/sdk/gvfg/include/gvfg_capture.h +++ b/sdk/gvfg/include/gvfg_capture.h @@ -128,8 +128,6 @@ extern "C" { double capture_fps; /* Runtime FPS measured from frames returned by gvfg_read_channel_frame(). */ uint64_t delivered_frames; /* Number of frames returned by gvfg_read_channel_frame(). */ - /* Frames known by the SDK to have been lost before application delivery. */ - uint64_t lost_frames; } gvfg_runtime_info_t; typedef struct @@ -171,9 +169,7 @@ extern "C" /* First complete frame after stream start, plug-in, or format recovery is ready. */ GVFG_EVENT_STREAM_READY = 3, /* Input format is changing; pause use of resources created for the old format. */ - GVFG_EVENT_FORMAT_CHANGE_BEGIN = 4, - /* One or more frames were known to be lost before application delivery. */ - GVFG_EVENT_FRAME_LOSS = 5 + GVFG_EVENT_FORMAT_CHANGE_BEGIN = 4 } gvfg_event_type_t; typedef enum @@ -183,16 +179,14 @@ extern "C" GVFG_EVENT_MASK_SIGNAL_DISCONNECTED = 1u << 1, GVFG_EVENT_MASK_STREAM_READY = 1u << 2, GVFG_EVENT_MASK_FORMAT_CHANGE_BEGIN = 1u << 3, - GVFG_EVENT_MASK_FRAME_LOSS = 1u << 4, - GVFG_EVENT_MASK_ALL = (1u << 5) - 1u + GVFG_EVENT_MASK_ALL = (1u << 4) - 1u } gvfg_event_mask_t; typedef struct { /* Set to sizeof(gvfg_event_t) before calling gvfg_poll_channel_event(). */ uint32_t struct_size; - int32_t type; /* gvfg_event_type_t value. */ - uint64_t count; /* Loss count for GVFG_EVENT_FRAME_LOSS; otherwise zero. */ + int32_t type; /* gvfg_event_type_t value. */ uint64_t reserved[4]; } gvfg_event_t; @@ -287,7 +281,7 @@ extern "C" /* * A handle may open both channels of the same device. The first call opens * the Windows device; the second channel shares that device connection and - * owns independent capture, event, frame-ring, and zero-copy state. + * owns independent capture, event, frame, and zero-copy state. */ /* diff --git a/sdk/gvfg/include/gvfg_debug.h b/sdk/gvfg/include/gvfg_debug.h index a2d8370..c20540e 100644 --- a/sdk/gvfg/include/gvfg_debug.h +++ b/sdk/gvfg/include/gvfg_debug.h @@ -37,25 +37,28 @@ typedef struct int backend_state; uint64_t backend_frames_captured; uint64_t backend_frames_delivered; - uint64_t backend_frames_dropped; uint64_t backend_dma_errors; uint64_t backend_interrupt_count; uint64_t backend_wait_timeouts; int backend_running; int backend_capture_active; - uint32_t backend_pending_events; uint64_t backend_latest_sequence; uint64_t backend_delivered_sequence; - uint64_t backend_active_delivery_slot; /* UINT64_MAX when no frame is held by the caller. */ - uint64_t backend_next_write_slot; - uint64_t backend_ring_size; int get_frame_zero_copy; uint64_t get_frame_timing_samples; double get_frame_timing_average_us; double get_frame_timing_max300_us; double get_frame_timing_max_us; + uint64_t event_wait_timing_samples; + double event_wait_timing_average_us; + double event_wait_timing_max300_us; + double event_wait_timing_max_us; + uint64_t sdk_processing_timing_samples; + double sdk_processing_timing_average_us; + double sdk_processing_timing_max300_us; + double sdk_processing_timing_max_us; } gvfg_debug_backend_stats_t; /* diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_backend_types.h b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_backend_types.h index 71cf3bd..5b2fe0e 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_backend_types.h +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_backend_types.h @@ -63,7 +63,6 @@ typedef struct pcies2mm_stream_stats_t pcies2mm_stream_state_t state; uint64_t frames_captured; uint64_t frames_delivered; - uint64_t frames_dropped; uint64_t dma_errors; uint64_t interrupt_count; } pcies2mm_stream_stats_t; @@ -72,17 +71,21 @@ typedef struct pcies2mm_debug_state_t { int running; int capture_active; - uint32_t pending_events; uint64_t latest_sequence; uint64_t delivered_sequence; - uint64_t active_delivery_slot; - uint64_t next_write_slot; - uint64_t ring_size; int get_frame_zero_copy; uint64_t get_frame_timing_samples; double get_frame_timing_average_us; double get_frame_timing_max300_us; double get_frame_timing_max_us; + uint64_t event_wait_timing_samples; + double event_wait_timing_average_us; + double event_wait_timing_max300_us; + double event_wait_timing_max_us; + uint64_t sdk_processing_timing_samples; + double sdk_processing_timing_average_us; + double sdk_processing_timing_max300_us; + double sdk_processing_timing_max_us; } pcies2mm_debug_state_t; typedef enum pcies2mm_event_type_t @@ -90,8 +93,7 @@ typedef enum pcies2mm_event_type_t PCIES2MM_EVENT_PLUG_IN = 1, PCIES2MM_EVENT_PLUG_OUT = 2, PCIES2MM_EVENT_STREAM_READY = 3, - PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN = 4, - PCIES2MM_EVENT_FRAME_LOSS = 5 + PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN = 4 } pcies2mm_event_type_t; enum @@ -100,12 +102,10 @@ enum PCIES2MM_EVENT_MASK_PLUG_OUT = 1u << 1, PCIES2MM_EVENT_MASK_STREAM_READY = 1u << 2, PCIES2MM_EVENT_MASK_FORMAT_CHANGE_BEGIN = 1u << 3, - PCIES2MM_EVENT_MASK_FRAME_LOSS = 1u << 4, PCIES2MM_EVENT_MASK_DEFAULT = PCIES2MM_EVENT_MASK_PLUG_IN | PCIES2MM_EVENT_MASK_PLUG_OUT | PCIES2MM_EVENT_MASK_STREAM_READY | - PCIES2MM_EVENT_MASK_FORMAT_CHANGE_BEGIN | - PCIES2MM_EVENT_MASK_FRAME_LOSS + PCIES2MM_EVENT_MASK_FORMAT_CHANGE_BEGIN }; typedef void (*pcies2mm_event_callback_t)(pcies2mm_event_type_t event, void *user); diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp index 2675810..66934f0 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp @@ -16,8 +16,6 @@ namespace constexpr uint32_t kMaxChannels = 2; constexpr uint32_t kDefaultWidth = 1920; constexpr uint32_t kDefaultHeight = 1080; - constexpr uint32_t kDefaultRingBufferCount = 3; - constexpr uint32_t kMaxRingBufferCount = 16; static bool is_write_only_register(uint32_t offset) { @@ -39,9 +37,12 @@ namespace return false; } - static bool should_log_counter(uint64_t count) + static bool is_transient_frame_not_ready_error(DWORD error) { - return count <= 5 || (count % 60) == 0; + return error == ERROR_NOT_READY || + error == ERROR_BUSY || + error == ERROR_RETRY || + error == ERROR_NO_MORE_ITEMS; } static std::string wide_to_utf8(const std::wstring &s) @@ -126,8 +127,6 @@ namespace return PCIES2MM_EVENT_MASK_STREAM_READY; case PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN: return PCIES2MM_EVENT_MASK_FORMAT_CHANGE_BEGIN; - case PCIES2MM_EVENT_FRAME_LOSS: - return PCIES2MM_EVENT_MASK_FRAME_LOSS; default: return 0; } @@ -153,7 +152,7 @@ namespace gvfg::internal stream_desc_.width = kDefaultWidth; stream_desc_.height = kDefaultHeight; stream_desc_.pixel_format = PCIES2MM_PIXFMT_YUY2; - stream_desc_.buffer_count = kDefaultRingBufferCount; + stream_desc_.buffer_count = 1; stream_bit_depth_ = 8; reset_stats(stats_, PCIES2MM_STREAM_STOPPED); } @@ -288,13 +287,13 @@ namespace gvfg::internal if (!enabled) { // Even while the stream is nominally stopped, an earlier failed - // teardown may have left a driver frame in the ring. No disable - // IOCTL is allowed until the acquire thread is joined and every - // outstanding frame has been returned successfully. - stop_event_monitoring(); + // teardown may have left a driver frame held. No disable + // IOCTL is allowed until every outstanding frame has been + // returned successfully. const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(true); if (releaseStatus != PCIES2MM_OK) return releaseStatus; + stop_event_monitoring(); } if (!giga_ioctl_set_frame_zerocopy(device_, active_channel(), enabled ? TRUE : FALSE)) @@ -342,7 +341,7 @@ namespace gvfg::internal if (!signalPresent) { out.connected = 0; - std::lock_guard lock(mutex_); + std::unique_lock lock(mutex_); signal_metadata_valid_ = false; return PCIES2MM_OK; } @@ -412,9 +411,7 @@ namespace gvfg::internal stream_desc_ = desc; stream_desc_.pixel_format = fmt; - stream_desc_.buffer_count = std::clamp(desc.buffer_count ? desc.buffer_count : kDefaultRingBufferCount, - 1u, - kMaxRingBufferCount); + stream_desc_.buffer_count = 1; stream_bit_depth_ = bit_depth_for_pixfmt(fmt); configured_ = true; reset_stats(stats_, PCIES2MM_STREAM_CONFIGURED); @@ -430,7 +427,7 @@ namespace gvfg::internal return PCIES2MM_OK; // Do not overwrite a retained token from an earlier failed release. - // Retry it before rebuilding the ring or restarting DMA. + // Retry it before rebuilding the buffer or restarting DMA. const pcies2mm_status_t pendingReleaseStatus = release_all_zero_copy_frames(true); if (pendingReleaseStatus != PCIES2MM_OK) return pendingReleaseStatus; @@ -441,15 +438,13 @@ namespace gvfg::internal { std::lock_guard lock(mutex_); - frame_ring_.assign(zero_copy_enabled_ ? 1u : stream_desc_.buffer_count, FrameSlot{}); - for (FrameSlot &slot : frame_ring_) - if (!zero_copy_enabled_) - slot.data.assign(bytes, 0); - next_write_slot_ = 0; - active_delivery_slot_ = static_cast(-1); + copy_buffer_.clear(); + if (!zero_copy_enabled_) + copy_buffer_.assign(bytes, 0); + held_frame_ = {}; + frame_held_ = false; + read_in_progress_ = false; active_delivery_started_ = {}; - last_delivery_started_ = {}; - pending_events_ = 0; latest_sequence_ = 0; delivered_sequence_ = 0; wait_timeout_count_ = 0; @@ -459,6 +454,18 @@ namespace gvfg::internal get_frame_timing_window_max_us_ = 0.0; get_frame_timing_last_max300_us_ = 0.0; get_frame_timing_lifetime_max_us_ = 0.0; + event_wait_timing_samples_ = 0; + event_wait_timing_window_samples_ = 0; + event_wait_timing_total_us_ = 0.0; + event_wait_timing_window_max_us_ = 0.0; + event_wait_timing_last_max300_us_ = 0.0; + event_wait_timing_lifetime_max_us_ = 0.0; + sdk_processing_timing_samples_ = 0; + sdk_processing_timing_window_samples_ = 0; + sdk_processing_timing_total_us_ = 0.0; + sdk_processing_timing_window_max_us_ = 0.0; + sdk_processing_timing_last_max300_us_ = 0.0; + sdk_processing_timing_lifetime_max_us_ = 0.0; stream_error_ = false; reset_stats(stats_, PCIES2MM_STREAM_CONFIGURED); } @@ -477,9 +484,6 @@ namespace gvfg::internal stream_desc_.width > 0 && stream_desc_.height > 0 && stream_desc_.pixel_format != PCIES2MM_PIXFMT_UNKNOWN; - signal_presence_known_.store(false, std::memory_order_release); - signal_present_.store(false, std::memory_order_release); - running_ = true; capture_active_ = false; reader_ready_ = false; @@ -497,8 +501,9 @@ namespace gvfg::internal { if (!running_) { + const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(true); stop_event_monitoring(); - return release_all_zero_copy_frames(true); + return releaseStatus; } running_ = false; @@ -510,175 +515,219 @@ namespace gvfg::internal if (device_ != INVALID_HANDLE_VALUE) stop_video(active_channel()); - // The event thread owns acquire/publish. Join it before examining the - // ring; otherwise an acquire can complete immediately after the ring - // was drained and leave a driver frame outstanding. - stop_event_monitoring(); - - const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(true); - if (dma_event_) SetEvent(dma_event_); - frame_cv_.notify_all(); - data_cv_.notify_all(); + + { + std::unique_lock lock(mutex_); + read_finished_cv_.wait(lock, [this] { return !read_in_progress_; }); + } + const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(true); + stop_event_monitoring(); { std::lock_guard lock(mutex_); - pending_events_ = 0; - active_delivery_slot_ = static_cast(-1); - for (FrameSlot &slot : frame_ring_) - slot.in_use = false; + held_frame_ = {}; + frame_held_ = false; stats_.state = configured_ ? PCIES2MM_STREAM_CONFIGURED : PCIES2MM_STREAM_STOPPED; } - frame_cv_.notify_all(); - data_cv_.notify_all(); return releaseStatus; } pcies2mm_status_t PcieS2mmCaptureSession::wait_frame(uint32_t timeoutMs, pcies2mm_frame_t &out) { reader_ready_.store(true, std::memory_order_release); - - bool descriptorReady = false; - bool probingSignal = false; - if (!capture_active_.load(std::memory_order_acquire)) - { - const bool presenceKnown = signal_presence_known_.load(std::memory_order_acquire); - const bool signalPresent = signal_present_.load(std::memory_order_acquire); - probingSignal = !presenceKnown; - // start_stream() already refreshed width/height/format before it - // armed the initial signal probe. Reuse that validated descriptor - // for the first read instead of issuing the same three register - // reads again immediately. - if (!presenceKnown && signal_probe_active_.load(std::memory_order_acquire)) - descriptorReady = true; - else if (!presenceKnown || signalPresent) - descriptorReady = refresh_stream_from_registers(true); - } - - std::unique_lock lock(mutex_); std::memset(&out, 0, sizeof(out)); - if (!running_) - return PCIES2MM_ESTATE; - - // Arm DMA while holding the same mutex used by publish_frame(). The - // condition-variable wait below releases it atomically, so the - // capture thread cannot publish or fill the FIFO before this reader - // is genuinely waiting. - if (descriptorReady && !capture_active_.load(std::memory_order_acquire)) { - if (!start_video(active_channel())) + std::unique_lock lock(mutex_); + if (!running_ || frame_held_ || read_in_progress_) + return PCIES2MM_ESTATE; + if (!capture_active_.load(std::memory_order_acquire)) { - const DWORD err = GetLastError(); - stop_video(active_channel()); - ++stats_.dma_errors; - lock.unlock(); - fail(PCIES2MM_EIO, "enable reader capture", err); - return PCIES2MM_EIO; + if (!signal_presence_known_.load(std::memory_order_acquire) || + !signal_present_.load(std::memory_order_acquire)) + return PCIES2MM_ETIMEOUT; + if (!ResetEvent(dma_event_)) + { + const DWORD err = GetLastError(); + ++stats_.dma_errors; + lock.unlock(); + return fail(PCIES2MM_EIO, "reset DMA event", err); + } + if (!start_video(active_channel())) + { + const DWORD err = GetLastError(); + ++stats_.dma_errors; + lock.unlock(); + return fail(PCIES2MM_EIO, "enable reader capture", err); + } + capture_active_.store(true, std::memory_order_release); + stream_ready_pending_.store(true, std::memory_order_release); } - capture_active_.store(true, std::memory_order_release); - signal_probe_active_.store(probingSignal, std::memory_order_release); - stream_ready_pending_.store(true, std::memory_order_release); - PCIES2MM_LOG("capture armed with reader waiting: channel=%u probe=%d", - active_channel(), - probingSignal ? 1 : 0); + read_in_progress_ = true; } - const auto hasFrame = [this]() - { - for (const FrameSlot &slot : frame_ring_) - { - if (slot.ready && slot.sequence > delivered_sequence_) - return true; - } - return stream_error_ || !running_; + const auto finishRead = [this]() { + std::lock_guard lock(mutex_); + read_in_progress_ = false; + read_finished_cv_.notify_all(); }; - if (timeoutMs == 0) + const bool infiniteWait = timeoutMs == UINT32_MAX; + const auto attemptStarted = std::chrono::steady_clock::now(); + const auto deadline = infiniteWait + ? (std::chrono::steady_clock::time_point::max)() + : attemptStarted + std::chrono::milliseconds(timeoutMs); + const DWORD bytes = static_cast(frame_size_bytes()); + const uint8_t *data = nullptr; + double eventWaitUs = 0.0; + double getFrameUs = 0.0; + for (;;) { - if (!hasFrame()) + DWORD waitMs = INFINITE; + if (!infiniteWait) { - ++wait_timeout_count_; + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline) + waitMs = 0; + else + { + const auto remainingUs = std::chrono::duration_cast(deadline - now).count(); + waitMs = static_cast((remainingUs + 999) / 1000); + } + } + + const auto eventWaitStarted = std::chrono::steady_clock::now(); + const DWORD waitResult = WaitForSingleObject(dma_event_, waitMs); + const auto eventWaitFinished = std::chrono::steady_clock::now(); + eventWaitUs += std::chrono::duration( + eventWaitFinished - eventWaitStarted).count(); + if (waitResult == WAIT_TIMEOUT) + { + { + std::lock_guard lock(mutex_); + ++wait_timeout_count_; + } + finishRead(); return PCIES2MM_ETIMEOUT; } - } - else if (timeoutMs == UINT32_MAX) - { - frame_cv_.wait(lock, hasFrame); - } - else if (!frame_cv_.wait_for(lock, std::chrono::milliseconds(timeoutMs), hasFrame)) - { - ++wait_timeout_count_; - return PCIES2MM_ETIMEOUT; - } - - size_t readySlot = frame_ring_.size(); - uint64_t readySequence = (std::numeric_limits::max)(); - for (size_t i = 0; i < frame_ring_.size(); ++i) - { - const FrameSlot &slot = frame_ring_[i]; - if (slot.ready && - slot.sequence > delivered_sequence_ && - slot.sequence < readySequence) + if (waitResult != WAIT_OBJECT_0) { - readySlot = i; - readySequence = slot.sequence; + const DWORD err = GetLastError(); + finishRead(); + return fail(PCIES2MM_EIO, "wait DMA event", err); } + if (!running_.load(std::memory_order_acquire)) + { + finishRead(); + return PCIES2MM_ESTATE; + } + if (!capture_active_.load(std::memory_order_acquire)) + { + finishRead(); + return PCIES2MM_ETIMEOUT; + } + + const auto getFrameStarted = std::chrono::steady_clock::now(); + int ret = -1; + DWORD frameError = ERROR_SUCCESS; + if (zero_copy_enabled_) + { + if (acquire_zero_copy_frame(active_channel(), data)) + ret = static_cast(bytes); + else + frameError = GetLastError(); + } + else + { + ret = get_frame(active_channel(), (std::numeric_limits::max)(), + copy_buffer_.data(), bytes); + if (ret < 0) + frameError = GetLastError(); + else if (static_cast(ret) != bytes) + frameError = ERROR_INVALID_DATA; + } + getFrameUs += std::chrono::duration( + std::chrono::steady_clock::now() - getFrameStarted).count(); + if (ret >= 0 && static_cast(ret) == bytes) + break; + + if (!is_transient_frame_not_ready_error(frameError)) + { + { + std::lock_guard lock(mutex_); + ++stats_.dma_errors; + } + finishRead(); + return fail(PCIES2MM_EIO, + zero_copy_enabled_ ? "zero-copy acquire frame" : "copy get frame", + frameError); + } + + PCIES2MM_LOG("frame not ready after DMA event: channel=%u winerr=%lu; wait for next event", + active_channel(), + static_cast(frameError)); } - if (!running_ && readySlot == frame_ring_.size()) - return PCIES2MM_ESTATE; - if (stream_error_ && readySlot == frame_ring_.size()) - return PCIES2MM_EIO; - if (readySlot == frame_ring_.size()) - return PCIES2MM_ETIMEOUT; - - FrameSlot &slot = frame_ring_[readySlot]; - slot.ready = false; - slot.in_use = true; - active_delivery_slot_ = readySlot; - active_delivery_started_ = std::chrono::steady_clock::now(); - last_delivery_started_ = active_delivery_started_; - delivered_sequence_ = slot.sequence; - ++stats_.frames_delivered; - - out.data = slot.zero_copy ? slot.external_data : slot.data.data(); - out.data_size_bytes = slot.bytes; - out.frame_id = delivered_sequence_; - out.width = stream_desc_.width; - out.height = stream_desc_.height; - out.pixel_format = stream_desc_.pixel_format; - out.bit_depth = stream_bit_depth_; + { + std::lock_guard lock(mutex_); + read_in_progress_ = false; + read_finished_cv_.notify_all(); + if (!running_) + { + if (zero_copy_enabled_ && data) + release_zero_copy_frame(active_channel()); + return PCIES2MM_ESTATE; + } + record_get_frame_timing(getFrameUs); + ++latest_sequence_; + delivered_sequence_ = latest_sequence_; + ++stats_.interrupt_count; + ++stats_.frames_captured; + ++stats_.frames_delivered; + stats_.state = PCIES2MM_STREAM_RUNNING; + signal_present_.store(true, std::memory_order_release); + signal_presence_known_.store(true, std::memory_order_release); + active_delivery_started_ = std::chrono::steady_clock::now(); + out.data = zero_copy_enabled_ ? data : copy_buffer_.data(); + out.data_size_bytes = bytes; + out.frame_id = delivered_sequence_; + out.width = stream_desc_.width; + out.height = stream_desc_.height; + out.pixel_format = stream_desc_.pixel_format; + out.bit_depth = stream_bit_depth_; + held_frame_ = out; + frame_held_ = true; + const double backendTotalUs = std::chrono::duration( + std::chrono::steady_clock::now() - attemptStarted).count(); + record_event_wait_timing(eventWaitUs); + record_sdk_processing_timing((std::max)(0.0, backendTotalUs - eventWaitUs - getFrameUs)); + } + if (stream_ready_pending_.exchange(false, std::memory_order_acq_rel)) + emit_event(PCIES2MM_EVENT_STREAM_READY); return PCIES2MM_OK; } pcies2mm_status_t PcieS2mmCaptureSession::release_frame(const pcies2mm_frame_t &frame) { std::unique_lock lock(mutex_); - if (active_delivery_slot_ >= frame_ring_.size()) + if (!frame_held_) return PCIES2MM_ESTATE; - - const FrameSlot &slot = frame_ring_[active_delivery_slot_]; - const uint8_t *expectedData = slot.zero_copy ? slot.external_data : slot.data.data(); - if (frame.data != expectedData || - frame.data_size_bytes != slot.bytes || - frame.frame_id != delivered_sequence_ || - frame.width != stream_desc_.width || - frame.height != stream_desc_.height || - frame.pixel_format != stream_desc_.pixel_format || - frame.bit_depth != stream_bit_depth_) + if (frame.data != held_frame_.data || + frame.data_size_bytes != held_frame_.data_size_bytes || + frame.frame_id != held_frame_.frame_id || + frame.width != held_frame_.width || + frame.height != held_frame_.height || + frame.pixel_format != held_frame_.pixel_format || + frame.bit_depth != held_frame_.bit_depth) return PCIES2MM_EINVAL; - if (slot.zero_copy && !release_zero_copy_frame(active_channel())) + if (zero_copy_enabled_ && !release_zero_copy_frame(active_channel())) { const DWORD err = GetLastError(); lock.unlock(); return fail(PCIES2MM_EIO, "release zero-copy frame", err); } - FrameSlot &releasedSlot = frame_ring_[active_delivery_slot_]; - releasedSlot.in_use = false; - releasedSlot.external_data = nullptr; - releasedSlot.zero_copy = false; const double heldMs = active_delivery_started_.time_since_epoch().count() != 0 ? std::chrono::duration( std::chrono::steady_clock::now() - active_delivery_started_).count() @@ -687,8 +736,9 @@ namespace gvfg::internal PCIES2MM_LOG("slow frame release: frame=%llu held_ms=%.3f", static_cast(frame.frame_id), heldMs); active_delivery_started_ = {}; - active_delivery_slot_ = static_cast(-1); - data_cv_.notify_all(); + held_frame_ = {}; + frame_held_ = false; + read_finished_cv_.notify_all(); return PCIES2MM_OK; } @@ -708,14 +758,8 @@ namespace gvfg::internal std::memset(&outDebugState, 0, sizeof(outDebugState)); outDebugState.running = running_.load(std::memory_order_relaxed) ? 1 : 0; outDebugState.capture_active = capture_active_.load(std::memory_order_relaxed) ? 1 : 0; - outDebugState.pending_events = pending_events_; outDebugState.latest_sequence = latest_sequence_; outDebugState.delivered_sequence = delivered_sequence_; - outDebugState.active_delivery_slot = active_delivery_slot_ == static_cast(-1) - ? UINT64_MAX - : static_cast(active_delivery_slot_); - outDebugState.next_write_slot = static_cast(next_write_slot_); - outDebugState.ring_size = static_cast(frame_ring_.size()); outDebugState.get_frame_zero_copy = zero_copy_enabled_ ? 1 : 0; outDebugState.get_frame_timing_samples = get_frame_timing_samples_; outDebugState.get_frame_timing_average_us = @@ -724,6 +768,20 @@ namespace gvfg::internal : 0.0; outDebugState.get_frame_timing_max300_us = get_frame_timing_last_max300_us_; outDebugState.get_frame_timing_max_us = get_frame_timing_lifetime_max_us_; + outDebugState.event_wait_timing_samples = event_wait_timing_samples_; + outDebugState.event_wait_timing_average_us = + event_wait_timing_samples_ > 0 + ? event_wait_timing_total_us_ / static_cast(event_wait_timing_samples_) + : 0.0; + outDebugState.event_wait_timing_max300_us = event_wait_timing_last_max300_us_; + outDebugState.event_wait_timing_max_us = event_wait_timing_lifetime_max_us_; + outDebugState.sdk_processing_timing_samples = sdk_processing_timing_samples_; + outDebugState.sdk_processing_timing_average_us = + sdk_processing_timing_samples_ > 0 + ? sdk_processing_timing_total_us_ / static_cast(sdk_processing_timing_samples_) + : 0.0; + outDebugState.sdk_processing_timing_max300_us = sdk_processing_timing_last_max300_us_; + outDebugState.sdk_processing_timing_max_us = sdk_processing_timing_lifetime_max_us_; } bool PcieS2mmCaptureSession::read_reg(uint32_t offset, uint32_t &out) const @@ -776,23 +834,17 @@ namespace gvfg::internal pcies2mm_status_t PcieS2mmCaptureSession::release_all_zero_copy_frames(bool includeInUse) { std::unique_lock lock(mutex_); - for (FrameSlot &slot : frame_ring_) + if (!frame_held_ || !includeInUse) + return PCIES2MM_OK; + if (zero_copy_enabled_ && held_frame_.data && !release_zero_copy_frame(active_channel())) { - if (!slot.zero_copy || !slot.external_data || (!includeInUse && slot.in_use)) - continue; - - if (!release_zero_copy_frame(active_channel())) - { - const DWORD err = GetLastError(); - lock.unlock(); - return fail(PCIES2MM_EIO, "release pending zero-copy frame", err); - } - - slot.external_data = nullptr; - slot.zero_copy = false; - slot.ready = false; - slot.in_use = false; + const DWORD err = GetLastError(); + lock.unlock(); + return fail(PCIES2MM_EIO, "release pending zero-copy frame", err); } + held_frame_ = {}; + frame_held_ = false; + read_finished_cv_.notify_all(); return PCIES2MM_OK; } @@ -931,21 +983,8 @@ namespace gvfg::internal void PcieS2mmCaptureSession::capture_thread_proc() { const uint32_t channel = active_channel(); - const uint32_t irqBit = video_irq_mask_bit(); - uint32_t irqMaskReadback = 0; - const bool irqMaskReadOk = read_reg(INTERRUPT_BASE + IRQ_MASK_STATUS_OFFSET, irqMaskReadback); - PCIES2MM_LOG("capture wait start: irq_bit=0x%08X mask_read=%s0x%08X", - irqBit, - irqMaskReadOk ? "" : "FAILED/", - irqMaskReadback); - HANDLE waitHandles[] = { - dma_event_, - format_change_event_, - plug_in_event_, - plug_out_event_, - }; - constexpr DWORD waitHandleCount = 4; - uint64_t diagnosticTimeouts = 0; + HANDLE waitHandles[] = {format_change_event_, plug_in_event_, plug_out_event_}; + constexpr DWORD waitHandleCount = 3; while (monitoring_.load(std::memory_order_acquire)) { @@ -956,84 +995,28 @@ namespace gvfg::internal if (!monitoring_.load(std::memory_order_acquire)) break; if (waitResult == WAIT_TIMEOUT) - { - if (!running_.load(std::memory_order_acquire)) - continue; - ++diagnosticTimeouts; - if (diagnosticTimeouts <= 5 || (diagnosticTimeouts % 10) == 0) - { - uint32_t videoEnable = 0; - uint32_t dmaEnable = 0; - uint32_t videoIrqStatus = 0; - uint32_t dmaIrqStatus = 0; - uint32_t irqPending = 0; - uint32_t irqMasked = 0; - uint32_t irqMask = 0; - const bool registersOk = - read_reg(video_base() + VIDEO_EN_OFFSET, videoEnable) && - read_reg(video_base() + VIDEO_DMA_EN_OFFSET, dmaEnable) && - read_reg(video_base() + VIDEO_IRQ_STATUS_OFFSET, videoIrqStatus) && - read_reg(video_base() + VIDEO_DMA_IRQ_STATUS_OFFSET, dmaIrqStatus) && - read_reg(INTERRUPT_BASE + IRQ_PENDING_STATUS_OFFSET, irqPending) && - read_reg(INTERRUPT_BASE + IRQ_MASKED_STATUS_OFFSET, irqMasked) && - read_reg(INTERRUPT_BASE + IRQ_MASK_STATUS_OFFSET, irqMask); - PCIES2MM_LOG("wait timeout #%llu: regs_ok=%d capture=%d probe=%d video_en=0x%08X dma_en=0x%08X video_irq=0x%08X dma_irq=0x%08X irq_pending=0x%08X irq_masked=0x%08X irq_mask=0x%08X", - static_cast(diagnosticTimeouts), - registersOk ? 1 : 0, - capture_active_.load(std::memory_order_acquire) ? 1 : 0, - signal_probe_active_.load(std::memory_order_acquire) ? 1 : 0, - videoEnable, - dmaEnable, - videoIrqStatus, - dmaIrqStatus, - irqPending, - irqMasked, - irqMask); - } - if (!signal_presence_known_.load(std::memory_order_acquire) && - reader_ready_.load(std::memory_order_acquire) && - !capture_active_.load(std::memory_order_acquire) && - refresh_stream_from_registers(true)) - { - if (start_video(active_channel())) - { - signal_probe_active_.store(true, std::memory_order_release); - stream_ready_pending_.store(true, std::memory_order_release); - capture_active_.store(true, std::memory_order_release); - } - else - { - stop_video(active_channel()); - } - } - if (signal_present_.load(std::memory_order_acquire) && - !capture_active_.load(std::memory_order_acquire)) - resume_capture_from_signal(channel); continue; - } if (waitResult < WAIT_OBJECT_0 || waitResult >= WAIT_OBJECT_0 + waitHandleCount) { std::lock_guard lock(mutex_); stream_error_ = true; ++stats_.dma_errors; - frame_cv_.notify_all(); + if (dma_event_) + SetEvent(dma_event_); break; } switch (waitResult - WAIT_OBJECT_0) { case 0: - handle_dma_event(channel); - break; - case 1: PCIES2MM_LOG("event: FORMAT_CHANGE"); handle_format_change_event(channel); break; - case 2: + case 1: PCIES2MM_LOG("event: PLUG_IN"); handle_plugin_event(channel); break; - case 3: + case 2: PCIES2MM_LOG("event: PLUG_OUT"); handle_unplug_event(channel); break; @@ -1045,197 +1028,6 @@ namespace gvfg::internal write_reg(INTERRUPT_BASE + IRQ_MASK_W1C_OFFSET, video_irq_mask_bit()); } - void PcieS2mmCaptureSession::handle_dma_event(uint32_t channel) - { - if (!capture_active_.load(std::memory_order_acquire)) - return; - - const DWORD bytes = static_cast(frame_size_bytes()); - size_t slotIndex = frame_ring_.size(); - uint8_t *slotData = nullptr; - bool frameLost = false; - { - std::unique_lock lock(mutex_); - ++pending_events_; - ++stats_.interrupt_count; - - auto hasWritableSlot = [this]() - { - for (const FrameSlot &slot : frame_ring_) - { - if (!slot.in_use && (!zero_copy_enabled_ || !slot.ready)) - return true; - } - return false; - }; - - if (zero_copy_enabled_ && !hasWritableSlot()) - { - if (pending_events_ > 0) - --pending_events_; - return; - } - - while (running_ && !hasWritableSlot()) - data_cv_.wait_for(lock, std::chrono::seconds(1)); - if (!running_) - return; - - // Prefer unused capacity. If every writable slot already holds a - // ready frame, overwrite the oldest unread one and report loss. - for (size_t attempt = 0; attempt < frame_ring_.size(); ++attempt) - { - const size_t candidate = (next_write_slot_ + attempt) % frame_ring_.size(); - if (!frame_ring_[candidate].in_use && !frame_ring_[candidate].ready) - { - slotIndex = candidate; - break; - } - } - if (!zero_copy_enabled_ && slotIndex == frame_ring_.size()) - { - uint64_t oldestSequence = (std::numeric_limits::max)(); - for (size_t i = 0; i < frame_ring_.size(); ++i) - { - const FrameSlot &slot = frame_ring_[i]; - if (!slot.in_use && slot.ready && slot.sequence < oldestSequence) - { - slotIndex = i; - oldestSequence = slot.sequence; - } - } - } - if (slotIndex == frame_ring_.size()) - return; - - FrameSlot &slot = frame_ring_[slotIndex]; - if (slot.ready && slot.sequence > delivered_sequence_) - { - ++stats_.frames_dropped; - frameLost = true; -#if GVFG_INTERNAL_DIAGNOSTICS - const auto now = std::chrono::steady_clock::now(); - const double heldMs = active_delivery_started_.time_since_epoch().count() != 0 - ? std::chrono::duration(now - active_delivery_started_).count() - : 0.0; - const double sinceReadMs = last_delivery_started_.time_since_epoch().count() != 0 - ? std::chrono::duration(now - last_delivery_started_).count() - : 0.0; - PCIES2MM_LOG("FIFO LOSS: total=%llu overwrite_slot=%zu overwrite_seq=%llu delivered=%llu latest=%llu active_slot=%zu held_ms=%.3f since_read_ms=%.3f pending=%u", - static_cast(stats_.frames_dropped), - slotIndex, - static_cast(slot.sequence), - static_cast(delivered_sequence_), - static_cast(latest_sequence_), - active_delivery_slot_, heldMs, sinceReadMs, pending_events_); - for (size_t i = 0; i < frame_ring_.size(); ++i) - { - const FrameSlot &diagnosticSlot = frame_ring_[i]; - PCIES2MM_LOG("FIFO slot[%zu]: ready=%d in_use=%d sequence=%llu bytes=%zu", - i, diagnosticSlot.ready ? 1 : 0, diagnosticSlot.in_use ? 1 : 0, - static_cast(diagnosticSlot.sequence), - diagnosticSlot.bytes); - } -#endif - } - slot.ready = false; - slot.in_use = true; - slot.external_data = nullptr; - slot.zero_copy = zero_copy_enabled_; - if (!zero_copy_enabled_) - { - if (slot.data.size() < bytes) - slot.data.resize(bytes); - slotData = slot.data.data(); - } - next_write_slot_ = (slotIndex + 1) % frame_ring_.size(); - } - - if (frameLost) - emit_event(PCIES2MM_EVENT_FRAME_LOSS); - - constexpr uint32_t frameIndex = (std::numeric_limits::max)(); - const auto getFrameStarted = std::chrono::steady_clock::now(); - const uint8_t *zeroCopyData = nullptr; - const int ret = zero_copy_enabled_ - ? (acquire_zero_copy_frame(channel, zeroCopyData) ? static_cast(bytes) : -1) - : get_frame(channel, frameIndex, slotData, bytes); - const double getFrameUs = std::chrono::duration( - std::chrono::steady_clock::now() - getFrameStarted).count(); - const bool getFrameSucceeded = ret >= 0 && static_cast(ret) == bytes; - if (getFrameSucceeded) - { - std::lock_guard timingLock(mutex_); - ++get_frame_timing_samples_; - ++get_frame_timing_window_samples_; - get_frame_timing_total_us_ += getFrameUs; - get_frame_timing_window_max_us_ = - (std::max)(get_frame_timing_window_max_us_, getFrameUs); - get_frame_timing_lifetime_max_us_ = - (std::max)(get_frame_timing_lifetime_max_us_, getFrameUs); - - if (get_frame_timing_window_samples_ >= 300) - { - get_frame_timing_last_max300_us_ = get_frame_timing_window_max_us_; - PCIES2MM_LOG("%s avg=%.3f us max300=%.3f us max=%.3f us samples=%llu", - zero_copy_enabled_ ? "ZEROCOPY_ACQUIRE" : "COPY_GET_FRAME", - get_frame_timing_total_us_ / - static_cast(get_frame_timing_samples_), - get_frame_timing_last_max300_us_, - get_frame_timing_lifetime_max_us_, - static_cast(get_frame_timing_samples_)); - get_frame_timing_window_samples_ = 0; - get_frame_timing_window_max_us_ = 0.0; - } - } - if (!running_) - { - if (zero_copy_enabled_ && zeroCopyData) - release_zero_copy_frame(channel); - return; - } - if (ret < 0 || static_cast(ret) != bytes) - { - std::lock_guard lock(mutex_); - if (slotIndex < frame_ring_.size()) - frame_ring_[slotIndex].in_use = false; - if (pending_events_ > 0) - --pending_events_; - ++stats_.dma_errors; - frame_cv_.notify_all(); - data_cv_.notify_all(); - PCIES2MM_ERROR_LOG("get_frame failed channel=%u frame=%u ret=%d expected=%lu", - channel, - frameIndex, - ret, - bytes); - return; - } - - if (zero_copy_enabled_) - { - std::lock_guard lock(mutex_); - if (slotIndex < frame_ring_.size()) - frame_ring_[slotIndex].external_data = zeroCopyData; - } - - 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); - } - - { - std::lock_guard lock(mutex_); - if (pending_events_ > 0) - --pending_events_; - publish_frame(slotIndex, static_cast(ret)); - } - - if (stream_ready_pending_.exchange(false, std::memory_order_acq_rel)) - emit_event(PCIES2MM_EVENT_STREAM_READY); - } - void PcieS2mmCaptureSession::handle_format_change_event(uint32_t channel) { { @@ -1245,11 +1037,15 @@ namespace gvfg::internal emit_event(PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN); stop_video(channel); capture_active_ = false; - if (reader_ready_.load(std::memory_order_acquire)) - resume_capture_from_signal(channel); - - frame_cv_.notify_all(); - data_cv_.notify_all(); + stream_ready_pending_ = false; + if (dma_event_) + SetEvent(dma_event_); + { + std::unique_lock lock(mutex_); + read_finished_cv_.wait(lock, [this] { return !read_in_progress_ && !frame_held_; }); + } + if (running_.load(std::memory_order_acquire)) + refresh_stream_from_registers(true); } void PcieS2mmCaptureSession::handle_plugin_event(uint32_t channel) @@ -1262,6 +1058,8 @@ namespace gvfg::internal { stop_video(channel); } + if (dma_event_) + SetEvent(dma_event_); signal_probe_active_.store(false, std::memory_order_release); signal_present_.store(true, std::memory_order_release); signal_presence_known_.store(true, std::memory_order_release); @@ -1270,10 +1068,12 @@ namespace gvfg::internal signal_metadata_valid_ = false; } emit_event(PCIES2MM_EVENT_PLUG_IN); - if (reader_ready_.load(std::memory_order_acquire)) - resume_capture_from_signal(channel); - frame_cv_.notify_all(); - data_cv_.notify_all(); + { + std::unique_lock lock(mutex_); + read_finished_cv_.wait(lock, [this] { return !read_in_progress_ && !frame_held_; }); + } + if (running_.load(std::memory_order_acquire)) + refresh_stream_from_registers(true); } void PcieS2mmCaptureSession::handle_unplug_event(uint32_t channel) @@ -1284,68 +1084,18 @@ namespace gvfg::internal signal_presence_known_.store(true, std::memory_order_release); stop_video(channel); capture_active_ = false; - // A ready frame is driver-owned even if the application has not read - // it yet. Return it before invalidating the ready queue. A caller-held - // frame remains valid until its matching release_frame(). - const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(false); - if (releaseStatus != PCIES2MM_OK) - PCIES2MM_ERROR_LOG("unplug could not release pending zero-copy frame"); + if (dma_event_) + SetEvent(dma_event_); emit_event(PCIES2MM_EVENT_PLUG_OUT); { std::lock_guard lock(mutex_); signal_metadata_valid_ = false; - pending_events_ = 0; - for (FrameSlot &slot : frame_ring_) - { - if (!slot.in_use) - slot.ready = false; - } stats_.state = PCIES2MM_STREAM_CONFIGURED; } - frame_cv_.notify_all(); - data_cv_.notify_all(); } - bool PcieS2mmCaptureSession::resume_capture_from_signal(uint32_t channel) - { - if (!running_.load(std::memory_order_acquire) || - !signal_present_.load(std::memory_order_acquire) || - !refresh_stream_from_registers(true)) - return false; - - if (!start_video(channel)) - { - const DWORD err = GetLastError(); - stop_video(channel); - capture_active_.store(false, std::memory_order_release); - stream_ready_pending_.store(false, std::memory_order_release); - { - std::lock_guard lock(mutex_); - stream_error_ = false; - stats_.state = PCIES2MM_STREAM_CONFIGURED; - ++stats_.dma_errors; - } - fail(PCIES2MM_EIO, "resume capture", err); - frame_cv_.notify_all(); - data_cv_.notify_all(); - return false; - } - - capture_active_.store(true, std::memory_order_release); - signal_probe_active_.store(false, std::memory_order_release); - stream_ready_pending_.store(true, std::memory_order_release); - { - std::lock_guard lock(mutex_); - stream_error_ = false; - stats_.state = PCIES2MM_STREAM_RUNNING; - } - frame_cv_.notify_all(); - data_cv_.notify_all(); - return true; - } - - bool PcieS2mmCaptureSession::refresh_stream_from_registers(bool resizeRing) + bool PcieS2mmCaptureSession::refresh_stream_from_registers(bool resizeBuffer) { uint32_t width = 0; uint32_t height = 0; @@ -1403,21 +1153,9 @@ namespace gvfg::internal return false; } - // Ring replacement must not discard a ready driver pointer. This runs - // on the single event thread, so no new DMA acquire can interleave. - if (resizeRing && release_all_zero_copy_frames(false) != PCIES2MM_OK) + std::lock_guard lock(mutex_); + if (frame_held_ || read_in_progress_) return false; - - std::unique_lock lock(mutex_); - const bool wasRunning = running_.load(std::memory_order_acquire); - if (resizeRing && wasRunning) - { - data_cv_.wait(lock, [this]() - { return !running_.load(std::memory_order_acquire) || - active_delivery_slot_ == static_cast(-1); }); - if (!running_.load(std::memory_order_acquire)) - return false; - } stream_desc_.width = width; stream_desc_.height = height; stream_desc_.pixel_format = pixelFormat; @@ -1429,43 +1167,15 @@ namespace gvfg::internal cached_signal_.pixel_format = pixelFormat; cached_signal_.bit_depth = bitDepth; signal_metadata_valid_ = true; - if (resizeRing) + if (resizeBuffer) { - frame_ring_.assign(zero_copy_enabled_ ? 1u : stream_desc_.buffer_count, FrameSlot{}); - for (FrameSlot &slot : frame_ring_) - if (!zero_copy_enabled_) - slot.data.assign(bytes, 0); - next_write_slot_ = 0; - active_delivery_slot_ = static_cast(-1); - pending_events_ = 0; + copy_buffer_.clear(); + if (!zero_copy_enabled_) + copy_buffer_.assign(bytes, 0); } return true; } - void PcieS2mmCaptureSession::publish_frame(size_t slotIndex, size_t bytes) - { - if (slotIndex >= frame_ring_.size()) - return; - - FrameSlot &slot = frame_ring_[slotIndex]; - slot.bytes = bytes; - slot.sequence = latest_sequence_ + 1; - slot.ready = true; - slot.in_use = false; - ++latest_sequence_; - ++stats_.frames_captured; - stats_.state = PCIES2MM_STREAM_RUNNING; - if (should_log_counter(latest_sequence_)) - { - PCIES2MM_LOG("publish_frame: id=%llu slot=%zu bytes=%zu", - static_cast(latest_sequence_), - slotIndex, - bytes); - } - frame_cv_.notify_one(); - data_cv_.notify_all(); - } - void PcieS2mmCaptureSession::emit_event(pcies2mm_event_type_t type) const { pcies2mm_event_callback_t callback = nullptr; @@ -1529,4 +1239,49 @@ namespace gvfg::internal { return bytes_per_frame(stream_desc_.width, stream_desc_.height, stream_desc_.pixel_format); } + + void PcieS2mmCaptureSession::record_get_frame_timing(double elapsedUs) + { + ++get_frame_timing_samples_; + ++get_frame_timing_window_samples_; + get_frame_timing_total_us_ += elapsedUs; + get_frame_timing_window_max_us_ = (std::max)(get_frame_timing_window_max_us_, elapsedUs); + get_frame_timing_lifetime_max_us_ = (std::max)(get_frame_timing_lifetime_max_us_, elapsedUs); + if (get_frame_timing_window_samples_ >= 300) + { + get_frame_timing_last_max300_us_ = get_frame_timing_window_max_us_; + get_frame_timing_window_samples_ = 0; + get_frame_timing_window_max_us_ = 0.0; + } + } + + void PcieS2mmCaptureSession::record_event_wait_timing(double elapsedUs) + { + ++event_wait_timing_samples_; + ++event_wait_timing_window_samples_; + event_wait_timing_total_us_ += elapsedUs; + event_wait_timing_window_max_us_ = (std::max)(event_wait_timing_window_max_us_, elapsedUs); + event_wait_timing_lifetime_max_us_ = (std::max)(event_wait_timing_lifetime_max_us_, elapsedUs); + if (event_wait_timing_window_samples_ >= 300) + { + event_wait_timing_last_max300_us_ = event_wait_timing_window_max_us_; + event_wait_timing_window_samples_ = 0; + event_wait_timing_window_max_us_ = 0.0; + } + } + + void PcieS2mmCaptureSession::record_sdk_processing_timing(double elapsedUs) + { + ++sdk_processing_timing_samples_; + ++sdk_processing_timing_window_samples_; + sdk_processing_timing_total_us_ += elapsedUs; + sdk_processing_timing_window_max_us_ = (std::max)(sdk_processing_timing_window_max_us_, elapsedUs); + sdk_processing_timing_lifetime_max_us_ = (std::max)(sdk_processing_timing_lifetime_max_us_, elapsedUs); + if (sdk_processing_timing_window_samples_ >= 300) + { + sdk_processing_timing_last_max300_us_ = sdk_processing_timing_window_max_us_; + sdk_processing_timing_window_samples_ = 0; + sdk_processing_timing_window_max_us_ = 0.0; + } + } } diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h index 810d61f..663f530 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h @@ -6,8 +6,8 @@ #include #include -#include #include +#include #include #include #include @@ -78,13 +78,10 @@ namespace gvfg::internal int get_frame(uint32_t channelIndex, uint32_t frameIndex, uint8_t *buffer, DWORD bufferSize) const; void capture_thread_proc(); - void handle_dma_event(uint32_t channel); void handle_format_change_event(uint32_t channel); void handle_plugin_event(uint32_t channel); void handle_unplug_event(uint32_t channel); - bool resume_capture_from_signal(uint32_t channel); - bool refresh_stream_from_registers(bool resizeRing); - void publish_frame(size_t slotIndex, size_t bytes); + bool refresh_stream_from_registers(bool resizeBuffer); void emit_event(pcies2mm_event_type_t type) const; pcies2mm_status_t fail(pcies2mm_status_t status, const char *where, DWORD winerr = GetLastError()) const; @@ -96,17 +93,9 @@ namespace gvfg::internal uint32_t video_base() const; uint32_t video_irq_mask_bit() const; size_t frame_size_bytes() const; - - struct FrameSlot - { - std::vector data; // Frame byte storage for this ring slot. - const uint8_t *external_data = nullptr; // Driver-owned zero-copy frame. - bool zero_copy = false; - size_t bytes = 0; // Number of valid bytes read into data. - uint64_t sequence = 0; // Monotonic frame sequence assigned on publish. - bool ready = false; // True after the data thread publishes a frame. - bool in_use = false; // True while writing or while the caller holds the slot. - }; + void record_get_frame_timing(double elapsedUs); + void record_event_wait_timing(double elapsedUs); + void record_sdk_processing_timing(double elapsedUs); std::wstring base_path_; std::wstring friendly_name_; @@ -138,16 +127,11 @@ namespace gvfg::internal std::thread capture_thread_; mutable std::mutex mutex_; + std::condition_variable read_finished_cv_; mutable std::mutex event_callback_mutex_; - std::condition_variable frame_cv_; - std::condition_variable data_cv_; pcies2mm_event_callback_t event_callback_ = nullptr; void *event_callback_user_ = nullptr; uint32_t event_mask_filter_ = PCIES2MM_EVENT_MASK_DEFAULT; - uint32_t pending_events_ = 0; - std::vector frame_ring_; - size_t next_write_slot_ = 0; - size_t active_delivery_slot_ = static_cast(-1); uint64_t latest_sequence_ = 0; uint64_t delivered_sequence_ = 0; uint64_t wait_timeout_count_ = 0; @@ -157,8 +141,23 @@ namespace gvfg::internal double get_frame_timing_window_max_us_ = 0.0; double get_frame_timing_last_max300_us_ = 0.0; double get_frame_timing_lifetime_max_us_ = 0.0; + uint64_t event_wait_timing_samples_ = 0; + uint32_t event_wait_timing_window_samples_ = 0; + double event_wait_timing_total_us_ = 0.0; + double event_wait_timing_window_max_us_ = 0.0; + double event_wait_timing_last_max300_us_ = 0.0; + double event_wait_timing_lifetime_max_us_ = 0.0; + uint64_t sdk_processing_timing_samples_ = 0; + uint32_t sdk_processing_timing_window_samples_ = 0; + double sdk_processing_timing_total_us_ = 0.0; + double sdk_processing_timing_window_max_us_ = 0.0; + double sdk_processing_timing_last_max300_us_ = 0.0; + double sdk_processing_timing_lifetime_max_us_ = 0.0; + std::vector copy_buffer_; + pcies2mm_frame_t held_frame_{}; + bool frame_held_ = false; + bool read_in_progress_ = false; std::chrono::steady_clock::time_point active_delivery_started_{}; - std::chrono::steady_clock::time_point last_delivery_started_{}; bool stream_error_ = false; pcies2mm_stream_stats_t stats_{}; mutable std::string last_error_; diff --git a/sdk/gvfg/src/gvfg_capture.cpp b/sdk/gvfg/src/gvfg_capture.cpp index c65e042..58fbbf6 100644 --- a/sdk/gvfg/src/gvfg_capture.cpp +++ b/sdk/gvfg/src/gvfg_capture.cpp @@ -31,7 +31,6 @@ namespace static_assert(GVFG_EVENT_MASK_SIGNAL_DISCONNECTED == PCIES2MM_EVENT_MASK_PLUG_OUT); static_assert(GVFG_EVENT_MASK_STREAM_READY == PCIES2MM_EVENT_MASK_STREAM_READY); static_assert(GVFG_EVENT_MASK_FORMAT_CHANGE_BEGIN == PCIES2MM_EVENT_MASK_FORMAT_CHANGE_BEGIN); - static_assert(GVFG_EVENT_MASK_FRAME_LOSS == PCIES2MM_EVENT_MASK_FRAME_LOSS); #if INTPTR_MAX == INT64_MAX static_assert(std::is_standard_layout_v); @@ -137,8 +136,6 @@ namespace return GVFG_EVENT_STREAM_READY; case PCIES2MM_EVENT_FORMAT_CHANGE_BEGIN: return GVFG_EVENT_FORMAT_CHANGE_BEGIN; - case PCIES2MM_EVENT_FRAME_LOSS: - return GVFG_EVENT_FRAME_LOSS; default: return GVFG_EVENT_UNKNOWN; } @@ -354,7 +351,6 @@ struct gvfg_channel_session_t pcies2mm_debug_state_t debugState{}; uint64_t waitTimeouts = 0; backend->get_debug_stats(stats, waitTimeouts, debugState); - out.lost_frames = stats.frames_dropped; return GVFG_OK; } @@ -380,19 +376,11 @@ struct gvfg_channel_session_t const gvfg_event_type_t type = map_event_type(event); { std::lock_guard lock(eventMutex); - if (type == GVFG_EVENT_FRAME_LOSS && !eventQueue.empty() && - eventQueue.back().type == GVFG_EVENT_FRAME_LOSS) - { - ++eventQueue.back().count; - eventCv.notify_one(); - return; - } if (eventQueue.size() >= 64) eventQueue.pop_front(); gvfg_event_t out{}; out.struct_size = sizeof(out); out.type = type; - out.count = type == GVFG_EVENT_FRAME_LOSS ? 1 : 0; eventQueue.push_back(out); } eventCv.notify_one(); @@ -438,14 +426,14 @@ struct gvfg_channel_session_t } // configure_stream() is also used to enter event-monitoring mode. Keep - // its inactive placeholder ring minimal; the real signal descriptor + // its inactive placeholder buffer minimal; the real signal descriptor // replaces it before DMA is enabled after reconnect. pcies2mm_stream_desc_t desc{}; desc.width = configureWidth; desc.height = configureHeight; desc.pixel_format = configureFormat; - desc.buffer_count = 3; + desc.buffer_count = 1; const pcies2mm_status_t st = backend->configure_stream(desc); if (st != PCIES2MM_OK) @@ -671,23 +659,26 @@ struct gvfg_channel_session_t out.backend_state = static_cast(stats.state); out.backend_frames_captured = stats.frames_captured; out.backend_frames_delivered = stats.frames_delivered; - out.backend_frames_dropped = stats.frames_dropped; out.backend_dma_errors = stats.dma_errors; out.backend_interrupt_count = stats.interrupt_count; out.backend_wait_timeouts = waitTimeouts; out.backend_running = debugState.running; out.backend_capture_active = debugState.capture_active; - out.backend_pending_events = debugState.pending_events; out.backend_latest_sequence = debugState.latest_sequence; out.backend_delivered_sequence = debugState.delivered_sequence; - out.backend_active_delivery_slot = debugState.active_delivery_slot; - out.backend_next_write_slot = debugState.next_write_slot; - out.backend_ring_size = debugState.ring_size; out.get_frame_zero_copy = debugState.get_frame_zero_copy; out.get_frame_timing_samples = debugState.get_frame_timing_samples; out.get_frame_timing_average_us = debugState.get_frame_timing_average_us; out.get_frame_timing_max300_us = debugState.get_frame_timing_max300_us; out.get_frame_timing_max_us = debugState.get_frame_timing_max_us; + out.event_wait_timing_samples = debugState.event_wait_timing_samples; + out.event_wait_timing_average_us = debugState.event_wait_timing_average_us; + out.event_wait_timing_max300_us = debugState.event_wait_timing_max300_us; + out.event_wait_timing_max_us = debugState.event_wait_timing_max_us; + out.sdk_processing_timing_samples = debugState.sdk_processing_timing_samples; + out.sdk_processing_timing_average_us = debugState.sdk_processing_timing_average_us; + out.sdk_processing_timing_max300_us = debugState.sdk_processing_timing_max300_us; + out.sdk_processing_timing_max_us = debugState.sdk_processing_timing_max_us; } return GVFG_OK;