Remove superseded standalone Qt sample

This commit is contained in:
Mark.lin
2026-10-02 09:17:50 +08:00
parent d17628981c
commit 51991b82a0
19 changed files with 10 additions and 2760 deletions
-155
View File
@@ -1,155 +0,0 @@
cmake_minimum_required(VERSION 3.16)
project(gvfg_qt_preview LANGUAGES CXX)
set(GVFG_SAMPLE_VERSION "1.0.1-internal")
include(GNUInstallDirs)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
if (NOT WIN32)
message(FATAL_ERROR "GVFG Qt Sample currently supports Windows only.")
endif()
set(GVFG_SDK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../GVFG_SDK"
CACHE PATH "GVFG SDK source root containing public headers")
set(_GVFG_DEFAULT_RELEASE_DIR
"${GVFG_SDK_ROOT}/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release")
set(GVFG_SDK_RELEASE_DIR "${_GVFG_DEFAULT_RELEASE_DIR}"
CACHE PATH "One fixed Release GVFG SDK build directory containing bin and lib")
if (GVFG_SDK_RELEASE_DIR STREQUAL "${GVFG_SDK_ROOT}/build-release")
set(GVFG_SDK_RELEASE_DIR "${_GVFG_DEFAULT_RELEASE_DIR}"
CACHE PATH "One fixed Release GVFG SDK build directory containing bin and lib" FORCE)
endif()
set(_GVFG_INCLUDE_DIR "${GVFG_SDK_ROOT}/sdk/gvfg/include")
set(_GVFG_PREVIEW_INCLUDE_DIR "${GVFG_SDK_ROOT}/helpers/gvfg_preview/include")
set(_GVFG_AUDIO_PLAYBACK_INCLUDE_DIR "${GVFG_SDK_ROOT}/helpers/gvfg_audio_playback/include")
if (MSVC)
set(_GVFG_IMPLIB_NAME "gvfg.lib")
set(_GVFG_PREVIEW_IMPLIB_NAME "gvfg_preview.lib")
set(_GVFG_AUDIO_PLAYBACK_IMPLIB_NAME "gvfg_audio_playback.lib")
elseif (MINGW)
set(_GVFG_IMPLIB_NAME "libgvfg.dll.a")
set(_GVFG_PREVIEW_IMPLIB_NAME "libgvfg_preview.dll.a")
set(_GVFG_AUDIO_PLAYBACK_IMPLIB_NAME "libgvfg_audio_playback.dll.a")
else()
message(FATAL_ERROR "Unsupported compiler. Use MSVC or MinGW on Windows x64.")
endif()
set(_GVFG_BIN_DIR "${GVFG_SDK_RELEASE_DIR}/bin")
set(_GVFG_LIB_DIR "${GVFG_SDK_RELEASE_DIR}/lib")
set(_GVFG_IMPLIB "${_GVFG_LIB_DIR}/${_GVFG_IMPLIB_NAME}")
set(_GVFG_PREVIEW_IMPLIB "${_GVFG_LIB_DIR}/${_GVFG_PREVIEW_IMPLIB_NAME}")
set(_GVFG_AUDIO_PLAYBACK_IMPLIB "${_GVFG_LIB_DIR}/${_GVFG_AUDIO_PLAYBACK_IMPLIB_NAME}")
message(STATUS "GVFG SDK Release build: ${GVFG_SDK_RELEASE_DIR}")
foreach(_required_file
"${_GVFG_INCLUDE_DIR}/gvfg_capture.h"
"${_GVFG_PREVIEW_INCLUDE_DIR}/gvfg_preview.h"
"${_GVFG_AUDIO_PLAYBACK_INCLUDE_DIR}/gvfg_audio_playback.h"
"${_GVFG_BIN_DIR}/gvfg.dll"
"${_GVFG_BIN_DIR}/gvfg_preview.dll"
"${_GVFG_BIN_DIR}/gvfg_audio_playback.dll"
"${_GVFG_IMPLIB}"
"${_GVFG_PREVIEW_IMPLIB}"
"${_GVFG_AUDIO_PLAYBACK_IMPLIB}")
if (NOT EXISTS "${_required_file}")
message(FATAL_ERROR
"Required prebuilt GVFG SDK file was not found: ${_required_file}\n"
"Build GVFG_SDK Release first or set GVFG_SDK_RELEASE_DIR.")
endif()
endforeach()
add_library(GVFG::Capture SHARED IMPORTED GLOBAL)
set_target_properties(GVFG::Capture PROPERTIES
IMPORTED_LOCATION "${_GVFG_BIN_DIR}/gvfg.dll"
IMPORTED_IMPLIB "${_GVFG_IMPLIB}"
INTERFACE_INCLUDE_DIRECTORIES "${_GVFG_INCLUDE_DIR}"
)
add_library(GVFG::Preview SHARED IMPORTED GLOBAL)
set_target_properties(GVFG::Preview PROPERTIES
IMPORTED_LOCATION "${_GVFG_BIN_DIR}/gvfg_preview.dll"
IMPORTED_IMPLIB "${_GVFG_PREVIEW_IMPLIB}"
INTERFACE_INCLUDE_DIRECTORIES "${_GVFG_PREVIEW_INCLUDE_DIR}"
)
add_library(GVFG::AudioPlayback SHARED IMPORTED GLOBAL)
set_target_properties(GVFG::AudioPlayback PROPERTIES
IMPORTED_LOCATION "${_GVFG_BIN_DIR}/gvfg_audio_playback.dll"
IMPORTED_IMPLIB "${_GVFG_AUDIO_PLAYBACK_IMPLIB}"
INTERFACE_INCLUDE_DIRECTORIES "${_GVFG_AUDIO_PLAYBACK_INCLUDE_DIR}"
)
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
set(GVFG_QT_PREVIEW_SOURCES
main.cpp
audio_playback.cpp
audio_playback.h
capture_controller.cpp
capture_controller.h
sample_log.cpp
sample_log.h
mainwindow.cpp
mainwindow.h
mainwindow.ui
previewwindow.cpp
previewwindow.h
previewwindow.ui
)
list(APPEND GVFG_QT_PREVIEW_SOURCES
$<$<CONFIG:Debug>:${CMAKE_CURRENT_SOURCE_DIR}/internal_diagnostics.cpp>
$<$<CONFIG:Debug>:${CMAKE_CURRENT_SOURCE_DIR}/internal_diagnostics.h>
)
if (QT_VERSION_MAJOR GREATER_EQUAL 6)
qt_add_executable(gvfg_qt_preview ${GVFG_QT_PREVIEW_SOURCES})
else()
add_executable(gvfg_qt_preview ${GVFG_QT_PREVIEW_SOURCES})
endif()
target_link_libraries(gvfg_qt_preview PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
GVFG::Capture
GVFG::Preview
GVFG::AudioPlayback
)
target_compile_definitions(gvfg_qt_preview PRIVATE
GVFG_SAMPLE_VERSION="${GVFG_SAMPLE_VERSION}"
GVFG_INTERNAL_DIAGNOSTICS=$<IF:$<CONFIG:Debug>,1,0>
)
if (MSVC)
target_compile_options(gvfg_qt_preview PRIVATE /utf-8)
endif()
add_custom_command(TARGET gvfg_qt_preview POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${_GVFG_BIN_DIR}/gvfg.dll"
"${_GVFG_BIN_DIR}/gvfg_preview.dll"
"${_GVFG_BIN_DIR}/gvfg_audio_playback.dll"
$<TARGET_FILE_DIR:gvfg_qt_preview>
)
set_target_properties(gvfg_qt_preview PROPERTIES
WIN32_EXECUTABLE TRUE
)
install(TARGETS gvfg_qt_preview
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
-23
View File
@@ -1,23 +0,0 @@
# 關鍵交付 Log
畫面保留原本狀態,不顯示完整交付統計,也不增加設定控制。正常的預覽與音訊佇列取捨不輸出 Log。
- `[LIB]`:GigabyteLib 回傳的 signal 或 event 現象。
- `[SDK]`/`[SDK API]`:SDK read 邊界或 API 回傳的現象。
- `[APP]`:Preview、audio output 或 Sample 自身核對的現象。
- 累計數字最多每 5 秒彙整一次;Stop 會補記尚未輸出的變化。
- Stop 不列印正常統計摘要;只有實際 API、preview 或 audio output 錯誤才記錄。
## 拿到 Log 後怎麼處理
Log 只標示觀測層、現象與數值。Video/audio `frame_id` 是 SDK 每次 Start 從 1 開始的成功交付序號,不再使用 GigabyteLib `FrameCount`;`[APP] Preview ...` 是 Sample 顯示路徑問題。
預覽使用 Present(0, 0),讓 DXGI 等待呈現相依條件,不做外部重試。SyncInterval 仍為 0,並非每張都保證顯示。預覽改成 FIFO,最多保留 3 張待處理影像(包含正在上傳的容量保留),另有 1 個處理中槽位,共 4 個 GPU 槽。60 FPS 下 3 張約 50 ms;這不是刻意等滿 50 ms 才顯示。從上傳完成入列開始計時,等待超過 50 ms 的影像才丟棄(expired);容量滿時跳過新影像(busy),不替換仍在期限內的舊影像。50 ms 是開始處理前的等待期限,不含 GPU 執行/DXGI Present 等待,不保證端到端延遲或實體螢幕逐張呈現。Stop/關閉/鎖等待只處理 Windows 同步送達的視窗訊息,避免 DXGI 等待 UI 而 UI 又等待 worker;不處理一般排隊輸入或 Qt callbacks。
Audio 與 Customer Sample 使用相同的 `gvfg_audio_playback.dll` WASAPI helper。APP 先複製 SDK PCM、release SDK frame,再以 SDK timestamp 寫入 helper 的 bounded queue;queue full、輸出失敗、retry、recovery 與 Stop 統計都會寫入內部版 log。audio frame 不保證與 video frame 等長。
Helper create/start/write 失敗時會記錄 status、文字錯誤與 retry;非 queue-full 錯誤會重建 Windows 預設播放端點。APP 不因播放裝置暫時失敗而停止 SDK capture。
統計從 APP 成功取得 SDK frame 開始。SDK ID 連續不能證明更上游沒有丟失;DXGI 接受 Present、audio helper 接受 PCM 也不代表實體螢幕已顯示或喇叭已實際發聲。已丟掉的原始資料無法靠這些處理補回。
擷取 API/驅動不修改。新版 APP 需配套的新版 gvfg_preview.dll。後續 GPU 優化修改了共用的轉換原始碼;若要發佈包含該優化的 SDK GPU buffer converter,也需重建其 DLL。尚待 build、播放/預覽異常測試與硬體長測;靜態檢查不能證明零丟失。
-198
View File
@@ -1,198 +0,0 @@
#include "audio_playback.h"
#include <utility>
namespace
{
constexpr auto kPlaybackRetryDelay = std::chrono::milliseconds(500);
}
AudioPlayback::~AudioPlayback() { stop(); }
gvfg_audio_playback_status_t AudioPlayback::startPlayerLocked()
{
gvfg_audio_player next = nullptr;
gvfg_audio_playback_status_t status = gvfg_audio_player_create(&next);
if (status == GVFG_AUDIO_PLAYBACK_OK)
{
gvfg_audio_playback_format_t outputFormat{};
outputFormat.sample_rate = format_.sample_rate;
outputFormat.channels = format_.channels;
outputFormat.bits_per_sample = format_.bits_per_sample;
status = gvfg_audio_player_start(next, &outputFormat);
}
if (status == GVFG_AUDIO_PLAYBACK_OK)
{
player_ = next;
return status;
}
gvfg_audio_player_destroy(next);
nextRetry_ = std::chrono::steady_clock::now() + kPlaybackRetryDelay;
return status;
}
void AudioPlayback::start(int channel, const gvfg_audio_format_t &format,
LogCallback logCallback)
{
stop();
gvfg_audio_playback_status_t status;
LogCallback callback;
{
std::lock_guard<std::mutex> lock(mutex_);
channel_ = channel;
format_ = format;
logCallback_ = std::move(logCallback);
statistics_ = {};
active_ = true;
status = startPlayerLocked();
callback = logCallback_;
}
if (!callback)
return;
if (status == GVFG_AUDIO_PLAYBACK_OK)
callback(QStringLiteral("CH%1 [AUDIO HELPER] started | %2 Hz %3 ch %4-bit PCM")
.arg(channel).arg(format.sample_rate).arg(format.channels).arg(format.bits_per_sample));
else
callback(QStringLiteral("CH%1 [AUDIO HELPER] WARNING start failed | status=%2 error=%3 | retry_ms=500")
.arg(channel).arg(static_cast<int>(status))
.arg(QString::fromUtf8(gvfg_audio_player_strerror(status))));
}
void AudioPlayback::stop()
{
gvfg_audio_player player = nullptr;
LogCallback callback;
Statistics stats;
int channel = 0;
bool wasActive = false;
{
std::lock_guard<std::mutex> lock(mutex_);
wasActive = active_;
active_ = false;
player = player_;
player_ = nullptr;
callback = logCallback_;
logCallback_ = {};
stats = statistics_;
channel = channel_;
}
gvfg_audio_player_destroy(player);
if (wasActive && callback)
callback(QStringLiteral("CH%1 [AUDIO HELPER] stopped | received=%2 release_failed=%3 output_failed=%4 queue_full=%5 retries=%6 recoveries=%7")
.arg(channel)
.arg(static_cast<qulonglong>(stats.receivedFrames))
.arg(static_cast<qulonglong>(stats.releaseFailedFrames))
.arg(static_cast<qulonglong>(stats.outputFailedFrames))
.arg(static_cast<qulonglong>(stats.queueFullFrames))
.arg(static_cast<qulonglong>(stats.retryAttempts))
.arg(static_cast<qulonglong>(stats.recoveries)));
}
bool AudioPlayback::enqueue(std::vector<uint8_t> pcm, uint64_t timestampNs)
{
QString message;
LogCallback callback;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!active_)
return false;
if (!player_ && std::chrono::steady_clock::now() >= nextRetry_)
{
++statistics_.retryAttempts;
const auto status = startPlayerLocked();
if (status == GVFG_AUDIO_PLAYBACK_OK)
{
++statistics_.recoveries;
message = QStringLiteral("CH%1 [AUDIO HELPER] output recovered | retry=%2")
.arg(channel_).arg(static_cast<qulonglong>(statistics_.retryAttempts));
}
else
{
message = QStringLiteral("CH%1 [AUDIO HELPER] retry failed | retry=%2 status=%3 error=%4")
.arg(channel_).arg(static_cast<qulonglong>(statistics_.retryAttempts))
.arg(static_cast<int>(status))
.arg(QString::fromUtf8(gvfg_audio_player_strerror(status)));
}
}
if (player_)
{
const auto status = gvfg_audio_player_write_timed(
player_, pcm.data(), static_cast<uint32_t>(pcm.size()), timestampNs);
if (status != GVFG_AUDIO_PLAYBACK_OK)
{
++statistics_.outputFailedFrames;
if (status == GVFG_AUDIO_PLAYBACK_EQUEUE_FULL)
{
++statistics_.queueFullFrames;
message = QStringLiteral("CH%1 [AUDIO HELPER] queue full | dropped=%2 bytes=%3 timestamp_ns=%4")
.arg(channel_)
.arg(static_cast<qulonglong>(statistics_.queueFullFrames))
.arg(pcm.size())
.arg(static_cast<qulonglong>(timestampNs));
}
else
{
gvfg_audio_player failed = player_;
player_ = nullptr;
gvfg_audio_player_destroy(failed);
nextRetry_ = std::chrono::steady_clock::now() + kPlaybackRetryDelay;
message = QStringLiteral("CH%1 [AUDIO HELPER] playback failed | status=%2 error=%3 bytes=%4 timestamp_ns=%5 | retry_ms=500")
.arg(channel_).arg(static_cast<int>(status))
.arg(QString::fromUtf8(gvfg_audio_player_strerror(status)))
.arg(pcm.size()).arg(static_cast<qulonglong>(timestampNs));
}
}
}
callback = logCallback_;
}
if (!message.isEmpty() && callback)
callback(message);
return true;
}
void AudioPlayback::updateVideoTimestamp(uint64_t timestampNs)
{
std::lock_guard<std::mutex> lock(mutex_);
if (player_)
gvfg_audio_player_update_video_timestamp(player_, timestampNs);
}
void AudioPlayback::resetTimeline(const QString &reason)
{
LogCallback callback;
gvfg_audio_playback_status_t status = GVFG_AUDIO_PLAYBACK_OK;
int channel = 0;
bool attempted = false;
{
std::lock_guard<std::mutex> lock(mutex_);
if (player_)
{
attempted = true;
status = gvfg_audio_player_reset_timeline(player_);
}
callback = logCallback_;
channel = channel_;
}
if (attempted && callback)
callback(QStringLiteral("CH%1 [AUDIO HELPER] timeline reset | reason=%2 status=%3 error=%4")
.arg(channel).arg(reason).arg(static_cast<int>(status))
.arg(QString::fromUtf8(gvfg_audio_player_strerror(status))));
}
void AudioPlayback::recordReceivedFrame()
{
std::lock_guard<std::mutex> lock(mutex_);
++statistics_.receivedFrames;
}
void AudioPlayback::recordReleaseFailure()
{
std::lock_guard<std::mutex> lock(mutex_);
++statistics_.releaseFailedFrames;
}
AudioPlayback::Statistics AudioPlayback::statistics() const
{
std::lock_guard<std::mutex> lock(mutex_);
return statistics_;
}
-55
View File
@@ -1,55 +0,0 @@
#pragma once
#include <gvfg_capture.h>
#include <gvfg_audio_playback.h>
#include <QString>
#include <chrono>
#include <cstdint>
#include <functional>
#include <mutex>
#include <vector>
class AudioPlayback final
{
public:
struct Statistics
{
uint64_t receivedFrames = 0;
uint64_t releaseFailedFrames = 0;
uint64_t outputFailedFrames = 0;
uint64_t queueFullFrames = 0;
uint64_t retryAttempts = 0;
uint64_t recoveries = 0;
};
using LogCallback = std::function<void(const QString &)>;
AudioPlayback() = default;
~AudioPlayback();
AudioPlayback(const AudioPlayback &) = delete;
AudioPlayback &operator=(const AudioPlayback &) = delete;
void start(int channel, const gvfg_audio_format_t &format, LogCallback logCallback);
void stop();
bool enqueue(std::vector<uint8_t> pcm, uint64_t timestampNs);
void updateVideoTimestamp(uint64_t timestampNs);
void resetTimeline(const QString &reason);
void recordReceivedFrame();
void recordReleaseFailure();
Statistics statistics() const;
private:
gvfg_audio_playback_status_t startPlayerLocked();
int channel_ = 0;
gvfg_audio_format_t format_{};
LogCallback logCallback_;
mutable std::mutex mutex_;
gvfg_audio_player player_ = nullptr;
bool active_ = false;
std::chrono::steady_clock::time_point nextRetry_{};
Statistics statistics_{};
};
File diff suppressed because it is too large Load Diff
-126
View File
@@ -1,126 +0,0 @@
#pragma once
#include "audio_playback.h"
#if GVFG_INTERNAL_DIAGNOSTICS
#include "internal_diagnostics.h"
#endif
#include <gvfg_capture.h>
#include <gvfg_preview.h>
#include <QObject>
#include <QStringList>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <thread>
class QTimer;
class CaptureController final : public QObject
{
Q_OBJECT
public:
explicit CaptureController(QObject *parent = nullptr);
~CaptureController() override;
void setSelectedDeviceIndex(int index) { selectedDeviceIndex_ = index; }
void setChannelOptions(int channel, bool zeroCopy, gvfg_pixel_format_t format, bool audioEnabled);
void setChannelStatusVisible(int channel, bool visible);
void setPreviewTarget(int channel, void *nativeWindow);
void setPreviewVisible(int channel, bool visible);
bool deviceOpen() const { return handle_ != nullptr; }
bool channelOpened(int channel) const;
bool channelRunning(int channel) const;
bool frameAvailable(int channel) const;
bool cachedSignalStatus(int channel, gvfg_signal_status_t *status) const;
QString sdkVersion() const;
QString gigabyteLibVersion() const;
public slots:
void refreshDevices();
void closeDevice();
void startCapture(int channel);
void stopCapture(int channel);
void stopAllCaptures();
bool applyPreview(int channel);
void processPendingEvents();
void updateSignalStatus(bool queryHardware = true);
signals:
void devicesChanged(const QStringList &names);
void stateChanged();
void statusChanged(const QString &text);
void sdiInfoChanged(const QString &text);
void logMessage(const QString &message);
#if GVFG_INTERNAL_DIAGNOSTICS
void diagnosticMessage(const QString &message);
#endif
void previewSourceSizeChanged(int channel, int width, int height);
void previewShowRequested(int channel);
void previewCloseRequested(int channel);
private:
bool openDevice();
bool applyOutputFormat(int channel);
bool prepareAudio(int channel);
void closeDeviceSession(bool clearSelection);
void closeDeviceIfIdle();
struct ChannelRuntime
{
bool opened = false;
bool zeroCopy = false;
bool requestedAudio = false;
gvfg_pixel_format_t requestedFormat = GVFG_PIXFMT_YUY2;
void *previewTarget = nullptr;
gvfg_preview_handle previewHandle = nullptr;
std::atomic<bool> running{false}, stopRequested{false}, signalConnected{false};
std::atomic<bool> frameAvailable{false}, previewVisible{false}, captureThreadExited{true};
std::thread captureThread, audioThread;
AudioPlayback audioPlayback;
bool audioEnabled = false;
gvfg_audio_format_t audioFormat{};
std::atomic<uint64_t> videoFailed{0};
gvfg_preview_delivery_stats_t previewBaseline{};
uint64_t lastLoggedPreviewFailures = 0;
uint64_t lastLoggedAudioReleaseFailures = 0, lastLoggedAudioOutputFailures = 0;
qint64 lastDeliveryLogMs = 0;
uint64_t previewFailureCount = 0;
gvfg_signal_status_t cachedSignalStatus{};
bool haveCachedSignalStatus = false;
QString cachedSdiInfoText;
QString lastLoggedInputStatus;
};
void reportError(const QString &apiName, gvfg_status_t status, int channel = -1);
void appendLog(const QString &message);
bool openChannel(int channel);
void refreshSdiInfo(int channel);
#if GVFG_INTERNAL_DIAGNOSTICS
void writeDiagnosticSnapshot(const QString &statusText);
#endif
void captureReadLoop(int channel);
void audioReadLoop(int channel);
void joinCaptureThread(int channel);
void joinAudioThread(int channel);
void logDeliveryStatus(int channel, bool finalSnapshot = false);
std::array<gvfg_device_info_t, GVFG_MAX_DEVICES> devices_{};
int deviceCount_ = 0;
gvfg_handle handle_ = nullptr;
int selectedDeviceIndex_ = -1;
std::array<ChannelRuntime, 2> channels_{};
#if GVFG_INTERNAL_DIAGNOSTICS
InternalDiagnostics internalDiagnostics_;
#endif
std::array<bool, 2> channelStatusVisible_{{true, true}};
QTimer *runtimeStatusTimer_ = nullptr;
QString lastSignalStatusText_;
bool closingDevice_ = false;
};
-214
View File
@@ -1,214 +0,0 @@
#include "internal_diagnostics.h"
#include <algorithm>
#if GVFG_INTERNAL_DIAGNOSTICS
#include <gvfg_debug.h>
#endif
void InternalDiagnostics::beginStart(int channel)
{
if (channel < 0 || channel >= static_cast<int>(metrics_.size()))
return;
metrics_[channel].startTime = std::chrono::steady_clock::now();
}
void InternalDiagnostics::finishStartCall(int channel)
{
if (channel < 0 || channel >= static_cast<int>(metrics_.size()))
return;
ChannelMetrics &metrics = metrics_[channel];
metrics.startCallMs = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - metrics.startTime)
.count();
}
void InternalDiagnostics::resetChannel(gvfg_handle handle, int channel)
{
if (channel < 0 || channel >= static_cast<int>(baselines_.size()))
return;
baselines_[channel] = {};
ChannelMetrics &metrics = metrics_[channel];
metrics.successfulFrames = 0;
metrics.windowSamples = 0;
metrics.windowMaximumMs = 0.0;
metrics.startupLatencyReported = false;
metrics.videoReceived.store(0, std::memory_order_relaxed);
metrics.readSamples.store(0, std::memory_order_relaxed);
metrics.readAverageMs.store(0.0, std::memory_order_relaxed);
metrics.readMaximumMs.store(0.0, std::memory_order_relaxed);
metrics.readWindowMaximumMs.store(0.0, std::memory_order_relaxed);
#if GVFG_INTERNAL_DIAGNOSTICS
gvfg_debug_backend_stats_t stats{};
if (handle != nullptr &&
gvfg_debug_get_channel_backend_stats(handle, channel, &stats) == GVFG_OK)
{
baselines_[channel] = {
stats.video_dma_event_wakes,
stats.extra_video_event_wakes,
stats.video_frames_from_lib,
stats.audio_dma_event_wakes,
stats.extra_audio_event_wakes,
stats.audio_frames_from_lib,
stats.audio_driver_frame_count};
}
#else
(void)handle;
#endif
}
void InternalDiagnostics::recordVideoRead(int channel, double elapsedMs)
{
constexpr uint64_t kTimingWarmupFrames = 30;
constexpr uint64_t kTimingWindowFrames = 300;
if (channel < 0 || channel >= static_cast<int>(metrics_.size()))
return;
ChannelMetrics &metrics = metrics_[channel];
metrics.videoReceived.fetch_add(1, std::memory_order_relaxed);
if (++metrics.successfulFrames <= kTimingWarmupFrames)
return;
++metrics.windowSamples;
metrics.windowMaximumMs = (std::max)(metrics.windowMaximumMs, elapsedMs);
const uint64_t totalSamples = metrics.readSamples.fetch_add(1, std::memory_order_relaxed) + 1;
const double previousAverage = metrics.readAverageMs.load(std::memory_order_relaxed);
metrics.readAverageMs.store(
previousAverage + (elapsedMs - previousAverage) / static_cast<double>(totalSamples),
std::memory_order_relaxed);
double observedMaximum = metrics.readMaximumMs.load(std::memory_order_relaxed);
while (elapsedMs > observedMaximum &&
!metrics.readMaximumMs.compare_exchange_weak(
observedMaximum, elapsedMs, std::memory_order_relaxed))
{
}
if (totalSamples <= kTimingWindowFrames)
metrics.readWindowMaximumMs.store(metrics.windowMaximumMs, std::memory_order_relaxed);
if (metrics.windowSamples >= kTimingWindowFrames)
{
metrics.readWindowMaximumMs.store(metrics.windowMaximumMs, std::memory_order_relaxed);
metrics.windowSamples = 0;
metrics.windowMaximumMs = 0.0;
}
}
QString InternalDiagnostics::takeStartupLatencyLine(int channel,
double firstReadMs,
double firstRenderMs,
uint64_t frameId)
{
if (channel < 0 || channel >= static_cast<int>(metrics_.size()))
return {};
ChannelMetrics &metrics = metrics_[channel];
if (metrics.startupLatencyReported)
return {};
metrics.startupLatencyReported = true;
const double totalMs = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - metrics.startTime)
.count();
return QStringLiteral("CH%1 Startup latency | Start -> start_channel return=%2 ms | "
"first read_frame call -> return=%3 ms | "
"first render_frame call -> return=%4 ms | "
"Start -> first render_frame return=%5 ms | SDK_frame_id=%6")
.arg(channel)
.arg(metrics.startCallMs, 0, 'f', 3)
.arg(firstReadMs, 0, 'f', 3)
.arg(firstRenderMs, 0, 'f', 3)
.arg(totalMs, 0, 'f', 3)
.arg(static_cast<qulonglong>(frameId));
}
void InternalDiagnostics::appendAudioStatusLine(QStringList &lines,
gvfg_handle handle,
int channel,
uint64_t audioReceived) const
{
#if GVFG_INTERNAL_DIAGNOSTICS
if (handle == nullptr || channel < 0 || channel >= static_cast<int>(baselines_.size()))
return;
gvfg_debug_backend_stats_t stats{};
if (gvfg_debug_get_channel_backend_stats(handle, channel, &stats) != GVFG_OK)
return;
const BackendBaseline &baseline = baselines_[channel];
const QString driverFrames = stats.audio_driver_frame_count_valid
? QString::number(static_cast<qulonglong>(
stats.audio_driver_frame_count - baseline.audioDriverFrameCount))
: QStringLiteral("unavailable");
lines << QStringLiteral("CH%1 Audio State | enabled=%2 running=%3 | event DMA=%4 Extra=%5 | driver_frames=%6")
.arg(channel)
.arg(stats.audio_enabled ? QStringLiteral("yes") : QStringLiteral("no"))
.arg(stats.stream_running ? QStringLiteral("yes") : QStringLiteral("no"))
.arg(stats.audio_frame_event_valid ? QStringLiteral("valid") : QStringLiteral("NULL"))
.arg(stats.audio_extra_event_valid ? QStringLiteral("valid") : QStringLiteral("NULL"))
.arg(driverFrames);
lines << QStringLiteral("CH%1 Audio Debug | LIB events DMA=%2 Extra=%3 | LIB->SDK %4 frames | SDK->APP %5 frames")
.arg(channel)
.arg(static_cast<qulonglong>(stats.audio_dma_event_wakes - baseline.audioDmaEventWakes))
.arg(static_cast<qulonglong>(stats.extra_audio_event_wakes - baseline.extraAudioEventWakes))
.arg(static_cast<qulonglong>(stats.audio_frames_from_lib - baseline.audioFramesFromLibrary))
.arg(static_cast<qulonglong>(audioReceived));
#else
(void)lines;
(void)handle;
(void)channel;
(void)audioReceived;
#endif
}
void InternalDiagnostics::appendVideoStatusLines(QStringList &lines,
gvfg_handle handle,
int channel,
bool zeroCopy) const
{
#if GVFG_INTERNAL_DIAGNOSTICS
if (handle == nullptr || channel < 0 || channel >= static_cast<int>(baselines_.size()))
return;
const ChannelMetrics &metrics = metrics_[channel];
const uint64_t readSamples = metrics.readSamples.load(std::memory_order_relaxed);
lines << (readSamples >= 300
? QStringLiteral("CH%1 Read | avg=%2 max300=%3 max=%4 ms samples=%5")
.arg(channel)
.arg(metrics.readAverageMs.load(std::memory_order_relaxed), 0, 'f', 3)
.arg(metrics.readWindowMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3)
.arg(metrics.readMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3)
.arg(static_cast<qulonglong>(readSamples))
: QStringLiteral("CH%1 Read | measuring").arg(channel));
gvfg_debug_backend_stats_t stats{};
if (gvfg_debug_get_channel_backend_stats(handle, channel, &stats) != GVFG_OK)
return;
const BackendBaseline &baseline = baselines_[channel];
lines << (stats.get_frame_timing_samples >= 300
? QStringLiteral("CH%1 %2 | avg=%3 max300=%4 max=%5 us samples=%6")
.arg(channel)
.arg(zeroCopy
? QStringLiteral("[LIB] GvfgGetVideoFrameZeroCopy")
: QStringLiteral("[LIB] GvfgGetVideoFrame"))
.arg(stats.get_frame_timing_average_us, 0, 'f', 3)
.arg(stats.get_frame_timing_max300_us, 0, 'f', 3)
.arg(stats.get_frame_timing_max_us, 0, 'f', 3)
.arg(static_cast<qulonglong>(stats.get_frame_timing_samples))
: QStringLiteral("CH%1 [LIB] GetVideoFrame | measuring").arg(channel));
lines << QStringLiteral("CH%1 Video Debug | LIB events DMA=%2 Extra=%3 | LIB->SDK %4 frames | SDK->APP %5 frames")
.arg(channel)
.arg(static_cast<qulonglong>(stats.video_dma_event_wakes - baseline.videoDmaEventWakes))
.arg(static_cast<qulonglong>(stats.extra_video_event_wakes - baseline.extraVideoEventWakes))
.arg(static_cast<qulonglong>(stats.video_frames_from_lib - baseline.videoFramesFromLibrary))
.arg(static_cast<qulonglong>(metrics.videoReceived.load(std::memory_order_relaxed)));
#else
(void)lines;
(void)handle;
(void)channel;
(void)zeroCopy;
#endif
}
-61
View File
@@ -1,61 +0,0 @@
#pragma once
#include <gvfg_capture.h>
#include <QStringList>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdint>
class InternalDiagnostics final
{
public:
void beginStart(int channel);
void finishStartCall(int channel);
void resetChannel(gvfg_handle handle, int channel);
void recordVideoRead(int channel, double elapsedMs);
QString takeStartupLatencyLine(int channel,
double firstReadMs,
double firstRenderMs,
uint64_t frameId);
void appendAudioStatusLine(QStringList &lines,
gvfg_handle handle,
int channel,
uint64_t audioReceived) const;
void appendVideoStatusLines(QStringList &lines,
gvfg_handle handle,
int channel,
bool zeroCopy) const;
private:
struct BackendBaseline
{
uint64_t videoDmaEventWakes = 0;
uint64_t extraVideoEventWakes = 0;
uint64_t videoFramesFromLibrary = 0;
uint64_t audioDmaEventWakes = 0;
uint64_t extraAudioEventWakes = 0;
uint64_t audioFramesFromLibrary = 0;
uint64_t audioDriverFrameCount = 0;
};
struct ChannelMetrics
{
std::chrono::steady_clock::time_point startTime{};
double startCallMs = 0.0;
uint64_t successfulFrames = 0;
uint64_t windowSamples = 0;
double windowMaximumMs = 0.0;
bool startupLatencyReported = false;
std::atomic<uint64_t> videoReceived{0};
std::atomic<uint64_t> readSamples{0};
std::atomic<double> readAverageMs{0.0};
std::atomic<double> readMaximumMs{0.0};
std::atomic<double> readWindowMaximumMs{0.0};
};
std::array<BackendBaseline, 2> baselines_{};
std::array<ChannelMetrics, 2> metrics_{};
};
-15
View File
@@ -1,15 +0,0 @@
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = createMainWindow();
window->show();
const int result = app.exec();
delete window;
return result;
}
-243
View File
@@ -1,243 +0,0 @@
#include "mainwindow.h"
#include "capture_controller.h"
#include "previewwindow.h"
#include "sample_log.h"
#include "ui_mainwindow.h"
#include <QCloseEvent>
#include <QStandardItemModel>
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
namespace
{
constexpr bool kChannel1UiVisible = false;
class LogHighlighter final : public QSyntaxHighlighter
{
public:
explicit LogHighlighter(QTextDocument *document) : QSyntaxHighlighter(document)
{
error_.setForeground(QColor(200, 0, 0)); error_.setFontWeight(QFont::Bold);
recovery_.setForeground(QColor(0, 128, 0)); recovery_.setFontWeight(QFont::Bold);
warning_.setForeground(QColor(190, 110, 0)); warning_.setFontWeight(QFont::Bold);
}
protected:
void highlightBlock(const QString &text) override
{
if (text.contains(QStringLiteral("VIDEO_INPUT_UNPLUG")) ||
text.contains(QStringLiteral("No signal"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("Video Undetected"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("failed"), Qt::CaseInsensitive) ||
text.contains(QStringLiteral("error"), Qt::CaseInsensitive))
setFormat(0, text.size(), error_);
else if (text.contains(QStringLiteral("warning"), Qt::CaseInsensitive))
setFormat(0, text.size(), warning_);
else if (text.contains(QStringLiteral("VIDEO_INPUT_PLUGIN")) ||
text.contains(QStringLiteral("recovered"), Qt::CaseInsensitive))
setFormat(0, text.size(), recovery_);
}
private:
QTextCharFormat error_, recovery_, warning_;
};
}
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent), ui_(new Ui::MainWindow), controller_(new CaptureController(this)),
log_(new SampleLog(this))
{
ui_->setupUi(this);
#if GVFG_INTERNAL_DIAGNOSTICS
setWindowTitle(QStringLiteral("GVFG Internal Diagnostic - APP v%1")
.arg(QStringLiteral(GVFG_SAMPLE_VERSION)));
#else
setWindowTitle(QStringLiteral("GVFG Preview Sample - APP v%1")
.arg(QStringLiteral(GVFG_SAMPLE_VERSION)));
#endif
ui_->logEdit->setMaximumBlockCount(300);
new LogHighlighter(ui_->logEdit->document());
ui_->statusLabel->setWordWrap(true);
for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel)
{
previewWindows_[channel] = new PreviewWindow();
previewWindows_[channel]->setWindowTitle(QStringLiteral("GVFG Preview - CH%1").arg(channel));
controller_->setPreviewTarget(channel, previewWindows_[channel]->nativePreviewHandle());
connect(previewWindows_[channel], &PreviewWindow::previewVisibilityChanged,
this, [this, channel](bool visible) { controller_->setPreviewVisible(channel, visible); });
}
controller_->setChannelStatusVisible(GVFG_CHANNEL_1, kChannel1UiVisible);
connect(controller_, &CaptureController::devicesChanged, this, [this](const QStringList &names) {
ui_->deviceCombo->clear();
if (names.isEmpty()) ui_->deviceCombo->addItem(QStringLiteral("No GVFG device found"), -1);
else for (int i = 0; i < names.size(); ++i) ui_->deviceCombo->addItem(names.at(i), i);
updateUiState();
});
connect(controller_, &CaptureController::stateChanged, this, &MainWindow::updateUiState);
connect(controller_, &CaptureController::statusChanged, ui_->statusLabel, &QLabel::setText);
connect(controller_, &CaptureController::sdiInfoChanged, ui_->sdiInfoLabel, &QLabel::setText);
connect(controller_, &CaptureController::logMessage, log_, &SampleLog::append, Qt::QueuedConnection);
#if GVFG_INTERNAL_DIAGNOSTICS
connect(controller_, &CaptureController::diagnosticMessage, log_, &SampleLog::appendDiagnostic,
Qt::QueuedConnection);
#endif
connect(log_, &SampleLog::lineReady, this, &MainWindow::appendLogLine);
connect(controller_, &CaptureController::previewSourceSizeChanged, this,
[this](int channel, int width, int height) {
if (width > 0 && height > 0) previewWindows_[channel]->setSourceSize(width, height);
});
connect(controller_, &CaptureController::previewShowRequested, this,
[this](int channel) {
previewWindows_[channel]->showPreview();
controller_->setPreviewTarget(channel, previewWindows_[channel]->nativePreviewHandle());
});
connect(controller_, &CaptureController::previewCloseRequested, this,
[this](int channel) { previewWindows_[channel]->closePreview(); });
connect(ui_->refreshButton, &QPushButton::clicked, controller_, &CaptureController::refreshDevices);
connect(ui_->deviceCombo, &QComboBox::currentIndexChanged, this, [this](int) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
if (controller_->deviceOpen())
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
updateUiState();
});
connect(ui_->ch0StartButton, &QPushButton::clicked, this, [this] { syncControllerOptions(0); controller_->startCapture(0); });
connect(ui_->ch1StartButton, &QPushButton::clicked, this, [this] { syncControllerOptions(1); controller_->startCapture(1); });
connect(ui_->ch0StopButton, &QPushButton::clicked, controller_, [this] { controller_->stopCapture(0); });
connect(ui_->ch1StopButton, &QPushButton::clicked, controller_, [this] { controller_->stopCapture(1); });
connect(ui_->ch0PreviewButton, &QPushButton::clicked, this, [this] { showPreviewWindow(0, false); });
connect(ui_->ch1PreviewButton, &QPushButton::clicked, this, [this] { showPreviewWindow(1, false); });
connect(ui_->ch0FullscreenButton, &QPushButton::clicked, this, [this] { showPreviewWindow(0, true); });
connect(ui_->ch1FullscreenButton, &QPushButton::clicked, this, [this] { showPreviewWindow(1, true); });
auto formatChanged = [this](int channel) {
updateOutputFormatOptions(channel);
syncControllerOptions(channel);
};
connect(ui_->ch0OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(0); });
connect(ui_->ch1OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(1); });
connect(ui_->ch0ZeroCopyCheckBox, &QCheckBox::toggled, this, [this](bool) {
syncControllerOptions(GVFG_CHANNEL_0);
if (controller_->deviceOpen()) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
}
});
connect(ui_->ch1ZeroCopyCheckBox, &QCheckBox::toggled, this, [this](bool) {
syncControllerOptions(GVFG_CHANNEL_1);
if (controller_->deviceOpen()) {
const int selectedDevice = ui_->deviceCombo->currentData().toInt();
controller_->closeDevice();
controller_->setSelectedDeviceIndex(selectedDevice);
}
});
updateOutputFormatOptions();
updateUiState();
log_->append(QStringLiteral("= GVFG Internal Sample startup ="));
log_->append(QStringLiteral("APP: v%1").arg(QStringLiteral(GVFG_SAMPLE_VERSION)));
log_->append(QStringLiteral("SDK: v%1").arg(controller_->sdkVersion()));
log_->append(QStringLiteral("GigaLib: v%1").arg(controller_->gigabyteLibVersion()));
log_->append(QStringLiteral("Diagnostics: %1")
#if GVFG_INTERNAL_DIAGNOSTICS
.arg(QStringLiteral("enabled")));
#else
.arg(QStringLiteral("disabled")));
#endif
log_->append(QStringLiteral("================================"));
log_->append(log_->fileAvailable()
? QStringLiteral("Log file | %1").arg(log_->filePath())
: QStringLiteral("Log file unavailable | %1").arg(log_->filePath()));
controller_->refreshDevices();
}
MainWindow::~MainWindow()
{
controller_->closeDevice();
QObject::disconnect(controller_, nullptr, nullptr, nullptr);
delete controller_;
controller_ = nullptr;
delete previewWindows_[0];
delete previewWindows_[1];
delete ui_;
}
QWidget *createMainWindow() { return new MainWindow(); }
void MainWindow::closeEvent(QCloseEvent *event)
{
controller_->closeDevice();
for (PreviewWindow *window : previewWindows_) if (window) window->closePreview();
QWidget::closeEvent(event);
}
void MainWindow::syncControllerOptions(int channel)
{
const bool zeroCopy = channel == 0 ? ui_->ch0ZeroCopyCheckBox->isChecked() : ui_->ch1ZeroCopyCheckBox->isChecked();
const int formatIndex = channel == 0 ? ui_->ch0OutputFormatCombo->currentIndex() : ui_->ch1OutputFormatCombo->currentIndex();
const bool audio = channel == 0 && ui_->ch0AudioCheckBox->isChecked();
controller_->setChannelOptions(channel, zeroCopy,
formatIndex == 1 ? GVFG_PIXFMT_Y210 : GVFG_PIXFMT_YUY2, audio);
}
void MainWindow::showPreviewWindow(int channel, bool fullscreen)
{
if (!controller_->channelRunning(channel) || !controller_->frameAvailable(channel)) return;
gvfg_signal_status_t signal{};
if (controller_->cachedSignalStatus(channel, &signal) && signal.width > 0 && signal.height > 0)
previewWindows_[channel]->setSourceSize(signal.width, signal.height);
if (fullscreen) previewWindows_[channel]->showFullscreenPreview();
else previewWindows_[channel]->showPreview();
controller_->setPreviewTarget(channel, previewWindows_[channel]->nativePreviewHandle());
if (!controller_->applyPreview(channel))
log_->append(
fullscreen
? QStringLiteral("CH%1 [APP] Fullscreen preview failed | window update").arg(channel)
: QStringLiteral("CH%1 [APP] Show preview failed | window update").arg(channel));
}
void MainWindow::updateOutputFormatOptions(int changedChannel)
{
QComboBox *combos[] = {ui_->ch0OutputFormatCombo, ui_->ch1OutputFormatCombo};
constexpr int y210 = 1;
if ((changedChannel == 0 || changedChannel == 1) && combos[changedChannel]->currentIndex() == y210)
{
const int other = changedChannel == 0 ? 1 : 0;
if (combos[other]->currentIndex() == y210) combos[other]->setCurrentIndex(0);
}
const bool enabled[] = {combos[1]->currentIndex() != y210, combos[0]->currentIndex() != y210};
for (int channel = 0; channel < 2; ++channel)
{
auto *model = qobject_cast<QStandardItemModel *>(combos[channel]->model());
if (model && model->item(y210)) model->item(y210)->setEnabled(enabled[channel]);
combos[channel]->setToolTip(
enabled[channel]
? QStringLiteral("Requested CH%1 capture output format").arg(channel)
: QStringLiteral("Y210 is already selected by the other channel"));
}
}
void MainWindow::updateUiState()
{
const bool running[] = {controller_->channelRunning(0), controller_->channelRunning(1)};
const bool anyRunning = running[0] || running[1];
const bool selected = ui_->deviceCombo->currentData().toInt() >= 0;
ui_->refreshButton->setEnabled(!anyRunning); ui_->deviceCombo->setEnabled(!anyRunning);
ui_->ch0StartButton->setEnabled(selected && !running[0]); ui_->ch1StartButton->setEnabled(selected && !running[1]);
ui_->ch0StopButton->setEnabled(running[0]); ui_->ch1StopButton->setEnabled(running[1]);
ui_->ch0PreviewButton->setEnabled(running[0] && controller_->frameAvailable(0));
ui_->ch1PreviewButton->setEnabled(running[1] && controller_->frameAvailable(1));
ui_->ch0FullscreenButton->setEnabled(ui_->ch0PreviewButton->isEnabled());
ui_->ch1FullscreenButton->setEnabled(ui_->ch1PreviewButton->isEnabled());
ui_->ch0OutputFormatCombo->setEnabled(!running[0]); ui_->ch1OutputFormatCombo->setEnabled(!running[1]);
ui_->ch0ZeroCopyCheckBox->setEnabled(!anyRunning);
ui_->ch1ZeroCopyCheckBox->setEnabled(!anyRunning);
ui_->ch0AudioCheckBox->setEnabled(!running[0]);
ui_->channel1GroupBox->setVisible(kChannel1UiVisible);
}
void MainWindow::appendLogLine(const QString &line) { ui_->logEdit->appendPlainText(line); }
-41
View File
@@ -1,41 +0,0 @@
#pragma once
#include <gvfg_capture.h>
#include <QWidget>
#include <array>
class CaptureController;
class QCloseEvent;
class PreviewWindow;
class SampleLog;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow final : public QWidget
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
protected:
void closeEvent(QCloseEvent *event) override;
private:
void syncControllerOptions(int channel);
void showPreviewWindow(int channel, bool fullscreen);
void updateOutputFormatOptions(int changedChannel = -1);
void updateUiState();
void appendLogLine(const QString &line);
Ui::MainWindow *ui_ = nullptr;
CaptureController *controller_ = nullptr;
SampleLog *log_ = nullptr;
std::array<PreviewWindow *, 2> previewWindows_{};
};
QWidget *createMainWindow();
-243
View File
@@ -1,243 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QWidget" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>960</width>
<height>640</height>
</rect>
</property>
<property name="windowTitle">
<string>GVFG Qt Preview Sample</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<layout class="QHBoxLayout" name="topLayout">
<item>
<widget class="QLabel" name="deviceLabel">
<property name="minimumSize">
<size>
<width>86</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>86</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Device:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="deviceCombo"/>
</item>
<item>
<widget class="QPushButton" name="refreshButton">
<property name="text">
<string>Refresh</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="sdiInfoLabel">
<property name="text">
<string>SDI Info: --</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="2" column="0">
<layout class="QHBoxLayout" name="channelPanelsLayout" stretch="1,1">
<item>
<widget class="QGroupBox" name="channel0GroupBox">
<property name="title">
<string>CH0</string>
</property>
<layout class="QGridLayout" name="channel0GridLayout">
<item row="0" column="0">
<widget class="QLabel" name="channel0FormatLabel">
<property name="text"><string>Output format:</string></property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="ch0OutputFormatCombo">
<property name="toolTip"><string>GigabyteLib extension: requested CH0 output format</string></property>
<item><property name="text"><string>YUY2 (8-bit 4:2:2)</string></property></item>
<item><property name="text"><string>Y210 (10-bit 4:2:2)</string></property></item>
</widget>
</item>
<item row="0" column="2">
<widget class="QCheckBox" name="ch0ZeroCopyCheckBox">
<property name="toolTip">
<string>Must be selected before opening CH0</string>
</property>
<property name="text">
<string>Zero-copy</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QCheckBox" name="ch0AudioCheckBox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="toolTip">
<string>Capture and play CH0 PCM audio together with video</string>
</property>
<property name="text">
<string>Audio</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0" colspan="4">
<layout class="QHBoxLayout" name="channel0ButtonLayout">
<item>
<widget class="QPushButton" name="ch0StartButton">
<property name="text">
<string>Start</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch0StopButton">
<property name="text">
<string>Stop</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch0PreviewButton">
<property name="text">
<string>Open view</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch0FullscreenButton">
<property name="text">
<string>Fullscreen</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="channel1GroupBox">
<property name="title">
<string>CH1</string>
</property>
<layout class="QGridLayout" name="channel1GridLayout">
<item row="0" column="0">
<widget class="QLabel" name="channel1FormatLabel">
<property name="text"><string>Output format:</string></property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="ch1OutputFormatCombo">
<property name="enabled"><bool>false</bool></property>
<property name="toolTip"><string>GigabyteLib extension: requested CH1 output format</string></property>
<item><property name="text"><string>YUY2 (8-bit 4:2:2)</string></property></item>
<item><property name="text"><string>Y210 (10-bit 4:2:2)</string></property></item>
</widget>
</item>
<item row="0" column="2">
<widget class="QCheckBox" name="ch1ZeroCopyCheckBox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Must be selected before opening CH1</string>
</property>
<property name="text">
<string>Zero-copy</string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="3">
<layout class="QHBoxLayout" name="channel1ButtonLayout">
<item>
<widget class="QPushButton" name="ch1StartButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Start</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch1StopButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Stop</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch1PreviewButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Open view</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ch1FullscreenButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Fullscreen</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
</item>
<item row="3" column="0">
<widget class="QLabel" name="statusLabel">
<property name="text">
<string>Idle</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QPlainTextEdit" name="logEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
-148
View File
@@ -1,148 +0,0 @@
#include "previewwindow.h"
#include "ui_previewwindow.h"
#include <QGuiApplication>
#include <QCloseEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QScreen>
#include <QSize>
#include <algorithm>
PreviewWindow::PreviewWindow(QWidget *parent)
: QWidget(parent), ui_(new Ui::PreviewWindow)
{
ui_->setupUi(this);
ui_->verticalLayout->setContentsMargins(0, 0, 0, 0);
ui_->verticalLayout->setSpacing(0);
ui_->previewHost->setAttribute(Qt::WA_NativeWindow, true);
ui_->previewHost->setStyleSheet(QStringLiteral("background: black;"));
}
PreviewWindow::~PreviewWindow()
{
delete ui_;
}
void *PreviewWindow::nativePreviewHandle() const
{
return reinterpret_cast<void *>(ui_->previewHost->winId());
}
void PreviewWindow::setSourceSize(int sourceWidth, int sourceHeight)
{
if (sourceWidth <= 0 || sourceHeight <= 0)
return;
if (sourceWidth_ == sourceWidth && sourceHeight_ == sourceHeight && isVisible())
return;
sourceWidth_ = sourceWidth;
sourceHeight_ = sourceHeight;
if (isFullScreen())
return;
QScreen *targetScreen = screen();
if (!targetScreen)
targetScreen = QGuiApplication::primaryScreen();
ui_->previewHost->setMinimumSize(QSize(1, 1));
ui_->previewHost->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
const QSize currentHostSize = ui_->previewHost->size();
const QSize windowOverhead = size() - currentHostSize;
QSize targetSize(sourceWidth, sourceHeight);
if (targetScreen)
{
const QSize maxSize = targetScreen->availableGeometry().size() - windowOverhead - QSize(16, 48);
const QSize boundedSize(std::max(320, maxSize.width()), std::max(180, maxSize.height()));
if (targetSize.width() > boundedSize.width() || targetSize.height() > boundedSize.height())
targetSize.scale(boundedSize, Qt::KeepAspectRatio);
}
resize(targetSize + windowOverhead);
}
void PreviewWindow::closePreview()
{
closeAllowed_ = true;
emit previewVisibilityChanged(false);
close();
}
void PreviewWindow::showPreview(int sourceWidth, int sourceHeight)
{
closeAllowed_ = false;
setSourceSize(sourceWidth, sourceHeight);
if (isFullScreen())
showNormal();
show();
emit previewVisibilityChanged(true);
raise();
activateWindow();
}
void PreviewWindow::showFullscreenPreview(int sourceWidth, int sourceHeight)
{
closeAllowed_ = false;
setSourceSize(sourceWidth, sourceHeight);
enterFullscreen();
emit previewVisibilityChanged(true);
}
void PreviewWindow::enterFullscreen()
{
showFullScreen();
raise();
activateWindow();
}
void PreviewWindow::exitFullscreen()
{
if (!isFullScreen())
return;
showNormal();
raise();
activateWindow();
}
void PreviewWindow::closeEvent(QCloseEvent *event)
{
if (closeAllowed_)
{
event->accept();
return;
}
hide();
emit previewVisibilityChanged(false);
event->ignore();
}
void PreviewWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape && isFullScreen())
{
exitFullscreen();
event->accept();
return;
}
if (event->key() == Qt::Key_F11)
{
isFullScreen() ? exitFullscreen() : enterFullscreen();
event->accept();
return;
}
QWidget::keyPressEvent(event);
}
void PreviewWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
isFullScreen() ? exitFullscreen() : enterFullscreen();
event->accept();
}
-47
View File
@@ -1,47 +0,0 @@
#pragma once
#include <QWidget>
class QKeyEvent;
class QMouseEvent;
QT_BEGIN_NAMESPACE
namespace Ui
{
class PreviewWindow;
}
QT_END_NAMESPACE
class PreviewWindow final : public QWidget
{
Q_OBJECT
public:
explicit PreviewWindow(QWidget *parent = nullptr);
~PreviewWindow() override;
void *nativePreviewHandle() const;
void setSourceSize(int sourceWidth, int sourceHeight);
void closePreview();
public slots:
void showPreview(int sourceWidth = 0, int sourceHeight = 0);
void showFullscreenPreview(int sourceWidth = 0, int sourceHeight = 0);
signals:
void previewVisibilityChanged(bool visible);
protected:
void closeEvent(QCloseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
private:
void enterFullscreen();
void exitFullscreen();
Ui::PreviewWindow *ui_ = nullptr;
bool closeAllowed_ = false;
int sourceWidth_ = 0;
int sourceHeight_ = 0;
};
-31
View File
@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PreviewWindow</class>
<widget class="QWidget" name="PreviewWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>960</width>
<height>540</height>
</rect>
</property>
<property name="windowTitle">
<string>GVFG Preview</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QWidget" name="previewHost" native="true">
<property name="minimumSize">
<size>
<width>640</width>
<height>360</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
-78
View File
@@ -1,78 +0,0 @@
#include "sample_log.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QStringList>
namespace
{
QString filePrefix()
{
#if GVFG_INTERNAL_DIAGNOSTICS
return QStringLiteral("gvfg_qt_preview_debug");
#else
return QStringLiteral("gvfg_qt_preview");
#endif
}
}
SampleLog::SampleLog(QObject *parent) : QObject(parent)
{
sessionStamp_ = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss"));
directoryPath_ = QCoreApplication::applicationDirPath() + QStringLiteral("/logs");
if (QDir().mkpath(directoryPath_)) openPart();
else filePath_ = directoryPath_;
}
void SampleLog::append(const QString &message)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = message.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
{
const QString line = QStringLiteral("[%1] %2%3")
.arg(timestamp, i == 0 ? QString() : QStringLiteral(" "), lines.at(i));
writeLine(line);
emit lineReady(line);
}
}
void SampleLog::appendDiagnostic(const QString &message)
{
const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz"));
const QStringList lines = message.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size(); ++i)
writeLine(QStringLiteral("[%1] %2%3").arg(
timestamp, i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "), lines.at(i)));
}
bool SampleLog::openPart()
{
if (file_.isOpen()) file_.close();
filePath_ = QStringLiteral("%1/%2_%3_part%4.log")
.arg(directoryPath_, filePrefix(), sessionStamp_).arg(partIndex_, 2, 10, QLatin1Char('0'));
file_.setFileName(filePath_);
if (!file_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) return false;
file_.write(QStringLiteral("\n==== %1 session %2 part %3 ====\n")
.arg(filePrefix(), QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz")))
.arg(partIndex_).toUtf8());
file_.flush();
return true;
}
void SampleLog::writeLine(const QString &line)
{
if (!file_.isOpen()) return;
if (file_.size() >= kMaxFileBytes)
{
file_.write(QStringLiteral("==== log rotated at %1 ====\n")
.arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))).toUtf8());
file_.flush();
++partIndex_;
if (!openPart()) return;
}
file_.write(line.toUtf8());
file_.write("\n");
file_.flush();
}
-30
View File
@@ -1,30 +0,0 @@
#pragma once
#include <QFile>
#include <QObject>
#include <QString>
class SampleLog final : public QObject
{
Q_OBJECT
public:
explicit SampleLog(QObject *parent = nullptr);
QString filePath() const { return filePath_; }
bool fileAvailable() const { return file_.isOpen(); }
public slots:
void append(const QString &message);
void appendDiagnostic(const QString &message);
signals:
void lineReady(const QString &line);
private:
bool openPart();
void writeLine(const QString &line);
static constexpr qint64 kMaxFileBytes = 20ll * 1024ll * 1024ll;
QFile file_;
QString directoryPath_, filePath_, sessionStamp_;
int partIndex_ = 1;
};
+9 -7
View File
@@ -1,6 +1,7 @@
# GVFG Standalone SDK
這個 repository 將 GVFG SDK 與 Qt Sample 分成兩個獨立 CMake project。
這個 repository 維護 GVFG SDK。Customer 與 Internal Qt Sample 位於各自的
Git worktree,不在這個 repository 內重複維護 Sample source。
這個 repo 以 GVFG 為 source of truth。其他專案應該透過 public header、
import library、runtime DLL 來使用 GVFG,不要直接把 GVFG source 編進去。
@@ -13,7 +14,8 @@ done-index 與舊 SDK frame-ring 流程不在相容範圍內。
## 內容
- `GVFG_SDK`:獨立 SDK project,使用內嵌的 `GvfgSdk.lib` 建立 `gvfg.dll` 與選用的 `gvfg_preview.dll`。
- `GVFG_Qt_Sample`:獨立 Qt APP project,只連結預先建好的 SDK,不會編譯 SDK source。
- `../Costomer_SDK_Release/GVFG_Customer_Sample`:乾淨的 Customer Sample worktree。
- `../GVFG_Internal_Sample`:包含完整診斷 log 的 Internal Sample worktree。
- `docs`:API 與整合說明。
Qt Sample 的 source boundary:
@@ -29,8 +31,8 @@ Qt Sample 的 source boundary:
## Build
先使用 MSVC 建立 SDK,再使用需要的 Qt kit 建立 Sample。兩個 project
使用不同 build directory,切換 Qt compiler 不會重新編譯 SDK source。
先使用 MSVC 建立 SDK,再到需要的 Sample worktree 使用 Qt kit 建立 Sample。
SDK 與 Sample 使用不同 build directory,切換 Qt compiler 不會重新編譯 SDK source。
SDK build 會保留 MSVC `.lib`,並在找到 MinGW `dlltool` 時從固定的
DLL export 清單同步產生 MinGW `.dll.a`;兩種上層共用同一組 MSVC DLL。
@@ -40,10 +42,10 @@ DLL export 清單同步產生 MinGW `.dll.a`;兩種上層共用同一組 MSVC
cmake -S GVFG_SDK -B GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release
cmake --build GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release --config Release
cmake -S GVFG_Qt_Sample -B GVFG_Qt_Sample/build-release ^
cmake -S ..\GVFG_Internal_Sample -B ..\GVFG_Internal_Sample\build\Internal_MSVC2022_64bit-Debug ^
-DCMAKE_PREFIX_PATH=C:\Qt\6.10.2\msvc2022_64 ^
-DGVFG_SDK_RELEASE_DIR=%CD%\GVFG_SDK\build\Desktop_Qt_6_10_2_MSVC2022_64bit-Release
cmake --build GVFG_Qt_Sample/build-release --config Release
cmake --build ..\GVFG_Internal_Sample\build\Internal_MSVC2022_64bit-Debug
```
Qt Sample 只從一個固定的 `GVFG_SDK_RELEASE_DIR` 找 DLL 與對應 compiler
@@ -68,7 +70,7 @@ GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release/lib/gvfg.lib
GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release/lib/gvfg_preview.lib
GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release/lib/libgvfg.dll.a
GVFG_SDK/build/Desktop_Qt_6_10_2_MSVC2022_64bit-Release/lib/libgvfg_preview.dll.a
GVFG_Qt_Sample/build-release/bin/gvfg_qt_preview.exe
../GVFG_Internal_Sample/build/Internal_MSVC2022_64bit-Debug/bin/gvfg_qt_preview.exe
```
MSVC 上層連結 `gvfg.lib` 與 `gvfg_preview.lib`;MinGW 上層連結
+1 -1
View File
@@ -5,7 +5,7 @@ set "PROJECT_DIR=%~dp0"
set "PROJECT_DIR=%PROJECT_DIR:~0,-1%"
if not defined SDK_SOURCE_BIN set "SDK_SOURCE_BIN=%PROJECT_DIR%\GVFG_SDK\build\Desktop_Qt_6_10_2_MSVC2022_64bit-Release\bin"
if not defined SAMPLE_SOURCE_BIN set "SAMPLE_SOURCE_BIN=%PROJECT_DIR%\GVFG_Qt_Sample\build\Desktop_Qt_6_10_2_MSVC2022_64bit-Debug\bin"
if not defined SAMPLE_SOURCE_BIN set "SAMPLE_SOURCE_BIN=%PROJECT_DIR%\..\GVFG_Internal_Sample\build\Internal_MSVC2022_64bit-Debug\bin"
if not defined QT_BIN set "QT_BIN=C:\Qt\6.10.2\msvc2022_64\bin"
if not defined VSDEVCMD set "VSDEVCMD=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat"