From 57ad00c40e9dcb678c2495aa0573ec43c9ce6602 Mon Sep 17 00:00:00 2001 From: "Mark.lin" Date: Fri, 11 Sep 2026 16:02:55 +0800 Subject: [PATCH] Separate Qt capture control from the UI Compared with 1214e72: - Move device discovery, channel lifecycle, signal monitoring, frame delivery, preview submission, runtime logging, and shutdown coordination from MainWindow into a dedicated CaptureController. - Add a GvfgClient RAII wrapper and gvfg_api namespace so one application module owns all direct calls to the public capture and preview C APIs. - Keep MainWindow focused on widget creation, user actions, option synchronization, preview-window presentation, and UI state updates through controller signals. - Preserve per-channel video workers, exact frame release handling, preview delivery accounting, startup timing, signal recovery, and diagnostic reporting while removing their implementation details from the UI class. - Preserve the audio read-copy-release path, bounded playback queue, playback-thread QAudioSink ownership, recovery behavior, and byte/frame accounting inside the controller. - Register the new source files in the standalone Qt sample target and document the resulting UI, capture-control, and API-adapter source boundaries. Validation: git diff --cached --check passed before commit. No build, runtime launch, capture, audio playback, device-event, shutdown, or hardware validation was run. --- GVFG_Qt_Sample/CMakeLists.txt | 4 + GVFG_Qt_Sample/capture_controller.cpp | 1390 ++++++++++++++++++++ GVFG_Qt_Sample/capture_controller.h | 136 ++ GVFG_Qt_Sample/gvfg_api.cpp | 47 + GVFG_Qt_Sample/gvfg_api.h | 59 + GVFG_Qt_Sample/mainwindow.cpp | 1679 ++----------------------- GVFG_Qt_Sample/mainwindow.h | 124 +- README.md | 6 + 8 files changed, 1776 insertions(+), 1669 deletions(-) create mode 100644 GVFG_Qt_Sample/capture_controller.cpp create mode 100644 GVFG_Qt_Sample/capture_controller.h create mode 100644 GVFG_Qt_Sample/gvfg_api.cpp create mode 100644 GVFG_Qt_Sample/gvfg_api.h diff --git a/GVFG_Qt_Sample/CMakeLists.txt b/GVFG_Qt_Sample/CMakeLists.txt index d388948..cb06dc9 100644 --- a/GVFG_Qt_Sample/CMakeLists.txt +++ b/GVFG_Qt_Sample/CMakeLists.txt @@ -95,6 +95,10 @@ find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Multimedia) set(GVFG_QT_PREVIEW_SOURCES main.cpp + capture_controller.cpp + capture_controller.h + gvfg_api.cpp + gvfg_api.h mainwindow.cpp mainwindow.h mainwindow.ui diff --git a/GVFG_Qt_Sample/capture_controller.cpp b/GVFG_Qt_Sample/capture_controller.cpp new file mode 100644 index 0000000..c5e5b5d --- /dev/null +++ b/GVFG_Qt_Sample/capture_controller.cpp @@ -0,0 +1,1390 @@ +#include "capture_controller.h" +#include "gvfg_api.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +namespace +{ + constexpr size_t kMaxQueuedAudioFrames = 10; + + QString logFilePrefix() + { +#if GVFG_INTERNAL_DIAGNOSTICS + return QStringLiteral("gvfg_qt_preview_debug"); +#else + return QStringLiteral("gvfg_qt_preview"); +#endif + } + +#if GVFG_INTERNAL_DIAGNOSTICS + QString boolText(int value) { return value ? QStringLiteral("yes") : QStringLiteral("no"); } + QString valueOrDash(uint64_t value) { return QString::number(static_cast(value)); } + + QString captureStatusText(const gvfg_debug_backend_stats_t &stats, bool signalConnected) + { + if (!stats.backend_running) return QStringLiteral("stopped"); + if (!signalConnected) return QStringLiteral("waiting_signal"); + if (!stats.backend_capture_active) return QStringLiteral("paused"); + return QStringLiteral("streaming"); + } +#endif + + QString frameText(bool valid, int width, int height, const char *pixelFormat, int bitDepth) + { + if (!valid || width <= 0 || height <= 0) return QStringLiteral("--"); + const QString format = pixelFormat && pixelFormat[0] != '\0' + ? QString::fromUtf8(pixelFormat) : QStringLiteral("--"); + const QString bit = bitDepth > 0 ? QString::number(bitDepth) : QStringLiteral("--"); + return QStringLiteral("%1x%2 %3 %4-bit").arg(width).arg(height).arg(format, bit); + } + + QString signalFrameText(const gvfg_signal_status_t &signal) + { + if (!signal.connected) return QStringLiteral("No signal"); + const QString resolution = signal.width > 0 && signal.height > 0 + ? QStringLiteral("%1x%2").arg(signal.width).arg(signal.height) + : QStringLiteral("--"); + const QString format = signal.pixel_format != GVFG_PIXFMT_UNKNOWN + ? QString::fromLatin1(gvfg_api::pixelFormatName(signal.pixel_format)) + : QStringLiteral("--"); + const QString bit = signal.bit_depth > 0 ? QString::number(signal.bit_depth) : QStringLiteral("--"); + return QStringLiteral("%1 %2 %3-bit").arg(resolution, format, bit); + } + + QString eventTypeText(gvfg_event_type_t type) + { + switch (type) + { + case GVFG_EVENT_SIGNAL_CONNECTED: return QStringLiteral("SIGNAL_CONNECTED"); + case GVFG_EVENT_SIGNAL_DISCONNECTED: return QStringLiteral("SIGNAL_DISCONNECTED"); + case GVFG_EVENT_STREAM_READY: return QStringLiteral("STREAM_READY"); + case GVFG_EVENT_FORMAT_CHANGE_BEGIN: return QStringLiteral("FORMAT_CHANGE_BEGIN"); + default: return QStringLiteral("UNKNOWN"); + } + } +} +CaptureController::CaptureController(QObject *parent) : QObject(parent) +{ + runtimeStatusTimer_ = new QTimer(this); + runtimeStatusTimer_->setInterval(200); + connect(runtimeStatusTimer_, &QTimer::timeout, this, [this] { + processPendingEvents(); + updateSignalStatus(false); + }); + openLogFile(); +} + +CaptureController::~CaptureController() +{ + closeDevice(); +} + +void CaptureController::setChannelOptions(int channel, bool zeroCopy, + gvfg_pixel_format_t format, bool audioEnabled) +{ + if (channel < GVFG_CHANNEL_0 || channel > GVFG_CHANNEL_1) + return; + channels_[channel].zeroCopy = zeroCopy; + channels_[channel].requestedFormat = format; + channels_[channel].requestedAudio = channel == GVFG_CHANNEL_0 && audioEnabled; +} + +void CaptureController::setPreviewTarget(int channel, void *nativeWindow) +{ + if (channel >= GVFG_CHANNEL_0 && channel <= GVFG_CHANNEL_1) + channels_[channel].previewTarget = nativeWindow; +} + +void CaptureController::setPreviewVisible(int channel, bool visible) +{ + if (channel >= GVFG_CHANNEL_0 && channel <= GVFG_CHANNEL_1) + channels_[channel].previewVisible.store(visible, std::memory_order_release); +} + +bool CaptureController::channelOpened(int channel) const +{ + return channel >= GVFG_CHANNEL_0 && channel <= GVFG_CHANNEL_1 && channels_[channel].opened; +} + +bool CaptureController::channelRunning(int channel) const +{ + return channel >= GVFG_CHANNEL_0 && channel <= GVFG_CHANNEL_1 && + channels_[channel].running.load(std::memory_order_acquire); +} + +bool CaptureController::frameAvailable(int channel) const +{ + return channel >= GVFG_CHANNEL_0 && channel <= GVFG_CHANNEL_1 && + channels_[channel].frameAvailable.load(std::memory_order_acquire); +} + +bool CaptureController::cachedSignalStatus(int channel, gvfg_signal_status_t *status) const +{ + if (!status || channel < GVFG_CHANNEL_0 || channel > GVFG_CHANNEL_1 || + !channels_[channel].haveCachedSignalStatus) + return false; + *status = channels_[channel].cachedSignalStatus; + return true; +} + +QString CaptureController::sdkVersion() const +{ + return QString::fromLatin1(gvfg_api::version()); +} + +void CaptureController::refreshDevices() +{ + if (client_.valid()) + closeDevice(); + + devices_ = {}; + + const int count = gvfg_api::enumerateDevices(devices_.data(), GVFG_MAX_DEVICES); + deviceCount_ = count > 0 ? count : 0; + + QStringList names; + for (int i = 0; i < deviceCount_; ++i) + { + const QString name = QString::fromUtf8(devices_[i].name); + const QString displayName = name.isEmpty() ? QStringLiteral("GVFG Capture") : name; + names.push_back(displayName); + } + + if (deviceCount_ <= 0) + { + appendLog(QStringLiteral("No GVFG device found")); + } + else + { + appendLog(QStringLiteral("Found %1 GVFG capture device(s)").arg(deviceCount_)); + } + emit devicesChanged(names); +} + +bool CaptureController::openDevice() +{ + if (client_.valid()) + return true; + + if (selectedDeviceIndex_ < 0) + { + appendLog(QStringLiteral("Open skipped: no device selected")); + return false; + } + + gvfg_status_t st = client_.create(); + if (st != GVFG_OK || !client_.valid()) + { + reportError(QStringLiteral("gvfg_create"), st); + emit stateChanged(); + return false; + } + + lastSignalStatusText_.clear(); + appendLog(QStringLiteral("Created device session for index %1").arg(selectedDeviceIndex_)); + runtimeStatusTimer_->start(); + updateSignalStatus(false); + emit stateChanged(); + return true; +} + +bool CaptureController::openChannel(int channel) +{ + ChannelRuntime &runtime = channels_[channel]; + if (runtime.opened) + return applyOutputFormat(channel); + if (!client_.valid() && !openDevice()) + return false; + + const bool zeroCopyEnabled = runtime.zeroCopy; + gvfg_status_t status = client_.setZeroCopy(channel, zeroCopyEnabled ? 1 : 0); + if (status != GVFG_OK) + { + reportError(QStringLiteral("gvfg_set_channel_zero_copy_enabled"), status, channel); + return false; + } + status = client_.openChannel( selectedDeviceIndex_, channel); + if (status != GVFG_OK) + { + reportError(QStringLiteral("gvfg_open_channel"), status, channel); + return false; + } + runtime.opened = true; + if (!applyOutputFormat(channel)) + return false; + + appendLog(QStringLiteral("Opened device index %1 CH%2 | mode=%3") + .arg(selectedDeviceIndex_) + .arg(channel) + .arg(zeroCopyEnabled ? QStringLiteral("zero-copy") : QStringLiteral("copy"))); + updateSignalStatus(); + return true; +} + +void CaptureController::closeDevice() +{ + if (runtimeStatusTimer_) + runtimeStatusTimer_->stop(); + + stopAllCaptures(); + for (ChannelRuntime &channel : channels_) + { + if (channel.previewHandle) + { + gvfg_api::previewDestroy(channel.previewHandle); + channel.previewHandle = nullptr; + } + } + + if (client_.valid()) + { + client_.destroy(); + appendLog(QStringLiteral("Closed device")); + } + + emit statusChanged(QStringLiteral("Idle")); + lastSignalStatusText_.clear(); + selectedDeviceIndex_ = -1; + for (ChannelRuntime &channel : channels_) + { + channel.opened = false; + channel.cachedSignalStatus = {}; + channel.haveCachedSignalStatus = false; + channel.lastLoggedInputStatus.clear(); + } + emit stateChanged(); +} + +bool CaptureController::applyOutputFormat(int channel) +{ + if (!client_.valid() || !channels_[channel].opened || + channels_[channel].running.load(std::memory_order_acquire)) + return false; + + const gvfg_pixel_format_t format = channels_[channel].requestedFormat; + const gvfg_status_t status = client_.setVideoFormat( channel, format); + if (status != GVFG_OK) + { + reportError(QStringLiteral("set output format register"), status, channel); + return false; + } + appendLog(QStringLiteral("CH%1 Output format | %2") + .arg(channel) + .arg(format == GVFG_PIXFMT_Y210 ? QStringLiteral("Y210") : QStringLiteral("YUY2"))); + return true; +} + +void CaptureController::startCapture(int channelIndex) +{ + ChannelRuntime &channel = channels_[channelIndex]; + if (channel.running.load(std::memory_order_acquire)) + return; + + if (!openChannel(channelIndex)) + return; + + // Consume queued signal events first. gvfg_start_channel() performs the + // single authoritative hardware revalidation; preview setup reuses the + // most recent UI cache instead of issuing another register query here. + processPendingEvents(); + if (!channel.haveCachedSignalStatus || !channel.cachedSignalStatus.connected) + { + appendLog(QStringLiteral("CH%1 Start skipped: no input signal").arg(channelIndex)); + return; + } + + const bool audioEnabled = channel.requestedAudio; + gvfg_status_t st = client_.setAudioEnabled( channelIndex, audioEnabled ? 1 : 0); + if (st != GVFG_OK) + { + reportError(QStringLiteral("gvfg_set_channel_audio_enabled"), st, channelIndex); + return; + } + channel.audioFormat = {}; + if (audioEnabled) + { + st = client_.getAudioFormat( channelIndex, &channel.audioFormat); + if (st != GVFG_OK) + { + reportError(QStringLiteral("gvfg_get_channel_audio_format"), st, channelIndex); + return; + } + if (channel.audioFormat.channels == 0 || channel.audioFormat.sample_rate == 0 || + (channel.audioFormat.bits_per_sample != 8 && + channel.audioFormat.bits_per_sample != 16 && + channel.audioFormat.bits_per_sample != 32)) + { + appendLog(QStringLiteral("CH%1 Audio format unsupported by Qt playback | %2 Hz %3 ch %4-bit") + .arg(channelIndex) + .arg(channel.audioFormat.sample_rate) + .arg(channel.audioFormat.channels) + .arg(channel.audioFormat.bits_per_sample)); + return; + } + } + + channel.frameAvailable.store(false, std::memory_order_release); + emit previewSourceSizeChanged(channelIndex, channel.cachedSignalStatus.width, + channel.cachedSignalStatus.height); + emit previewShowRequested(channelIndex); + if (!applyPreview(channelIndex)) + { + emit previewCloseRequested(channelIndex); + return; + } + + if (gvfg_api::previewPrepare(channel.previewHandle, + channel.cachedSignalStatus.width, + channel.cachedSignalStatus.height, + channel.cachedSignalStatus.bit_depth) != GVFG_PREVIEW_OK) + { + appendLog(QStringLiteral("CH%1 Preview prewarm failed; first frame may initialize GPU resources").arg(channelIndex)); + } + +#if GVFG_INTERNAL_DIAGNOSTICS + appendLog(QStringLiteral("FPGA signal before stream start")); +#endif + + if (gvfg_api::previewWaitIdle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK) + { + appendLog(QStringLiteral("CH%1 Preview still busy from previous run; retry Start after it completes.").arg(channelIndex)); + return; + } + channel.startupStartTime = std::chrono::steady_clock::now(); + st = client_.startChannel( channelIndex); + const auto startupStartCallEnd = std::chrono::steady_clock::now(); + channel.startupStartCallMs = + std::chrono::duration( + startupStartCallEnd - channel.startupStartTime) + .count(); + if (st != GVFG_OK) + { + reportError(QStringLiteral("gvfg_start_channel"), st, channelIndex); + emit previewCloseRequested(channelIndex); + updateSignalStatus(); + emit stateChanged(); + return; + } + + channel.previewFailureCount = 0; + channel.getFrameAverageMs.store(0.0, std::memory_order_relaxed); + channel.getFrameMaximumMs.store(0.0, std::memory_order_relaxed); + channel.getFrameWindowMaximumMs.store(0.0, std::memory_order_relaxed); + channel.getFrameSamples.store(0, std::memory_order_relaxed); + channel.audioEnabled = audioEnabled; + channel.videoReceived = 0; channel.videoSubmitted = 0; + channel.videoSkipped = 0; channel.videoFailed = 0; + channel.videoIdGaps = 0; channel.videoIdResets = 0; + channel.videoLastId = 0; + channel.lastLoggedVideoIssues = channel.lastLoggedAudioIssues = 0; + channel.lastDeliveryLogMs = 0; + channel.previewBaseline = {}; + gvfg_api::previewGetDeliveryStats(channel.previewHandle, &channel.previewBaseline); + { + std::lock_guard lock(channel.audioQueueMutex); + channel.audioQueue.clear(); + channel.audioReceivedFrames = 0; + channel.audioReceivedBytes = channel.audioAcceptedBytes = channel.audioQueuedBytes = 0; + channel.audioDroppedBytes = channel.audioCancelledBytes = 0; + channel.audioFailedBytes = channel.audioIdGaps = channel.audioIdResets = 0; + channel.audioLastId = 0; + } +#if GVFG_INTERNAL_DIAGNOSTICS + channel.haveDebugBaseline = false; + channel.lastDebugDmaErrors = 0; +#endif + channel.signalConnected.store(channel.cachedSignalStatus.connected != 0, + std::memory_order_release); + channel.stopRequested.store(false, std::memory_order_release); + channel.running.store(true, std::memory_order_release); + channel.captureThreadExited.store(false, std::memory_order_release); + channel.captureThread = std::thread([this, channelIndex]() + { captureReadLoop(channelIndex); }); + if (audioEnabled) + { + channel.audioPlaybackThread = std::thread([this, channelIndex]() + { audioPlaybackLoop(channelIndex); }); + channel.audioThread = std::thread([this, channelIndex]() + { audioReadLoop(channelIndex); }); + } + emit stateChanged(); + appendLog(audioEnabled + ? QStringLiteral("CH%1 Started video + audio | %2 Hz %3 ch %4-bit") + .arg(channelIndex) + .arg(channel.audioFormat.sample_rate) + .arg(channel.audioFormat.channels) + .arg(channel.audioFormat.bits_per_sample) + : QStringLiteral("CH%1 Started video-only").arg(channelIndex)); + updateSignalStatus(false); +} + +void CaptureController::stopCapture(int channelIndex) +{ + ChannelRuntime &channel = channels_[channelIndex]; + if (client_.valid() && channel.running.load(std::memory_order_acquire)) + { + channel.stopRequested.store(true, std::memory_order_release); + channel.signalReady.notify_all(); + channel.audioQueueReady.notify_all(); + joinCaptureThread(channelIndex); + joinAudioThread(channelIndex); + if (gvfg_api::previewWaitIdle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK) + appendLog(QStringLiteral("CH%1 Preview drain timed out; remaining in_flight is not counted as lost.").arg(channelIndex)); + logDeliveryStatus(channelIndex, true); + client_.stopChannel( channelIndex); + channel.running.store(false, std::memory_order_release); + channel.frameAvailable.store(false, std::memory_order_release); + channel.audioEnabled = false; + emit previewCloseRequested(channelIndex); + appendLog(QStringLiteral("CH%1 Stopped capture").arg(channelIndex)); + updateSignalStatus(); + } + + channel.frameAvailable.store(false, std::memory_order_release); + emit stateChanged(); +} + +void CaptureController::stopAllCaptures() +{ + stopCapture(GVFG_CHANNEL_0); + stopCapture(GVFG_CHANNEL_1); +} + +bool CaptureController::applyPreview(int channelIndex) +{ + ChannelRuntime &channel = channels_[channelIndex]; + if (!channel.previewHandle) + { + const gvfg_preview_status_t st = gvfg_api::previewCreate(&channel.previewHandle); + if (st != GVFG_PREVIEW_OK || !channel.previewHandle) + { + appendLog(QStringLiteral("CH%1 Preview setup failed: %2") + .arg(channelIndex) + .arg(QString::fromUtf8(gvfg_api::previewStatusText(st)))); + channel.previewHandle = nullptr; + return false; + } + } + + if (!channel.previewTarget) + { + appendLog(QStringLiteral("CH%1 Preview setup failed: no native window target").arg(channelIndex)); + return false; + } + const gvfg_preview_status_t st = gvfg_api::previewAttachWindow( + channel.previewHandle, channel.previewTarget); + if (st != GVFG_PREVIEW_OK) + { + appendLog(QStringLiteral("CH%1 Preview setup failed: %2") + .arg(channelIndex) + .arg(QString::fromUtf8(gvfg_api::previewStatusText(st)))); + return false; + } + return true; +} + +void CaptureController::processPendingEvents() +{ + if (!client_.valid()) + return; + + for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel) + { + if (!channels_[channel].opened) + continue; + gvfg_event_t event{}; + event.struct_size = sizeof(event); + while (client_.pollEvent( channel, &event, 0) == GVFG_OK) + { + const auto eventType = static_cast(event.type); + if (eventType != GVFG_EVENT_STREAM_READY) + appendLog(QStringLiteral("CH%1 EVENT %2").arg(channel).arg(eventTypeText(eventType))); + + if (eventType == GVFG_EVENT_SIGNAL_CONNECTED || + eventType == GVFG_EVENT_SIGNAL_DISCONNECTED || + eventType == GVFG_EVENT_FORMAT_CHANGE_BEGIN || + eventType == GVFG_EVENT_STREAM_READY) + updateSignalStatus(); + + if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED) + channels_[channel].signalConnected.store(false, std::memory_order_release); + else if (eventType == GVFG_EVENT_SIGNAL_CONNECTED || + eventType == GVFG_EVENT_STREAM_READY) + { + channels_[channel].signalConnected.store(true, std::memory_order_release); + channels_[channel].signalReady.notify_all(); + } + + if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED && channels_[channel].previewHandle) + gvfg_api::previewClear(channels_[channel].previewHandle); + + event = {}; + event.struct_size = sizeof(event); + } + } +} + +void CaptureController::updateSignalStatus(bool queryHardware) +{ + if (!client_.valid()) + return; + + QStringList statusLines; +#if GVFG_INTERNAL_DIAGNOSTICS + bool diagnosticProblemDetected = false; +#endif + for (int channelIndex = GVFG_CHANNEL_0; channelIndex <= GVFG_CHANNEL_1; ++channelIndex) + { + ChannelRuntime &channel = channels_[channelIndex]; + if (!channel.opened) + { + const bool zeroCopy = channel.zeroCopy; + statusLines << QStringLiteral("CH%1 | Not opened | %2") + .arg(channelIndex) + .arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy")); + continue; + } + if (queryHardware) + { + gvfg_signal_status_t signal{}; + if (client_.getSignalStatus( channelIndex, &signal) == GVFG_OK) + { + channel.cachedSignalStatus = signal; + channel.haveCachedSignalStatus = true; + } + } + if (!channel.haveCachedSignalStatus) + { + statusLines << QStringLiteral("CH%1 | Signal unavailable").arg(channelIndex); + continue; + } + + const gvfg_signal_status_t &signal = channel.cachedSignalStatus; + const QString inputStatus = signal.connected + ? QStringLiteral("CH%1 Connected | %2").arg(channelIndex).arg(signalFrameText(signal)) + : QStringLiteral("CH%1 No signal").arg(channelIndex); + if (inputStatus != channel.lastLoggedInputStatus) + { + appendLog(QStringLiteral("Input status | %1").arg(inputStatus)); + channel.lastLoggedInputStatus = inputStatus; + } + if (channel.previewVisible.load(std::memory_order_acquire) && signal.width > 0 && signal.height > 0) + emit previewSourceSizeChanged(channelIndex, signal.width, signal.height); + + gvfg_preview_info_t previewInfo{}; + const bool previewInfoOk = channel.previewHandle && + gvfg_api::previewGetInfo(channel.previewHandle, &previewInfo) == GVFG_PREVIEW_OK && + previewInfo.active; + gvfg_preview_stats_t previewStats{}; + const bool previewStatsOk = channel.previewHandle && + gvfg_api::previewGetStats(channel.previewHandle, &previewStats) == GVFG_PREVIEW_OK; + const QString previewFps = previewStatsOk && previewStats.present_fps > 0.0 + ? QString::number(previewStats.present_fps, 'f', 2) + : QStringLiteral("--"); + const QString previewFrame = previewInfoOk + ? frameText(true, previewInfo.width, previewInfo.height, + previewInfo.pixel_format, previewInfo.bit_depth) + : QStringLiteral("--"); + const bool zeroCopy = channel.zeroCopy; + statusLines << QStringLiteral("CH%1 | %2 | %3 | %4") + .arg(channelIndex) + .arg(channel.running.load(std::memory_order_acquire) ? QStringLiteral("Running") : QStringLiteral("Stopped")) + .arg(signalFrameText(signal)) + .arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy")); + if (channel.audioEnabled) + { + uint64_t receivedFrames = 0; + { + std::lock_guard lock(channel.audioQueueMutex); + receivedFrames = channel.audioReceivedFrames; + } + statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | received=%5 frames") + .arg(channelIndex) + .arg(channel.audioFormat.sample_rate) + .arg(channel.audioFormat.channels) + .arg(channel.audioFormat.bits_per_sample) + .arg(static_cast(receivedFrames)); +#if GVFG_INTERNAL_DIAGNOSTICS + uint64_t sdkBytes = 0; + uint64_t appOutputBytes = 0; + { + std::lock_guard lock(channel.audioQueueMutex); + sdkBytes = channel.audioReceivedBytes; + appOutputBytes = channel.audioAcceptedBytes; + } + gvfg_debug_backend_stats_t audioStats{}; + if (client_.getDebugStats( channelIndex, &audioStats) == GVFG_OK) + { + statusLines << QStringLiteral("CH%1 Audio Debug | Events DMA=%2 Extra=%3 | Driver->SDK %4 frames/%5 bytes | SDK->APP %6 frames/%7 bytes | APP->Output %8 bytes") + .arg(channelIndex) + .arg(static_cast(audioStats.audio_dma_event_wakes)) + .arg(static_cast(audioStats.extra_audio_event_wakes)) + .arg(static_cast(audioStats.audio_frames_from_driver)) + .arg(static_cast(audioStats.audio_bytes_from_driver)) + .arg(static_cast(receivedFrames)) + .arg(static_cast(sdkBytes)) + .arg(static_cast(appOutputBytes)); + } +#endif + } + statusLines << QStringLiteral("CH%1 Preview | %2 FPS | %3") + .arg(channelIndex) + .arg(previewFps, previewFrame); + logDeliveryStatus(channelIndex); + const uint64_t readSamples = channel.getFrameSamples.load(std::memory_order_relaxed); + statusLines << (readSamples >= 300 + ? QStringLiteral("CH%1 Read | avg=%2 max300=%3 max=%4 ms samples=%5") + .arg(channelIndex) + .arg(channel.getFrameAverageMs.load(std::memory_order_relaxed), 0, 'f', 3) + .arg(channel.getFrameWindowMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3) + .arg(channel.getFrameMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3) + .arg(static_cast(readSamples)) + : QStringLiteral("CH%1 Read | measuring").arg(channelIndex)); + + gvfg_runtime_info_t runtimeInfo{}; + if (client_.getRuntimeInfo( channelIndex, &runtimeInfo) == GVFG_OK) + { + statusLines << (runtimeInfo.driver_read_samples >= 300 + ? QStringLiteral("CH%1 %2 | avg=%3 max300=%4 max=%5 us samples=%6") + .arg(channelIndex) + .arg(runtimeInfo.zero_copy_enabled + ? QStringLiteral("ZeroCopy Acquire") + : QStringLiteral("Copy GetFrame")) + .arg(runtimeInfo.driver_read_average_us, 0, 'f', 3) + .arg(runtimeInfo.driver_read_max300_us, 0, 'f', 3) + .arg(runtimeInfo.driver_read_max_us, 0, 'f', 3) + .arg(static_cast(runtimeInfo.driver_read_samples)) + : QStringLiteral("CH%1 Driver GetFrame | measuring").arg(channelIndex)); + } + +#if GVFG_INTERNAL_DIAGNOSTICS + gvfg_debug_backend_stats_t backendStats{}; + if (client_.getDebugStats( channelIndex, &backendStats) == GVFG_OK) + { + statusLines << QStringLiteral("CH%1 Capture | status=%2 dma_errors=%3 no_frame_waits=%4") + .arg(channelIndex) + .arg(captureStatusText(backendStats, signal.connected != 0)) + .arg(static_cast(backendStats.backend_dma_errors)) + .arg(static_cast(backendStats.backend_wait_timeouts)); + if (channel.haveDebugBaseline && backendStats.backend_dma_errors > channel.lastDebugDmaErrors) + { + appendLog(QStringLiteral("CH%1 ERROR DMA failures +%2, total=%3") + .arg(channelIndex) + .arg(valueOrDash(backendStats.backend_dma_errors - channel.lastDebugDmaErrors), + valueOrDash(backendStats.backend_dma_errors))); + diagnosticProblemDetected = true; + } + channel.lastDebugDmaErrors = backendStats.backend_dma_errors; + channel.haveDebugBaseline = true; + } +#endif + } + + const QString statusText = statusLines.join(QLatin1Char('\n')); + const bool changed = lastSignalStatusText_ != statusText; + if (changed) + { + emit statusChanged(statusText); + lastSignalStatusText_ = statusText; + } + emit stateChanged(); + +#if GVFG_INTERNAL_DIAGNOSTICS + if (diagnosticProblemDetected) + writeDiagnosticSnapshot(statusText); +#endif +} + +void CaptureController::reportError(const QString &apiName, gvfg_status_t status, int channel) +{ + QString detail; + if (client_.valid() && (channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1)) + { + char message[512] = {}; + if (client_.getLastError( channel, message, sizeof(message)) == GVFG_OK) + detail = QString::fromUtf8(message); + } + emit errorOccurred(apiName, status, channel, detail); +} + +void CaptureController::appendLog(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)); + writeLogFileLine(line); + emit logMessage(line); + } +} + +void CaptureController::openLogFile() +{ + logSessionStamp_ = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss")); + logPartIndex_ = 1; + logDirPath_ = QCoreApplication::applicationDirPath() + QStringLiteral("/logs"); + if (!QDir().mkpath(logDirPath_)) + { + logFilePath_ = logDirPath_; + return; + } + + openLogFilePart(); +} + +bool CaptureController::openLogFilePart() +{ + std::lock_guard lock(logFileMutex_); + if (logFile_.isOpen()) + logFile_.close(); + + logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log") + .arg(logDirPath_, logFilePrefix(), logSessionStamp_) + .arg(logPartIndex_, 2, 10, QLatin1Char('0')); + logFile_.setFileName(logFilePath_); + if (!logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) + return false; + + const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n") + .arg(logFilePrefix(), + QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))) + .arg(logPartIndex_); + logFile_.write(header.toUtf8()); + logFile_.flush(); + return true; +} + +void CaptureController::rotateLogFileIfNeeded() +{ + if (!logFile_.isOpen() || logFile_.size() < kMaxLogFileBytes) + return; + + const QString footer = QStringLiteral("==== log rotated at %1 ====\n") + .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))); + logFile_.write(footer.toUtf8()); + logFile_.flush(); + ++logPartIndex_; + openLogFilePart(); +} + +void CaptureController::writeLogFileLine(const QString &line) +{ + std::lock_guard lock(logFileMutex_); + if (!logFile_.isOpen()) + return; + + if (logFile_.size() >= kMaxLogFileBytes) + { + const QString footer = QStringLiteral("==== log rotated at %1 ====\n") + .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))); + logFile_.write(footer.toUtf8()); + logFile_.flush(); + ++logPartIndex_; + if (logFile_.isOpen()) + logFile_.close(); + logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log") + .arg(logDirPath_, logFilePrefix(), logSessionStamp_) + .arg(logPartIndex_, 2, 10, QLatin1Char('0')); + logFile_.setFileName(logFilePath_); + if (logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) + { + const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n") + .arg(logFilePrefix(), + QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))) + .arg(logPartIndex_); + logFile_.write(header.toUtf8()); + } + } + + if (!logFile_.isOpen()) + return; + + logFile_.write(line.toUtf8()); + logFile_.write("\n"); + logFile_.flush(); +} + +#if GVFG_INTERNAL_DIAGNOSTICS +void CaptureController::writeDiagnosticSnapshot(const QString &statusText) +{ + const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz")); + const QStringList lines = statusText.split(QLatin1Char('\n')); + for (int i = 0; i < lines.size(); ++i) + { + const QString line = QStringLiteral("[%1] %2%3") + .arg(timestamp, + i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "), + lines.at(i)); + writeLogFileLine(line); + } +} +#endif + +void CaptureController::logDeliveryStatus(int channelIndex, bool finalSnapshot) +{ + auto &c = channels_[channelIndex]; + if (!finalSnapshot && !c.running.load()) + return; + const qint64 now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + // Keep normal operation quiet; aggregate repeated failures at most every 5 s. + if (!finalSnapshot && now - c.lastDeliveryLogMs < 5000) + return; + + const auto count = [](uint64_t value) { return QString::number(static_cast(value)); }; + gvfg_preview_delivery_stats_t p{}; + const bool previewOk = c.previewHandle && + gvfg_api::previewGetDeliveryStats(c.previewHandle, &p) == GVFG_PREVIEW_OK; + const auto &b = c.previewBaseline; + const uint64_t failed = (previewOk ? p.failed - b.failed : 0) + c.videoFailed.load(); + const uint64_t videoIssues = failed + c.videoIdGaps.load() + c.videoIdResets.load(); + + uint64_t audioIssues, audioGaps, audioResets, audioFailed; + bool audioAccounted; + { + std::lock_guard lock(c.audioQueueMutex); + audioGaps = c.audioIdGaps; + audioResets = c.audioIdResets; + audioFailed = c.audioFailedBytes; + audioIssues = audioGaps + audioResets + audioFailed; + audioAccounted = c.audioQueuedBytes == 0 && c.audioReceivedBytes == + c.audioAcceptedBytes + c.audioDroppedBytes + c.audioCancelledBytes + c.audioFailedBytes; + } + if (finalSnapshot) + { + const bool videoAccounted = previewOk && c.videoReceived.load() == + c.videoSubmitted.load() + c.videoSkipped.load() + c.videoFailed.load() && + c.videoSubmitted.load() == p.submitted - b.submitted; + if (!videoAccounted || !audioAccounted) + appendLog(QStringLiteral("CH%1 ERROR delivery accounting mismatch | video=%2 audio=%3") + .arg(channelIndex).arg(videoAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH")) + .arg(audioAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH"))); + } + // Also flush any changes since the last aggregate when stopping. + if (videoIssues != c.lastLoggedVideoIssues) + { + QString message = QStringLiteral("CH%1 ERROR preview delivery | failed=%2 id_gaps=%3 reset_or_duplicate=%4") + .arg(channelIndex).arg(count(failed)).arg(count(c.videoIdGaps.load())) + .arg(count(c.videoIdResets.load())); + appendLog(message); + } + if (audioIssues != c.lastLoggedAudioIssues) + { + QString message = QStringLiteral("CH%1 ERROR audio delivery | id_gaps=%2 reset_or_duplicate=%3 failed_bytes=%4") + .arg(channelIndex).arg(count(audioGaps)).arg(count(audioResets)).arg(count(audioFailed)); + appendLog(message); + } + if (finalSnapshot || videoIssues != c.lastLoggedVideoIssues || audioIssues != c.lastLoggedAudioIssues) + c.lastDeliveryLogMs = now; + c.lastLoggedVideoIssues = videoIssues; + c.lastLoggedAudioIssues = audioIssues; +} + +void CaptureController::captureReadLoop(int channelIndex) +{ + constexpr uint64_t kTimingWarmupFrames = 30; + constexpr uint64_t kGetFrameTimingSampleFrames = 300; + + std::chrono::steady_clock::time_point noFrameSince{}; + std::chrono::steady_clock::time_point nextNoFrameReport{}; + bool captureStalledLogged = false; + bool startupLatencyLogged = false; + uint64_t successfulFrameCount = 0; + uint64_t getFrameTimingSampleCount = 0; + double getFrameTimingMaximumMs = 0.0; + ChannelRuntime &channel = channels_[channelIndex]; + while (!channel.stopRequested.load(std::memory_order_acquire)) + { + { + std::unique_lock lock(channel.signalMutex); + channel.signalReady.wait(lock, [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire) || + channel.signalConnected.load(std::memory_order_acquire); + }); + } + if (channel.stopRequested.load(std::memory_order_acquire)) + break; + + gvfg_frame_t frame{}; + const auto getFrameStart = std::chrono::steady_clock::now(); + const gvfg_status_t st = client_.readFrame( channelIndex, &frame, 200); + const double getFrameElapsedMs = + std::chrono::duration( + std::chrono::steady_clock::now() - getFrameStart) + .count(); + if (st == GVFG_OK) + { + const uint64_t previousId = channel.videoLastId.exchange(frame.frame_id); + if (channel.videoReceived.fetch_add(1) != 0) + { + if (frame.frame_id > previousId && frame.frame_id - previousId > 1) + channel.videoIdGaps += frame.frame_id - previousId - 1; + else if (frame.frame_id <= previousId) + ++channel.videoIdResets; + } + const bool timingWarmupComplete = ++successfulFrameCount > kTimingWarmupFrames; + if (timingWarmupComplete) + { + ++getFrameTimingSampleCount; + getFrameTimingMaximumMs = (std::max)(getFrameTimingMaximumMs, getFrameElapsedMs); + const uint64_t totalSamples = channel.getFrameSamples.fetch_add(1, std::memory_order_relaxed) + 1; + const double previousAverage = channel.getFrameAverageMs.load(std::memory_order_relaxed); + channel.getFrameAverageMs.store( + previousAverage + (getFrameElapsedMs - previousAverage) / static_cast(totalSamples), + std::memory_order_relaxed); + double observedMaximum = channel.getFrameMaximumMs.load(std::memory_order_relaxed); + while (getFrameElapsedMs > observedMaximum && + !channel.getFrameMaximumMs.compare_exchange_weak( + observedMaximum, getFrameElapsedMs, std::memory_order_relaxed)) + { + } + if (totalSamples <= kGetFrameTimingSampleFrames) + channel.getFrameWindowMaximumMs.store(getFrameTimingMaximumMs, std::memory_order_relaxed); + if (getFrameTimingSampleCount >= kGetFrameTimingSampleFrames) + { + channel.getFrameWindowMaximumMs.store(getFrameTimingMaximumMs, std::memory_order_relaxed); + getFrameTimingSampleCount = 0; + getFrameTimingMaximumMs = 0.0; + } + } + noFrameSince = {}; + nextNoFrameReport = {}; + if (!channel.frameAvailable.exchange(true, std::memory_order_acq_rel)) + { + QMetaObject::invokeMethod(this, [this]() + { emit stateChanged(); }, Qt::QueuedConnection); + } + if (captureStalledLogged) + { + captureStalledLogged = false; + QMetaObject::invokeMethod(this, [this, channelIndex]() + { appendLog(QStringLiteral("CH%1 RECOVERED capture resumed").arg(channelIndex)); }, Qt::QueuedConnection); + } + + const bool attemptedPreview = channel.previewHandle && + channel.previewVisible.load(std::memory_order_acquire); + if (attemptedPreview) + { + gvfg_preview_frame_t previewFrame{}; + previewFrame.data = frame.data; + previewFrame.data_size = frame.data_size; + previewFrame.width = frame.width; + previewFrame.height = frame.height; + previewFrame.row_bytes = frame.row_stride_bytes; + previewFrame.bit_depth = frame.bit_depth; + previewFrame.frame_id = frame.frame_id; + + switch (frame.pixel_format) + { + case GVFG_PIXFMT_YUY2: + previewFrame.pixel_format = GVFG_PREVIEW_PIXFMT_YUY2; + break; + case GVFG_PIXFMT_Y210: + previewFrame.pixel_format = GVFG_PREVIEW_PIXFMT_Y210; + break; + default: + previewFrame.pixel_format = 0; + break; + } + + const auto previewStart = std::chrono::steady_clock::now(); + const gvfg_preview_status_t previewStatus = + gvfg_api::previewRenderFrame(channel.previewHandle, &previewFrame); + const auto previewEnd = std::chrono::steady_clock::now(); + const double previewElapsedMs = + std::chrono::duration(previewEnd - previewStart).count(); + if (previewStatus != GVFG_PREVIEW_OK) + { + ++channel.videoFailed; + const uint64_t failures = ++channel.previewFailureCount; + if (failures == 1) + { + QMetaObject::invokeMethod(this, [this, channelIndex, failures, previewStatus]() + { appendLog(QStringLiteral("CH%1 preview render failed #%2: %3") + .arg(channelIndex) + .arg(static_cast(failures)) + .arg(QString::fromUtf8(gvfg_api::previewStatusText(previewStatus)))); }, Qt::QueuedConnection); + } + } + else + { + ++channel.videoSubmitted; + if (!startupLatencyLogged) + { + startupLatencyLogged = true; + const double startupLatencyMs = + std::chrono::duration( + previewEnd - channel.startupStartTime) + .count(); + const double startCallMs = channel.startupStartCallMs; + const double firstReadMs = getFrameElapsedMs; + const double firstRenderFrameMs = previewElapsedMs; + const uint64_t startupFrameId = frame.frame_id; + QMetaObject::invokeMethod( + this, + [this, channelIndex, startCallMs, firstReadMs, + firstRenderFrameMs, startupLatencyMs, startupFrameId]() + { + appendLog(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 | frame_id=%6") + .arg(channelIndex) + .arg(startCallMs, 0, 'f', 3) + .arg(firstReadMs, 0, 'f', 3) + .arg(firstRenderFrameMs, 0, 'f', 3) + .arg(startupLatencyMs, 0, 'f', 3) + .arg(static_cast(startupFrameId))); + }, + Qt::QueuedConnection); + } + if (channel.previewFailureCount != 0) + { + const uint64_t failures = channel.previewFailureCount; + channel.previewFailureCount = 0; + QMetaObject::invokeMethod(this, [this, channelIndex, failures]() + { appendLog(QStringLiteral("CH%1 preview render recovered after %2 failure(s)") + .arg(channelIndex) + .arg(static_cast(failures))); }, Qt::QueuedConnection); + } + + } + } + if (!channel.previewHandle) + ++channel.videoFailed; + else if (!attemptedPreview) + ++channel.videoSkipped; + const gvfg_status_t releaseStatus = client_.releaseFrame( channelIndex, &frame); + if (releaseStatus != GVFG_OK) + { + QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]() + { reportError(QStringLiteral("gvfg_release_channel_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection); + break; + } + + continue; + } + + if (st == GVFG_ETIMEOUT) + { + const auto now = std::chrono::steady_clock::now(); + if (noFrameSince == std::chrono::steady_clock::time_point{}) + { + noFrameSince = now; + nextNoFrameReport = now + std::chrono::seconds(2); + } + if (now >= nextNoFrameReport) + { + captureStalledLogged = true; + const uint64_t elapsedMs = static_cast( + std::chrono::duration_cast(now - noFrameSince).count()); + nextNoFrameReport = now + std::chrono::seconds(10); + QMetaObject::invokeMethod(this, [this, channelIndex, elapsedMs]() + { + appendLog(QStringLiteral("CH%1 ERROR no capture frame for %2 ms") + .arg(channelIndex) + .arg(elapsedMs)); +#if GVFG_INTERNAL_DIAGNOSTICS + updateSignalStatus(false); + writeDiagnosticSnapshot(lastSignalStatusText_); +#endif + }, + Qt::QueuedConnection); + } + continue; + } + if (channel.stopRequested.load(std::memory_order_acquire)) + break; + + QMetaObject::invokeMethod(this, [this, channelIndex, st]() + { reportError(QStringLiteral("gvfg_read_channel_frame"), st, channelIndex); }, Qt::QueuedConnection); + break; + } + channel.captureThreadExited.store(true, std::memory_order_release); +} + +void CaptureController::joinCaptureThread(int channel) +{ + if (channels_[channel].captureThread.joinable()) + { + // The capture worker can wait behind preview resource updates. Keep + // DXGI's synchronous HWND messages flowing while joining it. + while (!channels_[channel].captureThreadExited.load(std::memory_order_acquire)) + { + MsgWaitForMultipleObjectsEx(0, nullptr, 1, QS_SENDMESSAGE, MWMO_INPUTAVAILABLE); + MSG message{}; + PeekMessageW(&message, nullptr, 0, 0, PM_NOREMOVE | PM_QS_SENDMESSAGE); + } + channels_[channel].captureThread.join(); + } +} + +void CaptureController::audioReadLoop(int channelIndex) +{ + ChannelRuntime &channel = channels_[channelIndex]; + while (!channel.stopRequested.load(std::memory_order_acquire)) + { + { + std::unique_lock lock(channel.signalMutex); + channel.signalReady.wait(lock, [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire) || + channel.signalConnected.load(std::memory_order_acquire); + }); + } + if (channel.stopRequested.load(std::memory_order_acquire)) + break; + + gvfg_audio_frame_t frame{}; + const gvfg_status_t status = client_.readAudioFrame(channelIndex, &frame, 200); + if (status == GVFG_ETIMEOUT) + continue; + if (status != GVFG_OK) + { + if (!channel.stopRequested.load(std::memory_order_acquire)) + { + QMetaObject::invokeMethod(this, [this, channelIndex, status]() + { reportError(QStringLiteral("gvfg_read_channel_audio_frame"), status, channelIndex); }, Qt::QueuedConnection); + } + break; + } + + const uint64_t audioId = frame.frame_id; + { + std::lock_guard lock(channel.audioQueueMutex); + if (channel.audioReceivedBytes != 0) + { + if (audioId > channel.audioLastId && audioId - channel.audioLastId > 1) + channel.audioIdGaps += audioId - channel.audioLastId - 1; + else if (audioId <= channel.audioLastId) + ++channel.audioIdResets; + } + channel.audioLastId = audioId; + channel.audioReceivedBytes += frame.data_size; + ++channel.audioReceivedFrames; + } + std::vector pcm(frame.data_size); + std::memcpy(pcm.data(), frame.data, frame.data_size); + const gvfg_status_t releaseStatus = + client_.releaseAudioFrame( channelIndex, &frame); + if (releaseStatus != GVFG_OK) + { + std::lock_guard lock(channel.audioQueueMutex); + channel.audioFailedBytes += pcm.size(); + } + if (releaseStatus != GVFG_OK && !channel.stopRequested.load(std::memory_order_acquire)) + { + QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]() + { reportError(QStringLiteral("gvfg_release_channel_audio_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection); + break; + } + + if (releaseStatus == GVFG_OK) + { + { + std::lock_guard lock(channel.audioQueueMutex); + if (channel.stopRequested.load(std::memory_order_acquire)) + { + channel.audioCancelledBytes += pcm.size(); + break; + } + if (channel.audioQueue.size() >= kMaxQueuedAudioFrames) + { + const auto &oldest = channel.audioQueue.front(); + channel.audioDroppedBytes += oldest.pcm.size(); + channel.audioQueuedBytes -= oldest.pcm.size(); + channel.audioQueue.pop_front(); + } + channel.audioQueuedBytes += pcm.size(); + channel.audioQueue.push_back({std::move(pcm)}); + } + channel.audioQueueReady.notify_one(); + } + } + channel.audioQueueReady.notify_all(); +} + +void CaptureController::audioPlaybackLoop(int channelIndex) +{ + ChannelRuntime &channel = channels_[channelIndex]; + const gvfg_audio_format_t format = channel.audioFormat; + + QAudioFormat outputFormat; + outputFormat.setSampleRate(static_cast(format.sample_rate)); + outputFormat.setChannelCount(static_cast(format.channels)); + switch (format.bits_per_sample) + { + case 8: + outputFormat.setSampleFormat(QAudioFormat::UInt8); + break; + case 16: + outputFormat.setSampleFormat(QAudioFormat::Int16); + break; + case 32: + outputFormat.setSampleFormat(QAudioFormat::Int32); + break; + default: + return; + } + + bool recovering = false; + while (!channel.stopRequested.load(std::memory_order_acquire)) + { + const QAudioDevice outputDevice = QMediaDevices::defaultAudioOutput(); + if (outputDevice.isNull() || !outputDevice.isFormatSupported(outputFormat)) + { + if (!recovering) + QMetaObject::invokeMethod(this, [this, channelIndex]() { + appendLog(QStringLiteral("CH%1 Audio output unavailable; monitoring playback will retry").arg(channelIndex)); + }, Qt::QueuedConnection); + recovering = true; + std::unique_lock lock(channel.audioQueueMutex); + while (!channel.audioQueue.empty()) + { + channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); + channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); + channel.audioQueue.pop_front(); + } + channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire); + }); + continue; + } + + QAudioSink audioSink(outputDevice, outputFormat); + QIODevice *audioOutput = audioSink.start(); + if (!audioOutput) + { + if (!recovering) + QMetaObject::invokeMethod(this, [this, channelIndex]() { + appendLog(QStringLiteral("CH%1 Audio output failed to start; monitoring playback will retry").arg(channelIndex)); + }, Qt::QueuedConnection); + recovering = true; + std::unique_lock lock(channel.audioQueueMutex); + while (!channel.audioQueue.empty()) + { + channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); + channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); + channel.audioQueue.pop_front(); + } + channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire); + }); + continue; + } + + if (recovering) + QMetaObject::invokeMethod(this, [this, channelIndex]() { + appendLog(QStringLiteral("CH%1 Audio monitoring playback recovered").arg(channelIndex)); + }, Qt::QueuedConnection); + recovering = false; + bool restartPlayback = false; + while (!channel.stopRequested.load(std::memory_order_acquire) && !restartPlayback) + { + std::vector pcm; + { + std::unique_lock lock(channel.audioQueueMutex); + channel.audioQueueReady.wait(lock, [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire) || + !channel.audioQueue.empty(); + }); + if (channel.stopRequested.load(std::memory_order_acquire)) + break; + pcm = std::move(channel.audioQueue.front().pcm); + channel.audioQueue.pop_front(); + channel.audioQueuedBytes -= pcm.size(); + } + + qint64 written = 0; + auto lastProgress = std::chrono::steady_clock::now(); + while (written < static_cast(pcm.size()) && + !channel.stopRequested.load(std::memory_order_acquire)) + { + const qint64 result = audioOutput->write( + reinterpret_cast(pcm.data()) + written, + static_cast(pcm.size()) - written); + const auto now = std::chrono::steady_clock::now(); + const bool stalled = result == 0 && now - lastProgress >= std::chrono::seconds(2); + { + std::lock_guard lock(channel.audioQueueMutex); + if (result > 0) + channel.audioAcceptedBytes += static_cast(result); + else if (result < 0 || stalled) + channel.audioFailedBytes += pcm.size() - static_cast(written); + } + if (result > 0) + { + written += result; + lastProgress = now; + continue; + } + if (result < 0 || stalled) + { + QMetaObject::invokeMethod(this, [this, channelIndex, stalled]() { + appendLog(stalled + ? QStringLiteral("CH%1 Audio output made no progress for 2 seconds; rebuilding monitoring playback").arg(channelIndex) + : QStringLiteral("CH%1 Audio output write failed; rebuilding monitoring playback").arg(channelIndex)); + }, Qt::QueuedConnection); + restartPlayback = true; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + if (written != static_cast(pcm.size()) && !restartPlayback) + { + std::lock_guard lock(channel.audioQueueMutex); + channel.audioCancelledBytes += pcm.size() - static_cast(written); + } + } + audioSink.stop(); + if (restartPlayback) + { + recovering = true; + std::unique_lock lock(channel.audioQueueMutex); + while (!channel.audioQueue.empty()) + { + channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); + channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); + channel.audioQueue.pop_front(); + } + channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { + return channel.stopRequested.load(std::memory_order_acquire); + }); + } + } +} + +void CaptureController::joinAudioThread(int channel) +{ + if (channels_[channel].audioThread.joinable()) + channels_[channel].audioThread.join(); + channels_[channel].audioQueueReady.notify_all(); + if (channels_[channel].audioPlaybackThread.joinable()) + channels_[channel].audioPlaybackThread.join(); + std::lock_guard lock(channels_[channel].audioQueueMutex); + channels_[channel].audioCancelledBytes += channels_[channel].audioQueuedBytes; + channels_[channel].audioQueuedBytes = 0; + channels_[channel].audioQueue.clear(); +} diff --git a/GVFG_Qt_Sample/capture_controller.h b/GVFG_Qt_Sample/capture_controller.h new file mode 100644 index 0000000..a7fb805 --- /dev/null +++ b/GVFG_Qt_Sample/capture_controller.h @@ -0,0 +1,136 @@ +#pragma once + +#include "gvfg_api.h" +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 setPreviewTarget(int channel, void *nativeWindow); + void setPreviewVisible(int channel, bool visible); + + bool deviceOpen() const { return client_.valid(); } + 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; + +public slots: + void refreshDevices(); + bool openDevice(); + void closeDevice(); + bool applyOutputFormat(int channel); + 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 logMessage(const QString &message); + void errorOccurred(const QString &apiName, gvfg_status_t status, int channel, const QString &detail); + void previewSourceSizeChanged(int channel, int width, int height); + void previewShowRequested(int channel); + void previewCloseRequested(int channel); + +private: + struct ChannelRuntime + { + struct AudioPacket { std::vector pcm; }; + 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 running{false}, stopRequested{false}, signalConnected{false}; + std::mutex signalMutex; + std::condition_variable signalReady; + std::atomic frameAvailable{false}, previewVisible{false}, captureThreadExited{true}; + std::thread captureThread, audioThread, audioPlaybackThread; + std::mutex audioQueueMutex; + std::condition_variable audioQueueReady; + std::deque audioQueue; + bool audioEnabled = false; + gvfg_audio_format_t audioFormat{}; + uint64_t audioReceivedFrames = 0, audioReceivedBytes = 0, audioAcceptedBytes = 0; + uint64_t audioQueuedBytes = 0, audioDroppedBytes = 0, audioCancelledBytes = 0; + uint64_t audioFailedBytes = 0, audioIdGaps = 0, audioIdResets = 0, audioLastId = 0; + std::atomic videoReceived{0}, videoSubmitted{0}, videoSkipped{0}, videoFailed{0}; + std::atomic videoIdGaps{0}, videoIdResets{0}, videoLastId{0}; + gvfg_preview_delivery_stats_t previewBaseline{}; + std::chrono::steady_clock::time_point startupStartTime{}; + double startupStartCallMs = 0.0; + uint64_t lastLoggedVideoIssues = 0, lastLoggedAudioIssues = 0; + qint64 lastDeliveryLogMs = 0; + std::atomic getFrameAverageMs{0.0}, getFrameMaximumMs{0.0}, getFrameWindowMaximumMs{0.0}; + std::atomic getFrameSamples{0}; + uint64_t previewFailureCount = 0; + gvfg_signal_status_t cachedSignalStatus{}; + bool haveCachedSignalStatus = false; + QString lastLoggedInputStatus; +#if GVFG_INTERNAL_DIAGNOSTICS + uint64_t lastDebugDmaErrors = 0; + bool haveDebugBaseline = false; +#endif + }; + + void reportError(const QString &apiName, gvfg_status_t status, int channel = -1); + void appendLog(const QString &message); + bool openChannel(int channel); + void openLogFile(); + bool openLogFilePart(); + void rotateLogFileIfNeeded(); + void writeLogFileLine(const QString &line); +#if GVFG_INTERNAL_DIAGNOSTICS + void writeDiagnosticSnapshot(const QString &statusText); +#endif + void captureReadLoop(int channel); + void audioReadLoop(int channel); + void audioPlaybackLoop(int channel); + void joinCaptureThread(int channel); + void joinAudioThread(int channel); + void logDeliveryStatus(int channel, bool finalSnapshot = false); + + static constexpr qint64 kMaxLogFileBytes = 20ll * 1024ll * 1024ll; + std::array devices_{}; + int deviceCount_ = 0; + GvfgClient client_; + int selectedDeviceIndex_ = -1; + std::array channels_{}; + QTimer *runtimeStatusTimer_ = nullptr; + QString lastSignalStatusText_; + QFile logFile_; + std::mutex logFileMutex_; + QString logDirPath_, logFilePath_, logSessionStamp_; + int logPartIndex_ = 1; +}; diff --git a/GVFG_Qt_Sample/gvfg_api.cpp b/GVFG_Qt_Sample/gvfg_api.cpp new file mode 100644 index 0000000..12eeca5 --- /dev/null +++ b/GVFG_Qt_Sample/gvfg_api.cpp @@ -0,0 +1,47 @@ +#include "gvfg_api.h" + +GvfgClient::~GvfgClient() { destroy(); } +gvfg_status_t GvfgClient::create() { return handle_ ? GVFG_OK : gvfg_create(&handle_); } +gvfg_status_t GvfgClient::destroy() +{ + if (!handle_) return GVFG_OK; + const gvfg_status_t status = gvfg_destroy(handle_); + handle_ = nullptr; + return status; +} +gvfg_status_t GvfgClient::openChannel(int device, int channel) { return gvfg_open_channel(handle_, device, channel); } +gvfg_status_t GvfgClient::setZeroCopy(int channel, int enabled) { return gvfg_set_channel_zero_copy_enabled(handle_, channel, enabled); } +gvfg_status_t GvfgClient::setVideoFormat(int channel, gvfg_pixel_format_t format) { return gvfg_set_channel_video_format(handle_, channel, format); } +gvfg_status_t GvfgClient::setAudioEnabled(int channel, int enabled) { return gvfg_set_channel_audio_enabled(handle_, channel, enabled); } +gvfg_status_t GvfgClient::getAudioFormat(int channel, gvfg_audio_format_t *format) const { return gvfg_get_channel_audio_format(handle_, channel, format); } +gvfg_status_t GvfgClient::startChannel(int channel) { return gvfg_start_channel(handle_, channel); } +gvfg_status_t GvfgClient::stopChannel(int channel) { return gvfg_stop_channel(handle_, channel); } +gvfg_status_t GvfgClient::readFrame(int channel, gvfg_frame_t *frame, uint32_t timeoutMs) { return gvfg_read_channel_frame(handle_, channel, frame, timeoutMs); } +gvfg_status_t GvfgClient::releaseFrame(int channel, const gvfg_frame_t *frame) { return gvfg_release_channel_frame(handle_, channel, frame); } +gvfg_status_t GvfgClient::readAudioFrame(int channel, gvfg_audio_frame_t *frame, uint32_t timeoutMs) { return gvfg_read_channel_audio_frame(handle_, channel, frame, timeoutMs); } +gvfg_status_t GvfgClient::releaseAudioFrame(int channel, const gvfg_audio_frame_t *frame) { return gvfg_release_channel_audio_frame(handle_, channel, frame); } +gvfg_status_t GvfgClient::pollEvent(int channel, gvfg_event_t *event, uint32_t timeoutMs) { return gvfg_poll_channel_event(handle_, channel, event, timeoutMs); } +gvfg_status_t GvfgClient::getSignalStatus(int channel, gvfg_signal_status_t *status) const { return gvfg_get_channel_signal_status(handle_, channel, status); } +gvfg_status_t GvfgClient::getRuntimeInfo(int channel, gvfg_runtime_info_t *info) const { return gvfg_get_channel_runtime_info(handle_, channel, info); } +gvfg_status_t GvfgClient::getLastError(int channel, char *message, uint32_t messageSize) const { return gvfg_get_channel_last_error_detail(handle_, channel, message, messageSize); } +gvfg_status_t GvfgClient::getDebugStats(int channel, gvfg_debug_backend_stats_t *stats) const { return gvfg_debug_get_channel_backend_stats(handle_, channel, stats); } + +namespace gvfg_api +{ +int enumerateDevices(gvfg_device_info_t *devices, int capacity) { return gvfg_enumerate_devices(devices, capacity); } +const char *version() { return gvfg_get_version(); } +const char *pixelFormatName(int format) { return gvfg_pixel_format_name(format); } +const char *statusText(gvfg_status_t status) { return gvfg_strerror(status); } + +gvfg_preview_status_t previewCreate(gvfg_preview_handle *handle) { return gvfg_preview_create(handle); } +gvfg_preview_status_t previewDestroy(gvfg_preview_handle handle) { return gvfg_preview_destroy(handle); } +gvfg_preview_status_t previewAttachWindow(gvfg_preview_handle handle, void *window) { return gvfg_preview_attach_window(handle, window); } +gvfg_preview_status_t previewPrepare(gvfg_preview_handle handle, int width, int height, int bitDepth) { return gvfg_preview_prepare(handle, width, height, bitDepth); } +gvfg_preview_status_t previewRenderFrame(gvfg_preview_handle handle, const gvfg_preview_frame_t *frame) { return gvfg_preview_render_frame(handle, frame); } +gvfg_preview_status_t previewClear(gvfg_preview_handle handle) { return gvfg_preview_clear(handle); } +gvfg_preview_status_t previewWaitIdle(gvfg_preview_handle handle, uint32_t timeoutMs) { return gvfg_preview_wait_idle(handle, timeoutMs); } +gvfg_preview_status_t previewGetInfo(gvfg_preview_handle handle, gvfg_preview_info_t *info) { return gvfg_preview_get_info(handle, info); } +gvfg_preview_status_t previewGetStats(gvfg_preview_handle handle, gvfg_preview_stats_t *stats) { return gvfg_preview_get_stats(handle, stats); } +gvfg_preview_status_t previewGetDeliveryStats(gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *stats) { return gvfg_preview_get_delivery_stats(handle, stats); } +const char *previewStatusText(gvfg_preview_status_t status) { return gvfg_preview_strerror(status); } +} diff --git a/GVFG_Qt_Sample/gvfg_api.h b/GVFG_Qt_Sample/gvfg_api.h new file mode 100644 index 0000000..b60b07e --- /dev/null +++ b/GVFG_Qt_Sample/gvfg_api.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include + +class GvfgClient final +{ +public: + GvfgClient() = default; + ~GvfgClient(); + GvfgClient(const GvfgClient &) = delete; + GvfgClient &operator=(const GvfgClient &) = delete; + + bool valid() const { return handle_ != nullptr; } + gvfg_status_t create(); + gvfg_status_t destroy(); + gvfg_status_t openChannel(int device, int channel); + gvfg_status_t setZeroCopy(int channel, int enabled); + gvfg_status_t setVideoFormat(int channel, gvfg_pixel_format_t format); + gvfg_status_t setAudioEnabled(int channel, int enabled); + gvfg_status_t getAudioFormat(int channel, gvfg_audio_format_t *format) const; + gvfg_status_t startChannel(int channel); + gvfg_status_t stopChannel(int channel); + gvfg_status_t readFrame(int channel, gvfg_frame_t *frame, uint32_t timeoutMs); + gvfg_status_t releaseFrame(int channel, const gvfg_frame_t *frame); + gvfg_status_t readAudioFrame(int channel, gvfg_audio_frame_t *frame, uint32_t timeoutMs); + gvfg_status_t releaseAudioFrame(int channel, const gvfg_audio_frame_t *frame); + gvfg_status_t pollEvent(int channel, gvfg_event_t *event, uint32_t timeoutMs); + gvfg_status_t getSignalStatus(int channel, gvfg_signal_status_t *status) const; + gvfg_status_t getRuntimeInfo(int channel, gvfg_runtime_info_t *info) const; + gvfg_status_t getLastError(int channel, char *message, uint32_t messageSize) const; + gvfg_status_t getDebugStats(int channel, gvfg_debug_backend_stats_t *stats) const; + +private: + gvfg_handle handle_ = nullptr; +}; + +// This namespace is the only application module that calls the public GVFG C +// ABI directly. UI and capture-control code depend on these adapters instead. +namespace gvfg_api +{ +int enumerateDevices(gvfg_device_info_t *devices, int capacity); +const char *version(); +const char *pixelFormatName(int format); +const char *statusText(gvfg_status_t status); + +gvfg_preview_status_t previewCreate(gvfg_preview_handle *handle); +gvfg_preview_status_t previewDestroy(gvfg_preview_handle handle); +gvfg_preview_status_t previewAttachWindow(gvfg_preview_handle handle, void *window); +gvfg_preview_status_t previewPrepare(gvfg_preview_handle handle, int width, int height, int bitDepth); +gvfg_preview_status_t previewRenderFrame(gvfg_preview_handle handle, const gvfg_preview_frame_t *frame); +gvfg_preview_status_t previewClear(gvfg_preview_handle handle); +gvfg_preview_status_t previewWaitIdle(gvfg_preview_handle handle, uint32_t timeoutMs); +gvfg_preview_status_t previewGetInfo(gvfg_preview_handle handle, gvfg_preview_info_t *info); +gvfg_preview_status_t previewGetStats(gvfg_preview_handle handle, gvfg_preview_stats_t *stats); +gvfg_preview_status_t previewGetDeliveryStats(gvfg_preview_handle handle, gvfg_preview_delivery_stats_t *stats); +const char *previewStatusText(gvfg_preview_status_t status); +} diff --git a/GVFG_Qt_Sample/mainwindow.cpp b/GVFG_Qt_Sample/mainwindow.cpp index f57747d..0420d35 100644 --- a/GVFG_Qt_Sample/mainwindow.cpp +++ b/GVFG_Qt_Sample/mainwindow.cpp @@ -1,1624 +1,197 @@ #include "mainwindow.h" +#include "capture_controller.h" +#include "gvfg_api.h" #include "previewwindow.h" #include "ui_mainwindow.h" -#include - #include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include -#include -#include - -#include -#include -#include -#include -#include - -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include namespace { - constexpr bool kChannel1UiVisible = false; - constexpr size_t kMaxQueuedAudioFrames = 10; +constexpr bool kChannel1UiVisible = false; - QString logFilePrefix() +class LogHighlighter final : public QSyntaxHighlighter +{ +public: + explicit LogHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { -#if GVFG_INTERNAL_DIAGNOSTICS - return QStringLiteral("gvfg_qt_preview_debug"); -#else - return QStringLiteral("gvfg_qt_preview"); -#endif + 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); } - - class LogHighlighter final : public QSyntaxHighlighter +protected: + void highlightBlock(const QString &text) override { - public: - explicit LogHighlighter(QTextDocument *document) - : QSyntaxHighlighter(document) - { - errorFormat_.setForeground(QColor(200, 0, 0)); - errorFormat_.setFontWeight(QFont::Bold); - recoveryFormat_.setForeground(QColor(0, 128, 0)); - recoveryFormat_.setFontWeight(QFont::Bold); - warningFormat_.setForeground(QColor(190, 110, 0)); - warningFormat_.setFontWeight(QFont::Bold); - } - - protected: - void highlightBlock(const QString &text) override - { - if (text.contains(QStringLiteral("SIGNAL_DISCONNECTED")) || - text.contains(QStringLiteral("failed"), Qt::CaseInsensitive) || - text.contains(QStringLiteral("error"), Qt::CaseInsensitive)) - { - setFormat(0, text.size(), errorFormat_); - return; - } - - if (text.contains(QStringLiteral("warning"), Qt::CaseInsensitive)) - { - setFormat(0, text.size(), warningFormat_); - return; - } - - if (text.contains(QStringLiteral("SIGNAL_CONNECTED")) || - text.contains(QStringLiteral("recovered"), Qt::CaseInsensitive)) - setFormat(0, text.size(), recoveryFormat_); - } - - private: - QTextCharFormat errorFormat_; - QTextCharFormat recoveryFormat_; - QTextCharFormat warningFormat_; - }; - -#if GVFG_INTERNAL_DIAGNOSTICS - QString boolText(int value) - { - return value ? QStringLiteral("yes") : QStringLiteral("no"); - } - - QString valueOrDash(uint64_t value) - { - return QString::number(static_cast(value)); - } - - QString captureStatusText(const gvfg_debug_backend_stats_t &stats, bool signalConnected) - { - if (!stats.backend_running) - return QStringLiteral("stopped"); - if (!signalConnected) - return QStringLiteral("waiting_signal"); - if (!stats.backend_capture_active) - return QStringLiteral("paused"); - return QStringLiteral("streaming"); - } - -#endif - - QString frameText(bool valid, int width, int height, const char *pixelFormat, int bitDepth) - { - if (!valid || width <= 0 || height <= 0) - return QStringLiteral("--"); - - const QString format = pixelFormat && pixelFormat[0] != '\0' - ? QString::fromUtf8(pixelFormat) - : QStringLiteral("--"); - const QString bit = bitDepth > 0 ? QString::number(bitDepth) : QStringLiteral("--"); - return QStringLiteral("%1x%2 %3 %4-bit").arg(width).arg(height).arg(format, bit); - } - - QString signalFrameText(const gvfg_signal_status_t &signal) - { - if (!signal.connected) - return QStringLiteral("No signal"); - - const QString resolution = (signal.width > 0 && signal.height > 0) - ? QStringLiteral("%1x%2").arg(signal.width).arg(signal.height) - : QStringLiteral("--"); - const QString format = signal.pixel_format != GVFG_PIXFMT_UNKNOWN - ? QString::fromLatin1(gvfg_pixel_format_name(signal.pixel_format)) - : QStringLiteral("--"); - const QString bit = signal.bit_depth > 0 ? QString::number(signal.bit_depth) : QStringLiteral("--"); - return QStringLiteral("%1 %2 %3-bit").arg(resolution, format, bit); - } - - QString channelLastError(gvfg_handle handle, int channel) - { - char message[512] = {}; - if (gvfg_get_channel_last_error_detail(handle, channel, message, sizeof(message)) != GVFG_OK || message[0] == '\0') - return {}; - return QString::fromUtf8(message); - } - - QString eventTypeText(gvfg_event_type_t type) - { - switch (type) - { - case GVFG_EVENT_SIGNAL_CONNECTED: - return QStringLiteral("SIGNAL_CONNECTED"); - case GVFG_EVENT_SIGNAL_DISCONNECTED: - return QStringLiteral("SIGNAL_DISCONNECTED"); - case GVFG_EVENT_STREAM_READY: - return QStringLiteral("STREAM_READY"); - case GVFG_EVENT_FORMAT_CHANGE_BEGIN: - return QStringLiteral("FORMAT_CHANGE_BEGIN"); - default: - return QStringLiteral("UNKNOWN"); - } + if (text.contains(QStringLiteral("SIGNAL_DISCONNECTED")) || + 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("SIGNAL_CONNECTED")) || + 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) + : QWidget(parent), ui_(new Ui::MainWindow), controller_(new CaptureController(this)) { ui_->setupUi(this); #if GVFG_INTERNAL_DIAGNOSTICS - setWindowTitle(QStringLiteral("GVFG Internal Diagnostic - SDK v%1") - .arg(QString::fromLatin1(gvfg_get_version()))); + setWindowTitle(QStringLiteral("GVFG Internal Diagnostic - SDK v%1").arg(controller_->sdkVersion())); #else - setWindowTitle(QStringLiteral("GVFG Preview Sample - SDK v%1") - .arg(QString::fromLatin1(gvfg_get_version()))); + setWindowTitle(QStringLiteral("GVFG Preview Sample - SDK v%1").arg(controller_->sdkVersion())); #endif - previewWindows_[GVFG_CHANNEL_0] = new PreviewWindow(); - previewWindows_[GVFG_CHANNEL_1] = new PreviewWindow(); - previewWindows_[GVFG_CHANNEL_0]->setWindowTitle(QStringLiteral("GVFG Preview - CH0")); - previewWindows_[GVFG_CHANNEL_1]->setWindowTitle(QStringLiteral("GVFG Preview - CH1")); - for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel) - { - connect(previewWindows_[channel], &PreviewWindow::previewVisibilityChanged, - this, [this, channel](bool visible) { - channels_[channel].previewVisible.store(visible, std::memory_order_release); - }); - } ui_->logEdit->setMaximumBlockCount(300); new LogHighlighter(ui_->logEdit->document()); ui_->statusLabel->setWordWrap(true); - runtimeStatusTimer_ = new QTimer(this); - runtimeStatusTimer_->setInterval(200); - openLogFile(); - connect(ui_->refreshButton, &QPushButton::clicked, this, [this]() - { refreshDevices(); }); - connect(ui_->openButton, &QPushButton::clicked, this, [this]() - { - if (handle_) - closeDevice(); - else - openDevice(); }); - connect(ui_->ch0PreviewButton, &QPushButton::clicked, this, [this]() - { showPreviewWindow(GVFG_CHANNEL_0); }); - connect(ui_->ch1PreviewButton, &QPushButton::clicked, this, [this]() - { showPreviewWindow(GVFG_CHANNEL_1); }); - connect(ui_->ch0FullscreenButton, &QPushButton::clicked, this, [this]() - { showFullscreenPreviewWindow(GVFG_CHANNEL_0); }); - connect(ui_->ch1FullscreenButton, &QPushButton::clicked, this, [this]() - { showFullscreenPreviewWindow(GVFG_CHANNEL_1); }); - connect(ui_->ch0StartButton, &QPushButton::clicked, this, [this]() - { startCapture(GVFG_CHANNEL_0); }); - connect(ui_->ch1StartButton, &QPushButton::clicked, this, [this]() - { startCapture(GVFG_CHANNEL_1); }); - connect(ui_->ch0OutputFormatCombo, &QComboBox::currentIndexChanged, this, [this](int) - { - updateOutputFormatOptions(GVFG_CHANNEL_0); - if (channels_[GVFG_CHANNEL_0].opened && - !channels_[GVFG_CHANNEL_0].running.load(std::memory_order_acquire)) - { - applyOutputFormat(GVFG_CHANNEL_0); - updateSignalStatus(); - } }); - connect(ui_->ch1OutputFormatCombo, &QComboBox::currentIndexChanged, this, [this](int) - { - updateOutputFormatOptions(GVFG_CHANNEL_1); - if (channels_[GVFG_CHANNEL_1].opened && - !channels_[GVFG_CHANNEL_1].running.load(std::memory_order_acquire)) - { - applyOutputFormat(GVFG_CHANNEL_1); - updateSignalStatus(); - } }); - connect(ui_->ch0StopButton, &QPushButton::clicked, this, [this]() - { stopCapture(GVFG_CHANNEL_0); }); - connect(ui_->ch1StopButton, &QPushButton::clicked, this, [this]() - { stopCapture(GVFG_CHANNEL_1); }); - connect(runtimeStatusTimer_, &QTimer::timeout, this, [this]() - { - processPendingEvents(); - updateSignalStatus(false); }); + 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); }); + } + + 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::logMessage, this, &MainWindow::appendLogLine); + connect(controller_, &CaptureController::errorOccurred, this, &MainWindow::showError); + 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(); }); + connect(controller_, &CaptureController::previewCloseRequested, this, + [this](int channel) { previewWindows_[channel]->closePreview(); }); + + connect(ui_->refreshButton, &QPushButton::clicked, controller_, &CaptureController::refreshDevices); + connect(ui_->openButton, &QPushButton::clicked, this, [this] { + if (controller_->deviceOpen()) controller_->closeDevice(); + else { controller_->setSelectedDeviceIndex(ui_->deviceCombo->currentData().toInt()); controller_->openDevice(); } + }); + 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); + if (controller_->channelOpened(channel) && !controller_->channelRunning(channel)) + { controller_->applyOutputFormat(channel); controller_->updateSignalStatus(); } + }; + connect(ui_->ch0OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(0); }); + connect(ui_->ch1OutputFormatCombo, &QComboBox::currentIndexChanged, this, [formatChanged](int) { formatChanged(1); }); updateOutputFormatOptions(); updateUiState(); - appendLog(QStringLiteral("GVFG SDK version | %1") - .arg(QString::fromLatin1(gvfg_get_version()))); - appendLog(logFile_.isOpen() - ? QStringLiteral("Log file | %1").arg(logFilePath_) - : QStringLiteral("Log file unavailable | %1").arg(logFilePath_)); - refreshDevices(); + appendLogLine(QStringLiteral("GVFG SDK version | %1").arg(controller_->sdkVersion())); + controller_->refreshDevices(); } MainWindow::~MainWindow() { - closeDevice(); - delete previewWindows_[GVFG_CHANNEL_0]; - delete previewWindows_[GVFG_CHANNEL_1]; + controller_->closeDevice(); + delete previewWindows_[0]; + delete previewWindows_[1]; delete ui_; } -QWidget *createMainWindow() -{ - return new MainWindow(); -} +QWidget *createMainWindow() { return new MainWindow(); } void MainWindow::closeEvent(QCloseEvent *event) { - closeDevice(); - for (PreviewWindow *window : previewWindows_) - if (window) - window->closePreview(); - + controller_->closeDevice(); + for (PreviewWindow *window : previewWindows_) if (window) window->closePreview(); QWidget::closeEvent(event); } -void MainWindow::refreshDevices() +void MainWindow::syncControllerOptions(int channel) { - if (handle_) - closeDevice(); - - ui_->deviceCombo->clear(); - devices_ = {}; - - const int count = gvfg_enumerate_devices(devices_.data(), GVFG_MAX_DEVICES); - deviceCount_ = count > 0 ? count : 0; - - for (int i = 0; i < deviceCount_; ++i) - { - const QString name = QString::fromUtf8(devices_[i].name); - const QString displayName = name.isEmpty() ? QStringLiteral("GVFG Capture") : name; - ui_->deviceCombo->addItem(displayName, i); - } - - if (deviceCount_ <= 0) - { - ui_->deviceCombo->addItem(QStringLiteral("No GVFG device found"), -1); - appendLog(QStringLiteral("No GVFG device found")); - } - else - { - appendLog(QStringLiteral("Found %1 GVFG capture device(s)").arg(deviceCount_)); - } + 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) +void MainWindow::showPreviewWindow(int channel, bool fullscreen) { - ChannelRuntime &runtime = channels_[channel]; - if (!runtime.running.load(std::memory_order_acquire) || - !runtime.frameAvailable.load(std::memory_order_acquire)) - return; - - if (runtime.haveCachedSignalStatus) - updatePreviewSourceSize(channel, runtime.cachedSignalStatus); - previewWindows_[channel]->showPreview(); - - if (handle_ && !applyPreview(channel)) - appendLog(QStringLiteral("CH%1 Show Preview failed: unable to update preview window").arg(channel)); -} - -void MainWindow::showFullscreenPreviewWindow(int channel) -{ - ChannelRuntime &runtime = channels_[channel]; - if (!runtime.running.load(std::memory_order_acquire) || - !runtime.frameAvailable.load(std::memory_order_acquire)) - return; - - if (runtime.haveCachedSignalStatus) - updatePreviewSourceSize(channel, runtime.cachedSignalStatus); - previewWindows_[channel]->showFullscreenPreview(); - - if (handle_ && !applyPreview(channel)) - appendLog(QStringLiteral("CH%1 Fullscreen Preview failed: unable to update preview window").arg(channel)); -} - -bool MainWindow::openDevice() -{ - if (handle_) - return true; - - if (ui_->deviceCombo->currentData().toInt() < 0) - { - appendLog(QStringLiteral("Open skipped: no device selected")); - return false; - } - - gvfg_status_t st = gvfg_create(&handle_); - if (st != GVFG_OK || !handle_) - { - showError(QStringLiteral("gvfg_create"), st); - handle_ = nullptr; - updateUiState(); - return false; - } - - selectedDeviceIndex_ = ui_->deviceCombo->currentData().toInt(); - - lastSignalStatusText_.clear(); - appendLog(QStringLiteral("Created device session for index %1").arg(selectedDeviceIndex_)); - runtimeStatusTimer_->start(); - updateSignalStatus(false); - updateUiState(); - return true; -} - -bool MainWindow::openChannel(int channel) -{ - ChannelRuntime &runtime = channels_[channel]; - if (runtime.opened) - return applyOutputFormat(channel); - if (!handle_ && !openDevice()) - return false; - - const bool zeroCopyEnabled = channel == GVFG_CHANNEL_0 - ? ui_->ch0ZeroCopyCheckBox->isChecked() - : ui_->ch1ZeroCopyCheckBox->isChecked(); - gvfg_status_t status = gvfg_set_channel_zero_copy_enabled( - handle_, channel, zeroCopyEnabled ? 1 : 0); - if (status != GVFG_OK) - { - showError(QStringLiteral("gvfg_set_channel_zero_copy_enabled"), status, channel); - return false; - } - status = gvfg_open_channel(handle_, selectedDeviceIndex_, channel); - if (status != GVFG_OK) - { - showError(QStringLiteral("gvfg_open_channel"), status, channel); - return false; - } - runtime.opened = true; - if (!applyOutputFormat(channel)) - return false; - - appendLog(QStringLiteral("Opened device index %1 CH%2 | mode=%3") - .arg(selectedDeviceIndex_) - .arg(channel) - .arg(zeroCopyEnabled ? QStringLiteral("zero-copy") : QStringLiteral("copy"))); - updateSignalStatus(); - return true; -} - -void MainWindow::closeDevice() -{ - if (runtimeStatusTimer_) - runtimeStatusTimer_->stop(); - - stopAllCaptures(); - for (ChannelRuntime &channel : channels_) - { - if (channel.previewHandle) - { - gvfg_preview_destroy(channel.previewHandle); - channel.previewHandle = nullptr; - } - } - - if (handle_) - { - gvfg_destroy(handle_); - handle_ = nullptr; - appendLog(QStringLiteral("Closed device")); - } - - ui_->statusLabel->setText(QStringLiteral("Idle")); - lastSignalStatusText_.clear(); - selectedDeviceIndex_ = -1; - for (ChannelRuntime &channel : channels_) - { - channel.opened = false; - channel.cachedSignalStatus = {}; - channel.haveCachedSignalStatus = false; - channel.lastLoggedInputStatus.clear(); - } - updateUiState(); -} - -bool MainWindow::applyOutputFormat(int channel) -{ - if (!handle_ || !channels_[channel].opened || - channels_[channel].running.load(std::memory_order_acquire)) - return false; - - const int formatIndex = channel == GVFG_CHANNEL_0 - ? ui_->ch0OutputFormatCombo->currentIndex() - : ui_->ch1OutputFormatCombo->currentIndex(); - const gvfg_pixel_format_t format = formatIndex == 1 - ? GVFG_PIXFMT_Y210 - : GVFG_PIXFMT_YUY2; - const gvfg_status_t status = gvfg_set_channel_video_format(handle_, channel, format); - if (status != GVFG_OK) - { - showError(QStringLiteral("set output format register"), status, channel); - return false; - } - appendLog(QStringLiteral("CH%1 Output format | %2") - .arg(channel) - .arg(format == GVFG_PIXFMT_Y210 ? QStringLiteral("Y210") : QStringLiteral("YUY2"))); - return true; + 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_->applyPreview(channel); } void MainWindow::updateOutputFormatOptions(int changedChannel) { QComboBox *combos[] = {ui_->ch0OutputFormatCombo, ui_->ch1OutputFormatCombo}; - constexpr int kY210Index = 1; - - if ((changedChannel == GVFG_CHANNEL_0 || changedChannel == GVFG_CHANNEL_1) && - combos[changedChannel]->currentIndex() == kY210Index) + constexpr int y210 = 1; + if ((changedChannel == 0 || changedChannel == 1) && combos[changedChannel]->currentIndex() == y210) { - const int otherChannel = changedChannel == GVFG_CHANNEL_0 - ? GVFG_CHANNEL_1 - : GVFG_CHANNEL_0; - if (combos[otherChannel]->currentIndex() == kY210Index) - combos[otherChannel]->setCurrentIndex(0); + const int other = changedChannel == 0 ? 1 : 0; + if (combos[other]->currentIndex() == y210) combos[other]->setCurrentIndex(0); } - - const bool ch0UsesY210 = combos[GVFG_CHANNEL_0]->currentIndex() == kY210Index; - const bool ch1UsesY210 = combos[GVFG_CHANNEL_1]->currentIndex() == kY210Index; - const bool y210Enabled[] = {!ch1UsesY210, !ch0UsesY210}; - - for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel) + const bool enabled[] = {combos[1]->currentIndex() != y210, combos[0]->currentIndex() != y210}; + for (int channel = 0; channel < 2; ++channel) { auto *model = qobject_cast(combos[channel]->model()); - if (model && model->item(kY210Index)) - model->item(kY210Index)->setEnabled(y210Enabled[channel]); - - combos[channel]->setToolTip(y210Enabled[channel] - ? QStringLiteral("Requested CH%1 capture output format").arg(channel) - : QStringLiteral("Y210 is already selected by the other channel")); + if (model && model->item(y210)) model->item(y210)->setEnabled(enabled[channel]); } } -void MainWindow::startCapture(int channelIndex) -{ - ChannelRuntime &channel = channels_[channelIndex]; - if (channel.running.load(std::memory_order_acquire)) - return; - - if (!openChannel(channelIndex)) - return; - - // Consume queued signal events first. gvfg_start_channel() performs the - // single authoritative hardware revalidation; preview setup reuses the - // most recent UI cache instead of issuing another register query here. - processPendingEvents(); - if (!channel.haveCachedSignalStatus || !channel.cachedSignalStatus.connected) - { - appendLog(QStringLiteral("CH%1 Start skipped: no input signal").arg(channelIndex)); - return; - } - - const bool audioEnabled = channelIndex == GVFG_CHANNEL_0 && ui_->ch0AudioCheckBox->isChecked(); - gvfg_status_t st = gvfg_set_channel_audio_enabled(handle_, channelIndex, audioEnabled ? 1 : 0); - if (st != GVFG_OK) - { - showError(QStringLiteral("gvfg_set_channel_audio_enabled"), st, channelIndex); - return; - } - channel.audioFormat = {}; - if (audioEnabled) - { - st = gvfg_get_channel_audio_format(handle_, channelIndex, &channel.audioFormat); - if (st != GVFG_OK) - { - showError(QStringLiteral("gvfg_get_channel_audio_format"), st, channelIndex); - return; - } - if (channel.audioFormat.channels == 0 || channel.audioFormat.sample_rate == 0 || - (channel.audioFormat.bits_per_sample != 8 && - channel.audioFormat.bits_per_sample != 16 && - channel.audioFormat.bits_per_sample != 32)) - { - appendLog(QStringLiteral("CH%1 Audio format unsupported by Qt playback | %2 Hz %3 ch %4-bit") - .arg(channelIndex) - .arg(channel.audioFormat.sample_rate) - .arg(channel.audioFormat.channels) - .arg(channel.audioFormat.bits_per_sample)); - return; - } - } - - channel.frameAvailable.store(false, std::memory_order_release); - updatePreviewSourceSize(channelIndex, channel.cachedSignalStatus); - previewWindows_[channelIndex]->showPreview(); - if (!applyPreview(channelIndex)) - { - previewWindows_[channelIndex]->closePreview(); - return; - } - - if (gvfg_preview_prepare(channel.previewHandle, - channel.cachedSignalStatus.width, - channel.cachedSignalStatus.height, - channel.cachedSignalStatus.bit_depth) != GVFG_PREVIEW_OK) - { - appendLog(QStringLiteral("CH%1 Preview prewarm failed; first frame may initialize GPU resources").arg(channelIndex)); - } - -#if GVFG_INTERNAL_DIAGNOSTICS - appendLog(QStringLiteral("FPGA signal before stream start")); -#endif - - if (gvfg_preview_wait_idle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK) - { - appendLog(QStringLiteral("CH%1 Preview still busy from previous run; retry Start after it completes.").arg(channelIndex)); - return; - } - channel.startupStartTime = std::chrono::steady_clock::now(); - st = gvfg_start_channel(handle_, channelIndex); - const auto startupStartCallEnd = std::chrono::steady_clock::now(); - channel.startupStartCallMs = - std::chrono::duration( - startupStartCallEnd - channel.startupStartTime) - .count(); - if (st != GVFG_OK) - { - showError(QStringLiteral("gvfg_start_channel"), st, channelIndex); - previewWindows_[channelIndex]->closePreview(); - updateSignalStatus(); - updateUiState(); - return; - } - - channel.previewFailureCount = 0; - channel.getFrameAverageMs.store(0.0, std::memory_order_relaxed); - channel.getFrameMaximumMs.store(0.0, std::memory_order_relaxed); - channel.getFrameWindowMaximumMs.store(0.0, std::memory_order_relaxed); - channel.getFrameSamples.store(0, std::memory_order_relaxed); - channel.audioEnabled = audioEnabled; - channel.videoReceived = 0; channel.videoSubmitted = 0; - channel.videoSkipped = 0; channel.videoFailed = 0; - channel.videoIdGaps = 0; channel.videoIdResets = 0; - channel.videoLastId = 0; - channel.lastLoggedVideoIssues = channel.lastLoggedAudioIssues = 0; - channel.lastDeliveryLogMs = 0; - channel.previewBaseline = {}; - gvfg_preview_get_delivery_stats(channel.previewHandle, &channel.previewBaseline); - { - std::lock_guard lock(channel.audioQueueMutex); - channel.audioQueue.clear(); - channel.audioReceivedFrames = 0; - channel.audioReceivedBytes = channel.audioAcceptedBytes = channel.audioQueuedBytes = 0; - channel.audioDroppedBytes = channel.audioCancelledBytes = 0; - channel.audioFailedBytes = channel.audioIdGaps = channel.audioIdResets = 0; - channel.audioLastId = 0; - } -#if GVFG_INTERNAL_DIAGNOSTICS - channel.haveDebugBaseline = false; - channel.lastDebugDmaErrors = 0; -#endif - channel.signalConnected.store(channel.cachedSignalStatus.connected != 0, - std::memory_order_release); - channel.stopRequested.store(false, std::memory_order_release); - channel.running.store(true, std::memory_order_release); - channel.captureThreadExited.store(false, std::memory_order_release); - channel.captureThread = std::thread([this, channelIndex]() - { captureReadLoop(channelIndex); }); - if (audioEnabled) - { - channel.audioPlaybackThread = std::thread([this, channelIndex]() - { audioPlaybackLoop(channelIndex); }); - channel.audioThread = std::thread([this, channelIndex]() - { audioReadLoop(channelIndex); }); - } - updateUiState(); - appendLog(audioEnabled - ? QStringLiteral("CH%1 Started video + audio | %2 Hz %3 ch %4-bit") - .arg(channelIndex) - .arg(channel.audioFormat.sample_rate) - .arg(channel.audioFormat.channels) - .arg(channel.audioFormat.bits_per_sample) - : QStringLiteral("CH%1 Started video-only").arg(channelIndex)); - updateSignalStatus(false); -} - -void MainWindow::stopCapture(int channelIndex) -{ - ChannelRuntime &channel = channels_[channelIndex]; - if (handle_ && channel.running.load(std::memory_order_acquire)) - { - channel.stopRequested.store(true, std::memory_order_release); - channel.signalReady.notify_all(); - channel.audioQueueReady.notify_all(); - joinCaptureThread(channelIndex); - joinAudioThread(channelIndex); - if (gvfg_preview_wait_idle(channel.previewHandle, 2000) != GVFG_PREVIEW_OK) - appendLog(QStringLiteral("CH%1 Preview drain timed out; remaining in_flight is not counted as lost.").arg(channelIndex)); - logDeliveryStatus(channelIndex, true); - gvfg_stop_channel(handle_, channelIndex); - channel.running.store(false, std::memory_order_release); - channel.frameAvailable.store(false, std::memory_order_release); - channel.audioEnabled = false; - if (previewWindows_[channelIndex]) - previewWindows_[channelIndex]->closePreview(); - appendLog(QStringLiteral("CH%1 Stopped capture").arg(channelIndex)); - updateSignalStatus(); - } - - channel.frameAvailable.store(false, std::memory_order_release); - updateUiState(); -} - -void MainWindow::stopAllCaptures() -{ - stopCapture(GVFG_CHANNEL_0); - stopCapture(GVFG_CHANNEL_1); -} - -bool MainWindow::applyPreview(int channelIndex) -{ - ChannelRuntime &channel = channels_[channelIndex]; - if (!channel.previewHandle) - { - const gvfg_preview_status_t st = gvfg_preview_create(&channel.previewHandle); - if (st != GVFG_PREVIEW_OK || !channel.previewHandle) - { - appendLog(QStringLiteral("CH%1 Preview setup failed: %2") - .arg(channelIndex) - .arg(QString::fromUtf8(gvfg_preview_strerror(st)))); - channel.previewHandle = nullptr; - return false; - } - } - - const gvfg_preview_status_t st = gvfg_preview_attach_window( - channel.previewHandle, previewWindows_[channelIndex]->nativePreviewHandle()); - if (st != GVFG_PREVIEW_OK) - { - appendLog(QStringLiteral("CH%1 Preview setup failed: %2") - .arg(channelIndex) - .arg(QString::fromUtf8(gvfg_preview_strerror(st)))); - return false; - } - return true; -} - -void MainWindow::updatePreviewSourceSize(int channel, const gvfg_signal_status_t &signal) -{ - if (signal.width > 0 && signal.height > 0) - previewWindows_[channel]->setSourceSize(signal.width, signal.height); -} - -void MainWindow::processPendingEvents() -{ - if (!handle_) - return; - - for (int channel = GVFG_CHANNEL_0; channel <= GVFG_CHANNEL_1; ++channel) - { - if (!channels_[channel].opened) - continue; - gvfg_event_t event{}; - event.struct_size = sizeof(event); - while (gvfg_poll_channel_event(handle_, channel, &event, 0) == GVFG_OK) - { - const auto eventType = static_cast(event.type); - if (eventType != GVFG_EVENT_STREAM_READY) - appendLog(QStringLiteral("CH%1 EVENT %2").arg(channel).arg(eventTypeText(eventType))); - - if (eventType == GVFG_EVENT_SIGNAL_CONNECTED || - eventType == GVFG_EVENT_SIGNAL_DISCONNECTED || - eventType == GVFG_EVENT_FORMAT_CHANGE_BEGIN || - eventType == GVFG_EVENT_STREAM_READY) - updateSignalStatus(); - - if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED) - channels_[channel].signalConnected.store(false, std::memory_order_release); - else if (eventType == GVFG_EVENT_SIGNAL_CONNECTED || - eventType == GVFG_EVENT_STREAM_READY) - { - channels_[channel].signalConnected.store(true, std::memory_order_release); - channels_[channel].signalReady.notify_all(); - } - - if (eventType == GVFG_EVENT_SIGNAL_DISCONNECTED && channels_[channel].previewHandle) - gvfg_preview_clear(channels_[channel].previewHandle); - - event = {}; - event.struct_size = sizeof(event); - } - } -} - -void MainWindow::updateSignalStatus(bool queryHardware) -{ - if (!handle_) - return; - - QStringList statusLines; -#if GVFG_INTERNAL_DIAGNOSTICS - bool diagnosticProblemDetected = false; -#endif - for (int channelIndex = GVFG_CHANNEL_0; channelIndex <= GVFG_CHANNEL_1; ++channelIndex) - { - if (channelIndex == GVFG_CHANNEL_1 && !kChannel1UiVisible) - continue; - - ChannelRuntime &channel = channels_[channelIndex]; - if (!channel.opened) - { - const bool zeroCopy = channelIndex == GVFG_CHANNEL_0 - ? ui_->ch0ZeroCopyCheckBox->isChecked() - : ui_->ch1ZeroCopyCheckBox->isChecked(); - statusLines << QStringLiteral("CH%1 | Not opened | %2") - .arg(channelIndex) - .arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy")); - continue; - } - if (queryHardware) - { - gvfg_signal_status_t signal{}; - if (gvfg_get_channel_signal_status(handle_, channelIndex, &signal) == GVFG_OK) - { - channel.cachedSignalStatus = signal; - channel.haveCachedSignalStatus = true; - } - } - if (!channel.haveCachedSignalStatus) - { - statusLines << QStringLiteral("CH%1 | Signal unavailable").arg(channelIndex); - continue; - } - - const gvfg_signal_status_t &signal = channel.cachedSignalStatus; - const QString inputStatus = signal.connected - ? QStringLiteral("CH%1 Connected | %2").arg(channelIndex).arg(signalFrameText(signal)) - : QStringLiteral("CH%1 No signal").arg(channelIndex); - if (inputStatus != channel.lastLoggedInputStatus) - { - appendLog(QStringLiteral("Input status | %1").arg(inputStatus)); - channel.lastLoggedInputStatus = inputStatus; - } - if (previewWindows_[channelIndex]->isVisible()) - updatePreviewSourceSize(channelIndex, signal); - - gvfg_preview_info_t previewInfo{}; - const bool previewInfoOk = channel.previewHandle && - gvfg_preview_get_info(channel.previewHandle, &previewInfo) == GVFG_PREVIEW_OK && - previewInfo.active; - gvfg_preview_stats_t previewStats{}; - const bool previewStatsOk = channel.previewHandle && - gvfg_preview_get_stats(channel.previewHandle, &previewStats) == GVFG_PREVIEW_OK; - const QString previewFps = previewStatsOk && previewStats.present_fps > 0.0 - ? QString::number(previewStats.present_fps, 'f', 2) - : QStringLiteral("--"); - const QString previewFrame = previewInfoOk - ? frameText(true, previewInfo.width, previewInfo.height, - previewInfo.pixel_format, previewInfo.bit_depth) - : QStringLiteral("--"); - const bool zeroCopy = channelIndex == GVFG_CHANNEL_0 - ? ui_->ch0ZeroCopyCheckBox->isChecked() - : ui_->ch1ZeroCopyCheckBox->isChecked(); - statusLines << QStringLiteral("CH%1 | %2 | %3 | %4") - .arg(channelIndex) - .arg(channel.running.load(std::memory_order_acquire) ? QStringLiteral("Running") : QStringLiteral("Stopped")) - .arg(signalFrameText(signal)) - .arg(zeroCopy ? QStringLiteral("Zero-copy") : QStringLiteral("Copy")); - if (channel.audioEnabled) - { - uint64_t receivedFrames = 0; - { - std::lock_guard lock(channel.audioQueueMutex); - receivedFrames = channel.audioReceivedFrames; - } - statusLines << QStringLiteral("CH%1 Audio | %2 Hz %3 ch %4-bit | received=%5 frames") - .arg(channelIndex) - .arg(channel.audioFormat.sample_rate) - .arg(channel.audioFormat.channels) - .arg(channel.audioFormat.bits_per_sample) - .arg(static_cast(receivedFrames)); -#if GVFG_INTERNAL_DIAGNOSTICS - uint64_t sdkBytes = 0; - uint64_t appOutputBytes = 0; - { - std::lock_guard lock(channel.audioQueueMutex); - sdkBytes = channel.audioReceivedBytes; - appOutputBytes = channel.audioAcceptedBytes; - } - gvfg_debug_backend_stats_t audioStats{}; - if (gvfg_debug_get_channel_backend_stats(handle_, channelIndex, &audioStats) == GVFG_OK) - { - statusLines << QStringLiteral("CH%1 Audio Debug | Events DMA=%2 Extra=%3 | Driver->SDK %4 frames/%5 bytes | SDK->APP %6 frames/%7 bytes | APP->Output %8 bytes") - .arg(channelIndex) - .arg(static_cast(audioStats.audio_dma_event_wakes)) - .arg(static_cast(audioStats.extra_audio_event_wakes)) - .arg(static_cast(audioStats.audio_frames_from_driver)) - .arg(static_cast(audioStats.audio_bytes_from_driver)) - .arg(static_cast(receivedFrames)) - .arg(static_cast(sdkBytes)) - .arg(static_cast(appOutputBytes)); - } -#endif - } - statusLines << QStringLiteral("CH%1 Preview | %2 FPS | %3") - .arg(channelIndex) - .arg(previewFps, previewFrame); - logDeliveryStatus(channelIndex); - const uint64_t readSamples = channel.getFrameSamples.load(std::memory_order_relaxed); - statusLines << (readSamples >= 300 - ? QStringLiteral("CH%1 Read | avg=%2 max300=%3 max=%4 ms samples=%5") - .arg(channelIndex) - .arg(channel.getFrameAverageMs.load(std::memory_order_relaxed), 0, 'f', 3) - .arg(channel.getFrameWindowMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3) - .arg(channel.getFrameMaximumMs.load(std::memory_order_relaxed), 0, 'f', 3) - .arg(static_cast(readSamples)) - : QStringLiteral("CH%1 Read | measuring").arg(channelIndex)); - - gvfg_runtime_info_t runtimeInfo{}; - if (gvfg_get_channel_runtime_info(handle_, channelIndex, &runtimeInfo) == GVFG_OK) - { - statusLines << (runtimeInfo.driver_read_samples >= 300 - ? QStringLiteral("CH%1 %2 | avg=%3 max300=%4 max=%5 us samples=%6") - .arg(channelIndex) - .arg(runtimeInfo.zero_copy_enabled - ? QStringLiteral("ZeroCopy Acquire") - : QStringLiteral("Copy GetFrame")) - .arg(runtimeInfo.driver_read_average_us, 0, 'f', 3) - .arg(runtimeInfo.driver_read_max300_us, 0, 'f', 3) - .arg(runtimeInfo.driver_read_max_us, 0, 'f', 3) - .arg(static_cast(runtimeInfo.driver_read_samples)) - : QStringLiteral("CH%1 Driver GetFrame | measuring").arg(channelIndex)); - } - -#if GVFG_INTERNAL_DIAGNOSTICS - gvfg_debug_backend_stats_t backendStats{}; - if (gvfg_debug_get_channel_backend_stats(handle_, channelIndex, &backendStats) == GVFG_OK) - { - statusLines << QStringLiteral("CH%1 Capture | status=%2 dma_errors=%3 no_frame_waits=%4") - .arg(channelIndex) - .arg(captureStatusText(backendStats, signal.connected != 0)) - .arg(static_cast(backendStats.backend_dma_errors)) - .arg(static_cast(backendStats.backend_wait_timeouts)); - if (channel.haveDebugBaseline && backendStats.backend_dma_errors > channel.lastDebugDmaErrors) - { - appendLog(QStringLiteral("CH%1 ERROR DMA failures +%2, total=%3") - .arg(channelIndex) - .arg(valueOrDash(backendStats.backend_dma_errors - channel.lastDebugDmaErrors), - valueOrDash(backendStats.backend_dma_errors))); - diagnosticProblemDetected = true; - } - channel.lastDebugDmaErrors = backendStats.backend_dma_errors; - channel.haveDebugBaseline = true; - } -#endif - } - - const QString statusText = statusLines.join(QLatin1Char('\n')); - const bool changed = lastSignalStatusText_ != statusText; - if (changed) - { - ui_->statusLabel->setText(statusText); - lastSignalStatusText_ = statusText; - } - updateUiState(); - -#if GVFG_INTERNAL_DIAGNOSTICS - if (diagnosticProblemDetected) - writeDiagnosticSnapshot(statusText); -#endif -} - void MainWindow::updateUiState() { - const bool deviceOpen = handle_ != nullptr; - const bool ch0Running = channels_[0].running.load(std::memory_order_acquire); - const bool ch1Running = channels_[1].running.load(std::memory_order_acquire); - const bool anyRunning = ch0Running || ch1Running; - const bool deviceSelected = ui_->deviceCombo->currentData().toInt() >= 0; - ui_->openButton->setText(deviceOpen ? QStringLiteral("Close Device") : QStringLiteral("Open Device")); + const bool open = controller_->deviceOpen(); + 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_->openButton->setText(open ? QStringLiteral("Close Device") : QStringLiteral("Open Device")); ui_->openButton->setEnabled(!anyRunning); - ui_->ch0StartButton->setEnabled(deviceSelected && !ch0Running); - ui_->ch1StartButton->setEnabled(deviceSelected && !ch1Running); - ui_->ch0StopButton->setEnabled(ch0Running); - ui_->ch1StopButton->setEnabled(ch1Running); - ui_->ch0PreviewButton->setEnabled(ch0Running && channels_[0].frameAvailable.load(std::memory_order_acquire)); - ui_->ch1PreviewButton->setEnabled(ch1Running && channels_[1].frameAvailable.load(std::memory_order_acquire)); + ui_->refreshButton->setEnabled(!open); ui_->deviceCombo->setEnabled(!open); + 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_->refreshButton->setEnabled(!deviceOpen); - ui_->deviceCombo->setEnabled(!deviceOpen); - ui_->ch0OutputFormatCombo->setEnabled(!ch0Running); - ui_->ch1OutputFormatCombo->setEnabled(!ch1Running); - ui_->ch0ZeroCopyCheckBox->setEnabled(!channels_[0].opened); - ui_->ch1ZeroCopyCheckBox->setEnabled(!channels_[1].opened); - ui_->ch0AudioCheckBox->setEnabled(!ch0Running); + ui_->ch0OutputFormatCombo->setEnabled(!running[0]); ui_->ch1OutputFormatCombo->setEnabled(!running[1]); + ui_->ch0ZeroCopyCheckBox->setEnabled(!controller_->channelOpened(0)); + ui_->ch1ZeroCopyCheckBox->setEnabled(!controller_->channelOpened(1)); + ui_->ch0AudioCheckBox->setEnabled(!running[0]); ui_->channel1GroupBox->setVisible(kChannel1UiVisible); } -void MainWindow::showError(const QString &apiName, gvfg_status_t status, int channel) +void MainWindow::showError(const QString &apiName, gvfg_status_t status, int channel, const QString &detail) { - QString message = QStringLiteral("%1 failed: %2") - .arg(apiName, QString::fromUtf8(gvfg_strerror(status))); - if (channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1) - message.prepend(QStringLiteral("CH%1 ").arg(channel)); - if (handle_ && (channel == GVFG_CHANNEL_0 || channel == GVFG_CHANNEL_1)) - { - const QString detail = channelLastError(handle_, channel); - if (!detail.isEmpty()) - message += QStringLiteral(" | %1").arg(detail); - } - appendLog(message); + QString message = QStringLiteral("%1 failed: %2").arg(apiName, QString::fromUtf8(gvfg_api::statusText(status))); + if (channel == 0 || channel == 1) message.prepend(QStringLiteral("CH%1 ").arg(channel)); + if (!detail.isEmpty()) message += QStringLiteral(" | %1").arg(detail); + appendLogLine(message); } -void MainWindow::openLogFile() -{ - logSessionStamp_ = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss")); - logPartIndex_ = 1; - logDirPath_ = QCoreApplication::applicationDirPath() + QStringLiteral("/logs"); - if (!QDir().mkpath(logDirPath_)) - { - logFilePath_ = logDirPath_; - return; - } - - openLogFilePart(); -} - -bool MainWindow::openLogFilePart() -{ - std::lock_guard lock(logFileMutex_); - if (logFile_.isOpen()) - logFile_.close(); - - logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log") - .arg(logDirPath_, logFilePrefix(), logSessionStamp_) - .arg(logPartIndex_, 2, 10, QLatin1Char('0')); - logFile_.setFileName(logFilePath_); - if (!logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) - return false; - - const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n") - .arg(logFilePrefix(), - QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))) - .arg(logPartIndex_); - logFile_.write(header.toUtf8()); - logFile_.flush(); - return true; -} - -void MainWindow::rotateLogFileIfNeeded() -{ - if (!logFile_.isOpen() || logFile_.size() < kMaxLogFileBytes) - return; - - const QString footer = QStringLiteral("==== log rotated at %1 ====\n") - .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))); - logFile_.write(footer.toUtf8()); - logFile_.flush(); - ++logPartIndex_; - openLogFilePart(); -} - -void MainWindow::writeLogFileLine(const QString &line) -{ - std::lock_guard lock(logFileMutex_); - if (!logFile_.isOpen()) - return; - - if (logFile_.size() >= kMaxLogFileBytes) - { - const QString footer = QStringLiteral("==== log rotated at %1 ====\n") - .arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))); - logFile_.write(footer.toUtf8()); - logFile_.flush(); - ++logPartIndex_; - if (logFile_.isOpen()) - logFile_.close(); - logFilePath_ = QStringLiteral("%1/%2_%3_part%4.log") - .arg(logDirPath_, logFilePrefix(), logSessionStamp_) - .arg(logPartIndex_, 2, 10, QLatin1Char('0')); - logFile_.setFileName(logFilePath_); - if (logFile_.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) - { - const QString header = QStringLiteral("\n==== %1 session %2 part %3 ====\n") - .arg(logFilePrefix(), - QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HH:mm:ss.zzz"))) - .arg(logPartIndex_); - logFile_.write(header.toUtf8()); - } - } - - if (!logFile_.isOpen()) - return; - - logFile_.write(line.toUtf8()); - logFile_.write("\n"); - logFile_.flush(); -} - -#if GVFG_INTERNAL_DIAGNOSTICS -void MainWindow::writeDiagnosticSnapshot(const QString &statusText) -{ - const QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss.zzz")); - const QStringList lines = statusText.split(QLatin1Char('\n')); - for (int i = 0; i < lines.size(); ++i) - { - const QString line = QStringLiteral("[%1] %2%3") - .arg(timestamp, - i == 0 ? QStringLiteral("Diagnostic | ") : QStringLiteral(" "), - lines.at(i)); - writeLogFileLine(line); - } -} -#endif - -void MainWindow::appendLog(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)); - ui_->logEdit->appendPlainText(line); - writeLogFileLine(line); - } -} - -void MainWindow::logDeliveryStatus(int channelIndex, bool finalSnapshot) -{ - auto &c = channels_[channelIndex]; - if (!finalSnapshot && !c.running.load()) - return; - const qint64 now = std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); - // Keep normal operation quiet; aggregate repeated failures at most every 5 s. - if (!finalSnapshot && now - c.lastDeliveryLogMs < 5000) - return; - - const auto count = [](uint64_t value) { return QString::number(static_cast(value)); }; - gvfg_preview_delivery_stats_t p{}; - const bool previewOk = c.previewHandle && - gvfg_preview_get_delivery_stats(c.previewHandle, &p) == GVFG_PREVIEW_OK; - const auto &b = c.previewBaseline; - const uint64_t failed = (previewOk ? p.failed - b.failed : 0) + c.videoFailed.load(); - const uint64_t videoIssues = failed + c.videoIdGaps.load() + c.videoIdResets.load(); - - uint64_t audioIssues, audioGaps, audioResets, audioFailed; - bool audioAccounted; - { - std::lock_guard lock(c.audioQueueMutex); - audioGaps = c.audioIdGaps; - audioResets = c.audioIdResets; - audioFailed = c.audioFailedBytes; - audioIssues = audioGaps + audioResets + audioFailed; - audioAccounted = c.audioQueuedBytes == 0 && c.audioReceivedBytes == - c.audioAcceptedBytes + c.audioDroppedBytes + c.audioCancelledBytes + c.audioFailedBytes; - } - if (finalSnapshot) - { - const bool videoAccounted = previewOk && c.videoReceived.load() == - c.videoSubmitted.load() + c.videoSkipped.load() + c.videoFailed.load() && - c.videoSubmitted.load() == p.submitted - b.submitted; - if (!videoAccounted || !audioAccounted) - appendLog(QStringLiteral("CH%1 ERROR delivery accounting mismatch | video=%2 audio=%3") - .arg(channelIndex).arg(videoAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH")) - .arg(audioAccounted ? QStringLiteral("OK") : QStringLiteral("MISMATCH"))); - } - // Also flush any changes since the last aggregate when stopping. - if (videoIssues != c.lastLoggedVideoIssues) - { - QString message = QStringLiteral("CH%1 ERROR preview delivery | failed=%2 id_gaps=%3 reset_or_duplicate=%4") - .arg(channelIndex).arg(count(failed)).arg(count(c.videoIdGaps.load())) - .arg(count(c.videoIdResets.load())); - appendLog(message); - } - if (audioIssues != c.lastLoggedAudioIssues) - { - QString message = QStringLiteral("CH%1 ERROR audio delivery | id_gaps=%2 reset_or_duplicate=%3 failed_bytes=%4") - .arg(channelIndex).arg(count(audioGaps)).arg(count(audioResets)).arg(count(audioFailed)); - appendLog(message); - } - if (finalSnapshot || videoIssues != c.lastLoggedVideoIssues || audioIssues != c.lastLoggedAudioIssues) - c.lastDeliveryLogMs = now; - c.lastLoggedVideoIssues = videoIssues; - c.lastLoggedAudioIssues = audioIssues; -} - -void MainWindow::captureReadLoop(int channelIndex) -{ - constexpr uint64_t kTimingWarmupFrames = 30; - constexpr uint64_t kGetFrameTimingSampleFrames = 300; - - std::chrono::steady_clock::time_point noFrameSince{}; - std::chrono::steady_clock::time_point nextNoFrameReport{}; - bool captureStalledLogged = false; - bool startupLatencyLogged = false; - uint64_t successfulFrameCount = 0; - uint64_t getFrameTimingSampleCount = 0; - double getFrameTimingMaximumMs = 0.0; - ChannelRuntime &channel = channels_[channelIndex]; - while (!channel.stopRequested.load(std::memory_order_acquire)) - { - { - std::unique_lock lock(channel.signalMutex); - channel.signalReady.wait(lock, [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire) || - channel.signalConnected.load(std::memory_order_acquire); - }); - } - if (channel.stopRequested.load(std::memory_order_acquire)) - break; - - gvfg_frame_t frame{}; - const auto getFrameStart = std::chrono::steady_clock::now(); - const gvfg_status_t st = gvfg_read_channel_frame(handle_, channelIndex, &frame, 200); - const double getFrameElapsedMs = - std::chrono::duration( - std::chrono::steady_clock::now() - getFrameStart) - .count(); - if (st == GVFG_OK) - { - const uint64_t previousId = channel.videoLastId.exchange(frame.frame_id); - if (channel.videoReceived.fetch_add(1) != 0) - { - if (frame.frame_id > previousId && frame.frame_id - previousId > 1) - channel.videoIdGaps += frame.frame_id - previousId - 1; - else if (frame.frame_id <= previousId) - ++channel.videoIdResets; - } - const bool timingWarmupComplete = ++successfulFrameCount > kTimingWarmupFrames; - if (timingWarmupComplete) - { - ++getFrameTimingSampleCount; - getFrameTimingMaximumMs = (std::max)(getFrameTimingMaximumMs, getFrameElapsedMs); - const uint64_t totalSamples = channel.getFrameSamples.fetch_add(1, std::memory_order_relaxed) + 1; - const double previousAverage = channel.getFrameAverageMs.load(std::memory_order_relaxed); - channel.getFrameAverageMs.store( - previousAverage + (getFrameElapsedMs - previousAverage) / static_cast(totalSamples), - std::memory_order_relaxed); - double observedMaximum = channel.getFrameMaximumMs.load(std::memory_order_relaxed); - while (getFrameElapsedMs > observedMaximum && - !channel.getFrameMaximumMs.compare_exchange_weak( - observedMaximum, getFrameElapsedMs, std::memory_order_relaxed)) - { - } - if (totalSamples <= kGetFrameTimingSampleFrames) - channel.getFrameWindowMaximumMs.store(getFrameTimingMaximumMs, std::memory_order_relaxed); - if (getFrameTimingSampleCount >= kGetFrameTimingSampleFrames) - { - channel.getFrameWindowMaximumMs.store(getFrameTimingMaximumMs, std::memory_order_relaxed); - getFrameTimingSampleCount = 0; - getFrameTimingMaximumMs = 0.0; - } - } - noFrameSince = {}; - nextNoFrameReport = {}; - if (!channel.frameAvailable.exchange(true, std::memory_order_acq_rel)) - { - QMetaObject::invokeMethod(this, [this]() - { updateUiState(); }, Qt::QueuedConnection); - } - if (captureStalledLogged) - { - captureStalledLogged = false; - QMetaObject::invokeMethod(this, [this, channelIndex]() - { appendLog(QStringLiteral("CH%1 RECOVERED capture resumed").arg(channelIndex)); }, Qt::QueuedConnection); - } - - const bool attemptedPreview = channel.previewHandle && - channel.previewVisible.load(std::memory_order_acquire); - if (attemptedPreview) - { - gvfg_preview_frame_t previewFrame{}; - previewFrame.data = frame.data; - previewFrame.data_size = frame.data_size; - previewFrame.width = frame.width; - previewFrame.height = frame.height; - previewFrame.row_bytes = frame.row_stride_bytes; - previewFrame.bit_depth = frame.bit_depth; - previewFrame.frame_id = frame.frame_id; - - switch (frame.pixel_format) - { - case GVFG_PIXFMT_YUY2: - previewFrame.pixel_format = GVFG_PREVIEW_PIXFMT_YUY2; - break; - case GVFG_PIXFMT_Y210: - previewFrame.pixel_format = GVFG_PREVIEW_PIXFMT_Y210; - break; - default: - previewFrame.pixel_format = 0; - break; - } - - const auto previewStart = std::chrono::steady_clock::now(); - const gvfg_preview_status_t previewStatus = - gvfg_preview_render_frame(channel.previewHandle, &previewFrame); - const auto previewEnd = std::chrono::steady_clock::now(); - const double previewElapsedMs = - std::chrono::duration(previewEnd - previewStart).count(); - if (previewStatus != GVFG_PREVIEW_OK) - { - ++channel.videoFailed; - const uint64_t failures = ++channel.previewFailureCount; - if (failures == 1) - { - QMetaObject::invokeMethod(this, [this, channelIndex, failures, previewStatus]() - { appendLog(QStringLiteral("CH%1 preview render failed #%2: %3") - .arg(channelIndex) - .arg(static_cast(failures)) - .arg(QString::fromUtf8(gvfg_preview_strerror(previewStatus)))); }, Qt::QueuedConnection); - } - } - else - { - ++channel.videoSubmitted; - if (!startupLatencyLogged) - { - startupLatencyLogged = true; - const double startupLatencyMs = - std::chrono::duration( - previewEnd - channel.startupStartTime) - .count(); - const double startCallMs = channel.startupStartCallMs; - const double firstReadMs = getFrameElapsedMs; - const double firstRenderFrameMs = previewElapsedMs; - const uint64_t startupFrameId = frame.frame_id; - QMetaObject::invokeMethod( - this, - [this, channelIndex, startCallMs, firstReadMs, - firstRenderFrameMs, startupLatencyMs, startupFrameId]() - { - appendLog(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 | frame_id=%6") - .arg(channelIndex) - .arg(startCallMs, 0, 'f', 3) - .arg(firstReadMs, 0, 'f', 3) - .arg(firstRenderFrameMs, 0, 'f', 3) - .arg(startupLatencyMs, 0, 'f', 3) - .arg(static_cast(startupFrameId))); - }, - Qt::QueuedConnection); - } - if (channel.previewFailureCount != 0) - { - const uint64_t failures = channel.previewFailureCount; - channel.previewFailureCount = 0; - QMetaObject::invokeMethod(this, [this, channelIndex, failures]() - { appendLog(QStringLiteral("CH%1 preview render recovered after %2 failure(s)") - .arg(channelIndex) - .arg(static_cast(failures))); }, Qt::QueuedConnection); - } - - } - } - if (!channel.previewHandle) - ++channel.videoFailed; - else if (!attemptedPreview) - ++channel.videoSkipped; - const gvfg_status_t releaseStatus = gvfg_release_channel_frame(handle_, channelIndex, &frame); - if (releaseStatus != GVFG_OK) - { - QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]() - { showError(QStringLiteral("gvfg_release_channel_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection); - break; - } - - continue; - } - - if (st == GVFG_ETIMEOUT) - { - const auto now = std::chrono::steady_clock::now(); - if (noFrameSince == std::chrono::steady_clock::time_point{}) - { - noFrameSince = now; - nextNoFrameReport = now + std::chrono::seconds(2); - } - if (now >= nextNoFrameReport) - { - captureStalledLogged = true; - const uint64_t elapsedMs = static_cast( - std::chrono::duration_cast(now - noFrameSince).count()); - nextNoFrameReport = now + std::chrono::seconds(10); - QMetaObject::invokeMethod(this, [this, channelIndex, elapsedMs]() - { - appendLog(QStringLiteral("CH%1 ERROR no capture frame for %2 ms") - .arg(channelIndex) - .arg(elapsedMs)); -#if GVFG_INTERNAL_DIAGNOSTICS - updateSignalStatus(false); - writeDiagnosticSnapshot(lastSignalStatusText_); -#endif - }, - Qt::QueuedConnection); - } - continue; - } - if (channel.stopRequested.load(std::memory_order_acquire)) - break; - - QMetaObject::invokeMethod(this, [this, channelIndex, st]() - { showError(QStringLiteral("gvfg_read_channel_frame"), st, channelIndex); }, Qt::QueuedConnection); - break; - } - channel.captureThreadExited.store(true, std::memory_order_release); -} - -void MainWindow::joinCaptureThread(int channel) -{ - if (channels_[channel].captureThread.joinable()) - { - // The capture worker can wait behind preview resource updates. Keep - // DXGI's synchronous HWND messages flowing while joining it. - while (!channels_[channel].captureThreadExited.load(std::memory_order_acquire)) - { - MsgWaitForMultipleObjectsEx(0, nullptr, 1, QS_SENDMESSAGE, MWMO_INPUTAVAILABLE); - MSG message{}; - PeekMessageW(&message, nullptr, 0, 0, PM_NOREMOVE | PM_QS_SENDMESSAGE); - } - channels_[channel].captureThread.join(); - } -} - -void MainWindow::audioReadLoop(int channelIndex) -{ - ChannelRuntime &channel = channels_[channelIndex]; - while (!channel.stopRequested.load(std::memory_order_acquire)) - { - { - std::unique_lock lock(channel.signalMutex); - channel.signalReady.wait(lock, [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire) || - channel.signalConnected.load(std::memory_order_acquire); - }); - } - if (channel.stopRequested.load(std::memory_order_acquire)) - break; - - gvfg_audio_frame_t frame{}; - const gvfg_status_t status = gvfg_read_channel_audio_frame( - handle_, channelIndex, &frame, 200); - if (status == GVFG_ETIMEOUT) - continue; - if (status != GVFG_OK) - { - if (!channel.stopRequested.load(std::memory_order_acquire)) - { - QMetaObject::invokeMethod(this, [this, channelIndex, status]() - { showError(QStringLiteral("gvfg_read_channel_audio_frame"), status, channelIndex); }, Qt::QueuedConnection); - } - break; - } - - const uint64_t audioId = frame.frame_id; - { - std::lock_guard lock(channel.audioQueueMutex); - if (channel.audioReceivedBytes != 0) - { - if (audioId > channel.audioLastId && audioId - channel.audioLastId > 1) - channel.audioIdGaps += audioId - channel.audioLastId - 1; - else if (audioId <= channel.audioLastId) - ++channel.audioIdResets; - } - channel.audioLastId = audioId; - channel.audioReceivedBytes += frame.data_size; - ++channel.audioReceivedFrames; - } - std::vector pcm(frame.data_size); - std::memcpy(pcm.data(), frame.data, frame.data_size); - const gvfg_status_t releaseStatus = - gvfg_release_channel_audio_frame(handle_, channelIndex, &frame); - if (releaseStatus != GVFG_OK) - { - std::lock_guard lock(channel.audioQueueMutex); - channel.audioFailedBytes += pcm.size(); - } - if (releaseStatus != GVFG_OK && !channel.stopRequested.load(std::memory_order_acquire)) - { - QMetaObject::invokeMethod(this, [this, channelIndex, releaseStatus]() - { showError(QStringLiteral("gvfg_release_channel_audio_frame"), releaseStatus, channelIndex); }, Qt::QueuedConnection); - break; - } - - if (releaseStatus == GVFG_OK) - { - { - std::lock_guard lock(channel.audioQueueMutex); - if (channel.stopRequested.load(std::memory_order_acquire)) - { - channel.audioCancelledBytes += pcm.size(); - break; - } - if (channel.audioQueue.size() >= kMaxQueuedAudioFrames) - { - const auto &oldest = channel.audioQueue.front(); - channel.audioDroppedBytes += oldest.pcm.size(); - channel.audioQueuedBytes -= oldest.pcm.size(); - channel.audioQueue.pop_front(); - } - channel.audioQueuedBytes += pcm.size(); - channel.audioQueue.push_back({std::move(pcm)}); - } - channel.audioQueueReady.notify_one(); - } - } - channel.audioQueueReady.notify_all(); -} - -void MainWindow::audioPlaybackLoop(int channelIndex) -{ - ChannelRuntime &channel = channels_[channelIndex]; - const gvfg_audio_format_t format = channel.audioFormat; - - QAudioFormat outputFormat; - outputFormat.setSampleRate(static_cast(format.sample_rate)); - outputFormat.setChannelCount(static_cast(format.channels)); - switch (format.bits_per_sample) - { - case 8: - outputFormat.setSampleFormat(QAudioFormat::UInt8); - break; - case 16: - outputFormat.setSampleFormat(QAudioFormat::Int16); - break; - case 32: - outputFormat.setSampleFormat(QAudioFormat::Int32); - break; - default: - return; - } - - bool recovering = false; - while (!channel.stopRequested.load(std::memory_order_acquire)) - { - const QAudioDevice outputDevice = QMediaDevices::defaultAudioOutput(); - if (outputDevice.isNull() || !outputDevice.isFormatSupported(outputFormat)) - { - if (!recovering) - QMetaObject::invokeMethod(this, [this, channelIndex]() { - appendLog(QStringLiteral("CH%1 Audio output unavailable; monitoring playback will retry").arg(channelIndex)); - }, Qt::QueuedConnection); - recovering = true; - std::unique_lock lock(channel.audioQueueMutex); - while (!channel.audioQueue.empty()) - { - channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); - channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); - channel.audioQueue.pop_front(); - } - channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire); - }); - continue; - } - - QAudioSink audioSink(outputDevice, outputFormat); - QIODevice *audioOutput = audioSink.start(); - if (!audioOutput) - { - if (!recovering) - QMetaObject::invokeMethod(this, [this, channelIndex]() { - appendLog(QStringLiteral("CH%1 Audio output failed to start; monitoring playback will retry").arg(channelIndex)); - }, Qt::QueuedConnection); - recovering = true; - std::unique_lock lock(channel.audioQueueMutex); - while (!channel.audioQueue.empty()) - { - channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); - channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); - channel.audioQueue.pop_front(); - } - channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire); - }); - continue; - } - - if (recovering) - QMetaObject::invokeMethod(this, [this, channelIndex]() { - appendLog(QStringLiteral("CH%1 Audio monitoring playback recovered").arg(channelIndex)); - }, Qt::QueuedConnection); - recovering = false; - bool restartPlayback = false; - while (!channel.stopRequested.load(std::memory_order_acquire) && !restartPlayback) - { - std::vector pcm; - { - std::unique_lock lock(channel.audioQueueMutex); - channel.audioQueueReady.wait(lock, [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire) || - !channel.audioQueue.empty(); - }); - if (channel.stopRequested.load(std::memory_order_acquire)) - break; - pcm = std::move(channel.audioQueue.front().pcm); - channel.audioQueue.pop_front(); - channel.audioQueuedBytes -= pcm.size(); - } - - qint64 written = 0; - auto lastProgress = std::chrono::steady_clock::now(); - while (written < static_cast(pcm.size()) && - !channel.stopRequested.load(std::memory_order_acquire)) - { - const qint64 result = audioOutput->write( - reinterpret_cast(pcm.data()) + written, - static_cast(pcm.size()) - written); - const auto now = std::chrono::steady_clock::now(); - const bool stalled = result == 0 && now - lastProgress >= std::chrono::seconds(2); - { - std::lock_guard lock(channel.audioQueueMutex); - if (result > 0) - channel.audioAcceptedBytes += static_cast(result); - else if (result < 0 || stalled) - channel.audioFailedBytes += pcm.size() - static_cast(written); - } - if (result > 0) - { - written += result; - lastProgress = now; - continue; - } - if (result < 0 || stalled) - { - QMetaObject::invokeMethod(this, [this, channelIndex, stalled]() { - appendLog(stalled - ? QStringLiteral("CH%1 Audio output made no progress for 2 seconds; rebuilding monitoring playback").arg(channelIndex) - : QStringLiteral("CH%1 Audio output write failed; rebuilding monitoring playback").arg(channelIndex)); - }, Qt::QueuedConnection); - restartPlayback = true; - break; - } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - if (written != static_cast(pcm.size()) && !restartPlayback) - { - std::lock_guard lock(channel.audioQueueMutex); - channel.audioCancelledBytes += pcm.size() - static_cast(written); - } - } - audioSink.stop(); - if (restartPlayback) - { - recovering = true; - std::unique_lock lock(channel.audioQueueMutex); - while (!channel.audioQueue.empty()) - { - channel.audioDroppedBytes += channel.audioQueue.front().pcm.size(); - channel.audioQueuedBytes -= channel.audioQueue.front().pcm.size(); - channel.audioQueue.pop_front(); - } - channel.audioQueueReady.wait_for(lock, std::chrono::milliseconds(500), [&channel]() { - return channel.stopRequested.load(std::memory_order_acquire); - }); - } - } -} - -void MainWindow::joinAudioThread(int channel) -{ - if (channels_[channel].audioThread.joinable()) - channels_[channel].audioThread.join(); - channels_[channel].audioQueueReady.notify_all(); - if (channels_[channel].audioPlaybackThread.joinable()) - channels_[channel].audioPlaybackThread.join(); - std::lock_guard lock(channels_[channel].audioQueueMutex); - channels_[channel].audioCancelledBytes += channels_[channel].audioQueuedBytes; - channels_[channel].audioQueuedBytes = 0; - channels_[channel].audioQueue.clear(); -} +void MainWindow::appendLogLine(const QString &line) { ui_->logEdit->appendPlainText(line); } diff --git a/GVFG_Qt_Sample/mainwindow.h b/GVFG_Qt_Sample/mainwindow.h index 5393abf..03d5692 100644 --- a/GVFG_Qt_Sample/mainwindow.h +++ b/GVFG_Qt_Sample/mainwindow.h @@ -1,31 +1,16 @@ #pragma once #include -#include -#include -#include #include - #include -#include -#include -#include -#include -#include -#include -#include -#include +class CaptureController; class QCloseEvent; class PreviewWindow; -class QTimer; QT_BEGIN_NAMESPACE -namespace Ui -{ -class MainWindow; -} +namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow final : public QWidget @@ -40,110 +25,17 @@ protected: void closeEvent(QCloseEvent *event) override; private: - struct ChannelRuntime - { - bool opened = false; - gvfg_preview_handle previewHandle = nullptr; - std::atomic running{false}; - std::atomic stopRequested{false}; - std::atomic signalConnected{false}; - std::mutex signalMutex; - std::condition_variable signalReady; - std::atomic frameAvailable{false}; - std::atomic previewVisible{false}; - std::atomic captureThreadExited{true}; - std::thread captureThread; - std::thread audioThread; - std::thread audioPlaybackThread; - std::mutex audioQueueMutex; - std::condition_variable audioQueueReady; - struct AudioPacket { std::vector pcm; }; - std::deque audioQueue; - bool audioEnabled = false; - gvfg_audio_format_t audioFormat{}; - // Audio accounting is protected by audioQueueMutex. Accepted means - // written to QAudioSink, not physically played by the device. - uint64_t audioReceivedFrames = 0; - uint64_t audioReceivedBytes = 0; - uint64_t audioAcceptedBytes = 0; - uint64_t audioQueuedBytes = 0; - uint64_t audioDroppedBytes = 0; - uint64_t audioCancelledBytes = 0; - uint64_t audioFailedBytes = 0; - uint64_t audioIdGaps = 0; - uint64_t audioIdResets = 0; - uint64_t audioLastId = 0; - std::atomic videoReceived{0}, videoSubmitted{0}, videoSkipped{0}, videoFailed{0}; - std::atomic videoIdGaps{0}, videoIdResets{0}; - std::atomic videoLastId{0}; - gvfg_preview_delivery_stats_t previewBaseline{}; - std::chrono::steady_clock::time_point startupStartTime{}; - double startupStartCallMs = 0.0; - uint64_t lastLoggedVideoIssues = 0, lastLoggedAudioIssues = 0; - qint64 lastDeliveryLogMs = 0; - std::atomic getFrameAverageMs{0.0}; - std::atomic getFrameMaximumMs{0.0}; - std::atomic getFrameWindowMaximumMs{0.0}; - std::atomic getFrameSamples{0}; - uint64_t previewFailureCount = 0; - gvfg_signal_status_t cachedSignalStatus{}; - bool haveCachedSignalStatus = false; - QString lastLoggedInputStatus; -#if GVFG_INTERNAL_DIAGNOSTICS - uint64_t lastDebugDmaErrors = 0; - bool haveDebugBaseline = false; -#endif - }; - - void refreshDevices(); - void showPreviewWindow(int channel); - void showFullscreenPreviewWindow(int channel); - bool openDevice(); - bool openChannel(int channel); - bool applyOutputFormat(int channel); + void syncControllerOptions(int channel); + void showPreviewWindow(int channel, bool fullscreen); void updateOutputFormatOptions(int changedChannel = -1); - void closeDevice(); - void startCapture(int channel); - void stopCapture(int channel); - void stopAllCaptures(); - bool applyPreview(int channel); - void updatePreviewSourceSize(int channel, const gvfg_signal_status_t &signal); - void processPendingEvents(); - void updateSignalStatus(bool queryHardware = true); void updateUiState(); - void showError(const QString &apiName, gvfg_status_t status, int channel = -1); - void openLogFile(); - bool openLogFilePart(); - void rotateLogFileIfNeeded(); - void writeLogFileLine(const QString &line); -#if GVFG_INTERNAL_DIAGNOSTICS - void writeDiagnosticSnapshot(const QString &statusText); -#endif - void appendLog(const QString &message); - void captureReadLoop(int channel); - void audioReadLoop(int channel); - void audioPlaybackLoop(int channel); - void joinCaptureThread(int channel); - void joinAudioThread(int channel); - void logDeliveryStatus(int channel, bool finalSnapshot = false); - - static constexpr qint64 kMaxLogFileBytes = 20ll * 1024ll * 1024ll; + void showError(const QString &apiName, gvfg_status_t status, int channel, + const QString &detail); + void appendLogLine(const QString &line); Ui::MainWindow *ui_ = nullptr; + CaptureController *controller_ = nullptr; std::array previewWindows_{}; - std::array devices_{}; - int deviceCount_ = 0; - gvfg_handle handle_ = nullptr; - int selectedDeviceIndex_ = -1; - std::array channels_{}; - QTimer *runtimeStatusTimer_ = nullptr; - QString lastSignalStatusText_; - QFile logFile_; - std::mutex logFileMutex_; - QString logDirPath_; - QString logFilePath_; - QString logSessionStamp_; - int logPartIndex_ = 1; }; QWidget *createMainWindow(); diff --git a/README.md b/README.md index a7d175c..c2bed18 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,12 @@ done-index 與舊 SDK frame-ring 流程不在相容範圍內。 - `GVFG_Qt_Sample`:獨立 Qt APP project,只連結預先建好的 SDK,不會編譯 SDK source。 - `docs`:API 與整合說明。 +Qt Sample 的 source boundary: + +- `mainwindow.cpp`:Widget 建立、signal/slot、畫面狀態與使用者操作。 +- `capture_controller.cpp/.h`:不依賴 UI widget 的裝置/channel lifecycle、video/audio worker、preview submission、狀態與 log 資料流。 +- `gvfg_api.cpp/.h`:唯一直接呼叫 `gvfg_*` 與 `gvfg_preview_*` C API 的 application adapter;`GvfgClient` 以 RAII 管理 capture handle。 + 客戶使用指南在 `docs/GVFG_CUSTOMER_API.md`,完整函式與結構參考在 `docs/GVFG_CUSTOMER_API_REFERENCE.md`。內部架構、package 切分、threading、frame ownership 說明在 `docs/GVFG_INTERNAL_NOTES.md`。