Skip to content

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++

feat: add HDR file capture export and multichannel PCM audio

Veyra Goal Agent9beac39bebf4
diff --git a/CMakeLists.txt b/CMakeLists.txt
index fd445b00..bb9f4810 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -588,6 +588,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_popup_selector_tests PRIVATE veyra_base comctl32)
add_dependencies(veyra_engine veyra_shader_hdr_video_sr)
add_executable(veyra_hdr_color_tests tests/integration/HdrColorTests.cpp)
+ add_executable(veyra_multichannel_tests tests/integration/MultichannelTests.cpp)
+ target_compile_features(veyra_multichannel_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_multichannel_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_multichannel_tests PRIVATE veyra_engine)
add_executable(veyra_hdr_enhancement_tests tests/integration/HdrEnhancementTests.cpp)
target_compile_features(veyra_hdr_enhancement_tests PRIVATE cxx_std_20)
target_compile_definitions(veyra_hdr_enhancement_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
diff --git a/README.md b/README.md
index 2f1597b7..0074a599 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ BUG反馈与新功能
### 视频与图片
-专业模式顶部点击 **截图**,保存处理后的完整画面到系统“图片”文件夹下的 `Veyra Screenshots`,格式为 PNG。原生 HDR 截图暂不支持。
+专业模式顶部点击 **截图**,保存处理后的完整画面到系统“图片”文件夹下的 `Veyra Screenshots`,SDR 保存为 PNG,开发分支的 HDR 保存为保留浮点高亮的 JPEG XR(`.jxr`),需支持 HDR 的看图软件。
点击底栏“打开”选择文件。底栏提供播放、进度、音量、字幕和全屏;切换到专业模式后,鼠标位于画面上时可用滚轮缩放。
@@ -78,7 +78,7 @@ BUG反馈与新功能
主机和 PSN 凭据加密保存在 **%LOCALAPPDATA%/Veyra/remoteplay**,绑定当前 Windows 用户,升级不需搬运;不要分享这个目录。退出 PSN 不删除主机配对。首次免配对码注册、外网串流未实现。
-**实验 HDR**:H.265 HDR 在 Windows HDR 开启且所有增强关闭时可原生输出;开启增强或使用 SDR 显示器时先映射为 SDR,不是原生 HDR NR。真实 PS5 HDR 与 Sony 登录仍待进一步验收。
+**实验 HDR(开发分支,未发布)**:H.265 HDR 在 Windows HDR 开启时可保留 HDR 输出,也可同时开启 NR、超分和补帧。NR / RTX Video SR 处理映射副本,再与原 HDR 基底合成,属于 HDR 保留增强,不是原生 HDR NR 模型;SDR 显示器仍先映射为 SDR。真实 PS5 HDR 与 Sony 登录仍待进一步验收。
### 增强与补帧
@@ -125,7 +125,7 @@ BUG反馈与新功能
C++20、Win32、D3D12;文件由 FFmpeg 处理,采集使用 DirectShow,视频导出使用 NVENC。各入口共享增强管线,采集保留最新帧,光流提供估算的运动信息。
-NR 与 DLSS 帧生成属于 **community experimental / 社区实验集成**,不是 NVIDIA 官方认证或完整游戏原生集成。采集画面没有游戏引擎的原生深度和运动数据,效果可能存在拖影或细节变化。AMD NR 暂未提供;FRUC 已移除;仅 PS5 有上述实验 HDR 路径,文件 / 采集 HDR、HDR 导出、AV1 / ProRes 导出尚不支持。实卡兼容性与长期稳定性仍需持续验证。
+NR 与 DLSS 帧生成属于 **community experimental / 社区实验集成**,不是 NVIDIA 官方认证或完整游戏原生集成。采集画面没有游戏引擎的原生深度和运动数据,效果可能存在拖影或细节变化。AMD NR 暂未提供;FRUC 已移除;HDR 适用范围见下文;AV1 / ProRes 导出尚不支持。实卡兼容性与长期稳定性仍需持续验证。
## 开发与许可
@@ -133,6 +133,17 @@ NR 与 DLSS 帧生成属于 **community experimental / 社区实验集成**,
Veyra 原有源码采用 [GPLv3](LICENSE);含串流的组合程序同时适用 [AGPLv3 与上游 OpenSSL 例外](licenses/remoteplay/CHIAKI_AGPL3_OPENSSL.txt)。应用源码对应版本标签,Release 另附串流依赖与 FFmpeg 对应源码包,普通用户无需下载。SDK、模型和运行时不进入源码仓库;Release 组件按各自许可与实验发布范围单独提供。
+## 开发分支:HDR 与 5.1(尚未发布)
+
+以下能力属于 `codex/hdr-multichannel` 的本地开发版,**GitHub 1.1.1 不包含**。
+
+- **HDR 输入 / 增强**:文件、P010/P016 采集与 PS5 HDR;支持明确标记的 BT.2020 NCL / PQ 或 HLG。Windows HDR 开启时,可组合 NR、DLSS SR / RTX Video SR、DLSS / XeSS 补帧。NR / Video SR 使用 SDR 代理和 HDR 基底合成,压缩高光和近黑区域的增强会衰减;不把 SDR 结果逆造为原始 HDR。HLG 使用 1000nit / gamma 1.2 参考转换。
+- **采集颜色**:默认使用设备元数据。设备漏报时,在采集面板选择手动 PQ 或 HLG,且必须选择 P010/P016。10bit 本身不代表 HDR;RGB / YUY2 HDR 及 BT.2020 constant-luminance 暂不支持。
+- **HDR 导出 / 截图**:视频选择 HEVC,输出 Main10 / BT.2020 / PQ;HLG 也统一输出 PQ。支持 NR、超分和内部 DLSS 补帧。XeSS 仍只支持预览;H.264 不承载此 HDR 导出。截图为 FP16 scRGB JPEG XR。导出不虚构或沿用处理前的峰值元数据;普通 PNG/JPEG 保持 SDR。
+- **5.1 音频**:文件解码与采集 PCM 保留声道位置,共用一套音频时钟、补偿和音量处理。采集优先尝试设备真实提供的多声道模式。Windows 输出设备须配置成 5.1;仅支持立体声时明确降混,在详细状态中显示输入 / 输出声道数。PS5 保持上游提供的立体声,不伪装成 5.1;本轮不提供 Dolby/DTS 压缩码流直通或 Atmos 对象音频。
+
+本机 RTX 5070 已验证 GPU 输出、HDR 文件导出及多声道软件数据;真实 HDR 屏观感、5.1 扬声器定位和各采集卡仍需实机验收。各组合记录及边界见 [施工记录](docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md)。新安装默认仍关闭全部效果。
+
## 致谢
感谢 [Magpie Experimental](https://github.com/SAOG0721/Magpie/tree/experimental) 在 NR 残差合成、光流与增强处理链方面提供的研究启发;感谢 [chiaki-ng](https://github.com/streetpea/chiaki-ng) 提供 PS5 串流基础,以及 [XeSS-GPU-Motion](https://github.com/gggz114514-oss/XeSS-GPU-Motion) 的 GPU DIS 光流实现。
diff --git a/README_EN.md b/README_EN.md
index 197d709b..fa6589bf 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -56,7 +56,7 @@ Stream input is up to 1080p. 2K / 4K / 8K are local upscaling targets. H.264 / H
Pairing and PSN credentials are encrypted in **%LOCALAPPDATA%/Veyra/remoteplay**, bound to the Windows user and retained across upgrades. Do not share this directory. Signing out retains console pairing. Pinless first registration and Internet streaming are not implemented.
-**Experimental HDR:** native output requires Windows HDR and all enhancements off. Otherwise HDR is tone-mapped to SDR before enhancement, not native HDR NR processing. Real PS5 HDR and Sony authorization need further validation.
+**Experimental HDR (development branch):** Windows HDR output can retain HDR with NR, SR and FG enabled. NR / RTX Video SR process an SDR proxy and composite changes onto the retained HDR base; this is not a native HDR NR model. SDR displays still use tone mapping. Real PS5 HDR and Sony authorization need further validation.
## Quick Guide
@@ -115,7 +115,7 @@ Video / image / capture card / PS5 -> color handling -> SR -> NR -> frame genera
C++20, Win32, and D3D12. FFmpeg handles media files, DirectShow handles capture, and NVENC handles video encoding. Inputs share one enhancement graph; capture retains the latest frame, and optical flow supplies estimated motion.
-NR and DLSS frame generation are **community-experimental integrations**, not NVIDIA certification or complete native game integration. Captured pixels lack game-engine depth and motion data; ghosting and altered detail are possible. AMD NR is unavailable, FRUC has been removed, and HDR / AV1 / ProRes export are unsupported. Capture compatibility and long-term stability remain under testing.
+NR and DLSS frame generation are **community-experimental integrations**, not NVIDIA certification or complete native game integration. Captured pixels lack game-engine depth and motion data; ghosting and altered detail are possible. AMD NR is unavailable, FRUC has been removed, and AV1 / ProRes export are unsupported; development HDR support is scoped below. Capture compatibility and long-term stability remain under testing.
## Development and License
@@ -135,7 +135,18 @@ Video export validates completeness before success and may take extra time to
finish. Embedded subtitles are not preserved. Avoid simultaneous exports from
multiple instances to the same target file.
-In Professional mode, click **Screenshot** in the top toolbar to save the latest processed full-resolution picture as PNG under **Pictures / Veyra Screenshots**. Application UI and window zoom are excluded; native HDR screenshots are not supported.
+In Professional mode, click **Screenshot** in the top toolbar to save the latest processed full-resolution picture under **Pictures / Veyra Screenshots**: PNG for SDR, floating-point JPEG XR (`.jxr`) for development HDR output. Use an HDR-capable viewer. Application UI and window zoom are excluded.
+
+## Development branch: HDR and 5.1 (unreleased)
+
+These changes are local to `codex/hdr-multichannel`; **the GitHub 1.1.1 package does not include them**.
+
+- Files, P010/P016 capture and PS5 can use explicitly described BT.2020 NCL PQ/HLG input. Windows HDR enables retained HDR output with NR, DLSS SR / RTX Video SR and DLSS / XeSS FG. NR / Video SR use an SDR proxy plus the retained HDR base, with reduced changes near black and compressed highlights. This is not native HDR NR inference. HLG uses a 1000-nit, gamma-1.2 reference conversion.
+- Capture defaults to device color metadata. Manual PQ / HLG is available for devices that omit it, requiring P010/P016. Ten-bit storage alone does not identify HDR. RGB/YUY2 HDR and BT.2020 constant-luminance input are unsupported.
+- HDR video export uses HEVC Main10 / BT.2020 / PQ, including HLG-to-PQ conversion and optional NR, SR and internal DLSS FG. XeSS remains preview-only. H.264 HDR export is rejected. HDR screenshots use lossless scRGB FP16 JPEG XR. Original mastering/peak metadata is not invented or reused after processing.
+- File and capture PCM preserve speaker positions through one audio clock, compensation and volume path. Capture tries actual multichannel device formats first. Configure the Windows endpoint for 5.1; stereo endpoints receive an explicit downmix. Detailed status reports input/output channel counts. PS5 remains stereo. Compressed Dolby/DTS passthrough and Atmos object audio are not implemented.
+
+RTX 5070 GPU output, HDR export and software channel isolation have local test evidence. HDR display appearance, real 5.1 speaker positioning and individual capture cards require hardware acceptance. See the [execution record](docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md). Fresh-install effects remain off.
## Acknowledgments
diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cpp
index 71575953..e1ea8730 100644
--- a/apps/veyra/ui/AppShell.cpp
+++ b/apps/veyra/ui/AppShell.cpp
@@ -291,7 +291,7 @@ for(auto [id,help]:std::initializer_list<std::pair<int,const wchar_t*>>{
{Fg,L"开关补帧。专业模式可选倍率和后端;数字翻倍,显卡工作量也会涨。"},
{Realtime,L"实时档降低NR内部处理尺寸,减轻负担;原生档更费算力。"},
{Multiplier,L"选择补帧倍率。帧数不是越多越好,跟不上时会跳过过期机会。"},
- {Save,L"保存当前处理后的完整画面为PNG,放到系统图片文件夹的 Veyra Screenshots。只拍画面,不拍工具栏;原生HDR暂不支持。"},
+ {Save,L"保存处理后的完整画面到系统图片文件夹的 Veyra Screenshots。SDR为PNG,HDR为保留高亮的JXR;只拍画面,不拍工具栏或驱动补帧。"},
{Master,L"总增强开关。关闭后保留设置,重新开启不用重调配方。"},
{DailyPreset,L"载入保存的增强预设,一键换口味。"},{Volume,L"播放音量,不改变音画同步偏移。"},{Mute,L"静音或恢复声音,让耳朵休息一下。"},
{Subtitle,L"显示或隐藏字幕。字幕在增强后叠加,不让算法给字加戏。"},{SubtitleLoad,L"加载本地字幕文件。对白太快,给眼睛加个帮手。"},{SubtitleSize,L"调整字幕字号,不改变导出视频尺寸。"},
@@ -430,9 +430,10 @@ if(masterPendingRevision&&!s.applying){if(s.sessionId==masterPendingSession&&s.r
if(smokeScreenshot&&screenshotStep==0&&s.frames>20){SendMessageW(hwnd,WM_COMMAND,Save,0);screenshotStep=1;}
if(screenshotPending){
std::error_code ec;
- if(s.status.starts_with(L"图片已保存")&&std::filesystem::exists(screenshotPath,ec)){
+ if(s.status.starts_with(L"HDR截图已保存")){auto path=std::filesystem::path(screenshotPath);path.replace_extension(L".jxr");screenshotPath=path.wstring();}
+ if((s.status.starts_with(L"图片已保存")||s.status.starts_with(L"HDR截图已保存"))&&std::filesystem::exists(screenshotPath,ec)){
screenshotPending=false;screenshotTick=GetTickCount64();setText(GetDlgItem(hwnd,Save),L"已保存");
- if(smokeScreenshot){screenshotStep=2;veyra::log::info("screenshot-test","toolbar handler saved processed PNG");}
+ if(smokeScreenshot){screenshotStep=2;veyra::log::info("screenshot-test","toolbar handler saved processed screenshot");}
}else if(s.status.find(L"保存失败")!=std::wstring::npos||s.status.find(L"保存异常")!=std::wstring::npos||s.status.find(L"截图尚未支持")!=std::wstring::npos||!s.running){
screenshotPending=false;screenshotTick=GetTickCount64();setText(GetDlgItem(hwnd,Save),L"保存失败");
MessageBoxW(hwnd,s.status.c_str(),L"截图未保存",MB_OK|MB_ICONINFORMATION);
diff --git a/apps/veyra/ui/CapturePanel.cpp b/apps/veyra/ui/CapturePanel.cpp
index 34a4b801..4d50f303 100644
--- a/apps/veyra/ui/CapturePanel.cpp
+++ b/apps/veyra/ui/CapturePanel.cpp
@@ -13,18 +13,20 @@ std::vector<source::CaptureFormat> formats;
void query(int device){if(busy)return;busy=true;queriedDevice=device;queryStarted=GetTickCount64();SetDlgItemTextW(window,8,L"正在查询设备能力…当前播放继续");EnableWindow(GetDlgItem(window,4),FALSE);EnableWindow(GetDlgItem(window,5),FALSE);EnableWindow(GetDlgItem(window,1),FALSE);
pending=std::async(std::launch::async,[device]{CoInitializeEx(nullptr,COINIT_MULTITHREADED);Query result;result.device=device;try{if(device<0){result.video=source::CaptureCardSource::devices();result.audio=source::CaptureCardSource::devices(true);}else result.formats=source::CaptureCardSource::formats(unsigned(device));}catch(...){}CoUninitialize();return result;});
}
-void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,308,308,14,84,240,154};for(int id=1;id<=9;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,id<=3?180:id==8?56:id==4||id==5?36:24),TRUE);}}
+void arrange(){RECT r{};GetClientRect(window,&r);const int width=MulDiv(r.right,96,veyra::ui::layoutDpi(window));const int ys[]={0,44,114,184,368,368,14,84,300,154,254,224};for(int id=1;id<=11;++id){int x=id==5?width-152:16;int w=id==4?width-184:id==5?136:width-32;MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,ys[id]),dip(window,w),dip(window,(id<=3||id==10)?180:id==8?56:id==4||id==5?36:24),TRUE);}}
LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
case WM_CREATE:{window=h;font=makeFont(h);titleTheme(h);auto add=[&](const wchar_t* cls,const wchar_t* label,int id,DWORD style){auto c=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,0,0,1,1,h,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,WPARAM(font),TRUE);themeControl(c);};
for(int i=1;i<=3;++i)add(L"COMBOBOX",L"",i,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);
+ add(L"COMBOBOX",L"",10,CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP);add(L"STATIC",L"输入颜色(变更需重连)",11,0);
+ for(auto name:{L"自动 · 使用设备元数据",L"手动 HDR10 / PQ · BT.2020",L"手动 HLG · BT.2020 / 1000nit参考"})SendDlgItemMessageW(h,10,CB_ADDSTRING,0,LPARAM(name));SendDlgItemMessageW(h,10,CB_SETCURSEL,0,0);
add(L"BUTTON",L"连接并开始观看",4,BS_PUSHBUTTON|WS_TABSTOP);marked(GetDlgItem(h,4));add(L"BUTTON",L"刷新设备",5,BS_PUSHBUTTON|WS_TABSTOP);
add(L"STATIC",L"视频输入设备",6,0);add(L"STATIC",L"设备实际支持的格式",7,0);add(L"STATIC",L"",8,0);add(L"STATIC",L"HDMI 音频监听",9,0);
- installDialogHelp(h,{{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"选择对应的采集音频设备,也可不采声音。画面和声音要认对门。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});
+ installDialogHelp(h,{{10,L"设备没报HDR信息时手动指定,需选P010/P016。P010也可能装SDR,别给普通画面强戴HDR帽子。"},{1,L"选采集卡的视频设备。别把摄像头误请来直播PS5。"},{2,L"选设备真实提供的分辨率、帧率和像素格式。清晰度、带宽和延迟都受它影响。"},{3,L"选择对应的采集音频设备,也可不采声音。画面和声音要认对门。"},{4,L"按当前格式连接采集卡,并应用当前增强设置。"},{5,L"重新扫描设备和格式。设备被其他软件占用时,刷新不一定能抢回来。"}});
EnableWindow(GetDlgItem(h,4),FALSE);arrange();SetTimer(h,1,100,nullptr);if(!busy)query(-1);return 0;}
case WM_TIMER:if(busy&&pending.wait_for(std::chrono::seconds(0))==std::future_status::ready){auto result=pending.get();busy=false;EnableWindow(GetDlgItem(h,5),TRUE);EnableWindow(GetDlgItem(h,1),TRUE);if(result.device<0){SendDlgItemMessageW(h,1,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);SendDlgItemMessageW(h,3,CB_RESETCONTENT,0,0);formats.clear();for(auto& name:result.video)SendDlgItemMessageW(h,1,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(L"不监听音频"));for(auto& name:result.audio)SendDlgItemMessageW(h,3,CB_ADDSTRING,0,LPARAM(name.c_str()));SendDlgItemMessageW(h,3,CB_SETCURSEL,0,0);SetDlgItemTextW(h,8,result.video.empty()?L"未找到采集设备。连接后点击刷新。":L"请选择设备以查询实际格式;点击连接前不会中断当前视频。");}
else{formats=std::move(result.formats);SendDlgItemMessageW(h,2,CB_RESETCONTENT,0,0);for(auto& format:formats)SendDlgItemMessageW(h,2,CB_ADDSTRING,0,LPARAM(format.label.c_str()));if(!formats.empty())SendDlgItemMessageW(h,2,CB_SETCURSEL,0,0);EnableWindow(GetDlgItem(h,4),!formats.empty());SetDlgItemTextW(h,8,formats.empty()?L"未读到有效的4K以内采集格式,或设备正被其他应用占用。":L"连接后使用当前增强设置。格式与音频变更需要重新连接。");}}
else if(busy&&GetTickCount64()-queryStarted>5000)SetDlgItemTextW(h,8,L"设备查询耗时较长。可以关闭此面板,当前播放不受影响。");return 0;
-case WM_COMMAND:if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)query(int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)));else if(LOWORD(wp)==5)query(-1);else if(LOWORD(wp)==4){int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)),format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0)),audio=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0))-1;if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()){start(std::format(L"capture:{}:{}:{}",device,formats[format].index,audio));DestroyWindow(h);}}return 0;
+case WM_COMMAND:if(LOWORD(wp)==1&&HIWORD(wp)==CBN_SELCHANGE)query(int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)));else if(LOWORD(wp)==5)query(-1);else if(LOWORD(wp)==4){int device=int(SendDlgItemMessageW(h,1,CB_GETCURSEL,0,0)),format=int(SendDlgItemMessageW(h,2,CB_GETCURSEL,0,0)),audio=int(SendDlgItemMessageW(h,3,CB_GETCURSEL,0,0))-1;if(!busy&&device==queriedDevice&&format>=0&&size_t(format)<formats.size()){start(std::format(L"capture:{}:{}:{}:{}",device,formats[format].index,audio,int(SendDlgItemMessageW(h,10,CB_GETCURSEL,0,0))));DestroyWindow(h);}}return 0;
case WM_CTLCOLORSTATIC:case WM_CTLCOLOREDIT:case WM_CTLCOLORLISTBOX:case WM_CTLCOLORBTN:return colors(msg,wp,lp);
case WM_SIZE:arrange();return 0;
case WM_DPICHANGED:{auto r=reinterpret_cast<RECT*>(lp);SetWindowPos(h,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER|SWP_NOACTIVATE);auto old=font;font=makeFont(h);EnumChildWindows(h,[](HWND c,LPARAM f)->BOOL{SendMessageW(c,WM_SETFONT,WPARAM(f),TRUE);return TRUE;},LPARAM(font));DeleteObject(old);arrange();return 0;}
@@ -33,5 +35,5 @@ case WM_CLOSE:DestroyWindow(h);return 0;
case WM_DESTROY:KillTimer(h,1);DeleteObject(font);window=nullptr;return 0;
}return DefWindowProcW(h,msg,wp,lp);}
}
-void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback){start=std::move(callback);if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡 · 连接设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,560),dip(parent,410),parent,nullptr,wc.hInstance,nullptr);}
+void showCapturePanel(HWND parent,std::function<void(const std::wstring&)> callback){start=std::move(callback);if(window){SetForegroundWindow(window);return;}WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraCaptureSetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"采集卡 · 连接设置",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,560),dip(parent,470),parent,nullptr,wc.hInstance,nullptr);}
}
diff --git a/apps/veyra/ui/LiveStatusPanel.h b/apps/veyra/ui/LiveStatusPanel.h
index 25eadb21..7363b886 100644
--- a/apps/veyra/ui/LiveStatusPanel.h
+++ b/apps/veyra/ui/LiveStatusPanel.h
@@ -126,6 +126,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"NR内部尺寸",s.applied.nr?std::format(L"{} x {}",s.metrics.resolution.nr.width,s.metrics.resolution.nr.height):L"关闭");
rows.emplace_back(L"NR运行版本",s.nrActive?(s.applied.nrRuntime==engine::NrRuntime::Ampere?L"RTX 30兼容 · 实验":s.applied.nrRuntime==engine::NrRuntime::Community?L"社区兼容 · 实验":L"NVIDIA原版"):L"未运行");
rows.emplace_back(L"显示模式",s.running?(s.applied.captureCompatible?L"直播兼容 · 实验":L"标准显示"):L"未运行");
+ if(s.audioAvailable)rows.emplace_back(L"音频声道 · 输入 / 输出",std::format(L"{} / {}{}",s.capture?s.captureAudio.inputChannels:s.audioInputChannels,s.capture?s.captureAudio.outputChannels:s.audioOutputChannels,(s.capture?s.captureAudio.outputChannels<s.captureAudio.inputChannels:s.audioOutputChannels<s.audioInputChannels)?L" · 降混":L""));
rows.emplace_back(L"音频同步",s.audioAvailable?(s.capture?(s.captureAudio.running?L"软件估算同步":L"等待视频锚点"):(s.audioEndpointRecovering?L"音频设备恢复中 · 时间线保持":s.audioRebuffering?L"重新同步 · 等待视频锚点":L"音频主时钟")):L"无音频");
if(!s.capture&&s.audioAvailable){
rows.emplace_back(L"音频设备恢复次数",std::to_wstring(s.audioEndpointRecoveries));
@@ -139,6 +140,7 @@ inline LRESULT CALLBACK proc(HWND h,UINT message,WPARAM wp,LPARAM lp){
rows.emplace_back(L"音频设备队列",std::format(L"{:.1f} ms",s.captureAudio.endpointBufferedMs));
rows.emplace_back(L"音频重锚 / 溢出",std::format(L"{} / {}",s.captureAudio.resets,s.captureAudio.overflows));
}
+ if(!s.colorStatus.empty())rows.emplace_back(L"实际颜色链路",s.colorStatus);
if(!s.backendWarning.empty())rows.emplace_back(L"后端状态",s.backendWarning);
if(!s.captureAudio.error.empty())rows.emplace_back(L"采集音频异常",s.captureAudio.error);
}
diff --git a/apps/veyra/ui/RemotePlayPanel.cpp b/apps/veyra/ui/RemotePlayPanel.cpp
index 2f3227b5..39507c68 100644
--- a/apps/veyra/ui/RemotePlayPanel.cpp
+++ b/apps/veyra/ui/RemotePlayPanel.cpp
@@ -136,7 +136,7 @@ case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
{Account,L"配对用的Base64 PSN Account ID,不是在线昵称。名字相同不代表身份证号码相同。"},
{PairPin,L"PS5远程游玩页面显示的8位配对码,有时效。过期了再领一张票。"},
{Quality,L"选择PS5发送的分辨率和帧率。更改后点击应用设置并重连;当前生效值看下方状态,不要被下拉框骗了。"},
- {CodecChoice,L"H.264兼容性好,H.265通常更省码率;更改后重连生效。HDR需要PS5实际输出HDR;关闭增强且Windows HDR开启时原生显示,开启增强则先转SDR,别把两种效果认错。"},
+ {CodecChoice,L"H.264兼容性好,H.265通常更省码率;更改后重连生效。HDR需要PS5实际输出HDR和Windows HDR开启;增强保留HDR基底并处理映射副本,NR本身不是原生HDR模型。SDR显示器会映射为SDR。"},
{Pair,L"用账户ID和8位码注册主机,凭据在本机加密保存。"},
{Connect,L"使用保存的配对信息连接PS5,把画面送进当前增强链路。"},
{Cancel,L"取消当前操作或断开串流,让连接安静收工。"},
diff --git a/apps/veyra/ui/SettingHelp.h b/apps/veyra/ui/SettingHelp.h
index 5beba497..7aabe92f 100644
--- a/apps/veyra/ui/SettingHelp.h
+++ b/apps/veyra/ui/SettingHelp.h
@@ -54,7 +54,7 @@ inline const wchar_t* settingHelp(int id){
case 313:return L"给选中的预设换名,配方不变。";
case 314:return L"删除选中的预设,需要确认;当前画面不会跟着被删。";
case 315:return L"设为下次启动的增强默认配方。软件仍从日常模式打开。";
- case 500:return L"选择导出编码:H.264兼容性广,HEVC通常更省空间。接收设备也得看得懂。";
+ case 500:return L"H.264兼容性广,HEVC通常更省空间。HDR视频须选HEVC,保存为Main10 / PQ;别把HDR硬塞进普通H.264。";
case 501:return L"选保存位置并导出视频。参数在开始时冻结,NR按原生处理;低延迟预览顺序不带进导出。";
case 502:return L"保存当前图片或视频帧。精彩的一瞬间,留下来。";
case 503:return L"暂停或继续导出任务,不是暂停你正在看的视频。";
diff --git a/docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md b/docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md
index 5fb1e8ed..ab150f79 100644
--- a/docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md
+++ b/docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md
@@ -17,6 +17,61 @@
以上是合成输入与数值/接口测试,不是 HDR 实屏画质验收或所有 NR 版本组合验收。无 PS5/采集实卡新测试。未发布。
-## 进行中
+## B:输入、5.1、导出、截图及状态(软件实现完成,硬件验收待用户)
-5.1 音频链改造尚未验收;后续补齐文件/采集颜色与手动覆盖、HLG、HDR 导出/截图、状态信息、生命周期和回归。当前不得对外宣传全部功能完成。
+- 文件和采集的 HDR 判定依据 PQ/HLG transfer,不再把 P010 或 BT.2020 标记本身等同 HDR。P010/P016 采集识别扩展 Windows 色彩元数据;设备漏报时提供手动 PQ/HLG,仍限制明确的 YUV HDR 合同。HDR RGB/YUY2、BT.2020 CL 不冒充已支持。HLG 参考 1000nit / gamma1.2,转换为统一线性 BT.709/scRGB。输入契约意外变成 SDR 时拒绝错误解释,需重新打开源。
+- NR、DLSS SR、Video SR、DLSS FG、XeSS FG 及 NR先行两种顺序保持一套图。原版、Community、Ampere 三运行版本在 RTX5070 的 HDR组合已执行,不能据此宣称 RTX30 验收。
+- 文件 PCM、采集 PCM、WASAPI、补偿、增益与淡出保留声道布局,统一按音频帧计数。WAVEFORMATEXTENSIBLE 支持 PCM16/24/32及float32、side/back掩码;未知多声道布局拒绝猜测。采集优先尝试设备实际枚举的多声道格式,仍使用直接连接与10ms协商。输出端不支持时执行明确矩阵降混,不只截取前两声道。PS5保持既有双声道。
+- HEVC Main10导出:GPU RGB→P010、NVENC D3D12输入fence、BT.2020/PQ VUI及容器标记;完整逐帧验证新增位深与颜色检查。HLG统一输出PQ。不重新伪造处理前的mastering/MaxCLL。原音轨封装复制,六声道保持。H.264 HDR拒绝,XeSS FG依旧仅预览。
+- 截图:HDR保存FP16 scRGB JPEG XR,SDR继续PNG/JPEG;工具栏识别实际JXR路径和完成状态。仅截图读回像素,正常预览/导出不新增像素回读。
+- 详细面板分别显示实际颜色链路、输入/输出声道与降混;PS5/采集/导出工具提示及中英文README同步。默认效果全关、运行组件、配对及用户设置不变。
+
+### 本轮关键发现与修正
+
+1. 新NVENC VUI赋值最初使用整数字面量,MSVC要求枚举;改为明确UNSPECIFIED枚举,随后构建通过。
+2. 多声道采集排序最初遗漏AudioFormat头文件,deleter的const类型无法move-assign;修正拥有者类型,原生连接测试通过。
+3. 首份生成的视频夹具缺少PQ/BT2020 primaries的有效位流标记。产品正确拒绝将其按SDR处理;用FFmpeg hevc_metadata补齐**测试素材**的描述后重新测试,不削弱产品防错检查。
+4. 硬解测试最初在首帧前检查实际硬解状态;FFmpeg此时尚未分配解码面。改为验证每张实际AVFrame为D3D12,与产品行为一致。
+5. 截图首轮仅验证JXR自回读,未覆盖GPU→CPU拷贝;代码复查发现FP16每行仍按4字节宽度复制。修复为bytesPerPixel,并新增独立GPU原图→JXR逐像素比较,覆盖右半幅、负分量和4000nit。首轮自回读结果**不能作为完整截图通过证明**;以下final-mode记录才是有效证明。
+6. NativeCaptureSink的上游缓冲建议仍限定nBlockAlign≤8,六声道会退回驱动默认。改为按1–8声道/16、24、32位校验,新增6ch float的11520字节/10ms协商检查。
+7. 两个旧契约测试把P010等同HDR、把扩展transfer16误称PQ并一律拒绝。按现在的颜色合同修订:P010本身不是HDR,15为PQ、16为HLG,明确元数据必须保留。新增完整BT2020元数据和声道掩码变更重连测试。测试命名空间/参数个数编译错误均已修正,不作为功能通过证据。
+
+### 实际命令及结果
+
+所有相对路径以仓库根为基准;构建输出在 `out/remoteplay/product-repair`,日志在 `logs/hdr-multichannel`。测试夹具、抓帧、JXR、日志和DLL均被Git忽略。
+
+- 构建:`cmd /c out\release-1.1.0-build.cmd`,最终增量构建通过。中间失败和修复记录为 `out/hdr-build4.log`至`out/hdr-build19.log`;部分编译单元沿用仓库现有`/WX-`和第三方头文件警告,不宣称零警告。
+- `veyra_pipeline_tests.exe`:52 checks,0 failures;`veyra_capture_color_tests.exe`:0 failures(`capture-color-final.txt`),包含多声道DirectShow连接、10ms协商、side/back掩码重连与PQ/HLG元数据。
+- `veyra_hdr_color_tests.exe`:30种采集颜色GPU用例及16个HDR组合(PQ/HLG、planar/P010、full/limited、HDR输出/SDR映射)全部pass=1;`hdr-color-final.txt`。
+- `veyra_hdr_enhancement_tests.exe 0/1/2/3/4/5/6`:分别执行。原版NR20次;有SR时SR20次;DLSS有效生成18,XeSS生成16。mode3/4验证VideoSR与两种顺序;mode6验证DLSS SR的NR先行。`mode-*.txt`、`final-mode-*.txt`。
+- `veyra_hdr_enhancement_tests.exe 2 1`与`2 2`:Community/Ampere,在RTX5070上20/20/18、约999nit通过;`runtime-1.txt`/`runtime-2.txt`。未在RTX30/40执行。
+- `veyra_hdr_enhancement_tests.exe 2 0 out/hdr-audio-fixtures/pq-tagged-51.mp4 0/1`:分别软件/D3D12硬解;20/20/18,原帧和生成帧高亮边界通过。HLG硬解同样通过。`file-hdr-hw0.txt`、`file-hdr-hw1-v2.txt`、`file-hlg-hw1.txt`。
+- 最终截图独立比较:1024像素黑/近黑/广色域/4000nit与2073600像素FP16输出逐像素误差0;3686400像素RGB10→scRGB的最大误差0.00243568(scRGB单位,约0.195nit),符合FP16量化。文件也单独无损回读校验。`final-mode-0/1/2/5.txt`。
+- `veyra_multichannel_tests.exe out/hdr-audio-fixtures`:28 checks,0 failures;44.1/48/96k、side/back、PCM16/24/32格式解析、六个独立声道音调(含中置/LFE,其他声道泄漏0)、音量/淡出同步及帧单位PTS通过。`multichannel-final.txt`。
+- `veyra_capture_audio_tests.exe --jitter --5.1`:5秒30/35ms处理延迟波动,新增重锚0、欠载0、丢失0、p95偏差24.81ms。`--endpoint-loss --5.1`:2次重试后恢复。`--drift-fast --5.1`、`--drift-slow --5.1`:各120秒,p95偏差4.27/4.23ms,稳态没有反复重锚、队列峰值89.65ms。均静音,当前物理输出是2.0,不代表5.1扬声器验收。
+- 首轮`audio-timeline.txt`含4项失败:旧测试把保留下来的单声道源交给默认立体声renderer。逐项核查日志后修正调用顺序,按`pipe.pcmFormat()`创建endpoint;同样修正player_probe调用者。最终重跑结果见`audio-timeline-final.txt`及后续补充,首轮不能作为通过证据。
+- 产品导出命令示例:`veyra.exe out/hdr-audio-fixtures/pq-tagged-51.mp4 --nr --fg --no-sr --hevc --export-out out/hdr-audio-fixtures/export-pq-nr-fg-v2.mp4`,30源帧→60输出帧;`--nr --video-sr 1 --fg --hevc --max-frames 12`导出4K,12源帧→24输出帧(含既有明确的CFR尾保持),完整验证通过。
+- FFprobe确认Main10、10bit、BT2020/PQ、6ch;独立FFmpeg逐帧解码参考高亮约994nit(原始编码夹具约1004nit);HLG→PQ NR导出约1004nit。`export-final-check.json`、`export-highlight.json`、`export-*-probe.json`。导出前后解码六声道PCM SHA256一致(`export-audio-check.json`),没有丢失音轨或降混。
+- 8秒真实播放器命令带`--nr --fg --smoke-screenshot --smoke-save ...`:文件6ch→当前2ch设备明确降混,工具栏PNG保存,failed=false;`ui-hdr.txt`。当前Windows桌面HDR未启用,**这项UI测试实际走HDR→SDR,不冒充HDR实屏**。
+- 总交付短测:`powershell -NoProfile -ExecutionPolicy Bypass -File scripts/gates/delivery.ps1 -Root "C:/Users/123/Desktop/Veyra DLSS Video Player" -BuildDirectory out/remoteplay/product-repair`。首轮46.89秒通过,`logs/delivery/f6ad0f28d1de46c2a2bc7fd82723cee2/result.json`;截图/缓冲末轮修正后的结果另附本节末。
+
+### 用户验收与边界
+
+桌面 `Veyra PS5 测试版.lnk` 已核对指向本次构建的 `out/remoteplay/product-repair/veyra.exe`。官方1.1.1及其他实验快捷方式不是这一版。没有新发布、push或运行库替换。
+
+用户下一步:在Windows中开启HDR,用PQ/HLG素材或确实输出HDR的采集卡,比较效果开关前后的黑位、高亮和色彩;分别试NR/SR/DLSS/XeSS及两种处理顺序。用真实5.1源与配置为5.1的HDMI/USB输出端,确认面板6→6,并逐个检查前左/前右/中置/LFE/环绕定位、暂停seek与长时间连续性。采集卡只枚举2声道时无法凭软件取得真实5.1。HDR截图需HDR看图器;HDR导出选HEVC。
+
+尚未执行:HDR屏实测亮度/视觉验收、真实5.1扬声器、采集卡5.1与HDR实卡、RTX30/40、PS5重新连接、OBS/WGC的HDR捕获及跨HDR/SDR物理显示器移动。不承诺所有素材画质改善、不承诺全开原生4K实时、不支持Dolby/DTS码流直通或Atmos对象。NR/VideoSR是保留HDR基底的代理增强,非原生HDR模型。
+
+运行库:patched FFmpeg `avcodec-63.dll` SHA256仍为 `0710F0D87A7FFCC9F998F1A35D0500345F6C66EB9A5A39C51D60D293142BD84F`,没有回退PS5 slice补丁。增强运行组件保持原有身份,不进入源码Git。
+
+HLG参考:[ITU-R BT.2100-2](https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.2100-2-201807-S%21%21PDF-E.pdf)。该转换是1000nit参考实现,不是基于现场显示器测量的自动调光。
+
+## B 最终软件验收记录
+
+- 最终交付门槛:`logs/delivery/e344611bab454e2d9a23c510aac08215/result.json`,23/23,44.67秒,status=software_short_gate_passed。与当前EXE SHA256一致:`9F28BE16AC94AA33F013C7A29E32E8CE49753C445BE10AA22E572C948EEFD045`。
+- HDR H.264拒绝测试exit1,正式文件和partial均未产生,`reject-h264.txt`。
+- `audio-timeline-final.txt`全项PASS、进程exit0;另外文件`--underrate`和`--jitter`各exit0。51/60持续欠速下4.007秒墙钟、3.989秒声音,新增音频暂停0、欠载0。1×/2×/4×视频节奏抖动均没有丢PCM/静音补洞。证据`file-audio--underrate.txt`、`file-audio--jitter.txt`。
+- 修复后的JXR独立逐像素检查、采集6ch/10ms协商、完整HDR/SDR颜色检查及最终交付短测均以当前代码通过。`git diff --check`通过;无SDK、运行库、模型、用户配置或媒体进入Git。
+- XeSS验证的是HDR10初始化、真实SDK生成计数与软件原帧数值;本轮没有独立回读XeSS驱动交换链生成帧作逐像素比较。实际生成帧观感仍需用户验收。
+- 对外状态:本地开发版可测,非发布版、非全部硬件验收完成。下一步只需用户进行上节列出的HDR屏/采集卡/5.1实机验收,收到日志后针对问题修复;未经新授权不发布。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index dfb0bd2d..48a329cc 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1967,3 +1967,14 @@ GitHub Release https://github.com/Likely7/Veyra-NRVideo/releases/tag/v1.0.0 于
## 2026-09-14 — HDR/多声道实施节点 A
用户授权施工、PS5真实多声道排除。本地分支codex/hdr-multichannel,checkpoint/pre-hdr-multichannel-20260914。HDR基底保留、NR/VideoSR代理合成、RGB10 DLSS/XeSS补帧首轮GPU通过;20帧真实NR/SR及18/16生成,1000nit输出998.932nit,零残差广色域/高光身份通过。完整构建成功,具体命令/失败/证据和未测边界见docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md。其他入口、音频及产品收尾继续施工,未发布。
+
+
+## 2026-09-14 — HDR/多声道实施节点 B:软件交付、等待实机验收
+
+完成文件/P010-P016采集PQ与HLG输入、手动颜色覆盖、HDR保留NR/两种SR/DLSS-XeSS补帧、HEVC Main10 PQ导出、浮点JXR截图;文件/采集PCM保持声道掩码,共用音频时钟/增益/补偿,输出端明确降混,采集上游6ch同样协商10ms。PS5双声道保持,不伪造5.1。双语README标明本地开发、未发布,致谢仍在底部。
+
+构建命令cmd /c out\release-1.1.0-build.cmd通过。最终delivery23/23、44.67秒,logs/delivery/e344611bab454e2d9a23c510aac08215/result.json;EXE 9F28BE16AC94AA33F013C7A29E32E8CE49753C445BE10AA22E572C948EEFD045。pipeline52/52、capture contract零失败、30采集GPU+16HDR颜色用例通过;三NR运行库在5070组合20次Evaluate、DLSS18/XeSS16生成;六声道28检查通过,快/慢时钟各120秒通过;文件音频时间线、欠速和抖动最终exit0。HDR4K NR+VideoSR+FG Main10导出24帧完整解码,六声道音轨保持;JXR最终逐像素比较通过。patched FFmpeg哈希仍0710F0D8…284F。
+
+本轮发现并纠正FP16截图只拷半行、六声道上游缓冲仍限定8字节、旧测试/播放器probe将单声道送进立体声renderer;首轮JXR自回读不能证明原图完整、首轮audio-timeline包含4失败,均保留失败日志并由独立检查/重跑覆盖。其他编译/夹具失败和真实Create/Evaluate结果详见docs/HDR_MULTICHANNEL_EXECUTION_2026-09-14.md及logs/hdr-multichannel。没有把失败删掉或把尾部PASS当整套通过。
+
+桌面Veyra PS5测试版快捷方式指向当前构建。当前桌面HDR未启用、音频输出2ch,真实UI测试明确走HDR转SDR和6→2降混;HDR输出数值/接口验证与HDR实屏是分开的证据。未测真实5.1扬声器、HDR实卡、30/40系列、PS5新会话、OBS HDR及跨显示器切换。只完成软件实施,不宣称所有设备和画质验收。下一步用户在HDR屏与真5.1设备上验收;没有新push、Release、运行库替换或关机。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 2514df62..b5363ef6 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -31,7 +31,9 @@ struct PlayerSnapshot {
EnhancementSettings desired,applied;bool applying=false;
bool nrActive=false,srActive=false,fgActive=false;
std::wstring backendWarning;
+ std::wstring colorStatus;
sink::CaptureAudioState captureAudio;
+ unsigned audioInputChannels=0,audioOutputChannels=0;
bool audioRebuffering=false;
uint64_t audioVideoWaits=0;
bool audioEndpointRecovering=false;HRESULT audioEndpointError=S_OK;uint64_t audioEndpointRecoveries=0;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index b54bf9d3..625ec7d3 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -68,10 +68,10 @@ struct EnhanceGraphDesc {
bool enableNvofStandalone = false; // run NVOF+densify per frame without FG (quality core)
bool noFeatures = false; // VEYRA_NO_FEATURES: NVOF/NGX objects skipped
bool noNgx = false; // VEYRA_NO_NGX: core/features skipped, NVOF only
- bool hdrInput = false; // PS5 Main10 ingress; explicit SDR mapping unless hdrOutput.
+ bool hdrInput = false; // PQ/HLG YUV ingress; SDR tone mapping unless hdrOutput.
unsigned captureBitDepth = 8; // SDR P010/P016 storage, independent of HDR transfer.
bool wideYuvInput() const { return hdrInput || captureBitDepth > 8; }
- bool hdrOutput = false; // Native scRGB passthrough, no SDR-only enhancement.
+ bool hdrOutput = false; // HDR-preserving output: scRGB without FG; RGB10/PQ with FG.
bool highQualityPresentation = false; // PS5 ordinary scaling, no AI SR
bool rgbInput = false; // allocate direct RGBA ingestion before NGX creation
bool yuy2Input = false; // packed Y0 U Y1 V -> linear FP16; never subsample to NV12
diff --git a/include/veyra/sink/AudioFormat.h b/include/veyra/sink/AudioFormat.h
new file mode 100644
index 00000000..dd2ecca8
--- /dev/null
+++ b/include/veyra/sink/AudioFormat.h
@@ -0,0 +1,53 @@
+#pragma once
+#include <windows.h>
+#include <mmreg.h>
+#include <ks.h>
+#include <ksmedia.h>
+#include <bit>
+#include <cstdint>
+#include <cstring>
+namespace veyra::sink {
+// Interleaved float PCM exchanged by the software pipeline, always 48 kHz.
+// WAVE and FFmpeg native channel masks share the standard speaker bit order.
+struct AudioFormat {
+ unsigned channels=2;
+ uint32_t mask=SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT;
+ bool valid()const{return channels>=1&&channels<=8&&std::popcount(mask)==int(channels)&&(mask&~0x3ffffu)==0;}
+ bool operator==(const AudioFormat&)const=default;
+};
+struct WavePcmFormat {
+ WAVEFORMATEX wave{};
+ AudioFormat layout;
+ unsigned validBits=0;
+ bool floating=false;
+};
+inline bool parseWavePcm(const void* bytes,size_t size,WavePcmFormat& out){
+ if(!bytes||size<sizeof(WAVEFORMATEX))return false;
+ WAVEFORMATEX w{};memcpy(&w,bytes,sizeof(w));
+ if(w.cbSize>size-sizeof(w)||w.nChannels<1||w.nChannels>8||w.nSamplesPerSec<8000||w.nSamplesPerSec>192000||
+ (w.wBitsPerSample!=16&&w.wBitsPerSample!=24&&w.wBitsPerSample!=32)||
+ w.nBlockAlign!=w.nChannels*(w.wBitsPerSample/8)||w.nAvgBytesPerSec!=w.nBlockAlign*w.nSamplesPerSec)return false;
+ WavePcmFormat result;result.wave=w;result.layout.channels=w.nChannels;result.validBits=w.wBitsPerSample;
+ if(w.wFormatTag==WAVE_FORMAT_EXTENSIBLE){
+ if(w.cbSize<22||size<sizeof(WAVEFORMATEXTENSIBLE))return false;
+ WAVEFORMATEXTENSIBLE e{};memcpy(&e,bytes,sizeof(e));
+ if(e.SubFormat!=KSDATAFORMAT_SUBTYPE_PCM&&e.SubFormat!=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)return false;
+ result.floating=e.SubFormat==KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+ result.validBits=e.Samples.wValidBitsPerSample;
+ result.layout.mask=e.dwChannelMask;
+ }else{
+ if(w.wFormatTag!=WAVE_FORMAT_PCM&&w.wFormatTag!=WAVE_FORMAT_IEEE_FLOAT)return false;
+ result.floating=w.wFormatTag==WAVE_FORMAT_IEEE_FLOAT;
+ // More than stereo without a speaker mask is ambiguous (side/back).
+ if(w.nChannels>2)return false;
+ result.layout.mask=w.nChannels==1?SPEAKER_FRONT_CENTER:SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT;
+ }
+ if(!result.layout.valid()||!result.validBits||result.validBits>w.wBitsPerSample||
+ (result.floating&&(w.wBitsPerSample!=32||result.validBits!=32)))return false;
+ out=result;return true;
+}
+inline WAVEFORMATEXTENSIBLE floatWave(AudioFormat layout){
+ WAVEFORMATEXTENSIBLE out{};out.Format={WAVE_FORMAT_EXTENSIBLE,WORD(layout.channels),48000,48000*layout.channels*4,WORD(layout.channels*4),32,22};
+ out.Samples.wValidBitsPerSample=32;out.dwChannelMask=layout.mask;out.SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;return out;
+}
+}
diff --git a/include/veyra/sink/AudioGain.h b/include/veyra/sink/AudioGain.h
index 25ceafb7..18d5a12f 100644
--- a/include/veyra/sink/AudioGain.h
+++ b/include/veyra/sink/AudioGain.h
@@ -4,15 +4,17 @@
#include <cstddef>
namespace veyra::sink {
// 5 ms full-scale ramp at 48 kHz, independent of PTS and renderer clock.
-inline void applyStereoGain(float* samples,size_t frames,float target,float& current){
+inline void applyPcmGain(float* samples,size_t frames,unsigned channels,float target,float& current){
target=std::isfinite(target)?std::clamp(target,0.0f,1.0f):0;
- for(size_t i=0;i<frames;++i){current+=std::clamp(target-current,-1.0f/240,1.0f/240);samples[i*2]*=current;samples[i*2+1]*=current;}
+ for(size_t i=0;i<frames;++i){current+=std::clamp(target-current,-1.0f/240,1.0f/240);for(unsigned c=0;c<channels;++c)samples[i*channels+c]*=current;}
}
// Full transition duration is fixed even when the current user gain is low.
-inline void fadeStereoTail(float* samples,size_t frames,float gain){
+inline void fadePcmTail(float* samples,size_t frames,unsigned channels,float gain){
if(!frames)return;
gain=std::isfinite(gain)?std::clamp(gain,0.0f,1.0f):0;
for(size_t i=0;i<frames;++i){const float envelope=frames>1?gain*float(frames-1-i)/float(frames-1):0;
- samples[2*i]*=envelope;samples[2*i+1]*=envelope;}
+ for(unsigned c=0;c<channels;++c)samples[channels*i+c]*=envelope;}
}
+inline void applyStereoGain(float* p,size_t n,float target,float& current){applyPcmGain(p,n,2,target,current);}
+inline void fadeStereoTail(float* p,size_t n,float gain){fadePcmTail(p,n,2,gain);}
}
diff --git a/include/veyra/sink/AudioPcmSource.h b/include/veyra/sink/AudioPcmSource.h
index 19b720d0..eb248b46 100644
--- a/include/veyra/sink/AudioPcmSource.h
+++ b/include/veyra/sink/AudioPcmSource.h
@@ -1,11 +1,13 @@
#pragma once
#include <cstddef>
#include <optional>
+#include "veyra/sink/AudioFormat.h"
namespace veyra::sink {
class AudioPcmSource {
public:
virtual ~AudioPcmSource() = default;
- virtual size_t pull(float* stereo, size_t frames, double* firstPtsMs) = 0;
+ virtual AudioFormat pcmFormat()const{return {};}
+ virtual size_t pull(float* interleaved, size_t frames, double* firstPtsMs) = 0;
virtual std::optional<double> lastPullEndPtsMs()const{return {};}
virtual bool padUnderruns()const{return true;}
};
diff --git a/include/veyra/sink/CaptureAudioSession.h b/include/veyra/sink/CaptureAudioSession.h
index e53fcae6..7af482d4 100644
--- a/include/veyra/sink/CaptureAudioSession.h
+++ b/include/veyra/sink/CaptureAudioSession.h
@@ -8,6 +8,7 @@
namespace veyra::sink {
struct CaptureAudioState {
bool available=false,running=false,clockEstimated=true,limited=false;
+ unsigned inputChannels=0,outputChannels=0;uint32_t inputChannelMask=0,outputChannelMask=0;
double compensationMs=0,bufferedMs=0,bufferHighWaterMs=0,endpointBufferedMs=0;
double driftCorrectionPpm=0;
double inputBlockMs=0,inputIntervalMs=0;
@@ -20,7 +21,7 @@ class CaptureAudioSession {
public:
CaptureAudioSession();
~CaptureAudioSession();
- bool configure(const WAVEFORMATEX&);
+ bool configure(const WAVEFORMATEX&,size_t formatBytes=sizeof(WAVEFORMATEX));
bool start();
void stop();
bool push(const void* data,size_t bytes,double ptsMs,bool discontinuity);
diff --git a/include/veyra/sink/ImageExportSink.h b/include/veyra/sink/ImageExportSink.h
index 3f3a4c88..61406834 100644
--- a/include/veyra/sink/ImageExportSink.h
+++ b/include/veyra/sink/ImageExportSink.h
@@ -9,5 +9,6 @@ struct RgbaImage { uint32_t width=0, height=0; std::vector<uint8_t> pixels; };
// Image export / explicit diagnostics only. Never used by playback or video export.
bool readRgba8(gfx::D3D12DeviceContext&, gfx::CommandSlotRing&, ID3D12Resource*, RgbaImage&);
bool saveImage(const std::wstring& path, const RgbaImage&, bool jpeg=false);
+bool saveHdrScreenshot(const std::wstring& path,gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,ID3D12Resource*);
bool loadImage(const std::wstring& path, RgbaImage&);
}
diff --git a/include/veyra/sink/WasapiAudioSink.h b/include/veyra/sink/WasapiAudioSink.h
index ca9c0b01..7e15c002 100644
--- a/include/veyra/sink/WasapiAudioSink.h
+++ b/include/veyra/sink/WasapiAudioSink.h
@@ -47,6 +47,7 @@ public:
~AudioPipeline();
bool open(const std::wstring& path);
+ AudioFormat pcmFormat()const override{return pcmFormat_;}
double bufferedMs() const;
// PTS (ms) of the first unconsumed buffered sample; < 0 when empty.
@@ -61,7 +62,7 @@ public:
double firstPtsAfterLastSeek() const;
bool decodingComplete() const { return decodedEof_.load(); }
- // Pull up to maxFrames stereo frames; sets the PTS of the first pulled
+ // Pull up to maxFrames source-layout frames; sets the PTS of the first pulled
// frame. Returns frames pulled (0 legal; caller writes silence and it is
// counted as an underrun by the pump only when the endpoint had space).
size_t pull(float* dst, size_t maxFrames, double* firstPtsMs) override;
@@ -107,10 +108,12 @@ private:
friend class AudioThread;
+ AudioFormat pcmFormat_;
AVFormatContext* fmt_ = nullptr;
AVCodecContext* codecCtx_ = nullptr;
AVStream* stream_ = nullptr;
AVPacket* packet_ = nullptr;
+ int swrInputRate_=0,swrInputFormat_=-1;
SwrContext* swr_ = nullptr;
int streamIndex_ = -1;
bool havePacket_ = false;
@@ -122,7 +125,7 @@ private:
static constexpr size_t kMaxRingFrames = kAudioRate * 2; // 2s hard bound
mutable std::mutex mutex_;
- std::deque<float> ring_{}; // stereo interleaved
+ std::deque<float> ring_{}; // source-layout interleaved
size_t ringFrames_ = 0;
std::deque<Segment> segments_{}; // PTS bookkeeping of ring contents
@@ -153,7 +156,8 @@ private:
class AudioRenderer {
public:
~AudioRenderer(){shutdown();}
- bool start();
+ bool start(AudioFormat input = {});
+ AudioFormat outputFormat()const{std::lock_guard lock(endpointMutex_);return outputFormat_;}
void setGain(float value){gain_.store(value);}
// Write actual PCM before starting the endpoint and its media clock.
@@ -209,11 +213,15 @@ private:
std::atomic<bool> started_{false};
std::atomic<bool> running_{false};
std::atomic<bool> fading_{false};bool pausedEndpoint_=false;
- float lastRawLeft_=0,lastRawRight_=0;
+ std::vector<float> lastRaw_=std::vector<float>(2,0);
+ AudioFormat inputFormat_,outputFormat_;
+ SwrContext* channelMix_=nullptr;
+ std::vector<float> mixed_;
+ bool copyPcm(BYTE* destination,const float* input,size_t frames);
bool comInited_ = false;
std::atomic<uint64_t> underruns_{0};
std::atomic<uint64_t> framesWritten_{0};
- std::vector<float> chunk_{std::vector<float>(8192 * 2)};
+ std::vector<float> chunk_;
};
} // namespace veyra::sink
diff --git a/include/veyra/source/CaptureMediaType.h b/include/veyra/source/CaptureMediaType.h
index 96ca9875..81eccbf2 100644
--- a/include/veyra/source/CaptureMediaType.h
+++ b/include/veyra/source/CaptureMediaType.h
@@ -83,9 +83,14 @@ inline bool captureMediaLayout(const AM_MEDIA_TYPE& type,CaptureMediaLayout& out
else if(ext.NominalRange!=DXVA2_NominalRange_Unknown)return false;
if(ext.VideoTransferMatrix==DXVA2_VideoTransferMatrix_BT601){out.color.matrix=pipeline::YuvMatrix::BT601;out.color.matrixAssumed=false;}
else if(ext.VideoTransferMatrix==DXVA2_VideoTransferMatrix_BT709){out.color.matrix=pipeline::YuvMatrix::BT709;out.color.matrixAssumed=false;}
+ // Extended Windows MF/DXVA color codes: BT2020_10/12=4/5,
+ // BT2020 primaries=9, ST2084=15, HLG=16 (Windows SDK mfobjects.h).
+ else if(ext.VideoTransferMatrix==4||ext.VideoTransferMatrix==5){out.color.matrix=pipeline::YuvMatrix::BT2020NCL;out.color.matrixAssumed=false;}
else if(ext.VideoTransferMatrix!=DXVA2_VideoTransferMatrix_Unknown)return false;
+ if(ext.VideoPrimaries==9){out.color.primaries=pipeline::ColorPrimaries::BT2020;out.color.primariesAssumed=false;}
if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_10){out.color.transfer=pipeline::TransferFunction::Linear;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction==DXVA2_VideoTransFunc_sRGB){out.color.transferAssumed=false;}
+ else if(ext.VideoTransferFunction==15||ext.VideoTransferFunction==16){out.color.transfer=ext.VideoTransferFunction==15?pipeline::TransferFunction::PQ:pipeline::TransferFunction::HLG;out.color.transferAssumed=false;}
else if(ext.VideoTransferFunction!=DXVA2_VideoTransFunc_Unknown&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_709&&ext.VideoTransferFunction!=DXVA2_VideoTransFunc_22)return false;
}
return true;
diff --git a/shaders/RgbToNv12.hlsl b/shaders/RgbToNv12.hlsl
index 72fb31b7..26308622 100644
--- a/shaders/RgbToNv12.hlsl
+++ b/shaders/RgbToNv12.hlsl
@@ -1,17 +1,23 @@
+#include "HdrColor.hlsli"
Texture2D<float4> rgb : register(t0);
RWTexture2D<float> yPlane : register(u0);
RWTexture2D<float2> uvPlane : register(u1);
cbuffer Constants : register(b0) { uint width; uint height; uint2 reserved; float4 padding; };
float3 convert(float3 c) {
+ if(reserved.x){
+ float y=dot(c,float3(.2627,.6780,.0593));
+ return round(float3(64+876*y,512+896*(c.b-y)/1.8814,512+896*(c.r-y)/1.4746))*64.0/65535.0;
+ }
float y=dot(c,float3(0.2126,0.7152,0.0722));
return float3((16+219*y)/255.0, (128+224*(c.b-y)/1.8556)/255.0, (128+224*(c.r-y)/1.5748)/255.0);
}
+float3 inputColor(uint2 p){float3 c=rgb[p].rgb;return reserved.x==1?HdrEncodePq(c):saturate(c);}
[numthreads(16,16,1)]
void main(uint3 id:SV_DispatchThreadID){
if(id.x>=width||id.y>=height)return;
- yPlane[id.xy]=convert(saturate(rgb[id.xy].rgb)).x;
+ yPlane[id.xy]=convert(inputColor(id.xy)).x;
if((id.x&1)==0&&(id.y&1)==0){
- float3 c=(rgb[id.xy].rgb+rgb[id.xy+uint2(1,0)].rgb+rgb[id.xy+uint2(0,1)].rgb+rgb[id.xy+uint2(1,1)].rgb)*0.25;
+ float3 c=(inputColor(id.xy)+inputColor(id.xy+uint2(1,0))+inputColor(id.xy+uint2(0,1))+inputColor(id.xy+uint2(1,1)))*0.25;
uvPlane[id.xy/2]=convert(saturate(c)).yz;
}
}
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index d5f6d64f..dde2a344 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -95,6 +95,12 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
const float m1=2610.0/16384.0,m2=2523.0/32.0;
float3 p=pow(rgb,1.0/m2);
float3 nits=10000.0*pow(max(p-3424.0/4096.0,0.0)/max(2413.0/128.0-2392.0/128.0*p,1e-6),1.0/m1);
+ if(colorParams0.z>4.5){
+ // BT.2100 HLG reference display: 1000-nit peak, gamma 1.2,
+ // ideal black. HLG scene light needs its OOTF before PQ/scRGB.
+ float3 scene=select(rgb<=.5,rgb*rgb/3.0,(exp((rgb-.55991073)/.17883277)+.28466892)/12.0);
+ nits=1000.0*scene*pow(max(dot(scene,float3(.2627,.6780,.0593)),0),.2);
+ }
float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);
if(yuvDimensions.z!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
else{
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index b8c28c8e..a28fe5f3 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -205,7 +205,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{
std::lock_guard lock(mutex_);
if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg)))snapshot_.backendWarning=L"当前 GPU 不支持所选 NVIDIA 增强";
- if(gd.hdrInput)snapshot_.backendWarning=gd.hdrOutput?L"HDR输入 → HDR保留增强/显示":L"HDR输入 → SDR色调映射后增强/显示";
if(graph.xessEnabled()&&!presenter.xessActive())snapshot_.backendWarning=L"XeSS 初始化失败;当前为普通呈现";
}
captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
@@ -235,7 +234,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
{std::lock_guard lock(mutex_);snapshot_.audioRebuffering=audioPipe.waitingForVideo();snapshot_.audioVideoWaits=audioPipe.videoWaitCount();}
if(recovering!=publishedAudioRecovery||error!=publishedAudioError||count!=publishedAudioRecoveries){
publishedAudioRecovery=recovering;publishedAudioError=error;publishedAudioRecoveries=count;
- std::lock_guard lock(mutex_);snapshot_.audioEndpointRecovering=recovering;snapshot_.audioEndpointError=error;snapshot_.audioEndpointRecoveries=count;
+ std::lock_guard lock(mutex_);snapshot_.audioInputChannels=audioPipe.pcmFormat().channels;snapshot_.audioOutputChannels=audio.outputFormat().channels;snapshot_.audioEndpointRecovering=recovering;snapshot_.audioEndpointError=error;snapshot_.audioEndpointRecoveries=count;
}
};
PresentationScheduler liveTimeline;uint64_t submitted=0,expired=0;std::deque<int64_t> submissionTimes;
@@ -381,7 +380,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(liveScheduler&&liveScheduler->failed()){status(L"视频呈现失败,请查看诊断",true);break;}
const float gain=muted_?0.0f:volume_.load();audio.setGain(gain);
captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
- if(physicalCapture){const bool available=captureSource.setAudioGain(gain);const auto audioState=captureSource.audioState();std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;snapshot_.captureAudio=audioState;}
+ if(physicalCapture){const bool available=captureSource.setAudioGain(gain);const auto audioState=captureSource.audioState();std::lock_guard lock(mutex_);snapshot_.audioAvailable=available;snapshot_.captureAudio=audioState;snapshot_.audioInputChannels=audioState.inputChannels;snapshot_.audioOutputChannels=audioState.outputChannels;}
#ifdef VEYRA_ENABLE_REMOTEPLAY
if(remote){remote->setAudioGain(gain);remote->setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
const auto state=remote->audioState();const auto session=remote->sessionSnapshot();const auto rates=remote->rates();
@@ -392,7 +391,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}
if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();
drainLivePresentation();
- if(graph.hdrOutput())status(L"原生HDR截图尚未支持;可使用SDR映射模式保存图片",false);else if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}
+ if(graph.hdrOutput()){auto hdrPath=std::filesystem::path(save);hdrPath.replace_extension(L".jxr");if(sink::saveHdrScreenshot(hdrPath.wstring(),ctx,ring,graph.videoFrameResource(out.videoSlot)))status(L"HDR截图已保存:"+hdrPath.wstring());else status(L"HDR截图保存失败,请查看日志",false);}else if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}
catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}
if(isImage)requested.multiplier=1;
if(requested.revision==options.settings.revision&&requested!=options.settings){
@@ -445,7 +444,6 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}else if(accepted)accepted=graph.applySettings(requested);
if(accepted){
options=next;gd=nextDesc;transaction=true;reset=true;
- if(gd.hdrInput){std::lock_guard lock(mutex_);snapshot_.backendWarning=gd.hdrOutput?L"HDR输入 → HDR保留增强/显示":L"HDR输入 → SDR色调映射后增强/显示";}
resetRecord->epoch=0;
if(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested settings revision={} nr={} sr={} fgBackend={} flowBackend={}",requested.revision,next.nr,next.sr,frameGenerationBackendName(requested.frameGenerationBackend),opticalFlowBackendName(requested.opticalFlowBackend)));
}
@@ -884,7 +882,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
measured.flow=frameFlow->snapshot(host100ns());
measured.sourceFrames=measured.flow.counters.sourceAccepted;measured.validGenerated=measured.flow.counters.fgReadyValid;measured.submitted=measured.flow.counters.realPresented+measured.flow.counters.generatedPresented;measured.expired=measured.flow.counters.generatedExpiredAfterEval;
const double ageP95=liveScheduler?completed.ageP95:captureAges.p95(),waitP95=liveScheduler?completed.waitP95:scheduleWaits.p95(),presentP95=liveScheduler?completed.presentP95:presentTimes.p95();
- ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
+ ++frames;{std::lock_guard lock(mutex_);snapshot_.metrics=measured;snapshot_.colorStatus=gd.hdrOutput?(graph.hdr10Output()?L"HDR → HDR10 / PQ":L"HDR → scRGB / 浮点"):gd.hdrInput?L"HDR → SDR色调映射":L"SDR → SDR";snapshot_.position=(isCapture||isImage?pts:lastFilePresentedMs)/1000;snapshot_.frames=sourceFrames;snapshot_.generated=graphStats.fgGeneratedFrames;snapshot_.lateMs=lateness;snapshot_.lateP95Ms=sorted.empty()?0:sorted[size_t((sorted.size()-1)*0.95)];
// Measured playback speed: media-PTS advance per wall time
// over ~1s windows (1.0 = normal speed), resampled on seek.
const auto speedNow=Clock::now();
diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cpp
index 2e702851..7ae52803 100644
--- a/src/engine/VideoExportJob.cpp
+++ b/src/engine/VideoExportJob.cpp
@@ -16,6 +16,7 @@ extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/mathematics.h>
+#include <libavutil/pixdesc.h>
}
namespace veyra::engine {
namespace { std::string utf8(const std::wstring& s){const int n=WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),nullptr,0,nullptr,nullptr);std::string r(n,0);WideCharToMultiByte(CP_UTF8,0,s.data(),int(s.size()),r.data(),n,nullptr,nullptr);return r;} }
@@ -30,6 +31,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
AVFormatContext *mux=nullptr,*audioInput=nullptr;AVStream* videoStream=nullptr;AVStream* audioStream=nullptr;AVPacket* audioPacket=av_packet_alloc();
int audioIndex=-1;bool audioPending=false,audioEof=false,ok=false,headerWritten=false;int64_t written=0;double audioEndSeconds=0,videoOriginSeconds=0;
std::wstring failureReason;
+ bool hdrExport=false;
uint32_t outputWidth=0,outputHeight=0;AVRational outputRate{};
const auto partial=output+L".partial";
try { do {
@@ -55,12 +57,15 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
outputRate=rate;
veyra::log::info("export-timeline",std::format("CFR declared={}/{} candidate={}/{} timestampQuantum={} sampled={} output={}/{} (timestamp-consistent candidate, quantized short clips may be ambiguous; every PTS validated)",info.nominalRateNum,info.nominalRateDen,rateNum,rateDen,info.timestampQuantum,samples.size(),rate.num,rate.den));
const auto resolution=pipeline::ResolutionPlan::make({info.width,info.height},options.sr,pipeline::NrSizePolicy::Native,true,options.settings.revision,options.settings.srTarget);
- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ pipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();hdrExport=gd.hdrOutput;
+ if(gd.hdrOutput&&!hevc){failureReason=L"HDR视频请使用HEVC Main10导出(选择HEVC)";break;}
+ gd.sourceWidth=info.width;gd.sourceHeight=info.height;gd.workWidth=resolution.base.width;gd.workHeight=resolution.base.height;gd.nrWidth=resolution.nr.width;gd.nrHeight=resolution.nr.height;gd.flowWidth=resolution.flow.width;gd.flowHeight=resolution.flow.height;gd.enableSr=resolution.srApplied;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;gd.contentRate=options.settings.content;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
if(!graph.initialize(gd)||!graph.createViews())break;
outputWidth=gd.workWidth;outputHeight=gd.workHeight;
if(avformat_alloc_output_context2(&mux,nullptr,"mp4",utf8(partial).c_str())<0||!mux)break;
videoStream=avformat_new_stream(mux,nullptr);if(!videoStream)break;videoStream->time_base={rate.den,rate.num};videoStream->avg_frame_rate=rate;
auto* cp=videoStream->codecpar;cp->codec_type=AVMEDIA_TYPE_VIDEO;cp->codec_id=hevc?AV_CODEC_ID_HEVC:AV_CODEC_ID_H264;cp->width=gd.workWidth;cp->height=gd.workHeight;cp->format=AV_PIX_FMT_YUV420P;cp->color_range=AVCOL_RANGE_MPEG;cp->color_space=AVCOL_SPC_BT709;cp->color_primaries=AVCOL_PRI_BT709;cp->color_trc=AVCOL_TRC_IEC61966_2_1;
+ if(gd.hdrOutput){cp->format=AV_PIX_FMT_YUV420P10LE;cp->color_space=AVCOL_SPC_BT2020_NCL;cp->color_primaries=AVCOL_PRI_BT2020;cp->color_trc=AVCOL_TRC_SMPTE2084;cp->profile=AV_PROFILE_HEVC_MAIN_10;}
auto inputUtf8=utf8(input);
if(avformat_open_input(&audioInput,inputUtf8.c_str(),nullptr,nullptr)<0||avformat_find_stream_info(audioInput,nullptr)<0){progress(0,L"无法读取源音轨信息,已停止导出");break;}
{
@@ -137,6 +142,11 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti
pipeline::FramePacket pkt;const AVFrame* frame=nullptr;const auto rs=check.read(pkt,&frame);
if(rs==source::SourceReadStatus::Eos){reachedEos=true;break;}
if(rs!=source::SourceReadStatus::Frame||pkt.pts.isUnknown()||decoded>=uint64_t(written)||!verifiedTimeline.accepts(decoded,pkt.pts.toDouble())){ok=false;break;}
+ if(hdrExport){
+ const auto* format=av_pix_fmt_desc_get(static_cast<AVPixelFormat>(frame->format));
+ if(!format||format->comp[0].depth<10||pkt.colorInfo.transfer!=pipeline::TransferFunction::PQ||
+ pkt.colorInfo.primaries!=pipeline::ColorPrimaries::BT2020||pkt.colorInfo.matrix!=pipeline::YuvMatrix::BT2020NCL){ok=false;break;}
+ }
++decoded;
}
ok=ok&&!cancel&&reachedEos&&decoded==uint64_t(written);
diff --git a/src/ngx/DlssFgBackend.cpp b/src/ngx/DlssFgBackend.cpp
index 8f9330ba..f48281a5 100644
--- a/src/ngx/DlssFgBackend.cpp
+++ b/src/ngx/DlssFgBackend.cpp
@@ -229,6 +229,12 @@ bool DlssFgBackend::evaluate(ID3D12GraphicsCommandList* cmdList,
return false;
}
+ if(desc.hdr&&(!desc.backbuffer||!desc.outputInterpolated||
+ desc.backbuffer->GetDesc().Format!=DXGI_FORMAT_R10G10B10A2_UNORM||
+ desc.outputInterpolated->GetDesc().Format!=DXGI_FORMAT_R10G10B10A2_UNORM)){
+ log::error("fg-backend","HDR Evaluate requires RGB10/PQ input and output textures");
+ status=Status::InvalidArgument;return false;
+ }
NVSDK_NGX_D3D12_DLSSG_Eval_Params evalParams{};
evalParams.pBackbuffer = desc.backbuffer;
evalParams.pDepth = desc.depth;
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index 4cff98a2..41acd1d7 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -691,13 +691,16 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
return false;
}
const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});
+ if(desc_.hdrInput&&!resolved.isHdrPath()){
+ veyra::log::error("hdr","HDR source transfer changed to SDR; reopen/rebuild required");return false;
+ }
if(resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10||(resolved.matrix==YuvMatrix::BT2020NCL&&!desc_.hdrInput)){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
- if(resolved.transfer==TransferFunction::PQ&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
- veyra::log::error("hdr","Unsupported PQ colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
+ if(resolved.isHdrPath()&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
+ veyra::log::error("hdr","Unsupported PQ/HLG colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
}
if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709));
- if (resolved.transfer==TransferFunction::HLG || (resolved.transfer==TransferFunction::PQ&&!desc_.hdrInput)) {
- veyra::log::error("graph", "HDR input is unsupported by the V1 SDR pipeline"); return false;
+ if (resolved.isHdrPath()&&(!desc_.hdrInput||desc_.rgbInput||desc_.yuy2Input)) {
+ veyra::log::error("graph", "HDR input requires an explicit YUV HDR contract; RGB/YUY2 HDR ingress is unsupported"); return false;
}
if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
if(prevValid_&&(std::llround(ptsMs*10000)-std::llround(prevPtsMs_*10000)<4||ptsMs-prevPtsMs_>1000)){
@@ -897,7 +900,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}else{
const float constants[8] = { resolved.range==ColorRange::Full?0.0f:1.0f,
resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
- resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?(nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?1.0f:0.0f):(desc_.captureBitDepth==16?2.0f:desc_.wideYuvInput()?1.0f:0.0f)),
+ resolved.transfer==TransferFunction::HLG?5.0f:resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?(nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?1.0f:0.0f):(desc_.captureBitDepth==16?2.0f:desc_.wideYuvInput()?1.0f:0.0f)),
uintBits(srcW_), uintBits(srcH_), uintBits(desc_.hdrOutput?1u:0u),
uintBits(resolved.reconstructChroma?std::max(1u,unsigned(resolved.chromaLocation)):0u) };
yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, nv12Texture ? 3 + parity * 2 : 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
diff --git a/src/sink/CaptureAudioSession.cpp b/src/sink/CaptureAudioSession.cpp
index f33082f0..f0579ee6 100644
--- a/src/sink/CaptureAudioSession.cpp
+++ b/src/sink/CaptureAudioSession.cpp
@@ -15,6 +15,8 @@ int64_t hostTime(){return std::chrono::duration_cast<std::chrono::nanoseconds>(s
struct CaptureAudioSession::Impl : AudioPcmSource {
struct Chunk {std::vector<uint8_t> bytes;double pts=0;bool discontinuity=false;};
WAVEFORMATEX format{};
+ AudioFormat layout;bool floating=false;
+ AudioFormat pcmFormat()const override{return layout;}
mutable std::mutex mutex;
std::condition_variable wake;
std::deque<Chunk> input;
@@ -35,21 +37,21 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
CaptureAudioState state;
std::thread thread;
static constexpr double maxAutoDelayMs=1500,maxQueuedMs=2000;
- double queuedMs()const{return 1000.0*(pcm.size()/2)/kAudioRate+1000.0*(inputBytes+convertingBytes)/format.nAvgBytesPerSec;}
+ double queuedMs()const{return 1000.0*(pcm.size()/layout.channels)/kAudioRate+1000.0*(inputBytes+convertingBytes)/format.nAvgBytesPerSec;}
void queueChanged(){state.bufferedMs=queuedMs();state.bufferHighWaterMs=std::max(state.bufferHighWaterMs,state.bufferedMs);}
void clearPcmLocked(){pcm.clear();haveHead=false;pcmTimeline.clear();pcmHead=pcmTail=0;pullEnd.reset();}
void clearPcm(){std::lock_guard lock(mutex);clearPcmLocked();queueChanged();}
void discardPcm(size_t frames){
- for(size_t i=0;i<frames*2;++i)pcm.pop_front();pcmHead+=frames;
+ for(size_t i=0;i<frames*layout.channels;++i)pcm.pop_front();pcmHead+=frames;
headPts=pcmTimeline.at(double(pcmHead)).value_or(headPts);
pcmTimeline.discardBefore(pcmHead);queueChanged();
}
void fail(const wchar_t* reason){std::lock_guard lock(mutex);state.available=false;state.running=false;state.skewMs.reset();state.error=reason;}
size_t pull(float* dst,size_t frames,double* pts)override{
std::lock_guard lock(mutex);
- const size_t take=std::min(frames,pcm.size()/2);
+ const size_t take=std::min(frames,pcm.size()/layout.channels);
*pts=haveHead?headPts:-1;
- for(size_t i=0;i<take*2;++i)dst[i]=pcm[i];
+ for(size_t i=0;i<take*layout.channels;++i)dst[i]=pcm[i];
discardPcm(take);pullEnd=take?std::optional<double>(headPts):std::nullopt;
return take;
}
@@ -61,8 +63,8 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const bool injectEndpointLoss=GetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",nullptr,0)>0;
bool injected=false;uint64_t endpointPumps=0;
SwrContext* swr=nullptr;
- AVChannelLayout out=AV_CHANNEL_LAYOUT_STEREO,in{};av_channel_layout_default(&in,format.nChannels);
- const auto inputFormat=format.wFormatTag==WAVE_FORMAT_IEEE_FLOAT?AV_SAMPLE_FMT_FLT:format.wBitsPerSample==16?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_S32;
+ AVChannelLayout out{},in{};av_channel_layout_from_mask(&out,layout.mask);av_channel_layout_from_mask(&in,layout.mask);
+ const auto inputFormat=floating?AV_SAMPLE_FMT_FLT:format.wBitsPerSample==16?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_S32;
const int configured=swr_alloc_set_opts2(&swr,&out,AV_SAMPLE_FMT_FLT,kAudioRate,&in,inputFormat,format.nSamplesPerSec,0,nullptr);
av_channel_layout_uninit(&in);
if(configured<0||!swr||swr_init(swr)<0){log::error("capture-audio","resampler initialization failed");swr_free(&swr);renderer.shutdown();fail(L"音频重采样初始化失败");return;}
@@ -95,9 +97,9 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const auto time=hostTime();
if(time<retryAt){std::unique_lock lock(mutex);wake.wait_for(lock,std::chrono::milliseconds(20),[&]{return stop.load();});continue;}
{std::lock_guard lock(mutex);++state.endpointRetries;}
- if(!renderer.start()){if(!recoverEndpoint())break;continue;}
+ if(!renderer.start(layout)){if(!recoverEndpoint())break;continue;}
endpointReady=true;lastUnderruns=renderer.underruns();
- {std::lock_guard lock(mutex);state.error.clear();pendingReset=true;}
+ {std::lock_guard lock(mutex);state.error.clear();state.inputChannels=layout.channels;state.inputChannelMask=layout.mask;const auto output=renderer.outputFormat();state.outputChannels=output.channels;state.outputChannelMask=output.mask;pendingReset=true;}
}
renderer.setGain(gain);
// Wait before collecting callbacks, so PCM arriving during the
@@ -124,8 +126,14 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
const auto delay=swr_get_delay(swr,format.nSamplesPerSec);
const int capacity=swr_get_out_samples(swr,inputFrames);
if(capacity<=0||capacity>int(kAudioRate)){log::error("capture-audio","invalid converted block capacity");fail(L"音频转换块大小无效");break;}
- std::vector<float> converted(size_t(capacity)*2);
+ std::vector<float> converted(size_t(capacity)*layout.channels);
uint8_t* dst[]={reinterpret_cast<uint8_t*>(converted.data())};const uint8_t* src[]={chunk.bytes.data()};
+ std::vector<int32_t> packed24;
+ if(format.wBitsPerSample==24){
+ packed24.resize(size_t(inputFrames)*layout.channels);
+ for(size_t i=0;i<packed24.size();++i){const auto* p=chunk.bytes.data()+i*3;const uint32_t v=(uint32_t(p[0])<<8)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<24);memcpy(&packed24[i],&v,4);}
+ src[0]=reinterpret_cast<const uint8_t*>(packed24.data());
+ }
const int count=swr_convert(swr,dst,capacity,src,inputFrames);
if(count<0){log::error("capture-audio",std::format("convert failed code={}",count));fail(L"音频转换失败");break;}
const double start=chunk.pts-1000.0*delay/format.nSamplesPerSec;
@@ -143,7 +151,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
}else{
if(!haveHead){headPts=start;haveHead=true;}
pcmTimeline.append(pcmTail,count,start,end);pcmTail+=count;
- pcm.insert(pcm.end(),converted.begin(),converted.begin()+size_t(count)*2);
+ pcm.insert(pcm.end(),converted.begin(),converted.begin()+size_t(count)*layout.channels);
}
queueChanged();
}
@@ -152,7 +160,7 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
std::lock_guard lock(mutex);
// Drain callback blocks already available before waiting for
// another endpoint event; otherwise silence can build a backlog.
- if(!input.empty()&&1000.0*(pcm.size()/2)/kAudioRate<renderer.capacityMs()+10)continue;
+ if(!input.empty()&&1000.0*(pcm.size()/layout.channels)/kAudioRate<renderer.capacityMs()+10)continue;
}
// Both streams use graph PTS. Relate the latest displayed video PTS
// to host time; the endpoint's own queued frames are not added again.
@@ -169,11 +177,11 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
}
bool justStarted=false;
const double startupPrefillMs=std::min(renderer.capacityMs(),10.0);
- if(!renderer.started()&&haveHead&&1000.0*(pcm.size()/2)/kAudioRate>=startupPrefillMs&&(appliedMode!=0||fresh)){
+ if(!renderer.started()&&haveHead&&1000.0*(pcm.size()/layout.channels)/kAudioRate>=startupPrefillMs&&(appliedMode!=0||fresh)){
// Live recovery discards expired sound rather than replaying
// an obsolete half-second after a GPU stall or graph reset.
const size_t prefill=size_t(std::ceil(startupPrefillMs*kAudioRate/1000));
- const size_t expired=std::min(pcm.size()/2-prefill,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));
+ const size_t expired=std::min(pcm.size()/layout.channels-prefill,size_t(std::max(0.0,(now-mapping-headPts-5)*kAudioRate/1000)));
{std::lock_guard lock(mutex);discardPcm(expired);}
const bool due=now>=mapping+headPts;
if(due&&!pcm.empty()){
@@ -234,12 +242,10 @@ struct CaptureAudioSession::Impl : AudioPcmSource {
};
CaptureAudioSession::CaptureAudioSession():p_(std::make_unique<Impl>()){}
CaptureAudioSession::~CaptureAudioSession(){stop();}
-bool CaptureAudioSession::configure(const WAVEFORMATEX& f){
- if(p_->thread.joinable()||f.nChannels<1||f.nChannels>2||f.nSamplesPerSec<8000||f.nSamplesPerSec>192000||
- (f.wFormatTag!=WAVE_FORMAT_PCM&&f.wFormatTag!=WAVE_FORMAT_IEEE_FLOAT)||
- (f.wBitsPerSample!=16&&f.wBitsPerSample!=32)||(f.wFormatTag==WAVE_FORMAT_IEEE_FLOAT&&f.wBitsPerSample!=32)||
- f.nBlockAlign!=f.nChannels*f.wBitsPerSample/8||f.nAvgBytesPerSec!=f.nBlockAlign*f.nSamplesPerSec)return false;
- p_->format=f;return true;
+bool CaptureAudioSession::configure(const WAVEFORMATEX& f,size_t bytes){
+ WavePcmFormat parsed;
+ if(p_->thread.joinable()||!parseWavePcm(&f,bytes,parsed))return false;
+ p_->format=parsed.wave;p_->layout=parsed.layout;p_->floating=parsed.floating;return true;
}
bool CaptureAudioSession::start(){
if(!p_->format.nBlockAlign||p_->thread.joinable())return false;
diff --git a/src/sink/ImageExportSink.cpp b/src/sink/ImageExportSink.cpp
index 25f09938..ace231fc 100644
--- a/src/sink/ImageExportSink.cpp
+++ b/src/sink/ImageExportSink.cpp
@@ -7,12 +7,13 @@
#include <cstring>
#include <filesystem>
#include <limits>
+#include <DirectXPackedVector.h>
+#include <cmath>
namespace veyra::sink {
using Microsoft::WRL::ComPtr;
-bool readRgba8(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,RgbaImage& img) {
+static bool readPixels(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,RgbaImage& img,unsigned bytesPerPixel) {
if(!tex) return false;
auto d=tex->GetDesc();
- if(d.Format!=DXGI_FORMAT_R8G8B8A8_UNORM) return false;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; UINT rows=0; UINT64 rowBytes=0,total=0;
ctx.device()->GetCopyableFootprints(&d,0,1,0,&fp,&rows,&rowBytes,&total);
D3D12_HEAP_PROPERTIES hp{}; hp.Type=D3D12_HEAP_TYPE_READBACK;
@@ -31,10 +32,48 @@ bool readRgba8(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Res
if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;
uint8_t* data=nullptr; D3D12_RANGE range{0,static_cast<SIZE_T>(total)};
if(FAILED(rb->Map(0,&range,reinterpret_cast<void**>(&data))))return false;
- img.width=static_cast<uint32_t>(d.Width);img.height=d.Height;img.pixels.resize(size_t(img.width)*img.height*4);
- for(UINT y=0;y<img.height;++y)std::memcpy(img.pixels.data()+size_t(y)*img.width*4,data+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(img.width)*4);
+ img.width=static_cast<uint32_t>(d.Width);img.height=d.Height;img.pixels.resize(size_t(img.width)*img.height*bytesPerPixel);
+ for(UINT y=0;y<img.height;++y)std::memcpy(img.pixels.data()+size_t(y)*img.width*bytesPerPixel,data+fp.Offset+size_t(y)*fp.Footprint.RowPitch,size_t(img.width)*bytesPerPixel);
D3D12_RANGE empty{0,0};rb->Unmap(0,&empty);return true;
}
+bool readRgba8(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* tex,RgbaImage& img){
+ return tex&&tex->GetDesc().Format==DXGI_FORMAT_R8G8B8A8_UNORM&&readPixels(ctx,ring,tex,img,4);
+}
+bool saveHdrScreenshot(const std::wstring& path,gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12Resource* texture){
+ if(!texture||std::filesystem::exists(path))return false;
+ const auto format=texture->GetDesc().Format;const bool pq=format==DXGI_FORMAT_R10G10B10A2_UNORM;
+ if(!pq&&format!=DXGI_FORMAT_R16G16B16A16_FLOAT)return false;
+ RgbaImage raw;if(!readPixels(ctx,ring,texture,raw,pq?4:8))return false;
+ const size_t count=size_t(raw.width)*raw.height;std::vector<uint16_t> pixels(count*4);
+ if(!pq)memcpy(pixels.data(),raw.pixels.data(),count*8);
+ else for(size_t i=0;i<count;++i){
+ uint32_t packed;memcpy(&packed,raw.pixels.data()+i*4,4);double linear[3];
+ for(unsigned c=0;c<3;++c){const double p=pow(double((packed>>(10*c))&1023)/1023,32.0/2523);linear[c]=125*pow(std::max(p-3424.0/4096,0.0)/(2413.0/128-2392.0/128*p),16384.0/2610);}
+ const double matrix[3][3]={{1.660491,-.587641,-.072850},{-.124550,1.132900,-.008349},{-.018151,-.100579,1.118730}};
+ for(unsigned c=0;c<3;++c)pixels[i*4+c]=DirectX::PackedVector::XMConvertFloatToHalf(float(matrix[c][0]*linear[0]+matrix[c][1]*linear[1]+matrix[c][2]*linear[2]));
+ pixels[i*4+3]=DirectX::PackedVector::XMConvertFloatToHalf(1);
+ }
+ const auto partial=path+L".partial";HANDLE file=CreateFileW(partial.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr);if(file==INVALID_HANDLE_VALUE)return false;CloseHandle(file);
+ struct Guard{std::wstring path;bool active=true;~Guard(){if(active)DeleteFileW(path.c_str());}} guard{partial};
+ ComPtr<IWICImagingFactory> factory;ComPtr<IWICStream> stream;ComPtr<IWICBitmapEncoder> encoder;ComPtr<IWICBitmapFrameEncode> frame;ComPtr<IPropertyBag2> options;
+ if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory)))||FAILED(factory->CreateStream(&stream))||FAILED(stream->InitializeFromFilename(partial.c_str(),GENERIC_WRITE))||FAILED(factory->CreateEncoder(GUID_ContainerFormatWmp,nullptr,&encoder))||FAILED(encoder->Initialize(stream.Get(),WICBitmapEncoderNoCache))||FAILED(encoder->CreateNewFrame(&frame,&options)))return false;
+ PROPBAG2 property{};property.pstrName=const_cast<wchar_t*>(L"Lossless");VARIANT lossless{};lossless.vt=VT_BOOL;lossless.boolVal=VARIANT_TRUE;
+ if(FAILED(options->Write(1,&property,&lossless))||FAILED(frame->Initialize(options.Get()))||FAILED(frame->SetSize(raw.width,raw.height)))return false;
+ auto pixelFormat=GUID_WICPixelFormat64bppRGBAHalf;
+ if(FAILED(frame->SetPixelFormat(&pixelFormat))||pixelFormat!=GUID_WICPixelFormat64bppRGBAHalf||count>UINT_MAX/8)return false;
+ if(FAILED(frame->WritePixels(raw.height,raw.width*8,UINT(count*8),reinterpret_cast<BYTE*>(pixels.data())))||FAILED(frame->Commit())||FAILED(encoder->Commit()))return false;
+ frame.Reset();encoder.Reset();stream.Reset();
+ // Verify lossless floating-point storage, not an 8-bit thumbnail decode.
+ ComPtr<IWICBitmapDecoder> decoder;ComPtr<IWICBitmapFrameDecode> decoded;
+ if(FAILED(factory->CreateDecoderFromFilename(partial.c_str(),nullptr,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&decoder))||FAILED(decoder->GetFrame(0,&decoded)))return false;
+ WICPixelFormatGUID decodedFormat;UINT width=0,height=0;
+ if(FAILED(decoded->GetPixelFormat(&decodedFormat))||decodedFormat!=pixelFormat||FAILED(decoded->GetSize(&width,&height))||width!=raw.width||height!=raw.height)return false;
+ std::vector<uint16_t> verify(count*4);
+ if(FAILED(decoded->CopyPixels(nullptr,width*8,UINT(count*8),reinterpret_cast<BYTE*>(verify.data())))||verify!=pixels)return false;
+ decoded.Reset();decoder.Reset();
+ if(!MoveFileExW(partial.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH))return false;guard.active=false;
+ log::info("hdr-screenshot","saved and lossless-verified scRGB FP16 JPEG XR; 1=80 nits, includes software processing only");return true;
+}
bool loadImage(const std::wstring& path,RgbaImage& img) {
ComPtr<IWICImagingFactory> fac;ComPtr<IWICBitmapDecoder> dec;ComPtr<IWICBitmapFrameDecode> frame;ComPtr<IWICFormatConverter> conv;
if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&fac)))||
diff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cpp
index eab233d4..89337b51 100644
--- a/src/sink/NvencD3D12Encoder.cpp
+++ b/src/sink/NvencD3D12Encoder.cpp
@@ -12,6 +12,7 @@ using namespace veyra::pipeline;
struct NvencD3D12Encoder::Impl {
HMODULE dll=nullptr;void* encoder=nullptr;NV_ENCODE_API_FUNCTION_LIST api{};
gfx::D3D12DeviceContext* ctx=nullptr;gfx::CommandSlotRing* ring=nullptr;EnhanceGraph* graph=nullptr;
+ bool hdr=false;NV_ENC_BUFFER_FORMAT inputFormat=NV_ENC_BUFFER_FORMAT_NV12;
unsigned w=0,h=0;uint64_t submitted=0,completed=0;
ComPtr<ID3D12Fence> fence;HANDLE event=nullptr;
ComputePass convert;StateTracker states;ComPtr<ID3D12Resource> y,uv;
@@ -40,6 +41,8 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
p.api.version=NV_ENCODE_API_FUNCTION_LIST_VER;if(!create||!p.check(create(&p.api),"CreateInstance"))return false;
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS open{};open.version=NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;open.apiVersion=NVENCAPI_VERSION;open.device=ctx.device();open.deviceType=NV_ENC_DEVICE_TYPE_DIRECTX;
if(!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session"))return false;
+ p.hdr=graph.hdrOutput();if(p.hdr&&!hevc){veyra::log::error("nvenc","HDR export requires HEVC Main10");return false;}
+ p.inputFormat=p.hdr?NV_ENC_BUFFER_FORMAT_YUV420_10BIT:NV_ENC_BUFFER_FORMAT_NV12;
const GUID codec=hevc?NV_ENC_CODEC_HEVC_GUID:NV_ENC_CODEC_H264_GUID;
int maxWidth=0,maxHeight=0;
NV_ENC_CAPS_PARAM caps{};caps.version=NV_ENC_CAPS_PARAM_VER;caps.capsToQuery=NV_ENC_CAPS_WIDTH_MAX;
@@ -50,27 +53,38 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(maxWidth<=0||maxHeight<=0||p.w>unsigned(maxWidth)||p.h>unsigned(maxHeight)||(p.w&1)||(p.h&1)){
veyra::log::error("nvenc","requested dimensions unsupported by selected codec/NV12 input");return false;
}
+ if(p.hdr){int supported=0;caps.capsToQuery=NV_ENC_CAPS_SUPPORT_10BIT_ENCODE;if(!p.check(p.api.nvEncGetEncodeCaps(p.encoder,codec,&caps,&supported),"10bit support")||!supported)return false;}
NV_ENC_PRESET_CONFIG preset{};preset.version=NV_ENC_PRESET_CONFIG_VER;preset.presetCfg.version=NV_ENC_CONFIG_VER;
if(!p.check(p.api.nvEncGetEncodePresetConfigEx(p.encoder,codec,NV_ENC_PRESET_P4_GUID,NV_ENC_TUNING_INFO_LOW_LATENCY,&preset),"GetPreset"))return false;
preset.presetCfg.frameIntervalP=1;preset.presetCfg.gopLength=120;preset.presetCfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_CONSTQP;
preset.presetCfg.rcParams.constQP={20,22,22};preset.presetCfg.rcParams.enableLookahead=0;
+ if(p.hdr){
+ preset.presetCfg.profileGUID=NV_ENC_HEVC_PROFILE_MAIN10_GUID;
+ auto& config=preset.presetCfg.encodeCodecConfig.hevcConfig;
+ config.inputBitDepth=config.outputBitDepth=NV_ENC_BIT_DEPTH_10;
+ auto& vui=config.hevcVUIParameters;
+ vui.videoSignalTypePresentFlag=1;vui.videoFormat=NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED;vui.videoFullRangeFlag=0;vui.colourDescriptionPresentFlag=1;
+ vui.colourPrimaries=NV_ENC_VUI_COLOR_PRIMARIES_BT2020;
+ vui.transferCharacteristics=NV_ENC_VUI_TRANSFER_CHARACTERISTIC_SMPTE2084;
+ vui.colourMatrix=NV_ENC_VUI_MATRIX_COEFFS_BT2020_NCL;
+ }
NV_ENC_INITIALIZE_PARAMS init{};init.version=NV_ENC_INITIALIZE_PARAMS_VER;init.encodeGUID=codec;init.presetGUID=NV_ENC_PRESET_P4_GUID;init.tuningInfo=NV_ENC_TUNING_INFO_LOW_LATENCY;
init.encodeWidth=p.w;init.encodeHeight=p.h;init.darWidth=p.w;init.darHeight=p.h;init.frameRateNum=fpsNum;init.frameRateDen=fpsDen;init.enablePTD=1;init.encodeConfig=&preset.presetCfg;init.maxEncodeWidth=p.w;init.maxEncodeHeight=p.h;
- init.bufferFormat=NV_ENC_BUFFER_FORMAT_NV12;
+ init.bufferFormat=p.inputFormat;
if(!p.check(p.api.nvEncInitializeEncoder(p.encoder,&init),"InitializeEncoder"))return false;
p.sequence.resize(4096);uint32_t size=0;NV_ENC_SEQUENCE_PARAM_PAYLOAD seq{};seq.version=NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;seq.inBufferSize=4096;seq.spsppsBuffer=p.sequence.data();seq.outSPSPPSPayloadSize=&size;
if(!p.check(p.api.nvEncGetSequenceParams(p.encoder,&seq),"GetSequenceParams"))return false;p.sequence.resize(size);
if(FAILED(ctx.device()->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&p.fence))))return false;p.event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!p.event)return false;
- p.y=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_R8_UNORM,true);p.uv=makeTexture(ctx.device(),p.w/2,p.h/2,DXGI_FORMAT_R8G8_UNORM,true);if(!p.y||!p.uv)return false;
+ p.y=makeTexture(ctx.device(),p.w,p.h,p.hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,true);p.uv=makeTexture(ctx.device(),p.w/2,p.h/2,p.hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,true);if(!p.y||!p.uv)return false;
std::vector<uint8_t> cs;if(!p.convert.loadShader("RgbToNv12.dxil",cs)||!p.convert.create(ctx.device(),cs,10,1,2))return false;
- for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,cpuHandleOf(p.convert,i));
- makeUav(ctx.device(),p.y.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,8));makeUav(ctx.device(),p.uv.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,9));
+ for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(p.convert,i));
+ makeUav(ctx.device(),p.y.Get(),p.hdr?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,cpuHandleOf(p.convert,8));makeUav(ctx.device(),p.uv.Get(),p.hdr?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(p.convert,9));
for(auto& s:p.slots){
- s.input=makeTexture(ctx.device(),p.w,p.h,DXGI_FORMAT_NV12,false);if(!s.input)return false;
+ s.input=makeTexture(ctx.device(),p.w,p.h,p.hdr?DXGI_FORMAT_P010:DXGI_FORMAT_NV12,false);if(!s.input)return false;
D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=(uint64_t(p.w)*p.h*4+4095)&~4095ull;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&s.output))))return false;
- auto reg=[&](ID3D12Resource* resource,bool output,NV_ENC_REGISTERED_PTR& registered,NV_ENC_INPUT_PTR& mapped){NV_ENC_REGISTER_RESOURCE r{};r.version=NV_ENC_REGISTER_RESOURCE_VER;r.resourceType=NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;r.resourceToRegister=resource;r.width=output?static_cast<uint32_t>(bd.Width):p.w;r.height=output?1:p.h;r.bufferFormat=output?NV_ENC_BUFFER_FORMAT_U8:NV_ENC_BUFFER_FORMAT_NV12;r.bufferUsage=output?NV_ENC_OUTPUT_BITSTREAM:NV_ENC_INPUT_IMAGE;
- if(!p.check(p.api.nvEncRegisterResource(p.encoder,&r),output?"RegisterOutput":"RegisterNV12"))return false;registered=r.registeredResource;
+ auto reg=[&](ID3D12Resource* resource,bool output,NV_ENC_REGISTERED_PTR& registered,NV_ENC_INPUT_PTR& mapped){NV_ENC_REGISTER_RESOURCE r{};r.version=NV_ENC_REGISTER_RESOURCE_VER;r.resourceType=NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;r.resourceToRegister=resource;r.width=output?static_cast<uint32_t>(bd.Width):p.w;r.height=output?1:p.h;r.bufferFormat=output?NV_ENC_BUFFER_FORMAT_U8:p.inputFormat;r.bufferUsage=output?NV_ENC_OUTPUT_BITSTREAM:NV_ENC_INPUT_IMAGE;
+ if(!p.check(p.api.nvEncRegisterResource(p.encoder,&r),output?"RegisterOutput":p.hdr?"RegisterP010":"RegisterNV12"))return false;registered=r.registeredResource;
NV_ENC_MAP_INPUT_RESOURCE m{};m.version=NV_ENC_MAP_INPUT_RESOURCE_VER;m.registeredResource=registered;if(!p.check(p.api.nvEncMapInputResource(p.encoder,&m),"MapResource"))return false;mapped=m.mappedResource;return true;};
if(!reg(s.input.Get(),false,s.registeredIn,s.mappedIn)||!reg(s.output.Get(),true,s.registeredOut,s.mappedOut))return false;
s.in.version=NV_ENC_INPUT_RESOURCE_D3D12_VER;s.in.pInputBuffer=s.mappedIn;s.in.inputFencePoint.version=NV_ENC_FENCE_POINT_D3D12_VER;s.in.inputFencePoint.pFence=ctx.fence();s.in.inputFencePoint.bWait=1;
@@ -81,12 +95,12 @@ bool NvencD3D12Encoder::encode(unsigned frameSlot,bool generated,int64_t pts){au
Status st=Status::Ok;uint32_t slot=0;auto* list=p.ring->acquireNext(slot,st);if(!list)return false;
auto* color=generated?p.graph->generatedFrameResource(frameSlot):p.graph->videoFrameResource(frameSlot);
p.states.transition(list,color,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),0,0,0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,8).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
+ const float dims[8]={std::bit_cast<float>(p.w),std::bit_cast<float>(p.h),std::bit_cast<float>(p.hdr?(p.graph->hdr10Output()?2u:1u):0u),0,0,0,0,0};p.convert.bind(list,dims,gpuHandleOf(p.convert,frameSlot+(generated?2:0)).ptr,gpuHandleOf(p.convert,8).ptr);list->Dispatch((p.w+15)/16,(p.h+15)/16,1);
p.states.uavBarrier(list,p.y.Get());p.states.uavBarrier(list,p.uv.Get());p.states.transition(list,p.y.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,p.uv.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COPY_DEST);
for(unsigned plane=0;plane<2;++plane){D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=plane?p.uv.Get():p.y.Get();a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=s.input.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.SubresourceIndex=plane;list->CopyTextureRegion(&b,0,0,0,&a,nullptr);}
p.states.transition(list,s.input.Get(),D3D12_RESOURCE_STATE_COMMON);p.states.transition(list,color,D3D12_RESOURCE_STATE_COMMON);if(!p.ring->submitAndSignal(slot))return false;
s.in.inputFencePoint.waitValue=p.ring->lastSignaledValue();s.value=p.submitted+1;s.out.outputFencePoint.signalValue=s.value;
- NV_ENC_PIC_PARAMS pic{};pic.version=NV_ENC_PIC_PARAMS_VER;pic.inputWidth=p.w;pic.inputHeight=p.h;pic.inputBuffer=&s.in;pic.outputBitstream=&s.out;pic.bufferFmt=NV_ENC_BUFFER_FORMAT_NV12;pic.pictureStruct=NV_ENC_PIC_STRUCT_FRAME;pic.inputTimeStamp=pts;pic.inputDuration=1;
+ NV_ENC_PIC_PARAMS pic{};pic.version=NV_ENC_PIC_PARAMS_VER;pic.inputWidth=p.w;pic.inputHeight=p.h;pic.inputBuffer=&s.in;pic.outputBitstream=&s.out;pic.bufferFmt=p.inputFormat;pic.pictureStruct=NV_ENC_PIC_STRUCT_FRAME;pic.inputTimeStamp=pts;pic.inputDuration=1;
if(!p.check(p.api.nvEncEncodePicture(p.encoder,&pic),"EncodePicture"))return false;s.pending=true;++p.submitted;return true;
}
bool NvencD3D12Encoder::finish(){auto& p=*p_;while(p.completed<p.submitted){if(!p.drain(p.slots[p.completed%4]))return false;}return true;}
diff --git a/src/sink/WasapiAudioSink.cpp b/src/sink/WasapiAudioSink.cpp
index 3ee40114..933b906e 100644
--- a/src/sink/WasapiAudioSink.cpp
+++ b/src/sink/WasapiAudioSink.cpp
@@ -45,6 +45,13 @@ bool AudioPipeline::open(const std::wstring& path)
if (avcodec_parameters_to_context(codecCtx_, fmt_->streams[si]->codecpar) < 0) return false;
if (avcodec_open2(codecCtx_, codec, nullptr) < 0) return false;
stream_ = fmt_->streams[si];
+ const auto& layout=codecCtx_->ch_layout;
+ if(layout.order==AV_CHANNEL_ORDER_NATIVE&&layout.u.mask<=UINT32_MAX)pcmFormat_={unsigned(layout.nb_channels),uint32_t(layout.u.mask)};
+ else if(layout.nb_channels==1)pcmFormat_={1,SPEAKER_FRONT_CENTER};
+ else if(layout.nb_channels==2)pcmFormat_={};
+ else {log::error("audio","Unsupported or unspecified multichannel speaker layout");return false;}
+ if(!pcmFormat_.valid())return false;
+ log::info("audio-format",std::format("file input channels={} mask=0x{:X}; preserve to renderer",pcmFormat_.channels,pcmFormat_.mask));
veyra::log::info("audio", std::format("audio stream idx={} codec={} rate={}",
si, codec->name, codecCtx_->sample_rate));
return true;
@@ -86,9 +93,9 @@ size_t AudioPipeline::pull(float* dst, size_t maxFrames, double* firstPtsMs)
while (copied < take && !segments_.empty()) {
Segment& seg = segments_.front();
const size_t n = std::min(take - copied, seg.frames);
- // Ring is a deque of float pairs: copy n frames.
- for (size_t i = 0; i < n * 2; ++i) {
- dst[copied * 2 + i] = ring_.front();
+ // Copy n interleaved frames, retaining every source channel.
+ for (size_t i = 0; i < n * pcmFormat_.channels; ++i) {
+ dst[copied * pcmFormat_.channels + i] = ring_.front();
ring_.pop_front();
}
copied += n;
@@ -124,11 +131,23 @@ double AudioPipeline::requestSeek(double targetMs)
void AudioPipeline::pushDecoded(const AVFrame* frame)
{
- // Convert to 48k stereo float in converted_.
+ // Fail closed on an unannounced format change instead of reusing an old
+ // channel stride/rate and reading the wrong planes. Seek clears swr_.
+ const auto& layout=frame->ch_layout;
+ const bool layoutMatches=layout.nb_channels==int(pcmFormat_.channels)&&
+ ((layout.order==AV_CHANNEL_ORDER_NATIVE&&layout.u.mask==pcmFormat_.mask)||
+ (layout.order==AV_CHANNEL_ORDER_UNSPEC&&layout.nb_channels<=2));
+ if(!layoutMatches||frame->sample_rate<=0||
+ (swr_&&(frame->sample_rate!=swrInputRate_||frame->format!=swrInputFormat_))){
+ log::error("audio-format","Decoded audio layout/rate/format changed; reopen source required");
+ stopFlag_=true;return;
+ }
+ // Convert to 48 kHz float in converted_, preserving the speaker layout.
if (swr_ == nullptr) {
- AVChannelLayout outLayout = AV_CHANNEL_LAYOUT_STEREO;
- AVChannelLayout inLayout = frame->ch_layout.nb_channels > 0
+ AVChannelLayout outLayout{};av_channel_layout_from_mask(&outLayout,pcmFormat_.mask);
+ AVChannelLayout inLayout = frame->ch_layout.order == AV_CHANNEL_ORDER_NATIVE
? frame->ch_layout : outLayout;
+ swrInputRate_=frame->sample_rate;swrInputFormat_=frame->format;
const int result = swr_alloc_set_opts2(&swr_,
&outLayout, AV_SAMPLE_FMT_FLT, kAudioRate,
&inLayout, static_cast<AVSampleFormat>(frame->format), frame->sample_rate,
@@ -151,10 +170,10 @@ void AudioPipeline::pushDecoded(const AVFrame* frame)
log::error("audio", "decoded audio block exceeds bounded conversion capacity");
return;
}
- converted_.resize(static_cast<size_t>(capacity) * 2);
+ converted_.resize(static_cast<size_t>(capacity) * pcmFormat_.channels);
uint8_t* planes[1] = { reinterpret_cast<uint8_t*>(converted_.data()) };
const int outSamples = swr_convert(swr_, planes,
- static_cast<int>(converted_.size() / 2),
+ static_cast<int>(converted_.size() / pcmFormat_.channels),
const_cast<const uint8_t**>(frame->extended_data), frame->nb_samples);
if (outSamples < 0) { log::error("audio", std::format("swr_convert failed code={}", outSamples)); return; }
pushConverted(outSamples);
@@ -203,7 +222,7 @@ void AudioPipeline::pushConverted(int frames)
veyra::log::error("audio", "ring overflow despite watermarks (bug)");
return;
}
- ring_.insert(ring_.end(), converted_.data() + skip * 2, converted_.data() + static_cast<size_t>(frames) * 2);
+ ring_.insert(ring_.end(), converted_.data() + skip * pcmFormat_.channels, converted_.data() + static_cast<size_t>(frames) * pcmFormat_.channels);
ringFrames_ += addFrames;
if (!segments_.empty()) {
Segment& last = segments_.back();
@@ -235,7 +254,7 @@ void AudioPipeline::decodeBlock()
if (received == AVERROR_EOF) {
if (swr_) {
uint8_t* planes[] = {reinterpret_cast<uint8_t*>(converted_.data())};
- const int count = swr_convert(swr_, planes, static_cast<int>(converted_.size() / 2), nullptr, 0);
+ const int count = swr_convert(swr_, planes, static_cast<int>(converted_.size() / pcmFormat_.channels), nullptr, 0);
if (count > 0) { pushConverted(count); continue; }
if (count < 0) log::error("audio", std::format("resampler drain failed code={}", count));
}
@@ -287,11 +306,22 @@ void AudioPipeline::closeAll()
if (fmt_ != nullptr) avformat_close_input(&fmt_);
}
-bool AudioRenderer::start()
+bool AudioRenderer::copyPcm(BYTE* destination,const float* input,size_t frames){
+ if(!channelMix_){std::memcpy(destination,input,frames*outputFormat_.channels*sizeof(float));return true;}
+ mixed_.resize(frames*outputFormat_.channels);
+ uint8_t* out[]={reinterpret_cast<uint8_t*>(mixed_.data())};const uint8_t* in[]={reinterpret_cast<const uint8_t*>(input)};
+ const int converted=swr_convert(channelMix_,out,int(frames),in,int(frames));
+ if(converted!=int(frames))return checked(E_FAIL,"Channel mapping unexpectedly changed frame count");
+ std::memcpy(destination,mixed_.data(),frames*outputFormat_.channels*sizeof(float));return true;
+}
+
+bool AudioRenderer::start(AudioFormat input)
{
std::lock_guard endpointLock(endpointMutex_);
if(client_||enum_)return checked(E_UNEXPECTED,"Endpoint already initialized");
lastError_=S_OK;bufferedMs_=0;smoothedGain_=0;
+ if(!input.valid())return checked(E_INVALIDARG,"Invalid input channel layout");
+ inputFormat_=input;lastRaw_.assign(input.channels,0);
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
comInited_ = SUCCEEDED(hr);
if(FAILED(hr)&&hr!=RPC_E_CHANGED_MODE)return checked(hr,"Initialize COM");
@@ -303,17 +333,25 @@ bool AudioRenderer::start()
hr = device_->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr,
reinterpret_cast<void**>(&client_));
if (!checked(hr,"Activate AudioClient")) return false;
- WAVEFORMATEX mix{};
- mix.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
- mix.nChannels = 2;
- mix.nSamplesPerSec = kAudioRate;
- mix.wBitsPerSample = 32;
- mix.nBlockAlign = 8;
- mix.nAvgBytesPerSec = mix.nSamplesPerSec * mix.nBlockAlign;
+ WAVEFORMATEX* deviceMix=nullptr;
+ if(!checked(client_->GetMixFormat(&deviceMix),"GetMixFormat"))return false;
+ WavePcmFormat deviceFormat;const bool known=parseWavePcm(deviceMix,sizeof(WAVEFORMATEX)+deviceMix->cbSize,deviceFormat);
+ outputFormat_=input;
+ if(!known||(deviceFormat.layout.mask&input.mask)!=input.mask)
+ outputFormat_=known?deviceFormat.layout:AudioFormat{};
+ CoTaskMemFree(deviceMix);
+ auto mix=floatWave(outputFormat_);
+ if(outputFormat_!=inputFormat_){
+ AVChannelLayout from{},to{};av_channel_layout_from_mask(&from,inputFormat_.mask);av_channel_layout_from_mask(&to,outputFormat_.mask);
+ const int result=swr_alloc_set_opts2(&channelMix_,&to,AV_SAMPLE_FMT_FLT,kAudioRate,&from,AV_SAMPLE_FMT_FLT,kAudioRate,0,nullptr);
+ av_channel_layout_uninit(&from);av_channel_layout_uninit(&to);
+ if(result<0||!channelMix_||swr_init(channelMix_)<0)return checked(E_FAIL,"Configure endpoint channel mapping");
+ }
+ log::info("audio-format",std::format("input={} mask=0x{:X} output={} mask=0x{:X} downmix={} deviceLayoutKnown={}",input.channels,input.mask,outputFormat_.channels,outputFormat_.mask,outputFormat_.channels<input.channels,known));
sampleRate_ = kAudioRate;
hr = client_->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
- 10 * 10000, 0, &mix, nullptr);
+ 10 * 10000, 0, &mix.Format, nullptr);
const bool initOk = checked(hr,"Initialize AudioClient");
if (!initOk) return false;
if (!checked(client_->GetBufferSize(&bufferFrames_),"GetBufferSize")) return false;
@@ -376,7 +414,8 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs
const auto consumed=static_cast<uint64_t>(std::ceil(double(pos-anchorPos_)*sampleRate_/clockFrequency_));
timelineWriteFrame_=std::max(timelineWriteFrame_.load(),consumed);
}
- chunk_.resize(static_cast<size_t>(avail) * 2);
+ if(pipeline.pcmFormat()!=inputFormat_)return checked(E_INVALIDARG,"PCM source channel layout changed without reset");
+ chunk_.resize(static_cast<size_t>(avail) * inputFormat_.channels);
BYTE* dest = nullptr;
if (!checked(render_->GetBuffer(avail, &dest),"GetBuffer")) return false;
double firstPts = -1.0;
@@ -386,21 +425,21 @@ bool AudioRenderer::pumpOnce(AudioPcmSource& pipeline, double* firstWrittenPtsMs
if (!started_ && !got) return checked(render_->ReleaseBuffer(0, 0),"Release empty prefill");
const UINT32 written=started_&&pipeline.padUnderruns()?avail:static_cast<UINT32>(got);
if (got > 0) {
- lastRawLeft_=chunk_[(got-1)*2];lastRawRight_=chunk_[(got-1)*2+1];
+ for(unsigned c=0;c<inputFormat_.channels;++c)lastRaw_[c]=chunk_[(got-1)*inputFormat_.channels+c];
const float target=std::clamp(gain_.load(),0.0f,1.0f);
- applyStereoGain(chunk_.data(),got,target,smoothedGain_);
+ applyPcmGain(chunk_.data(),got,inputFormat_.channels,target,smoothedGain_);
if(target!=loggedGain_&&std::abs(smoothedGain_-target)<.00001f){loggedGain_=target;log::info("audio-gain",std::format("target={} reached={} framesWritten={} clockPreserved=true applicationPCM=true",target,smoothedGain_,framesWritten_.load()));}
- std::memcpy(dest, chunk_.data(), got * 8);
+ if(!copyPcm(dest,chunk_.data(),got)){render_->ReleaseBuffer(0,0);return false;}
if (got < written) {
- std::memset(dest + got * 8, 0, (written - got) * 8);
+ std::memset(dest + got * outputFormat_.channels*4, 0, (written - got) * outputFormat_.channels*4);
underruns_.fetch_add(1);
}
} else {
- std::memset(dest, 0, static_cast<size_t>(avail) * 8);
+ std::memset(dest, 0, static_cast<size_t>(avail) * outputFormat_.channels*4);
underruns_.fetch_add(1);
}
if (!checked(render_->ReleaseBuffer(written, 0),"ReleaseBuffer")) return false;
- if(written>got)lastRawLeft_=lastRawRight_=0;
+ if(written>got)std::fill(lastRaw_.begin(),lastRaw_.end(),0);
{
std::lock_guard lock(timelineMutex_);
if(got&&endPts){timedPcm_=true;outputTimeline_.append(timelineWriteFrame_,got,firstPts,*endPts);}
@@ -439,7 +478,7 @@ void AudioRenderer::stopAndReset()
timelineWriteFrame_=0;
bufferedMs_=0;smoothedGain_=0;
{std::lock_guard lock(timelineMutex_);outputTimeline_.clear();timedPcm_=false;}
- fading_=false;pausedEndpoint_=false;lastRawLeft_=lastRawRight_=0;
+ fading_=false;pausedEndpoint_=false;std::fill(lastRaw_.begin(),lastRaw_.end(),0);
}
AudioFadeResult AudioRenderer::fadeAndReset(AudioPcmSource& source,const std::atomic<bool>& cancel)
@@ -450,7 +489,7 @@ AudioFadeResult AudioRenderer::fadeAndReset(AudioPcmSource& source,const std::at
fading_=true;
const auto begin=std::chrono::steady_clock::now();
constexpr UINT32 frames=kAudioRate/200;
- std::array<float,frames*2> tail{};
+ std::vector<float> tail(size_t(frames)*inputFormat_.channels);
bool submitted=false;AudioFadeResult result=AudioFadeResult::TimedOut;
while(std::chrono::steady_clock::now()-begin<std::chrono::milliseconds(80)){
if(cancel){result=AudioFadeResult::Cancelled;break;}
@@ -462,13 +501,12 @@ AudioFadeResult AudioRenderer::fadeAndReset(AudioPcmSource& source,const std::at
BYTE* dest=nullptr;
if(!checked(render_->GetBuffer(frames,&dest),"Fade GetBuffer")){result=AudioFadeResult::Failed;break;}
double pts=-1;const size_t got=source.pull(tail.data(),frames,&pts);
- const float left=got?tail[(got-1)*2]:(padding?lastRawLeft_:0),right=got?tail[(got-1)*2+1]:(padding?lastRawRight_:0);
- for(size_t i=got;i<frames;++i){tail[i*2]=left;tail[i*2+1]=right;}
- fadeStereoTail(tail.data(),frames,smoothedGain_);
- std::memcpy(dest,tail.data(),sizeof(tail));
+ for(unsigned c=0;c<inputFormat_.channels;++c){const float last=got?tail[(got-1)*inputFormat_.channels+c]:(padding?lastRaw_[c]:0);for(size_t i=got;i<frames;++i)tail[i*inputFormat_.channels+c]=last;}
+ fadePcmTail(tail.data(),frames,inputFormat_.channels,smoothedGain_);
+ if(!copyPcm(dest,tail.data(),frames)){render_->ReleaseBuffer(0,0);result=AudioFadeResult::Failed;break;}
if(!checked(render_->ReleaseBuffer(frames,0),"Fade ReleaseBuffer")){result=AudioFadeResult::Failed;break;}
submitted=true;framesWritten_+=frames;
- log::info("audio-fade",std::format("submitted frames={} realPcm={} finalLeft={} finalRight={}",frames,got,tail[frames*2-2],tail[frames*2-1]));
+ log::info("audio-fade",std::format("submitted frames={} realPcm={} finalLeft={} finalRight={}",frames,got,tail[tail.size()-inputFormat_.channels],tail.back()));
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
@@ -486,6 +524,7 @@ void AudioRenderer::shutdown()
if (client_) { (void)client_->Stop(); (void)client_->Reset(); }
#define REL(x) if (x) { x->Release(); x = nullptr; }
REL(clock_); REL(render_); REL(client_); REL(device_); REL(enum_);
+ swr_free(&channelMix_);
#undef REL
if (event_ != nullptr) { CloseHandle(event_); event_ = nullptr; }
running_ = false;
@@ -507,7 +546,7 @@ void AudioRenderer::setPaused(bool value)
void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
{
const auto t0 = std::chrono::steady_clock::now();
- bool endpointReady = renderer && (!ownEndpoint || renderer->start());
+ bool endpointReady = renderer && (!ownEndpoint || renderer->start(pcmFormat_));
double lastClockMs = 0, recoveryTargetMs = 0;
auto retryAt = t0;
// Steady-state under-rate must never stop sound: the audio device clock is
@@ -627,7 +666,7 @@ void AudioPipeline::runOnAudioThread(AudioRenderer* renderer, bool ownEndpoint)
if(renderer&&ownEndpoint&&!endpointReady){
if(clockExhausted_){endpointRecovering_=false;}
else if(std::chrono::steady_clock::now()>=retryAt){
- if(renderer->start()){
+ if(renderer->start(pcmFormat_)){
endpointReady=true;
const bool rewound=rewind(recoveryTargetMs);
pauseApplied=shouldPause();
diff --git a/src/source/CaptureCardSource.cpp b/src/source/CaptureCardSource.cpp
index 75e59d0a..8ad64bec 100644
--- a/src/source/CaptureCardSource.cpp
+++ b/src/source/CaptureCardSource.cpp
@@ -4,6 +4,7 @@
#include "veyra/source/NativeCaptureSink.h"
#include "veyra/pipeline/ColorMetadata.h"
#include "veyra/Log.h"
+#include "veyra/sink/AudioFormat.h"
#include <windows.h>
#include <dshow.h>
#include <dvdmedia.h>
@@ -137,20 +138,41 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
}
freeType(native);const bool layoutValid=SUCCEEDED(hr)&&captureMediaLayout(connected,p.layout);freeType(&connected,false);
if(!layoutValid){log::error("capture",std::format("unsupported negotiated layout/connect failure hr=0x{:08X}",uint32_t(hr)));return false;}
+ unsigned colorOverride=0;swscanf_s(desc.path.c_str(),L"capture:%u:%d:%d:%u",&index,&format,&audio,&colorOverride);
+ if(colorOverride>2)return false;
+ if(colorOverride){
+ if(p.layout.format!=AV_PIX_FMT_P010&&p.layout.format!=AV_PIX_FMT_P016){log::error("capture-color","Explicit HDR requires P010/P016; select a 10/16-bit capture format");return false;}
+ p.layout.color.transfer=colorOverride==1?pipeline::TransferFunction::PQ:pipeline::TransferFunction::HLG;
+ p.layout.color.matrix=pipeline::YuvMatrix::BT2020NCL;p.layout.color.primaries=pipeline::ColorPrimaries::BT2020;
+ p.layout.color.transferAssumed=p.layout.color.matrixAssumed=p.layout.color.primariesAssumed=false;
+ log::info("capture-color",std::format("manual override={} BT2020; range retains negotiated metadata",colorOverride==1?"PQ":"HLG"));
+ }
p.info={};p.info.kind=pipeline::SourceKind::CaptureCard;p.info.width=p.layout.width;p.info.height=p.layout.height;p.info.averageFps=p.layout.duration>0?1e7/p.layout.duration:0;p.info.duration=pipeline::Rational::unknown();p.info.color=p.layout.color;
p.nominalDuration100ns=p.layout.duration;
- log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (SDR display-referred)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));
+ log::info("capture-color",std::format("format={} stride={} rowBytes={} bytes={} bottomUp={} matrix={} assumed={} range={} assumed={} workingTransfer={} assumed={} (explicit transfer contract)",int(p.layout.format),p.layout.stride,p.layout.rowBytes,p.layout.sampleBytes,p.layout.bottomUp,int(p.info.color.matrix),p.info.color.matrixAssumed,int(p.info.color.range),p.info.color.rangeAssumed,int(p.info.color.transfer),p.info.color.transferAssumed));
if(audio>=0){
const bool connected=[&]{
if(!bind(unsigned(audio),true,p.audioFilter)||FAILED(p.graph->AddFilter(p.audioFilter.Get(),L"Capture audio")))return false;
ComPtr<IPin> audioPin;
if(FAILED(p.builder->FindPin(p.audioFilter.Get(),PINDIR_OUTPUT,&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Audio,FALSE,0,&audioPin)))return false;
ComPtr<IEnumMediaTypes> types;if(FAILED(audioPin->EnumMediaTypes(&types)))return false;
+ // Preserve the device's actual speaker layout. Enumeration order is
+ // commonly stereo first even when native 5.1 is available.
+ auto releaseType=[](AM_MEDIA_TYPE* type){freeType(type);};
+ using AudioType=std::unique_ptr<AM_MEDIA_TYPE,decltype(releaseType)>;
+ std::vector<AudioType> audioTypes;
+ for(;;){AM_MEDIA_TYPE* type=nullptr;if(types->Next(1,&type,nullptr)!=S_OK)break;
+ AudioType owned(type,releaseType);sink::WavePcmFormat pcm;
+ if(type->formattype==FORMAT_WaveFormatEx&&sink::parseWavePcm(type->pbFormat,type->cbFormat,pcm))audioTypes.push_back(std::move(owned));
+ }
+ std::stable_sort(audioTypes.begin(),audioTypes.end(),[](const auto& a,const auto& b){
+ return reinterpret_cast<const WAVEFORMATEX*>(a->pbFormat)->nChannels>reinterpret_cast<const WAVEFORMATEX*>(b->pbFormat)->nChannels;
+ });
bool connectedAudio=false;
- for(;;){
- AM_MEDIA_TYPE* type=nullptr;if(types->Next(1,&type,nullptr)!=S_OK)break;
+ for(const auto& owned:audioTypes){
+ auto* type=owned.get();
auto session=std::make_unique<sink::CaptureAudioSession>();ComPtr<IBaseFilter> candidate;ComPtr<IPin> terminal;
- if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)&&session->configure(*reinterpret_cast<WAVEFORMATEX*>(type->pbFormat))){
+ if(type->formattype==FORMAT_WaveFormatEx&&type->pbFormat&&type->cbFormat>=sizeof(WAVEFORMATEX)&&session->configure(*reinterpret_cast<WAVEFORMATEX*>(type->pbFormat),type->cbFormat)){
auto* target=session.get();
hr=createNativeAudioSink(*type,[target](IMediaSample* sample){
BYTE* bytes=nullptr;REFERENCE_TIME begin=0,end=0;
@@ -167,7 +189,7 @@ bool CaptureCardSource::configure(const SourceOpenDesc& desc){close();p_->lastAu
else if(candidate)p.graph->RemoveFilter(candidate.Get());
log::info("capture-audio",std::format("PCM ConnectDirect hr=0x{:X}",unsigned(hr)));
}
- freeType(type);if(connectedAudio)break;
+ if(connectedAudio)break;
}
return connectedAudio;
}();
diff --git a/src/source/NativeCaptureSink.cpp b/src/source/NativeCaptureSink.cpp
index af105507..6b753116 100644
--- a/src/source/NativeCaptureSink.cpp
+++ b/src/source/NativeCaptureSink.cpp
@@ -1,6 +1,7 @@
#include "veyra/source/NativeCaptureSink.h"
#include "veyra/source/CaptureMediaType.h"
#include "veyra/Log.h"
+#include "veyra/sink/AudioFormat.h"
#include <format>
#include <mmreg.h>
#include <atomic>
@@ -22,16 +23,11 @@ HRESULT copyType(AM_MEDIA_TYPE& dst,const AM_MEDIA_TYPE& src){
}
bool audioType(const AM_MEDIA_TYPE& t){
if(t.majortype!=MEDIATYPE_Audio||t.formattype!=FORMAT_WaveFormatEx||!t.pbFormat||t.cbFormat<sizeof(WAVEFORMATEX))return false;
- const auto& f=*reinterpret_cast<const WAVEFORMATEX*>(t.pbFormat);
- return (f.wFormatTag==WAVE_FORMAT_PCM||f.wFormatTag==WAVE_FORMAT_IEEE_FLOAT)&&
- f.nChannels>=1&&f.nChannels<=2&&f.nSamplesPerSec>=8000&&f.nSamplesPerSec<=192000&&
- (f.wBitsPerSample==16||f.wBitsPerSample==32)&&
- (f.wFormatTag!=WAVE_FORMAT_IEEE_FLOAT||f.wBitsPerSample==32)&&
- f.nBlockAlign==f.nChannels*f.wBitsPerSample/8&&f.nAvgBytesPerSec==f.nSamplesPerSec*f.nBlockAlign;
+ sink::WavePcmFormat parsed;return sink::parseWavePcm(t.pbFormat,t.cbFormat,parsed);
}
bool sameAudio(const AM_MEDIA_TYPE& a,const AM_MEDIA_TYPE& b){
return audioType(a)&&audioType(b)&&a.subtype==b.subtype&&
- std::memcmp(a.pbFormat,b.pbFormat,sizeof(WAVEFORMATEX))==0;
+ a.cbFormat==b.cbFormat&&std::memcmp(a.pbFormat,b.pbFormat,a.cbFormat)==0;
}
class PinEnum final:public IEnumPins {
std::atomic<ULONG> refs_{1};ComPtr<IPin> pin_;bool used_=false;
@@ -147,7 +143,9 @@ public:
}
HRESULT suggestCaptureAudioBuffering(IPin* pin,const WAVEFORMATEX& format){
if(!pin)return E_POINTER;
- if(!format.nBlockAlign||format.nSamplesPerSec<8000||format.nSamplesPerSec>192000||format.nBlockAlign>8||
+ if(!format.nBlockAlign||format.nSamplesPerSec<8000||format.nSamplesPerSec>192000||format.nChannels<1||format.nChannels>8||
+ (format.wBitsPerSample!=16&&format.wBitsPerSample!=24&&format.wBitsPerSample!=32)||
+ format.nBlockAlign!=format.nChannels*(format.wBitsPerSample/8)||
format.nAvgBytesPerSec!=uint64_t(format.nSamplesPerSec)*format.nBlockAlign)return E_INVALIDARG;
ComPtr<IAMBufferNegotiation> negotiation;
const auto queryHr=pin->QueryInterface(IID_PPV_ARGS(&negotiation));
diff --git a/tests/integration/AudioTimelineTests.cpp b/tests/integration/AudioTimelineTests.cpp
index 567f7c53..2544d896 100644
--- a/tests/integration/AudioTimelineTests.cpp
+++ b/tests/integration/AudioTimelineTests.cpp
@@ -36,7 +36,7 @@ void decode(const std::filesystem::path& file) {
check(until([&] { return pipe.decodingComplete(); }), "decoder and resampler fully drained");
check(std::abs(pipe.headPtsMs()) < 0.05, "first PCM timestamp is block start at zero");
check(std::abs(pipe.tailPtsMs()-750) < 0.05, "resampled tail preserves 750ms duration");
- size_t total=0; double pts=0, maxError=0; std::vector<float> block(2*137);
+ size_t total=0; double pts=0, maxError=0; std::vector<float> block(pipe.pcmFormat().channels*137);
while (auto n=pipe.pull(block.data(),137,&pts)) {
maxError=std::max(maxError,std::abs(pts-1000.0*total/kAudioRate)); total+=n;
}
@@ -119,9 +119,9 @@ int wmain(int argc, wchar_t** argv) {
for(uint32_t rate:{48000u,44100u}) { const auto file=dir/(std::to_string(rate)+".wav"); fixture(file,rate); decode(file); }
AudioRenderer renderer;
check(!std::isfinite(renderer.mediaTimeMs()), "unstarted clock is invalid");
- if (!renderer.start()) { check(false,"WASAPI endpoint initialization"); renderer.shutdown(); return 1; }
- renderer.setGain(0);
AudioPipeline pipe; check(pipe.open((dir/"48000.wav").wstring()),"open renderer fixture");
+ if (!renderer.start(pipe.pcmFormat())) { check(false,"WASAPI endpoint initialization"); renderer.shutdown(); return 1; }
+ renderer.setGain(0);
pipe.startThread(&renderer);
check(until([&]{return renderer.started();}),"WASAPI prefilled and started");
check(renderer.framesWritten()>0 && std::isfinite(renderer.mediaTimeMs()),"valid clock only after actual PCM submission");
diff --git a/tests/integration/CaptureAudioTests.cpp b/tests/integration/CaptureAudioTests.cpp
index 6a93f087..4ccbafe6 100644
--- a/tests/integration/CaptureAudioTests.cpp
+++ b/tests/integration/CaptureAudioTests.cpp
@@ -1,4 +1,5 @@
#include "veyra/sink/CaptureAudioSession.h"
+#include "veyra/sink/AudioFormat.h"
#include <chrono>
#include <thread>
#include <iostream>
@@ -19,14 +20,16 @@ int main(int argc,char** argv){
else std::this_thread::sleep_until(due);
}
} pacer;
- const bool endpointTest=argc==2&&std::string_view(argv[1])=="--endpoint-loss";
- const bool jitterTest=argc==2&&std::string_view(argv[1])=="--jitter";
- const bool fastDrift=argc==2&&std::string_view(argv[1])=="--drift-fast";
- const bool driftTest=fastDrift||(argc==2&&std::string_view(argv[1])=="--drift-slow");
+ const bool endpointTest=argc>=2&&std::string_view(argv[1])=="--endpoint-loss";
+ const bool jitterTest=argc>=2&&std::string_view(argv[1])=="--jitter";
+ const bool fastDrift=argc>=2&&std::string_view(argv[1])=="--drift-fast";
+ const bool driftTest=fastDrift||(argc>=2&&std::string_view(argv[1])=="--drift-slow");
if(endpointTest)SetEnvironmentVariableW(L"VEYRA_TEST_CAPTURE_AUDIO_ENDPOINT_LOSS",L"1");
+ const bool multichannel=argc>=3&&std::string_view(argv[2])=="--5.1";
CaptureAudioSession audio;WAVEFORMATEX f{};f.wFormatTag=WAVE_FORMAT_PCM;f.nChannels=2;f.nSamplesPerSec=48000;f.wBitsPerSample=16;f.nBlockAlign=4;f.nAvgBytesPerSec=192000;
- if(!audio.configure(f)||!audio.start())return 2;audio.setGain(0);
- std::vector<int16_t> pcm(960,0);const auto start=Clock::now();
+ auto extended=floatWave({6,0x60f});extended.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;extended.Format.wBitsPerSample=16;extended.Samples.wValidBitsPerSample=16;extended.Format.nBlockAlign=12;extended.Format.nAvgBytesPerSec=576000;
+ if(!(multichannel?audio.configure(extended.Format,sizeof(extended)):audio.configure(f))||!audio.start())return 2;audio.setGain(0);
+ std::vector<int16_t> pcm(480*(multichannel?6:2),0);const auto start=Clock::now();
if(jitterTest){
uint64_t settledResets=0,settledUnderruns=0;unsigned missing=0;std::vector<double> errors;
for(unsigned i=0;i<500;++i){
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
index 74baefce..7398ab65 100644
--- a/tests/integration/HdrColorTests.cpp
+++ b/tests/integration/HdrColorTests.cpp
@@ -19,18 +19,18 @@ int wmain(int argc,wchar_t** argv){
gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
int failures=captureGpuCases(ctx,ring);
- for(bool native:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
+ for(bool hlg:{false,true})for(bool native:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=32;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.hdrInput=true;gd.hdrOutput=native;
if(!graph.initialize(gd)||!graph.createViews())return 3;
- AVFrame* f=av_frame_alloc();f->width=64;f->height=32;f->format=planar?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_P010;f->color_range=full?AVCOL_RANGE_JPEG:AVCOL_RANGE_MPEG;f->colorspace=AVCOL_SPC_BT2020_NCL;f->color_trc=AVCOL_TRC_SMPTE2084;f->color_primaries=AVCOL_PRI_BT2020;
+ AVFrame* f=av_frame_alloc();f->width=64;f->height=32;f->format=planar?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_P010;f->color_range=full?AVCOL_RANGE_JPEG:AVCOL_RANGE_MPEG;f->colorspace=AVCOL_SPC_BT2020_NCL;f->color_trc=hlg?AVCOL_TRC_ARIB_STD_B67:AVCOL_TRC_SMPTE2084;f->color_primaries=AVCOL_PRI_BT2020;
if(av_frame_get_buffer(f,32)<0)return 4;
// Published ST2084 reference encodings: black, 100 cd/m2, 1000 cd/m2.
- constexpr double encoded[]={0,.5080784215,.7518270962};constexpr double nits[]={0,100,1000};
+ const double encoded[]={0,hlg?.75:.5080784215,hlg?1.0:.7518270962};const double nits[]={0,hlg?203.152:100,1000};
for(unsigned y=0;y<32;++y)for(unsigned x=0;x<64;++x){auto code=uint16_t(std::lround((full?0:64)+encoded[std::min(x/22,2u)]*(full?1023:876)));reinterpret_cast<uint16_t*>(f->data[0]+y*f->linesize[0])[x]=planar?code:uint16_t(code<<6);}
for(unsigned y=0;y<16;++y)for(unsigned x=0;x<(planar?32u:64u);++x)reinterpret_cast<uint16_t*>(f->data[1]+y*f->linesize[1])[x]=planar?512:32768;
if(planar)for(unsigned y=0;y<16;++y)for(unsigned x=0;x<32;++x)reinterpret_cast<uint16_t*>(f->data[2]+y*f->linesize[2])[x]=512;
- pipeline::ColorDescription color;color.pixelFormat=pipeline::SourcePixelFormat::P010;color.transfer=pipeline::TransferFunction::PQ;color.matrix=pipeline::YuvMatrix::BT2020NCL;
+ pipeline::ColorDescription color;color.pixelFormat=pipeline::SourcePixelFormat::P010;color.transfer=hlg?pipeline::TransferFunction::HLG:pipeline::TransferFunction::PQ;color.matrix=pipeline::YuvMatrix::BT2020NCL;
pipeline::EnhanceGraph::FrameOutputs out;bool ok=graph.process(f,0,true,out,1,&color);double error=0;
if(ok&&!native){sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);if(ok){for(unsigned i=0;i<3;++i){double l=nits[i]/203.0,p=1000.0/203.0,m=std::clamp(l*(1+l/(p*p))/(1+l),0.0,1.0);double expected=m<=.0031308?12.92*m:1.055*pow(m,1/2.4)-.055;double actual=image.pixels[(i*22+5)*4]/255.0;error=std::max(error,std::abs(expected-actual));}ok=error<.012;}}
if(ok&&native){
@@ -48,7 +48,7 @@ int wmain(int argc,wchar_t** argv){
engine::VideoPresenter presenter;ok=window&&presenter.open(ctx,window,graph)&&presenter.present(ctx,ring,graph,out.videoSlot,false);
ring.drainQueue();presenter.close();if(window)DestroyWindow(window);
}
- std::cout<<"HDR_COLOR native="<<native<<" planar="<<planar<<" full="<<full<<" error="<<error<<" pass="<<ok<<std::endl;if(!ok)++failures;
+ std::cout<<"HDR_COLOR hlg="<<hlg<<" native="<<native<<" planar="<<planar<<" full="<<full<<" error="<<error<<" pass="<<ok<<std::endl;if(!ok)++failures;
out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
}
if(argc>1)for(unsigned mode=0;mode<3;++mode)for(bool hardware:{false,true}){
diff --git a/tests/integration/HdrEnhancementTests.cpp b/tests/integration/HdrEnhancementTests.cpp
index 34dda575..d69ac1fe 100644
--- a/tests/integration/HdrEnhancementTests.cpp
+++ b/tests/integration/HdrEnhancementTests.cpp
@@ -4,11 +4,15 @@
#include "veyra/gfx/CommandSlotRing.h"
#include "veyra/engine/VideoPresenter.h"
#include "veyra/RuntimePaths.h"
+#include "veyra/sink/ImageExportSink.h"
+#include "veyra/source/MediaFileSource.h"
+#include <filesystem>
#include <DirectXPackedVector.h>
#include <iostream>
#include <bit>
#include <cmath>
#include <array>
+#include <wincodec.h>
using namespace veyra;
using namespace veyra::pipeline;
// Readback is confined to this test; production HDR remains GPU-resident.
@@ -34,6 +38,21 @@ static bool read(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,ID3D12R
}
D3D12_RANGE none{};buffer->Unmap(0,&none);return true;
}
+// Independent comparison against GPU readback; encoder self-roundtrip alone
+// would miss a half-width copy or a wrong pre-encode transfer conversion.
+static bool verifyJxr(const std::filesystem::path& path,const std::vector<float>& expected,unsigned width,unsigned height,bool encoded2020){
+ ComPtr<IWICImagingFactory> factory;ComPtr<IWICBitmapDecoder> decoder;ComPtr<IWICBitmapFrameDecode> frame;
+ if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory)))||FAILED(factory->CreateDecoderFromFilename(path.c_str(),nullptr,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&decoder))||FAILED(decoder->GetFrame(0,&frame)))return false;
+ WICPixelFormatGUID format;UINT w=0,h=0;
+ if(FAILED(frame->GetPixelFormat(&format))||format!=GUID_WICPixelFormat64bppRGBAHalf||FAILED(frame->GetSize(&w,&h))||w!=width||h!=height)return false;
+ std::vector<uint16_t> data(size_t(w)*h*4);if(FAILED(frame->CopyPixels(nullptr,w*8,UINT(data.size()*2),reinterpret_cast<BYTE*>(data.data()))))return false;
+ double error=0;const double matrix[3][3]={{1.660491,-.587641,-.072850},{-.124550,1.132900,-.008349},{-.018151,-.100579,1.118730}};
+ for(size_t i=0;i<size_t(w)*h;++i)for(unsigned c=0;c<3;++c){const double ref=encoded2020?matrix[c][0]*expected[i*3]+matrix[c][1]*expected[i*3+1]+matrix[c][2]*expected[i*3+2]:expected[i*3+c];
+ error=std::max(error,std::abs(DirectX::PackedVector::XMConvertHalfToFloat(data[i*4+c])-ref));
+ }
+ std::cout<<"HDR_JXR_GPU_COMPARE pixels="<<size_t(w)*h<<" maxError="<<error<<" encoded2020="<<encoded2020<<std::endl;
+ return error<=(encoded2020?.02:0);
+}
static bool shaderIdentity(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring){
auto original=makeTexture(ctx.device(),64,16,DXGI_FORMAT_R16G16B16A16_FLOAT,true);
auto proxy=makeTexture(ctx.device(),64,16,DXGI_FORMAT_R8G8B8A8_UNORM,true);
@@ -51,6 +70,8 @@ static bool shaderIdentity(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ri
states.transition(list,original.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,proxy.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);enc.bind(list,constants,gpuHandleOf(enc,0).ptr,gpuHandleOf(enc,1).ptr);list->Dispatch(4,1,1);states.uavBarrier(list,proxy.Get());states.transition(list,proxy.Get(),D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);states.transition(list,final.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);dec.bind(list,constants,gpuHandleOf(dec,0).ptr,gpuHandleOf(dec,3).ptr);list->Dispatch(4,1,1);states.uavBarrier(list,final.Get());states.transition(list,final.Get(),D3D12_RESOURCE_STATE_COMMON);states.transition(list,original.Get(),D3D12_RESOURCE_STATE_COMMON);
if(!ring.submitAndSignal(slot)||!ring.waitIdle())return false;
std::vector<float>a,b;bool ok=read(ctx,ring,original.Get(),a)&&read(ctx,ring,final.Get(),b)&&a==b;
+ const auto imagePath=std::filesystem::path(L"out")/(L"hdr-identity-"+std::to_wstring(GetTickCount64())+L".jxr");
+ ok=ok&&sink::saveHdrScreenshot(imagePath.wstring(),ctx,ring,original.Get())&&verifyJxr(imagePath,a,64,16,false);
std::cout<<"HDR_SHADER_IDENTITY pixels=1024 black_nearblack_white_1000_4000_nits_widegamut="<<ok<<std::endl;return ok;
}
int wmain(int argc,wchar_t** argv){
@@ -58,8 +79,14 @@ int wmain(int argc,wchar_t** argv){
CoInitializeEx(nullptr,COINIT_MULTITHREADED);gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status status;gfx::DeviceContextDesc dd;
if(!ctx.initialize(dd,status)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,status))return 2;
if(!shaderIdentity(ctx,ring))return 3;if(!mode)return 0;
+ const bool fileInput=argc>3,hardware=argc>4&&_wtoi(argv[4])!=0;
+ source::MediaFileSource source;
+ if(fileInput){source::SourceOpenDesc od;od.path=argv[3];od.preferHardwareDecode=hardware;od.d3d12Device=ctx.device();od.d3d12Queue=ctx.directQueue();
+ if(!source.open(od)||!source.info().color.isHdrPath()||source.info().width!=1920||source.info().height!=1080)return 9;
+ }
EnhanceGraph graph(ctx,ring);EnhanceGraphDesc gd;gd.sourceWidth=1920;gd.sourceHeight=1080;gd.workWidth=mode>1?2560:1920;gd.workHeight=mode>1?1440:1080;gd.nrWidth=1920;gd.nrHeight=1080;
gd.hdrInput=gd.hdrOutput=true;gd.enableNr=true;gd.enableSr=mode>1;gd.enableFg=mode>1;gd.videoSrQuality=(mode==3||mode==4)?1:0;gd.nrBeforeSr=mode==4||mode==6;gd.enableNvofStandalone=true;gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ if(argc>2)gd.nrRuntime=engine::NrRuntime(_wtoi(argv[2]));
if(mode==5)gd.frameGenerationBackend=engine::FrameGenerationBackend::XeSS;
if(!graph.initialize(gd))return 4;
HWND window=nullptr;engine::VideoPresenter presenter;
@@ -71,15 +98,17 @@ int wmain(int argc,wchar_t** argv){
unsigned generated=0;bool ok=true;double highlight=0;
for(unsigned frame=0;frame<20&&ok;++frame){
for(int y=0;y<1080;++y)for(int x=0;x<1920;++x){const double v=x>1440?.7518270962:x>960?.5806888810:.15+.35*(.5+.5*sin((x+frame*4)*.05)*sin(y*.04));reinterpret_cast<uint16_t*>(f->data[0]+y*f->linesize[0])[x]=uint16_t(std::lround(64+876*v))<<6;}
- EnhanceGraph::FrameOutputs out;ok=graph.process(f,frame*1000.0/60,frame==0||frame==10,out,frame+1);if(!ok)break;
+ const AVFrame* input=f;FramePacket packet;
+ if(fileInput){if(source.read(packet,&input)!=source::SourceReadStatus::Frame||(input->format==AV_PIX_FMT_D3D12)!=hardware){ok=false;break;}}
+ EnhanceGraph::FrameOutputs out;ok=graph.process(input,frame*1000.0/60,frame==0||frame==10,out,frame+1,fileInput?&packet.colorInfo:nullptr);if(!ok)break;
std::vector<float> pixels;ok=read(ctx,ring,graph.videoFrameResource(out.videoSlot),pixels);
if(ok){highlight=pixels[(size_t(gd.workHeight/2)*gd.workWidth+gd.workWidth*7/8)*3];ok=highlight>11.5&&highlight<13.5&&std::all_of(pixels.begin(),pixels.end(),[](float v){return std::isfinite(v)&&std::abs(v)<150;});}
+ if(frame==19&&ok){const auto target=std::filesystem::path(L"out")/(L"hdr-test-"+std::to_wstring(GetTickCount64())+L".jxr");ok=sink::saveHdrScreenshot(target.wstring(),ctx,ring,graph.videoFrameResource(out.videoSlot))&&verifyJxr(target,pixels,gd.workWidth,gd.workHeight,graph.hdr10Output());}
if(mode==5&&ok){ok=presenter.present(ctx,ring,graph,out.videoSlot,false,true,0,false,.5f,out.batch.identity);Sleep(17);}
- if(mode>1&&mode!=5&&ok){ok=graph.resolveGeneration(out);if(ok&&out.hasGenerated){std::vector<float> middle;ok=read(ctx,ring,graph.generatedFrameResource(out.genSlot),middle)&&std::all_of(middle.begin(),middle.end(),[](float v){return std::isfinite(v)&&std::abs(v)<150;});++generated;}}
+ if(mode>1&&mode!=5&&ok){ok=graph.resolveGeneration(out);if(ok&&out.hasGenerated){std::vector<float> middle;ok=read(ctx,ring,graph.generatedFrameResource(out.genSlot),middle)&&std::all_of(middle.begin(),middle.end(),[](float v){return std::isfinite(v)&&std::abs(v)<150;});if(ok){const auto h=middle[(size_t(gd.workHeight/2)*gd.workWidth+gd.workWidth*7/8)*3];ok=h>11.5&&h<13.5;}++generated;}}
}
if(mode==5)generated=unsigned(presenter.xessGeneratedCount());
ok=ok&&graph.metrics().nrEvaluateCount==20&&(mode==1||generated>0);
- std::cout<<"HDR_ENHANCEMENT mode="<<mode<<" nr="<<graph.metrics().nrEvaluateCount<<" sr="<<graph.metrics().srEvaluateCount<<" generated="<<generated<<" highlight_nits="<<highlight*80<<" pass="<<ok<<std::endl;
+ std::cout<<"HDR_ENHANCEMENT file="<<fileInput<<" hardware="<<hardware<<" mode="<<mode<<" nr="<<graph.metrics().nrEvaluateCount<<" sr="<<graph.metrics().srEvaluateCount<<" generated="<<generated<<" highlight_nits="<<highlight*80<<" pass="<<ok<<std::endl;
ring.drainQueue();presenter.close();if(window)DestroyWindow(window);graph.shutdown();av_frame_free(&f);ring.shutdown();ctx.shutdown();CoUninitialize();return ok?0:8;
}
-
diff --git a/tests/integration/MultichannelTests.cpp b/tests/integration/MultichannelTests.cpp
new file mode 100644
index 00000000..969e95aa
--- /dev/null
+++ b/tests/integration/MultichannelTests.cpp
@@ -0,0 +1,60 @@
+#include "veyra/sink/WasapiAudioSink.h"
+#include "veyra/sink/CaptureAudioSession.h"
+#include "veyra/sink/AudioGain.h"
+#include <fstream>
+#include <filesystem>
+#include <iostream>
+#include <cmath>
+using namespace veyra::sink;
+static void wave(const std::filesystem::path& path,unsigned rate,uint32_t mask,bool isolated=false){
+ auto w=floatWave({6,mask});w.Format.nSamplesPerSec=rate;w.Format.nAvgBytesPerSec=rate*24;
+ std::ofstream out(path,std::ios::binary);auto number=[&](uint32_t n){out.write(reinterpret_cast<const char*>(&n),4);};
+ const uint32_t size=rate*24;out.write("RIFF",4);number(60+size);out.write("WAVEfmt ",8);number(40);out.write(reinterpret_cast<const char*>(&w),40);out.write("data",4);number(size);
+ for(unsigned i=0;i<rate;++i)for(unsigned c=0;c<6;++c){const float value=isolated?(i/(rate/10)==c?float(.2*sin(2*3.141592653589793*(c==3?60:300+c*100)*i/rate)):0):.04f*(c+1);out.write(reinterpret_cast<const char*>(&value),4);}
+}
+int wmain(int argc,wchar_t** argv){
+ if(argc!=2)return 2;const std::filesystem::path root=argv[1];std::filesystem::create_directories(root);
+ unsigned failures=0,checks=0;auto check=[&](bool ok,const char* name){++checks;if(!ok)++failures;std::cout<<name<<" pass="<<ok<<std::endl;};
+ for(auto mask:{0x3fu,0x60fu})for(unsigned bits:{16,24,32}){
+ auto w=floatWave({6,mask});w.SubFormat=KSDATAFORMAT_SUBTYPE_PCM;w.Format.wBitsPerSample=WORD(bits);w.Format.nBlockAlign=WORD(bits/8*6);w.Format.nAvgBytesPerSec=w.Format.nBlockAlign*48000;w.Samples.wValidBitsPerSample=WORD(bits);
+ WavePcmFormat parsed;check(parseWavePcm(&w,sizeof(w),parsed)&&parsed.layout.mask==mask&&parsed.layout.channels==6,"PCM extended layout");
+ check(!parseWavePcm(&w,sizeof(WAVEFORMATEX),parsed),"truncated extended format rejected");
+ w.dwChannelMask=3;check(!parseWavePcm(&w,sizeof(w),parsed),"six channels with stereo mask rejected");
+ }
+ for(auto mask:{0x3fu,0x60fu})for(unsigned rate:{44100u,48000u,96000u}){
+ const auto path=root/(std::to_wstring(mask)+L"-"+std::to_wstring(rate)+L".wav");wave(path,rate,mask);
+ AudioPipeline pipe;bool ok=pipe.open(path.wstring())&&pipe.pcmFormat()==AudioFormat{6,mask};
+ if(ok){pipe.startThread(nullptr);const auto until=std::chrono::steady_clock::now()+std::chrono::seconds(3);while(pipe.bufferedMs()<500&&std::chrono::steady_clock::now()<until)Sleep(2);pipe.stopThread();
+ std::vector<float> pcm(10000*6+16,-9);double pts=-1;const auto n=pipe.pull(pcm.data(),10000,&pts);ok=n==10000;
+ double error=0;for(size_t i=100;i<n;++i)for(unsigned c=0;c<6;++c)error=std::max(error,std::abs(double(pcm[i*6+c]-.04f*(c+1))));
+ ok=ok&&error<.0001&&pipe.overruns()==0&&std::all_of(pcm.begin()+60000,pcm.end(),[](float v){return v==-9;});
+ double next=-1;pipe.pull(pcm.data(),1,&next);ok=ok&&std::abs(next-pts-10000.0/48)<.01;
+ std::cout<<"rate="<<rate<<" mask="<<mask<<" amplitudeError="<<error<<" pts="<<pts<<" next="<<next<<std::endl;
+ }
+ check(ok,"file six channels independent and PTS in audio frames");
+ }
+ {
+ const auto path=root/L"six-speaker-isolation.wav";wave(path,48000,0x60f,true);
+ AudioPipeline pipe;bool ok=pipe.open(path.wstring());
+ if(ok){pipe.startThread(nullptr);const auto until=std::chrono::steady_clock::now()+std::chrono::seconds(3);while(pipe.bufferedMs()<650&&std::chrono::steady_clock::now()<until)Sleep(2);pipe.stopThread();
+ std::vector<float> samples(28800*6);const auto n=pipe.pull(samples.data(),28800,nullptr);ok=n==28800;
+ for(unsigned speaker=0;speaker<6;++speaker){double active=0,leak=0;
+ for(unsigned i=speaker*4800;i<(speaker+1)*4800;++i)for(unsigned c=0;c<6;++c)
+ if(c==speaker)active+=samples[i*6+c]*samples[i*6+c];else leak+=std::abs(samples[i*6+c]);
+ ok=ok&&active>90&&active<100&&leak<.00001;
+ std::cout<<"speaker="<<speaker<<" energy="<<active<<" otherChannelLeak="<<leak<<std::endl;
+ }
+ }
+ check(ok,"six independent speaker bursts including center and LFE");
+ }
+ std::vector<float> pcm(240*6,1);float gain=0;applyPcmGain(pcm.data(),240,6,1,gain);bool equal=true;
+ for(unsigned i=0;i<240;++i)for(unsigned c=1;c<6;++c)equal&=pcm[i*6+c]==pcm[i*6];
+ fadePcmTail(pcm.data(),240,6,gain);check(equal&&std::all_of(pcm.end()-6,pcm.end(),[](float v){return v==0;}),"six-channel simultaneous gain and fade");
+ CaptureAudioSession capture;auto format=floatWave({6,0x60f});check(capture.configure(format.Format,sizeof(format)),"capture accepts true 5.1 mask");capture.setGain(0);capture.setSync(2,0);
+ bool started=capture.start();std::vector<float> silence(480*6,0);const auto begin=std::chrono::steady_clock::now();
+ for(unsigned i=0;started&&i<80;++i){std::this_thread::sleep_until(begin+std::chrono::milliseconds(i*10));started=capture.push(silence.data(),silence.size()*4,i*10.0,i==0);}
+ const auto state=capture.snapshot();capture.stop();
+ std::cout<<"capture input="<<state.inputChannels<<" output="<<state.outputChannels<<" mask="<<state.outputChannelMask<<" blocks="<<state.inputBlocks<<std::endl;
+ check(started&&state.available&&state.running&&state.inputChannels==6&&state.outputChannels>0&&state.overflows==0,"5.1 capture to actual WASAPI endpoint (muted; no speaker claim)");
+ std::cout<<"MULTICHANNEL checks="<<checks<<" failures="<<failures<<std::endl;return failures?1:0;
+}
diff --git a/tests/unit/CaptureColorContractTests.cpp b/tests/unit/CaptureColorContractTests.cpp
index 0f91f9a4..9f291f4e 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 "veyra/sink/AudioFormat.h"
#include <iostream>
#include <vector>
#include <atomic>
@@ -104,5 +105,20 @@ int main(){
filter->Stop();sample.Reset();allocator->Decommit();input->Disconnect();
}
memory.Reset();input.Reset();filter.Reset();output.Reset();allocator.Reset();
+ {
+ auto hdrVi=vi;hdrVi.bmiHeader.biHeight=4;hdrVi.bmiHeader.biSizeImage=48;hdrVi.bmiHeader.biBitCount=24;
+ auto hdrType=type;hdrType.subtype={source::captureFourcc('P','0','1','0'),0,0x10,{0x80,0,0,0xaa,0,0x38,0x9b,0x71}};hdrType.pbFormat=reinterpret_cast<BYTE*>(&hdrVi);
+ DXVA2_ExtendedFormat hdrFlags{};hdrFlags.NominalRange=DXVA2_NominalRange_16_235;hdrFlags.VideoTransferMatrix=4;hdrFlags.VideoPrimaries=9;
+ for(unsigned transfer:{15u,16u}){hdrFlags.VideoTransferFunction=transfer;hdrVi.dwControlFlags=hdrFlags.value|AMCONTROL_COLORINFO_PRESENT;
+ check(source::captureMediaLayout(hdrType,layout)&&layout.color.isHdrPath()&&layout.color.primaries==pipeline::ColorPrimaries::BT2020&&layout.color.matrix==pipeline::YuvMatrix::BT2020NCL&&!layout.color.transferAssumed,"capture negotiates explicit PQ/HLG BT2020 metadata");
+ }
+ auto multi=sink::floatWave({6,0x60f});AM_MEDIA_TYPE mt=audio;mt.subtype=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;mt.cbFormat=sizeof(multi);mt.pbFormat=reinterpret_cast<BYTE*>(&multi);
+ output.Attach(new OutputPin);auto* peer=static_cast<OutputPin*>(output.Get());peer->supportsBuffering=true;
+ check(source::suggestCaptureAudioBuffering(output.Get(),multi.Format)==S_OK&&peer->suggested.cbBuffer==11520,"six-channel float upstream negotiation retains 10ms target");
+ check(SUCCEEDED(source::createNativeAudioSink(mt,[](IMediaSample*){return S_OK;},filter,input))&&input->ReceiveConnection(output.Get(),&mt)==S_OK,"native sink directly connects six-channel extensible PCM");
+ auto changed=multi;changed.dwChannelMask=0x3f;auto alternative=mt;alternative.pbFormat=reinterpret_cast<BYTE*>(&changed);
+ check(input->QueryAccept(&alternative)==S_FALSE,"side-to-back layout change requires reconnect even at identical byte stride");
+ input->Disconnect();input.Reset();filter.Reset();output.Reset();
+ }
CoUninitialize();std::cout<<"failures="<<failures<<'\n';return failures?1:0;
}
diff --git a/tests/unit/CaptureFormatCases.h b/tests/unit/CaptureFormatCases.h
index 27dad92b..7d74790f 100644
--- a/tests/unit/CaptureFormatCases.h
+++ b/tests/unit/CaptureFormatCases.h
@@ -51,7 +51,7 @@ template<class Check> void captureFormatCases(Check check){
check(copyCaptureSample(l,raw.data(),raw.size(),*f)&&f->data[0][0]==0&&f->data[0][1]==0&&f->data[0][2]==255,"RGB555/565 red channel masks");av_frame_free(&f);
}
t.subtype=fourcc("P010");DXVA2_ExtendedFormat ext{};ext.VideoTransferFunction=16;vi.dwControlFlags=ext.value|AMCONTROL_COLORINFO_PRESENT;
- check(!captureMediaLayout(t,l),"capture PQ metadata not silently interpreted as SDR");vi.dwControlFlags=0;
+ check(captureMediaLayout(t,l)&&l.color.transfer==veyra::pipeline::TransferFunction::HLG&&!l.color.transferAssumed,"capture HLG metadata is retained, never silently interpreted as SDR");vi.dwControlFlags=0;
t.subtype=fourcc("ABCD");check(capturePixelName(t.subtype)==L"ABCD"&&!captureMediaLayout(t,l),"unknown FourCC readable but not advertised as native");
t.subtype.Data2=3;check(capturePixelName(t.subtype).find(L"未知格式")!=std::wstring::npos&&!captureMediaLayout(t,l),"private GUID cannot alias standard FourCC");
}
diff --git a/tests/unit/PipelineContractTests.cpp b/tests/unit/PipelineContractTests.cpp
index 42dc7a80..bdbece04 100644
--- a/tests/unit/PipelineContractTests.cpp
+++ b/tests/unit/PipelineContractTests.cpp
@@ -69,9 +69,12 @@ int main() {
cd.matrixAssumed = true; // HD SDR documented default
cd.rotationDegrees = 0;
check("color:hdr-path-detected", [&] {
- ColorDescription hdr; hdr.pixelFormat = SourcePixelFormat::P010;
+ ColorDescription hdr; hdr.pixelFormat = SourcePixelFormat::P010;hdr.transfer=TransferFunction::PQ;
return hdr.isHdrPath();
}());
+ ColorDescription tenBit;tenBit.pixelFormat=SourcePixelFormat::P010;
+ check("color:ten-bit-alone-is-not-HDR",!tenBit.isHdrPath());
+ tenBit.transfer=TransferFunction::HLG;check("color:HLG-is-HDR",tenBit.isHdrPath());
check("color:assumed-flag-survives", cd.matrixAssumed && !cd.rangeAssumed);
constexpr FrameFlags seekCut =
diff --git a/tools/player_probe/main.cpp b/tools/player_probe/main.cpp
index 66abc9dc..4b64e94d 100644
--- a/tools/player_probe/main.cpp
+++ b/tools/player_probe/main.cpp
@@ -482,7 +482,7 @@ int main(int argc, char** argv)
// --- Audio start (after GPU init) ------------------------------------
if (hasAudio) {
- if (!audio.start()) {
+ if (!audio.start(audioPipe.pcmFormat())) {
veyra::log::error("player", "audio renderer open failed");
break;
}