Refactor SDK to pure pull-based capture API

- Remove customer-facing SDK preview APIs and preview structs
- Strip D3D preview/render pipeline from gvfg.dll
- Keep gvfg.dll focused on capture, frame ownership, runtime status, and events
- Move Qt preview rendering into sample-owned private renderer
- Update Qt preview sample to render frames after gvfg_read_frame()
- Refresh customer API docs around read_frame/release_frame/poll_event flow
- Update architecture notes to mark preview as app/internal-tool code
This commit is contained in:
Mark.lin
2026-06-15 14:03:21 +08:00
parent c21f6981ea
commit 97971e6242
14 changed files with 947 additions and 1286 deletions
+1
View File
@@ -1,5 +1,6 @@
build*/
out/
packages/
demosrc/
.vs/
.vscode/
+139 -793
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -43,16 +43,16 @@
<mxGeometry x="1280" y="310" width="260" height="120" as="geometry"/>
</mxCell>
<mxCell id="wait" value="captureLoop()&#xa;backend-&gt;wait_frame(1000, frame)" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14;fontStyle=1" vertex="1" parent="1">
<mxCell id="wait" value="gvfg_read_frame()&#xa;backend-&gt;wait_frame(timeout, frame)" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14;fontStyle=1" vertex="1" parent="1">
<mxGeometry x="80" y="560" width="270" height="80" as="geometry"/>
</mxCell>
<mxCell id="select" value="wait_frame() selects newest ready slot&#xa;slot.ready = false&#xa;slot.in_use = true&#xa;out.data = slot.data.data()" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14" vertex="1" parent="1">
<mxGeometry x="430" y="540" width="310" height="120" as="geometry"/>
</mxCell>
<mxCell id="render" value="renderGpuFrame(frame)&#xa;SDK preview uses same slot pointer" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14" vertex="1" parent="1">
<mxCell id="render" value="app/private preview renderer&#xa;uses frame before release" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14" vertex="1" parent="1">
<mxGeometry x="820" y="540" width="270" height="90" as="geometry"/>
</mxCell>
<mxCell id="callback" value="emitNativeFrame(frame)&#xa;customer callback gets out.data = frame.data" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14" vertex="1" parent="1">
<mxCell id="callback" value="app uses frame&#xa;data valid until gvfg_release_frame()" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14" vertex="1" parent="1">
<mxGeometry x="1160" y="540" width="300" height="90" as="geometry"/>
</mxCell>
<mxCell id="release" value="release_frame(frame)&#xa;slot.in_use = false&#xa;data_cv_.notify_all()" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=14;fontStyle=1" vertex="1" parent="1">
+16 -18
View File
@@ -68,17 +68,14 @@ flowchart TD
B --> C["gvfg_set_callbacks\noptional frame/error callback"]
C --> D["gvfg_set_event_callback\noptional event callback"]
D --> E["gvfg_open"]
E --> F["gvfg_set_preview\noptional SDK-managed preview"]
F --> G["gvfg_start"]
E --> G["gvfg_start"]
G --> H["running"]
H --> I["gvfg_get_runtime_info\nor gvfg_get_signal_status"]
H --> J["frame callback\noptional"]
H --> K["event callback\noptional"]
H --> L["D3D preview present\noptional"]
H --> J["gvfg_read_frame\napp-owned loop"]
H --> K["gvfg_poll_event\noptional"]
I --> H
J --> H
K --> H
L --> H
H --> M["gvfg_stop"]
M --> N["gvfg_destroy"]
```
@@ -87,9 +84,10 @@ flowchart TD
1. `refreshDevices()` calls `gvfg_enumerate_devices()`.
2. `openDevice()` calls `gvfg_create()`, callback setup, then `gvfg_open()`.
3. `startCapture()` calls `gvfg_set_preview()` and `gvfg_start()`.
4. A timer calls `gvfg_get_runtime_info()` to refresh signal, preview, callback, and FPS status.
5. `stopCapture()` calls `gvfg_stop()`, and `closeDevice()` calls `gvfg_destroy()`.
3. `startCapture()` calls `gvfg_start()` and starts an app-owned read loop.
4. The read loop calls `gvfg_read_frame()`, renders preview with app-private code, then calls `gvfg_release_frame()`.
5. A timer calls `gvfg_get_runtime_info()` to refresh signal, read-frame, and FPS status.
6. `stopCapture()` calls `gvfg_stop()`, and `closeDevice()` calls `gvfg_destroy()`.
## 3. SDK Frame 資料流圖
@@ -99,12 +97,11 @@ flowchart LR
EventWorker --> DataWorker["XdmaCaptureSession data worker"]
DataWorker --> Ring["frame_ring_ slot\nready=true, sequence++"]
Ring --> WaitFrame["wait_frame()"]
WaitFrame --> CaptureLoop["gvfg_handle_t::captureLoop"]
CaptureLoop --> Preview["renderGpuFrame()\nD3D preview path"]
CaptureLoop --> Callback["emitNativeFrame()\ncustomer callback path"]
WaitFrame --> ReadFrame["gvfg_read_frame()"]
ReadFrame --> App["App-owned read loop\nframe valid until release"]
App --> Preview["app-private preview renderer\ninternal/demo tool only"]
Preview --> HWND["App-provided HWND"]
Callback --> App["App onFrame callback\npointer valid only during callback"]
CaptureLoop --> Release["release_frame()\nslot reusable"]
App --> Release["gvfg_release_frame()\nslot reusable"]
Release --> Ring
```
@@ -112,7 +109,7 @@ flowchart LR
1. data worker 什麼時候寫入 `frame_ring_`。
2. `wait_frame()` 什麼時候把 slot 交給 `gvfg_capture.cpp`。
3. `renderGpuFrame()` 和 `emitNativeFrame()` 共用同一個 backend frame 的時間點。
3. `gvfg_read_frame()` owns the backend frame until the app calls `gvfg_release_frame()`.
4. `release_frame()` 後 slot 什麼時候可重用。
更底層的外部來源細節先不放進這張圖。
@@ -129,11 +126,12 @@ sequenceDiagram
Source->>Backend: backend event
Backend->>Backend: classify event and update capture state
Backend->>Facade: xdma_event_callback_t
Facade->>Facade: map XDMA event to gvfg_event_t
Facade->>App: gvfg_on_event_cb
Facade->>Facade: map XDMA event and queue gvfg_event_t
App->>Facade: gvfg_poll_event()
Facade->>App: gvfg_event_t
```
`VIDEO_IRQ` 類型的事件會推動 frame 資料進入 SDK frame path。Hotplug 類型事件則可能讓 backend pause/resume capture,並透過 `gvfg_on_event_cb` 通知 App。
`VIDEO_IRQ` 類型的事件會推動 frame 資料進入 SDK frame path。Hotplug 類型事件則可能讓 backend pause/resume capture,App 可透過 `gvfg_poll_event()` 取得事件。
## 5. Build / 交付圖
+72
View File
@@ -0,0 +1,72 @@
# GVFG Pull API Notes
## Direction
The customer-facing capture path follows an FFmpeg-style pull model:
```text
gvfg_enumerate_devices
-> gvfg_create
-> gvfg_open
-> gvfg_start
-> loop:
gvfg_read_frame
use frame data
gvfg_release_frame
gvfg_poll_event optional
-> gvfg_stop
-> gvfg_destroy
```
## Frame Ownership
- `gvfg_read_frame()` returns one SDK-owned frame buffer.
- `frame.data` remains valid until `gvfg_release_frame()` is called.
- A handle may hold only one frame at a time.
- If the application needs the frame after release, it must copy the data.
## Threading Model
The SDK may keep internal driver I/O workers, but it no longer starts a public
frame callback loop for the application.
Applications own their threading model:
```text
UI thread
-> start capture
-> create app-owned worker thread
worker thread
-> gvfg_read_frame
-> process or signal UI
-> gvfg_release_frame
```
This keeps the customer API simple while avoiding hidden callback-thread rules.
## Preview Boundary
Preview is not part of the customer SDK API. Internal apps or debug tools may
render frames after `gvfg_read_frame()` with app-owned code:
```text
gvfg_read_frame
-> app/private preview renderer
-> optional snapshot or recording
-> gvfg_release_frame
```
This keeps `gvfg.dll` focused on capture and avoids exposing D3D/render helper
APIs to customers.
## Legacy APIs
`gvfg_set_callbacks()` and `gvfg_set_event_callback()` remain in the header for
source compatibility during the transition. New customer code should prefer:
```text
gvfg_read_frame
gvfg_release_frame
gvfg_poll_event
```
+145
View File
@@ -0,0 +1,145 @@
@echo off
setlocal EnableExtensions
set "PROJECT_DIR=%~dp0"
set "PROJECT_DIR=%PROJECT_DIR:~0,-1%"
set "PROJECT_NAME=GVFG_Standalone"
set "CONFIG=Release"
if "%~1"=="" (
set "OUTPUT_DIR=%PROJECT_DIR%\packages"
) else (
set "OUTPUT_DIR=%~1"
)
if not defined BUILD_DIR set "BUILD_DIR=%PROJECT_DIR%\build_customer_release"
if not defined QT_DIR set "QT_DIR=C:\Qt\6.10.2\msvc2022_64"
if not defined QT_BIN set "QT_BIN=%QT_DIR%\bin"
if not defined CMAKE_EXE set "CMAKE_EXE=C:\Qt\Tools\CMake_64\bin\cmake.exe"
if not exist "%CMAKE_EXE%" set "CMAKE_EXE=cmake"
if not defined VSDEVCMD set "VSDEVCMD=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat"
set "Path="
set "PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0"
for /f %%I in ('powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-Date -Format yyyyMMdd_HHmmss"') do set "STAMP=%%I"
set "PACKAGE_NAME=%PROJECT_NAME%_Customer_Release_%STAMP%"
set "ZIP_PATH=%OUTPUT_DIR%\%PACKAGE_NAME%.zip"
set "STAGE_ROOT=%TEMP%\%PACKAGE_NAME%_%RANDOM%"
set "STAGE_DIR=%STAGE_ROOT%\%PACKAGE_NAME%"
echo [release] Project: "%PROJECT_DIR%"
echo [release] Build: "%BUILD_DIR%"
echo [release] Output: "%ZIP_PATH%"
if not exist "%OUTPUT_DIR%" (
echo [release] Create output folder...
mkdir "%OUTPUT_DIR%" || goto fail
)
if exist "%VSDEVCMD%" (
echo [release] Load Visual Studio x64 build environment...
call "%VSDEVCMD%" -arch=x64 || goto fail
) else (
echo [release] VSDEVCMD not found. Assuming this is already a Visual Studio developer shell.
)
echo [release] Configure CMake...
"%CMAKE_EXE%" -S "%PROJECT_DIR%" -B "%BUILD_DIR%" -DBUILD_GVFG_SAMPLES=ON -DCMAKE_PREFIX_PATH="%QT_DIR%"
if errorlevel 1 goto fail
echo [release] Build %CONFIG%...
"%CMAKE_EXE%" --build "%BUILD_DIR%" --target gvfg_qt_preview --config %CONFIG%
if errorlevel 1 goto fail
set "BIN_DIR=%BUILD_DIR%\bin\%CONFIG%"
set "LIB_DIR=%BUILD_DIR%\lib\%CONFIG%"
if not exist "%BIN_DIR%\gvfg.dll" (
echo [release] ERROR: "%BIN_DIR%\gvfg.dll" not found.
goto fail
)
if not exist "%LIB_DIR%\gvfg.lib" (
echo [release] ERROR: "%LIB_DIR%\gvfg.lib" not found.
goto fail
)
if not exist "%BIN_DIR%\gvfg_qt_preview.exe" (
echo [release] ERROR: "%BIN_DIR%\gvfg_qt_preview.exe" not found.
goto fail
)
if exist "%STAGE_ROOT%" rmdir /S /Q "%STAGE_ROOT%" || goto fail
echo [release] Stage customer package...
mkdir "%STAGE_DIR%\bin" || goto fail
mkdir "%STAGE_DIR%\lib" || goto fail
mkdir "%STAGE_DIR%\include" || goto fail
mkdir "%STAGE_DIR%\docs" || goto fail
mkdir "%STAGE_DIR%\samples\gvfg_qt_preview" || goto fail
mkdir "%STAGE_DIR%\samples\gvfg_qt_preview_source" || goto fail
copy /Y "%PROJECT_DIR%\sdk\gvfg\include\gvfg_capture.h" "%STAGE_DIR%\include\" >nul || goto fail
copy /Y "%BIN_DIR%\gvfg.dll" "%STAGE_DIR%\bin\" >nul || goto fail
copy /Y "%LIB_DIR%\gvfg.lib" "%STAGE_DIR%\lib\" >nul || goto fail
copy /Y "%BIN_DIR%\gvfg_qt_preview.exe" "%STAGE_DIR%\samples\gvfg_qt_preview\" >nul || goto fail
copy /Y "%BIN_DIR%\gvfg.dll" "%STAGE_DIR%\samples\gvfg_qt_preview\" >nul || goto fail
copy /Y "%PROJECT_DIR%\README.md" "%STAGE_DIR%\" >nul || goto fail
copy /Y "%PROJECT_DIR%\docs\GVFG_CUSTOMER_API.md" "%STAGE_DIR%\docs\" >nul || goto fail
robocopy "%PROJECT_DIR%\samples\gvfg_qt_preview" "%STAGE_DIR%\samples\gvfg_qt_preview_source" ^
/E ^
/XF "*.user" "*.suo" "*.obj" "*.pdb" "*.ilk" "*.exp" "*.lib" "*.dll" "*.exe" "*.zip" ^
/NFL /NDL /NJH /NJS /NP
if errorlevel 8 (
echo [release] ERROR: robocopy sample source failed.
goto fail
)
echo [release] Deploy Qt runtime for sample...
if not exist "%QT_BIN%\windeployqt.exe" (
echo [release] ERROR: "%QT_BIN%\windeployqt.exe" not found.
echo [release] Set QT_DIR or QT_BIN before running this script.
goto fail
)
"%QT_BIN%\windeployqt.exe" --release --compiler-runtime --force "%STAGE_DIR%\samples\gvfg_qt_preview\gvfg_qt_preview.exe"
if errorlevel 1 goto fail
echo [release] Write package notes...
(
echo GVFG Standalone Customer Release
echo.
echo Layout:
echo include\gvfg_capture.h
echo lib\gvfg.lib
echo bin\gvfg.dll
echo samples\gvfg_qt_preview\gvfg_qt_preview.exe
echo samples\gvfg_qt_preview_source\
echo docs\GVFG_CUSTOMER_API.md
echo.
echo Link with lib\gvfg.lib and deploy bin\gvfg.dll next to the customer application executable.
echo Run samples\gvfg_qt_preview\gvfg_qt_preview.exe to verify the packaged runtime.
) > "%STAGE_DIR%\PACKAGE_README.txt"
echo [release] Create zip...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
"Compress-Archive -Path '%STAGE_DIR%' -DestinationPath '%ZIP_PATH%' -Force"
if errorlevel 1 goto fail
echo [release] Clean staging folder...
rmdir /S /Q "%STAGE_ROOT%" || goto fail
echo [release] Done.
echo [release] Zip: "%ZIP_PATH%"
if "%NO_PAUSE%"=="" pause
exit /b 0
:fail
echo [release] FAILED.
if exist "%STAGE_ROOT%" rmdir /S /Q "%STAGE_ROOT%" >nul 2>nul
if "%NO_PAUSE%"=="" pause
exit /b 1
+14
View File
@@ -17,6 +17,10 @@ if (QT_VERSION_MAJOR GREATER_EQUAL 6)
previewwindow.cpp
previewwindow.h
previewwindow.ui
sample_preview_renderer.cpp
sample_preview_renderer.h
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/gvfg_log_bridge.cpp
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/render/shared_scene_pipeline.cpp
)
else()
add_executable(gvfg_qt_preview
@@ -27,16 +31,26 @@ else()
previewwindow.cpp
previewwindow.h
previewwindow.ui
sample_preview_renderer.cpp
sample_preview_renderer.h
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/gvfg_log_bridge.cpp
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/render/shared_scene_pipeline.cpp
)
endif()
target_link_libraries(gvfg_qt_preview PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
gvfg
user32
dxgi
d3d11
D3DCompiler
)
target_include_directories(gvfg_qt_preview PRIVATE
${CMAKE_SOURCE_DIR}/sdk/gvfg/include
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/internal
${CMAKE_SOURCE_DIR}/sdk/gvfg/src/render
)
if (MSVC)
+86 -89
View File
@@ -145,9 +145,6 @@ bool MainWindow::openDevice()
return false;
}
gvfg_set_callbacks(handle_, &MainWindow::onFrame, &MainWindow::onError, this);
gvfg_set_event_callback(handle_, &MainWindow::onEvent, this, GVFG_EVENT_MASK_DEFAULT);
const int deviceIndex = ui_->deviceCombo->currentData().toInt();
st = gvfg_open(handle_, deviceIndex);
if (st != GVFG_OK)
@@ -169,6 +166,7 @@ bool MainWindow::openDevice()
void MainWindow::closeDevice()
{
stopCapture();
previewRenderer_.shutdown();
if (signalStatusTimer_)
signalStatusTimer_->stop();
@@ -211,7 +209,10 @@ void MainWindow::startCapture()
}
frameCount_ = 0;
captureStop_.store(false, std::memory_order_release);
captureRunning_ = true;
captureThread_ = std::thread([this]()
{ captureReadLoop(); });
updateUiState();
appendLog(QStringLiteral("Started capture"));
updateSignalStatus(true);
@@ -221,6 +222,8 @@ void MainWindow::stopCapture()
{
if (handle_ && captureRunning_)
{
captureStop_.store(true, std::memory_order_release);
joinCaptureThread();
gvfg_stop(handle_);
captureRunning_ = false;
appendLog(QStringLiteral("Stopped capture"));
@@ -232,18 +235,9 @@ void MainWindow::stopCapture()
bool MainWindow::applyPreview()
{
if (!handle_)
return false;
gvfg_preview_desc_t preview{};
preview.hwnd = previewWindow_->nativePreviewHandle();
preview.enable_preview = 1;
preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO;
const gvfg_status_t st = gvfg_set_preview(handle_, &preview);
if (st != GVFG_OK)
if (!previewRenderer_.configure(previewWindow_->nativePreviewHandle()))
{
showError(QStringLiteral("gvfg_set_preview"), st);
appendLog(QStringLiteral("Preview setup failed: invalid preview window"));
return false;
}
return true;
@@ -252,7 +246,7 @@ bool MainWindow::applyPreview()
void MainWindow::updatePreviewSourceSize(const gvfg_runtime_info_t &info)
{
const auto &signal = info.input_signal;
const auto &callback = info.callback_frame;
const auto &readFrame = info.callback_frame;
if (signal.width > 0 && signal.height > 0)
{
@@ -260,8 +254,8 @@ void MainWindow::updatePreviewSourceSize(const gvfg_runtime_info_t &info)
return;
}
if (callback.valid && callback.width > 0 && callback.height > 0)
previewWindow_->setSourceSize(callback.width, callback.height);
if (readFrame.valid && readFrame.width > 0 && readFrame.height > 0)
previewWindow_->setSourceSize(readFrame.width, readFrame.height);
}
void MainWindow::updatePreviewSourceSize()
@@ -284,8 +278,7 @@ void MainWindow::updateSignalStatus(bool writeLog)
return;
const auto &signal = info.input_signal;
const auto &preview = info.preview_output;
const auto &callback = info.callback_frame;
const auto &readFrame = info.callback_frame;
if (previewWindow_->isVisible())
updatePreviewSourceSize(info);
@@ -320,21 +313,20 @@ void MainWindow::updateSignalStatus(bool writeLog)
.arg(hex32(signal.raw.frame_rate))
.arg(signal.raw.bit_depth)
.arg(hex32(signal.raw.status));
const QString line3 = preview.active
const QString line3 = previewRenderer_.active()
? QStringLiteral("Preview output | frame=%1x%2 format=%3 bitdepth=%4")
.arg(preview.width)
.arg(preview.height)
.arg(QString::fromUtf8(preview.pixel_format))
.arg(preview.bit_depth)
: (preview.enabled ? QStringLiteral("Preview output | configured, inactive")
: QStringLiteral("Preview output | disabled"));
const QString line4 = callback.valid
? QStringLiteral("Callback frame | frame=%1x%2 format=%3 bitdepth=%4")
.arg(callback.width)
.arg(callback.height)
.arg(QString::fromUtf8(callback.pixel_format))
.arg(callback.bit_depth)
: QStringLiteral("Callback frame | --");
.arg(previewRenderer_.width())
.arg(previewRenderer_.height())
.arg(QString::fromUtf8(previewRenderer_.pixelFormat()))
.arg(previewRenderer_.bitDepth())
: QStringLiteral("Preview output | app renderer inactive");
const QString line4 = readFrame.valid
? QStringLiteral("Read frame | frame=%1x%2 format=%3 bitdepth=%4")
.arg(readFrame.width)
.arg(readFrame.height)
.arg(QString::fromUtf8(readFrame.pixel_format))
.arg(readFrame.bit_depth)
: QStringLiteral("Read frame | --");
const QString line5 = QStringLiteral("App runtime | capture=%1 fps delivered=%2")
.arg(info.capture_fps > 0.0 ? QString::number(info.capture_fps, 'f', 2)
: QStringLiteral("--"))
@@ -377,69 +369,74 @@ void MainWindow::appendLog(const QString &message)
ui_->logEdit->appendPlainText(line);
}
void MainWindow::onFrame(const gvfg_frame_t *frame, void *user)
void MainWindow::captureReadLoop()
{
MainWindow *self = static_cast<MainWindow *>(user);
if (!self || !frame)
return;
const uint64_t count = ++self->frameCount_;
if (count <= 5 || (count % 60) == 0)
while (!captureStop_.load(std::memory_order_acquire))
{
const int width = frame->width;
const int height = frame->height;
const uint64_t frameId = frame->frame_id;
QMetaObject::invokeMethod(self,
[self, count, frameId, width, height]()
gvfg_event_t event{};
while (gvfg_poll_event(handle_, &event, 0) == GVFG_OK)
{
const QString type = eventTypeText(event.type);
const uint32_t irqBit = event.irq_bit;
const uint32_t irqMask = event.irq_mask;
const uint64_t timestampNs = event.timestamp_ns;
QMetaObject::invokeMethod(this,
[this, type, irqBit, irqMask, timestampNs]()
{
appendLog(QStringLiteral("event %1 irq=%2 mask=%3 ts=%4")
.arg(type)
.arg(irqBit)
.arg(hex32(irqMask))
.arg(static_cast<qulonglong>(timestampNs)));
},
Qt::QueuedConnection);
}
gvfg_frame_t frame{};
const gvfg_status_t st = gvfg_read_frame(handle_, &frame, 200);
if (st == GVFG_OK)
{
const uint64_t count = ++frameCount_;
const int width = frame.width;
const int height = frame.height;
const uint64_t frameId = frame.frame_id;
previewRenderer_.render(frame);
gvfg_release_frame(handle_, &frame);
if (count <= 5 || (count % 60) == 0)
{
QMetaObject::invokeMethod(this,
[this, count, frameId, width, height]()
{
appendLog(QStringLiteral("read_frame #%1 source id=%2 %3x%4")
.arg(static_cast<qulonglong>(count))
.arg(static_cast<qulonglong>(frameId))
.arg(width)
.arg(height));
},
Qt::QueuedConnection);
}
continue;
}
if (st == GVFG_ETIMEOUT)
continue;
if (captureStop_.load(std::memory_order_acquire) || st == GVFG_ESTATE)
break;
QMetaObject::invokeMethod(this,
[this, st]()
{
self->appendLog(QStringLiteral("callback #%1 source id=%2 %3x%4")
.arg(static_cast<qulonglong>(count))
.arg(static_cast<qulonglong>(frameId))
.arg(width)
.arg(height));
appendLog(QStringLiteral("gvfg_read_frame failed: %1")
.arg(QString::fromUtf8(gvfg_strerror(st))));
},
Qt::QueuedConnection);
break;
}
}
void MainWindow::onEvent(const gvfg_event_t *event, void *user)
void MainWindow::joinCaptureThread()
{
MainWindow *self = static_cast<MainWindow *>(user);
if (!self || !event)
return;
const QString type = eventTypeText(event->type);
const uint32_t irqBit = event->irq_bit;
const uint32_t irqMask = event->irq_mask;
const uint64_t timestampNs = event->timestamp_ns;
QMetaObject::invokeMethod(self,
[self, type, irqBit, irqMask, timestampNs]()
{
self->appendLog(QStringLiteral("event %1 irq=%2 mask=%3 ts=%4")
.arg(type)
.arg(irqBit)
.arg(hex32(irqMask))
.arg(static_cast<qulonglong>(timestampNs)));
},
Qt::QueuedConnection);
}
void MainWindow::onError(gvfg_status_t status, const char *message, void *user)
{
MainWindow *self = static_cast<MainWindow *>(user);
if (!self)
return;
const QString text = message && message[0]
? QString::fromUtf8(message)
: QString::fromUtf8(gvfg_strerror(status));
QMetaObject::invokeMethod(self,
[self, status, text]()
{
self->appendLog(QStringLiteral("message %1: %2")
.arg(static_cast<int>(status))
.arg(text));
},
Qt::QueuedConnection);
if (captureThread_.joinable())
captureThread_.join();
}
+8 -4
View File
@@ -2,12 +2,15 @@
#include <gvfg_capture.h>
#include "sample_preview_renderer.h"
#include <QString>
#include <QWidget>
#include <array>
#include <atomic>
#include <cstdint>
#include <thread>
class QCloseEvent;
class PreviewWindow;
@@ -46,17 +49,18 @@ private:
void updateUiState();
void showError(const QString &apiName, gvfg_status_t status);
void appendLog(const QString &message);
static void onFrame(const gvfg_frame_t *frame, void *user);
static void onEvent(const gvfg_event_t *event, void *user);
static void onError(gvfg_status_t status, const char *message, void *user);
void captureReadLoop();
void joinCaptureThread();
Ui::MainWindow *ui_ = nullptr;
PreviewWindow *previewWindow_ = nullptr;
std::array<gvfg_device_info_t, GVFG_MAX_DEVICES> devices_{};
int deviceCount_ = 0;
gvfg_handle handle_ = nullptr;
SamplePreviewRenderer previewRenderer_;
bool captureRunning_ = false;
std::atomic<bool> captureStop_{false};
std::thread captureThread_;
std::atomic<uint64_t> frameCount_{0};
QTimer *signalStatusTimer_ = nullptr;
QString lastSignalStatusText_;
@@ -0,0 +1,198 @@
#include "sample_preview_renderer.h"
#include "gvfg_render_types.h"
#include "shared_scene_pipeline.h"
#include <d3d11_4.h>
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;
struct SamplePreviewRenderer::D3DState
{
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
};
SamplePreviewRenderer::SamplePreviewRenderer() = default;
SamplePreviewRenderer::~SamplePreviewRenderer()
{
shutdown();
}
bool SamplePreviewRenderer::configure(void *hwnd)
{
std::lock_guard<std::mutex> lock(mutex_);
hwnd_ = hwnd;
configured_ = hwnd_ != nullptr;
if (pipeline_)
{
gvfg::internal::gvfg_render_preview_desc_t desc{};
desc.hwnd = hwnd_;
desc.enable_preview = configured_ ? 1 : 0;
desc.use_fp16_pipeline = 1;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
}
return configured_;
}
bool SamplePreviewRenderer::render(const gvfg_frame_t &frame)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!configured_ || !hwnd_ || !frame.data || frame.width <= 0 || frame.height <= 0)
return false;
if (!ensureDevice() || !ensurePipeline(frame.width, frame.height, frame.bit_depth > 0 ? frame.bit_depth : 8))
return false;
const auto *base = static_cast<const uint8_t *>(frame.data);
gvfg::internal::gvfg_render_pixfmt_t renderFmt = gvfg::internal::GVFG_RENDER_FMT_YUY2;
bool uploaded = false;
switch (frame.pixel_format)
{
case GVFG_PIXFMT_YUY2:
renderFmt = gvfg::internal::GVFG_RENDER_FMT_YUY2;
uploaded = pipeline_->upload_yuy2_frame(base, frame.width * 2, frame.width, frame.height);
break;
case GVFG_PIXFMT_Y210:
renderFmt = gvfg::internal::GVFG_RENDER_FMT_Y210;
uploaded = pipeline_->upload_y210_frame(base, frame.width * 4, frame.width, frame.height);
break;
default:
return false;
}
if (!uploaded ||
!pipeline_->render_uploaded_yuv_to_fp16(renderFmt, frame.width, frame.height) ||
!pipeline_->copy_fp16_to_scene())
return false;
bool ok = true;
if (!pipeline_->preview_swapchain_10bit())
ok = pipeline_->blit_fp16_to_rgba8(frame.width, frame.height);
if (!ok)
return false;
pipeline_->present_preview(frame.width, frame.height);
width_ = pipeline_->preview_w_;
height_ = pipeline_->preview_h_;
bitDepth_ = pipeline_->preview_swapchain_10bit() ? 10 : 8;
swapchain10Bit_ = pipeline_->preview_swapchain_10bit();
return true;
}
void SamplePreviewRenderer::shutdown()
{
std::lock_guard<std::mutex> lock(mutex_);
if (pipeline_)
pipeline_->release_preview_swapchain();
pipeline_.reset();
d3d_.reset();
configured_ = false;
hwnd_ = nullptr;
width_ = 0;
height_ = 0;
bitDepth_ = 0;
swapchain10Bit_ = false;
}
bool SamplePreviewRenderer::active() const
{
std::lock_guard<std::mutex> lock(mutex_);
return configured_ && pipeline_ && width_ > 0 && height_ > 0;
}
int SamplePreviewRenderer::width() const
{
std::lock_guard<std::mutex> lock(mutex_);
return width_;
}
int SamplePreviewRenderer::height() const
{
std::lock_guard<std::mutex> lock(mutex_);
return height_;
}
int SamplePreviewRenderer::bitDepth() const
{
std::lock_guard<std::mutex> lock(mutex_);
return bitDepth_;
}
const char *SamplePreviewRenderer::pixelFormat() const
{
std::lock_guard<std::mutex> lock(mutex_);
return swapchain10Bit_ ? "RGB10A2" : "BGRA8";
}
bool SamplePreviewRenderer::ensureDevice()
{
if (d3d_ && d3d_->device && d3d_->context)
return true;
auto state = std::make_unique<D3DState>();
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0};
D3D_FEATURE_LEVEL got{};
HRESULT hr = D3D11CreateDevice(nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
flags,
levels,
_countof(levels),
D3D11_SDK_VERSION,
&state->device,
&got,
&state->context);
#ifdef _DEBUG
if (FAILED(hr))
{
flags &= ~D3D11_CREATE_DEVICE_DEBUG;
hr = D3D11CreateDevice(nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
flags,
levels,
_countof(levels),
D3D11_SDK_VERSION,
&state->device,
&got,
&state->context);
}
#endif
if (FAILED(hr) || !state->device || !state->context)
return false;
ComPtr<ID3D11Multithread> mt;
if (SUCCEEDED(state->device.As(&mt)) && mt)
mt->SetMultithreadProtected(TRUE);
d3d_ = std::move(state);
return true;
}
bool SamplePreviewRenderer::ensurePipeline(int width, int height, int sourceBitDepth)
{
if (!pipeline_)
pipeline_ = std::make_unique<gvfg::internal::SharedScenePipeline>();
if (!pipeline_->initialize(d3d_->device.Get(), d3d_->context.Get()))
return false;
gvfg::internal::gvfg_render_preview_desc_t desc{};
desc.hwnd = hwnd_;
desc.enable_preview = configured_ ? 1 : 0;
desc.use_fp16_pipeline = 1;
desc.swapchain_10bit = gvfg::internal::GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
pipeline_->configurePreview(desc);
pipeline_->set_source_bit_depth(sourceBitDepth > 0 ? sourceBitDepth : 8);
return pipeline_->ensure_rt_and_pipeline(width, height) &&
pipeline_->ensure_preview_swapchain(width, height);
}
@@ -0,0 +1,44 @@
#pragma once
#include <gvfg_capture.h>
#include <memory>
#include <mutex>
namespace gvfg::internal
{
class SharedScenePipeline;
}
class SamplePreviewRenderer
{
public:
SamplePreviewRenderer();
~SamplePreviewRenderer();
bool configure(void *hwnd);
bool render(const gvfg_frame_t &frame);
void shutdown();
bool active() const;
int width() const;
int height() const;
int bitDepth() const;
const char *pixelFormat() const;
private:
bool ensureDevice();
bool ensurePipeline(int width, int height, int sourceBitDepth);
mutable std::mutex mutex_;
void *hwnd_ = nullptr;
bool configured_ = false;
int width_ = 0;
int height_ = 0;
int bitDepth_ = 0;
bool swapchain10Bit_ = false;
struct D3DState;
std::unique_ptr<D3DState> d3d_;
std::unique_ptr<gvfg::internal::SharedScenePipeline> pipeline_;
};
-4
View File
@@ -14,7 +14,6 @@ add_library(gvfg SHARED
src/backend/xdma/xdma_public.h
src/gvfg_capture.cpp
src/gvfg_log_bridge.cpp
src/render/shared_scene_pipeline.cpp
)
set_target_properties(gvfg PROPERTIES
@@ -29,7 +28,6 @@ target_include_directories(gvfg
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/backend/xdma
${CMAKE_CURRENT_SOURCE_DIR}/src/internal
${CMAKE_CURRENT_SOURCE_DIR}/src/render
)
target_compile_definitions(gvfg PRIVATE
@@ -43,8 +41,6 @@ endif()
target_link_libraries(gvfg PRIVATE
setupapi
user32
dxgi d3d11 D3DCompiler
)
if (MSVC)
+89 -111
View File
@@ -13,31 +13,26 @@
*
* gvfg_handle h = NULL;
* gvfg_create(&h);
* gvfg_set_callbacks(h, on_frame, on_error, user);
* // Optional: gvfg_set_frame_callback_interval(h, 6); // one callback per 6 frames
*
* // Optional: let the SDK render preview directly into a native HWND.
* gvfg_preview_desc_t preview = {};
* preview.hwnd = hwnd;
* preview.enable_preview = 1;
* preview.swapchain_bitdepth = GVFG_PREVIEW_BITDEPTH_AUTO;
* gvfg_set_preview(h, &preview);
*
* gvfg_open(h, devices[0].index);
* gvfg_start(h);
*
* // Capture is now running. Use callbacks for frames/messages and
* // gvfg_get_runtime_info() for status.
* while (running) {
* gvfg_frame_t frame = {};
* if (gvfg_read_frame(h, &frame, 1000) == GVFG_OK) {
* // Use frame.data before releasing the frame.
* gvfg_release_frame(h, &frame);
* }
* }
*
* gvfg_stop(h);
* gvfg_destroy(h);
*
* Threading notes:
* - Frame and error callbacks are called from an SDK worker thread, not from
* the UI thread. UI applications should marshal callback work back to their
* UI thread.
* - The frame data pointer is valid only during the callback. Copy the data if
* it must be used after the callback returns.
* - The main frame API is pull-based: applications call gvfg_read_frame() from
* the thread they choose.
* - The frame data pointer remains valid until gvfg_release_frame() is called.
* Copy the data if it must outlive that call.
* - At most one frame may be held by a handle at a time.
*/
#include <stdint.h>
@@ -73,13 +68,6 @@ typedef enum
GVFG_ETIMEOUT = -6 /* Timed out waiting for driver/backend work. */
} gvfg_status_t;
typedef enum
{
GVFG_PREVIEW_BITDEPTH_AUTO = 0, /* Let the SDK choose the best swapchain format. */
GVFG_PREVIEW_BITDEPTH_10BIT = 10, /* Prefer a 10-bit preview swapchain when available. */
GVFG_PREVIEW_BITDEPTH_8BIT = 8 /* Force an 8-bit preview swapchain. */
} gvfg_preview_bitdepth_t;
typedef enum
{
GVFG_PIXFMT_UNKNOWN = 0,
@@ -100,13 +88,6 @@ typedef struct
char name[128]; /* Display name for UI/logging. UTF-8, null-terminated. */
} gvfg_device_info_t;
typedef struct
{
void *hwnd; /* Native Windows HWND that stays alive while capture runs. */
int enable_preview; /* Non-zero enables SDK-managed preview rendering. */
int swapchain_bitdepth; /* gvfg_preview_bitdepth_t value. */
} gvfg_preview_desc_t;
typedef struct
{
uint32_t width; /* Raw FPGA width value. */
@@ -136,47 +117,24 @@ typedef struct
typedef struct
{
int width; /* Width of frames delivered to the customer callback. */
int height; /* Height of frames delivered to the customer callback. */
int bit_depth; /* Bits per color channel of the callback buffer. */
char pixel_format[32]; /* Native callback buffer format, for example YUY2, Y210, NV12, or P010. */
int valid; /* Non-zero while capture is running after at least one callback frame. */
int width; /* Width of the most recent frame returned by gvfg_read_frame(). */
int height; /* Height of the most recent frame returned by gvfg_read_frame(). */
int bit_depth; /* Bits per color channel of the frame buffer. */
char pixel_format[32]; /* Native frame buffer format, for example YUY2, Y210, NV12, or P010. */
int valid; /* Non-zero while capture is running after at least one frame read. */
} gvfg_callback_frame_info_t;
typedef struct
{
int enabled; /* Non-zero when SDK-managed preview was requested. */
int active; /* Non-zero when the preview pipeline is active. */
int width; /* Preview render width. */
int height; /* Preview render height. */
int bit_depth; /* Preview output bit depth, usually 8 or 10. */
char pixel_format[32]; /* Preview output format, for example BGRA8 or RGB10A2. */
} gvfg_preview_output_info_t;
typedef struct
{
gvfg_signal_status_t input_signal; /* FPGA-reported signal metadata. */
gvfg_preview_output_info_t preview_output; /* SDK-managed preview output, separate from callbacks. */
gvfg_callback_frame_info_t callback_frame; /* Frame buffer delivered by gvfg.dll to the app callback. */
double capture_fps; /* Runtime FPS measured from backend frames seen by the SDK worker. */
uint64_t delivered_frames; /* Number of frames delivered to the app callback. */
gvfg_callback_frame_info_t callback_frame; /* Last frame returned by gvfg_read_frame(); name kept for ABI compatibility. */
double capture_fps; /* Runtime FPS measured from frames returned by gvfg_read_frame(). */
uint64_t delivered_frames; /* Number of frames returned by gvfg_read_frame(). */
} gvfg_runtime_info_t;
typedef struct
{
int enabled; /* Non-zero when preview was requested. */
int active; /* Non-zero when the preview pipeline is currently active. */
int width; /* Preview render width. */
int height; /* Preview render height. */
int swapchain_bitdepth; /* Actual preview swapchain bit depth, usually 8 or 10. */
int swapchain_10bit; /* Non-zero when the active swapchain is 10-bit. */
char render_path[128]; /* Human-readable preview pipeline description. */
char backbuffer_format[64]; /* DXGI backbuffer format name. */
} gvfg_preview_info_t;
typedef struct
{
const void *data; /* Native frame buffer. Valid only during the frame callback. */
const void *data; /* Native frame buffer. Valid until gvfg_release_frame() is called. */
uint64_t data_size; /* Total bytes available from data. */
int width; /* Frame width in pixels. */
int height; /* Frame height in pixels. */
@@ -220,9 +178,7 @@ typedef struct
/* Opaque session handle created by gvfg_create() and released by gvfg_destroy(). */
typedef struct gvfg_handle_t *gvfg_handle;
/* Called when the SDK provides a frame for application use.
* This callback is not required for SDK-managed preview rendering.
*/
/* Legacy callback type kept for source compatibility. */
typedef void (*gvfg_on_frame_cb)(const gvfg_frame_t *frame, void *user);
/* Called for capture events such as PLUG_IN / PLUG_OUT. */
@@ -278,12 +234,12 @@ GVFG_API gvfg_status_t gvfg_create(gvfg_handle *out_handle);
GVFG_API gvfg_status_t gvfg_destroy(gvfg_handle handle);
/*
* Register frame and error callbacks.
* Register legacy frame and error callbacks.
*
* Parameters:
* - handle: Session handle returned by gvfg_create().
* - on_frame: Function called when a frame is available. Pass NULL if frame
* callbacks are not needed.
* - on_frame: Reserved for the legacy callback path. The pull-based
* gvfg_read_frame() API is the primary frame API.
* - on_error: Function called for asynchronous SDK messages/errors. Pass NULL
* if error callbacks are not needed.
* - user: Application-defined pointer passed back to both callbacks.
@@ -292,8 +248,8 @@ GVFG_API gvfg_status_t gvfg_destroy(gvfg_handle handle);
* - GVFG_OK on success.
* - GVFG_EINVAL if handle is NULL.
*
* Callbacks are called from an SDK worker thread. The application must marshal
* UI work to its UI thread.
* New applications should use gvfg_read_frame() and gvfg_release_frame()
* instead of frame callbacks.
*/
GVFG_API gvfg_status_t gvfg_set_callbacks(gvfg_handle handle,
gvfg_on_frame_cb on_frame,
@@ -312,19 +268,18 @@ GVFG_API gvfg_status_t gvfg_set_callbacks(gvfg_handle handle,
* - GVFG_OK on success.
* - GVFG_EINVAL if handle is NULL.
*
* This only affects the application frame callback. SDK-managed preview
* rendering, gvfg_get_runtime_info(), and capture itself continue at full rate.
* This setting is kept for source compatibility with the legacy callback API.
*/
GVFG_API gvfg_status_t gvfg_set_frame_callback_interval(gvfg_handle handle,
uint32_t frame_interval);
/*
* Register capture event callback.
* Register legacy capture event callback.
*
* Parameters:
* - handle: Session handle returned by gvfg_create().
* - on_event: Function called when an enabled capture event occurs. Pass NULL
* to disable event callbacks.
* to disable event callbacks. New applications should use gvfg_poll_event().
* - user: Application-defined pointer passed back to the callback.
* - event_mask: GVFG_EVENT_MASK_* bits. Pass 0 to use GVFG_EVENT_MASK_DEFAULT.
*
@@ -341,24 +296,6 @@ GVFG_API gvfg_status_t gvfg_set_event_callback(gvfg_handle handle,
void *user,
uint32_t event_mask);
/*
* Configure SDK-managed preview rendering.
*
* Parameters:
* - handle: Session handle returned by gvfg_create().
* - desc: Preview configuration. Must not be NULL. When preview is enabled,
* desc->hwnd must be a valid native Windows HWND.
*
* Returns:
* - GVFG_OK on success.
* - GVFG_EINVAL if handle or desc is NULL.
*
* This API is optional. If enabled, call it before gvfg_start() and keep the
* HWND alive while capture is running. Applications that render frames
* themselves can skip this API and use the frame callback instead.
*/
GVFG_API gvfg_status_t gvfg_set_preview(gvfg_handle handle, const gvfg_preview_desc_t *desc);
/*
* Open a device by index from gvfg_enumerate_devices().
*
@@ -388,11 +325,67 @@ GVFG_API gvfg_status_t gvfg_open(gvfg_handle handle, int device_index);
* - GVFG_ESTATE if no device is open.
* - GVFG_EIO or another status code if stream configuration/start fails.
*
* After success, frames and asynchronous messages are delivered through the
* callbacks registered by gvfg_set_callbacks().
* After success, call gvfg_read_frame() to receive frames and gvfg_poll_event()
* to receive capture events.
*/
GVFG_API gvfg_status_t gvfg_start(gvfg_handle handle);
/*
* Read one captured frame.
*
* Parameters:
* - handle: Running capture session.
* - out_frame: Receives a frame descriptor. Must not be NULL.
* - timeout_ms: Maximum time to wait. Use 0 to wait indefinitely.
*
* Returns:
* - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_frame is NULL.
* - GVFG_ESTATE if capture is not running or a previous frame has not been
* released.
* - 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.
*/
GVFG_API gvfg_status_t gvfg_read_frame(gvfg_handle handle,
gvfg_frame_t *out_frame,
uint32_t timeout_ms);
/*
* Release a frame returned by gvfg_read_frame().
*
* Parameters:
* - handle: Running capture session.
* - frame: Frame previously returned by gvfg_read_frame(). The SDK currently
* uses this as a lifetime token; pass the same descriptor back.
*
* Returns:
* - GVFG_OK on success.
* - GVFG_EINVAL if handle or frame is NULL.
* - GVFG_ESTATE if no frame is currently held.
*/
GVFG_API gvfg_status_t gvfg_release_frame(gvfg_handle handle,
const gvfg_frame_t *frame);
/*
* Poll one capture event.
*
* Parameters:
* - handle: Opened session handle.
* - out_event: Receives the event. Must not be NULL.
* - timeout_ms: Maximum time to wait. Use 0 to return immediately.
*
* Returns:
* - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_event is NULL.
* - GVFG_ETIMEOUT if no event is available before timeout_ms expires.
*/
GVFG_API gvfg_status_t gvfg_poll_event(gvfg_handle handle,
gvfg_event_t *out_event,
uint32_t timeout_ms);
/*
* Stop capture.
*
@@ -403,7 +396,7 @@ GVFG_API gvfg_status_t gvfg_start(gvfg_handle handle);
* - GVFG_OK on success, including when capture is already stopped.
* - GVFG_EINVAL if handle is NULL.
*
* This waits for the SDK capture worker thread to exit.
* This stops backend capture and invalidates any unreleased frame.
*/
GVFG_API gvfg_status_t gvfg_stop(gvfg_handle handle);
@@ -440,21 +433,6 @@ GVFG_API gvfg_status_t gvfg_get_signal_status(gvfg_handle handle, gvfg_signal_st
*/
GVFG_API gvfg_status_t gvfg_get_runtime_info(gvfg_handle handle, gvfg_runtime_info_t *out_info);
/*
* Query SDK-managed preview diagnostics.
*
* Parameters:
* - handle: Session handle returned by gvfg_create().
* - out_info: Receives preview information. Must not be NULL.
*
* Returns:
* - GVFG_OK on success.
* - GVFG_EINVAL if handle or out_info is NULL.
*
* This is useful only when the application uses gvfg_set_preview().
*/
GVFG_API gvfg_status_t gvfg_get_preview_info(gvfg_handle handle, gvfg_preview_info_t *out_info);
/*
* Convert a GVFG status code to a static English error string.
*
+132 -264
View File
@@ -1,25 +1,19 @@
#include "gvfg_capture.h"
#include "gvfg_render_types.h"
#include "shared_scene_pipeline.h"
#include "xdma_capture_session.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <d3d11_4.h>
#include <dxgi.h>
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;
using namespace gvfg::internal;
namespace
@@ -139,23 +133,6 @@ namespace
return out ? out : XDMA_EVENT_MASK_DEFAULT;
}
const char *dxgi_format_name(DXGI_FORMAT fmt)
{
switch (fmt)
{
case DXGI_FORMAT_UNKNOWN:
return "UNKNOWN";
case DXGI_FORMAT_B8G8R8A8_UNORM:
return "B8G8R8A8_UNORM";
case DXGI_FORMAT_R10G10B10A2_UNORM:
return "R10G10B10A2_UNORM";
case DXGI_FORMAT_R16G16B16A16_FLOAT:
return "R16G16B16A16_FLOAT";
default:
return "DXGI_FORMAT_OTHER";
}
}
bool fpga_field_valid(uint32_t mask, int bit)
{
return (mask & (1u << bit)) != 0;
@@ -325,9 +302,6 @@ struct gvfg_handle_t
if (cfg != GVFG_OK)
return cfg;
if (previewHwnd && !createRenderPipeline())
emitError(GVFG_ENOTSUP, "GVFG preview pipeline unavailable");
resetRuntimeCounters();
const xdma_status_t st = backend->start_stream();
if (st != XDMA_OK)
@@ -337,16 +311,13 @@ struct gvfg_handle_t
}
running = true;
captureThread = std::thread([this]()
{ captureLoop(); });
return GVFG_OK;
}
gvfg_status_t stop()
{
running = false;
if (captureThread.joinable())
captureThread.join();
releaseHeldFrameForStop();
if (backend)
backend->stop_stream();
return GVFG_OK;
@@ -355,7 +326,6 @@ struct gvfg_handle_t
void close()
{
stop();
releaseRenderPipeline();
if (backend)
{
backend->set_event_callback(nullptr, nullptr, 0);
@@ -374,17 +344,6 @@ struct gvfg_handle_t
return GVFG_OK;
}
gvfg_status_t setPreview(const gvfg_preview_desc_t &desc)
{
previewDesc = desc;
previewHwnd = desc.enable_preview ? desc.hwnd : nullptr;
if (pipeline)
pipeline->configurePreview(toRenderPreviewDesc());
if (previewHwnd && width > 0 && height > 0)
createRenderPipeline();
return GVFG_OK;
}
gvfg_status_t getSignalStatus(gvfg_signal_status_t &out)
{
std::memset(&out, 0, sizeof(out));
@@ -432,16 +391,6 @@ struct gvfg_handle_t
getSignalStatus(out.input_signal);
const uint64_t frames = deliveredFrames.load(std::memory_order_relaxed);
const bool deliveredValid = running.load(std::memory_order_relaxed) && frames > 0;
out.preview_output.enabled = previewHwnd ? 1 : 0;
out.preview_output.active = (pipeline && previewHwnd) ? 1 : 0;
if (out.preview_output.active)
{
out.preview_output.width = pipeline->preview_w_;
out.preview_output.height = pipeline->preview_h_;
out.preview_output.bit_depth = pipeline->preview_swapchain_10bit() ? 10 : 8;
copy_cstr(out.preview_output.pixel_format, sizeof(out.preview_output.pixel_format),
pipeline->preview_swapchain_10bit() ? "RGB10A2" : "BGRA8");
}
out.callback_frame.valid = deliveredValid ? 1 : 0;
if (deliveredValid)
@@ -458,32 +407,11 @@ struct gvfg_handle_t
return GVFG_OK;
}
gvfg_status_t getPreviewInfo(gvfg_preview_info_t &out)
{
std::memset(&out, 0, sizeof(out));
out.enabled = previewHwnd ? 1 : 0;
out.active = (pipeline && previewHwnd) ? 1 : 0;
out.width = pipeline ? pipeline->preview_w_ : 0;
out.height = pipeline ? pipeline->preview_h_ : 0;
out.swapchain_bitdepth = pipeline ? (pipeline->preview_swapchain_10bit() ? 10 : 8)
: previewDesc.swapchain_bitdepth;
out.swapchain_10bit = pipeline && pipeline->preview_swapchain_10bit() ? 1 : 0;
copy_cstr(out.render_path, sizeof(out.render_path),
pipeline ? (pipeline->preview_swapchain_10bit()
? "YUY2 Shader -> FP16 Scene -> 10bit Swapchain"
: "YUY2 Shader -> FP16 Scene -> 8bit Swapchain")
: (previewHwnd ? "Preview helper configured, pipeline inactive"
: "Preview helper disabled"));
copy_cstr(out.backbuffer_format, sizeof(out.backbuffer_format),
pipeline ? dxgi_format_name(pipeline->preview_backbuffer_format()) : "N/A");
return GVFG_OK;
}
void syncBackendEventCallback()
{
if (!backend)
return;
backend->set_event_callback(onEvent ? &gvfg_handle_t::onBackendEvent : nullptr,
backend->set_event_callback(&gvfg_handle_t::onBackendEvent,
this,
map_event_mask_to_xdma(eventMask));
}
@@ -498,15 +426,21 @@ struct gvfg_handle_t
void emitEvent(const xdma_event_t &event)
{
if (!onEvent)
return;
gvfg_event_t out{};
out.type = map_event_type(event.type);
out.irq_bit = event.irq_bit;
out.irq_mask = event.irq_mask;
out.timestamp_ns = event.timestamp_ns;
onEvent(&out, eventCallbackUser);
{
std::lock_guard<std::mutex> lock(eventMutex);
if (eventQueue.size() >= 64)
eventQueue.pop_front();
eventQueue.push_back(out);
}
eventCv.notify_one();
if (onEvent)
onEvent(&out, eventCallbackUser);
}
void querySignal()
@@ -626,176 +560,42 @@ struct gvfg_handle_t
return GVFG_OK;
}
gvfg_render_preview_desc_t toRenderPreviewDesc() const
gvfg_status_t readFrame(gvfg_frame_t &out, uint32_t timeoutMs)
{
gvfg_render_preview_desc_t desc{};
desc.hwnd = previewHwnd;
desc.enable_preview = previewHwnd ? 1 : 0;
desc.use_fp16_pipeline = 1;
switch (previewDesc.swapchain_bitdepth)
std::memset(&out, 0, sizeof(out));
if (!backend || !running)
return GVFG_ESTATE;
{
case GVFG_PREVIEW_BITDEPTH_8BIT:
desc.swapchain_10bit = GVFG_RENDER_PREVIEW_BITDEPTH_8BIT;
break;
case GVFG_PREVIEW_BITDEPTH_10BIT:
desc.swapchain_10bit = GVFG_RENDER_PREVIEW_BITDEPTH_10BIT;
break;
case GVFG_PREVIEW_BITDEPTH_AUTO:
default:
desc.swapchain_10bit = GVFG_RENDER_PREVIEW_BITDEPTH_AUTO;
break;
std::lock_guard<std::mutex> lock(frameMutex);
if (readInProgress || frameHeld)
return GVFG_ESTATE;
readInProgress = true;
}
return desc;
}
bool createRenderPipeline()
{
if (!previewHwnd || width == 0 || height == 0)
return false;
if (!pipeline)
pipeline = std::make_unique<SharedScenePipeline>();
if (!d3d)
xdma_frame_t frame{};
const xdma_status_t st = backend->wait_frame(timeoutMs, frame);
if (st != XDMA_OK)
{
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0};
D3D_FEATURE_LEVEL got{};
HRESULT hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
flags, levels, _countof(levels), D3D11_SDK_VERSION,
&d3d, &got, &ctx);
#ifdef _DEBUG
if (FAILED(hr))
{
flags &= ~D3D11_CREATE_DEVICE_DEBUG;
hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
flags, levels, _countof(levels), D3D11_SDK_VERSION,
&d3d, &got, &ctx);
std::lock_guard<std::mutex> lock(frameMutex);
readInProgress = false;
}
#endif
if (FAILED(hr) || !d3d || !ctx)
return false;
ComPtr<ID3D11Multithread> mt;
if (SUCCEEDED(d3d.As(&mt)) && mt)
mt->SetMultithreadProtected(TRUE);
}
if (!pipeline->initialize(d3d.Get(), ctx.Get()))
return false;
pipeline->configurePreview(toRenderPreviewDesc());
pipeline->set_source_bit_depth(static_cast<int>(bitDepth ? bitDepth : 8));
return pipeline->ensure_rt_and_pipeline(static_cast<int>(width), static_cast<int>(height)) &&
pipeline->ensure_preview_swapchain(static_cast<int>(width), static_cast<int>(height));
}
void releaseRenderPipeline()
{
if (pipeline)
{
pipeline->release_preview_swapchain();
pipeline.reset();
}
ctx.Reset();
d3d.Reset();
}
void captureLoop()
{
while (running)
{
xdma_frame_t frame{};
const xdma_status_t st = backend->wait_frame(1000, frame);
if (!running)
break;
if (st == XDMA_ETIMEOUT)
continue;
if (st != XDMA_OK)
{
if (st != XDMA_ETIMEOUT && st != XDMA_ESTATE)
emitError(map_status(st), xdma_error_text(st, backend.get()));
break;
}
return map_status(st);
}
updateRuntimeFps(now_ns());
renderGpuFrame(frame);
emitNativeFrame(frame);
updateRuntimeFps(now_ns());
if (!frame.data || frame.width == 0 || frame.height == 0)
{
backend->release_frame(frame);
}
}
bool renderGpuFrame(const xdma_frame_t &frame)
{
if (!pipeline || !previewHwnd || !frame.data)
return false;
const int w = static_cast<int>(frame.width);
const int h = static_cast<int>(frame.height);
if (w <= 0 || h <= 0)
return false;
if (!pipeline->ensure_rt_and_pipeline(w, h) || !pipeline->ensure_preview_swapchain(w, h))
return false;
uint32_t fallbackBitDepth = 8;
{
std::lock_guard<std::mutex> lock(stateMutex);
fallbackBitDepth = bitDepth ? bitDepth : 8;
}
pipeline->set_source_bit_depth(static_cast<int>(frame.bit_depth ? frame.bit_depth : fallbackBitDepth));
const auto *base = static_cast<const uint8_t *>(frame.data);
gvfg_render_pixfmt_t renderFmt = GVFG_RENDER_FMT_YUY2;
bool uploaded = false;
switch (frame.pixel_format)
{
case XDMA_PIXFMT_YUY2:
{
renderFmt = GVFG_RENDER_FMT_YUY2;
uploaded = pipeline->upload_yuy2_frame(base, w * 2, w, h);
break;
}
case XDMA_PIXFMT_Y210:
{
renderFmt = GVFG_RENDER_FMT_Y210;
uploaded = pipeline->upload_y210_frame(base, w * 4, w, h);
break;
}
case XDMA_PIXFMT_NV12:
case XDMA_PIXFMT_P010:
return false;
default:
return false;
std::lock_guard<std::mutex> lock(frameMutex);
readInProgress = false;
return GVFG_EIO;
}
if (!uploaded ||
!pipeline->render_uploaded_yuv_to_fp16(renderFmt, w, h) ||
!pipeline->copy_fp16_to_scene())
return false;
bool ok = true;
if (!pipeline->preview_swapchain_10bit())
ok = pipeline->blit_fp16_to_rgba8(w, h);
if (ok)
pipeline->present_preview(w, h);
return ok;
}
void emitNativeFrame(const xdma_frame_t &frame)
{
if (!onFrame || !frame.data)
return;
if (!shouldEmitFrameCallback(frame.frame_id))
return;
if (frame.width == 0 || frame.height == 0)
return;
gvfg_frame_t out{};
out.data = frame.data;
out.data_size = static_cast<uint64_t>(frame.data_size_bytes);
out.width = static_cast<int>(frame.width);
@@ -803,16 +603,76 @@ struct gvfg_handle_t
out.pixel_format = to_gvfg_pixel_format(frame.pixel_format);
out.bit_depth = static_cast<int>(frame.bit_depth);
out.frame_id = frame.frame_id;
onFrame(&out, callbackUser);
noteDeliveredFrame(out.width, out.height, out.bit_depth, out.pixel_format);
std::lock_guard<std::mutex> lock(frameMutex);
heldBackendFrame = frame;
readInProgress = false;
frameHeld = true;
return GVFG_OK;
}
bool shouldEmitFrameCallback(uint64_t frameId) const
gvfg_status_t releaseFrame(const gvfg_frame_t &)
{
const uint32_t interval = callbackFrameInterval.load(std::memory_order_relaxed);
if (interval <= 1)
return true;
return (frameId % interval) == 1;
if (!backend)
return GVFG_ESTATE;
xdma_frame_t frame{};
{
std::lock_guard<std::mutex> lock(frameMutex);
if (!frameHeld)
return GVFG_ESTATE;
frame = heldBackendFrame;
heldBackendFrame = {};
frameHeld = false;
}
return map_status(backend->release_frame(frame));
}
void releaseHeldFrameForStop()
{
if (!backend)
return;
xdma_frame_t frame{};
bool shouldRelease = false;
{
std::lock_guard<std::mutex> lock(frameMutex);
if (frameHeld)
{
frame = heldBackendFrame;
heldBackendFrame = {};
frameHeld = false;
shouldRelease = true;
}
}
if (shouldRelease)
backend->release_frame(frame);
}
gvfg_status_t pollEvent(gvfg_event_t &out, uint32_t timeoutMs)
{
std::unique_lock<std::mutex> lock(eventMutex);
const auto hasEvent = [this]()
{
return !eventQueue.empty();
};
if (timeoutMs == 0)
{
if (!hasEvent())
return GVFG_ETIMEOUT;
}
else if (!eventCv.wait_for(lock, std::chrono::milliseconds(timeoutMs), hasEvent))
{
return GVFG_ETIMEOUT;
}
out = eventQueue.front();
eventQueue.pop_front();
return GVFG_OK;
}
void emitError(gvfg_status_t code, const char *msg)
@@ -859,8 +719,6 @@ struct gvfg_handle_t
std::unique_ptr<gvfg::internal::XdmaCaptureSession> backend;
int currentIndex = -1;
xdma_input_t selectedInput = XDMA_INPUT_SDI;
gvfg_preview_desc_t previewDesc{};
void *previewHwnd = nullptr;
uint32_t width = 0;
uint32_t height = 0;
@@ -893,11 +751,14 @@ struct gvfg_handle_t
uint32_t eventMask = GVFG_EVENT_MASK_DEFAULT;
std::atomic<bool> running{false};
std::thread captureThread;
std::mutex frameMutex;
bool readInProgress = false;
bool frameHeld = false;
xdma_frame_t heldBackendFrame{};
std::mutex eventMutex;
std::condition_variable eventCv;
std::deque<gvfg_event_t> eventQueue;
ComPtr<ID3D11Device> d3d;
ComPtr<ID3D11DeviceContext> ctx;
std::unique_ptr<SharedScenePipeline> pipeline;
};
extern "C"
@@ -975,13 +836,6 @@ extern "C"
return handle->setEventCallback(on_event, user, event_mask);
}
gvfg_status_t gvfg_set_preview(gvfg_handle handle, const gvfg_preview_desc_t *desc)
{
if (!handle || !desc)
return GVFG_EINVAL;
return handle->setPreview(*desc);
}
gvfg_status_t gvfg_open(gvfg_handle handle, int device_index)
{
if (!handle)
@@ -996,6 +850,27 @@ extern "C"
return handle->start();
}
gvfg_status_t gvfg_read_frame(gvfg_handle handle, gvfg_frame_t *out_frame, uint32_t timeout_ms)
{
if (!handle || !out_frame)
return GVFG_EINVAL;
return handle->readFrame(*out_frame, timeout_ms);
}
gvfg_status_t gvfg_release_frame(gvfg_handle handle, const gvfg_frame_t *frame)
{
if (!handle || !frame)
return GVFG_EINVAL;
return handle->releaseFrame(*frame);
}
gvfg_status_t gvfg_poll_event(gvfg_handle handle, gvfg_event_t *out_event, uint32_t timeout_ms)
{
if (!handle || !out_event)
return GVFG_EINVAL;
return handle->pollEvent(*out_event, timeout_ms);
}
gvfg_status_t gvfg_stop(gvfg_handle handle)
{
if (!handle)
@@ -1017,13 +892,6 @@ extern "C"
return handle->getRuntimeInfo(*out_info);
}
gvfg_status_t gvfg_get_preview_info(gvfg_handle handle, gvfg_preview_info_t *out_info)
{
if (!handle || !out_info)
return GVFG_EINVAL;
return handle->getPreviewInfo(*out_info);
}
const char *gvfg_strerror(gvfg_status_t status)
{
switch (status)