Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
fix(capture): pair Elgato MK2 native HDR with vendor controls
Veyra Goal Agentbe3e2e639bbc
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 774d6487..0c4ab684 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -490,6 +490,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/source/NativeCaptureSink.cppsrc/source/MediaFileSource.cppsrc/source/CaptureCardSource.cpp+ src/source/ElgatoHdrControl.cppsrc/source/ScreenCaptureSource.cppsrc/source/AverMediaAudioSwitch.cppsrc/source/CaptureCompressedDecoder.cppdiff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex a882bec8..7eaaf3aa 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -2,6 +2,28 @@NVIDIA SDKs and runtimes are excluded from source control. The publisher-authorized experimental Release package contains only selected runtime DLLs and applicable notices, as documented in `docs/RUNTIME_COMPONENTS_0.0.2.md`. This is not vendor endorsement or a general redistribution grant. ReShade/RenoDX add-ons are not loaded or distributed by the product.+## Elgato MK.2 capture control++MIT adaptations in `src/source/ElgatoHdrControl.cpp` and its header:++- https://github.com/elgatosf/capture-device-support at+ `fe9630974d47f51bf54826e72fb8b654e620aa93`, `SampleCode/DriverInterface.cpp`+ and `Library/HDMIInfoFramesAPI.h`: private property GUID, IDs 720/721/722,+ two-part HDR packet and hardware HDR-to-SDR control protocol. Copyright+ (c) 2022 Corsair Memory, Inc.+- https://github.com/nitlink-dev/nitlink at+ `4f8a723406f63c6e92832488a6022fcf25233871`,+ `src/capture/elgato_hdr_control.cpp` and `elgato_device_identity.h`:+ exact MK.2 aliases, packet read size checks and hardware/native HDR pairing.+ Copyright (c) 2026 NitLink Contributors.++Veyra changes: use the already selected DirectShow filter instead of opening+another device; scope to MK.2/P010; validate packet length/type/checksum;+retain manual overrides; log HRESULT/readback and restore a readable initial+tonemap value on close. No vendor shader, SDK header or binary is vendored.+No global color/chroma formula change. Full license:+`licenses/capture/ELGATO_NITLINK_MIT.txt`.+## NVENC API declarationsSource: https://github.com/FFmpeg/nv-codec-headers ; encoder ABI baseline `e844e5b26f46bb77479f063029595293aa8f812d` (tag `n13.0.19.0`, SDK 13.0 declarations), stored only under ignored `third_party_local/nvidia/nv-codec-headers-13.0`. Stage with `git clone --depth 1 --branch n13.0.19.0 https://github.com/FFmpeg/nv-codec-headers.git third_party_local/nvidia/nv-codec-headers-13.0`. CMake accepts `VEYRA_NVENC_HEADERS_ROOT`; compilation checks major/minor 13.0. The previous 13.1 checkout `eddcea9e27f6b772057c9b3f87de2cc1737faffc` remains unmodified for other local tools. Veyra now queries the driver's maximum API before creating the 13.0 function table/session and uses the same ABI for every structure, without pretending that a version-number-only downgrade changes structure layouts. No header or runtime is copied into source control.diff --git a/docs/ELGATO_MK2_HDR_PLAN_2026-09-20.md b/docs/ELGATO_MK2_HDR_PLAN_2026-09-20.mdnew file mode 100644index 00000000..6d0a9fc1--- /dev/null+++ b/docs/ELGATO_MK2_HDR_PLAN_2026-09-20.md@@ -0,0 +1,62 @@+# Elgato MK.2 HDR repair++## Evidence and scope++User's `veyra-app(30).log` has native P010 3840x2160/60, no converters,+VIDEOINFOHEADER2 colorInfoPresent=false. Final manual PQ path correctly uses+BT2020-NCL limited -> scRGB FP16 without SDR tone mapping. Windows HDR is on.+The comparison is Veyra versus a PNG of Elgato Studio viewed in Photos, not+a controlled live pixel comparison. Neither the image nor this log proves+the capture card's internal tone mapping state.++Nitlink commit 4f8a723406f63c6e92832488a6022fcf25233871 reads the vendor HDR+packet and disables internal tone mapping. Official Elgato support commit+fe9630974d47f51bf54826e72fb8b654e620aa93 confirms properties 720/721 (two+16-byte HDMI HDR packet halves), 722 (DWORD: 0 native HDR, 1 tone-mapped SDR),+and P010 for DirectShow HDR. Veyra had none of those property calls.+MK.2 limited-chroma decoding in Nitlink agrees with Veyra's existing 896-span+formula. Do not change shaders or compensate red globally.++## Implementation++1. Checkpoint pre-elgato-hdr-control-20260920 at c84eb72; retain isolated beta branch.+2. Only exact MK.2 aliases and negotiated P010 enter the helper. Use the+ capture graph's existing device; no second device open, vendor DLL or worker.+3. Read and validate both packet halves, header, length, checksum, EOTF and+ static metadata descriptor. Empty packet denotes SDR; failures/unknown+ EOTF never establish HDR. PQ/HLG are supported, traditional HDR gamma is not.+4. Auto can fill missing HDR interpretation from InfoFrame. Preserve explicit+ driver matrix, primaries and range. Missing gamut retains labelled BT2100+ assumptions. Explicit user color/range remains authoritative.+5. Native HDR disables card tone mapping; explicit Rec709 enables it. No+ device write just because a format has ten bits. Writes occur on stopped,+ connected graph before Run, never during active frame callbacks.+6. Read original state and verify successful Set when readable. Set failure+ or contradictory readback fails connection rather than mislabelling data.+ Read-only QuerySupported is diagnostic, as the official sample uses Set+ directly. Write-only drivers are accepted but logged as unverified readback;+ their unknown original value cannot safely be restored and is not invented.+7. Session close restores known original state after Stop; configure failures+ release the local RAII helper. No per-frame polling or extra queue latency.++## Acceptance and boundaries++Build application and capture-color tests using existing isolated beta build.+Mock actual IKsPropertySet: corrupt/short packets, unknown EOTF, PQ/HLG/SDR,+explicit override, unrelated device/non-P010, rejected/ignored writes,+write-only firmware, original-state restoration and preserved color metadata.+Existing raw capture layout/native sink/audio contract cases must still pass.+Package audit and baseline smoke use existing release scripts.++No MK.2 is attached locally. Software/mock success is not actual color approval.+Device should already receive HDR before Connect. Live HDMI SDR/HDR changes+without reconnect are not implemented by this repair. Test P010, auto color,+auto range first; compare same scene with enhancements/grading disabled.+If auto packet unavailable, select PQ explicitly and reconnect. Do not force+full range to compensate color. Request the new capture-elgato log if wrong.+If property changes pass but color stays wrong, compare actual source samples+and renderer output against Studio/Nitlink; do not claim metadata was the only cause.++Artifacts: build/color-mixer-hue-20260920; logs/elgato-hdr-20260920;+tmp/elgato-hdr-20260920; downloads/{nitlink-hdr,elgato-capture-support}-20260920;+test-packages/1.4.4beta-elgato-20260920 under E:/项目/Veyra.diff --git a/docs/RELEASE_NOTES_1.4.4.md b/docs/RELEASE_NOTES_1.4.4.mdindex 11a001f0..c0a75846 100644--- a/docs/RELEASE_NOTES_1.4.4.md+++ b/docs/RELEASE_NOTES_1.4.4.md@@ -7,10 +7,16 @@- 手动 HDR 使用 P010/P016。压缩采集继续读取码流元数据;不支持的手动组合明确报错,不静默忽略。- 修正混色器色相分区之间的响应缺口,以及跨越红色色相零点时的错误。保持原有调节幅度;旧预设在分区交界处的表现可能变化。-Elgato 4K60 Pro MK.2 HDR 测试:选择 P010、Rec.2100 PQ、有限 / Limited 后重连。+新增 Elgato 4K60 Pro MK.2 专用 HDR 入口:读取驱动私有 HDR InfoFrame,+接收原生 HDR 时关闭卡内 HDR→SDR 映射;可读取原状态时退出采集恢复。+不修改其他采集卡,也不修改全局色彩公式。接口来源为 Elgato 官方与 Nitlink(MIT)。++Elgato 4K60 Pro MK.2 HDR 测试:先让 HDMI 输入 HDR,选择 P010、自动颜色、自动范围后重连。+驱动私有元数据读取失败时再尝试 Rec.2100 PQ;新日志带 capture-elgato 接口诊断。先关闭调色和增强,与 OBS 同一画面比较。P010 本身不能证明输入是 HDR。原生 HDR 仍按 PQ 绝对亮度输出,没有强加减红或二次色调映射。-该设备的偏红问题尚待实卡反馈,不能将新增选项等同于根因已修复。+接口及回归测试通过不等于实卡颜色验收。该设备的偏色问题仍待用户复测;+HDMI 源运行中切换 SDR/HDR 后需要重新连接采集。本版不新增白点/峰值滑块。OBS 全局输出的 300/1400 nit 不直接等同于采集输入参数。运行组件身份、实验功能边界及 1.4.3 已知限制保留。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 35edc9e1..2bb0bb7c 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -1,5 +1,45 @@# Veyra 工作记录+## 2026-09-20 Elgato MK.2 vendor HDR control++Investigated user log veyra-app(30).log and Nitlink; official Elgato support+confirms Veyra omitted the vendor InfoFrame and card-side HDR-to-SDR switch.+This is a concrete integration gap, not proof of the user's sole color cause.+Checkpoint `checkpoint/pre-elgato-hdr-control-20260920` at c84eb72; branch+`codex/capture-color-144beta-20260920`. Plan and evidence:+`docs/ELGATO_MK2_HDR_PLAN_2026-09-20.md`.++Added ElgatoHdrControl header/source, wired CaptureCardSource configure/close,+added ElgatoHdrCases to CaptureColorContractTests/CMake; exact MK.2/P010 only.+No shader/color formula changes. Added upstream pinned MIT provenance and+license to notices and portable packer; refreshed beta release notes.++Commands: `scripts/build-isolated.ps1 -Root . -BuildDirectory+E:/项目/Veyra/build/color-mixer-hue-20260920 -DependencyCache+E:/项目/Veyra/build/frame-pacing-20260918/CMakeCache.txt -TempDirectory+E:/项目/Veyra/tmp/elgato-hdr-20260920 -Targets veyra,veyra_capture_color_tests+-DisplayVersion 1.4.4beta` passed. Capture tests: 185 PASS, failures=0.+Build retains pre-existing third-party warnings. No failed compilation/tests.+Logs: `E:/项目/Veyra/logs/elgato-hdr-20260920/{build,capture-color,package,smoke}.txt`.++Packaged using `scripts/package-portable.ps1 -Version 1.4.4 -Label beta-elgato+-LocalVideoHdr` with the build above and output+`E:/项目/Veyra/test-packages/1.4.4beta-elgato-20260920`.+ZIP: Veyra-1.4.4beta-elgato-win64-portable.zip, 472356915 bytes,+SHA256 EFF48396AE7E58ECECABEDD069D1158E079753042D0FC97B6D5C2DD775321994.+Independent ZIP stream verification matches all 122 manifest payload hashes+and sizes, including new MIT license. Publisher runtime audit and forbidden+payload scan passed; no new runtime or SDK in source Git.++`scripts/acceptance/portable-smoke.ps1` passed all seven cases (7 seconds each),+input `E:/项目/Veyra/tests/1.4.2beta/visible-scene.mkv`, results under+`E:/项目/Veyra/tests/elgato-hdr-20260920/portable-smoke/result.json`.+Process TEMP/TMP redirected to task tmp. Prior beta retained for comparison.+No MK.2 attached: actual driver Set/readback and actual HDR color remain user+acceptance items. Live HDMI SDR/HDR changes require reconnect. Write-only+driver original state cannot be restored; this limitation is logged. No push+or GitHub release performed.+## 2026-09-20 1.4.4beta 本地内测包在 `codex/capture-color-144beta-20260920` 接入采集卡输入色彩空间与范围选择:diff --git a/include/veyra/source/ElgatoHdrControl.h b/include/veyra/source/ElgatoHdrControl.hnew file mode 100644index 00000000..ba809e5c--- /dev/null+++ b/include/veyra/source/ElgatoHdrControl.h@@ -0,0 +1,31 @@+#pragma once+#include "veyra/pipeline/FramePacket.h"+#include <dshow.h>+#include <wrl/client.h>+#include <array>+#include <string_view>++namespace veyra::source {+struct ElgatoHdrPacket {+ bool valid=false;+ unsigned eotf=0;+ float peak=0, maxCll=0, maxFall=0;+};+bool isElgatoMk2(std::wstring_view name);+ElgatoHdrPacket parseElgatoHdrPacket(const std::array<unsigned char,32>& bytes);++// Session-scoped device control; release it after Stop and before the filter.+class ElgatoHdrControl {+public:+ ~ElgatoHdrControl();+ ElgatoHdrControl()=default;+ ElgatoHdrControl(const ElgatoHdrControl&)=delete;+ ElgatoHdrControl& operator=(const ElgatoHdrControl&)=delete;+ bool configure(IUnknown* filter,std::wstring_view name,bool p010,+ unsigned overrideValue,pipeline::ColorDescription& color);+private:+ Microsoft::WRL::ComPtr<IKsPropertySet> properties_;+ DWORD original_=0;+ bool restore_=false;+};+}diff --git a/licenses/capture/ELGATO_NITLINK_MIT.txt b/licenses/capture/ELGATO_NITLINK_MIT.txtnew file mode 100644index 00000000..ca6834c8--- /dev/null+++ b/licenses/capture/ELGATO_NITLINK_MIT.txt@@ -0,0 +1,25 @@+Elgato capture-device-support+Copyright (c) 2022 Corsair Memory, Inc.++Nitlink+Copyright (c) 2026 NitLink Contributors++MIT License++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1index 2b5f9b8c..c27fd5f6 100644--- a/scripts/package-portable.ps1+++ b/scripts/package-portable.ps1@@ -146,6 +146,7 @@ if (Test-Path -LiteralPath $ffmpegLocalBuild) {}Copy-Payload (Join-Path $resolvedRoot 'assets/icons/lucide/LICENSE') 'licenses/LUCIDE-LICENSE.txt'Copy-Payload (Join-Path $resolvedRoot 'licenses/WIN32_CAPTURE_SAMPLE_MIT.txt') 'licenses/WIN32_CAPTURE_SAMPLE_MIT.txt'+Copy-Payload (Join-Path $resolvedRoot 'licenses/capture/ELGATO_NITLINK_MIT.txt') 'licenses/capture/ELGATO_NITLINK_MIT.txt'foreach ($name in @('RTX40MFG_LICENSE.txt','HDE_LICENSE.txt')) {Copy-Payload (Join-Path $resolvedRoot "src/ngx/compat/$name") "licenses/$name"}diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cppindex a7e802b2..0ab2a247 100644--- a/src/source/CaptureCardSource.cpp+++ b/src/source/CaptureCardSource.cpp@@ -9,6 +9,7 @@#include "veyra/source/CaptureCodec.h"#include "veyra/source/CaptureCompressedDecoder.h"#include "veyra/source/AverMediaAudioSwitch.h"+#include "veyra/source/ElgatoHdrControl.h"#include "veyra/pipeline/ColorMetadata.h"#include "veyra/Log.h"#include "veyra/sink/AudioFormat.h"@@ -235,6 +236,7 @@ struct CaptureCardSource::Impl:ISampleGrabberCB {ComPtr<IGraphBuilder> graph;ComPtr<ICaptureGraphBuilder2> builder;ComPtr<IBaseFilter> device,grabFilter,nullFilter,audioFilter;ComPtr<IAMStreamConfig> config;ComPtr<ISampleGrabber> grab;ComPtr<IMediaControl> control;ComPtr<IMediaEvent> events;float lastAudioGain=-1;bool audioGainSupported=false;ComPtr<IBaseFilter> audioSink;ComPtr<IReferenceClock> referenceClock;+ std::unique_ptr<ElgatoHdrControl> elgatoHdr;std::unique_ptr<sink::CaptureAudioSession> audioSession;// Dolby/DTS passthrough: when the device offers only compressed media types// the raw bursts are decoded here and the session is configured with the@@ -694,6 +696,18 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.cleconst unsigned colorOverride=selection.colorOverride;log::info("capture-color",std::format("driver controlFlags=0x{:08X} colorInfoPresent={} transfer={} matrix={} primaries={} chroma={} override={}",p.layout.colorControlFlags,bool(p.layout.colorControlFlags&AMCONTROL_COLORINFO_PRESENT),int(p.layout.color.transfer),int(p.layout.color.matrix),int(p.layout.color.primaries),int(p.layout.color.chromaLocation),colorOverride));if(!validCaptureColorOverride(colorOverride))return false;+ auto elgatoHdr=std::make_unique<ElgatoHdrControl>();+ if(!compressedPath&&p.layout.format==AV_PIX_FMT_P010){+ std::wstring deviceName;+ const auto devices=monikers(false);+ for(size_t i=0;i<devices.size();++i){+ if(selection.stable?monikerPath(devices[i].Get())==selection.videoPath:i==index){deviceName=propertyString(devices[i].Get(),L"FriendlyName");break;}+ }+ if(!elgatoHdr->configure(p.device.Get(),deviceName,true,colorOverride,p.layout.color)){+ error_=L"Elgato HDR 输出模式设置失败,请关闭其他采集程序后重新连接,并检查日志中的 capture-elgato。";+ return false;+ }+ }if(colorOverride){if(compressedPath){error_=L"压缩采集使用码流颜色信息;手动颜色和范围请选择原生采集格式。";log::error("capture-color","Manual color override requires raw capture; compressed override is not silently ignored");return false;}const auto space=captureColorSpace(colorOverride);@@ -769,6 +783,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();error_.clep.decodeStop=false;p.decodeThread=std::thread([&p]{p.decodeLoop();});log::info("capture-decode",std::format("decode worker started queue={} backend={} (single decode thread; the parallel pool is a later refinement)",p.compressedQueueLimit,p.compressedDecoder.backendName()));}+ p.elgatoHdr=std::move(elgatoHdr);p.configured=true;reconnectDesc_=desc;reconnectInfo_=p.info;reconnectFormat_.clear();for(const auto& candidate:enumerateFormats(p.config.Get()))if(candidate.index==format){reconnectFormat_=candidate.key;break;}@@ -1210,6 +1225,7 @@ SourceReadStatus CaptureCardSource::readWithWait(pipeline::FramePacket& packet,cvoid CaptureCardSource::close()noexcept{auto& p=*p_;if(p.control){const HRESULT hr=p.control->Stop();if(FAILED(hr))log::error("capture-close",std::format("Stop failed hr=0x{:08X}; releasing graph",uint32_t(hr)));}if(p.grab){const HRESULT hr=p.grab->SetCallback(nullptr,0);if(FAILED(hr))log::error("capture-close",std::format("detach callback hr=0x{:08X}",uint32_t(hr)));}if(p.wasapi)p.wasapi->stop();p.wasapi.reset();+ p.elgatoHdr.reset();p.averMediaSwitch.stop();p.embeddedAudioUnavailable=false;if(p.audioSession)p.audioSession->stop();p.audioError.clear();if(p.audioPassthrough)p.audioPassthrough->close();diff --git a/src/source/ElgatoHdrControl.cpp b/src/source/ElgatoHdrControl.cppnew file mode 100644index 00000000..cbbbf74e--- /dev/null+++ b/src/source/ElgatoHdrControl.cpp@@ -0,0 +1,101 @@+// Adapted from elgatosf/capture-device-support (MIT, Corsair Memory, Inc. 2022)+// and Nitlink (MIT, NitLink Contributors 2026). Pins and changes: THIRD_PARTY_NOTICES.md.+#include "veyra/source/ElgatoHdrControl.h"+#include "veyra/source/CaptureColorOverride.h"+#include "veyra/Log.h"+#include <algorithm>+#include <format>++namespace veyra::source {+namespace {+constexpr GUID propertySet{0xD1E5209F,0x68FD,0x4529,{0xBE,0xE0,0x5E,0x7A,0x1F,0x47,0x92,0x26}};+constexpr DWORD packetLow=720,packetHigh=721,tonemap=722;+void record(const char* op,DWORD id,HRESULT hr,DWORD size) {+ log::info("capture-elgato",std::format("{} property={} hr=0x{:08X} bytesOrFlags={}",op,id,uint32_t(hr),size));+}+HRESULT read(IKsPropertySet* ps,DWORD id,void* data,DWORD size) {+ DWORD returned=0;+ const HRESULT hr=ps->Get(propertySet,id,nullptr,0,data,size,&returned);+ record("Get",id,hr,returned);+ return FAILED(hr)?hr:returned==size?S_OK:HRESULT_FROM_WIN32(ERROR_INVALID_DATA);+}+}+bool isElgatoMk2(std::wstring_view name) {+ for(const auto* alias:{L"Game Capture 4K60 Pro MK.2",L"Elgato Game Capture 4K60 Pro MK.2"})+ if(CompareStringOrdinal(name.data(),int(name.size()),alias,-1,TRUE)==CSTR_EQUAL)return true;+ return false;+}+ElgatoHdrPacket parseElgatoHdrPacket(const std::array<unsigned char,32>& b) {+ // Unlike an absent/failed read, an all-zero packet is the driver's SDR report.+ if(std::all_of(b.begin(),b.end(),[](auto v){return v==0;}))return {true};+ if((b[0]&0x7f)!=7||b[1]!=1||b[2]!=26||b[5]!=0)return {};+ unsigned sum=0;for(unsigned i=0;i<30;++i)sum+=b[i];+ if((sum&255)!=0||(b[4]!=0&&b[4]!=2&&b[4]!=3))return {};+ const auto u16=[&](unsigned i){return float(unsigned(b[i])|(unsigned(b[i+1])<<8));};+ return {true,b[4],u16(22),u16(26),u16(28)};+}+bool ElgatoHdrControl::configure(IUnknown* filter,std::wstring_view name,bool p010,+ unsigned overrideValue,pipeline::ColorDescription& color) {+ if(!filter||!p010||!isElgatoMk2(name))return true;+ if(!validCaptureColorOverride(overrideValue))return false;+ auto hr=filter->QueryInterface(IID_PPV_ARGS(&properties_));+ record("QueryInterface",0,hr,0);+ if(FAILED(hr)) {+ log::warn("capture-elgato","MK.2 private control unavailable; keeping existing color contract");+ return true;+ }+ std::array<unsigned char,32> bytes{};+ const auto low=read(properties_.Get(),packetLow,bytes.data(),16);+ const auto high=read(properties_.Get(),packetHigh,bytes.data()+16,16);+ const auto packet=SUCCEEDED(low)&&SUCCEEDED(high)?parseElgatoHdrPacket(bytes):ElgatoHdrPacket{};+ log::info("capture-elgato",std::format("HDR InfoFrame valid={} header={:02X}/{:02X}/{:02X} eotf={} peak={} maxCLL={} maxFALL={}",packet.valid,bytes[0],bytes[1],bytes[2],packet.eotf,packet.peak,packet.maxCll,packet.maxFall));+ const unsigned space=captureColorSpace(overrideValue);+ const bool sourceHdr=packet.valid&&(packet.eotf==2||packet.eotf==3);+ // A bit depth alone never triggers HDR or a hardware write. Explicit space+ // is authoritative; auto only adopts a validated source InfoFrame.+ const bool wantHdr=space==1||space==2||(!space&&(sourceHdr||color.isHdrPath()));+ if(!wantHdr&&space!=3)return true;+ const DWORD desired=wantHdr?0:1;+ const bool originalKnown=SUCCEEDED(read(properties_.Get(),tonemap,&original_,sizeof(original_)))&&original_<=1;+ if(!originalKnown||original_!=desired) {+ DWORD flags=0;hr=properties_->QuerySupported(propertySet,tonemap,&flags);+ record("QuerySupported",tonemap,hr,flags);+ // Official SDK issues Set directly. QuerySupported is advisory because+ // installed MK.2 drivers need not advertise every private property.+ DWORD value=desired;+ hr=properties_->Set(propertySet,tonemap,nullptr,0,&value,sizeof(value));+ record("Set",tonemap,hr,sizeof(value));+ if(FAILED(hr))return false;+ restore_=originalKnown;+ DWORD actual=0;+ const auto readback=read(properties_.Get(),tonemap,&actual,sizeof(actual));+ if(SUCCEEDED(readback)&&actual!=desired) {+ log::error("capture-elgato","Tonemap readback disagrees; refusing a mislabeled color contract");+ return false;+ }+ if(!originalKnown)log::warn("capture-elgato","Tonemap original state unreadable; Set succeeded but close cannot restore an unknown value");+ }+ if(!space&&sourceHdr) {+ const auto previous=color;+ applyCaptureColorOverride(color,packet.eotf==2?1:2);+ // InfoFrame declares EOTF, not YUV encoding or quantization. Preserve+ // explicit driver matrix/primaries; only fill their missing defaults.+ color.matrixAssumed=color.primariesAssumed=true;+ if(!previous.matrixAssumed&&previous.matrix!=pipeline::YuvMatrix::Unknown){color.matrix=previous.matrix;color.matrixAssumed=false;}+ if(!previous.primariesAssumed&&previous.primaries!=pipeline::ColorPrimaries::Unknown){color.primaries=previous.primaries;color.primariesAssumed=false;}+ }+ if(wantHdr&&sourceHdr&&(space==0||(space==1&&packet.eotf==2)||(space==2&&packet.eotf==3))) {+ color.hdrMasteringPeakNits=packet.peak;+ color.hdrMaxCllNits=packet.maxCll;+ color.hdrMaxFallNits=packet.maxFall;+ }+ log::info("capture-elgato",std::format("MK.2 P010 hardwareTonemap={} manualSpace={} sourceEotf={} nativeHdrRequested={}",desired,space,packet.eotf,wantHdr));+ return true;+}+ElgatoHdrControl::~ElgatoHdrControl() {+ if(restore_&&properties_) {+ const auto hr=properties_->Set(propertySet,tonemap,nullptr,0,&original_,sizeof(original_));+ record("Restore",tonemap,hr,sizeof(original_));+ }+}+}diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cppindex 4a9406f7..998be866 100644--- a/tests/unit/CaptureColorContractTests.cpp+++ b/tests/unit/CaptureColorContractTests.cpp@@ -1,6 +1,7 @@#include "veyra/source/CaptureMediaType.h"#include "veyra/source/NativeCaptureSink.h"#include "CaptureFormatCases.h"+#include "ElgatoHdrCases.h"#include "veyra/sink/AudioFormat.h"#include <iostream>#include <vector>@@ -35,6 +36,7 @@ int main(){CoInitializeEx(nullptr,COINIT_MULTITHREADED);int failures=0;auto check=[&](bool pass,const char* name){std::cout<<(pass?"PASS ":"FAIL ")<<name<<'\n';if(!pass)++failures;};captureFormatCases(check);+ elgatoHdrCases(check);VIDEOINFOHEADER2 vi{};vi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);vi.bmiHeader.biWidth=4;vi.bmiHeader.biHeight=2;vi.bmiHeader.biBitCount=16;vi.bmiHeader.biSizeImage=24;vi.AvgTimePerFrame=166667;AM_MEDIA_TYPE type{};type.majortype=MEDIATYPE_Video;type.subtype=MEDIASUBTYPE_YUY2;type.formattype=FORMAT_VideoInfo2;type.pbFormat=reinterpret_cast<BYTE*>(&vi);type.cbFormat=sizeof(vi);source::CaptureMediaLayout layout;check(source::captureMediaLayout(type,layout)&&layout.stride==12&&layout.rowBytes==8&&!layout.bottomUp,"VideoInfo2 YUY2 padded row contract");diff --git a/tests/unit/ElgatoHdrCases.h b/tests/unit/ElgatoHdrCases.hnew file mode 100644index 00000000..4fd75f9f--- /dev/null+++ b/tests/unit/ElgatoHdrCases.h@@ -0,0 +1,107 @@+#pragma once+#include "veyra/source/ElgatoHdrControl.h"+#include <cstring>++namespace {+struct ElgatoProperties final:IKsPropertySet {+ std::array<unsigned char,32> packet{};+ DWORD mode=1;unsigned gets=0,sets=0;+ bool shortPacket=false,readableMode=true,rejectSet=false,ignoreSet=false,queryFails=false;+ void hdr(unsigned eotf=2){+ packet={};packet[0]=0x87;packet[1]=1;packet[2]=26;packet[4]=static_cast<unsigned char>(eotf);+ packet[22]=0xe8;packet[23]=3;packet[26]=0x90;packet[27]=1;packet[28]=100;+ checksum();+ }+ void checksum(){packet[3]=0;unsigned sum=0;for(unsigned i=0;i<30;++i)sum+=packet[i];packet[3]=static_cast<unsigned char>(0-sum);}+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id,void** out)override{+ if(!out)return E_POINTER;*out=nullptr;+ if(id!=IID_IUnknown&&id!=__uuidof(IKsPropertySet))return E_NOINTERFACE;+ *out=static_cast<IKsPropertySet*>(this);AddRef();return S_OK;+ }+ ULONG STDMETHODCALLTYPE AddRef()override{return 2;}+ ULONG STDMETHODCALLTYPE Release()override{return 1;}+ HRESULT STDMETHODCALLTYPE Set(REFGUID id,DWORD prop,LPVOID instance,DWORD instanceSize,LPVOID data,DWORD size)override{+ ++sets;if(id.Data1!=0xD1E5209F||prop!=722||instance||instanceSize||size!=4)return E_INVALIDARG;+ if(rejectSet)return E_FAIL;if(!ignoreSet)std::memcpy(&mode,data,4);return S_OK;+ }+ HRESULT STDMETHODCALLTYPE Get(REFGUID id,DWORD prop,LPVOID instance,DWORD instanceSize,LPVOID data,DWORD size,DWORD* returned)override{+ ++gets;*returned=0;if(id.Data1!=0xD1E5209F||instance||instanceSize)return E_INVALIDARG;+ if((prop==720||prop==721)&&size==16){std::memcpy(data,packet.data()+(prop==720?0:16),16);*returned=shortPacket?15:16;return S_OK;}+ if(prop==722&&size==4&&readableMode){std::memcpy(data,&mode,4);*returned=4;return S_OK;}+ return E_NOTIMPL;+ }+ HRESULT STDMETHODCALLTYPE QuerySupported(REFGUID,DWORD,DWORD* flags)override{+ *flags=KSPROPERTY_SUPPORT_GET|KSPROPERTY_SUPPORT_SET;return queryFails?E_NOTIMPL:S_OK;+ }+};+template<class Check> void elgatoHdrCases(Check check) {+ using namespace veyra;+ constexpr auto name=L"Game Capture 4K60 Pro MK.2";+ const auto defaults=[] {pipeline::ColorDescription c;c.matrixAssumed=c.primariesAssumed=c.transferAssumed=true;c.transfer=pipeline::TransferFunction::SRGB;c.range=pipeline::ColorRange::Limited;return c;};+ check(source::isElgatoMk2(name)&&source::isElgatoMk2(L"elgato game capture 4k60 pro mk.2")&&!source::isElgatoMk2(L"Elgato 4K Pro"),"MK.2 exact device aliases only");+ ElgatoProperties ps;ps.hdr();+ auto parsed=source::parseElgatoHdrPacket(ps.packet);+ check(parsed.valid&&parsed.eotf==2&&parsed.peak==1000&&parsed.maxCll==400&&parsed.maxFall==100,"HDR InfoFrame PQ and little endian mastering metadata");+ auto broken=ps.packet;broken[20]^=1;+ check(!source::parseElgatoHdrPacket(broken).valid,"reject corrupt InfoFrame checksum");+ broken=ps.packet;broken[2]=255;check(!source::parseElgatoHdrPacket(broken).valid,"reject unbounded packet length");+ ps.packet[0]=0x82;ps.checksum();check(!source::parseElgatoHdrPacket(ps.packet).valid,"reject other InfoFrame type");+ ps.hdr(1);check(!source::parseElgatoHdrPacket(ps.packet).valid,"unknown HDR gamma is not PQ");+ ps.hdr();auto color=defaults();+ {+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,0,color)&&ps.mode==0&&color.transfer==pipeline::TransferFunction::PQ&&color.range==pipeline::ColorRange::Limited&&color.hdrMaxCllNits==400,"auto HDR disables card tonemap and propagates metadata without changing range");+ }+ check(ps.mode==1&&ps.sets==2,"close restores readable initial hardware state");+ ps={};ps.hdr();ps.mode=0;color=defaults();+ color.range=pipeline::ColorRange::Full;color.matrix=pipeline::YuvMatrix::BT709;color.matrixAssumed=false;+ color.primaries=pipeline::ColorPrimaries::BT709;color.primariesAssumed=false;+ {+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,0,color)&&ps.sets==0&&color.range==pipeline::ColorRange::Full&&color.matrix==pipeline::YuvMatrix::BT709&&color.primaries==pipeline::ColorPrimaries::BT709&&!color.matrixAssumed&&!color.primariesAssumed,"vendor EOTF never overwrites explicit driver gamut/range or re-writes native mode");+ }+ ps={};color=defaults();color.transfer=pipeline::TransferFunction::PQ;color.transferAssumed=false;+ {+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,0,color)&&ps.mode==0,"driver-declared HDR also disables hardware tonemap without vendor HDR packet");+ }+ ps={};ps.hdr(3);color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,8,color)&&color.transfer==pipeline::TransferFunction::HLG,"range-only override still allows auto HLG detection");+ }+ ps={};ps.hdr();color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,L"Other Capture",true,1,color)&&ps.gets==0&&ps.sets==0,"other devices receive zero vendor calls");+ }+ {+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,false,0,color)&&ps.gets==0,"non-P010 receives zero vendor calls");+ }+ ps={};color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,0,color)&&ps.sets==0&&color.transfer==pipeline::TransferFunction::SRGB,"zero SDR packet never enables HDR");+ }+ ps={};ps.hdr();ps.shortPacket=true;color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,0,color)&&ps.sets==0&&color.transferAssumed,"short vendor reads never establish HDR");+ }+ ps={};ps.hdr();ps.rejectSet=true;color=defaults();{+ source::ElgatoHdrControl control;+ check(!control.configure(&ps,name,true,0,color)&&color.transferAssumed,"failed hardware change cannot relabel SDR output PQ");+ }+ ps={};ps.hdr();ps.ignoreSet=true;color=defaults();{+ source::ElgatoHdrControl control;+ check(!control.configure(&ps,name,true,1,color),"reject successful Set with contradictory readback");+ }+ ps={};ps.hdr();ps.mode=0;color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,3,color)&&ps.mode==1&&!color.isHdrPath(),"manual Rec709 requests hardware SDR instead of relabeling raw PQ");+ }+ check(ps.mode==0,"manual SDR close restores original native mode");+ ps={};ps.queryFails=true;ps.readableMode=false;color=defaults();{+ source::ElgatoHdrControl control;+ check(control.configure(&ps,name,true,1,color)&&ps.mode==0,"explicit PQ works with write-only property and broken QuerySupported");+ }+ check(ps.sets==1,"unknown original state is never fabricated on restore");+}+}