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(export): vendor-neutral encoders (NVENC + Media Foundation MFT) and adjustable bitrate
Veyra Goal Agent4002d8310209
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 05ccd689..6c9929fa 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -438,6 +438,8 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformsrc/sink/BitstreamAudioSink.cppsrc/sink/ImageExportSink.cppsrc/sink/NvencD3D12Encoder.cpp+ src/sink/MfVideoEncoder.cpp+ src/sink/VideoEncoderFactory.cpp)veyra_apply_warnings(veyra_sinks)target_compile_options(veyra_sinks PRIVATE /WX-)@@ -449,7 +451,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_include_directories(veyra_sinks PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/third_party_local/nvidia/nv-codec-headers/include")target_compile_definitions(veyra_sinks PRIVATE VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")add_dependencies(veyra_sinks veyra_shader_rgb_nv12)-target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt)+ target_link_libraries(veyra_sinks PUBLIC veyra_base veyra_gfx ole32 windowscodecs mmdevapi avrt mfplat mfuuid mf)target_link_libraries(veyra_sinks PRIVATE ${FFMPEG_LIBRARIES})if(FFMPEG_INCLUDE_DIRS)target_include_directories(veyra_sinks PRIVATE ${FFMPEG_INCLUDE_DIRS})diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 924bb14c..7662dac3 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -243,6 +243,22 @@ Local evidence (RTX 5070, structure and mechanics only):restored=1), delivery gate`logs/delivery/548a606d92484286806f272d4744d2a7/result.json`.+## Media Foundation encoder(系统硬件编码路径,移植自 FFmpeg mfenc.c)++Source: FFmpeg n9.0.1 `libavcodec/mfenc.c` 与 `libavcodec/mf_utils.c`+(LGPL-2.1-or-later;本地源码 `C:\veyra-deps\ffmpeg-ps5-slices-source`)。+`src/sink/MfVideoEncoder.cpp` 移植了其中被证明可用的部分:`MFTEnumEx` 硬件枚举与激活、+`MF_TRANSFORM_ASYNC_UNLOCK` 异步解锁、输入/输出媒体类型协商、`ICodecAPI`+(码率/低延迟/GOP/B 帧/质量)设置、事件驱动的 `ProcessInput`/`ProcessOutput` 循环、+`MFT_MESSAGE_COMMAND_DRAIN` 收尾,以及 `MF_MT_MPEG_SEQUENCE_HEADER`(SPS/PPS)+作为封装 extradata。++Veyra 的差异(非上游代码):输入不是 AVFrame,而是 Veyra 自己 D3D12 图渲染出的 NV12+经 readback 打包;枚举结果按当前显卡厂商优选并对每个候选做完整契约协商(一台机器上可能+同时装着多家驱动的编码 MFT);首个样本与 GOP 边界强制关键帧;码流直接交给 Veyra 的+MP4 封装路径。MFT 本身属于 Windows 与显卡驱动,不随包分发。FFmpeg 采用+LGPL-2.1-or-later,与 Veyra 的 GPLv3 兼容;上游作者归属见上。+## dav1d (1.3.0 AV1 playback)FFmpeg dynamically links dav1d 1.5.4 from the pinned local vcpkg build. The portable package includes its complete aggregated copyright/license text in `licenses/DAV1D-COPYRIGHT.txt` and provenance in `licenses/DAV1D-SPDX.json`. The FFmpeg corresponding-source ZIP includes dav1d source and its vcpkg port. Upstream: https://code.videolan.org/videolan/dav1d . License set recorded by the build: Apache-2.0, BSD-2-Clause, ISC and MIT; retain all notices supplied with the source.diff --git a/apps/veyra/SettingsWindow.cpp b/apps/veyra/SettingsWindow.cppindex 130a6130..23a756cc 100644--- a/apps/veyra/SettingsWindow.cpp+++ b/apps/veyra/SettingsWindow.cpp@@ -97,6 +97,7 @@ void populate(engine::EnhancementSettings s){if(send(202,CB_GETCOUNT)!=multiplierCount){send(202,CB_RESETCONTENT);const wchar_t* choices[]={L"关闭补帧",L"2X · 一张中间帧",L"3X · 两张中间帧",L"4X · 三张中间帧",L"6X · 五张中间帧"};for(int i=0;i<multiplierCount;++i)send(202,CB_ADDSTRING,0,LPARAM(choices[i]));}send(207,CB_SETCURSEL,s.videoSrQuality,0);send(202,CB_SETCURSEL,multiplierChoiceIndex(s.multiplier),0);send(208,CB_SETCURSEL,int(s.frameGenerationBackend),0);send(203,CB_SETCURSEL,int(s.nrPolicy),0);+ send(508,CB_SETCURSEL,int(engine::exportBitrateIndex(s.exportBitrateMbps)),0);send(218,CB_SETCURSEL,int(s.nrRuntime));check(219,s.captureCompatible?BST_CHECKED:BST_UNCHECKED);check(220,s.lowLatency?BST_CHECKED:BST_UNCHECKED);send(204,CB_SETCURSEL,int(s.flow),0);send(205,CB_SETCURSEL,int(s.content),0);@@ -115,6 +116,7 @@ bool read(engine::EnhancementSettings& s,bool allPages=false){s=enhancementEnablconst auto multiplier=send(202,CB_GETCURSEL,0,0),generation=send(208,CB_GETCURSEL,0,0),flowBackend=send(209,CB_GETCURSEL,0,0),flowQuality=send(204,CB_GETCURSEL,0,0),content=send(205,CB_GETCURSEL,0,0);if(multiplier==CB_ERR||generation==CB_ERR||flowBackend==CB_ERR||flowQuality==CB_ERR||content==CB_ERR){message(L"设置控件未完成初始化;未保存预设");return false;}s.multiplier=(multiplier>=0&&multiplier<int(engine::kFgMultiplierChoiceCount))?engine::kFgMultiplierChoices[multiplier]:1;s.frameGenerationBackend=static_cast<engine::FrameGenerationBackend>(generation);s.opticalFlowBackend=static_cast<engine::OpticalFlowBackend>(flowBackend);s.amdFlowHalfResolution=checked(215)==BST_CHECKED;s.flow=static_cast<engine::FlowQuality>(flowQuality);s.content=static_cast<engine::ContentRate>(content);+ {const int bitrate=send(508,CB_GETCURSEL,0,0);if(bitrate==CB_ERR||bitrate<0||bitrate>=int(engine::kExportBitrateChoiceCount)){message(L"导出码率控件未完成初始化;未保存设置");return false;}s.exportBitrateMbps=engine::kExportBitrateChoices[bitrate];}s.audioSync=static_cast<engine::AudioSyncMode>(send(216,CB_GETCURSEL));s.nrRuntime=static_cast<engine::NrRuntime>(send(218,CB_GETCURSEL));s.captureCompatible=checked(219)==BST_CHECKED;s.lowLatency=checked(220)==BST_CHECKED;@@ -157,6 +159,7 @@ bool liveField(int id){case 216:s.audioSync=static_cast<engine::AudioSyncMode>(send(id,CB_GETCURSEL));break;case 217:{wchar_t value[32]{};GetWindowTextW(item(id),value,32);wchar_t* end=nullptr;const auto parsed=wcstol(value,&end,10);if(end==value||*end||parsed<-250||parsed>250){message(L"声音偏移须为 -250 至 250 ms");return false;}s.audioOffsetMs=int(parsed);break;}case 207:s.videoSrQuality=uint32_t(send(id,CB_GETCURSEL));break;+ case 508:{const int index=send(id,CB_GETCURSEL,0,0);if(index==CB_ERR||index<0||index>=int(engine::kExportBitrateChoiceCount))return false;s.exportBitrateMbps=engine::kExportBitrateChoices[index];break;}case 700:case 701:case 702:s.model.style=id-700;break;case 710:case 711:s.model.autoMask=id-710;break;case 720:case 721:s.model.uiCorrection=id-720;break;@@ -246,6 +249,11 @@ case WM_CREATE:{window=h;font=makeFont(h);items.clear();displayedBackendWarning.button(L"暂停 / 继续导出",503,3,12,310);button(L"取消导出",504,3,12,354);add(L"BUTTON",L"优先观看 · 降低导出占用",505,BS_AUTOCHECKBOX|WS_TABSTOP,3,12,406,-1,36);check(505,BST_CHECKED);add(L"STATIC",L"",506,0,3,12,458,-1,120);add(L"STATIC",L"",507,0,3,12,588,-1,80);+ // Export bitrate row, inserted between the codec selector and everything+ // below it (the page scrolls, so the shift keeps the reading order).+ for(auto& entry:items)if(entry.page==3&&entry.y>=108)entry.y+=72;+ add(L"STATIC",L"导出码率",1121,0,3,12,104,-1,24);+ combo(508,3,132,{L"自动 · 恒定质量",L"6 Mbps",L"10 Mbps",L"16 Mbps",L"24 Mbps",L"40 Mbps",L"60 Mbps",L"100 Mbps",L"150 Mbps",L"200 Mbps"});add(L"STATIC",L"",400,0,-1,12,900,-1,92);add(L"STATIC",L"",401,0,-1,12,996,-1,86);for(auto& entry:items)if(entry.page==0&&entry.y>=146)entry.y+=176;add(L"BUTTON",L"NR保护区域",206,BS_AUTOCHECKBOX|WS_TABSTOP,0,12,146,-1,36);diff --git a/apps/veyra/ui/AppShell.cpp b/apps/veyra/ui/AppShell.cppindex 8ff4bbb3..3627a741 100644--- a/apps/veyra/ui/AppShell.cpp+++ b/apps/veyra/ui/AppShell.cpp@@ -559,7 +559,7 @@ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);INITCOCoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);initialOptions=veyra::engine::PlayerOptions::from(veyra::ui::defaultSettings());-int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-fg-only")smokeFgOnly=true;else if(arg==L"--smoke-transport")smokeTransport=true;else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-screenshot")smokeScreenshot=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--capture-audio"&&i+1<argc)initialOptions.settings.captureAudio=static_cast<veyra::engine::CaptureAudioIngress>(std::clamp(_wtoi(argv[++i]),0,2));else if(arg==L"--flow-amd")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::AmdFidelityFx;else if(arg==L"--flow-gpudis")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::GpuDis;else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,5);initialOptions.sr=true;}else if(arg==L"--nr-ampere")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Ampere;else if(arg==L"--nr-community")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Community;else if(arg==L"--nr-original")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Original;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);+int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<argc;++i){const std::wstring arg=argv[i];if(arg==L"--export-worker"&&i+1<argc)workerMapping=reinterpret_cast<HANDLE>(_wcstoui64(argv[++i],nullptr,10));else if(arg==L"--smoke-view"&&i+1<argc)smokeView=argv[++i];else if(arg==L"--smoke-fg-only")smokeFgOnly=true;else if(arg==L"--smoke-transport")smokeTransport=true;else if(arg==L"--smoke-repair-ui")smokeRepair=true;else if(arg==L"--smoke-repair-ui-reject")smokeRepair=smokeRepairReject=true;else if(arg==L"--smoke-hover")smokeZoom=smokeHover=true;else if(arg==L"--smoke-protection")smokeProtection=true;else if(arg==L"--smoke-zoom")smokeZoom=true;else if(arg==L"--smoke-empty")smokeEmpty=true;else if(arg==L"--smoke-dual")smokeDual=true;else if(arg==L"--smoke-dual-pause"){smokeDual=smokeDualPause=true;}else if(arg==L"--smoke-master-reject")smokeMaster=smokeMasterReject=true;else if(arg==L"--smoke-master")smokeMaster=true;else if(arg==L"--smoke-audio")smokeAudio=true;else if(arg==L"--smoke-job-cancel")smokeJobCancel=true;else if(arg==L"--smoke-job-exit")smokeJobExit=true;else if(arg==L"--smoke-job")smokeJob=true;else if(arg==L"--smoke-dual-export"&&i+1<argc)smokeDualOutput=argv[++i];else if(arg==L"--smoke-seconds"&&i+1<argc)smokeSeconds=std::clamp(_wtoi(argv[++i]),1,240);else if(arg==L"--export-out"&&i+1<argc)exportOutput=argv[++i];else if(arg==L"--max-frames"&&i+1<argc)exportFrames=std::max(1,_wtoi(argv[++i]));else if(arg==L"--cancel-after-ms"&&i+1<argc)cancelAfterMs=std::clamp(_wtoi(argv[++i]),1,240000);else if(arg==L"--hevc")exportHevc=true;else if(arg==L"--bitrate-mbps"&&i+1<argc)initialOptions.settings.exportBitrateMbps=uint32_t(std::clamp(_wtoi(argv[++i]),0,300));else if(arg==L"--smoke-rollback-flow"){smokeRollback=true;smokeRollbackFlow=true;}else if(arg==L"--smoke-rollback")smokeRollback=true;else if(arg==L"--smoke-ui")smokeUi=true;else if(arg==L"--no-fg")initialOptions.fg=false;else if(arg==L"--smoke-settings")smokeSettings=true;else if(arg==L"--smoke-screenshot")smokeScreenshot=true;else if(arg==L"--smoke-controls")smokeControls=true;else if(arg==L"--smoke-save"&&i+1<argc)smokeSave=argv[++i];else if(arg==L"--native")initialOptions.realtime=false;else if(arg==L"--realtime")initialOptions.realtime=true;else if(arg==L"--fg")initialOptions.fg=true;else if(arg==L"--fg-multiplier"&&i+1<argc){initialOptions.fgMultiplier=std::clamp(_wtoi(argv[++i]),2,4);initialOptions.fg=true;}else if(arg==L"--capture-audio"&&i+1<argc)initialOptions.settings.captureAudio=static_cast<veyra::engine::CaptureAudioIngress>(std::clamp(_wtoi(argv[++i]),0,2));else if(arg==L"--flow-amd")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::AmdFidelityFx;else if(arg==L"--flow-gpudis")initialOptions.settings.opticalFlowBackend=veyra::engine::OpticalFlowBackend::GpuDis;else if(arg==L"--video-sr"&&i+1<argc){initialOptions.settings.videoSrQuality=std::clamp(_wtoi(argv[++i]),1,5);initialOptions.sr=true;}else if(arg==L"--nr-ampere")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Ampere;else if(arg==L"--nr-community")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Community;else if(arg==L"--nr-original")initialOptions.settings.nrRuntime=veyra::engine::NrRuntime::Original;else if(arg==L"--sr")initialOptions.sr=true;else if(arg==L"--no-nr")initialOptions.nr=false;else if(arg==L"--nr")initialOptions.nr=true;else if(arg==L"--no-sr")initialOptions.sr=false;else autoInput=arg;}LocalFree(argv);// The legacy argument clamp caps --fg-multiplier at 4X. Re-read the flag here so// 6X (and 2X/3X/4X) can be exercised from the command line for diagnostics and// smoke tests; the interactive UI uses the capability-driven list instead.@@ -571,7 +571,7 @@ int argc=0;auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);for(int i=1;i<a// anywhere on the command line instead of only at the end.{int positionalArgc=0;auto positionalArgv=CommandLineToArgvW(GetCommandLineW(),&positionalArgc);std::wstring positional;- const wchar_t* valueFlags[]={L"--export-worker",L"--smoke-view",L"--smoke-dual-export",L"--smoke-seconds",L"--export-out",L"--max-frames",L"--cancel-after-ms",L"--smoke-save",L"--fg-multiplier",L"--capture-audio",L"--video-sr"};+ const wchar_t* valueFlags[]={L"--export-worker",L"--smoke-view",L"--smoke-dual-export",L"--smoke-seconds",L"--export-out",L"--max-frames",L"--cancel-after-ms",L"--smoke-save",L"--fg-multiplier",L"--capture-audio",L"--video-sr",L"--bitrate-mbps"};for(int i=1;i<positionalArgc;++i){const std::wstring a=positionalArgv[i];bool takesValue=false;for(const wchar_t* flag:valueFlags)if(a==flag){takesValue=true;break;}if(takesValue){++i;continue;}diff --git a/apps/veyra/ui/SettingHelp.h b/apps/veyra/ui/SettingHelp.hindex 548e03fc..8d9ae6fd 100644--- a/apps/veyra/ui/SettingHelp.h+++ b/apps/veyra/ui/SettingHelp.h@@ -36,6 +36,7 @@ inline const wchar_t* settingHelp(int id){case 206:return L"让框选区域少受NR改动,最多4块。只管NR,不给超分和补帧当保镖。";case 207:return L"选择DLSS SR或RTX视频超分,以及视频超分质量。两条路线各有脾气,试着看画质和耗时。";case 208:return L"选择DLSS、实验XeSS或AMD FSR补帧。XeSS/FSR的生成帧只存在于显示交换链,导出管线拿不到;导出时会自动改用DLSS补帧,显卡不支持则关闭补帧,提示和日志都会写明。别只看名字,看实际效果。";+ case 508:return L"导出码率:只决定导出文件的大小与画质,不影响预览。自动=编码器恒定质量档(NVENC CONSTQP / 系统编码器质量模式)。H.264 一般 10-40 Mbps 够用,4K 或高动态建议 60-150;HEVC 同等画质可以取更低。";case 209:return L"选择运动估算后端。NVOF、FidelityFX、GPU DIS负责看出物体怎么动。DIS是实验算法,走通用计算单元,可能和NR抢活干,不保证更快;选它不会换掉你的补帧方式,也不会解锁AMD NR。";case 211:return L"把增强参数恢复为内建默认。调迷路了就走这里,保存的用户预设不会被删。";case 213:return L"在画面上拖框添加NR保护区域,Esc取消。把不想被改的地方圈出来。";@@ -54,7 +55,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通常更省空间。HDR视频须选HEVC,保存为Main10 / PQ;别把HDR硬塞进普通H.264。";+ case 500:return L"H.264兼容性广,HEVC通常更省空间。HDR视频须选HEVC,保存为Main10 / PQ;别把HDR硬塞进普通H.264。编码器按显卡自动选择:N卡用NVENC(零拷贝最快),A卡/I卡用系统硬件编码(驱动自带的H.264/HEVC编码器),HDR导出仍需N卡。";case 501:return L"选保存位置并导出视频。参数在开始时冻结,NR按原生处理;低延迟预览顺序不带进导出。";case 502:return L"保存当前图片或视频帧。精彩的一瞬间,留下来。";case 503:return L"暂停或继续导出任务,不是暂停你正在看的视频。";diff --git a/docs/EXPORT_ENCODER_BITRATE_2026-09-16.md b/docs/EXPORT_ENCODER_BITRATE_2026-09-16.mdnew file mode 100644index 00000000..32e0fac7--- /dev/null+++ b/docs/EXPORT_ENCODER_BITRATE_2026-09-16.md@@ -0,0 +1,83 @@+# 2026-09-16 导出编码器多厂商化 + 可调码率(隔离分支)++用户指令:"能不能换编码?让全部都支持导出?还有加个可以调整码率的功能"。+分支 `codex/framegen-fsr-dolby-20260916`,未合并 main、未推送、未发布。++## 1. 之前的现状(事实)++- 导出硬性要求 NVIDIA:`VideoExportJob` 在非 N 卡上直接报"当前视频导出使用 NVIDIA+ NVENC;尚未实现 AMD AMF 或 Intel 编码后端"并放弃,AMD/Intel 用户**一个文件都导不出**。+- 我们的 FFmpeg 是**只解不编**的定制构建+ (`C:\veyra-deps\ffmpeg-ps5-dav1d-installed`:`CONFIG_LIBX264_ENCODER=no`、+ `CONFIG_H264_AMF_ENCODER=no`、`CONFIG_H264_QSV_ENCODER=no`、`CONFIG_H264_MF_ENCODER=no`),+ 所以"用 FFmpeg 的 amf/qsv/mf/x264 编码器"必须重建 FFmpeg,代价与许可证面都更大。+- 本机(RTX 5070)`ffmpeg -encoders` 显示 `h264_mf`/`hevc_mf` 可用、`hevc_mf` 实测失败+ (NVIDIA 不提供 HEVC 的 MF 编码器),`h264_mf` 实测 exit 0 —— MF 是**可验证**的通用路径。++## 2. 本轮实现++### 2.1 编码器抽象(`include/veyra/sink/VideoEncoder.h`)++`VideoEncoder` 接口 + `openVideoEncoder()` 工厂:**NVIDIA 适配器走 NVENC(D3D12 零拷贝),+其余适配器走 Media Foundation 硬件 MFT**;NVENC 会话被拒(旧/混杂 `nvEncodeAPI64.dll`、+该卡不支持的编码格式)时自动回落到 MF,而不是让用户丢掉整个导出。++### 2.2 Media Foundation 编码器(`src/sink/MfVideoEncoder.cpp`)++移植 FFmpeg `mfenc.c`(LGPL-2.1+)的 MFT 流程,见 `THIRD_PARTY_NOTICES.md`。要点:++- `MFTEnumEx(MFT_CATEGORY_VIDEO_ENCODER, MFT_ENUM_FLAG_HARDWARE|SORTANDFILTER)`;+- **按显卡厂商优选**:本机枚举同时出现 `AMDh264Encoder`(驱动带着)与 `NVIDIA H.264 Encoder MFT`,+ 取第一个会在 A 卡驱动上得到 `MF_E_HW_MFT_FAILED_START_STREAMING (0xC00D6D76)`。现在按+ vendor 关键字排序并对每个候选做完整类型协商,取第一个成功的;+- NV12 输入来自 Veyra 自己的 D3D12 图:`RgbToNv12` 着色器 → READBACK 缓冲 → 紧凑打包+ (MFT 只接受系统内存 NV12);+- 码率通过 `ICodecAPI`:`MeanBitRate`/`MaxBitRate`/`BufferSize`(0.5s CPB) ++ `PeakConstrainedVBR`;`LowLatencyMode`、`GOPSize`、`QualityVsSpeed` 同步设置;+- 输出样本:异步 MFT 自己分配 `out.pSample`(这条曾导致 300 帧全部被丢弃,已修);+- 首个样本与 GOP 边界用 `CODECAPI_AVEncVideoForceKeyFrame` 强制关键帧。++### 2.3 码率(NVENC + MF)++- `EnhancementSettings.exportBitrateMbps`(0 = 编码器恒定质量档,上限 300);+ 该字段**不参与** `sameVideoConfiguration`,改码率不会重建预览管线;+- NVENC:`NV_ENC_PARAMS_RC_VBR`,`averageBitRate=maxBitRate=target`,+ `vbvBufferSize = target/2`(半秒);0 时沿用 `CONSTQP 20/22/22`;+- MF:上面的 `PeakConstrainedVBR`;+- 预设格式 v14 → **v15**(行尾追加码率字段;解析顺序必须与写出顺序一致,本轮踩过一次);+- UI:设置面板"导出"页新增"导出码率"下拉(自动/6/10/16/24/40/60/100/150/200 Mbps);+- CLI:`--bitrate-mbps N`。++### 2.4 非 N 卡特性门控++导出图的 `enableNr/enableSr/enableNvofStandalone/enableFg` 现在与预览同规则:+DLSS NR / DLSS SR / DLSS FG / NVOF 仅 NVIDIA;AMD FSR 超分(`--video-sr 5`)是+唯一厂商中立的超分路径,非 N 卡请求 DLSS 系功能时**降级并在提示/日志中写明**,不再整任务失败。++## 3. 本机证据(RTX 5070)++| 场景 | 命令要点 | 结果 |+| --- | --- | --- |+| NVENC 码率 | `--bitrate-mbps 6` / `40` | 实际 6.11 / 32.8 Mbps(简单内容低于目标属正常 VBR) |+| MF 硬件编码 | `VEYRA_TEST_FORCE_MF_ENCODER=1 --bitrate-mbps 10` | 300 帧写满、`export-verify decoded=300 passed=true`、实际 10.16 Mbps |+| MF 30 Mbps | 同上 `--bitrate-mbps 30` | 26.1 Mbps、验证通过 |+| NVENC 全拒 → 回落 | `VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=2` | 自动选 MF,16 Mbps 实际 15.2 Mbps,exit 0 |+| MF + 补帧 | `--fg-xess --fg-multiplier 2` | XeSS 替换为 DLSS 2X,600 帧 @60fps、验证通过 |+| HDR + MF | `pq-tagged-51.mp4 --hevc` | 明确拒绝(8bit MFT 不支持 Main10),无 partial/final |+| HDR + NVENC | 同素材 | 30 帧 HEVC Main10、验证通过(无回归) |++自动检查:修复合同 169 项 0 失败;预设往返(新增码率字段)66 组 legacy 迁移 + 全字段往返 PASS;+delivery 短测 PASS `logs/delivery/35f4f46808fb4236856701704e5a7f52/result.json`。++## 4. 边界(如实)++- **MF 路径只支持 8bit 4:2:0**:HDR(HEVC Main10)导出仍然只有 NVENC;非 N 卡导出 HDR 会+ 明确报错而不是偷偷输出 SDR。非 N 卡的 HEVC 取决于该驱动是否提供 HEVC MFT(Intel/AMD 通常提供)。+- **性能**:MF 输入走"GPU 渲染 → readback → CPU 打包",4K60 输出会有可观的 PCIe 与内存拷贝+ 开销(每帧约 12 MB)。后续可优化为 D3D12 共享纹理 + D3D11 互操作,本轮未做。+- **未在 AMD/Intel 实卡上验证**:本机只有 N 卡,MF 路径是用 NVIDIA 的 MFT 跑通的;+ AMD/Intel 走同一条 API,但驱动差异(支持的 profile/码率控制/GOP 设置)需要用户实机复测。+- **AMF/QSV 原生后端未接入**:MF 走的就是这两家驱动里的编码器,原生 SDK 只提供更细的控制,+ 不是"能不能导出"的必要条件。+- 软件编码(x264/x265)未接入:需要重建带编码器的 FFmpeg 或引入 openh264/x264 依赖,+ 且 4K 软件编码速度不现实;当前策略是"任何现代显卡的驱动 MFT"。diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex e3e387d8..cedd73b2 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -69,6 +69,18 @@- 证据:本机 30 秒 FSR 运行 `real=839/generated=838/presented=1677`、`presentSubmitFps=30.00`、`gpuFgBatchP95Ms=0.197`;delivery 短测 PASS `logs/delivery/442f41e29b684e7e87174bc075d4e282/result.json`。- **边界(如实)**:FgBatch 为**应用侧**计时(提供方内部的插值工作不经过我们的队列,无法打点);用户机器上"SDK提交=0"的原始触发未能在本机复现(本机 r3 正常),累计对齐是针对该症状的根治性修法,需要用户在 r4 包上复测确认。+### 2026-09-16 导出编码器多厂商化(AMD/Intel 可导出)+ 可调码率++用户:"能不能换编码?让全部都支持导出?还有加个可以调整码率的功能"。完整方案、证据与边界见 [导出编码器与码率](EXPORT_ENCODER_BITRATE_2026-09-16.md)。++- **现状确认**:导出此前硬性要求 NVENC,非 N 卡直接拒绝(AMD/Intel 用户导不出任何文件);我们的 FFmpeg 是只解不编的定制构建(无 x264/amf/qsv/mf 编码器),所以"用 FFmpeg 的编码器"要重建 FFmpeg。+- **实现**:新增 `VideoEncoder` 抽象与工厂(`include/veyra/sink/VideoEncoder.h`、`src/sink/VideoEncoderFactory.cpp`):NVIDIA 走 NVENC(零拷贝不变),其余显卡走 Media Foundation 硬件 MFT;NVENC 被拒时自动回落 MF。`src/sink/MfVideoEncoder.cpp` 移植 FFmpeg `mfenc.c`(LGPL-2.1+,已记入 `THIRD_PARTY_NOTICES.md`)的 MFT 枚举/异步解锁/类型协商/ICodecAPI/事件循环/收尾流程,输入为 Veyra D3D12 图渲染的 NV12 经 readback 打包。+- **两个真问题(本轮实测抓出)**:① 本机同时枚举到 `AMDh264Encoder` 与 `NVIDIA H.264 Encoder MFT`,取第一个会在无 A 卡时 `MF_E_HW_MFT_FAILED_START_STREAMING (0xC00D6D76)` → 改为按显卡厂商优选 + 逐候选完整协商;② 硬件 MFT 自己分配输出样本(替换 `out.pSample`),错误地取自己的空指针导致 300 帧全被丢弃、导出"成功"却 0 帧 → 已修,现 `drained submitted=300 written=300`。+- **码率**:`EnhancementSettings.exportBitrateMbps`(0=恒定质量档,上限 300;不参与 `sameVideoConfiguration`,改码率不重建预览管线);NVENC VBR(平均=峰值, VBV 半秒)、MF PeakConstrainedVBR;预设格式 v14→v15(行尾追加,解析顺序须与写出顺序一致——本轮踩过一次并修复);UI 导出页新增"导出码率"下拉(自动/6/10/16/24/40/60/100/150/200 Mbps);CLI `--bitrate-mbps`。+- **非 N 卡特性门控**:导出的 NR/DLSS-SR/NVOF/DLSS-FG 仅 NVIDIA,AMD FSR 超分保留;请求不可用功能时降级并写明,不再整任务失败。+- **实测(RTX 5070)**:NVENC 6/40 Mbps → 实际 6.11/32.8;强制 MF 10/30 Mbps → 10.16/26.1,300 帧逐帧验证通过;`VEYRA_TEST_NVENC_FIRST_OPEN_FAILS=2`(模拟用户那种 NVENC 被拒)→ 自动 MF,exit 0;MF + XeSS→DLSS 2X 补帧 → 600 帧验证通过;HDR 走 MF → 明确拒绝且不留 partial,HDR 走 NVENC 正常(无回归)。修复合同 169 项 0 失败、预设往返 PASS、delivery 短测 PASS `logs/delivery/35f4f46808fb4236856701704e5a7f52/result.json`。+- **未做/边界**:MF 只支持 8bit(HDR 仍需 NVENC);MF 输入经 CPU readback(4K 有开销,后续可做 D3D12 共享纹理 + D3D11 互操作);**AMD/Intel 实卡未验证**(本机只有 N 卡,走同一 API 但需实机复测);AMF/QSV 原生后端与软件 x264/x265 未接入。+### 2026-09-16 导出失败两例修复 + XeSS/FSR 补帧导出(用户:"修,并且看看是不是用XeSS补帧没办法导出,也一起修了")两位粉丝群用户的导出失败日志逐条定位到根因,并按"必须能出文件"的目标修掉;完整复现素材、命令与证据见 [导出修复与补帧导出](EXPORT_REPAIR_AND_FG_EXPORT_2026-09-16.md)。diff --git a/include/veyra/engine/EnhancementSettings.h b/include/veyra/engine/EnhancementSettings.hindex d7507ed6..5cebc21b 100644--- a/include/veyra/engine/EnhancementSettings.h+++ b/include/veyra/engine/EnhancementSettings.h@@ -16,6 +16,12 @@ constexpr bool presentSinkFrameGeneration(FrameGenerationBackend backend) {// exposes 2/3/4/6 and MFG buyers pick from those; 1 = generation off.inline constexpr uint32_t kFgMultiplierChoices[]={1,2,3,4,6};inline constexpr size_t kFgMultiplierChoiceCount=sizeof(kFgMultiplierChoices)/sizeof(kFgMultiplierChoices[0]);+// Export bitrate presets in Mbps; index 0 keeps the encoder's constant-quality+// default. Labels are the UI strings for the same order.+inline constexpr uint32_t kExportBitrateChoices[]={0,6,10,16,24,40,60,100,150,200};+inline constexpr size_t kExportBitrateChoiceCount=sizeof(kExportBitrateChoices)/sizeof(kExportBitrateChoices[0]);+inline constexpr const wchar_t* kExportBitrateLabels[]={L"自动 · 恒定质量",L"6 Mbps",L"10 Mbps",L"16 Mbps",L"24 Mbps",L"40 Mbps",L"60 Mbps",L"100 Mbps",L"150 Mbps",L"200 Mbps"};+inline size_t exportBitrateIndex(uint32_t mbps){for(size_t i=0;i<kExportBitrateChoiceCount;++i)if(kExportBitrateChoices[i]==mbps)return i;return 0;}// videoSrQuality values: 0 = DLSS SR, 1..4 = RTX video SR quality steps,// 5 = AMD FSR upscaling (vendor neutral; verified on an NVIDIA adapter).inline constexpr uint32_t kVideoSrFsr=5;@@ -105,6 +111,10 @@ struct EnhancementSettings {uint32_t videoSrQuality=0; // 0 DLSS SR; 1–4 RTX Video SRuint32_t multiplier=1;FrameGenerationBackend frameGenerationBackend=FrameGenerationBackend::Dlss;+ // Export target bitrate in Mbps; 0 keeps the encoder's constant-quality+ // default (NVENC CONSTQP / MFT quality mode). Only the export job consumes+ // it: preview never re-encodes.+ uint32_t exportBitrateMbps=0;pipeline::NrSizePolicy nrPolicy=pipeline::NrSizePolicy::Realtime;FlowQuality flow=FlowQuality::Balanced;OpticalFlowBackend opticalFlowBackend=OpticalFlowBackend::Nvidia;@@ -118,6 +128,9 @@ struct EnhancementSettings {video.revision=other.revision;video.audioSync=other.audioSync;video.audioOffsetMs=other.audioOffsetMs;+ // Export-only fields: changing the bitrate must never invalidate the+ // running preview graph (the controller would otherwise rebuild it).+ video.exportBitrateMbps=other.exportBitrateMbps;return video==other;}void rejectVideoRequest(const EnhancementSettings& attempted,const EnhancementSettings& previous) {@@ -151,6 +164,9 @@ struct EnhancementSettings {if(!pipeline::validSrTarget(srTarget))return "invalid SR target";if(opticalFlowBackend!=OpticalFlowBackend::Nvidia&&opticalFlowBackend!=OpticalFlowBackend::AmdFidelityFx&&opticalFlowBackend!=OpticalFlowBackend::GpuDis)return "invalid optical flow backend";if(multiplier<1||multiplier>6)return "unsupported multiplier";+ // 0 = auto quality; explicit values are capped at 300 Mbps so a typo+ // cannot ask a driver for a nonsense rate.+ if(exportBitrateMbps>300)return "export bitrate out of range";if(!pipeline::validNrSizePolicy(nrPolicy))return "invalid NR size policy";if(flow<FlowQuality::Performance||flow>FlowQuality::Quality||content<ContentRate::Transport||content>ContentRate::Capture60To30)return "invalid flow/content mode";return {};diff --git a/include/veyra/sink/NvencD3D12Encoder.h b/include/veyra/sink/NvencD3D12Encoder.hindex 8f18830a..465ba52b 100644--- a/include/veyra/sink/NvencD3D12Encoder.h+++ b/include/veyra/sink/NvencD3D12Encoder.h@@ -3,18 +3,22 @@#include <functional>#include <memory>#include <vector>+#include "veyra/sink/VideoEncoder.h"namespace veyra::gfx {class D3D12DeviceContext;class CommandSlotRing;}namespace veyra::pipeline {class EnhanceGraph;}namespace veyra::sink {-class NvencD3D12Encoder {+// NVIDIA path: D3D12 NVENC with a zero-copy conversion into the registered+// NV12/P010 input texture. Selected automatically on NVIDIA adapters.+class NvencD3D12Encoder final : public VideoEncoder {public:- using PacketWriter=std::function<bool(const uint8_t*,size_t,int64_t,bool)>;NvencD3D12Encoder();~NvencD3D12Encoder();- bool open(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,bool hevc,unsigned fpsNum,unsigned fpsDen,PacketWriter);- bool encode(unsigned frameSlot,bool generated,int64_t pts);- bool finish();- void close();- std::vector<uint8_t> headers() const;+ bool open(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,const EncoderConfig&,PacketWriter) override;+ bool encode(unsigned frameSlot,bool generated,int64_t pts) override;+ bool finish() override;+ void close() override;+ std::vector<uint8_t> headers() const override;+ EncoderBackend backend() const override {return EncoderBackend::Nvenc;}+ std::wstring describe() const override;private:struct Impl;std::unique_ptr<Impl> p_;};diff --git a/include/veyra/sink/VideoEncoder.h b/include/veyra/sink/VideoEncoder.hnew file mode 100644index 00000000..6eea9344--- /dev/null+++ b/include/veyra/sink/VideoEncoder.h@@ -0,0 +1,79 @@+#pragma once++// Product video encoder abstraction for the export job. Exactly one encoder is+// active per export; the backend is chosen from adapter capability, never from+// a build-time switch:+// * NVIDIA adapter -> NVENC (D3D12, zero-copy, the fastest path)+// * any other adapter -> Media Foundation hardware MFT (AMD/Intel/NVIDIA+// driver encoders exposed through the OS)+// The Media Foundation path is 8-bit 4:2:0 only, so HDR (HEVC Main10) export+// still requires NVENC; the export job states that instead of silently+// producing an SDR file.+#include <cstdint>+#include <functional>+#include <memory>+#include <string>+#include <vector>++namespace veyra::gfx { class D3D12DeviceContext; class CommandSlotRing; }+namespace veyra::pipeline { class EnhanceGraph; }++namespace veyra::sink {++// (bitstream, bytes, output frame index, keyframe) -> accepted?+using PacketWriter=std::function<bool(const uint8_t*,size_t,int64_t,bool)>;++enum class EncoderBackend { None, Nvenc, MediaFoundation };++constexpr std::string_view encoderBackendName(EncoderBackend backend) {+ switch(backend) {+ case EncoderBackend::Nvenc: return "NVIDIA-NVENC";+ case EncoderBackend::MediaFoundation: return "MediaFoundation-MFT";+ case EncoderBackend::None: break;+ }+ return "none";+}++struct EncoderConfig {+ bool hevc=false;+ unsigned fpsNum=0;+ unsigned fpsDen=1;+ // Export target bitrate in Mbps; 0 keeps the backend's constant-quality+ // default (NVENC CONSTQP / MFT quality mode).+ uint32_t bitrateMbps=0;+ // Active adapter identity. A machine can have several vendors' hardware+ // MFTs registered at once (an AMD driver's MFT is visible on an NVIDIA+ // host), so the Media Foundation path must prefer the MFT of the GPU that+ // actually renders the frames. 0x10DE/0x1002/0x8086 = NVIDIA/AMD/Intel.+ uint32_t adapterVendorId=0;+};++class VideoEncoder {+public:+ virtual ~VideoEncoder()=default;+ virtual bool open(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,const EncoderConfig&,PacketWriter)=0;+ virtual std::vector<uint8_t> headers() const=0;+ virtual bool encode(unsigned frameSlot,bool generated,int64_t pts)=0;+ virtual bool finish()=0;+ virtual void close()=0;+ virtual EncoderBackend backend() const=0;+ // Human-readable identity for logs and the export status line, e.g.+ // "NVIDIA NVENC H.264 (D3D12)" or "Media Foundation HEVC (NVIDIA ... MFT)".+ virtual std::wstring describe() const=0;+};++// Capability-driven selection. Returns nullptr when no usable encoder exists+// for the requested codec and fills `detail` with the reason (used verbatim in+// the user-facing failure message).+std::unique_ptr<VideoEncoder> openVideoEncoder(gfx::D3D12DeviceContext&,gfx::CommandSlotRing&,pipeline::EnhanceGraph&,+ const EncoderConfig&,PacketWriter,std::wstring& detail);++// Read-only capability probe for logs/tests: is a hardware Media Foundation+// encoder registered for the requested codec? Never opens a session.+struct EncoderCapability {+ bool mediaFoundation=false; // a hardware MFT was found+ std::wstring mediaFoundationName;// friendly name of that MFT+};+EncoderCapability queryMediaFoundationEncoder(bool hevc);++} // namespace veyra::sinkdiff --git a/src/engine/PresetStore.cpp b/src/engine/PresetStore.cppindex d295a252..1795b0c5 100644--- a/src/engine/PresetStore.cpp+++ b/src/engine/PresetStore.cpp@@ -13,12 +13,12 @@ bool nameOk(const std::wstring& s){return !s.empty()&&s.size()<=48&&s.front()!=Lstd::wstring trim(std::wstring s){auto a=s.find_first_not_of(L" \t\r\n");if(a==s.npos)return {};auto b=s.find_last_not_of(L" \t\r\n");return s.substr(a,b-a+1);}}std::string PresetStore::serialize()const{- std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 14\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';- for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<'\n';}return o.str();+ std::ostringstream o;o.imbue(std::locale::classic());o<<std::setprecision(std::numeric_limits<float>::max_digits10)<<"VEYRA_PRESETS 15\n"<<std::quoted(utf8(default_))<<' '<<entries_.size()<<'\n';+ for(auto& p:entries_){const auto& s=p.settings;const auto& m=s.model;const auto& r=s.residual;o<<std::quoted(utf8(p.name))<<' '<<m.intensity<<' '<<m.tone<<' '<<m.structure<<' '<<m.skin<<' '<<m.style<<' '<<m.autoMask<<' '<<m.uiCorrection<<' '<<r.total<<' '<<r.darken<<' '<<r.brighten<<' '<<r.color<<' '<<r.luminance<<' '<<s.nr<<' '<<s.sr<<' '<<s.multiplier<<' '<<int(s.nrPolicy)<<' '<<int(s.flow)<<' '<<int(s.content)<<' '<<s.protection.enabled<<' '<<s.protection.featherPixels;for(auto q:s.protection.regions)o<<' '<<q.left<<' '<<q.top<<' '<<q.right<<' '<<q.bottom;o<<' '<<s.videoSrQuality<<' '<<int(s.frameGenerationBackend)<<' '<<int(s.srTarget)<<' '<<int(s.opticalFlowBackend)<<' '<<s.amdFlowHalfResolution<<' '<<int(s.audioSync)<<' '<<s.audioOffsetMs<<' '<<int(s.nrRuntime)<<' '<<s.captureCompatible<<' '<<s.lowLatency<<' '<<s.forceSdrPreview<<' '<<int(s.captureAudio)<<' '<<s.exportBitrateMbps<<'\n';}return o.str();}bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,std::wstring& def){if(data.size()>65536)return false;std::istringstream in(data);in.imbue(std::locale::classic());std::string magic,d;int version=0;size_t count=0;- if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>14)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;+ if(!(in>>magic>>version)||magic!="VEYRA_PRESETS"||(version<1||version>15)||!(in>>std::quoted(d)>>count)||count>64)return false;def=wide(d);if(!d.empty()&&def.empty())return false;for(size_t i=0;i<count;++i){UserPreset p;std::string n;int policy,flow,content,nr,sr;auto& s=p.settings;auto& m=s.model;auto& r=s.residual;if(!(in>>std::quoted(n)>>m.intensity>>m.tone>>m.structure>>m.skin>>m.style>>m.autoMask>>m.uiCorrection>>r.total>>r.darken>>r.brighten>>r.color>>r.luminance>>nr>>sr>>s.multiplier>>policy>>flow>>content))return false;if(version>=2){int enabled;if(!(in>>enabled>>s.protection.featherPixels)||enabled<0||enabled>1)return false;s.protection.enabled=enabled!=0;@@ -37,6 +37,8 @@ bool PresetStore::parse(const std::string& data,std::vector<UserPreset>& out,stdif(version>=11){int low;if(!(in>>low)||low<0||low>1)return false;s.lowLatency=low!=0;}if(version>=12){int sdr;if(!(in>>sdr)||sdr<0||sdr>1)return false;s.forceSdrPreview=sdr!=0;}if(version>=14){int ingress;if(!(in>>ingress)||ingress<0||ingress>2)return false;s.captureAudio=static_cast<CaptureAudioIngress>(ingress);}+ // v15 appends the export bitrate to the line, so it must be read last.+ if(version>=15){if(!(in>>s.exportBitrateMbps))return false;}p.name=wide(n);if(!nameOk(p.name)||std::any_of(out.begin(),out.end(),[&](auto& a){return a.name==p.name;})||nr<0||nr>1||sr<0||sr>1)return false;s.nr=nr;s.sr=sr;s.nrPolicy=static_cast<pipeline::NrSizePolicy>(policy);s.flow=static_cast<FlowQuality>(flow);s.content=static_cast<ContentRate>(content);if(!s.validate().empty())return false;out.push_back(std::move(p));diff --git a/src/engine/VideoExportJob.cpp b/src/engine/VideoExportJob.cppindex a80ac3b5..92f1d95c 100644--- a/src/engine/VideoExportJob.cpp+++ b/src/engine/VideoExportJob.cpp@@ -3,7 +3,7 @@#include "veyra/source/MediaFileSource.h"#include "veyra/pipeline/EnhanceGraph.h"#include "veyra/pipeline/ResolutionPlan.h"-#include "veyra/sink/NvencD3D12Encoder.h"+#include "veyra/sink/VideoEncoder.h"#include "veyra/gfx/D3D12DeviceContext.h"#include "veyra/gfx/CommandSlotRing.h"#include "veyra/RuntimePaths.h"@@ -38,10 +38,12 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiveyra::log::warn("export",std::format("present-sink frame generation cannot feed the encoder requested={} multiplier={}; substituting the in-graph DLSS path",frameGenerationBackendName(requested),options.fgMultiplier));options.settings.frameGenerationBackend=FrameGenerationBackend::Dlss;}- gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);sink::NvencD3D12Encoder enc;+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;source::MediaFileSource source;pipeline::EnhanceGraph graph(ctx,ring);+ std::unique_ptr<sink::VideoEncoder> encoder;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;uint64_t tailSnapped=0;+ std::wstring encoderName;std::wstring failureReason;auto failAv=[&](const wchar_t* stage,int code){char error[AV_ERROR_MAX_STRING_SIZE]{};av_strerror(code,error,sizeof(error));@@ -55,11 +57,12 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptitry { do {Status st=Status::Ok;gfx::DeviceContextDesc dd;dd.commandSlotCount=6;if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),6,st))break;- if(!ctx.adapter().isNvidia){- progress(0,L"当前视频导出使用 NVIDIA NVENC;尚未实现 AMD AMF 或 Intel 编码后端");- veyra::log::warn("export","export rejected: selected adapter has no NVIDIA NVENC; AMD AMF and Intel encoder backends are not implemented");- break;- }+ // Export runs on every adapter now: NVIDIA uses NVENC (D3D12,+ // zero-copy) and everything else uses the driver's Media Foundation+ // hardware encoder. Features that need NGX/NVOF stay NVIDIA-only and+ // are gated below instead of failing the job.+ const bool nvidiaAdapter=ctx.adapter().isNvidia;+ if(!nvidiaAdapter)veyra::log::info("export",std::format("adapter={} vendor={}; DLSS NR/SR/FG and NVOF are unavailable, encoder falls back to the system Media Foundation hardware MFT",utf8(ctx.adapter().description),ctx.adapter().vendorIdHex));source::SourceOpenDesc od;od.path=input;od.preferHardwareDecode=false;if(!source.open(od)){failureReason=source.errorMessage();break;}auto info=source.info();if(!pipeline::Extent{info.width,info.height}.valid()){progress(0,L"输入尺寸超出GPU单纹理能力");break;}// Bounded metadata scan; decoded pixels are not retained. Rewind the@@ -81,7 +84,16 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptipipeline::EnhanceGraphDesc gd;gd.hdrInput=gd.hdrOutput=info.color.isHdrPath();hdrExport=gd.hdrOutput;gd.captureBitDepth=info.color.pixelFormat==pipeline::SourcePixelFormat::P010?10:info.color.pixelFormat==pipeline::SourcePixelFormat::P016?16:8;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();+ // Adapter gate mirrors the preview rules (EngineController): DLSS NR,+ // DLSS SR and the NVOF guidance need an NVIDIA device; AMD FSR+ // upscaling is the only vendor-neutral video SR we ship. Requesting an+ // unavailable feature must degrade the export, never fail it.+ const bool nvidiaFeatures=nvidiaAdapter;+ const bool srAvailable=resolution.srApplied&&(nvidiaFeatures||options.settings.videoSrQuality==kVideoSrFsr);+ if(options.nr&&!nvidiaFeatures)fgNote+=fgNote.empty()?L"当前显卡不能使用 DLSS NR,本次导出自动关闭 NR":L";当前显卡不能使用 DLSS NR,本次导出自动关闭 NR";+ if(options.sr&&!srAvailable)fgNote+=fgNote.empty()?L"当前显卡不能使用所选超分,本次导出关闭超分":L";当前显卡不能使用所选超分,本次导出关闭超分";+ if(!nvidiaFeatures&&srAvailable)fgNote+=fgNote.empty()?L"本次导出使用 AMD FSR 超分":L";本次导出使用 AMD FSR 超分";+ 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=srAvailable;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaFeatures;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg&&nvidiaFeatures;gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=options.nr&&nvidiaFeatures;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();// One attempt per frame-generation request. A rejected multiplier is a// capability statement, not an infrastructure failure: retry at 2X (the// floor every DLSS-G capable GPU honours) and only then fall back to a@@ -93,6 +105,7 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptifgFailure=graph.failedBackend()==FailedBackend::Fg;graph.shutdown();};+ if(options.fg&&!nvidiaFeatures){options.fg=false;options.fgMultiplier=1;}if(options.fg){startGraph(true,options.fgMultiplier);if(!graphReady&&fgFailure&&options.fgMultiplier>2){@@ -141,9 +154,19 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptiAVPacket* pkt=av_packet_alloc();if(!pkt)return false;if(av_new_packet(pkt,int(size))<0){av_packet_free(&pkt);return false;}memcpy(pkt->data,bytes,size);pkt->stream_index=videoStream->index;pkt->pts=pkt->dts=pts;pkt->duration=1;if(key)pkt->flags|=AV_PKT_FLAG_KEY;av_packet_rescale_ts(pkt,{rate.den,rate.num},videoStream->time_base);const int rc=av_interleaved_write_frame(mux,pkt);av_packet_free(&pkt);if(rc<0)return failAv(L"写入视频帧",rc);++written;audioEndSeconds=(pts+1)*double(rate.den)/rate.num;return writeAudioUntil(audioEndSeconds);};// Must drain before rate/writeAudioUntil/writer leave scope, including cancel/error.- struct EncoderCloser {sink::NvencD3D12Encoder& encoder;~EncoderCloser(){encoder.close();}} closer{enc};- if(!enc.open(ctx,ring,graph,hevc,rate.num,rate.den,writer))break;- auto headers=enc.headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());+ struct EncoderCloser {sink::VideoEncoder* encoder;~EncoderCloser(){if(encoder)encoder->close();}} closer{encoder.get()};+ sink::EncoderConfig encoderConfig;encoderConfig.hevc=hevc;encoderConfig.fpsNum=unsigned(rate.num);encoderConfig.fpsDen=unsigned(rate.den);encoderConfig.bitrateMbps=options.settings.exportBitrateMbps;+ std::wstring encoderDetail;+ encoder=sink::openVideoEncoder(ctx,ring,graph,encoderConfig,writer,encoderDetail);+ if(!encoder){+ progress(0,encoderDetail.empty()?L"没有可用的视频编码器":encoderDetail);+ if(failureReason.empty())failureReason=encoderDetail.empty()?L"没有可用的视频编码器":encoderDetail;+ veyra::log::error("export","no usable video encoder for this adapter/codec");+ break;+ }+ encoderName=encoder->describe();+ veyra::log::info("export",std::format("encoder={} codec={} bitrateMbps={} rate={}/{}",std::string(sink::encoderBackendName(encoder->backend())),hevc?"HEVC":"H264",encoderConfig.bitrateMbps,rate.num,rate.den));+ auto headers=encoder->headers();cp->extradata=static_cast<uint8_t*>(av_mallocz(headers.size()+AV_INPUT_BUFFER_PADDING_SIZE));if(!cp->extradata)break;memcpy(cp->extradata,headers.data(),headers.size());cp->extradata_size=int(headers.size());int muxResult=avio_open(&mux->pb,utf8(partial).c_str(),AVIO_FLAG_WRITE);if(muxResult<0){failAv(L"创建输出文件",muxResult);break;}muxResult=avformat_write_header(mux,nullptr);@@ -181,30 +204,30 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOptifor(uint32_t j=1;j<options.fgMultiplier;++j){pipeline::BatchFrame* item=nullptr;for(uint32_t k=0;k<out.batch.count;++k)if(out.batch.frames[k].subframe==j&&out.batch.frames[k].validity==pipeline::GenerationValidity::Valid)item=&out.batch.frames[k];- if(item){if(!enc.encode(item->lease->slot,true,outputIndex++)){error=true;break;}item->lease->consumerFence=ring.lastSignaledValue();++generatedCount;}- else {if(!lastReal||!enc.encode(lastReal->slot,false,outputIndex++)){error=true;break;}lastReal->consumerFence=ring.lastSignaledValue();++holdCount;}+ if(item){if(!encoder->encode(item->lease->slot,true,outputIndex++)){error=true;break;}item->lease->consumerFence=ring.lastSignaledValue();++generatedCount;}+ else {if(!lastReal||!encoder->encode(lastReal->slot,false,outputIndex++)){error=true;break;}lastReal->consumerFence=ring.lastSignaledValue();++holdCount;}}}if(error)break;auto& real=out.batch.frames[out.batch.count-1];- if(!enc.encode(real.lease->slot,false,outputIndex++)){error=true;break;}+ if(!encoder->encode(real.lease->slot,false,outputIndex++)){error=true;break;}real.lease->consumerFence=ring.lastSignaledValue();lastReal=real.lease;- ++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});progress(info.duration.toDouble()>0?std::clamp((packet.pts.toDouble()-videoOriginSeconds)/info.duration.toDouble(),0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧(D3D12 NVENC)",sourceCount,outputIndex));+ ++sourceCount;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});progress(info.duration.toDouble()>0?std::clamp((packet.pts.toDouble()-videoOriginSeconds)/info.duration.toDouble(),0.0,.99):0,std::format(L"正在导出:{}张源帧 / {}张编码帧({})",sourceCount,outputIndex,encoderName));if(maxFrames&&sourceCount>=maxFrames)break;}if(error||cancel)break;- if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!enc.encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}+ if(options.fg&&lastReal)for(uint32_t j=1;j<options.fgMultiplier;++j){if(!encoder->encode(lastReal->slot,false,outputIndex++)){error=true;break;}++holdCount;}if(error)break;- veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} backend={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,frameGenerationBackendName(options.settings.frameGenerationBackend),utf8(fgNote)));+ veyra::log::info("export-counts",std::format("source={} generated={} hold={} output={} multiplier={} tailSnapped={} backend={} encoder={} bitrateMbps={} note={} (CFR holds are not DLSSG)",sourceCount,generatedCount,holdCount,outputIndex,options.fg?options.fgMultiplier:1,tailSnapped,frameGenerationBackendName(options.settings.frameGenerationBackend),std::string(sink::encoderBackendName(encoder->backend())),options.settings.exportBitrateMbps,utf8(fgNote)));progress(.99,L"正在收尾:等待编码器输出剩余帧");- if(!enc.finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看NVENC诊断";break;}+ if(!encoder->finish()){if(failureReason.empty())failureReason=L"编码器收尾失败,请查看编码器诊断";break;}if(!writeAudioUntil(audioEndSeconds))break;progress(.995,L"正在收尾:写入MP4索引");muxResult=av_write_trailer(mux);if(muxResult<0){failAv(L"写入MP4索引",muxResult);break;}ok=written>0;if(counts)counts({sourceCount,generatedCount,holdCount,uint64_t(written)});}while(false); }catch(const std::exception& e){veyra::log::error("export",std::format("exception: {}",e.what()));failureReason=L"导出异常,请查看诊断";ok=false;}- enc.close();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);+ encoder.reset();if(mux){if(mux->pb){const int rc=avio_closep(&mux->pb);if(rc<0){failAv(L"刷新并关闭输出文件",rc);ok=false;}}avformat_free_context(mux);}if(audioInput)avformat_close_input(&audioInput);av_packet_free(&audioPacket);ring.drainQueue();graph.shutdown();source.close();ring.shutdown();ctx.shutdown();if(ok){progress(.999,L"正在封装和验证输出");@@ -243,8 +266,8 @@ bool exportVideo(const std::wstring& input,const std::wstring& output,PlayerOpti}}if(ok){- std::wstring done=L"视频导出完成,逐帧完整性验证通过";- if(tailSnapped>0)done=std::format(L"视频导出完成,逐帧完整性验证通过(尾部 {} 帧时间戳已按恒定帧率对齐)",tailSnapped);+ std::wstring done=encoderName.empty()?L"视频导出完成,逐帧完整性验证通过":std::format(L"视频导出完成({}),逐帧完整性验证通过",encoderName);+ if(tailSnapped>0)done+=std::format(L"(尾部 {} 帧时间戳已按恒定帧率对齐)",tailSnapped);progress(1,fgNote.empty()?done:fgNote+L";"+done);}else {diff --git a/src/sink/MfVideoEncoder.cpp b/src/sink/MfVideoEncoder.cppnew file mode 100644index 00000000..8268c75d--- /dev/null+++ b/src/sink/MfVideoEncoder.cpp@@ -0,0 +1,692 @@+#include "veyra/sink/VideoEncoder.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/pipeline/GpuPassUtils.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/gfx/CommandSlotRing.h"+#include "veyra/Log.h"++#include <windows.h>+#include <d3d12.h>+#include <strmif.h> // ICodecAPI (codec property set)+#include <codecapi.h>+#include <mfapi.h>+#include <mferror.h>+#include <mfidl.h>+#include <mfobjects.h>+#include <mftransform.h>++#include <algorithm>+#include <atomic>+#include <bit>+#include <chrono>+#include <cstring>+#include <cmath>+#include <format>+#include <thread>+#include <vector>++// Media Foundation hardware encoder for every non-NVIDIA adapter (and the+// fallback path when NVENC refuses a session). The MFT setup sequence -+// MFTEnumEx with MFT_ENUM_FLAG_HARDWARE, async unlock, type negotiation,+// ICodecAPI rate control, event-driven ProcessInput/ProcessOutput, drain on+// EOS - is ported from FFmpeg's libavcodec/mfenc.c (LGPL-2.1-or-later,+// FFmpeg n9.0.1, local source C:\veyra-deps\ffmpeg-ps5-slices-source). Veyra is+// GPLv3 and the port is recorded in THIRD_PARTY_NOTICES.md. Divergence: Veyra+// feeds NV12 from its own D3D12 graph (readback pack) instead of AVFrame, and+// the MFT output is written straight into the MP4 writer.+namespace veyra::sink {+namespace {+using namespace veyra::pipeline;++constexpr int64_t kTicksPerSecond=10000000; // Media Foundation 100ns units+constexpr unsigned kWaitEventTimeoutMs=30000;++// Codec property GUIDs, copied verbatim from the Windows SDK's codecapi.h+// STATIC_CODECAPI_* values (10.0.26100.0). Defining them locally avoids+// <initguid.h>, which would emit every GUID of strmif/codecapi into this+// translation unit, and avoids depending on strmiids/wmcodecdspuuid.+constexpr GUID kPropDefaultBPictureCount{0x8d390aac,0xdc5c,0x4200,{0xb5,0x7f,0x81,0x4d,0x04,0xba,0xba,0xb2}};+constexpr GUID kPropLowLatencyMode{0x9c27891a,0xed7a,0x40e1,{0x88,0xe8,0xb2,0x27,0x27,0xa0,0x24,0xee}};+constexpr GUID kPropGOPSize{0x95f31b26,0x95a4,0x41aa,{0x93,0x03,0x24,0x6a,0x7f,0xc6,0xee,0xf1}};+constexpr GUID kPropQualityVsSpeed{0x98332df8,0x03cd,0x476b,{0x89,0xfa,0x3f,0x9e,0x44,0x2d,0xec,0x9f}};+constexpr GUID kPropMeanBitRate{0xf7222374,0x2144,0x4815,{0xb5,0x50,0xa3,0x7f,0x8e,0x12,0xee,0x52}};+constexpr GUID kPropMaxBitRate{0x9651eae4,0x39b9,0x4ebf,{0x85,0xef,0xd7,0xf4,0x44,0xec,0x74,0x65}};+constexpr GUID kPropBufferSize{0x0db96574,0xb6a4,0x4c8b,{0x81,0x06,0x37,0x73,0xde,0x03,0x10,0xcd}};+constexpr GUID kPropRateControlMode{0x1c0608e9,0x370c,0x4710,{0x8a,0x58,0xcb,0x61,0x81,0xc4,0x24,0x23}};+constexpr GUID kPropCommonQuality{0xfcbf57a3,0x7ea5,0x4b0c,{0x96,0x44,0x69,0xb4,0x0c,0x39,0xc3,0x91}};+constexpr GUID kPropForceKeyFrame{0x398c1b98,0x8353,0x475a,{0x9e,0xf2,0x8f,0x26,0x5d,0x26,0x03,0x45}};++std::string hrName(HRESULT hr){return std::format("0x{:08X}",unsigned(hr));}++std::atomic<int> gMfSessions{0};+bool acquireMediaFoundation(){+ if(gMfSessions.fetch_add(1)==0){+ const HRESULT hr=MFStartup(MF_VERSION,MFSTARTUP_LITE);+ if(FAILED(hr)){+ gMfSessions.fetch_sub(1);+ log::error("mf-encoder",std::format("MFStartup failed hr={}",hrName(hr)));+ return false;+ }+ }+ return true;+}+void releaseMediaFoundation(){if(gMfSessions.fetch_sub(1)==1)MFShutdown();}++std::wstring attributeString(IMFAttributes* attributes,const GUID& key){+ LPWSTR raw=nullptr;UINT32 length=0;+ if(!attributes||FAILED(attributes->GetAllocatedString(key,&raw,&length))||!raw)return {};+ std::wstring value(raw,length);CoTaskMemFree(raw);return value;+}++struct MftCandidate {ComPtr<IMFActivate> activate;std::wstring name;};++std::wstring vendorKeyword(uint32_t vendorId){+ switch(vendorId){+ case 0x10DE:return L"NVIDIA";+ case 0x1002:case 0x1022:return L"AMD";+ case 0x8086:return L"Intel";+ default:return {};+ }+}+bool containsFold(const std::wstring& haystack,const std::wstring& needle){+ if(needle.empty()||haystack.size()<needle.size())return false;+ auto lower=[](wchar_t c){return wchar_t(towlower(c));};+ for(size_t i=0;i+needle.size()<=haystack.size();++i){+ bool match=true;+ for(size_t j=0;j<needle.size();++j)if(lower(haystack[i+j])!=lower(needle[j])){match=false;break;}+ if(match)return true;+ }+ return false;+}++// All hardware MFTs that accept NV12 input and produce the requested codec,+// ordered so the active adapter's own vendor comes first. (mfenc.c:+// MFTEnumEx(MFT_CATEGORY_VIDEO_ENCODER, MFT_ENUM_FLAG_HARDWARE |+// MFT_ENUM_FLAG_SORTANDFILTER, ...); the vendor preference is Veyra's, because+// a machine can carry several vendors' MFTs and only one has the hardware.)+bool listHardwareMfts(bool hevc,uint32_t adapterVendorId,std::vector<MftCandidate>& candidates,std::wstring& detail){+ MFT_REGISTER_TYPE_INFO inputInfo{MFMediaType_Video,MFVideoFormat_NV12};+ MFT_REGISTER_TYPE_INFO outputInfo{MFMediaType_Video,hevc?MFVideoFormat_HEVC:MFVideoFormat_H264};+ IMFActivate** activates=nullptr;UINT32 count=0;+ const HRESULT listed=MFTEnumEx(MFT_CATEGORY_VIDEO_ENCODER,MFT_ENUM_FLAG_HARDWARE|MFT_ENUM_FLAG_SORTANDFILTER,&inputInfo,&outputInfo,&activates,&count);+ if(FAILED(listed)){detail=L"系统编码器枚举失败";log::error("mf-encoder",std::format("MFTEnumEx failed hr={}",hrName(listed)));return false;}+ if(count==0){+ detail=hevc?L"系统里没有可用的 HEVC 硬件编码器":L"系统里没有可用的 H.264 硬件编码器";+ log::warn("mf-encoder","no hardware MFT for the requested codec");CoTaskMemFree(activates);return false;+ }+ const auto keyword=vendorKeyword(adapterVendorId);+ for(UINT32 index=0;index<count;++index){+ const auto name=attributeString(activates[index],MFT_FRIENDLY_NAME_Attribute);+ log::info("mf-encoder",std::format("candidate[{}] {} nv12->{} vendorMatch={}",index,std::string(name.begin(),name.end()),hevc?"HEVC":"H264",containsFold(name,keyword)));+ MftCandidate candidate;candidate.name=name;+ activates[index]->QueryInterface(IID_PPV_ARGS(&candidate.activate));+ if(candidate.activate)candidates.push_back(std::move(candidate));+ }+ for(UINT32 index=0;index<count;++index)activates[index]->Release();+ CoTaskMemFree(activates);+ if(candidates.empty()){detail=L"系统硬件编码器无法激活";return false;}+ std::stable_sort(candidates.begin(),candidates.end(),[&](const MftCandidate& a,const MftCandidate& b){+ return containsFold(a.name,keyword)&&!containsFold(b.name,keyword);+ });+ return true;+}++uint32_t alignUp(uint32_t value,uint32_t alignment){return (value+alignment-1)/alignment*alignment;}++class MfVideoEncoder final : public VideoEncoder {+public:+ ~MfVideoEncoder() override {close();}++ bool open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,const EncoderConfig& config,PacketWriter writer) override;+ std::vector<uint8_t> headers() const override {return extradata_;}+ bool encode(unsigned frameSlot,bool generated,int64_t pts) override;+ bool finish() override;+ void close() override;+ EncoderBackend backend() const override {return EncoderBackend::MediaFoundation;}+ std::wstring describe() const override {+ return hevc_?std::format(L"系统硬件编码 HEVC({})",friendly_):std::format(L"系统硬件编码 H.264({})",friendly_);+ }++private:+ bool setupTypes();+ bool applyRateControl();+ bool readExtradata();+ bool createOutputSample(IMFSample** sample);+ bool waitEvents();+ bool drainOutputs(bool waitForOutput);+ bool writeSample(IMFSample* sample);+ bool convertToNv12(unsigned frameSlot,bool generated);+ bool sampleFromPacked(int64_t pts,IMFSample** sample);++ gfx::D3D12DeviceContext* ctx_=nullptr;+ gfx::CommandSlotRing* ring_=nullptr;+ EnhanceGraph* graph_=nullptr;+ PacketWriter writer_;+ ComPtr<IMFTransform> transform_;+ ComPtr<ICodecAPI> codecApi_;+ ComPtr<IMFMediaEventGenerator> events_;+ DWORD inputId_=0,outputId_=0;+ bool async_=false,needInput_=false,haveOutput_=false,marker_=false;+ bool draining_=false,drainingDone_=false,sampleSent_=false;+ bool outputProvidesSamples_=false;+ MFT_OUTPUT_STREAM_INFO outputInfo_{};+ ComPtr<IMFMediaType> inputType_,outputType_;+ std::vector<uint8_t> extradata_;+ std::wstring friendly_;+ bool hevc_=false;+ uint32_t bitrateMbps_=0;+ unsigned fpsNum_=1,fpsDen_=1;+ uint32_t width_=0,height_=0;+ ComputePass convert_;+ StateTracker states_;+ ComPtr<ID3D12Resource> y_,uv_,yRead_,uvRead_;+ UINT yPitch_=0,uvPitch_=0;+ std::vector<uint8_t> packed_;+ HANDLE fenceEvent_=nullptr;+ bool mfAcquired_=false;+ uint64_t submitted_=0,written_=0;+ uint64_t nextKeyframe_=0;+ uint64_t gopLength_=1;+ uint64_t needInputEvents_=0,haveOutputEvents_=0;+};++bool MfVideoEncoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,const EncoderConfig& config,PacketWriter writer){+ ctx_=&ctx;ring_=˚graph_=&graph;writer_=std::move(writer);+ hevc_=config.hevc;bitrateMbps_=config.bitrateMbps;+ fpsNum_=std::max(1u,config.fpsNum);fpsDen_=std::max(1u,config.fpsDen);+ width_=graph.workWidth();height_=graph.workHeight();+ if(graph.hdrOutput()){+ // The MFT path is 8-bit 4:2:0 only; producing an SDR file from an HDR+ // source without telling the user would be a silent quality lie.+ log::error("mf-encoder","HDR export requires NVENC (HEVC Main10); Media Foundation path refused");+ return false;+ }+ if(width_<16||height_<16||(width_&1)||(height_&1)){+ log::error("mf-encoder",std::format("unsupported extent {}x{} for NV12",width_,height_));+ return false;+ }+ if(!acquireMediaFoundation())return false;+ mfAcquired_=true;+ std::vector<MftCandidate> candidates;std::wstring detail;+ if(!listHardwareMfts(hevc_,config.adapterVendorId,candidates,detail)){+ log::error("mf-encoder",std::format("no hardware MFT: {}",std::string(detail.begin(),detail.end())));+ return false;+ }+ // Negotiate against the candidates in vendor-preference order: an MFT from+ // another vendor's driver enumerates fine but fails with+ // MF_E_HW_MFT_FAILED_START_STREAMING (0xC00D6D76) when it has no device.+ for(auto& candidate:candidates){+ events_.Reset();codecApi_.Reset();inputType_.Reset();outputType_.Reset();extradata_.clear();+ async_=false;needInput_=false;haveOutput_=false;marker_=false;drainingDone_=false;draining_=false;sampleSent_=false;+ ComPtr<IMFTransform> transform;+ if(FAILED(candidate.activate->ActivateObject(IID_PPV_ARGS(&transform)))||!transform){+ log::warn("mf-encoder",std::format("activate failed for {}",std::string(candidate.name.begin(),candidate.name.end())));+ continue;+ }+ transform_=transform;friendly_=candidate.name;inputId_=0;outputId_=0;+ if(FAILED(transform_->GetStreamIDs(1,&inputId_,1,&outputId_))){inputId_=0;outputId_=0;}+ // Async MFTs must be unlocked before the event interface is used+ // (mfenc.c mf_unlock_async); hardware encoders are async-only.+ ComPtr<IMFAttributes> attributes;+ UINT32 async=0;+ if(SUCCEEDED(transform_->GetAttributes(&attributes))&&SUCCEEDED(attributes->GetUINT32(MF_TRANSFORM_ASYNC,&async))&&async){+ attributes->SetUINT32(MF_TRANSFORM_ASYNC_UNLOCK,TRUE);+ if(SUCCEEDED(transform_->QueryInterface(IID_PPV_ARGS(&events_))))async_=true;+ else log::warn("mf-encoder","async MFT without an event generator; continuing synchronously");+ }+ if(FAILED(transform_->QueryInterface(IID_PPV_ARGS(&codecApi_)))){+ log::warn("mf-encoder","no ICodecAPI on this MFT; bitrate settings are unavailable");+ }+ if(applyRateControl()&&setupTypes()&&readExtradata()){+ // ~2 s GOP: the first sample and every GOP boundary are forced,+ // which is what makes vendor MFTs emit their first output+ // (mfenc.c forces a key frame on the first sample and on I-frames).+ gopLength_=std::max<uint64_t>(1,uint64_t(std::max(1u,fpsNum_))*2/std::max(1u,fpsDen_));+ nextKeyframe_=0;+ log::info("mf-encoder",std::format("selected MFT {} codec={} extent={}x{} fps={}/{} bitrate={}Mbps",+ std::string(friendly_.begin(),friendly_.end()),hevc_?"HEVC":"H264",width_,height_,fpsNum_,fpsDen_,bitrateMbps_));+ break;+ }+ log::warn("mf-encoder",std::format("MFT {} refused the encoder contract; trying the next candidate",std::string(friendly_.begin(),friendly_.end())));+ transform_.Reset();events_.Reset();codecApi_.Reset();friendly_.clear();+ }+ if(transform_==nullptr){+ log::error("mf-encoder",std::format("no hardware MFT accepted the contract ({} candidates)",candidates.size()));+ return false;+ }+ if(FAILED(transform_->GetOutputStreamInfo(outputId_,&outputInfo_)))return false;+ outputProvidesSamples_=(outputInfo_.dwFlags&(MFT_OUTPUT_STREAM_PROVIDES_SAMPLES|MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES))!=0;+ // Same NV12 conversion the NVENC path uses; the result is read back because+ // MFTs take system-memory NV12 (no shared D3D12 texture contract).+ std::vector<uint8_t> shader;+ if(!convert_.loadShader("RgbToNv12.dxil",shader)||!convert_.create(ctx.device(),shader,10,1,2))return false;+ for(unsigned i=0;i<8;++i)makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),graph.outputFormat(),cpuHandleOf(convert_,i));+ y_=makeTexture(ctx.device(),width_,height_,DXGI_FORMAT_R8_UNORM,true);+ uv_=makeTexture(ctx.device(),width_/2,height_/2,DXGI_FORMAT_R8G8_UNORM,true);+ if(!y_||!uv_)return false;+ makeUav(ctx.device(),y_.Get(),DXGI_FORMAT_R8_UNORM,cpuHandleOf(convert_,8));+ makeUav(ctx.device(),uv_.Get(),DXGI_FORMAT_R8G8_UNORM,cpuHandleOf(convert_,9));+ auto makeReadback=[&](uint32_t rows,uint32_t rowBytes,ComPtr<ID3D12Resource>& out,UINT& pitch){+ pitch=alignUp(rowBytes,256);+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;+ D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=uint64_t(pitch)*rows;+ bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;+ return SUCCEEDED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&out)));+ };+ if(!makeReadback(height_,width_,yRead_,yPitch_)||!makeReadback(height_/2,width_,uvRead_,uvPitch_))return false;+ packed_.resize(size_t(width_)*height_+size_t(width_)*(height_/2));+ fenceEvent_=CreateEventW(nullptr,FALSE,FALSE,nullptr);+ if(!fenceEvent_)return false;+ if(FAILED(transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0)))return false;+ transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,0);+ transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM,0);+ return true;+}++bool MfVideoEncoder::applyRateControl(){+ if(codecApi_==nullptr)return true;+ // Values must be set before SetOutputType on several MFTs (mfenc.c+ // mf_encv_output_adjust ordering).+ auto set=[&](const GUID& key,VARIANT& value,const char* label){+ const HRESULT hr=codecApi_->SetValue(&key,&value);+ if(FAILED(hr))log::info("mf-encoder",std::format("SetValue {} failed hr={}",label,hrName(hr)));+ return true;+ };+ VARIANT value;VariantInit(&value);value.vt=VT_UI4;+ value.ulVal=0;set(kPropDefaultBPictureCount,value,"BPictureCount");+ value.ulVal=1;set(kPropLowLatencyMode,value,"LowLatencyMode");+ value.ulVal=std::max(1u,fpsNum_*2);set(kPropGOPSize,value,"GOPSize");+ value.ulVal=70;set(kPropQualityVsSpeed,value,"QualityVsSpeed");+ if(bitrateMbps_>0){+ const uint32_t bitsPerSecond=bitrateMbps_*1000000u;+ value.ulVal=bitsPerSecond;set(kPropMeanBitRate,value,"MeanBitRate");+ set(kPropMaxBitRate,value,"MaxBitRate");+ value.ulVal=bitsPerSecond/2;set(kPropBufferSize,value,"BufferSize"); // 0.5 s CPB+ // Peak-constrained VBR: honours the requested average while still+ // allowing short peaks, the same tradeoff as the NVENC VBR path.+ value.ulVal=uint32_t(eAVEncCommonRateControlMode_PeakConstrainedVBR);+ set(kPropRateControlMode,value,"RateControlMode");+ log::info("mf-encoder",std::format("rate control PeakConstrainedVBR target={}Mbps",bitrateMbps_));+ }else{+ value.ulVal=uint32_t(eAVEncCommonRateControlMode_UnconstrainedVBR);+ set(kPropRateControlMode,value,"RateControlMode");+ value.ulVal=75;set(kPropCommonQuality,value,"Quality");+ }+ return true;+}++bool MfVideoEncoder::setupTypes(){+ const auto frameRate=[&](IMFMediaType* type){+ return type->SetUINT64(MF_MT_FRAME_SIZE,(uint64_t(width_)<<32)|height_)==S_OK+ &&type->SetUINT64(MF_MT_FRAME_RATE,(uint64_t(fpsNum_)<<32)|fpsDen_)==S_OK+ &&type->SetUINT32(MF_MT_INTERLACE_MODE,MFVideoInterlace_Progressive)==S_OK+ &&type->SetUINT64(MF_MT_PIXEL_ASPECT_RATIO,(uint64_t(1)<<32)|1)==S_OK;+ };+ bool needInput=true,needOutput=true;+ for(int round=0;round<3&&(needInput||needOutput);++round){+ if(needOutput){+ ComPtr<IMFMediaType> output;+ if(SUCCEEDED(MFCreateMediaType(&output))&&output){+ output->SetGUID(MF_MT_MAJOR_TYPE,MFMediaType_Video);+ output->SetGUID(MF_MT_SUBTYPE,hevc_?MFVideoFormat_HEVC:MFVideoFormat_H264);+ output->SetUINT32(MF_MT_AVG_BITRATE,bitrateMbps_>0?bitrateMbps_*1000000u:(hevc_?20000000u:16000000u));+ output->SetUINT32(MF_MT_MPEG2_PROFILE,hevc_?eAVEncH265VProfile_Main_420_8:eAVEncH264VProfile_High);+ frameRate(output.Get());+ const HRESULT hr=transform_->SetOutputType(outputId_,output.Get(),0);+ if(SUCCEEDED(hr)){outputType_=output;needOutput=false;}+ else if(hr==MF_E_TRANSFORM_TYPE_NOT_SET){log::info("mf-encoder","output type needs the input type first");}+ else{+ // Vendor MFTs often insist on their own type set; adopt the+ // first advertised type and stamp our geometry onto it.+ ComPtr<IMFMediaType> advertised;+ if(SUCCEEDED(transform_->GetOutputAvailableType(outputId_,0,&advertised))&&advertised){+ advertised->SetUINT32(MF_MT_AVG_BITRATE,bitrateMbps_>0?bitrateMbps_*1000000u:(hevc_?20000000u:16000000u));+ frameRate(advertised.Get());+ const HRESULT retry=transform_->SetOutputType(outputId_,advertised.Get(),0);+ if(SUCCEEDED(retry)){outputType_=advertised;needOutput=false;}+ else log::error("mf-encoder",std::format("SetOutputType failed hr={} retry={}",hrName(hr),hrName(retry)));+ }else log::error("mf-encoder",std::format("SetOutputType failed hr={} and no advertised type",hrName(hr)));+ }+ }+ }+ if(needInput){+ ComPtr<IMFMediaType> input;+ if(SUCCEEDED(MFCreateMediaType(&input))&&input){+ input->SetGUID(MF_MT_MAJOR_TYPE,MFMediaType_Video);+ input->SetGUID(MF_MT_SUBTYPE,MFVideoFormat_NV12);+ frameRate(input.Get());+ const HRESULT hr=transform_->SetInputType(inputId_,input.Get(),0);+ if(SUCCEEDED(hr)){inputType_=input;needInput=false;}+ else if(hr==MF_E_TRANSFORM_TYPE_NOT_SET){log::info("mf-encoder","input type needs the output type first");}+ else{+ ComPtr<IMFMediaType> advertised;+ if(SUCCEEDED(transform_->GetInputAvailableType(inputId_,0,&advertised))&&advertised){+ frameRate(advertised.Get());+ const HRESULT retry=transform_->SetInputType(inputId_,advertised.Get(),0);+ if(SUCCEEDED(retry)){inputType_=advertised;needInput=false;}+ else log::error("mf-encoder",std::format("SetInputType failed hr={} retry={}",hrName(hr),hrName(retry)));+ }else log::error("mf-encoder",std::format("SetInputType failed hr={} and no advertised type",hrName(hr)));+ }+ }+ }+ }+ if(needInput||needOutput){+ log::error("mf-encoder",std::format("format negotiation failed input={} output={}",needInput,needOutput));+ return false;+ }+ return true;+}++bool MfVideoEncoder::readExtradata(){+ ComPtr<IMFMediaType> current;+ if(FAILED(transform_->GetOutputCurrentType(outputId_,¤t))||!current){+ log::error("mf-encoder","GetOutputCurrentType failed");+ return false;+ }+ UINT32 size=0;+ if(FAILED(current->GetBlobSize(MF_MT_MPEG_SEQUENCE_HEADER,&size))||size==0){+ log::error("mf-encoder","the MFT did not publish MF_MT_MPEG_SEQUENCE_HEADER (SPS/PPS)");+ return false;+ }+ extradata_.resize(size);+ if(FAILED(current->GetBlob(MF_MT_MPEG_SEQUENCE_HEADER,extradata_.data(),size,nullptr))){+ log::error("mf-encoder","GetBlob(sequence header) failed");+ return false;+ }+ log::info("mf-encoder",std::format("sequence header bytes={}",extradata_.size()));+ return true;+}++bool MfVideoEncoder::createOutputSample(IMFSample** sample){+ *sample=nullptr;+ if(outputProvidesSamples_)return true;+ const DWORD size=outputInfo_.cbSize?outputInfo_.cbSize:size_t(width_)*height_*2;+ ComPtr<IMFMediaBuffer> buffer;+ if(FAILED(MFCreateMemoryBuffer(size,&buffer))){+ log::error("mf-encoder",std::format("MFCreateMemoryBuffer failed size={}",size));+ return false;+ }+ ComPtr<IMFSample> created;+ if(FAILED(MFCreateSample(&created))||FAILED(created->AddBuffer(buffer.Get()))){+ log::error("mf-encoder","MFCreateSample/AddBuffer failed");+ return false;+ }+ *sample=created.Detach();+ return true;+}++bool MfVideoEncoder::waitEvents(){+ const auto start=GetTickCount64();+ for(;;){+ if(needInput_||haveOutput_||drainingDone_||marker_)return true;+ IMFMediaEvent* event=nullptr;+ const HRESULT hr=events_->GetEvent(MF_EVENT_FLAG_NO_WAIT,&event);+ if(hr==MF_E_NO_EVENTS_AVAILABLE){+ if(GetTickCount64()-start>kWaitEventTimeoutMs){+ log::error("mf-encoder","timeout waiting for an encoder MFT event");+ return false;+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(1));+ continue;+ }+ if(FAILED(hr)){+ log::error("mf-encoder",std::format("GetEvent failed hr={}",hrName(hr)));+ return false;+ }+ MediaEventType type=0;+ if(SUCCEEDED(event->GetType(&type))){+ switch(type){+ case METransformNeedInput: if(!draining_)needInput_=true; ++needInputEvents_; break;+ case METransformHaveOutput: haveOutput_=true; ++haveOutputEvents_; break;+ case METransformDrainComplete: drainingDone_=true; break;+ case METransformMarker: marker_=true; break;+ default: break;+ }+ }+ event->Release();+ }+}++bool MfVideoEncoder::writeSample(IMFSample* sample){+ DWORD length=0;+ if(FAILED(sample->GetTotalLength(&length))||length==0)return length==0;+ ComPtr<IMFMediaBuffer> buffer;+ if(FAILED(sample->ConvertToContiguousBuffer(&buffer))){+ log::error("mf-encoder","ConvertToContiguousBuffer failed");+ return false;+ }+ BYTE* data=nullptr;+ if(FAILED(buffer->Lock(&data,nullptr,nullptr))){+ log::error("mf-encoder","IMFMediaBuffer::Lock failed");+ return false;+ }+ LONGLONG time=0;+ if(FAILED(sample->GetSampleTime(&time)))time=0;+ const int64_t index=llround(double(time)*double(fpsNum_)/double(fpsDen_)/double(kTicksPerSecond));+ UINT32 clean=0;+ const bool key=SUCCEEDED(sample->GetUINT32(MFSampleExtension_CleanPoint,&clean))&&clean!=0;+ const bool accepted=writer_(data,length,index,key);+ buffer->Unlock();+ if(!accepted)log::error("mf-encoder",std::format("mux rejected the encoded frame index={} bytes={}",index,length));+ else ++written_;+ return accepted;+}++bool MfVideoEncoder::drainOutputs(bool waitForOutput){+ for(;;){+ if(async_){+ if(!haveOutput_){+ if(!waitForOutput)return true;+ if(!waitEvents())return false;+ if(!haveOutput_)return true;+ }+ }+ // Synchronous MFTs produce one output per input; ProcessOutput is tried+ // once and "need more input" is treated as normal there.+ // MFTs that allocate their own output samples (NVIDIA/AMD hardware MFTs+ // do) replace out.pSample on success; taking our own empty pointer here+ // silently dropped every encoded frame.+ IMFSample* provided=nullptr;+ if(!createOutputSample(&provided))return false;+ MFT_OUTPUT_DATA_BUFFER out{};+ out.dwStreamID=outputId_;+ out.pSample=provided;+ DWORD status=0;+ const HRESULT hr=transform_->ProcessOutput(0,1,&out,&status);+ if(out.pEvents)out.pEvents->Release();+ haveOutput_=false;+ if(hr==MF_E_TRANSFORM_NEED_MORE_INPUT){+ if(provided)provided->Release();+ if(draining_)drainingDone_=true;+ return true;+ }+ if(hr==MF_E_TRANSFORM_STREAM_CHANGE){+ if(provided)provided->Release();+ log::info("mf-encoder","stream change requested; renegotiating types");+ if(!setupTypes()||!readExtradata())return false;+ continue;+ }+ if(FAILED(hr)){+ if(provided)provided->Release();+ log::error("mf-encoder",std::format("ProcessOutput failed hr={}",hrName(hr)));+ return false;+ }+ IMFSample* result=out.pSample?out.pSample:provided;+ if(result!=provided&&provided)provided->Release();+ const bool accepted=result?writeSample(result):true;+ if(result)result->Release();+ if(!accepted)return false;+ if(!async_)return true;+ }+}++bool MfVideoEncoder::convertToNv12(unsigned frameSlot,bool generated){+ Status status=Status::Ok;+ uint32_t slot=0;+ auto* list=ring_->acquireNext(slot,status);+ if(!list)return false;+ auto* color=generated?graph_->generatedFrameResource(frameSlot):graph_->videoFrameResource(frameSlot);+ states_.transition(list,color,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);+ states_.transition(list,y_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ states_.transition(list,uv_.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ const float dims[8]={std::bit_cast<float>(width_),std::bit_cast<float>(height_),0,0,0,0,0,0};+ convert_.bind(list,dims,gpuHandleOf(convert_,frameSlot+(generated?2:0)).ptr,gpuHandleOf(convert_,8).ptr);+ list->Dispatch((width_+15)/16,(height_+15)/16,1);+ states_.uavBarrier(list,y_.Get());+ states_.uavBarrier(list,uv_.Get());+ states_.transition(list,y_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ states_.transition(list,uv_.Get(),D3D12_RESOURCE_STATE_COPY_SOURCE);+ states_.transition(list,yRead_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ states_.transition(list,uvRead_.Get(),D3D12_RESOURCE_STATE_COPY_DEST);+ auto copyPlane=[&](ID3D12Resource* source,ID3D12Resource* destination,UINT pitch,UINT rows,UINT planeWidth){+ D3D12_TEXTURE_COPY_LOCATION from{},to{};+ from.pResource=source;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=0;+ to.pResource=destination;to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;+ to.PlacedFootprint.Footprint.Format=source->GetDesc().Format;+ to.PlacedFootprint.Footprint.Width=planeWidth;+ to.PlacedFootprint.Footprint.Height=rows;+ to.PlacedFootprint.Footprint.Depth=1;+ to.PlacedFootprint.Footprint.RowPitch=pitch;+ list->CopyTextureRegion(&to,0,0,0,&from,nullptr);+ };+ copyPlane(y_.Get(),yRead_.Get(),yPitch_,height_,width_);+ copyPlane(uv_.Get(),uvRead_.Get(),uvPitch_,height_/2,width_/2);+ states_.transition(list,color,D3D12_RESOURCE_STATE_COMMON);+ if(!ring_->submitAndSignal(slot))return false;+ // The slot ring signals the device context's queue fence; waiting on our own+ // (never-signalled) fence here was the first-frame timeout.+ const uint64_t value=ring_->lastSignaledValue();+ if(ctx_->fence()->GetCompletedValue()<value){+ if(FAILED(ctx_->fence()->SetEventOnCompletion(value,fenceEvent_))||WaitForSingleObject(fenceEvent_,10000)!=WAIT_OBJECT_0){+ log::error("mf-encoder",std::format("readback fence wait failed value={}",value));+ return false;+ }+ }+ for(unsigned plane=0;plane<2;++plane){+ void* mapped=nullptr;+ ID3D12Resource* resource=plane?uvRead_.Get():yRead_.Get();+ const UINT pitch=plane?uvPitch_:yPitch_;+ const uint32_t rows=plane?height_/2:height_;+ if(FAILED(resource->Map(0,nullptr,&mapped)))return false;+ uint8_t* destination=plane?packed_.data()+size_t(width_)*height_:packed_.data();+ for(uint32_t row=0;row<rows;++row){+ std::memcpy(destination+size_t(row)*width_,static_cast<const uint8_t*>(mapped)+size_t(row)*pitch,width_);+ }+ resource->Unmap(0,nullptr);+ }+ return true;+}++bool MfVideoEncoder::sampleFromPacked(int64_t pts,IMFSample** sample){+ ComPtr<IMFMediaBuffer> buffer;+ if(FAILED(MFCreateMemoryBuffer(DWORD(packed_.size()),&buffer)))return false;+ BYTE* data=nullptr;+ if(FAILED(buffer->Lock(&data,nullptr,nullptr)))return false;+ std::memcpy(data,packed_.data(),packed_.size());+ buffer->Unlock();+ buffer->SetCurrentLength(DWORD(packed_.size()));+ ComPtr<IMFSample> created;+ if(FAILED(MFCreateSample(&created))||FAILED(created->AddBuffer(buffer.Get())))return false;+ const LONGLONG time=pts*kTicksPerSecond*fpsDen_/fpsNum_;+ const LONGLONG duration=kTicksPerSecond*fpsDen_/fpsNum_;+ created->SetSampleTime(time);+ created->SetSampleDuration(duration);+ if(!sampleSent_)created->SetUINT32(MFSampleExtension_Discontinuity,TRUE);+ *sample=created.Detach();+ return true;+}++bool MfVideoEncoder::encode(unsigned frameSlot,bool generated,int64_t pts){+ if(transform_==nullptr)return false;+ if(uint64_t(std::max<int64_t>(0,pts))>=nextKeyframe_&&codecApi_!=nullptr){+ VARIANT value;VariantInit(&value);value.vt=VT_UI4;value.ulVal=1;+ const HRESULT forced=codecApi_->SetValue(&kPropForceKeyFrame,&value);+ if(FAILED(forced))log::info("mf-encoder",std::format("ForceKeyFrame failed hr={} index={}",hrName(forced),pts));+ nextKeyframe_=uint64_t(std::max<int64_t>(0,pts))+gopLength_;+ }+ if(!convertToNv12(frameSlot,generated))return false;+ IMFSample* sample=nullptr;+ if(!sampleFromPacked(pts,&sample))return false;+ for(;;){+ if(async_){+ if(!waitEvents()){sample->Release();return false;}+ if(!drainOutputs(false)){sample->Release();return false;}+ if(!needInput_)continue;+ }+ const HRESULT hr=transform_->ProcessInput(inputId_,sample,0);+ if(hr==MF_E_NOTACCEPTING){+ if(!drainOutputs(true)){sample->Release();return false;}+ continue;+ }+ if(FAILED(hr)){+ log::error("mf-encoder",std::format("ProcessInput failed hr={}",hrName(hr)));+ sample->Release();+ return false;+ }+ needInput_=false;sampleSent_=true;++submitted_;+ break;+ }+ sample->Release();+ return async_?drainOutputs(false):drainOutputs(true);+}++bool MfVideoEncoder::finish(){+ if(transform_==nullptr)return true;+ if(!draining_){+ const HRESULT hr=transform_->ProcessMessage(MFT_MESSAGE_COMMAND_DRAIN,0);+ if(FAILED(hr))log::warn("mf-encoder",std::format("MFT_MESSAGE_COMMAND_DRAIN failed hr={}",hrName(hr)));+ draining_=true;needInput_=false;+ }+ const auto start=GetTickCount64();+ while(!drainingDone_){+ if(async_){+ if(!waitEvents()){+ log::error("mf-encoder",std::format("drain event wait failed submitted={} written={}",submitted_,written_));+ return false;+ }+ }+ if(!drainOutputs(true)){+ log::error("mf-encoder",std::format("drain output failed submitted={} written={}",submitted_,written_));+ return false;+ }+ if(!async_&&!haveOutput_)drainingDone_=true;+ if(GetTickCount64()-start>kWaitEventTimeoutMs*2){+ log::error("mf-encoder",std::format("drain timeout submitted={}",submitted_));+ return false;+ }+ }+ log::info("mf-encoder",std::format("drained submitted={} written={} needInputEvents={} haveOutputEvents={}",submitted_,written_,needInputEvents_,haveOutputEvents_));+ return true;+}++void MfVideoEncoder::close(){+ if(transform_)transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH,0);+ events_.Reset();+ codecApi_.Reset();+ transform_.Reset();+ inputType_.Reset();outputType_.Reset();+ convert_=ComputePass{};+ y_.Reset();uv_.Reset();yRead_.Reset();uvRead_.Reset();+ if(fenceEvent_){CloseHandle(fenceEvent_);fenceEvent_=nullptr;}+ if(mfAcquired_){releaseMediaFoundation();mfAcquired_=false;}+}+} // namespace++std::unique_ptr<VideoEncoder> createMediaFoundationEncoder(){return std::make_unique<MfVideoEncoder>();}++EncoderCapability queryMediaFoundationEncoder(bool hevc){+ EncoderCapability capability;+ MFT_REGISTER_TYPE_INFO inputInfo{MFMediaType_Video,MFVideoFormat_NV12};+ MFT_REGISTER_TYPE_INFO outputInfo{MFMediaType_Video,hevc?MFVideoFormat_HEVC:MFVideoFormat_H264};+ IMFActivate** activates=nullptr;UINT32 count=0;+ const bool started=SUCCEEDED(MFStartup(MF_VERSION,MFSTARTUP_LITE));+ if(SUCCEEDED(MFTEnumEx(MFT_CATEGORY_VIDEO_ENCODER,MFT_ENUM_FLAG_HARDWARE|MFT_ENUM_FLAG_SORTANDFILTER,&inputInfo,&outputInfo,&activates,&count))&&count>0){+ capability.mediaFoundation=true;+ capability.mediaFoundationName=attributeString(activates[0],MFT_FRIENDLY_NAME_Attribute);+ for(UINT32 index=0;index<count;++index)activates[index]->Release();+ CoTaskMemFree(activates);+ }+ if(started)MFShutdown();+ return capability;+}+} // namespace veyra::sinkdiff --git a/src/sink/NvencD3D12Encoder.cpp b/src/sink/NvencD3D12Encoder.cppindex 83c11caa..fe8629fa 100644--- a/src/sink/NvencD3D12Encoder.cpp+++ b/src/sink/NvencD3D12Encoder.cpp@@ -12,8 +12,9 @@ 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;+ bool hdr=false;bool hevc=false;NV_ENC_BUFFER_FORMAT inputFormat=NV_ENC_BUFFER_FORMAT_NV12;unsigned w=0,h=0;uint64_t submitted=0,completed=0;+ uint32_t bitrateMbps=0;ComPtr<ID3D12Fence> fence;HANDLE event=nullptr;ComputePass convert;StateTracker states;ComPtr<ID3D12Resource> y,uv;PacketWriter writer;std::vector<uint8_t> sequence;@@ -33,8 +34,13 @@ struct NvencD3D12Encoder::Impl {NvencD3D12Encoder::NvencD3D12Encoder():p_(std::make_unique<Impl>()){}NvencD3D12Encoder::~NvencD3D12Encoder(){close();}std::vector<uint8_t> NvencD3D12Encoder::headers()const{return p_->sequence;}-bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,bool hevc,unsigned fpsNum,unsigned fpsDen,PacketWriter writer){+std::wstring NvencD3D12Encoder::describe()const{+ return p_->hevc?L"NVIDIA NVENC HEVC (D3D12)":L"NVIDIA NVENC H.264 (D3D12)";+}+bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,EnhanceGraph& graph,const EncoderConfig& config,PacketWriter writer){+ const bool hevc=config.hevc;const unsigned fpsNum=config.fpsNum,fpsDen=config.fpsDen;auto& p=*p_;p.ctx=&ctx;p.ring=˚p.graph=&graph;p.w=graph.workWidth();p.h=graph.workHeight();p.writer=std::move(writer);+ p.hevc=hevc;p.bitrateMbps=config.bitrateMbps;wchar_t dir[MAX_PATH]{};GetSystemDirectoryW(dir,MAX_PATH);const auto dllPath=std::wstring(dir)+L"\\nvEncodeAPI64.dll";p.dll=LoadLibraryExW(dllPath.c_str(),nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32);if(!p.dll)return false;using Create=NVENCSTATUS(NVENCAPI*)(NV_ENCODE_API_FUNCTION_LIST*);auto create=reinterpret_cast<Create>(GetProcAddress(p.dll,"NvEncodeAPICreateInstance"));@@ -48,13 +54,22 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&// downwards before giving up.// Test-only: pretend the compiled declaration was refused, so the fallback// ladder below still gets exercised on a healthy driver. Never set by the UI.- const bool forcedMiss=GetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",nullptr,0)>0;+ // 1 = skip the first open only (exercises the ladder), 2 = refuse every+ // attempt (exercises the export's Media Foundation fallback). Test-only.+ wchar_t forcedText[8]{};GetEnvironmentVariableW(L"VEYRA_TEST_NVENC_FIRST_OPEN_FAILS",forcedText,8);+ const int forcedMode=_wtoi(forcedText);+ const bool forcedMiss=forcedMode>0;+ const bool forcedMissAll=forcedMode>=2;if(forcedMiss)veyra::log::warn("nvenc","test-only: skipping the first OpenD3D12Session so the apiVersion ladder runs");if(forcedMiss||!p.check(p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder),"OpenD3D12Session")) {const uint32_t fallbackVersions[]={NVENCAPI_MAJOR_VERSION,13u,12u,11u};bool opened=false;uint32_t accepted=0;for(const uint32_t major:fallbackVersions){if(!forcedMiss&&major==NVENCAPI_MAJOR_VERSION)continue; // already refused above+ if(forcedMissAll){+ log::info("nvenc",std::format("test-only: refusing apiVersion={}.0 as well",major));+ continue;+ }open.apiVersion=major;const auto result=p.api.nvEncOpenEncodeSessionEx(&open,&p.encoder);log::info("nvenc",std::format("OpenD3D12Session retry apiVersion={}.0 status={}",major,unsigned(result)));@@ -78,8 +93,24 @@ bool NvencD3D12Encoder::open(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&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;+ preset.presetCfg.frameIntervalP=1;preset.presetCfg.gopLength=120;preset.presetCfg.rcParams.enableLookahead=0;+ if(p.bitrateMbps>0){+ // Explicit user bitrate: VBR with the target as both average and peak,+ // which is what "编码码率" means to users (the VBV cap keeps peaks+ // bounded so the average is actually met).+ const uint32_t bitsPerSecond=p.bitrateMbps*1000000u;+ preset.presetCfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_VBR;+ preset.presetCfg.rcParams.averageBitRate=bitsPerSecond;+ preset.presetCfg.rcParams.maxBitRate=bitsPerSecond;+ // Half-second VBV: long enough for VBR to actually spend the requested+ // budget on complex scenes, short enough that the peak stays bounded.+ preset.presetCfg.rcParams.vbvBufferSize=bitsPerSecond/2;+ preset.presetCfg.rcParams.vbvInitialDelay=preset.presetCfg.rcParams.vbvBufferSize;+ veyra::log::info("nvenc",std::format("rate control VBR target={}Mbps bufferBits={}",p.bitrateMbps,preset.presetCfg.rcParams.vbvBufferSize));+ }else{+ preset.presetCfg.rcParams.rateControlMode=NV_ENC_PARAMS_RC_CONSTQP;+ preset.presetCfg.rcParams.constQP={20,22,22};+ }if(p.hdr){preset.presetCfg.profileGUID=NV_ENC_HEVC_PROFILE_MAIN10_GUID;auto& config=preset.presetCfg.encodeCodecConfig.hevcConfig;diff --git a/src/sink/VideoEncoderFactory.cpp b/src/sink/VideoEncoderFactory.cppnew file mode 100644index 00000000..7c404d96--- /dev/null+++ b/src/sink/VideoEncoderFactory.cpp@@ -0,0 +1,51 @@+#include "veyra/sink/VideoEncoder.h"+#include "veyra/sink/NvencD3D12Encoder.h"+#include "veyra/gfx/D3D12DeviceContext.h"+#include "veyra/pipeline/EnhanceGraph.h"+#include "veyra/Log.h"++#include <format>++namespace veyra::sink {+// Defined in MfVideoEncoder.cpp (kept out of the header: the MFT details are an+// implementation concern of this sink library).+std::unique_ptr<VideoEncoder> createMediaFoundationEncoder();++std::unique_ptr<VideoEncoder> openVideoEncoder(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing& ring,pipeline::EnhanceGraph& graph,+ const EncoderConfig& config,PacketWriter writer,std::wstring& detail){+ detail.clear();+ const bool nvidia=ctx.adapter().isNvidia;+ EncoderConfig request=config;request.adapterVendorId=ctx.adapter().vendorId;+ // HDR (HEVC Main10) has no Media Foundation representation: the MFT path is+ // 8-bit 4:2:0 only, so an HDR export without NVENC fails loudly instead of+ // writing a silently tone-mapped file.+ if(graph.hdrOutput()&&!nvidia){+ detail=L"HDR(10bit)导出需要 NVIDIA NVENC;当前显卡只有 8bit 系统编码器。请关闭 HDR 或换 N 卡导出";+ log::error("export","HDR export refused: the media foundation path is 8-bit only");+ return nullptr;+ }+ // Test-only: force the Media Foundation path on an NVIDIA host so the+ // fallback encoder can be exercised without non-NVIDIA hardware. Never set+ // by the product UI.+ const bool forceMediaFoundation=GetEnvironmentVariableW(L"VEYRA_TEST_FORCE_MF_ENCODER",nullptr,0)>0;+ if(nvidia&&!forceMediaFoundation){+ auto nvenc=std::make_unique<NvencD3D12Encoder>();+ if(nvenc->open(ctx,ring,graph,request,writer)){+ log::info("export",std::format("encoder selected={}",std::string(encoderBackendName(nvenc->backend()))));+ return nvenc;+ }+ // A refused NVENC session (mixed/old nvEncodeAPI64.dll, codec the GPU+ // cannot encode) must not cost the user the whole export while the OS+ // exposes a hardware MFT for the same codec.+ log::warn("export","NVENC session unavailable; falling back to the Media Foundation hardware encoder");+ }+ auto mf=createMediaFoundationEncoder();+ if(mf->open(ctx,ring,graph,request,writer)){+ log::info("export",std::format("encoder selected={}",std::string(encoderBackendName(mf->backend()))));+ return mf;+ }+ detail=nvidia?L"NVIDIA NVENC 与系统硬件编码器都无法初始化;请更新显卡驱动后重试"+ :L"当前显卡没有可用的硬件编码器(系统未提供 H.264/HEVC 编码 MFT);请更新显卡驱动后重试";+ return nullptr;+}+} // namespace veyra::sinkdiff --git a/tests/unit/RepairPresetTests.cpp b/tests/unit/RepairPresetTests.cppindex aa5cccce..01be60e7 100644--- a/tests/unit/RepairPresetTests.cpp+++ b/tests/unit/RepairPresetTests.cpp@@ -42,7 +42,7 @@ bool legacyBackends(const std::filesystem::path& path) {if(version>=7&&(value.audioSync!=AudioSyncMode::Manual||value.audioOffsetMs!=137))return false;if(!store.put(L"legacy",value,true))return false;std::ifstream file(path);std::string magic;int savedVersion=0;file>>magic>>savedVersion;- if(magic!="VEYRA_PRESETS"||savedVersion!=14)return false;+ if(magic!="VEYRA_PRESETS"||savedVersion!=15)return false;PresetStore reloaded(path);if(!reloaded.load()||reloaded.defaultSettings()!=value)return false;}else{@@ -92,6 +92,11 @@ ok=ok&&a.put(L"test",s)&&a.setDefault(0)&&!a.put(L"test",s);PresetStore b(p);ok=auto fsrSr=s;fsrSr.videoSrQuality=veyra::engine::kVideoSrFsr;ok=ok&&b.put(L"FSR SR",fsrSr);PresetStore fsrSrReload(p);ok=ok&&fsrSrReload.load()&&fsrSrReload.entries().back().settings.videoSrQuality==veyra::engine::kVideoSrFsr&&b.erase(1);auto badSr=s;badSr.videoSrQuality=veyra::engine::kVideoSrFsr+1;ok=ok&&!b.put(L"invalid video SR",badSr);+ // Export bitrate round-trips through the preset format (v15) and stays inside+ // the range the encoders accept.+ auto bitrate=s;bitrate.exportBitrateMbps=60;ok=ok&&b.put(L"bitrate 60",bitrate);+ PresetStore bitrateReload(p);ok=ok&&bitrateReload.load()&&bitrateReload.entries().back().settings.exportBitrateMbps==60&&b.erase(1);+ auto badBitrate=s;badBitrate.exportBitrateMbps=301;ok=ok&&!b.put(L"invalid bitrate",badBitrate);auto invalid=s;invalid.model.tone=9;ok=ok&&!b.put(L"bad",invalid)&&b.entries().size()==1&&b.erase(0)&&b.entries().empty();auto badRegion=s;badRegion.protection.regions[0].left=2;ok=ok&&!b.put(L"invalid region",badRegion);// Capture audio ingress: the manual Dolby/DTS selector round-trips and an