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(engine): chain-driven rebuild decision, export chain, preset library
Veyra Goal Agent74415d201269
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 14869720..cc3a404d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -752,7 +752,7 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_link_libraries(veyra_repair_fg_tests PRIVATE veyra_pipeline veyra_sinks veyra_nvof)# Headless quality-core runner (Playbook R3.3): the phase5 gate's quality- add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp)+ add_library(veyra_engine STATIC src/engine/EngineController.cpp src/engine/EngineControllerImage.cpp src/engine/PosterFrame.cpp src/engine/EffectChain.cpp src/engine/PresetLibrary.cpp src/engine/TiledImageProcessor.cpp src/engine/PresetStore.cpp src/engine/VideoPresenter.cpp src/engine/VideoExportJob.cpp src/engine/ExportJobManager.cpp src/engine/Subtitles.cpp src/engine/FgCompatibilityProbe.cpp)target_sources(veyra_pipeline PRIVATE src/guidance/AmdOpticalFlow.cppsrc/guidance/GpuDisOpticalFlow.cpp third_party/gpu-dis/src/gpu/native_strict_dis_provider.cpp)target_include_directories(veyra_pipeline PRIVATE third_party/gpu-dis/src/gpu)@@ -771,6 +771,11 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avformtarget_compile_options(veyra_engine PRIVATE /utf-8)target_compile_definitions(veyra_engine PUBLIC VEYRA_PROJECT_ROOT="${CMAKE_CURRENT_SOURCE_DIR}" VEYRA_SHADER_DIR="${CMAKE_BINARY_DIR}/shaders")target_link_libraries(veyra_engine PUBLIC veyra_pipeline veyra_sources veyra_sinks veyra_ngx veyra_nvof)+ add_executable(veyra_preset_library_tests tests/unit/PresetLibraryTests.cpp src/engine/PresetLibrary.cpp src/engine/EffectChain.cpp)+ target_compile_features(veyra_preset_library_tests PRIVATE cxx_std_20)+ target_include_directories(veyra_preset_library_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ target_link_libraries(veyra_preset_library_tests PRIVATE veyra_base)+add_executable(veyra_effect_chain_tests tests/unit/EffectChainTests.cpp src/engine/EffectChain.cpp)target_compile_features(veyra_effect_chain_tests PRIVATE cxx_std_20)target_include_directories(veyra_effect_chain_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)diff --git a/docs/UI_MIGRATION_EXECUTION_2026-09-25.md b/docs/UI_MIGRATION_EXECUTION_2026-09-25.mdindex be807d58..ea8e9183 100644--- a/docs/UI_MIGRATION_EXECUTION_2026-09-25.md+++ b/docs/UI_MIGRATION_EXECUTION_2026-09-25.md@@ -19,6 +19,9 @@| S1.1 | 合并图描述构建 | 完成 | `checkpoint/ui-mig-s1.1` | 6 处合并为 `describeStages()`;13 项哈希一致 || S1.7 | 快照补字段(宽高比 / 时长 / 封面) | 完成 | `checkpoint/ui-mig-s1.7` | 宽高比与时长实测正确;关键哈希一致 || S1.2+S1.3 | 效果链模型与效果注册表 | 完成 | `checkpoint/ui-mig-s1.2` | 40 项单元检查全过;引擎尚未改用它 |+| S1.4 | 重建判断改由链推导(影子比对) | 完成 | `checkpoint/ui-mig-s1.4` | 6 个 smoke 用例,0 处不一致 |+| S1.5 | 导出携带效果链 | 完成 | `checkpoint/ui-mig-s1.4` | 共享内存版本 2→3,接收端反算校验 |+| S1.6 | 统一预设库 | 完成 | `checkpoint/ui-mig-s1.6` | 33 项单元检查全过;旧文件只读导入 |## 发现并修复的 bug@@ -31,6 +34,21 @@## 日志+### S1.6(2026-09-25)统一预设库+- 新增 `include/veyra/engine/PresetLibrary.h` + `src/engine/PresetLibrary.cpp`:一个存储放全部预设,每个预设用 `contents` 掩码声明自己包含哪些部分(画质链路 / 调色 / 补帧 / 音频偏移),**这正是设计稿里“另存为时勾选要保存的部分”**。+- 列表预设与节点预设用 `kind` 分开,互相不串。+- 内置四个预设(原画 / 流畅 / 均衡 / 极致);内置只读:不能改名、不能删除,但可以复制后改。+- 管理操作:另存(重名可覆盖,覆盖内置会被拒)、改名、复制、删除、设为启动默认。+- `apply()` 只覆盖预设声明包含的部分,其余字段原样保留 —— “只存链路”的预设不会顺手清掉用户的调色。+- `importLegacy()` 用于把旧的 `user-presets.v1` / `nr-presets.v1` 导入:重名的一律跳过,不覆盖用户已有预设。+- 文件格式 `VEYRA_PRESET_LIBRARY 1`,原子写(临时文件 + `MoveFileEx`),损坏文件保留原文并拒绝覆盖。+- 新增 `veyra_preset_library_tests`(33 项检查):内置只读、部分内容保存与套用、完整往返(含每层 NR 参数与节点模式标记)、管理操作与默认项持久化、旧文件导入不覆盖、损坏文件保护。+- **注意**:这一步只是把库建好,界面还没接上;现有 Win32 界面继续用旧的 `PresetStore`。++### S1.4 + S1.5(2026-09-25)重建判断与导出链路+- S1.4:`EngineController` 现在同时计算旧的字段式判断和新的 `requiresGraphRebuild()`,不一致就写 `settings-rebuild` 警告日志,但**仍按旧判断执行**。跑 6 个 settings 类 smoke 用例(master / settings / fg-only / view / output-cap / rollback),0 处不一致。确认后再切换、再删旧判断。+- S1.5:导出的共享内存头从版本 2 升到 3,多带一份 `EffectChain`;工作进程收到后会把链反算回设置并与头部里的设置逐字段比对,不一致直接拒绝任务,避免读到错版布局。+### S1.2 + S1.3(2026-09-25)效果链模型与效果注册表- 新增 `include/veyra/engine/EffectChain.h` + `src/engine/EffectChain.cpp`:- `EffectType` 六种(调色、超分辨率、NR、保护区域、RTX Video HDR、补帧),每种在 `effectCatalog()` 里登记名称、实例上限(调色 6、NR 4、其余 1)、是否可重复、是否必须最后、是否改变分辨率、是否实验;diff --git a/include/veyra/engine/PresetLibrary.h b/include/veyra/engine/PresetLibrary.hnew file mode 100644index 00000000..347bb6ad--- /dev/null+++ b/include/veyra/engine/PresetLibrary.h@@ -0,0 +1,86 @@+#pragma once+#include "veyra/engine/ColorSettings.h"+#include "veyra/engine/EffectChain.h"+#include "veyra/engine/EnhancementSettings.h"+#include <filesystem>+#include <optional>+#include <string>+#include <vector>++namespace veyra::engine {+// One preset library for everything the user can save: the processing chain,+// the colour grade, frame generation and the audio offset. Which of those a+// preset carries is the user's choice at save time (the UI shows checkboxes),+// so an old "NR preset" is simply a preset whose contents are the chain only.+//+// Two kinds are kept apart: list presets describe the fixed product order, node+// presets a hand-built graph. They are never mixed, because switching modes+// rebuilds the pipeline.+enum class PresetContent : uint32_t {+ None = 0,+ Chain = 1u << 0, // stages + their parameters+ Color = 1u << 1, // colour grade+ FrameGeneration = 1u << 2, // multiplier and backend+ Audio = 1u << 3, // sync mode and offset+};+constexpr uint32_t presetContentMask(PresetContent value) { return uint32_t(value); }+inline constexpr uint32_t kPresetAllContent =+ presetContentMask(PresetContent::Chain) | presetContentMask(PresetContent::Color) |+ presetContentMask(PresetContent::FrameGeneration) | presetContentMask(PresetContent::Audio);++// The frame-generation pair a preset can carry. Deliberately smaller than the+// full EnhancementSettings: a preset must never smuggle in capture or export+// fields.+struct PresetFrameGeneration {+ uint32_t multiplier = 2;+ FrameGenerationBackend backend = FrameGenerationBackend::Dlss;+ bool operator==(const PresetFrameGeneration&) const = default;+};++struct PresetEntry {+ std::wstring name;+ std::wstring note;+ ChainMode kind = ChainMode::List;+ bool builtin = false; // read-only: can be copied, never renamed or erased+ uint32_t contents = kPresetAllContent;+ EffectChain chain{};+ ColorSettings color{};+ PresetFrameGeneration fg{};+ AudioSyncMode audioSync = AudioSyncMode::Automatic;+ int32_t audioOffsetMs = 0;+ bool operator==(const PresetEntry&) const = default;+};++class PresetLibrary {+public:+ explicit PresetLibrary(std::filesystem::path path) : path_(std::move(path)) {}+ // Missing file is not an error: the library starts with the built-ins.+ bool load();+ bool save();+ bool put(const PresetEntry& entry, bool replace = false);+ bool rename(size_t index, std::wstring name);+ bool duplicate(size_t index);+ bool erase(size_t index);+ bool setDefault(size_t index);+ const std::optional<size_t> defaultIndex() const;+ // Applies the parts the preset carries onto `settings`, leaving everything+ // else (capture, export, resolution policy) untouched.+ static void apply(const PresetEntry& entry, EnhancementSettings& settings);+ // True when the preset can be applied to a settings struct of this kind.+ static bool matchesKind(const PresetEntry& entry, ChainMode kind) { return entry.kind == kind; }+ const std::vector<PresetEntry>& entries() const { return entries_; }+ const std::wstring& error() const { return error_; }+ bool corrupt() const { return corrupt_; }+ // Imports an existing single-purpose store (the old VEYRA_PRESETS files)+ // as chain-only or colour-only presets. Never overwrites an existing name.+ bool importLegacy(const std::vector<PresetEntry>& entries);+private:+ static bool parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error);+ std::string serialize() const;+ void addBuiltins();+ std::filesystem::path path_;+ std::vector<PresetEntry> entries_;+ std::wstring defaultName_, error_;+ bool corrupt_ = false;+};+}diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 895b390c..f530afcf 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -35,6 +35,7 @@#include "veyra/gfx/CommandSlotRing.h"#include "veyra/RuntimePaths.h"#include "veyra/engine/GraphDescription.h"+#include "veyra/engine/EffectChain.h"#include "veyra/engine/PosterFrame.h"#include <avrt.h>#include <chrono>@@ -861,7 +862,34 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,sconst bool xessFg=presentSinkFrameGeneration(next.settings.frameGenerationBackend);describeStages(stageRequest(next),next.snapshot(),nextDesc);nextDesc.hdrOutput=requested.useHdrPreview(nextDesc.hdrInput,displayHdrActive());- const bool rebuild=gd.videoHdr.enabled!=nextDesc.videoHdr.enabled||gd.nrTemporal!=nextDesc.nrTemporal||(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))||gd.hdrOutput!=nextDesc.hdrOutput||previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.color.enabled!=nextDesc.color.enabled||gd.color.lutNameString()!=nextDesc.color.lutNameString()||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;+ // Legacy field-by-field rebuild decision. It stays until+ // the shadow comparison below shows the chain-derived+ // predicate agrees on every real edit; requiresGraphRebuild()+ // is the source of truth after that.+ const bool legacyRebuild=gd.videoHdr.enabled!=nextDesc.videoHdr.enabled||gd.nrTemporal!=nextDesc.nrTemporal||(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))||gd.hdrOutput!=nextDesc.hdrOutput||previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.color.enabled!=nextDesc.color.enabled||gd.color.lutNameString()!=nextDesc.color.lutNameString()||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;+ // Shadow comparison: same inputs, the chain description and+ // its predicate. A mismatch is a bug in whichever rule is+ // wrong, never something to paper over.+ bool chainRebuild=false;+ {+ const auto previousChain=engine::toChain(previous);+ const auto requestedChain=engine::toChain(requested);+ if(!(previousChain==requestedChain)||gd.enableNr!=nextDesc.enableNr||gd.enableSr!=nextDesc.enableSr||+ gd.enableFg!=nextDesc.enableFg||gd.nrBeforeSr!=nextDesc.nrBeforeSr){+ chainRebuild=engine::requiresGraphRebuild(previous,requested);+ }+ // The size fields are computed from the source extent,+ // which the predicate cannot see; compare them here.+ if(gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||+ gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||+ gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight)chainRebuild=true;+ if(chainRebuild!=legacyRebuild){+ veyra::log::warn("settings-rebuild",std::format(+ "rebuild decision mismatch revision {}->{} legacy={} chain={}; applying the legacy decision and reporting this",+ previous.revision,requested.revision,legacyRebuild,chainRebuild));+ }+ }+ const bool rebuild=legacyRebuild;bool accepted=ring.drainQueue();out={};hasOutput=false;resetRecord->rebuilt=rebuild;markResetStage(diagnostics::ResetStage::Drain);diff --git a/src/engine/ExportJobManager.cpp b/src/engine/ExportJobManager.cppindex d6040d07..d0f4586b 100644--- a/src/engine/ExportJobManager.cpp+++ b/src/engine/ExportJobManager.cpp@@ -1,4 +1,5 @@#include "veyra/engine/ExportJobManager.h"+#include "veyra/engine/EffectChain.h"#include "veyra/engine/VideoExportJob.h"#include "veyra/Log.h"#include "veyra/RuntimePaths.h"@@ -17,8 +18,13 @@ std::string utf8(std::wstring_view value) {}constexpr DWORD magic=0x56585931;struct Shared {- DWORD signature=magic,version=2,bytes=sizeof(Shared);+ // Version 3 carries the effect chain alongside the settings struct. The+ // chain is fixed-capacity and trivially copyable, so it can cross the+ // process boundary; a worker that sees another version refuses the job+ // instead of reading a mismatched layout.+ DWORD signature=magic,version=3,bytes=sizeof(Shared);EnhancementSettings settings;+ EffectChain chain;wchar_t input[32768]{},output[32768]{};unsigned hevc=0,maxFrames=0;int audioStreamIndex=-1;@@ -50,7 +56,7 @@ bool ExportJobManager::start(const std::wstring& input,const std::wstring& outpup_->mapping=CreateFileMappingW(INVALID_HANDLE_VALUE,&sa,PAGE_READWRITE,0,sizeof(Shared),nullptr);if(!p_->mapping)return fail(L"无法创建导出通信资源");p_->shared=static_cast<Shared*>(MapViewOfFile(p_->mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!p_->shared)return fail(L"无法映射导出通信资源");- new(p_->shared) Shared{};auto& s=*p_->shared;s.settings=settings;s.settings.nrPolicy=pipeline::NrSizePolicy::Native;s.hevc=hevc;s.maxFrames=maxFrames;+ new(p_->shared) Shared{};auto& s=*p_->shared;s.settings=settings;s.settings.nrPolicy=pipeline::NrSizePolicy::Native;s.chain=toChain(s.settings);s.hevc=hevc;s.maxFrames=maxFrames;s.audioStreamIndex=audioStreamIndex;wcscpy_s(s.input,input.c_str());wcscpy_s(s.output,output.c_str());p_->job=CreateJobObjectW(nullptr,nullptr);JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;@@ -90,8 +96,13 @@ ExportJobSnapshot ExportJobManager::poll(){}int runExportWorker(HANDLE mapping){auto s=static_cast<Shared*>(MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(Shared)));if(!s)return 1;- if(s->signature!=magic||s->version!=2||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}+ if(s->signature!=magic||s->version!=3||s->bytes!=sizeof(Shared)||s->audioStreamIndex< -1||!s->settings.validate().empty()||s->input[32767]||s->output[32767]){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}Logger::instance().openFile((runtime::logsDirectory()/std::format("export-worker-{}.log",GetCurrentProcessId())).wstring());+ // The chain is the description of record for this job; the settings struct+ // stays the runtime input until the executor consumes chains directly.+ // Re-deriving one from the other must agree, otherwise the job is refused.+ {auto fromChainSettings=s->settings;fromChain(s->chain,fromChainSettings);+ if(fromChainSettings!=s->settings){UnmapViewOfFile(s);CloseHandle(mapping);return 1;}}const auto settings=s->settings;log::info("export-frozen",std::format("revision={} nr={} sr={} multiplier={} intensity={} tone={} structure={} skin={} style={} autoMask={} ui={} total={} darken={} brighten={} color={} luminance={} flow={} content={} nativeNR=true",settings.revision,settings.nr,settings.sr,settings.multiplier,settings.model.intensity,settings.model.tone,settings.model.structure,settings.model.skin,settings.model.style,settings.model.autoMask,settings.model.uiCorrection,settings.residual.total,settings.residual.darken,settings.residual.brighten,settings.residual.color,settings.residual.luminance,int(settings.flow),int(settings.content)));std::atomic<bool> cancel=false,done=false;std::thread monitor([&]{while(!done){if(InterlockedCompareExchange(&s->cancel,0,0))cancel=true;std::this_thread::sleep_for(std::chrono::milliseconds(10));}});auto frameBoundary=[&]{diff --git a/src/engine/PresetLibrary.cpp b/src/engine/PresetLibrary.cppnew file mode 100644index 00000000..19222039--- /dev/null+++ b/src/engine/PresetLibrary.cpp@@ -0,0 +1,289 @@+#include "veyra/engine/PresetLibrary.h"++#include <windows.h>++#include <algorithm>+#include <fstream>+#include <iomanip>+#include <limits>+#include <sstream>++namespace veyra::engine {+namespace {+std::string utf8(const std::wstring& s) {+ if (s.empty()) return {};+ const int n = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, s.data(), int(s.size()), nullptr, 0, nullptr, nullptr);+ std::string r(n > 0 ? size_t(n) : 0, '\0');+ if (n > 0) WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, s.data(), int(s.size()), r.data(), n, nullptr, nullptr);+ return r;+}+std::wstring wide(const std::string& s) {+ if (s.empty()) return {};+ const int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), int(s.size()), nullptr, 0);+ std::wstring r(n > 0 ? size_t(n) : 0, L'\0');+ if (n > 0) MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), int(s.size()), r.data(), n);+ return r;+}+bool nameOk(const std::wstring& s) {+ return !s.empty() && s.size() <= 48 && s.front() != L' ' && s.back() != L' ' &&+ std::none_of(s.begin(), s.end(), [](wchar_t c) { return c < 32; });+}+} // namespace++void PresetLibrary::addBuiltins() {+ auto add = [this](const wchar_t* name, const wchar_t* note, ChainMode kind, bool nr, bool sr,+ uint32_t multiplier, bool hdr, bool color) {+ PresetEntry entry;+ entry.name = name; entry.note = note; entry.kind = kind; entry.builtin = true;+ EnhancementSettings s;+ s.nr = nr; s.sr = sr; s.multiplier = multiplier;+ s.videoHdr.enabled = hdr; s.color.enabled = color;+ entry.chain = toChain(s);+ entry.color = s.color;+ entry.fg = {std::max(2u, s.multiplier), FrameGenerationBackend::Dlss};+ entries_.push_back(std::move(entry));+ };+ if (!entries_.empty()) return;+ // Built-ins are the same in both modes: the chain differs only by order,+ // and a list preset describes the product order by construction.+ add(L"原画", L"所有增强关闭", ChainMode::List, false, false, 1, false, false);+ add(L"流畅", L"超分 2K · 补帧 2X", ChainMode::List, false, true, 2, false, false);+ add(L"均衡", L"超分 4K · NR 1 层 · 补帧 2X", ChainMode::List, true, true, 2, false, false);+ add(L"极致", L"超分 4K · NR 1 层 · HDR · 补帧 2X", ChainMode::List, true, true, 2, true, false);+}++bool PresetLibrary::load() {+ error_.clear();+ addBuiltins();+ if (!std::filesystem::exists(path_)) return true;+ std::error_code ec;+ const auto size = std::filesystem::file_size(path_, ec);+ if (ec || size > 262144) { corrupt_ = true; error_ = L"预设库文件过大,原文件保留"; return false; }+ std::ifstream f(path_, std::ios::binary);+ if (!f) { corrupt_ = true; error_ = L"预设库无法读取,原文件保留"; return false; }+ const std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ std::vector<PresetEntry> loaded;+ std::wstring def, parseError;+ if (!parse(data, loaded, def, parseError)) {+ corrupt_ = true;+ error_ = parseError.empty() ? L"预设库损坏或版本不支持;原文件已保留,禁止覆盖" : parseError;+ return false;+ }+ // The file's own presets replace the built-ins; built-ins are re-added so a+ // user who deleted nothing always sees them.+ entries_ = std::move(loaded);+ defaultName_ = def;+ addBuiltins();+ for (auto& entry : entries_) entry.builtin = entry.builtin || (entry.name == L"原画" || entry.name == L"流畅" || entry.name == L"均衡" || entry.name == L"极致");+ return true;+}++bool PresetLibrary::save() {+ if (corrupt_) { error_ = L"预设库损坏,已拒绝覆盖原文件"; return false; }+ std::error_code ec;+ std::filesystem::create_directories(path_.parent_path(), ec);+ const auto temporary = std::filesystem::path(path_).concat(L".tmp");+ { std::ofstream f(temporary, std::ios::binary | std::ios::trunc); if (!f) { error_ = L"预设库写入失败"; return false; } f << serialize(); if (!f) { error_ = L"预设库写入失败"; return false; } }+ if (!MoveFileExW(temporary.c_str(), path_.c_str(), MOVEFILE_REPLACE_EXISTING)) {+ std::filesystem::remove(temporary, ec);+ error_ = L"预设库替换失败";+ return false;+ }+ return true;+}++bool PresetLibrary::put(const PresetEntry& entry, bool replace) {+ if (!nameOk(entry.name)) { error_ = L"预设名称非法"; return false; }+ const auto found = std::find_if(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == entry.name; });+ if (found != entries_.end()) {+ if (!replace) { error_ = L"同名预设已存在"; return false; }+ if (found->builtin) { error_ = L"内置预设不能覆盖,请换一个名称"; return false; }+ *found = entry;+ return save();+ }+ if (entries_.size() >= 64) { error_ = L"预设数量已达上限"; return false; }+ entries_.push_back(entry);+ return save();+}++bool PresetLibrary::rename(size_t index, std::wstring name) {+ if (index >= entries_.size() || entries_[index].builtin) { error_ = L"内置预设不能改名"; return false; }+ if (!nameOk(name)) { error_ = L"预设名称非法"; return false; }+ if (std::any_of(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == name; })) { error_ = L"同名预设已存在"; return false; }+ if (defaultName_ == entries_[index].name) defaultName_ = name;+ entries_[index].name = std::move(name);+ return save();+}++bool PresetLibrary::duplicate(size_t index) {+ if (index >= entries_.size()) return false;+ if (entries_.size() >= 64) { error_ = L"预设数量已达上限"; return false; }+ PresetEntry copy = entries_[index];+ copy.builtin = false;+ for (int n = 2; n < 100; ++n) {+ std::wstring candidate = copy.name + L" " + std::to_wstring(n);+ if (std::none_of(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == candidate; })) { copy.name = std::move(candidate); break; }+ }+ entries_.insert(entries_.begin() + std::ptrdiff_t(index) + 1, std::move(copy));+ return save();+}++bool PresetLibrary::erase(size_t index) {+ if (index >= entries_.size()) return false;+ if (entries_[index].builtin) { error_ = L"内置预设不能删除;可以复制后修改"; return false; }+ if (defaultName_ == entries_[index].name) defaultName_.clear();+ entries_.erase(entries_.begin() + std::ptrdiff_t(index));+ return save();+}++bool PresetLibrary::setDefault(size_t index) {+ if (index >= entries_.size()) return false;+ defaultName_ = entries_[index].name;+ return save();+}++const std::optional<size_t> PresetLibrary::defaultIndex() const {+ if (defaultName_.empty()) return std::nullopt;+ for (size_t i = 0; i < entries_.size(); ++i) if (entries_[i].name == defaultName_) return i;+ return std::nullopt;+}++void PresetLibrary::apply(const PresetEntry& entry, EnhancementSettings& settings) {+ // fromChain() rewrites every stage field, including the ones this preset+ // does not claim (a colour grade travels inside the chain because the+ // colour stage is part of it). Keep the unclaimed parts exactly as the+ // caller had them, so "chain only" never silently resets a colour look.+ const auto keepColor = settings.color;+ const auto keepMultiplier = settings.multiplier;+ const auto keepBackend = settings.frameGenerationBackend;+ const auto keepAudioSync = settings.audioSync;+ const auto keepAudioOffset = settings.audioOffsetMs;+ if (entry.contents & presetContentMask(PresetContent::Chain)) fromChain(entry.chain, settings);+ if (entry.contents & presetContentMask(PresetContent::Color)) settings.color = entry.color;+ else settings.color = keepColor;+ if (entry.contents & presetContentMask(PresetContent::FrameGeneration)) {+ settings.multiplier = std::max(1u, entry.fg.multiplier);+ settings.frameGenerationBackend = entry.fg.backend;+ } else {+ settings.multiplier = keepMultiplier;+ settings.frameGenerationBackend = keepBackend;+ }+ if (entry.contents & presetContentMask(PresetContent::Audio)) {+ settings.audioSync = entry.audioSync;+ settings.audioOffsetMs = entry.audioOffsetMs;+ } else {+ settings.audioSync = keepAudioSync;+ settings.audioOffsetMs = keepAudioOffset;+ }+}++bool PresetLibrary::importLegacy(const std::vector<PresetEntry>& incoming) {+ bool changed = false;+ for (const auto& entry : incoming) {+ if (!nameOk(entry.name)) continue;+ const bool duplicateName = std::any_of(entries_.begin(), entries_.end(), [&](const PresetEntry& e) { return e.name == entry.name; });+ if (duplicateName) continue; // never overwrite what the user already has+ if (entries_.size() >= 64) break;+ entries_.push_back(entry);+ changed = true;+ }+ return changed ? save() : true;+}++std::string PresetLibrary::serialize() const {+ std::ostringstream o;+ o.imbue(std::locale::classic());+ o << std::setprecision(std::numeric_limits<float>::max_digits10);+ o << "VEYRA_PRESET_LIBRARY 1\n" << std::quoted(utf8(defaultName_)) << ' ' << entries_.size() << '\n';+ for (const auto& e : entries_) {+ o << std::quoted(utf8(e.name)) << ' ' << std::quoted(utf8(e.note)) << ' '+ << int(e.kind) << ' ' << (e.builtin ? 1 : 0) << ' ' << e.contents << ' '+ << e.fg.multiplier << ' ' << int(e.fg.backend) << ' ' << int(e.audioSync) << ' ' << e.audioOffsetMs << ' '+ << e.chain.nodeCount << ' ' << int(e.chain.mode) << ' ' << e.chain.fgMultiplier << ' '+ << (e.chain.fgStrictAdmission ? 1 : 0) << ' ';+ for (uint32_t i = 0; i < e.chain.nodeCount; ++i) {+ const auto& n = e.chain.nodes[i];+ o << int(n.type) << ' ' << (n.enabled ? 1 : 0) << ' ' << n.viewX << ' ' << n.viewY << ' '+ << n.nr.model.intensity << ' ' << n.nr.model.tone << ' ' << n.nr.model.structure << ' '+ << n.nr.model.skin << ' ' << n.nr.model.style << ' ' << n.nr.model.autoMask << ' ' << n.nr.model.uiCorrection << ' '+ << n.nr.residual.total << ' ' << n.nr.residual.darken << ' ' << n.nr.residual.brighten << ' '+ << n.nr.residual.color << ' ' << n.nr.residual.luminance << ' '+ << int(n.nr.runtime) << ' ' << (n.nr.temporal ? 1 : 0) << ' ' << (n.nr.lowLatencyPairing ? 1 : 0) << ' '+ << (n.protection.enabled ? 1 : 0) << ' ' << n.protection.featherPixels;+ for (const auto& r : n.protection.regions) o << ' ' << r.left << ' ' << r.top << ' ' << r.right << ' ' << r.bottom;+ o << ' ' << (n.videoHdr.enabled ? 1 : 0) << ' ' << n.videoHdr.contrast << ' ' << n.videoHdr.saturation << ' '+ << n.videoHdr.middleGray << ' ' << n.videoHdr.peakNits << ' ';+ }+ o << ' ';+ writeColorSettings(o, e.color, utf8(e.color.lutNameString()));+ o << '\n';+ }+ return o.str();+}++bool PresetLibrary::parse(const std::string& data, std::vector<PresetEntry>& out, std::wstring& def, std::wstring& error) {+ if (data.size() > 262144) { error = L"预设库超过 256 KiB"; return false; }+ std::istringstream in(data);+ in.imbue(std::locale::classic());+ std::string magic, quoted;+ int version = 0;+ size_t count = 0;+ if (!(in >> magic >> version) || magic != "VEYRA_PRESET_LIBRARY" || version < 1 || version > 1) { error = L"预设库格式或版本不支持"; return false; }+ if (!(in >> std::quoted(quoted) >> count) || count > 64) { error = L"预设库条目数非法"; return false; }+ def = wide(quoted);+ for (size_t i = 0; i < count; ++i) {+ PresetEntry e;+ std::string name, note;+ int kind = 0, builtin = 0, fgBackend = 0, audioSync = 0, chainMode = 0, strict = 0;+ uint32_t nodeCount = 0;+ if (!(in >> std::quoted(name) >> std::quoted(note) >> kind >> builtin >> e.contents >> e.fg.multiplier >> fgBackend >> audioSync >> e.audioOffsetMs >> nodeCount >> chainMode >> e.chain.fgMultiplier >> strict)) { error = L"预设库头部字段损坏"; return false; }+ if (kind < 0 || kind > 1 || nodeCount > kMaxChainNodes || e.fg.multiplier < 1 || e.fg.multiplier > 6) { error = L"预设库字段超出范围"; return false; }+ e.name = wide(name);+ e.note = wide(note);+ e.kind = static_cast<ChainMode>(kind);+ e.builtin = builtin != 0;+ e.fg.backend = static_cast<FrameGenerationBackend>(fgBackend);+ e.audioSync = static_cast<AudioSyncMode>(audioSync);+ e.chain.nodeCount = nodeCount;+ e.chain.mode = static_cast<ChainMode>(chainMode);+ e.chain.fgStrictAdmission = strict != 0;+ if (!nameOk(e.name)) { error = L"预设库里的名称非法"; return false; }+ if (e.audioOffsetMs < -250 || e.audioOffsetMs > 250) { error = L"预设库音频偏移超出范围"; return false; }+ for (uint32_t n = 0; n < nodeCount; ++n) {+ ChainNode& node = e.chain.nodes[n];+ int type = 0, enabled = 0, runtime = 0, temporal = 0, lowLatency = 0, protEnabled = 0, hdrEnabled = 0;+ if (!(in >> type >> enabled >> node.viewX >> node.viewY+ >> node.nr.model.intensity >> node.nr.model.tone >> node.nr.model.structure >> node.nr.model.skin+ >> node.nr.model.style >> node.nr.model.autoMask >> node.nr.model.uiCorrection+ >> node.nr.residual.total >> node.nr.residual.darken >> node.nr.residual.brighten+ >> node.nr.residual.color >> node.nr.residual.luminance+ >> runtime >> temporal >> lowLatency >> protEnabled >> node.protection.featherPixels)) { error = L"预设库节点字段损坏"; return false; }+ for (auto& r : node.protection.regions) if (!(in >> r.left >> r.top >> r.right >> r.bottom)) { error = L"预设库保护区域损坏"; return false; }+ if (!(in >> hdrEnabled >> node.videoHdr.contrast >> node.videoHdr.saturation >> node.videoHdr.middleGray >> node.videoHdr.peakNits)) { error = L"预设库 HDR 字段损坏"; return false; }+ if (type < 0 || type >= int(EffectType::Count) || enabled < 0 || enabled > 1 || runtime < 0 || runtime > 2 ||+ temporal < 0 || temporal > 1 || lowLatency < 0 || lowLatency > 1 || protEnabled < 0 || protEnabled > 1 || hdrEnabled < 0 || hdrEnabled > 1) {+ error = L"预设库节点取值超出范围"; return false;+ }+ node.type = static_cast<EffectType>(type);+ node.enabled = enabled != 0;+ node.nr.runtime = static_cast<NrRuntime>(runtime);+ node.nr.temporal = temporal != 0;+ node.nr.lowLatencyPairing = lowLatency != 0;+ node.protection.enabled = protEnabled != 0;+ node.videoHdr.enabled = hdrEnabled != 0;+ }+ in >> std::ws;+ std::string lut;+ // 19 is the current colour-block schema: it includes the per-section+ // bypass mask that the writer always emits.+ if (!readColorSettings(in, e.color, lut, 19)) { error = L"预设库调色字段损坏"; return false; }+ if (!lut.empty() && !e.color.setLutName(wide(lut))) { error = L"预设库 LUT 名称非法"; return false; }+ if (auto problem = e.color.validate(); !problem.empty()) { error = L"预设库调色参数超出范围"; return false; }+ if (auto verdict = validateChain(e.chain); !verdict.accepted) { error = L"预设库链路违反顺序规则"; return false; }+ out.push_back(std::move(e));+ }+ in >> std::ws;+ if (!in.eof()) { error = L"预设库尾部有多余数据"; return false; }+ return true;+}+}diff --git a/tests/unit/PresetLibraryTests.cpp b/tests/unit/PresetLibraryTests.cppnew file mode 100644index 00000000..720100cb--- /dev/null+++ b/tests/unit/PresetLibraryTests.cpp@@ -0,0 +1,172 @@+// PresetLibrary: one store for chain/colour/frame-generation/audio content,+// with per-preset contents, built-ins, and safe migration from the old stores.+#include "veyra/engine/PresetLibrary.h"++#include <cstdio>+#include <filesystem>+#include <fstream>++using namespace veyra::engine;++namespace {+int failures = 0;+void check(bool ok, const char* label) {+ std::printf("%s %s\n", ok ? "PASS" : "FAIL", label);+ if (!ok) ++failures;+}+std::filesystem::path scratch(const wchar_t* name) {+ auto dir = std::filesystem::temp_directory_path() / L"veyra-preset-library-tests";+ std::filesystem::create_directories(dir);+ auto path = dir / name;+ std::error_code ec;+ std::filesystem::remove(path, ec);+ return path;+}+EnhancementSettings sample() {+ EnhancementSettings s;+ s.nr = true; s.sr = true; s.multiplier = 4; s.color.enabled = true; s.color.exposure = 0.5f;+ s.videoHdr.enabled = true; s.model.intensity = 0.6f; s.audioOffsetMs = 25;+ s.audioSync = AudioSyncMode::Manual; s.exportBitrateMbps = 77; s.captureCompatible = true;+ return s;+}+} // namespace++int main() {+ // 1. Built-ins exist before anything is saved, and are read-only.+ {+ const auto path = scratch(L"builtins.v1");+ PresetLibrary library(path);+ check(library.load(), "load succeeds when the file is missing");+ check(library.entries().size() == 4, "four built-in presets are present");+ bool allBuiltin = true;+ for (const auto& e : library.entries()) allBuiltin = allBuiltin && e.builtin;+ check(allBuiltin, "built-ins are flagged read-only");+ check(!library.erase(0), "a built-in cannot be erased");+ check(!library.rename(0, L"改个名"), "a built-in cannot be renamed");+ check(library.duplicate(0), "a built-in can be duplicated");+ check(library.entries().size() == 5 && !library.entries()[1].builtin, "the copy is a normal preset");+ }++ // 2. A preset keeps only the parts it claims.+ {+ const auto path = scratch(L"contents.v1");+ PresetLibrary library(path);+ library.load();+ auto settings = sample();+ PresetEntry chainOnly;+ chainOnly.name = L"只存链路";+ chainOnly.contents = presetContentMask(PresetContent::Chain);+ chainOnly.chain = toChain(settings);+ check(library.put(chainOnly), "saving a chain-only preset succeeds");+ if (!library.load()) { std::printf(" parse error: %ls\n", library.error().c_str()); }+ check(library.load(), "reload succeeds");+ auto target = sample();+ target.color.exposure = -1.0f; // must survive: colour is not in the preset+ target.audioOffsetMs = -50; // must survive too+ PresetLibrary::apply(library.entries().back(), target);+ check(target.nr == settings.nr && target.sr == settings.sr && target.multiplier == settings.multiplier,+ "chain-only apply restores the stages");+ check(target.color.exposure == -1.0f, "chain-only apply leaves the colour grade alone");+ check(target.audioOffsetMs == -50, "chain-only apply leaves the audio offset alone");+ }++ // 3. Full preset round trip through the file.+ {+ const auto path = scratch(L"full.v1");+ PresetLibrary library(path);+ library.load();+ auto settings = sample();+ PresetEntry entry;+ entry.name = L"全部";+ entry.note = L"测试";+ entry.kind = ChainMode::Node;+ entry.contents = kPresetAllContent;+ entry.chain = toChain(settings);+ entry.chain.mode = ChainMode::Node;+ entry.chain.nodes[2].nr.model.style = 2;+ entry.chain.nodes[2].nr.temporal = true;+ entry.color = settings.color;+ entry.fg = {4, FrameGenerationBackend::Dlss};+ entry.audioSync = AudioSyncMode::Manual;+ entry.audioOffsetMs = 25;+ check(library.put(entry), "saving a full preset succeeds");+ check(library.load(), "reload succeeds");+ const auto& loaded = library.entries().back();+ check(loaded.name == L"全部" && loaded.note == L"测试", "name and note survive");+ check(loaded.kind == ChainMode::Node && loaded.chain.mode == ChainMode::Node, "the kind survives");+ check(loaded.contents == kPresetAllContent, "the content mask survives");+ check(loaded.chain.nodeCount == entry.chain.nodeCount, "the node count survives");+ check(loaded.chain.nodes[2].nr.model.style == 2 && loaded.chain.nodes[2].nr.temporal,+ "per-layer NR parameters survive");+ check(loaded.color.exposure == entry.color.exposure, "the colour grade survives");+ check(loaded.fg.multiplier == 4, "the frame-generation multiplier survives");+ check(loaded.audioOffsetMs == 25 && loaded.audioSync == AudioSyncMode::Manual, "the audio fields survive");+ auto target = EnhancementSettings{};+ target.exportBitrateMbps = 12;+ PresetLibrary::apply(loaded, target);+ check(target.exportBitrateMbps == 12, "applying a preset never touches export settings");+ check(target.captureCompatible == false, "applying a preset never touches capture settings");+ }++ // 4. Management: rename, duplicate, erase, default.+ {+ const auto path = scratch(L"manage.v1");+ PresetLibrary library(path);+ library.load();+ PresetEntry entry; entry.name = L"甲"; entry.contents = presetContentMask(PresetContent::Chain);+ entry.chain = toChain(sample());+ check(library.put(entry), "put 甲");+ entry.name = L"乙";+ check(library.put(entry), "put 乙");+ const auto index = library.entries().size() - 1;+ check(library.rename(index, L"丙"), "rename 乙 to 丙");+ check(!library.rename(index, L"甲"), "rename refuses a duplicate name");+ check(library.setDefault(index), "set default");+ PresetLibrary reloaded(path);+ check(reloaded.load(), "reload for management checks");+ check(reloaded.defaultIndex().has_value() && reloaded.entries()[*reloaded.defaultIndex()].name == L"丙",+ "the default preset survives a save/load cycle");+ const auto before = reloaded.entries().size();+ check(reloaded.duplicate(*reloaded.defaultIndex()), "duplicate the default");+ check(reloaded.entries().size() == before + 1, "duplicate adds an entry");+ check(reloaded.erase(*reloaded.defaultIndex()), "erase the default");+ check(!reloaded.defaultIndex().has_value(), "erasing the default clears it");+ }++ // 5. Legacy import never overwrites and keeps the chain.+ {+ const auto path = scratch(L"legacy.v1");+ PresetLibrary library(path);+ library.load();+ std::vector<PresetEntry> incoming;+ PresetEntry nrOnly; nrOnly.name = L"夜间游戏"; nrOnly.contents = presetContentMask(PresetContent::Chain);+ nrOnly.chain = toChain(sample());+ incoming.push_back(nrOnly);+ PresetEntry clashing; clashing.name = L"极致"; clashing.builtin = true;+ clashing.contents = presetContentMask(PresetContent::Chain);+ clashing.chain = toChain(EnhancementSettings{});+ incoming.push_back(clashing);+ check(library.importLegacy(incoming), "importing legacy presets succeeds");+ const auto found = std::find_if(library.entries().begin(), library.entries().end(),+ [](const PresetEntry& e) { return e.name == L"极致"; });+ check(found != library.entries().end() && found->builtin, "a name clash keeps the existing preset");+ check(std::any_of(library.entries().begin(), library.entries().end(),+ [](const PresetEntry& e) { return e.name == L"夜间游戏"; }), "the imported preset is present");+ }++ // 6. A corrupt file is preserved, never overwritten.+ {+ const auto path = scratch(L"corrupt.v1");+ { std::ofstream f(path, std::ios::binary); f << "VEYRA_PRESET_LIBRARY 99 nonsense\n"; }+ PresetLibrary library(path);+ check(!library.load(), "a corrupt library reports failure");+ check(library.corrupt(), "the corruption flag is set");+ check(!library.save(), "a corrupt library refuses to overwrite the file");+ std::ifstream f(path, std::ios::binary);+ std::string content((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ check(content.find("nonsense") != std::string::npos, "the original file is untouched");+ }++ std::printf(failures ? "preset library: %d FAILURES\n" : "preset library: all checks passed\n", failures);+ return failures ? 1 : 0;+}