diff --git a/GVFG_SDK/CMakeLists.txt b/GVFG_SDK/CMakeLists.txt index da4f4ca..72738b6 100644 --- a/GVFG_SDK/CMakeLists.txt +++ b/GVFG_SDK/CMakeLists.txt @@ -3,16 +3,10 @@ cmake_minimum_required(VERSION 3.16) project(gvfg_sdk LANGUAGES CXX) # Version policy: breaking public API changes bump MAJOR; features bump MINOR; fixes bump PATCH. -set(GVFG_SDK_VERSION "3.1.0") +set(GVFG_SDK_VERSION "3.2.0") option(GVFG_ENABLE_INTERNAL_DIAGNOSTICS "Enable SDK diagnostics in non-Debug builds" OFF) -option(GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - "UNSAFE local experiment: write OSD into driver zero-copy buffers" OFF) -if (GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE) - message(WARNING "EXPERIMENTAL driver-buffer writes enabled. Writable pages do not guarantee DMA ownership. Do not ship this build.") -endif() - include(GNUInstallDirs) set(CMAKE_CXX_STANDARD 17) @@ -53,8 +47,8 @@ if (NOT WIN32) message(FATAL_ERROR "GVFG SDK currently supports Windows only.") endif() -add_subdirectory(helpers/gvfg_osd) add_subdirectory(sdk/gvfg) +add_subdirectory(helpers/gvfg_osd) add_subdirectory(helpers/gvfg_preview) add_subdirectory(helpers/gvfg_audio_playback) add_subdirectory(helpers/gvfg_playback) diff --git a/GVFG_SDK/helpers/gvfg_osd/CMakeLists.txt b/GVFG_SDK/helpers/gvfg_osd/CMakeLists.txt index 8919bf3..1edeaec 100644 --- a/GVFG_SDK/helpers/gvfg_osd/CMakeLists.txt +++ b/GVFG_SDK/helpers/gvfg_osd/CMakeLists.txt @@ -1,28 +1,27 @@ -project(gvfg_osd_core LANGUAGES CXX) - -add_library(gvfg_osd_core STATIC - include/gvfg_osd.h - src/gvfg_osd.cpp -) - -set_target_properties(gvfg_osd_core PROPERTIES - AUTOMOC OFF - AUTOUIC OFF - AUTORCC OFF -) - -target_include_directories(gvfg_osd_core - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/include -) - -target_link_libraries(gvfg_osd_core PUBLIC - d2d1 - dwrite - windowscodecs - ole32 -) - -if (MSVC) - target_compile_options(gvfg_osd_core PRIVATE /utf-8 /EHsc) +add_library(gvfg_osd SHARED gvfg_osd.def include/gvfg_osd.h + src/gvfg_osd_api.cpp src/gvfg_osd.cpp src/gvfg_osd_core.h + src/gvfg_gpu_osd.cpp src/gvfg_gpu_osd.h) +set_target_properties(gvfg_osd PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) +target_include_directories(gvfg_osd PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/../../sdk/gvfg/include + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../sdk/gvfg/src) +target_compile_definitions(gvfg_osd PRIVATE GVFG_OSD_BUILD) +target_link_libraries(gvfg_osd PRIVATE gvfg d2d1 dwrite windowscodecs ole32 d3d11 D3DCompiler) +if(MSVC) + target_compile_options(gvfg_osd PRIVATE /utf-8 /EHsc) endif() +if(MSVC AND GVFG_MINGW_DLLTOOL) + add_custom_command(TARGET gvfg_osd POST_BUILD + COMMAND "${GVFG_MINGW_DLLTOOL}" + -d "${CMAKE_CURRENT_SOURCE_DIR}/gvfg_osd.def" + -D gvfg_osd.dll -l libgvfg_osd.dll.a + WORKING_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}" + COMMENT "Generating MinGW import library for gvfg_osd.dll" + VERBATIM + ) + install(FILES "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/libgvfg_osd.dll.a" + DESTINATION ${CMAKE_INSTALL_LIBDIR}) +endif() +install(TARGETS gvfg_osd + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) +install(FILES include/gvfg_osd.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) diff --git a/GVFG_SDK/helpers/gvfg_osd/README.md b/GVFG_SDK/helpers/gvfg_osd/README.md index 5413669..7ea90f8 100644 --- a/GVFG_SDK/helpers/gvfg_osd/README.md +++ b/GVFG_SDK/helpers/gvfg_osd/README.md @@ -77,38 +77,3 @@ to application receipt is acquisition plus OSD/delivery cost. Waiting for the next frame is excluded. The public frame timestamp and old timed-read ABI are unchanged; this uses a separate internal result type and export. Do not ship the internal debug header in customer packages. - -### Unsafe local zero-copy experiment (default OFF) - -Set `GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE=ON` in the standalone SDK's -CMake configuration, rebuild `gvfg.dll` and its import library, then rebuild -the srcroot viewer against the matching SDK. Enable zero-copy and apply OSD. -This is an SDK build option, not the viewer console option. - -The experimental backend supplies the original mutable vendor pointer, without -casting away const on the public API. Before processing, `VirtualQuery` checks -the entire destination ROI span for committed `PAGE_READWRITE` pages; readonly, -guard, copy-on-write, and failed queries fall back to independent output and a -full-frame copy. Permissions are checked again immediately before ROI writes; -failure at that point returns `GVFG_EIO` without writing. No `VirtualProtect` -or vendor release contract change is used. Successful in-place processing -retains the backend hold until normal application frame release. - -WARNING: these checks do not prevent concurrent DMA, buffer reuse, or a mapping -change after the check. Corruption and access violations remain possible; C++ -exception handling is not an access-violation safety guarantee. Do not ship this -configuration. A successful capture does not establish driver ownership safety. - -The viewer warns at startup and labels each 300-frame diagnostic batch as actual -driver-buffer writes, fallback copies, or no in-place processing. Flags use the -separate `gvfg_debug_get_channel_osd_experiment_flags` export; existing timing -struct layouts stay unchanged. Revert by setting the option OFF and rebuilding -the SDK. The client-facing frame pointer remains read-only in all modes. - -Fallback batches also report the final frame's first rejected region: a readable -reason, native Protect/State/Type, VirtualQuery return byte count, and Win32 error -(captured immediately only when VirtualQuery returns zero). Other frames may -have different reasons. This uses the separate internal -`gvfg_debug_get_channel_osd_page_check` export, queried while the frame is held; -rebuild both SDK and viewer together. No per-frame logging or permission changes -are introduced. Zero Win32 error does not imply a writable page. diff --git a/GVFG_SDK/helpers/gvfg_osd/gvfg_osd.def b/GVFG_SDK/helpers/gvfg_osd/gvfg_osd.def new file mode 100644 index 0000000..df2e4b2 --- /dev/null +++ b/GVFG_SDK/helpers/gvfg_osd/gvfg_osd.def @@ -0,0 +1,9 @@ +LIBRARY gvfg_osd + +EXPORTS + gvfg_get_osd_fonts + gvfg_measure_osd_text + gvfg_render_osd_frame_bgra + gvfg_set_channel_osd + gvfg_set_channel_osd_visible + gvfg_clear_channel_osd diff --git a/GVFG_SDK/helpers/gvfg_osd/include/gvfg_osd.h b/GVFG_SDK/helpers/gvfg_osd/include/gvfg_osd.h index bd5cae9..c79bc93 100644 --- a/GVFG_SDK/helpers/gvfg_osd/include/gvfg_osd.h +++ b/GVFG_SDK/helpers/gvfg_osd/include/gvfg_osd.h @@ -1,104 +1,113 @@ -#ifndef GVFG_OSD_H -#define GVFG_OSD_H +#pragma once -#include +#include "gvfg_capture.h" + +#if defined(_WIN32) +# if defined(GVFG_OSD_BUILD) +# define GVFG_OSD_API __declspec(dllexport) +# else +# define GVFG_OSD_API __declspec(dllimport) +# endif +#else +# define GVFG_OSD_API +#endif #ifdef __cplusplus extern "C" { #endif + /* Strings are copied synchronously by gvfg_set_channel_osd(). */ + typedef struct gvfg_channel_osd_config_t + { + const char *text; /* NUL-terminated printable ASCII, 1..32 characters. */ + const char *font_family; /* NUL-terminated UTF-8 installed font family name. */ + uint32_t font_size_px; /* Non-zero em size; 96-DPI rendering, not ink height. */ + uint32_t color_rgb; /* 0x00RRGGBB. */ + int32_t x; /* Text-box left in frame pixels; clamped to fit. */ + int32_t y; /* Text-box top in frame pixels; clamped to fit. */ + } gvfg_channel_osd_config_t; + + typedef struct gvfg_osd_font_list_t + { + uint32_t count; + const char *const *names; /* SDK-owned UTF-8 family names; do not modify/free. */ + } gvfg_osd_font_list_t; + + typedef struct gvfg_osd_bitmap_t + { + const uint8_t *data; /* SDK-owned; do not modify/free. See the render function's lifetime. */ + uint64_t data_size; /* stride * height bytes. */ + uint32_t width; + uint32_t height; + uint32_t stride; /* Byte distance between rows; width * 4. */ + } gvfg_osd_bitmap_t; + +#define GVFG_OSD_SLOT_COUNT 2u #define GVFG_OSD_MAX_TEXT_CHARACTERS 32u -typedef void *gvfg_osd_handle; + /* Refresh installed fonts and return an SDK-owned snapshot. No device needed. + * Pointers expire at the next call (including a failed call), or DLL unload. + * Copy names before then. Serialize calls and use of this borrowed list. + * Returns an empty list on failure; no callback or caller-side free is needed. + */ + GVFG_OSD_API gvfg_status_t gvfg_get_osd_fonts( + GVFG_PARAM_OUT gvfg_osd_font_list_t *out_list); -typedef enum gvfg_osd_status_t -{ - GVFG_OSD_OK = 0, - GVFG_OSD_EINVAL = -1, - GVFG_OSD_ENOMEM = -2, - GVFG_OSD_ERENDER = -3 -} gvfg_osd_status_t; + /* Measure the same conservative text box used for rendering, including + * overhang and a one-pixel guard per edge. Ignores x/y/color; no device needed. + * Outputs are zeroed on failure. Missing font/invalid input: GVFG_EINVAL. + */ + GVFG_OSD_API gvfg_status_t gvfg_measure_osd_text( + GVFG_PARAM_IN const gvfg_channel_osd_config_t *config, + GVFG_PARAM_OUT uint32_t *out_width, + GVFG_PARAM_OUT uint32_t *out_height); -typedef enum gvfg_osd_pixel_format_t -{ - GVFG_OSD_PIXFMT_YUY2 = 1, - GVFG_OSD_PIXFMT_Y210 = 2 -} gvfg_osd_pixel_format_t; + /* Prepare one transparent video-sized overlay for FPGA transfer. No capture + * handle needed; pass the target video width/height in pixels. Output is + * top-down BGRA8888, premultiplied alpha, stride = width * 4. + * NULL slots are omitted (hidden/unused); both NULL produce a blank frame. + * x/y are frame coordinates, clamped to fit; oversized text is skipped. + * Slot 1 is composited over slot 0. No video pixels are included. + * Data is valid until the next call to this function on the same thread + * (including failure), thread exit or DLL unload. Copy for async transfer. + * Invalid inputs/dimensions (including byte size above UINT32_MAX) return + * GVFG_EINVAL; allocation/render failures return GVFG_EIO. On failure the + * output is empty. Does not affect GPU capture OSD. + */ + GVFG_OSD_API gvfg_status_t gvfg_render_osd_frame_bgra( + GVFG_PARAM_IN uint32_t video_width, + GVFG_PARAM_IN uint32_t video_height, + GVFG_PARAM_IN const gvfg_channel_osd_config_t *slot0, + GVFG_PARAM_IN const gvfg_channel_osd_config_t *slot1, + GVFG_PARAM_OUT gvfg_osd_bitmap_t *out_bitmap); -/* - * Generates an off-line OSD surface using the requested installed system font. Text is - * restricted to printable ASCII and at most GVFG_OSD_MAX_TEXT_CHARACTERS - * characters on one line without wrapping. color_rgb is 0xRRGGBB. - * x/y identify the top-left of the conservative measured text box (including - * glyph overhang and a one-pixel guard). They are clamped to keep that box - * inside the frame. Rendering returns EINVAL if the box cannot fit the frame. - * Output YUV uses BT.709 limited range. The mask is one coverage byte per - * pixel: 0 is transparent and 255 is fully covered. - */ -typedef struct gvfg_osd_config_t -{ - uint32_t struct_size; - uint32_t width; - uint32_t height; - uint32_t pixel_format; - const char *text; - const char *font_family; /* UTF-8, NUL-terminated. */ - uint32_t text_length; - int32_t x; - int32_t y; - uint32_t font_size_px; - uint32_t color_rgb; -} gvfg_osd_config_t; + /* Set and show slot 0 or 1 on an opened channel. Strings are copied before + * return; slot 1 is blended over slot 0. Applies to subsequent YUY2/Y210 + * frames using BT.709 limited range. X/Y are clamped to fit the text box. + * An oversized slot is skipped until settings/frame size allow it to fit; + * capture and the other slot continue. No wrapping/shrinking/truncation. + */ + GVFG_OSD_API gvfg_status_t gvfg_set_channel_osd( + GVFG_PARAM_IN gvfg_handle handle, + GVFG_PARAM_IN int channel_index, + GVFG_PARAM_IN uint32_t osd_index, + GVFG_PARAM_IN const gvfg_channel_osd_config_t *config); -/* All buffers are caller-owned and are used only for the duration of render. */ -typedef struct gvfg_osd_output_t -{ - uint32_t struct_size; - void *yuv_data; - uint64_t yuv_size; - uint32_t yuv_stride; - void *mask_data; - uint64_t mask_size; - uint32_t mask_stride; -} gvfg_osd_output_t; + /* visible must be 0 or 1. Retains settings and cached glyph surfaces. + * Showing an unconfigured/cleared slot returns GVFG_ESTATE. + */ + GVFG_OSD_API gvfg_status_t gvfg_set_channel_osd_visible( + GVFG_PARAM_IN gvfg_handle handle, + GVFG_PARAM_IN int channel_index, + GVFG_PARAM_IN uint32_t osd_index, + GVFG_PARAM_IN int visible); -gvfg_osd_status_t gvfg_osd_create( - gvfg_osd_handle *out_handle); - -void gvfg_osd_destroy( - gvfg_osd_handle handle); - -/* Conservative whole-text bounds in pixels, not pixel-tight raster bounds. */ -gvfg_osd_status_t gvfg_osd_measure( - gvfg_osd_handle handle, - const char *text, - uint32_t text_length, - uint32_t font_size_px, - const char *font_family, - uint32_t *out_width, - uint32_t *out_height); - -/* SDK-owned snapshot, invalidated by the next call. Serialize call/read access. */ -gvfg_osd_status_t gvfg_osd_get_fonts(uint32_t *out_count, const char *const **out_names); - -gvfg_osd_status_t gvfg_osd_render( - gvfg_osd_handle handle, - const gvfg_osd_config_t *config, - const gvfg_osd_output_t *output); - -/* Caller-owned, top-down BGRA8888 with premultiplied alpha. Ignores pixel_format. - * Unlike YUV output, width may be odd. No RGB/YUV conversion is performed. - */ -gvfg_osd_status_t gvfg_osd_render_bgra( - gvfg_osd_handle handle, - const gvfg_osd_config_t *config, - void *data, uint64_t data_size, uint32_t stride); - -const char *gvfg_osd_strerror( - gvfg_osd_status_t status); + /* Disable one slot and discard its settings and cached glyph surfaces. */ + GVFG_OSD_API gvfg_status_t gvfg_clear_channel_osd( + GVFG_PARAM_IN gvfg_handle handle, + GVFG_PARAM_IN int channel_index, + GVFG_PARAM_IN uint32_t osd_index); #ifdef __cplusplus } #endif - -#endif diff --git a/GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.cpp b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.cpp similarity index 86% rename from GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.cpp rename to GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.cpp index 4df178c..06a0714 100644 --- a/GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.cpp +++ b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.cpp @@ -1,6 +1,6 @@ #include "gvfg_gpu_osd.h" -#include "gvfg_osd.h" +#include "gvfg_osd_core.h" #include #include @@ -22,56 +22,6 @@ namespace gvfg::internal { namespace { -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE -// Permission snapshot only: this does NOT establish exclusive DMA ownership. -bool writableExperimentalRange(const gvfg_frame_t &source, uint64_t offset, uint64_t span, - gvfg_debug_osd_page_check_t *result) -{ - gvfg_debug_osd_page_check_t check{}; - const auto reject = [&](gvfg_debug_osd_page_reason_t reason) { - check.reason = static_cast(reason); - if (result) - *result = check; - return false; - }; - const uintptr_t base = reinterpret_cast(source.data); - const uintptr_t limit = (std::numeric_limits::max)(); - if (!span || offset > source.data_size || span > source.data_size - offset || - offset > limit - base || span > limit - (base + offset)) - return reject(GVFG_DEBUG_OSD_PAGE_INVALID_RANGE); - uintptr_t cursor = base + static_cast(offset); - const uintptr_t end = cursor + static_cast(span); - while (cursor < end) - { - MEMORY_BASIC_INFORMATION info{}; - const SIZE_T queried = VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)); - // Capture the error immediately, and only on a failed native call. - check.win32_error = queried == 0 ? GetLastError() : 0; - check.query_bytes = static_cast(queried); - check.protect = info.Protect; - check.state = info.State; - check.type = info.Type; - if (queried != sizeof(info)) - return reject(GVFG_DEBUG_OSD_PAGE_QUERY_FAILED); - if (info.State != MEM_COMMIT) - return reject(GVFG_DEBUG_OSD_PAGE_NOT_COMMITTED); - if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) - return reject(GVFG_DEBUG_OSD_PAGE_GUARD_OR_NOACCESS); - if ((info.Protect & 0xffu) != PAGE_READWRITE) - return reject(GVFG_DEBUG_OSD_PAGE_NOT_READWRITE); - const uintptr_t regionBase = reinterpret_cast(info.BaseAddress); - if (info.RegionSize > limit - regionBase) - return reject(GVFG_DEBUG_OSD_PAGE_INVALID_REGION); - const uintptr_t next = regionBase + info.RegionSize; - if (next <= cursor) - return reject(GVFG_DEBUG_OSD_PAGE_INVALID_REGION); - cursor = next; - } - if (result) - *result = {}; - return true; -} -#endif constexpr char kOsdBlendShader[] = R"( Texture2D sourceTexture : register(t0); Texture2D osdTexture : register(t1); @@ -499,20 +449,10 @@ struct GpuOsdProcessor::Impl bool &applied, gvfg_debug_osd_frame_timing_t *timing, uint8_t *writableSource, - bool experimentalZeroCopy, - bool *inPlaceApplied, - uint32_t *experimentFlags, - gvfg_debug_osd_page_check_t *pageCheck) + bool *inPlaceApplied) { - if (pageCheck) - *pageCheck = {}; if (inPlaceApplied) *inPlaceApplied = false; -#ifndef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - if (experimentalZeroCopy) - return GVFG_EINVAL; - (void)experimentFlags; -#endif using Clock = std::chrono::steady_clock; auto stageStart = timing ? Clock::now() : Clock::time_point{}; const auto finishStage = [timing, &stageStart](gvfg_debug_osd_stage_t stage) { @@ -576,19 +516,6 @@ struct GpuOsdProcessor::Impl if (sourceOffset64 > (std::numeric_limits::max)()) return GVFG_EINVAL; const size_t sourceOffset = static_cast(sourceOffset64); -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - const uint64_t writeSpan = static_cast(region.height - 1u) * - source.row_stride_bytes + regionRowBytes; - if (experimentalZeroCopy && - (!writableSource || !writableExperimentalRange(source, sourceOffset, writeSpan, pageCheck))) - { - if (!writableSource && pageCheck) - pageCheck->reason = GVFG_DEBUG_OSD_PAGE_NO_POINTER; - writableSource = nullptr; - if (experimentFlags) - *experimentFlags |= GVFG_DEBUG_OSD_EXPERIMENT_REJECTED; - } -#endif if (!writableSource) destination.resize(static_cast(rowBytes) * static_cast(source.height)); uint8_t *outputData = writableSource ? writableSource : destination.data(); @@ -651,16 +578,6 @@ struct GpuOsdProcessor::Impl } const size_t destinationOffset = static_cast(region.top) * outputStride + static_cast(region.left) * bytesPerPixel; -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - // Recheck immediately before writing. Permissions can still change after - // this check; neither this nor the SDK hold prevents concurrent DMA. - if (experimentalZeroCopy && writableSource && - !writableExperimentalRange(source, sourceOffset, writeSpan, pageCheck)) - { - context->Unmap(readbackTexture.Get(), 0); - return GVFG_EIO; - } -#endif for (uint32_t row = 0; row < region.height; ++row) { std::memcpy(outputData + destinationOffset + static_cast(row) * outputStride, @@ -674,8 +591,6 @@ struct GpuOsdProcessor::Impl applied = true; if (inPlaceApplied) *inPlaceApplied = writableSource != nullptr; - if (experimentalZeroCopy && writableSource && experimentFlags) - *experimentFlags |= GVFG_DEBUG_OSD_EXPERIMENT_USED; if (timing) timing->osd_applied = 1; return GVFG_OK; @@ -723,15 +638,11 @@ gvfg_status_t GpuOsdProcessor::process(const gvfg_frame_t &source, bool &applied, gvfg_debug_osd_frame_timing_t *timing, uint8_t *writableSource, - bool experimentalZeroCopy, - bool *inPlaceApplied, - uint32_t *experimentFlags, - gvfg_debug_osd_page_check_t *pageCheck) + bool *inPlaceApplied) { try { - return impl_->process(source, destination, destinationStride, applied, timing, writableSource, - experimentalZeroCopy, inPlaceApplied, experimentFlags, pageCheck); + return impl_->process(source, destination, destinationStride, applied, timing, writableSource, inPlaceApplied); } catch (...) { diff --git a/GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.h b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.h similarity index 70% rename from GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.h rename to GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.h index ea5af6b..b74b0f7 100644 --- a/GVFG_SDK/sdk/gvfg/src/gpu/gvfg_gpu_osd.h +++ b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_gpu_osd.h @@ -1,6 +1,6 @@ #pragma once -#include "gvfg_capture.h" +#include "gvfg_osd.h" #include "gvfg_debug.h" #include @@ -20,8 +20,6 @@ public: gvfg_status_t setVisible(uint32_t index, int visible); // writableSource must equal source.data. Only the backend can grant this // writable SDK-owned storage, held until the caller releases the frame. - // The default-OFF experimental override admits driver storage only after - // page checks; this is not a driver/DMA ownership guarantee. // nullptr preserves the separate-output path used for driver zero-copy. gvfg_status_t process(const gvfg_frame_t &source, std::vector &destination, @@ -29,10 +27,7 @@ public: bool &applied, gvfg_debug_osd_frame_timing_t *timing = nullptr, uint8_t *writableSource = nullptr, - bool experimentalZeroCopy = false, - bool *inPlaceApplied = nullptr, - uint32_t *experimentFlags = nullptr, - gvfg_debug_osd_page_check_t *pageCheck = nullptr); + bool *inPlaceApplied = nullptr); private: struct Impl; diff --git a/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd.cpp b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd.cpp index 8e5a2db..b7f55a2 100644 --- a/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd.cpp +++ b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd.cpp @@ -1,4 +1,4 @@ -#include "gvfg_osd.h" +#include "gvfg_osd_core.h" #include #include diff --git a/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_api.cpp b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_api.cpp new file mode 100644 index 0000000..163427d --- /dev/null +++ b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_api.cpp @@ -0,0 +1,240 @@ +#include "gvfg_osd.h" +#include "gvfg_osd_core.h" +#include "gvfg_gpu_osd.h" +#include "gvfg_frame_processor.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +struct OsdFrameProcessor +{ + gvfg::internal::GpuOsdProcessor gpu; + std::vector pixels; +}; + +const gvfg_frame_processor processor{ + [](void **context) -> gvfg_status_t { + try + { + *context = new OsdFrameProcessor; + return GVFG_OK; + } + catch (const std::bad_alloc &) + { + return GVFG_EIO; + } + }, + [](void *context) { delete static_cast(context); }, + [](void *context, const gvfg_frame_t &source, gvfg_frame_t &output, + bool &applied, gvfg_debug_osd_frame_timing_t *timing, uint8_t *writable, + bool *inPlace) { + auto &state = *static_cast(context); + int stride = 0; + const auto status = state.gpu.process(source, state.pixels, stride, applied, timing, + writable, inPlace); + if (status == GVFG_OK && applied && !*inPlace) + { + output.data = state.pixels.data(); + output.data_size = state.pixels.size(); + output.row_stride_bytes = stride; + } + return status; + } +}; + +struct SlotCommand +{ + uint32_t index; + const gvfg_channel_osd_config_t *config; + int visible; +}; +} + +extern "C" +{ + gvfg_status_t gvfg_get_osd_fonts(gvfg_osd_font_list_t *out_list) + { + if (!out_list) + return GVFG_EINVAL; + *out_list = {}; + const auto status = gvfg_osd_get_fonts(&out_list->count, &out_list->names); + return status == GVFG_OSD_OK ? GVFG_OK : GVFG_EIO; + } + + gvfg_status_t gvfg_measure_osd_text(const gvfg_channel_osd_config_t *config, + uint32_t *out_width, uint32_t *out_height) + { + if (out_width) *out_width = 0; + if (out_height) *out_height = 0; + if (!config || !config->text || !out_width || !out_height) + return GVFG_EINVAL; + const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u); + if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS) + return GVFG_EINVAL; + try + { + gvfg_osd_handle rawHandle = nullptr; + if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK) + return GVFG_EIO; + const std::unique_ptr helper(rawHandle, &gvfg_osd_destroy); + const auto status = gvfg_osd_measure(helper.get(), config->text, + static_cast(length), config->font_size_px, config->font_family, + out_width, out_height); + return status == GVFG_OSD_OK ? GVFG_OK : + status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; + } + catch (...) { return GVFG_EIO; } + } + + static gvfg_status_t renderOsdBgraTile(const gvfg_channel_osd_config_t *config, + gvfg_osd_bitmap_t *out_bitmap, + std::vector &pixels) + { + if (!config || !config->text) + return GVFG_EINVAL; + const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u); + if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS) + return GVFG_EINVAL; + try + { + gvfg_osd_handle rawHandle = nullptr; + if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK) + return GVFG_EIO; + const std::unique_ptr helper(rawHandle, &gvfg_osd_destroy); + uint32_t width = 0, height = 0; + auto status = gvfg_osd_measure(helper.get(), config->text, + static_cast(length), config->font_size_px, config->font_family, + &width, &height); + if (status != GVFG_OSD_OK) + return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; + const uint64_t stride = static_cast(width) * 4u; + // WIC GetDataPointer reports its byte count as UINT. + if (width > INT_MAX || height > INT_MAX || stride > UINT_MAX || + stride * height > UINT_MAX || + stride * height > (std::numeric_limits::max)()) + return GVFG_EINVAL; + pixels.resize(static_cast(stride * height)); + gvfg_osd_config_t render{}; + render.struct_size = sizeof(render); + render.width = width; + render.height = height; + render.text = config->text; + render.font_family = config->font_family; + render.text_length = static_cast(length); + render.font_size_px = config->font_size_px; + render.color_rgb = config->color_rgb; + status = gvfg_osd_render_bgra(helper.get(), &render, pixels.data(), pixels.size(), + static_cast(stride)); + if (status != GVFG_OSD_OK) + return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; + out_bitmap->data = pixels.data(); + out_bitmap->data_size = pixels.size(); + out_bitmap->width = width; + out_bitmap->height = height; + out_bitmap->stride = static_cast(stride); + return GVFG_OK; + } + catch (...) { return GVFG_EIO; } + } + + gvfg_status_t gvfg_render_osd_frame_bgra(uint32_t video_width, uint32_t video_height, + const gvfg_channel_osd_config_t *slot0, + const gvfg_channel_osd_config_t *slot1, + gvfg_osd_bitmap_t *out_bitmap) + { + thread_local std::vector frame; + frame.clear(); + if (!out_bitmap) + return GVFG_EINVAL; + *out_bitmap = {}; + const uint64_t stride = static_cast(video_width) * 4u; + if (!video_width || !video_height || stride > UINT32_MAX || + stride * video_height > UINT32_MAX || + stride * video_height > (std::numeric_limits::max)()) + return GVFG_EINVAL; + + try + { + frame.assign(static_cast(stride * video_height), 0); + std::vector tilePixels; + for (const auto *slot : {slot0, slot1}) + { + if (!slot) + continue; + gvfg_osd_bitmap_t tile{}; + const auto status = renderOsdBgraTile(slot, &tile, tilePixels); + if (status != GVFG_OK) + return status; + if (tile.width > video_width || tile.height > video_height) + continue; + + const size_t x = std::clamp(slot->x, 0, video_width - tile.width); + const size_t y = std::clamp(slot->y, 0, video_height - tile.height); + for (uint32_t row = 0; row < tile.height; ++row) + { + const auto *src = tile.data + static_cast(row) * tile.stride; + auto *dst = frame.data() + (y + row) * static_cast(stride) + x * 4u; + for (uint32_t col = 0; col < tile.width; ++col, src += 4, dst += 4) + { + if (!src[3]) + continue; + // Both layers are premultiplied, including at glyph edges. + const unsigned remaining = 255u - src[3]; + for (unsigned c = 0; c < 4; ++c) + dst[c] = static_cast(src[c] + (dst[c] * remaining + 127u) / 255u); + } + } + } + *out_bitmap = {frame.data(), frame.size(), video_width, video_height, + static_cast(stride)}; + return GVFG_OK; + } + catch (...) { return GVFG_EIO; } + } + + gvfg_status_t gvfg_set_channel_osd(gvfg_handle handle, int channel_index, + uint32_t index, const gvfg_channel_osd_config_t *config) + { + if (!config || index >= GVFG_OSD_SLOT_COUNT) + return gvfg_control_frame_processor(handle, channel_index, &processor, false, + nullptr, nullptr, "OSD config or index is invalid"); + const SlotCommand command{index, config, 0}; + return gvfg_control_frame_processor(handle, channel_index, &processor, true, + [](void *context, const void *argument) { + const auto &slot = *static_cast(argument); + return static_cast(context)->gpu.configure(slot.index, *slot.config); + }, &command, "Could not configure OSD slot"); + } + + gvfg_status_t gvfg_set_channel_osd_visible(gvfg_handle handle, int channel_index, + uint32_t index, int visible) + { + if (index >= GVFG_OSD_SLOT_COUNT || (visible != 0 && visible != 1)) + return gvfg_control_frame_processor(handle, channel_index, &processor, false, + nullptr, nullptr, "OSD index or visibility is invalid"); + const SlotCommand command{index, nullptr, visible}; + return gvfg_control_frame_processor(handle, channel_index, &processor, true, + [](void *context, const void *argument) { + const auto &slot = *static_cast(argument); + return static_cast(context)->gpu.setVisible(slot.index, slot.visible); + }, &command, "Could not change OSD visibility"); + } + + gvfg_status_t gvfg_clear_channel_osd(gvfg_handle handle, int channel_index, uint32_t index) + { + if (index >= GVFG_OSD_SLOT_COUNT) + return gvfg_control_frame_processor(handle, channel_index, &processor, false, + nullptr, nullptr, "OSD index is invalid"); + return gvfg_control_frame_processor(handle, channel_index, &processor, false, + [](void *context, const void *argument) { + return static_cast(context)->gpu.clear(*static_cast(argument)); + }, &index, "Could not clear OSD slot"); + } +} diff --git a/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_core.h b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_core.h new file mode 100644 index 0000000..9f47a63 --- /dev/null +++ b/GVFG_SDK/helpers/gvfg_osd/src/gvfg_osd_core.h @@ -0,0 +1,106 @@ +#ifndef GVFG_OSD_H +#define GVFG_OSD_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef GVFG_OSD_MAX_TEXT_CHARACTERS +#define GVFG_OSD_MAX_TEXT_CHARACTERS 32u +#endif + +typedef void *gvfg_osd_handle; + +typedef enum gvfg_osd_status_t +{ + GVFG_OSD_OK = 0, + GVFG_OSD_EINVAL = -1, + GVFG_OSD_ENOMEM = -2, + GVFG_OSD_ERENDER = -3 +} gvfg_osd_status_t; + +typedef enum gvfg_osd_pixel_format_t +{ + GVFG_OSD_PIXFMT_YUY2 = 1, + GVFG_OSD_PIXFMT_Y210 = 2 +} gvfg_osd_pixel_format_t; + +/* + * Generates an off-line OSD surface using the requested installed system font. Text is + * restricted to printable ASCII and at most GVFG_OSD_MAX_TEXT_CHARACTERS + * characters on one line without wrapping. color_rgb is 0xRRGGBB. + * x/y identify the top-left of the conservative measured text box (including + * glyph overhang and a one-pixel guard). They are clamped to keep that box + * inside the frame. Rendering returns EINVAL if the box cannot fit the frame. + * Output YUV uses BT.709 limited range. The mask is one coverage byte per + * pixel: 0 is transparent and 255 is fully covered. + */ +typedef struct gvfg_osd_config_t +{ + uint32_t struct_size; + uint32_t width; + uint32_t height; + uint32_t pixel_format; + const char *text; + const char *font_family; /* UTF-8, NUL-terminated. */ + uint32_t text_length; + int32_t x; + int32_t y; + uint32_t font_size_px; + uint32_t color_rgb; +} gvfg_osd_config_t; + +/* All buffers are caller-owned and are used only for the duration of render. */ +typedef struct gvfg_osd_output_t +{ + uint32_t struct_size; + void *yuv_data; + uint64_t yuv_size; + uint32_t yuv_stride; + void *mask_data; + uint64_t mask_size; + uint32_t mask_stride; +} gvfg_osd_output_t; + +gvfg_osd_status_t gvfg_osd_create( + gvfg_osd_handle *out_handle); + +void gvfg_osd_destroy( + gvfg_osd_handle handle); + +/* Conservative whole-text bounds in pixels, not pixel-tight raster bounds. */ +gvfg_osd_status_t gvfg_osd_measure( + gvfg_osd_handle handle, + const char *text, + uint32_t text_length, + uint32_t font_size_px, + const char *font_family, + uint32_t *out_width, + uint32_t *out_height); + +/* SDK-owned snapshot, invalidated by the next call. Serialize call/read access. */ +gvfg_osd_status_t gvfg_osd_get_fonts(uint32_t *out_count, const char *const **out_names); + +gvfg_osd_status_t gvfg_osd_render( + gvfg_osd_handle handle, + const gvfg_osd_config_t *config, + const gvfg_osd_output_t *output); + +/* Caller-owned, top-down BGRA8888 with premultiplied alpha. Ignores pixel_format. + * Unlike YUV output, width may be odd. No RGB/YUV conversion is performed. + */ +gvfg_osd_status_t gvfg_osd_render_bgra( + gvfg_osd_handle handle, + const gvfg_osd_config_t *config, + void *data, uint64_t data_size, uint32_t stride); + +const char *gvfg_osd_strerror( + gvfg_osd_status_t status); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/GVFG_SDK/helpers/gvfg_playback/include/gvfg_playback.h b/GVFG_SDK/helpers/gvfg_playback/include/gvfg_playback.h index 823953c..bd549cb 100644 --- a/GVFG_SDK/helpers/gvfg_playback/include/gvfg_playback.h +++ b/GVFG_SDK/helpers/gvfg_playback/include/gvfg_playback.h @@ -145,13 +145,15 @@ GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_submit_video(gvfg_playbac * Requires an attached window and a stopped handle. Caller data stays valid * through return. Used for RAW/DICOM image display; no audio is initialized. */ GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_present_image(gvfg_playback p, const gvfg_preview_frame_t *image); -/* In A/V mode an audio-output failure disables monitoring for this handle, - * preserving video playback. Subsequent audio submissions return EAUDIO. - * Keep capture/recording audio independent; do not retry output on this handle. - * Recreate the handle to retry monitoring. Stop/reset does not clear EAUDIO. +/* In A/V mode an unavailable audio output returns EAUDIO while video continues. + * With reconnect enabled, keep submitting new PCM so monitoring can resume + * when the default output becomes available. Otherwise recreate the handle + * to retry monitoring. Keep capture/recording audio independent. * A/V start may succeed with monitoring disabled; audio-only start still fails * if its output is unavailable. Other errors retain their normal meaning. */ GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_submit_audio(gvfg_playback p, const void *pcm, uint32_t bytes, uint64_t timestamp_ns); +/* Opt in before start. Retries the default Windows output in A/V mode only. */ +GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_enable_audio_reconnect(gvfg_playback p); GVFG_PLAYBACK_API gvfg_playback_status_t gvfg_playback_set_volume(gvfg_playback p, float gain); /* Default enabled=1. Set 0 for independent best-effort playback with no * automatic return to synchronization. May be called before start or while diff --git a/GVFG_SDK/helpers/gvfg_playback/src/gvfg_playback.cpp b/GVFG_SDK/helpers/gvfg_playback/src/gvfg_playback.cpp index 6f9e7b0..d373d66 100644 --- a/GVFG_SDK/helpers/gvfg_playback/src/gvfg_playback.cpp +++ b/GVFG_SDK/helpers/gvfg_playback/src/gvfg_playback.cpp @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -42,6 +44,8 @@ struct gvfg_playback_t { bool stopping = false, active = false; bool sync_enabled = true; bool audio_output_failed = false; + bool audio_reconnect_enabled = false; + uint64_t audio_retry_at = 0; float gain = 1.0f; void *hwnd = nullptr; SignalCard signal_card; @@ -94,14 +98,14 @@ struct gvfg_playback_t { if (!has_video()) { fail(GVFG_PLAYBACK_EOUTPUT); return; } if (audio_output_failed) return; audio_output_failed = true; + audio_retry_at = now_ns() + 1'000'000'000; drop_audio(); gvfg_audio_player_destroy(audio); audio = nullptr; audio_source_clock = {}; audio_timeline = {}; first_audio = audio_end = 0; stats.audio_timestamp_ns = 0; stats.av_difference_ns = 0; stats.audio_rate_ratio = 1; - // Retain video packets and move off a failed audio master. Monitoring - // remains disabled across resets; a fresh handle may retry the device. + // Retain video packets and move off a failed audio master. degrade(now_ns()); } void fail(gvfg_playback_status_t error) { @@ -130,11 +134,46 @@ struct gvfg_playback_t { }; void gvfg_playback_t::loop() { + using AudioPlayer = std::unique_ptr; + std::future audio_retry; uint64_t last_control = 0; bool started = false, preview_ready = false; for (;;) { std::unique_lock lock(mutex); if (stopping) break; + if (audio_retry.valid() && audio_retry.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + auto candidate = audio_retry.get(); + audio_retry_at = now_ns() + 1'000'000'000; + if (candidate && audio_output_failed) { + gvfg_audio_player_set_volume(candidate.get(), gain); + audio = candidate.release(); + last_audio_delivery = last_audio_arrival = 0; + recovery_rate = {}; + fallback_audio_primed = false; + audio_wait_since = stable_since = 0; + audio_output_failed = false; + } + } + if (audio_reconnect_enabled && config.mode == GVFG_PLAYBACK_AUDIO_VIDEO && + audio_output_failed && !audio_retry.valid() && now_ns() >= audio_retry_at && + stats.last_error == GVFG_PLAYBACK_OK) { + const auto format = config.audio_format; + try { + audio_retry = std::async(std::launch::async, [format] { + AudioPlayer candidate(nullptr, gvfg_audio_player_destroy); + try { + candidate.reset(audio_output_create_managed()); + if (candidate && gvfg_audio_player_start(candidate.get(), &format) != GVFG_AUDIO_PLAYBACK_OK) + candidate.reset(); + } catch (...) { + candidate.reset(); + } + return candidate; + }); + } catch (...) { + audio_retry_at = now_ns() + 1'000'000'000; + } + } if (stats.last_error != GVFG_PLAYBACK_OK) { changed.wait_for(lock, std::chrono::milliseconds(2)); continue; } @@ -555,6 +594,13 @@ gvfg_playback_status_t gvfg_playback_set_sync_enabled(gvfg_playback p, int enabl if (p->active && !p->sync_enabled) p->degrade(now_ns(), false); return GVFG_PLAYBACK_OK; } +gvfg_playback_status_t gvfg_playback_enable_audio_reconnect(gvfg_playback p) { + if (!p) return GVFG_PLAYBACK_EINVAL; + std::lock_guard lock(p->mutex); + if (p->active) return GVFG_PLAYBACK_ESTATE; + p->audio_reconnect_enabled = true; + return GVFG_PLAYBACK_OK; +} gvfg_playback_status_t gvfg_playback_stop(gvfg_playback p) { if (!p) return GVFG_PLAYBACK_EINVAL; { std::lock_guard lock(p->mutex); p->stopping = true; p->changed.notify_all(); } diff --git a/GVFG_SDK/sdk/gvfg/CMakeLists.txt b/GVFG_SDK/sdk/gvfg/CMakeLists.txt index 543fae4..4539dfe 100644 --- a/GVFG_SDK/sdk/gvfg/CMakeLists.txt +++ b/GVFG_SDK/sdk/gvfg/CMakeLists.txt @@ -16,8 +16,7 @@ add_library(gvfg SHARED src/gpu/d3d_conversion_pipeline.cpp src/gpu/d3d_conversion_pipeline.h src/gpu/gvfg_gpu_convert.cpp - src/gpu/gvfg_gpu_osd.cpp - src/gpu/gvfg_gpu_osd.h + src/gvfg_frame_processor.h src/gvfg_error_state.h src/gvfg_capture.cpp ) @@ -46,12 +45,8 @@ target_compile_definitions(gvfg PRIVATE target_compile_definitions(gvfg PRIVATE GVFG_INTERNAL_DIAGNOSTICS=$,$> ) -if (GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE) - target_compile_definitions(gvfg PRIVATE GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE=1) -endif() target_link_libraries(gvfg PRIVATE - gvfg_osd_core "${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/GigabyteLib/GvfgSdk.lib" setupapi user32 diff --git a/GVFG_SDK/sdk/gvfg/gvfg.def b/GVFG_SDK/sdk/gvfg/gvfg.def index 3e231fe..a3b3790 100644 --- a/GVFG_SDK/sdk/gvfg/gvfg.def +++ b/GVFG_SDK/sdk/gvfg/gvfg.def @@ -1,6 +1,7 @@ LIBRARY gvfg EXPORTS + gvfg_control_frame_processor gvfg_enumerate_devices gvfg_create gvfg_destroy @@ -8,12 +9,6 @@ EXPORTS gvfg_set_channel_zero_copy_enabled gvfg_get_channel_zero_copy_enabled gvfg_set_channel_video_format - gvfg_get_osd_fonts - gvfg_set_channel_osd_visible - gvfg_measure_osd_text - gvfg_render_osd_frame_bgra - gvfg_set_channel_osd - gvfg_clear_channel_osd gvfg_set_channel_audio_enabled gvfg_get_channel_audio_format gvfg_start_channel @@ -30,6 +25,7 @@ EXPORTS gvfg_stop_channel gvfg_get_channel_signal_status gvfg_get_channel_sdi_info + gvfg_get_channel_hdmi_audio_info gvfg_get_channel_hdmi_info gvfg_get_chip_info gvfg_get_channel_runtime_info @@ -41,8 +37,6 @@ EXPORTS gvfg_debug_get_channel_backend_stats gvfg_debug_read_channel_frame_timed gvfg_debug_read_channel_frame_profiled - gvfg_debug_get_channel_osd_experiment_flags - gvfg_debug_get_channel_osd_page_check gvfg_debug_get_device_capabilities gvfg_debug_set_user_led gvfg_debug_read_register diff --git a/GVFG_SDK/sdk/gvfg/include/gvfg_capture.h b/GVFG_SDK/sdk/gvfg/include/gvfg_capture.h index 2989871..dbe1d83 100644 --- a/GVFG_SDK/sdk/gvfg/include/gvfg_capture.h +++ b/GVFG_SDK/sdk/gvfg/include/gvfg_capture.h @@ -191,6 +191,17 @@ extern "C" char color_space_name[32]; } gvfg_hdmi_info_t; + typedef struct + { + int connected; /* HDMI audio signal lock. */ + uint32_t sample_frequency; /* HDMI audio sample-frequency code. */ + uint32_t bits_per_sample; + uint32_t channels; + uint32_t format; /* HDMI audio format code. */ + char sample_frequency_name[24]; + char format_name[24]; + } gvfg_hdmi_audio_info_t; + typedef struct { uint32_t version_date; /* Chip version date, interpreted in hexadecimal. */ @@ -227,35 +238,6 @@ extern "C" uint64_t timestamp_ns; /* Monotonic SDK delivery time; same clock domain as audio. */ } gvfg_frame_t; - /* Strings are copied synchronously by gvfg_set_channel_osd(). */ - typedef struct gvfg_channel_osd_config_t - { - const char *text; /* NUL-terminated printable ASCII, 1..32 characters. */ - const char *font_family; /* NUL-terminated UTF-8 installed font family name. */ - uint32_t font_size_px; /* Non-zero em size; 96-DPI rendering, not ink height. */ - uint32_t color_rgb; /* 0x00RRGGBB. */ - int32_t x; /* Text-box left in frame pixels; clamped to fit. */ - int32_t y; /* Text-box top in frame pixels; clamped to fit. */ - } gvfg_channel_osd_config_t; - - typedef struct gvfg_osd_font_list_t - { - uint32_t count; - const char *const *names; /* SDK-owned UTF-8 family names; do not modify/free. */ - } gvfg_osd_font_list_t; - - typedef struct gvfg_osd_bitmap_t - { - const uint8_t *data; /* SDK-owned; do not modify/free. See the render function's lifetime. */ - uint64_t data_size; /* stride * height bytes. */ - uint32_t width; - uint32_t height; - uint32_t stride; /* Byte distance between rows; width * 4. */ - } gvfg_osd_bitmap_t; - -#define GVFG_OSD_SLOT_COUNT 2u -#define GVFG_OSD_MAX_TEXT_CHARACTERS 32u - typedef struct { const void *data; /* PCM data. Valid until gvfg_release_channel_audio_frame(). */ @@ -394,75 +376,15 @@ extern "C" * Select the capture output format before capture starts. Only one channel * on a handle may select Y210 at a time; a conflicting request returns * GVFG_EBUSY. Applications may request either channel first. + * With a locked input, success means the hardware reports the selected + * format. Without a locked input, success means the request was accepted + * and its format will be verified when capture starts. */ GVFG_API gvfg_status_t gvfg_set_channel_video_format( GVFG_PARAM_IN gvfg_handle handle, GVFG_PARAM_IN int channel_index, GVFG_PARAM_IN gvfg_pixel_format_t format); - /* Refresh installed fonts and return an SDK-owned snapshot. No device needed. - * Pointers expire at the next call (including a failed call), or DLL unload. - * Copy names before then. Serialize calls and use of this borrowed list. - * Returns an empty list on failure; no callback or caller-side free is needed. - */ - GVFG_API gvfg_status_t gvfg_get_osd_fonts( - GVFG_PARAM_OUT gvfg_osd_font_list_t *out_list); - - /* Measure the same conservative text box used for rendering, including - * overhang and a one-pixel guard per edge. Ignores x/y/color; no device needed. - * Outputs are zeroed on failure. Missing font/invalid input: GVFG_EINVAL. - */ - GVFG_API gvfg_status_t gvfg_measure_osd_text( - GVFG_PARAM_IN const gvfg_channel_osd_config_t *config, - GVFG_PARAM_OUT uint32_t *out_width, - GVFG_PARAM_OUT uint32_t *out_height); - - /* Prepare one transparent video-sized overlay for FPGA transfer. No capture - * handle needed; pass the target video width/height in pixels. Output is - * top-down BGRA8888, premultiplied alpha, stride = width * 4. - * NULL slots are omitted (hidden/unused); both NULL produce a blank frame. - * x/y are frame coordinates, clamped to fit; oversized text is skipped. - * Slot 1 is composited over slot 0. No video pixels are included. - * Data is valid until the next call to this function on the same thread - * (including failure), thread exit or DLL unload. Copy for async transfer. - * Invalid inputs/dimensions (including byte size above UINT32_MAX) return - * GVFG_EINVAL; allocation/render failures return GVFG_EIO. On failure the - * output is empty. Does not affect GPU capture OSD. - */ - GVFG_API gvfg_status_t gvfg_render_osd_frame_bgra( - GVFG_PARAM_IN uint32_t video_width, - GVFG_PARAM_IN uint32_t video_height, - GVFG_PARAM_IN const gvfg_channel_osd_config_t *slot0, - GVFG_PARAM_IN const gvfg_channel_osd_config_t *slot1, - GVFG_PARAM_OUT gvfg_osd_bitmap_t *out_bitmap); - - /* Set and show slot 0 or 1 on an opened channel. Strings are copied before - * return; slot 1 is blended over slot 0. Applies to subsequent YUY2/Y210 - * frames using BT.709 limited range. X/Y are clamped to fit the text box. - * An oversized slot is skipped until settings/frame size allow it to fit; - * capture and the other slot continue. No wrapping/shrinking/truncation. - */ - GVFG_API gvfg_status_t gvfg_set_channel_osd( - GVFG_PARAM_IN gvfg_handle handle, - GVFG_PARAM_IN int channel_index, - GVFG_PARAM_IN uint32_t osd_index, - GVFG_PARAM_IN const gvfg_channel_osd_config_t *config); - - /* visible must be 0 or 1. Retains settings and cached glyph surfaces. - * Showing an unconfigured/cleared slot returns GVFG_ESTATE. - */ - GVFG_API gvfg_status_t gvfg_set_channel_osd_visible( - GVFG_PARAM_IN gvfg_handle handle, - GVFG_PARAM_IN int channel_index, - GVFG_PARAM_IN uint32_t osd_index, - GVFG_PARAM_IN int visible); - - /* Disable one slot and discard its settings and cached glyph surfaces. */ - GVFG_API gvfg_status_t gvfg_clear_channel_osd( - GVFG_PARAM_IN gvfg_handle handle, - GVFG_PARAM_IN int channel_index, - GVFG_PARAM_IN uint32_t osd_index); - /* * Enable or disable audio for the next channel start. Video remains * enabled; applications do not need to construct stream flag masks. @@ -487,7 +409,8 @@ extern "C" * - GVFG_OK on success, including when capture is already running. * - GVFG_EINVAL if handle is NULL. * - GVFG_ESTATE if no device is open. - * - GVFG_ETIMEOUT if a fresh signal query reports no connected input. + * - GVFG_ETIMEOUT if a fresh signal query reports no connected input or + * the hardware output format differs from the explicitly selected format. * - GVFG_EIO or another status code if stream configuration/start fails. * * After success, call gvfg_read_channel_frame() to receive frames and @@ -671,7 +594,9 @@ extern "C" * out_status->connected set to 0. Before capture starts, this function * refreshes the status from the capture backend. While capture is running, it returns * the SDK cache; format-change, input-plug and input-unplug processing updates - * that cache before the corresponding public event is queued. + * that cache before the corresponding public event is queued. If the + * current state cannot be confirmed after a change, returns an error + * until the cache is valid again. */ GVFG_API gvfg_status_t gvfg_get_channel_signal_status( GVFG_PARAM_IN gvfg_handle handle, @@ -688,6 +613,11 @@ extern "C" GVFG_PARAM_IN int channel_index, GVFG_PARAM_OUT gvfg_hdmi_info_t *out_info); + GVFG_API gvfg_status_t gvfg_get_channel_hdmi_audio_info( + GVFG_PARAM_IN gvfg_handle handle, + GVFG_PARAM_IN int channel_index, + GVFG_PARAM_OUT gvfg_hdmi_audio_info_t *out_info); + GVFG_API gvfg_status_t gvfg_get_chip_info( GVFG_PARAM_IN gvfg_handle handle, GVFG_PARAM_OUT gvfg_chip_info_t *out_info); diff --git a/GVFG_SDK/sdk/gvfg/include/gvfg_debug.h b/GVFG_SDK/sdk/gvfg/include/gvfg_debug.h index 8e88f35..8a5a339 100644 --- a/GVFG_SDK/sdk/gvfg/include/gvfg_debug.h +++ b/GVFG_SDK/sdk/gvfg/include/gvfg_debug.h @@ -103,55 +103,6 @@ typedef struct uint64_t acquisition_begin_ns; } gvfg_debug_frame_read_timing_t; -enum -{ - GVFG_DEBUG_OSD_EXPERIMENT_ENABLED = 1u, - GVFG_DEBUG_OSD_EXPERIMENT_USED = 2u, - GVFG_DEBUG_OSD_EXPERIMENT_REJECTED = 4u -}; - -typedef enum -{ - GVFG_DEBUG_OSD_PAGE_OK = 0, - GVFG_DEBUG_OSD_PAGE_NO_POINTER, - GVFG_DEBUG_OSD_PAGE_INVALID_RANGE, - GVFG_DEBUG_OSD_PAGE_QUERY_FAILED, - GVFG_DEBUG_OSD_PAGE_NOT_COMMITTED, - GVFG_DEBUG_OSD_PAGE_GUARD_OR_NOACCESS, - GVFG_DEBUG_OSD_PAGE_NOT_READWRITE, - GVFG_DEBUG_OSD_PAGE_INVALID_REGION -} gvfg_debug_osd_page_reason_t; - -/* Separate diagnostic type: existing timing/flags ABI remains unchanged. - * Native Windows values; win32_error is meaningful only for QUERY_FAILED. - * Does not expose addresses or imply DMA safety. */ -typedef struct -{ - uint32_t reason; - uint32_t protect; - uint32_t state; - uint32_t type; - uint32_t win32_error; - uint32_t query_bytes; -} gvfg_debug_osd_page_check_t; - -/* Query before releasing the matching successfully delivered frame. */ -GVFG_DEBUG_API gvfg_status_t gvfg_debug_get_channel_osd_page_check( - GVFG_PARAM_IN gvfg_handle handle, - GVFG_PARAM_IN int channel_index, - GVFG_PARAM_IN uint64_t frame_id, - GVFG_PARAM_OUT gvfg_debug_osd_page_check_t *out_check); - -/* frame_id=0 queries build configuration only. Otherwise the frame must still - * be held and its ID must match. Never implies a DMA ownership guarantee. - * Separate query preserves all existing timing struct layouts/read ABIs. - */ -GVFG_DEBUG_API gvfg_status_t gvfg_debug_get_channel_osd_experiment_flags( - GVFG_PARAM_IN gvfg_handle handle, - GVFG_PARAM_IN int channel_index, - GVFG_PARAM_IN uint64_t frame_id, - GVFG_PARAM_OUT uint32_t *out_flags); - GVFG_DEBUG_API gvfg_status_t gvfg_debug_read_channel_frame_profiled( GVFG_PARAM_IN gvfg_handle handle, GVFG_PARAM_IN int channel_index, diff --git a/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp b/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp index e59dee6..56d186d 100644 --- a/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp +++ b/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp @@ -183,6 +183,7 @@ namespace gvfg::internal if (channel_open_ && context_) GvfgCloseVideoChn(context_, channel_); channel_open_ = false; + driver_stream_running_ = false; { std::lock_guard lock(state_mutex_); video_info_valid_ = false; @@ -263,15 +264,24 @@ namespace gvfg::internal if (openStatus != GVFG_OK) return openStatus; - gvfg_pixel_format_t requestedFormat = GVFG_PIXFMT_UNKNOWN; + const gvfg_status_t readStatus = refresh_video_info(); + if (readStatus != GVFG_OK) + return readStatus; + + gvfg_pixel_format_t previousFormat = GVFG_PIXFMT_UNKNOWN; + bool signalConnected = false; { std::lock_guard lock(state_mutex_); - requestedFormat = requested_video_format_; + previousFormat = requested_video_format_; + signalConnected = cached_signal_.connected != 0; + if (signalConnected && cached_signal_.pixel_format == format) + { + requested_video_format_ = format; + format_change_pending_ = false; + return GVFG_OK; + } } - if (requestedFormat == format) - return GVFG_OK; - if (!events_.hVideoFormatChangedEvent) return reject(GVFG_EIO, "Capture backend did not provide a video-format event"); #ifndef NDEBUG @@ -286,14 +296,31 @@ namespace gvfg::internal : GVFG_VIDEO_COLOR_DEPTH_8_BITS; const gvfg_status_t status = from_vendor( GvfgSetVideoColorDepth(context_, channel_, colorDepth), "GvfgSetVideoColorDepth"); - if (status == GVFG_OK) + if (status != GVFG_OK) + return status; { std::lock_guard lock(state_mutex_); requested_video_format_ = format; format_change_pending_ = true; video_info_valid_ = false; } - return status; + // Without a locked input, verify the accepted request at start. + if (!signalConnected) + return GVFG_OK; + + gvfg_signal_status_t signal{}; + const gvfg_status_t verifyStatus = get_signal_status(signal, true); + if (verifyStatus == GVFG_OK && signal.connected) + return GVFG_OK; + + { + std::lock_guard lock(state_mutex_); + requested_video_format_ = previousFormat; + format_change_pending_ = false; + } + if (verifyStatus != GVFG_OK) + return verifyStatus; + return reject(GVFG_ETIMEOUT, "Input signal lost while verifying capture video format"); } gvfg_status_t GigabyteCaptureSession::refresh_video_info() @@ -325,7 +352,8 @@ namespace gvfg::internal return GVFG_OK; } - gvfg_status_t GigabyteCaptureSession::get_signal_status(gvfg_signal_status_t &out) + gvfg_status_t GigabyteCaptureSession::get_signal_status(gvfg_signal_status_t &out, + bool verifyRequestedFormat) { const gvfg_status_t openStatus = ensure_vendor_channel_open(); if (openStatus != GVFG_OK) @@ -352,33 +380,30 @@ namespace gvfg::internal return reject(GVFG_EIO, "Capture video-format event wait failed"); if (wait == WAIT_OBJECT_0) Sleep(kVideoFormatSettleMs); - - // Setting the already-active color depth does not necessarily emit a - // format-change event. Query once after the wait and accept the - // request when the hardware is already reporting the requested format. - const gvfg_status_t status = refresh_video_info(); - if (status != GVFG_OK) - return status; - - bool formatMatches = false; - { - std::lock_guard lock(state_mutex_); - format_change_pending_ = false; - formatMatches = cached_signal_.pixel_format == requestedFormat; - out = cached_signal_; - } - if (!formatMatches) - return reject(GVFG_ETIMEOUT, - "Capture video format did not match the requested format"); - return GVFG_OK; } + // The already-active color depth may not emit an event. Read the + // hardware status even when the event wait times out. const gvfg_status_t status = refresh_video_info(); if (status != GVFG_OK) return status; - std::lock_guard lock(state_mutex_); - out = cached_signal_; + { + std::lock_guard lock(state_mutex_); + if (formatChangePending && requested_video_format_ == requestedFormat) + format_change_pending_ = false; + out = cached_signal_; + } + if ((formatChangePending || verifyRequestedFormat) && out.connected && + requestedFormat != GVFG_PIXFMT_UNKNOWN && out.pixel_format != requestedFormat) + { + char message[128]{}; + std::snprintf(message, sizeof(message), + "Capture channel %d expected %s, hardware reports %s", + static_cast(channel_), gvfg_pixel_format_name(requestedFormat), + gvfg_pixel_format_name(static_cast(out.pixel_format))); + return reject(GVFG_ETIMEOUT, message); + } return GVFG_OK; } @@ -406,7 +431,7 @@ namespace gvfg::internal GVFG_HDMI_VIDEO_INPUT_INFO info{}; { - std::lock_guard captureLock(capture_mutex_); + std::lock_guard inputInfoLock(input_info_mutex_); const gvfg_status_t status = from_vendor( GvfgGetHdmiVideoInputInfo(context_, channel_, &info), "GvfgGetHdmiVideoInputInfo"); if (status != GVFG_OK) @@ -438,6 +463,49 @@ namespace gvfg::internal return GVFG_OK; } + gvfg_status_t GigabyteCaptureSession::get_hdmi_audio_info(gvfg_hdmi_audio_info_t &out) + { + const gvfg_status_t openStatus = ensure_vendor_channel_open(); + if (openStatus != GVFG_OK) + return openStatus; + + GVFG_HDMI_AUDIO_INPUT_INFO info{}; + { + std::lock_guard inputInfoLock(input_info_mutex_); + const gvfg_status_t status = from_vendor( + GvfgGetHdmiAudioInputInfo(context_, channel_, &info), "GvfgGetHdmiAudioInputInfo"); + if (status != GVFG_OK) + return status; + } + + out.connected = info.AudioSignalLock != 0; + out.sample_frequency = info.SamplesPerSec; + out.bits_per_sample = info.BitsPerSample; + out.channels = info.Channels; + out.format = info.Format; + if (!out.connected) + return GVFG_OK; + + // Indexed by GVFG_HDMI_AUDIO_SAMPLE_FREQ and GVFG_HDMI_AUDIO_FORMAT. + constexpr const char *frequencies[] = { + "32 kHz", "44.1 kHz", "48 kHz", "88.2 kHz", "96 kHz", "176.4 kHz", + "192 kHz", "HBR", "From stream" + }; + constexpr const char *formats[] = { + "Unknown", "Linear PCM", "AC-3", "MPEG-1", "MP3", "MPEG-2", "AAC", "DTS", + "ATRAC", "One Bit Audio", "Dolby Digital", "DTS-HD", "MAT", "DST", "WMA Pro" + }; + const char *frequency = out.sample_frequency < sizeof(frequencies) / sizeof(frequencies[0]) + ? frequencies[out.sample_frequency] : "Unknown"; + const char *format = out.format < sizeof(formats) / sizeof(formats[0]) + ? formats[out.format] : "Unknown"; + if (out.format == GVFG_HDMI_AUD_FMT_COMPRESSED_AUDIO) + format = "Compressed Audio"; + strncpy_s(out.sample_frequency_name, frequency, _TRUNCATE); + strncpy_s(out.format_name, format, _TRUNCATE); + return GVFG_OK; + } + gvfg_status_t GigabyteCaptureSession::get_chip_info(gvfg_chip_info_t &out) { const gvfg_status_t openStatus = ensure_vendor_channel_open(); @@ -469,9 +537,20 @@ namespace gvfg::internal const gvfg_status_t openStatus = ensure_vendor_channel_open(); if (openStatus != GVFG_OK) return openStatus; + std::lock_guard inputInfoLock(input_info_mutex_); GVFG_SDI_VIDEO_INFO info{}; - gvfg_status_t status = from_vendor( - GvfgGetSdiVideoInputInfo(context_, channel_, &info), "GvfgGetSdiVideoInputInfo"); + const GVFG_HRESULT result = GvfgGetSdiVideoInputInfo(context_, channel_, &info); + char debugMessage[256]; + std::snprintf(debugMessage, sizeof(debugMessage), + "[GVFG] GvfgGetSdiVideoInputInfo CH%" PRIu32 + " returned 0x%08" PRIX32 " | VideoSignalLock=%" PRIu32 + " | ErrorCount=%" PRIu32 "\n", + static_cast(channel_), static_cast(result), + static_cast(info.VideoSignalLock), + static_cast(info.ErrorCount)); + OutputDebugStringA(debugMessage); + + gvfg_status_t status = from_vendor(result, "GvfgGetSdiVideoInputInfo"); if (status != GVFG_OK) return status; GVFG_SDI_VIDEO_INFO_STR text{}; @@ -505,12 +584,7 @@ namespace gvfg::internal const gvfg_status_t openStatus = ensure_vendor_channel_open(); if (openStatus != GVFG_OK) return openStatus; - bool refresh = false; - { - std::lock_guard lock(state_mutex_); - refresh = !audio_info_valid_; - } - if (refresh) + if (!running_) { const gvfg_status_t status = refresh_audio_info(); if (status != GVFG_OK) @@ -518,6 +592,10 @@ namespace gvfg::internal } std::lock_guard lock(state_mutex_); out = {}; + if (recovery_pending_) + return GVFG_ETIMEOUT; + if (!audio_info_valid_) + return audio_info_status_; out.sample_rate = audio_info_.SamplesPerSec; out.channels = audio_info_.Channels; out.bits_per_sample = audio_info_.BitsPerSample; @@ -528,14 +606,19 @@ namespace gvfg::internal gvfg_status_t GigabyteCaptureSession::refresh_audio_info() { GVFG_AUDIO_INFO info{}; + std::lock_guard captureLock(capture_mutex_); const gvfg_status_t status = from_vendor( GvfgGetAudioInfo(context_, channel_, &info), "GvfgGetAudioInfo"); - if (status != GVFG_OK) - return status; std::lock_guard lock(state_mutex_); - audio_info_ = info; - audio_info_valid_ = true; - return GVFG_OK; + audio_info_ = {}; + audio_info_status_ = status; + audio_info_valid_ = status == GVFG_OK && info.cbBufSize && info.SamplesPerSec && + info.Channels && info.BitsPerSample; + if (audio_info_valid_) + audio_info_ = info; + else if (status == GVFG_OK) + audio_info_status_ = reject(GVFG_ETIMEOUT, "Capture audio format is unavailable"); + return audio_info_status_; } gvfg_status_t GigabyteCaptureSession::set_event_callback( @@ -554,14 +637,20 @@ namespace gvfg::internal const gvfg_status_t openStatus = ensure_vendor_channel_open(); if (openStatus != GVFG_OK) return openStatus; - // Clear stale frame notifications without consuming format or input events. + const gvfg_status_t status = reset_frame_events(); + configured_ = status == GVFG_OK; + return status; + } + + gvfg_status_t GigabyteCaptureSession::reset_frame_events() + { + // Preserve format and input events for the monitor. for (HANDLE frameEvent : {events_.hVideoFrameInEvent, events_.hVideoExtraFrame, events_.hAudioFrameInEvent, events_.hAudioExtraFrame}) { if (frameEvent && !ResetEvent(frameEvent)) return reject(GVFG_EIO, "Capture frame event reset failed"); } - configured_ = true; return GVFG_OK; } @@ -580,6 +669,7 @@ namespace gvfg::internal "GvfgStartCapture"); if (status != GVFG_OK) return status; + driver_stream_running_ = true; { std::lock_guard lock(state_mutex_); frame_held_ = false; @@ -613,12 +703,14 @@ namespace gvfg::internal if (wasRunning && channel_open_ && context_) { std::lock_guard captureLock(capture_mutex_); - const gvfg_status_t stopStatus = from_vendor(GvfgStopCapture(context_, channel_), - "GvfgStopCapture"); + const gvfg_status_t stopStatus = driver_stream_running_ + ? from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture") + : GVFG_OK; if (result == GVFG_OK) result = stopStatus; if (stopStatus == GVFG_OK) { + driver_stream_running_ = false; #ifndef NDEBUG if (events_.hVideoFormatChangedEvent && WaitForSingleObject(events_.hVideoFormatChangedEvent, 0) == WAIT_OBJECT_0) @@ -641,10 +733,14 @@ namespace gvfg::internal *acquisitionBeginNs = 0; if (!running_ || !context_) return reject(GVFG_ESTATE, "Capture frame read rejected: stream is not running"); + uint64_t generation = 0; { std::lock_guard lock(state_mutex_); + generation = signal_generation_; if (frame_held_) return reject(GVFG_ESTATE, "Capture frame read rejected: previous frame is held"); + if (!recovery_pending_ && !video_info_valid_ && video_info_status_ != GVFG_ETIMEOUT) + return video_info_status_; } std::array handles{stop_event_, recovery_event_, @@ -674,19 +770,23 @@ namespace gvfg::internal ++extra_video_event_wakes_; } + std::lock_guard captureLock(capture_mutex_); gvfg_signal_status_t signal{}; + size_t bytes = 0; { std::lock_guard lock(state_mutex_); + if (!running_) + return GVFG_ESTATE; + if (recovery_pending_ || generation != signal_generation_) + return GVFG_ETIMEOUT; + if (!video_info_valid_) + return video_info_status_; signal = cached_signal_; + bytes = video_info_.cbBufSize; } if (!signal.connected || signal.width == 0 || signal.height == 0) return GVFG_ETIMEOUT; - size_t bytes = 0; - { - std::lock_guard lock(state_mutex_); - bytes = video_info_.cbBufSize; - } const void *data = nullptr; void *zeroCopyData = nullptr; gvfg_status_t status = GVFG_OK; @@ -694,11 +794,8 @@ namespace gvfg::internal { void *buffer = nullptr; const auto begin = std::chrono::steady_clock::now(); - { - std::lock_guard captureLock(capture_mutex_); - status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer), - "GvfgGetVideoFrameZeroCopy"); - } + status = from_vendor(GvfgGetVideoFrameZeroCopy(context_, channel_, &buffer), + "GvfgGetVideoFrameZeroCopy"); const auto end = std::chrono::steady_clock::now(); record_get_frame_timing(std::chrono::duration(end - begin).count()); data = buffer; @@ -709,12 +806,9 @@ namespace gvfg::internal if (copy_buffer_.size() != bytes) copy_buffer_.assign(bytes, 0); const auto begin = std::chrono::steady_clock::now(); - { - std::lock_guard captureLock(capture_mutex_); - status = from_vendor(GvfgGetVideoFrame(context_, channel_, copy_buffer_.data(), - static_cast(copy_buffer_.size())), - "GvfgGetVideoFrame"); - } + status = from_vendor(GvfgGetVideoFrame(context_, channel_, copy_buffer_.data(), + static_cast(copy_buffer_.size())), + "GvfgGetVideoFrame"); const auto end = std::chrono::steady_clock::now(); record_get_frame_timing(std::chrono::duration(end - begin).count()); data = copy_buffer_.data(); @@ -750,20 +844,6 @@ namespace gvfg::internal return copy_buffer_.data(); } - uint8_t *GigabyteCaptureSession::experimental_zero_copy_frame_data(const gvfg_frame_t &frame) - { -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - std::lock_guard lock(state_mutex_); - if (!zero_copy_enabled_ || !frame_held_ || !held_zero_copy_data_ || - frame.data != held_zero_copy_data_ || frame.data_size != held_zero_copy_bytes_) - return nullptr; - return static_cast(held_zero_copy_data_); -#else - (void)frame; - return nullptr; -#endif - } - gvfg_status_t GigabyteCaptureSession::release_frame() { { @@ -779,25 +859,31 @@ namespace gvfg::internal return GVFG_OK; } - void GigabyteCaptureSession::get_cached_signal_status(gvfg_signal_status_t &out) const + gvfg_status_t GigabyteCaptureSession::get_cached_signal_status(gvfg_signal_status_t &out) const { std::lock_guard lock(state_mutex_); + out = {}; + if (recovery_pending_) + return GVFG_ETIMEOUT; + if (!video_info_valid_) + return video_info_status_; out = cached_signal_; + return GVFG_OK; } gvfg_status_t GigabyteCaptureSession::wait_audio( - uint32_t timeoutMs, void *destination, uint32_t destinationCapacity, uint32_t &outBytes) + uint32_t timeoutMs, std::vector &buffer, GigabyteAudioInfo &format) { - outBytes = 0; - if (!running_ || !audio_enabled_ || !destination) + format = {}; + if (!running_ || !audio_enabled_) return reject(GVFG_ESTATE, "Capture audio read rejected"); - uint32_t frameBytes = 0; + uint64_t generation = 0; { std::lock_guard lock(state_mutex_); - frameBytes = audio_info_.cbBufSize; + generation = signal_generation_; + if (!recovery_pending_ && !audio_info_valid_ && audio_info_status_ != GVFG_ETIMEOUT) + return audio_info_status_; } - if (frameBytes == 0 || frameBytes > destinationCapacity) - return reject(GVFG_EINVAL, "Capture audio destination is too small"); if (!events_.hAudioFrameInEvent) return reject(GVFG_EIO, "Capture backend did not provide an audio-frame event"); @@ -814,22 +900,30 @@ namespace gvfg::internal return wait_for_recovery(timeoutMs); if (wait != WAIT_OBJECT_0 + 2 && wait != WAIT_OBJECT_0 + 3) return reject(GVFG_EIO, "Capture audio event wait failed"); + std::lock_guard captureLock(capture_mutex_); { std::lock_guard lock(state_mutex_); + if (!running_) + return GVFG_ESTATE; + if (recovery_pending_ || generation != signal_generation_) + return GVFG_ETIMEOUT; + if (!audio_info_valid_) + return audio_info_status_; + format.sample_rate = audio_info_.SamplesPerSec; + format.channels = audio_info_.Channels; + format.bits_per_sample = audio_info_.BitsPerSample; + format.frame_bytes = audio_info_.cbBufSize; if (wait == WAIT_OBJECT_0 + 2) ++audio_event_wakes_; else ++extra_audio_event_wakes_; } - gvfg_status_t status = GVFG_OK; - { - std::lock_guard captureLock(capture_mutex_); - status = from_vendor(GvfgGetAudioFrame(context_, channel_, destination, frameBytes), - "GvfgGetAudioFrame"); - } + buffer.resize(format.frame_bytes); + const gvfg_status_t status = from_vendor( + GvfgGetAudioFrame(context_, channel_, buffer.data(), format.frame_bytes), + "GvfgGetAudioFrame"); if (status != GVFG_OK) return status; - outBytes = frameBytes; { std::lock_guard lock(state_mutex_); ++audio_frames_from_lib_; @@ -880,39 +974,10 @@ namespace gvfg::internal const int kind = kinds[wait - WAIT_OBJECT_0]; if (kind == 0 || !monitoring_) return; - if (kind == 1) - { -#ifndef NDEBUG - OutputDebugStringA("[GVFG] Received VIDEO_FORMAT_CHANGED\n"); -#endif - refresh_video_info(); - emit_event(GVFG_EVENT_VIDEO_FORMAT_CHANGED); - } - else if (kind == 2) - { - refresh_video_info(); - if (running_) - { - recovery_status_ = GVFG_OK; - recovery_pending_ = true; - SetEvent(recovery_event_); - recover_stream_after_plugin(); - // Recovery restarts the vendor stream. Refresh the geometry - // again before publishing the plug-in event to clients. - refresh_video_info(); - } - emit_event(GVFG_EVENT_VIDEO_INPUT_PLUGIN); - } - else if (kind == 3) - { - { - std::lock_guard lock(state_mutex_); - cached_signal_ = {}; - cached_signal_.channel = channel_; - video_info_valid_ = false; - } - emit_event(GVFG_EVENT_VIDEO_INPUT_UNPLUG); - } + constexpr std::array signalEvents{ + GVFG_EVENT_VIDEO_FORMAT_CHANGED, GVFG_EVENT_VIDEO_INPUT_PLUGIN, + GVFG_EVENT_VIDEO_INPUT_UNPLUG}; + handle_signal_event(signalEvents[static_cast(kind - 1)]); } } @@ -1042,7 +1107,100 @@ namespace gvfg::internal return status; } - gvfg_status_t GigabyteCaptureSession::recover_stream_after_plugin() + void GigabyteCaptureSession::handle_signal_event(gvfg_event_type_t event) + { + const bool unplugged = event == GVFG_EVENT_VIDEO_INPUT_UNPLUG; + GVFG_VIDEO_INFO previousVideo{}; + GVFG_AUDIO_INFO previousAudio{}; + bool previousVideoValid = false; + bool previousAudioValid = false; + { + std::lock_guard captureLock(capture_mutex_); + std::lock_guard stateLock(state_mutex_); + if (!running_) + return; + ++signal_generation_; + previousVideo = video_info_; + previousAudio = audio_info_; + previousVideoValid = video_info_valid_; + previousAudioValid = audio_info_valid_; + cached_signal_ = {}; + cached_signal_.channel = channel_; + video_info_ = {}; + audio_info_ = {}; + video_info_valid_ = unplugged; + audio_info_valid_ = false; + video_info_status_ = GVFG_ETIMEOUT; + audio_info_status_ = GVFG_ETIMEOUT; + recovery_status_ = GVFG_OK; + recovery_pending_ = !unplugged; + if (recovery_pending_) + SetEvent(recovery_event_); + } + + if (!unplugged) + { + gvfg_signal_status_t signal{}; + gvfg_status_t status = get_signal_status(signal, true); + if (status == GVFG_OK && !signal.connected) + status = reject(GVFG_ETIMEOUT, "Input signal is not locked during capture recovery"); + + gvfg_status_t audioStatus = GVFG_OK; + if (status == GVFG_OK && audio_enabled_) + audioStatus = refresh_audio_info(); + + bool restart = event == GVFG_EVENT_VIDEO_INPUT_PLUGIN || !previousVideoValid; + { + std::lock_guard lock(state_mutex_); + restart = restart || previousVideo.Fourcc != video_info_.Fourcc || + previousVideo.Width != video_info_.Width || + previousVideo.Height != video_info_.Height || + previousVideo.cbBufSize != video_info_.cbBufSize || + previousVideo.VideoSignalLock != video_info_.VideoSignalLock || + (audio_enabled_ && audio_info_valid_ && + (!previousAudioValid || + previousAudio.SamplesPerSec != audio_info_.SamplesPerSec || + previousAudio.Channels != audio_info_.Channels || + previousAudio.BitsPerSample != audio_info_.BitsPerSample || + previousAudio.cbBufSize != audio_info_.cbBufSize)); + } + + if (status == GVFG_OK && restart) + { + status = restart_stream_after_signal_change(); + if (status == GVFG_OK) + status = get_signal_status(signal, true); + if (status == GVFG_OK && !signal.connected) + status = reject(GVFG_ETIMEOUT, "Input signal lost after capture restarted"); + if (status == GVFG_OK && audio_enabled_) + audioStatus = refresh_audio_info(); + } + + { + std::lock_guard lock(state_mutex_); + if (status != GVFG_OK) + { + video_info_valid_ = false; + audio_info_valid_ = false; + video_info_status_ = status; + audio_info_status_ = status; + } + else if (audioStatus != GVFG_OK) + { + audio_info_valid_ = false; + audio_info_status_ = audioStatus; + } + recovery_status_ = status; + recovery_pending_ = false; + ResetEvent(recovery_event_); + } + recovery_cv_.notify_all(); + } + if (running_) + emit_event(event); + } + + gvfg_status_t GigabyteCaptureSession::restart_stream_after_signal_change() { { std::unique_lock stateLock(state_mutex_); @@ -1051,26 +1209,22 @@ namespace gvfg::internal } std::lock_guard captureLock(capture_mutex_); - if (!recovery_pending_) - { - ResetEvent(recovery_event_); - return GVFG_OK; - } if (!running_) + return GVFG_ESTATE; + if (driver_stream_running_) { - recovery_pending_ = false; - ResetEvent(recovery_event_); - recovery_cv_.notify_all(); - return GVFG_OK; + const gvfg_status_t stopStatus = + from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture"); + if (stopStatus != GVFG_OK) + return stopStatus; + driver_stream_running_ = false; } - - gvfg_status_t status = from_vendor(GvfgStopCapture(context_, channel_), "GvfgStopCapture"); - if (status == GVFG_OK) - status = from_vendor(GvfgStartCapture(context_, channel_), "GvfgStartCapture"); - recovery_status_ = status; - recovery_pending_ = false; - ResetEvent(recovery_event_); - recovery_cv_.notify_all(); + const gvfg_status_t resetStatus = reset_frame_events(); + if (resetStatus != GVFG_OK) + return resetStatus; + const gvfg_status_t status = + from_vendor(GvfgStartCapture(context_, channel_), "GvfgStartCapture"); + driver_stream_running_ = status == GVFG_OK; return status; } diff --git a/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.h b/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.h index 1a08382..5acf68c 100644 --- a/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.h +++ b/GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.h @@ -46,10 +46,12 @@ namespace gvfg::internal bool zero_copy_enabled() const { return zero_copy_enabled_; } gvfg_status_t set_audio_enabled(bool enabled); gvfg_status_t set_video_format(gvfg_pixel_format_t format); - gvfg_status_t get_signal_status(gvfg_signal_status_t &out); - void get_cached_signal_status(gvfg_signal_status_t &out) const; + gvfg_status_t get_signal_status(gvfg_signal_status_t &out, + bool verifyRequestedFormat); + gvfg_status_t get_cached_signal_status(gvfg_signal_status_t &out) const; gvfg_status_t get_device_capabilities(gvfg_debug_device_capabilities_t &out); gvfg_status_t get_sdi_info(gvfg_sdi_info_t &out); + gvfg_status_t get_hdmi_audio_info(gvfg_hdmi_audio_info_t &out); gvfg_status_t get_hdmi_info(gvfg_hdmi_info_t &out); gvfg_status_t get_chip_info(gvfg_chip_info_t &out); gvfg_status_t set_user_led(bool on); @@ -63,10 +65,8 @@ namespace gvfg::internal // Internal writable access only to the currently held SDK-owned copy. // Driver zero-copy buffers are never returned. Valid until release. uint8_t *writable_copy_frame_data(const gvfg_frame_t &frame); - // Opt-in test candidate only, not a driver write/hold guarantee. - uint8_t *experimental_zero_copy_frame_data(const gvfg_frame_t &frame); - gvfg_status_t wait_audio(uint32_t timeoutMs, void *destination, - uint32_t destinationCapacity, uint32_t &outBytes); + gvfg_status_t wait_audio(uint32_t timeoutMs, std::vector &buffer, + GigabyteAudioInfo &format); gvfg_status_t release_frame(); void fill_debug_stats(gvfg_debug_backend_stats_t &out); gvfg_status_t debug_read_register(uint32_t offset, uint32_t &outValue); @@ -80,7 +80,9 @@ namespace gvfg::internal void stop_event_monitoring(); void event_thread_proc(); void emit_event(gvfg_event_type_t type) const; - gvfg_status_t recover_stream_after_plugin(); + void handle_signal_event(gvfg_event_type_t event); + gvfg_status_t restart_stream_after_signal_change(); + gvfg_status_t reset_frame_events(); gvfg_status_t wait_for_recovery(uint32_t timeoutMs); gvfg_status_t refresh_video_info(); gvfg_status_t refresh_audio_info(); @@ -98,6 +100,9 @@ namespace gvfg::internal bool events_created_ = false; bool channel_open_ = false; bool video_info_valid_ = false; + gvfg_status_t video_info_status_ = GVFG_ETIMEOUT; + gvfg_status_t audio_info_status_ = GVFG_ETIMEOUT; + uint64_t signal_generation_ = 0; bool format_change_pending_ = false; gvfg_pixel_format_t requested_video_format_ = GVFG_PIXFMT_UNKNOWN; bool audio_info_valid_ = false; @@ -108,6 +113,7 @@ namespace gvfg::internal bool configured_ = false; bool zero_copy_enabled_ = false; bool audio_enabled_ = false; + bool driver_stream_running_ = false; // Protected by capture_mutex_ while open. std::atomic running_{false}; std::atomic recovery_pending_{false}; std::atomic recovery_status_{GVFG_OK}; @@ -119,6 +125,7 @@ namespace gvfg::internal mutable std::mutex state_mutex_; std::condition_variable recovery_cv_; std::mutex capture_mutex_; + std::mutex input_info_mutex_; std::vector copy_buffer_; bool frame_held_ = false; void *held_zero_copy_data_ = nullptr; diff --git a/GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp b/GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp index 409172f..bce9ea4 100644 --- a/GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp +++ b/GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp @@ -6,8 +6,7 @@ #include "gvfg_debug.h" #include "gigabyte_capture_session.h" -#include "gpu/gvfg_gpu_osd.h" -#include "gvfg_osd.h" +#include "gvfg_frame_processor.h" #include "gvfgframework.h" #include @@ -199,7 +198,8 @@ struct gvfg_channel_session_t return cfg; if (audioEnabled) { - const gvfg_status_t audioStatus = session->get_audio_format(cachedAudioFormat); + GigabyteAudioInfo format{}; + const gvfg_status_t audioStatus = session->get_audio_format(format); if (audioStatus != GVFG_OK) return audioStatus; } @@ -315,13 +315,13 @@ struct gvfg_channel_session_t eventCv.notify_one(); } - gvfg_status_t querySignal() + gvfg_status_t querySignal(bool verifyRequestedFormat = false) { if (!session) return GVFG_ESTATE; gvfg_signal_status_t sig{}; - const gvfg_status_t status = session->get_signal_status(sig); + const gvfg_status_t status = session->get_signal_status(sig, verifyRequestedFormat); std::lock_guard lock(stateMutex); width = status == GVFG_OK ? sig.width : 0; @@ -341,7 +341,7 @@ struct gvfg_channel_session_t return GVFG_ESTATE; gvfg_signal_status_t sig{}; - session->get_cached_signal_status(sig); + const gvfg_status_t status = session->get_cached_signal_status(sig); std::lock_guard lock(stateMutex); width = sig.width > 0 ? static_cast(sig.width) : 0; @@ -350,7 +350,7 @@ struct gvfg_channel_session_t pixelFormat = static_cast(sig.pixel_format); videoInterface = sig.video_interface; signalConnected = sig.connected != 0; - return GVFG_OK; + return status; } gvfg_status_t configureStream() @@ -358,7 +358,7 @@ struct gvfg_channel_session_t if (!session) return reject(GVFG_ESTATE, "configure stream rejected: channel is not open"); - const gvfg_status_t signalStatus = querySignal(); + const gvfg_status_t signalStatus = querySignal(true); if (signalStatus != GVFG_OK) return signalStatus; { @@ -430,28 +430,23 @@ struct gvfg_channel_session_t } bool osdApplied = false; - int processedStride = 0; - // This capability comes from the backend, never from const_cast of a - // public frame pointer. Driver storage is excluded by default; only - // the explicit unsafe build option below can admit it for experiments. - uint8_t *writableSource = session->writable_copy_frame_data(frame); - bool experimentalZeroCopy = false; - bool inPlaceApplied = false; - uint32_t experimentFlags = 0; - gvfg_debug_osd_page_check_t pageCheck{}; -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - experimentFlags = GVFG_DEBUG_OSD_EXPERIMENT_ENABLED; - if (!writableSource) + gvfg_frame_t processedFrame{}; + const gvfg_frame_processor *processor = nullptr; + void *processorContext = nullptr; { - writableSource = session->experimental_zero_copy_frame_data(frame); - experimentalZeroCopy = writableSource != nullptr; + std::lock_guard lock(processorMutex); + processor = frameProcessor.ops; + processorContext = frameProcessor.context; } -#endif + // Only SDK-owned copy-mode buffers are available for in-place writes. + uint8_t *writableSource = processor ? session->writable_copy_frame_data(frame) : nullptr; + bool inPlaceApplied = false; const uint64_t processBeginNs = timing ? now_ns() : 0; - const gvfg_status_t osdStatus = - osdProcessor.process(frame, processedVideoBuffer, processedStride, osdApplied, timing, - writableSource, experimentalZeroCopy, &inPlaceApplied, &experimentFlags, &pageCheck); - if (timing) + const gvfg_status_t osdStatus = processor + ? processor->process(processorContext, frame, processedFrame, osdApplied, timing, + writableSource, &inPlaceApplied) + : GVFG_OK; + if (timing && processor) timing->stage_ms[GVFG_DEBUG_OSD_PROCESS_TOTAL] = static_cast(now_ns() - processBeginNs) / 1e6; if (osdStatus != GVFG_OK) { @@ -477,9 +472,9 @@ struct gvfg_channel_session_t return releaseStatus; } backendFrameHeld = false; - frame.data = processedVideoBuffer.data(); - frame.data_size = static_cast(processedVideoBuffer.size()); - frame.row_stride_bytes = processedStride; + frame.data = processedFrame.data; + frame.data_size = processedFrame.data_size; + frame.row_stride_bytes = processedFrame.row_stride_bytes; } bool stoppedWhileWaiting = false; @@ -494,8 +489,6 @@ struct gvfg_channel_session_t { frame.frame_id = ++videoFrameId; heldSessionFrame = frame; - heldOsdExperimentFlags = experimentFlags; - heldOsdPageCheck = pageCheck; heldFrameNeedsBackendRelease = backendFrameHeld; readInProgress = false; frameHeld = true; @@ -526,31 +519,6 @@ struct gvfg_channel_session_t return GVFG_OK; } - gvfg_status_t osdExperimentFlags(uint64_t frameId, uint32_t &flags) - { - flags = 0; -#ifdef GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE - flags = GVFG_DEBUG_OSD_EXPERIMENT_ENABLED; -#endif - if (frameId == 0) - return GVFG_OK; - std::lock_guard lock(frameMutex); - if (!frameHeld || heldSessionFrame.frame_id != frameId) - return GVFG_ESTATE; - flags = heldOsdExperimentFlags; - return GVFG_OK; - } - - gvfg_status_t osdPageCheck(uint64_t frameId, gvfg_debug_osd_page_check_t &check) - { - check = {}; - std::lock_guard lock(frameMutex); - if (!frameId || !frameHeld || heldSessionFrame.frame_id != frameId) - return GVFG_ESTATE; - check = heldOsdPageCheck; - return GVFG_OK; - } - gvfg_status_t releaseFrame(const gvfg_frame_t &frameToken) { if (!session) @@ -684,31 +652,28 @@ struct gvfg_channel_session_t return session->set_video_format(format); } - gvfg_status_t setOsd(uint32_t index, const gvfg_channel_osd_config_t &config) + gvfg_status_t controlFrameProcessor(const gvfg_frame_processor *processor, bool create, + gvfg_frame_processor_control control, const void *argument, + const char *error) { if (!session) - return reject(GVFG_ESTATE, "gvfg_set_channel_osd rejected: channel is not open"); - const gvfg_status_t status = osdProcessor.configure(index, config); - return status == GVFG_OK - ? GVFG_OK - : reject(status, status == GVFG_EINVAL - ? "gvfg_set_channel_osd rejected: configuration is invalid" - : "gvfg_set_channel_osd failed to store configuration"); - } + return reject(GVFG_ESTATE, "Frame processor channel is not open"); - gvfg_status_t clearOsd(uint32_t index) - { - if (!session) - return reject(GVFG_ESTATE, "gvfg_clear_channel_osd rejected: channel is not open"); - return osdProcessor.clear(index); - } + std::lock_guard lock(processorMutex); + if (!frameProcessor.ops) + { + if (!create) + return GVFG_OK; + const auto status = processor->create(&frameProcessor.context); + if (status != GVFG_OK) + return reject(status, error); + frameProcessor.ops = processor; + } + if (frameProcessor.ops != processor) + return reject(GVFG_ESTATE, "A different frame processor is already attached"); - gvfg_status_t setOsdVisible(uint32_t index, int visible) - { - if (!session) - return reject(GVFG_ESTATE, "OSD visibility rejected: channel is not open"); - const gvfg_status_t status = osdProcessor.setVisible(index, visible); - return status == GVFG_OK ? status : reject(status, "OSD visibility rejected: invalid slot, visibility, or no saved configuration"); + const auto status = control(frameProcessor.context, argument); + return status == GVFG_OK ? status : reject(status, error); } gvfg_status_t setAudioEnabled(bool enabled) @@ -740,7 +705,6 @@ struct gvfg_channel_session_t const gvfg_status_t status = session->get_audio_format(format); if (status != GVFG_OK) return status; - cachedAudioFormat = format; out.sample_rate = format.sample_rate; out.channels = format.channels; out.bits_per_sample = format.bits_per_sample; @@ -764,26 +728,19 @@ struct gvfg_channel_session_t audioReadInProgress = true; } - const GigabyteAudioInfo format = cachedAudioFormat; - gvfg_status_t status = format.frame_bytes != 0 ? GVFG_OK : GVFG_ESTATE; - uint32_t bytes = 0; - if (status == GVFG_OK) - { - audioBuffer.resize(format.frame_bytes); - status = session->wait_audio(timeoutMs, audioBuffer.data(), - static_cast(audioBuffer.size()), bytes); - } + GigabyteAudioInfo format{}; + const gvfg_status_t status = session->wait_audio(timeoutMs, audioBuffer, format); { std::lock_guard lock(audioMutex); audioReadInProgress = false; if (status != GVFG_OK) return status; - if (!running.load(std::memory_order_acquire) || bytes == 0 || bytes > audioBuffer.size()) + if (!running.load(std::memory_order_acquire)) return reject(GVFG_ESTATE, "gvfg_read_channel_audio_frame completed after capture stopped or returned invalid data"); audioFrameHeld = true; out.data = audioBuffer.data(); - out.data_size = bytes; + out.data_size = format.frame_bytes; out.sample_rate = format.sample_rate; out.channels = format.channels; out.bits_per_sample = format.bits_per_sample; @@ -871,7 +828,6 @@ struct gvfg_channel_session_t uint32_t selectedChannel = GVFG_CHANNEL_0; bool zeroCopyRequested = false; bool audioEnabled = false; - GigabyteAudioInfo cachedAudioFormat{}; uint32_t width = 0; uint32_t height = 0; @@ -892,14 +848,22 @@ struct gvfg_channel_session_t std::atomic running{false}; std::mutex frameMutex; bool readInProgress = false; - uint32_t heldOsdExperimentFlags = 0; - gvfg_debug_osd_page_check_t heldOsdPageCheck{}; bool frameHeld = false; bool heldFrameNeedsBackendRelease = false; uint64_t videoFrameId = 0; gvfg_frame_t heldSessionFrame{}; - gvfg::internal::GpuOsdProcessor osdProcessor; - std::vector processedVideoBuffer; + std::mutex processorMutex; + struct FrameProcessorState + { + const gvfg_frame_processor *ops = nullptr; + void *context = nullptr; + + ~FrameProcessorState() + { + if (ops) + ops->destroy(context); + } + } frameProcessor; std::mutex audioMutex; std::vector audioBuffer; bool audioReadInProgress = false; @@ -1212,179 +1176,18 @@ extern "C" return handle->setChannelVideoFormat(channel_index, format); } - gvfg_status_t gvfg_get_osd_fonts(gvfg_osd_font_list_t *out_list) - { - if (!out_list) - return GVFG_EINVAL; - *out_list = {}; - const auto status = gvfg_osd_get_fonts(&out_list->count, &out_list->names); - return status == GVFG_OSD_OK ? GVFG_OK : GVFG_EIO; - } - - gvfg_status_t gvfg_measure_osd_text(const gvfg_channel_osd_config_t *config, - uint32_t *out_width, uint32_t *out_height) - { - if (out_width) *out_width = 0; - if (out_height) *out_height = 0; - if (!config || !config->text || !out_width || !out_height) - return GVFG_EINVAL; - const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u); - if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS) - return GVFG_EINVAL; - try - { - gvfg_osd_handle rawHandle = nullptr; - if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK) - return GVFG_EIO; - const std::unique_ptr helper(rawHandle, &gvfg_osd_destroy); - const auto status = gvfg_osd_measure(helper.get(), config->text, - static_cast(length), config->font_size_px, config->font_family, - out_width, out_height); - return status == GVFG_OSD_OK ? GVFG_OK : - status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; - } - catch (...) { return GVFG_EIO; } - } - - static gvfg_status_t renderOsdBgraTile(const gvfg_channel_osd_config_t *config, - gvfg_osd_bitmap_t *out_bitmap, - std::vector &pixels) - { - if (!config || !config->text) - return GVFG_EINVAL; - const size_t length = strnlen_s(config->text, GVFG_OSD_MAX_TEXT_CHARACTERS + 1u); - if (length == 0 || length > GVFG_OSD_MAX_TEXT_CHARACTERS) - return GVFG_EINVAL; - try - { - gvfg_osd_handle rawHandle = nullptr; - if (gvfg_osd_create(&rawHandle) != GVFG_OSD_OK) - return GVFG_EIO; - const std::unique_ptr helper(rawHandle, &gvfg_osd_destroy); - uint32_t width = 0, height = 0; - auto status = gvfg_osd_measure(helper.get(), config->text, - static_cast(length), config->font_size_px, config->font_family, - &width, &height); - if (status != GVFG_OSD_OK) - return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; - const uint64_t stride = static_cast(width) * 4u; - // WIC GetDataPointer reports its byte count as UINT. - if (width > INT_MAX || height > INT_MAX || stride > UINT_MAX || - stride * height > UINT_MAX || - stride * height > (std::numeric_limits::max)()) - return GVFG_EINVAL; - pixels.resize(static_cast(stride * height)); - gvfg_osd_config_t render{}; - render.struct_size = sizeof(render); - render.width = width; - render.height = height; - render.text = config->text; - render.font_family = config->font_family; - render.text_length = static_cast(length); - render.font_size_px = config->font_size_px; - render.color_rgb = config->color_rgb; - status = gvfg_osd_render_bgra(helper.get(), &render, pixels.data(), pixels.size(), - static_cast(stride)); - if (status != GVFG_OSD_OK) - return status == GVFG_OSD_EINVAL ? GVFG_EINVAL : GVFG_EIO; - out_bitmap->data = pixels.data(); - out_bitmap->data_size = pixels.size(); - out_bitmap->width = width; - out_bitmap->height = height; - out_bitmap->stride = static_cast(stride); - return GVFG_OK; - } - catch (...) { return GVFG_EIO; } - } - - gvfg_status_t gvfg_render_osd_frame_bgra(uint32_t video_width, uint32_t video_height, - const gvfg_channel_osd_config_t *slot0, - const gvfg_channel_osd_config_t *slot1, - gvfg_osd_bitmap_t *out_bitmap) - { - thread_local std::vector frame; - frame.clear(); - if (!out_bitmap) - return GVFG_EINVAL; - *out_bitmap = {}; - const uint64_t stride = static_cast(video_width) * 4u; - if (!video_width || !video_height || stride > UINT32_MAX || - stride * video_height > UINT32_MAX || - stride * video_height > (std::numeric_limits::max)()) - return GVFG_EINVAL; - - try - { - frame.assign(static_cast(stride * video_height), 0); - std::vector tilePixels; - for (const auto *slot : {slot0, slot1}) - { - if (!slot) - continue; - gvfg_osd_bitmap_t tile{}; - const auto status = renderOsdBgraTile(slot, &tile, tilePixels); - if (status != GVFG_OK) - return status; - if (tile.width > video_width || tile.height > video_height) - continue; - - const size_t x = std::clamp(slot->x, 0, video_width - tile.width); - const size_t y = std::clamp(slot->y, 0, video_height - tile.height); - for (uint32_t row = 0; row < tile.height; ++row) - { - const auto *src = tile.data + static_cast(row) * tile.stride; - auto *dst = frame.data() + (y + row) * static_cast(stride) + x * 4u; - for (uint32_t col = 0; col < tile.width; ++col, src += 4, dst += 4) - { - if (!src[3]) - continue; - // Both layers are premultiplied, including at glyph edges. - const unsigned remaining = 255u - src[3]; - for (unsigned c = 0; c < 4; ++c) - dst[c] = static_cast(src[c] + (dst[c] * remaining + 127u) / 255u); - } - } - } - *out_bitmap = {frame.data(), frame.size(), video_width, video_height, - static_cast(stride)}; - return GVFG_OK; - } - catch (...) { return GVFG_EIO; } - } - - gvfg_status_t gvfg_set_channel_osd(gvfg_handle handle, int channel_index, - uint32_t osd_index, const gvfg_channel_osd_config_t *config) + gvfg_status_t gvfg_control_frame_processor( + gvfg_handle handle, int channel_index, const gvfg_frame_processor *processor, + bool create, gvfg_frame_processor_control control, const void *argument, + const char *error) { if (!handle) return GVFG_EINVAL; - if (!config || osd_index >= GVFG_OSD_SLOT_COUNT) - return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD config or index is invalid"); + if (!control) + return handle->rejectChannel(channel_index, GVFG_EINVAL, error); auto *channel = handle->findChannel(channel_index); - return channel ? channel->setOsd(osd_index, *config) - : handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open"); - } - - gvfg_status_t gvfg_set_channel_osd_visible(gvfg_handle handle, int channel_index, - uint32_t osd_index, int visible) - { - if (!handle) - return GVFG_EINVAL; - if (osd_index >= GVFG_OSD_SLOT_COUNT || (visible != 0 && visible != 1)) - return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD index or visibility is invalid"); - auto *channel = handle->findChannel(channel_index); - return channel ? channel->setOsdVisible(osd_index, visible) - : handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open"); - } - - gvfg_status_t gvfg_clear_channel_osd(gvfg_handle handle, int channel_index, uint32_t osd_index) - { - if (!handle) - return GVFG_EINVAL; - if (osd_index >= GVFG_OSD_SLOT_COUNT) - return handle->rejectChannel(channel_index, GVFG_EINVAL, "OSD index is invalid"); - auto *channel = handle->findChannel(channel_index); - return channel ? channel->clearOsd(osd_index) - : handle->rejectChannel(channel_index, GVFG_ESTATE, "OSD channel is not open"); + return channel ? channel->controlFrameProcessor(processor, create, control, argument, error) + : handle->rejectChannel(channel_index, GVFG_ESTATE, "Frame processor channel is not open"); } gvfg_status_t gvfg_set_channel_audio_enabled(gvfg_handle handle, @@ -1467,32 +1270,6 @@ extern "C" "gvfg_debug_read_channel_frame_profiled rejected: channel is not open"); } - gvfg_status_t gvfg_debug_get_channel_osd_experiment_flags(gvfg_handle handle, - int channel_index, - uint64_t frame_id, - uint32_t *out_flags) - { - if (out_flags) - *out_flags = 0; - if (!handle || !out_flags) - return GVFG_EINVAL; - gvfg_channel_session_t *channel = handle->findChannel(channel_index); - return channel ? channel->osdExperimentFlags(frame_id, *out_flags) : GVFG_ESTATE; - } - - gvfg_status_t gvfg_debug_get_channel_osd_page_check(gvfg_handle handle, - int channel_index, - uint64_t frame_id, - gvfg_debug_osd_page_check_t *out_check) - { - if (out_check) - *out_check = {}; - if (!handle || !out_check) - return GVFG_EINVAL; - gvfg_channel_session_t *channel = handle->findChannel(channel_index); - return channel ? channel->osdPageCheck(frame_id, *out_check) : GVFG_ESTATE; - } - gvfg_status_t gvfg_release_channel_frame(gvfg_handle handle, int channel_index, const gvfg_frame_t *frame) @@ -1654,6 +1431,24 @@ extern "C" return channel->session->get_hdmi_info(*out_info); } + gvfg_status_t gvfg_get_channel_hdmi_audio_info( + gvfg_handle handle, int channel_index, gvfg_hdmi_audio_info_t *out_info) + { + if (!handle || (channel_index != GVFG_CHANNEL_0 && channel_index != GVFG_CHANNEL_1)) + return GVFG_EINVAL; + if (!out_info) + return handle->rejectChannel( + channel_index, GVFG_EINVAL, + "gvfg_get_channel_hdmi_audio_info rejected: out_info is null"); + *out_info = {}; + auto *channel = handle->findChannel(channel_index); + if (!channel || !channel->session) + return handle->rejectChannel( + channel_index, GVFG_ESTATE, + "gvfg_get_channel_hdmi_audio_info rejected: channel is not open"); + return channel->session->get_hdmi_audio_info(*out_info); + } + gvfg_status_t gvfg_get_chip_info(gvfg_handle handle, gvfg_chip_info_t *out_info) { if (!handle) diff --git a/GVFG_SDK/sdk/gvfg/src/gvfg_frame_processor.h b/GVFG_SDK/sdk/gvfg/src/gvfg_frame_processor.h new file mode 100644 index 0000000..fd9c17c --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/src/gvfg_frame_processor.h @@ -0,0 +1,19 @@ +#pragma once + +#include "gvfg_debug.h" + +struct gvfg_frame_processor +{ + gvfg_status_t (*create)(void **); + void (*destroy)(void *); + gvfg_status_t (*process)(void *, const gvfg_frame_t &, gvfg_frame_t &, + bool &, gvfg_debug_osd_frame_timing_t *, uint8_t *, + bool *); +}; + +using gvfg_frame_processor_control = gvfg_status_t (*)(void *, const void *); + +extern "C" GVFG_API gvfg_status_t gvfg_control_frame_processor( + gvfg_handle handle, int channel, const gvfg_frame_processor *processor, + bool create, gvfg_frame_processor_control control, const void *argument, + const char *error); diff --git a/GVFG_SDK/third_party/GigabyteLib/GvfgSdk.lib b/GVFG_SDK/third_party/GigabyteLib/GvfgSdk.lib index bd72f8c..3cfa206 100644 Binary files a/GVFG_SDK/third_party/GigabyteLib/GvfgSdk.lib and b/GVFG_SDK/third_party/GigabyteLib/GvfgSdk.lib differ diff --git a/GVFG_SDK/third_party/GigabyteLib/gvfgframework.h b/GVFG_SDK/third_party/GigabyteLib/gvfgframework.h index ef3c988..a79af35 100644 --- a/GVFG_SDK/third_party/GigabyteLib/gvfgframework.h +++ b/GVFG_SDK/third_party/GigabyteLib/gvfgframework.h @@ -29,7 +29,7 @@ extern "C" { #define GVFG_PARAM_OUT #define GVFG_SDK_API -#define GVFG_SDK_VER "1.0.4" +#define GVFG_SDK_VER "1.0.5" #ifdef __cplusplus diff --git a/GVFG_SDK/third_party/GigabyteLib/gvfgsdkapi.h b/GVFG_SDK/third_party/GigabyteLib/gvfgsdkapi.h index fd92542..5335a5b 100644 --- a/GVFG_SDK/third_party/GigabyteLib/gvfgsdkapi.h +++ b/GVFG_SDK/third_party/GigabyteLib/gvfgsdkapi.h @@ -43,6 +43,50 @@ extern "C" { typedef struct _GVFG_CONTEXT GVFG_CONTEXT, *PGVFG_CONTEXT; + +typedef enum +{ + // HDMI Audio Format + + GVFG_HDMI_AUD_FMT_LINEAR_PCM = 1, + GVFG_HDMI_AUD_FMT_AC3 = 2, + GVFG_HDMI_AUD_FMT_MPEG1 = 3, + GVFG_HDMI_AUD_FMT_MP3 = 4, + GVFG_HDMI_AUD_FMT_MPEG2 = 5, + GVFG_HDMI_AUD_FMT_AAC = 6, + GVFG_HDMI_AUD_FMT_DTS = 7, + GVFG_HDMI_AUD_FMT_ATRAC = 8, + GVFG_HDMI_AUD_FMT_ONE_BIT_HDMI_AUDIO = 9, + GVFG_HDMI_AUD_FMT_DOLBY_DIGITAL = 10, + GVFG_HDMI_AUD_FMT_DTS_HD = 11, + GVFG_HDMI_AUD_FMT_MAT = 12, + GVFG_HDMI_AUD_FMT_DST = 13, + GVFG_HDMI_AUD_FMT_WMA_PRO = 14, + GVFG_HDMI_AUD_FMT_ID_MAX_SIZE = 15, + GVFG_HDMI_AUD_FMT_COMPRESSED_AUDIO = 0xff + +} GVFG_HDMI_AUDIO_FORMAT; + + + +typedef enum +{ + // HDMI Audio Sampling Frequencey + + GVFG_HDMI_AUD_FREQ_32KHZ = 0, + GVFG_HDMI_AUD_FREQ_44KHZ = 1, + GVFG_HDMI_AUD_FREQ_48KHZ = 2, + GVFG_HDMI_AUD_FREQ_88KHZ = 3, + GVFG_HDMI_AUD_FREQ_96KHZ = 4, + GVFG_HDMI_AUD_FREQ_176KHZ = 5, + GVFG_HDMI_AUD_FREQ_192KHZ = 6, + GVFG_HDMI_AUD_FREQ_HBR = 7, + GVFG_HDMI_AUD_FREQ_FROM_STRM = 8 + +} GVFG_HDMI_AUDIO_SAMPLE_FREQ; + + + // HDMI Video color format typedef enum @@ -150,10 +194,11 @@ typedef enum GVFG_HRESULT { typedef struct _GVFG_CHIP_INFO { - // Data are in hex + // Data are in hex representation. + // For example, VerDate: 0x20161115 is 2026/11/15 - UINT32 VerDate; - UINT32 VerTime; + UINT32 VerDate; // YearMonthDate + UINT32 VerTime; // HourMinuteSecond } GVFG_CHIP_INFO, *PGVFG_CHIP_INFO; @@ -343,6 +388,22 @@ typedef struct _GVFG_HDMI_VIDEO_INPUT_INFO { } GVFG_HDMI_VIDEO_INPUT_INFO, *PGVFG_HDMI_VIDEO_INPUT_INFO; + +typedef struct _GVFG_HDMI_AUDIO_INPUT_INFO { + + UINT32 AudioSignalLock; // 0: signal is not locked. + // 1: signal is locked. + + UINT16 SamplesPerSec; // GVFG_HDMI_AUDIO_SAMPLE_FREQ + UINT16 BitsPerSample; // 16 or 24 + UINT16 Channels; // number of channels + + UINT16 Format; // GVFG_HDMI_AUDIO_FORMAT + + +} GVFG_HDMI_AUDIO_INPUT_INFO, *PGVFG_HDMI_AUDIO_INPUT_INFO; + + /********************************************************************* * FUNCTION: Create events notify handles. * PURPOSE: Driver uses these handles to notify user active events. @@ -850,12 +911,37 @@ GVFG_SDK_API GVFG_HRESULT GvfgSetVideoColorDepth(GVFG_PARAM_IN PGVFG_CONTEXT pCx * RETURNS: GVFG_HRESULT_OK: success. * other: failure. * + * Note : It may take upto 100 ms to execute. + * *********************************************************************/ GVFG_SDK_API GVFG_HRESULT GvfgGetHdmiVideoInputInfo(GVFG_PARAM_IN PGVFG_CONTEXT pCxt, GVFG_PARAM_IN ULONG videoChn, GVFG_PARAM_OUT PGVFG_HDMI_VIDEO_INPUT_INFO pHdmiInfo); +/********************************************************************* + * FUNCTION: Get HDMI interface audio information. + * + * + * PURPOSE: This is the HDMI video input information, decoding from the HDMI audio payload stream. + * + * PARAMS: pCxt - Gigabyte device context. + * Device context created by the GvfgOpenDev(...) + * + * videoChn - video channel index. + * + * pHdmiInfo - HDMI audio input information. + * + * + * RETURNS: GVFG_HRESULT_OK: success. + * other: failure. + * + * Note : It may take upto 100 ms to execute. + * + *********************************************************************/ +GVFG_SDK_API GVFG_HRESULT GvfgGetHdmiAudioInputInfo(GVFG_PARAM_IN PGVFG_CONTEXT pCxt, + GVFG_PARAM_IN ULONG videoChn, + GVFG_PARAM_OUT PGVFG_HDMI_AUDIO_INPUT_INFO pHdmiAudioInfo); diff --git a/docs/GVFG_CUSTOMER_API.md b/docs/GVFG_CUSTOMER_API.md index 536c561..b3c856f 100644 --- a/docs/GVFG_CUSTOMER_API.md +++ b/docs/GVFG_CUSTOMER_API.md @@ -222,6 +222,8 @@ Zero-copy 模式必須在 channel open 前選擇;要切換模式時,先銷 ### SDK OSD +使用 OSD 時請包含 `gvfg_osd.h`,連結 `gvfg_osd.lib`(MinGW 使用 `libgvfg_osd.dll.a`),並隨應用程式部署同一次 SDK 建置的 `gvfg_osd.dll` 和 `gvfg.dll`。一般擷取只需連結 `gvfg.dll` 對應的 import library。 + 每個已 open 的 channel 可設定兩組 OSD,`osd_index` 為 `0`、`1`;重疊時第 `1` 組在上方。 OSD 會加入後續取得的 YUY2/Y210 frame,preview、snapshot 或錄影是否顯示 OSD, 取決於它們是否使用這份 frame。 diff --git a/docs/GVFG_Customer_doc/GVFG_CUSTOMER_API_REFERENCE.md b/docs/GVFG_Customer_doc/GVFG_CUSTOMER_API_REFERENCE.md index dfb961e..141b539 100644 --- a/docs/GVFG_Customer_doc/GVFG_CUSTOMER_API_REFERENCE.md +++ b/docs/GVFG_Customer_doc/GVFG_CUSTOMER_API_REFERENCE.md @@ -254,6 +254,8 @@ typedef struct gvfg_handle_t *gvfg_handle; ### 1.20 `gvfg_channel_osd_config_t` 與 `gvfg_osd_font_list_t` +使用 OSD 時請包含 `gvfg_osd.h`,連結 `gvfg_osd.lib`(MinGW 使用 `libgvfg_osd.dll.a`),並隨應用程式部署同一次 SDK 建置的 `gvfg_osd.dll` 和 `gvfg.dll`。一般擷取只需連結 `gvfg.dll` 對應的 import library。 + ```c typedef struct gvfg_channel_osd_config_t { const char *text; diff --git a/docs/INTERNAL_BUILD_GUIDE.md b/docs/INTERNAL_BUILD_GUIDE.md index 94a81f5..1799ca3 100644 --- a/docs/INTERNAL_BUILD_GUIDE.md +++ b/docs/INTERNAL_BUILD_GUIDE.md @@ -34,7 +34,8 @@ SDK 與 Demo 現在不是同一個頂層 CMake 專案。不存在 `BUILD_GVFG_SA | SDK target | 類型 | 說明 | |---|---|---| -| `gvfg` | SHARED | Capture facade、vendor adapter、GPU conversion/OSD | +| `gvfg` | SHARED | Capture facade、vendor adapter、GPU conversion | +| `gvfg_osd` | SHARED | 文字與字型、BGRA 疊圖、GPU 通道 OSD | | `gvfg_playback` | SHARED | 對外播放 DLL,只匯出 Playback 函式 | | `gvfg_preview` | STATIC | D3D backend,私下連結進 Playback | | `gvfg_audio_playback` | STATIC | WASAPI backend,私下連結進 Playback | @@ -54,7 +55,8 @@ SDK build 不需要 Qt,也不產生 Demo EXE。 `GVFG_MINGW_DLLTOOL` 是 FILEPATH,可指向 dlltool 以產生客戶端 GNU 匯入庫。 這不表示 MSVC vendor 靜態庫可直接由 MinGW 建置 SDK。 -`GVFG_EXPERIMENTAL_ZERO_COPY_OSD_INPLACE` 是現有預設 OFF 的實驗選項,不屬於客戶播放設定。 +SDK 會一併建置 `gvfg_osd.dll`。使用 OSD 的應用程式(例如 Qt Viewer)需包含 `gvfg_osd.h`、連結 OSD import library,並部署 OSD DLL。 + ## 4. Sample 的三種 SDK 來源