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

Merserk0255631f54f4
diff --git a/app.py b/app.py
index 6571c54..9f9abf0 100644
--- a/app.py
+++ b/app.py
@@ -40,11 +40,22 @@ from src.video import (
CONFIG_PATH = Path(__file__).resolve().with_name("config.ini")
PREVIEW_SECONDS = 3.0
+AUTOMATIC_MASK_CHOICES = ("Off", "On")
_CONFIG_LOCK = threading.Lock()
APP_CSS = """
+/* Keep the header links identical even when one URL has been visited. */
+#app-title a,
+#app-title a:visited,
+#app-title a:hover,
+#app-title a:active {
+ color: #00bfff !important;
+ opacity: 1 !important;
+}
+
/* Keep large upload batches compact: roughly three file rows, then scroll. */
-#image-upload-list .file-preview-holder {
+#image-upload-list .file-preview-holder,
+#image-output-list .file-preview-holder {
max-height: 210px !important;
overflow-x: hidden !important;
overflow-y: auto !important;
@@ -52,12 +63,14 @@ APP_CSS = """
scrollbar-gutter: stable;
}
-#image-upload-list .file-preview {
+#image-upload-list .file-preview,
+#image-output-list .file-preview {
max-height: none !important;
}
-/* A single input preview is a true 16:9 viewport containing the whole image. */
-#image-input-preview:has(.gallery-item:only-child) {
+/* A single input or output preview is a full 16:9 viewport without scrolling. */
+#image-input-preview:has(.gallery-item:only-child),
+#image-output-preview:has(.gallery-item:only-child) {
aspect-ratio: 16 / 9;
height: auto !important;
min-height: 0 !important;
@@ -67,22 +80,30 @@ APP_CSS = """
#image-input-preview:has(.gallery-item:only-child) .grid-wrap,
#image-input-preview:has(.gallery-item:only-child) .grid-container,
#image-input-preview:has(.gallery-item:only-child) .gallery-item,
-#image-input-preview:has(.gallery-item:only-child) .thumbnail-lg {
+#image-input-preview:has(.gallery-item:only-child) .thumbnail-lg,
+#image-output-preview:has(.gallery-item:only-child) .gallery-container,
+#image-output-preview:has(.gallery-item:only-child) .grid-wrap,
+#image-output-preview:has(.gallery-item:only-child) .grid-container,
+#image-output-preview:has(.gallery-item:only-child) .gallery-item,
+#image-output-preview:has(.gallery-item:only-child) .thumbnail-lg {
box-sizing: border-box;
height: 100% !important;
min-height: 0 !important;
}
-#image-input-preview:has(.gallery-item:only-child) .grid-wrap {
+#image-input-preview:has(.gallery-item:only-child) .grid-wrap,
+#image-output-preview:has(.gallery-item:only-child) .grid-wrap {
overflow: hidden !important;
}
-#image-input-preview:has(.gallery-item:only-child) .grid-container {
+#image-input-preview:has(.gallery-item:only-child) .grid-container,
+#image-output-preview:has(.gallery-item:only-child) .grid-container {
grid-template-rows: minmax(0, 1fr) !important;
grid-auto-rows: minmax(0, 1fr) !important;
}
-#image-input-preview:has(.gallery-item:only-child) img {
+#image-input-preview:has(.gallery-item:only-child) img,
+#image-output-preview:has(.gallery-item:only-child) img {
height: 100% !important;
width: 100% !important;
object-fit: contain !important;
@@ -90,7 +111,20 @@ APP_CSS = """
"""
-def _neural_values(settings: UISettings) -> tuple[str, str, float, float, float, float, float]:
+def _automatic_mask_choice(enabled: bool) -> str:
+ return "On" if enabled else "Off"
+
+
+def _parse_automatic_mask(value: str) -> bool:
+ if value not in AUTOMATIC_MASK_CHOICES:
+ choices = ", ".join(AUTOMATIC_MASK_CHOICES)
+ raise ValueError(f"Automatic Mask must be one of: {choices}.")
+ return value == "On"
+
+
+def _neural_values(
+ settings: UISettings,
+) -> tuple[str, str, float, float, float, float, float, str]:
return (
settings.nr_preset,
settings.nr_style,
@@ -99,6 +133,7 @@ def _neural_values(settings: UISettings) -> tuple[str, str, float, float, float,
settings.local_structure_strength,
settings.skin_structure_strength,
settings.upscaling_factor,
+ _automatic_mask_choice(settings.automatic_mask),
)
@@ -110,9 +145,10 @@ def persist_image_settings(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
image_format: str,
image_quality: float,
-) -> tuple[str, float, float, float, float, float]:
+) -> tuple[str, str, float, float, float, float, float, str]:
with _CONFIG_LOCK:
current = load_settings(CONFIG_PATH)
settings = replace(
@@ -124,6 +160,7 @@ def persist_image_settings(
local_structure_strength=local_structure_strength,
skin_structure_strength=skin_structure_strength,
upscaling_factor=upscaling_factor,
+ automatic_mask=_parse_automatic_mask(automatic_mask),
image_format=image_format,
image_quality=int(image_quality),
)
@@ -139,10 +176,11 @@ def persist_video_settings(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
codec: str,
container: str,
quality: str,
-) -> tuple[str, float, float, float, float, float]:
+) -> tuple[str, str, float, float, float, float, float, str]:
with _CONFIG_LOCK:
current = load_settings(CONFIG_PATH)
settings = replace(
@@ -154,6 +192,7 @@ def persist_video_settings(
local_structure_strength=local_structure_strength,
skin_structure_strength=skin_structure_strength,
upscaling_factor=upscaling_factor,
+ automatic_mask=_parse_automatic_mask(automatic_mask),
codec=codec,
container=container,
quality=quality,
@@ -189,6 +228,7 @@ def _process_video(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
codec: str,
container: str,
quality: str,
@@ -206,6 +246,7 @@ def _process_video(
local_tone_strength=local_tone_strength,
local_structure_strength=local_structure_strength,
skin_structure_strength=skin_structure_strength,
+ automatic_mask=_parse_automatic_mask(automatic_mask),
upscaling_factor=upscaling_factor,
codec="H.264" if is_preview else codec,
container="MP4" if is_preview else container,
@@ -256,6 +297,7 @@ def render_video(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
codec: str,
container: str,
quality: str,
@@ -263,7 +305,8 @@ def render_video(
):
return _process_video(
input_path, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, codec, container, quality, progress, None, None
+ skin_structure_strength, upscaling_factor, automatic_mask, codec, container, quality,
+ progress, None, None
)
@@ -276,6 +319,7 @@ def preview_video(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
codec: str,
container: str,
quality: str,
@@ -283,8 +327,8 @@ def preview_video(
):
return _process_video(
input_path, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, codec, container, quality, progress,
- PREVIEW_SECONDS, None
+ skin_structure_strength, upscaling_factor, automatic_mask, codec, container, quality,
+ progress, PREVIEW_SECONDS, None
)
@@ -297,6 +341,7 @@ def preview_one_frame(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
codec: str,
container: str,
quality: str,
@@ -304,7 +349,8 @@ def preview_one_frame(
):
return _process_video(
input_path, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, codec, container, quality, progress, None, 1
+ skin_structure_strength, upscaling_factor, automatic_mask, codec, container, quality,
+ progress, None, 1
)
@@ -334,6 +380,7 @@ def render_image_batch(
local_structure_strength: float,
skin_structure_strength: float,
upscaling_factor: float,
+ automatic_mask: str,
image_format: str,
image_quality: float,
progress=gr.Progress(track_tqdm=False),
@@ -349,6 +396,7 @@ def render_image_batch(
local_tone_strength=local_tone_strength,
local_structure_strength=local_structure_strength,
skin_structure_strength=skin_structure_strength,
+ automatic_mask=_parse_automatic_mask(automatic_mask),
upscaling_factor=upscaling_factor,
output_format=image_format,
quality=int(image_quality),
@@ -417,9 +465,18 @@ def build_neural_controls(settings: UISettings):
label="Skin Structure Strength", info="Skin-specific structure; -1.00 is the native default.",
buttons=["reset"]
)
+ automatic_mask = gr.Radio(
+ choices=AUTOMATIC_MASK_CHOICES,
+ value=_automatic_mask_choice(settings.automatic_mask),
+ label="Automatic Mask",
+ info=(
+ "Experimental runtime-generated mask that changes where Neural Rendering is "
+ "applied; it may cause flicker or inconsistent results."
+ ),
+ )
return [
nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor
+ skin_structure_strength, upscaling_factor, automatic_mask
]
@@ -430,7 +487,12 @@ def build_app() -> gr.Blocks:
upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]
with gr.Blocks(title="DLSS 5 Visual Enhancer") as demo:
- gr.Markdown("# DLSS 5 Visual Enhancer")
+ gr.Markdown(
+ "# DLSS 5 Visual Enhancer\n"
+ "[Support on Patreon](https://www.patreon.com/MM744) | "
+ "[GitHub](https://github.com/Merserk/dlss5-visual-enhancer)",
+ elem_id="app-title",
+ )
with gr.Tabs(selected="image"):
with gr.Tab("Image", id="image"):
with gr.Row():
@@ -494,11 +556,13 @@ def build_app() -> gr.Blocks:
object_fit="contain",
interactive=False,
buttons=["download", "download_all", "fullscreen"],
+ elem_id="image-output-preview",
)
image_output_files = gr.File(
label="Rendered image files",
file_count="multiple",
interactive=False,
+ elem_id="image-output-list",
)
image_zip = gr.DownloadButton(
"Download successful images as ZIP"
diff --git a/src/ffmpeg.py b/src/ffmpeg.py
index 9481ce4..44cd27e 100644
--- a/src/ffmpeg.py
+++ b/src/ffmpeg.py
@@ -297,7 +297,41 @@ def start_encoder(
return process, thread, logs, selected, quality
+def _probe_rendered_duration(path: Path) -> float:
+ """Read the intermediate video's duration without decoding/counting its frames."""
+ data = _run_json(
+ [
+ str(FFPROBE),
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=duration:format=duration",
+ "-of",
+ "json",
+ str(path),
+ ]
+ )
+ streams = data.get("streams") or []
+ values = [
+ (streams[0] if streams else {}).get("duration"),
+ (data.get("format") or {}).get("duration"),
+ ]
+ for raw_value in values:
+ try:
+ duration = float(raw_value)
+ except (TypeError, ValueError):
+ continue
+ if math.isfinite(duration) and duration > 0:
+ return duration
+ raise RuntimeError(
+ "Could not determine the rendered video's duration for the final audio mux."
+ )
+
+
def final_mux(temp_video: Path, source: Path, output: Path, container: str) -> None:
+ duration = _probe_rendered_duration(temp_video)
if container == "MKV":
maps = ["-map", "0:v:0", "-map", "1:a?", "-map", "1:s?"]
streams = ["-c:v", "copy", "-c:a", "copy", "-c:s", "copy"]
@@ -321,6 +355,8 @@ def final_mux(temp_video: Path, source: Path, output: Path, container: str) -> N
"-y",
"-i",
str(temp_video),
+ "-t",
+ f"{duration:.9f}",
"-i",
str(source),
*maps,
@@ -329,7 +365,6 @@ def final_mux(temp_video: Path, source: Path, output: Path, container: str) -> N
"-map_chapters",
"1",
*streams,
- "-shortest",
str(output),
]
result = subprocess.run(
diff --git a/src/images.py b/src/images.py
index b0f6c61..935cb53 100644
--- a/src/images.py
+++ b/src/images.py
@@ -26,9 +26,12 @@ from .runtime import (
DLSSFrameSession,
active_job,
detect_gpu,
+ inspect_runtime_bundle,
resize_fit,
+ validate_gpu_runtime,
validate_runtime_files,
verify_feature_18,
+ write_failure_report,
)
from .video import (
ConversionOptions,
@@ -65,6 +68,7 @@ class ImageConversionOptions:
preserve_metadata: bool = True
warmup_frames: int = 120
nr_preset: str = "Default"
+ automatic_mask: bool = False
def neural_options(self) -> ConversionOptions:
return ConversionOptions(
@@ -74,6 +78,7 @@ class ImageConversionOptions:
local_tone_strength=self.local_tone_strength,
local_structure_strength=self.local_structure_strength,
skin_structure_strength=self.skin_structure_strength,
+ automatic_mask=self.automatic_mask,
upscaling_factor=self.upscaling_factor,
warmup_frames=self.warmup_frames,
)
@@ -430,6 +435,20 @@ def convert_images(
processed_total = 0
with active_job() as controller:
gpu = detect_gpu()
+ runtime_bundle = inspect_runtime_bundle()
+ try:
+ validate_gpu_runtime(gpu, runtime_bundle)
+ except Exception as exc:
+ report_path = write_failure_report(
+ operation="image-batch-runtime-validation",
+ source="; ".join(str(path) for path in paths),
+ error=exc,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
+ )
+ raise RuntimeError(f"{exc}\nDiagnostic report: {report_path}") from exc
+ if progress:
+ progress(0.0, f"Starting feature 18 on {gpu['display_name']}")
total = len(probes)
for (output_width, output_height), group in groups.items():
cursor = 0
@@ -451,12 +470,22 @@ def convert_images(
factor=factor,
mode=mode,
native_settings=resolve_native_settings(neural),
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
controller=controller,
)
except Exception as exc:
controller.terminate_processes()
+ report_path = write_failure_report(
+ operation="image-batch-dlss-setup",
+ source="; ".join(str(item.path) for item in remaining),
+ error=exc,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
+ )
+ failure = f"{exc}\nDiagnostic report: {report_path}"
for item in remaining:
- failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))
+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)
break
segment: list[tuple[_ImageProbe, ImageConversionResult, _DecodedImage]] = []
@@ -509,7 +538,7 @@ def convert_images(
str(output),
"",
time.perf_counter() - started,
- str(gpu["name"]),
+ str(gpu["display_name"]),
item.width,
item.height,
session.render_width,
@@ -529,8 +558,20 @@ def convert_images(
interrupted = True
break
except Exception as exc:
- failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))
session.abort()
+ report_path = write_failure_report(
+ operation="image-render",
+ source=str(item.path),
+ error=exc,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
+ worker_code=session.worker.poll(),
+ worker_logs=session.worker_logs,
+ reshade_lines=session.reshade_diagnostics(),
+ )
+ failures_by_index[item.index] = ImageConversionFailure(
+ str(item.path), f"{exc}\nDiagnostic report: {report_path}"
+ )
interrupted = True
cursor += 1
processed_total += 1
@@ -540,6 +581,10 @@ def convert_images(
if progress:
progress(processed_total / total, f"Rendered {item.path.name}")
+ if not segment and interrupted:
+ if cancelled:
+ break
+ continue
if not interrupted:
try:
session.close()
@@ -548,7 +593,9 @@ def convert_images(
try:
if close_error:
raise close_error
- evidence = verify_feature_18(session.worker_logs)
+ evidence = verify_feature_18(
+ session.worker_logs, session.reshade_log_text()
+ )
assert gpu is not None
for item, result, decoded in segment:
result.report_path = _write_report(
@@ -556,11 +603,22 @@ def convert_images(
)
successes_by_index[item.index] = result
except Exception as exc:
+ report_path = write_failure_report(
+ operation="image-batch-verification",
+ source="; ".join(str(item.path) for item, _result, _decoded in segment),
+ error=exc,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
+ worker_code=session.worker.poll(),
+ worker_logs=session.worker_logs,
+ reshade_lines=session.reshade_diagnostics(),
+ )
+ failure = f"{exc}\nDiagnostic report: {report_path}"
for item, result, _decoded in segment:
output = Path(result.output_path)
if output.exists():
output.unlink()
- failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))
+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)
if cancelled:
break
if cancelled:
diff --git a/src/runtime.py b/src/runtime.py
index d73c760..6975dbe 100644
--- a/src/runtime.py
+++ b/src/runtime.py
@@ -1,12 +1,15 @@
from __future__ import annotations
+import hashlib
+import json
import re
import struct
import subprocess
import threading
+import time
from contextlib import contextmanager
from pathlib import Path
-from typing import Iterator
+from typing import Any, Iterator
import cv2
import numpy as np
@@ -17,10 +20,22 @@ RUNTIME = ROOT / "bin" / "runtime"
FFMPEG = ROOT / "bin" / "ffmpeg" / "bin" / "ffmpeg.exe"
FFPROBE = ROOT / "bin" / "ffmpeg" / "bin" / "ffprobe.exe"
WORKER = RUNTIME / "nvngx.dll" # Signed-snippet caller checks require this image name.
+ADDON = RUNTIME / "renodx-dlss5.addon64"
+NEURAL_RUNTIME = RUNTIME / "nvngx_dlssnr.dll"
OUTPUTS = ROOT / "outputs"
LOGS = ROOT / "logs"
JOBS = ROOT / "jobs"
+EXPECTED_AMPERE_ADDON_SHA256 = (
+ "245C06137AD13B1CA03AFAAD5100C1E8F0DCE8C11FE50A9272EA562F33CEA601"
+)
+EXPECTED_AMPERE_NEURAL_SHA256 = (
+ "6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927"
+)
+
+_FINGERPRINT_LOCK = threading.Lock()
+_FINGERPRINT_CACHE: dict[tuple[str, int, int], str] = {}
+
VIDEO_MAGIC = 0x33563544
SETUP_MAGIC = 0x33505553
FRAME_MAGIC = 0x314D5246
@@ -29,6 +44,168 @@ VIDEO_HEADER_FORMAT = "<13I4f"
SETUP_RESPONSE_FORMAT = "<11I"
+def _file_sha256(path: Path) -> str:
+ """Hash a runtime component, cached until its size or modification time changes."""
+ resolved = path.resolve()
+ stat = resolved.stat()
+ key = (str(resolved), stat.st_size, stat.st_mtime_ns)
+ with _FINGERPRINT_LOCK:
+ cached = _FINGERPRINT_CACHE.get(key)
+ if cached is not None:
+ return cached
+
+ digest = hashlib.sha256()
+ with resolved.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(block)
+ value = digest.hexdigest().upper()
+ with _FINGERPRINT_LOCK:
+ stale = [entry for entry in _FINGERPRINT_CACHE if entry[0] == str(resolved)]
+ for entry in stale:
+ _FINGERPRINT_CACHE.pop(entry, None)
+ _FINGERPRINT_CACHE[key] = value
+ return value
+
+
+def inspect_runtime_bundle(
+ addon_path: Path | None = None,
+ neural_path: Path | None = None,
+) -> dict[str, Any]:
+ """Return reproducible component identities for compatibility checks and reports."""
+ addon = addon_path or ADDON
+ neural = neural_path or NEURAL_RUNTIME
+ addon_hash = _file_sha256(addon)
+ neural_hash = _file_sha256(neural)
+ known_pair = (
+ addon_hash == EXPECTED_AMPERE_ADDON_SHA256
+ and neural_hash == EXPECTED_AMPERE_NEURAL_SHA256
+ )
+ return {
+ "known_ampere_pair": known_pair,
+ "addon": {
+ "path": str(addon.resolve()),
+ "sha256": addon_hash,
+ "expected_sha256": EXPECTED_AMPERE_ADDON_SHA256,
+ "matches_expected": addon_hash == EXPECTED_AMPERE_ADDON_SHA256,
+ "version": "4.60",
+ "release": "RenoDX DLSS5 v4.60",
+ },
+ "neural_runtime": {
+ "path": str(neural.resolve()),
+ "sha256": neural_hash,
+ "expected_sha256": EXPECTED_AMPERE_NEURAL_SHA256,
+ "matches_expected": neural_hash == EXPECTED_AMPERE_NEURAL_SHA256,
+ "version": "310.8.SF-v2",
+ "release": "DLSS NR 310.8.SF-v2",
+ },
+ }
+
+
+def validate_gpu_runtime(
+ gpu: dict[str, Any], bundle: dict[str, Any] | None = None
+) -> dict[str, Any]:
+ """Require the tested community component pair for experimental Ampere use."""
+ inspected = bundle or inspect_runtime_bundle()
+ if int(gpu.get("generation", 0)) == 30 and not inspected["known_ampere_pair"]:
+ addon_hash = inspected["addon"]["sha256"]
+ neural_hash = inspected["neural_runtime"]["sha256"]
+ raise RuntimeError(
+ f"{gpu.get('name', 'RTX 30-series GPU')} requires the tested experimental Ampere "
+ "runtime pair: RenoDX DLSS5 v4.60 plus DLSS NR 310.8.SF-v2. "
+ f"Installed hashes are add-on {addon_hash} and neural runtime {neural_hash}. "
+ "Restore the matching runtime files before rendering."
+ )
+ return inspected
+
+
+def classify_worker_failure(
+ *,
+ worker_code: int,
+ frame_index: int,
+ worker_logs: list[str],
+ reshade_lines: list[str],
+ gpu: dict[str, Any],
+ runtime_bundle: dict[str, Any],
+) -> str:
+ """Translate native/add-on failures into an actionable feature-18 diagnosis."""
+ evidence = "\n".join([*worker_logs, *reshade_lines])
+ access_violation = (
+ "evaluate raised 0xC0000005" in evidence
+ or "feature 18 evaluate raised an exception" in evidence
+ )
+ generation = int(gpu.get("generation", 0))
+ if access_violation and generation == 30:
+ summary = (
+ "DLSS 5 feature 18 hit access violation 0xC0000005 on the experimental "
+ f"RTX 30-series path before frame {frame_index} completed. Ordinary D3D12/NGX "
+ "initialization may still have succeeded; the failure is inside the patched neural "
+ "runtime/add-on evaluation."
+ )
+ if runtime_bundle.get("known_ampere_pair"):
+ summary += (
+ " The tested v4.60/SF-v2 component pair is installed. Update to the latest "
+ "NVIDIA driver; if the failure remains, this closed community runtime is "
+ "incompatible with this Ampere system and there is no truthful non-neural fallback."
+ )
+ elif access_violation:
+ summary = (
+ f"DLSS 5 feature 18 raised access violation 0xC0000005 before frame {frame_index} "
+ "completed inside the neural runtime/add-on evaluation."
+ )
+ else:
+ summary = (
+ f"Native DLSS worker exited with code {worker_code} before frame {frame_index} "
+ "completed."
+ )
+
+ addon_hash = runtime_bundle.get("addon", {}).get("sha256", "unavailable")
+ neural_hash = runtime_bundle.get("neural_runtime", {}).get("sha256", "unavailable")
+ details = [
+ summary,
+ f"GPU: {gpu.get('name', 'unknown')} | driver: {gpu.get('driver', 'unknown')}",
+ f"RenoDX add-on SHA-256: {addon_hash}",
+ f"DLSSNR runtime SHA-256: {neural_hash}",
+ ]
+ if worker_logs:
+ details.append("Worker log:\n" + "\n".join(worker_logs[-60:]))
+ if reshade_lines:
+ details.append("ReShade feature-18 log:\n" + "\n".join(reshade_lines[-60:]))
+ return "\n".join(details)
+
+
+def write_failure_report(
+ *,
+ operation: str,
+ source: str,
+ error: BaseException | str,
+ gpu: dict[str, Any] | None,
+ runtime_bundle: dict[str, Any] | None,
+ worker_code: int | None = None,
+ worker_logs: list[str] | None = None,
+ reshade_lines: list[str] | None = None,
+ logs_dir: Path | None = None,
+) -> Path:
+ """Persist diagnostics even when the incomplete media output is removed."""
+ destination = logs_dir or LOGS
+ destination.mkdir(parents=True, exist_ok=True)
+ safe_operation = re.sub(r"[^A-Za-z0-9_.-]+", "-", operation).strip("-") or "render"
+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
+ report_path = destination / f"{safe_operation}-failure-{stamp}.json"
+ report = {
+ "status": "failure",
+ "operation": operation,
+ "input": source,
+ "error": str(error),
+ "gpu": gpu,
+ "runtime_bundle": runtime_bundle,
+ "worker_exit_code": worker_code,
+ "worker_log": list(worker_logs or []),
+ "reshade_feature_18_log": list(reshade_lines or []),
+ }
+ report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
+ return report_path.resolve()
+
+
class Cancelled(RuntimeError):
pass
@@ -153,6 +330,11 @@ def detect_gpu() -> dict:
raise RuntimeError(f"{name} is outside the supported RTX 30/40/50 scope.")
return {
"name": name,
+ "display_name": (
+ f"{name} (experimental RTX 30 path; may be very slow)"
+ if generation == 30
+ else name
+ ),
"driver": driver,
"memory_mb": int(memory),
"compute_capability": capability,
@@ -167,9 +349,9 @@ def validate_runtime_files() -> None:
FFPROBE,
WORKER,
RUNTIME / "dxgi.dll",
- RUNTIME / "renodx-dlss5.addon64",
+ ADDON,
RUNTIME / "nvngx_dlss.dll",
- RUNTIME / "nvngx_dlssnr.dll",
+ NEURAL_RUNTIME,
]
missing = [str(path) for path in required if not path.exists()]
if missing:
@@ -201,6 +383,8 @@ class DLSSFrameSession:
factor: float,
mode: dict[str, str | int],
native_settings: dict[str, int | float],
+ gpu: dict[str, Any],
+ runtime_bundle: dict[str, Any],
controller: JobController,
) -> None:
self.controller = controller
@@ -209,6 +393,12 @@ class DLSSFrameSession:
self.factor = factor
self.mode = mode
self.native_settings = native_settings
+ self.gpu = gpu
+ self.runtime_bundle = runtime_bundle
+ reshade_log_path = RUNTIME / "ReShade.log"
+ self._reshade_log_baseline = (
+ reshade_log_path.read_bytes() if reshade_log_path.exists() else b""
+ )
creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
self.worker = subprocess.Popen(
[str(WORKER), "--video"],
@@ -311,6 +501,33 @@ class DLSSFrameSession:
self.abort()
raise
+ def reshade_log_text(self) -> str:
+ """Return only ReShade output created during this worker session."""
+ path = RUNTIME / "ReShade.log"
+ if not path.exists():
+ return ""
+ current = path.read_bytes()
+ if self._reshade_log_baseline and current.startswith(self._reshade_log_baseline):
+ current = current[len(self._reshade_log_baseline) :]
+ return current.decode("utf-8", errors="replace")
+
+ def reshade_diagnostics(self, limit: int = 300) -> list[str]:
+ """Return new log lines from this worker, favoring feature-18 evidence."""
+ lines = self.reshade_log_text().splitlines()
+ process_marker = f"[{self.worker.pid}]"
+ current_process = [line for line in lines if process_marker in line]
+ selected = current_process or lines
+ relevant = [
+ line
+ for line in selected
+ if "DLSS 5 Neural Rendering" in line
+ or "DLSSNR" in line
+ or "feature 18" in line
+ or "exception" in line.lower()
+ or "failed" in line.lower()
+ ]
+ return (relevant or selected)[-limit:]
+
def process(
self,
*,
@@ -333,14 +550,15 @@ class DLSSFrameSession:
except EOFError as exc:
worker_code = self.worker.wait(timeout=10)
self.worker_thread.join(timeout=2)
- details = (
- "\n".join(self.worker_logs[-60:])
- or "The worker produced no diagnostic output."
+ details = classify_worker_failure(
+ worker_code=worker_code,
+ frame_index=index,
+ worker_logs=self.worker_logs,
+ reshade_lines=self.reshade_diagnostics(),
+ gpu=self.gpu,
+ runtime_bundle=self.runtime_bundle,
)
- raise RuntimeError(
- f"Native DLSS worker exited with code {worker_code} before frame {index} "
- f"completed:\n{details}"
- ) from exc
+ raise RuntimeError(details) from exc
magic, out_index, ok, byte_count, ngx_result, out_pts = struct.unpack(
"<5Iq", result_header
)
@@ -387,13 +605,16 @@ class DLSSFrameSession:
self.closed = True
-def verify_feature_18(worker_logs: list[str]) -> dict[str, object]:
- reshade_log_path = RUNTIME / "ReShade.log"
- reshade_log = (
- reshade_log_path.read_text(encoding="utf-8", errors="replace")
- if reshade_log_path.exists()
- else ""
- )
+def verify_feature_18(
+ worker_logs: list[str], reshade_log: str | None = None
+) -> dict[str, object]:
+ if reshade_log is None:
+ reshade_log_path = RUNTIME / "ReShade.log"
+ reshade_log = (
+ reshade_log_path.read_text(encoding="utf-8", errors="replace")
+ if reshade_log_path.exists()
+ else ""
+ )
feature_created = "feature 18 created via the signed snippet" in reshade_log
feature_evaluated = "inline feature 18 evaluation succeeded" in reshade_log
runtime_initialized = "signed DLSSNR 310.8.0 D3D12 runtime initialized" in reshade_log
diff --git a/src/settings.py b/src/settings.py
index 5f0119f..7a83597 100644
--- a/src/settings.py
+++ b/src/settings.py
@@ -37,8 +37,11 @@ class UISettings:
image_format: str = "PNG"
image_quality: int = 95
nr_preset: str = "Default"
+ automatic_mask: bool = False
- def component_values(self) -> tuple[str, str, float, float, float, float, float, str, str, str]:
+ def component_values(
+ self,
+ ) -> tuple[str, str, float, float, float, float, float, bool, str, str, str]:
return (
self.nr_preset,
self.nr_style,
@@ -47,6 +50,7 @@ class UISettings:
self.local_structure_strength,
self.skin_structure_strength,
self.upscaling_factor,
+ self.automatic_mask,
self.codec,
self.container,
self.quality,
@@ -65,10 +69,13 @@ def _validate(settings: UISettings) -> UISettings:
local_tone_strength=settings.local_tone_strength,
local_structure_strength=settings.local_structure_strength,
skin_structure_strength=settings.skin_structure_strength,
+ automatic_mask=settings.automatic_mask,
upscaling_factor=settings.upscaling_factor,
)
)
resolve_upscaling_mode(settings.upscaling_factor)
+ if not isinstance(settings.automatic_mask, bool):
+ raise ValueError("Automatic Mask must be a boolean value.")
allowed = {
"Video codec": (settings.codec, CODEC_CHOICES),
"Container": (settings.container, CONTAINER_CHOICES),
@@ -117,6 +124,13 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:
value = number("image_quality", 1, 100, DEFAULT_SETTINGS.image_quality)
return int(value) if float(value).is_integer() else DEFAULT_SETTINGS.image_quality
+ def boolean(key: str, default: bool) -> bool:
+ raw_value = section.get(key)
+ if raw_value is None:
+ return default
+ parsed = configparser.ConfigParser.BOOLEAN_STATES.get(str(raw_value).casefold())
+ return parsed if parsed is not None else default
+
return UISettings(
nr_preset=choice("nr_preset", tuple(NR_PRESETS), DEFAULT_SETTINGS.nr_preset),
nr_style=choice("nr_style", tuple(NR_STYLES), DEFAULT_SETTINGS.nr_style),
@@ -130,6 +144,7 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:
skin_structure_strength=number(
"skin_structure_strength", -1.0, 2.0, DEFAULT_SETTINGS.skin_structure_strength
),
+ automatic_mask=boolean("automatic_mask", DEFAULT_SETTINGS.automatic_mask),
upscaling_factor=upscaling_factor(),
codec=choice("codec", CODEC_CHOICES, DEFAULT_SETTINGS.codec),
container=choice("container", CONTAINER_CHOICES, DEFAULT_SETTINGS.container),
@@ -153,6 +168,7 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:
"local_tone_strength": f"{settings.local_tone_strength:.2f}",
"local_structure_strength": f"{settings.local_structure_strength:.2f}",
"skin_structure_strength": f"{settings.skin_structure_strength:.2f}",
+ "automatic_mask": str(settings.automatic_mask).lower(),
"upscaling_factor": f"{settings.upscaling_factor:g}",
"codec": settings.codec,
"container": settings.container,
diff --git a/src/video.py b/src/video.py
index 3a966fe..9b39a88 100644
--- a/src/video.py
+++ b/src/video.py
@@ -27,10 +27,13 @@ from .runtime import (
DLSSFrameSession,
active_job,
detect_gpu,
+ inspect_runtime_bundle,
resize_fit,
rotate_frame,
+ validate_gpu_runtime,
validate_runtime_files,
verify_feature_18,
+ write_failure_report,
)
@@ -57,6 +60,7 @@ class ConversionOptions:
preview_seconds: float | None = None
preview_frames: int | None = None
nr_preset: str = "Default"
+ automatic_mask: bool = False
NR_PRESETS = {
@@ -179,11 +183,14 @@ def resolve_native_settings(options: ConversionOptions) -> dict[str, int | float
raise ValueError(f"{label} must be between {minimum:g} and {maximum:g}.")
validated[label] = value
+ if not isinstance(options.automatic_mask, bool):
+ raise ValueError("Automatic Mask must be a boolean value.")
+
return {
"profile": 0,
"preset": preset,
"style": style,
- "auto_mask": 0,
+ "auto_mask": int(options.automatic_mask),
"ui_correction": 0,
"intensity": validated["NR Intensity"],
"local_tone": validated["Local Tone Strength"],
@@ -353,6 +360,8 @@ def convert_video(
job_dir: Path | None = None
output: Path | None = None
session: DLSSFrameSession | None = None
+ gpu: dict | None = None
+ runtime_bundle: dict | None = None
encoder = None
nut = None
input_container = None
@@ -365,6 +374,8 @@ def convert_video(
else:
frame_count = int(metadata["frames"])
gpu = detect_gpu()
+ runtime_bundle = inspect_runtime_bundle()
+ validate_gpu_runtime(gpu, runtime_bundle)
input_width = int(metadata["width"])
input_height = int(metadata["height"])
factor, mode = resolve_upscaling_mode(options.upscaling_factor)
@@ -395,7 +406,7 @@ def convert_video(
temp_video = job_dir / "processed-video.mkv"
native = resolve_native_settings(options)
if progress:
- progress(0.01, f"Starting feature 18 on {gpu['name']}")
+ progress(0.01, f"Starting feature 18 on {gpu['display_name']}")
session = DLSSFrameSession(
input_width=input_width,
@@ -407,6 +418,8 @@ def convert_video(
factor=factor,
mode=mode,
native_settings=native,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
controller=controller,
)
render_width = session.render_width
@@ -513,7 +526,9 @@ def convert_video(
"Video encoder failed:\n" + "\n".join(encoder_logs[-40:])
)
- feature_evidence = verify_feature_18(session.worker_logs)
+ feature_evidence = verify_feature_18(
+ session.worker_logs, session.reshade_log_text()
+ )
nr_count = delivered
nr_upscaling_requested = factor > 1.0
nr_upscaling_active = bool(feature_evidence["nr_upscaling_active"])
@@ -615,7 +630,7 @@ def convert_video(
delivered,
nr_count,
elapsed,
- gpu["name"],
+ gpu["display_name"],
input_width,
input_height,
render_width,
@@ -644,7 +659,22 @@ def convert_video(
output.unlink()
if was_cancelled and not isinstance(exc, Cancelled):
raise Cancelled("Render stopped by user.") from exc
- raise
+ if isinstance(exc, Cancelled):
+ raise
+ worker_logs = session.worker_logs if session is not None else []
+ reshade_lines = session.reshade_diagnostics() if session is not None else []
+ worker_code = session.worker.poll() if session is not None else None
+ report_path = write_failure_report(
+ operation="video-render",
+ source=str(source),
+ error=exc,
+ gpu=gpu,
+ runtime_bundle=runtime_bundle,
+ worker_code=worker_code,
+ worker_logs=worker_logs,
+ reshade_lines=reshade_lines,
+ )
+ raise RuntimeError(f"{exc}\nDiagnostic report: {report_path}") from exc
finally:
if job_dir and job_dir.exists():
shutil.rmtree(job_dir, ignore_errors=True)