diff --git a/README.md b/README.md index 01b198e..314a418 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,22 @@ SDK 不再呼叫 `IOCTL_PCIES2MM_GET_VIDEO_DONE_INDEX`,也不會在新 IOCTL `IRQ_MASK_W1S_OFFSET`。若搭配舊版 driver,stream start 或 frame capture 可能失敗。 +### Zero-copy selection + +上層程式可在 `gvfg_create()` 後、`gvfg_open_channel()` 前選擇 zero-copy: + +```c +gvfg_handle handle = NULL; +gvfg_create(&handle); +gvfg_set_zero_copy_enabled(handle, 1); /* 0: copy, 1: zero-copy */ +gvfg_open_channel(handle, device_index, GVFG_CHANNEL_0); +``` + +預設為 copy mode。Device open 後不可切換模式;如需切換,必須 destroy +並重建 session。Zero-copy mode 仍使用相同的 `gvfg_read_frame()` / +`gvfg_release_frame()` ownership contract,每次成功 read 都必須 release。 +SDK 會在 open 時 enable zero-copy,並在 close/destroy 時 disable。 + `gvfg_qt_preview.exe` 只使用 public API,主畫面只顯示 input 與 Preview 狀態;IRQ、DMA、ring slot 等資訊只存在 internal diagnostic tool。 diff --git a/docs/GVFG_CUSTOMER_API.md b/docs/GVFG_CUSTOMER_API.md index 89c2543..b5e358c 100644 --- a/docs/GVFG_CUSTOMER_API.md +++ b/docs/GVFG_CUSTOMER_API.md @@ -32,6 +32,7 @@ bin/gvfg_preview.dll ```text gvfg_enumerate_devices -> gvfg_create +-> gvfg_set_zero_copy_enabled (optional, before open) -> gvfg_open_channel -> gvfg_start -> 重複: @@ -90,8 +91,9 @@ int main(void) - API 是 pull model;應用程式自行決定在哪個執行緒呼叫 `gvfg_read_frame()`。GUI 程式建議在 worker thread 讀取,再把 UI 更新送回 UI thread。 -- `frame.data` 由 SDK 擁有,只在對應的 `gvfg_release_frame()` 前有效。資料若要 - 長期保存,必須先複製。 +- Copy mode 的 `frame.data` 由 SDK 擁有;zero-copy mode 則指向 driver-owned + buffer。兩種模式都只在對應的 `gvfg_release_frame()` 前有效,資料若要長期 + 保存,必須先複製。 - 每個 handle 同時最多持有一個 frame。尚未 release 又呼叫 `gvfg_read_frame()`,會回傳 `GVFG_ESTATE`。 - release 時必須傳回原本的完整 `gvfg_frame_t`,不可修改欄位。 @@ -149,6 +151,9 @@ int main(void) - `gvfg_enumerate_devices(out_devices, max_devices)`:列舉裝置。傳入 `NULL, 0` 可只查數量;回傳值是寫入數量或可用裝置數,無裝置時為 `0`。 - `gvfg_create(&handle)`:建立 closed session。 +- `gvfg_set_zero_copy_enabled(handle, enabled)`:選用 zero-copy;只能在 + `gvfg_open_channel()` 前呼叫,預設為關閉。 +- `gvfg_get_zero_copy_enabled(handle, &enabled)`:查詢 session 選擇的模式。 - `gvfg_open_channel(handle, device_index, channel)`:開啟列舉所得裝置,channel 必須為 `GVFG_CHANNEL_0` 或 `GVFG_CHANNEL_1`。 - `gvfg_start(handle)`:開始擷取。若目前無訊號,成功進入訊號監看模式;此時 @@ -156,11 +161,20 @@ int main(void) - `gvfg_stop(handle)`:停止擷取;重複呼叫仍回傳成功。 - `gvfg_destroy(handle)`:必要時先停止,再銷毀 handle。銷毀後不得再使用。 +Zero-copy mode 的 driver lifecycle 由 SDK 管理:open 時 enable,每次成功 +`gvfg_read_frame()` 後由 `gvfg_release_frame()` 歸還 driver frame,destroy/close +前 disable。Device open 後不可直接切換;應 destroy session、重新 create、設定模式 +後再 open。 + ### Frame -- `gvfg_read_frame(handle, &frame, timeout_ms)`:取得一個 SDK-owned frame。 +- `gvfg_read_frame(handle, &frame, timeout_ms)`:取得一個 frame;ownership 依 copy/ + zero-copy mode 而定,但 release contract 相同。 - `gvfg_release_frame(handle, &frame)`:釋放原 frame token。 +`gvfg_set_video_format()` 只能在 stream 尚未開始或已 stop 時呼叫;streaming 中 +切換會回傳 `GVFG_ESTATE`。應用程式應在 UI 上同步鎖定格式選項。 + ### 查詢 - `gvfg_get_signal_status(handle, &status)`:查詢 selected channel 的連線、尺寸、 diff --git a/docs/GVFG_CUSTOMER_API_REFERENCE.md b/docs/GVFG_CUSTOMER_API_REFERENCE.md index 5dc65e2..2f8c3b8 100644 --- a/docs/GVFG_CUSTOMER_API_REFERENCE.md +++ b/docs/GVFG_CUSTOMER_API_REFERENCE.md @@ -86,7 +86,7 @@ register 與 DMA 實作不屬於本文件。 | 欄位 | 型別 | 說明 | | ------------------ | -------------- | -------------------------------------------- | -| `data` | `const void *` | SDK-owned 原生 frame buffer;release 或 stop 後失效 | +| `data` | `const void *` | Copy mode 為 SDK-owned、zero-copy 為 driver-owned;release 或 stop 後失效 | | `data_size` | `uint64_t` | `data` 指向的總 byte 數 | | `width` | `int` | frame 寬度,單位 pixel | | `height` | `int` | frame 高度,單位 pixel | @@ -191,6 +191,33 @@ gvfg_status_t gvfg_open_channel(gvfg_handle handle, 對同一 handle 再次 open 會先關閉原 backend session;應用程式仍應依正常 lifecycle 先 stop,再切換裝置或 channel。 +### Zero-copy mode selection + +```c +gvfg_status_t gvfg_set_zero_copy_enabled(gvfg_handle handle, int enabled); +gvfg_status_t gvfg_get_zero_copy_enabled(gvfg_handle handle, int *out_enabled); +``` + +- `set` 只能在 `gvfg_create()` 後、`gvfg_open_channel()` 前呼叫。 +- `enabled` 只接受 0(copy)或 1(zero-copy),預設為 0。 +- Device 已 open 時呼叫 `set` 會回傳 `GVFG_ESTATE`。 +- `get` 可查詢 session 選定模式;`out_enabled` 不可為 NULL。 +- Zero-copy mode 的 `frame.data` 為 driver-owned pointer;仍必須以相同 descriptor + 呼叫 `gvfg_release_frame()`,且同一 handle 同時最多持有一張 frame。 +- SDK 在 open 時 enable driver zero-copy,在 destroy/close 前 disable。 + +### `gvfg_set_video_format` + +```c +gvfg_status_t gvfg_set_video_format(gvfg_handle handle, + gvfg_pixel_format_t format); +``` + +- 支援 `GVFG_PIXFMT_YUY2` 與 `GVFG_PIXFMT_Y210`。 +- Device 必須已 open,且 stream 必須尚未 start 或已 stop。 +- Streaming 中呼叫回傳 `GVFG_ESTATE`;不支援的 format 回傳 `GVFG_ENOTSUP` 或 + `GVFG_EINVAL`。 + ### 1.17 `gvfg_start` ```c @@ -220,6 +247,9 @@ gvfg_status_t gvfg_read_frame(gvfg_handle handle, - `GVFG_ETIMEOUT`:期限內沒有 frame。 - `GVFG_EIO`/`GVFG_ENOTSUP`:frame/backend 無效或格式不支援。 +Copy mode 回傳 SDK ring buffer;zero-copy mode 回傳 driver-owned buffer。兩者的 +pointer 都只保證有效到對應的 `gvfg_release_frame()`。 + ### 1.19 `gvfg_release_frame` ```c @@ -229,7 +259,7 @@ gvfg_status_t gvfg_release_frame(gvfg_handle handle, - `handle`:取得該 frame 的同一個 handle。 - `frame`:`gvfg_read_frame()` 原封不動回傳的完整 descriptor。 -- `GVFG_OK`:成功歸還 frame,slot 可再次使用。 +- `GVFG_OK`:成功歸還 frame;copy slot 可再次使用,或 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 index 10ddf5f..4840a5a 100644 --- a/docs/GVFG_DMA_RING_DATA_FLOW.drawio +++ b/docs/GVFG_DMA_RING_DATA_FLOW.drawio @@ -1,106 +1,51 @@ - - - + + + - - - + + + + + - - - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + diff --git a/docs/GVFG_INTERNAL_NOTES.md b/docs/GVFG_INTERNAL_NOTES.md index 861729b..d79ee16 100644 --- a/docs/GVFG_INTERNAL_NOTES.md +++ b/docs/GVFG_INTERNAL_NOTES.md @@ -65,14 +65,14 @@ Created/Closed -> Opened -> Running -> Opened -> Destroyed ## 4. DMA 與 frame ring -目前資料路徑: +Copy mode 資料路徑: ```text source frame -> hardware/driver DMA buffer -> DMA complete event --> capture worker 查詢 done index --> IOCTL_GET_FRAME 複製到 SDK ring free slot +-> 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 @@ -94,6 +94,26 @@ ring 滿時的行為是即時擷取的 drop/backpressure policy,不是 lossles internal stats 觀察 `frames_dropped`。不要將 slot 數、driver DMA buffer 數或 done-index 演算法暴露為客戶契約。 +Zero-copy mode 資料路徑: + +```text +gvfg_create +-> gvfg_set_zero_copy_enabled(1) +-> open channel 時 IOCTL_GIGA_ENABLE_FRAME_ZEROCOPY(channel) +-> DMA complete event +-> IOCTL_GIGA_ACQUIRE_VIDEO_FRAME_ZEROCOPY(channel, 0xFFFFFFFF) +-> facade 回傳 driver-owned pointer +-> customer/preview/conversion +-> gvfg_release_frame +-> IOCTL_GIGA_RELEASE_VIDEO_FRAME(channel) +-> 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。 + ## 5. Frame token 與 ABI Facade 在 release 時驗證原 token 的 data、size、width、height、stride、format、 @@ -103,6 +123,20 @@ x64 `gvfg_frame_t` ABI 已在 `gvfg_capture.cpp` 以 static assertions 固定為 及明確欄位 offsets。修改公開 struct 時必須視為 ABI 變更,不能只重新編譯 DLL。 新增 metadata 優先考慮新 query API 或帶 size/version 的新 struct。 +## Driver ABI requirement + +目前 SDK 只支援新版 PCIE S2MM driver,必要 private ABI 包含: + +- `IOCTL_GIGA_VIDEO_START` (`0x808`) / `IOCTL_GIGA_VIDEO_STOP` (`0x809`)。 +- `IOCTL_GIGA_RELEASE_VIDEO_FRAME` (`0x80A`)。 +- `IOCTL_GIGA_ACQUIRE_VIDEO_FRAME_ZEROCOPY` (`0x80B`)。 +- `IOCTL_GIGA_ENABLE_FRAME_ZEROCOPY` (`0x80C`) / + `IOCTL_GIGA_DISABLE_FRAME_ZEROCOPY` (`0x80D`)。 +- Copy mode 的 `IOCTL_PCIES2MM_GET_FRAME` 接受 `frameIndex=0xFFFFFFFF`。 + +不再呼叫 `GET_VIDEO_DONE_INDEX`,也不再 fallback 直接寫入 video enable、DMA enable +或 IRQ mask registers。舊 driver 不屬於此 revision 的支援範圍。 + 目前原生格式: - YUY2:2 bytes/pixel,8-bit packed 4:2:2,byte order 為 Y0 U0 Y1 V0。 diff --git a/samples/gvfg_qt_preview/mainwindow.cpp b/samples/gvfg_qt_preview/mainwindow.cpp index 0f69ce1..a46c6be 100644 --- a/samples/gvfg_qt_preview/mainwindow.cpp +++ b/samples/gvfg_qt_preview/mainwindow.cpp @@ -317,6 +317,15 @@ bool MainWindow::openDevice() return false; } + const bool zeroCopyEnabled = ui_->zeroCopyCheckBox->isChecked(); + st = gvfg_set_zero_copy_enabled(handle_, zeroCopyEnabled ? 1 : 0); + if (st != GVFG_OK) + { + showError(QStringLiteral("gvfg_set_zero_copy_enabled"), st); + closeDevice(); + return false; + } + const int selection = ui_->deviceCombo->currentData().toInt(); const int deviceIndex = selection / 2; const int channelIndex = selection % 2; @@ -335,7 +344,10 @@ bool MainWindow::openDevice() } lastSignalStatusText_.clear(); - appendLog(QStringLiteral("Opened device index %1 CH%2").arg(deviceIndex).arg(channelIndex)); + appendLog(QStringLiteral("Opened device index %1 CH%2 | mode=%3") + .arg(deviceIndex) + .arg(channelIndex) + .arg(zeroCopyEnabled ? QStringLiteral("zero-copy") : QStringLiteral("copy"))); appendLog(QStringLiteral("Signal monitoring active")); updateSignalStatus(); runtimeStatusTimer_->start(); @@ -629,6 +641,10 @@ void MainWindow::updateSignalStatus(bool queryHardware) .arg(signalFrameText(signal)) : QStringLiteral("Input | CH%1 | No signal") .arg(signal.channel)); + statusLines << QStringLiteral("Mode | %1") + .arg(ui_->zeroCopyCheckBox->isChecked() + ? QStringLiteral("Zero-copy") + : QStringLiteral("Copy")); statusLines << (previewInfoOk ? previewCallSamples > 0 ? QStringLiteral("Preview | %1 | %2 | GPU call avg=%3 max300=%4 max=%5 ms/frame samples=%6") @@ -736,7 +752,8 @@ void MainWindow::updateUiState() ui_->fullscreenPreviewButton->setEnabled(viewAvailable); ui_->refreshButton->setEnabled(!deviceOpen && !captureRunning_); ui_->deviceCombo->setEnabled(!deviceOpen && !captureRunning_); - ui_->outputFormatCombo->setEnabled(deviceOpen && !captureRunning_); + ui_->outputFormatCombo->setEnabled(!captureRunning_); + ui_->zeroCopyCheckBox->setEnabled(!deviceOpen && !captureRunning_); } void MainWindow::showError(const QString &apiName, gvfg_status_t status) @@ -1023,7 +1040,14 @@ void MainWindow::captureReadLoop() } } } - gvfg_release_frame(handle_, &frame); + const gvfg_status_t releaseStatus = gvfg_release_frame(handle_, &frame); + if (releaseStatus != GVFG_OK) + { + QMetaObject::invokeMethod(this, [this, releaseStatus]() + { showError(QStringLiteral("gvfg_release_frame"), releaseStatus); }, + Qt::QueuedConnection); + break; + } continue; } diff --git a/samples/gvfg_qt_preview/mainwindow.ui b/samples/gvfg_qt_preview/mainwindow.ui index 6c37bb3..af15182 100644 --- a/samples/gvfg_qt_preview/mainwindow.ui +++ b/samples/gvfg_qt_preview/mainwindow.ui @@ -126,6 +126,16 @@ + + + + Must be selected before opening the device + + + Zero-copy + + + diff --git a/sdk/gvfg/include/gvfg_capture.h b/sdk/gvfg/include/gvfg_capture.h index 45da715..46ac328 100644 --- a/sdk/gvfg/include/gvfg_capture.h +++ b/sdk/gvfg/include/gvfg_capture.h @@ -259,9 +259,25 @@ extern "C" _In_ int channel_index); /* - * Select the native capture format. This may be called before or during - * capture. A running stream reports GVFG_EVENT_FORMAT_CHANGE_BEGIN while - * the new format is applied. + * Select driver zero-copy frame delivery. + * + * Call after gvfg_create() and before gvfg_open_channel(). The default is + * disabled. Once a device is open the mode cannot be changed. In zero-copy + * mode, gvfg_read_frame() returns driver-owned memory and every successful + * read must be paired with gvfg_release_frame(). + */ + GVFG_API gvfg_status_t gvfg_set_zero_copy_enabled( + _In_ gvfg_handle handle, + _In_ int enabled); + + GVFG_API gvfg_status_t gvfg_get_zero_copy_enabled( + _In_ gvfg_handle handle, + _Out_ int *out_enabled); + + /* + * Select the native capture format. Call after opening the device and + * before gvfg_start(), or after gvfg_stop(). A running stream rejects the + * change with GVFG_ESTATE. * * Currently the SDK implements this through a temporary hardware register; * applications must use this API so the backend can move to an IOCTL later. @@ -307,8 +323,9 @@ extern "C" * - GVFG_ETIMEOUT if no frame is ready before timeout_ms expires. * - GVFG_EIO for driver/backend failures. * - * The returned data pointer is owned by the SDK and remains valid until - * gvfg_release_frame() is called. A handle may hold only one frame at a time. + * In copy mode the returned data pointer is owned by the SDK. In zero-copy + * mode it points to driver-owned memory. In both modes it remains valid + * until gvfg_release_frame() is called, and a handle may hold only one frame. */ GVFG_API gvfg_status_t gvfg_read_frame( _In_ gvfg_handle handle, diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp index 9cd5f67..1b11cab 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.cpp @@ -178,11 +178,18 @@ namespace gvfg::internal pcies2mm_status_t PcieS2mmCaptureSession::close() { - stop_stream(); + pcies2mm_status_t result = stop_stream(); stop_event_monitoring(); + if (zero_copy_enabled_ && device_ != INVALID_HANDLE_VALUE) + { + const pcies2mm_status_t disableStatus = set_zero_copy_enabled(false); + if (result == PCIES2MM_OK) + result = disableStatus; + } close_handles(); opened_ = false; configured_ = false; + zero_copy_enabled_ = false; signal_presence_known_.store(false, std::memory_order_release); signal_present_.store(false, std::memory_order_release); signal_probe_active_.store(false, std::memory_order_release); @@ -190,7 +197,7 @@ namespace gvfg::internal base_path_.clear(); friendly_name_.clear(); reset_stats(stats_, PCIES2MM_STREAM_STOPPED); - return PCIES2MM_OK; + return result; } void PcieS2mmCaptureSession::close_handles() @@ -218,6 +225,38 @@ namespace gvfg::internal return PCIES2MM_OK; } + pcies2mm_status_t PcieS2mmCaptureSession::set_zero_copy_enabled(bool enabled) + { + if (!opened_ || device_ == INVALID_HANDLE_VALUE) + return PCIES2MM_ESTATE; + if (running_) + return PCIES2MM_ESTATE; + if (zero_copy_enabled_ == enabled) + return PCIES2MM_OK; + + 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(); + const pcies2mm_status_t releaseStatus = release_all_zero_copy_frames(true); + if (releaseStatus != PCIES2MM_OK) + return releaseStatus; + } + + ULONG channel = active_channel(); + DWORD bytesReturned = 0; + const DWORD ioctl = enabled ? IOCTL_GIGA_ENABLE_FRAME_ZEROCOPY + : IOCTL_GIGA_DISABLE_FRAME_ZEROCOPY; + if (!DeviceIoControl(device_, ioctl, &channel, sizeof(channel), nullptr, 0, + &bytesReturned, nullptr)) + return fail(PCIES2MM_EIO, enabled ? "enable zero copy" : "disable zero copy"); + zero_copy_enabled_ = enabled; + return PCIES2MM_OK; + } + pcies2mm_status_t PcieS2mmCaptureSession::set_video_format(pcies2mm_pixel_format_t format) { if (!opened_) @@ -246,12 +285,12 @@ namespace gvfg::internal out.channel = channel_; uint32_t modeLocked = 0; - uint32_t timingLocked = 0; + uint32_t rxTLocked = 0; if (!read_reg(video_base() + VIDEO_RX_MODE_LOCKED_OFFSET, modeLocked) || - !read_reg(video_base() + VIDEO_RX_T_LOCKED_OFFSET, timingLocked)) + !read_reg(video_base() + VIDEO_RX_T_LOCKED_OFFSET, rxTLocked)) return fail(PCIES2MM_EIO, "read signal lock registers"); - const bool signalPresent = modeLocked == 1u && timingLocked == 1u; + const bool signalPresent = modeLocked == 1u && rxTLocked == 1u; signal_presence_known_.store(true, std::memory_order_release); signal_present_.store(signalPresent, std::memory_order_release); if (!signalPresent) @@ -343,15 +382,22 @@ namespace gvfg::internal if (running_) return PCIES2MM_OK; + // Do not overwrite a retained token from an earlier failed release. + // Retry it before rebuilding the ring or restarting DMA. + const pcies2mm_status_t pendingReleaseStatus = release_all_zero_copy_frames(true); + if (pendingReleaseStatus != PCIES2MM_OK) + return pendingReleaseStatus; + const size_t bytes = frame_size_bytes(); if (bytes == 0 || bytes > (std::numeric_limits::max)()) return fail(PCIES2MM_EINVAL, "frame_size_bytes", ERROR_INVALID_PARAMETER); { std::lock_guard lock(mutex_); - frame_ring_.assign(stream_desc_.buffer_count, FrameSlot{}); + frame_ring_.assign(zero_copy_enabled_ ? 1u : stream_desc_.buffer_count, FrameSlot{}); for (FrameSlot &slot : frame_ring_) - slot.data.assign(bytes, 0); + if (!zero_copy_enabled_) + slot.data.assign(bytes, 0); next_write_slot_ = 0; active_delivery_slot_ = static_cast(-1); active_delivery_started_ = {}; @@ -365,8 +411,11 @@ namespace gvfg::internal } const uint32_t channel = active_channel(); - if (!monitoring_.load(std::memory_order_acquire)) - return fail(PCIES2MM_ESTATE, "event monitoring is not active", ERROR_INVALID_STATE); + // stop_stream() joins the event thread so no zero-copy acquire can race + // teardown. Recreate event monitoring when the same open handle starts + // another stream. + if (!monitoring_.load(std::memory_order_acquire) && !start_event_monitoring()) + return fail(PCIES2MM_EIO, "start event monitoring"); // Events are edge-triggered, so a source connected before registration // may not produce a plug-in event. Probe DMA using the register layout, // but do not report connected until a full frame is received. @@ -390,7 +439,10 @@ namespace gvfg::internal pcies2mm_status_t PcieS2mmCaptureSession::stop_stream() { if (!running_) - return PCIES2MM_OK; + { + stop_event_monitoring(); + return release_all_zero_copy_frames(true); + } running_ = false; capture_active_ = false; @@ -401,6 +453,13 @@ 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(); @@ -416,7 +475,7 @@ namespace gvfg::internal } frame_cv_.notify_all(); data_cv_.notify_all(); - return PCIES2MM_OK; + return releaseStatus; } pcies2mm_status_t PcieS2mmCaptureSession::wait_frame(uint32_t timeoutMs, pcies2mm_frame_t &out) @@ -520,7 +579,7 @@ namespace gvfg::internal delivered_sequence_ = slot.sequence; ++stats_.frames_delivered; - out.data = slot.data.data(); + 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; @@ -532,12 +591,13 @@ namespace gvfg::internal pcies2mm_status_t PcieS2mmCaptureSession::release_frame(const pcies2mm_frame_t &frame) { - std::lock_guard lock(mutex_); + std::unique_lock lock(mutex_); if (active_delivery_slot_ >= frame_ring_.size()) return PCIES2MM_ESTATE; const FrameSlot &slot = frame_ring_[active_delivery_slot_]; - if (frame.data != slot.data.data() || + 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 || @@ -546,7 +606,16 @@ namespace gvfg::internal frame.bit_depth != stream_bit_depth_) return PCIES2MM_EINVAL; - frame_ring_[active_delivery_slot_].in_use = false; + if (slot.zero_copy && !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() @@ -659,6 +728,63 @@ namespace gvfg::internal nullptr) != FALSE; } + bool PcieS2mmCaptureSession::acquire_zero_copy_frame(uint32_t channelIndex, + const uint8_t *&outData) const + { + ULONG input[2] = {channelIndex, (std::numeric_limits::max)()}; + void *buffer = nullptr; + DWORD bytesReturned = 0; + const BOOL ok = DeviceIoControl(device_, + IOCTL_GIGA_ACQUIRE_VIDEO_FRAME_ZEROCOPY, + input, + sizeof(input), + &buffer, + sizeof(buffer), + &bytesReturned, + nullptr); + if (!ok || !buffer) + return false; + outData = static_cast(buffer); + return true; + } + + bool PcieS2mmCaptureSession::release_zero_copy_frame(uint32_t channelIndex) const + { + ULONG channel = channelIndex; + DWORD bytesReturned = 0; + return DeviceIoControl(device_, + IOCTL_GIGA_RELEASE_VIDEO_FRAME, + &channel, + sizeof(channel), + nullptr, + 0, + &bytesReturned, + nullptr) != FALSE; + } + + pcies2mm_status_t PcieS2mmCaptureSession::release_all_zero_copy_frames(bool includeInUse) + { + std::unique_lock lock(mutex_); + for (FrameSlot &slot : frame_ring_) + { + 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; + } + return PCIES2MM_OK; + } + pcies2mm_status_t PcieS2mmCaptureSession::debug_write_register(uint32_t offset, uint32_t value) const { @@ -951,12 +1077,19 @@ namespace gvfg::internal { for (const FrameSlot &slot : frame_ring_) { - if (!slot.in_use) + 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_) @@ -973,7 +1106,7 @@ namespace gvfg::internal break; } } - if (slotIndex == frame_ring_.size()) + 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) @@ -1021,9 +1154,14 @@ namespace gvfg::internal } slot.ready = false; slot.in_use = true; - if (slot.data.size() < bytes) - slot.data.resize(bytes); - slotData = slot.data.data(); + 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(); } @@ -1032,14 +1170,21 @@ namespace gvfg::internal constexpr uint32_t frameIndex = (std::numeric_limits::max)(); const auto getFrameStarted = std::chrono::steady_clock::now(); - const int ret = get_frame(channel, frameIndex, slotData, bytes); + 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 getFrameMs = std::chrono::duration( std::chrono::steady_clock::now() - getFrameStarted).count(); if (getFrameMs >= 10.0) PCIES2MM_LOG("slow GET_FRAME: frame_index=0x%08X elapsed_ms=%.3f ret=%d", frameIndex, getFrameMs, ret); 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_); @@ -1058,6 +1203,13 @@ namespace gvfg::internal 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); @@ -1123,6 +1275,12 @@ 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"); emit_event(PCIES2MM_EVENT_PLUG_OUT); { @@ -1236,6 +1394,11 @@ 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) + return false; + std::unique_lock lock(mutex_); const bool wasRunning = running_.load(std::memory_order_acquire); if (resizeRing && wasRunning) @@ -1259,9 +1422,10 @@ namespace gvfg::internal signal_metadata_valid_ = true; if (resizeRing) { - frame_ring_.assign(stream_desc_.buffer_count, FrameSlot{}); + frame_ring_.assign(zero_copy_enabled_ ? 1u : stream_desc_.buffer_count, FrameSlot{}); for (FrameSlot &slot : frame_ring_) - slot.data.assign(bytes, 0); + if (!zero_copy_enabled_) + slot.data.assign(bytes, 0); next_write_slot_ = 0; active_delivery_slot_ = static_cast(-1); pending_events_ = 0; diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h index a25cf68..ff4f9fd 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_capture_session.h @@ -29,6 +29,8 @@ namespace gvfg::internal pcies2mm_status_t close(); pcies2mm_status_t set_channel(uint32_t channel); + pcies2mm_status_t set_zero_copy_enabled(bool enabled); + bool zero_copy_enabled() const { return zero_copy_enabled_; } pcies2mm_status_t set_video_format(pcies2mm_pixel_format_t format); pcies2mm_status_t get_signal_status(pcies2mm_signal_status_t &out) const; @@ -54,6 +56,9 @@ namespace gvfg::internal bool write_reg(uint32_t offset, uint32_t value) const; bool start_video(uint32_t channelIndex) const; bool stop_video(uint32_t channelIndex) const; + bool acquire_zero_copy_frame(uint32_t channelIndex, const uint8_t *&outData) const; + bool release_zero_copy_frame(uint32_t channelIndex) const; + pcies2mm_status_t release_all_zero_copy_frames(bool includeInUse); bool register_event(uint32_t channelIndex, uint32_t eventType, HANDLE eventHandle); void unregister_event(uint32_t channelIndex, uint32_t eventType); bool create_and_register_events(uint32_t channelIndex); @@ -86,6 +91,8 @@ namespace gvfg::internal 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. @@ -106,6 +113,7 @@ namespace gvfg::internal uint32_t channel_ = 0; bool opened_ = false; bool configured_ = false; + bool zero_copy_enabled_ = false; std::atomic running_{false}; std::atomic monitoring_{false}; diff --git a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_ioctl.h b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_ioctl.h index 091f075..77b26ef 100644 --- a/sdk/gvfg/src/backend/pcies2mm/pcies2mm_ioctl.h +++ b/sdk/gvfg/src/backend/pcies2mm/pcies2mm_ioctl.h @@ -16,6 +16,10 @@ #define IOCTL_PCIES2MM_UNREGISTER_EVENT PCIES2MM_IOCTL(0x804, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_GIGA_VIDEO_START PCIES2MM_IOCTL(0x808, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_GIGA_VIDEO_STOP PCIES2MM_IOCTL(0x809, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_GIGA_RELEASE_VIDEO_FRAME PCIES2MM_IOCTL(0x80A, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_GIGA_ACQUIRE_VIDEO_FRAME_ZEROCOPY PCIES2MM_IOCTL(0x80B, METHOD_BUFFERED, FILE_ANY_ACCESS) +#define IOCTL_GIGA_ENABLE_FRAME_ZEROCOPY PCIES2MM_IOCTL(0x80C, METHOD_NEITHER, FILE_ANY_ACCESS) +#define IOCTL_GIGA_DISABLE_FRAME_ZEROCOPY PCIES2MM_IOCTL(0x80D, METHOD_NEITHER, FILE_ANY_ACCESS) enum PCIES2MM_DRIVER_EVENT_TYPE { diff --git a/sdk/gvfg/src/gvfg_capture.cpp b/sdk/gvfg/src/gvfg_capture.cpp index 94b3eac..633f979 100644 --- a/sdk/gvfg/src/gvfg_capture.cpp +++ b/sdk/gvfg/src/gvfg_capture.cpp @@ -228,10 +228,29 @@ struct gvfg_handle_t return map_status(stChannel); } + if (zeroCopyRequested) + { + const pcies2mm_status_t stZeroCopy = backend->set_zero_copy_enabled(true); + if (stZeroCopy != PCIES2MM_OK) + { + recordError(pcies2mm_error_text(stZeroCopy, backend.get())); + close(); + return map_status(stZeroCopy); + } + } + querySignal(); return GVFG_OK; } + gvfg_status_t setZeroCopyEnabled(bool enabled) + { + if (backend) + return GVFG_ESTATE; + zeroCopyRequested = enabled; + return GVFG_OK; + } + gvfg_status_t start() { if (!backend) @@ -265,9 +284,13 @@ struct gvfg_handle_t running = false; eventCv.notify_all(); releaseHeldFrameForStop(); - if (backend) - backend->stop_stream(); - return GVFG_OK; + if (!backend) + return GVFG_OK; + + const pcies2mm_status_t st = backend->stop_stream(); + if (st != PCIES2MM_OK) + recordError(pcies2mm_error_text(st, backend.get())); + return map_status(st); } void close() @@ -734,6 +757,7 @@ struct gvfg_handle_t std::unique_ptr backend; int currentIndex = -1; uint32_t selectedChannel = GVFG_CHANNEL_0; + bool zeroCopyRequested = false; uint32_t width = 0; uint32_t height = 0; @@ -815,6 +839,21 @@ extern "C" return handle->open(device_index, channel_index); } + gvfg_status_t gvfg_set_zero_copy_enabled(gvfg_handle handle, int enabled) + { + if (!handle || (enabled != 0 && enabled != 1)) + return GVFG_EINVAL; + return handle->setZeroCopyEnabled(enabled != 0); + } + + gvfg_status_t gvfg_get_zero_copy_enabled(gvfg_handle handle, int *out_enabled) + { + if (!handle || !out_enabled) + return GVFG_EINVAL; + *out_enabled = handle->zeroCopyRequested ? 1 : 0; + return GVFG_OK; + } + gvfg_status_t gvfg_start(gvfg_handle handle) { if (!handle)