Skip to content

DLSS 5 Neural Rendering for Images & Video with Frame Generation, RTX Video Super Resolution, HDR, and Color Grading

Add files via upload

Merserk09310aa9f7ef
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 178059a..9810dba 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.28)
-project(VisualEnhancer VERSION 16.5.0 LANGUAGES C CXX RC)
+project(VisualEnhancer VERSION 17.0.0 LANGUAGES C CXX RC)
if(NOT WIN32 OR NOT MSVC OR NOT CMAKE_CXX_COMPILER_ARCHITECTURE_ID STREQUAL "x64")
message(FATAL_ERROR "Visual Enhancer requires a Windows MSVC x64 toolchain.")
@@ -154,9 +154,26 @@ if(BUILD_TESTING)
find_package(Qt6 6.12...<6.13 REQUIRED COMPONENTS Test)
get_filename_component(VE_QT_RUNTIME_ROOT "${Qt6_DIR}/../../.." ABSOLUTE)
add_executable(ve_storage_tests "${VE_TEST_ROOT}/storage_tests.cpp")
+ add_executable(ve_dlss_rr_settings_tests "${VE_TEST_ROOT}/dlss_rr_settings_tests.cpp")
+ add_executable(ve_dlss_rr_delivery_smoke "${VE_TEST_ROOT}/dlss_rr_delivery_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_delivery_smoke PRIVATE ve_core Qt6::Test)
+ add_executable(ve_dlss_rr_initialization_smoke "${VE_TEST_ROOT}/dlss_rr_initialization_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_initialization_smoke PRIVATE ve_core Qt6::Test)
+ add_executable(ve_dlss_rr_mixed_preview_smoke "${VE_TEST_ROOT}/dlss_rr_mixed_preview_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_mixed_preview_smoke PRIVATE ve_core Qt6::Test)
+ add_executable(ve_dlss_rr_parked_preview_smoke "${VE_TEST_ROOT}/dlss_rr_parked_preview_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_parked_preview_smoke PRIVATE ve_core Qt6::Test)
+ add_executable(ve_dlss_rr_stream_timing_smoke "${VE_TEST_ROOT}/dlss_rr_stream_timing_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_stream_timing_smoke PRIVATE ve_core Qt6::Test)
+ add_executable(ve_dlss_rr_worker_preview_smoke "${VE_TEST_ROOT}/dlss_rr_worker_preview_smoke.cpp")
+ target_link_libraries(ve_dlss_rr_worker_preview_smoke PRIVATE ve_core Qt6::Test)
+ target_link_libraries(ve_dlss_rr_settings_tests PRIVATE ve_core Qt6::Test)
+ add_test(NAME dlss_rr_settings_contracts COMMAND $<TARGET_FILE:ve_dlss_rr_settings_tests> -o -,txt)
target_link_libraries(ve_storage_tests PRIVATE ve_desktop Qt6::Test)
add_executable(ve_processing_cache_tests "${VE_TEST_ROOT}/processing_cache_tests.cpp")
target_link_libraries(ve_processing_cache_tests PRIVATE ve_desktop Qt6::Test)
+ add_executable(ve_resolution_tests "${VE_TEST_ROOT}/resolution_tests.cpp")
+ target_link_libraries(ve_resolution_tests PRIVATE ve_desktop Qt6::Test)
add_executable(ve_translation_tests "${VE_TEST_ROOT}/translation_tests.cpp")
target_link_libraries(ve_translation_tests PRIVATE ve_desktop Qt6::Test)
target_compile_options(ve_translation_tests PRIVATE /utf-8)
@@ -176,8 +193,9 @@ if(BUILD_TESTING)
target_link_libraries(ve_cli_cancel_probe PRIVATE user32)
add_test(NAME storage_contracts COMMAND $<TARGET_FILE:ve_storage_tests> -o -,txt)
add_test(NAME processing_cache_contracts COMMAND $<TARGET_FILE:ve_processing_cache_tests> -o -,txt)
+ add_test(NAME resolution_contracts COMMAND $<TARGET_FILE:ve_resolution_tests> -o -,txt)
add_test(NAME translation_contracts COMMAND $<TARGET_FILE:ve_translation_tests> -o -,txt)
- set_tests_properties(storage_contracts processing_cache_contracts translation_contracts PROPERTIES
+ set_tests_properties(storage_contracts processing_cache_contracts translation_contracts resolution_contracts PROPERTIES
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_PLUGIN_PATH=${VE_QT_RUNTIME_ROOT}/plugins"
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${VE_QT_RUNTIME_ROOT}/bin"
diff --git a/build.ps1 b/build.ps1
index fee249d..0a277e6 100644
--- a/build.ps1
+++ b/build.ps1
@@ -8,15 +8,28 @@ param(
[string]$Destination,
[string]$NativeBuildRoot,
[string]$RuntimeSource,
+ [switch]$RebuildNative,
[string]$CertificateThumbprint,
[string]$TimestampServer = 'http://timestamp.digicert.com',
- [switch]$MachineCertificateStore
+ [switch]$MachineCertificateStore,
+ [switch]$RequireSignatures,
+ [switch]$ScanDefender,
+ [string]$OutputDirectory,
+ [switch]$StageOnly
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'tools/Toolchain.ps1')
$resolvedQt = Resolve-VeQtRoot $QtRoot
$resolvedBuild = Resolve-VePath $BuildDir $PSScriptRoot
$generator = Get-VeVisualStudioGenerator
+if ($RebuildNative) {
+ $nativeRoot = Join-Path (Split-Path -Parent $PSScriptRoot) 'native (dev)'
+ $nativeShell = (Get-Process -Id $PID).Path
+ foreach ($feature in @('neural_rendering', 'super_resolution', 'ray_reconstruction', 'frame_interpolation', 'rtx_video', 'video_effects')) {
+ Invoke-VeCommand $nativeShell @('-NoProfile', '-File', (Join-Path $nativeRoot "modules/$feature/build_bridge.ps1"), '-NoDeploy')
+ }
+ $NativeBuildRoot = Join-Path $nativeRoot 'modules'
+}
$testOption = if ($Test) { 'ON' } else { 'OFF' }
Write-Host "Building C++23 with $generator and Qt at $resolvedQt"
Invoke-VeCommand 'cmake' @('-S', $PSScriptRoot, '-B', $resolvedBuild, '-G', $generator, '-A', 'x64',
@@ -34,5 +47,6 @@ if ($Deploy) {
-Configuration $Configuration -Destination $Destination -NativeBuildRoot $NativeBuildRoot `
-RuntimeSource $RuntimeSource `
-CertificateThumbprint $CertificateThumbprint `
- -TimestampServer $TimestampServer -MachineCertificateStore:$MachineCertificateStore
+ -TimestampServer $TimestampServer -MachineCertificateStore:$MachineCertificateStore `
+ -RequireSignatures:$RequireSignatures -ScanDefender:$ScanDefender -OutputDirectory $OutputDirectory -StageOnly:$StageOnly
}
diff --git a/src/application/choices.hpp b/src/application/choices.hpp
index 1a1c6b8..3cbdce9 100644
--- a/src/application/choices.hpp
+++ b/src/application/choices.hpp
@@ -28,7 +28,7 @@ inline std::optional<QVariant> staticChoices(Property property) {
}
case Property::nrScaleChoices:
return QJsonDocument::fromJson(
- R"json([{"label":"Source (Original)","value":1.0},{"label":"200%","value":2.0},{"label":"175%","value":1.75},{"label":"150%","value":1.5},{"label":"125%","value":1.25},{"label":"75%","value":0.75},{"label":"50%","value":0.5},{"label":"25%","value":0.25}])json")
+ R"json([{"label":"Source (Original)","value":1.0},{"label":"1600%","value":16.0},{"label":"800%","value":8.0},{"label":"400%","value":4.0},{"label":"300%","value":3.0},{"label":"200%","value":2.0},{"label":"175%","value":1.75},{"label":"150%","value":1.5},{"label":"125%","value":1.25},{"label":"75%","value":0.75},{"label":"50%","value":0.5},{"label":"25%","value":0.25}])json")
.array()
.toVariantList();
case Property::imageScalingFilterChoices:
diff --git a/src/application/controller.cpp b/src/application/controller.cpp
index 2d355b4..97ff94c 100644
--- a/src/application/controller.cpp
+++ b/src/application/controller.cpp
@@ -165,6 +165,11 @@ QVariant AppController::read(Property property) const {
cards.append(QVariantMap{{"id", stage}, {"enabled", active.contains(stage)}});
return cards;
}
+ case Property::rrSettings: {
+ QVariantMap result;const auto values=settings_.values();
+ for(auto it=values.begin();it!=values.end();++it)if(it.key().startsWith("rr_"))result.insert(it.key(),it.value());
+ return result;
+ }
case Property::vfxSettings: {
QVariantMap result;const auto values=settings_.values();
for(auto it=values.begin();it!=values.end();++it)if(it.key().startsWith("vfx_"))result.insert(it.key(),it.value());
@@ -548,6 +553,7 @@ QVariant AppController::execute(Action action, const QVariantList& args) {
case Action::refreshProcessingCache: updateProcessingCache(); return {};
case Action::cleanProcessingCache: updateProcessingCache(true); return {};
case Action::setVfxSetting:
+ case Action::setRrSetting:
case Action::setLutFile:
case Action::setLutAdjustment:
case Action::resetLutAdjustments:
diff --git a/src/application/controller_settings.cpp b/src/application/controller_settings.cpp
index 51ca7e8..2b6218a 100644
--- a/src/application/controller_settings.cpp
+++ b/src/application/controller_settings.cpp
@@ -22,6 +22,12 @@ QVariant AppController::handleSettings(Action action, const QVariantList& args)
settingsChanged();
};
switch (action) {
+ case Action::setRrSetting: {
+ const auto key=args.value(0).toString();
+ if(!key.startsWith("rr_")||!settings_.values().contains(key))throw std::runtime_error("Unknown Ray Reconstruction setting.");
+ auto result=settings_.set(key,args.value(1));if(!result)throw std::runtime_error(result.error().toStdString());
+ settingsChanged();return {};
+ }
case Action::setVfxSetting: {
const auto key=args.value(0).toString();
if(!key.startsWith("vfx_")||!settings_.values().contains(key))throw std::runtime_error("Unknown NVIDIA VFX setting.");
@@ -116,6 +122,8 @@ QVariant AppController::handleSettings(Action action, const QVariantList& args)
if (!order.contains(stage))
throw std::runtime_error("Unknown processing card.");
if (args[1].toBool()) {
+ if(stage=="dlss_ray_reconstruction")active.removeAll("dlss_super_resolution");
+ else if(stage=="dlss_super_resolution")active.removeAll("dlss_ray_reconstruction");
if (!active.contains(stage))
active.append(stage);
} else
diff --git a/src/application/controller_workflows.cpp b/src/application/controller_workflows.cpp
index 4cb3318..7b9ecec 100644
--- a/src/application/controller_workflows.cpp
+++ b/src/application/controller_workflows.cpp
@@ -18,6 +18,7 @@
#include <QNetworkRequest>
#include <QRegularExpression>
#include <QSaveFile>
+#include <QScopeGuard>
#include <QTemporaryDir>
#include <QUuid>
#include <QUrl>
@@ -25,8 +26,27 @@
#include <algorithm>
#include <cmath>
#include <windows.h>
+#include <shlobj.h>
namespace ve {
+namespace {
+bool selectFileInExplorer(const QString& path) {
+ if (path.isEmpty()) return false;
+ const auto initialized = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ if (FAILED(initialized) && initialized != RPC_E_CHANGED_MODE) return false;
+ const auto apartment = qScopeGuard([initialized] {
+ if (SUCCEEDED(initialized)) CoUninitialize();
+ });
+ const auto native = QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath()).toStdWString();
+ PIDLIST_ABSOLUTE raw = nullptr;
+ const auto parsed = SHParseDisplayName(native.c_str(), nullptr, &raw, 0, nullptr);
+ const auto item = qScopeGuard([raw] { CoTaskMemFree(raw); });
+ // A single absolute item with cidl=0 opens its parent and selects it.
+ // No file association is invoked, and paths need no command-line quoting.
+ return SUCCEEDED(parsed) && SUCCEEDED(SHOpenFolderAndSelectItems(raw, 0, nullptr, 0));
+}
+} // namespace
+
void AppController::copyClipboardText(const QString& text, quint64 request, quint32 sequence, int attempts) {
if (shuttingDown_ || request != clipboardRequestRevision_ || GetClipboardSequenceNumber() != sequence) return;
if (OpenClipboard(nullptr)) {
@@ -117,10 +137,20 @@ QVariant AppController::handleWorkflow(Action action, const QVariantList& args)
loadSelected();
}
return {};
- case Action::showSelectedInExplorer: {
- const auto path = context().queue->selectedPath();
- if (!path.isEmpty())
- QProcess::startDetached("explorer.exe", {"/select," + QDir::toNativeSeparators(path)});
+ case Action::showSelectedInExplorer:
+ case Action::showInExplorer: {
+ const auto path = localPath(action == Action::showSelectedInExplorer
+ ? context().queue->selectedPath() : args[0].toString());
+ if (!path.isEmpty()) {
+ // Shell parsing can wait for network locations; keep it off the UI thread.
+ auto future = QtConcurrent::run(&pool_, [this, path] {
+ if (!selectFileInExplorer(path))
+ QMetaObject::invokeMethod(this, [this, path] {
+ if (!shuttingDown_) log(QString("Could not show %1 in File Explorer.").arg(path), "error");
+ }, Qt::QueuedConnection);
+ });
+ (void)future;
+ }
return {};
}
case Action::clearCompletedQueueItems:
@@ -576,6 +606,7 @@ void AppController::preview(double positionMs, bool still) {
const auto info = current.source;
const auto settings = info.video ? videoPreviewSettings(settings_) : settings_;
const bool vfxGenerated=info.video&&settings.stages(true).contains("vfx_frame_generation");
+ const bool nativeRrAfterFi=info.video&&rrNeedsGeneratedHistory(settings.stages(true));
const auto requestedPosition=quantizePlayhead(positionMs>=0?positionMs:current.playheadSeconds*1000,
vfxGenerated?vfxFrameRate(info.fps,vfxSettingsForStages(settings,settings.stages(true))):info.fps,info.duration);
const auto position=quantizePlayhead(requestedPosition.seconds*1000,info.fps,info.duration);
@@ -603,7 +634,7 @@ void AppController::preview(double positionMs, bool still) {
auto future = QtConcurrent::run(&previewPool_, [this, index, path, settings, info, seconds, still,
workflowType, id, generation, settingsRevision,
previewRevision, posterGeneration, position, control,
- fastColor, previewElapsed, vfxGenerated, requestedPosition] {
+ fastColor, previewElapsed, vfxGenerated, nativeRrAfterFi, requestedPosition] {
QJsonObject profile{{"queue_ms", double(previewElapsed.nsecsElapsed()) / 1e6},
{"frame", qint64(position.number)}};
QElapsedTimer phase;
@@ -646,12 +677,13 @@ void AppController::preview(double positionMs, bool still) {
(void)sourceDirectory.filePath("source-preview.mkv");
if (!sourceDirectory.isValid())
throw std::runtime_error("Cannot create the preview source directory.");
- const auto previewSource =
+ const bool rrHistory=stages.contains("dlss_ray_reconstruction");
+ const auto previewSource = rrHistory?path:
extractVideoPreviewSource(path, info, sourceDirectory.path(), seconds, clipSeconds,
false, *control, settings.ffmpeg_device);
Pipeline pipeline;
const auto result =
- pipeline.render({previewSource, clip, settings, workflowType, true, 0, clipSeconds},
+ pipeline.render({previewSource, clip, settings, workflowType, true, rrHistory?seconds:0, clipSeconds},
*control, [this, id](const Progress &progress) {
QMetaObject::invokeMethod(
this,
@@ -675,7 +707,7 @@ void AppController::preview(double positionMs, bool still) {
auto effective = workflowSettings(settings, workflowType, info.video);
const auto estimate = estimatePipeline(info, settings, workflowType);
auto stages = estimate.stages;
- stages.removeAll("frame_generation");
+ if(!nativeRrAfterFi)stages.removeAll("frame_generation");
// Live auxiliary files can change independently of controls;
// retain pixel-based provider identity for those outputs.
const bool immutableOutput =
@@ -693,7 +725,7 @@ void AppController::preview(double positionMs, bool still) {
(!info.hdr || info.transfer == "smpte2084") &&
(stages == QStringList{"neural_model"} || stages == QStringList{"rtx_video_hdr"});
const bool directVideoStill =
- stages.size() == 1 && rotation % 360 == 0 && (!hdrPreview || fastHdr);
+ stages.size() == 1 && !stages.contains("dlss_ray_reconstruction") && rotation % 360 == 0 && (!hdrPreview || fastHdr);
if(info.video&&hasVfxStages(stages)){
auto source=videoFrames_.frame(path,info,position,*control,false,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device!="cpu");input=source.pixels;prefetchSource=true;
const auto identity=source.identity+QByteArray::number(requestedPosition.seconds,'g',17)+"/isolated-vfx/v1";
@@ -738,7 +770,7 @@ void AppController::preview(double positionMs, bool still) {
previewStages_.store(keys.back(), {output, false, false});
}
} else if (info.video && !directVideoStill) {
- if (!hdrPreview || hasVfxStages(stages)) {
+ if (!hdrPreview || hasVfxStages(stages) || stages.contains("dlss_ray_reconstruction")) {
auto source = videoFrames_.frame(path, info, position, *control, false,
gpuOrdinal(settings.ai_gpu_uuid),
settings.ffmpeg_device == "auto");
@@ -752,13 +784,13 @@ void AppController::preview(double positionMs, bool still) {
if (!videoStill_)
videoStill_ = std::make_unique<VideoStillPreview>();
std::vector<TimedImage> temporal;
- if(stages.contains("dlss_super_resolution")||vfxGenerated) {
- const int count=stages.contains("dlss_super_resolution")?(effective.upscale_dlss_mode=="DLAA"?8:18):0;
+ if(!stages.contains("dlss_ray_reconstruction")&&(stages.contains("dlss_super_resolution")||vfxGenerated)) {
+ const int count=reconstructionHistoryFrames(effective,stages);
temporal=videoFrames_.temporalContext(path,info,position,source.absoluteSeconds,count,
- *control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device=="auto",vfxGenerated);
+ *control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device=="auto",vfxGenerated||nativeRrAfterFi);
}
output = videoStill_->process(input, effective, info, stages, previewStages_,
- source.identity, *control,temporal,vfxGenerated?requestedPosition.seconds:-1);
+ source.identity, *control,temporal,vfxGenerated?requestedPosition.seconds+info.presentationStartSeconds():stages.contains("dlss_ray_reconstruction")?source.absoluteSeconds:-1,path);
if(hdrPreview){auto colors=info;colors.hdr=true;if(stages.contains("rtx_video_hdr")){colors.primaries="bt2020";colors.transfer="smpte2084";}output=toneMapVideoPreview(output,colors,*control,settings.ffmpeg_device);}
profile["processing_ms"] = double(phase.nsecsElapsed()) / 1e6;
const auto keys = previewStageKeys(source.identity, effective, info, stages, true,
diff --git a/src/application/qml_facade.hpp b/src/application/qml_facade.hpp
index 7ceafb6..574cd32 100644
--- a/src/application/qml_facade.hpp
+++ b/src/application/qml_facade.hpp
@@ -19,6 +19,7 @@ enum class Property {
nrMode,
workflowStages,
vfxSettings,
+ rrSettings,
vfxStatus,
sharpeningMethodChoices,
ffmpegDeviceChoices,
@@ -223,6 +224,7 @@ enum class Action {
refreshProcessingCache,
cleanProcessingCache,
setVfxSetting,
+ setRrSetting,
setLutFile,
setLutAdjustment,
resetLutAdjustments,
@@ -248,6 +250,7 @@ enum class Action {
clearActiveQueue,
clearSelectedPreviewItem,
showSelectedInExplorer,
+ showInExplorer,
clearCompletedQueueItems,
retryFailedQueueItems,
startActiveBatch,
@@ -282,6 +285,7 @@ class QmlFacade : public QObject {
Q_PROPERTY(QString processingCacheStatus READ processingCacheStatus NOTIFY processingCacheChanged)
Q_PROPERTY(QString processingCacheDetails READ processingCacheDetails NOTIFY processingCacheChanged)
Q_PROPERTY(QVariantMap vfxSettings READ vfxSettings NOTIFY settingsUpdated)
+ Q_PROPERTY(QVariantMap rrSettings READ rrSettings NOTIFY settingsUpdated)
Q_PROPERTY(QString vfxStatus READ vfxStatus NOTIFY vfxStatusChanged)
Q_PROPERTY(QString activeTab READ activeTab WRITE write_activeTab NOTIFY activeTabChanged)
Q_PROPERTY(QString nrMode READ nrMode WRITE write_nrMode NOTIFY nrModeChanged)
@@ -936,6 +940,8 @@ class QmlFacade : public QObject {
QString currentLogPath() const { return read(Property::currentLogPath).toString(); }
QString fullLog() const { return read(Property::fullLog).toString(); }
QVariantMap vfxSettings() const { return read(Property::vfxSettings).toMap(); }
+ QVariantMap rrSettings() const { return read(Property::rrSettings).toMap(); }
+ Q_INVOKABLE void setRrSetting(QString key, QVariant value) { execute(Action::setRrSetting, {key,value}); }
QString vfxStatus() const { return read(Property::vfxStatus).toString(); }
Q_INVOKABLE void setVfxSetting(QString key, QVariant value) { execute(Action::setVfxSetting, {key,value}); }
Q_INVOKABLE void setLutFile(QString a0) { execute(Action::setLutFile, {QVariant::fromValue(a0)}); }
@@ -988,6 +994,7 @@ class QmlFacade : public QObject {
Q_INVOKABLE void clearActiveQueue() { execute(Action::clearActiveQueue, {}); }
Q_INVOKABLE void clearSelectedPreviewItem() { execute(Action::clearSelectedPreviewItem, {}); }
Q_INVOKABLE void showSelectedInExplorer() { execute(Action::showSelectedInExplorer, {}); }
+ Q_INVOKABLE void showInExplorer(QString path) { execute(Action::showInExplorer, {path}); }
Q_INVOKABLE void clearCompletedQueueItems() { execute(Action::clearCompletedQueueItems, {}); }
Q_INVOKABLE void retryFailedQueueItems() { execute(Action::retryFailedQueueItems, {}); }
Q_INVOKABLE void startActiveBatch() { execute(Action::startActiveBatch, {}); }
diff --git a/src/configuration/settings.cpp b/src/configuration/settings.cpp
index b34f9ed..096f5f6 100644
--- a/src/configuration/settings.cpp
+++ b/src/configuration/settings.cpp
@@ -105,6 +105,8 @@ void migrateStages(Settings& settings, bool video) {
if (!order.contains(stage)) {
if (stage == "dlss_super_resolution")
order.insert(std::max<qsizetype>(0, order.indexOf("super_resolution")), stage);
+ else if (stage == "dlss_ray_reconstruction")
+ order.insert(order.indexOf("dlss_super_resolution") + 1, stage);
else if (stage == "rtx_video_hdr")
order.insert(order.indexOf("super_resolution") + 1, stage);
else
@@ -349,6 +351,8 @@ std::expected<void, QString> Settings::validate() const {
for (const auto& stage : enabled)
if (!seen.contains(stage))
return std::unexpected("Pipeline enabled stages contain an unavailable card.");
+ if (enabled.contains("dlss_ray_reconstruction") && enabled.contains("dlss_super_resolution"))
+ return std::unexpected("Select either DLSS Ray Reconstruction or DLSS Super Resolution in one workflow.");
}
const auto map = values();
for (auto it = map.begin(); it != map.end(); ++it) {
@@ -382,7 +386,7 @@ std::expected<void, QString> Settings::validate() const {
high = 4;
} else if (key.endsWith("_width") || key.endsWith("_height")) {
low = key.startsWith("upscale_image_") ? 1 : 2;
- high = 16384;
+ high = 32768;
} else if (key.endsWith("hdr_contrast") || key.endsWith("hdr_saturation") || key == "lut_mix")
high = 200;
else if (key == "upscale_hdr_middle_gray") {
@@ -453,8 +457,10 @@ std::expected<void, QString> Settings::validate() const {
}
if (!QStringList{"PNG", "JPEG", "WebP", "AVIF", "TIFF"}.contains(image_format))
return std::unexpected("Unknown image format.");
- if (!QList<double>{1, 2, 1.75, 1.5, 1.25, .75, .5, .25}.contains(upscaling_factor))
- return std::unexpected("Unknown Neural Rendering scale factor.");
+ // Standard spatial scaling has no model-defined list of ratios. Actual
+ // dimensions are checked against the input at pipeline estimation time.
+ if (!std::isfinite(upscaling_factor) || upscaling_factor <= 0 || upscaling_factor > 32768)
+ return std::unexpected("Standard scale factor must be positive and at most 32768.");
if (nr_scale_method != "Standard" && nr_scale_method != "DLSS")
return std::unexpected("Unknown Neural Rendering scale method.");
if (upscale_mode != "Image" && upscale_mode != "Video")
@@ -609,10 +615,10 @@ std::expected<void, QString> Settings::save(const QString& path) const {
return {};
}
QJsonObject Settings::preset(const QString& name) const {
- auto migrated=*this;migrateStages(migrated,true);auto map = migrated.values();
+ auto migrated=*this;migrateStages(migrated,false);migrateStages(migrated,true);auto map = migrated.values();
map.remove("nr_mask");
return {{"format", "dlss5-visual-enhancer-settings-preset"},
- {"schema_version", 36},
+ {"schema_version", 38},
{"name", name.trimmed()},
{"settings", QJsonObject::fromVariantMap(map)}};
}
@@ -646,7 +652,7 @@ std::expected<QString, QString> Settings::importPreset(const QString& path) {
std::floor(object.value("schema_version").toDouble()) != object.value("schema_version").toDouble())
return std::unexpected(QT_TRANSLATE_NOOP("App", "Preset schema_version must be an integer."));
const int version = object.value("schema_version").toInt();
- if (version < 1 || version > 36)
+ if (version < 1 || version > 38)
return std::unexpected(QT_TRANSLATE_NOOP("App", "Unsupported preset schema version."));
const auto name = object.value("name").toString().trimmed();
if (!object.value("settings").isObject() || name.isEmpty() || name.size() > 120 ||
@@ -724,6 +730,24 @@ std::expected<QString, QString> Settings::importPreset(const QString& path) {
for(const auto& stage:candidate.video_stage_order)if(!canonicalStages(true).contains(stage)&&stage!="nvidia_vfx")return std::unexpected("Pipeline contains an unavailable processing card.");
migrateStages(candidate,true);
}
+ if (version < 37) {
+ // Old presets never enabled RR. Preserve all previous relative ordering.
+ const Settings defaults;
+ candidate.rr_optical_flow_quality=defaults.rr_optical_flow_quality;
+ for(bool video:{false,true}) {
+ auto& order=video?candidate.video_stage_order:candidate.image_stage_order;
+ auto& enabled=video?candidate.video_enabled_stages:candidate.image_enabled_stages;
+ const QSet<QString> seen(order.begin(),order.end()), active(enabled.begin(),enabled.end());
+ if(seen.size()!=order.size()||active.size()!=enabled.size())
+ return std::unexpected("Pipeline contains duplicate processing cards.");
+ for(const auto& stage:order)if(!canonicalStages(video).contains(stage))
+ return std::unexpected("Pipeline contains an unavailable processing card.");
+ for(const auto& stage:enabled)if(!order.contains(stage))
+ return std::unexpected("Pipeline enables an unavailable processing card.");
+ enabled.removeAll("dlss_ray_reconstruction");
+ migrateStages(candidate,video);
+ }
+ }
if (auto valid = candidate.validate(); !valid)
return std::unexpected(valid.error());
*this = std::move(candidate);
diff --git a/src/configuration/settings_fields.inc b/src/configuration/settings_fields.inc
index 3ceb5a8..9f5abf0 100644
--- a/src/configuration/settings_fields.inc
+++ b/src/configuration/settings_fields.inc
@@ -1,12 +1,12 @@
// Persisted processing settings. Shared by the GUI, CLI, and rendering services.
VE_SETTING(QStringList, image_stage_order,
(QStringList{QStringLiteral("neural_model"), QStringLiteral("scale_method"),
- QStringLiteral("dlss_super_resolution"), QStringLiteral("super_resolution"),
+ QStringLiteral("dlss_super_resolution"), QStringLiteral("dlss_ray_reconstruction"), QStringLiteral("super_resolution"),
QStringLiteral("coloring"), QStringLiteral("cas_sharpening"),
QStringLiteral("grain")}))
VE_SETTING(QStringList, video_stage_order,
(QStringList{QStringLiteral("neural_model"), QStringLiteral("scale_method"),
- QStringLiteral("dlss_super_resolution"), QStringLiteral("super_resolution"),
+ QStringLiteral("dlss_super_resolution"), QStringLiteral("dlss_ray_reconstruction"), QStringLiteral("super_resolution"),
QStringLiteral("rtx_video_hdr"), QStringLiteral("frame_generation"),
QStringLiteral("coloring"), QStringLiteral("cas_sharpening"),
QStringLiteral("grain"), QStringLiteral("vfx_vsr"),
@@ -44,6 +44,7 @@ VE_SETTING(QString, nr_style, (QStringLiteral("Style 0")))
VE_SETTING(double, nr_intensity, (1.0))
VE_SETTING(int, nr_passes, (1))
VE_SETTING(QString, nr_optical_flow_quality, (QStringLiteral("High")))
+VE_SETTING(QString, rr_optical_flow_quality, (QStringLiteral("High")))
VE_SETTING(double, local_tone_strength, (1.0))
VE_SETTING(double, local_structure_strength, (1.0))
VE_SETTING(double, skin_structure_strength, (1.0))
diff --git a/src/console/cli.cpp b/src/console/cli.cpp
index 0008272..ac1e7cb 100644
--- a/src/console/cli.cpp
+++ b/src/console/cli.cpp
@@ -37,7 +37,7 @@ void json(const QJsonObject& value) {
void help(const QString& command = {}) {
output << "Visual Enhancer for images and videos, from your terminal.\n\n"
"Usage: VE_CLI.exe COMMAND [INPUT ...] [OPTIONS]\n\n"
- "Commands: render, upscale, interpolate, devices\n";
+ "Commands: render, reconstruct, upscale, interpolate, devices\n";
if (command == "devices")
output << " --json Write GPU information as JSON\n";
else if (!command.isEmpty()) {
@@ -56,6 +56,9 @@ void help(const QString& command = {}) {
output << " --format png|jpeg|webp|avif|tiff\n";
if (command == "render")
output << " --style 0|1|2\n --strength 0..2\n";
+ if (command == "reconstruct")
+ output << " Native-resolution (1x) Ray Reconstruction\n"
+ " --flow-quality high|medium|low Video NVOFA quality\n";
if (command == "upscale")
output << " --engine rtx|dlss\n --scale FACTOR RTX scale factor, at least 1\n "
"--size WIDTHxHEIGHT Exact RTX dimensions\n --mode "
@@ -76,7 +79,7 @@ struct Arguments {
Arguments parse(QStringList values) {
Arguments result;
result.command = values.takeFirst();
- if (!QStringList{"render", "upscale", "interpolate", "devices"}.contains(result.command))
+ if (!QStringList{"render", "reconstruct", "upscale", "interpolate", "devices"}.contains(result.command))
throw UsageError("Unknown command: " + result.command);
const QSet<QString> switches{"--json", "--quiet", "--dry-run", "--recursive"};
QSet<QString> options{"--output", "--preset", "--gpu", "--codec", "--container", "--quality"};
@@ -84,6 +87,8 @@ Arguments parse(QStringList values) {
options.insert("--format");
if (result.command == "render")
options.unite({"--style", "--strength"});
+ if (result.command == "reconstruct")
+ options.insert("--flow-quality");
if (result.command == "upscale")
options.unite({"--engine", "--scale", "--size", "--mode"});
if (result.command == "interpolate")
@@ -157,6 +162,10 @@ Settings settingsFor(const Arguments& args, const QStringList& paths) {
choice(args, "--style", {{"0", "Style 0"}, {"1", "Style 1"}, {"2", "Style 2"}});
if (args.options.contains("--strength"))
settings.nr_intensity = number(args.options.value("--strength"), "--strength");
+ } else if (args.command == "reconstruct") {
+ settings.image_enabled_stages=settings.video_enabled_stages={"dlss_ray_reconstruction"};
+ if(args.options.contains("--flow-quality"))
+ settings.rr_optical_flow_quality=choice(args,"--flow-quality",{{"high","High"},{"medium","Medium"},{"low","Low"}});
} else if (args.command == "upscale") {
if (args.options.contains("--engine"))
settings.upscale_image_engine = settings.upscale_engine =
@@ -191,10 +200,10 @@ Settings settingsFor(const Arguments& args, const QStringList& paths) {
if (args.options.contains("--size")) {
const auto match = QRegularExpression("^(\\d+)[xX](\\d+)$").match(args.options.value("--size"));
if (!match.hasMatch())
- throw UsageError("Use WIDTHxHEIGHT, with each dimension from 2 to 16384.");
+ throw UsageError("Use WIDTHxHEIGHT, with each dimension from 2 to 32768.");
const int width = match.captured(1).toInt(), height = match.captured(2).toInt();
- if (std::min(width, height) < 2 || std::max(width, height) > 16384)
- throw UsageError("Use WIDTHxHEIGHT, with each dimension from 2 to 16384.");
+ if (std::min(width, height) < 2 || std::max(width, height) > 32768)
+ throw UsageError("Use WIDTHxHEIGHT, with each dimension from 2 to 32768.");
settings.upscale_image_size_mode = settings.upscale_size_mode = "Custom dimensions";
settings.upscale_image_width = settings.upscale_width = width;
settings.upscale_image_height = settings.upscale_height = height;
diff --git a/src/desktop/qml/components/BatchQueueDrawer.qml b/src/desktop/qml/components/BatchQueueDrawer.qml
index bdbed64..7c86fa1 100644
--- a/src/desktop/qml/components/BatchQueueDrawer.qml
+++ b/src/desktop/qml/components/BatchQueueDrawer.qml
@@ -543,8 +543,8 @@ Rectangle {
closePolicy: QQC2.Popup.CloseOnEscape | QQC2.Popup.CloseOnPressOutside
background: Rectangle { color: Theme.bgSurface; radius: Theme.radiusMedium; border.color: Theme.borderActive }
RowAction { text: qsTranslate("App", "Preview file"); menuIcon: "preview"; enabled: drawer.canModify; onTriggered: { if (drawer.appBridge) drawer.appBridge.selectQueueItem(queueRow.index) } }
- RowAction { text: qsTranslate("App", "Open source folder"); menuIcon: "folder"; onTriggered: { if (drawer.appBridge) drawer.appBridge.openFolder(queueRow.inputPath) } }
- RowAction { objectName: "queueRevealOutput"; text: qsTranslate("App", "Show output in Explorer"); menuIcon: "reveal_in_explorer"; enabled: queueRow.outputPath !== ""; onTriggered: { if (drawer.appBridge) drawer.appBridge.openFolder(queueRow.outputPath) } }
+ RowAction { objectName: "queueRevealInput"; text: qsTranslate("App", "Show input in Explorer"); menuIcon: "reveal_in_explorer"; onTriggered: { if (drawer.appBridge) drawer.appBridge.showInExplorer(queueRow.inputPath) } }
+ RowAction { objectName: "queueRevealOutput"; text: qsTranslate("App", "Show output in Explorer"); menuIcon: "reveal_in_explorer"; enabled: queueRow.outputPath !== ""; onTriggered: { if (drawer.appBridge) drawer.appBridge.showInExplorer(queueRow.outputPath) } }
QQC2.MenuSeparator { contentItem: Rectangle { implicitHeight: 1; color: Theme.borderSubtle } }
RowAction { objectName: "queueRemoveItem"; text: qsTranslate("App", "Remove from queue"); menuIcon: "trash"; enabled: drawer.canModify; onTriggered: { if (drawer.appBridge) drawer.appBridge.removeQueueItem(queueRow.index) } }
}
diff --git a/src/desktop/qml/components/RayReconstructionControls.qml b/src/desktop/qml/components/RayReconstructionControls.qml
new file mode 100644
index 0000000..21f2b99
--- /dev/null
+++ b/src/desktop/qml/components/RayReconstructionControls.qml
@@ -0,0 +1,21 @@
+import QtQuick
+import ".."
+import "../controls"
+
+Column {
+ id: root
+ property var appBridge: null
+ readonly property bool isImage: appBridge ? appBridge.nrMode === "Image" : true
+ readonly property var values: appBridge ? appBridge.rrSettings : ({})
+ width: parent ? parent.width : 320
+ spacing: 12
+ AppComboBox {
+ objectName: "rrOpticalFlowQuality"
+ width: parent.width
+ visible: !root.isImage
+ label: qsTranslate("App", "Optical Flow Quality")
+ model: appBridge ? appBridge.opticalFlowQualityChoices : ["High", "Medium", "Low"]
+ currentValue: root.values.rr_optical_flow_quality || "High"
+ onActivated: v => { if (appBridge) appBridge.setRrSetting("rr_optical_flow_quality", v) }
+ }
+}
diff --git a/src/desktop/qml/components/WorkflowStageCard.qml b/src/desktop/qml/components/WorkflowStageCard.qml
index c9c9c06..f6f93b9 100644
--- a/src/desktop/qml/components/WorkflowStageCard.qml
+++ b/src/desktop/qml/components/WorkflowStageCard.qml
@@ -11,7 +11,10 @@ Item {
property int stageIndex: 0
property int stageCount: 0
property var stageRepeater: null
+ property bool collapsible: true
+ property bool hasControls: true
property bool collapsed: true
+ readonly property bool expanded: hasControls && (!collapsible || !collapsed)
property real dragOffset: 0
property real slotOffset: 0
property int dragTarget: stageIndex
@@ -23,7 +26,7 @@ Item {
signal dragFinished(string stageId, int targetIndex)
implicitWidth: 320
- implicitHeight: header.height + (collapsed ? 0 : contentContainer.childrenRect.height + 24)
+ implicitHeight: header.height + (expanded ? contentContainer.childrenRect.height + 24 : 0)
z: dragging ? 100 : 0
scale: dragging ? 1.018 : 1.0
transform: [
@@ -67,7 +70,7 @@ Item {
Text {
id: titleText
- width: Math.max(70, parent.width - 40 - 22 * 3 - 3 * 4)
+ width: Math.max(70, parent.width - 40 - 22 * (card.collapsible ? 3 : 2) - 3 * (card.collapsible ? 4 : 3))
height: parent.height
verticalAlignment: Text.AlignVCenter
text: card.title
@@ -79,7 +82,7 @@ Item {
MouseArea {
anchors.fill: parent
cursorShape: Qt.OpenHandCursor
- onClicked: card.collapsed = !card.collapsed
+ onClicked: { if (card.collapsible) card.collapsed = !card.collapsed }
}
}
@@ -106,11 +109,13 @@ Item {
}
}
AppIconButton {
+ visible: card.collapsible
+ enabled: card.collapsible
iconName: card.collapsed ? "chevron_right" : "chevron_left"
buttonSize: 22
anchors.verticalCenter: parent.verticalCenter
tooltipText: (card.collapsed ? qsTranslate("App", "Expand %1") : qsTranslate("App", "Collapse %1")).arg(card.title)
- onClicked: card.collapsed = !card.collapsed
+ onClicked: { if (card.collapsible) card.collapsed = !card.collapsed }
}
DragHandler {
@@ -160,7 +165,7 @@ Item {
}
Rectangle {
- visible: !card.collapsed
+ visible: card.expanded
x: 12
y: header.height
width: parent.width - 24
@@ -169,7 +174,7 @@ Item {
}
Item {
id: contentContainer
- visible: !card.collapsed
+ visible: card.expanded
x: 12
y: header.height + 12
width: parent.width - 24
diff --git a/src/desktop/qml/views/NeuralRenderingView.qml b/src/desktop/qml/views/NeuralRenderingView.qml
index 94faf24..a354fba 100644
--- a/src/desktop/qml/views/NeuralRenderingView.qml
+++ b/src/desktop/qml/views/NeuralRenderingView.qml
@@ -68,6 +68,7 @@ Item {
if (id === "neural_model") return qsTranslate("App", "DLSS Neural Rendering")
if (id === "scale_method") return qsTranslate("App", "Scaling")
if (id === "dlss_super_resolution") return qsTranslate("App", "DLSS Super Resolution")
+ if (id === "dlss_ray_reconstruction") return qsTranslate("App", "DLSS Ray Reconstruction")
if (id === "super_resolution") return qsTranslate("App", "RTX Super Resolution")
if (id === "rtx_video_hdr") return qsTranslate("App", "RTX Video HDR")
if (id === "vfx_vsr") return qsTranslate("App", "Video Super Resolution")
@@ -82,6 +83,7 @@ Item {
Component { id: neuralControls; NeuralModelControls { appBridge: root.appBridge } }
Component { id: scaleControls; ScaleMethodControls { appBridge: root.appBridge } }
Component { id: dlssControls; DlssSuperResolutionControls { appBridge: root.appBridge } }
+ Component { id: rrControls; RayReconstructionControls { appBridge: root.appBridge } }
Component { id: superControls; SuperResolutionControls { appBridge: root.appBridge } }
Component { id: hdrControls; RtxVideoHdrControls { appBridge: root.appBridge } }
Component { id: vfxControls; VfxControls { appBridge: root.appBridge; stageId: parent ? parent.effectStage : "" } }
@@ -199,6 +201,8 @@ Item {
width: contentCol.width
appBridge: root.appBridge
stageId: model.stageKey
+ collapsible: stageId !== "dlss_ray_reconstruction" || !root.isImage
+ hasControls: stageId !== "dlss_ray_reconstruction" || !root.isImage
stageEnabled: model.enabledValue
stageIndex: index
stageCount: root.workflowRepeater ? root.workflowRepeater.count : 0
@@ -238,13 +242,14 @@ Item {
width: parent.width
property string effectStage: stageCard.stageId
property bool visited: false
- readonly property bool expanded: !stageCard.collapsed
+ readonly property bool expanded: stageCard.expanded
active: visited
onExpandedChanged: { if (expanded) visited = true }
Component.onCompleted: { if (expanded) visited = true }
sourceComponent: stageId === "neural_model" ? neuralControls
: stageId === "scale_method" ? scaleControls
: stageId === "dlss_super_resolution" ? dlssControls
+ : stageId === "dlss_ray_reconstruction" ? rrControls
: stageId === "super_resolution" ? superControls
: stageId === "rtx_video_hdr" ? hdrControls
: stageId.indexOf("vfx_") === 0 ? vfxControls
diff --git a/src/desktop/translations/app_ar.qm b/src/desktop/translations/app_ar.qm
index 3ab8db8..fbdfcca 100644
Binary files a/src/desktop/translations/app_ar.qm and b/src/desktop/translations/app_ar.qm differ
diff --git a/src/desktop/translations/app_ar.ts b/src/desktop/translations/app_ar.ts
index f4bbb28..a4703ad 100644
--- a/src/desktop/translations/app_ar.ts
+++ b/src/desktop/translations/app_ar.ts
@@ -1514,8 +1514,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>فتح مجلد المصدر</translation>
+ <source>Show input in Explorer</source>
+ <translation>إظهار ملف الإدخال في مستكشف الملفات</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2657,5 +2657,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA وDLSS وRTX علامات تجارية لشركة NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>تستخدم الصور ومقاطع الفيديو المستوردة بيانات تقديرية للمواد. تعتمد النتائج على المصدر.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_de.qm b/src/desktop/translations/app_de.qm
index adae6b4..79a9477 100644
Binary files a/src/desktop/translations/app_de.qm and b/src/desktop/translations/app_de.qm differ
diff --git a/src/desktop/translations/app_de.ts b/src/desktop/translations/app_de.ts
index 668c2c6..6c1eb6b 100644
--- a/src/desktop/translations/app_de.ts
+++ b/src/desktop/translations/app_de.ts
@@ -1498,8 +1498,8 @@ Standbild angezeigt. Mit &lt; &gt; navigieren oder Datei extern öffnen.</transl
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>Quellordner öffnen</translation>
+ <source>Show input in Explorer</source>
+ <translation>Eingabedatei im Explorer anzeigen</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2641,5 +2641,13 @@ Standbild angezeigt. Mit &lt; &gt; navigieren oder Datei extern öffnen.</transl
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS und RTX sind Marken der NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>Importierte Bilder und Videos verwenden geschätzte Materialdaten. Die Ergebnisse hängen von der Quelle ab.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_es.qm b/src/desktop/translations/app_es.qm
index 82e706a..a43ce37 100644
Binary files a/src/desktop/translations/app_es.qm and b/src/desktop/translations/app_es.qm differ
diff --git a/src/desktop/translations/app_es.ts b/src/desktop/translations/app_es.ts
index 516f0a9..6cbf650 100644
--- a/src/desktop/translations/app_es.ts
+++ b/src/desktop/translations/app_es.ts
@@ -1498,8 +1498,8 @@ Se muestra un fotograma. Navega con &lt; &gt; o abre el archivo externamente.</t
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>Abrir carpeta de origen</translation>
+ <source>Show input in Explorer</source>
+ <translation>Mostrar archivo de entrada en el Explorador</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2641,5 +2641,13 @@ Se muestra un fotograma. Navega con &lt; &gt; o abre el archivo externamente.</t
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS y RTX son marcas de NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>Las imágenes y los vídeos importados usan datos de materiales estimados. Los resultados dependen de la fuente.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_fr.qm b/src/desktop/translations/app_fr.qm
index f5831cd..070ced2 100644
Binary files a/src/desktop/translations/app_fr.qm and b/src/desktop/translations/app_fr.qm differ
diff --git a/src/desktop/translations/app_fr.ts b/src/desktop/translations/app_fr.ts
index 5386602..8d158d6 100644
--- a/src/desktop/translations/app_fr.ts
+++ b/src/desktop/translations/app_fr.ts
@@ -1498,8 +1498,8 @@ Image fixe affichée. Parcourez avec &lt; &gt; ou ouvrez le fichier dans une app
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>Ouvrir le dossier source</translation>
+ <source>Show input in Explorer</source>
+ <translation>Afficher le fichier d’entrée dans l’Explorateur</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2641,5 +2641,13 @@ Image fixe affichée. Parcourez avec &lt; &gt; ou ouvrez le fichier dans une app
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS et RTX sont des marques de NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>Les images et vidéos importées utilisent des données de matériaux estimées. Les résultats dépendent de la source.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_hi.qm b/src/desktop/translations/app_hi.qm
index 62c977d..ce77b2f 100644
Binary files a/src/desktop/translations/app_hi.qm and b/src/desktop/translations/app_hi.qm differ
diff --git a/src/desktop/translations/app_hi.ts b/src/desktop/translations/app_hi.ts
index b94744a..27ee6be 100644
--- a/src/desktop/translations/app_hi.ts
+++ b/src/desktop/translations/app_hi.ts
@@ -1498,8 +1498,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>स्रोत फ़ोल्डर खोलें</translation>
+ <source>Show input in Explorer</source>
+ <translation>इनपुट फ़ाइल को एक्सप्लोरर में दिखाएँ</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2641,5 +2641,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS और RTX, NVIDIA Corporation के ट्रेडमार्क हैं।</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>आयातित छवियों और वीडियो में सामग्री के अनुमानित संकेतों का उपयोग होता है। परिणाम स्रोत पर निर्भर करते हैं।</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_ja.qm b/src/desktop/translations/app_ja.qm
index 6d85552..a7d4b60 100644
Binary files a/src/desktop/translations/app_ja.qm and b/src/desktop/translations/app_ja.qm differ
diff --git a/src/desktop/translations/app_ja.ts b/src/desktop/translations/app_ja.ts
index 1e709f0..2720db0 100644
--- a/src/desktop/translations/app_ja.ts
+++ b/src/desktop/translations/app_ja.ts
@@ -1494,8 +1494,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>元のフォルダーを開く</translation>
+ <source>Show input in Explorer</source>
+ <translation>入力ファイルをエクスプローラーで表示</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2637,5 +2637,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk。NVIDIA、DLSS、RTXはNVIDIA Corporationの商標です。</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>読み込んだ画像と動画には、推定したマテリアル情報を使用します。結果はソースによって異なります。</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_ko.qm b/src/desktop/translations/app_ko.qm
index 6be5f20..cfbd41e 100644
Binary files a/src/desktop/translations/app_ko.qm and b/src/desktop/translations/app_ko.qm differ
diff --git a/src/desktop/translations/app_ko.ts b/src/desktop/translations/app_ko.ts
index 3fdaec7..b1864ab 100644
--- a/src/desktop/translations/app_ko.ts
+++ b/src/desktop/translations/app_ko.ts
@@ -1494,8 +1494,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>원본 폴더 열기</translation>
+ <source>Show input in Explorer</source>
+ <translation>탐색기에서 입력 파일 표시</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2637,5 +2637,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS 및 RTX는 NVIDIA Corporation의 상표입니다.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>가져온 이미지와 동영상에는 추정된 재질 정보를 사용합니다. 결과는 원본에 따라 달라집니다.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_pl.qm b/src/desktop/translations/app_pl.qm
index d6eb136..4b7f3af 100644
Binary files a/src/desktop/translations/app_pl.qm and b/src/desktop/translations/app_pl.qm differ
diff --git a/src/desktop/translations/app_pl.ts b/src/desktop/translations/app_pl.ts
index 777922f..b319bd2 100644
--- a/src/desktop/translations/app_pl.ts
+++ b/src/desktop/translations/app_pl.ts
@@ -1502,8 +1502,8 @@ Wyświetlono klatkę. Użyj &lt; &gt; lub otwórz plik zewnętrznie.</translatio
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>Otwórz folder źródłowy</translation>
+ <source>Show input in Explorer</source>
+ <translation>Pokaż plik wejściowy w Eksploratorze</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2645,5 +2645,13 @@ Wyświetlono klatkę. Użyj &lt; &gt; lub otwórz plik zewnętrznie.</translatio
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS i RTX są znakami towarowymi NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>Importowane obrazy i filmy korzystają z szacowanych danych materiałów. Wyniki zależą od źródła.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_uk.qm b/src/desktop/translations/app_uk.qm
index bcaaccf..5149ef4 100644
Binary files a/src/desktop/translations/app_uk.qm and b/src/desktop/translations/app_uk.qm differ
diff --git a/src/desktop/translations/app_uk.ts b/src/desktop/translations/app_uk.ts
index 50bf3cc..095d808 100644
--- a/src/desktop/translations/app_uk.ts
+++ b/src/desktop/translations/app_uk.ts
@@ -1502,8 +1502,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>Відкрити папку джерела</translation>
+ <source>Show input in Explorer</source>
+ <translation>Показати вхідний файл у Провіднику</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2645,5 +2645,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk. NVIDIA, DLSS і RTX є торговельними марками NVIDIA Corporation.</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>Для імпортованих зображень і відео використовуються оцінені дані матеріалів. Результати залежать від джерела.</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_zh_CN.qm b/src/desktop/translations/app_zh_CN.qm
index b9de38c..09b1503 100644
Binary files a/src/desktop/translations/app_zh_CN.qm and b/src/desktop/translations/app_zh_CN.qm differ
diff --git a/src/desktop/translations/app_zh_CN.ts b/src/desktop/translations/app_zh_CN.ts
index 63ff3e9..c1cb3ec 100644
--- a/src/desktop/translations/app_zh_CN.ts
+++ b/src/desktop/translations/app_zh_CN.ts
@@ -1494,8 +1494,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>打开源文件夹</translation>
+ <source>Show input in Explorer</source>
+ <translation>在资源管理器中显示输入文件</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2637,5 +2637,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk。NVIDIA、DLSS 和 RTX 是 NVIDIA Corporation 的商标。</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>导入的图像和视频使用估算的材质信息。效果取决于源素材。</translation>
+ </message>
+</context>
</TS>
diff --git a/src/desktop/translations/app_zh_TW.qm b/src/desktop/translations/app_zh_TW.qm
index be2fb46..0c5cc12 100644
Binary files a/src/desktop/translations/app_zh_TW.qm and b/src/desktop/translations/app_zh_TW.qm differ
diff --git a/src/desktop/translations/app_zh_TW.ts b/src/desktop/translations/app_zh_TW.ts
index d9eb661..bc28b3c 100644
--- a/src/desktop/translations/app_zh_TW.ts
+++ b/src/desktop/translations/app_zh_TW.ts
@@ -1494,8 +1494,8 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
</message>
<message>
<location filename="../qml/components/BatchQueueDrawer.qml" line="513" />
- <source>Open source folder</source>
- <translation>開啟來源資料夾</translation>
+ <source>Show input in Explorer</source>
+ <translation>在檔案總管中顯示輸入檔案</translation>
</message>
<message>
<source>Opened containing folder for %1.</source>
@@ -2637,5 +2637,13 @@ Poster frame shown. Scrub with &lt; &gt; or open the file externally.</source>
<source>© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation.</source>
<translation>© 2026 Merserk。NVIDIA、DLSS 與 RTX 是 NVIDIA Corporation 的商標。</translation>
</message>
- </context>
+ <message>
+ <source>DLSS Ray Reconstruction</source>
+ <translation>DLSS Ray Reconstruction</translation>
+ </message>
+ <message>
+ <source>Imported images and videos use estimated material guides. Results depend on the source.</source>
+ <translation>匯入的影像和影片使用估算的材質資訊。效果取決於來源素材。</translation>
+ </message>
+</context>
</TS>
diff --git a/src/infrastructure/paths.cpp b/src/infrastructure/paths.cpp
index f3f1f92..9a0475d 100644
--- a/src/infrastructure/paths.cpp
+++ b/src/infrastructure/paths.cpp
@@ -1,4 +1,5 @@
#include "paths.hpp"
+#include "media/resolution.hpp"
#include <QDir>
#include <QDirIterator>
#include <QFileInfo>
@@ -59,6 +60,7 @@ QString Paths::nativeDataDirectory() const {
return writableDirectory(QStandardPaths::AppLocalDataLocation, "NVIDIA");
}
void Paths::prepare() const {
+ configureImageDecoding();
for (const auto* relative : {"outputs", "logs"}) {
if (!QDir().mkpath(at(relative)))
throw std::runtime_error(("Cannot create application folder: " + at(relative)).toStdString());
diff --git a/src/infrastructure/vulkan_device.cpp b/src/infrastructure/vulkan_device.cpp
index 5048476..665daed 100644
--- a/src/infrastructure/vulkan_device.cpp
+++ b/src/infrastructure/vulkan_device.cpp
@@ -65,6 +65,7 @@ std::vector<VulkanDevice> enumerate() {
device.index = int(index);
device.name = QString::fromUtf8(props.properties.deviceName);
device.discrete = props.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
+ device.maximumImageDimension2D = props.properties.limits.maxImageDimension2D;
device.uuid = QUuid::fromRfc4122(
QByteArray(reinterpret_cast<const char*>(identity.deviceUUID), VK_UUID_SIZE))
.toString(QUuid::WithoutBraces);
@@ -105,10 +106,12 @@ std::vector<VulkanDevice> vulkanCandidates(const QString& selection, bool filter
QStringList vulkanArguments(const VulkanDevice& device) {
return {"-init_hw_device", "vulkan=ve_vk:" + QString::number(device.index), "-filter_hw_device", "ve_vk"};
}
-QStringList vulkanFilterArguments(const QString& selection) {
+QStringList vulkanFilterArguments(const QString& selection, QSize largestFrame) {
static std::mutex mutex;
static std::unordered_map<int, bool> supported;
for (const auto& device : vulkanCandidates(selection, true)) {
+ if (largestFrame.isValid() && (uint32_t(largestFrame.width()) > device.maximumImageDimension2D ||
+ uint32_t(largestFrame.height()) > device.maximumImageDimension2D)) continue;
std::scoped_lock lock(mutex);
auto found = supported.find(device.index);
if (found == supported.end()) {
@@ -123,6 +126,9 @@ QStringList vulkanFilterArguments(const QString& selection) {
if (found->second)
return vulkanArguments(device);
}
+ if (largestFrame.isValid())
+ throw std::runtime_error(QString("No selected Vulkan GPU supports filtering %1x%2 with its native 2D image limits.")
+ .arg(largestFrame.width()).arg(largestFrame.height()).toStdString());
throw std::runtime_error(
"Vulkan GPU filtering is unavailable. Install a current AMD, Intel or NVIDIA Vulkan driver.");
}
diff --git a/src/infrastructure/vulkan_device.hpp b/src/infrastructure/vulkan_device.hpp
index 1b3c973..66de4d5 100644
--- a/src/infrastructure/vulkan_device.hpp
+++ b/src/infrastructure/vulkan_device.hpp
@@ -1,6 +1,7 @@
#pragma once
#include <QString>
#include <QStringList>
+#include <QSize>
#include <vector>
namespace ve {
@@ -8,6 +9,7 @@ struct VulkanDevice {
int index = 0;
QString name, uuid;
bool discrete = false;
+ uint32_t maximumImageDimension2D = 0;
QStringList extensions;
[[nodiscard]] QString selection() const { return "vulkan:" + uuid; }
[[nodiscard]] QString label() const {
@@ -17,5 +19,5 @@ struct VulkanDevice {
[[nodiscard]] const std::vector<VulkanDevice>& vulkanDevices();
[[nodiscard]] std::vector<VulkanDevice> vulkanCandidates(const QString& selection, bool filters = false);
[[nodiscard]] QStringList vulkanArguments(const VulkanDevice& device);
-[[nodiscard]] QStringList vulkanFilterArguments(const QString& selection);
+[[nodiscard]] QStringList vulkanFilterArguments(const QString& selection, QSize largestFrame = {});
} // namespace ve
diff --git a/src/media/av_api.hpp b/src/media/av_api.hpp
index 3696f97..ecf62d9 100644
--- a/src/media/av_api.hpp
+++ b/src/media/av_api.hpp
@@ -26,6 +26,7 @@ struct Api {
AV_FN(avcodec_flush_buffers); AV_FN(avformat_flush);
AV_FN(avcodec_send_frame); AV_FN(avcodec_receive_packet);
AV_FN(av_frame_alloc); AV_FN(av_frame_free); AV_FN(av_frame_copy_props);
+ AV_FN(av_frame_new_side_data); AV_FN(av_frame_get_side_data);
AV_FN(av_frame_get_buffer); AV_FN(av_frame_make_writable);
AV_FN(av_image_get_buffer_size); AV_FN(av_image_copy_to_buffer);
AV_FN(av_buffer_create);
diff --git a/src/media/cuda_video.cpp b/src/media/cuda_video.cpp
index 4f7a5dd..30c2dea 100644
--- a/src/media/cuda_video.cpp
+++ b/src/media/cuda_video.cpp
@@ -1,4 +1,5 @@
#include "cuda_video.hpp"
+#include "host_video.hpp"
#include "av_api.hpp"
#include "configuration/settings.hpp"
#include "infrastructure/windows_runtime.hpp"
@@ -7,6 +8,7 @@
#include <cmath>
#include <map>
#include <mutex>
+#include <cstring>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
@@ -130,7 +132,7 @@ struct CudaVideoDecoder::Impl {
AVPacket* packet = nullptr;
int stream = -1;
bool draining = false;
- double start = 0;
+ double start = 0, timestampOffset=0;
qint64 origin = AV_NOPTS_VALUE;
Impl(const QString& path, int ordinal, double seconds, JobControl& job) : control(job), start(seconds) {
try {
@@ -143,8 +145,11 @@ struct CudaVideoDecoder::Impl {
check(api.avformat_open_input(&format, path.toUtf8().constData(), nullptr, nullptr), "Open source");
check(api.avformat_find_stream_info(format, nullptr), "Probe source");
prepareDecoder(ordinal);
+ const auto* track=format->streams[stream];
+ if(track->start_time!=AV_NOPTS_VALUE)timestampOffset=track->start_time*av_q2d(track->time_base);
+ else if(format->start_time!=AV_NOPTS_VALUE)timestampOffset=double(format->start_time)/AV_TIME_BASE;
if (start > 0)
- check(api.avformat_seek_file(format, -1, INT64_MIN, qint64(std::max(0., start - .002) * AV_TIME_BASE),
+ check(api.avformat_seek_file(format, -1, INT64_MIN, qint64((timestampOffset+std::max(0., start - .002)) * AV_TIME_BASE),
INT64_MAX, 0), "Seek NVDEC source");
} catch (const Cancelled&) { release(); throw; }
catch (const std::exception& e) { release(); throw CudaUnavailable(e.what()); }
@@ -271,7 +276,7 @@ std::optional<CudaVideoFrame> CudaVideoDecoder::read() {
if (output.pts == AV_NOPTS_VALUE)
throw std::runtime_error("Decoded video frame has no presentation timestamp.");
const double seconds = output.pts * double(output.timeBase.numerator) / output.timeBase.denominator;
- if (seconds + .002 < s.start)
+ if (seconds + .002 < s.start+s.timestampOffset)
continue;
if (s.origin == AV_NOPTS_VALUE) s.origin = output.pts;
output.pts -= s.origin;
@@ -378,6 +383,7 @@ struct CudaVideoEncoder::Impl {
stream->time_base = codec->time_base;
stream->avg_frame_rate = codec->framerate;
check(api.avcodec_parameters_from_context(stream->codecpar, codec), "Describe encoded stream");
+ retainStaticHdrMetadata(stream->codecpar,info);
check(api.avio_open(&format->pb, path.toUtf8().constData(), AVIO_FLAG_WRITE), "Open video destination");
api.av_dict_set(&options,"video_track_timescale","60000000",0);
check(api.avformat_write_header(format, &options), "Write video header");
@@ -437,6 +443,9 @@ void CudaVideoEncoder::write(const CudaVideoFrame& frame) {
av->duration = s.api.av_rescale_q(frame.duration, sourceBase, s.codec->time_base);
if(s.explicitDurations)s.durations[av->pts]=av->duration;
if(s.codec->chroma_sample_location!=AVCHROMA_LOC_UNSPECIFIED)av->chroma_location=s.codec->chroma_sample_location;
+ // NVENC reads static HDR SEI from submitted frames. Also retain the same
+ // values on codec parameters for containers with native HDR metadata.
+ copyStaticHdrMetadata(av,s.stream->codecpar);
check(s.api.avcodec_send_frame(s.codec, av), "Submit NVENC frame");
s.packets();
}
diff --git a/src/media/host_video.cpp b/src/media/host_video.cpp
index 01b994e..fb3e3e4 100644
--- a/src/media/host_video.cpp
+++ b/src/media/host_video.cpp
@@ -1,4 +1,5 @@
#include "host_video.hpp"
+#include "resolution.hpp"
#include "av_api.hpp"
#include "cuda_video.hpp"
#include "native_frame.hpp"
@@ -68,6 +69,21 @@ void retainHdrMetadata(AVCodecParameters* parameters, const MediaInfo& info) {
}
}
} // namespace
+void retainStaticHdrMetadata(AVCodecParameters* parameters,const MediaInfo& info) {
+ retainHdrMetadata(parameters,info);
+}
+void copyStaticHdrMetadata(AVFrame* frame,const AVCodecParameters* parameters) {
+ auto& api=av::Api::get();
+ for(int index=0;index<parameters->nb_coded_side_data;++index){
+ const auto& side=parameters->coded_side_data[index];
+ if(side.type!=AV_PKT_DATA_MASTERING_DISPLAY_METADATA&&side.type!=AV_PKT_DATA_CONTENT_LIGHT_LEVEL)continue;
+ const auto type=side.type==AV_PKT_DATA_MASTERING_DISPLAY_METADATA?AV_FRAME_DATA_MASTERING_DISPLAY_METADATA:AV_FRAME_DATA_CONTENT_LIGHT_LEVEL;
+ if(api.av_frame_get_side_data(frame,type))continue;
+ auto* retained=api.av_frame_new_side_data(frame,type,side.size);
+ if(!retained)throw std::bad_alloc{};
+ std::memcpy(retained->data,side.data,side.size);
+ }
+}
QString ffv1PreviewPixelFormat(const MediaInfo& info) {
const auto bits = std::max(info.precisionBits(), info.hdr ? 10 : 8);
if (bits == 8) return "bgr0";
@@ -232,7 +248,7 @@ struct HostVideoDecoder::Impl {
av::check(api.avformat_find_stream_info(format, nullptr), "Probe host source");
stream = api.av_find_best_stream(format, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
av::check(stream, "Find host video stream");
- if (timelinePacking) {
+ {
const auto* track=format->streams[stream];
if (track->start_time!=AV_NOPTS_VALUE)
timestampOffset=track->start_time*av_q2d(track->time_base);
@@ -367,6 +383,7 @@ std::optional<TimedImage> HostVideoDecoder::read() {
QImage image(destination->data[0], destination->width, destination->height, destination->linesize[0],
s.bits > 8 ? QImage::Format_RGBA64 : QImage::Format_RGBA8888);
image = s.rotation ? image.transformed(QTransform().rotate(s.rotation), Qt::FastTransformation) : image.copy();
+ requireImageAllocation(image, "Decoded video image allocation");
return TimedImage{image, pts, duration, base};
}
}
@@ -438,7 +455,7 @@ struct HostVideoEncoder::Impl {
stream->time_base = codec->time_base; stream->avg_frame_rate = codec->framerate;
stream->sample_aspect_ratio=codec->sample_aspect_ratio;
av::check(api.avcodec_parameters_from_context(stream->codecpar, codec), "Describe host output");
- if (name == "ffv1") retainHdrMetadata(stream->codecpar, info);
+ retainStaticHdrMetadata(stream->codecpar, info);
av::check(api.avio_open(&format->pb, path.toUtf8().constData(), AVIO_FLAG_WRITE), "Open host video output");
if (name!="ffv1") api.av_dict_set(&options,"video_track_timescale","60000000",0);
av::check(api.avformat_write_header(format, &options), "Write host video header");
@@ -486,6 +503,7 @@ struct HostVideoEncoder::Impl {
destination->duration = api.av_rescale_q(duration, {timeBase.numerator, timeBase.denominator}, codec->time_base);
if(explicitDurations)durations[destination->pts]=destination->duration;
destination->pict_type=forceIntra ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
+ copyStaticHdrMetadata(destination,stream->codecpar);
av::check(api.avcodec_send_frame(codec, destination), "Submit host encoder pixels");
packets();
}
diff --git a/src/media/host_video.hpp b/src/media/host_video.hpp
index 7bfa1b2..cdaeb9b 100644
--- a/src/media/host_video.hpp
+++ b/src/media/host_video.hpp
@@ -3,6 +3,8 @@
#include "packet_stream.hpp"
#include <memory>
#include <optional>
+struct AVCodecParameters;
+struct AVFrame;
namespace ve {
struct Settings;
@@ -10,6 +12,8 @@ struct CudaVideoFrame;
enum class HostDecodePrecision { Source, Unorm8, Unorm16 };
enum class HostEncodePurpose { Delivery, NativePreview };
[[nodiscard]] QString ffv1PreviewPixelFormat(const MediaInfo& info);
+void retainStaticHdrMetadata(AVCodecParameters* parameters,const MediaInfo& info);
+void copyStaticHdrMetadata(AVFrame* frame,const AVCodecParameters* parameters);
class HostRgb10Boundary {
public:
HostRgb10Boundary();
diff --git a/src/media/image_alpha.cpp b/src/media/image_alpha.cpp
index 57448ac..d9ce3b5 100644
--- a/src/media/image_alpha.cpp
+++ b/src/media/image_alpha.cpp
@@ -1,4 +1,5 @@
#include "image_alpha.hpp"
+#include "resolution.hpp"
#include <algorithm>
#include <cmath>
#include <numbers>
@@ -52,6 +53,7 @@ void restoreImageAlpha(QImage& output,const QImage& input,JobControl& control) {
if (!input.hasAlphaChannel()) return;
const bool wide=input.depth()>32;
const auto source=input.convertToFormat(QImage::Format_RGBA64);
+ requireImageAllocation(source, "Alpha input conversion");
const int width=output.width(),height=output.height();
std::vector<int> horizontal(size_t(width)*source.height());
const auto xKernels=kernels(source.width(),width), yKernels=kernels(source.height(),height);
@@ -65,6 +67,7 @@ void restoreImageAlpha(QImage& output,const QImage& input,JobControl& control) {
}
const auto format=wide ? QImage::Format_RGBA64 : output.format();
output=output.convertToFormat(QImage::Format_RGBA64);
+ requireImageAllocation(output, "Alpha output conversion");
for (int y=0;y<height;++y) {
control.checkpoint();
auto* row=reinterpret_cast<QRgba64*>(output.scanLine(y));
@@ -76,5 +79,6 @@ void restoreImageAlpha(QImage& output,const QImage& input,JobControl& control) {
}
}
output=output.convertToFormat(format);
+ requireImageAllocation(output, "Alpha output packing");
}
}
diff --git a/src/media/image_codecs.cpp b/src/media/image_codecs.cpp
index 7a53b6d..1054d05 100644
--- a/src/media/image_codecs.cpp
+++ b/src/media/image_codecs.cpp
@@ -1,4 +1,5 @@
#include "image_codecs.hpp"
+#include "resolution.hpp"
#include "infrastructure/paths.hpp"
#include <QColorSpace>
#include <QDir>
@@ -65,6 +66,7 @@ void heifCheck(const heif_error& error) {
}
} // namespace
QImage decodeControlMask(const QString& path, JobControl& control) {
+ configureImageDecoding();
control.checkpoint();
QImage image;
if (isRawImage(path))
@@ -73,6 +75,7 @@ QImage decodeControlMask(const QString& path, JobControl& control) {
image = decodeHeifImage(path, control);
else {
QImageReader reader(path);
+ if (reader.size().isValid()) requireResolution(reader.size(), "Control mask");
reader.setAutoTransform(true);
image = reader.read();
if (image.isNull())
@@ -82,7 +85,10 @@ QImage decodeControlMask(const QString& path, JobControl& control) {
image.format() == QImage::Format_Grayscale16 ||
image.format() == QImage::Format_Mono || image.format() == QImage::Format_MonoLSB;
const auto rgba = image.convertToFormat(QImage::Format_RGBA64);
+ requireResolution(image.size(), "Control mask");
+ requireImageAllocation(rgba, "Control mask conversion");
QImage result(image.size(), QImage::Format_RGBA32FPx4);
+ requireImageAllocation(result, "Control mask allocation");
// Read the unassociated 16-bit channels directly to avoid rounding through
// Qt's premultiplied float conversion. Grayscale broadcasts to all four.
for (int y = 0; y < result.height(); ++y) {
@@ -100,7 +106,9 @@ QImage decodeControlMask(const QString& path, JobControl& control) {
}
QImage jpegOverWhite(const QImage& image) {
const auto source=image.convertToFormat(QImage::Format_RGBA8888);
+ requireImageAllocation(source, "JPEG input conversion");
QImage result(image.size(), QImage::Format_RGB888);
+ requireImageAllocation(result, "JPEG image allocation");
for (int y=0;y<source.height();++y) {
const auto* from=source.constScanLine(y);
auto* to=result.scanLine(y);
@@ -180,31 +188,34 @@ QSize rawImageSize(const QString& path) {
QImage decodeRawImage(const QString& path, JobControl& control) {
control.checkpoint();
LibRaw decoder;
+ decoder.imgdata.rawparams.max_raw_memory_mb = imageDecoderBudgetMiB;
decoder.set_progress_handler(rawProgress, &control);
decoder.imgdata.params.use_camera_wb = 1;
decoder.imgdata.params.output_color = 1;
decoder.imgdata.params.output_bps = 16;
openRaw(decoder, path);
+ requireResolution({decoder.imgdata.sizes.width, decoder.imgdata.sizes.height}, "RAW image");
const auto unpacked = decoder.unpack();
control.checkpoint();
rawCheck(unpacked);
const auto processed = decoder.dcraw_process();
control.checkpoint();
rawCheck(processed);
- int status = 0;
- const auto release = [](libraw_processed_image_t* image) { LibRaw::dcraw_clear_mem(image); };
- std::unique_ptr<libraw_processed_image_t, decltype(release)> pixels(decoder.dcraw_make_mem_image(&status),
- release);
- rawCheck(status);
- if (!pixels || pixels->type != LIBRAW_IMAGE_BITMAP || pixels->bits != 16 || pixels->colors < 3)
+ int width=0,height=0,colors=0,bits=0;
+ decoder.get_mem_image_format(&width,&height,&colors,&bits);
+ if (bits != 16 || (colors != 3 && colors != 4))
throw std::runtime_error("LibRaw did not return a supported RGB image.");
- QImage result(pixels->width, pixels->height, QImage::Format_RGBA64);
- const auto* rgb = reinterpret_cast<const quint16*>(pixels->data);
+ requireResolution({width,height}, "Decoded RAW image");
+ QImage result(width,height,QImage::Format_RGBA64);
+ requireImageAllocation(result, "RAW image allocation");
+ // Export directly into owned rows, avoiding a second full RGB image and
+ // the legacy processed-image record's 32-bit data_size field.
+ rawCheck(decoder.copy_mem_image(result.bits(),int(result.bytesPerLine()),0));
for (int y = 0; y < result.height(); ++y) {
control.checkpoint();
auto* row = reinterpret_cast<QRgba64*>(result.scanLine(y));
- for (int x = 0; x < result.width(); ++x) {
- const auto* source = rgb + (qsizetype(y) * result.width() + x) * pixels->colors;
+ for (int x = result.width()-1; x >= 0; --x) {
+ const auto* source = reinterpret_cast<const quint16*>(result.constScanLine(y)) + x*colors;
row[x] = QRgba64::fromRgba64(source[0], source[1], source[2], 65535);
}
}
@@ -216,10 +227,13 @@ QImage decodeHeifImage(const QString& path, JobControl& control) {
auto& library = HeifLibrary::instance();
#define HEIF_FUNCTION(name) const auto name = library.resolve<decltype(&::name)>(#name)
HEIF_FUNCTION(heif_context_alloc);
+ HEIF_FUNCTION(heif_context_get_security_limits);
HEIF_FUNCTION(heif_context_free);
HEIF_FUNCTION(heif_context_read_from_memory_without_copy);
HEIF_FUNCTION(heif_context_get_primary_image_handle);
HEIF_FUNCTION(heif_image_handle_release);
+ HEIF_FUNCTION(heif_image_handle_get_width);
+ HEIF_FUNCTION(heif_image_handle_get_height);
HEIF_FUNCTION(heif_decode_image);
HEIF_FUNCTION(heif_image_release);
HEIF_FUNCTION(heif_image_get_width);
@@ -237,24 +251,30 @@ QImage decodeHeifImage(const QString& path, JobControl& control) {
heif_context_free);
if (!context)
throw std::bad_alloc{};
+ auto* limits = heif_context_get_security_limits(context.get());
+ limits->max_image_size_pixels = maximumImagePixels;
+ limits->max_memory_block_size = quint64(imageDecoderBudgetMiB) * 1024 * 1024;
heifCheck(heif_context_read_from_memory_without_copy(context.get(), bytes.constData(),
size_t(bytes.size()), nullptr));
heif_image_handle* rawHandle = nullptr;
heifCheck(heif_context_get_primary_image_handle(context.get(), &rawHandle));
std::unique_ptr<heif_image_handle, decltype(heif_image_handle_release)> handle(rawHandle,
heif_image_handle_release);
+ requireResolution({heif_image_handle_get_width(handle.get()),heif_image_handle_get_height(handle.get())}, "HEIF image");
heif_image* rawImage = nullptr;
heifCheck(heif_decode_image(handle.get(), &rawImage, heif_colorspace_RGB,
heif_chroma_interleaved_RRGGBBAA_LE, nullptr));
std::unique_ptr<heif_image, decltype(heif_image_release)> image(rawImage, heif_image_release);
const int width = heif_image_get_width(image.get(), heif_channel_interleaved),
height = heif_image_get_height(image.get(), heif_channel_interleaved);
+ requireResolution({width,height}, "Decoded HEIF image");
int stride = 0;
const auto* data = heif_image_get_plane_readonly(image.get(), heif_channel_interleaved, &stride);
const int depth = heif_image_get_bits_per_pixel_range(image.get(), heif_channel_interleaved);
if (!data || width < 1 || height < 1 || depth < 1 || depth > 16 || stride < width * 8)
throw std::runtime_error("HEIF decoder returned invalid image dimensions or precision.");
QImage result(width, height, QImage::Format_RGBA64);
+ requireImageAllocation(result, "HEIF image allocation");
const auto maximum = double((1u << depth) - 1);
for (int y = 0; y < height; ++y) {
control.checkpoint();
@@ -275,6 +295,8 @@ QImage decodeHeifImage(const QString& path, JobControl& control) {
}
if (!result.colorSpace().isValid())
result.setColorSpace(QColorSpace::SRgb);
- return result.convertedToColorSpace(QColorSpace::SRgb);
+ auto converted=result.convertedToColorSpace(QColorSpace::SRgb);
+ requireImageAllocation(converted, "HEIF color conversion");
+ return converted;
}
} // namespace ve
diff --git a/src/media/image_metadata.cpp b/src/media/image_metadata.cpp
index a5ae62e..83d1ba4 100644
--- a/src/media/image_metadata.cpp
+++ b/src/media/image_metadata.cpp
@@ -171,6 +171,25 @@ void save(const QString& path, const QByteArray& data) {
if (!file.open(QIODevice::WriteOnly) || file.write(data) != data.size() || !file.commit())
throw std::runtime_error(file.errorString().toStdString());
}
+void insertMetadata(const QString& path, qsizetype prefixBytes, const QByteArray& chunks, JobControl& control) {
+ if (chunks.isEmpty()) return;
+ QFile input(path);
+ QSaveFile output(path);
+ if (!input.open(QIODevice::ReadOnly) || !output.open(QIODevice::WriteOnly))
+ throw std::runtime_error("Cannot open image for metadata insertion.");
+ const auto prefix=input.read(prefixBytes);
+ if (prefix.size()!=prefixBytes || output.write(prefix)!=prefix.size() || output.write(chunks)!=chunks.size())
+ throw std::runtime_error("Cannot write image metadata.");
+ while (!input.atEnd()) {
+ control.checkpoint();
+ const auto block=input.read(8*1024*1024);
+ if (block.isEmpty() || output.write(block)!=block.size())
+ throw std::runtime_error("Cannot copy image data while inserting metadata.");
+ }
+ input.close();
+ control.checkpoint();
+ if (!output.commit()) throw std::runtime_error(output.errorString().toStdString());
+}
} // namespace
QString mergeRenderDescription(const QString& existing, const QString& note) {
if (existing.isEmpty())
@@ -266,7 +285,7 @@ void writeImageMetadata(const QString& destination, const ImageMetadata& metadat
QFile input(destination);
if (!input.open(QIODevice::ReadOnly))
throw std::runtime_error(input.errorString().toStdString());
- const auto original = input.readAll();
+ const auto original = input.read(2);
input.close();
if (!original.startsWith(QByteArray::fromHex("ffd8")))
throw std::runtime_error("Invalid JPEG image.");
@@ -281,13 +300,13 @@ void writeImageMetadata(const QString& destination, const ImageMetadata& metadat
payload += metadata.icc.mid(index * 65519, 65519);
chunks += segment(0xe2, payload);
}
- save(destination, original.left(2) + chunks + original.mid(2));
+ insertMetadata(destination,2,chunks,control);
}
if (QFileInfo(destination).suffix().compare("png", Qt::CaseInsensitive) == 0) {
QFile input(destination);
if (!input.open(QIODevice::ReadOnly))
throw std::runtime_error(input.errorString().toStdString());
- const auto original = input.readAll();
+ const auto original = input.read(33);
input.close();
if (!original.startsWith(QByteArray::fromHex("89504e470d0a1a0a")) || original.size() < 33)
throw std::runtime_error("Invalid PNG image.");
@@ -296,7 +315,7 @@ void writeImageMetadata(const QString& destination, const ImageMetadata& metadat
chunks += pngChunk("eXIf", metadata.exif);
if (!metadata.xmp.isEmpty())
chunks += pngChunk("iTXt", QByteArray("XML:com.adobe.xmp\0\0\0\0\0", 22) + metadata.xmp);
- save(destination, original.left(33) + chunks + original.mid(33));
+ insertMetadata(destination,33,chunks,control);
return;
}
if (metadata.exif.isEmpty() && metadata.xmp.isEmpty())
diff --git a/src/media/media.cpp b/src/media/media.cpp
index 386b2ed..2aeb3bd 100644
--- a/src/media/media.cpp
+++ b/src/media/media.cpp
@@ -3,6 +3,7 @@
#include "image_codecs.hpp"
#include "image_metadata.hpp"
#include "png_encoder.hpp"
+#include "resolution.hpp"
#include "infrastructure/log.hpp"
#include "infrastructure/paths.hpp"
#include "infrastructure/process.hpp"
@@ -39,14 +40,19 @@ void requireSuccess(const ProcessResult& result) {
throw std::runtime_error(QString::fromUtf8(result.error).right(6000).toStdString());
}
QImage readRaster(QImageReader& reader) {
+ configureImageDecoding();
+ if (reader.size().isValid()) requireResolution(reader.size(), "Input image");
reader.setAutoTransform(true);
auto image=reader.read();
if (image.isNull()) return {};
+ requireResolution(image.size(), "Decoded image");
if (image.depth()<=32) {
if (image.colorSpace().isValid()) image.convertToColorSpace(QColorSpace::SRgb);
image.setColorSpace(QColorSpace::SRgb);
}
- return image.convertToFormat(image.depth()<=32 ? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
+ auto result = image.convertToFormat(image.depth()<=32 ? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
+ requireImageAllocation(result, "Image conversion");
+ return result;
}
} // namespace
int MediaInfo::precisionBits() const {
@@ -61,6 +67,13 @@ int MediaInfo::precisionBits() const {
const auto declared = metadata.value("bits_per_raw_sample").toVariant().toInt();
return declared > 0 ? declared : hdr ? 10 : 8;
}
+double MediaInfo::presentationStartSeconds() const {
+ bool valid=false;
+ const auto stream=metadata.value("start_time").toVariant().toDouble(&valid);
+ if(valid&&std::isfinite(stream))return stream;
+ const auto format=metadata.value("source_format").toObject().value("start_time").toVariant().toDouble(&valid);
+ return valid&&std::isfinite(format)?format:0.;
+}
int MediaInfo::clockwiseRotation() const {
int display = metadata.value("tags").toObject().value("rotate").toVariant().toInt();
for (const auto& side : metadata.value("side_data_list").toArray())
@@ -186,21 +199,25 @@ MediaInfo probeMedia(const QString& path, JobControl* control, const QStringList
QByteArray rgbaBytes(const QImage& image, bool sixteenBit) {
const auto converted =
image.convertToFormat(sixteenBit ? QImage::Format_RGBA64 : QImage::Format_RGBA8888);
+ requireImageAllocation(converted, "Packed image conversion");
const qsizetype stride = qsizetype(converted.width()) * (sixteenBit ? 8 : 4);
- QByteArray result(stride * converted.height(), Qt::Uninitialized);
+ QByteArray result(imageByteCount(converted.size(),sixteenBit ? 8 : 4), Qt::Uninitialized);
for (int y = 0; y < converted.height(); ++y)
std::memcpy(result.data() + stride * y, converted.constScanLine(y), static_cast<size_t>(stride));
return result;
}
QImage fromRgbaBytes(const QByteArray& bytes, int width, int height, bool sixteenBit) {
- const auto expected = qsizetype(width) * height * (sixteenBit ? 8 : 4);
+ const auto expected = imageByteCount({width, height}, sixteenBit ? 8 : 4);
if (bytes.size() != expected)
throw std::runtime_error("Decoder returned an incomplete image.");
- return QImage(reinterpret_cast<const uchar*>(bytes.constData()), width, height,
+ auto image = QImage(reinterpret_cast<const uchar*>(bytes.constData()), width, height,
width * (sixteenBit ? 8 : 4), sixteenBit ? QImage::Format_RGBA64 : QImage::Format_RGBA8888)
.copy();
+ requireImageAllocation(image, "Decoded image allocation");
+ return image;
}
QImage decodeImage(const QString& path, JobControl& control) {
+ configureImageDecoding();
control.checkpoint();
if (isRawImage(path))
return decodeRawImage(path, control);
@@ -213,14 +230,20 @@ QImage decodeImage(const QString& path, JobControl& control) {
if (!directory.isValid()) throw std::runtime_error("Cannot create the AVIF decoder directory.");
const auto decoded = directory.filePath("decoded.png");
const auto result = runProcess(Paths::instance().at("bin/avif/avifdec.exe"),
- {"--depth", wide ? "16" : "8", "--png-compress", "1", path, decoded}, &control, 0);
+ // libavif 1.4.2's CLI rejects pixel limits above its
+ // compiled 268435456 maximum. Retain that feature limit.
+ {"--depth", wide ? "16" : "8", "--dimension-limit", QString::number(maximumImageDimension),
+ "--png-compress", "1", path, decoded}, &control, 0);
requireSuccess(result);
QImageReader reader(decoded);
+ if (reader.size().isValid()) requireResolution(reader.size(), "AVIF image");
reader.setAutoTransform(true);
auto image = reader.read();
if (image.isNull())
throw std::runtime_error(reader.errorString().toStdString());
- return image.convertToFormat(wide ? QImage::Format_RGBA64 : QImage::Format_RGBA8888);
+ auto converted = image.convertToFormat(wide ? QImage::Format_RGBA64 : QImage::Format_RGBA8888);
+ requireImageAllocation(converted, "AVIF image conversion");
+ return converted;
}
QImageReader reader(path);
auto image = readRaster(reader);
@@ -228,6 +251,7 @@ QImage decodeImage(const QString& path, JobControl& control) {
return image;
}
const auto info = probeMedia(path, &control);
+ requireResolution({info.width, info.height}, "Input image");
const auto process = runProcess(
Paths::instance().ffmpeg(),
{"-v", "error", "-i", path, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgba64le", "pipe:1"},
@@ -259,6 +283,8 @@ QImage decodeVideoFrame(const QString& path, double seconds, JobControl& control
void encodeImage(const QString& path, const QImage& pixels, const QString& format, int quality, int bitDepth,
JobControl& control, const QString& metadataSource, const QString& note) {
control.checkpoint();
+ requireResolution(pixels.size(), "Output image");
+ if (format == "WebP") requireResolution(pixels.size(), "WebP format", 16383);
ImageMetadata metadata;
try {
metadata = readImageMetadata(metadataSource, control);
@@ -273,6 +299,7 @@ void encodeImage(const QString& path, const QImage& pixels, const QString& forma
auto image = pixels.convertToFormat(bitDepth == 16 && (format == "PNG" || format == "TIFF" || format=="AVIF")
? QImage::Format_RGBA64
: QImage::Format_RGBA8888);
+ requireImageAllocation(image, "Output image conversion");
if (!image.colorSpace().isValid())
image.setColorSpace(QColorSpace::SRgb);
metadata.icc = image.colorSpace().iccProfile();
diff --git a/src/media/media.hpp b/src/media/media.hpp
index c42b1bf..bd1b70d 100644
--- a/src/media/media.hpp
+++ b/src/media/media.hpp
@@ -19,6 +19,7 @@ struct MediaInfo {
[[nodiscard]] QString description() const;
[[nodiscard]] int clockwiseRotation() const;
[[nodiscard]] int precisionBits() const;
+ [[nodiscard]] double presentationStartSeconds() const;
// Set by processing routes that explicitly retain the source pixel aspect.
[[nodiscard]] QSize outputSampleAspectRatio() const;
};
diff --git a/src/media/native_rgb.hpp b/src/media/native_rgb.hpp
new file mode 100644
index 0000000..ff4eda0
--- /dev/null
+++ b/src/media/native_rgb.hpp
@@ -0,0 +1,28 @@
+#pragma once
+#include <QSize>
+#include <QStringView>
+#include <cstdint>
+#include <memory>
+
+namespace ve {
+// Oriented opaque CUDA RGBA16F, encoded in the named media transfer.
+// The owner retains the allocation and its producing native feature/device.
+struct GpuRgbFrame {
+ std::shared_ptr<void> owner;
+ QSize size;
+ uint64_t pointer=0;
+ uint32_t stride=0;
+ uint32_t transfer=1; // sRGB/709/linear/gamma22/gamma28/PQ/HLG = 0..6.
+ uint32_t primaries=1; // Native FI convention: 0=601, 1=709, 2=2020.
+ bool historyReset=false;
+};
+inline uint32_t nativeMediaTransfer(QStringView value){
+ if(value==u"smpte2084")return 5;
+ if(value==u"arib-std-b67")return 6;
+ if(value==u"iec61966-2-1"||value==u"srgb")return 0;
+ if(value==u"linear")return 2;
+ if(value==u"gamma22"||value==u"bt470m")return 3;
+ if(value==u"gamma28"||value==u"bt470bg")return 4;
+ return 1;
+}
+} // namespace ve
diff --git a/src/media/resolution.hpp b/src/media/resolution.hpp
new file mode 100644
index 0000000..a3e5ec1
--- /dev/null
+++ b/src/media/resolution.hpp
@@ -0,0 +1,55 @@
+#pragma once
+#include <QImage>
+#include <QImageReader>
+#include <QSize>
+#include <QString>
+#include <algorithm>
+#include <cmath>
+#include <mutex>
+#include <stdexcept>
+
+namespace ve {
+inline constexpr int maximumImageDimension = 32768;
+inline constexpr int maximumDlssTextureDimension = 16384;
+inline constexpr int imageDecoderBudgetMiB = 32768;
+inline constexpr quint64 maximumImagePixels = quint64(maximumImageDimension) * maximumImageDimension;
+
+inline void configureImageDecoding() {
+ // Set once, before readers run concurrently. Do not change process-wide
+ // environment variables or disable the codecs' other data validation.
+ static std::once_flag configured;
+ std::call_once(configured, [] { QImageReader::setAllocationLimit(imageDecoderBudgetMiB); });
+}
+
+inline void requireResolution(QSize size, const QString& operation = QStringLiteral("Image"),
+ int maximum = maximumImageDimension) {
+ if (size.width() <= 0 || size.height() <= 0 || size.width() > maximum || size.height() > maximum)
+ throw std::runtime_error(QString("%1 dimensions %2x%3 must be positive and at most %4 pixels per side.")
+ .arg(operation).arg(size.width()).arg(size.height()).arg(maximum).toStdString());
+}
+
+inline qsizetype imageByteCount(QSize size, int pixelBytes) {
+ requireResolution(size);
+ if (pixelBytes < 1 || pixelBytes > 16)
+ throw std::runtime_error("Unsupported image pixel size.");
+ // x64 only: even a 32K square float RGBA frame fits qsizetype. Widen
+ // before multiplication; several supported frames exceed 32-bit sizes.
+ return qsizetype(size.width()) * size.height() * pixelBytes;
+}
+
+enum class DimensionRounding { Ceil, EvenCeil, EvenNearest };
+inline int checkedDimension(double value, DimensionRounding rounding = DimensionRounding::Ceil) {
+ if (!std::isfinite(value) || value <= 0 || value > maximumImageDimension)
+ throw std::runtime_error("Requested resolution must be finite, positive and at most 32768 pixels per side.");
+ const double rounded = rounding == DimensionRounding::EvenNearest ? std::max(2., std::floor(value / 2 + .5) * 2)
+ : rounding == DimensionRounding::EvenCeil ? std::ceil(value / 2) * 2 : std::ceil(value);
+ if (rounded > maximumImageDimension)
+ throw std::runtime_error("Aligned resolution exceeds 32768 pixels per side.");
+ return int(rounded);
+}
+
+inline void requireImageAllocation(const QImage& image, const char* operation) {
+ if (image.isNull())
+ throw std::runtime_error(std::string(operation) + ": insufficient memory for the image buffer.");
+}
+} // namespace ve
diff --git a/src/media/video_preview.cpp b/src/media/video_preview.cpp
index 7b76d4f..5b98620 100644
--- a/src/media/video_preview.cpp
+++ b/src/media/video_preview.cpp
@@ -116,7 +116,7 @@ std::vector<TimedImage> VideoFrameReader::temporalContext(const QString& path, c
if(int(frames.size())>count+1)frames.pop_front();
if(seconds>=absoluteSeconds-1e-6) {
if(std::abs(seconds-absoluteSeconds)>1e-5)
- throw std::runtime_error("Native SR preview could not match the selected frame timestamp.");
+ throw std::runtime_error("Native reconstruction preview could not match the selected frame timestamp.");
if(includeFollowing){
if(auto following=decoder.read())frames.push_back(std::move(*following));
const double origin=decoder.timeOrigin();
@@ -139,6 +139,27 @@ void VideoFrameReader::prefetch(const QString &path, const MediaInfo &info, Fram
(void)frame(path, info, next, control, timeline, ordinal, cuda);
}
}
+double reconstructionContextStart(const QString& path,const MediaInfo& info,double selectedSeconds,
+ int precedingFrames,JobControl& control,int ordinal,bool preferCuda){
+ const double selected=std::max(0.,selectedSeconds),fps=info.fps>0?info.fps:30.;
+ const int count=std::clamp(precedingFrames,0,4096);
+ if(!info.variableFrameRate||!count)return std::max(0.,selected-count/fps);
+ double window=std::max(1.,2.*count/fps);
+ for(;;){
+ control.checkpoint();const double start=std::max(0.,selected-window);
+ HostVideoDecoder decoder(path,info,ordinal,start,preferCuda,control);
+ std::deque<double> times;
+ while(auto frame=decoder.read()){
+ control.checkpoint();const double time=frame->seconds()+decoder.timeOrigin()-info.presentationStartSeconds();
+ if(time>selected+1e-6)break;
+ if(!times.empty()&&time<=times.back())throw std::runtime_error("RR preview history has non-increasing timestamps.");
+ times.push_back(time);if(int(times.size())>count+1)times.pop_front();
+ if(time>=selected-1e-6)break;
+ }
+ if(int(times.size())>=count+1||start<=0)return times.empty()?0.:std::max(0.,times.front());
+ window*=2;
+ }
+}
QImage decodeTimelineFrame(const QString &path, const MediaInfo &source, double seconds, JobControl &control,
TimelinePrecision precision) {
const PreviewSeek seek(seconds);
diff --git a/src/media/video_preview.hpp b/src/media/video_preview.hpp
index 9dcc406..f3c8064 100644
--- a/src/media/video_preview.hpp
+++ b/src/media/video_preview.hpp
@@ -30,6 +30,9 @@ class VideoFrameReader {
struct Impl;
std::unique_ptr<Impl> impl_;
};
+// Select VFR context timestamps without retaining decoded image history.
+[[nodiscard]] double reconstructionContextStart(const QString& path,const MediaInfo& info,double selectedSeconds,
+ int precedingFrames,JobControl& control,int ordinal,bool preferCuda);
// Timeline stills retain the decoder's source precision. Posters use the
// reference's inexpensive JPEG path; neither operation opens native sessions.
[[nodiscard]] QImage decodeTimelineFrame(const QString &path, const MediaInfo &source, double seconds,
diff --git a/src/presentation/image_providers.cpp b/src/presentation/image_providers.cpp
index af6893f..337d547 100644
--- a/src/presentation/image_providers.cpp
+++ b/src/presentation/image_providers.cpp
@@ -1,4 +1,5 @@
#include "image_providers.hpp"
+#include "media/resolution.hpp"
#include "infrastructure/log.hpp"
#include <QElapsedTimer>
#include "infrastructure/paths.hpp"
@@ -133,6 +134,8 @@ QString PreviewProvider::storeFrame(const QImage& source, const QString& key, bo
}
}
const auto image = source.convertToFormat(source.depth() > 32 ? QImage::Format_RGBA64 : QImage::Format_RGBA8888);
+ requireResolution(image.size(), "Preview image");
+ requireImageAllocation(image, "Preview image conversion");
quint64 epoch = 0;
{
QMutexLocker lock(&mutex_);
@@ -275,14 +278,24 @@ QImage PreviewProvider::requestImage(const QString& urlId, QSize* size, const QS
qint32 format = 0;
QDataStream header(&file);
header >> magic >> dimensions >> format >> profile >> dpr >> dx >> dy;
- if (magic == 0x56454933 && dimensions.isValid() && dimensions.width() <= 16384 &&
- dimensions.height() <= 16384 && (format == QImage::Format_RGBA64 || format == QImage::Format_RGBA8888)) {
+ if (header.status() == QDataStream::Ok && magic == 0x56454933 && dimensions.isValid() &&
+ dimensions.width() <= maximumImageDimension && dimensions.height() <= maximumImageDimension &&
+ (format == QImage::Format_RGBA64 || format == QImage::Format_RGBA8888) &&
+ file.size()-file.pos() == imageByteCount(dimensions, format == QImage::Format_RGBA64 ? 8 : 4)) {
image = QImage(dimensions, QImage::Format(format));
- const auto data = file.readAll();
- if (data.size() != image.sizeInBytes())
- image = {};
- else {
- std::memcpy(image.bits(), data.constData(), size_t(data.size()));
+ if (!image.isNull()) {
+ // Read into the final allocation in bounded chunks. A
+ // 32K image must not require a second 4-8 GiB byte array.
+ const auto bytes = image.sizeInBytes();
+ qint64 offset=0;
+ while (offset < bytes) {
+ const auto received=file.read(reinterpret_cast<char*>(image.bits())+offset,
+ std::min<qint64>(8ll*1024*1024,bytes-offset));
+ if (received<=0) { image={}; break; }
+ offset+=received;
+ }
+ }
+ if (!image.isNull()) {
if (!profile.isEmpty()) image.setColorSpace(QColorSpace::fromIccProfile(profile));
image.setDevicePixelRatio(dpr);
image.setDotsPerMeterX(dx);
@@ -293,7 +306,10 @@ QImage PreviewProvider::requestImage(const QString& urlId, QSize* size, const QS
}
if (size)
*size = image.size();
- return requested.isValid() ? image.scaled(requested, Qt::KeepAspectRatio, Qt::SmoothTransformation)
- : image;
+ // Qt Quick still uses a GPU texture for display. Cap that copy, while
+ // preserving the full frame and its dimensions for processing/export.
+ QSize display=requested.isValid() ? requested : image.size();
+ if (display.width()>8192 || display.height()>8192) display.scale(8192,8192,Qt::KeepAspectRatio);
+ return !image.isNull() && display != image.size() ? image.scaled(display, Qt::KeepAspectRatio, Qt::SmoothTransformation) : image;
}
} // namespace ve
diff --git a/src/processing/effects.cpp b/src/processing/effects.cpp
index 5c93370..7bc9393 100644
--- a/src/processing/effects.cpp
+++ b/src/processing/effects.cpp
@@ -1,4 +1,5 @@
#include "effects.hpp"
+#include "media/resolution.hpp"
#include "color_analysis.hpp"
#include "infrastructure/paths.hpp"
#include "infrastructure/process.hpp"
@@ -58,7 +59,9 @@ QRgba64 pixel(Rgb rgb, quint16 alpha) {
}
QImage transform(const QImage& input, JobControl& control, const auto& operation) {
const auto source = input.convertToFormat(QImage::Format_RGBA64);
+ requireImageAllocation(source, "Effect input conversion");
QImage output(source.size(), QImage::Format_RGBA64);
+ requireImageAllocation(output, "Effect output allocation");
for (int y = 0; y < source.height(); ++y) {
control.checkpoint();
const auto* from = reinterpret_cast<const QRgba64*>(source.constScanLine(y));
@@ -99,6 +102,8 @@ std::vector<QImage> filterFrames(std::span<const QImage> frames, const QString&
if (frames.empty())
return {};
const auto size = frames.front().size();
+ requireResolution(size, "Filter input");
+ requireResolution(output, "Filter output");
const bool wide=frames.front().depth()>32;
const QString format=wide ? "rgba64le" : "rgba";
QByteArray data;
@@ -113,7 +118,7 @@ std::vector<QImage> filterFrames(std::span<const QImage> frames, const QString&
libplacebo("format="+format) + ",hwdownload,format="+format;
const auto result =
runProcess(Paths::instance().ffmpeg(),
- QStringList{"-v", "error"} + vulkanFilterArguments(device) +
+ QStringList{"-v", "error"} + vulkanFilterArguments(device, size.expandedTo(output)) +
QStringList{"-f",
"rawvideo",
"-pixel_format",
@@ -524,8 +529,8 @@ struct VideoFilterStage::Impl {
QStringList graph;
for (const auto& stage : stages) {
if (stage == "scale_method") {
- const QSize scaled(int(std::ceil(output.width()*settings.upscaling_factor/2))*2,
- int(std::ceil(output.height()*settings.upscaling_factor/2))*2);
+ const QSize scaled(checkedDimension(output.width()*settings.upscaling_factor,DimensionRounding::EvenCeil),
+ checkedDimension(output.height()*settings.upscaling_factor,DimensionRounding::EvenCeil));
graph.append(resizingGraph(output, scaled, settings.video_scaling_filter, false)); output = scaled;
} else if (stage == "cas_sharpening" && settings.cas_sharpness) {
graph.append(sharpeningGraph(settings, transfer == "iec61966-2-1" ? "srgb" : transfer == "linear" ? "linear" : "bt709"));
@@ -584,7 +589,9 @@ struct VideoFilterStage::Impl {
libplacebo("format=p010le:range=tv:color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc")+
",hwdownload,format=p010le";
}
- const auto args = QStringList{"-v", "error"} + vulkanFilterArguments(settings.ffmpeg_device) +
+ requireResolution(input, "Video filter input");
+ requireResolution(output, "Video filter output");
+ const auto args = QStringList{"-v", "error"} + vulkanFilterArguments(settings.ffmpeg_device,input.expandedTo(output)) +
QStringList{"-nofind_stream_info", "-f", "rawvideo", "-pixel_format", "rgba64le",
"-video_size", QString::number(input.width())+'x'+QString::number(input.height()), "-framerate",
QString::number(colors.fps > 0 ? colors.fps : 30., 'g', 15), "-threads:v", "1", "-i", "pipe:0", "-vf", filter,
diff --git a/src/processing/frame_stream.cpp b/src/processing/frame_stream.cpp
index 3fec7ac..805892b 100644
--- a/src/processing/frame_stream.cpp
+++ b/src/processing/frame_stream.cpp
@@ -1,4 +1,5 @@
#include "frame_stream.hpp"
+#include "media/resolution.hpp"
#include "infrastructure/paths.hpp"
#include "pipeline.hpp"
#include "preview_cache.hpp"
@@ -78,17 +79,22 @@ struct Stage {
control);
return filter->read();
}
+ const double seconds=frame->seconds();
+ if(name=="dlss_ray_reconstruction"&&(!std::isfinite(seconds)||
+ (previousSeconds&&seconds<=*previousSeconds)))
+ throw std::runtime_error("Ray Reconstruction requires finite, increasing presentation timestamps.");
if (!native) {
native = std::make_unique<FramePipeline>(settings, info, QStringList{name}, finalOutput,
bool(normalizer));
if (cache)
native->reuseResetPreviewResources();
}
- const double seconds=frame->seconds();
const double interval=previousSeconds && seconds>*previousSeconds ? seconds-*previousSeconds
: frame->duration>0 ? frame->duration*double(frame->timeBase.numerator)/frame->timeBase.denominator
: info.fps>0 ? 1./info.fps : 1./60;
- frame->image = native->process(frame->image, control, index, index == 0, float(std::clamp(interval*1000.,.01,1000.)));
+ const bool gap=name=="dlss_ray_reconstruction"&&previousSeconds&&
+ interval>std::max(.25,info.fps>0?4./info.fps:.25);
+ frame->image = native->process(frame->image, control, index, index == 0 || gap, float(std::clamp(interval*1000.,.01,1000.)));
previousSeconds=seconds;
++index;
return frame;
@@ -134,7 +140,7 @@ FrameStreamPipeline::FrameStreamPipeline(Settings settings, MediaInfo info, cons
if (cache)
stage->cacheOutput = index + 1 < stages.size();
source_ = [stage] { return stage->read(); };
- if(name=="scale_method"){info.width=int(std::ceil(info.width*settings.upscaling_factor/2))*2;info.height=int(std::ceil(info.height*settings.upscaling_factor/2))*2;}
+ if(name=="scale_method"){info.width=checkedDimension(info.width*settings.upscaling_factor,DimensionRounding::EvenCeil);info.height=checkedDimension(info.height*settings.upscaling_factor,DimensionRounding::EvenCeil);}
else if(name=="super_resolution"){auto size=rtxOutputSize({info.width,info.height},settings,true);info.width=size.width();info.height=size.height();}
else if(name=="dlss_super_resolution"){auto size=dlssOutputSize({info.width,info.height},settings.upscale_dlss_mode,true);info.width=size.width();info.height=size.height();}
if (name == "rtx_video_hdr") {
@@ -151,7 +157,9 @@ FrameStreamPipeline::FrameStreamPipeline(Settings settings, MediaInfo info, cons
.contains(name) ||
name == "dlss_super_resolution" && !final)
info.pixelFormat = "gbrp10le";
- else if (name == "neural_model" || name == "dlss_super_resolution")
+ else if(name=="dlss_ray_reconstruction"){
+ info.pixelFormat="rgba64le";info.sourceBitDepth=16;
+ }else if (name == "neural_model" || name == "dlss_super_resolution")
info.pixelFormat =
info.pixelFormat == "rgba" || info.pixelFormat.contains("8") || info.pixelFormat == "yuv420p"
? "rgba"
diff --git a/src/processing/interpolation_video.cpp b/src/processing/interpolation_video.cpp
index e8ed215..2e56647 100644
--- a/src/processing/interpolation_video.cpp
+++ b/src/processing/interpolation_video.cpp
@@ -4,6 +4,7 @@
#include "vfx_native.hpp"
#include "media/av_api.hpp"
#include "media/cuda_video.hpp"
+#include "media/native_rgb.hpp"
#include "media/frame_time.hpp"
#include "media/host_video.hpp"
#include "media/video_delivery.hpp"
@@ -61,8 +62,13 @@ class InterpolationDelivery {
if (cudaEncoding_ && !settings_.codec.contains("NVIDIA NVENC")) settings_.codec+=" (NVIDIA NVENC)";
neuralDelivery_=cudaEncoding_ && !after.isEmpty() && after.back()=="neural_model";
if (neuralDelivery_) after.removeLast();
+ if(cudaEncoding_&&!preview_&&after==QStringList{"dlss_ray_reconstruction"}){
+ rr_=std::make_unique<NativeEngines::RayReconstruction>(QSize(pixels_.width,pixels_.height),
+ settings_.rr_optical_flow_quality,false,true,nativeMediaTransfer(pixels_.transfer));
+ after.clear();output_.pixelFormat="rgba64le";
+ }
if (!after.isEmpty()) {
- output_.pixelFormat=after.back()=="dlss_super_resolution" || after.back()=="neural_model" ? "rgba64le" : "gbrp10le";
+ output_.pixelFormat=after.back()=="dlss_super_resolution" || after.back()=="dlss_ray_reconstruction" || after.back()=="neural_model" ? "rgba64le" : "gbrp10le";
post_=std::make_unique<FramePipeline>(settings, pixels_, after, !neuralDelivery_);
capacity_=videoBatchCapacity({std::max(pixels_.width, output_.width), std::max(pixels_.height, output_.height)});
}
@@ -86,7 +92,11 @@ class InterpolationDelivery {
control_.checkpoint();
ensureEncoder();
if (gpu_) {
- auto frame=selected.pixels.toVideo(*pool_, gpu_->pixelFormat()==VideoPixelFormat::P010, pixels_.hdr ? 2u : 1u, 0);
+ const bool reset=!rrSegment_||*rrSegment_!=selected.segment;
+ auto frame=rr_?rr_->process(selected.pixels.toRgb(),*pool_,gpu_->pixelFormat()==VideoPixelFormat::P010,
+ reset,quint32(index),float(1000.*base_.numerator/base_.denominator)):
+ selected.pixels.toVideo(*pool_, gpu_->pixelFormat()==VideoPixelFormat::P010, pixels_.hdr ? 2u : 1u, 0);
+ rrSegment_=selected.segment;
frame.pts=index; frame.duration=1; frame.timeBase=base_;
gpu_->write(frame);
} else {
@@ -106,6 +116,7 @@ class InterpolationDelivery {
if (gpu_) gpu_->finish();
else if (neural_) neural_->finish();
else host_->finish();
+ if(rr_)ve::info("dlssrr","FG -> RR FP16 RGB device counters: "+rr_->diagnostics());
}
private:
void ensureEncoder() {
@@ -146,6 +157,8 @@ class InterpolationDelivery {
std::vector<QImage> images_;
std::vector<qint64> indices_;
std::unique_ptr<FramePipeline> post_;
+ std::unique_ptr<NativeEngines::RayReconstruction> rr_;
+ std::optional<int> rrSegment_;
std::unique_ptr<CudaFramePool> pool_;
std::unique_ptr<HostVideoEncoder> host_;
std::unique_ptr<CudaVideoEncoder> gpu_;
@@ -154,10 +167,20 @@ class InterpolationDelivery {
} // namespace
bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& input, const Settings& configured,
const PipelineEstimate& estimate, const QString& destination, JobControl& control, const ProgressCallback& progress) {
- if (estimate.stages.isEmpty() || estimate.stages.front() != "frame_generation" || input.width%2 || input.height%2)
+ const bool rrBefore=estimate.stages==QStringList{"dlss_ray_reconstruction","frame_generation"};
+ const bool rrAfter=estimate.stages==QStringList{"frame_generation","dlss_ray_reconstruction"};
+ const bool rrCombined=rrBefore||rrAfter;
+ if (estimate.stages.isEmpty() || (!rrBefore&&estimate.stages.front() != "frame_generation") || input.width%2 || input.height%2)
return false;
auto settings=configured;
if (request.preview) { settings.codec="FFV1 Lossless RGB 10-bit"; settings.container="MKV"; }
+ const bool cudaEncoding = settings.codec.contains("NVIDIA NVENC") ||
+ (settings.ffmpeg_device != "cpu" && QStringList{"H.264", "H.265", "AV1"}.contains(settings.codec));
+ if(rrCombined&&(request.preview||!cudaEncoding||
+ (input.hdr?input.primaries!="bt2020"||input.colorSpace!="bt2020nc"||
+ !QStringList{"smpte2084","arib-std-b67"}.contains(input.transfer):
+ input.primaries!="bt709"||input.colorSpace!="bt709"||
+ !QStringList{"bt709","gamma22","bt470m"}.contains(input.transfer))))return false;
const int ordinal = gpuOrdinal(settings.ai_gpu_uuid);
const auto devices = detectGpus();
const auto selected = std::ranges::find_if(devices, [ordinal](const Gpu& gpu) { return gpu.index == ordinal; });
@@ -175,9 +198,9 @@ bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& inp
ScratchDirectory directory(QStringLiteral("interpolation-XXXXXX"));
if (!directory.isValid()) throw std::runtime_error("Cannot create the interpolation directory.");
auto info = input; info.fps = fps; info.pixelFormat = info.hdr ? "gbrp10le" : "rgba";
+ if(rrBefore){info.width=estimate.width;info.height=estimate.height;}
+ if(rrCombined)info.pixelFormat="rgba64le";
info.colorSpace="gbr"; info.range="pc";
- const bool cudaEncoding = settings.codec.contains("NVIDIA NVENC") ||
- (settings.ffmpeg_device != "cpu" && QStringList{"H.264", "H.265", "AV1"}.contains(settings.codec));
const auto video = directory.filePath(settings.codec.startsWith("ProRes") ? "video.mov" : request.preview ? "video.mkv" : "video.nut");
QElapsedTimer elapsed; elapsed.start();
qint64 decoded = 0;
@@ -188,7 +211,10 @@ bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& inp
auto frame = decoder->read();
if (!frame) throw std::runtime_error("The source contains no decodable video frames.");
sourceTimeOrigin=decoder->timeOrigin();
- NativeEngines::instance().prepare(ordinal, {"frame_generation"});
+ NativeEngines::instance().prepare(ordinal, rrCombined?estimate.stages:QStringList{"frame_generation"});
+ std::unique_ptr<NativeEngines::RayReconstruction> rrSource;
+ if(rrBefore)rrSource=std::make_unique<NativeEngines::RayReconstruction>(QSize(input.width,input.height),
+ settings.rr_optical_flow_quality,false,true,nativeMediaTransfer(input.transfer));
const auto maximum = NativeEngines::Interpolation::nativeMaximum();
const bool native = !input.variableFrameRate && std::abs(ratio-multiple)<1e-7 && multiple>=2 && multiple<=maximum;
if (fps>input.fps && settings.frame_interpolation_engine == "Native DLSSG" && !native)
@@ -200,11 +226,12 @@ bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& inp
std::vector<InterpolationStage> stages;
for (int level=0; level<levels; ++level) stages.push_back({std::make_unique<NativeEngines::Interpolation>(
QSize(info.width, info.height), generated, info.hdr, settings.frame_interpolation_optical_flow_quality,
- false, level == levels-1 ? 64 : 0), {}, generated});
+ rrCombined, level == levels-1 ? 64 : 0), {}, generated});
// Source resampling still needs the native RGB conversion, but generates no frames.
if (stages.empty()) stages.push_back({std::make_unique<NativeEngines::Interpolation>(
- QSize(info.width, info.height), 1, info.hdr, settings.frame_interpolation_optical_flow_quality, false, 64), {}, 0});
- InterpolationDelivery delivery(video, settings, info, estimate, decoder->device(), cudaEncoding, ordinal, base, count, control, progress, request.preview);
+ QSize(info.width, info.height), 1, info.hdr, settings.frame_interpolation_optical_flow_quality, rrCombined, 64), {}, 0});
+ auto deliveryEstimate=estimate;if(rrBefore)deliveryEstimate.stages={"frame_generation"};
+ InterpolationDelivery delivery(video, settings, info, deliveryEstimate, decoder->device(), cudaEncoding, ordinal, base, count, control, progress, request.preview);
auto writeSelected = [&](const TimedSurface& selected, qint64 index) {
delivery.write(selected,index);
};
@@ -231,8 +258,13 @@ bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& inp
if (request.seconds>0 && time.seconds()>=duration-1e-9) break;
if (lastTime && (time<=*lastTime || time-*lastTime>nominal.fraction(2,1))) ++segment;
frame->rotation = uint32_t((rotation%360+360)%360);
- auto result = stages.front().session->evaluate(*frame, input,
- stages.front().previous && segment != stages.front().previous->segment, true);
+ const bool discontinuity=stages.front().previous&&segment!=stages.front().previous->segment;
+ NativeEngines::Interpolation::Result result;
+ if(rrSource){
+ const auto interval=lastTime?(time-*lastTime).seconds():nominal.seconds();
+ auto rgb=rrSource->processRgb(*frame,!decoded||discontinuity,quint32(decoded),float(std::clamp(interval*1000.,.01,1000.)));
+ result=stages.front().session->evaluate(rgb,discontinuity,true);
+ }else result=stages.front().session->evaluate(*frame,input,discontinuity,true);
if (levels == 0) result.generated.clear();
auto items = stages.front().push(std::move(result), time, segment);
segment = stages.front().previous->segment;
@@ -244,6 +276,7 @@ bool renderInterpolationVideo(const RenderRequest& request, const MediaInfo& inp
if (request.seconds > 0) actualDuration = std::min(actualDuration, request.seconds);
writer.finish(qint64(std::ceil(actualDuration*fps-1e-9)));
delivery.finish();
+ if(rrSource)ve::info("dlssrr","RR -> FG FP16 RGB device counters: "+rrSource->diagnostics());
ve::info("video", "Interpolation streamed through temporal stages directly to the selected encoder.");
} catch (const CudaUnavailable& error) {
if (decoded) throw;
diff --git a/src/processing/native_engines.cpp b/src/processing/native_engines.cpp
index d8f7ee4..941ad4d 100644
--- a/src/processing/native_engines.cpp
+++ b/src/processing/native_engines.cpp
@@ -1,4 +1,5 @@
#include "native_engines.hpp"
+#include "media/resolution.hpp"
#include "frame_interpolation/dlssg_bridge.h"
#include "infrastructure/log.hpp"
#include "infrastructure/paths.hpp"
@@ -6,9 +7,11 @@
#include "media/image_codecs.hpp"
#include "media/native_frame.hpp"
#include "media/cuda_video.hpp"
+#include "media/native_rgb.hpp"
#include "neural_rendering/dlss5nr_bridge.h"
#include "rtx_video/rtx_video_bridge.h"
#include "super_resolution/dlss_bridge.h"
+#include "ray_reconstruction/dlssrr_bridge.h"
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
@@ -160,6 +163,7 @@ Dlss5NrRenderParamsV11 neuralParameters(const Settings& settings, QSize size, bo
struct NativeEngines::Impl {
Module nr{"dlssnr", "neuroframe_engine_neural_rendering.dll", "dlss5nr"};
Module sr{"dlsssr", "neuroframe_engine_super_resolution.dll", "dlsssr"};
+ Module rr{"dlssrr", "neuroframe_engine_ray_reconstruction.dll", "dlssrr"};
Module rtx{"rtx_video", "neuroframe_engine_upscaling.dll", "rtxv"};
Module fi{"dlssg", "neuroframe_engine_frame_interpolation.dll", "fi"};
std::recursive_mutex mutex;
@@ -224,22 +228,26 @@ void NativeEngines::prepare(int ordinal, const QStringList& stages) {
impl_->ordinal = ordinal;
if (stages.contains("neural_model") || stages.contains("dlss_super_resolution"))
impl_->sr.initialize(ordinal); // Register NGX search paths before feature 18 creates its device.
- if (stages.contains("neural_model")) impl_->nr.initialize(ordinal);
if (stages.contains("frame_generation")) impl_->fi.initialize(ordinal);
+ if (stages.contains("dlss_ray_reconstruction")) {
+ impl_->rr.initialize(ordinal);
+ if(impl_->rr.function<uint32_t(__cdecl*)()>("dlssrr_abi_version")()!=2)
+ throw std::runtime_error("DLSS Ray Reconstruction requires native-resolution ABI 2.");
+ }
+ if (stages.contains("neural_model")) impl_->nr.initialize(ordinal);
if (stages.contains("super_resolution") || stages.contains("rtx_video_hdr")) impl_->rtx.initialize(ordinal);
using Abi = uint32_t(__cdecl*)();
- if (impl_->nr.function<Abi>("dlss5nr_frame_abi_version")() != 11 ||
- impl_->sr.function<Abi>("dlsssr_abi_version")() != 4)
+ const bool nr=stages.contains("neural_model"),sr=stages.contains("dlss_super_resolution");
+ if ((nr && impl_->nr.function<Abi>("dlss5nr_frame_abi_version")() != 11) ||
+ ((nr||sr) && impl_->sr.function<Abi>("dlsssr_abi_version")() != 4))
throw std::runtime_error("The bundled NVIDIA engines use an incompatible ABI.");
- impl_->diagnostics = "Neural Rendering " + impl_->nr.version() + " (ABI 11)\nDLSS Super Resolution " +
- impl_->sr.version() + " (ABI 4)";
- for (auto* module : {&impl_->fi, &impl_->rtx}) {
- try {
- impl_->diagnostics += '\n' + module->version();
- } catch (const std::exception& error) {
- impl_->diagnostics += '\n' + QString::fromUtf8(error.what());
- }
- }
+ QStringList diagnostics;
+ if(nr)diagnostics<<"Neural Rendering "+impl_->nr.version()+" (ABI 11)";
+ if(nr||sr)diagnostics<<"DLSS Super Resolution "+impl_->sr.version()+" (ABI 4)";
+ if(stages.contains("dlss_ray_reconstruction"))diagnostics<<"DLSS Ray Reconstruction "+impl_->rr.version()+" (ABI 2, 1x)";
+ if(stages.contains("frame_generation"))diagnostics<<"Frame Generation "+impl_->fi.version();
+ if(stages.contains("super_resolution")||stages.contains("rtx_video_hdr"))diagnostics<<"RTX Video "+impl_->rtx.version();
+ impl_->diagnostics=diagnostics.join('\n');
info("runtime", impl_->diagnostics);
}
QString NativeEngines::diagnostics() const {
@@ -419,6 +427,7 @@ QImage NativeEngines::SuperResolution::process(const QImage& input, bool reset,
? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
const bool eightBit=still_ && !wideOutput_ && source.depth()<=32;
QImage output(output_,eightBit ? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
+ requireImageAllocation(output, "DLSS output allocation");
FrameDesc frame{sizeof(FrameDesc),
4,
source.constBits(),
@@ -440,6 +449,147 @@ QImage NativeEngines::SuperResolution::process(const QImage& input, bool reset,
output.setColorSpace(input.colorSpace());
return output;
}
+NativeEngines::RayReconstruction::RayReconstruction(QSize size, const QString& flowQuality, bool still,
+ bool wideOutput, quint32 colorTransfer, bool alpha)
+ : output_(size),still_(still),wideOutput_(wideOutput),transfer_(colorTransfer) {
+ auto& impl = *instance().impl_;
+ std::lock_guard lock(impl.mutex);
+ impl.rr.initialize(impl.ordinal);
+ DlssRrSessionDesc descriptor{
+ sizeof(DlssRrSessionDesc),
+ 2,
+ uint32_t(size.width()),
+ uint32_t(size.height()),
+ uint32_t(still),
+ flowIndex(flowQuality), colorTransfer, colorTransfer>=5?2u:1u, 0u, alpha ? 1u : 0u};
+ std::array<char, 4096> error{};
+ using Create = void*(__cdecl*)(const DlssRrSessionDesc*, char*, int);
+ session_ =
+ impl.rr.function<Create>("dlssrr_session_create")(&descriptor, error.data(), int(error.size()));
+ check(session_ != nullptr, error);
+}
+NativeEngines::RayReconstruction::~RayReconstruction() {
+ if (session_) {
+ auto& impl = *instance().impl_;
+ std::lock_guard lock(impl.mutex);
+ impl.rr.function<void(__cdecl*)(void*)>("dlssrr_session_release")(session_);
+ }
+}
+QImage NativeEngines::RayReconstruction::process(const QImage& input, bool reset, quint32 phase, float frameTimeMs) {
+ auto& impl = *instance().impl_;
+ std::lock_guard lock(impl.mutex);
+ const auto source = input.convertToFormat(input.format() == QImage::Format_RGBA8888
+ ? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
+ const bool eightBit=still_ && !wideOutput_ && source.depth()<=32;
+ QImage output(output_,eightBit ? QImage::Format_RGBA8888 : QImage::Format_RGBA64);
+ requireImageAllocation(output, "DLSS output allocation");
+ DlssRrFrameDesc frame{sizeof(DlssRrFrameDesc),
+ 2,
+ source.constBits(),
+ uint32_t(source.bytesPerLine()),
+ output.bits(),
+ uint32_t(output.bytesPerLine()),
+ uint32_t(reset),
+ phase,
+ source.format() == QImage::Format_RGBA8888 ? 1u : 2u,
+ eightBit ? 1u : 2u, frameTimeMs};
+ DlssRrFrameResult result{};
+ result.size = sizeof(result);
+ result.abi = 2;
+ std::array<char, 4096> error{};
+ using Process = int(__cdecl*)(void*, const DlssRrFrameDesc*, DlssRrFrameResult*, char*, int);
+ check(impl.rr.function<Process>("dlssrr_process_rgba16f")(session_, &frame, &result, error.data(),
+ int(error.size())),
+ error);
+ output.setColorSpace(input.colorSpace());
+ return output;
+}
+CudaVideoFrame NativeEngines::RayReconstruction::process(const CudaVideoFrame& input, CudaFramePool& pool,
+ bool p010, bool reset, quint32 phase, float frameTimeMs) {
+ if(!input.owner || input.memory!=FrameMemory::Cuda)
+ throw std::runtime_error("Ray Reconstruction requires owned CUDA decoder planes.");
+ auto& impl=*instance().impl_;
+ std::lock_guard lock(impl.mutex);
+ DlssRrCudaFrameDesc frame{};
+ frame.size=sizeof(frame);frame.abi=2;frame.width=uint32_t(input.size.width());frame.height=uint32_t(input.size.height());
+ frame.pixel_format=input.format==VideoPixelFormat::P010?5u:4u;
+ frame.y_pointer=input.planes[0];frame.uv_pointer=input.planes[1];frame.y_stride=input.strides[0];frame.uv_stride=input.strides[1];
+ frame.color_matrix=input.colorMatrix;frame.color_range=input.colorRange;frame.rotation=input.rotation;
+ frame.reset=uint32_t(reset);frame.phase=phase;frame.output_p010=uint32_t(p010);
+ frame.video_color=1;frame.chroma_location=input.chromaLocation;frame.frame_time_ms=frameTimeMs;
+ DlssRrFrameResult result{};result.size=sizeof(result);result.abi=2;
+ void* surface=nullptr;
+ std::array<char,4096> error{};
+ using Process=int(__cdecl*)(void*,const DlssRrCudaFrameDesc*,DlssRrFrameResult*,void**,char*,int);
+ check(impl.rr.function<Process>("dlssrr_process_cuda_yuv")(session_,&frame,&result,&surface,error.data(),int(error.size())),error);
+ // A surface owns its allocation independently of the session. AVBufferRef
+ // keeps it alive through NVENC reordering and flush, including exceptions.
+ const auto release=impl.rr.function<void(__cdecl*)(void*)>("dlssrr_cuda_surface_release");
+ std::shared_ptr<void> owner(surface,[release](void* value){release(value);});
+ DlssRrCudaSurfaceDesc desc{};desc.size=sizeof(desc);desc.abi=2;
+ using Describe=int(__cdecl*)(void*,DlssRrCudaSurfaceDesc*);
+ if(!impl.rr.function<Describe>("dlssrr_cuda_surface_desc")(surface,&desc) ||
+ desc.width!=uint32_t(output_.width()) || desc.height!=uint32_t(output_.height()) || desc.pixel_format!=(p010?5u:4u))
+ throw std::runtime_error("Ray Reconstruction returned an incompatible device surface.");
+ auto output=pool.wrap(std::move(owner),{desc.y_pointer,desc.uv_pointer,0},{desc.stride,desc.stride,0},input.colorMatrix,input.colorRange);
+ output.pts=input.pts;output.duration=input.duration;output.timeBase=input.timeBase;
+ return output;
+}
+QString NativeEngines::RayReconstruction::diagnostics() const {
+ auto& impl=*instance().impl_;
+ std::lock_guard lock(impl.mutex);
+ std::array<char,4096> value{};
+ using Status=int(__cdecl*)(void*,char*,int);
+ if(!impl.rr.function<Status>("dlssrr_session_status")(session_,value.data(),int(value.size())))
+ throw std::runtime_error("Cannot read Ray Reconstruction delivery counters.");
+ return QString::fromUtf8(value.data());
+}
+GpuRgbFrame NativeEngines::RayReconstruction::processRgb(const CudaVideoFrame& input,bool reset,quint32 phase,float frameTimeMs) {
+ if(!input.owner||input.memory!=FrameMemory::Cuda)throw std::runtime_error("RR RGB delivery requires owned CUDA input.");
+ auto& impl=*instance().impl_;std::lock_guard lock(impl.mutex);
+ DlssRrCudaFrameDesc frame{};frame.size=sizeof(frame);frame.abi=2;
+ frame.width=uint32_t(input.size.width());frame.height=uint32_t(input.size.height());
+ frame.pixel_format=input.format==VideoPixelFormat::P010?5u:4u;
+ frame.y_pointer=input.planes[0];frame.uv_pointer=input.planes[1];frame.y_stride=input.strides[0];frame.uv_stride=input.strides[1];
+ frame.color_matrix=input.colorMatrix;frame.color_range=input.colorRange;frame.rotation=input.rotation;
+ frame.reset=uint32_t(reset);frame.phase=phase;frame.output_p010=2;frame.video_color=1;
+ frame.chroma_location=input.chromaLocation;frame.frame_time_ms=frameTimeMs;
+ DlssRrFrameResult result{};result.size=sizeof(result);result.abi=2;
+ void* surface=nullptr;std::array<char,4096> error{};
+ using Process=int(__cdecl*)(void*,const DlssRrCudaFrameDesc*,DlssRrFrameResult*,void**,char*,int);
+ check(impl.rr.function<Process>("dlssrr_process_cuda_yuv")(session_,&frame,&result,&surface,error.data(),int(error.size())),error);
+ const auto release=impl.rr.function<void(__cdecl*)(void*)>("dlssrr_cuda_surface_release");
+ std::shared_ptr<void> owner(surface,[release](void* value){release(value);});
+ DlssRrCudaSurfaceDesc desc{};desc.size=sizeof(desc);desc.abi=2;
+ using Describe=int(__cdecl*)(void*,DlssRrCudaSurfaceDesc*);
+ if(!impl.rr.function<Describe>("dlssrr_cuda_surface_desc")(surface,&desc)||desc.pixel_format!=2||desc.uv_pointer||
+ desc.width!=uint32_t(output_.width())||desc.height!=uint32_t(output_.height()))
+ throw std::runtime_error("RR returned an incompatible RGB surface.");
+ return {std::move(owner),output_,desc.y_pointer,desc.stride,transfer_,transfer_>=5?2u:1u,bool(result.reserved&1u)};
+}
+CudaVideoFrame NativeEngines::RayReconstruction::process(const GpuRgbFrame& input,CudaFramePool& pool,
+ bool p010,bool reset,quint32 phase,float frameTimeMs) {
+ if(!input.owner||!input.pointer||input.transfer!=transfer_)
+ throw std::runtime_error("RR RGB input requires an owned surface with the session's transfer function.");
+ auto& impl=*instance().impl_;std::lock_guard lock(impl.mutex);
+ DlssRrCudaRgbFrameDesc frame{};frame.size=sizeof(frame);frame.abi=2;
+ frame.width=uint32_t(input.size.width());frame.height=uint32_t(input.size.height());frame.pointer=input.pointer;
+ frame.stride=input.stride;frame.reset=uint32_t(reset||input.historyReset);frame.phase=phase;
+ frame.output_format=uint32_t(p010);frame.frame_time_ms=frameTimeMs;
+ frame.color_matrix=input.primaries==2?2u:1u;frame.color_range=0;
+ DlssRrFrameResult result{};result.size=sizeof(result);result.abi=2;
+ void* surface=nullptr;std::array<char,4096> error{};
+ using Process=int(__cdecl*)(void*,const DlssRrCudaRgbFrameDesc*,DlssRrFrameResult*,void**,char*,int);
+ check(impl.rr.function<Process>("dlssrr_process_cuda_rgba16f")(session_,&frame,&result,&surface,error.data(),int(error.size())),error);
+ const auto release=impl.rr.function<void(__cdecl*)(void*)>("dlssrr_cuda_surface_release");
+ std::shared_ptr<void> owner(surface,[release](void* value){release(value);});
+ DlssRrCudaSurfaceDesc desc{};desc.size=sizeof(desc);desc.abi=2;
+ using Describe=int(__cdecl*)(void*,DlssRrCudaSurfaceDesc*);
+ if(!impl.rr.function<Describe>("dlssrr_cuda_surface_desc")(surface,&desc)||desc.pixel_format!=(p010?5u:4u)||
+ desc.width!=uint32_t(output_.width())||desc.height!=uint32_t(output_.height()))
+ throw std::runtime_error("RR returned an incompatible RGB delivery surface.");
+ return pool.wrap(std::move(owner),{desc.y_pointer,desc.uv_pointer,0},{desc.stride,desc.stride,0},frame.color_matrix,frame.color_range);
+}
NativeEngines::RtxVideo::RtxVideo(QSize input, QSize output, const Settings& settings, bool hdr, bool video, bool wideInput)
: output_(output), hdr_(hdr), packed_(video && wideInput), floatHdr_(hdr && settings.upscale_hdr_precision == "FP16"), video_(video) {
auto& impl = *instance().impl_;
@@ -522,6 +672,7 @@ QImage NativeEngines::RtxVideo::evaluate(const RtxvFrameDescV1& from) {
auto& impl=*instance().impl_;
std::lock_guard lock(impl.mutex);
QImage output(output_, hdr_ && floatHdr_ ? QImage::Format_RGBA16FPx4 : QImage::Format_RGBA8888);
+ requireImageAllocation(output, "RTX Video output allocation");
auto descriptor = [](const QImage& image, int format) {
RtxvFrameDescV1 frame{};
frame.struct_size = sizeof(frame);
@@ -589,6 +740,7 @@ struct NativeEngines::Interpolation::State {
struct NativeEngines::Interpolation::Surface::Storage {
void* handle = nullptr;
FrameDescriptorV1 descriptor{};
+ quint32 mediaTransfer=1;
std::shared_ptr<Interpolation::State> session;
~Storage() {
if (!handle) return;
@@ -599,8 +751,7 @@ struct NativeEngines::Interpolation::Surface::Storage {
};
NativeEngines::Interpolation::Interpolation(QSize size, int generated, bool hdr, const QString& flowQuality,
bool highPrecision, int surfacePoolSize)
- : state_(std::make_shared<State>()), size_(size), hdr_(hdr), floating_(hdr) {
- Q_UNUSED(highPrecision);
+ : state_(std::make_shared<State>()), size_(size), hdr_(hdr), floating_(hdr||highPrecision) {
auto& impl = *instance().impl_;
std::lock_guard lock(impl.mutex);
impl.fi.initialize(impl.ordinal);
@@ -641,7 +792,7 @@ std::vector<QImage> NativeEngines::Interpolation::process(const QImage& input, b
for (const auto& surface : result.generated) output.push_back(surface.toHost());
return output;
}
-NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(const QImage& input, bool reset, bool detectCuts) {
+NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(const QImage& input, bool reset, bool detectCuts,quint32 transfer) {
const auto source =
input.convertToFormat(floating_ ? QImage::Format_RGBA16FPx4 : QImage::Format_RGBA8888);
FrameDescriptorV1 frame{};
@@ -655,11 +806,11 @@ NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(cons
frame.strides[0] = uint32_t(source.bytesPerLine());
frame.color_matrix = hdr_ ? 2u : 1u;
frame.color_range = 1;
- frame.color_primaries = hdr_ ? 9u : 1u;
+ frame.color_primaries = hdr_ ? 2u : 1u;
frame.color_transfer = hdr_ ? 16u : 1u;
frame.reserved[0] = 1;
frame.reserved[1] = 1;
- return copyCurrentInput(evaluateDescriptor(frame, reset, detectCuts), frame);
+ return copyCurrentInput(evaluateDescriptor(frame, reset, detectCuts), frame,transfer==0xffffffffu?(hdr_?5u:1u):transfer);
}
NativeEngines::Interpolation::Surface NativeEngines::Interpolation::own(void* handle) {
if (!handle) throw std::runtime_error("DLSSG returned an empty surface.");
@@ -720,9 +871,9 @@ NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(
frame.color_transfer = colors.transfer == "iec61966-2-1" ? 1u : colors.transfer == "bt470m" ? 2u
: colors.transfer == "bt470bg" ? 3u : colors.transfer == "linear" ? 4u : 0u;
frame.rotation = input.rotation; frame.reserved[0] = 1; frame.reserved[1] = input.chromaLocation;
- return copyCurrentInput(evaluateDescriptor(frame, reset, detectCuts), frame);
+ return copyCurrentInput(evaluateDescriptor(frame, reset, detectCuts), frame,nativeMediaTransfer(colors.transfer));
}
-NativeEngines::Interpolation::Result NativeEngines::Interpolation::copyCurrentInput(Result result, const FrameDescriptorV1& frame) {
+NativeEngines::Interpolation::Result NativeEngines::Interpolation::copyCurrentInput(Result result, const FrameDescriptorV1& frame,quint32 transfer) {
auto& impl = *instance().impl_;
std::lock_guard lock(impl.mutex);
std::array<char, 4096> error{};
@@ -730,12 +881,14 @@ NativeEngines::Interpolation::Result NativeEngines::Interpolation::copyCurrentIn
auto* handle = impl.fi.function<Copy>("fi_session_copy_input_rgb")(state_->session, error.data(), int(error.size()));
check(handle != nullptr, error);
result.source = own(handle);
+ result.source.state_->mediaTransfer=transfer;
// Describing a surface only supplies its layout. Preserve interpretation separately.
auto& descriptor = result.source.state_->descriptor;
descriptor.color_matrix = frame.color_matrix; descriptor.color_range = frame.color_range;
descriptor.color_primaries = frame.color_primaries; descriptor.color_transfer = frame.color_transfer;
descriptor.reserved[0] = 1; descriptor.reserved[1] = frame.reserved[1];
for (auto& surface : result.generated) {
+ surface.state_->mediaTransfer=transfer;
auto& generated = surface.state_->descriptor;
generated.color_matrix = descriptor.color_matrix; generated.color_range = descriptor.color_range;
generated.color_primaries = descriptor.color_primaries; generated.color_transfer = descriptor.color_transfer;
@@ -749,6 +902,7 @@ NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(
auto result = evaluateDescriptor(input.state_->descriptor, reset, detectCuts);
result.source = input;
for (auto& surface : result.generated) {
+ surface.state_->mediaTransfer=input.state_->mediaTransfer;
auto& descriptor = surface.state_->descriptor;
const auto& from = input.state_->descriptor;
descriptor.color_matrix = from.color_matrix; descriptor.color_range = from.color_range;
@@ -757,6 +911,22 @@ NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(
}
return result;
}
+NativeEngines::Interpolation::Result NativeEngines::Interpolation::evaluate(const GpuRgbFrame& input,bool reset,bool detectCuts) {
+ if(!floating_||!input.owner||!input.pointer||input.transfer>6||input.primaries>2)
+ throw std::runtime_error("RGB interpolation requires an owned encoded FP16 surface and FP16 session.");
+ FrameDescriptorV1 frame{};frame.struct_size=sizeof(frame);frame.abi_version=4;frame.memory_type=2;frame.pixel_format=2;
+ frame.width=uint32_t(input.size.width());frame.height=uint32_t(input.size.height());frame.planes[0]=input.pointer;frame.strides[0]=input.stride;
+ frame.color_matrix=input.primaries==2?2u:1u;frame.color_range=1;frame.color_primaries=input.primaries;
+ static constexpr uint32_t transfers[]={1,0,4,2,3,0,0};frame.color_transfer=transfers[input.transfer];
+ frame.reserved[0]=1;frame.reserved[1]=1;
+ return copyCurrentInput(evaluateDescriptor(frame,reset||input.historyReset,detectCuts),frame,input.transfer);
+}
+GpuRgbFrame NativeEngines::Interpolation::Surface::toRgb() const {
+ if(!state_||state_->descriptor.pixel_format!=2)
+ throw std::runtime_error("RGB reconstruction requires an owned FP16 interpolation surface.");
+ const auto& frame=state_->descriptor;
+ return {state_,{int(frame.width),int(frame.height)},frame.planes[0],frame.strides[0],state_->mediaTransfer,frame.color_primaries,false};
+}
QImage NativeEngines::Interpolation::Surface::toHost() const {
if (!state_) throw std::runtime_error("Cannot download a released DLSSG surface.");
auto& impl = *instance().impl_;
@@ -764,6 +934,7 @@ QImage NativeEngines::Interpolation::Surface::toHost() const {
const auto& descriptor = state_->descriptor;
QImage pixels(int(descriptor.width), int(descriptor.height), descriptor.pixel_format == 2
? QImage::Format_RGBA16FPx4 : QImage::Format_RGBA8888);
+ requireImageAllocation(pixels, "Frame Generation output allocation");
std::array<char, 4096> error{};
using Copy = int(__cdecl*)(void*, void*, uint32_t, char*, int);
check(impl.fi.function<Copy>("fi_surface_copy_rgb_to_host")(state_->handle, pixels.bits(),
diff --git a/src/processing/native_engines.hpp b/src/processing/native_engines.hpp
index 99ed311..12cd756 100644
--- a/src/processing/native_engines.hpp
+++ b/src/processing/native_engines.hpp
@@ -10,6 +10,7 @@ struct RtxvFrameDescV1;
namespace ve {
struct CudaVideoFrame;
+struct GpuRgbFrame;
class CudaFramePool;
struct MediaInfo;
class JobControl;
@@ -29,6 +30,7 @@ class NativeEngines {
[[nodiscard]] QImage neural(const QImage& input, const Settings& settings, bool video, bool reset);
class NeuralRendering;
class SuperResolution;
+ class RayReconstruction;
class RtxVideo;
class Interpolation;
@@ -69,6 +71,25 @@ class NativeEngines::SuperResolution {
QSize output_;
bool still_=false, wideOutput_=false;
};
+class NativeEngines::RayReconstruction {
+ public:
+ RayReconstruction(QSize size, const QString& flowQuality, bool still, bool wideOutput = false,
+ quint32 colorTransfer = 0, bool alpha = false);
+ ~RayReconstruction();
+ [[nodiscard]] QImage process(const QImage& input, bool reset, quint32 phase = 0, float frameTimeMs = 0);
+ [[nodiscard]] CudaVideoFrame process(const CudaVideoFrame& input, CudaFramePool& pool,
+ bool p010, bool reset, quint32 phase = 0, float frameTimeMs = 0);
+ [[nodiscard]] GpuRgbFrame processRgb(const CudaVideoFrame& input,bool reset,quint32 phase=0,float frameTimeMs=0);
+ [[nodiscard]] CudaVideoFrame process(const GpuRgbFrame& input,CudaFramePool& pool,
+ bool p010,bool reset,quint32 phase=0,float frameTimeMs=0);
+ [[nodiscard]] QString diagnostics() const;
+
+ private:
+ void* session_ = nullptr;
+ QSize output_;
+ bool still_=false, wideOutput_=false;
+ quint32 transfer_=0;
+};
class NativeEngines::RtxVideo {
public:
RtxVideo(QSize input, QSize output, const Settings& settings, bool hdr, bool video, bool wideInput = false);
@@ -93,6 +114,7 @@ class NativeEngines::Interpolation {
[[nodiscard]] QImage toHost() const;
[[nodiscard]] QImage toHostRgb10() const;
[[nodiscard]] CudaVideoFrame toVideo(CudaFramePool& pool, bool p010, uint32_t matrix, uint32_t range) const;
+ [[nodiscard]] GpuRgbFrame toRgb() const;
[[nodiscard]] explicit operator bool() const { return bool(state_); }
private:
struct Storage;
@@ -109,15 +131,16 @@ class NativeEngines::Interpolation {
bool highPrecision = false, int surfacePoolSize = 0);
~Interpolation();
[[nodiscard]] std::vector<QImage> process(const QImage& input, bool reset);
- [[nodiscard]] Result evaluate(const QImage& input, bool reset = false, bool detectCuts = true);
+ [[nodiscard]] Result evaluate(const QImage& input, bool reset = false, bool detectCuts = true,quint32 transfer=0xffffffffu);
[[nodiscard]] Result evaluate(const CudaVideoFrame& input, const MediaInfo& colors, bool reset = false,
bool detectCuts = true);
[[nodiscard]] Result evaluate(const Surface& input, bool reset = false, bool detectCuts = false);
+ [[nodiscard]] Result evaluate(const GpuRgbFrame& input,bool reset=false,bool detectCuts=true);
[[nodiscard]] static int nativeMaximum();
private:
[[nodiscard]] Result evaluateDescriptor(const FrameDescriptorV1& descriptor, bool reset, bool detectCuts);
- [[nodiscard]] Result copyCurrentInput(Result result, const FrameDescriptorV1& descriptor);
+ [[nodiscard]] Result copyCurrentInput(Result result, const FrameDescriptorV1& descriptor,quint32 transfer=1);
[[nodiscard]] Surface own(void* surface);
std::shared_ptr<State> state_;
QSize size_;
diff --git a/src/processing/pipeline.cpp b/src/processing/pipeline.cpp
index 3b6e419..de9aeac 100644
--- a/src/processing/pipeline.cpp
+++ b/src/processing/pipeline.cpp
@@ -6,10 +6,13 @@
#include "infrastructure/paths.hpp"
#include "infrastructure/process.hpp"
#include "media/frame_batch.hpp"
+#include "media/resolution.hpp"
#include "media/frame_time.hpp"
#include "media/av_api.hpp"
#include "media/native_frame.hpp"
#include "media/cuda_video.hpp"
+#include "media/native_rgb.hpp"
+#include "media/video_preview.hpp"
#include "media/host_video.hpp"
#include "media/video_delivery.hpp"
#include "interpolation_video.hpp"
@@ -45,7 +48,7 @@
namespace ve {
namespace {
int even(double value) {
- return std::max(2, int(std::floor(value / 2 + .5)) * 2);
+ return checkedDimension(value, DimensionRounding::EvenNearest);
}
QString imageExtension(const QString& format) {
return QMap<QString, QString>{
@@ -136,6 +139,91 @@ bool renderCudaVideo(const RenderRequest& request, const MediaInfo& source, cons
request.preview ? std::nullopt : std::optional(sourceTimeOrigin));
return true;
}
+bool renderRayReconstructionVideo(const RenderRequest& request,const MediaInfo& source,const Settings& settings,
+ const PipelineEstimate& estimate,const QString& destination,JobControl& control,
+ const ProgressCallback& progress) {
+ if(request.preview || estimate.stages!=QStringList{"dlss_ray_reconstruction"} ||
+ (source.width|source.height|estimate.width|estimate.height)&1) return false;
+ const bool nvenc=settings.codec.contains("NVIDIA NVENC") || (settings.ffmpeg_device!="cpu" &&
+ QStringList{"H.264","H.265","AV1"}.contains(settings.codec));
+ // The device encoder signals 709 limited SDR or 2020 limited HDR. Other
+ // source color spaces retain their established host conversion boundary.
+ if(!nvenc || source.range=="pc" ||
+ (source.hdr ? source.primaries!="bt2020" || source.colorSpace!="bt2020nc"
+ : !QStringList{"bt709","unknown","unspecified",""}.contains(source.primaries) ||
+ !QStringList{"bt709","unknown","unspecified",""}.contains(source.colorSpace)))return false;
+ if(!source.hdr&&!QStringList{"bt709","gamma22","bt470m","unknown","unspecified",""}.contains(source.transfer))return false;
+ const int ordinal=gpuOrdinal(settings.ai_gpu_uuid);
+ const auto devices=detectGpus();
+ const auto selected=std::ranges::find_if(devices,[ordinal](const Gpu& gpu){return gpu.index==ordinal;});
+ if(selected==devices.end() || (settings.video_gpu_uuid!="auto"&&settings.video_gpu_uuid!=selected->uuid) ||
+ (settings.ffmpeg_device!="auto"&&settings.ffmpeg_device!="cpu"&&
+ settings.ffmpeg_device.mid(7).compare(selected->uuid.mid(4),Qt::CaseInsensitive)!=0))return false;
+ ScratchDirectory temporary(QStringLiteral("rr-cuda-render-XXXXXX"));
+ if(!temporary.isValid())throw std::runtime_error("Cannot create the Ray Reconstruction render directory.");
+ const auto video=temporary.filePath("video.mp4");
+ const auto codec=settings.codec.startsWith("H.264")?QString("h264_nvenc"):
+ settings.codec.startsWith("H.265")?QString("hevc_nvenc"):QString("av1_nvenc");
+ const double duration=request.seconds>0?std::min(request.seconds,source.duration-request.startSeconds):source.duration-request.startSeconds;
+ qint64 count=0;double actualDuration=0,origin=0;
+ QElapsedTimer timer;timer.start();
+ try {
+ CudaVideoDecoder decoder(request.input,ordinal,request.startSeconds,control);
+ auto frame=decoder.read();
+ if(!frame)throw std::runtime_error("Source contains no decodable video frames.");
+ origin=decoder.timeOrigin();
+ auto colors=source;colors.width=estimate.width;colors.height=estimate.height;colors.hdr=estimate.hdr;
+ // RR reconstruction retains FP16 internally and requests a 10-bit
+ // encoder surface for HEVC/AV1, including 8-bit source material.
+ colors.pixelFormat="p010le";
+ NativeEngines::instance().prepare(ordinal,estimate.stages);
+ const quint32 transfer=source.transfer=="smpte2084"?5u:source.transfer=="arib-std-b67"?6u:
+ source.transfer=="linear"?2u:QStringList{"iec61966-2-1","srgb"}.contains(source.transfer)?0u:
+ QStringList{"gamma22","bt470m"}.contains(source.transfer)?3u:
+ QStringList{"gamma28","bt470bg"}.contains(source.transfer)?4u:1u;
+ NativeEngines::RayReconstruction session({source.width,source.height},
+ settings.rr_optical_flow_quality,false,true,transfer);
+ // Construct encoder after the session; its delayed references flush
+ // and release before the session during normal and exceptional exits.
+ CudaVideoEncoder encoder(video,codec,settings,colors,decoder.timeBase(),decoder.device(),ordinal,control);
+ const bool p010=encoder.pixelFormat()==VideoPixelFormat::P010;
+ CudaFramePool pool(decoder.device(),{estimate.width,estimate.height},p010,source.hdr);
+ info("video","NVDEC -> DLSS Ray Reconstruction/NVOFA -> "+codec+" (owned device surfaces)");
+ qint64 previous=-1;
+ while(frame){
+ control.checkpoint();
+ const double seconds=frame->pts*double(frame->timeBase.numerator)/frame->timeBase.denominator;
+ if(request.seconds>0&&seconds>=duration-1e-9)break;
+ if(frame->pts<=previous)throw std::runtime_error("Video has non-increasing presentation timestamps.");
+ const float delta=previous>=0?float((frame->pts-previous)*1000.*frame->timeBase.numerator/frame->timeBase.denominator):
+ source.fps>0?float(1000./source.fps):0.f;
+ const bool gap=count>0&&delta>std::max(250.f,source.fps>0?float(4000./source.fps):250.f);
+ previous=frame->pts;frame->rotation=uint32_t(source.clockwiseRotation());
+ // Decoder metadata is authoritative when present. The transport
+ // uses the encoder's matching, explicitly selected output matrix.
+ if(frame->colorMatrix!=(source.hdr?2u:1u)||frame->colorRange!=0)
+ throw CudaUnavailable("RR device delivery requires matching 709/2020 limited-range planes.");
+ auto output=session.process(*frame,pool,p010,count==0||gap,quint32(count),std::clamp(delta,.01f,1000.f));
+ control.checkpoint();encoder.write(output);++count;
+ actualDuration=std::max(actualDuration,seconds+(frame->duration>0?
+ frame->duration*double(frame->timeBase.numerator)/frame->timeBase.denominator:1/source.fps));
+ if(progress)progress({std::min(.98,duration>0?seconds/duration:.1),QT_TRANSLATE_NOOP("App","Processing video"),
+ count,source.frames,timer.elapsed()>0?count*1000./timer.elapsed():0});
+ frame=decoder.read();
+ }
+ encoder.finish();
+ info("dlssrr","Device delivery counters: "+session.diagnostics());
+ }catch(const CudaUnavailable& error){
+ if(count)throw;
+ control.checkpoint();info("dlssrr","CUDA delivery unavailable; using host composition: "+QString::fromUtf8(error.what()));
+ return false;
+ }
+ if(count<=0)throw std::runtime_error("Ray Reconstruction produced no video frames.");
+ control.checkpoint();if(request.seconds>0)actualDuration=std::min(actualDuration,request.seconds);
+ muxDelivery(video,destination,request,source,settings,actualDuration,control,
+ request.preview?std::nullopt:std::optional(origin));
+ return true;
+}
class OutputTransaction {
public:
explicit OutputTransaction(const QString& destination) : target_(destination) {
@@ -209,11 +297,14 @@ struct InterpolationGrid {
std::unique_ptr<VideoFilterStage> hdrInput;
MediaInfo hdrColors;
std::deque<CudaVideoFrame> preparedHdr;
- InterpolationGrid(const MediaInfo& source, const Settings& settings, double target, QSize size, bool inputRgb10) {
+ bool highPrecision=false;
+ quint32 mediaTransfer=1;
+ InterpolationGrid(const MediaInfo& source, const Settings& settings, double target, QSize size, bool inputRgb10,bool wideRgb=false) {
hdr=source.hdr;
rgb10=inputRgb10;
+ highPrecision=wideRgb;mediaTransfer=nativeMediaTransfer(source.transfer);
if (rgb10 && !hdr) rgbBoundary=std::make_unique<HostRgb10Boundary>();
- if (hdr) {
+ if (hdr&&!highPrecision) {
hdrColors=source;
hdrColors.colorSpace="bt2020nc"; hdrColors.range="tv";
hdrColors.primaries="bt2020"; hdrColors.transfer="smpte2084";
@@ -232,7 +323,7 @@ struct InterpolationGrid {
throw std::runtime_error("Target FPS is outside the native DLSSG grid. Choose Auto or Cascade.");
if (exact && settings.frame_interpolation_engine != "Cascade") {
stages.push_back({std::make_unique<NativeEngines::Interpolation>(size, integer-1, source.hdr,
- settings.frame_interpolation_optical_flow_quality,false,64),{},integer-1});
+ settings.frame_interpolation_optical_flow_quality,highPrecision,64),{},integer-1});
} else {
const int levels = std::abs(ratio - 2) < 1e-7 ? 1
: std::abs(ratio - 4) < 1e-7 ? 2
@@ -240,7 +331,7 @@ struct InterpolationGrid {
: 3;
for (int level = 0; level < levels; ++level)
stages.push_back({std::make_unique<NativeEngines::Interpolation>(
- size,1,source.hdr,settings.frame_interpolation_optical_flow_quality,false,level==levels-1 ? 64 : 0),{},1});
+ size,1,source.hdr,settings.frame_interpolation_optical_flow_quality,highPrecision,level==levels-1 ? 64 : 0),{},1});
}
}
void prepare(std::span<const QImage> pixels, JobControl& control) {
@@ -250,15 +341,15 @@ struct InterpolationGrid {
for (auto& frame : converted) preparedHdr.push_back(std::move(frame));
}
std::vector<Output> push(const QImage& pixels, FrameTime time, JobControl& control) {
- const auto input=rgbBoundary ? rgbBoundary->decodeRgba8(pixels,control) : pixels;
- if (stages.empty()) return {{input.convertToFormat(hdr ? QImage::Format_RGBA64 : QImage::Format_RGBA8888),{},time}};
+ const auto input=rgbBoundary ? highPrecision?decodedRgb10Rgba(pixels):rgbBoundary->decodeRgba8(pixels,control) : pixels;
+ if (stages.empty()) return {{input.convertToFormat(hdr||highPrecision ? QImage::Format_RGBA64 : QImage::Format_RGBA8888),{},time}};
auto& first=stages.front();
int segment=first.previous ? first.previous->segment : 0;
if (first.previous && (time<=first.previous->time || time-first.previous->time>nominal.fraction(2,1))) ++segment;
const bool reset=first.previous && segment!=first.previous->segment;
if (hdrInput && preparedHdr.empty()) throw std::logic_error("Missing HDR interpolation input.");
auto result=hdrInput ? first.session->evaluate(preparedHdr.front(),hdrColors,reset,true)
- : first.session->evaluate(input,reset,true);
+ : first.session->evaluate(input,reset,true,mediaTransfer);
if (hdrInput) preparedHdr.pop_front();
auto frames=first.push(std::move(result),time,segment);
for (size_t level=1; level<stages.size(); ++level) {
@@ -281,21 +372,25 @@ struct InterpolationGrid {
};
} // namespace
QSize dlssOutputSize(QSize input, const QString& mode, bool video) {
+ requireResolution(input, "DLSS input texture", maximumDlssTextureDimension);
const double factor =
QMap<QString, double>{
{"DLAA", 1}, {"Quality", 1.5}, {"Balanced", 1.724}, {"Performance", 2}, {"Ultra Performance", 3}}
.value(mode, 0);
if (!factor || input.width() < 32 || input.height() < 32)
throw std::runtime_error("DLSS input must be at least 32 by 32 pixels and use a supported mode.");
+ if (input.width()*factor > maximumDlssTextureDimension || input.height()*factor > maximumDlssTextureDimension)
+ throw std::runtime_error("DLSS output exceeds the 16384-pixel texture limit.");
const int width =
- video ? int(std::ceil(input.width() * factor / 2)) * 2 : int(std::ceil(input.width() * factor));
+ checkedDimension(input.width() * factor, video ? DimensionRounding::EvenCeil : DimensionRounding::Ceil);
const int height =
- video ? int(std::ceil(input.height() * factor / 2)) * 2 : int(std::ceil(input.height() * factor));
+ checkedDimension(input.height() * factor, video ? DimensionRounding::EvenCeil : DimensionRounding::Ceil);
if (std::max(width, height) > 16384)
throw std::runtime_error("DLSS output exceeds the 16384-pixel texture limit.");
return {width, height};
}
QSize rtxOutputSize(QSize input, const Settings& settings, bool video) {
+ requireResolution(input, "RTX input");
const QString mode = video ? settings.upscale_size_mode : settings.upscale_image_size_mode;
const double factor = video ? settings.upscale_scale_factor : settings.upscale_image_scale_factor;
const bool locked = video ? settings.upscale_aspect_lock : settings.upscale_image_aspect_lock;
@@ -305,12 +400,11 @@ QSize rtxOutputSize(QSize input, const Settings& settings, bool video) {
const double height = mode == "Scale factor" ? input.height() * factor
: locked ? width * input.height() / input.width()
: double(video ? settings.upscale_height : settings.upscale_image_height);
- QSize output(video ? int(std::ceil(width / 2)) * 2 : int(std::ceil(width)),
- video ? int(std::ceil(height / 2)) * 2 : int(std::ceil(height)));
- if (output.width() < input.width() || output.height() < input.height() ||
- std::max(output.width(), output.height()) > 16384)
+ const auto rounding = video ? DimensionRounding::EvenCeil : DimensionRounding::Ceil;
+ QSize output(checkedDimension(width, rounding), checkedDimension(height, rounding));
+ if (output.width() < input.width() || output.height() < input.height())
throw std::runtime_error(
- "RTX Super Resolution output must be at least the input size and at most 16384 pixels.");
+ "RTX Super Resolution output must be at least the input size.");
return output;
}
Settings workflowSettings(Settings s, Workflow workflow, bool video) {
@@ -360,6 +454,7 @@ Settings videoPreviewSettings(Settings settings) {
return settings;
}
PipelineEstimate estimatePipeline(const MediaInfo& info, const Settings& raw, Workflow workflow) {
+ requireResolution({info.width, info.height}, "Input media");
if (auto valid = raw.validate(); !valid)
throw std::runtime_error(valid.error().toStdString());
const auto settings = workflowSettings(raw, workflow, info.video);
@@ -368,6 +463,9 @@ PipelineEstimate estimatePipeline(const MediaInfo& info, const Settings& raw, Wo
throw std::runtime_error("Use one frame-generation engine per workflow. Disable DLSS Frame Generation or VFX Video Frame Generation.");
for (const auto& stage : result.stages) {
QSize size(result.width, result.height);
+ if (stage == "neural_model" || stage == "frame_generation")
+ requireResolution(size, stage == "neural_model" ? "DLSS Neural Rendering texture" : "DLSS Frame Generation texture",
+ maximumDlssTextureDimension);
if (stage == "neural_model" && std::min(size.width(), size.height()) < 64)
throw std::runtime_error("DLSS Neural Rendering requires at least 64 by 64 input.");
else if (stage == "scale_method") {
@@ -384,6 +482,9 @@ PipelineEstimate estimatePipeline(const MediaInfo& info, const Settings& raw, Wo
"Move it before HDR conversion.");
size = dlssOutputSize(
size, info.video ? settings.upscale_dlss_mode : settings.upscale_image_dlss_mode, info.video);
+ } else if (stage == "dlss_ray_reconstruction") {
+ if(info.video && result.hdr && !QStringList{"smpte2084","arib-std-b67"}.contains(info.transfer) && !result.stages.contains("rtx_video_hdr"))
+ throw std::runtime_error("Ray Reconstruction requires explicit PQ or HLG signaling for HDR video.");
} else if (stage == "super_resolution") {
if (info.video && result.hdr)
throw std::runtime_error("RTX Super Resolution cannot process HDR video at this position. "
@@ -416,11 +517,14 @@ PipelineEstimate estimatePipeline(const MediaInfo& info, const Settings& raw, Wo
if (!settings.lut_path.isEmpty() && !QFileInfo(settings.lut_path).isFile())
throw std::runtime_error("The selected .cube LUT is unavailable.");
}
+ requireResolution(size, "Processing stage output");
result.width = size.width();
result.height = size.height();
}
if (info.video && !containersForCodec(settings.codec).contains(settings.container))
throw std::runtime_error("The selected codec does not support this container.");
+ if (!info.video && settings.image_format == "WebP")
+ requireResolution({result.width, result.height}, "WebP format", 16383);
if (info.video && (result.width % 2 || result.height % 2) && !settings.codec.startsWith("FFV1"))
throw std::runtime_error("Video export requires even output dimensions.");
if (info.video && result.hdr && !settings.hdr_mode)
@@ -454,6 +558,8 @@ QString renderOutputPath(const QString& input, const QString& directory, const S
}
namespace {
uint32_t dlssSourceTransfer(const MediaInfo& info) {
+ if(info.transfer=="smpte2084")return 5;
+ if(info.transfer=="arib-std-b67")return 6;
if(!info.video || QStringList{"iec61966-2-1","srgb"}.contains(info.transfer))return 0;
if(info.transfer=="linear")return 2;
if(QStringList{"gamma22","bt470m"}.contains(info.transfer))return 3;
@@ -476,6 +582,7 @@ struct FramePipeline::Impl {
QStringList stages;
std::unique_ptr<NativeEngines::NeuralRendering> nr;
std::vector<std::unique_ptr<NativeEngines::SuperResolution>> sr;
+ std::vector<std::unique_ptr<NativeEngines::RayReconstruction>> rr;
std::vector<std::unique_ptr<NativeEngines::RtxVideo>> rtx;
std::vector<std::unique_ptr<VideoEffects>> vfx;
std::vector<TemporalGuide> guides;
@@ -489,6 +596,7 @@ struct FramePipeline::Impl {
Impl(Settings s, MediaInfo media, QStringList active, bool final,bool normalized)
: settings(std::move(s)), info(std::move(media)), stages(normalizeVfxStages(active,settings)), finalOutput(final),rtxInputNormalized(normalized) {
sr.resize(size_t(stages.size()));
+ rr.resize(size_t(stages.size()));
rtx.resize(size_t(stages.size()));
vfx.resize(size_t(stages.size()));
guides.resize(size_t(stages.size()));
@@ -589,7 +697,7 @@ std::vector<QImage> FramePipeline::processBatch(std::span<const QImage> input, J
for (size_t frame = 0; frame < images.size(); ++frame) {
control.checkpoint();
auto& image = images[frame];
- if (workingInfo.video && rgb10 && (stage == "neural_model" || stage == "dlss_super_resolution"))
+ if (workingInfo.video && rgb10 && (stage == "neural_model" || stage == "dlss_super_resolution" || stage == "dlss_ray_reconstruction"))
image = decodedRgb10Rgba(image);
const bool resetFrame = reset && frame == 0;
if (stage == "neural_model") {
@@ -616,6 +724,19 @@ std::vector<QImage> FramePipeline::processBatch(std::span<const QImage> input, J
? state.guides[size_t(index)].resetMedia(image, resetFrame) : resetFrame;
const float delta=frameTimeMs>0 ? frameTimeMs : workingInfo.fps>0 ? float(1000./workingInfo.fps) : 0.f;
image = session->process(image, resetHistory, quint32(firstFrame + qint64(frame)), delta);
+ } else if(stage=="dlss_ray_reconstruction"){
+ auto& session=state.rr[size_t(index)];
+ const bool alpha=!workingInfo.video&&dlssNativeAlpha(image);
+ auto rrColors=workingInfo;
+ if(hdr&&!workingInfo.hdr){rrColors.hdr=true;rrColors.primaries="bt2020";rrColors.transfer="smpte2084";}
+ if(!session)session=std::make_unique<NativeEngines::RayReconstruction>(
+ image.size(),
+ s.rr_optical_flow_quality,!workingInfo.video,!workingInfo.video&&
+ (s.image_bit_depth==16||index+1<state.stages.size()||!state.finalOutput),
+ dlssSourceTransfer(rrColors),alpha);
+ const bool resetHistory=resetFrame;
+ const float delta=frameTimeMs>0?frameTimeMs:workingInfo.fps>0?float(1000./workingInfo.fps):0.f;
+ image=session->process(image,resetHistory,quint32(firstFrame+qint64(frame)),delta);
} else if(isVfxStage(stage)){
auto colors=stageInputInfo;colors.width=image.width();colors.height=image.height();colors.hdr=hdr;
const auto selected=vfxSettingsForStages(s,{stage});
@@ -665,7 +786,7 @@ std::vector<QImage> FramePipeline::processBatch(std::span<const QImage> input, J
if (!state.rgbBoundary) state.rgbBoundary = std::make_unique<HostRgb10Boundary>();
for (auto& image : images) image = state.rgbBoundary->convert(image, control);
rgb10 = true;
- } else if (stage == "neural_model" || stage == "dlss_super_resolution") rgb10 = false;
+ } else if (stage == "neural_model" || stage == "dlss_super_resolution" || stage == "dlss_ray_reconstruction") rgb10 = false;
remember();
}
if (!workingInfo.video)
@@ -700,9 +821,34 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
const auto requestedSettings = request.preview && input.video ? videoPreviewSettings(request.settings) : request.settings;
auto settings = workflowSettings(requestedSettings, request.workflow, input.video);
const auto estimate = estimatePipeline(input, requestedSettings, request.workflow);
+ if(request.preview&&input.video&&request.startSeconds>0&&!request.temporalContextIncluded&&
+ estimate.stages.contains("dlss_ray_reconstruction")) {
+ ScratchDirectory context(QStringLiteral("rr-preview-context-XXXXXX"));
+ if(!context.isValid())throw std::runtime_error("Cannot create Ray Reconstruction preview history.");
+ const double start=reconstructionContextStart(request.input,input,request.startSeconds,
+ reconstructionHistoryFrames(settings,estimate.stages),control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device=="auto");
+ const double prefix=request.startSeconds-start;
+ auto warmed=request;warmed.output=context.filePath("warmed.mkv");warmed.startSeconds=start;
+ warmed.seconds=request.seconds>0?prefix+request.seconds:0;warmed.temporalContextIncluded=true;
+ const auto result=render(warmed,control,progress);
+ const double origin=result.info.metadata.value("ve_source_time_origin").toDouble(start);
+ const double discard=std::max(0.,request.startSeconds+input.presentationStartSeconds()-origin);
+ OutputTransaction output(request.output);
+ QStringList trim{"-v","error","-y","-ss",QString::number(discard,'f',12),"-i",warmed.output,
+ "-map","0:v:0","-an","-c:v","copy","-map_metadata","0"};
+ if(request.seconds>0)trim<<"-t"<<QString::number(request.seconds,'f',12);
+ trim<<"-avoid_negative_ts"<<"make_zero"<<output.path();
+ const auto trimmed=runProcess(Paths::instance().ffmpeg(),trim,&control,0);
+ if(trimmed.exitCode)throw std::runtime_error(trimmed.error.toStdString());
+ control.checkpoint();output.commit();
+ auto outputInfo=probeMedia(request.output,&control);
+ info("dlssrr",QString("Preview discarded %1 s of bounded RR context (maximum 32 source frames).").arg(discard,0,'g',12));
+ return {request.input,request.output,Log::instance().sessionPath(),outputInfo,activeElapsed()/1000.};
+ }
if(input.video&&hasVfxStages(estimate.stages)&&!request.isolatedVfxWorker)return renderIsolatedVfx(request,control,progress);
OutputTransaction output(request.output);
if (input.video && (renderVfxVideo(request,input,settings,estimate,output.path(),control,progress) ||
+ renderRayReconstructionVideo(request,input,settings,estimate,output.path(),control,progress) ||
renderCudaVideo(request, input, settings, estimate, output.path(), control, progress) ||
renderInterpolationVideo(request, input, settings, estimate, output.path(), control, progress))) {
output.commit();
@@ -711,7 +857,7 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
info("render", request.input + " -> " + request.output);
return {request.input, request.output, Log::instance().sessionPath(), result, activeElapsed() / 1000.};
}
- if (estimate.stages.contains("neural_model") || estimate.stages.contains("dlss_super_resolution") ||
+ if (estimate.stages.contains("neural_model") || estimate.stages.contains("dlss_super_resolution") || estimate.stages.contains("dlss_ray_reconstruction") ||
estimate.stages.contains("super_resolution") || estimate.stages.contains("frame_generation") ||
estimate.stages.contains("rtx_video_hdr"))
NativeEngines::instance().prepare(gpuOrdinal(settings.ai_gpu_uuid), estimate.stages);
@@ -743,6 +889,9 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
intermediate.width = beforeEstimate.width;
intermediate.height = beforeEstimate.height;
intermediate.hdr = beforeEstimate.hdr;
+ if(before.contains("rtx_video_hdr")){intermediate.primaries="bt2020";intermediate.transfer="smpte2084";}
+ const bool rrInterpolationPrecision=fiPosition>=0&&
+ ((!before.isEmpty()&&before.back()=="dlss_ray_reconstruction")||(!after.isEmpty()&&after.front()=="dlss_ray_reconstruction"));
const double sourceFps = input.fps > 0 ? input.fps : 30.,
targetFps =
fiPosition < 0 ? sourceFps : targetFrameRate(settings.frame_interpolation_target_fps);
@@ -752,14 +901,14 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
const qint64 total = static_cast<qint64>(std::ceil(duration * targetFps - 1e-8));
double actualDuration = 0;
const bool nativeStages = std::ranges::any_of(estimate.stages, [](const QString& stage) {
- return QStringList{"neural_model", "dlss_super_resolution", "super_resolution", "rtx_video_hdr",
+ return QStringList{"neural_model", "dlss_super_resolution", "dlss_ray_reconstruction", "super_resolution", "rtx_video_hdr",
"frame_generation"}.contains(stage);
});
const auto codec = request.preview ? QString("FFV1 Lossless RGB 10-bit")
: nativeStages ? nativeDeliveryCodec(settings) : settings.codec;
const bool nativeNeuralDelivery = estimate.stages.size() > 1 && estimate.stages.back() == "neural_model" &&
codec.contains("NVIDIA NVENC") && gpuOrdinal(settings.video_gpu_uuid) == gpuOrdinal(settings.ai_gpu_uuid);
- const bool dlssMedia = before.contains("dlss_super_resolution");
+ const bool dlssMedia = before.contains("dlss_super_resolution")||before.contains("dlss_ray_reconstruction");
const bool nativeDecoder = dlssMedia || !before.isEmpty() && QStringList{"neural_model", "super_resolution", "rtx_video_hdr"}.contains(before.front())
|| (before.isEmpty() && fiPosition == 0);
const bool sourceWide = input.precisionBits() > 8;
@@ -803,7 +952,9 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
preInfo.primaries=preInfo.hdr ? "bt2020" : "bt709"; preInfo.transfer=preInfo.hdr ? "smpte2084" : "bt709";
}
auto postInfo=intermediate;
- if (fiPosition>=0) { postInfo.pixelFormat=postInfo.hdr ? "gbrp10le" : "rgba"; postInfo.colorSpace="gbr"; postInfo.range="pc"; }
+ if(fiPosition>=0)postInfo.fps=targetFps;
+ if (fiPosition>=0) { postInfo.pixelFormat=rrInterpolationPrecision?"rgba64le":postInfo.hdr ? "gbrp10le" : "rgba";
+ if(rrInterpolationPrecision)postInfo.sourceBitDepth=16;postInfo.colorSpace="gbr"; postInfo.range="pc"; }
if (nativeNeuralDelivery) {
if (fiPosition < 0) preStages.removeLast();
else after.removeLast();
@@ -892,14 +1043,20 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
encodedInfo.primaries = primaries; encodedInfo.transfer = transfer;
if(hasVfxStages(estimate.stages))retainVfxPixelAspect(encodedInfo,input);
if (!estimate.stages.isEmpty() && estimate.stages.back() != "neural_model" && estimate.stages.back() != "frame_generation"
- && estimate.stages.back() != "dlss_super_resolution")
+ && estimate.stages.back() != "dlss_super_resolution" && estimate.stages.back() != "dlss_ray_reconstruction")
encodedInfo.pixelFormat = "gbrp10le";
else if (encodedInfo.pixelFormat == "gbrp10le" && !estimate.stages.isEmpty() &&
- QStringList{"neural_model","dlss_super_resolution"}.contains(estimate.stages.back()))
+ QStringList{"neural_model","dlss_super_resolution","dlss_ray_reconstruction"}.contains(estimate.stages.back()))
// The input cache was planar RGB10; the native result is packed
// RGBA16 and needs the encoder's genuine swscale packing boundary.
encodedInfo.pixelFormat = "rgba64le";
- if (fiPosition>=0 && after.isEmpty()) encodedInfo.pixelFormat=intermediate.hdr ? "gbrp10le" : "rgba";
+ if(!estimate.stages.isEmpty()&&estimate.stages.back()=="dlss_ray_reconstruction"){
+ encodedInfo.pixelFormat="rgba64le";encodedInfo.sourceBitDepth=16;
+ }
+ if (fiPosition>=0 && after.isEmpty()) {
+ encodedInfo.pixelFormat=rrInterpolationPrecision?"rgba64le":intermediate.hdr ? "gbrp10le" : "rgba";
+ if(rrInterpolationPrecision)encodedInfo.sourceBitDepth=16;
+ }
const auto timeBase = fiPosition < 0 ? decodedTimeBase
: settings.frame_interpolation_target_fps.contains('.')
? TimeBase{1001, int(std::lround(targetFps * 1001))}
@@ -939,7 +1096,7 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
if (fiPosition >= 0)
interpolation = std::make_unique<InterpolationGrid>(intermediate, settings, targetFps,
QSize(intermediate.width, intermediate.height), !before.isEmpty()
- && before.back() != "neural_model");
+ && before.back() != "neural_model"&&before.back()!="dlss_ray_reconstruction",rrInterpolationPrecision);
const auto batchSize =
videoBatchCapacity({std::max(input.width, estimate.width), std::max(input.height, estimate.height)});
struct CachedPacket {
@@ -1032,7 +1189,7 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
report(total>0 ? std::min(.98,written/double(total)) : .1,QT_TRANSLATE_NOOP("App", "Processing video"),written,total);
} else {
const auto pixels = selected.surface
- ? interpolation->hdr ? selected.surface.toHostRgb10() : selected.surface.toHost()
+ ? interpolation->hdr&&!interpolation->highPrecision ? selected.surface.toHostRgb10() : selected.surface.toHost()
: selected.pixels;
writeFrame(pixels,index,1);
}
@@ -1071,6 +1228,7 @@ RenderResult Pipeline::render(const RenderRequest& request, JobControl& control,
output.commit();
report(1, QT_TRANSLATE_NOOP("App", "Video complete"), outputIndex, total);
auto outputInfo = probeMedia(request.output, &control);
+ if(sourceTimeOrigin)outputInfo.metadata.insert("ve_source_time_origin",*sourceTimeOrigin);
info("render", request.input + " -> " + request.output);
return {request.input, request.output, Log::instance().sessionPath(), outputInfo,
activeElapsed() / 1000.};
diff --git a/src/processing/pipeline.hpp b/src/processing/pipeline.hpp
index 2a1b41c..1a69295 100644
--- a/src/processing/pipeline.hpp
+++ b/src/processing/pipeline.hpp
@@ -9,6 +9,14 @@
namespace ve {
class PreviewFrameCache;
+inline int reconstructionHistoryFrames(const Settings& settings,const QStringList& stages) {
+ if(stages.contains("dlss_ray_reconstruction"))return 32;
+ return stages.contains("dlss_super_resolution")?(settings.upscale_dlss_mode=="DLAA"?8:18):0;
+}
+inline bool rrNeedsGeneratedHistory(const QStringList& stages) {
+ const auto fi=stages.indexOf("frame_generation"),rr=stages.indexOf("dlss_ray_reconstruction");
+ return fi>=0&&rr>fi;
+}
enum class Workflow { NeuralRendering, Upscale, FrameInterpolation };
struct PipelineEstimate {
int width = 0, height = 0;
@@ -32,6 +40,7 @@ struct RenderRequest {
double seconds = 0; // Zero exports the complete source.
PreviewFrameCache* stillSources = nullptr; // Optional reuse of the original decoded preview image.
bool isolatedVfxWorker = false; // Set only by the internal worker, independently of Qt's storage identity.
+ bool temporalContextIncluded = false; // Internal guard for bounded RR clip overlap.
};
struct RenderResult {
QString input, output, report;
diff --git a/src/processing/preview_cache.hpp b/src/processing/preview_cache.hpp
index 4234bf1..6dcca41 100644
--- a/src/processing/preview_cache.hpp
+++ b/src/processing/preview_cache.hpp
@@ -127,6 +127,7 @@ inline QList<QByteArray> previewStageKeys(QByteArray identity, const Settings& s
"local_structure_strength","skin_structure_strength","automatic_mask","nr_mask"}},
{"scale_method",{"upscaling_factor","image_scaling_filter","video_scaling_filter"}},
{"dlss_super_resolution",{"upscale_dlss_mode","upscale_dlss_preset","upscale_image_dlss_mode","upscale_image_dlss_preset","upscale_optical_flow_quality"}},
+ {"dlss_ray_reconstruction",{"rr_optical_flow_quality"}},
{"super_resolution",{"upscale_vsr_quality","upscale_size_mode","upscale_scale_factor","upscale_width","upscale_height","upscale_aspect_lock",
"upscale_image_vsr_quality","upscale_image_size_mode","upscale_image_scale_factor","upscale_image_width","upscale_image_height","upscale_image_aspect_lock"}},
{"rtx_video_hdr",{"upscale_hdr_contrast","upscale_hdr_saturation","upscale_hdr_middle_gray","upscale_hdr_peak_luminance","upscale_hdr_precision"}},
@@ -143,6 +144,7 @@ inline QList<QByteArray> previewStageKeys(QByteArray identity, const Settings& s
for (qsizetype index=0; index<stages.size(); ++index) {
const auto& stage=stages[index];
QVariantMap relevant;
+ if(stage=="dlss_ray_reconstruction")identity+="/rr-native-1x-abi2/rr-guides-v2/fixed-still-video/scene-v2/full-fingerprint/streamed-parked-32-v3/single-still/";
for (const auto& field : fields.value(stage)) relevant.insert(field,settings.value(field));
if(isVfxStage(stage)||(hasVfxStages(settings.stages(true))&&QStringList{"super_resolution","rtx_video_hdr"}.contains(stage))){
identity+=info.metadata.value("sample_aspect_ratio").toString().toUtf8();
@@ -172,15 +174,18 @@ inline QList<QByteArray> previewStageKeys(QByteArray identity, const Settings& s
identity+=QByteArray::number(pixels.cacheKey());
}
const QString module=stage=="neural_model" ? "dlssnr" : stage=="dlss_super_resolution" ? "dlsssr"
+ : stage=="dlss_ray_reconstruction" ? "dlssrr"
: stage=="super_resolution" || stage=="rtx_video_hdr" ? "rtx_video"
: stage=="frame_generation" ? "dlssg" : QString{};
const QString binary=stage=="neural_model" ? "neuroframe_engine_neural_rendering.dll"
: stage=="dlss_super_resolution" ? "neuroframe_engine_super_resolution.dll"
+ : stage=="dlss_ray_reconstruction" ? "neuroframe_engine_ray_reconstruction.dll"
: stage=="frame_generation" ? "neuroframe_engine_frame_interpolation.dll" : "neuroframe_engine_upscaling.dll";
if (!module.isEmpty()) {
identity+=previewFileIdentity(root+"/bin/runtime/"+module+'/'+binary);
const QString model=stage=="neural_model" ? "nvngx_dlssnr.dll"
: stage=="dlss_super_resolution" ? "nvngx_dlss.dll"
+ : stage=="dlss_ray_reconstruction" ? "nvngx_dlssd.dll"
: stage=="frame_generation" ? "nvngx_dlssg.dll"
: stage=="super_resolution" ? "nvngx_vsr.dll"
: stage=="rtx_video_hdr" ? "nvngx_truehdr.dll" : QString{};
diff --git a/src/processing/vfx_native.cpp b/src/processing/vfx_native.cpp
index 9937f27..d8ae84e 100644
--- a/src/processing/vfx_native.cpp
+++ b/src/processing/vfx_native.cpp
@@ -1,4 +1,5 @@
#include "vfx_native.hpp"
+#include "media/resolution.hpp"
#include "native_engines.hpp"
#include "infrastructure/paths.hpp"
#include "infrastructure/process.hpp"
@@ -102,7 +103,7 @@ VfxFrameDescV2 vfxDescriptor(const QImage& input,const MediaInfo& colors){
auto f=descriptor<VfxFrameDescV2>();f.memory_type=VFX_HOST;f.pixel_format=input.format()==QImage::Format_RGBA64?VFX_RGBA16:VFX_RGBA8;f.width=input.width();f.height=input.height();f.planes[0]=reinterpret_cast<uint64_t>(input.constBits());f.strides[0]=input.bytesPerLine();colorDescription(f,colors);f.color_range=1;return f;
}
QSize vfxSpatialSize(QSize input,const Settings& s){
- if(!input.isValid())throw std::runtime_error("Invalid VFX input dimensions.");
+ requireResolution(input, "VFX input");
double w=input.width(),h=input.height();
if(s.vfx_vsr_enabled&&!restores(s)){
if(s.vfx_size_mode=="Scale factor"){w*=s.vfx_scale_factor;h*=s.vfx_scale_factor;}
@@ -115,8 +116,7 @@ QSize vfxSpatialSize(QSize input,const Settings& s){
w*=s.vfx_upscale_scale;h*=s.vfx_upscale_scale;
if(std::abs(w-std::round(w))>1e-6||std::abs(h-std::round(h))>1e-6)throw std::runtime_error("Lightweight Upscale requires exact integral dimensions; choose a different scale.");
}
- if(w>16384||h>16384)throw std::runtime_error("VFX output exceeds 16384 pixels.");
- return {int(std::round(w)),int(std::round(h))};
+ return {checkedDimension(std::round(w)),checkedDimension(std::round(h))};
}
double vfxFrameRate(double source,const Settings& s){
if(!s.vfx_frame_generation_enabled)return source;
@@ -142,8 +142,9 @@ QImage vfxDisplayAspect(const QImage& pixels,const MediaInfo& source){
auto colors=source;retainVfxPixelAspect(colors,source);const auto ratio=colors.outputSampleAspectRatio();
if(ratio.width()==ratio.height())return pixels;
const double width=double(pixels.width())*ratio.width()/ratio.height();
- if(width<=0||width>16384)throw std::runtime_error("VFX preview display aspect exceeds its image limit.");
- return pixels.scaled(int(std::round(width)),pixels.height(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
+ auto result = pixels.scaled(checkedDimension(std::round(width)),pixels.height(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
+ requireImageAllocation(result, "VFX display aspect conversion");
+ return result;
}
void VideoEffects::initialize(int ordinal){
prepareCudaPrimaryContext(ordinal);auto& api=Api::get();std::lock_guard lock(api.mutex);Error error{};
diff --git a/src/processing/vfx_worker.cpp b/src/processing/vfx_worker.cpp
index f90e887..9ec956a 100644
--- a/src/processing/vfx_worker.cpp
+++ b/src/processing/vfx_worker.cpp
@@ -55,6 +55,7 @@ RenderResult renderIsolatedVfx(const RenderRequest& request,JobControl& control,
const auto rendered=directory.filePath("processed."+QFileInfo(request.output).suffix());
auto job=base("render",request.input,rendered,request.settings,directory.filePath("preset.json"));
job.insert("workflow",int(request.workflow));job.insert("preview",request.preview);job.insert("start",request.startSeconds);job.insert("seconds",request.seconds);
+ job.insert("temporal_context",request.temporalContextIncluded);
const auto path=directory.filePath("job.json");save(path,job);directory.cacheRoot()->registerFile(path+".state");call(path,control,[&](const Progress& p){if(progress){auto delivery=p;delivery.fraction=std::min(.98,p.fraction);progress(delivery);}});
QDir().mkpath(QFileInfo(request.output).absolutePath());
QFile source(rendered);QTemporaryFile destination(QFileInfo(request.output).absolutePath()+"/.vfx-delivery-XXXXXX");
@@ -88,14 +89,16 @@ int runVfxWorker(const QString& path){
if(job.value("kind")=="render"){
RenderRequest request{input,output,settings,Workflow(job.value("workflow").toInt()),job.value("preview").toBool(),job.value("start").toDouble(),job.value("seconds").toDouble()};
request.isolatedVfxWorker=true;
+ request.temporalContextIncluded=job.value("temporal_context").toBool();
const auto rendered=Pipeline{}.render(request,control,[](const Progress& p){send({{"kind","progress"},{"fraction",p.fraction},{"message",p.message},{"frames",p.frames},{"total",p.totalFrames},{"fps",p.fps}});});(void)rendered;
}else if(job.value("kind")=="still"){
auto info=probeMedia(input,&control);const double seconds=job.value("seconds").toDouble();
const auto position=quantizePlayhead(seconds*1000,info.fps,info.duration);const auto stages=settings.stages(true);
VideoFrameReader reader;auto source=reader.frame(input,info,position,control,false,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device!="cpu");
- const bool generated=settings.vfx_frame_generation_enabled;const bool history=stages.contains("dlss_super_resolution");
- std::vector<TimedImage> temporal;if(history||generated)temporal=reader.temporalContext(input,info,position,source.absoluteSeconds,history?(settings.upscale_dlss_mode=="DLAA"?8:18):0,control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device!="cpu",generated);
- PreviewFrameCache cache;VideoStillPreview preview;auto pixels=preview.process(source.pixels,settings,info,stages,cache,source.identity,control,temporal,generated?seconds:-1);
+ const bool generated=settings.vfx_frame_generation_enabled;const bool history=stages.contains("dlss_super_resolution")||stages.contains("dlss_ray_reconstruction");
+ const bool nativeAfter=rrNeedsGeneratedHistory(stages);
+ std::vector<TimedImage> temporal;if(!stages.contains("dlss_ray_reconstruction")&&(history||generated))temporal=reader.temporalContext(input,info,position,source.absoluteSeconds,reconstructionHistoryFrames(settings,stages),control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device!="cpu",generated||nativeAfter);
+ PreviewFrameCache cache;VideoStillPreview preview;auto pixels=preview.process(source.pixels,settings,info,stages,cache,source.identity,control,temporal,generated?seconds+info.presentationStartSeconds():stages.contains("dlss_ray_reconstruction")?source.absoluteSeconds:-1,input);
if(info.hdr||stages.contains("rtx_video_hdr")){auto colors=info;colors.hdr=true;if(stages.contains("rtx_video_hdr")){colors.primaries="bt2020";colors.transfer="smpte2084";}pixels=toneMapVideoPreview(pixels,colors,control,settings.ffmpeg_device);}
pixels=vfxDisplayAspect(pixels,info);if(!pixels.save(output,"PNG"))throw std::runtime_error("Cannot save VFX worker preview.");
}else throw std::runtime_error("Unknown VFX worker operation.");
diff --git a/src/processing/video_still_preview.cpp b/src/processing/video_still_preview.cpp
index 51941a4..9337279 100644
--- a/src/processing/video_still_preview.cpp
+++ b/src/processing/video_still_preview.cpp
@@ -1,15 +1,18 @@
#include "video_still_preview.hpp"
#include "frame_stream.hpp"
+#include "native_engines.hpp"
#include "infrastructure/paths.hpp"
#include "media/video_preview.hpp"
#include "infrastructure/scratch.hpp"
#include <utility>
+#include <limits>
+#include <cmath>
namespace ve {
QImage VideoStillPreview::process(const QImage &input, Settings settings, MediaInfo info,
const QStringList &requestedStages, PreviewFrameCache &cache,
const QByteArray &identity, JobControl &control,
- const std::vector<TimedImage>& temporal, double generatedSeconds) {
+ const std::vector<TimedImage>& temporal, double generatedSeconds,const QString& sourceMediaPath) {
ProcessingCacheActivity cacheActivity;
const auto stages=normalizeVfxStages(requestedStages,settings);
// These are the exact metadata/layout boundaries that the old source FFV1
@@ -21,7 +24,7 @@ QImage VideoStillPreview::process(const QImage &input, Settings settings, MediaI
// The former source container quantized wide layouts back to the original
// integer depth before the streaming stages read them. Preserve that step.
info.pixelFormat = ffv1PreviewPixelFormat(info);
- const bool nativeTemporal=stages.contains("dlss_super_resolution");
+ const bool nativeTemporal=stages.contains("dlss_super_resolution")||stages.contains("dlss_ray_reconstruction");
if(nativeTemporal)info.pixelFormat=input.depth()>32?"rgba64le":"rgba";
info.colorSpace = "gbr";
info.range = "pc";
@@ -33,7 +36,7 @@ QImage VideoStillPreview::process(const QImage &input, Settings settings, MediaI
auto temporalIdentity=identity;
temporalIdentity+=QByteArray::number(generatedSeconds,'g',17);
if(!temporal.empty()) {
- temporalIdentity+="/native-sr-history/v1/";
+ temporalIdentity+="/native-reconstruction-history/v2/";
for(const auto& frame:temporal) {
temporalIdentity+=previewPixelIdentity(frame.image,control);
temporalIdentity+=QByteArray::number(frame.pts)+'/'+QByteArray::number(frame.timeBase.numerator)+'/'+QByteArray::number(frame.timeBase.denominator);
@@ -45,6 +48,75 @@ QImage VideoStillPreview::process(const QImage &input, Settings settings, MediaI
QCryptographicHash::Sha256);
if (auto cached = cache.find(displayKey))
return std::move(cached->pixels);
+ if(!sourceMediaPath.isEmpty()&&stages.contains("dlss_ray_reconstruction")){
+ // Stream the context through the export graph. Retaining 32 complete
+ // UHD images in RAM would either exceed the history budget or silently
+ // shorten the selected history when the source precision increases.
+ ScratchDirectory directory(QStringLiteral("rr-parked-context-XXXXXX"));
+ if(!directory.isValid())throw std::runtime_error("Cannot create streamed RR preview context.");
+ const double fps=info.fps>0?info.fps:30.;
+ // Original-source callers provide an absolute presentation timestamp;
+ // negative presentation origins are valid as well.
+ const double selectedAbsolute=std::isfinite(generatedSeconds)?generatedSeconds:info.presentationStartSeconds();
+ const double selectedRelative=std::max(0.,selectedAbsolute-info.presentationStartSeconds());
+ const double start=reconstructionContextStart(sourceMediaPath,info,selectedRelative,
+ reconstructionHistoryFrames(settings,stages),control,gpuOrdinal(settings.ai_gpu_uuid),settings.ffmpeg_device=="auto");
+ settings.video_enabled_stages=stages;
+ RenderRequest request{sourceMediaPath,directory.filePath("processed.mkv"),settings,
+ Workflow::NeuralRendering,true,start,selectedRelative-start+std::max(.25,3./fps)};
+ request.temporalContextIncluded=true;
+ const auto result=Pipeline{}.render(request,control);
+ const double origin=result.info.metadata.value("ve_source_time_origin").toDouble(info.presentationStartSeconds()+start);
+ const double target=std::max(0.,selectedAbsolute-origin);
+ HostVideoDecoder decoder(result.output,result.info,0,0,false,control);
+ std::optional<TimedImage> selected;
+ double distance=std::numeric_limits<double>::infinity();
+ while(auto frame=decoder.read()){
+ control.checkpoint();const auto candidate=std::abs(frame->seconds()-target);
+ if(candidate<distance){distance=candidate;selected=std::move(frame);}
+ else if(frame->seconds()>target)break;
+ }
+ if(!selected)throw std::runtime_error("Streamed RR preview returned no selected frame.");
+ auto pixels=display_.display(selected->image,result.info,control);
+ control.checkpoint();cache.store(displayKey,{pixels,false,false});return pixels;
+ }
+ if(rrNeedsGeneratedHistory(stages)){
+ // RR after FG must consume the generated temporal frames as export
+ // does. Preserve the decoded source context losslessly and run the
+ // same clip graph rather than dropping FG from the parked preview.
+ auto frames=temporal;
+ if(frames.empty())frames.push_back({input,0,1,{1,30}});
+ ScratchDirectory directory(QStringLiteral("rr-generated-history-XXXXXX"));
+ if(!directory.isValid())throw std::runtime_error("Cannot create generated RR preview history.");
+ const auto sourcePath=directory.filePath("source.mkv"),rendered=directory.filePath("processed.mkv");
+ auto packing=info;packing.pixelFormat=frames.front().image.depth()>32?"rgba64le":"rgba";
+ packing.sourceBitDepth=frames.front().image.depth()>32?16:8;
+ const auto origin=frames.front();
+ {
+ HostVideoEncoder encoder(sourcePath,"FFV1",settings,packing,0,control,HostEncodePurpose::NativePreview);
+ for(const auto& frame:frames){
+ control.checkpoint();
+ if(frame.timeBase.numerator!=origin.timeBase.numerator||frame.timeBase.denominator!=origin.timeBase.denominator)
+ throw std::runtime_error("RR preview context changed time base.");
+ encoder.write(frame.image,frame.pts-origin.pts,frame.duration,frame.timeBase);
+ }
+ encoder.finish();
+ }
+ settings.video_enabled_stages=stages;
+ const auto result=Pipeline{}.render({sourcePath,rendered,settings,Workflow::NeuralRendering,true},control);
+ const double target=std::max(0.,(generatedSeconds>=0?generatedSeconds:frames.back().seconds())-origin.seconds());
+ HostVideoDecoder decoder(rendered,result.info,0,0,false,control);
+ std::optional<TimedImage> selected;
+ double distance=std::numeric_limits<double>::infinity();
+ while(auto frame=decoder.read()){
+ control.checkpoint();const double candidate=std::abs(frame->seconds()-target);
+ if(candidate<distance){distance=candidate;selected=std::move(frame);}
+ else if(frame->seconds()>target)break;
+ }
+ if(!selected)throw std::runtime_error("Generated RR preview returned no selected frame.");
+ auto pixels=display_.display(selected->image,result.info,control);
+ control.checkpoint();cache.store(displayKey,{pixels,false,false});return pixels;
+ }
if (!nativeTemporal && info.sourceBitDepth > 8 && info.sourceBitDepth < 16 && !stages.isEmpty() &&
QStringList{"scale_method", "cas_sharpening", "grain", "coloring"}.contains(stages.front())) {
// Leading GPU filters reconstruct sub-16-bit planar source codes with
@@ -90,7 +162,7 @@ QImage VideoStillPreview::process(const QImage &input, Settings settings, MediaI
while(auto frame=pipeline.read()) {control.checkpoint();if(generatedTarget>=0&&frame->seconds()>generatedTarget+1e-7)break;output=std::move(frame);}
if (!output)
throw std::runtime_error("Video still preview returned no frame.");
- if (!stages.isEmpty() && stages.back() != "neural_model" && stages.back() != "dlss_super_resolution")
+ if (!stages.isEmpty() && stages.back() != "neural_model" && stages.back() != "dlss_super_resolution" && stages.back() != "dlss_ray_reconstruction")
info.pixelFormat = "gbrp10le";
else if (info.pixelFormat == "gbrp10le" && !stages.isEmpty())
info.pixelFormat = "rgba64le";
diff --git a/src/processing/video_still_preview.hpp b/src/processing/video_still_preview.hpp
index 68848ed..eacaa67 100644
--- a/src/processing/video_still_preview.hpp
+++ b/src/processing/video_still_preview.hpp
@@ -9,7 +9,8 @@ class VideoStillPreview {
[[nodiscard]] QImage process(const QImage &input, Settings settings, MediaInfo info,
const QStringList &stages, PreviewFrameCache &cache,
const QByteArray &identity, JobControl &control,
- const std::vector<TimedImage>& temporal = {}, double generatedSeconds=-1);
+ const std::vector<TimedImage>& temporal = {}, double generatedSeconds=-1,
+ const QString& sourceMediaPath={});
private:
HostPreviewBoundary display_;
diff --git a/tools/QT-RELINKING.txt b/tools/QT-RELINKING.txt
new file mode 100644
index 0000000..294a6c3
--- /dev/null
+++ b/tools/QT-RELINKING.txt
@@ -0,0 +1,17 @@
+REPLACING AND REBUILDING QT IN VISUAL ENHANCER
+
+Visual Enhancer dynamically links the Qt libraries, plugins and QML modules.
+This build uses an MSVC x64 Qt 6.12.x kit; Qt is not embedded in the executable.
+
+Build application source against a compatible modified Qt kit:
+
+ ./Build/build.ps1 -QtRoot 'C:/path/to/modified/Qt/msvc_x64' -Deploy
+
+For an ABI-compatible replacement, deploy matching DLLs, plugins, QML modules
+and multimedia dependencies beside the application while it is closed.
+No signature or hash registration gate restricts replacement of Qt.
+
+The Merserk Source License does not restrict rights granted under applicable
+third-party Qt licenses, including replacement, relinking and debugging.
+License texts and Qt-provided SPDX inventories are under bin/licenses/.
+Qt sources: https://download.qt.io/archive/qt/6.12/
diff --git a/tools/Release.ps1 b/tools/Release.ps1
index 86b2087..f4b6220 100644
--- a/tools/Release.ps1
+++ b/tools/Release.ps1
@@ -4,6 +4,7 @@ function Get-VeOwnedBinaries([string]$PackageRoot) {
foreach ($relative in @('Visual Enhancer.exe', 'VE_CLI.exe',
'bin/runtime/dlssnr/neuroframe_engine_neural_rendering.dll',
'bin/runtime/dlsssr/neuroframe_engine_super_resolution.dll',
+ 'bin/runtime/dlssrr/neuroframe_engine_ray_reconstruction.dll',
'bin/runtime/dlssg/neuroframe_engine_frame_interpolation.dll',
'bin/runtime/rtx_video/neuroframe_engine_upscaling.dll',
'bin/runtime/vfx/neuroframe_engine_video_effects.dll')) {
diff --git a/tools/audit-release.ps1 b/tools/audit-release.ps1
index bcae6ee..7d7cd72 100644
--- a/tools/audit-release.ps1
+++ b/tools/audit-release.ps1
@@ -21,6 +21,23 @@ foreach ($required in @('resources/desktop/qml/Main.qml', 'resources/desktop/app
$owned = @(Get-VeOwnedBinaries $root)
$ownedPaths = @($owned.FullName)
$releaseVersion = $owned[0].VersionInfo.ProductVersion
+$contracts = @{
+ neural_rendering = 'dlssnr/neuroframe_engine_neural_rendering.dll'
+ super_resolution = 'dlsssr/neuroframe_engine_super_resolution.dll'
+ ray_reconstruction = 'dlssrr/neuroframe_engine_ray_reconstruction.dll'
+ frame_interpolation = 'dlssg/neuroframe_engine_frame_interpolation.dll'
+ rtx_video = 'rtx_video/neuroframe_engine_upscaling.dll'
+ video_effects = 'vfx/neuroframe_engine_video_effects.dll'
+}
+foreach ($module in $contracts.Keys) {
+ $contractPath = Join-Path (Split-Path -Parent (Split-Path -Parent $PSScriptRoot)) "native (dev)/modules/$module/contract.json"
+ $contract = Get-Content -LiteralPath $contractPath -Raw | ConvertFrom-Json
+ if ($module -ne 'video_effects' -and $contract.initialization_abi -ne 2) { throw "Outdated initialization contract: $module" }
+ $exports = @(Get-VePeExports (Join-Path $root ('bin/runtime/' + $contracts[$module])))
+ foreach ($export in $contract.exports) {
+ if ($export -notin $exports) { throw "Missing $module export: $export" }
+ }
+}
$inventory = foreach ($file in (Get-ChildItem -LiteralPath $root -Recurse -File |
Where-Object { $_.Extension -in @('.exe', '.dll') -and -not $_.FullName.StartsWith((Join-Path $root 'outputs') + '\', [StringComparison]::OrdinalIgnoreCase) -and -not $_.FullName.StartsWith((Join-Path $root 'logs') + '\', [StringComparison]::OrdinalIgnoreCase) } | Sort-Object FullName)) {
$isOwned = $file.FullName -in $ownedPaths
diff --git a/tools/deploy.ps1 b/tools/deploy.ps1
index f8c415e..1d5dd32 100644
--- a/tools/deploy.ps1
+++ b/tools/deploy.ps1
@@ -8,190 +8,48 @@ param(
[string]$RuntimeSource,
[string]$CertificateThumbprint,
[string]$TimestampServer = 'http://timestamp.digicert.com',
- [switch]$MachineCertificateStore
+ [switch]$MachineCertificateStore,
+ [switch]$RequireSignatures,
+ [switch]$ScanDefender,
+ [string]$OutputDirectory,
+ [switch]$StageOnly
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Toolchain.ps1')
-$projectRoot = Split-Path -Parent $PSScriptRoot
-$workspaceRoot = Split-Path -Parent $projectRoot
-$resolvedQt = Resolve-VeQtRoot $QtRoot
-$resolvedBuild = Resolve-VePath $BuildDir $projectRoot
-if (-not $Destination) { $Destination = Join-Path $workspaceRoot 'Visual Enhancer' }
-$resolvedDestination = Resolve-VePath $Destination $projectRoot
-if ($resolvedDestination -eq $projectRoot -or $resolvedDestination -eq $workspaceRoot) {
- throw 'Deploy to the Visual Enhancer folder or another dedicated application folder.'
-}
-$appDirectory = $resolvedDestination
-$runtimeSource = if ($RuntimeSource) { Resolve-VePath $RuntimeSource $projectRoot }
- else { Join-Path $workspaceRoot 'Visual Enhancer' }
-$binaryDirectory = Join-Path $resolvedBuild $Configuration
-$deployment = Join-Path $resolvedQt 'bin/windeployqt.exe'
-foreach ($name in @('Visual Enhancer.exe', 'VE_CLI.exe')) {
- $binary = Join-Path $binaryDirectory $name
- if (-not (Test-Path -LiteralPath $binary)) { throw "Build $Configuration first: $binary is missing." }
-}
-if (-not (Test-Path -LiteralPath (Join-Path $runtimeSource 'bin/runtime'))) {
- throw "Required media tools and native engines are missing from $runtimeSource/bin."
-}
-$nativeModules = @{
- neural_rendering = @('dlssnr', 'neuroframe_engine_neural_rendering.dll')
- super_resolution = @('dlsssr', 'neuroframe_engine_super_resolution.dll')
- frame_interpolation = @('dlssg', 'neuroframe_engine_frame_interpolation.dll')
- rtx_video = @('rtx_video', 'neuroframe_engine_upscaling.dll')
- video_effects = @('vfx', 'neuroframe_engine_video_effects.dll')
-}
-if ($NativeBuildRoot) {
- $resolvedNativeBuildRoot = Resolve-VePath $NativeBuildRoot $projectRoot
- foreach ($feature in $nativeModules.Keys) {
- $binary = Join-Path $resolvedNativeBuildRoot "$feature/build/$($nativeModules[$feature][1])"
- if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Rebuild native engine first: $binary" }
- }
-}
-# Copy directory contents explicitly so runtime assets become ordinary files,
-# including any source asset directories backed by junctions.
-function Copy-VeTree([string]$Source, [string]$Target) {
- if ([IO.Path]::GetFullPath($Source) -eq [IO.Path]::GetFullPath($Target)) { return }
- New-Item -ItemType Directory -Path $Target -Force | Out-Null
- foreach ($item in Get-ChildItem -LiteralPath $Source -Force) {
- $targetItem = Join-Path $Target $item.Name
- if ($item.PSIsContainer) { Copy-VeTree $item.FullName $targetItem }
- else { Copy-Item -LiteralPath $item.FullName -Destination $targetItem -Force }
- }
-}
-if ((Test-Path -LiteralPath $appDirectory) -and @(Get-ChildItem -LiteralPath $appDirectory -Force).Count) {
- throw 'Package into a new empty application directory.'
-}
-New-Item -ItemType Directory -Path $appDirectory -Force | Out-Null
-Copy-VeTree (Join-Path $runtimeSource 'bin') (Join-Path $appDirectory 'bin')
-$vfxModuleRoot = Join-Path $workspaceRoot 'native (dev)/modules/video_effects'
-$vfxBinary = Join-Path $vfxModuleRoot 'build/neuroframe_engine_video_effects.dll'
-if($NativeBuildRoot){$vfxBinary=Join-Path $resolvedNativeBuildRoot 'video_effects/build/neuroframe_engine_video_effects.dll'}
-$vfxRuntime = Join-Path $appDirectory 'bin/runtime/vfx'
-if(Test-Path -LiteralPath $vfxBinary){
- New-Item -ItemType Directory -Force -Path $vfxRuntime | Out-Null
- Copy-Item -LiteralPath $vfxBinary -Destination $vfxRuntime -Force
- & (Join-Path $vfxModuleRoot 'package_runtime.ps1') -Destination $vfxRuntime
- # NGX plugins shared by RTX Video and VFX must come from the same SDK release.
- $vfxSdk = Join-Path $workspaceRoot 'native (dev)/external/VFXSDK_windows_1.3.0.0/VideoFX'
- foreach ($plugin in @(@('nvvfxvideosuperres','nvngx_vsr.dll'),@('nvvfxtruehdr','nvngx_truehdr.dll'))) {
- Copy-Item -LiteralPath (Join-Path $vfxSdk "features/$($plugin[0])/bin/$($plugin[1])") -Destination (Join-Path $appDirectory "bin/runtime/rtx_video/$($plugin[1])") -Force
- }
-}elseif(-not(Test-Path -LiteralPath (Join-Path $vfxRuntime 'neuroframe_engine_video_effects.dll'))){throw 'Build the NVIDIA VFX bridge before packaging the application.'}
-if ($NativeBuildRoot) {
- foreach ($feature in $nativeModules.Keys) {
- $binary = Join-Path $resolvedNativeBuildRoot "$feature/build/$($nativeModules[$feature][1])"
- $target = Join-Path $appDirectory "bin/runtime/$($nativeModules[$feature][0])/$($nativeModules[$feature][1])"
- Copy-Item -LiteralPath $binary -Destination $target -Force
- }
-}
-foreach ($name in @('LICENSE.txt', 'THIRD-PARTY-NOTICES.txt')) {
- $source = Join-Path $runtimeSource $name
- $target = Join-Path $appDirectory $name
- if ($source -ne $target -and (Test-Path -LiteralPath $source)) {
- Copy-Item -LiteralPath $source -Destination $target -Force
- }
-}
-$resources = Join-Path $appDirectory 'resources'
-$brandingDirectory = Join-Path $resources 'branding'
-New-Item -ItemType Directory -Path $brandingDirectory -Force | Out-Null
-$brandingSource = Join-Path $runtimeSource 'resources/branding/icon.png'
-if (-not (Test-Path -LiteralPath $brandingSource -PathType Leaf)) {
- $brandingSource = Join-Path $workspaceRoot 'native (dev)/assets/icon.png'
-}
-if (Test-Path -LiteralPath $brandingSource -PathType Leaf) {
- Copy-Item -LiteralPath $brandingSource -Destination $brandingDirectory -Force
-}
-Copy-VeTree (Join-Path $projectRoot 'src/desktop') (Join-Path $resources 'desktop')
-Copy-VeTree (Join-Path $projectRoot 'src/processing/shaders') (Join-Path $resources 'shaders')
-foreach ($name in @('Visual Enhancer.exe', 'VE_CLI.exe')) {
- Copy-Item -LiteralPath (Join-Path $binaryDirectory $name) -Destination (Join-Path $resolvedDestination $name) -Force
-}
-$mode = if ($Configuration -eq 'Debug') { '--debug' } else { '--release' }
-$visualStudio = Get-VeVisualStudioInstallation
-$originalVcDirectory = [Environment]::GetEnvironmentVariable('VCINSTALLDIR')
-try {
- $env:VCINSTALLDIR = (Join-Path $visualStudio.installationPath 'VC') + '\'
- $deploymentArguments = @($mode, '--compiler-runtime', '--skip-plugin-types', 'qmltooling', '--dir', $appDirectory,
- '--qmldir', (Join-Path $projectRoot 'src/desktop/qml'),
- (Join-Path $appDirectory 'Visual Enhancer.exe'), (Join-Path $appDirectory 'VE_CLI.exe'))
- Invoke-VeCommand $deployment $deploymentArguments
-} finally { $env:VCINSTALLDIR = $originalVcDirectory }
-$offscreenName = if ($Configuration -eq 'Debug') { 'qoffscreend.dll' } else { 'qoffscreen.dll' }
-$offscreenSource = Join-Path $resolvedQt "plugins/platforms/$offscreenName"
-if (-not (Test-Path -LiteralPath $offscreenSource)) { throw "Missing Qt offscreen plugin: $offscreenSource" }
-$platformDirectory = Join-Path $appDirectory 'platforms'
-New-Item -ItemType Directory -Path $platformDirectory -Force | Out-Null
-# The CLI uses QGuiApplication with the offscreen platform for image processing.
-Copy-Item -LiteralPath $offscreenSource -Destination $platformDirectory -Force
-$redistRoot = Join-Path $visualStudio.installationPath 'VC/Redist/MSVC'
-$redistVersion = Get-ChildItem -LiteralPath $redistRoot -Directory |
- Where-Object { $_.Name -match '^\d+\.\d+\.\d+$' } |
- Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1
-if (-not $redistVersion) { throw 'The Visual C++ runtime directory was not found.' }
-$architecturePath = if ($Configuration -eq 'Debug') { 'debug_nonredist/x64' } else { 'x64' }
-$crtDirectory = Get-ChildItem -LiteralPath (Join-Path $redistVersion.FullName $architecturePath) -Directory |
- Where-Object { $_.Name -match '^Microsoft\.VC\d+\.(Debug)?CRT$' } | Select-Object -First 1
-if (-not $crtDirectory) { throw 'The matching x64 Visual C++ runtime was not found.' }
-Get-ChildItem -LiteralPath $crtDirectory.FullName -File -Filter '*.dll' | ForEach-Object {
- Copy-Item -LiteralPath $_.FullName -Destination $appDirectory -Force
-}
-# Runtime paths are embedded in the application executables.
-$externalQtConfiguration = Join-Path $resolvedDestination 'qt.conf'
-if (Test-Path -LiteralPath $externalQtConfiguration) { Remove-Item -LiteralPath $externalQtConfiguration -Force }
-# Remove only obsolete application entry files after the replacement executables
-# and their dependencies have been deployed successfully.
-foreach ($name in @('Visual Enhancer.app.dll', 'VE_CLI.app.dll', 'Visual Enhancer.app.exe', 'VE_CLI.app.exe', 'qt.conf')) {
- $obsolete = Join-Path $appDirectory $name
- if (Test-Path -LiteralPath $obsolete) { Remove-Item -LiteralPath $obsolete -Force }
-}
-# The application fixes its Qt Quick style to Basic. Keep its runtime imports,
-# translations and dialogs, but omit development metadata and unused styles.
-# Validate each target before removing old files from an existing installation.
-function Remove-VePackagedArtifact([string]$RelativePath) {
- $appRoot = [IO.Path]::GetFullPath($appDirectory).TrimEnd('\', '/') + [IO.Path]::DirectorySeparatorChar
- $target = [IO.Path]::GetFullPath((Join-Path $appDirectory $RelativePath))
- if (-not $target.StartsWith($appRoot, [StringComparison]::OrdinalIgnoreCase)) {
- throw "Packaging cleanup target is outside the application directory: $RelativePath"
- }
- if (Test-Path -LiteralPath $target) {
- $item = Get-Item -LiteralPath $target -Force
- if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
- throw "Packaging cleanup cannot follow a linked directory: $RelativePath"
- }
- if ($item.PSIsContainer) {
- $links = @(Get-ChildItem -LiteralPath $target -Recurse -Force |
- Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint })
- if ($links.Count) { throw "Packaging cleanup found a linked directory in $RelativePath" }
- }
- Remove-Item -LiteralPath $target -Recurse -Force
- }
-}
-foreach ($relative in @('release', 'qmltooling', 'vc_redist.x64.exe', 'qml/QtQuick/NativeStyle')) {
- Remove-VePackagedArtifact $relative
-}
-foreach ($style in @('Fusion', 'Imagine', 'Material', 'Universal', 'FluentWinUI3', 'Windows', 'Native')) {
- Remove-VePackagedArtifact "qml/QtQuick/Controls/$style"
- foreach ($suffix in @('.dll', 'd.dll', 'StyleImpl.dll', 'StyleImpld.dll')) {
- Remove-VePackagedArtifact "Qt6QuickControls2$style$suffix"
- }
-}
-foreach ($name in @('Qt6QuickNativeStyle.dll', 'Qt6QuickNativeStyled.dll')) {
- Remove-VePackagedArtifact $name
-}
-foreach ($directory in @('qml', 'resources/desktop/translations')) {
- Get-ChildItem -LiteralPath (Join-Path $appDirectory $directory) -Recurse -File |
- Where-Object { $_.Extension -in @('.qmltypes', '.ts') } | ForEach-Object {
- Remove-VePackagedArtifact ([IO.Path]::GetRelativePath($appDirectory, $_.FullName))
- }
-}
-foreach ($directory in @('outputs', 'logs')) {
- New-Item -ItemType Directory -Path (Join-Path $resolvedDestination $directory) -Force | Out-Null
-}
-if ($CertificateThumbprint) {
- & (Join-Path $PSScriptRoot 'sign-release.ps1') -PackageRoot $resolvedDestination `
- -CertificateThumbprint $CertificateThumbprint -TimestampServer $TimestampServer `
- -MachineCertificateStore:$MachineCertificateStore
-}
-& (Join-Path $PSScriptRoot 'audit-release.ps1') -PackageRoot $resolvedDestination `
- -RequireSignatures:([bool]$CertificateThumbprint)
-Write-Host "Ready-to-run application: $resolvedDestination"
+$workspace = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
+if (-not $Destination) { $Destination = Join-Path $workspace 'Visual Enhancer' }
+$destinationRoot = Resolve-VePath $Destination (Split-Path -Parent $PSScriptRoot)
+if ($destinationRoot -eq $workspace -or $destinationRoot -eq (Join-Path $workspace 'Build')) {
+ throw 'Deploy into a dedicated application directory.'
+}
+$operation = Join-Path (Split-Path -Parent $destinationRoot) ('.ve-deployments/' + [Guid]::NewGuid().ToString('N'))
+$stage = Join-Path $operation 'package'
+if (-not $OutputDirectory) { $OutputDirectory = Join-Path $operation 'reports' }
+New-Item -ItemType Directory -Path $operation -Force | Out-Null
+# An old installation can supply dependencies, but never executable launchers or user state.
+if (-not $RuntimeSource) {
+ $prepared = Join-Path $workspace 'native (dev)/external/VisualEnhancerRuntime'
+ if (Test-Path -LiteralPath (Join-Path $prepared 'bin/runtime')) { $RuntimeSource = $prepared }
+ elseif (Test-Path -LiteralPath (Join-Path $destinationRoot 'bin/runtime')) { $RuntimeSource = $destinationRoot }
+ else { $RuntimeSource = Join-Path $destinationRoot 'app' }
+}
+& (Join-Path $PSScriptRoot 'package.ps1') -Configuration $Configuration -QtRoot $QtRoot -BuildDir $BuildDir `
+ -Destination $stage -NativeBuildRoot $NativeBuildRoot -RuntimeSource $RuntimeSource `
+ -CertificateThumbprint $CertificateThumbprint -TimestampServer $TimestampServer `
+ -MachineCertificateStore:$MachineCertificateStore -RequireSignatures:$RequireSignatures -OutputDirectory $OutputDirectory
+$entrypointTests = Join-Path $workspace 'Tests/entrypoint_tests.ps1'
+if (Test-Path -LiteralPath $entrypointTests -PathType Leaf) {
+ & $entrypointTests -PackageRoot $stage -OutputDirectory $OutputDirectory
+}
+[ordered]@{ stage = $stage; destination = $destinationRoot; operation = $operation } |
+ ConvertTo-Json | Set-Content -LiteralPath (Join-Path $OutputDirectory 'stage.json') -Encoding utf8
+if ($ScanDefender) {
+ & (Join-Path $PSScriptRoot 'scan-release.ps1') -PackageRoot $stage -OutputDirectory $OutputDirectory
+}
+if ($StageOnly) {
+ Write-Host "Validated staged package: $stage"
+ return
+}
+& (Join-Path $PSScriptRoot 'promote-package.ps1') -Stage $stage -Destination $destinationRoot `
+ -BackupDirectory (Join-Path $operation 'previous') -OutputDirectory $OutputDirectory
+Write-Host "Ready-to-run application: $destinationRoot"
diff --git a/tools/package.ps1 b/tools/package.ps1
new file mode 100644
index 0000000..38f7b32
--- /dev/null
+++ b/tools/package.ps1
@@ -0,0 +1,237 @@
+[CmdletBinding()]
+param(
+ [ValidateSet('Debug', 'Release', 'RelWithDebInfo')][string]$Configuration = 'Release',
+ [string]$QtRoot,
+ [string]$BuildDir = 'out',
+ [string]$Destination,
+ [string]$NativeBuildRoot,
+ [string]$RuntimeSource,
+ [string]$CertificateThumbprint,
+ [string]$TimestampServer = 'http://timestamp.digicert.com',
+ [switch]$MachineCertificateStore,
+ [switch]$RequireSignatures,
+ [string]$OutputDirectory
+)
+$ErrorActionPreference = 'Stop'
+. (Join-Path $PSScriptRoot 'Toolchain.ps1')
+$projectRoot = Split-Path -Parent $PSScriptRoot
+$workspaceRoot = Split-Path -Parent $projectRoot
+$resolvedQt = Resolve-VeQtRoot $QtRoot
+$resolvedBuild = Resolve-VePath $BuildDir $projectRoot
+if (-not $Destination) { $Destination = Join-Path $workspaceRoot 'Visual Enhancer' }
+$resolvedDestination = Resolve-VePath $Destination $projectRoot
+if ($resolvedDestination -eq $projectRoot -or $resolvedDestination -eq $workspaceRoot) {
+ throw 'Deploy to the Visual Enhancer folder or another dedicated application folder.'
+}
+$appDirectory = $resolvedDestination
+$runtimeSource = if ($RuntimeSource) { Resolve-VePath $RuntimeSource $projectRoot }
+ elseif (Test-Path -LiteralPath (Join-Path $workspaceRoot 'native (dev)/external/VisualEnhancerRuntime/bin/runtime')) {
+ Join-Path $workspaceRoot 'native (dev)/external/VisualEnhancerRuntime'
+ } elseif (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Visual Enhancer/bin/runtime')) {
+ Join-Path $workspaceRoot 'Visual Enhancer'
+ } else { Join-Path $workspaceRoot 'Visual Enhancer/app' }
+$binaryDirectory = Join-Path $resolvedBuild $Configuration
+$deployment = Join-Path $resolvedQt 'bin/windeployqt.exe'
+foreach ($name in @('Visual Enhancer.exe', 'VE_CLI.exe')) {
+ $binary = Join-Path $binaryDirectory $name
+ if (-not (Test-Path -LiteralPath $binary)) { throw "Build $Configuration first: $binary is missing." }
+}
+if (-not (Test-Path -LiteralPath (Join-Path $runtimeSource 'bin/runtime'))) {
+ throw "Required media tools and native engines are missing from $runtimeSource/bin. Prepare dependencies with tools/prepare-runtime.ps1 or pass -RuntimeSource."
+}
+foreach ($required in @('bin/ffmpeg/bin/ffmpeg.exe', 'bin/ffmpeg/bin/ffprobe.exe', 'bin/avif/avifenc.exe',
+ 'bin/exiv2/exiv2.exe', 'bin/runtime/dlssnr/nvngx_dlssnr.dll', 'bin/runtime/dlsssr/nvngx_dlss.dll',
+ 'bin/runtime/dlssg/nvngx_dlssg.dll', 'bin/runtime/dlssrr/nvngx_dlssd.dll')) {
+ if (-not (Test-Path -LiteralPath (Join-Path $runtimeSource $required) -PathType Leaf)) {
+ throw "Required runtime dependency is missing: $runtimeSource/$required"
+ }
+}
+$nativeModules = @{
+ neural_rendering = @('dlssnr', 'neuroframe_engine_neural_rendering.dll')
+ super_resolution = @('dlsssr', 'neuroframe_engine_super_resolution.dll')
+ ray_reconstruction = @('dlssrr', 'neuroframe_engine_ray_reconstruction.dll')
+ frame_interpolation = @('dlssg', 'neuroframe_engine_frame_interpolation.dll')
+ rtx_video = @('rtx_video', 'neuroframe_engine_upscaling.dll')
+ video_effects = @('vfx', 'neuroframe_engine_video_effects.dll')
+}
+if (-not $NativeBuildRoot) {
+ $localNativeRoot = Join-Path $workspaceRoot 'native (dev)/modules'
+ $missingLocalEngines = @($nativeModules.Keys | Where-Object {
+ -not (Test-Path -LiteralPath (Join-Path $localNativeRoot "$_/build/$($nativeModules[$_][1])") -PathType Leaf)
+ })
+ if (-not $missingLocalEngines.Count) { $NativeBuildRoot = $localNativeRoot }
+}
+if ($NativeBuildRoot) {
+ $resolvedNativeBuildRoot = Resolve-VePath $NativeBuildRoot $projectRoot
+ foreach ($feature in $nativeModules.Keys) {
+ $binary = Join-Path $resolvedNativeBuildRoot "$feature/build/$($nativeModules[$feature][1])"
+ if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Rebuild native engine first: $binary" }
+ }
+}
+# Copy directory contents explicitly so runtime assets become ordinary files,
+# including any source asset directories backed by junctions.
+function Copy-VeTree([string]$Source, [string]$Target) {
+ if ([IO.Path]::GetFullPath($Source) -eq [IO.Path]::GetFullPath($Target)) { return }
+ New-Item -ItemType Directory -Path $Target -Force | Out-Null
+ foreach ($item in Get-ChildItem -LiteralPath $Source -Force) {
+ $targetItem = Join-Path $Target $item.Name
+ if ($item.PSIsContainer) { Copy-VeTree $item.FullName $targetItem }
+ else { Copy-Item -LiteralPath $item.FullName -Destination $targetItem -Force }
+ }
+}
+if ((Test-Path -LiteralPath $appDirectory) -and @(Get-ChildItem -LiteralPath $appDirectory -Force).Count) {
+ throw 'Package into a new empty directory; use deploy.ps1 for validated installation upgrades.'
+}
+New-Item -ItemType Directory -Path $appDirectory -Force | Out-Null
+if ([IO.Path]::GetFullPath($runtimeSource) -ne [IO.Path]::GetFullPath($appDirectory)) {
+ # Replacing a wheel can change every DLL filename. Remove superseded files
+ # from these supplied dependency sets to avoid ambiguous libav/libheif loads.
+ foreach ($relative in @('bin/runtime/av', 'bin/runtime/image-codecs')) {
+ $sourceDirectory = Join-Path $runtimeSource $relative
+ $targetDirectory = Join-Path $appDirectory $relative
+ if (-not (Test-Path -LiteralPath $sourceDirectory -PathType Container)) { throw "Missing dependency set: $sourceDirectory" }
+ if (Test-Path -LiteralPath $targetDirectory) {
+ if ((Get-Item -LiteralPath $targetDirectory).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Dependency target cannot be a link: $targetDirectory" }
+ foreach ($file in Get-ChildItem -LiteralPath $targetDirectory -File) {
+ if (-not (Test-Path -LiteralPath (Join-Path $sourceDirectory $file.Name) -PathType Leaf)) {
+ Remove-Item -LiteralPath $file.FullName -Force
+ }
+ }
+ }
+ }
+}
+Copy-VeTree (Join-Path $runtimeSource 'bin') (Join-Path $appDirectory 'bin')
+Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'QT-RELINKING.txt') -Destination (Join-Path $appDirectory 'bin/licenses/QT-RELINKING.txt') -Force
+$vfxModuleRoot = Join-Path $workspaceRoot 'native (dev)/modules/video_effects'
+$vfxBinary = Join-Path $vfxModuleRoot 'build/neuroframe_engine_video_effects.dll'
+if($NativeBuildRoot){$vfxBinary=Join-Path $resolvedNativeBuildRoot 'video_effects/build/neuroframe_engine_video_effects.dll'}
+$vfxRuntime = Join-Path $appDirectory 'bin/runtime/vfx'
+if(Test-Path -LiteralPath $vfxBinary){
+ New-Item -ItemType Directory -Force -Path $vfxRuntime | Out-Null
+ Copy-Item -LiteralPath $vfxBinary -Destination $vfxRuntime -Force
+ & (Join-Path $vfxModuleRoot 'package_runtime.ps1') -Destination $vfxRuntime
+ # NGX plugins shared by RTX Video and VFX must come from the same SDK release.
+ $vfxSdk = Join-Path $workspaceRoot 'native (dev)/external/VFXSDK_windows_1.3.0.0/VideoFX'
+ foreach ($plugin in @(@('nvvfxvideosuperres','nvngx_vsr.dll'),@('nvvfxtruehdr','nvngx_truehdr.dll'))) {
+ Copy-Item -LiteralPath (Join-Path $vfxSdk "features/$($plugin[0])/bin/$($plugin[1])") -Destination (Join-Path $appDirectory "bin/runtime/rtx_video/$($plugin[1])") -Force
+ }
+}elseif(-not(Test-Path -LiteralPath (Join-Path $vfxRuntime 'neuroframe_engine_video_effects.dll'))){throw 'Build the NVIDIA VFX bridge before packaging the application.'}
+if ($NativeBuildRoot) {
+ foreach ($feature in $nativeModules.Keys) {
+ $binary = Join-Path $resolvedNativeBuildRoot "$feature/build/$($nativeModules[$feature][1])"
+ $target = Join-Path $appDirectory "bin/runtime/$($nativeModules[$feature][0])/$($nativeModules[$feature][1])"
+ Copy-Item -LiteralPath $binary -Destination $target -Force
+ }
+}
+foreach ($name in @('LICENSE.txt', 'THIRD-PARTY-NOTICES.txt')) {
+ $source = Join-Path $runtimeSource $name
+ $target = Join-Path $appDirectory $name
+ if ($source -ne $target -and (Test-Path -LiteralPath $source)) {
+ Copy-Item -LiteralPath $source -Destination $target -Force
+ }
+}
+$resources = Join-Path $appDirectory 'resources'
+$brandingDirectory = Join-Path $resources 'branding'
+New-Item -ItemType Directory -Path $brandingDirectory -Force | Out-Null
+$brandingSource = Join-Path $runtimeSource 'resources/branding/icon.png'
+if (-not (Test-Path -LiteralPath $brandingSource -PathType Leaf)) {
+ $brandingSource = Join-Path $workspaceRoot 'native (dev)/assets/icon.png'
+}
+if (-not (Test-Path -LiteralPath $brandingSource -PathType Leaf)) {
+ throw 'The selected runtime source must include resources/branding/icon.png.'
+}
+Copy-Item -LiteralPath $brandingSource -Destination $brandingDirectory -Force
+Copy-VeTree (Join-Path $projectRoot 'src/desktop') (Join-Path $resources 'desktop')
+Copy-VeTree (Join-Path $projectRoot 'src/processing/shaders') (Join-Path $resources 'shaders')
+foreach ($name in @('Visual Enhancer.exe', 'VE_CLI.exe')) {
+ Copy-Item -LiteralPath (Join-Path $binaryDirectory $name) -Destination (Join-Path $resolvedDestination $name) -Force
+}
+$mode = if ($Configuration -eq 'Debug') { '--debug' } else { '--release' }
+$visualStudio = Get-VeVisualStudioInstallation
+$originalVcDirectory = [Environment]::GetEnvironmentVariable('VCINSTALLDIR')
+try {
+ $env:VCINSTALLDIR = (Join-Path $visualStudio.installationPath 'VC') + '\'
+ $deploymentArguments = @($mode, '--compiler-runtime', '--skip-plugin-types', 'qmltooling', '--dir', $appDirectory,
+ '--qmldir', (Join-Path $projectRoot 'src/desktop/qml'),
+ (Join-Path $appDirectory 'Visual Enhancer.exe'), (Join-Path $appDirectory 'VE_CLI.exe'))
+ Invoke-VeCommand $deployment $deploymentArguments
+} finally { $env:VCINSTALLDIR = $originalVcDirectory }
+$offscreenName = if ($Configuration -eq 'Debug') { 'qoffscreend.dll' } else { 'qoffscreen.dll' }
+$offscreenSource = Join-Path $resolvedQt "plugins/platforms/$offscreenName"
+if (-not (Test-Path -LiteralPath $offscreenSource)) { throw "Missing Qt offscreen plugin: $offscreenSource" }
+$platformDirectory = Join-Path $appDirectory 'platforms'
+New-Item -ItemType Directory -Path $platformDirectory -Force | Out-Null
+# The CLI uses QGuiApplication with the offscreen platform for image processing.
+Copy-Item -LiteralPath $offscreenSource -Destination $platformDirectory -Force
+$redistRoot = Join-Path $visualStudio.installationPath 'VC/Redist/MSVC'
+$redistVersion = Get-ChildItem -LiteralPath $redistRoot -Directory |
+ Where-Object { $_.Name -match '^\d+\.\d+\.\d+$' } |
+ Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1
+if (-not $redistVersion) { throw 'The Visual C++ runtime directory was not found.' }
+$architecturePath = if ($Configuration -eq 'Debug') { 'debug_nonredist/x64' } else { 'x64' }
+$crtDirectory = Get-ChildItem -LiteralPath (Join-Path $redistVersion.FullName $architecturePath) -Directory |
+ Where-Object { $_.Name -match '^Microsoft\.VC\d+\.(Debug)?CRT$' } | Select-Object -First 1
+if (-not $crtDirectory) { throw 'The matching x64 Visual C++ runtime was not found.' }
+Get-ChildItem -LiteralPath $crtDirectory.FullName -File -Filter '*.dll' | ForEach-Object {
+ Copy-Item -LiteralPath $_.FullName -Destination $appDirectory -Force
+}
+# Runtime paths are embedded in the application executables.
+$externalQtConfiguration = Join-Path $resolvedDestination 'qt.conf'
+if (Test-Path -LiteralPath $externalQtConfiguration) { Remove-Item -LiteralPath $externalQtConfiguration -Force }
+# Remove only obsolete application entry files after the replacement executables
+# and their dependencies have been deployed successfully.
+foreach ($name in @('Visual Enhancer.app.dll', 'VE_CLI.app.dll', 'Visual Enhancer.app.exe', 'VE_CLI.app.exe', 'qt.conf')) {
+ $obsolete = Join-Path $appDirectory $name
+ if (Test-Path -LiteralPath $obsolete) { Remove-Item -LiteralPath $obsolete -Force }
+}
+# The application fixes its Qt Quick style to Basic. Keep its runtime imports,
+# translations and dialogs, but omit development metadata and unused styles.
+# Validate each target before removing old files from an existing installation.
+function Remove-VePackagedArtifact([string]$RelativePath) {
+ $appRoot = [IO.Path]::GetFullPath($appDirectory).TrimEnd('\', '/') + [IO.Path]::DirectorySeparatorChar
+ $target = [IO.Path]::GetFullPath((Join-Path $appDirectory $RelativePath))
+ if (-not $target.StartsWith($appRoot, [StringComparison]::OrdinalIgnoreCase)) {
+ throw "Packaging cleanup target is outside the package: $RelativePath"
+ }
+ if (Test-Path -LiteralPath $target) {
+ $item = Get-Item -LiteralPath $target -Force
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ throw "Packaging cleanup cannot follow a linked directory: $RelativePath"
+ }
+ if ($item.PSIsContainer) {
+ $links = @(Get-ChildItem -LiteralPath $target -Recurse -Force |
+ Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint })
+ if ($links.Count) { throw "Packaging cleanup found a linked directory in $RelativePath" }
+ }
+ Remove-Item -LiteralPath $target -Recurse -Force
+ }
+}
+foreach ($relative in @('release', 'qmltooling', 'vc_redist.x64.exe', 'qml/QtQuick/NativeStyle')) {
+ Remove-VePackagedArtifact $relative
+}
+foreach ($style in @('Fusion', 'Imagine', 'Material', 'Universal', 'FluentWinUI3', 'Windows', 'Native')) {
+ Remove-VePackagedArtifact "qml/QtQuick/Controls/$style"
+ foreach ($suffix in @('.dll', 'd.dll', 'StyleImpl.dll', 'StyleImpld.dll')) {
+ Remove-VePackagedArtifact "Qt6QuickControls2$style$suffix"
+ }
+}
+foreach ($name in @('Qt6QuickNativeStyle.dll', 'Qt6QuickNativeStyled.dll')) {
+ Remove-VePackagedArtifact $name
+}
+foreach ($directory in @('qml', 'resources/desktop/translations')) {
+ Get-ChildItem -LiteralPath (Join-Path $appDirectory $directory) -Recurse -File |
+ Where-Object { $_.Extension -in @('.qmltypes', '.ts') } | ForEach-Object {
+ Remove-VePackagedArtifact ([IO.Path]::GetRelativePath($appDirectory, $_.FullName))
+ }
+}
+foreach ($directory in @('outputs', 'logs')) {
+ New-Item -ItemType Directory -Path (Join-Path $resolvedDestination $directory) -Force | Out-Null
+}
+if ($CertificateThumbprint) {
+ & (Join-Path $PSScriptRoot 'sign-release.ps1') -PackageRoot $resolvedDestination `
+ -CertificateThumbprint $CertificateThumbprint -TimestampServer $TimestampServer `
+ -MachineCertificateStore:$MachineCertificateStore
+}
+& (Join-Path $PSScriptRoot 'audit-release.ps1') -PackageRoot $resolvedDestination `
+ -RequireSignatures:($RequireSignatures -or [bool]$CertificateThumbprint) -OutputDirectory $OutputDirectory
+Write-Host "Ready-to-run application: $resolvedDestination"
diff --git a/tools/prepare-runtime.ps1 b/tools/prepare-runtime.ps1
new file mode 100644
index 0000000..c863d3e
--- /dev/null
+++ b/tools/prepare-runtime.ps1
@@ -0,0 +1,110 @@
+[CmdletBinding()]
+param(
+ [string]$QtRoot,
+ [string]$DownloadRoot = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'VisualEnhancerBuildCache'),
+ [string]$Destination
+)
+$ErrorActionPreference = 'Stop'
+. (Join-Path $PSScriptRoot 'Toolchain.ps1')
+$projectRoot = Split-Path -Parent $PSScriptRoot
+$workspaceRoot = Split-Path -Parent $projectRoot
+$nativeRoot = Join-Path $workspaceRoot 'native (dev)'
+$externalRoot = Join-Path $nativeRoot 'external'
+$resolvedQt = Resolve-VeQtRoot $QtRoot
+if (-not $Destination) { $Destination = Join-Path $externalRoot 'VisualEnhancerRuntime' }
+$destinationRoot = Resolve-VePath $Destination $projectRoot
+$downloadDirectory = Resolve-VePath $DownloadRoot $projectRoot
+$sevenZip = Get-Command 7z.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -First 1
+if (-not $sevenZip) { $sevenZip = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) '7-Zip/7z.exe' }
+if (-not (Test-Path -LiteralPath $sevenZip -PathType Leaf)) { throw 'Install 7-Zip to unpack the upstream dependencies.' }
+New-Item -ItemType Directory -Force -Path $downloadDirectory, $destinationRoot | Out-Null
+
+# Versions and SHA-256 values are pinned. Only vendor dependencies are extracted
+# from archives; no application executable or engine DLL comes from a release.
+# PyAV 16 supplies libavcodec 62/libavutil 60/swscale 9, matching our headers.
+$downloads = @(
+ @{Name='ffmpeg-9.0.2-full_build.7z';Url='https://github.com/GyanD/codexffmpeg/releases/download/9.0.2/ffmpeg-9.0.2-full_build.7z';Hash='f0e46253c70dfe902bac915dfb4224f0cf1b7c6eeab9da2ccc9a5581f9a71b13'},
+ @{Name='windows-artifacts.zip';Url='https://github.com/AOMediaCodec/libavif/releases/download/v1.4.2/windows-artifacts.zip';Hash='cb2d9fea43dcbab1d0707e3b37eb7b08070ad2fb60a2c188c39ec12382c0484a'},
+ @{Name='exiv2-0.28.9-2022msvc-AMD64.zip';Url='https://github.com/Exiv2/exiv2/releases/download/v0.28.9/exiv2-0.28.9-2022msvc-AMD64.zip';Hash='47b455d7102d5d3b92227e580c582d4c36f0291902dc70af95062c32852d3f1c'},
+ @{Name='av-16.0.1-cp312-cp312-win_amd64.whl';Url='https://files.pythonhosted.org/packages/15/37/c7811eca0f318d5fd3212f7e8c3d8335f75a54907c97a89213dc580b8056/av-16.0.1-cp312-cp312-win_amd64.whl';Hash='0c669b6b6668c8ae74451c15ec6d6d8a36e4c3803dc5d9910f607a174dd18f17'},
+ @{Name='pillow_heif-1.8.1-cp312-cp312-win_amd64.whl';Url='https://files.pythonhosted.org/packages/db/fd/2ff579be4694ac68cc73bfaafe1abc255bd658b678bfb3b33922784ddaf0/pillow_heif-1.8.1-cp312-cp312-win_amd64.whl';Hash='ce0ff957ad901a5a6bf8cd22ea26c4304bab7cf2f93d0a2f03046487e5711910'},
+ # The private NR model has no public SDK/source package. Extract its original
+ # NVIDIA DLL alone from the project's published archive, then verify it.
+ @{Name='Visual.Enhancer.v15.0.zip';Url='https://github.com/Merserk/dlss5-visual-enhancer/releases/download/v15.0/Visual.Enhancer.v15.0.zip';Hash='0b29deb922c5e8601b1493feb935755e07b89164a88d3922d76e33b6e5ecb93e'}
+)
+$extracted = @{}
+foreach ($download in $downloads) {
+ $archive = Join-Path $downloadDirectory $download.Name
+ if (-not (Test-Path -LiteralPath $archive -PathType Leaf) -or (Get-FileHash -LiteralPath $archive).Hash -ne $download.Hash) {
+ Invoke-VeCommand 'curl.exe' @('--fail','--location','--silent','--show-error','--connect-timeout','15',
+ '--max-time','300','--retry','1','--output',$archive,$download.Url)
+ }
+ if ((Get-FileHash -LiteralPath $archive).Hash -ne $download.Hash) { throw "Dependency checksum failed: $($download.Name)" }
+ $directory = Join-Path $downloadDirectory "extracted/$($download.Name)"
+ $arguments = @('x', $archive, "-o$directory", '-y', '-bso0', '-bsp0')
+ if ($download.Name -eq 'Visual.Enhancer.v15.0.zip') { $arguments += @('*nvngx_dlssnr.dll', '-r') }
+ Invoke-VeCommand $sevenZip $arguments
+ $extracted[$download.Name] = $directory
+}
+function Copy-Dependency([string]$Source, [string]$RelativeTarget) {
+ if (-not (Test-Path -LiteralPath $Source -PathType Leaf)) { throw "Missing dependency input: $Source" }
+ $target = Join-Path $destinationRoot $RelativeTarget
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $target) | Out-Null
+ Copy-Item -LiteralPath $Source -Destination $target -Force
+}
+$ffmpegRoot = Join-Path $extracted['ffmpeg-9.0.2-full_build.7z'] 'ffmpeg-9.0.2-full_build'
+foreach ($name in @('ffmpeg.exe', 'ffprobe.exe')) { Copy-Dependency (Join-Path $ffmpegRoot "bin/$name") "bin/ffmpeg/bin/$name" }
+Copy-Dependency (Join-Path $ffmpegRoot 'LICENSE') 'bin/ffmpeg/LICENSE'
+foreach ($name in @('avifenc.exe', 'avifdec.exe')) { Copy-Dependency (Join-Path $extracted['windows-artifacts.zip'] $name) "bin/avif/$name" }
+$exiv2Root = Join-Path $extracted['exiv2-0.28.9-2022msvc-AMD64.zip'] 'exiv2-0.28.9-2022msvc-AMD64'
+foreach ($file in Get-ChildItem -LiteralPath (Join-Path $exiv2Root 'bin') -File | Where-Object { $_.Name -eq 'exiv2.exe' -or $_.Extension -eq '.dll' }) {
+ Copy-Dependency $file.FullName "bin/exiv2/$($file.Name)"
+}
+Copy-Dependency (Join-Path $exiv2Root 'COPYING') 'bin/exiv2/COPYING'
+$avRoot = $extracted['av-16.0.1-cp312-cp312-win_amd64.whl']
+foreach ($file in Get-ChildItem -LiteralPath (Join-Path $avRoot 'av.libs') -File -Filter '*.dll') { Copy-Dependency $file.FullName "bin/runtime/av/$($file.Name)" }
+Copy-Dependency (Join-Path $avRoot 'av-16.0.1.dist-info/licenses/LICENSE.txt') 'bin/licenses/PYAV-NATIVE-DEPENDENCIES.txt'
+$heifRoot = $extracted['pillow_heif-1.8.1-cp312-cp312-win_amd64.whl']
+foreach ($file in Get-ChildItem -LiteralPath $heifRoot -Recurse -File -Filter '*.dll') { Copy-Dependency $file.FullName "bin/runtime/image-codecs/$($file.Name)" }
+Copy-Dependency (Join-Path $heifRoot 'pillow_heif-1.8.1.dist-info/licenses/LICENSES_bundled.txt') 'bin/licenses/HEIF-NATIVE-DEPENDENCIES.txt'
+Copy-Dependency (Join-Path $heifRoot 'pillow_heif-1.8.1.dist-info/licenses/LICENSE.txt') 'bin/licenses/PILLOW-HEIF-LICENSE.txt'
+$nrModel = @(Get-ChildItem -LiteralPath $extracted['Visual.Enhancer.v15.0.zip'] -Recurse -File -Filter 'nvngx_dlssnr.dll')
+if ($nrModel.Count -ne 1 -or (Get-FileHash -LiteralPath $nrModel[0].FullName).Hash -ne '6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927') { throw 'Unexpected NVIDIA Neural Rendering model.' }
+Copy-Dependency $nrModel[0].FullName 'bin/runtime/dlssnr/nvngx_dlssnr.dll'
+Copy-Dependency (Join-Path $externalRoot 'DLSS/lib/Windows_x86_64/rel/nvngx_dlss.dll') 'bin/runtime/dlsssr/nvngx_dlss.dll'
+Copy-Dependency (Join-Path $externalRoot 'DLSS/lib/Windows_x86_64/rel/nvngx_dlssg.dll') 'bin/runtime/dlssg/nvngx_dlssg.dll'
+Copy-Dependency (Join-Path $externalRoot 'streamline-sdk-v2.14.16/bin/x64/nvngx_dlssd.dll') 'bin/runtime/dlssrr/nvngx_dlssd.dll'
+Copy-Dependency (Join-Path $externalRoot 'streamline-sdk-v2.14.16/bin/x64/nvngx_dlss.license.txt') 'bin/runtime/dlssrr/LICENSE-NVIDIA-DLSS.txt'
+foreach ($feature in @('dlssnr', 'dlsssr', 'dlssg')) { Copy-Dependency (Join-Path $externalRoot 'DLSS/LICENSE.txt') "bin/runtime/$feature/LICENSE-NVIDIA-DLSS.txt" }
+Copy-Dependency (Join-Path $externalRoot 'RTX_Video_SDK_v1.1.0/NVIDIA_RTX_Video_SDK_License.pdf') 'bin/runtime/rtx_video/NVIDIA_RTX_Video_SDK_License.pdf'
+
+# Retain licensing records directly from the selected Qt kit and upstream tags.
+$licenseDirectory = Join-Path $destinationRoot 'bin/licenses'
+New-Item -ItemType Directory -Force -Path (Join-Path $licenseDirectory 'qt') | Out-Null
+foreach ($module in @('qtbase', 'qtdeclarative', 'qtimageformats', 'qtmultimedia', 'qtshadertools', 'qtsvg')) {
+ $inventory = Get-ChildItem -LiteralPath (Join-Path $resolvedQt 'sbom') -File -Filter "$module-*.spdx.json" | Select-Object -First 1
+ if (-not $inventory) { throw "Missing Qt license inventory: $module" }
+ Copy-Dependency $inventory.FullName "bin/licenses/qt/$($inventory.Name)"
+ $sbom = Get-Content -LiteralPath $inventory.FullName -Raw | ConvertFrom-Json
+ foreach ($license in $sbom.hasExtractedLicensingInfos) {
+ [IO.File]::WriteAllText((Join-Path $licenseDirectory "qt/$($license.licenseId).txt"), $license.extractedText, [Text.UTF8Encoding]::new($false))
+ }
+}
+foreach ($license in @('GPL-2.0-only', 'GPL-3.0-only', 'LGPL-2.1-or-later', 'LGPL-3.0-only', 'Qt-GPL-exception-1.0')) {
+ $name = $license.Replace('-only', '').Replace('-or-later', '') + '.txt'
+ Invoke-VeCommand 'curl.exe' @('--fail','--location','--silent','--show-error','--connect-timeout','15','--max-time','30',
+ '--output',(Join-Path $licenseDirectory $name),"https://raw.githubusercontent.com/qt/qtbase/v6.12.0/LICENSES/$license.txt")
+}
+Invoke-VeCommand 'curl.exe' @('--fail','--location','--silent','--show-error','--connect-timeout','15','--max-time','30',
+ '--output',(Join-Path $destinationRoot 'bin/avif/LICENSE'),'https://raw.githubusercontent.com/AOMediaCodec/libavif/v1.4.2/LICENSE')
+Invoke-VeCommand 'curl.exe' @('--fail','--location','--silent','--show-error','--connect-timeout','15','--max-time','30',
+ '--output',(Join-Path $licenseDirectory 'Vulkan-Loader-LICENSE.txt'),'https://raw.githubusercontent.com/KhronosGroup/Vulkan-Loader/v1.4.321/LICENSE.txt')
+$licenseSource = Join-Path $projectRoot 'LICENSE.txt'
+if (-not (Test-Path -LiteralPath $licenseSource -PathType Leaf)) {
+ $licenseSource = Join-Path $projectRoot 'LICENSE'
+}
+Copy-Dependency $licenseSource 'LICENSE.txt'
+Copy-Dependency (Join-Path $projectRoot 'THIRD-PARTY-NOTICES') 'THIRD-PARTY-NOTICES.txt'
+Copy-Dependency (Join-Path $PSScriptRoot 'QT-RELINKING.txt') 'bin/licenses/QT-RELINKING.txt'
+$downloads | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath (Join-Path $destinationRoot 'dependency-sources.json') -Encoding UTF8
+Write-Host "Runtime dependencies prepared: $destinationRoot"
diff --git a/tools/promote-package.ps1 b/tools/promote-package.ps1
new file mode 100644
index 0000000..1230578
--- /dev/null
+++ b/tools/promote-package.ps1
@@ -0,0 +1,94 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)][string]$Stage,
+ [Parameter(Mandatory)][string]$Destination,
+ [Parameter(Mandatory)][string]$BackupDirectory,
+ [Parameter(Mandatory)][string]$OutputDirectory
+)
+$ErrorActionPreference = 'Stop'
+. (Join-Path $PSScriptRoot 'Release.ps1')
+$stageRoot = (Resolve-Path -LiteralPath $Stage).Path.TrimEnd('\', '/')
+$destinationRoot = [IO.Path]::GetFullPath($Destination).TrimEnd('\', '/')
+$backupRoot = [IO.Path]::GetFullPath($BackupDirectory).TrimEnd('\', '/')
+function Assert-VeSeparatePath([string]$A, [string]$B) {
+ if ($A -eq $B -or $A.StartsWith($B + '\', [StringComparison]::OrdinalIgnoreCase) -or
+ $B.StartsWith($A + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Stage, destination and backup must be separate dedicated directories.' }
+}
+Assert-VeSeparatePath $stageRoot $destinationRoot
+Assert-VeSeparatePath $stageRoot $backupRoot
+Assert-VeSeparatePath $destinationRoot $backupRoot
+if ([IO.Path]::GetPathRoot($stageRoot) -ne [IO.Path]::GetPathRoot($destinationRoot) -or
+ [IO.Path]::GetPathRoot($backupRoot) -ne [IO.Path]::GetPathRoot($destinationRoot)) { throw 'Promotion and rollback require directories on the same volume.' }
+if (Test-Path -LiteralPath $backupRoot) { throw 'The backup directory must not already exist.' }
+foreach ($path in @($stageRoot, $destinationRoot)) {
+ if (Test-Path -LiteralPath $path) {
+ if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Cannot promote a linked directory: $path" }
+ if (@(Get-ChildItem -LiteralPath $path -Recurse -Force | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }).Count) {
+ throw "Cannot promote a tree containing filesystem links: $path"
+ }
+ }
+}
+$null = @(Get-VeOwnedBinaries $stageRoot)
+if ((Test-Path -LiteralPath (Join-Path $stageRoot 'app')) -or (Test-Path -LiteralPath (Join-Path $stageRoot 'data'))) { throw 'The staged package still has the legacy layout.' }
+$running = @(Get-Process | Where-Object { $_.Path -and ($_.Path.StartsWith($destinationRoot + '\', [StringComparison]::OrdinalIgnoreCase) -or $_.Path.StartsWith($stageRoot + '\', [StringComparison]::OrdinalIgnoreCase)) })
+if ($running.Count) { throw "Close Visual Enhancer and its workers before promotion: $($running.Id -join ', ')" }
+
+$collisions = [Collections.Generic.List[string]]::new()
+function Copy-VeUserFiles([string]$Source, [string]$Target) {
+ New-Item -ItemType Directory -Path $Target -Force | Out-Null
+ foreach ($item in Get-ChildItem -LiteralPath $Source -Force) {
+ $targetPath = Join-Path $Target $item.Name
+ if ($item.PSIsContainer) {
+ if (Test-Path -LiteralPath $targetPath -PathType Leaf) { throw "File/directory collision: $targetPath" }
+ Copy-VeUserFiles $item.FullName $targetPath
+ } else {
+ if (Test-Path -LiteralPath $targetPath) {
+ if ((Test-Path -LiteralPath $targetPath -PathType Leaf) -and
+ (Get-FileHash -LiteralPath $item.FullName).Hash -eq (Get-FileHash -LiteralPath $targetPath).Hash) { continue }
+ $index = 1
+ do {
+ $targetPath = Join-Path $Target ($item.BaseName + '-legacy-' + $index++ + $item.Extension)
+ } while (Test-Path -LiteralPath $targetPath)
+ $collisions.Add($targetPath)
+ }
+ Copy-Item -LiteralPath $item.FullName -Destination $targetPath
+ }
+ }
+}
+foreach ($name in @('outputs', 'logs')) {
+ foreach ($relative in @($name, ('data/' + $name))) {
+ $source = Join-Path $destinationRoot $relative
+ if (Test-Path -LiteralPath $source -PathType Container) { Copy-VeUserFiles $source (Join-Path $stageRoot $name) }
+ }
+}
+New-Item -ItemType Directory -Path (Split-Path -Parent $backupRoot),$OutputDirectory -Force | Out-Null
+$hadDestination = Test-Path -LiteralPath $destinationRoot
+if ($hadDestination) {
+ # Recognize the existing product before moving the entire installation.
+ if (-not (Test-Path -LiteralPath (Join-Path $destinationRoot 'Visual Enhancer.exe') -PathType Leaf)) {
+ throw 'The destination is not an existing Visual Enhancer installation.'
+ }
+ Move-Item -LiteralPath $destinationRoot -Destination $backupRoot
+}
+try {
+ Move-Item -LiteralPath $stageRoot -Destination $destinationRoot
+} catch {
+ if ($hadDestination -and -not (Test-Path -LiteralPath $destinationRoot)) { Move-Item -LiteralPath $backupRoot -Destination $destinationRoot }
+ throw
+}
+# Only a preference equal to this installation's former default is migrated.
+# Arbitrary user-selected folders and all other preferences remain unchanged.
+$key = 'HKCU:\Software\Merserk\Visual Enhancer\export'
+$migration = $false
+if (Test-Path -LiteralPath $key) {
+ $old = (Get-Item -LiteralPath $key).GetValue('folder', $null)
+ $knownDefault = Join-Path $destinationRoot 'data/outputs'
+ if ($old -and $old.Replace('/', '\').TrimEnd('\') -eq $knownDefault.Replace('/', '\')) {
+ $old | Set-Content -LiteralPath (Join-Path $OutputDirectory 'previous-export-folder.txt') -Encoding utf8
+ Set-ItemProperty -LiteralPath $key -Name folder -Value (Join-Path $destinationRoot 'outputs')
+ $migration = $true
+ }
+}
+[ordered]@{ installed = $destinationRoot; previous = if ($hadDestination) { $backupRoot } else { $null }; generated_utc = [DateTime]::UtcNow.ToString('o'); export_default_migrated = $migration; collision_copies = @($collisions) } |
+ ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $OutputDirectory 'promotion.json') -Encoding utf8
+Write-Host "Previous installation preserved at: $backupRoot"
diff --git a/tools/scan-release.ps1 b/tools/scan-release.ps1
new file mode 100644
index 0000000..b7a3be2
--- /dev/null
+++ b/tools/scan-release.ps1
@@ -0,0 +1,49 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)][string]$PackageRoot,
+ [Parameter(Mandatory)][string]$OutputDirectory,
+ [string]$Archive
+)
+$ErrorActionPreference = 'Stop'
+. (Join-Path $PSScriptRoot 'Release.ps1')
+$root = (Resolve-Path -LiteralPath $PackageRoot).Path
+$reports = [IO.Path]::GetFullPath($OutputDirectory)
+if ($reports -eq $root -or $reports.StartsWith($root.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Keep scan reports outside the release package.' }
+New-Item -ItemType Directory -Path $reports -Force | Out-Null
+$status = Get-MpComputerStatus
+$status | Select-Object AMServiceEnabled, AntivirusEnabled, RealTimeProtectionEnabled, BehaviorMonitorEnabled,
+ IoavProtectionEnabled, AMProductVersion, AMEngineVersion, AntivirusSignatureVersion, AntivirusSignatureLastUpdated |
+ ConvertTo-Json | Set-Content -LiteralPath (Join-Path $reports 'defender-status.json') -Encoding utf8
+if (-not $status.AntivirusEnabled -or -not $status.RealTimeProtectionEnabled) { throw 'Microsoft Defender must be enabled for the release scan.' }
+$tool = Join-Path $env:ProgramData 'Microsoft/Windows Defender/Platform/CurrentVersion/MpCmdRun.exe'
+if (-not (Test-Path -LiteralPath $tool -PathType Leaf)) {
+ $tool = Join-Path $env:ProgramFiles 'Windows Defender/MpCmdRun.exe'
+}
+if (-not (Test-Path -LiteralPath $tool -PathType Leaf)) { throw 'Microsoft Defender command-line scanner is unavailable.' }
+$targets = @((Get-VeOwnedBinaries $root).FullName) + @($root)
+if ($Archive) { $targets += (Resolve-Path -LiteralPath $Archive).Path }
+$results = [Collections.Generic.List[object]]::new()
+$failed = $false
+foreach ($target in $targets) {
+ $index = $results.Count + 1
+ $before = if (Test-Path -LiteralPath $target -PathType Leaf) { (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash } else { $null }
+ $started = [DateTime]::UtcNow
+ # The documented custom-scan option prevents remediation and ignores file
+ # exclusions. No exclusions, policy changes, quarantine restore or submission.
+ $scanOutput = @(& $tool -Scan -ScanType 3 -File $target -DisableRemediation 2>&1)
+ $code = $LASTEXITCODE
+ $scanOutput | Set-Content -LiteralPath (Join-Path $reports "defender-scan-$index.txt") -Encoding utf8
+ $after = if (Test-Path -LiteralPath $target -PathType Leaf) { (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash } else { $null }
+ $text = $scanOutput -join "`n"
+ $clean = $code -eq 0 -and $text -match 'found no threats' -and $before -eq $after
+ if (-not $clean) { $failed = $true }
+ $results.Add([pscustomobject]@{
+ target = $target; sha256 = $before; sha256_after = $after; started_utc = $started.ToString('o')
+ completed_utc = [DateTime]::UtcNow.ToString('o'); exit_code = $code; clean_confirmed = $clean
+ output_file = "defender-scan-$index.txt"; arguments = @('-Scan', '-ScanType', '3', '-File', $target, '-DisableRemediation')
+ })
+}
+[ordered]@{ engine = $status.AMEngineVersion; intelligence = $status.AntivirusSignatureVersion; scanner = $tool; targets = @($results) } |
+ ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $reports 'defender-scans.json') -Encoding utf8
+if ($failed) { throw "Defender did not confirm all targets clean. Review $reports/defender-scans.json and the exact scanner output. This scan set did not pass; do not publish an archive with an inconclusive result." }
+Write-Host "Defender confirmed $($targets.Count) custom scans clean; version, hashes and exact output recorded in $reports."