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

Merserkec228c3790fc
diff --git a/app.py b/app.py
index c2eb4f7..e92106f 100644
--- a/app.py
+++ b/app.py
@@ -1,71 +1,34 @@
from __future__ import annotations
-import threading
-import traceback
-import sys
-from dataclasses import replace
from pathlib import Path
-import gradio as gr
-from PIL import Image
+# Show LOADING immediately before heavy imports (gradio etc.) to avoid black screen after start.bat
+import time as _early_time
+
+try:
+ from src.core.terminal import TerminalUI as _EarlyTerminalUI
-from src.images import (
- IMAGE_FORMATS,
- RAW_EXTENSIONS,
- ImageConversionOptions,
- convert_images,
- decode_image,
- take_image_preview,
-)
-from src.naming import RENAME_MODES
-from src.ffmpeg import probe_nvenc_codecs, probe_video
-from src.frame_interpolation import (
- ENGINE_CHOICES,
- FPS_CHOICES,
- FrameInterpolationOptions,
- choose_interpolation_plan,
- interpolate_video,
- interpolate_videos,
- probe_frame_interpolation_capabilities,
-)
-from src.runtime import (
- LOGS,
- OUTPUTS,
- cancel_active_job,
- gpu_choice_label,
- validate_gpu_runtime,
-)
-from src.prepare import prepare_runtime
-from src.settings import (
- CODEC_CHOICES,
- CONTAINER_CHOICES,
- DEFAULT_SETTINGS,
- QUALITY_CHOICES,
- UISettings,
- export_settings_preset,
- import_settings_preset,
- load_settings,
- preset_filename,
- save_settings,
-)
-from src.video import (
- ConversionOptions,
- DLSS_MODEL_PRESETS,
- NR_PRESETS,
- NR_STYLES,
- UPSCALING_CHOICES,
- convert_video,
- convert_videos,
-)
+ _early_ui = _EarlyTerminalUI(Path(__file__).with_name("logs"))
+ _early_ui.enable_vt_mode()
+ _early_time.sleep(0.05)
+ _early_ui.render_loading()
+ _EARLY_TS = _early_time.time()
+except Exception:
+ _early_ui = None
+ _EARLY_TS = 0.0
+import gradio as gr
-CONFIG_PATH = Path(__file__).resolve().with_name("config.ini")
-PREVIEW_SECONDS = 3.0
-AUTOMATIC_MASK_CHOICES = ("Off", "On")
-_CONFIG_LOCK = threading.Lock()
-_CURRENT_SETTINGS: UISettings | None = None
+from src.core.paths import LOGS, OUTPUTS
+from src.core.runtime import prepare_runtime
+from src.core.terminal import init_console
+from src.frame_interpolation.ui import build_frame_interpolation_tab
+from src.image.decoder import initialize_image_runtime
+from src.image.ui import build_image_tab
+from src.settings.ui import bind_settings_events, build_settings_tab, initialize_settings
+from src.video.ui import build_video_tab
-APP_CSS = """
+APP_CSS = r"""
/* Keep the header links identical even when one URL has been visited. */
#app-title a,
#app-title a:visited,
@@ -141,923 +104,11 @@ APP_CSS = """
"""
-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 rename_suffix_update(mode: str):
- return gr.update(interactive=mode == "Custom")
-
-
-def _neural_values(
- settings: UISettings,
-) -> tuple[str, str, float, float, float, float, float, str]:
- return (
- settings.nr_preset,
- settings.nr_style,
- settings.nr_intensity,
- settings.local_tone_strength,
- settings.local_structure_strength,
- settings.skin_structure_strength,
- settings.upscaling_factor,
- _automatic_mask_choice(settings.automatic_mask),
- )
-
-
-def _shared_dlss_values(
- settings: UISettings,
-) -> tuple[str, str, float, float, float, float, float, str, str]:
- return (*_neural_values(settings), settings.dlss_model_preset)
-
-
-def persist_image_settings(
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- image_format: str,
- image_quality: float,
- rename_mode: str,
- custom_suffix: str,
-) -> tuple[str, str, float, float, float, float, float, str, str]:
- global _CURRENT_SETTINGS
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- settings = replace(
- current,
- nr_preset=nr_preset,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- local_tone_strength=local_tone_strength,
- local_structure_strength=local_structure_strength,
- skin_structure_strength=skin_structure_strength,
- upscaling_factor=upscaling_factor,
- automatic_mask=_parse_automatic_mask(automatic_mask),
- dlss_model_preset=dlss_model_preset,
- image_format=image_format,
- image_quality=int(image_quality),
- image_rename_mode=rename_mode,
- image_custom_suffix=custom_suffix,
- )
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- _CURRENT_SETTINGS = settings
- return _shared_dlss_values(settings)
-
-
-def persist_video_settings(
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- rename_mode: str,
- custom_suffix: str,
-) -> tuple[str, str, float, float, float, float, float, str, str]:
- global _CURRENT_SETTINGS
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- settings = replace(
- current,
- nr_preset=nr_preset,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- local_tone_strength=local_tone_strength,
- local_structure_strength=local_structure_strength,
- skin_structure_strength=skin_structure_strength,
- upscaling_factor=upscaling_factor,
- automatic_mask=_parse_automatic_mask(automatic_mask),
- dlss_model_preset=dlss_model_preset,
- codec=codec,
- container=container,
- quality=quality,
- video_rename_mode=rename_mode,
- video_custom_suffix=custom_suffix,
- )
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- _CURRENT_SETTINGS = settings
- return _shared_dlss_values(settings)
-
-
-def persist_frame_interpolation_settings(
- target_fps: str,
- engine: str,
- codec: str,
- container: str,
- quality: str,
- rename_mode: str,
- custom_suffix: str,
-) -> None:
- global _CURRENT_SETTINGS
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- settings = replace(
- current,
- frame_interpolation_target_fps=target_fps,
- frame_interpolation_engine=engine,
- frame_interpolation_codec=codec,
- frame_interpolation_container=container,
- frame_interpolation_quality=quality,
- frame_interpolation_rename_mode=rename_mode,
- frame_interpolation_custom_suffix=custom_suffix,
- )
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- _CURRENT_SETTINGS = settings
-
-
-def _settings_component_values(settings: UISettings) -> tuple:
- shared = _shared_dlss_values(settings)
- return (
- *shared,
- *shared,
- settings.image_format,
- settings.image_quality,
- settings.image_rename_mode,
- gr.update(
- value=settings.image_custom_suffix,
- interactive=settings.image_rename_mode == "Custom",
- ),
- settings.codec,
- settings.container,
- settings.quality,
- settings.video_rename_mode,
- gr.update(
- value=settings.video_custom_suffix,
- interactive=settings.video_rename_mode == "Custom",
- ),
- settings.frame_interpolation_target_fps,
- settings.frame_interpolation_engine,
- settings.frame_interpolation_codec,
- settings.frame_interpolation_container,
- settings.frame_interpolation_quality,
- settings.frame_interpolation_rename_mode,
- gr.update(
- value=settings.frame_interpolation_custom_suffix,
- interactive=settings.frame_interpolation_rename_mode == "Custom",
- ),
- settings.ai_gpu_uuid,
- settings.video_gpu_uuid,
- )
-
-
-def _processing_gpu_settings() -> tuple[str, str]:
- with _CONFIG_LOCK:
- settings = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- return settings.ai_gpu_uuid, settings.video_gpu_uuid
-
-
-def _gpu_choices(prepared) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:
- automatic = [("Automatic (first compatible)", "auto")]
- ai = []
- for gpu in prepared.gpus:
- if not gpu.get("ai_compatible") or not gpu.get("adapter_luid"):
- continue
- try:
- validate_gpu_runtime(gpu, prepared.runtime_bundle)
- except RuntimeError:
- continue
- ai.append((gpu_choice_label(gpu), str(gpu["uuid"])))
- video = [
- (gpu_choice_label(gpu), str(gpu["uuid"]))
- for gpu in prepared.gpus
- if gpu.get("cuda_ordinal") is not None
- and probe_nvenc_codecs(int(gpu["cuda_ordinal"]))
- ]
- return automatic + ai, automatic + video
-
-
-def _normalize_gpu_settings(settings: UISettings, prepared) -> tuple[UISettings, str]:
- ai_choices, video_choices = _gpu_choices(prepared)
- ai_values = {value for _label, value in ai_choices}
- video_values = {value for _label, value in video_choices}
- warnings = []
- ai_uuid = settings.ai_gpu_uuid
- video_uuid = settings.video_gpu_uuid
- if ai_uuid not in ai_values:
- warnings.append("Saved AI Processing GPU is unavailable; using Automatic.")
- ai_uuid = "auto"
- if video_uuid not in video_values:
- warnings.append("Saved Video Processing GPU is unavailable; using Automatic.")
- video_uuid = "auto"
- return replace(settings, ai_gpu_uuid=ai_uuid, video_gpu_uuid=video_uuid), " ".join(warnings)
-
-
-def persist_gpu_settings(ai_gpu_uuid: str, video_gpu_uuid: str) -> str:
- global _CURRENT_SETTINGS
- prepared = prepare_runtime()
- ai_choices, video_choices = _gpu_choices(prepared)
- if ai_gpu_uuid not in {value for _label, value in ai_choices}:
- raise gr.Error("Choose an available AI Processing GPU.")
- if video_gpu_uuid not in {value for _label, value in video_choices}:
- raise gr.Error("Choose an available Video Processing GPU.")
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- settings = replace(
- current, ai_gpu_uuid=ai_gpu_uuid, video_gpu_uuid=video_gpu_uuid
- )
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- _CURRENT_SETTINGS = settings
- ai_name = "Automatic" if ai_gpu_uuid == "auto" else next(
- label for label, value in ai_choices if value == ai_gpu_uuid
- )
- video_name = "Automatic" if video_gpu_uuid == "auto" else next(
- label for label, value in video_choices if value == video_gpu_uuid
- )
- return f"AI Processing: {ai_name}\n\nVideo Processing: {video_name}"
-
-
-def reset_saved_settings() -> tuple:
- global _CURRENT_SETTINGS
- with _CONFIG_LOCK:
- save_settings(CONFIG_PATH, DEFAULT_SETTINGS)
- _CURRENT_SETTINGS = DEFAULT_SETTINGS
- message = "All Image, Video, and Frame Interpolation settings were reset to defaults."
- return (
- *_settings_component_values(DEFAULT_SETTINGS),
- message,
- message,
- message,
- "AI Processing and Video Processing GPU selections were reset to Automatic.",
- )
-
-
-def settings_preset_download(name: str) -> str | None:
- if not isinstance(name, str) or not name.strip():
- return None
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- try:
- path = export_settings_preset(name, current)
- except ValueError:
- return None
- return str(path)
-
-
-def settings_preset_export_status(name: str) -> str:
- try:
- filename = preset_filename(name)
- except ValueError as exc:
- return f"Export failed: {exc}"
- return f"Exported preset {name.strip()!r} as {filename}."
-
-
-def apply_settings_preset(
- uploaded_path: str | None, current_name: str
-) -> tuple:
- global _CURRENT_SETTINGS
- with _CONFIG_LOCK:
- current = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- try:
- if not uploaded_path:
- raise ValueError("Choose a JSON preset file before importing.")
- name, imported = import_settings_preset(uploaded_path, current)
- imported, gpu_warning = _normalize_gpu_settings(
- imported, prepare_runtime()
- )
- save_settings(CONFIG_PATH, imported)
- except (OSError, ValueError) as exc:
- return (
- current_name,
- *_settings_component_values(current),
- f"Import failed: {exc}",
- )
- _CURRENT_SETTINGS = imported
- return (
- name,
- *_settings_component_values(imported),
- f"Imported preset {name!r}; all tabs and saved startup settings were updated."
- + (f" {gpu_warning}" if gpu_warning else ""),
- )
-
-
-def _process_video(
- input_path: str | None,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- progress,
- preview_seconds: float | None,
- preview_frames: int | None,
-) -> tuple[str | None, str]:
- if not input_path:
- raise gr.Error("Choose a video first.")
- is_preview = preview_seconds is not None or preview_frames is not None
- ai_gpu_uuid, video_gpu_uuid = _processing_gpu_settings()
- options = ConversionOptions(
- ai_gpu_uuid=ai_gpu_uuid,
- video_gpu_uuid=video_gpu_uuid,
- nr_preset=nr_preset,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- 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),
- dlss_model_preset=dlss_model_preset,
- upscaling_factor=upscaling_factor,
- codec="H.264" if is_preview else codec,
- container="MP4" if is_preview else container,
- quality=quality,
- preview_seconds=preview_seconds,
- preview_frames=preview_frames,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = convert_video(input_path, options, progress=report)
- except Exception as exc:
- traceback.print_exc()
- raise gr.Error(str(exc)) from exc
- output_preview = result.output_path if options.container == "MP4" else None
- source_name = Path(input_path).name
- if preview_frames is not None:
- return output_preview, (
- f"One-frame preview complete for {source_name} on {result.gpu} "
- f"in {result.elapsed_seconds:.1f}s. "
- f"DLSS {result.dlss_mode}: {result.render_width}×{result.render_height} → "
- f"{result.output_width}×{result.output_height}. Signed feature 18 confirmed."
- )
- if is_preview:
- return output_preview, (
- f"Preview complete for {source_name}: {result.frames} frames from the first "
- f"{PREVIEW_SECONDS:g} seconds processed "
- f"on {result.gpu} in {result.elapsed_seconds:.1f}s. DLSS {result.dlss_mode}: "
- f"{result.render_width}×{result.render_height} → {result.output_width}×{result.output_height}. "
- "All frames returned success with signed feature 18 confirmed."
- )
- status = (
- f"Complete: {result.frames} frames processed on {result.gpu} in {result.elapsed_seconds:.1f}s. "
- f"All {result.nr_count_evidence} frames returned success with signed feature 18 confirmed. "
- f"DLSS {result.dlss_mode}: {result.render_width}×{result.render_height} → "
- f"{result.output_width}×{result.output_height}."
- )
- if container != "MP4":
- status += f" {container} output was created successfully, but browser preview is unavailable."
- return output_preview, status
-
-
-def render_video(
- input_path: str,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- progress=gr.Progress(track_tqdm=False),
-):
- return _process_video(
- input_path, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
- codec, container, quality,
- progress, None, None
- )
-
-
-def _normalize_video_paths(paths: list[str] | str | None) -> list[str]:
- if not paths:
- return []
- return [paths] if isinstance(paths, str) else list(paths)
-
-
-def first_video_path(paths: list[str] | str | None) -> str | None:
- normalized = _normalize_video_paths(paths)
- return normalized[0] if normalized else None
-
-
-def update_video_preview_mode(paths: list[str] | str | None):
- normalized = _normalize_video_paths(paths)
- single = len(normalized) == 1
- input_value = normalized[0] if single else None
- return (
- gr.update(value=input_value, visible=single),
- gr.update(value=None, visible=single),
- gr.update(visible=single),
- gr.update(visible=single),
- )
-
-
-def frame_interpolation_capability_text() -> str:
- ai_gpu_uuid, _video_gpu_uuid = _processing_gpu_settings()
- capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
- hags = "Enabled" if capabilities.hags_enabled else "Disabled"
- native = (
- f"{capabilities.native_multiplier}× "
- f"({capabilities.native_generated_frame_max} generated frame per evaluation)"
- )
- cascade = "Available" if capabilities.cascade_available else "Unavailable"
- state = "Ready" if capabilities.available else "Unavailable"
- detail = f"\n{capabilities.detail}" if capabilities.detail else ""
- return (
- f"{state} — GPU: {capabilities.gpu} | Driver: {capabilities.driver} | "
- f"HAGS: {hags}\nNative maximum: {native} | Experimental cascade: {cascade} | "
- f"DLSSG runtime: {capabilities.runtime_version}{detail}"
- )
-
-
-def describe_frame_interpolation_plan(
- paths: list[str] | str | None,
- target_fps: str,
- engine: str,
-) -> str:
- selected = first_video_path(paths)
- if not selected:
- return "Choose a video to preflight its DLSSG path and temporal precision."
- try:
- metadata = probe_video(selected, count_mode="metadata")
- ai_gpu_uuid, _video_gpu_uuid = _processing_gpu_settings()
- capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
- plan = choose_interpolation_plan(
- metadata["rate"],
- FrameInterpolationOptions(target_fps=target_fps).target_rate,
- engine,
- capabilities.native_multiplier,
- cfr=bool(metadata.get("cfr", True)),
- )
- if plan.cascade_stages:
- precision = (
- f"≤ {float(plan.maximum_temporal_error) * 1000:.3f} ms "
- f"(1/{2 * plan.grid_multiplier} source-frame interval)"
- )
- elif plan.path == "Native DLSSG":
- precision = "Exact native temporal grid"
- else:
- precision = "Nearest real source frame"
- return (
- f"{Path(selected).name}: {metadata['rate']} FPS → {target_fps} FPS | "
- f"Path: {plan.path} | Cascade stages: {plan.cascade_stages} | "
- f"Internal grid: {plan.grid_multiplier}× | Precision: {precision}"
- )
- except Exception as exc:
- return f"Preflight: {exc}"
-
-
-def update_frame_interpolation_preview_mode(
- paths: list[str] | str | None,
- target_fps: str,
- engine: str,
-):
- normalized = _normalize_video_paths(paths)
- single = len(normalized) == 1
- return (
- gr.update(value=normalized[0] if single else None, visible=single),
- gr.update(value=None, visible=single),
- gr.update(visible=single),
- describe_frame_interpolation_plan(paths, target_fps, engine),
- )
-
-
-def render_frame_interpolation_batch(
- input_paths: list[str] | str | None,
- target_fps: str,
- engine: str,
- codec: str,
- container: str,
- quality: str,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
-):
- paths = _normalize_video_paths(input_paths)
- if not paths:
- raise gr.Error("Choose at least one video first.")
- options = FrameInterpolationOptions(
- ai_gpu_uuid=_processing_gpu_settings()[0],
- video_gpu_uuid=_processing_gpu_settings()[1],
- target_fps=target_fps,
- engine=engine,
- codec=codec,
- container=container,
- quality=quality,
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = interpolate_videos(paths, options, report)
- except Exception as exc:
- traceback.print_exc()
- raise gr.Error(str(exc)) from exc
- ordered: list[tuple[int, list[str]]] = []
- for item in result.successes:
- value = item.result
- details = (
- f"{value.output_frames} frames; {value.selected_path}; "
- f"native {value.native_multiplier}×; cascade stages {value.cascade_stages}; "
- f"copied {value.copied_frames}, DLSSG {value.generated_frames}, "
- f"cuts {value.scene_cuts}; report: {value.report_path}"
- )
- ordered.append(
- (item.index, [Path(item.input_path).name, "Complete", Path(value.output_path).name, details])
- )
- for item in result.failures:
- state = "Skipped" if item.error == "Cancelled before rendering." else (
- "Cancelled" if item.cancelled else "Failed"
- )
- ordered.append((item.index, [Path(item.input_path).name, state, "", item.error]))
- rows = [row for _index, row in sorted(ordered, key=lambda entry: entry[0])]
- files = [item.result.output_path for item in result.successes]
- preview = None
- if len(paths) == 1 and result.successes and Path(files[0]).suffix.lower() == ".mp4":
- preview = files[0]
- status = (
- f"{'Cancelled' if result.cancelled else 'Complete'}: "
- f"{len(result.successes)} completed, {len(result.failures)} failed/cancelled. "
- f"Batch manifest: {result.manifest_path}"
- )
- return gr.update(value=preview, visible=len(paths) == 1), files, rows, status
-
-
-def preview_frame_interpolation(
- input_paths: list[str] | str | None,
- target_fps: str,
- engine: str,
- codec: str,
- container: str,
- quality: str,
- progress=gr.Progress(track_tqdm=False),
-):
- selected = first_video_path(input_paths)
- if not selected:
- raise gr.Error("Choose one video first.")
- options = FrameInterpolationOptions(
- ai_gpu_uuid=_processing_gpu_settings()[0],
- video_gpu_uuid=_processing_gpu_settings()[1],
- target_fps=target_fps,
- engine=engine,
- codec="H.264",
- container="MP4",
- quality=quality,
- preview_seconds=PREVIEW_SECONDS,
- )
- try:
- result = interpolate_video(
- selected,
- options,
- lambda value, message: progress(value, desc=message),
- )
- except Exception as exc:
- traceback.print_exc()
- raise gr.Error(str(exc)) from exc
- return result.output_path, (
- f"Preview complete: {result.output_frames} frames, {result.selected_path}, "
- f"{result.cascade_stages} cascade stage(s), {result.generated_frames} DLSSG-selected "
- f"frames in {result.elapsed_seconds:.1f}s. Report: {result.report_path}"
- )
-
-
-def render_video_batch(
- input_paths: list[str] | str | None,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
-) -> tuple[object, list[str], list[list[str]], str]:
- paths = _normalize_video_paths(input_paths)
- if not paths:
- raise gr.Error("Choose at least one video first.")
- options = ConversionOptions(
- ai_gpu_uuid=_processing_gpu_settings()[0],
- video_gpu_uuid=_processing_gpu_settings()[1],
- nr_preset=nr_preset,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- 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),
- dlss_model_preset=dlss_model_preset,
- upscaling_factor=upscaling_factor,
- codec=codec,
- container=container,
- quality=quality,
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = convert_videos(paths, options, progress=report)
- except Exception as exc:
- traceback.print_exc()
- raise gr.Error(str(exc)) from exc
-
- ordered_rows: list[tuple[int, list[str]]] = []
- for item in result.successes:
- conversion = item.result
- details = (
- f"{conversion.frames} frames in {conversion.elapsed_seconds:.1f}s; "
- f"DLSS {conversion.dlss_mode}: "
- f"{conversion.render_width}×{conversion.render_height} → "
- f"{conversion.output_width}×{conversion.output_height}; "
- f"report: {conversion.report_path}"
- )
- ordered_rows.append(
- (
- item.index,
- [
- Path(item.input_path).name,
- "Complete",
- Path(conversion.output_path).name,
- details,
- ],
- )
- )
- for item in result.failures:
- state = "Skipped" if item.error == "Cancelled before rendering." else (
- "Cancelled" if item.cancelled else "Failed"
- )
- ordered_rows.append(
- (item.index, [Path(item.input_path).name, state, "", item.error])
- )
- rows = [row for _index, row in sorted(ordered_rows, key=lambda entry: entry[0])]
- files = [item.result.output_path for item in result.successes]
- output_preview = None
- if len(paths) == 1 and result.successes:
- candidate = result.successes[0].result.output_path
- if Path(candidate).suffix.lower() == ".mp4":
- output_preview = candidate
- failed_count = sum(not item.cancelled for item in result.failures)
- cancelled_count = sum(
- item.cancelled and item.error != "Cancelled before rendering."
- for item in result.failures
- )
- skipped_count = sum(
- item.error == "Cancelled before rendering." for item in result.failures
- )
- state = "Cancelled" if result.cancelled else "Complete"
- status = (
- f"{state}: {len(result.successes)} completed, {failed_count} failed, "
- f"{cancelled_count} cancelled, {skipped_count} skipped. "
- f"Batch manifest: {result.manifest_path}"
- )
- return gr.update(value=output_preview, visible=len(paths) == 1), files, rows, status
-
-
-def preview_video(
- input_path: list[str] | str | None,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- progress=gr.Progress(track_tqdm=False),
-):
- selected = first_video_path(input_path)
- return _process_video(
- selected, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
- codec, container, quality,
- progress, PREVIEW_SECONDS, None
- )
-
-
-def preview_one_frame(
- input_path: list[str] | str | None,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- codec: str,
- container: str,
- quality: str,
- progress=gr.Progress(track_tqdm=False),
-):
- selected = first_video_path(input_path)
- return _process_video(
- selected, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
- codec, container, quality,
- progress, None, 1
- )
-
-
-def preview_input_images(paths: list[str] | str | None):
- if not paths:
- return []
- if isinstance(paths, str):
- paths = [paths]
- previews = []
- for raw_path in paths:
- try:
- decoded = decode_image(raw_path)
- image = Image.fromarray(decoded.rgba, mode="RGBA")
- image.thumbnail((1200, 900), Image.Resampling.LANCZOS)
- previews.append((image, Path(raw_path).name))
- except Exception:
- continue
- return previews
-
-
-def render_image_batch(
- input_paths: list[str] | str | None,
- nr_preset: str,
- nr_style: str,
- nr_intensity: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- dlss_model_preset: str,
- image_format: str,
- image_quality: float,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
-):
- if not input_paths:
- raise gr.Error("Choose at least one image first.")
- if isinstance(input_paths, str):
- input_paths = [input_paths]
- options = ImageConversionOptions(
- ai_gpu_uuid=_processing_gpu_settings()[0],
- nr_preset=nr_preset,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- 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),
- dlss_model_preset=dlss_model_preset,
- upscaling_factor=upscaling_factor,
- output_format=image_format,
- quality=int(image_quality),
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = convert_images(input_paths, options, progress=report)
- except Exception as exc:
- traceback.print_exc()
- raise gr.Error(str(exc)) from exc
-
- gallery = []
- for item in result.successes:
- preview = take_image_preview(item.output_path)
- if preview is None:
- with Image.open(item.output_path) as output:
- preview = output.convert("RGBA")
- preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)
- preview = preview.copy()
- gallery.append((preview, Path(item.output_path).name))
- files = [item.output_path for item in result.successes]
- rows = [
- [Path(item.input_path).name, "Complete", Path(item.output_path).name, "; ".join(item.warnings)]
- for item in result.successes
- ]
- rows.extend(
- [Path(item.input_path).name, "Failed", "", item.error] for item in result.failures
- )
- state = "Cancelled" if result.cancelled else "Complete"
- status = (
- f"{state}: {len(result.successes)} image(s) rendered, {len(result.failures)} failed. "
- "Every successful output returned feature-18 success and has a diagnostic report."
- )
- return gallery, files, result.zip_path, rows, status
-
-
-def build_neural_controls(settings: UISettings):
- nr_preset = gr.Dropdown(
- list(NR_PRESETS), value=settings.nr_preset, label="NR Preset",
- info="Experimental content-dependent neural-rendering model hint. Default is recommended."
- )
- nr_style = gr.Radio(
- list(NR_STYLES), value=settings.nr_style, label="NR Style",
- info="Selects the native neural-rendering style."
- )
- upscaling_factor = gr.Dropdown(
- choices=list(UPSCALING_CHOICES), value=settings.upscaling_factor,
- label="Upscaling factor", info="Uses NVIDIA's fixed DLSS modes. DLAA keeps source resolution."
- )
- with gr.Row():
- nr_intensity = gr.Slider(
- 0.0, 2.0, value=settings.nr_intensity, step=0.05, precision=2,
- label="NR Intensity", info="Overall neural-rendering strength.", buttons=["reset"]
- )
- local_tone_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_tone_strength, step=0.05, precision=2,
- label="Local Tone Strength", info="Local tone and contrast enhancement.", buttons=["reset"]
- )
- with gr.Row():
- local_structure_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_structure_strength, step=0.05, precision=2,
- label="Local Structure Strength", info="Local detail and texture structure.", buttons=["reset"]
- )
- skin_structure_strength = gr.Slider(
- -1.0, 2.0, value=settings.skin_structure_strength, step=0.05, precision=2,
- 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, automatic_mask
- ]
-
-
-def build_dlss_model_control(settings: UISettings):
- return gr.Dropdown(
- choices=list(DLSS_MODEL_PRESETS),
- value=settings.dlss_model_preset,
- label="DLSS Model Preset",
- info=(
- "Default lets NVIDIA select its normal mode-specific presets. "
- "J, K, L, or M forces that model preset for every DLSS scaling mode."
- ),
- )
-
-
def build_app() -> gr.Blocks:
- """Build the UI from the cached settings without rewriting configuration."""
- global _CURRENT_SETTINGS
+ """Build the UI from cached settings and feature-owned tab modules."""
prepared = prepare_runtime()
- settings = _CURRENT_SETTINGS or load_settings(CONFIG_PATH)
- settings, gpu_warning = _normalize_gpu_settings(settings, prepared)
- if settings != (_CURRENT_SETTINGS or load_settings(CONFIG_PATH)):
- save_settings(CONFIG_PATH, settings)
- _CURRENT_SETTINGS = settings
- ai_gpu_choices, video_gpu_choices = _gpu_choices(prepared)
- upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]
+ initialize_image_runtime()
+ settings, _gpu_warning, ai_gpu_choices, video_gpu_choices = initialize_settings(prepared)
with gr.Blocks(title="DLSS 5 Visual Enhancer") as demo:
gr.Markdown(
@@ -1068,709 +119,68 @@ def build_app() -> gr.Blocks:
)
with gr.Tabs(selected="image"):
with gr.Tab("Image", id="image"):
- with gr.Row():
- with gr.Column(scale=3):
- image_sources = gr.File(
- label="Input image(s)",
- file_count="multiple",
- file_types=upload_types,
- type="filepath",
- allow_reordering=True,
- elem_id="image-upload-list",
- )
- image_input_gallery = gr.Gallery(
- label="Input preview",
- columns=3,
- height=320,
- object_fit="contain",
- interactive=False,
- buttons=["fullscreen"],
- elem_id="image-input-preview",
- )
- with gr.Accordion(
- "DLSS 5 Neural Rendering Settings", open=True
- ):
- image_neural = build_neural_controls(settings)
- with gr.Accordion("DLSS 5 Settings", open=True):
- image_model_preset = build_dlss_model_control(settings)
- with gr.Row():
- image_format = gr.Dropdown(
- list(IMAGE_FORMATS),
- value=settings.image_format,
- label="Output format",
- info=(
- "PNG and TIFF are lossless; JPEG composites transparency "
- "over white."
- ),
- )
- image_quality = gr.Slider(
- 1,
- 100,
- value=settings.image_quality,
- step=1,
- precision=0,
- label="Lossy quality",
- info=(
- "Used by JPEG, WebP, and AVIF; ignored by PNG/TIFF."
- ),
- )
- with gr.Row():
- image_rename_mode = gr.Radio(
- RENAME_MODES,
- value=settings.image_rename_mode,
- label="Rename",
- info=(
- "Auto adds the current DLSS5 timestamp; Copy keeps the "
- "original base name; Custom appends your suffix."
- ),
- )
- image_custom_suffix = gr.Textbox(
- value=settings.image_custom_suffix,
- label="Custom suffix",
- placeholder="_DLSS5",
- interactive=settings.image_rename_mode == "Custom",
- )
- gr.Markdown(
- "Images are processed as 8-bit SDR sRGB. Animated and multipage "
- "files use their first frame/page."
- )
- with gr.Row():
- image_render = gr.Button("Render image(s)", variant="primary")
- image_stop = gr.Button("Stop", variant="stop")
- image_reset = gr.Button("Reset settings")
- image_status = gr.Textbox(label="Status", interactive=False)
- with gr.Column(scale=3):
- image_output_gallery = gr.Gallery(
- label="Enhanced previews",
- columns=2,
- height=520,
- 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"
- )
- image_results = gr.Dataframe(
- headers=["Input", "Result", "Output", "Details"],
- datatype=["str", "str", "str", "str"],
- interactive=False,
- label="Batch results",
- wrap=True,
- )
-
+ image_tab = build_image_tab(settings)
with gr.Tab("Video", id="video"):
- with gr.Row():
- with gr.Column(scale=3):
- video_sources = gr.File(
- label="Input video(s)",
- file_count="multiple",
- file_types=["video"],
- type="filepath",
- allow_reordering=True,
- elem_id="video-upload-list",
- )
- video_input_preview = gr.Video(
- label="Input video preview",
- interactive=False,
- visible=False,
- )
- with gr.Accordion(
- "DLSS 5 Neural Rendering Settings", open=True
- ):
- video_neural = build_neural_controls(settings)
- with gr.Accordion("DLSS 5 Settings", open=True):
- video_model_preset = build_dlss_model_control(settings)
- video_quality = gr.Radio(
- QUALITY_CHOICES,
- value=settings.quality,
- label="Encoding quality",
- info=(
- "Auto uses output resolution, FPS, and codec. Good = Auto×2, "
- "Best = Auto×4, Max = CQ 0."
- ),
- )
- with gr.Row():
- video_codec = gr.Dropdown(
- CODEC_CHOICES,
- value=settings.codec,
- label="Video codec",
- info=(
- "ProRes Proxy uses 10-bit 4:2:2 and requires MOV or MKV."
- ),
- )
- video_container = gr.Dropdown(
- CONTAINER_CHOICES,
- value=settings.container,
- label="Container",
- )
- with gr.Row():
- video_rename_mode = gr.Radio(
- RENAME_MODES,
- value=settings.video_rename_mode,
- label="Rename",
- info=(
- "Auto adds the current DLSS5 timestamp; Copy keeps the "
- "original base name; Custom appends your suffix."
- ),
- )
- video_custom_suffix = gr.Textbox(
- value=settings.video_custom_suffix,
- label="Custom suffix",
- placeholder="_DLSS5",
- interactive=settings.video_rename_mode == "Custom",
- )
- gr.Checkbox(
- value=False,
- interactive=False,
- label=(
- "Preserve HDR (disabled: verified feature-18 path is RGBA8; "
- "HDR safely outputs as SDR)"
- ),
- )
- with gr.Row():
- video_preview_frame = gr.Button(
- "Preview 1 frame", visible=False
- )
- video_preview = gr.Button("Preview 3 sec", visible=False)
- video_render = gr.Button("Render video(s)", variant="primary")
- video_stop = gr.Button("Stop", variant="stop")
- video_reset = gr.Button("Reset settings")
- video_status = gr.Textbox(label="Status", interactive=False)
- with gr.Column(scale=3):
- output_video = gr.Video(
- label="Output video",
- interactive=False,
- visible=False,
- )
- video_output_files = gr.File(
- label="Rendered video files",
- file_count="multiple",
- interactive=False,
- elem_id="video-output-list",
- )
- video_results = gr.Dataframe(
- headers=["Input", "Result", "Output", "Details"],
- datatype=["str", "str", "str", "str"],
- interactive=False,
- label="Batch results",
- wrap=True,
- )
-
+ video_tab = build_video_tab(settings)
with gr.Tab("Frame Interpolation", id="frame-interpolation"):
- with gr.Row():
- with gr.Column(scale=3):
- frame_interpolation_sources = gr.File(
- label="Input video(s)",
- file_count="multiple",
- file_types=["video"],
- type="filepath",
- allow_reordering=True,
- elem_id="frame-interpolation-upload-list",
- )
- frame_interpolation_input_preview = gr.Video(
- label="Input video preview",
- interactive=False,
- visible=False,
- )
- with gr.Accordion("DLSS Frame Generation Settings", open=True):
- with gr.Row():
- frame_interpolation_target_fps = gr.Dropdown(
- FPS_CHOICES,
- value=settings.frame_interpolation_target_fps,
- label="Output FPS",
- info="Fractional choices use exact 1001-based rates.",
- )
- frame_interpolation_engine = gr.Radio(
- ENGINE_CHOICES,
- value=settings.frame_interpolation_engine,
- label="DLSS engine",
- info=(
- "Auto uses a supported exact native grid, then the "
- "2× cascade when required."
- ),
- )
- frame_interpolation_capabilities = gr.Textbox(
- value=frame_interpolation_capability_text(),
- label="GPU / HAGS / driver / DLSSG capability",
- interactive=False,
- lines=3,
- )
- frame_interpolation_plan = gr.Textbox(
- value=(
- "Choose a video to preflight its DLSSG path and temporal "
- "precision."
- ),
- label="Per-file interpolation plan",
- interactive=False,
- lines=2,
- )
- frame_interpolation_quality = gr.Radio(
- QUALITY_CHOICES,
- value=settings.frame_interpolation_quality,
- label="Encoding quality",
- info="Auto uses output resolution, selected FPS, and codec.",
- )
- with gr.Row():
- frame_interpolation_codec = gr.Dropdown(
- CODEC_CHOICES,
- value=settings.frame_interpolation_codec,
- label="Video codec",
- )
- frame_interpolation_container = gr.Dropdown(
- CONTAINER_CHOICES,
- value=settings.frame_interpolation_container,
- label="Container",
- )
- with gr.Row():
- frame_interpolation_rename_mode = gr.Radio(
- RENAME_MODES,
- value=settings.frame_interpolation_rename_mode,
- label="Rename",
- info=(
- "Auto adds a DLSSFG timestamp; Copy keeps the original base "
- "name; Custom appends your suffix."
- ),
- )
- frame_interpolation_custom_suffix = gr.Textbox(
- value=settings.frame_interpolation_custom_suffix,
- label="Custom suffix",
- placeholder="_DLSSFG",
- interactive=(
- settings.frame_interpolation_rename_mode == "Custom"
- ),
- )
- gr.Markdown(
- "Pure NVIDIA DLSSG: CPU optical flow supplies guide vectors only; "
- "every invented image is returned by signed DLSSG 310.7. HDR "
- "PQ/HLG input is rejected in v1. Maximum output/source rate is 6×."
- )
- with gr.Row():
- frame_interpolation_preview = gr.Button(
- "Preview 3 sec", visible=False
- )
- frame_interpolation_render = gr.Button(
- "Interpolate video(s)", variant="primary"
- )
- frame_interpolation_stop = gr.Button("Stop", variant="stop")
- frame_interpolation_reset = gr.Button("Reset settings")
- frame_interpolation_status = gr.Textbox(
- label="Status", interactive=False
- )
- with gr.Column(scale=3):
- frame_interpolation_output_video = gr.Video(
- label="Interpolated output",
- interactive=False,
- visible=False,
- )
- frame_interpolation_output_files = gr.File(
- label="Interpolated video files",
- file_count="multiple",
- interactive=False,
- elem_id="frame-interpolation-output-list",
- )
- frame_interpolation_results = gr.Dataframe(
- headers=["Input", "Result", "Output", "Details"],
- datatype=["str", "str", "str", "str"],
- interactive=False,
- label="Batch results",
- wrap=True,
- )
-
+ frame_tab = build_frame_interpolation_tab(settings)
with gr.Tab("Settings", id="settings"):
- gr.Markdown(
- "## GPU Selection\n"
- "AI Processing controls DLSS and Frame Generation. Video Processing "
- "controls FFmpeg NVENC only; ProRes and mux-only work remain CPU-based."
- )
- with gr.Row():
- ai_gpu_selector = gr.Dropdown(
- choices=ai_gpu_choices,
- value=settings.ai_gpu_uuid,
- label="AI Processing GPU",
- info="Used for every DLSS Neural Rendering and Frame Generation operation.",
- )
- video_gpu_selector = gr.Dropdown(
- choices=video_gpu_choices,
- value=settings.video_gpu_uuid,
- label="Video Processing GPU",
- info="Used for FFmpeg H.264, HEVC, and AV1 NVENC encoding only.",
- )
- gpu_status = gr.Markdown(
- gpu_warning or "GPU selections are ready.",
- elem_id="gpu-selection-status",
- )
- gr.Markdown(
- "## Settings Presets\n"
- "Export every adjustable option from the Image, Video, and Frame "
- "Interpolation tabs, or import a preset to apply it everywhere."
- )
- with gr.Row():
- preset_name = gr.Textbox(
- label="Preset name",
- placeholder="Cinematic 2",
- info="The exported file uses this name; the original name is stored in JSON.",
- scale=3,
- )
- preset_export = gr.DownloadButton(
- "Export preset",
- value=settings_preset_download,
- inputs=preset_name,
- variant="primary",
- scale=1,
- )
- preset_import = gr.UploadButton(
- "Import preset",
- file_count="single",
- file_types=[".json"],
- type="filepath",
- variant="primary",
- scale=1,
- )
- preset_status = gr.Markdown(
- "",
- elem_id="preset-status",
- )
-
- image_inputs = [
- image_sources,
- *image_neural,
- image_model_preset,
- image_format,
- image_quality,
- image_rename_mode,
- image_custom_suffix,
- ]
- video_inputs = [
- video_sources,
- *video_neural,
- video_model_preset,
- video_codec,
- video_container,
- video_quality,
- video_rename_mode,
- video_custom_suffix,
- ]
- video_preview_inputs = [
- video_sources,
- *video_neural,
- video_model_preset,
- video_codec,
- video_container,
- video_quality,
- ]
- image_settings_inputs = [
- *image_neural,
- image_model_preset,
- image_format,
- image_quality,
- image_rename_mode,
- image_custom_suffix,
- ]
- video_settings_inputs = [
- *video_neural,
- video_model_preset,
- video_codec,
- video_container,
- video_quality,
- video_rename_mode,
- video_custom_suffix,
- ]
- frame_interpolation_inputs = [
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- frame_interpolation_codec,
- frame_interpolation_container,
- frame_interpolation_quality,
- frame_interpolation_rename_mode,
- frame_interpolation_custom_suffix,
- ]
- frame_interpolation_preview_inputs = [
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- frame_interpolation_codec,
- frame_interpolation_container,
- frame_interpolation_quality,
- ]
- frame_interpolation_settings_inputs = [
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- frame_interpolation_codec,
- frame_interpolation_container,
- frame_interpolation_quality,
- frame_interpolation_rename_mode,
- frame_interpolation_custom_suffix,
- ]
- settings_component_outputs = [
- *image_neural,
- image_model_preset,
- *video_neural,
- video_model_preset,
- image_format,
- image_quality,
- image_rename_mode,
- image_custom_suffix,
- video_codec,
- video_container,
- video_quality,
- video_rename_mode,
- video_custom_suffix,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- frame_interpolation_codec,
- frame_interpolation_container,
- frame_interpolation_quality,
- frame_interpolation_rename_mode,
- frame_interpolation_custom_suffix,
- ai_gpu_selector,
- video_gpu_selector,
- ]
-
- image_sources.change(
- preview_input_images,
- inputs=image_sources,
- outputs=image_input_gallery,
- queue=False,
- show_progress="hidden",
- )
- video_sources.change(
- update_video_preview_mode,
- inputs=video_sources,
- outputs=[
- video_input_preview,
- output_video,
- video_preview_frame,
- video_preview,
- ],
- queue=False,
- show_progress="hidden",
- )
- frame_interpolation_sources.change(
- update_frame_interpolation_preview_mode,
- inputs=[
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- ],
- outputs=[
- frame_interpolation_input_preview,
- frame_interpolation_output_video,
- frame_interpolation_preview,
- frame_interpolation_plan,
- ],
- queue=False,
- show_progress="hidden",
- )
- image_rename_mode.change(
- rename_suffix_update,
- inputs=image_rename_mode,
- outputs=image_custom_suffix,
- queue=False,
- )
- video_rename_mode.change(
- rename_suffix_update,
- inputs=video_rename_mode,
- outputs=video_custom_suffix,
- queue=False,
- )
- frame_interpolation_rename_mode.change(
- rename_suffix_update,
- inputs=frame_interpolation_rename_mode,
- outputs=frame_interpolation_custom_suffix,
- queue=False,
- )
- for component in [frame_interpolation_target_fps, frame_interpolation_engine]:
- component.change(
- describe_frame_interpolation_plan,
- inputs=[
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- ],
- outputs=frame_interpolation_plan,
- queue=False,
- show_progress="hidden",
- )
- for component in image_settings_inputs:
- component.input(
- persist_image_settings,
- inputs=image_settings_inputs,
- outputs=[*video_neural, video_model_preset],
- queue=False,
- )
- for component in video_settings_inputs:
- component.input(
- persist_video_settings,
- inputs=video_settings_inputs,
- outputs=[*image_neural, image_model_preset],
- queue=False,
- )
- for component in frame_interpolation_settings_inputs:
- component.input(
- persist_frame_interpolation_settings,
- inputs=frame_interpolation_settings_inputs,
- queue=False,
- )
-
- preset_export.click(
- settings_preset_export_status,
- inputs=preset_name,
- outputs=preset_status,
- queue=False,
- )
- preset_import_event = preset_import.upload(
- apply_settings_preset,
- inputs=[preset_import, preset_name],
- outputs=[preset_name, *settings_component_outputs, preset_status],
- queue=False,
- )
- preset_import_event.then(
- persist_gpu_settings,
- inputs=[ai_gpu_selector, video_gpu_selector],
- outputs=gpu_status,
- queue=False,
- ).then(
- frame_interpolation_capability_text,
- outputs=frame_interpolation_capabilities,
- queue=False,
- show_progress="hidden",
- ).then(
- describe_frame_interpolation_plan,
- inputs=[
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- ],
- outputs=frame_interpolation_plan,
- queue=False,
- show_progress="hidden",
- )
-
- for selector in [ai_gpu_selector, video_gpu_selector]:
- selector.input(
- persist_gpu_settings,
- inputs=[ai_gpu_selector, video_gpu_selector],
- outputs=gpu_status,
- queue=False,
- ).then(
- frame_interpolation_capability_text,
- outputs=frame_interpolation_capabilities,
- queue=False,
- show_progress="hidden",
- ).then(
- describe_frame_interpolation_plan,
- inputs=[
- frame_interpolation_sources,
- frame_interpolation_target_fps,
- frame_interpolation_engine,
- ],
- outputs=frame_interpolation_plan,
- queue=False,
- show_progress="hidden",
- )
-
- image_render.click(
- render_image_batch,
- inputs=image_inputs,
- outputs=[
- image_output_gallery,
- image_output_files,
- image_zip,
- image_results,
- image_status,
- ],
- concurrency_limit=1,
- )
- image_stop.click(cancel_active_job, outputs=image_status, queue=False)
-
- video_render.click(
- render_video_batch,
- inputs=video_inputs,
- outputs=[output_video, video_output_files, video_results, video_status],
- concurrency_limit=1,
- )
- video_preview.click(
- preview_video,
- inputs=video_preview_inputs,
- outputs=[output_video, video_status],
- concurrency_limit=1,
- )
- video_preview_frame.click(
- preview_one_frame,
- inputs=video_preview_inputs,
- outputs=[output_video, video_status],
- concurrency_limit=1,
- )
- video_stop.click(cancel_active_job, outputs=video_status, queue=False)
-
- frame_interpolation_render.click(
- render_frame_interpolation_batch,
- inputs=frame_interpolation_inputs,
- outputs=[
- frame_interpolation_output_video,
- frame_interpolation_output_files,
- frame_interpolation_results,
- frame_interpolation_status,
- ],
- concurrency_limit=1,
- )
- frame_interpolation_preview.click(
- preview_frame_interpolation,
- inputs=frame_interpolation_preview_inputs,
- outputs=[frame_interpolation_output_video, frame_interpolation_status],
- concurrency_limit=1,
- )
- frame_interpolation_stop.click(
- cancel_active_job, outputs=frame_interpolation_status, queue=False
- )
+ settings_tab = build_settings_tab(settings, ai_gpu_choices, video_gpu_choices)
- reset_outputs = [
- *settings_component_outputs,
- image_status,
- video_status,
- frame_interpolation_status,
- gpu_status,
- ]
- image_reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
- video_reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
- frame_interpolation_reset.click(
- reset_saved_settings, outputs=reset_outputs, queue=False
- )
+ bind_settings_events(settings_tab, image_tab, video_tab, frame_tab)
return demo
def main() -> None:
- print("Preparing DLSS, GPU, image, and FFmpeg runtime before launching the UI...", flush=True)
+ OUTPUTS.mkdir(exist_ok=True)
+ LOGS.mkdir(exist_ok=True)
+ # Reuse early loading UI if it was already rendered at import time (avoids second flash and keeps alt buffer)
+ global _early_ui # type: ignore
+ if "_EARLY_UI" in globals() and _early_ui is not None and getattr(_early_ui, "_alt_active", False):
+ ui = _early_ui # type: ignore
+ # Complete init that early block did not do (listener + redirect)
+ try:
+ ui.start_input_listener()
+ except Exception:
+ pass
+ try:
+ ui.silence_and_redirect()
+ except Exception:
+ pass
+ try:
+ import atexit
+
+ atexit.register(ui.restore_cursor)
+ except Exception:
+ pass
+ else:
+ ui = init_console(LOGS)
try:
- prepared = prepare_runtime()
+ prepare_runtime()
except Exception as exc:
- print(f"Startup preparation failed: {exc}", file=sys.stderr, flush=True)
+ with open(LOGS / "startup_error.log", "a", encoding="utf-8") as f:
+ f.write(f"Startup preparation failed: {exc}\n")
raise SystemExit(1) from exc
- print(
- f"Runtime ready on {prepared.gpu['display_name']}; launching Gradio.",
- flush=True,
- )
- OUTPUTS.mkdir(exist_ok=True)
- LOGS.mkdir(exist_ok=True)
+
demo = build_app()
- demo.queue(default_concurrency_limit=1).launch(
- css=APP_CSS,
- theme=gr.themes.Ocean(),
- server_name="127.0.0.1",
- inbrowser=True,
- share=False,
- allowed_paths=[str(OUTPUTS.resolve())],
- show_error=True,
- )
+ # Replace loading screen with final DLSS 5 Visual Enhancer splash
+ try:
+ ui.render_screen()
+ except Exception:
+ pass
+ try:
+ demo.queue(default_concurrency_limit=1).launch(
+ css=APP_CSS,
+ theme=gr.themes.Ocean(),
+ server_name="127.0.0.1",
+ inbrowser=True,
+ share=False,
+ allowed_paths=[str(OUTPUTS.resolve())],
+ show_error=True,
+ quiet=True,
+ )
+ except KeyboardInterrupt:
+ pass
if __name__ == "__main__":
diff --git a/src/__init__.py b/src/__init__.py
index f9e5538..3ceb7d0 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -1,11 +1,11 @@
"""Portable DLSS 5 Visual Enhancer for images and video."""
-from .ffmpeg import probe_video
-from .images import (
+from .core.ffmpeg import probe_video
+from .image import (
ImageBatchResult,
+ ImageConversionFailure,
ImageConversionOptions,
ImageConversionResult,
- ImageConversionFailure,
convert_image,
convert_images,
probe_image,
diff --git a/src/core/__init__.py b/src/core/__init__.py
new file mode 100644
index 0000000..035fb1f
--- /dev/null
+++ b/src/core/__init__.py
@@ -0,0 +1,12 @@
+from .gpu_detection import clear_gpu_detection_cache, detect_gpus
+from .gpu_selection import detect_gpu, gpu_choice_label, resolve_ai_gpu, resolve_runtime_ai_gpu
+from .jobs import Cancelled, JobController, active_job, cancel_active_job
+from .paths import ADDON, DLSS_DIR, DLSS_SUPERRES, DLSSG_DIR, FFMPEG, FFPROBE, HOST_DIR, HOST_DXGI, JOBS, LOGS, NEURAL_RUNTIME, OUTPUTS, RESHADE_LOG, ROOT, RUNTIME, WORKER
+
+__all__ = [
+ "ADDON", "Cancelled", "DLSS_DIR", "DLSS_SUPERRES", "DLSSG_DIR", "FFMPEG", "FFPROBE",
+ "HOST_DIR", "HOST_DXGI", "JOBS", "LOGS", "NEURAL_RUNTIME",
+ "OUTPUTS", "RESHADE_LOG", "ROOT", "RUNTIME", "WORKER", "JobController", "active_job",
+ "cancel_active_job", "clear_gpu_detection_cache", "detect_gpu", "detect_gpus",
+ "gpu_choice_label", "resolve_ai_gpu", "resolve_runtime_ai_gpu",
+]
diff --git a/src/core/ffmpeg/__init__.py b/src/core/ffmpeg/__init__.py
new file mode 100644
index 0000000..04ae051
--- /dev/null
+++ b/src/core/ffmpeg/__init__.py
@@ -0,0 +1,25 @@
+from .codecs import (
+ AUTO_BITRATE_DIVISORS, CODEC_CHOICES, ENCODING_QUALITIES, HDR_ALLOWED_CODECS,
+ _base_codec, _is_hdr_allowed_codec, _is_nvenc_codec, _normalize_codec,
+ calculate_auto_bitrate_kbps, hdr_mode_supported, resolve_encoding_quality,
+ validate_codec_container,
+)
+from .encoder import probe_nvenc_codecs, resolve_video_gpu, start_encoder
+from .mux import final_mux
+from .preview import (
+ DEFAULT_PREVIEW_ENCODING, PREVIEW_ENCODING_CHOICES, is_browser_playable,
+ is_user_playable_request, make_browser_preview, normalize_preview_encoding,
+ resolve_final_preview, resolve_preview_codec, wants_compat_preview,
+)
+from .probe import preview_frame_count, probe_video
+
+__all__ = [
+ "AUTO_BITRATE_DIVISORS", "CODEC_CHOICES", "DEFAULT_PREVIEW_ENCODING",
+ "ENCODING_QUALITIES", "HDR_ALLOWED_CODECS", "PREVIEW_ENCODING_CHOICES",
+ "calculate_auto_bitrate_kbps", "final_mux", "hdr_mode_supported",
+ "is_browser_playable", "is_user_playable_request", "make_browser_preview",
+ "normalize_preview_encoding", "preview_frame_count", "probe_nvenc_codecs",
+ "probe_video", "resolve_encoding_quality", "resolve_final_preview",
+ "resolve_preview_codec", "resolve_video_gpu", "start_encoder",
+ "validate_codec_container", "wants_compat_preview",
+]
diff --git a/src/core/ffmpeg/codecs.py b/src/core/ffmpeg/codecs.py
new file mode 100644
index 0000000..31c999e
--- /dev/null
+++ b/src/core/ffmpeg/codecs.py
@@ -0,0 +1,230 @@
+from __future__ import annotations
+
+import math
+
+
+ENCODING_QUALITIES = ("Auto (Default)", "Max", "Best", "Good")
+
+# User-facing codec choices: plain = CPU (libx264/libx265/libsvtav1), suffixed = NVIDIA NVENC.
+CODEC_CHOICES = (
+ "H.264",
+ "H.264 (NVIDIA NVENC)",
+ "H.265",
+ "H.265 (NVIDIA NVENC)",
+ "AV1",
+ "AV1 (NVIDIA NVENC)",
+ "ProRes Proxy",
+)
+
+_CODEC_ALIASES = {
+ "HEVC": "H.265",
+ "H265": "H.265",
+ "H.265 (HEVC)": "H.265",
+ "HEVC (NVIDIA NVENC)": "H.265 (NVIDIA NVENC)",
+}
+
+_BASE_CODEC_MAP = {
+ "H.264": "H.264",
+ "H.264 (NVIDIA NVENC)": "H.264",
+ "H.265": "H.265",
+ "H.265 (NVIDIA NVENC)": "H.265",
+ "AV1": "AV1",
+ "AV1 (NVIDIA NVENC)": "AV1",
+ "ProRes Proxy": "ProRes Proxy",
+}
+
+_IS_NVENC_SET = {
+ "H.264 (NVIDIA NVENC)",
+ "H.265 (NVIDIA NVENC)",
+ "AV1 (NVIDIA NVENC)",
+}
+
+_CPU_ENCODERS = {
+ "H.264": "libx264",
+ "H.265": "libx265",
+ "AV1": "libsvtav1",
+}
+
+_NVENC_ENCODERS = {
+ "H.264 (NVIDIA NVENC)": "h264_nvenc",
+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",
+ "AV1 (NVIDIA NVENC)": "av1_nvenc",
+}
+
+# Keep AUTO_BITRATE_DIVISORS keyed by base codec; "HEVC" alias preserved for compat.
+AUTO_BITRATE_DIVISORS = {
+ "H.264": 165_888,
+ "H.265": 331_776,
+ "HEVC": 331_776,
+ "AV1": 414_720,
+}
+
+# HDR Mode is only meaningful for 10-bit capable codecs. H.264 (both CPU/NVENC) stays 8-bit SDR.
+HDR_ALLOWED_CODECS = {
+ "H.265",
+ "H.265 (NVIDIA NVENC)",
+ "AV1",
+ "AV1 (NVIDIA NVENC)",
+ "ProRes Proxy",
+}
+
+def _normalize_codec(codec: str) -> str:
+ if not isinstance(codec, str):
+ return codec
+ c = codec.strip()
+ return _CODEC_ALIASES.get(c, c)
+
+
+def _base_codec(codec: str) -> str:
+ norm = _normalize_codec(codec)
+ base = _BASE_CODEC_MAP.get(norm)
+ if base is None:
+ raise ValueError(f"Unknown video codec: {codec!r}.")
+ return base
+
+
+def _is_nvenc_codec(codec: str) -> bool:
+ return _normalize_codec(codec) in _IS_NVENC_SET
+
+
+def _is_hdr_allowed_codec(codec: str) -> bool:
+ return _normalize_codec(codec) in HDR_ALLOWED_CODECS
+
+
+def _is_hdr_allowed_for_encoding(codec: str) -> bool:
+ """Check if HDR Mode (10-bit + colorspace copy) is supported for this codec."""
+ return _is_hdr_allowed_codec(codec)
+
+
+def hdr_mode_supported(codec: str) -> bool:
+ """Public helper for UI: is HDR Mode toggle meaningful for this codec?"""
+ return _is_hdr_allowed_codec(codec)
+
+
+def _hdr_color_args(metadata: dict | None) -> list[str]:
+ """Return ffmpeg color flags copying input colorspace when possible.
+
+ We copy color_space / color_primaries / color_transfer if they are known.
+ For HDR mode we also ensure 10-bit; metadata may be from SDR as well – we still
+ copy what we have, which preserves SDR in same space if input was SDR.
+ """
+ if not metadata:
+ return []
+ args: list[str] = []
+ # ffprobe values map directly to ffmpeg -colorspace etc when not 'unknown'
+ cs = metadata.get("color_space")
+ if isinstance(cs, str) and cs not in ("unknown", "", None):
+ # ffmpeg expects 'bt709', 'bt2020nc', 'bt2020c', etc. Probe already returns that.
+ args.extend(["-colorspace", cs])
+ cp = metadata.get("color_primaries")
+ if isinstance(cp, str) and cp not in ("unknown", "", None):
+ args.extend(["-color_primaries", cp])
+ trc = metadata.get("color_transfer")
+ if isinstance(trc, str) and trc not in ("unknown", "", None):
+ args.extend(["-color_trc", trc])
+ # color_range is not probed currently; default tv for HDR
+ # If HDR, ensure range is tv
+ if metadata.get("hdr"):
+ # Ensure we signal full vs limited correctly – probe doesn't give range, use tv
+ # Don't double-add if already present
+ if "-color_range" not in args:
+ args.extend(["-color_range", "tv"])
+ return args
+
+
+def _x265_hdr_params(metadata: dict | None) -> str | None:
+ """Build x265-params for HDR/SDR copy when using libx265 10-bit."""
+ if not metadata:
+ return None
+ # x265 expects colorprim, transfer, colormatrix as specific strings
+ # Map ffprobe names to x265 names (they align for common cases)
+ mapping = {
+ "color_primaries": metadata.get("color_primaries", "unknown"),
+ "color_transfer": metadata.get("color_transfer", "unknown"),
+ "color_space": metadata.get("color_space", "unknown"),
+ }
+ # Filter unknowns – use bt709 fallback for SDR
+ prim = mapping["color_primaries"] if mapping["color_primaries"] not in ("unknown", "", None) else "bt709"
+ trc = mapping["color_transfer"] if mapping["color_transfer"] not in ("unknown", "", None) else "bt709"
+ cmat = mapping["color_space"] if mapping["color_space"] not in ("unknown", "", None) else "bt709"
+ # x265 colormatrix for bt2020nc is bt2020nc, for bt709 is bt709
+ # Ensure x265-compatible values: bt2020nc is valid, bt709 is valid
+ return f"colorprim={prim}:transfer={trc}:colormatrix={cmat}:range=limited"
+
+
+def validate_codec_container(codec: str, container: str) -> None:
+ norm = _normalize_codec(codec)
+ if norm == "ProRes Proxy" and container == "MP4":
+ raise ValueError("ProRes Proxy is not supported in MP4. Choose the MOV or MKV container.")
+ if norm not in CODEC_CHOICES and norm not in _CODEC_ALIASES.values():
+ # Allow alias but error on truly unknown for early feedback; _codec_command will also validate.
+ if norm not in ("H.264", "H.264 (NVIDIA NVENC)", "H.265", "H.265 (NVIDIA NVENC)", "AV1", "AV1 (NVIDIA NVENC)", "ProRes Proxy", "HEVC"):
+ raise ValueError(f"Unknown video codec: {codec!r}.")
+
+
+def calculate_auto_bitrate_kbps(
+ width: int,
+ height: int,
+ fps: float,
+ codec: str,
+ bit_depth: int = 8,
+) -> int:
+ norm = _normalize_codec(codec)
+ base = _base_codec(norm) if norm in _BASE_CODEC_MAP else norm
+ # ProRes has no auto bitrate
+ if base == "ProRes Proxy":
+ raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.")
+ try:
+ divisor = AUTO_BITRATE_DIVISORS[base]
+ except KeyError:
+ # Fallback for HEVC alias
+ try:
+ divisor = AUTO_BITRATE_DIVISORS[_normalize_codec(codec)]
+ except KeyError as exc:
+ raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.") from exc
+ if width <= 0 or height <= 0 or not math.isfinite(fps) or fps <= 0 or bit_depth <= 0:
+ raise ValueError("Automatic bitrate requires positive dimensions, frame rate, and bit depth.")
+ value = width * height * fps * bit_depth * 2 / divisor
+ return max(1, int(math.floor(value + 0.5)))
+
+
+def resolve_encoding_quality(
+ quality_name: str,
+ codec: str,
+ width: int,
+ height: int,
+ fps: float,
+ hdr_mode: bool = False,
+) -> dict:
+ if quality_name not in ENCODING_QUALITIES:
+ raise ValueError(f"Unknown encoding quality: {quality_name!r}.")
+ norm = _normalize_codec(codec)
+ if norm not in CODEC_CHOICES:
+ # Accept HEVC alias
+ if norm not in _BASE_CODEC_MAP and norm != "HEVC":
+ raise ValueError(f"Unknown video codec: {codec!r}.")
+ if _normalize_codec(norm) == "ProRes Proxy" or _base_codec(norm) == "ProRes Proxy":
+ return {
+ "selection": quality_name,
+ "mode": "fixed-prores-proxy-profile",
+ "target_bitrate_kbps": None,
+ "cq": None,
+ }
+ if quality_name == "Max":
+ return {
+ "selection": quality_name,
+ "mode": "constant-quality",
+ "target_bitrate_kbps": None,
+ "cq": 0,
+ }
+ multiplier = {"Auto (Default)": 1, "Good": 2, "Best": 4}[quality_name]
+ bit_depth = 10 if hdr_mode and _is_hdr_allowed_codec(codec) else 8
+ auto = calculate_auto_bitrate_kbps(width, height, fps, codec, bit_depth=bit_depth)
+ return {
+ "selection": quality_name,
+ "mode": "target-bitrate",
+ "auto_bitrate_kbps": auto,
+ "multiplier": multiplier,
+ "target_bitrate_kbps": auto * multiplier,
+ "cq": None,
+ }
diff --git a/src/core/ffmpeg/encoder.py b/src/core/ffmpeg/encoder.py
new file mode 100644
index 0000000..1e4b002
--- /dev/null
+++ b/src/core/ffmpeg/encoder.py
@@ -0,0 +1,338 @@
+from __future__ import annotations
+
+import subprocess
+import threading
+from functools import lru_cache
+from pathlib import Path
+
+from ..jobs import JobController, drain_text
+from ..paths import FFMPEG
+from .codecs import (
+ CODEC_CHOICES, _NVENC_ENCODERS, _base_codec, _hdr_color_args,
+ _is_hdr_allowed_codec, _is_nvenc_codec, _normalize_codec, _x265_hdr_params,
+ resolve_encoding_quality,
+)
+
+def _encoder_probe(
+ codec: str, width: int, height: int, gpu_ordinal: int | None = None
+) -> bool:
+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []
+ command = [
+ str(FFMPEG),
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ f"color=size={width}x{height}:rate=1",
+ "-frames:v",
+ "1",
+ "-c:v",
+ codec,
+ *gpu_args,
+ "-f",
+ "null",
+ "-",
+ ]
+ return (
+ subprocess.run(
+ command,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ ).returncode
+ == 0
+ )
+
+
+# Legacy mapping kept for external callers; new display names use _NVENC_ENCODERS.
+_NVENC_CODECS = {
+ "H.264": "h264_nvenc",
+ "HEVC": "hevc_nvenc",
+ "AV1": "av1_nvenc",
+ "H.265": "hevc_nvenc",
+ "H.264 (NVIDIA NVENC)": "h264_nvenc",
+ "H.265 (NVIDIA NVENC)": "hevc_nvenc",
+ "AV1 (NVIDIA NVENC)": "av1_nvenc",
+}
+
+
+def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:
+ """Return user-facing codecs that can initialize NVENC on one CUDA device.
+
+ Returns display names like "H.264 (NVIDIA NVENC)" so UI can filter.
+ """
+ # Probe the three actual NVENC encoders once, then map to display names.
+ mapping = {
+ "h264_nvenc": "H.264 (NVIDIA NVENC)",
+ "hevc_nvenc": "H.265 (NVIDIA NVENC)",
+ "av1_nvenc": "AV1 (NVIDIA NVENC)",
+ }
+ supported = []
+ for encoder, display in mapping.items():
+ if _encoder_probe(encoder, 256, 256, int(gpu_ordinal)):
+ supported.append(display)
+ return tuple(supported)
+
+
+def resolve_video_gpu(
+ gpus: tuple[dict, ...],
+ gpu_uuid: str,
+ codec: str,
+ width: int,
+ height: int,
+) -> dict | None:
+ """Resolve a stable UUID to a device that supports the requested NVENC codec.
+
+ CPU codecs (plain H.264/H.265/AV1 without '(NVIDIA NVENC)') never require a GPU.
+ NVENC codecs explicitly require a cuda device that can init the encoder.
+ """
+ norm = _normalize_codec(codec)
+ if norm == "ProRes Proxy":
+ return None
+ # CPU variants do not need a GPU
+ if not _is_nvenc_codec(norm):
+ # Validate that plain codecs are known; if unknown, raise.
+ if norm not in CODEC_CHOICES and norm not in ("HEVC", "H.265"):
+ # Try base check
+ try:
+ _base_codec(norm)
+ except ValueError as exc:
+ raise ValueError(f"Unknown video codec: {codec!r}.") from exc
+ # Plain variants: no GPU needed (CPU encoding)
+ return None
+ # NVENC path
+ try:
+ encoder = _NVENC_ENCODERS[norm]
+ except KeyError as exc:
+ raise ValueError(f"Unknown video codec: {codec!r}.") from exc
+ candidates = [gpu for gpu in gpus if gpu.get("cuda_ordinal") is not None]
+ if gpu_uuid != "auto":
+ candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]
+ if not candidates:
+ raise RuntimeError("The selected Video Processing GPU is unavailable.")
+ for gpu in candidates:
+ ordinal = int(gpu["cuda_ordinal"])
+ if _encoder_probe(encoder, width, height, ordinal):
+ selected = dict(gpu)
+ selected["nvenc_codec"] = encoder
+ return selected
+ selection = "selected GPU" if gpu_uuid != "auto" else "available NVIDIA GPUs"
+ raise RuntimeError(
+ f"{norm} cannot encode the requested {width}×{height} output on the "
+ f"{selection}. Choose another Video Processing GPU, codec, or output size."
+ )
+
+
+def _codec_command(
+ codec: str,
+ quality_name: str,
+ width: int,
+ height: int,
+ fps: float,
+ gpu_ordinal: int | None = None,
+ require_nvenc: bool = False,
+ hdr_mode: bool = False,
+ hdr_metadata: dict | None = None,
+) -> tuple[list[str], str, dict]:
+ """Return FFmpeg codec args for an explicit user-facing codec choice.
+
+ Plain names (H.264, H.265, AV1) are strictly CPU (libx264/libx265/libsvtav1).
+ Suffixed names (H.264 (NVIDIA NVENC) etc.) are strictly NVENC and require a GPU.
+ `require_nvenc` is kept for backward compat – NVENC codecs always require NVENC,
+ CPU codecs always forbid fallback to NVENC.
+ When ``hdr_mode`` is True, output is 10-bit (yuv420p10le/p010le) and input
+ colorspace is copied via ``hdr_metadata`` for HDR_ALLOWED_CODECS.
+ """
+ norm = _normalize_codec(codec)
+ if hdr_mode and not _is_hdr_allowed_codec(norm):
+ raise ValueError(
+ f"HDR Mode is not available for {codec!r}; choose H.265, H.265 (NVIDIA NVENC), "
+ "AV1, AV1 (NVIDIA NVENC) or ProRes Proxy."
+ )
+ # HDR mode needs 10-bit divisor
+ quality = resolve_encoding_quality(quality_name, codec, width, height, fps, hdr_mode=hdr_mode)
+ # ProRes Proxy is always 10-bit; HDR just copies colorspace
+ if norm == "ProRes Proxy":
+ hdr_extra = _hdr_color_args(hdr_metadata) if hdr_mode and hdr_metadata else []
+ return (
+ ["-c:v", "prores_ks", "-profile:v", "0", "-pix_fmt", "yuv422p10le", *hdr_extra],
+ "prores_ks (Proxy)",
+ quality,
+ )
+ if quality["mode"] == "constant-quality":
+ nvenc_quality = ["-rc", "vbr", "-cq", "0", "-b:v", "0"]
+ software_quality = ["-crf", "0"]
+ bitrate = None
+ else:
+ bitrate = f"{quality['target_bitrate_kbps']}k"
+ nvenc_quality = ["-rc", "vbr", "-b:v", bitrate]
+ software_quality = ["-b:v", bitrate]
+ gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []
+ hdr_color = _hdr_color_args(hdr_metadata) if hdr_mode and hdr_metadata else []
+
+ # CPU variants – never probe NVENC, always use software encoder
+ if norm == "H.264":
+ # H.264 is always 8-bit SDR – HDR Mode is not allowed (checked above), so plain yuv420p
+ if require_nvenc:
+ raise RuntimeError(
+ f"H.264 (CPU) was requested but NVENC was required; choose H.264 (NVIDIA NVENC) for GPU encoding."
+ )
+ if hdr_mode:
+ raise ValueError("HDR Mode is not available for H.264; choose H.265/AV1/ProRes.")
+ return (
+ ["-c:v", "libx264", "-preset", "slow", *software_quality, "-pix_fmt", "yuv420p"],
+ "libx264",
+ quality,
+ )
+ if norm == "H.265" or norm == "HEVC":
+ if require_nvenc:
+ raise RuntimeError(
+ f"H.265 (CPU) was requested but NVENC was required; choose H.265 (NVIDIA NVENC) for GPU encoding."
+ )
+ # HDR → 10-bit yuv420p10le, SDR → yuv420p.
+ pix_fmt = "yuv420p10le" if hdr_mode else "yuv420p"
+ if hdr_mode:
+ x265_params = _x265_hdr_params(hdr_metadata)
+ x265_extra = ["-x265-params", x265_params] if x265_params else []
+ # For x265, use x265-params exclusively for HDR (generic breaks VUI)
+ return (
+ ["-c:v", "libx265", "-preset", "slow", *software_quality, "-pix_fmt", pix_fmt, *x265_extra],
+ "libx265",
+ quality,
+ )
+ return (
+ ["-c:v", "libx265", "-preset", "slow", *software_quality, "-pix_fmt", pix_fmt, *hdr_color],
+ "libx265",
+ quality,
+ )
+ if norm == "AV1":
+ if require_nvenc:
+ raise RuntimeError(
+ "AV1 (CPU) was requested but NVENC was required; choose AV1 (NVIDIA NVENC) for GPU encoding."
+ )
+ pix_fmt = "yuv420p10le" if hdr_mode else "yuv420p"
+ # Prefer libsvtav1 (fastest CPU AV1), fallback to libaom-av1
+ if _encoder_probe("libsvtav1", width, height):
+ if quality["mode"] == "constant-quality":
+ return (
+ ["-c:v", "libsvtav1", "-preset", "6", "-crf", "0", "-pix_fmt", pix_fmt, *hdr_color],
+ "libsvtav1",
+ quality,
+ )
+ return (
+ ["-c:v", "libsvtav1", "-preset", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],
+ "libsvtav1",
+ quality,
+ )
+ if _encoder_probe("libaom-av1", width, height):
+ if quality["mode"] == "constant-quality":
+ return (
+ ["-c:v", "libaom-av1", "-cpu-used", "4", "-crf", "0", "-b:v", "0", "-pix_fmt", pix_fmt, *hdr_color],
+ "libaom-av1",
+ quality,
+ )
+ return (
+ ["-c:v", "libaom-av1", "-cpu-used", "6", "-b:v", bitrate, "-pix_fmt", pix_fmt, *hdr_color],
+ "libaom-av1",
+ quality,
+ )
+ raise RuntimeError(
+ "AV1 CPU encoding is unavailable: neither libsvtav1 nor libaom-av1 can initialize. "
+ "Choose H.264/H.265 or AV1 (NVIDIA NVENC) if a GPU is available."
+ )
+
+ # NVENC variants – strictly require NVENC probe success
+ if norm == "H.264 (NVIDIA NVENC)":
+ if hdr_mode:
+ raise ValueError("HDR Mode is not available for H.264 (NVIDIA NVENC); choose H.265/AV1.")
+ if not _encoder_probe("h264_nvenc", width, height, gpu_ordinal):
+ raise RuntimeError(
+ f"H.264 (NVIDIA NVENC) cannot encode {width}×{height} on the selected Video Processing GPU. "
+ "Choose H.264 (CPU) or another GPU."
+ )
+ return (
+ [
+ "-c:v", "h264_nvenc", *gpu_args, "-preset", "p6", "-tune", "hq",
+ *nvenc_quality, "-pix_fmt", "yuv420p",
+ ],
+ "h264_nvenc",
+ quality,
+ )
+ if norm == "H.265 (NVIDIA NVENC)":
+ if not _encoder_probe("hevc_nvenc", width, height, gpu_ordinal):
+ raise RuntimeError(
+ f"H.265 (NVIDIA NVENC) cannot encode {width}×{height} on the selected Video Processing GPU. "
+ "Choose H.265 (CPU) or another GPU."
+ )
+ pix_fmt = "p010le" if hdr_mode else "yuv420p"
+ # HEVC HDR should use main10 implicitly via p010le
+ return (
+ [
+ "-c:v", "hevc_nvenc", *gpu_args, "-preset", "p6", "-tune", "hq",
+ *nvenc_quality, "-pix_fmt", pix_fmt, *hdr_color,
+ ],
+ "hevc_nvenc",
+ quality,
+ )
+ if norm == "AV1 (NVIDIA NVENC)":
+ if not _encoder_probe("av1_nvenc", width, height, gpu_ordinal):
+ raise RuntimeError(
+ f"AV1 (NVIDIA NVENC) cannot encode {width}×{height} on the selected GPU/driver. "
+ "Choose AV1 (CPU) with libsvtav1, or H.264/H.265, or a lower upscaling factor."
+ )
+ pix_fmt = "p010le" if hdr_mode else "yuv420p"
+ return (
+ ["-c:v", "av1_nvenc", *gpu_args, "-preset", "p6", *nvenc_quality, "-pix_fmt", pix_fmt, *hdr_color],
+ "av1_nvenc",
+ quality,
+ )
+
+ raise ValueError(f"Unknown video codec: {codec!r}.")
+
+
+def start_encoder(
+ temp_video: Path,
+ codec: str,
+ quality_name: str,
+ controller: JobController,
+ width: int,
+ height: int,
+ fps: float,
+ gpu_ordinal: int | None = None,
+ require_nvenc: bool = False,
+ hdr_mode: bool = False,
+ hdr_metadata: dict | None = None,
+):
+ codec_args, selected, quality = _codec_command(
+ codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc, hdr_mode, hdr_metadata
+ )
+ command = [
+ str(FFMPEG),
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-y",
+ "-f",
+ "nut",
+ "-i",
+ "pipe:0",
+ "-map",
+ "0:v:0",
+ "-an",
+ *codec_args,
+ "-fps_mode",
+ "passthrough",
+ str(temp_video),
+ ]
+ process = subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.PIPE,
+ )
+ controller.register(process)
+ logs: list[str] = []
+ assert process.stderr is not None
+ thread = threading.Thread(target=drain_text, args=(process.stderr, logs), daemon=True)
+ thread.start()
+ return process, thread, logs, selected, quality
diff --git a/src/core/ffmpeg/mux.py b/src/core/ffmpeg/mux.py
new file mode 100644
index 0000000..5c8ead1
--- /dev/null
+++ b/src/core/ffmpeg/mux.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+import math
+import subprocess
+from pathlib import Path
+
+from ..jobs import JobController
+from ..paths import FFMPEG, FFPROBE
+from .probe import _run_json
+
+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,
+ controller: JobController | None = None,
+ preserve_supported_subtitles: bool = False,
+) -> 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"]
+ else:
+ maps = ["-map", "0:v:0", "-map", "1:a?"]
+ streams = [
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ "-movflags",
+ "+faststart",
+ ]
+ if preserve_supported_subtitles:
+ subtitle_data = _run_json(
+ [
+ str(FFPROBE),
+ "-v",
+ "error",
+ "-select_streams",
+ "s",
+ "-show_entries",
+ "stream=index,codec_name",
+ "-of",
+ "json",
+ str(source),
+ ]
+ )
+ supported_text = {"ass", "ssa", "subrip", "mov_text", "webvtt", "text"}
+ subtitle_indices = [
+ int(stream["index"])
+ for stream in subtitle_data.get("streams") or []
+ if stream.get("codec_name") in supported_text
+ ]
+ for stream_index in subtitle_indices:
+ maps.extend(["-map", f"1:{stream_index}"])
+ if subtitle_indices:
+ streams.extend(["-c:s", "mov_text"])
+ command = [
+ str(FFMPEG),
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-y",
+ "-i",
+ str(temp_video),
+ "-t",
+ f"{duration:.9f}",
+ "-i",
+ str(source),
+ *maps,
+ "-map_metadata",
+ "1",
+ "-map_chapters",
+ "1",
+ *streams,
+ str(output),
+ ]
+ process = subprocess.Popen(
+ command,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if controller is not None:
+ controller.register(process)
+ try:
+ _stdout, stderr = process.communicate()
+ finally:
+ if controller is not None:
+ controller.unregister(process)
+ if process.returncode:
+ raise RuntimeError("Final audio/metadata mux failed:\n" + stderr[-4000:])
diff --git a/src/core/ffmpeg/preview.py b/src/core/ffmpeg/preview.py
new file mode 100644
index 0000000..0c76c77
--- /dev/null
+++ b/src/core/ffmpeg/preview.py
@@ -0,0 +1,200 @@
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+from ..paths import FFMPEG
+from .codecs import _base_codec
+
+PREVIEW_ENCODING_CHOICES = ("Auto", "Always H.264", "Disabled")
+DEFAULT_PREVIEW_ENCODING = "Auto"
+
+
+def normalize_preview_encoding(value: object) -> str:
+ """Return a valid preview-encoding mode, defaulting to Auto."""
+ if isinstance(value, str) and value.strip() in PREVIEW_ENCODING_CHOICES:
+ return value.strip()
+ return DEFAULT_PREVIEW_ENCODING
+
+
+def is_user_playable_request(codec: str, container: str) -> bool:
+ """Pre-check whether the requested encode settings are browser-playable.
+
+ Strict definition: MP4 container + H.264 base codec (plain or NVENC).
+ Used to pick the encode path without paying for a probe first.
+ """
+ try:
+ if container != "MP4":
+ return False
+ return _base_codec(codec) == "H.264"
+ except Exception:
+ return False
+
+
+def resolve_preview_codec(
+ requested_codec: str, requested_container: str, mode: object
+) -> tuple[str, str]:
+ """Return the (codec, container) to encode a truncated preview with."""
+ normalized = normalize_preview_encoding(mode)
+ if normalized == "Disabled":
+ return requested_codec, requested_container
+ if normalized == "Always H.264":
+ return "H.264", "MP4"
+ # Auto: reuse the user's settings when they are already browser-playable,
+ # otherwise fall back to the compatible H.264/MP4 preview.
+ if is_user_playable_request(requested_codec, requested_container):
+ return requested_codec, requested_container
+ return "H.264", "MP4"
+
+
+def wants_compat_preview(
+ requested_codec: str, requested_container: str, mode: object
+) -> bool:
+ """True when a truncated preview must use the forced H.264 SDR path."""
+ normalized = normalize_preview_encoding(mode)
+ if normalized == "Disabled":
+ return False
+ if normalized == "Always H.264":
+ return True
+ return not is_user_playable_request(requested_codec, requested_container)
+
+
+def is_browser_playable(path: str | Path) -> bool:
+ """Probe the actual output file: playable iff MP4 + H.264 video stream."""
+ from .probe import probe_video
+
+ candidate = Path(path)
+ if candidate.suffix.lower() != ".mp4":
+ return False
+ try:
+ metadata = probe_video(candidate, count_mode="metadata")
+ except Exception:
+ return False
+ codec = str(metadata.get("codec") or "").lower()
+ if codec not in ("h264", "avc"):
+ return False
+ container_format = str(metadata.get("format") or "").lower()
+ # ffprobe reports e.g. "mov,mp4,m4a,3gp,3g2,mj2" for MP4 files.
+ if "mp4" not in container_format:
+ return False
+ return True
+
+
+def make_browser_preview(
+ source: str | Path,
+ dest_dir: str | Path | None = None,
+ controller=None,
+) -> str:
+ """Transcode an existing result file to a browser-playable H.264 MP4.
+
+ Returns the new preview path as a string. Raises RuntimeError on failure.
+ """
+ from ..paths import OUTPUTS
+
+ src = Path(source)
+ if not src.is_file():
+ raise FileNotFoundError(src)
+ out_dir = Path(dest_dir) if dest_dir is not None else OUTPUTS
+ out_dir.mkdir(parents=True, exist_ok=True)
+ dest = out_dir / f"{src.stem}_BROWSERPREVIEW.mp4"
+ counter = 1
+ while dest.exists():
+ counter += 1
+ dest = out_dir / f"{src.stem}_BROWSERPREVIEW_{counter}.mp4"
+ command = [
+ str(FFMPEG),
+ "-hide_banner",
+ "-loglevel",
+ "warning",
+ "-y",
+ "-i",
+ str(src),
+ "-map",
+ "0:v:0",
+ "-map",
+ "0:a?",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "18",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ "-movflags",
+ "+faststart",
+ str(dest),
+ ]
+ process = subprocess.Popen(
+ command,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if controller is not None:
+ try:
+ controller.register(process)
+ except Exception:
+ pass
+ try:
+ _stdout, stderr = process.communicate()
+ finally:
+ if controller is not None:
+ try:
+ controller.unregister(process)
+ except Exception:
+ pass
+ if process.returncode:
+ raise RuntimeError(
+ "Browser preview transcode failed:\n" + (stderr or "")[-4000:]
+ )
+ if not dest.is_file():
+ raise RuntimeError("Browser preview transcode produced no output file.")
+ # Verify the derivative is actually playable before handing it to Gradio.
+ if not is_browser_playable(dest):
+ raise RuntimeError("Browser preview transcode produced an unplayable file.")
+ return str(dest)
+
+
+def resolve_final_preview(
+ result_path: str | Path | None,
+ mode: object,
+ controller=None,
+) -> tuple[str | None, bool]:
+ """Decide which file the final-render in-app player should show.
+
+ Returns (display_path, used_derivative). Applies the agreed policy:
+ - Always H.264: current behavior (MP4 result only, else no preview).
+ - Disabled: always show the actual file (even MKV/MOV).
+ - Auto: probe the result; show directly when playable, else transcode
+ one H.264 derivative and show that.
+ """
+ if not result_path:
+ return None, False
+ normalized = normalize_preview_encoding(mode)
+ candidate = str(result_path)
+ if normalized == "Disabled":
+ return candidate, False
+ if normalized == "Always H.264":
+ if Path(candidate).suffix.lower() == ".mp4":
+ return candidate, False
+ return None, False
+ # Auto
+ try:
+ if is_browser_playable(candidate):
+ return candidate, False
+ except Exception:
+ pass
+ try:
+ derived = make_browser_preview(candidate, controller=controller)
+ except Exception:
+ # Never break the render status path: fall back to no in-app preview
+ # (the real file is still in the download list).
+ return None, False
+ return derived, True
diff --git a/src/core/ffmpeg/probe.py b/src/core/ffmpeg/probe.py
new file mode 100644
index 0000000..7e667dc
--- /dev/null
+++ b/src/core/ffmpeg/probe.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+from fractions import Fraction
+from pathlib import Path
+
+import av
+
+from ..paths import FFPROBE
+
+def _run_json(command: list[str]) -> dict:
+ result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if result.returncode:
+ raise RuntimeError(result.stderr.strip() or "Media probe failed")
+ return json.loads(result.stdout)
+
+
+def probe_video(
+ path: str | os.PathLike[str], *, count_mode: str = "exact"
+) -> dict:
+ """Probe video metadata, optionally counting decoded frames or packets.
+
+ The default remains the legacy exact decoded-frame count for external callers.
+ Conversion paths use metadata first and pay for exact counting only as fallback.
+ """
+ if count_mode not in {"metadata", "exact", "packets"}:
+ raise ValueError(f"Unknown video count mode: {count_mode!r}.")
+ count_args = {
+ "metadata": [],
+ "exact": ["-count_frames"],
+ "packets": ["-count_packets"],
+ }[count_mode]
+ data = _run_json(
+ [
+ str(FFPROBE),
+ "-v",
+ "error",
+ *count_args,
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=index,codec_name,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,nb_read_packets,color_primaries,color_transfer,color_space:stream_tags=rotate:stream_side_data=rotation",
+ "-show_entries",
+ "format=duration,format_name",
+ "-of",
+ "json",
+ str(path),
+ ]
+ )
+ streams = data.get("streams") or []
+ if not streams:
+ raise ValueError("The selected file contains no decodable video stream.")
+ stream = streams[0]
+ rotation = int((stream.get("tags") or {}).get("rotate", 0) or 0)
+ for side in stream.get("side_data_list") or []:
+ if "rotation" in side:
+ rotation = int(side["rotation"] or 0)
+ rotation %= 360
+ width, height = int(stream["width"]), int(stream["height"])
+ if rotation in (90, 270):
+ width, height = height, width
+ if count_mode == "packets":
+ frames = int(stream.get("nb_read_packets") or stream.get("nb_frames") or 0)
+ frame_count_source = "packets" if stream.get("nb_read_packets") else "metadata"
+ elif count_mode == "exact":
+ frames = int(stream.get("nb_read_frames") or stream.get("nb_frames") or 0)
+ frame_count_source = "decoded" if stream.get("nb_read_frames") else "metadata"
+ else:
+ frames = int(stream.get("nb_frames") or 0)
+ frame_count_source = "metadata" if frames > 0 else "unavailable"
+ if count_mode == "exact" and frames <= 0:
+ raise ValueError("Could not determine an exact frame count for this video.")
+ average_rate_text = stream.get("avg_frame_rate") or "0/0"
+ nominal_rate_text = stream.get("r_frame_rate") or "0/0"
+ rate_text = average_rate_text if average_rate_text != "0/0" else nominal_rate_text
+ if rate_text == "0/0":
+ rate_text = "30/1"
+ rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)
+ nominal_rate = (
+ Fraction(nominal_rate_text)
+ if nominal_rate_text != "0/0"
+ else rate
+ )
+ transfer = stream.get("color_transfer") or "unknown"
+ primaries = stream.get("color_primaries") or "unknown"
+ color_space = stream.get("color_space") or "unknown"
+ return {
+ "width": width,
+ "height": height,
+ "coded_width": int(stream["width"]),
+ "coded_height": int(stream["height"]),
+ "rotation": rotation,
+ "frames": frames,
+ "frame_count_source": frame_count_source,
+ "fps": float(rate),
+ "rate": rate,
+ "nominal_rate": nominal_rate,
+ "cfr": rate == nominal_rate,
+ "time_base": Fraction(stream.get("time_base") or "1/1000"),
+ "duration": float(
+ (data.get("format") or {}).get("duration") or stream.get("duration") or 0
+ ),
+ "codec": stream.get("codec_name") or "unknown",
+ "format": (data.get("format") or {}).get("format_name") or "unknown",
+ "color_transfer": transfer,
+ "color_primaries": primaries,
+ "color_space": color_space,
+ "hdr": transfer in {"smpte2084", "arib-std-b67"},
+ }
+
+def preview_frame_count(source: Path, seconds: float) -> int:
+ """Count frames whose presentation times fall within the opening interval."""
+ container = av.open(str(source))
+ try:
+ stream = container.streams.video[0]
+ rate = float(stream.average_rate or 30)
+ first_time: float | None = None
+ count = 0
+ for frame in container.decode(stream):
+ timestamp = (
+ float(frame.pts * stream.time_base)
+ if frame.pts is not None and stream.time_base is not None
+ else count / rate
+ )
+ if first_time is None:
+ first_time = timestamp
+ if count and timestamp - first_time >= seconds:
+ break
+ count += 1
+ if count == 0:
+ raise RuntimeError("The input video contains no decodable preview frames.")
+ return count
+ finally:
+ container.close()
diff --git a/src/core/gpu_detection.py b/src/core/gpu_detection.py
new file mode 100644
index 0000000..717fc0e
--- /dev/null
+++ b/src/core/gpu_detection.py
@@ -0,0 +1,191 @@
+from __future__ import annotations
+
+import ctypes
+import re
+import subprocess
+from functools import lru_cache
+from typing import Any
+
+
+_RTX_ARCHITECTURES: dict[tuple[int, int], tuple[str, int]] = {
+ (7, 5): ("Turing", 20),
+ (8, 0): ("Ampere", 30),
+ (8, 6): ("Ampere", 30),
+ (8, 7): ("Ampere", 30),
+ (8, 8): ("Ampere", 30),
+ (8, 9): ("Ada", 40),
+ (10, 0): ("Blackwell", 50),
+ (10, 3): ("Blackwell", 50),
+ (11, 0): ("Blackwell", 50),
+ (12, 0): ("Blackwell", 50),
+ (12, 1): ("Blackwell", 50),
+}
+
+
+def _classify_rtx_architecture(name: str, capability: str) -> tuple[str, int | None]:
+ """Best-effort RTX metadata; never use this to decide whether an RTX GPU may run."""
+ match = re.fullmatch(r"(\d+)\.(\d+)", capability.strip())
+ if match is not None:
+ compute_capability = (int(match.group(1)), int(match.group(2)))
+ classified = _RTX_ARCHITECTURES.get(compute_capability)
+ if classified is not None:
+ return classified
+
+ name_match = re.search(r"\bRTX\s*(20|30|40|50)\d{2}\b", name.upper())
+ if name_match is not None:
+ generation = int(name_match.group(1))
+ architecture = {20: "Turing", 30: "Ampere", 40: "Ada", 50: "Blackwell"}.get(
+ generation, "Unknown"
+ )
+ return architecture, generation
+ return "Unknown RTX", None
+
+
+def _normalize_pci_bus_id(value: str) -> str:
+ match = re.fullmatch(
+ r"(?:([0-9A-Fa-f]{4,8}):)?([0-9A-Fa-f]{2}):([0-9A-Fa-f]{2})\.([0-7])",
+ value.strip(),
+ )
+ if match is None:
+ return value.strip().upper()
+ domain = int(match.group(1) or "0", 16)
+ return f"{domain:04X}:{match.group(2).upper()}:{match.group(3).upper()}.{match.group(4)}"
+
+
+def _cuda_device_identities() -> dict[str, dict[str, Any]]:
+ """Map normalized PCI bus IDs to CUDA ordinals for optional NVENC selection."""
+ try:
+ loader = getattr(ctypes, "WinDLL", ctypes.CDLL)
+ cuda = loader("nvcuda.dll")
+ except (AttributeError, OSError):
+ return {}
+
+ c_int_p = ctypes.POINTER(ctypes.c_int)
+ cuda.cuInit.argtypes = [ctypes.c_uint]
+ cuda.cuInit.restype = ctypes.c_int
+ cuda.cuDeviceGetCount.argtypes = [c_int_p]
+ cuda.cuDeviceGetCount.restype = ctypes.c_int
+ cuda.cuDeviceGet.argtypes = [c_int_p, ctypes.c_int]
+ cuda.cuDeviceGet.restype = ctypes.c_int
+ cuda.cuDeviceGetPCIBusId.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
+ cuda.cuDeviceGetPCIBusId.restype = ctypes.c_int
+ if cuda.cuInit(0) != 0:
+ return {}
+ count = ctypes.c_int()
+ if cuda.cuDeviceGetCount(ctypes.byref(count)) != 0:
+ return {}
+ identities: dict[str, dict[str, Any]] = {}
+ for ordinal in range(max(0, count.value)):
+ device = ctypes.c_int()
+ if cuda.cuDeviceGet(ctypes.byref(device), ordinal) != 0:
+ continue
+ bus_buffer = ctypes.create_string_buffer(32)
+ if cuda.cuDeviceGetPCIBusId(bus_buffer, len(bus_buffer), device.value) != 0:
+ continue
+ identities[_normalize_pci_bus_id(bus_buffer.value.decode("ascii", "replace"))] = {
+ "cuda_ordinal": ordinal,
+ }
+ return identities
+
+
+@lru_cache(maxsize=1)
+def detect_gpus() -> tuple[dict[str, Any], ...]:
+ command = [
+ "nvidia-smi",
+ "--query-gpu=index,uuid,pci.bus_id,name,driver_version,memory.total,compute_cap",
+ "--format=csv,noheader,nounits",
+ ]
+ fallback_command = [
+ "nvidia-smi",
+ "--query-gpu=index,uuid,pci.bus_id,name,driver_version,memory.total",
+ "--format=csv,noheader,nounits",
+ ]
+ try:
+ result = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ used_fallback_query = False
+ if result.returncode:
+ result = subprocess.run(
+ fallback_command, capture_output=True, text=True, timeout=10
+ )
+ used_fallback_query = True
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise RuntimeError(
+ "NVIDIA driver tools are unavailable; an RTX GPU and current driver are required."
+ ) from exc
+ if result.returncode:
+ detail = result.stderr.strip() or result.stdout.strip()
+ message = "nvidia-smi failed while detecting an RTX GPU"
+ raise RuntimeError(f"{message}: {detail}" if detail else f"{message}.")
+ cuda_identities = _cuda_device_identities()
+ devices: list[dict[str, Any]] = []
+ for fallback_index, line in enumerate(result.stdout.splitlines()):
+ parts = [part.strip() for part in line.split(",")]
+ if not parts or not any(parts):
+ continue
+ if len(parts) == 4:
+ legacy_row = True
+ name, driver, memory, capability = parts
+ index, uuid, pci_bus_id = str(fallback_index), f"index:{fallback_index}", ""
+ elif len(parts) == 6 and used_fallback_query:
+ legacy_row = False
+ index, uuid, pci_bus_id, name, driver, memory = parts
+ capability = "unknown"
+ elif len(parts) == 7:
+ legacy_row = False
+ index, uuid, pci_bus_id, name, driver, memory, capability = parts
+ else:
+ name = parts[3] if len(parts) > 3 else parts[0] or "NVIDIA GPU"
+ raise RuntimeError(
+ f"{name} returned incomplete nvidia-smi data; expected name, driver, "
+ "memory, compute capability, UUID, and PCI bus ID."
+ )
+ if any(not value for value in (name, driver, memory)):
+ raise RuntimeError(
+ f"{name or 'NVIDIA GPU'} returned incomplete nvidia-smi data; expected name, "
+ "driver, and memory capacity."
+ )
+ capability = capability or "unknown"
+ try:
+ memory_mb = int(memory)
+ smi_index = int(index)
+ except ValueError as exc:
+ raise RuntimeError(
+ f"{name} reported malformed index or memory capacity through nvidia-smi."
+ ) from exc
+ normalized_pci = _normalize_pci_bus_id(pci_bus_id) if pci_bus_id else ""
+ identity = cuda_identities.get(normalized_pci, {})
+ is_rtx = "RTX" in name.upper()
+ architecture: str | None = None
+ generation: int | None = None
+ compatibility_error = ""
+ if is_rtx:
+ architecture, generation = _classify_rtx_architecture(name, capability)
+ else:
+ compatibility_error = "The device name does not identify an RTX GPU."
+ devices.append(
+ {
+ "index": smi_index,
+ "uuid": uuid,
+ "pci_bus_id": normalized_pci,
+ "name": name,
+ "display_name": name,
+ "driver": driver,
+ "memory_mb": memory_mb,
+ "compute_capability": capability,
+ "architecture": architecture,
+ "generation": generation,
+ "beta": False,
+ "ai_compatible": is_rtx,
+ "compatibility_error": compatibility_error,
+ "cuda_ordinal": (
+ smi_index if legacy_row else identity.get("cuda_ordinal", smi_index)
+ ),
+ }
+ )
+ if not devices:
+ raise RuntimeError("No NVIDIA GPU was detected.")
+ return tuple(devices)
+
+
+def clear_gpu_detection_cache() -> None:
+ detect_gpus.cache_clear()
diff --git a/src/core/gpu_selection.py b/src/core/gpu_selection.py
new file mode 100644
index 0000000..b1fb63b
--- /dev/null
+++ b/src/core/gpu_selection.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import Any
+
+from .gpu_detection import clear_gpu_detection_cache, detect_gpus
+
+
+def gpu_choice_label(gpu: dict[str, Any]) -> str:
+ memory_gib = float(gpu.get("memory_mb", 0)) / 1024
+ location = gpu.get("pci_bus_id") or f"index {gpu.get('index', '?')}"
+ return f"{gpu.get('name', 'NVIDIA GPU')} | {memory_gib:.0f} GB | PCI {location}"
+
+
+def resolve_ai_gpu(gpus: tuple[dict[str, Any], ...], gpu_uuid: str = "auto") -> dict[str, Any]:
+ compatible = [gpu for gpu in gpus if gpu.get("ai_compatible")]
+ if gpu_uuid != "auto":
+ selected = next((gpu for gpu in compatible if gpu.get("uuid") == gpu_uuid), None)
+ if selected is not None:
+ return dict(selected)
+ raise RuntimeError("The selected AI Processing GPU is unavailable or incompatible.")
+ if not compatible:
+ details = "; ".join(
+ str(gpu.get("compatibility_error")) for gpu in gpus if gpu.get("compatibility_error")
+ )
+ message = "No supported NVIDIA RTX GPU was detected."
+ raise RuntimeError(f"{message} {details}" if details else message)
+ return dict(compatible[0])
+
+
+def resolve_runtime_ai_gpu(
+ gpus: tuple[dict[str, Any], ...],
+ runtime_bundle: dict[str, Any],
+ gpu_uuid: str = "auto",
+) -> dict[str, Any]:
+ """Resolve any NVIDIA RTX GPU; native runtimes decide actual feature support."""
+ del runtime_bundle
+ return resolve_ai_gpu(gpus, gpu_uuid)
+
+
+@lru_cache(maxsize=32)
+def _detect_gpu_cached(gpu_uuid: str = "auto") -> dict:
+ return resolve_ai_gpu(detect_gpus(), gpu_uuid)
+
+
+def detect_gpu(gpu_uuid: str = "auto") -> dict:
+ return _detect_gpu_cached(gpu_uuid)
+
+
+def _clear_gpu_detection_cache() -> None:
+ _detect_gpu_cached.cache_clear()
+ clear_gpu_detection_cache()
+
+
+# Publicly named version for the new module boundary.
+clear_gpu_selection_cache = _clear_gpu_detection_cache
+
+
+detect_gpu.cache_clear = _clear_gpu_detection_cache # type: ignore[attr-defined]
diff --git a/src/core/jobs.py b/src/core/jobs.py
new file mode 100644
index 0000000..c71faf5
--- /dev/null
+++ b/src/core/jobs.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import subprocess
+import threading
+from collections import deque
+from contextlib import contextmanager
+from typing import Iterator
+
+
+class Cancelled(RuntimeError):
+ pass
+
+
+class JobController:
+ """Own cancellation state and subprocesses for one render."""
+
+ def __init__(self) -> None:
+ self.cancel = threading.Event()
+ self._lock = threading.Lock()
+ self._processes: list[subprocess.Popen] = []
+
+ def register(self, process: subprocess.Popen) -> None:
+ with self._lock:
+ self._processes.append(process)
+ cancelled = self.cancel.is_set()
+ if cancelled and process.poll() is None:
+ try:
+ process.terminate()
+ except OSError:
+ pass
+
+ def unregister(self, process: subprocess.Popen) -> None:
+ with self._lock:
+ if process in self._processes:
+ self._processes.remove(process)
+
+ def stop(self) -> None:
+ self.cancel.set()
+ self.terminate_processes()
+
+ def terminate_processes(self) -> None:
+ with self._lock:
+ processes = list(self._processes)
+ for process in processes:
+ if process.poll() is None:
+ try:
+ process.terminate()
+ except OSError:
+ pass
+
+
+_RENDER_LOCK = threading.Lock()
+_ACTIVE_LOCK = threading.Lock()
+_ACTIVE: JobController | None = None
+
+
+@contextmanager
+def active_job() -> Iterator[JobController]:
+ """Claim the single GPU render slot and always release its resources."""
+ global _ACTIVE
+ if not _RENDER_LOCK.acquire(blocking=False):
+ raise RuntimeError("Another GPU render is already running.")
+ controller = JobController()
+ with _ACTIVE_LOCK:
+ _ACTIVE = controller
+ try:
+ yield controller
+ finally:
+ controller.terminate_processes()
+ with _ACTIVE_LOCK:
+ if _ACTIVE is controller:
+ _ACTIVE = None
+ _RENDER_LOCK.release()
+
+
+def cancel_active_job() -> str:
+ with _ACTIVE_LOCK:
+ controller = _ACTIVE
+ if controller is None:
+ return "No render is running."
+ controller.stop()
+ return "Stop requested; incomplete output will be removed and completed batch files retained."
+
+
+def drain_text(stream, lines: list[str]) -> None:
+ for raw in iter(stream.readline, b""):
+ lines.append(raw.decode("utf-8", "replace").rstrip())
+
+
+class BoundedLogBuffer:
+ """Keep diagnostic evidence and a bounded tail instead of every frame log."""
+
+ _IMPORTANT = (
+ "profile applied",
+ "model preset",
+ "DLSS 5 add-on",
+ "carrier ready",
+ "stream source",
+ "optimal settings",
+ "complete:",
+ "failed",
+ "error",
+ "exception",
+ )
+
+ def __init__(self, max_tail: int = 500, max_important: int = 100) -> None:
+ self._tail: deque[str] = deque(maxlen=max_tail)
+ self._important: list[str] = []
+ self._max_important = max_important
+ self._seen = 0
+ self._lock = threading.Lock()
+
+ def append(self, line: str) -> None:
+ with self._lock:
+ self._seen += 1
+ self._tail.append(line)
+ lowered = line.casefold()
+ if (
+ len(self._important) < self._max_important
+ and any(marker.casefold() in lowered for marker in self._IMPORTANT)
+ ):
+ self._important.append(line)
+
+ def snapshot(self) -> list[str]:
+ with self._lock:
+ important = list(self._important)
+ tail = list(self._tail)
+ seen: set[str] = set()
+ return [line for line in [*important, *tail] if not (line in seen or seen.add(line))]
+
+ @property
+ def dropped_lines(self) -> int:
+ with self._lock:
+ return max(0, self._seen - len(self._tail))
+
+
+def drain_bounded_text(stream, buffer: BoundedLogBuffer) -> None:
+ for raw in iter(stream.readline, b""):
+ buffer.append(raw.decode("utf-8", "replace").rstrip())
diff --git a/src/naming.py b/src/core/naming.py
similarity index 100%
rename from src/naming.py
rename to src/core/naming.py
diff --git a/src/core/paths.py b/src/core/paths.py
new file mode 100644
index 0000000..cb14a8b
--- /dev/null
+++ b/src/core/paths.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+RUNTIME = ROOT / "bin" / "runtime"
+HOST_DIR = RUNTIME / "host"
+DLSS_DIR = RUNTIME / "dlss"
+DLSSG_DIR = RUNTIME / "dlssg"
+FFMPEG = ROOT / "bin" / "ffmpeg" / "bin" / "ffmpeg.exe"
+FFPROBE = ROOT / "bin" / "ffmpeg" / "bin" / "ffprobe.exe"
+WORKER = HOST_DIR / "nvngx.dll" # Signed-snippet caller checks require this image name.
+ADDON = HOST_DIR / "renodx-dlss5.addon64"
+HOST_DXGI = HOST_DIR / "dxgi.dll"
+RESHADE_LOG = HOST_DIR / "ReShade.log"
+DLSS_SUPERRES = DLSS_DIR / "nvngx_dlss.dll"
+# The RenoDX add-on only discovers the signed NR runtime next to itself in
+# host/, so NEURAL_RUNTIME lives there even though it is a DLSS component.
+NEURAL_RUNTIME = HOST_DIR / "nvngx_dlssnr.dll"
+OUTPUTS = ROOT / "outputs"
+LOGS = ROOT / "logs"
+JOBS = ROOT / "jobs"
+CONFIG_DIR = ROOT / "config"
+CONFIG_PATH = CONFIG_DIR / "config.ini"
diff --git a/src/runtime.py b/src/core/runtime.py
similarity index 50%
rename from src/runtime.py
rename to src/core/runtime.py
index a18c8d2..8f71a12 100644
--- a/src/runtime.py
+++ b/src/core/runtime.py
@@ -1,43 +1,172 @@
from __future__ import annotations
-import hashlib
+import atexit
import json
-import ctypes
+import math
+import mmap
import re
import struct
import subprocess
import threading
import time
-from collections import deque
-from contextlib import contextmanager
-from functools import lru_cache
+from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any
import cv2
import numpy as np
+from .gpu_detection import detect_gpus
+from .gpu_selection import resolve_runtime_ai_gpu
+from .jobs import BoundedLogBuffer, Cancelled, JobController, drain_bounded_text
+from .paths import ADDON, DLSS_SUPERRES, FFMPEG, FFPROBE, HOST_DIR, HOST_DXGI, LOGS, NEURAL_RUNTIME, RESHADE_LOG, RUNTIME, WORKER
-ROOT = Path(__file__).resolve().parents[1]
-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 = (
- "D5ADF82EB44B065F4C590AC91FE824BAB07AFEA0EB9F994BDE936710C8593952"
-)
-EXPECTED_AMPERE_NEURAL_SHA256 = (
- "6EB209E764F39872625DEBD6ABAF45E2BB6322F6F270F781F70C059AE30B3927"
+
+# Shared DLSS Neural Rendering controls and sizing. These are feature-neutral and
+# used by both Image and Video processing.
+NR_PRESETS = {
+ "Default": 0,
+ "Preset #1": 1,
+ "Preset #2": 2,
+ "Preset #3": 3,
+}
+
+NR_STYLES = {
+ "Default": 0,
+ "Natural": 1,
+ "Cinematic": 2,
+}
+
+DLSS_MODEL_PRESETS = {
+ "Default": 0,
+ "J": 10,
+ "K": 11,
+ "L": 12,
+ "M": 13,
+}
+
+UPSCALING_MODES = {
+ 1.0: {"label": "1× (DLAA / native)", "name": "DLAA", "perf_quality": 5},
+ 1.5: {"label": "1.5× (Quality)", "name": "Quality", "perf_quality": 2},
+ 1.724: {"label": "1.724× (Balanced)", "name": "Balanced", "perf_quality": 1},
+ 2.0: {"label": "2× (Performance)", "name": "Performance", "perf_quality": 0},
+ 3.0: {
+ "label": "3× (Ultra Performance)",
+ "name": "Ultra Performance",
+ "perf_quality": 3,
+ },
+}
+UPSCALING_CHOICES = tuple(
+ (mode["label"], factor) for factor, mode in UPSCALING_MODES.items()
)
-_FINGERPRINT_LOCK = threading.Lock()
-_FINGERPRINT_CACHE: dict[tuple[str, int, int], str] = {}
+def resolve_upscaling_mode(raw_factor: float) -> tuple[float, dict[str, str | int]]:
+ try:
+ factor = float(raw_factor)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ "Upscaling factor must be one of the supported NVIDIA DLSS modes."
+ ) from exc
+ if not math.isfinite(factor):
+ raise ValueError("Upscaling factor must be one of the supported NVIDIA DLSS modes.")
+ for supported, mode in UPSCALING_MODES.items():
+ if math.isclose(factor, supported, rel_tol=0.0, abs_tol=1e-9):
+ return supported, mode
+ choices = ", ".join(f"{factor:g}×" for factor in UPSCALING_MODES)
+ raise ValueError(f"Unsupported upscaling factor {factor:g}×. Choose one of: {choices}.")
+
+
+def _nearest_even(value: float) -> int:
+ return max(2, int(math.floor(value / 2.0 + 0.5)) * 2)
+
+
+def resolve_output_size(width: int, height: int, factor: float) -> tuple[int, int]:
+ factor, _ = resolve_upscaling_mode(factor)
+ output_width = _nearest_even(int(width) * factor)
+ output_height = _nearest_even(int(height) * factor)
+ long_edge = max(output_width, output_height)
+ short_edge = min(output_width, output_height)
+ if long_edge > 7680 or short_edge > 4320:
+ valid = [
+ candidate
+ for candidate in UPSCALING_MODES
+ if max(_nearest_even(width * candidate), _nearest_even(height * candidate)) <= 7680
+ and min(_nearest_even(width * candidate), _nearest_even(height * candidate))
+ <= 4320
+ ]
+ recommendation = max(valid) if valid else None
+ hint = (
+ f" Choose {recommendation:g}× or lower for this video."
+ if recommendation is not None
+ else " The source already exceeds the supported 8K boundary."
+ )
+ raise ValueError(
+ f"The requested {output_width}×{output_height} output exceeds the supported "
+ f"7680×4320 boundary.{hint}"
+ )
+ return output_width, output_height
+
+def resolve_native_settings(options: Any) -> dict[str, int | float]:
+ """Validate public NR controls and translate them to the worker protocol."""
+ try:
+ preset = NR_PRESETS[options.nr_preset]
+ except KeyError as exc:
+ choices = ", ".join(NR_PRESETS)
+ raise ValueError(
+ f"Unknown NR Preset: {options.nr_preset!r}. Choose one of: {choices}."
+ ) from exc
+
+ try:
+ style = NR_STYLES[options.nr_style]
+ except KeyError as exc:
+ choices = ", ".join(NR_STYLES)
+ raise ValueError(
+ f"Unknown NR Style: {options.nr_style!r}. Choose one of: {choices}."
+ ) from exc
+
+ try:
+ model_preset = DLSS_MODEL_PRESETS[options.dlss_model_preset]
+ except KeyError as exc:
+ choices = ", ".join(DLSS_MODEL_PRESETS)
+ raise ValueError(
+ f"Unknown DLSS Model Preset: {options.dlss_model_preset!r}. "
+ f"Choose one of: {choices}."
+ ) from exc
+
+ controls = {
+ "NR Intensity": (options.nr_intensity, 0.0, 2.0),
+ "Local Tone Strength": (options.local_tone_strength, 0.0, 2.0),
+ "Local Structure Strength": (options.local_structure_strength, 0.0, 2.0),
+ "Skin Structure Strength": (options.skin_structure_strength, -1.0, 2.0),
+ }
+ validated: dict[str, float] = {}
+ for label, (raw_value, minimum, maximum) in controls.items():
+ try:
+ value = float(raw_value)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ f"{label} must be a number between {minimum:g} and {maximum:g}."
+ ) from exc
+ if not math.isfinite(value) or not minimum <= value <= maximum:
+ 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": int(options.automatic_mask),
+ "ui_correction": 0,
+ "intensity": validated["NR Intensity"],
+ "local_tone": validated["Local Tone Strength"],
+ "local_structure": validated["Local Structure Strength"],
+ "skin_structure": validated["Skin Structure Strength"],
+ "dlss_model_preset": model_preset,
+ }
VIDEO_MAGIC = 0x34563544
SETUP_MAGIC = 0x34505553
@@ -46,65 +175,26 @@ OUT_MAGIC = 0x3154554F
VIDEO_HEADER_FORMAT = "<14I4f"
SETUP_RESPONSE_FORMAT = "<12I"
-
-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."""
+ """Return runtime component identities for diagnostics without hash locking."""
addon = addon_path or ADDON
neural = neural_path or NEURAL_RUNTIME
- addon_hash = _file_sha256(addon)
- neural_hash = _file_sha256(neural)
- worker_hash = _file_sha256(WORKER)
- 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.70",
- "release": "RenoDX DLSS5 v4.70",
+ "version": "unlocked",
+ "release": "RenoDX DLSS5 runtime (unlocked)",
},
"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",
+ "version": "unlocked",
+ "release": "DLSS NR runtime (unlocked)",
},
"worker": {
"path": str(WORKER.resolve()),
- "sha256": worker_hash,
},
}
@@ -112,18 +202,9 @@ def inspect_runtime_bundle(
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.70 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
+ """Return runtime metadata without generation, version, or hash compatibility locks."""
+ del gpu
+ return bundle or inspect_runtime_bundle()
def classify_worker_failure(
@@ -141,7 +222,7 @@ def classify_worker_failure(
"evaluate raised 0xC0000005" in evidence
or "feature 18 evaluate raised an exception" in evidence
)
- generation = int(gpu.get("generation", 0))
+ generation = int(gpu.get("generation") or 0)
if access_violation and generation == 30:
summary = (
"DLSS 5 feature 18 hit access violation 0xC0000005 on the experimental "
@@ -149,12 +230,10 @@ def classify_worker_failure(
"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.70/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."
- )
+ summary += (
+ " The native runtime rejected or crashed on this RTX 30-series system. "
+ "Update the NVIDIA driver or try a different compatible runtime build."
+ )
elif access_violation:
summary = (
f"DLSS 5 feature 18 raised access violation 0xC0000005 before frame {frame_index} "
@@ -166,13 +245,11 @@ def classify_worker_failure(
"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}",
+ f"RenoDX add-on: {runtime_bundle.get('addon', {}).get('path', 'unavailable')}",
+ f"DLSSNR runtime: {runtime_bundle.get('neural_runtime', {}).get('path', 'unavailable')}",
]
if worker_logs:
details.append("Worker log:\n" + "\n".join(worker_logs[-60:]))
@@ -213,139 +290,6 @@ def write_failure_report(
report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
return report_path.resolve()
-
-class Cancelled(RuntimeError):
- pass
-
-
-class JobController:
- """Own cancellation state and subprocesses for one render."""
-
- def __init__(self) -> None:
- self.cancel = threading.Event()
- self._lock = threading.Lock()
- self._processes: list[subprocess.Popen] = []
-
- def register(self, process: subprocess.Popen) -> None:
- with self._lock:
- self._processes.append(process)
- cancelled = self.cancel.is_set()
- if cancelled and process.poll() is None:
- try:
- process.terminate()
- except OSError:
- pass
-
- def unregister(self, process: subprocess.Popen) -> None:
- with self._lock:
- if process in self._processes:
- self._processes.remove(process)
-
- def stop(self) -> None:
- self.cancel.set()
- self.terminate_processes()
-
- def terminate_processes(self) -> None:
- with self._lock:
- processes = list(self._processes)
- for process in processes:
- if process.poll() is None:
- try:
- process.terminate()
- except OSError:
- pass
-
-
-_RENDER_LOCK = threading.Lock()
-_ACTIVE_LOCK = threading.Lock()
-_ACTIVE: JobController | None = None
-
-
-@contextmanager
-def active_job() -> Iterator[JobController]:
- """Claim the single GPU render slot and always release its resources."""
- global _ACTIVE
- if not _RENDER_LOCK.acquire(blocking=False):
- raise RuntimeError("Another GPU render is already running.")
- controller = JobController()
- with _ACTIVE_LOCK:
- _ACTIVE = controller
- try:
- yield controller
- finally:
- controller.terminate_processes()
- with _ACTIVE_LOCK:
- if _ACTIVE is controller:
- _ACTIVE = None
- _RENDER_LOCK.release()
-
-
-def cancel_active_job() -> str:
- with _ACTIVE_LOCK:
- controller = _ACTIVE
- if controller is None:
- return "No render is running."
- controller.stop()
- return "Stop requested; incomplete output will be removed and completed batch files retained."
-
-
-def drain_text(stream, lines: list[str]) -> None:
- for raw in iter(stream.readline, b""):
- lines.append(raw.decode("utf-8", "replace").rstrip())
-
-
-class BoundedLogBuffer:
- """Keep diagnostic evidence and a bounded tail instead of every frame log."""
-
- _IMPORTANT = (
- "profile applied",
- "model preset",
- "DLSS 5 add-on",
- "carrier ready",
- "stream source",
- "optimal settings",
- "complete:",
- "failed",
- "error",
- "exception",
- )
-
- def __init__(self, max_tail: int = 500, max_important: int = 100) -> None:
- self._tail: deque[str] = deque(maxlen=max_tail)
- self._important: list[str] = []
- self._max_important = max_important
- self._seen = 0
- self._lock = threading.Lock()
-
- def append(self, line: str) -> None:
- with self._lock:
- self._seen += 1
- self._tail.append(line)
- lowered = line.casefold()
- if (
- len(self._important) < self._max_important
- and any(marker.casefold() in lowered for marker in self._IMPORTANT)
- ):
- self._important.append(line)
-
- def snapshot(self) -> list[str]:
- with self._lock:
- important = list(self._important)
- tail = list(self._tail)
- seen: set[str] = set()
- return [line for line in [*important, *tail] if not (line in seen or seen.add(line))]
-
- @property
- def dropped_lines(self) -> int:
- with self._lock:
- return max(0, self._seen - len(self._tail))
-
-
-def drain_bounded_text(stream, buffer: BoundedLogBuffer) -> None:
- for raw in iter(stream.readline, b""):
- buffer.append(raw.decode("utf-8", "replace").rstrip())
-
-
def resize_fit(rgba: np.ndarray, width: int, height: int) -> np.ndarray:
source_height, source_width = rgba.shape[:2]
if source_width == width and source_height == height:
@@ -371,269 +315,38 @@ def rotate_frame(frame: np.ndarray, rotation: int) -> np.ndarray:
return np.ascontiguousarray(np.rot90(frame, 1))
return frame
-
-_RTX_ARCHITECTURES: dict[tuple[int, int], tuple[str, int]] = {
- (8, 0): ("Ampere", 30),
- (8, 6): ("Ampere", 30),
- (8, 7): ("Ampere", 30),
- (8, 8): ("Ampere", 30),
- (8, 9): ("Ada", 40),
- (10, 0): ("Blackwell", 50),
- (10, 3): ("Blackwell", 50),
- (11, 0): ("Blackwell", 50),
- (12, 0): ("Blackwell", 50),
- (12, 1): ("Blackwell", 50),
-}
-
-
-def _classify_rtx_architecture(name: str, capability: str) -> tuple[str, int]:
- match = re.fullmatch(r"(\d+)\.(\d+)", capability.strip())
- if match is None:
- raise RuntimeError(
- f"{name} reported malformed compute capability {capability!r}; "
- "a current NVIDIA driver is required."
- )
- compute_capability = (int(match.group(1)), int(match.group(2)))
- classified = _RTX_ARCHITECTURES.get(compute_capability)
- if classified is None:
- raise RuntimeError(
- f"{name} (compute capability {capability}) is not a supported RTX architecture. "
- "This build supports Ampere, Ada, and Blackwell RTX GPUs only."
- )
- return classified
-
-
-def _normalize_pci_bus_id(value: str) -> str:
- match = re.fullmatch(
- r"(?:([0-9A-Fa-f]{4,8}):)?([0-9A-Fa-f]{2}):([0-9A-Fa-f]{2})\.([0-7])",
- value.strip(),
- )
- if match is None:
- return value.strip().upper()
- domain = int(match.group(1) or "0", 16)
- return f"{domain:04X}:{match.group(2).upper()}:{match.group(3).upper()}.{match.group(4)}"
-
-
-def _cuda_device_identities() -> dict[str, dict[str, Any]]:
- """Map normalized PCI bus IDs to the CUDA ordinal and Windows DXGI LUID."""
- try:
- loader = getattr(ctypes, "WinDLL", ctypes.CDLL)
- cuda = loader("nvcuda.dll")
- except (AttributeError, OSError):
- return {}
-
- c_int_p = ctypes.POINTER(ctypes.c_int)
- cuda.cuInit.argtypes = [ctypes.c_uint]
- cuda.cuInit.restype = ctypes.c_int
- cuda.cuDeviceGetCount.argtypes = [c_int_p]
- cuda.cuDeviceGetCount.restype = ctypes.c_int
- cuda.cuDeviceGet.argtypes = [c_int_p, ctypes.c_int]
- cuda.cuDeviceGet.restype = ctypes.c_int
- cuda.cuDeviceGetPCIBusId.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
- cuda.cuDeviceGetPCIBusId.restype = ctypes.c_int
- get_luid = getattr(cuda, "cuDeviceGetLuid", None)
- if get_luid is not None:
- get_luid.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint), ctypes.c_int]
- get_luid.restype = ctypes.c_int
-
- if cuda.cuInit(0) != 0:
- return {}
- count = ctypes.c_int()
- if cuda.cuDeviceGetCount(ctypes.byref(count)) != 0:
- return {}
- identities: dict[str, dict[str, Any]] = {}
- for ordinal in range(max(0, count.value)):
- device = ctypes.c_int()
- if cuda.cuDeviceGet(ctypes.byref(device), ordinal) != 0:
- continue
- bus_buffer = ctypes.create_string_buffer(32)
- if cuda.cuDeviceGetPCIBusId(bus_buffer, len(bus_buffer), device.value) != 0:
- continue
- luid_hex: str | None = None
- if get_luid is not None:
- luid = (ctypes.c_ubyte * 8)()
- node_mask = ctypes.c_uint()
- if get_luid(luid, ctypes.byref(node_mask), device.value) == 0:
- luid_hex = bytes(luid).hex()
- identities[_normalize_pci_bus_id(bus_buffer.value.decode("ascii", "replace"))] = {
- "cuda_ordinal": ordinal,
- "adapter_luid": luid_hex,
- }
- return identities
-
-
-@lru_cache(maxsize=1)
-def detect_gpus() -> tuple[dict[str, Any], ...]:
- command = [
- "nvidia-smi",
- "--query-gpu=index,uuid,pci.bus_id,name,driver_version,memory.total,compute_cap",
- "--format=csv,noheader,nounits",
- ]
- try:
- result = subprocess.run(command, capture_output=True, text=True, timeout=10)
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise RuntimeError(
- "NVIDIA driver tools are unavailable; an RTX GPU and current driver are required."
- ) from exc
- if result.returncode:
- detail = result.stderr.strip() or result.stdout.strip()
- message = "nvidia-smi failed while detecting an RTX GPU"
- raise RuntimeError(f"{message}: {detail}" if detail else f"{message}.")
- cuda_identities = _cuda_device_identities()
- devices: list[dict[str, Any]] = []
- for fallback_index, line in enumerate(result.stdout.splitlines()):
- parts = [part.strip() for part in line.split(",")]
- if not parts or not any(parts):
- continue
- # Four-column rows preserve compatibility with isolated detector tests and
- # older nvidia-smi builds; production drivers use the seven-column query.
- if len(parts) == 4:
- legacy_row = True
- name, driver, memory, capability = parts
- index, uuid, pci_bus_id = str(fallback_index), f"index:{fallback_index}", ""
- elif len(parts) == 7:
- legacy_row = False
- index, uuid, pci_bus_id, name, driver, memory, capability = parts
- else:
- name = parts[3] if len(parts) > 3 else parts[0] or "NVIDIA GPU"
- raise RuntimeError(
- f"{name} returned incomplete nvidia-smi data; expected name, driver, "
- "memory, compute capability, UUID, and PCI bus ID."
- )
- if any(not value for value in (name, driver, memory, capability)):
- raise RuntimeError(
- f"{name or 'NVIDIA GPU'} returned incomplete nvidia-smi data; expected name, "
- "driver, memory, and compute capability."
- )
- try:
- memory_mb = int(memory)
- smi_index = int(index)
- except ValueError as exc:
- raise RuntimeError(
- f"{name} reported malformed index or memory capacity through nvidia-smi."
- ) from exc
- normalized_pci = _normalize_pci_bus_id(pci_bus_id) if pci_bus_id else ""
- identity = cuda_identities.get(normalized_pci, {})
- architecture: str | None = None
- generation: int | None = None
- compatibility_error = ""
- if "RTX" in name.upper():
- try:
- architecture, generation = _classify_rtx_architecture(name, capability)
- except RuntimeError as exc:
- compatibility_error = str(exc)
- else:
- compatibility_error = "The device name does not identify an RTX GPU."
- devices.append(
- {
- "index": smi_index,
- "uuid": uuid,
- "pci_bus_id": normalized_pci,
- "name": name,
- "display_name": (
- f"{name} (experimental RTX 30 path; may be very slow)"
- if generation == 30
- else name
- ),
- "driver": driver,
- "memory_mb": memory_mb,
- "compute_capability": capability,
- "architecture": architecture,
- "generation": generation,
- "beta": generation == 30,
- "ai_compatible": generation is not None,
- "compatibility_error": compatibility_error,
- "cuda_ordinal": identity.get("cuda_ordinal")
- if not legacy_row
- else smi_index,
- "adapter_luid": identity.get("adapter_luid"),
- }
- )
- if not devices:
- raise RuntimeError("No NVIDIA GPU was detected.")
- return tuple(devices)
-
-
-def gpu_choice_label(gpu: dict[str, Any]) -> str:
- memory_gib = float(gpu.get("memory_mb", 0)) / 1024
- location = gpu.get("pci_bus_id") or f"index {gpu.get('index', '?')}"
- return f"{gpu.get('name', 'NVIDIA GPU')} | {memory_gib:.0f} GB | PCI {location}"
-
-
-def resolve_ai_gpu(gpus: tuple[dict[str, Any], ...], gpu_uuid: str = "auto") -> dict[str, Any]:
- compatible = [gpu for gpu in gpus if gpu.get("ai_compatible")]
- if gpu_uuid != "auto":
- selected = next((gpu for gpu in compatible if gpu.get("uuid") == gpu_uuid), None)
- if selected is not None:
- return dict(selected)
- raise RuntimeError("The selected AI Processing GPU is unavailable or incompatible.")
- if not compatible:
- details = "; ".join(
- str(gpu.get("compatibility_error")) for gpu in gpus if gpu.get("compatibility_error")
- )
- message = "No supported NVIDIA RTX GPU was detected."
- raise RuntimeError(f"{message} {details}" if details else message)
- return dict(compatible[0])
-
-
-def resolve_runtime_ai_gpu(
- gpus: tuple[dict[str, Any], ...],
- runtime_bundle: dict[str, Any],
- gpu_uuid: str = "auto",
-) -> dict[str, Any]:
- """Resolve an AI device and enforce architecture-specific runtime pairing."""
- candidates = [
- gpu
- for gpu in gpus
- if gpu.get("ai_compatible") and gpu.get("adapter_luid")
+def validate_runtime_files() -> None:
+ # Old flat bin/runtime/ layout (pre host/dlss/dlssg split). Fail fast with a
+ # clear message instead of auto-migrating, so a half-moved tree can't silently
+ # run with mismatched NGX/add-on components.
+ stale = [
+ RUNTIME / "nvngx.dll",
+ RUNTIME / "dxgi.dll",
+ RUNTIME / "renodx-dlss5.addon64",
+ RUNTIME / "ReShade.ini",
+ RUNTIME / "nvngx_dlss.dll",
+ RUNTIME / "nvngx_dlssnr.dll",
+ RUNTIME / "frame_interpolation",
]
- if gpu_uuid != "auto":
- candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]
- if not candidates:
- raise RuntimeError("The selected AI Processing GPU is unavailable or incompatible.")
- errors: list[str] = []
- for candidate in candidates:
- try:
- validate_gpu_runtime(candidate, runtime_bundle)
- except RuntimeError as exc:
- errors.append(str(exc))
- continue
- return dict(candidate)
- if errors:
- raise RuntimeError("No compatible AI Processing GPU/runtime pair is available. " + " ".join(errors))
- if not candidates:
+ leftovers = [str(path) for path in stale if path.exists()]
+ if leftovers:
raise RuntimeError(
- "No compatible AI Processing GPU could be mapped to a Windows adapter LUID. "
- "Update or reinstall the NVIDIA display driver."
+ "The portable runtime still uses the old flat bin/runtime/ layout. "
+ "Move host files (nvngx.dll, dxgi.dll, renodx-dlss5.addon64, ReShade.ini, "
+ "nvngx_dlssnr.dll) to bin/runtime/host/, nvngx_dlss.dll to "
+ "bin/runtime/dlss/, and frame_interpolation/dlssg/* to bin/runtime/dlssg/.\n"
+ + "\n".join(leftovers)
)
- return resolve_ai_gpu(gpus, gpu_uuid)
-
-
-@lru_cache(maxsize=32)
-def _detect_gpu_cached(gpu_uuid: str = "auto") -> dict:
- return resolve_ai_gpu(detect_gpus(), gpu_uuid)
-
-
-def detect_gpu(gpu_uuid: str = "auto") -> dict:
- return _detect_gpu_cached(gpu_uuid)
-
-
-def _clear_gpu_detection_cache() -> None:
- _detect_gpu_cached.cache_clear()
- detect_gpus.cache_clear()
-
-
-detect_gpu.cache_clear = _clear_gpu_detection_cache # type: ignore[attr-defined]
-
-
-def validate_runtime_files() -> None:
+ # Note: ReShade.ini is not required here. The worker rewrites every NR key
+ # into the host's ReShade.ini on each run (and heals EnableHooks), so the
+ # file is runtime state that is recreated when missing.
required = [
FFMPEG,
FFPROBE,
WORKER,
- RUNTIME / "dxgi.dll",
+ HOST_DXGI,
ADDON,
- RUNTIME / "nvngx_dlss.dll",
+ DLSS_SUPERRES,
NEURAL_RUNTIME,
]
missing = [str(path) for path in required if not path.exists()]
@@ -695,7 +408,7 @@ class DLSSFrameSession:
self.native_settings = native_settings
self.gpu = gpu
self.runtime_bundle = runtime_bundle
- reshade_log_path = RUNTIME / "ReShade.log"
+ reshade_log_path = RESHADE_LOG
self._reshade_log_baseline_size = 0
self._reshade_log_baseline_tail = b""
if reshade_log_path.exists():
@@ -706,11 +419,9 @@ class DLSSFrameSession:
self._reshade_log_baseline_tail = stream.read(tail_size)
creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
worker_command = [str(WORKER), "--video"]
- if gpu.get("adapter_luid"):
- worker_command.extend(["--adapter-luid", str(gpu["adapter_luid"])])
self.worker = subprocess.Popen(
worker_command,
- cwd=RUNTIME,
+ cwd=HOST_DIR,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
@@ -820,7 +531,7 @@ class DLSSFrameSession:
def reshade_log_text(self) -> str:
"""Return only ReShade output created during this worker session."""
- path = RUNTIME / "ReShade.log"
+ path = RESHADE_LOG
if not path.exists():
return ""
with path.open("rb") as stream:
@@ -939,7 +650,7 @@ 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_path = RESHADE_LOG
reshade_log = (
reshade_log_path.read_text(encoding="utf-8", errors="replace")
if reshade_log_path.exists()
@@ -980,3 +691,116 @@ def verify_feature_18(
or "NR upscaling fell back" in line
],
}
+
+@dataclass(slots=True)
+class PreparedRuntime:
+ """Reusable, source-independent state prepared once for this process."""
+
+ gpu: dict[str, Any]
+ gpus: tuple[dict[str, Any], ...]
+ runtime_bundle: dict[str, Any]
+ encoder_inventory: dict[str, bool]
+ warmed_files: tuple[str, ...]
+ _mappings: list[mmap.mmap] = field(default_factory=list, repr=False)
+
+ def close(self) -> None:
+ while self._mappings:
+ mapping = self._mappings.pop()
+ try:
+ mapping.close()
+ except (BufferError, OSError):
+ pass
+
+
+_PREPARE_LOCK = threading.Lock()
+_PREPARED: PreparedRuntime | None = None
+
+
+def _warm_mapping(path: Path) -> mmap.mmap | None:
+ if not path.is_file() or path.stat().st_size == 0:
+ return None
+ with path.open("rb") as stream:
+ mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)
+ # Touch regularly spaced pages. Sequential hashing already warms the largest
+ # model; this also covers un-hashed loader and FFmpeg components.
+ checksum = 0
+ for offset in range(0, len(mapping), 64 * 1024):
+ checksum ^= mapping[offset]
+ checksum ^= mapping[-1]
+ del checksum
+ return mapping
+
+
+def _encoder_inventory() -> dict[str, bool]:
+ result = subprocess.run(
+ [str(FFMPEG), "-hide_banner", "-encoders"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if result.returncode:
+ raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")
+ output = result.stdout
+ return {
+ "h264_nvenc": "h264_nvenc" in output,
+ "hevc_nvenc": "hevc_nvenc" in output,
+ "av1_nvenc": "av1_nvenc" in output,
+ "prores_ks": "prores_ks" in output,
+ }
+
+def prepare_runtime() -> PreparedRuntime:
+ """Prepare all reusable runtime state before UI launch or first conversion."""
+ global _PREPARED
+ if _PREPARED is not None:
+ return _PREPARED
+ with _PREPARE_LOCK:
+ if _PREPARED is not None:
+ return _PREPARED
+
+ validate_runtime_files()
+ gpus = detect_gpus()
+ runtime_bundle = inspect_runtime_bundle()
+ gpu = resolve_runtime_ai_gpu(gpus, runtime_bundle)
+ inventory = _encoder_inventory()
+
+ paths = (
+ WORKER,
+ HOST_DXGI,
+ ADDON,
+ DLSS_SUPERRES,
+ NEURAL_RUNTIME,
+ FFMPEG,
+ FFPROBE,
+ )
+ mappings: list[mmap.mmap] = []
+ try:
+ for path in paths:
+ mapping = _warm_mapping(path)
+ if mapping is not None:
+ mappings.append(mapping)
+ except Exception:
+ for mapping in mappings:
+ mapping.close()
+ raise
+
+ _PREPARED = PreparedRuntime(
+ gpu=dict(gpu),
+ gpus=tuple(dict(device) for device in gpus),
+ runtime_bundle=runtime_bundle,
+ encoder_inventory=inventory,
+ warmed_files=tuple(str(path.resolve()) for path in paths),
+ _mappings=mappings,
+ )
+ return _PREPARED
+
+
+def close_prepared_runtime() -> None:
+ global _PREPARED
+ with _PREPARE_LOCK:
+ prepared = _PREPARED
+ _PREPARED = None
+ if prepared is not None:
+ prepared.close()
+
+atexit.register(close_prepared_runtime)
diff --git a/src/core/terminal.py b/src/core/terminal.py
new file mode 100644
index 0000000..0d9b012
--- /dev/null
+++ b/src/core/terminal.py
@@ -0,0 +1,490 @@
+from __future__ import annotations
+
+import atexit
+import ctypes
+from ctypes import wintypes
+import io
+import logging
+import os
+import shutil
+import sys
+import threading
+import time
+import warnings
+import webbrowser
+from pathlib import Path
+
+
+GITHUB_URL = "https://github.com/Merserk/dlss5-visual-enhancer"
+AUTHOR_NAME = "Merserk"
+
+# Palette:
+# Left (0%): #0286C3 -> RGB(2, 134, 195)
+# 63%: #0FB881 -> RGB(15, 184, 129)
+# Right (100%): #079E6E -> RGB(7, 158, 110)
+C_LEFT = (2, 134, 195)
+C_MID = (15, 184, 129)
+C_RIGHT = (7, 158, 110)
+
+CHEVRON = [
+ " ███ ",
+ "░░░███ ",
+ " ░░░███ ",
+ " ░░░███",
+ " ███░ ",
+ " ███░ ",
+ " ███░ ",
+ "░░░ ",
+]
+CHAR_D = [
+ "█████████ ",
+ "░░███░░░░██",
+ " ░███ ░░██",
+ " ░███ ░██",
+ " ░███ ░░██",
+ " ░███░░░░██",
+ " █████████ ",
+ " ░░░░░░░░░",
+]
+CHAR_L = [
+ "█████ ",
+ "░░███ ",
+ " ░███ ",
+ " ░███ ",
+ " ░███ █",
+ " ░███ ██",
+ " ████████",
+ " ░░░░░░░",
+]
+CHAR_S = [
+ " █████████ ",
+ "███░░░░░███",
+ "░███░░░ ░░░",
+ " ░░███████ ",
+ " ░░░░░███",
+ "███░░ ███",
+ "░░█████████",
+ " ░░░░░░░░░",
+]
+CHAR_5 = [
+ "██████████",
+ "░░███░░░░░",
+ " ░████████",
+ " ░░░░░░░███",
+ " ░███",
+ "███░░ ███",
+ "░░█████████",
+ " ░░░░░░░░░",
+]
+
+
+def get_gradient_rgb(t: float) -> tuple[int, int, int]:
+ """Interpolate RGB color according to the 90deg linear gradient."""
+ t = max(0.0, min(1.0, float(t)))
+ if t <= 0.63:
+ st = t / 0.63
+ r = int(C_LEFT[0] + (C_MID[0] - C_LEFT[0]) * st)
+ g = int(C_LEFT[1] + (C_MID[1] - C_LEFT[1]) * st)
+ b = int(C_LEFT[2] + (C_MID[2] - C_LEFT[2]) * st)
+ else:
+ st = (t - 0.63) / 0.37
+ r = int(C_MID[0] + (C_RIGHT[0] - C_MID[0]) * st)
+ g = int(C_MID[1] + (C_RIGHT[1] - C_MID[1]) * st)
+ b = int(C_MID[2] + (C_RIGHT[2] - C_MID[2]) * st)
+ return (max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)))
+
+
+def colorize_text(text: str, t_start: float = 0.0, t_end: float = 1.0, bold: bool = False) -> str:
+ """Colorize a single line with gradient based on character column."""
+ res = []
+ n = max(1, len(text) - 1)
+ for i, ch in enumerate(text):
+ if ch == " ":
+ res.append(" ")
+ else:
+ t = t_start + (t_end - t_start) * (i / n)
+ r, g, b = get_gradient_rgb(t)
+ if bold:
+ res.append(f"\033[1;38;2;{r};{g};{b}m{ch}\033[0m")
+ else:
+ res.append(f"\033[38;2;{r};{g};{b}m{ch}\033[0m")
+ return "".join(res)
+
+
+class FileLoggerStream:
+ """Redirects stdout/stderr cleanly to a log file instead of terminal.
+
+ Implements the minimal file-like API expected by uvicorn/click/gradio
+ (isatty, fileno, reconfigure, encoding) so `sys.stdout.isatty()` etc.
+ do not crash after `sys.stdout` is replaced.
+ """
+
+ def __init__(self, log_path: Path):
+ self.log_path = log_path
+ self._lock = threading.Lock()
+ self.encoding = "utf-8"
+ self.errors = "replace"
+ self._closed = False
+
+ def write(self, s: str) -> int:
+ if not s:
+ return 0
+ try:
+ with self._lock:
+ with open(self.log_path, "a", encoding="utf-8", errors="replace") as f:
+ f.write(s)
+ except Exception:
+ pass
+ return len(s)
+
+ def writelines(self, lines) -> None:
+ for line in lines:
+ self.write(line)
+
+ def flush(self) -> None:
+ pass
+
+ def isatty(self) -> bool:
+ return False
+
+ def fileno(self):
+ raise io.UnsupportedOperation("FileLoggerStream has no fileno")
+
+ def reconfigure(self, *args, **kwargs) -> None:
+ # Accept stream.reconfigure(encoding=...) calls from render_screen / libs
+ if "encoding" in kwargs:
+ self.encoding = kwargs["encoding"]
+ if "errors" in kwargs:
+ self.errors = kwargs["errors"]
+
+ @property
+ def buffer(self):
+ raise io.UnsupportedOperation("FileLoggerStream has no buffer")
+
+ def readable(self) -> bool:
+ return False
+
+ def writable(self) -> bool:
+ return True
+
+ def seekable(self) -> bool:
+ return False
+
+ @property
+ def closed(self) -> bool:
+ return self._closed
+
+ def close(self) -> None:
+ self._closed = True
+
+
+class TerminalUI:
+ """Renders and manages the clean console window UI."""
+
+ def __init__(self, log_dir: Path):
+ self.log_dir = log_dir
+ self.log_file = log_dir / "app.log"
+ self._stop_event = threading.Event()
+ self._listener_thread: threading.Thread | None = None
+ self._button_row = 0
+ self._button_col_start = 2
+ self._button_col_end = 14
+ self._alt_active = False
+
+ def enable_vt_mode(self) -> None:
+ """Enable Windows Virtual Terminal Processing for 24-bit ANSI colors."""
+ if sys.platform != "win32":
+ return
+ try:
+ kernel32 = ctypes.windll.kernel32
+ # Enable ANSI on standard out
+ h_out = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
+ mode = wintypes.DWORD()
+ if kernel32.GetConsoleMode(h_out, ctypes.byref(mode)):
+ # ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
+ kernel32.SetConsoleMode(h_out, mode.value | 0x0004)
+ except Exception:
+ pass
+
+ def render_screen(self) -> None:
+ """Draw the complete styled terminal interface."""
+ for stream in (sys.__stdout__, sys.stdout):
+ if hasattr(stream, "reconfigure"):
+ try:
+ stream.reconfigure(encoding="utf-8", errors="replace")
+ except Exception:
+ pass
+
+ # Robust VT and size - retry until real window size
+ for _ in range(4):
+ self.enable_vt_mode()
+ os.system("")
+ term_cols, term_rows = shutil.get_terminal_size((100, 30))
+ if term_cols >= 80 and term_rows >= 20:
+ break
+ time.sleep(0.05)
+ else:
+ term_cols, term_rows = shutil.get_terminal_size((120, 30))
+
+ # Single line - DLSS 5 VISUAL ENHANCER, DLSS closer (1 space) and larger via fullwidth + bold
+ dlss_part = "D L S S 5"
+ visual_part = "V I S U A L E N H A N C E R"
+ title_text = dlss_part + " " + visual_part
+ # Fullwidth chars are 2 cols wide, so use display width for centering (approx)
+ title_w = len(title_text) + dlss_part.count("D") + dlss_part.count("L") + dlss_part.count("S") + dlss_part.count("5")
+ # Simpler: use len as approximation, will still center visually
+ title_w = len(title_text)
+ pad_title = " " * max(0, (term_cols - title_w) // 2)
+
+ # Enter alternate screen buffer on first render, otherwise just move home and clear
+ if not self._alt_active:
+ sys.__stdout__.write("\033[?1049h")
+ self._alt_active = True
+ sys.__stdout__.write("\033[H\033[?25l")
+ sys.__stdout__.flush()
+
+ out_lines: list[str] = []
+ # Center single title vertically, keep footer at bottom
+ banner_block_h = 1
+ footer_h = 1
+ target_rows = max(term_rows, 24)
+ available = max(0, target_rows - banner_block_h - footer_h - 2)
+ pad_top = available // 2
+ pad_bottom = available - pad_top
+ out_lines.extend([""] * pad_top)
+ out_lines.append(pad_title + colorize_text(title_text, bold=True))
+ out_lines.append("")
+
+ # Vertical spacing after block before footer
+ for _ in range(pad_bottom):
+ out_lines.append("")
+
+ # Bottom row: GitHub on left, Merserk on right
+ self._button_row = len(out_lines) + 1
+
+ # OSC 8 Hyperlink button (plain GitHub text without brackets) - GitHub #0286C3, Merserk #079E6E
+ osc8_button = (
+ f"\033]8;;{GITHUB_URL}\033\\"
+ f"\033[1;38;2;{C_LEFT[0]};{C_LEFT[1]};{C_LEFT[2]}mGitHub\033[0m"
+ f"\033]8;;\033\\"
+ )
+ visible_button_len = len(" GitHub")
+ author_colored = f"\033[1;38;2;{C_RIGHT[0]};{C_RIGHT[1]};{C_RIGHT[2]}m{AUTHOR_NAME}\033[0m"
+ visible_author_len = len(AUTHOR_NAME) + 2
+
+ gap = max(2, term_cols - visible_button_len - visible_author_len)
+ footer_line = " " + osc8_button + (" " * gap) + author_colored + " "
+ out_lines.append(footer_line)
+
+ # Output in-place without adding to scrollback - no trailing newline, erase to end
+ sys.__stdout__.write("\n".join(out_lines))
+ sys.__stdout__.write("\033[J")
+ sys.__stdout__.flush()
+
+ def render_loading(self) -> None:
+ """Draw centered LOADING screen with same DLSS 5 Visual Enhancer style, no footer."""
+ for stream in (sys.__stdout__, sys.stdout):
+ if hasattr(stream, "reconfigure"):
+ try:
+ stream.reconfigure(encoding="utf-8", errors="replace")
+ except Exception:
+ pass
+ # Robust VT and size - early import time conhost may report 0,0 / 80x24 fallback
+ for _ in range(4):
+ self.enable_vt_mode()
+ os.system("")
+ term_cols, term_rows = shutil.get_terminal_size((100, 30))
+ if term_cols >= 80 and term_rows >= 20:
+ break
+ time.sleep(0.05)
+ else:
+ term_cols, term_rows = shutil.get_terminal_size((120, 30))
+ loading_text = "L O A D I N G"
+ loading_w = len(loading_text)
+ pad_loading = " " * max(0, (term_cols - loading_w) // 2)
+ # Center vertically, no footer
+ banner_block_h = 1
+ target_rows = max(term_rows, 24)
+ available = max(0, target_rows - banner_block_h - 2)
+ pad_top = available // 2
+ pad_bottom = available - pad_top
+ if not self._alt_active:
+ sys.__stdout__.write("\033[?1049h")
+ self._alt_active = True
+ sys.__stdout__.write("\033[H\033[?25l")
+ sys.__stdout__.flush()
+ out_lines: list[str] = []
+ out_lines.extend([""] * pad_top)
+ out_lines.append(pad_loading + colorize_text(loading_text, bold=True))
+ out_lines.append("")
+ for _ in range(pad_bottom):
+ out_lines.append("")
+ # No footer on loading screen per request - in-place, no trailing newline
+ sys.__stdout__.write("\n".join(out_lines))
+ sys.__stdout__.write("\033[J")
+ sys.__stdout__.flush()
+
+ def start_input_listener(self) -> None:
+ """Start background daemon thread listening for clicks or hotkey to open GitHub."""
+ if sys.platform != "win32":
+ return
+
+ def _input_worker() -> None:
+ kernel32 = ctypes.windll.kernel32
+ GENERIC_READ = 0x80000000
+ GENERIC_WRITE = 0x40000000
+ FILE_SHARE_READ = 1
+ FILE_SHARE_WRITE = 2
+ OPEN_EXISTING = 3
+ ENABLE_MOUSE_INPUT = 0x0010
+ ENABLE_EXTENDED_FLAGS = 0x0080
+ ENABLE_WINDOW_INPUT = 0x0008
+
+ h_in = kernel32.CreateFileW(
+ "CONIN$",
+ GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ None,
+ OPEN_EXISTING,
+ 0,
+ None,
+ )
+ if h_in == -1 or h_in == 0:
+ return
+
+ try:
+ orig_mode = wintypes.DWORD()
+ if kernel32.GetConsoleMode(h_in, ctypes.byref(orig_mode)):
+ # Enable mouse events, disable quick edit mode to receive clicks
+ new_mode = (orig_mode.value | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS | ENABLE_WINDOW_INPUT) & ~0x0040
+ kernel32.SetConsoleMode(h_in, new_mode)
+
+ class COORD(ctypes.Structure):
+ _fields_ = [("X", wintypes.SHORT), ("Y", wintypes.SHORT)]
+
+ class KEY_EVENT_RECORD(ctypes.Structure):
+ _fields_ = [
+ ("bKeyDown", wintypes.BOOL),
+ ("wRepeatCount", wintypes.WORD),
+ ("wVirtualKeyCode", wintypes.WORD),
+ ("wVirtualScanCode", wintypes.WORD),
+ ("uChar", wintypes.WCHAR),
+ ("dwControlKeyState", wintypes.DWORD),
+ ]
+
+ class MOUSE_EVENT_RECORD(ctypes.Structure):
+ _fields_ = [
+ ("dwMousePosition", COORD),
+ ("dwButtonState", wintypes.DWORD),
+ ("dwControlKeyState", wintypes.DWORD),
+ ("dwEventFlags", wintypes.DWORD),
+ ]
+
+ class EVENT_UNION(ctypes.Union):
+ _fields_ = [
+ ("KeyEvent", KEY_EVENT_RECORD),
+ ("MouseEvent", MOUSE_EVENT_RECORD),
+ ]
+
+ class INPUT_RECORD(ctypes.Structure):
+ _fields_ = [
+ ("EventType", wintypes.WORD),
+ ("Event", EVENT_UNION),
+ ]
+
+ record = INPUT_RECORD()
+ events_read = wintypes.DWORD()
+
+ last_open_time = 0.0
+
+ while not self._stop_event.is_set():
+ # Wait with 250ms timeout so thread responds to stop event
+ wait_res = kernel32.WaitForSingleObject(h_in, 250)
+ if wait_res != 0:
+ continue
+
+ if not kernel32.ReadConsoleInputW(
+ h_in, ctypes.byref(record), 1, ctypes.byref(events_read)
+ ) or events_read.value == 0:
+ continue
+
+ # Key event: 'g', 'G', or Enter
+ if record.EventType == 0x0001: # KEY_EVENT
+ ke = record.Event.KeyEvent
+ if ke.bKeyDown:
+ char = str(ke.uChar).lower()
+ if char == "g" or ke.wVirtualKeyCode == 0x0D: # Enter
+ now = time.time()
+ if now - last_open_time > 1.5:
+ last_open_time = now
+ webbrowser.open(GITHUB_URL)
+
+ # Mouse event: click on bottom-left region
+ elif record.EventType == 0x0002: # MOUSE_EVENT
+ me = record.Event.MouseEvent
+ # FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001
+ if me.dwButtonState & 0x0001:
+ x = me.dwMousePosition.X
+ y = me.dwMousePosition.Y
+ _, term_rows = shutil.get_terminal_size((100, 30))
+ # Check if click is near the bottom left (GitHub button area)
+ if y >= term_rows - 4 and x <= 16:
+ now = time.time()
+ if now - last_open_time > 1.5:
+ last_open_time = now
+ webbrowser.open(GITHUB_URL)
+
+ except Exception:
+ pass
+ finally:
+ try:
+ kernel32.CloseHandle(h_in)
+ except Exception:
+ pass
+
+ self._listener_thread = threading.Thread(target=_input_worker, daemon=True)
+ self._listener_thread.start()
+
+ def silence_and_redirect(self) -> None:
+ """Silence stdout/stderr and redirect all logging/exceptions to app.log."""
+ self.log_dir.mkdir(parents=True, exist_ok=True)
+ log_stream = FileLoggerStream(self.log_file)
+
+ # Redirect standard streams
+ sys.stdout = log_stream # type: ignore[assignment]
+ sys.stderr = log_stream # type: ignore[assignment]
+
+ # Suppress warnings
+ warnings.filterwarnings("ignore")
+
+ # Configure file logging for libraries
+ file_handler = logging.FileHandler(str(self.log_file), encoding="utf-8")
+ file_handler.setLevel(logging.INFO)
+ formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s: %(message)s")
+ file_handler.setFormatter(formatter)
+
+ for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access", "gradio", "fastapi"):
+ lg = logging.getLogger(logger_name)
+ lg.handlers = [file_handler]
+ lg.setLevel(logging.WARNING)
+
+ def restore_cursor(self) -> None:
+ """Show terminal cursor and leave alternate buffer on exit."""
+ try:
+ if getattr(self, "_alt_active", False):
+ sys.__stdout__.write("\033[?1049l")
+ self._alt_active = False
+ sys.__stdout__.write("\033[?25h")
+ sys.__stdout__.flush()
+ except Exception:
+ pass
+
+
+def init_console(log_dir: Path) -> TerminalUI:
+ """Initialize and display the loading screen immediately, then final UI after prep."""
+ ui = TerminalUI(log_dir)
+ ui.render_loading()
+ ui.start_input_listener()
+ ui.silence_and_redirect()
+ atexit.register(ui.restore_cursor)
+ return ui
diff --git a/src/ffmpeg.py b/src/ffmpeg.py
deleted file mode 100644
index 7e25124..0000000
--- a/src/ffmpeg.py
+++ /dev/null
@@ -1,550 +0,0 @@
-from __future__ import annotations
-
-import json
-import math
-import os
-import subprocess
-import threading
-from fractions import Fraction
-from functools import lru_cache
-from pathlib import Path
-
-import av
-
-from .runtime import FFMPEG, FFPROBE, JobController, drain_text
-
-
-ENCODING_QUALITIES = ("Auto (Default)", "Max", "Best", "Good")
-AUTO_BITRATE_DIVISORS = {
- "H.264": 165_888,
- "HEVC": 331_776,
- "AV1": 414_720,
-}
-
-
-def validate_codec_container(codec: str, container: str) -> None:
- if codec == "ProRes Proxy" and container == "MP4":
- raise ValueError("ProRes Proxy is not supported in MP4. Choose the MOV or MKV container.")
-
-
-def calculate_auto_bitrate_kbps(
- width: int,
- height: int,
- fps: float,
- codec: str,
- bit_depth: int = 8,
-) -> int:
- try:
- divisor = AUTO_BITRATE_DIVISORS[codec]
- except KeyError as exc:
- raise ValueError(f"Automatic bitrate is unavailable for codec {codec!r}.") from exc
- if width <= 0 or height <= 0 or not math.isfinite(fps) or fps <= 0 or bit_depth <= 0:
- raise ValueError("Automatic bitrate requires positive dimensions, frame rate, and bit depth.")
- value = width * height * fps * bit_depth * 2 / divisor
- return max(1, int(math.floor(value + 0.5)))
-
-
-def resolve_encoding_quality(
- quality_name: str,
- codec: str,
- width: int,
- height: int,
- fps: float,
-) -> dict:
- if quality_name not in ENCODING_QUALITIES:
- raise ValueError(f"Unknown encoding quality: {quality_name!r}.")
- if codec == "ProRes Proxy":
- return {
- "selection": quality_name,
- "mode": "fixed-prores-proxy-profile",
- "target_bitrate_kbps": None,
- "cq": None,
- }
- if quality_name == "Max":
- return {
- "selection": quality_name,
- "mode": "constant-quality",
- "target_bitrate_kbps": None,
- "cq": 0,
- }
- multiplier = {"Auto (Default)": 1, "Good": 2, "Best": 4}[quality_name]
- auto = calculate_auto_bitrate_kbps(width, height, fps, codec)
- return {
- "selection": quality_name,
- "mode": "target-bitrate",
- "auto_bitrate_kbps": auto,
- "multiplier": multiplier,
- "target_bitrate_kbps": auto * multiplier,
- "cq": None,
- }
-
-
-def _run_json(command: list[str]) -> dict:
- result = subprocess.run(
- command,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- if result.returncode:
- raise RuntimeError(result.stderr.strip() or "Media probe failed")
- return json.loads(result.stdout)
-
-
-def probe_video(
- path: str | os.PathLike[str], *, count_mode: str = "exact"
-) -> dict:
- """Probe video metadata, optionally counting decoded frames or packets.
-
- The default remains the legacy exact decoded-frame count for external callers.
- Conversion paths use metadata first and pay for exact counting only as fallback.
- """
- if count_mode not in {"metadata", "exact", "packets"}:
- raise ValueError(f"Unknown video count mode: {count_mode!r}.")
- count_args = {
- "metadata": [],
- "exact": ["-count_frames"],
- "packets": ["-count_packets"],
- }[count_mode]
- data = _run_json(
- [
- str(FFPROBE),
- "-v",
- "error",
- *count_args,
- "-select_streams",
- "v:0",
- "-show_entries",
- "stream=index,codec_name,width,height,avg_frame_rate,r_frame_rate,time_base,duration,nb_frames,nb_read_frames,nb_read_packets,color_primaries,color_transfer,color_space:stream_tags=rotate:stream_side_data=rotation",
- "-show_entries",
- "format=duration,format_name",
- "-of",
- "json",
- str(path),
- ]
- )
- streams = data.get("streams") or []
- if not streams:
- raise ValueError("The selected file contains no decodable video stream.")
- stream = streams[0]
- rotation = int((stream.get("tags") or {}).get("rotate", 0) or 0)
- for side in stream.get("side_data_list") or []:
- if "rotation" in side:
- rotation = int(side["rotation"] or 0)
- rotation %= 360
- width, height = int(stream["width"]), int(stream["height"])
- if rotation in (90, 270):
- width, height = height, width
- if count_mode == "packets":
- frames = int(stream.get("nb_read_packets") or stream.get("nb_frames") or 0)
- frame_count_source = "packets" if stream.get("nb_read_packets") else "metadata"
- elif count_mode == "exact":
- frames = int(stream.get("nb_read_frames") or stream.get("nb_frames") or 0)
- frame_count_source = "decoded" if stream.get("nb_read_frames") else "metadata"
- else:
- frames = int(stream.get("nb_frames") or 0)
- frame_count_source = "metadata" if frames > 0 else "unavailable"
- if count_mode == "exact" and frames <= 0:
- raise ValueError("Could not determine an exact frame count for this video.")
- average_rate_text = stream.get("avg_frame_rate") or "0/0"
- nominal_rate_text = stream.get("r_frame_rate") or "0/0"
- rate_text = average_rate_text if average_rate_text != "0/0" else nominal_rate_text
- if rate_text == "0/0":
- rate_text = "30/1"
- rate = Fraction(rate_text) if rate_text != "0/0" else Fraction(30, 1)
- nominal_rate = (
- Fraction(nominal_rate_text)
- if nominal_rate_text != "0/0"
- else rate
- )
- transfer = stream.get("color_transfer") or "unknown"
- return {
- "width": width,
- "height": height,
- "coded_width": int(stream["width"]),
- "coded_height": int(stream["height"]),
- "rotation": rotation,
- "frames": frames,
- "frame_count_source": frame_count_source,
- "fps": float(rate),
- "rate": rate,
- "nominal_rate": nominal_rate,
- "cfr": rate == nominal_rate,
- "time_base": Fraction(stream.get("time_base") or "1/1000"),
- "duration": float(
- (data.get("format") or {}).get("duration") or stream.get("duration") or 0
- ),
- "codec": stream.get("codec_name") or "unknown",
- "format": (data.get("format") or {}).get("format_name") or "unknown",
- "color_transfer": transfer,
- "hdr": transfer in {"smpte2084", "arib-std-b67"},
- }
-
-
-@lru_cache(maxsize=256)
-def _encoder_probe(
- codec: str, width: int, height: int, gpu_ordinal: int | None = None
-) -> bool:
- gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []
- command = [
- str(FFMPEG),
- "-v",
- "error",
- "-f",
- "lavfi",
- "-i",
- f"color=size={width}x{height}:rate=1",
- "-frames:v",
- "1",
- "-c:v",
- codec,
- *gpu_args,
- "-f",
- "null",
- "-",
- ]
- return (
- subprocess.run(
- command,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- ).returncode
- == 0
- )
-
-
-_NVENC_CODECS = {
- "H.264": "h264_nvenc",
- "HEVC": "hevc_nvenc",
- "AV1": "av1_nvenc",
-}
-
-
-def probe_nvenc_codecs(gpu_ordinal: int) -> tuple[str, ...]:
- """Return user-facing codecs that can initialize NVENC on one CUDA device."""
- return tuple(
- codec
- for codec, encoder in _NVENC_CODECS.items()
- if _encoder_probe(encoder, 256, 256, int(gpu_ordinal))
- )
-
-
-def resolve_video_gpu(
- gpus: tuple[dict, ...],
- gpu_uuid: str,
- codec: str,
- width: int,
- height: int,
-) -> dict | None:
- """Resolve a stable UUID to a device that supports the requested NVENC codec."""
- if codec == "ProRes Proxy":
- return None
- try:
- encoder = _NVENC_CODECS[codec]
- except KeyError as exc:
- raise ValueError(f"Unknown video codec: {codec!r}.") from exc
- candidates = [gpu for gpu in gpus if gpu.get("cuda_ordinal") is not None]
- if gpu_uuid != "auto":
- candidates = [gpu for gpu in candidates if gpu.get("uuid") == gpu_uuid]
- if not candidates:
- raise RuntimeError("The selected Video Processing GPU is unavailable.")
- for gpu in candidates:
- ordinal = int(gpu["cuda_ordinal"])
- if _encoder_probe(encoder, width, height, ordinal):
- selected = dict(gpu)
- selected["nvenc_codec"] = encoder
- return selected
- selection = "selected GPU" if gpu_uuid != "auto" else "available NVIDIA GPUs"
- raise RuntimeError(
- f"{codec} NVENC cannot encode the requested {width}×{height} output on the "
- f"{selection}. Choose another Video Processing GPU, codec, or output size."
- )
-
-
-def _codec_command(
- codec: str,
- quality_name: str,
- width: int,
- height: int,
- fps: float,
- gpu_ordinal: int | None = None,
- require_nvenc: bool = False,
-) -> tuple[list[str], str, dict]:
- quality = resolve_encoding_quality(quality_name, codec, width, height, fps)
- if codec == "ProRes Proxy":
- return (
- ["-c:v", "prores_ks", "-profile:v", "0", "-pix_fmt", "yuv422p10le"],
- "prores_ks (Proxy)",
- quality,
- )
- if quality["mode"] == "constant-quality":
- nvenc_quality = ["-rc", "vbr", "-cq", "0", "-b:v", "0"]
- software_quality = ["-crf", "0"]
- else:
- bitrate = f"{quality['target_bitrate_kbps']}k"
- nvenc_quality = ["-rc", "vbr", "-b:v", bitrate]
- software_quality = ["-b:v", bitrate]
- gpu_args = ["-gpu", str(gpu_ordinal)] if gpu_ordinal is not None else []
- if codec == "H.264":
- if _encoder_probe("h264_nvenc", width, height, gpu_ordinal):
- return (
- [
- "-c:v",
- "h264_nvenc",
- *gpu_args,
- "-preset",
- "p6",
- "-tune",
- "hq",
- *nvenc_quality,
- "-pix_fmt",
- "yuv420p",
- ],
- "h264_nvenc",
- quality,
- )
- if require_nvenc:
- raise RuntimeError(
- f"H.264 NVENC cannot encode {width}×{height} on the selected Video Processing GPU."
- )
- return (
- ["-c:v", "libx264", "-preset", "slow", *software_quality, "-pix_fmt", "yuv420p"],
- "libx264",
- quality,
- )
- if codec == "HEVC":
- if _encoder_probe("hevc_nvenc", width, height, gpu_ordinal):
- return (
- [
- "-c:v",
- "hevc_nvenc",
- *gpu_args,
- "-preset",
- "p6",
- "-tune",
- "hq",
- *nvenc_quality,
- "-pix_fmt",
- "yuv420p",
- ],
- "hevc_nvenc",
- quality,
- )
- if require_nvenc:
- raise RuntimeError(
- f"HEVC NVENC cannot encode {width}×{height} on the selected Video Processing GPU."
- )
- return (
- ["-c:v", "libx265", "-preset", "slow", *software_quality, "-pix_fmt", "yuv420p"],
- "libx265",
- quality,
- )
- if codec != "AV1":
- raise ValueError(f"Unknown video codec: {codec!r}.")
- if not _encoder_probe("av1_nvenc", width, height, gpu_ordinal):
- raise RuntimeError(
- f"AV1 NVENC cannot encode the requested {width}×{height} output on this GPU/driver. "
- "Choose H.264/HEVC or a lower upscaling factor."
- )
- return (
- [
- "-c:v", "av1_nvenc", *gpu_args, "-preset", "p6", *nvenc_quality,
- "-pix_fmt", "yuv420p",
- ],
- "av1_nvenc",
- quality,
- )
-
-
-def start_encoder(
- temp_video: Path,
- codec: str,
- quality_name: str,
- controller: JobController,
- width: int,
- height: int,
- fps: float,
- gpu_ordinal: int | None = None,
- require_nvenc: bool = False,
-):
- codec_args, selected, quality = _codec_command(
- codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc
- )
- command = [
- str(FFMPEG),
- "-hide_banner",
- "-loglevel",
- "warning",
- "-y",
- "-f",
- "nut",
- "-i",
- "pipe:0",
- "-map",
- "0:v:0",
- "-an",
- *codec_args,
- "-fps_mode",
- "passthrough",
- str(temp_video),
- ]
- process = subprocess.Popen(
- command,
- stdin=subprocess.PIPE,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- )
- controller.register(process)
- logs: list[str] = []
- assert process.stderr is not None
- thread = threading.Thread(target=drain_text, args=(process.stderr, logs), daemon=True)
- thread.start()
- 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,
- controller: JobController | None = None,
- preserve_supported_subtitles: bool = False,
-) -> 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"]
- else:
- maps = ["-map", "0:v:0", "-map", "1:a?"]
- streams = [
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- "-b:a",
- "192k",
- "-movflags",
- "+faststart",
- ]
- if preserve_supported_subtitles:
- subtitle_data = _run_json(
- [
- str(FFPROBE),
- "-v",
- "error",
- "-select_streams",
- "s",
- "-show_entries",
- "stream=index,codec_name",
- "-of",
- "json",
- str(source),
- ]
- )
- supported_text = {"ass", "ssa", "subrip", "mov_text", "webvtt", "text"}
- subtitle_indices = [
- int(stream["index"])
- for stream in subtitle_data.get("streams") or []
- if stream.get("codec_name") in supported_text
- ]
- for stream_index in subtitle_indices:
- maps.extend(["-map", f"1:{stream_index}"])
- if subtitle_indices:
- streams.extend(["-c:s", "mov_text"])
- command = [
- str(FFMPEG),
- "-hide_banner",
- "-loglevel",
- "warning",
- "-y",
- "-i",
- str(temp_video),
- "-t",
- f"{duration:.9f}",
- "-i",
- str(source),
- *maps,
- "-map_metadata",
- "1",
- "-map_chapters",
- "1",
- *streams,
- str(output),
- ]
- process = subprocess.Popen(
- command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- if controller is not None:
- controller.register(process)
- try:
- _stdout, stderr = process.communicate()
- finally:
- if controller is not None:
- controller.unregister(process)
- if process.returncode:
- raise RuntimeError("Final audio/metadata mux failed:\n" + stderr[-4000:])
-
-
-def preview_frame_count(source: Path, seconds: float) -> int:
- """Count frames whose presentation times fall within the opening interval."""
- container = av.open(str(source))
- try:
- stream = container.streams.video[0]
- rate = float(stream.average_rate or 30)
- first_time: float | None = None
- count = 0
- for frame in container.decode(stream):
- timestamp = (
- float(frame.pts * stream.time_base)
- if frame.pts is not None and stream.time_base is not None
- else count / rate
- )
- if first_time is None:
- first_time = timestamp
- if count and timestamp - first_time >= seconds:
- break
- count += 1
- if count == 0:
- raise RuntimeError("The input video contains no decodable preview frames.")
- return count
- finally:
- container.close()
diff --git a/src/frame_interpolation/__init__.py b/src/frame_interpolation/__init__.py
index 5139f91..5df74a2 100644
--- a/src/frame_interpolation/__init__.py
+++ b/src/frame_interpolation/__init__.py
@@ -1,42 +1,18 @@
+from .batch import interpolate_videos
from .capabilities import probe_frame_interpolation_capabilities
from .models import (
- ENGINE_CHOICES,
- FPS_CHOICES,
- FPS_RATES,
- FrameInterpolationBatchResult,
- FrameInterpolationCapabilities,
- FrameInterpolationOptions,
- FrameInterpolationResult,
- resolve_target_rate,
+ ENGINE_CHOICES, FPS_CHOICES, FrameInterpolationBatchResult, FrameInterpolationCapabilities,
+ FrameInterpolationFailure, FrameInterpolationOptions, FrameInterpolationResult,
+ FrameInterpolationSuccess, InterpolationPlan, resolve_target_rate,
)
+from .processor import interpolate_video
from .scheduler import choose_interpolation_plan, output_frame_count, select_grid_timestamps
-
-def interpolate_video(*args, **kwargs):
- from .pipeline import interpolate_video as implementation
-
- return implementation(*args, **kwargs)
-
-
-def interpolate_videos(*args, **kwargs):
- from .pipeline import interpolate_videos as implementation
-
- return implementation(*args, **kwargs)
-
-
__all__ = [
- "ENGINE_CHOICES",
- "FPS_CHOICES",
- "FPS_RATES",
- "FrameInterpolationBatchResult",
- "FrameInterpolationCapabilities",
- "FrameInterpolationOptions",
- "FrameInterpolationResult",
- "choose_interpolation_plan",
- "interpolate_video",
- "interpolate_videos",
- "output_frame_count",
- "probe_frame_interpolation_capabilities",
- "resolve_target_rate",
+ "ENGINE_CHOICES", "FPS_CHOICES", "FrameInterpolationBatchResult",
+ "FrameInterpolationCapabilities", "FrameInterpolationFailure", "FrameInterpolationOptions",
+ "FrameInterpolationResult", "FrameInterpolationSuccess", "InterpolationPlan",
+ "choose_interpolation_plan", "interpolate_video", "interpolate_videos",
+ "output_frame_count", "probe_frame_interpolation_capabilities", "resolve_target_rate",
"select_grid_timestamps",
]
diff --git a/src/frame_interpolation/batch.py b/src/frame_interpolation/batch.py
new file mode 100644
index 0000000..d66e95b
--- /dev/null
+++ b/src/frame_interpolation/batch.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+import json
+import os
+import time
+from dataclasses import asdict
+from pathlib import Path
+from typing import Callable, Iterable
+
+from ..core.jobs import Cancelled, active_job
+from ..core.paths import LOGS
+from .models import (
+ FrameInterpolationBatchResult, FrameInterpolationFailure, FrameInterpolationOptions,
+ FrameInterpolationSuccess,
+)
+from .processor import _BATCH_CONTEXT, _json_safe, interpolate_video
+
+def interpolate_videos(
+ input_paths: Iterable[str | os.PathLike[str]],
+ options: FrameInterpolationOptions | None = None,
+ progress: Callable[[float, str], None] | None = None,
+) -> FrameInterpolationBatchResult:
+ options = options or FrameInterpolationOptions()
+ paths = [Path(path).resolve() for path in input_paths]
+ if not paths:
+ raise ValueError("Choose at least one video.")
+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
+ successes: list[FrameInterpolationSuccess] = []
+ failures: list[FrameInterpolationFailure] = []
+ cancelled = False
+ with active_job() as controller:
+ _BATCH_CONTEXT.controller = controller
+ try:
+ for index, path in enumerate(paths):
+ if controller.cancel.is_set():
+ cancelled = True
+ failures.extend(
+ FrameInterpolationFailure(i, str(item), "Cancelled before rendering.", True)
+ for i, item in enumerate(paths[index:], start=index)
+ )
+ break
+ def item_progress(value: float, message: str, *, position=index) -> None:
+ if progress:
+ progress((position + value) / len(paths), f"[{position + 1}/{len(paths)}] {message}")
+ try:
+ result = interpolate_video(path, options, item_progress)
+ successes.append(FrameInterpolationSuccess(index, str(path), result))
+ except Cancelled as exc:
+ cancelled = True
+ failures.append(FrameInterpolationFailure(index, str(path), str(exc), True))
+ failures.extend(
+ FrameInterpolationFailure(
+ queued_index,
+ str(queued),
+ "Cancelled before rendering.",
+ True,
+ )
+ for queued_index, queued in enumerate(
+ paths[index + 1 :], start=index + 1
+ )
+ )
+ break
+ except Exception as exc:
+ failures.append(FrameInterpolationFailure(index, str(path), str(exc)))
+ finally:
+ del _BATCH_CONTEXT.controller
+ manifest = {
+ "status": "cancelled" if cancelled else ("partial" if failures else "success"),
+ "options": _json_safe(asdict(options)),
+ "successes": [asdict(item) for item in successes],
+ "failures": [asdict(item) for item in failures],
+ }
+ LOGS.mkdir(exist_ok=True)
+ manifest_path = LOGS / f"DLSSFG_BATCH_{stamp}.manifest.json"
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+ return FrameInterpolationBatchResult(successes, failures, cancelled, str(manifest_path.resolve()))
diff --git a/src/frame_interpolation/capabilities.py b/src/frame_interpolation/capabilities.py
index 788f333..5c37636 100644
--- a/src/frame_interpolation/capabilities.py
+++ b/src/frame_interpolation/capabilities.py
@@ -1,32 +1,19 @@
from __future__ import annotations
-import hashlib
import json
import os
import subprocess
from functools import lru_cache
from pathlib import Path
-from ..runtime import ROOT, detect_gpu
+from ..core.paths import DLSSG_DIR
+from ..core.gpu_selection import detect_gpu
from .models import FrameInterpolationCapabilities
-RUNTIME_DIR = ROOT / "bin" / "runtime" / "frame_interpolation" / "dlssg"
+RUNTIME_DIR = DLSSG_DIR
DLSSG_RUNTIME = RUNTIME_DIR / "nvngx_dlssg.dll"
DLSSG_WORKER = RUNTIME_DIR / "dlssg-worker.exe"
-MANIFEST = RUNTIME_DIR / "manifest.json"
-EXPECTED_RUNTIME_SHA256 = "135EAF0733C1E37381A8C28ABCF7A862404A54132B81787C04E35D09EFC5E36F"
-EXPECTED_WORKER_SHA256 = "8A747F9ED613842D5B8B34A811AD43BC1A9466540E2E5A0C8EF4005F0DB9E384"
-
-
-def _sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for block in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(block)
- return digest.hexdigest().upper()
-
-
def _hags_enabled() -> bool:
if os.name != "nt":
return False
@@ -69,12 +56,10 @@ def _authenticode_status(path: Path) -> str:
return process.stdout.strip() if process.returncode == 0 else "Unavailable"
-def _probe_worker(adapter_luid: str | None = None) -> dict:
+def _probe_worker() -> dict:
if not DLSSG_WORKER.is_file():
raise RuntimeError(f"DLSSG worker is missing: {DLSSG_WORKER}")
command = [str(DLSSG_WORKER), "--probe"]
- if adapter_luid:
- command.extend(["--adapter-luid", adapter_luid])
process = subprocess.run(
command,
cwd=str(RUNTIME_DIR),
@@ -103,34 +88,41 @@ def probe_frame_interpolation_capabilities(
hags = _hags_enabled()
if not DLSSG_RUNTIME.is_file():
return FrameInterpolationCapabilities(
- False, gpu_name, driver, hags, 0, 1, False, "missing", "", "missing",
- "Missing", f"Signed NVIDIA DLSSG runtime is missing: {DLSSG_RUNTIME}",
+ available=False,
+ gpu=gpu_name,
+ driver=driver,
+ hags_enabled=hags,
+ native_generated_frame_max=0,
+ native_multiplier=1,
+ cascade_available=False,
+ runtime_version="missing",
+ worker_version="missing",
+ signature_status="Missing",
+ detail=f"NVIDIA DLSSG runtime is missing: {DLSSG_RUNTIME}",
+ gpu_uuid=str(gpu.get("uuid") or ai_gpu_uuid),
)
- runtime_hash = _sha256(DLSSG_RUNTIME)
- signature_status = _authenticode_status(DLSSG_RUNTIME)
- if runtime_hash != EXPECTED_RUNTIME_SHA256:
- return FrameInterpolationCapabilities(
- False, gpu_name, driver, hags, 0, 1, False, "unknown", runtime_hash,
- "unknown", "Hash mismatch",
- "The staged nvngx_dlssg.dll does not match the pinned NVIDIA 310.7 release.",
- )
- if signature_status != "Valid":
- return FrameInterpolationCapabilities(
- False, gpu_name, driver, hags, 0, 1, False, "310.7.0.0", runtime_hash,
- "unknown", signature_status,
- "Windows did not validate the NVIDIA Authenticode signature on nvngx_dlssg.dll.",
- )
- if not DLSSG_WORKER.is_file() or _sha256(DLSSG_WORKER) != EXPECTED_WORKER_SHA256:
+ if not DLSSG_WORKER.is_file():
return FrameInterpolationCapabilities(
- False, gpu_name, driver, hags, 0, 1, False, "310.7.0.0", runtime_hash,
- "unknown", "Worker hash mismatch",
- "The direct D3D12 worker is missing or does not match its source build manifest.",
+ available=False,
+ gpu=gpu_name,
+ driver=driver,
+ hags_enabled=hags,
+ native_generated_frame_max=0,
+ native_multiplier=1,
+ cascade_available=False,
+ runtime_version="unknown",
+ worker_version="missing",
+ signature_status=_authenticode_status(DLSSG_RUNTIME),
+ detail=f"Direct D3D12 DLSSG worker is missing: {DLSSG_WORKER}",
+ gpu_uuid=str(gpu.get("uuid") or ai_gpu_uuid),
)
+
+ signature_status = _authenticode_status(DLSSG_RUNTIME)
try:
- probed = _probe_worker(gpu.get("adapter_luid"))
+ probed = _probe_worker()
generated_max = max(0, int(probed.get("multi_frame_count_max", 0)))
multiplier = generated_max + 1 if generated_max else 1
- available = bool(probed.get("available", False)) and generated_max >= 1 and hags
+ available = bool(probed.get("available", False)) and generated_max >= 1
detail = str(probed.get("detail") or "")
except Exception as exc:
generated_max = 0
@@ -138,6 +130,17 @@ def probe_frame_interpolation_capabilities(
available = False
detail = str(exc)
probed = {}
+
+ diagnostic_notes: list[str] = []
+ if not hags:
+ diagnostic_notes.append("HAGS is disabled; the native runtime may reject Frame Generation.")
+ if signature_status not in {"Valid", "Unavailable"}:
+ diagnostic_notes.append(
+ f"Authenticode status is {signature_status}; this is diagnostic only and is not blocked."
+ )
+ if diagnostic_notes:
+ detail = " ".join([part for part in [detail, *diagnostic_notes] if part])
+
return FrameInterpolationCapabilities(
available=available,
gpu=gpu_name,
@@ -146,10 +149,9 @@ def probe_frame_interpolation_capabilities(
native_generated_frame_max=generated_max,
native_multiplier=multiplier,
cascade_available=available and multiplier >= 2,
- runtime_version=str(probed.get("runtime_version") or "310.7.0.0"),
- runtime_sha256=runtime_hash,
- worker_version=str(probed.get("worker_version") or "1"),
- signature_status=f"{signature_status} (NVIDIA; pinned hash)",
+ runtime_version=str(probed.get("runtime_version") or "unknown"),
+ worker_version=str(probed.get("worker_version") or "unknown"),
+ signature_status=signature_status,
detail=detail,
gpu_uuid=str(gpu.get("uuid") or ai_gpu_uuid),
)
diff --git a/src/frame_interpolation/models.py b/src/frame_interpolation/models.py
index 200ff27..ef4e2fd 100644
--- a/src/frame_interpolation/models.py
+++ b/src/frame_interpolation/models.py
@@ -43,9 +43,13 @@ class FrameInterpolationOptions:
codec: str = "H.264"
container: str = "MP4"
quality: str = "Auto (Default)"
+ hdr_mode: bool = False
rename_mode: str = "Auto"
custom_suffix: str = "_DLSSFG"
preview_seconds: float | None = None
+ # True = truncated preview uses the forced H.264 SDR path (current behavior).
+ # False = truncated preview uses the user's codec/container (HDR preserved).
+ preview_compat: bool = True
@property
def target_rate(self) -> Fraction:
@@ -62,7 +66,6 @@ class FrameInterpolationCapabilities:
native_multiplier: int
cascade_available: bool
runtime_version: str
- runtime_sha256: str
worker_version: str
signature_status: str
detail: str = ""
diff --git a/src/frame_interpolation/native.py b/src/frame_interpolation/native.py
index ba53b10..ce822ce 100644
--- a/src/frame_interpolation/native.py
+++ b/src/frame_interpolation/native.py
@@ -8,7 +8,7 @@ from fractions import Fraction
import numpy as np
-from ..runtime import Cancelled, JobController
+from ..core.jobs import Cancelled, JobController
from .capabilities import DLSSG_WORKER, RUNTIME_DIR
@@ -38,7 +38,6 @@ class DirectDLSSGSession:
frame_count: int,
generated_count: int,
controller: JobController,
- adapter_luid: str | None = None,
) -> None:
if not DLSSG_WORKER.is_file():
raise RuntimeError(f"Direct DLSSG worker is missing: {DLSSG_WORKER}")
@@ -49,8 +48,6 @@ class DirectDLSSGSession:
self.controller = controller
self.logs: collections.deque[str] = collections.deque(maxlen=300)
command = [str(DLSSG_WORKER), "--serve"]
- if adapter_luid:
- command.extend(["--adapter-luid", adapter_luid])
self.process = subprocess.Popen(
command,
cwd=str(RUNTIME_DIR),
diff --git a/src/frame_interpolation/preview.py b/src/frame_interpolation/preview.py
new file mode 100644
index 0000000..6ef26d2
--- /dev/null
+++ b/src/frame_interpolation/preview.py
@@ -0,0 +1,158 @@
+from __future__ import annotations
+
+import traceback
+from pathlib import Path
+
+import gradio as gr
+
+from ..core.ffmpeg import probe_video
+from ..core.ffmpeg.preview import (
+ is_browser_playable, make_browser_preview, normalize_preview_encoding,
+ resolve_preview_codec, wants_compat_preview,
+)
+from ..settings.storage import current_preview_encoding, processing_gpu_settings
+from .capabilities import probe_frame_interpolation_capabilities
+from .models import FrameInterpolationOptions
+from .processor import interpolate_video
+from .scheduler import choose_interpolation_plan
+
+PREVIEW_SECONDS = 3.0
+
+
+def normalize_video_paths(paths: list[str] | str | None) -> list[str]:
+ if not paths:
+ return []
+ return [paths] if isinstance(paths, str) else list(paths)
+
+
+def first_video_path(paths: list[str] | str | None) -> str | None:
+ normalized = normalize_video_paths(paths)
+ return normalized[0] if normalized else None
+
+def frame_interpolation_capability_text() -> str:
+ ai_gpu_uuid, _video_gpu_uuid = processing_gpu_settings()
+ capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
+ hags = "Enabled" if capabilities.hags_enabled else "Disabled"
+ native = (
+ f"{capabilities.native_multiplier}× "
+ f"({capabilities.native_generated_frame_max} generated frame per evaluation)"
+ )
+ cascade = "Available" if capabilities.cascade_available else "Unavailable"
+ state = "Ready" if capabilities.available else "Unavailable"
+ detail = f"\n{capabilities.detail}" if capabilities.detail else ""
+ return (
+ f"{state} — GPU: {capabilities.gpu} | Driver: {capabilities.driver} | "
+ f"HAGS: {hags}\nNative maximum: {native} | Experimental cascade: {cascade} | "
+ f"DLSSG runtime: {capabilities.runtime_version}{detail}"
+ )
+
+
+def describe_frame_interpolation_plan(
+ paths: list[str] | str | None,
+ target_fps: str,
+ engine: str,
+) -> str:
+ selected = first_video_path(paths)
+ if not selected:
+ return "Choose a video to preflight its DLSSG path and temporal precision."
+ try:
+ metadata = probe_video(selected, count_mode="metadata")
+ ai_gpu_uuid, _video_gpu_uuid = processing_gpu_settings()
+ capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
+ plan = choose_interpolation_plan(
+ metadata["rate"],
+ FrameInterpolationOptions(target_fps=target_fps).target_rate,
+ engine,
+ capabilities.native_multiplier,
+ cfr=bool(metadata.get("cfr", True)),
+ )
+ if plan.cascade_stages:
+ precision = (
+ f"≤ {float(plan.maximum_temporal_error) * 1000:.3f} ms "
+ f"(1/{2 * plan.grid_multiplier} source-frame interval)"
+ )
+ elif plan.path == "Native DLSSG":
+ precision = "Exact native temporal grid"
+ else:
+ precision = "Nearest real source frame"
+ return (
+ f"{Path(selected).name}: {metadata['rate']} FPS → {target_fps} FPS | "
+ f"Path: {plan.path} | Cascade stages: {plan.cascade_stages} | "
+ f"Internal grid: {plan.grid_multiplier}× | Precision: {precision}"
+ )
+ except Exception as exc:
+ return f"Preflight: {exc}"
+
+
+def update_frame_interpolation_preview_mode(
+ paths: list[str] | str | None,
+ target_fps: str,
+ engine: str,
+):
+ normalized = normalize_video_paths(paths)
+ single = len(normalized) == 1
+ return (
+ gr.update(value=normalized[0] if single else None, visible=single),
+ gr.update(value=None, visible=single),
+ gr.update(visible=single),
+ )
+
+def preview_frame_interpolation(
+ input_paths: list[str] | str | None,
+ target_fps: str,
+ engine: str,
+ codec: str,
+ container: str,
+ quality: str,
+ progress=gr.Progress(track_tqdm=False),
+):
+ selected = first_video_path(input_paths)
+ if not selected:
+ raise gr.Error("Choose one video first.")
+ try:
+ preview_mode = normalize_preview_encoding(current_preview_encoding())
+ except Exception:
+ preview_mode = "Auto"
+ effective_codec, effective_container = resolve_preview_codec(
+ codec, container, preview_mode
+ )
+ compat_preview = wants_compat_preview(codec, container, preview_mode)
+ options = FrameInterpolationOptions(
+ ai_gpu_uuid=processing_gpu_settings()[0],
+ video_gpu_uuid=processing_gpu_settings()[1],
+ target_fps=target_fps,
+ engine=engine,
+ codec=effective_codec,
+ container=effective_container,
+ quality=quality,
+ preview_seconds=PREVIEW_SECONDS,
+ preview_compat=compat_preview,
+ )
+ try:
+ result = interpolate_video(
+ selected,
+ options,
+ lambda value, message: progress(value, desc=message),
+ )
+ except Exception as exc:
+ traceback.print_exc()
+ return None, f"Failed: {exc}"
+ output_preview = result.output_path
+ derived_note = ""
+ if preview_mode == "Auto" and not compat_preview:
+ try:
+ playable = is_browser_playable(result.output_path)
+ except Exception:
+ playable = False
+ if not playable:
+ try:
+ output_preview = make_browser_preview(result.output_path)
+ derived_note = " (browser preview transcoded to H.264)"
+ except Exception:
+ output_preview = result.output_path
+ return output_preview, (
+ f"Preview complete: {result.output_frames} frames, {result.selected_path}, "
+ f"{result.cascade_stages} cascade stage(s), {result.generated_frames} DLSSG-selected "
+ f"frames in {result.elapsed_seconds:.1f}s. Report: {result.report_path}"
+ f"{derived_note}"
+ )
diff --git a/src/frame_interpolation/pipeline.py b/src/frame_interpolation/processor.py
similarity index 82%
rename from src/frame_interpolation/pipeline.py
rename to src/frame_interpolation/processor.py
index 7bb8427..bd0905c 100644
--- a/src/frame_interpolation/pipeline.py
+++ b/src/frame_interpolation/processor.py
@@ -10,34 +10,24 @@ from contextlib import nullcontext
from dataclasses import asdict, dataclass
from fractions import Fraction
from pathlib import Path
-from typing import Callable, Iterable
+from typing import Callable
import av
import numpy as np
-from .. import ffmpeg
-from ..naming import output_filename, require_available_output, validate_rename
-from ..runtime import (
- JOBS,
- LOGS,
- OUTPUTS,
- Cancelled,
- active_job,
- resolve_runtime_ai_gpu,
- rotate_frame,
-)
+from ..core import ffmpeg
+from ..core.gpu_selection import resolve_runtime_ai_gpu
+from ..core.jobs import Cancelled, active_job
+from ..core.naming import output_filename, require_available_output, validate_rename
+from ..core.paths import JOBS, LOGS, OUTPUTS
+from ..core.runtime import prepare_runtime, rotate_frame
from .capabilities import probe_frame_interpolation_capabilities
from .guides import DLSSGGuideGenerator
-from .models import (
- FrameInterpolationBatchResult,
- FrameInterpolationFailure,
- FrameInterpolationOptions,
- FrameInterpolationResult,
- FrameInterpolationSuccess,
-)
+from .models import FrameInterpolationOptions, FrameInterpolationResult
from .native import DirectDLSSGSession
from .scheduler import choose_interpolation_plan, output_frame_count
+_BATCH_CONTEXT = threading.local()
@dataclass(slots=True)
class TimedFrame:
@@ -170,10 +160,6 @@ class NearestTimestampWriter:
for packet in self.stream.encode():
self.nut.mux(packet)
-
-_BATCH_CONTEXT = threading.local()
-
-
def _json_safe(value):
if isinstance(value, Fraction):
return str(value)
@@ -196,18 +182,19 @@ def _validate(options: FrameInterpolationOptions) -> None:
_ = options.target_rate
validate_rename(options.rename_mode, options.custom_suffix)
ffmpeg.validate_codec_container(options.codec, options.container)
+ if getattr(options, "hdr_mode", False) and not ffmpeg.hdr_mode_supported(options.codec):
+ raise ValueError(
+ f"HDR Mode is only available for H.265, H.265 (NVIDIA NVENC), AV1, AV1 (NVIDIA NVENC) and ProRes Proxy; current codec is {options.codec!r}."
+ )
if options.preview_seconds is not None:
if not math.isfinite(float(options.preview_seconds)) or float(options.preview_seconds) <= 0:
raise ValueError("Preview duration must be positive.")
-
def interpolate_video(
input_path: str | os.PathLike[str],
options: FrameInterpolationOptions | None = None,
progress: Callable[[float, str], None] | None = None,
) -> FrameInterpolationResult:
- from ..prepare import prepare_runtime
-
options = options or FrameInterpolationOptions()
_validate(options)
source = Path(input_path).resolve()
@@ -227,6 +214,24 @@ def interpolate_video(
with job_context as controller:
assert controller is not None
started = time.perf_counter()
+
+ def _report_progress(value: float, desc: str) -> None:
+ if progress is None:
+ return
+ try:
+ v = float(value)
+ v = 0.0 if v < 0 else (1.0 if v > 1 else v)
+ elapsed = time.perf_counter() - started
+ if 0.01 < v < 0.99 and elapsed > 0.5:
+ eta = elapsed * (1 - v) / max(v, 1e-6)
+ desc = f"{desc} - Time Remaining: {eta:.1f}s"
+ progress(v, desc)
+ except Exception:
+ try:
+ progress(value, desc)
+ except Exception:
+ pass
+
timings: dict[str, float] = {}
output: Path | None = None
job_dir: Path | None = None
@@ -235,11 +240,25 @@ def interpolate_video(
try:
probe_started = time.perf_counter()
metadata = ffmpeg.probe_video(source, count_mode="metadata")
- if metadata["hdr"]:
+ is_preview = options.preview_seconds is not None
+ compat_preview = is_preview and bool(getattr(options, "preview_compat", True))
+ effective_hdr = (
+ bool(getattr(options, "hdr_mode", False))
+ and (not is_preview or not compat_preview)
+ and ffmpeg.hdr_mode_supported(options.codec)
+ )
+ if metadata["hdr"] and not effective_hdr:
raise ValueError(
- "Frame Interpolation v1 accepts SDR video only. Convert PQ/HLG input to SDR "
- "before using DLSSG."
+ "Frame Interpolation v1 accepts SDR video only. Enable HDR Mode (H.265/AV1/ProRes, 10-bit, copies input colorspace) to keep HDR, or convert PQ/HLG to SDR."
)
+ hdr_metadata = None
+ if effective_hdr:
+ hdr_metadata = {
+ "color_space": metadata.get("color_space", "unknown"),
+ "color_primaries": metadata.get("color_primaries", "unknown"),
+ "color_transfer": metadata.get("color_transfer", "unknown"),
+ "hdr": bool(metadata.get("hdr", False)),
+ }
source_rate = Fraction(metadata["rate"])
cfr = bool(metadata.get("cfr", True))
frames = int(metadata["frames"])
@@ -262,8 +281,7 @@ def interpolate_video(
)
output_count = output_frame_count(duration, options.target_rate)
timings["probe_seconds"] = time.perf_counter() - probe_started
- if progress:
- progress(0.01, f"{plan.path}: {source_rate} → {options.target_rate} FPS")
+ _report_progress(0.01, f"{plan.path}: {source_rate} → {options.target_rate} FPS")
OUTPUTS.mkdir(exist_ok=True)
JOBS.mkdir(exist_ok=True)
@@ -280,7 +298,7 @@ def interpolate_video(
# NUT preserves the exact rational frame clock between PyAV and FFmpeg;
# Matroska's millisecond timestamp scale rounds 60000/1001 and short previews.
temp_video = job_dir / "interpolated-video.nut"
- selected_codec = "H.264" if options.preview_seconds else options.codec
+ selected_codec = "H.264" if compat_preview else options.codec
video_gpu = ffmpeg.resolve_video_gpu(
prepared_runtime.gpus,
options.video_gpu_uuid,
@@ -298,13 +316,15 @@ def interpolate_video(
float(options.target_rate),
None if video_gpu is None else int(video_gpu["cuda_ordinal"]),
video_gpu is not None,
+ hdr_mode=effective_hdr,
+ hdr_metadata=hdr_metadata,
)
assert encoder.stdin is not None
if plan.path == "Native DLSSG":
sessions.append(
DirectDLSSGSession(
int(metadata["width"]), int(metadata["height"]), frames,
- plan.generated_per_interval, controller, ai_gpu.get("adapter_luid"),
+ plan.generated_per_interval, controller,
)
)
elif plan.path == "Cascade":
@@ -313,7 +333,6 @@ def interpolate_video(
sessions.append(
DirectDLSSGSession(
int(metadata["width"]), int(metadata["height"]), expected, 1, controller
- , ai_gpu.get("adapter_luid")
)
)
stages = [
@@ -372,8 +391,8 @@ def interpolate_video(
for item in items:
writer.push(item)
decoded += 1
- if progress and decoded % max(1, frames // 100) == 0:
- progress(0.04 + 0.82 * decoded / frames, f"DLSSG source frame {decoded}/{frames}")
+ if decoded % max(1, frames // 100) == 0:
+ _report_progress(0.04 + 0.82 * decoded / frames, f"DLSSG source frame {decoded}/{frames}")
finally:
container.close()
writer.finish()
@@ -387,8 +406,7 @@ def interpolate_video(
controller.unregister(encoder)
if encoder_code:
raise RuntimeError("Video encoder failed:\n" + "\n".join(encoder_logs[-40:]))
- if progress:
- progress(0.9, "Muxing original audio, subtitles, chapters, and metadata")
+ _report_progress(0.9, "Muxing original audio, subtitles, chapters, and metadata")
ffmpeg.final_mux(
temp_video,
source,
@@ -436,8 +454,7 @@ def interpolate_video(
}
report_path = LOGS / f"DLSSFG_{source.stem}_{stamp}.report.json"
report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
- if progress:
- progress(1.0, "Frame interpolation complete")
+ _report_progress(1.0, "Frame interpolation complete")
return FrameInterpolationResult(
output_path=str(output.resolve()),
report_path=str(report_path.resolve()),
@@ -485,64 +502,3 @@ def interpolate_video(
encoder.terminate()
if job_dir and job_dir.exists():
shutil.rmtree(job_dir, ignore_errors=True)
-
-
-def interpolate_videos(
- input_paths: Iterable[str | os.PathLike[str]],
- options: FrameInterpolationOptions | None = None,
- progress: Callable[[float, str], None] | None = None,
-) -> FrameInterpolationBatchResult:
- options = options or FrameInterpolationOptions()
- paths = [Path(path).resolve() for path in input_paths]
- if not paths:
- raise ValueError("Choose at least one video.")
- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
- successes: list[FrameInterpolationSuccess] = []
- failures: list[FrameInterpolationFailure] = []
- cancelled = False
- with active_job() as controller:
- _BATCH_CONTEXT.controller = controller
- try:
- for index, path in enumerate(paths):
- if controller.cancel.is_set():
- cancelled = True
- failures.extend(
- FrameInterpolationFailure(i, str(item), "Cancelled before rendering.", True)
- for i, item in enumerate(paths[index:], start=index)
- )
- break
- def item_progress(value: float, message: str, *, position=index) -> None:
- if progress:
- progress((position + value) / len(paths), f"[{position + 1}/{len(paths)}] {message}")
- try:
- result = interpolate_video(path, options, item_progress)
- successes.append(FrameInterpolationSuccess(index, str(path), result))
- except Cancelled as exc:
- cancelled = True
- failures.append(FrameInterpolationFailure(index, str(path), str(exc), True))
- failures.extend(
- FrameInterpolationFailure(
- queued_index,
- str(queued),
- "Cancelled before rendering.",
- True,
- )
- for queued_index, queued in enumerate(
- paths[index + 1 :], start=index + 1
- )
- )
- break
- except Exception as exc:
- failures.append(FrameInterpolationFailure(index, str(path), str(exc)))
- finally:
- del _BATCH_CONTEXT.controller
- manifest = {
- "status": "cancelled" if cancelled else ("partial" if failures else "success"),
- "options": _json_safe(asdict(options)),
- "successes": [asdict(item) for item in successes],
- "failures": [asdict(item) for item in failures],
- }
- LOGS.mkdir(exist_ok=True)
- manifest_path = LOGS / f"DLSSFG_BATCH_{stamp}.manifest.json"
- manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
- return FrameInterpolationBatchResult(successes, failures, cancelled, str(manifest_path.resolve()))
diff --git a/src/frame_interpolation/ui.py b/src/frame_interpolation/ui.py
new file mode 100644
index 0000000..58a53db
--- /dev/null
+++ b/src/frame_interpolation/ui.py
@@ -0,0 +1,233 @@
+from __future__ import annotations
+
+import traceback
+from dataclasses import dataclass
+from pathlib import Path
+
+import gradio as gr
+
+from ..core.ffmpeg import hdr_mode_supported
+from ..core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview
+from ..core.jobs import cancel_active_job
+from ..core.naming import RENAME_MODES
+from ..settings.models import CODEC_CHOICES, CONTAINER_CHOICES, QUALITY_CHOICES, UISettings, coerce_hdr_mode
+from ..settings.storage import current_preview_encoding, processing_gpu_settings
+from .batch import interpolate_videos
+from .models import ENGINE_CHOICES, FPS_CHOICES, FrameInterpolationOptions
+from .preview import normalize_video_paths, preview_frame_interpolation, update_frame_interpolation_preview_mode
+
+
+def hdr_mode_update(codec: str):
+ allowed = hdr_mode_supported(codec)
+ if not allowed:
+ return gr.update(value=False, interactive=False)
+ return gr.update(interactive=True)
+
+
+def rename_suffix_update(mode: str):
+ return gr.update(interactive=mode == "Custom")
+
+def render_frame_interpolation_batch(
+ input_paths: list[str] | str | None,
+ target_fps: str,
+ engine: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool,
+ rename_mode: str,
+ custom_suffix: str,
+ progress=gr.Progress(track_tqdm=False),
+):
+ paths = normalize_video_paths(input_paths)
+ if not paths:
+ raise gr.Error("Choose at least one video first.")
+ effective_hdr = coerce_hdr_mode(codec, hdr_mode)
+ options = FrameInterpolationOptions(
+ ai_gpu_uuid=processing_gpu_settings()[0],
+ video_gpu_uuid=processing_gpu_settings()[1],
+ target_fps=target_fps,
+ engine=engine,
+ codec=codec,
+ container=container,
+ quality=quality,
+ hdr_mode=effective_hdr,
+ rename_mode=rename_mode,
+ custom_suffix=custom_suffix,
+ )
+
+ def report(value: float, message: str) -> None:
+ progress(value, desc=message)
+
+ try:
+ result = interpolate_videos(paths, options, report)
+ except Exception as exc:
+ traceback.print_exc()
+ return gr.update(value=None, visible=len(paths) == 1), [], [], f"Failed: {exc}"
+ ordered: list[tuple[int, list[str]]] = []
+ for item in result.successes:
+ value = item.result
+ details = (
+ f"{value.output_frames} frames; {value.selected_path}; "
+ f"native {value.native_multiplier}×; cascade stages {value.cascade_stages}; "
+ f"copied {value.copied_frames}, DLSSG {value.generated_frames}, "
+ f"cuts {value.scene_cuts}; report: {value.report_path}"
+ )
+ ordered.append(
+ (item.index, [Path(item.input_path).name, "Complete", Path(value.output_path).name, details])
+ )
+ for item in result.failures:
+ state = "Skipped" if item.error == "Cancelled before rendering." else (
+ "Cancelled" if item.cancelled else "Failed"
+ )
+ ordered.append((item.index, [Path(item.input_path).name, state, "", item.error]))
+ rows = [row for _index, row in sorted(ordered, key=lambda entry: entry[0])]
+ files = [item.result.output_path for item in result.successes]
+ try:
+ preview_mode = normalize_preview_encoding(current_preview_encoding())
+ except Exception:
+ preview_mode = "Auto"
+ preview = None
+ used_derivative = False
+ if len(paths) == 1 and result.successes:
+ preview, used_derivative = resolve_final_preview(files[0], preview_mode)
+ status = (
+ f"{'Cancelled' if result.cancelled else 'Complete'}: "
+ f"{len(result.successes)} completed, {len(result.failures)} failed/cancelled. "
+ f"Batch manifest: {result.manifest_path}"
+ )
+ if result.failures:
+ status += f"\nFirst error: {result.failures[0].error}"
+ if used_derivative:
+ status += "\nBrowser preview transcoded to H.264; the original file is unchanged."
+ return gr.update(value=preview, visible=len(paths) == 1), files, rows, status
+
+@dataclass(slots=True)
+class FrameInterpolationTab:
+ sources: object
+ input_preview: object
+ target_fps: object
+ engine: object
+ quality: object
+ codec: object
+ container: object
+ rename_mode: object
+ custom_suffix: object
+ hdr_mode: object
+ preview: object
+ render: object
+ stop: object
+ reset: object
+ output_video: object
+ output_files: object
+ status: object
+ results: object
+
+ @property
+ def render_inputs(self) -> list[object]:
+ return [
+ self.sources, self.target_fps, self.engine, self.codec, self.container, self.quality,
+ self.hdr_mode, self.rename_mode, self.custom_suffix,
+ ]
+
+ @property
+ def preview_inputs(self) -> list[object]:
+ return [self.sources, self.target_fps, self.engine, self.codec, self.container, self.quality]
+
+ @property
+ def settings_inputs(self) -> list[object]:
+ return [
+ self.target_fps, self.engine, self.codec, self.container, self.quality,
+ self.hdr_mode, self.rename_mode, self.custom_suffix,
+ ]
+
+
+def build_frame_interpolation_tab(settings: UISettings) -> FrameInterpolationTab:
+ with gr.Row():
+ with gr.Column(scale=3):
+ sources = gr.File(
+ label="Input video(s)", file_count="multiple", file_types=["video"],
+ type="filepath", allow_reordering=True, elem_id="frame-interpolation-upload-list",
+ )
+ input_preview = gr.Video(label="Input video preview", interactive=False, visible=False)
+ with gr.Accordion("DLSS Frame Generation Settings", open=True):
+ with gr.Row():
+ target_fps = gr.Dropdown(
+ FPS_CHOICES, value=settings.frame_interpolation_target_fps,
+ label="Output FPS", info="Fractional choices use exact 1001-based rates.",
+ )
+ engine = gr.Radio(
+ ENGINE_CHOICES, value=settings.frame_interpolation_engine, label="DLSS engine",
+ info="Auto uses a supported exact native grid, then the 2× cascade when required.",
+ )
+ quality = gr.Radio(
+ QUALITY_CHOICES, value=settings.frame_interpolation_quality,
+ label="Encoding quality", info="Auto uses output resolution, selected FPS, and codec.",
+ )
+ with gr.Row():
+ codec = gr.Dropdown(
+ CODEC_CHOICES, value=settings.frame_interpolation_codec,
+ label="Video codec", info="Plain = CPU, Suffixed = NVIDIA NVENC.",
+ )
+ container = gr.Dropdown(
+ CONTAINER_CHOICES, value=settings.frame_interpolation_container, label="Container"
+ )
+ with gr.Row():
+ rename_mode = gr.Radio(
+ RENAME_MODES, value=settings.frame_interpolation_rename_mode, label="Rename",
+ info="Auto adds a DLSSFG timestamp; Copy keeps the original base name; Custom appends your suffix.",
+ )
+ custom_suffix = gr.Textbox(
+ value=settings.frame_interpolation_custom_suffix, label="Custom suffix",
+ placeholder="_DLSSFG", interactive=settings.frame_interpolation_rename_mode == "Custom",
+ )
+ hdr_mode = gr.Checkbox(
+ value=settings.frame_interpolation_hdr_mode and hdr_mode_supported(settings.frame_interpolation_codec),
+ label="HDR Mode",
+ info="When on: 10-bit output, copies input colorspace; keeps HDR if input is HDR. Only for H.265 / AV1 / ProRes.",
+ interactive=hdr_mode_supported(settings.frame_interpolation_codec),
+ )
+ with gr.Row():
+ preview = gr.Button("Preview 3 sec", visible=False)
+ render = gr.Button("Interpolate video(s)", variant="primary")
+ stop = gr.Button("Stop", variant="stop")
+ reset = gr.Button("Reset settings")
+ with gr.Column(scale=3):
+ output_video = gr.Video(label="Interpolated output", interactive=False, visible=False)
+ output_files = gr.File(
+ label="Interpolated video files", file_count="multiple", interactive=False,
+ elem_id="frame-interpolation-output-list",
+ )
+ status = gr.Textbox(label="Status", interactive=False)
+ results = gr.Dataframe(
+ headers=["Input", "Result", "Output", "Details"],
+ datatype=["str", "str", "str", "str"], interactive=False,
+ label="Batch results", wrap=True,
+ )
+ tab = FrameInterpolationTab(
+ sources, input_preview, target_fps, engine, quality, codec, container, rename_mode,
+ custom_suffix, hdr_mode, preview, render, stop, reset, output_video, output_files, status, results
+ )
+ bind_frame_interpolation_events(tab)
+ return tab
+
+
+def bind_frame_interpolation_events(tab: FrameInterpolationTab) -> None:
+ tab.sources.change(
+ update_frame_interpolation_preview_mode, inputs=[tab.sources, tab.target_fps, tab.engine],
+ outputs=[tab.input_preview, tab.output_video, tab.preview],
+ queue=False, show_progress="hidden",
+ )
+ tab.codec.change(hdr_mode_update, inputs=tab.codec, outputs=tab.hdr_mode, queue=False)
+ tab.rename_mode.change(rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False)
+ tab.render.click(
+ render_frame_interpolation_batch, inputs=tab.render_inputs,
+ outputs=[tab.output_video, tab.output_files, tab.results, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_video,
+ )
+ tab.preview.click(
+ preview_frame_interpolation, inputs=tab.preview_inputs, outputs=[tab.output_video, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_video,
+ )
+ tab.stop.click(cancel_active_job, outputs=tab.status, queue=False)
+
diff --git a/src/image/__init__.py b/src/image/__init__.py
new file mode 100644
index 0000000..b205ec0
--- /dev/null
+++ b/src/image/__init__.py
@@ -0,0 +1,15 @@
+from .batch import convert_images
+from .decoder import decode_image, initialize_image_runtime, probe_image
+from .encoder import save_image, take_image_preview
+from .models import (
+ IMAGE_EXTENSIONS, IMAGE_FORMATS, RAW_EXTENSIONS, ImageBatchResult,
+ ImageConversionFailure, ImageConversionOptions, ImageConversionResult,
+)
+from .processor import convert_image
+
+__all__ = [
+ "IMAGE_EXTENSIONS", "IMAGE_FORMATS", "RAW_EXTENSIONS", "ImageBatchResult",
+ "ImageConversionFailure", "ImageConversionOptions", "ImageConversionResult",
+ "convert_image", "convert_images", "decode_image", "initialize_image_runtime",
+ "probe_image", "save_image", "take_image_preview",
+]
diff --git a/src/image/batch.py b/src/image/batch.py
new file mode 100644
index 0000000..db394fe
--- /dev/null
+++ b/src/image/batch.py
@@ -0,0 +1,415 @@
+from __future__ import annotations
+
+import os
+import time
+from concurrent.futures import Future, ThreadPoolExecutor
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Iterable
+
+import cv2
+import numpy as np
+
+from ..core.gpu_selection import resolve_runtime_ai_gpu
+from ..core.jobs import Cancelled, active_job
+from ..core.naming import output_filename, require_available_output, validate_rename
+from ..core.paths import LOGS, OUTPUTS
+from ..core.runtime import (
+ DLSSFrameSession, prepare_runtime, resize_fit, resolve_native_settings,
+ resolve_output_size, resolve_upscaling_mode, verify_feature_18, write_failure_report,
+)
+from .decoder import _DecodedImage, decode_image, probe_image
+from .encoder import _encode_image
+from .models import (
+ IMAGE_EXTENSIONS, IMAGE_FORMATS, RAW_EXTENSIONS, ImageBatchResult, ImageConversionFailure,
+ ImageConversionOptions, ImageConversionResult,
+)
+from .reports import _ImageReportData, _build_manifest_and_zip, _report_data, _write_report
+
+@dataclass(slots=True)
+class _ImageProbe:
+ index: int
+ path: Path
+ width: int
+ height: int
+ output_width: int
+ output_height: int
+ decoded: _DecodedImage | None = None
+
+def _validate_options(options: ImageConversionOptions) -> ImageConversionOptions:
+ if options.output_format not in IMAGE_FORMATS:
+ raise ValueError(f"Unknown image output format: {options.output_format!r}.")
+ if isinstance(options.quality, bool):
+ raise ValueError("Image quality must be an integer from 1 to 100.")
+ try:
+ quality = int(options.quality)
+ except (TypeError, ValueError) as exc:
+ raise ValueError("Image quality must be an integer from 1 to 100.") from exc
+ if quality != options.quality or not 1 <= quality <= 100:
+ raise ValueError("Image quality must be an integer from 1 to 100.")
+ validate_rename(options.rename_mode, options.custom_suffix)
+ resolve_native_settings(options)
+ resolve_upscaling_mode(options.upscaling_factor)
+ return options
+
+def _output_path(
+ source: Path,
+ output_format: str,
+ stamp: str,
+ index: int,
+ rename_mode: str,
+ custom_suffix: str,
+) -> Path:
+ suffix = IMAGE_EXTENSIONS[output_format]
+ safe_stem = source.stem.strip().rstrip(".") or "image"
+ return OUTPUTS / output_filename(
+ source,
+ suffix,
+ rename_mode,
+ custom_suffix,
+ f"{safe_stem}_DLSS5_IMAGE_{stamp}-{index + 1:04d}",
+ )
+
+def convert_images(
+ input_paths: Iterable[str | os.PathLike[str]],
+ options: ImageConversionOptions | None = None,
+ progress: Callable[[float, str], None] | None = None,
+) -> ImageBatchResult:
+ options = options or ImageConversionOptions()
+ neural = _validate_options(options)
+ paths = [Path(path).resolve() for path in input_paths]
+ if not paths:
+ raise ValueError("Choose at least one image.")
+ prepared_runtime = prepare_runtime()
+ OUTPUTS.mkdir(exist_ok=True)
+ LOGS.mkdir(exist_ok=True)
+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
+ batch_started = time.perf_counter()
+
+ def _report_progress(value: float, desc: str) -> None:
+ if progress is None:
+ return
+ try:
+ v = float(value)
+ v = 0.0 if v < 0 else (1.0 if v > 1 else v)
+ elapsed = time.perf_counter() - batch_started
+ if 0.01 < v < 0.99 and elapsed > 0.5:
+ eta = elapsed * (1 - v) / max(v, 1e-6)
+ desc = f"{desc} - Time Remaining: {eta:.1f}s"
+ progress(v, desc)
+ except Exception:
+ try:
+ progress(value, desc)
+ except Exception:
+ pass
+
+ failures_by_index: dict[int, ImageConversionFailure] = {}
+ probes: list[_ImageProbe] = []
+ for index, path in enumerate(paths):
+ try:
+ decoded: _DecodedImage | None = None
+ if path.suffix.lower() in {*RAW_EXTENSIONS, ".svg"}:
+ decoded = decode_image(path)
+ height, width = decoded.rgba.shape[:2]
+ if width < 64 or height < 64:
+ raise ValueError(
+ f"{path.name} is {width}×{height}; DLSS requires both input "
+ "dimensions to be at least 64 pixels."
+ )
+ else:
+ width, height = probe_image(path)
+ output_width, output_height = resolve_output_size(
+ width, height, options.upscaling_factor
+ )
+ probes.append(
+ _ImageProbe(
+ index, path, width, height, output_width, output_height, decoded
+ )
+ )
+ except Exception as exc:
+ failures_by_index[index] = ImageConversionFailure(str(path), str(exc))
+
+ planned_outputs: dict[int, Path] = {}
+ reserved_outputs: set[str] = set()
+ available_probes: list[_ImageProbe] = []
+ for probe in probes:
+ output = _output_path(
+ probe.path,
+ options.output_format,
+ stamp,
+ probe.index,
+ options.rename_mode,
+ options.custom_suffix,
+ )
+ output_key = str(output.resolve()).casefold()
+ try:
+ require_available_output(output)
+ if output_key in reserved_outputs:
+ raise FileExistsError(
+ f"More than one input would create {output.name}. "
+ "Choose Auto naming or use unique input names."
+ )
+ except Exception as exc:
+ failures_by_index[probe.index] = ImageConversionFailure(
+ str(probe.path), str(exc)
+ )
+ continue
+ reserved_outputs.add(output_key)
+ planned_outputs[probe.index] = output
+ available_probes.append(probe)
+ probes = available_probes
+
+ if not probes:
+ manifest_path, zip_path = _build_manifest_and_zip(
+ stamp, options, [], list(failures_by_index.values()), False
+ )
+ return ImageBatchResult([], list(failures_by_index.values()), False, manifest_path, zip_path)
+
+ groups: dict[tuple[int, int], list[_ImageProbe]] = {}
+ for probe in probes:
+ groups.setdefault((probe.output_width, probe.output_height), []).append(probe)
+
+ successes_by_index: dict[int, ImageConversionResult] = {}
+ cancelled = False
+ gpu: dict | None = None
+ processed_total = 0
+ decode_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="dlss5-image-decode")
+ encode_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="dlss5-image-encode")
+ with active_job() as controller:
+ gpu = resolve_runtime_ai_gpu(
+ prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid
+ )
+ runtime_bundle = prepared_runtime.runtime_bundle
+ _report_progress(0.0, f"Starting feature 18 on {gpu['display_name']}")
+ total = len(probes)
+ factor, mode = resolve_upscaling_mode(neural.upscaling_factor)
+ native_settings = resolve_native_settings(neural)
+ try:
+ for (output_width, output_height), group in groups.items():
+ cursor = 0
+ while cursor < len(group):
+ if controller.cancel.is_set():
+ cancelled = True
+ break
+ remaining = group[cursor:]
+ first = remaining[0]
+ try:
+ session = DLSSFrameSession(
+ input_width=first.width,
+ input_height=first.height,
+ output_width=output_width,
+ output_height=output_height,
+ frame_count=len(remaining),
+ warmup_frames=neural.warmup_frames,
+ factor=factor,
+ mode=mode,
+ native_settings=native_settings,
+ 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), failure)
+ break
+
+ segment: list[
+ tuple[
+ _ImageProbe,
+ ImageConversionResult,
+ _ImageReportData,
+ Future[list[str]],
+ float,
+ ]
+ ] = []
+ sent = 0
+ motion = np.zeros(
+ (session.render_height, session.render_width, 2), dtype=np.float16
+ )
+ interrupted = False
+ close_error: Exception | None = None
+ decode_future: Future[_DecodedImage] | None = decode_executor.submit(
+ lambda probe=group[cursor]: probe.decoded or decode_image(probe.path)
+ )
+ while cursor < len(group):
+ item = group[cursor]
+ started = time.perf_counter()
+ if controller.cancel.is_set():
+ cancelled = True
+ interrupted = True
+ session.abort()
+ break
+ _report_progress(processed_total / max(1, total), f"Preparing {item.path.name}")
+ try:
+ assert decode_future is not None
+ decoded = decode_future.result()
+ item.decoded = None
+ next_cursor = cursor + 1
+ decode_future = (
+ decode_executor.submit(
+ lambda probe=group[next_cursor]:
+ probe.decoded or decode_image(probe.path)
+ )
+ if next_cursor < len(group)
+ else None
+ )
+ except Exception as exc:
+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))
+ cursor += 1
+ processed_total += 1
+ session.abort()
+ interrupted = True
+ break
+ try:
+ render_rgba = resize_fit(
+ decoded.rgba, session.render_width, session.render_height
+ )
+ processed, _pts = session.process(
+ index=sent,
+ rgba=render_rgba,
+ motion=motion,
+ reset=True,
+ pts=sent,
+ )
+ alpha = (
+ decoded.alpha
+ if decoded.alpha.shape == (output_height, output_width)
+ else cv2.resize(
+ decoded.alpha,
+ (output_width, output_height),
+ interpolation=cv2.INTER_LANCZOS4,
+ )
+ )
+ processed[..., 3] = alpha
+ output = planned_outputs[item.index]
+ result = ImageConversionResult(
+ str(item.path),
+ str(output),
+ "",
+ time.perf_counter() - started,
+ str(gpu["display_name"]),
+ item.width,
+ item.height,
+ session.render_width,
+ session.render_height,
+ output_width,
+ output_height,
+ float(options.upscaling_factor),
+ str(session.mode["name"]),
+ options.output_format,
+ options.dlss_model_preset,
+ session.applied_dlss_model_preset,
+ list(decoded.warnings),
+ )
+ encoding = encode_executor.submit(
+ _encode_image, output, processed, options, decoded.metadata
+ )
+ segment.append(
+ (item, result, _report_data(decoded), encoding, started)
+ )
+ # Keep at most two full rendered frames queued for encoding.
+ # Completed futures retain only their small warning list.
+ if len(segment) > 2:
+ segment[-3][3].result()
+ sent += 1
+ except Cancelled:
+ cancelled = True
+ session.abort()
+ interrupted = True
+ break
+ except Exception as 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
+ break
+ cursor += 1
+ processed_total += 1
+ _report_progress(processed_total / total, f"Rendered {item.path.name}")
+
+ if not segment and interrupted:
+ if cancelled:
+ break
+ continue
+ if not interrupted:
+ try:
+ session.close()
+ except Exception as exc:
+ close_error = exc
+ try:
+ if close_error:
+ raise close_error
+ evidence = verify_feature_18(
+ session.worker_logs, session.reshade_log_text()
+ )
+ assert gpu is not None
+ for item, result, decoded, encoding, item_started in segment:
+ result.warnings.extend(encoding.result())
+ result.elapsed_seconds = time.perf_counter() - item_started
+ for item, result, decoded, _encoding, _item_started in segment:
+ result.report_path = _write_report(
+ result, options, decoded, gpu, session, evidence
+ )
+ 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, *_rest 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, encoding, _item_started in segment:
+ if not encoding.done():
+ encoding.cancel()
+ output = Path(result.output_path)
+ if output.exists():
+ output.unlink()
+ failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)
+ if cancelled:
+ break
+ if cancelled:
+ break
+ finally:
+ decode_executor.shutdown(wait=True, cancel_futures=True)
+ encode_executor.shutdown(wait=True, cancel_futures=True)
+ if cancelled:
+ completed = set(successes_by_index) | set(failures_by_index)
+ for probe in probes:
+ if probe.index not in completed:
+ failures_by_index[probe.index] = ImageConversionFailure(
+ str(probe.path), "Cancelled before rendering."
+ )
+ successes = [successes_by_index[index] for index in sorted(successes_by_index)]
+ failures = [failures_by_index[index] for index in sorted(failures_by_index)]
+ manifest_path, zip_path = _build_manifest_and_zip(
+ stamp, options, successes, failures, cancelled
+ )
+ _report_progress(1.0, "Cancelled" if cancelled else "Complete")
+ return ImageBatchResult(successes, failures, cancelled, manifest_path, zip_path)
diff --git a/src/image/decoder.py b/src/image/decoder.py
new file mode 100644
index 0000000..f9d6872
--- /dev/null
+++ b/src/image/decoder.py
@@ -0,0 +1,144 @@
+from __future__ import annotations
+
+import io
+import os
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+
+import numpy as np
+import pillow_heif
+import rawpy
+import resvg_py
+from PIL import Image, ImageCms, ImageOps
+
+from .models import RAW_EXTENSIONS
+
+pillow_heif.register_heif_opener()
+Image.MAX_IMAGE_PIXELS = 100_000_000
+
+@dataclass(slots=True)
+class _DecodedImage:
+ rgba: np.ndarray
+ alpha: np.ndarray
+ decoder: str
+ metadata: dict[str, object]
+ warnings: list[str]
+
+def _orientation_swaps_dimensions(image: Image.Image) -> bool:
+ try:
+ return int(image.getexif().get(274, 1)) in {5, 6, 7, 8}
+ except (TypeError, ValueError):
+ return False
+
+
+def _open_pillow_source(path: Path) -> tuple[Image.Image, str]:
+ suffix = path.suffix.lower()
+ if suffix in RAW_EXTENSIONS:
+ with rawpy.imread(str(path)) as raw:
+ array = raw.postprocess(
+ use_camera_wb=True,
+ output_color=rawpy.ColorSpace.sRGB,
+ output_bps=8,
+ )
+ return Image.fromarray(array, mode="RGB"), "LibRaw"
+ if suffix == ".svg":
+ png = resvg_py.svg_to_bytes(svg_path=str(path), resources_dir=str(path.parent))
+ return Image.open(io.BytesIO(png)), "resvg"
+ return Image.open(path), "Pillow"
+
+
+def probe_image(path: str | os.PathLike[str]) -> tuple[int, int]:
+ source = Path(path).resolve()
+ if not source.is_file():
+ raise FileNotFoundError(source)
+ image, _decoder = _open_pillow_source(source)
+ try:
+ width, height = image.size
+ if _orientation_swaps_dimensions(image):
+ width, height = height, width
+ finally:
+ image.close()
+ if width < 64 or height < 64:
+ raise ValueError(
+ f"{source.name} is {width}×{height}; DLSS requires both input dimensions to be at least 64 pixels."
+ )
+ return width, height
+
+
+@lru_cache(maxsize=1)
+def _srgb_profile_bytes() -> bytes:
+ return ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
+
+
+def initialize_image_runtime() -> None:
+ """Initialize reusable image color-management state during app preparation."""
+ _srgb_profile_bytes()
+
+def decode_image(path: str | os.PathLike[str]) -> _DecodedImage:
+ source = Path(path).resolve()
+ image, decoder = _open_pillow_source(source)
+ opened_image = image
+ warnings: list[str] = []
+ try:
+ frame_count = int(getattr(image, "n_frames", 1) or 1)
+ if frame_count > 1:
+ warnings.append(f"Used the first frame/page of {frame_count}.")
+ image.seek(0)
+ original_mode = image.mode
+ info = dict(image.info)
+ image = ImageOps.exif_transpose(image)
+ image.load()
+ if original_mode not in {"1", "L", "LA", "P", "RGB", "RGBA", "CMYK"}:
+ warnings.append(f"Converted {original_mode} source data to 8-bit SDR sRGB.")
+
+ has_alpha = image.mode in {"LA", "RGBA"} or (
+ image.mode == "P" and "transparency" in info
+ )
+ alpha_image = (
+ image.convert("RGBA").getchannel("A")
+ if has_alpha
+ else Image.new("L", image.size, 255)
+ )
+ rgb_image = image.convert("RGB")
+ icc_profile = info.get("icc_profile")
+ if isinstance(icc_profile, bytes) and icc_profile:
+ try:
+ source_profile = ImageCms.ImageCmsProfile(io.BytesIO(icc_profile))
+ rgb_image = ImageCms.profileToProfile(
+ rgb_image,
+ source_profile,
+ ImageCms.createProfile("sRGB"),
+ outputMode="RGB",
+ )
+ except (ImageCms.PyCMSError, OSError, ValueError) as exc:
+ warnings.append(f"Embedded color profile could not be applied ({exc}); assumed sRGB.")
+
+ rgb = np.asarray(rgb_image, dtype=np.uint8)
+ alpha = np.asarray(alpha_image, dtype=np.uint8)
+ rgba = np.empty((*rgb.shape[:2], 4), dtype=np.uint8)
+ rgba[..., :3] = rgb
+ rgba[..., 3] = alpha
+ exif = image.getexif()
+ if exif:
+ exif[274] = 1
+ metadata: dict[str, object] = {
+ "icc_profile": _srgb_profile_bytes(),
+ "exif": exif.tobytes() if exif else None,
+ "dpi": info.get("dpi"),
+ "xmp": info.get("xmp"),
+ "source_mode": original_mode,
+ "source_format": image.format or source.suffix.lstrip(".").upper(),
+ "frame_count": frame_count,
+ }
+ return _DecodedImage(
+ np.ascontiguousarray(rgba),
+ np.ascontiguousarray(alpha),
+ decoder,
+ metadata,
+ warnings,
+ )
+ finally:
+ image.close()
+ if opened_image is not image:
+ opened_image.close()
diff --git a/src/image/encoder.py b/src/image/encoder.py
new file mode 100644
index 0000000..fcd66f7
--- /dev/null
+++ b/src/image/encoder.py
@@ -0,0 +1,116 @@
+from __future__ import annotations
+
+import os
+import threading
+import time
+from collections import OrderedDict
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+from .models import ImageConversionOptions
+
+_PREVIEW_CACHE_LIMIT = 32
+_preview_cache: OrderedDict[str, Image.Image] = OrderedDict()
+_preview_cache_lock = threading.Lock()
+
+def take_image_preview(output_path: str | os.PathLike[str]) -> Image.Image | None:
+ """Return and remove a UI thumbnail created from the rendered frame in memory."""
+ key = str(Path(output_path).resolve())
+ with _preview_cache_lock:
+ return _preview_cache.pop(key, None)
+
+
+def _remember_image_preview(
+ output_path: Path, rgba: np.ndarray, output_format: str
+) -> None:
+ image = Image.fromarray(rgba, mode="RGBA")
+ try:
+ if output_format == "JPEG":
+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))
+ background.alpha_composite(image)
+ preview = background
+ else:
+ preview = image.copy()
+ preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)
+ key = str(output_path.resolve())
+ with _preview_cache_lock:
+ previous = _preview_cache.pop(key, None)
+ if previous is not None:
+ previous.close()
+ _preview_cache[key] = preview
+ while len(_preview_cache) > _PREVIEW_CACHE_LIMIT:
+ _unused_key, unused = _preview_cache.popitem(last=False)
+ unused.close()
+ finally:
+ image.close()
+
+
+def _encode_image(
+ output: Path,
+ rgba: np.ndarray,
+ options: ImageConversionOptions,
+ metadata: dict[str, object],
+) -> list[str]:
+ warnings = save_image(output, rgba, options, metadata)
+ try:
+ _remember_image_preview(output, rgba, options.output_format)
+ except Exception:
+ # A UI convenience must never invalidate an otherwise correct output.
+ pass
+ return warnings
+
+def _metadata_save_args(metadata: dict[str, object], output_format: str) -> dict[str, object]:
+ args: dict[str, object] = {}
+ if metadata.get("icc_profile"):
+ args["icc_profile"] = metadata["icc_profile"]
+ if metadata.get("dpi"):
+ args["dpi"] = metadata["dpi"]
+ if metadata.get("exif") and output_format in {"JPEG", "WebP", "AVIF", "TIFF", "PNG"}:
+ args["exif"] = metadata["exif"]
+ if metadata.get("xmp") and output_format in {"WebP", "AVIF"}:
+ args["xmp"] = metadata["xmp"]
+ return args
+
+
+def save_image(
+ output: Path,
+ rgba: np.ndarray,
+ options: ImageConversionOptions,
+ metadata: dict[str, object],
+) -> list[str]:
+ output_format = options.output_format
+ image = Image.fromarray(rgba, mode="RGBA")
+ warnings: list[str] = []
+ args = _metadata_save_args(metadata, output_format) if options.preserve_metadata else {}
+ if output_format == "PNG":
+ args.update(optimize=False, compress_level=6)
+ elif output_format == "TIFF":
+ args.update(compression="tiff_deflate")
+ elif output_format == "JPEG":
+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))
+ background.alpha_composite(image)
+ image = background.convert("RGB")
+ args.update(
+ quality=int(options.quality),
+ subsampling=0,
+ optimize=False,
+ progressive=False,
+ )
+ if np.any(rgba[..., 3] != 255):
+ warnings.append("Transparency was composited over white for JPEG output.")
+ elif output_format == "WebP":
+ args.update(quality=int(options.quality), method=6)
+ elif output_format == "AVIF":
+ args.update(quality=int(options.quality), speed=4)
+
+ temporary = output.with_name(f".{output.stem}.{time.time_ns()}{output.suffix}")
+ try:
+ image.save(temporary, format=output_format, **args)
+ os.replace(temporary, output)
+ finally:
+ image.close()
+ if temporary.exists():
+ temporary.unlink()
+ return warnings
diff --git a/src/image/models.py b/src/image/models.py
new file mode 100644
index 0000000..16548ff
--- /dev/null
+++ b/src/image/models.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+IMAGE_FORMATS = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")
+IMAGE_EXTENSIONS = {"PNG": ".png", "JPEG": ".jpg", "WebP": ".webp", "AVIF": ".avif", "TIFF": ".tiff"}
+RAW_EXTENSIONS = {
+ ".3fr", ".arw", ".bay", ".cap", ".cr2", ".cr3", ".dcr", ".dcs", ".dng",
+ ".drf", ".eip", ".erf", ".fff", ".gpr", ".iiq", ".k25", ".kdc", ".mdc",
+ ".mef", ".mos", ".mrw", ".nef", ".nrw", ".obm", ".orf", ".pef", ".ptx",
+ ".pxn", ".r3d", ".raf", ".raw", ".rw2", ".rwl", ".rwz", ".sr2", ".srf",
+ ".srw", ".x3f",
+}
+
+@dataclass(slots=True)
+class ImageConversionOptions:
+ ai_gpu_uuid: str = "auto"
+ nr_style: str = "Default"
+ nr_intensity: float = 1.0
+ local_tone_strength: float = 1.0
+ local_structure_strength: float = 1.0
+ skin_structure_strength: float = -1.0
+ upscaling_factor: float = 1.0
+ output_format: str = "PNG"
+ quality: int = 95
+ preserve_metadata: bool = True
+ warmup_frames: int = 0
+ nr_preset: str = "Default"
+ automatic_mask: bool = False
+ rename_mode: str = "Auto"
+ custom_suffix: str = "_DLSS5"
+ dlss_model_preset: str = "Default"
+
+ def neural_options(self) -> "ImageConversionOptions":
+ # Image already carries every shared neural-rendering field needed by core.runtime.
+ return self
+
+
+@dataclass(slots=True)
+class ImageConversionResult:
+ input_path: str
+ output_path: str
+ report_path: str
+ elapsed_seconds: float
+ gpu: str
+ input_width: int
+ input_height: int
+ render_width: int
+ render_height: int
+ output_width: int
+ output_height: int
+ upscaling_factor: float
+ dlss_mode: str
+ output_format: str
+ dlss_model_preset: str = "Default"
+ applied_dlss_model_preset: int = 0
+ warnings: list[str] = field(default_factory=list)
+
+
+@dataclass(slots=True)
+class ImageConversionFailure:
+ input_path: str
+ error: str
+
+
+@dataclass(slots=True)
+class ImageBatchResult:
+ successes: list[ImageConversionResult]
+ failures: list[ImageConversionFailure]
+ cancelled: bool
+ manifest_path: str
+ zip_path: str | None
diff --git a/src/image/processor.py b/src/image/processor.py
new file mode 100644
index 0000000..f266970
--- /dev/null
+++ b/src/image/processor.py
@@ -0,0 +1,19 @@
+from __future__ import annotations
+
+import os
+from typing import Callable
+
+from .batch import convert_images
+from .models import ImageConversionOptions, ImageConversionResult
+
+def convert_image(
+ input_path: str | os.PathLike[str],
+ options: ImageConversionOptions | None = None,
+ progress: Callable[[float, str], None] | None = None,
+) -> ImageConversionResult:
+ result = convert_images([input_path], options, progress)
+ if result.successes:
+ return result.successes[0]
+ if result.failures:
+ raise RuntimeError(result.failures[0].error)
+ raise RuntimeError("Image conversion produced no result.")
diff --git a/src/image/reports.py b/src/image/reports.py
new file mode 100644
index 0000000..249af01
--- /dev/null
+++ b/src/image/reports.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+import json
+import os
+import time
+import zipfile
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+from PIL import TiffImagePlugin
+
+from ..core.paths import LOGS, OUTPUTS
+from ..core.runtime import DLSSFrameSession, DLSS_MODEL_PRESETS
+from .decoder import _DecodedImage
+from .models import ImageConversionFailure, ImageConversionOptions, ImageConversionResult
+
+@dataclass(slots=True)
+class _ImageReportData:
+ decoder: str
+ metadata: dict[str, object]
+ warnings: list[str]
+
+
+def _report_data(decoded: _DecodedImage) -> _ImageReportData:
+ """Keep diagnostics without retaining the decoded pixel and alpha arrays."""
+ return _ImageReportData(decoded.decoder, decoded.metadata, decoded.warnings)
+
+
+def _json_safe_metadata(value: object) -> object:
+ """Create a report-only JSON-safe copy without changing save metadata."""
+ if value is None or isinstance(value, (bool, int, float, str)):
+ return value
+ if isinstance(value, TiffImagePlugin.IFDRational):
+ return float(value)
+ if isinstance(value, dict):
+ return {str(key): _json_safe_metadata(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple, set)):
+ return [_json_safe_metadata(item) for item in value]
+ if isinstance(value, bytes):
+ return {"type": "bytes", "length": len(value)}
+ return str(value)
+
+def _write_report(
+ result: ImageConversionResult,
+ options: ImageConversionOptions,
+ decoded: _ImageReportData,
+ gpu: dict,
+ session: DLSSFrameSession,
+ evidence: dict[str, object],
+) -> str:
+ report = {
+ "status": "success",
+ "input": result.input_path,
+ "output": result.output_path,
+ "options": asdict(options),
+ "gpu": gpu,
+ "decoder": decoded.decoder,
+ "source_metadata": {
+ key: _json_safe_metadata(value)
+ for key, value in decoded.metadata.items()
+ if key not in {"icc_profile", "exif", "xmp"}
+ },
+ "warnings": result.warnings,
+ "input_dimensions": {"width": result.input_width, "height": result.input_height},
+ "negotiated_render_dimensions": {"width": result.render_width, "height": result.render_height},
+ "negotiated_render_range": {
+ "minimum": {"width": session.minimum_width, "height": session.minimum_height},
+ "maximum": {"width": session.maximum_width, "height": session.maximum_height},
+ },
+ "output_dimensions": {"width": result.output_width, "height": result.output_height},
+ "dlss_mode": result.dlss_mode,
+ "requested_upscaling_factor": result.upscaling_factor,
+ "dlss_model_preset": result.dlss_model_preset,
+ "requested_dlss_model_preset": result.dlss_model_preset,
+ "requested_dlss_model_preset_code": DLSS_MODEL_PRESETS[
+ result.dlss_model_preset
+ ],
+ "applied_dlss_model_preset": result.applied_dlss_model_preset,
+ "applied_dlss_model_preset_name": next(
+ name
+ for name, code in DLSS_MODEL_PRESETS.items()
+ if code == result.applied_dlss_model_preset
+ ),
+ "pipeline": "renodx-dlssnr-feature18-image",
+ "feature_id": 18,
+ "feature_18_confirmed": True,
+ "ngx_setup_result": f"0x{session.setup_result:08X}",
+ "carrier_create_result": evidence["carrier_create_result"],
+ "native_settings": session.native_settings,
+ "addon_release": session.runtime_bundle["addon"]["release"],
+ "worker_log": session.worker_logs,
+ "worker_log_dropped_lines": session.worker_log_dropped_lines,
+ "dlssnr_evidence": evidence["evidence"],
+ "elapsed_seconds": result.elapsed_seconds,
+ }
+ report_path = LOGS / f"{Path(result.output_path).name}.report.json"
+ report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
+ return str(report_path)
+
+
+def _build_manifest_and_zip(
+ stamp: str,
+ options: ImageConversionOptions,
+ successes: list[ImageConversionResult],
+ failures: list[ImageConversionFailure],
+ cancelled: bool,
+) -> tuple[str, str | None]:
+ manifest = {
+ "status": "cancelled" if cancelled else ("partial" if failures else "success"),
+ "options": asdict(options),
+ "successes": [asdict(item) for item in successes],
+ "failures": [asdict(item) for item in failures],
+ }
+ manifest_path = LOGS / f"DLSS5_IMAGE_BATCH_{stamp}.manifest.json"
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+ if not successes:
+ return str(manifest_path), None
+ zip_path = OUTPUTS / f"DLSS5_IMAGE_BATCH_{stamp}.zip"
+ temporary = zip_path.with_name(f".{zip_path.stem}.{time.time_ns()}.zip")
+ try:
+ with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED) as archive:
+ for item in successes:
+ archive.write(item.output_path, arcname=Path(item.output_path).name)
+ os.replace(temporary, zip_path)
+ finally:
+ if temporary.exists():
+ temporary.unlink()
+ return str(manifest_path), str(zip_path)
diff --git a/src/image/ui.py b/src/image/ui.py
new file mode 100644
index 0000000..54c8172
--- /dev/null
+++ b/src/image/ui.py
@@ -0,0 +1,281 @@
+from __future__ import annotations
+
+import traceback
+from dataclasses import dataclass
+from pathlib import Path
+
+import gradio as gr
+from PIL import Image
+
+from ..core.jobs import cancel_active_job
+from ..core.naming import RENAME_MODES
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES
+from ..settings.models import AUTOMATIC_MASK_CHOICES, UISettings, automatic_mask_choice, parse_automatic_mask
+from ..settings.storage import processing_gpu_settings
+from .decoder import decode_image
+from .encoder import take_image_preview
+from .batch import convert_images
+from .models import IMAGE_FORMATS, RAW_EXTENSIONS, ImageConversionOptions
+
+
+def rename_suffix_update(mode: str):
+ return gr.update(interactive=mode == "Custom")
+
+
+UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
+
+
+def build_neural_controls(settings: UISettings):
+ nr_preset = gr.Dropdown(
+ list(NR_PRESETS), value=settings.nr_preset, label="NR Preset",
+ info="Experimental content-dependent neural-rendering model hint. Default is recommended."
+ )
+ nr_style = gr.Radio(
+ list(NR_STYLES), value=settings.nr_style, label="NR Style",
+ info="Selects the native neural-rendering style."
+ )
+ upscaling_factor = gr.Dropdown(
+ choices=list(UPSCALING_CHOICES), value=settings.upscaling_factor,
+ label="Upscaling factor", info="Uses NVIDIA's fixed DLSS modes. DLAA keeps source resolution."
+ )
+ with gr.Row():
+ nr_intensity = gr.Slider(
+ 0.0, 2.0, value=settings.nr_intensity, step=0.05, precision=2,
+ label="NR Intensity", info="Overall neural-rendering strength.", buttons=["reset"]
+ )
+ local_tone_strength = gr.Slider(
+ 0.0, 2.0, value=settings.local_tone_strength, step=0.05, precision=2,
+ label="Local Tone Strength", info="Local tone and contrast enhancement.", buttons=["reset"]
+ )
+ with gr.Row():
+ local_structure_strength = gr.Slider(
+ 0.0, 2.0, value=settings.local_structure_strength, step=0.05, precision=2,
+ label="Local Structure Strength", info="Local detail and texture structure.", buttons=["reset"]
+ )
+ skin_structure_strength = gr.Slider(
+ -1.0, 2.0, value=settings.skin_structure_strength, step=0.05, precision=2,
+ 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, automatic_mask
+ ]
+
+
+def build_dlss_model_control(settings: UISettings):
+ return gr.Dropdown(
+ choices=list(DLSS_MODEL_PRESETS),
+ value=settings.dlss_model_preset,
+ label="DLSS Model Preset",
+ info=(
+ "Default lets NVIDIA select its normal mode-specific presets. "
+ "J, K, L, or M forces that model preset for every DLSS scaling mode."
+ ),
+ )
+
+def preview_input_images(paths: list[str] | str | None):
+ if not paths:
+ return []
+ if isinstance(paths, str):
+ paths = [paths]
+ previews = []
+ for raw_path in paths:
+ try:
+ decoded = decode_image(raw_path)
+ image = Image.fromarray(decoded.rgba, mode="RGBA")
+ image.thumbnail((1200, 900), Image.Resampling.LANCZOS)
+ previews.append((image, Path(raw_path).name))
+ except Exception:
+ continue
+ return previews
+
+
+def render_image_batch(
+ input_paths: list[str] | str | None,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ image_format: str,
+ image_quality: float,
+ rename_mode: str,
+ custom_suffix: str,
+ progress=gr.Progress(track_tqdm=False),
+):
+ if not input_paths:
+ raise gr.Error("Choose at least one image first.")
+ if isinstance(input_paths, str):
+ input_paths = [input_paths]
+ options = ImageConversionOptions(
+ ai_gpu_uuid=processing_gpu_settings()[0],
+ nr_preset=nr_preset,
+ nr_style=nr_style,
+ nr_intensity=nr_intensity,
+ 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),
+ dlss_model_preset=dlss_model_preset,
+ upscaling_factor=upscaling_factor,
+ output_format=image_format,
+ quality=int(image_quality),
+ rename_mode=rename_mode,
+ custom_suffix=custom_suffix,
+ )
+
+ def report(value: float, message: str) -> None:
+ progress(value, desc=message)
+
+ try:
+ result = convert_images(input_paths, options, progress=report)
+ except Exception as exc:
+ traceback.print_exc()
+ return [], [], None, [], f"Failed: {exc}"
+
+ gallery = []
+ for item in result.successes:
+ preview = take_image_preview(item.output_path)
+ if preview is None:
+ with Image.open(item.output_path) as output:
+ preview = output.convert("RGBA")
+ preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)
+ preview = preview.copy()
+ gallery.append((preview, Path(item.output_path).name))
+ files = [item.output_path for item in result.successes]
+ rows = [
+ [Path(item.input_path).name, "Complete", Path(item.output_path).name, "; ".join(item.warnings)]
+ for item in result.successes
+ ]
+ rows.extend(
+ [Path(item.input_path).name, "Failed", "", item.error] for item in result.failures
+ )
+ state = "Cancelled" if result.cancelled else "Complete"
+ status = (
+ f"{state}: {len(result.successes)} image(s) rendered, {len(result.failures)} failed. "
+ "Every successful output returned feature-18 success and has a diagnostic report."
+ )
+ if result.failures:
+ status += f"\nFirst error: {result.failures[0].error}"
+ return gallery, files, result.zip_path, rows, status
+
+@dataclass(slots=True)
+class ImageTab:
+ sources: object
+ input_gallery: object
+ neural: list[object]
+ model_preset: object
+ output_format: object
+ quality: object
+ rename_mode: object
+ custom_suffix: object
+ render: object
+ stop: object
+ reset: object
+ output_gallery: object
+ output_files: object
+ zip_download: object
+ status: object
+ results: object
+
+ @property
+ def render_inputs(self) -> list[object]:
+ return [self.sources, *self.neural, self.model_preset, self.output_format, self.quality, self.rename_mode, self.custom_suffix]
+
+ @property
+ def settings_inputs(self) -> list[object]:
+ return [*self.neural, self.model_preset, self.output_format, self.quality, self.rename_mode, self.custom_suffix]
+
+
+def build_image_tab(settings: UISettings) -> ImageTab:
+ upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]
+ with gr.Row():
+ with gr.Column(scale=3):
+ sources = gr.File(
+ label="Input image(s)", file_count="multiple", file_types=upload_types,
+ type="filepath", allow_reordering=True, elem_id="image-upload-list",
+ )
+ input_gallery = gr.Gallery(
+ label="Input preview", columns=3, height=520, object_fit="contain",
+ interactive=False, buttons=["fullscreen"], elem_id="image-input-preview",
+ )
+ with gr.Accordion("DLSS 5 Neural Rendering Settings", open=True):
+ neural = build_neural_controls(settings)
+ with gr.Accordion("DLSS 5 Settings", open=True):
+ model_preset = build_dlss_model_control(settings)
+ with gr.Row():
+ output_format = gr.Dropdown(
+ list(IMAGE_FORMATS), value=settings.image_format, label="Output format",
+ info="PNG and TIFF are lossless; JPEG composites transparency over white.",
+ )
+ quality = gr.Slider(
+ 1, 100, value=settings.image_quality, step=1, precision=0,
+ label="Lossy quality", info="Used by JPEG, WebP, and AVIF; ignored by PNG/TIFF.",
+ )
+ with gr.Row():
+ rename_mode = gr.Radio(
+ RENAME_MODES, value=settings.image_rename_mode, label="Rename",
+ info="Auto adds the current DLSS5 timestamp; Copy keeps the original base name; Custom appends your suffix.",
+ )
+ custom_suffix = gr.Textbox(
+ value=settings.image_custom_suffix, label="Custom suffix", placeholder="_DLSS5",
+ interactive=settings.image_rename_mode == "Custom",
+ )
+ with gr.Row():
+ render = gr.Button("Render image(s)", variant="primary")
+ stop = gr.Button("Stop", variant="stop")
+ reset = gr.Button("Reset settings")
+ with gr.Column(scale=3):
+ output_gallery = gr.Gallery(
+ label="Enhanced previews", columns=2, height=520, object_fit="contain",
+ interactive=False, buttons=["download", "download_all", "fullscreen"],
+ elem_id="image-output-preview",
+ )
+ output_files = gr.File(
+ label="Rendered image files", file_count="multiple", interactive=False,
+ elem_id="image-output-list",
+ )
+ zip_download = gr.DownloadButton("Download successful images as ZIP")
+ status = gr.Textbox(label="Status", interactive=False)
+ results = gr.Dataframe(
+ headers=["Input", "Result", "Output", "Details"],
+ datatype=["str", "str", "str", "str"], interactive=False,
+ label="Batch results", wrap=True,
+ )
+ tab = ImageTab(
+ sources, input_gallery, neural, model_preset, output_format, quality, rename_mode,
+ custom_suffix, render, stop, reset, output_gallery, output_files, zip_download, status, results
+ )
+ bind_image_events(tab)
+ return tab
+
+
+def bind_image_events(tab: ImageTab) -> None:
+ tab.sources.change(
+ preview_input_images, inputs=tab.sources, outputs=tab.input_gallery,
+ queue=False, show_progress="hidden",
+ )
+ tab.rename_mode.change(
+ rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False,
+ )
+ tab.render.click(
+ render_image_batch, inputs=tab.render_inputs,
+ outputs=[tab.output_gallery, tab.output_files, tab.zip_download, tab.results, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_gallery,
+ )
+ tab.stop.click(cancel_active_job, outputs=tab.status, queue=False)
+
diff --git a/src/images.py b/src/images.py
deleted file mode 100644
index c613622..0000000
--- a/src/images.py
+++ /dev/null
@@ -1,883 +0,0 @@
-from __future__ import annotations
-
-import io
-import json
-import os
-import threading
-import time
-import zipfile
-from collections import OrderedDict
-from concurrent.futures import Future, ThreadPoolExecutor
-from dataclasses import asdict, dataclass, field
-from functools import lru_cache
-from pathlib import Path
-from typing import Callable, Iterable
-
-import cv2
-import numpy as np
-import pillow_heif
-import rawpy
-import resvg_py
-from PIL import Image, ImageCms, ImageOps, TiffImagePlugin
-
-from .naming import output_filename, require_available_output, validate_rename
-from .runtime import (
- LOGS,
- OUTPUTS,
- Cancelled,
- DLSSFrameSession,
- active_job,
- resize_fit,
- resolve_runtime_ai_gpu,
- validate_gpu_runtime,
- verify_feature_18,
- write_failure_report,
-)
-from .video import (
- ConversionOptions,
- DLSS_MODEL_PRESETS,
- resolve_native_settings,
- resolve_output_size,
- resolve_upscaling_mode,
-)
-
-
-pillow_heif.register_heif_opener()
-Image.MAX_IMAGE_PIXELS = 100_000_000
-
-IMAGE_FORMATS = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")
-IMAGE_EXTENSIONS = {"PNG": ".png", "JPEG": ".jpg", "WebP": ".webp", "AVIF": ".avif", "TIFF": ".tiff"}
-_PREVIEW_CACHE_LIMIT = 32
-_preview_cache: OrderedDict[str, Image.Image] = OrderedDict()
-_preview_cache_lock = threading.Lock()
-RAW_EXTENSIONS = {
- ".3fr", ".arw", ".bay", ".cap", ".cr2", ".cr3", ".dcr", ".dcs", ".dng",
- ".drf", ".eip", ".erf", ".fff", ".gpr", ".iiq", ".k25", ".kdc", ".mdc",
- ".mef", ".mos", ".mrw", ".nef", ".nrw", ".obm", ".orf", ".pef", ".ptx",
- ".pxn", ".r3d", ".raf", ".raw", ".rw2", ".rwl", ".rwz", ".sr2", ".srf",
- ".srw", ".x3f",
-}
-
-
-@dataclass(slots=True)
-class ImageConversionOptions:
- ai_gpu_uuid: str = "auto"
- nr_style: str = "Default"
- nr_intensity: float = 1.0
- local_tone_strength: float = 1.0
- local_structure_strength: float = 1.0
- skin_structure_strength: float = -1.0
- upscaling_factor: float = 1.0
- output_format: str = "PNG"
- quality: int = 95
- preserve_metadata: bool = True
- warmup_frames: int = 0
- nr_preset: str = "Default"
- automatic_mask: bool = False
- rename_mode: str = "Auto"
- custom_suffix: str = "_DLSS5"
- dlss_model_preset: str = "Default"
-
- def neural_options(self) -> ConversionOptions:
- return ConversionOptions(
- ai_gpu_uuid=self.ai_gpu_uuid,
- nr_preset=self.nr_preset,
- nr_style=self.nr_style,
- nr_intensity=self.nr_intensity,
- 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,
- dlss_model_preset=self.dlss_model_preset,
- )
-
-
-@dataclass(slots=True)
-class ImageConversionResult:
- input_path: str
- output_path: str
- report_path: str
- elapsed_seconds: float
- gpu: str
- input_width: int
- input_height: int
- render_width: int
- render_height: int
- output_width: int
- output_height: int
- upscaling_factor: float
- dlss_mode: str
- output_format: str
- dlss_model_preset: str = "Default"
- applied_dlss_model_preset: int = 0
- warnings: list[str] = field(default_factory=list)
-
-
-@dataclass(slots=True)
-class ImageConversionFailure:
- input_path: str
- error: str
-
-
-@dataclass(slots=True)
-class ImageBatchResult:
- successes: list[ImageConversionResult]
- failures: list[ImageConversionFailure]
- cancelled: bool
- manifest_path: str
- zip_path: str | None
-
-
-@dataclass(slots=True)
-class _ImageProbe:
- index: int
- path: Path
- width: int
- height: int
- output_width: int
- output_height: int
- decoded: _DecodedImage | None = None
-
-
-@dataclass(slots=True)
-class _DecodedImage:
- rgba: np.ndarray
- alpha: np.ndarray
- decoder: str
- metadata: dict[str, object]
- warnings: list[str]
-
-
-@dataclass(slots=True)
-class _ImageReportData:
- decoder: str
- metadata: dict[str, object]
- warnings: list[str]
-
-
-def _report_data(decoded: _DecodedImage) -> _ImageReportData:
- """Keep diagnostics without retaining the decoded pixel and alpha arrays."""
- return _ImageReportData(decoded.decoder, decoded.metadata, decoded.warnings)
-
-
-def _json_safe_metadata(value: object) -> object:
- """Create a report-only JSON-safe copy without changing save metadata."""
- if value is None or isinstance(value, (bool, int, float, str)):
- return value
- if isinstance(value, TiffImagePlugin.IFDRational):
- return float(value)
- if isinstance(value, dict):
- return {str(key): _json_safe_metadata(item) for key, item in value.items()}
- if isinstance(value, (list, tuple, set)):
- return [_json_safe_metadata(item) for item in value]
- if isinstance(value, bytes):
- return {"type": "bytes", "length": len(value)}
- return str(value)
-
-
-def _validate_options(options: ImageConversionOptions) -> ConversionOptions:
- if options.output_format not in IMAGE_FORMATS:
- raise ValueError(f"Unknown image output format: {options.output_format!r}.")
- if isinstance(options.quality, bool):
- raise ValueError("Image quality must be an integer from 1 to 100.")
- try:
- quality = int(options.quality)
- except (TypeError, ValueError) as exc:
- raise ValueError("Image quality must be an integer from 1 to 100.") from exc
- if quality != options.quality or not 1 <= quality <= 100:
- raise ValueError("Image quality must be an integer from 1 to 100.")
- validate_rename(options.rename_mode, options.custom_suffix)
- neural = options.neural_options()
- resolve_native_settings(neural)
- resolve_upscaling_mode(neural.upscaling_factor)
- return neural
-
-
-def _orientation_swaps_dimensions(image: Image.Image) -> bool:
- try:
- return int(image.getexif().get(274, 1)) in {5, 6, 7, 8}
- except (TypeError, ValueError):
- return False
-
-
-def _open_pillow_source(path: Path) -> tuple[Image.Image, str]:
- suffix = path.suffix.lower()
- if suffix in RAW_EXTENSIONS:
- with rawpy.imread(str(path)) as raw:
- array = raw.postprocess(
- use_camera_wb=True,
- output_color=rawpy.ColorSpace.sRGB,
- output_bps=8,
- )
- return Image.fromarray(array, mode="RGB"), "LibRaw"
- if suffix == ".svg":
- png = resvg_py.svg_to_bytes(svg_path=str(path), resources_dir=str(path.parent))
- return Image.open(io.BytesIO(png)), "resvg"
- return Image.open(path), "Pillow"
-
-
-def probe_image(path: str | os.PathLike[str]) -> tuple[int, int]:
- source = Path(path).resolve()
- if not source.is_file():
- raise FileNotFoundError(source)
- image, _decoder = _open_pillow_source(source)
- try:
- width, height = image.size
- if _orientation_swaps_dimensions(image):
- width, height = height, width
- finally:
- image.close()
- if width < 64 or height < 64:
- raise ValueError(
- f"{source.name} is {width}×{height}; DLSS requires both input dimensions to be at least 64 pixels."
- )
- return width, height
-
-
-@lru_cache(maxsize=1)
-def _srgb_profile_bytes() -> bytes:
- return ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
-
-
-def initialize_image_runtime() -> None:
- """Initialize reusable image color-management state during app preparation."""
- _srgb_profile_bytes()
-
-
-def take_image_preview(output_path: str | os.PathLike[str]) -> Image.Image | None:
- """Return and remove a UI thumbnail created from the rendered frame in memory."""
- key = str(Path(output_path).resolve())
- with _preview_cache_lock:
- return _preview_cache.pop(key, None)
-
-
-def _remember_image_preview(
- output_path: Path, rgba: np.ndarray, output_format: str
-) -> None:
- image = Image.fromarray(rgba, mode="RGBA")
- try:
- if output_format == "JPEG":
- background = Image.new("RGBA", image.size, (255, 255, 255, 255))
- background.alpha_composite(image)
- preview = background
- else:
- preview = image.copy()
- preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)
- key = str(output_path.resolve())
- with _preview_cache_lock:
- previous = _preview_cache.pop(key, None)
- if previous is not None:
- previous.close()
- _preview_cache[key] = preview
- while len(_preview_cache) > _PREVIEW_CACHE_LIMIT:
- _unused_key, unused = _preview_cache.popitem(last=False)
- unused.close()
- finally:
- image.close()
-
-
-def _encode_image(
- output: Path,
- rgba: np.ndarray,
- options: ImageConversionOptions,
- metadata: dict[str, object],
-) -> list[str]:
- warnings = save_image(output, rgba, options, metadata)
- try:
- _remember_image_preview(output, rgba, options.output_format)
- except Exception:
- # A UI convenience must never invalidate an otherwise correct output.
- pass
- return warnings
-
-
-def decode_image(path: str | os.PathLike[str]) -> _DecodedImage:
- source = Path(path).resolve()
- image, decoder = _open_pillow_source(source)
- opened_image = image
- warnings: list[str] = []
- try:
- frame_count = int(getattr(image, "n_frames", 1) or 1)
- if frame_count > 1:
- warnings.append(f"Used the first frame/page of {frame_count}.")
- image.seek(0)
- original_mode = image.mode
- info = dict(image.info)
- image = ImageOps.exif_transpose(image)
- image.load()
- if original_mode not in {"1", "L", "LA", "P", "RGB", "RGBA", "CMYK"}:
- warnings.append(f"Converted {original_mode} source data to 8-bit SDR sRGB.")
-
- has_alpha = image.mode in {"LA", "RGBA"} or (
- image.mode == "P" and "transparency" in info
- )
- alpha_image = (
- image.convert("RGBA").getchannel("A")
- if has_alpha
- else Image.new("L", image.size, 255)
- )
- rgb_image = image.convert("RGB")
- icc_profile = info.get("icc_profile")
- if isinstance(icc_profile, bytes) and icc_profile:
- try:
- source_profile = ImageCms.ImageCmsProfile(io.BytesIO(icc_profile))
- rgb_image = ImageCms.profileToProfile(
- rgb_image,
- source_profile,
- ImageCms.createProfile("sRGB"),
- outputMode="RGB",
- )
- except (ImageCms.PyCMSError, OSError, ValueError) as exc:
- warnings.append(f"Embedded color profile could not be applied ({exc}); assumed sRGB.")
-
- rgb = np.asarray(rgb_image, dtype=np.uint8)
- alpha = np.asarray(alpha_image, dtype=np.uint8)
- rgba = np.empty((*rgb.shape[:2], 4), dtype=np.uint8)
- rgba[..., :3] = rgb
- rgba[..., 3] = alpha
- exif = image.getexif()
- if exif:
- exif[274] = 1
- metadata: dict[str, object] = {
- "icc_profile": _srgb_profile_bytes(),
- "exif": exif.tobytes() if exif else None,
- "dpi": info.get("dpi"),
- "xmp": info.get("xmp"),
- "source_mode": original_mode,
- "source_format": image.format or source.suffix.lstrip(".").upper(),
- "frame_count": frame_count,
- }
- return _DecodedImage(
- np.ascontiguousarray(rgba),
- np.ascontiguousarray(alpha),
- decoder,
- metadata,
- warnings,
- )
- finally:
- image.close()
- if opened_image is not image:
- opened_image.close()
-
-
-def _metadata_save_args(metadata: dict[str, object], output_format: str) -> dict[str, object]:
- args: dict[str, object] = {}
- if metadata.get("icc_profile"):
- args["icc_profile"] = metadata["icc_profile"]
- if metadata.get("dpi"):
- args["dpi"] = metadata["dpi"]
- if metadata.get("exif") and output_format in {"JPEG", "WebP", "AVIF", "TIFF", "PNG"}:
- args["exif"] = metadata["exif"]
- if metadata.get("xmp") and output_format in {"WebP", "AVIF"}:
- args["xmp"] = metadata["xmp"]
- return args
-
-
-def save_image(
- output: Path,
- rgba: np.ndarray,
- options: ImageConversionOptions,
- metadata: dict[str, object],
-) -> list[str]:
- output_format = options.output_format
- image = Image.fromarray(rgba, mode="RGBA")
- warnings: list[str] = []
- args = _metadata_save_args(metadata, output_format) if options.preserve_metadata else {}
- if output_format == "PNG":
- args.update(optimize=False, compress_level=6)
- elif output_format == "TIFF":
- args.update(compression="tiff_deflate")
- elif output_format == "JPEG":
- background = Image.new("RGBA", image.size, (255, 255, 255, 255))
- background.alpha_composite(image)
- image = background.convert("RGB")
- args.update(
- quality=int(options.quality),
- subsampling=0,
- optimize=False,
- progressive=False,
- )
- if np.any(rgba[..., 3] != 255):
- warnings.append("Transparency was composited over white for JPEG output.")
- elif output_format == "WebP":
- args.update(quality=int(options.quality), method=6)
- elif output_format == "AVIF":
- args.update(quality=int(options.quality), speed=4)
-
- temporary = output.with_name(f".{output.stem}.{time.time_ns()}{output.suffix}")
- try:
- image.save(temporary, format=output_format, **args)
- os.replace(temporary, output)
- finally:
- image.close()
- if temporary.exists():
- temporary.unlink()
- return warnings
-
-
-def _output_path(
- source: Path,
- output_format: str,
- stamp: str,
- index: int,
- rename_mode: str,
- custom_suffix: str,
-) -> Path:
- suffix = IMAGE_EXTENSIONS[output_format]
- safe_stem = source.stem.strip().rstrip(".") or "image"
- return OUTPUTS / output_filename(
- source,
- suffix,
- rename_mode,
- custom_suffix,
- f"{safe_stem}_DLSS5_IMAGE_{stamp}-{index + 1:04d}",
- )
-
-
-def _write_report(
- result: ImageConversionResult,
- options: ImageConversionOptions,
- decoded: _ImageReportData,
- gpu: dict,
- session: DLSSFrameSession,
- evidence: dict[str, object],
-) -> str:
- report = {
- "status": "success",
- "input": result.input_path,
- "output": result.output_path,
- "options": asdict(options),
- "gpu": gpu,
- "decoder": decoded.decoder,
- "source_metadata": {
- key: _json_safe_metadata(value)
- for key, value in decoded.metadata.items()
- if key not in {"icc_profile", "exif", "xmp"}
- },
- "warnings": result.warnings,
- "input_dimensions": {"width": result.input_width, "height": result.input_height},
- "negotiated_render_dimensions": {"width": result.render_width, "height": result.render_height},
- "negotiated_render_range": {
- "minimum": {"width": session.minimum_width, "height": session.minimum_height},
- "maximum": {"width": session.maximum_width, "height": session.maximum_height},
- },
- "output_dimensions": {"width": result.output_width, "height": result.output_height},
- "dlss_mode": result.dlss_mode,
- "requested_upscaling_factor": result.upscaling_factor,
- "dlss_model_preset": result.dlss_model_preset,
- "requested_dlss_model_preset": result.dlss_model_preset,
- "requested_dlss_model_preset_code": DLSS_MODEL_PRESETS[
- result.dlss_model_preset
- ],
- "applied_dlss_model_preset": result.applied_dlss_model_preset,
- "applied_dlss_model_preset_name": next(
- name
- for name, code in DLSS_MODEL_PRESETS.items()
- if code == result.applied_dlss_model_preset
- ),
- "pipeline": "renodx-dlssnr-feature18-image",
- "feature_id": 18,
- "feature_18_confirmed": True,
- "ngx_setup_result": f"0x{session.setup_result:08X}",
- "carrier_create_result": evidence["carrier_create_result"],
- "native_settings": session.native_settings,
- "addon_release": session.runtime_bundle["addon"]["release"],
- "addon_sha256": session.runtime_bundle["addon"]["sha256"].lower(),
- "model_sha256": session.runtime_bundle["neural_runtime"]["sha256"].lower(),
- "worker_sha256": session.runtime_bundle["worker"]["sha256"].lower(),
- "worker_log": session.worker_logs,
- "worker_log_dropped_lines": session.worker_log_dropped_lines,
- "dlssnr_evidence": evidence["evidence"],
- "elapsed_seconds": result.elapsed_seconds,
- }
- report_path = LOGS / f"{Path(result.output_path).name}.report.json"
- report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
- return str(report_path)
-
-
-def _build_manifest_and_zip(
- stamp: str,
- options: ImageConversionOptions,
- successes: list[ImageConversionResult],
- failures: list[ImageConversionFailure],
- cancelled: bool,
-) -> tuple[str, str | None]:
- manifest = {
- "status": "cancelled" if cancelled else ("partial" if failures else "success"),
- "options": asdict(options),
- "successes": [asdict(item) for item in successes],
- "failures": [asdict(item) for item in failures],
- }
- manifest_path = LOGS / f"DLSS5_IMAGE_BATCH_{stamp}.manifest.json"
- manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
- if not successes:
- return str(manifest_path), None
- zip_path = OUTPUTS / f"DLSS5_IMAGE_BATCH_{stamp}.zip"
- temporary = zip_path.with_name(f".{zip_path.stem}.{time.time_ns()}.zip")
- try:
- with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED) as archive:
- for item in successes:
- archive.write(item.output_path, arcname=Path(item.output_path).name)
- os.replace(temporary, zip_path)
- finally:
- if temporary.exists():
- temporary.unlink()
- return str(manifest_path), str(zip_path)
-
-
-def convert_images(
- input_paths: Iterable[str | os.PathLike[str]],
- options: ImageConversionOptions | None = None,
- progress: Callable[[float, str], None] | None = None,
-) -> ImageBatchResult:
- from .prepare import prepare_runtime
-
- options = options or ImageConversionOptions()
- neural = _validate_options(options)
- paths = [Path(path).resolve() for path in input_paths]
- if not paths:
- raise ValueError("Choose at least one image.")
- prepared_runtime = prepare_runtime()
- OUTPUTS.mkdir(exist_ok=True)
- LOGS.mkdir(exist_ok=True)
- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
- failures_by_index: dict[int, ImageConversionFailure] = {}
- probes: list[_ImageProbe] = []
- for index, path in enumerate(paths):
- try:
- decoded: _DecodedImage | None = None
- if path.suffix.lower() in {*RAW_EXTENSIONS, ".svg"}:
- decoded = decode_image(path)
- height, width = decoded.rgba.shape[:2]
- if width < 64 or height < 64:
- raise ValueError(
- f"{path.name} is {width}×{height}; DLSS requires both input "
- "dimensions to be at least 64 pixels."
- )
- else:
- width, height = probe_image(path)
- output_width, output_height = resolve_output_size(
- width, height, options.upscaling_factor
- )
- probes.append(
- _ImageProbe(
- index, path, width, height, output_width, output_height, decoded
- )
- )
- except Exception as exc:
- failures_by_index[index] = ImageConversionFailure(str(path), str(exc))
-
- planned_outputs: dict[int, Path] = {}
- reserved_outputs: set[str] = set()
- available_probes: list[_ImageProbe] = []
- for probe in probes:
- output = _output_path(
- probe.path,
- options.output_format,
- stamp,
- probe.index,
- options.rename_mode,
- options.custom_suffix,
- )
- output_key = str(output.resolve()).casefold()
- try:
- require_available_output(output)
- if output_key in reserved_outputs:
- raise FileExistsError(
- f"More than one input would create {output.name}. "
- "Choose Auto naming or use unique input names."
- )
- except Exception as exc:
- failures_by_index[probe.index] = ImageConversionFailure(
- str(probe.path), str(exc)
- )
- continue
- reserved_outputs.add(output_key)
- planned_outputs[probe.index] = output
- available_probes.append(probe)
- probes = available_probes
-
- if not probes:
- manifest_path, zip_path = _build_manifest_and_zip(
- stamp, options, [], list(failures_by_index.values()), False
- )
- return ImageBatchResult([], list(failures_by_index.values()), False, manifest_path, zip_path)
-
- groups: dict[tuple[int, int], list[_ImageProbe]] = {}
- for probe in probes:
- groups.setdefault((probe.output_width, probe.output_height), []).append(probe)
-
- successes_by_index: dict[int, ImageConversionResult] = {}
- cancelled = False
- gpu: dict | None = None
- processed_total = 0
- decode_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="dlss5-image-decode")
- encode_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="dlss5-image-encode")
- with active_job() as controller:
- gpu = resolve_runtime_ai_gpu(
- prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid
- )
- runtime_bundle = prepared_runtime.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)
- factor, mode = resolve_upscaling_mode(neural.upscaling_factor)
- native_settings = resolve_native_settings(neural)
- try:
- for (output_width, output_height), group in groups.items():
- cursor = 0
- while cursor < len(group):
- if controller.cancel.is_set():
- cancelled = True
- break
- remaining = group[cursor:]
- first = remaining[0]
- try:
- session = DLSSFrameSession(
- input_width=first.width,
- input_height=first.height,
- output_width=output_width,
- output_height=output_height,
- frame_count=len(remaining),
- warmup_frames=neural.warmup_frames,
- factor=factor,
- mode=mode,
- native_settings=native_settings,
- 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), failure)
- break
-
- segment: list[
- tuple[
- _ImageProbe,
- ImageConversionResult,
- _ImageReportData,
- Future[list[str]],
- float,
- ]
- ] = []
- sent = 0
- motion = np.zeros(
- (session.render_height, session.render_width, 2), dtype=np.float16
- )
- interrupted = False
- close_error: Exception | None = None
- decode_future: Future[_DecodedImage] | None = decode_executor.submit(
- lambda probe=group[cursor]: probe.decoded or decode_image(probe.path)
- )
- while cursor < len(group):
- item = group[cursor]
- started = time.perf_counter()
- if controller.cancel.is_set():
- cancelled = True
- interrupted = True
- session.abort()
- break
- if progress:
- progress(processed_total / max(1, total), f"Preparing {item.path.name}")
- try:
- assert decode_future is not None
- decoded = decode_future.result()
- item.decoded = None
- next_cursor = cursor + 1
- decode_future = (
- decode_executor.submit(
- lambda probe=group[next_cursor]:
- probe.decoded or decode_image(probe.path)
- )
- if next_cursor < len(group)
- else None
- )
- except Exception as exc:
- failures_by_index[item.index] = ImageConversionFailure(str(item.path), str(exc))
- cursor += 1
- processed_total += 1
- session.abort()
- interrupted = True
- break
- try:
- render_rgba = resize_fit(
- decoded.rgba, session.render_width, session.render_height
- )
- processed, _pts = session.process(
- index=sent,
- rgba=render_rgba,
- motion=motion,
- reset=True,
- pts=sent,
- )
- alpha = (
- decoded.alpha
- if decoded.alpha.shape == (output_height, output_width)
- else cv2.resize(
- decoded.alpha,
- (output_width, output_height),
- interpolation=cv2.INTER_LANCZOS4,
- )
- )
- processed[..., 3] = alpha
- output = planned_outputs[item.index]
- result = ImageConversionResult(
- str(item.path),
- str(output),
- "",
- time.perf_counter() - started,
- str(gpu["display_name"]),
- item.width,
- item.height,
- session.render_width,
- session.render_height,
- output_width,
- output_height,
- float(options.upscaling_factor),
- str(session.mode["name"]),
- options.output_format,
- options.dlss_model_preset,
- session.applied_dlss_model_preset,
- list(decoded.warnings),
- )
- encoding = encode_executor.submit(
- _encode_image, output, processed, options, decoded.metadata
- )
- segment.append(
- (item, result, _report_data(decoded), encoding, started)
- )
- # Keep at most two full rendered frames queued for encoding.
- # Completed futures retain only their small warning list.
- if len(segment) > 2:
- segment[-3][3].result()
- sent += 1
- except Cancelled:
- cancelled = True
- session.abort()
- interrupted = True
- break
- except Exception as 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
- break
- cursor += 1
- processed_total += 1
- 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()
- except Exception as exc:
- close_error = exc
- try:
- if close_error:
- raise close_error
- evidence = verify_feature_18(
- session.worker_logs, session.reshade_log_text()
- )
- assert gpu is not None
- for item, result, decoded, encoding, item_started in segment:
- result.warnings.extend(encoding.result())
- result.elapsed_seconds = time.perf_counter() - item_started
- for item, result, decoded, _encoding, _item_started in segment:
- result.report_path = _write_report(
- result, options, decoded, gpu, session, evidence
- )
- 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, *_rest 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, encoding, _item_started in segment:
- if not encoding.done():
- encoding.cancel()
- output = Path(result.output_path)
- if output.exists():
- output.unlink()
- failures_by_index[item.index] = ImageConversionFailure(str(item.path), failure)
- if cancelled:
- break
- if cancelled:
- break
- finally:
- decode_executor.shutdown(wait=True, cancel_futures=True)
- encode_executor.shutdown(wait=True, cancel_futures=True)
- if cancelled:
- completed = set(successes_by_index) | set(failures_by_index)
- for probe in probes:
- if probe.index not in completed:
- failures_by_index[probe.index] = ImageConversionFailure(
- str(probe.path), "Cancelled before rendering."
- )
- successes = [successes_by_index[index] for index in sorted(successes_by_index)]
- failures = [failures_by_index[index] for index in sorted(failures_by_index)]
- manifest_path, zip_path = _build_manifest_and_zip(
- stamp, options, successes, failures, cancelled
- )
- if progress:
- progress(1.0, "Cancelled" if cancelled else "Complete")
- return ImageBatchResult(successes, failures, cancelled, manifest_path, zip_path)
-
-
-def convert_image(
- input_path: str | os.PathLike[str],
- options: ImageConversionOptions | None = None,
- progress: Callable[[float, str], None] | None = None,
-) -> ImageConversionResult:
- result = convert_images([input_path], options, progress)
- if result.successes:
- return result.successes[0]
- if result.failures:
- raise RuntimeError(result.failures[0].error)
- raise RuntimeError("Image conversion produced no result.")
diff --git a/src/prepare.py b/src/prepare.py
deleted file mode 100644
index 0674ac7..0000000
--- a/src/prepare.py
+++ /dev/null
@@ -1,143 +0,0 @@
-from __future__ import annotations
-
-import atexit
-import mmap
-import subprocess
-import threading
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-from .runtime import (
- ADDON,
- FFMPEG,
- FFPROBE,
- NEURAL_RUNTIME,
- RUNTIME,
- WORKER,
- detect_gpus,
- inspect_runtime_bundle,
- resolve_runtime_ai_gpu,
- validate_runtime_files,
-)
-
-
-@dataclass(slots=True)
-class PreparedRuntime:
- """Reusable, source-independent state prepared once for this process."""
-
- gpu: dict[str, Any]
- gpus: tuple[dict[str, Any], ...]
- runtime_bundle: dict[str, Any]
- encoder_inventory: dict[str, bool]
- warmed_files: tuple[str, ...]
- _mappings: list[mmap.mmap] = field(default_factory=list, repr=False)
-
- def close(self) -> None:
- while self._mappings:
- mapping = self._mappings.pop()
- try:
- mapping.close()
- except (BufferError, OSError):
- pass
-
-
-_PREPARE_LOCK = threading.Lock()
-_PREPARED: PreparedRuntime | None = None
-
-
-def _warm_mapping(path: Path) -> mmap.mmap | None:
- if not path.is_file() or path.stat().st_size == 0:
- return None
- with path.open("rb") as stream:
- mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)
- # Touch regularly spaced pages. Sequential hashing already warms the largest
- # model; this also covers un-hashed loader and FFmpeg components.
- checksum = 0
- for offset in range(0, len(mapping), 64 * 1024):
- checksum ^= mapping[offset]
- checksum ^= mapping[-1]
- del checksum
- return mapping
-
-
-def _encoder_inventory() -> dict[str, bool]:
- result = subprocess.run(
- [str(FFMPEG), "-hide_banner", "-encoders"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- if result.returncode:
- raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")
- output = result.stdout
- return {
- "h264_nvenc": "h264_nvenc" in output,
- "hevc_nvenc": "hevc_nvenc" in output,
- "av1_nvenc": "av1_nvenc" in output,
- "prores_ks": "prores_ks" in output,
- }
-
-
-def prepare_runtime() -> PreparedRuntime:
- """Prepare all reusable runtime state before UI launch or first conversion."""
- global _PREPARED
- if _PREPARED is not None:
- return _PREPARED
- with _PREPARE_LOCK:
- if _PREPARED is not None:
- return _PREPARED
-
- validate_runtime_files()
- gpus = detect_gpus()
- runtime_bundle = inspect_runtime_bundle()
- gpu = resolve_runtime_ai_gpu(gpus, runtime_bundle)
- inventory = _encoder_inventory()
-
- # Initialize Pillow's reusable sRGB profile and optional image backends.
- from .images import initialize_image_runtime
-
- initialize_image_runtime()
-
- paths = (
- WORKER,
- RUNTIME / "dxgi.dll",
- ADDON,
- RUNTIME / "nvngx_dlss.dll",
- NEURAL_RUNTIME,
- FFMPEG,
- FFPROBE,
- )
- mappings: list[mmap.mmap] = []
- try:
- for path in paths:
- mapping = _warm_mapping(path)
- if mapping is not None:
- mappings.append(mapping)
- except Exception:
- for mapping in mappings:
- mapping.close()
- raise
-
- _PREPARED = PreparedRuntime(
- gpu=dict(gpu),
- gpus=tuple(dict(device) for device in gpus),
- runtime_bundle=runtime_bundle,
- encoder_inventory=inventory,
- warmed_files=tuple(str(path.resolve()) for path in paths),
- _mappings=mappings,
- )
- return _PREPARED
-
-
-def close_prepared_runtime() -> None:
- global _PREPARED
- with _PREPARE_LOCK:
- prepared = _PREPARED
- _PREPARED = None
- if prepared is not None:
- prepared.close()
-
-
-atexit.register(close_prepared_runtime)
diff --git a/src/settings.py b/src/settings.py
deleted file mode 100644
index 2d51b33..0000000
--- a/src/settings.py
+++ /dev/null
@@ -1,474 +0,0 @@
-from __future__ import annotations
-
-import configparser
-import json
-import math
-import os
-import re
-import tempfile
-from dataclasses import asdict, dataclass, fields, replace
-from pathlib import Path
-from typing import Any
-
-from .ffmpeg import ENCODING_QUALITIES
-from .frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES
-from .naming import RENAME_MODES, validate_rename
-from .video import (
- DLSS_MODEL_PRESETS,
- NR_PRESETS,
- NR_STYLES,
- ConversionOptions,
- resolve_native_settings,
- resolve_upscaling_mode,
-)
-
-
-QUALITY_CHOICES = ENCODING_QUALITIES
-CODEC_CHOICES = ("H.264", "HEVC", "AV1", "ProRes Proxy")
-CONTAINER_CHOICES = ("MP4", "MKV", "MOV")
-IMAGE_FORMAT_CHOICES = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")
-CONFIG_SECTION = "Settings"
-PRESET_FORMAT = "dlss5-visual-enhancer-settings-preset"
-PRESET_SCHEMA_VERSION = 1
-MAX_PRESET_BYTES = 1024 * 1024
-_WINDOWS_RESERVED_NAMES = {
- "CON",
- "PRN",
- "AUX",
- "NUL",
- *(f"COM{index}" for index in range(1, 10)),
- *(f"LPT{index}" for index in range(1, 10)),
-}
-
-
-@dataclass(frozen=True, slots=True)
-class UISettings:
- ai_gpu_uuid: str = "auto"
- video_gpu_uuid: str = "auto"
- nr_style: str = "Default"
- nr_intensity: float = 1.0
- local_tone_strength: float = 1.0
- local_structure_strength: float = 1.0
- skin_structure_strength: float = -1.0
- upscaling_factor: float = 1.0
- codec: str = "H.264"
- container: str = "MP4"
- quality: str = "Auto (Default)"
- image_format: str = "PNG"
- image_quality: int = 95
- nr_preset: str = "Default"
- automatic_mask: bool = False
- image_rename_mode: str = "Auto"
- image_custom_suffix: str = "_DLSS5"
- video_rename_mode: str = "Auto"
- video_custom_suffix: str = "_DLSS5"
- dlss_model_preset: str = "Default"
- frame_interpolation_target_fps: str = "60"
- frame_interpolation_engine: str = "Auto"
- frame_interpolation_codec: str = "H.264"
- frame_interpolation_container: str = "MP4"
- frame_interpolation_quality: str = "Auto (Default)"
- frame_interpolation_rename_mode: str = "Auto"
- frame_interpolation_custom_suffix: str = "_DLSSFG"
-
- def component_values(
- self,
- ) -> tuple[str, str, float, float, float, float, float, bool, str, str, str, str]:
- return (
- self.nr_preset,
- self.nr_style,
- self.nr_intensity,
- self.local_tone_strength,
- self.local_structure_strength,
- self.skin_structure_strength,
- self.upscaling_factor,
- self.automatic_mask,
- self.codec,
- self.container,
- self.quality,
- self.dlss_model_preset,
- )
-
-
-DEFAULT_SETTINGS = UISettings()
-
-
-def _validate(settings: UISettings) -> UISettings:
- for label, value in (
- ("AI Processing GPU", settings.ai_gpu_uuid),
- ("Video Processing GPU", settings.video_gpu_uuid),
- ):
- if not isinstance(value, str) or not value.strip() or len(value) > 160:
- raise ValueError(f"{label} selection must be Automatic or a valid GPU UUID.")
- resolve_native_settings(
- ConversionOptions(
- nr_preset=settings.nr_preset,
- nr_style=settings.nr_style,
- nr_intensity=settings.nr_intensity,
- 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,
- dlss_model_preset=settings.dlss_model_preset,
- )
- )
- 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),
- "Encoding quality": (settings.quality, QUALITY_CHOICES),
- "Image format": (settings.image_format, IMAGE_FORMAT_CHOICES),
- "Frame Interpolation FPS": (
- settings.frame_interpolation_target_fps,
- FPS_CHOICES,
- ),
- "Frame Interpolation engine": (
- settings.frame_interpolation_engine,
- ENGINE_CHOICES,
- ),
- "Frame Interpolation codec": (
- settings.frame_interpolation_codec,
- CODEC_CHOICES,
- ),
- "Frame Interpolation container": (
- settings.frame_interpolation_container,
- CONTAINER_CHOICES,
- ),
- "Frame Interpolation quality": (
- settings.frame_interpolation_quality,
- QUALITY_CHOICES,
- ),
- }
- for label, (value, choices) in allowed.items():
- if value not in choices:
- raise ValueError(f"Unknown {label}: {value!r}.")
- if isinstance(settings.image_quality, bool) or not 1 <= int(settings.image_quality) <= 100:
- raise ValueError("Image quality must be an integer from 1 to 100.")
- if int(settings.image_quality) != settings.image_quality:
- raise ValueError("Image quality must be an integer from 1 to 100.")
- validate_rename(settings.image_rename_mode, settings.image_custom_suffix)
- validate_rename(settings.video_rename_mode, settings.video_custom_suffix)
- validate_rename(
- settings.frame_interpolation_rename_mode,
- settings.frame_interpolation_custom_suffix,
- )
- return settings
-
-
-def _preset_name(value: str) -> str:
- if not isinstance(value, str):
- raise ValueError("Preset name must be text.")
- name = value.strip()
- if not name:
- raise ValueError("Enter a preset name before exporting.")
- if len(name) > 120:
- raise ValueError("Preset name must be 120 characters or fewer.")
- if any(ord(character) < 32 for character in name):
- raise ValueError("Preset name cannot contain control characters.")
- return name
-
-
-def preset_filename(name: str) -> str:
- """Return a portable JSON filename while preserving the display name in the file."""
- display_name = _preset_name(name)
- characters = [
- character if character.isalnum() or character in "-_" else "_"
- for character in display_name
- ]
- stem = re.sub(r"_+", "_", "".join(characters)).strip("-_")[:80].rstrip("-_")
- if not stem:
- raise ValueError("Preset name must contain at least one letter or number.")
- if stem.upper() in _WINDOWS_RESERVED_NAMES:
- stem += "_preset"
- return f"{stem}.json"
-
-
-def preset_document(name: str, settings: UISettings) -> dict[str, Any]:
- """Build the versioned user-facing preset document."""
- display_name = _preset_name(name)
- _validate(settings)
- return {
- "format": PRESET_FORMAT,
- "schema_version": PRESET_SCHEMA_VERSION,
- "name": display_name,
- "settings": asdict(settings),
- }
-
-
-def export_settings_preset(name: str, settings: UISettings) -> Path:
- """Write a validated preset to an isolated temporary download directory."""
- document = preset_document(name, settings)
- filename = preset_filename(document["name"])
- directory = Path(tempfile.mkdtemp(prefix="dlss5-settings-preset-"))
- path = directory / filename
- path.write_text(
- json.dumps(document, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- return path.resolve()
-
-
-def _coerce_preset_value(field_name: str, value: Any, current: UISettings) -> Any:
- expected = getattr(current, field_name)
- if isinstance(expected, bool):
- if not isinstance(value, bool):
- raise ValueError(f"Preset setting {field_name!r} must be a boolean.")
- return value
- if isinstance(expected, int):
- if isinstance(value, bool) or not isinstance(value, int):
- raise ValueError(f"Preset setting {field_name!r} must be an integer.")
- return value
- if isinstance(expected, float):
- if isinstance(value, bool) or not isinstance(value, (int, float)):
- raise ValueError(f"Preset setting {field_name!r} must be a number.")
- number = float(value)
- if not math.isfinite(number):
- raise ValueError(f"Preset setting {field_name!r} must be finite.")
- return number
- if isinstance(expected, str):
- if not isinstance(value, str):
- raise ValueError(f"Preset setting {field_name!r} must be text.")
- return value
- raise ValueError(f"Preset setting {field_name!r} has an unsupported type.")
-
-
-def import_settings_preset(
- path: str | os.PathLike[str], current: UISettings
-) -> tuple[str, UISettings]:
- """Load, compatibly merge, and atomically validate a version-1 preset."""
- preset_path = Path(path)
- if preset_path.suffix.casefold() != ".json":
- raise ValueError("Choose a JSON preset file.")
- try:
- size = preset_path.stat().st_size
- except OSError as exc:
- raise ValueError("The selected preset file cannot be read.") from exc
- if size > MAX_PRESET_BYTES:
- raise ValueError("Preset file is too large; the maximum size is 1 MiB.")
- try:
- document = json.loads(preset_path.read_text(encoding="utf-8"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- raise ValueError("Preset file is not valid UTF-8 JSON.") from exc
- if not isinstance(document, dict):
- raise ValueError("Preset JSON must contain an object at its top level.")
- if document.get("format") != PRESET_FORMAT:
- raise ValueError("This JSON file is not a DLSS 5 Visual Enhancer settings preset.")
- version = document.get("schema_version")
- if isinstance(version, bool) or not isinstance(version, int):
- raise ValueError("Preset schema_version must be an integer.")
- if version != PRESET_SCHEMA_VERSION:
- direction = "newer" if version > PRESET_SCHEMA_VERSION else "unsupported"
- raise ValueError(
- f"Preset schema version {version} is {direction}; this build supports version "
- f"{PRESET_SCHEMA_VERSION}."
- )
- name = _preset_name(document.get("name"))
- imported = document.get("settings")
- if not isinstance(imported, dict):
- raise ValueError("Preset settings must be a JSON object.")
-
- known_names = {field.name for field in fields(UISettings)}
- changes = {
- key: _coerce_preset_value(key, value, current)
- for key, value in imported.items()
- if key in known_names
- }
- merged = replace(current, **changes)
- return name, _validate(merged)
-
-
-def load_settings(path: str | os.PathLike[str]) -> UISettings:
- config_path = Path(path)
- parser = configparser.ConfigParser()
- try:
- with config_path.open("r", encoding="utf-8") as stream:
- parser.read_file(stream)
- except (OSError, configparser.Error):
- return DEFAULT_SETTINGS
-
- section = parser[CONFIG_SECTION] if parser.has_section(CONFIG_SECTION) else {}
-
- def choice(key: str, choices: tuple[str, ...], default: str) -> str:
- value = section.get(key, default)
- return value if value in choices else default
-
- def number(key: str, minimum: float, maximum: float, default: float) -> float:
- try:
- value = float(section.get(key, str(default)))
- except (TypeError, ValueError):
- return default
- return value if math.isfinite(value) and minimum <= value <= maximum else default
-
- def upscaling_factor() -> float:
- try:
- return resolve_upscaling_mode(float(section.get("upscaling_factor", "1.0")))[0]
- except (TypeError, ValueError):
- return DEFAULT_SETTINGS.upscaling_factor
-
- def image_quality() -> int:
- 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
-
- def frame_interpolation_engine() -> str:
- value = section.get(
- "frame_interpolation_engine",
- DEFAULT_SETTINGS.frame_interpolation_engine,
- )
- if value == "Experimental Cascade":
- return "Cascade"
- return value if value in ENGINE_CHOICES else DEFAULT_SETTINGS.frame_interpolation_engine
-
- image_rename_mode = choice(
- "image_rename_mode", RENAME_MODES, DEFAULT_SETTINGS.image_rename_mode
- )
- image_custom_suffix = section.get(
- "image_custom_suffix", DEFAULT_SETTINGS.image_custom_suffix
- )
- video_rename_mode = choice(
- "video_rename_mode", RENAME_MODES, DEFAULT_SETTINGS.video_rename_mode
- )
- video_custom_suffix = section.get(
- "video_custom_suffix", DEFAULT_SETTINGS.video_custom_suffix
- )
- frame_interpolation_rename_mode = choice(
- "frame_interpolation_rename_mode",
- RENAME_MODES,
- DEFAULT_SETTINGS.frame_interpolation_rename_mode,
- )
- frame_interpolation_custom_suffix = section.get(
- "frame_interpolation_custom_suffix",
- DEFAULT_SETTINGS.frame_interpolation_custom_suffix,
- )
- try:
- validate_rename(image_rename_mode, image_custom_suffix)
- except ValueError:
- image_rename_mode = DEFAULT_SETTINGS.image_rename_mode
- image_custom_suffix = DEFAULT_SETTINGS.image_custom_suffix
- try:
- validate_rename(video_rename_mode, video_custom_suffix)
- except ValueError:
- video_rename_mode = DEFAULT_SETTINGS.video_rename_mode
- video_custom_suffix = DEFAULT_SETTINGS.video_custom_suffix
- try:
- validate_rename(
- frame_interpolation_rename_mode,
- frame_interpolation_custom_suffix,
- )
- except ValueError:
- frame_interpolation_rename_mode = DEFAULT_SETTINGS.frame_interpolation_rename_mode
- frame_interpolation_custom_suffix = DEFAULT_SETTINGS.frame_interpolation_custom_suffix
-
- return UISettings(
- ai_gpu_uuid=section.get("ai_gpu_uuid", DEFAULT_SETTINGS.ai_gpu_uuid).strip()
- or DEFAULT_SETTINGS.ai_gpu_uuid,
- video_gpu_uuid=section.get("video_gpu_uuid", DEFAULT_SETTINGS.video_gpu_uuid).strip()
- or DEFAULT_SETTINGS.video_gpu_uuid,
- nr_preset=choice("nr_preset", tuple(NR_PRESETS), DEFAULT_SETTINGS.nr_preset),
- nr_style=choice("nr_style", tuple(NR_STYLES), DEFAULT_SETTINGS.nr_style),
- nr_intensity=number("nr_intensity", 0.0, 2.0, DEFAULT_SETTINGS.nr_intensity),
- local_tone_strength=number(
- "local_tone_strength", 0.0, 2.0, DEFAULT_SETTINGS.local_tone_strength
- ),
- local_structure_strength=number(
- "local_structure_strength", 0.0, 2.0, DEFAULT_SETTINGS.local_structure_strength
- ),
- 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),
- quality=choice("quality", QUALITY_CHOICES, DEFAULT_SETTINGS.quality),
- image_format=choice(
- "image_format", IMAGE_FORMAT_CHOICES, DEFAULT_SETTINGS.image_format
- ),
- image_quality=image_quality(),
- dlss_model_preset=choice(
- "dlss_model_preset",
- tuple(DLSS_MODEL_PRESETS),
- DEFAULT_SETTINGS.dlss_model_preset,
- ),
- image_rename_mode=image_rename_mode,
- image_custom_suffix=image_custom_suffix,
- video_rename_mode=video_rename_mode,
- video_custom_suffix=video_custom_suffix,
- frame_interpolation_target_fps=choice(
- "frame_interpolation_target_fps",
- FPS_CHOICES,
- DEFAULT_SETTINGS.frame_interpolation_target_fps,
- ),
- frame_interpolation_engine=frame_interpolation_engine(),
- frame_interpolation_codec=choice(
- "frame_interpolation_codec",
- CODEC_CHOICES,
- DEFAULT_SETTINGS.frame_interpolation_codec,
- ),
- frame_interpolation_container=choice(
- "frame_interpolation_container",
- CONTAINER_CHOICES,
- DEFAULT_SETTINGS.frame_interpolation_container,
- ),
- frame_interpolation_quality=choice(
- "frame_interpolation_quality",
- QUALITY_CHOICES,
- DEFAULT_SETTINGS.frame_interpolation_quality,
- ),
- frame_interpolation_rename_mode=frame_interpolation_rename_mode,
- frame_interpolation_custom_suffix=frame_interpolation_custom_suffix,
- )
-
-
-def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:
- settings = _validate(settings)
- config_path = Path(path)
- config_path.parent.mkdir(parents=True, exist_ok=True)
- parser = configparser.ConfigParser()
- parser[CONFIG_SECTION] = {
- "ai_gpu_uuid": settings.ai_gpu_uuid,
- "video_gpu_uuid": settings.video_gpu_uuid,
- "nr_preset": settings.nr_preset,
- "nr_style": settings.nr_style,
- "nr_intensity": f"{settings.nr_intensity:.2f}",
- "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,
- "quality": settings.quality,
- "image_format": settings.image_format,
- "image_quality": str(settings.image_quality),
- "image_rename_mode": settings.image_rename_mode,
- "image_custom_suffix": settings.image_custom_suffix,
- "video_rename_mode": settings.video_rename_mode,
- "video_custom_suffix": settings.video_custom_suffix,
- "dlss_model_preset": settings.dlss_model_preset,
- "frame_interpolation_target_fps": settings.frame_interpolation_target_fps,
- "frame_interpolation_engine": settings.frame_interpolation_engine,
- "frame_interpolation_codec": settings.frame_interpolation_codec,
- "frame_interpolation_container": settings.frame_interpolation_container,
- "frame_interpolation_quality": settings.frame_interpolation_quality,
- "frame_interpolation_rename_mode": settings.frame_interpolation_rename_mode,
- "frame_interpolation_custom_suffix": settings.frame_interpolation_custom_suffix,
- }
-
- temporary = config_path.with_name(f".{config_path.name}.tmp")
- try:
- with temporary.open("w", encoding="utf-8", newline="") as stream:
- parser.write(stream)
- os.replace(temporary, config_path)
- finally:
- if temporary.exists():
- temporary.unlink()
diff --git a/src/settings/__init__.py b/src/settings/__init__.py
new file mode 100644
index 0000000..227dfaa
--- /dev/null
+++ b/src/settings/__init__.py
@@ -0,0 +1,13 @@
+from .models import (
+ CODEC_CHOICES, CONTAINER_CHOICES, DEFAULT_SETTINGS, IMAGE_FORMAT_CHOICES, QUALITY_CHOICES, UISettings,
+)
+from .presets import (
+ export_settings_preset, import_settings_preset, preset_document, preset_filename,
+)
+from .storage import load_settings, save_settings
+
+__all__ = [
+ "CODEC_CHOICES", "CONTAINER_CHOICES", "DEFAULT_SETTINGS", "IMAGE_FORMAT_CHOICES",
+ "QUALITY_CHOICES", "UISettings", "export_settings_preset", "import_settings_preset",
+ "load_settings", "preset_document", "preset_filename", "save_settings",
+]
diff --git a/src/settings/migration.py b/src/settings/migration.py
new file mode 100644
index 0000000..d2cc95a
--- /dev/null
+++ b/src/settings/migration.py
@@ -0,0 +1,19 @@
+from __future__ import annotations
+
+from ..core.ffmpeg import _normalize_codec
+
+_CODEC_ALIAS_TO_CANONICAL = {
+ "HEVC": "H.265",
+ "H265": "H.265",
+ "HEVC (NVIDIA NVENC)": "H.265 (NVIDIA NVENC)",
+}
+
+def _migrate_codec(value: str) -> str:
+ if not isinstance(value, str):
+ return value
+ v = value.strip()
+ # Use ffmpeg normalizer which already handles alias
+ try:
+ return _normalize_codec(v)
+ except Exception:
+ return _CODEC_ALIAS_TO_CANONICAL.get(v, v)
diff --git a/src/settings/models.py b/src/settings/models.py
new file mode 100644
index 0000000..473cfc8
--- /dev/null
+++ b/src/settings/models.py
@@ -0,0 +1,169 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+
+from ..core.ffmpeg import CODEC_CHOICES as FFMPEG_CODEC_CHOICES, ENCODING_QUALITIES, HDR_ALLOWED_CODECS, hdr_mode_supported
+from ..core.naming import RENAME_MODES, validate_rename
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, resolve_native_settings, resolve_upscaling_mode
+from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES
+from .migration import _migrate_codec
+
+QUALITY_CHOICES = ENCODING_QUALITIES
+CODEC_CHOICES = FFMPEG_CODEC_CHOICES
+CONTAINER_CHOICES = ("MP4", "MKV", "MOV")
+IMAGE_FORMAT_CHOICES = ("PNG", "JPEG", "WebP", "AVIF", "TIFF")
+CONFIG_SECTION = "Settings"
+PRESET_FORMAT = "dlss5-visual-enhancer-settings-preset"
+PRESET_SCHEMA_VERSION = 1
+MAX_PRESET_BYTES = 1024 * 1024
+
+AUTOMATIC_MASK_CHOICES = ("Off", "On")
+
+PREVIEW_ENCODING_CHOICES = ("Auto", "Always H.264", "Disabled")
+
+
+def coerce_hdr_mode(codec: str, enabled: bool) -> bool:
+ return bool(enabled) and hdr_mode_supported(codec)
+
+
+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"
+
+@dataclass(frozen=True, slots=True)
+class UISettings:
+ ai_gpu_uuid: str = "auto"
+ video_gpu_uuid: str = "auto"
+ nr_style: str = "Default"
+ nr_intensity: float = 1.0
+ local_tone_strength: float = 1.0
+ local_structure_strength: float = 1.0
+ skin_structure_strength: float = -1.0
+ upscaling_factor: float = 1.0
+ codec: str = "H.264"
+ container: str = "MP4"
+ quality: str = "Auto (Default)"
+ hdr_mode: bool = False
+ image_format: str = "PNG"
+ image_quality: int = 95
+ nr_preset: str = "Default"
+ automatic_mask: bool = False
+ image_rename_mode: str = "Auto"
+ image_custom_suffix: str = "_DLSS5"
+ video_rename_mode: str = "Auto"
+ video_custom_suffix: str = "_DLSS5"
+ dlss_model_preset: str = "Default"
+ frame_interpolation_target_fps: str = "60"
+ frame_interpolation_engine: str = "Auto"
+ frame_interpolation_codec: str = "H.264"
+ frame_interpolation_container: str = "MP4"
+ frame_interpolation_quality: str = "Auto (Default)"
+ frame_interpolation_hdr_mode: bool = False
+ frame_interpolation_rename_mode: str = "Auto"
+ frame_interpolation_custom_suffix: str = "_DLSSFG"
+ preview_encoding: str = "Auto"
+
+ def component_values(
+ self,
+ ) -> tuple[str, str, float, float, float, float, float, bool, str, str, str, str]:
+ return (
+ self.nr_preset,
+ self.nr_style,
+ self.nr_intensity,
+ self.local_tone_strength,
+ self.local_structure_strength,
+ self.skin_structure_strength,
+ self.upscaling_factor,
+ self.automatic_mask,
+ self.codec,
+ self.container,
+ self.quality,
+ self.dlss_model_preset,
+ )
+
+
+DEFAULT_SETTINGS = UISettings()
+
+
+def _validate(settings: UISettings) -> UISettings:
+ for label, value in (
+ ("AI Processing GPU", settings.ai_gpu_uuid),
+ ("Video Processing GPU", settings.video_gpu_uuid),
+ ):
+ if not isinstance(value, str) or not value.strip() or len(value) > 160:
+ raise ValueError(f"{label} selection must be Automatic or a valid GPU UUID.")
+ resolve_native_settings(settings)
+ resolve_upscaling_mode(settings.upscaling_factor)
+ if not isinstance(settings.automatic_mask, bool):
+ raise ValueError("Automatic Mask must be a boolean value.")
+ if not isinstance(settings.hdr_mode, bool):
+ raise ValueError("HDR Mode must be a boolean value.")
+ if not isinstance(settings.frame_interpolation_hdr_mode, bool):
+ raise ValueError("Frame Interpolation HDR Mode must be a boolean value.")
+ # Migrate old codec names before validation
+ migrated_codec = _migrate_codec(settings.codec)
+ migrated_fi_codec = _migrate_codec(settings.frame_interpolation_codec)
+ if migrated_codec != settings.codec or migrated_fi_codec != settings.frame_interpolation_codec:
+ settings = replace(settings, codec=migrated_codec, frame_interpolation_codec=migrated_fi_codec)
+ # HDR Mode is only allowed for 10-bit capable codecs; if enabled with H.264, auto-disable for old configs
+ # For strict validation (presets), raise if mismatched – caller can decide; here we raise for explicit mismatch
+ _HDR_ALLOWED = HDR_ALLOWED_CODECS
+
+ if settings.hdr_mode and settings.codec not in _HDR_ALLOWED:
+ raise ValueError(
+ f"HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.codec!r}."
+ )
+ if settings.frame_interpolation_hdr_mode and settings.frame_interpolation_codec not in _HDR_ALLOWED:
+ raise ValueError(
+ f"Frame Interpolation HDR Mode is only available for {', '.join(sorted(_HDR_ALLOWED))}; current codec is {settings.frame_interpolation_codec!r}."
+ )
+ allowed = {
+ "Video codec": (settings.codec, CODEC_CHOICES),
+ "Container": (settings.container, CONTAINER_CHOICES),
+ "Encoding quality": (settings.quality, QUALITY_CHOICES),
+ "Image format": (settings.image_format, IMAGE_FORMAT_CHOICES),
+ "Frame Interpolation FPS": (
+ settings.frame_interpolation_target_fps,
+ FPS_CHOICES,
+ ),
+ "Frame Interpolation engine": (
+ settings.frame_interpolation_engine,
+ ENGINE_CHOICES,
+ ),
+ "Frame Interpolation codec": (
+ settings.frame_interpolation_codec,
+ CODEC_CHOICES,
+ ),
+ "Frame Interpolation container": (
+ settings.frame_interpolation_container,
+ CONTAINER_CHOICES,
+ ),
+ "Frame Interpolation quality": (
+ settings.frame_interpolation_quality,
+ QUALITY_CHOICES,
+ ),
+ "Preview encoding": (
+ settings.preview_encoding,
+ PREVIEW_ENCODING_CHOICES,
+ ),
+ }
+ for label, (value, choices) in allowed.items():
+ if value not in choices:
+ raise ValueError(f"Unknown {label}: {value!r}.")
+ if isinstance(settings.image_quality, bool) or not 1 <= int(settings.image_quality) <= 100:
+ raise ValueError("Image quality must be an integer from 1 to 100.")
+ if int(settings.image_quality) != settings.image_quality:
+ raise ValueError("Image quality must be an integer from 1 to 100.")
+ validate_rename(settings.image_rename_mode, settings.image_custom_suffix)
+ validate_rename(settings.video_rename_mode, settings.video_custom_suffix)
+ validate_rename(
+ settings.frame_interpolation_rename_mode,
+ settings.frame_interpolation_custom_suffix,
+ )
+ return settings
diff --git a/src/settings/presets.py b/src/settings/presets.py
new file mode 100644
index 0000000..5ea0ab0
--- /dev/null
+++ b/src/settings/presets.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+import json
+import math
+import os
+import re
+import tempfile
+from dataclasses import asdict, fields, replace
+from pathlib import Path
+from typing import Any
+
+from .models import (
+ DEFAULT_SETTINGS, MAX_PRESET_BYTES, PRESET_FORMAT, PRESET_SCHEMA_VERSION, UISettings, _validate,
+)
+
+_WINDOWS_RESERVED_NAMES = {
+ "CON", "PRN", "AUX", "NUL",
+ *(f"COM{index}" for index in range(1, 10)),
+ *(f"LPT{index}" for index in range(1, 10)),
+}
+
+def _preset_name(value: str) -> str:
+ if not isinstance(value, str):
+ raise ValueError("Preset name must be text.")
+ name = value.strip()
+ if not name:
+ raise ValueError("Enter a preset name before exporting.")
+ if len(name) > 120:
+ raise ValueError("Preset name must be 120 characters or fewer.")
+ if any(ord(character) < 32 for character in name):
+ raise ValueError("Preset name cannot contain control characters.")
+ return name
+
+
+def preset_filename(name: str) -> str:
+ """Return a portable JSON filename while preserving the display name in the file."""
+ display_name = _preset_name(name)
+ characters = [
+ character if character.isalnum() or character in "-_" else "_"
+ for character in display_name
+ ]
+ stem = re.sub(r"_+", "_", "".join(characters)).strip("-_")[:80].rstrip("-_")
+ if not stem:
+ raise ValueError("Preset name must contain at least one letter or number.")
+ if stem.upper() in _WINDOWS_RESERVED_NAMES:
+ stem += "_preset"
+ return f"{stem}.json"
+
+
+def preset_document(name: str, settings: UISettings) -> dict[str, Any]:
+ """Build the versioned user-facing preset document."""
+ display_name = _preset_name(name)
+ _validate(settings)
+ return {
+ "format": PRESET_FORMAT,
+ "schema_version": PRESET_SCHEMA_VERSION,
+ "name": display_name,
+ "settings": asdict(settings),
+ }
+
+
+def export_settings_preset(name: str, settings: UISettings) -> Path:
+ """Write a validated preset to an isolated temporary download directory."""
+ document = preset_document(name, settings)
+ filename = preset_filename(document["name"])
+ directory = Path(tempfile.mkdtemp(prefix="dlss5-settings-preset-"))
+ path = directory / filename
+ path.write_text(
+ json.dumps(document, indent=2, ensure_ascii=False) + "\n",
+ encoding="utf-8",
+ )
+ return path.resolve()
+
+
+def _coerce_preset_value(field_name: str, value: Any, current: UISettings) -> Any:
+ expected = getattr(current, field_name)
+ if isinstance(expected, bool):
+ if not isinstance(value, bool):
+ raise ValueError(f"Preset setting {field_name!r} must be a boolean.")
+ return value
+ if isinstance(expected, int):
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValueError(f"Preset setting {field_name!r} must be an integer.")
+ return value
+ if isinstance(expected, float):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"Preset setting {field_name!r} must be a number.")
+ number = float(value)
+ if not math.isfinite(number):
+ raise ValueError(f"Preset setting {field_name!r} must be finite.")
+ return number
+ if isinstance(expected, str):
+ if not isinstance(value, str):
+ raise ValueError(f"Preset setting {field_name!r} must be text.")
+ return value
+ raise ValueError(f"Preset setting {field_name!r} has an unsupported type.")
+
+
+def import_settings_preset(
+ path: str | os.PathLike[str], current: UISettings
+) -> tuple[str, UISettings]:
+ """Load, compatibly merge, and atomically validate a version-1 preset."""
+ preset_path = Path(path)
+ if preset_path.suffix.casefold() != ".json":
+ raise ValueError("Choose a JSON preset file.")
+ try:
+ size = preset_path.stat().st_size
+ except OSError as exc:
+ raise ValueError("The selected preset file cannot be read.") from exc
+ if size > MAX_PRESET_BYTES:
+ raise ValueError("Preset file is too large; the maximum size is 1 MiB.")
+ try:
+ document = json.loads(preset_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise ValueError("Preset file is not valid UTF-8 JSON.") from exc
+ if not isinstance(document, dict):
+ raise ValueError("Preset JSON must contain an object at its top level.")
+ if document.get("format") != PRESET_FORMAT:
+ raise ValueError("This JSON file is not a DLSS 5 Visual Enhancer settings preset.")
+ version = document.get("schema_version")
+ if isinstance(version, bool) or not isinstance(version, int):
+ raise ValueError("Preset schema_version must be an integer.")
+ if version != PRESET_SCHEMA_VERSION:
+ direction = "newer" if version > PRESET_SCHEMA_VERSION else "unsupported"
+ raise ValueError(
+ f"Preset schema version {version} is {direction}; this build supports version "
+ f"{PRESET_SCHEMA_VERSION}."
+ )
+ name = _preset_name(document.get("name"))
+ imported = document.get("settings")
+ if not isinstance(imported, dict):
+ raise ValueError("Preset settings must be a JSON object.")
+
+ known_names = {field.name for field in fields(UISettings)}
+ changes = {
+ key: _coerce_preset_value(key, value, current)
+ for key, value in imported.items()
+ if key in known_names
+ }
+ merged = replace(current, **changes)
+ return name, _validate(merged)
diff --git a/src/settings/storage.py b/src/settings/storage.py
new file mode 100644
index 0000000..7824143
--- /dev/null
+++ b/src/settings/storage.py
@@ -0,0 +1,285 @@
+from __future__ import annotations
+
+import configparser
+import math
+import os
+import threading
+from dataclasses import replace
+from pathlib import Path
+
+from ..core.ffmpeg import HDR_ALLOWED_CODECS
+from ..core.paths import CONFIG_PATH
+from ..core.naming import RENAME_MODES, validate_rename
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, resolve_upscaling_mode
+from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES
+from .migration import _migrate_codec
+from .models import (
+ CODEC_CHOICES, CONFIG_SECTION, CONTAINER_CHOICES, DEFAULT_SETTINGS, IMAGE_FORMAT_CHOICES,
+ PREVIEW_ENCODING_CHOICES, QUALITY_CHOICES, UISettings, _validate,
+)
+
+def load_settings(path: str | os.PathLike[str]) -> UISettings:
+ config_path = Path(path)
+ parser = configparser.ConfigParser()
+ try:
+ with config_path.open("r", encoding="utf-8") as stream:
+ parser.read_file(stream)
+ except (OSError, configparser.Error):
+ return DEFAULT_SETTINGS
+
+ section = parser[CONFIG_SECTION] if parser.has_section(CONFIG_SECTION) else {}
+
+ def choice(key: str, choices: tuple[str, ...], default: str) -> str:
+ value = section.get(key, default)
+ # Migrate old HEVC naming before validation
+ if key in ("codec", "frame_interpolation_codec"):
+ migrated = _migrate_codec(value)
+ if migrated in choices:
+ return migrated
+ return value if value in choices else default
+
+ def codec_choice(key: str, default: str) -> str:
+ raw = section.get(key, default)
+ migrated = _migrate_codec(raw)
+ if migrated in CODEC_CHOICES:
+ return migrated
+ return default
+
+ def number(key: str, minimum: float, maximum: float, default: float) -> float:
+ try:
+ value = float(section.get(key, str(default)))
+ except (TypeError, ValueError):
+ return default
+ return value if math.isfinite(value) and minimum <= value <= maximum else default
+
+ def upscaling_factor() -> float:
+ try:
+ return resolve_upscaling_mode(float(section.get("upscaling_factor", "1.0")))[0]
+ except (TypeError, ValueError):
+ return DEFAULT_SETTINGS.upscaling_factor
+
+ def image_quality() -> int:
+ 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
+
+ def hdr_mode_value() -> bool:
+ # Support both new 'hdr_mode' and legacy 'preserve_hdr' keys
+ raw = section.get("hdr_mode")
+ if raw is None:
+ raw = section.get("preserve_hdr")
+ if raw is None:
+ return DEFAULT_SETTINGS.hdr_mode
+ parsed = configparser.ConfigParser.BOOLEAN_STATES.get(str(raw).casefold())
+ return parsed if parsed is not None else DEFAULT_SETTINGS.hdr_mode
+
+ def fi_hdr_mode_value() -> bool:
+ raw = section.get("frame_interpolation_hdr_mode")
+ if raw is None:
+ # Check legacy if ever used
+ raw = section.get("frame_interpolation_preserve_hdr")
+ if raw is None:
+ return DEFAULT_SETTINGS.frame_interpolation_hdr_mode
+ parsed = configparser.ConfigParser.BOOLEAN_STATES.get(str(raw).casefold())
+ return parsed if parsed is not None else DEFAULT_SETTINGS.frame_interpolation_hdr_mode
+
+ def frame_interpolation_engine() -> str:
+ value = section.get(
+ "frame_interpolation_engine",
+ DEFAULT_SETTINGS.frame_interpolation_engine,
+ )
+ if value == "Experimental Cascade":
+ return "Cascade"
+ return value if value in ENGINE_CHOICES else DEFAULT_SETTINGS.frame_interpolation_engine
+
+ image_rename_mode = choice(
+ "image_rename_mode", RENAME_MODES, DEFAULT_SETTINGS.image_rename_mode
+ )
+ image_custom_suffix = section.get(
+ "image_custom_suffix", DEFAULT_SETTINGS.image_custom_suffix
+ )
+ video_rename_mode = choice(
+ "video_rename_mode", RENAME_MODES, DEFAULT_SETTINGS.video_rename_mode
+ )
+ video_custom_suffix = section.get(
+ "video_custom_suffix", DEFAULT_SETTINGS.video_custom_suffix
+ )
+ frame_interpolation_rename_mode = choice(
+ "frame_interpolation_rename_mode",
+ RENAME_MODES,
+ DEFAULT_SETTINGS.frame_interpolation_rename_mode,
+ )
+ frame_interpolation_custom_suffix = section.get(
+ "frame_interpolation_custom_suffix",
+ DEFAULT_SETTINGS.frame_interpolation_custom_suffix,
+ )
+ try:
+ validate_rename(image_rename_mode, image_custom_suffix)
+ except ValueError:
+ image_rename_mode = DEFAULT_SETTINGS.image_rename_mode
+ image_custom_suffix = DEFAULT_SETTINGS.image_custom_suffix
+ try:
+ validate_rename(video_rename_mode, video_custom_suffix)
+ except ValueError:
+ video_rename_mode = DEFAULT_SETTINGS.video_rename_mode
+ video_custom_suffix = DEFAULT_SETTINGS.video_custom_suffix
+ try:
+ validate_rename(
+ frame_interpolation_rename_mode,
+ frame_interpolation_custom_suffix,
+ )
+ except ValueError:
+ frame_interpolation_rename_mode = DEFAULT_SETTINGS.frame_interpolation_rename_mode
+ frame_interpolation_custom_suffix = DEFAULT_SETTINGS.frame_interpolation_custom_suffix
+
+ settings = UISettings(
+ ai_gpu_uuid=section.get("ai_gpu_uuid", DEFAULT_SETTINGS.ai_gpu_uuid).strip()
+ or DEFAULT_SETTINGS.ai_gpu_uuid,
+ video_gpu_uuid=section.get("video_gpu_uuid", DEFAULT_SETTINGS.video_gpu_uuid).strip()
+ or DEFAULT_SETTINGS.video_gpu_uuid,
+ nr_preset=choice("nr_preset", tuple(NR_PRESETS), DEFAULT_SETTINGS.nr_preset),
+ nr_style=choice("nr_style", tuple(NR_STYLES), DEFAULT_SETTINGS.nr_style),
+ nr_intensity=number("nr_intensity", 0.0, 2.0, DEFAULT_SETTINGS.nr_intensity),
+ local_tone_strength=number(
+ "local_tone_strength", 0.0, 2.0, DEFAULT_SETTINGS.local_tone_strength
+ ),
+ local_structure_strength=number(
+ "local_structure_strength", 0.0, 2.0, DEFAULT_SETTINGS.local_structure_strength
+ ),
+ 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=codec_choice("codec", DEFAULT_SETTINGS.codec),
+ container=choice("container", CONTAINER_CHOICES, DEFAULT_SETTINGS.container),
+ quality=choice("quality", QUALITY_CHOICES, DEFAULT_SETTINGS.quality),
+ hdr_mode=hdr_mode_value(),
+ image_format=choice(
+ "image_format", IMAGE_FORMAT_CHOICES, DEFAULT_SETTINGS.image_format
+ ),
+ image_quality=image_quality(),
+ dlss_model_preset=choice(
+ "dlss_model_preset",
+ tuple(DLSS_MODEL_PRESETS),
+ DEFAULT_SETTINGS.dlss_model_preset,
+ ),
+ image_rename_mode=image_rename_mode,
+ image_custom_suffix=image_custom_suffix,
+ video_rename_mode=video_rename_mode,
+ video_custom_suffix=video_custom_suffix,
+ frame_interpolation_target_fps=choice(
+ "frame_interpolation_target_fps",
+ FPS_CHOICES,
+ DEFAULT_SETTINGS.frame_interpolation_target_fps,
+ ),
+ frame_interpolation_engine=frame_interpolation_engine(),
+ frame_interpolation_codec=codec_choice(
+ "frame_interpolation_codec",
+ DEFAULT_SETTINGS.frame_interpolation_codec,
+ ),
+ frame_interpolation_container=choice(
+ "frame_interpolation_container",
+ CONTAINER_CHOICES,
+ DEFAULT_SETTINGS.frame_interpolation_container,
+ ),
+ frame_interpolation_quality=choice(
+ "frame_interpolation_quality",
+ QUALITY_CHOICES,
+ DEFAULT_SETTINGS.frame_interpolation_quality,
+ ),
+ frame_interpolation_hdr_mode=fi_hdr_mode_value(),
+ frame_interpolation_rename_mode=frame_interpolation_rename_mode,
+ frame_interpolation_custom_suffix=frame_interpolation_custom_suffix,
+ preview_encoding=choice(
+ "preview_encoding",
+ PREVIEW_ENCODING_CHOICES,
+ DEFAULT_SETTINGS.preview_encoding,
+ ),
+ )
+ # Auto-disable HDR Mode if codec does not support it (e.g. H.264)
+ try:
+ if settings.hdr_mode and settings.codec not in HDR_ALLOWED_CODECS:
+ settings = replace(settings, hdr_mode=False)
+ if settings.frame_interpolation_hdr_mode and settings.frame_interpolation_codec not in HDR_ALLOWED_CODECS:
+ settings = replace(settings, frame_interpolation_hdr_mode=False)
+ except Exception:
+ pass
+ return settings
+
+
+def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:
+ settings = _validate(settings)
+ config_path = Path(path)
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ parser = configparser.ConfigParser()
+ parser[CONFIG_SECTION] = {
+ "ai_gpu_uuid": settings.ai_gpu_uuid,
+ "video_gpu_uuid": settings.video_gpu_uuid,
+ "nr_preset": settings.nr_preset,
+ "nr_style": settings.nr_style,
+ "nr_intensity": f"{settings.nr_intensity:.2f}",
+ "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,
+ "quality": settings.quality,
+ "hdr_mode": str(settings.hdr_mode).lower(),
+ "image_format": settings.image_format,
+ "image_quality": str(settings.image_quality),
+ "image_rename_mode": settings.image_rename_mode,
+ "image_custom_suffix": settings.image_custom_suffix,
+ "video_rename_mode": settings.video_rename_mode,
+ "video_custom_suffix": settings.video_custom_suffix,
+ "dlss_model_preset": settings.dlss_model_preset,
+ "frame_interpolation_target_fps": settings.frame_interpolation_target_fps,
+ "frame_interpolation_engine": settings.frame_interpolation_engine,
+ "frame_interpolation_codec": settings.frame_interpolation_codec,
+ "frame_interpolation_container": settings.frame_interpolation_container,
+ "frame_interpolation_quality": settings.frame_interpolation_quality,
+ "frame_interpolation_hdr_mode": str(settings.frame_interpolation_hdr_mode).lower(),
+ "frame_interpolation_rename_mode": settings.frame_interpolation_rename_mode,
+ "frame_interpolation_custom_suffix": settings.frame_interpolation_custom_suffix,
+ "preview_encoding": settings.preview_encoding,
+ }
+
+ temporary = config_path.with_name(f".{config_path.name}.tmp")
+ try:
+ with temporary.open("w", encoding="utf-8", newline="") as stream:
+ parser.write(stream)
+ os.replace(temporary, config_path)
+ finally:
+ if temporary.exists():
+ temporary.unlink()
+
+
+class _SettingsState:
+ def __init__(self) -> None:
+ self.lock = threading.Lock()
+ self.current: UISettings | None = None
+
+
+SETTINGS_STATE = _SettingsState()
+
+
+def processing_gpu_settings() -> tuple[str, str]:
+ with SETTINGS_STATE.lock:
+ settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ return settings.ai_gpu_uuid, settings.video_gpu_uuid
+
+
+def current_preview_encoding() -> str:
+ from ..core.ffmpeg.preview import normalize_preview_encoding
+
+ with SETTINGS_STATE.lock:
+ settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ return normalize_preview_encoding(settings.preview_encoding)
diff --git a/src/settings/ui.py b/src/settings/ui.py
new file mode 100644
index 0000000..29a5118
--- /dev/null
+++ b/src/settings/ui.py
@@ -0,0 +1,506 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+
+import gradio as gr
+
+from ..core.ffmpeg import hdr_mode_supported, probe_nvenc_codecs
+from ..core.gpu_selection import gpu_choice_label
+from ..core.paths import CONFIG_PATH
+from ..core.runtime import prepare_runtime
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES
+from ..core.naming import RENAME_MODES
+from ..core.ffmpeg.preview import normalize_preview_encoding
+from .models import (
+ AUTOMATIC_MASK_CHOICES, CODEC_CHOICES, CONTAINER_CHOICES, DEFAULT_SETTINGS, PREVIEW_ENCODING_CHOICES,
+ QUALITY_CHOICES, UISettings,
+ automatic_mask_choice, coerce_hdr_mode, parse_automatic_mask,
+)
+from .presets import export_settings_preset, import_settings_preset, preset_filename
+from .storage import SETTINGS_STATE, load_settings, save_settings
+
+_CONFIG_LOCK = SETTINGS_STATE.lock
+UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
+
+def _neural_values(
+ settings: UISettings,
+) -> tuple[str, str, float, float, float, float, float, str]:
+ return (
+ settings.nr_preset,
+ settings.nr_style,
+ settings.nr_intensity,
+ settings.local_tone_strength,
+ settings.local_structure_strength,
+ settings.skin_structure_strength,
+ settings.upscaling_factor,
+ automatic_mask_choice(settings.automatic_mask),
+ )
+
+
+def _shared_dlss_values(
+ settings: UISettings,
+) -> tuple[str, str, float, float, float, float, float, str, str]:
+ return (*_neural_values(settings), settings.dlss_model_preset)
+
+
+def persist_image_settings(
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ image_format: str,
+ image_quality: float,
+ rename_mode: str,
+ custom_suffix: str,
+) -> tuple[str, str, float, float, float, float, float, str, str]:
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ settings = replace(
+ current,
+ nr_preset=nr_preset,
+ nr_style=nr_style,
+ nr_intensity=nr_intensity,
+ local_tone_strength=local_tone_strength,
+ local_structure_strength=local_structure_strength,
+ skin_structure_strength=skin_structure_strength,
+ upscaling_factor=upscaling_factor,
+ automatic_mask=parse_automatic_mask(automatic_mask),
+ dlss_model_preset=dlss_model_preset,
+ image_format=image_format,
+ image_quality=int(image_quality),
+ image_rename_mode=rename_mode,
+ image_custom_suffix=custom_suffix,
+ )
+ if settings != current:
+ save_settings(CONFIG_PATH, settings)
+ SETTINGS_STATE.current = settings
+ return _shared_dlss_values(settings)
+
+
+def persist_video_settings(
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool,
+ rename_mode: str,
+ custom_suffix: str,
+) -> tuple[str, str, float, float, float, float, float, str, str]:
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ coerced_hdr = coerce_hdr_mode(codec, hdr_mode)
+ settings = replace(
+ current,
+ nr_preset=nr_preset,
+ nr_style=nr_style,
+ nr_intensity=nr_intensity,
+ local_tone_strength=local_tone_strength,
+ local_structure_strength=local_structure_strength,
+ skin_structure_strength=skin_structure_strength,
+ upscaling_factor=upscaling_factor,
+ automatic_mask=parse_automatic_mask(automatic_mask),
+ dlss_model_preset=dlss_model_preset,
+ codec=codec,
+ container=container,
+ quality=quality,
+ hdr_mode=coerced_hdr,
+ video_rename_mode=rename_mode,
+ video_custom_suffix=custom_suffix,
+ )
+ if settings != current:
+ save_settings(CONFIG_PATH, settings)
+ SETTINGS_STATE.current = settings
+ return _shared_dlss_values(settings)
+
+
+def persist_frame_interpolation_settings(
+ target_fps: str,
+ engine: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool,
+ rename_mode: str,
+ custom_suffix: str,
+) -> None:
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ coerced_hdr = coerce_hdr_mode(codec, hdr_mode)
+ settings = replace(
+ current,
+ frame_interpolation_target_fps=target_fps,
+ frame_interpolation_engine=engine,
+ frame_interpolation_codec=codec,
+ frame_interpolation_container=container,
+ frame_interpolation_quality=quality,
+ frame_interpolation_hdr_mode=coerced_hdr,
+ frame_interpolation_rename_mode=rename_mode,
+ frame_interpolation_custom_suffix=custom_suffix,
+ )
+ if settings != current:
+ save_settings(CONFIG_PATH, settings)
+ SETTINGS_STATE.current = settings
+
+
+def _settings_component_values(settings: UISettings) -> tuple:
+ shared = _shared_dlss_values(settings)
+ return (
+ *shared,
+ *shared,
+ settings.image_format,
+ settings.image_quality,
+ settings.image_rename_mode,
+ gr.update(
+ value=settings.image_custom_suffix,
+ interactive=settings.image_rename_mode == "Custom",
+ ),
+ settings.codec,
+ settings.container,
+ settings.quality,
+ gr.update(value=settings.hdr_mode, interactive=hdr_mode_supported(settings.codec)),
+ settings.video_rename_mode,
+ gr.update(
+ value=settings.video_custom_suffix,
+ interactive=settings.video_rename_mode == "Custom",
+ ),
+ settings.frame_interpolation_target_fps,
+ settings.frame_interpolation_engine,
+ settings.frame_interpolation_codec,
+ settings.frame_interpolation_container,
+ settings.frame_interpolation_quality,
+ gr.update(value=settings.frame_interpolation_hdr_mode, interactive=hdr_mode_supported(settings.frame_interpolation_codec)),
+ settings.frame_interpolation_rename_mode,
+ gr.update(
+ value=settings.frame_interpolation_custom_suffix,
+ interactive=settings.frame_interpolation_rename_mode == "Custom",
+ ),
+ settings.ai_gpu_uuid,
+ settings.video_gpu_uuid,
+ settings.preview_encoding,
+ )
+
+
+def _gpu_choices(prepared) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:
+ automatic = [("Auto", "auto")]
+ ai = []
+ for gpu in prepared.gpus:
+ if not gpu.get("ai_compatible"):
+ continue
+ ai.append((gpu_choice_label(gpu), str(gpu["uuid"])))
+ video = [
+ (gpu_choice_label(gpu), str(gpu["uuid"]))
+ for gpu in prepared.gpus
+ if gpu.get("cuda_ordinal") is not None
+ and probe_nvenc_codecs(int(gpu["cuda_ordinal"]))
+ ]
+ return automatic + ai, automatic + video
+
+
+def _normalize_gpu_settings(settings: UISettings, prepared) -> tuple[UISettings, str]:
+ ai_choices, video_choices = _gpu_choices(prepared)
+ ai_values = {value for _label, value in ai_choices}
+ video_values = {value for _label, value in video_choices}
+ warnings = []
+ ai_uuid = settings.ai_gpu_uuid
+ video_uuid = settings.video_gpu_uuid
+ if ai_uuid not in ai_values:
+ warnings.append("Saved AI Processing GPU is unavailable; using Auto.")
+ ai_uuid = "auto"
+ if video_uuid not in video_values:
+ warnings.append("Saved Video Processing GPU is unavailable; using Auto.")
+ video_uuid = "auto"
+ return replace(settings, ai_gpu_uuid=ai_uuid, video_gpu_uuid=video_uuid), " ".join(warnings)
+
+
+def persist_preview_encoding(preview_encoding: str) -> None:
+ normalized = normalize_preview_encoding(preview_encoding)
+ if not isinstance(preview_encoding, str) or preview_encoding.strip() not in PREVIEW_ENCODING_CHOICES:
+ raise gr.Error(
+ f"Preview Encoding must be one of: {', '.join(PREVIEW_ENCODING_CHOICES)}."
+ )
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ settings = replace(current, preview_encoding=normalized)
+ if settings != current:
+ save_settings(CONFIG_PATH, settings)
+ SETTINGS_STATE.current = settings
+
+
+def persist_gpu_settings(ai_gpu_uuid: str, video_gpu_uuid: str) -> str:
+ prepared = prepare_runtime()
+ ai_choices, video_choices = _gpu_choices(prepared)
+ if ai_gpu_uuid not in {value for _label, value in ai_choices}:
+ raise gr.Error("Choose an available AI Processing GPU.")
+ if video_gpu_uuid not in {value for _label, value in video_choices}:
+ raise gr.Error("Choose an available Video Processing GPU.")
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ settings = replace(
+ current, ai_gpu_uuid=ai_gpu_uuid, video_gpu_uuid=video_gpu_uuid
+ )
+ if settings != current:
+ save_settings(CONFIG_PATH, settings)
+ SETTINGS_STATE.current = settings
+ ai_name = "Auto" if ai_gpu_uuid == "auto" else next(
+ label for label, value in ai_choices if value == ai_gpu_uuid
+ )
+ video_name = "Auto" if video_gpu_uuid == "auto" else next(
+ label for label, value in video_choices if value == video_gpu_uuid
+ )
+ return f"AI Processing: {ai_name}\n\nVideo Processing: {video_name}"
+
+
+def reset_saved_settings() -> tuple:
+ with _CONFIG_LOCK:
+ save_settings(CONFIG_PATH, DEFAULT_SETTINGS)
+ SETTINGS_STATE.current = DEFAULT_SETTINGS
+ message = "All Image, Video, and Frame Interpolation settings were reset to defaults."
+ return (
+ *_settings_component_values(DEFAULT_SETTINGS),
+ message,
+ message,
+ message,
+ )
+
+
+def settings_preset_download(name: str) -> str | None:
+ if not isinstance(name, str) or not name.strip():
+ return None
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ try:
+ path = export_settings_preset(name, current)
+ except ValueError:
+ return None
+ return str(path)
+
+
+def settings_preset_export_status(name: str) -> str:
+ try:
+ filename = preset_filename(name)
+ except ValueError as exc:
+ return f"Export failed: {exc}"
+ return f"Exported preset {name.strip()!r} as {filename}."
+
+
+def apply_settings_preset(
+ uploaded_path: str | None, current_name: str
+) -> tuple:
+ with _CONFIG_LOCK:
+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ try:
+ if not uploaded_path:
+ raise ValueError("Choose a JSON preset file before importing.")
+ name, imported = import_settings_preset(uploaded_path, current)
+ imported, gpu_warning = _normalize_gpu_settings(
+ imported, prepare_runtime()
+ )
+ save_settings(CONFIG_PATH, imported)
+ except (OSError, ValueError) as exc:
+ return (
+ current_name,
+ *_settings_component_values(current),
+ f"Import failed: {exc}",
+ )
+ SETTINGS_STATE.current = imported
+ return (
+ name,
+ *_settings_component_values(imported),
+ f"Imported preset {name!r}; all tabs and saved startup settings were updated."
+ + (f" {gpu_warning}" if gpu_warning else ""),
+ )
+
+@dataclass(slots=True)
+class SettingsTab:
+ ai_gpu_selector: object
+ video_gpu_selector: object
+ preview_encoding_selector: object
+ preset_name: object
+ preset_export: object
+ preset_import: object
+ preset_status: object
+
+
+def initialize_settings(prepared) -> tuple[UISettings, str, list[tuple[str, str]], list[tuple[str, str]]]:
+ settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+ normalized, warning = _normalize_gpu_settings(settings, prepared)
+ if normalized != settings:
+ save_settings(CONFIG_PATH, normalized)
+ SETTINGS_STATE.current = normalized
+ ai_choices, video_choices = _gpu_choices(prepared)
+ return normalized, warning, ai_choices, video_choices
+
+
+def current_settings() -> UISettings:
+ with _CONFIG_LOCK:
+ return SETTINGS_STATE.current or load_settings(CONFIG_PATH)
+
+
+def build_settings_tab(
+ settings: UISettings,
+ ai_gpu_choices: list[tuple[str, str]],
+ video_gpu_choices: list[tuple[str, str]],
+) -> SettingsTab:
+ gr.Markdown(
+ "## GPU Selection\n"
+ "AI Processing controls DLSS and Frame Generation. Video Processing "
+ "controls only codecs suffixed (NVIDIA NVENC); plain H.264/H.265/AV1 and ProRes remain CPU-based."
+ )
+ with gr.Row():
+ ai_gpu_selector = gr.Dropdown(
+ choices=ai_gpu_choices,
+ value=settings.ai_gpu_uuid,
+ label="AI Processing GPU",
+ info="Used for every DLSS Neural Rendering and Frame Generation operation.",
+ )
+ video_gpu_selector = gr.Dropdown(
+ choices=video_gpu_choices,
+ value=settings.video_gpu_uuid,
+ label="Video Processing GPU",
+ info="Used only for codecs suffixed (NVIDIA NVENC); plain H.264/H.265/AV1 and ProRes stay on CPU.",
+ )
+ gr.Markdown(
+ "## Preview Encoding\n"
+ "Controls how in-app video previews are produced for the Video and Frame "
+ "Interpolation tabs (preview buttons and final-render player)."
+ )
+ preview_encoding_selector = gr.Radio(
+ choices=list(PREVIEW_ENCODING_CHOICES),
+ value=normalize_preview_encoding(settings.preview_encoding),
+ label="Preview Encoding",
+ info=(
+ "Auto uses the result directly when the browser can play it (MP4 + H.264, "
+ "verified by probe); otherwise creates an H.264 preview. "
+ "Always H.264 always generates a browser-compatible preview. "
+ "Disabled never creates one and sends the actual file to the browser. "
+ "Non-H.264 previews can be slower and larger."
+ ),
+ )
+ gr.Markdown(
+ "## Settings Presets\n"
+ "Export every adjustable option from the Image, Video, and Frame "
+ "Interpolation tabs, or import a preset to apply it everywhere."
+ )
+ preset_name = gr.Textbox(
+ label="Preset name",
+ placeholder="Cinematic 2",
+ info="The exported file uses this name; the original name is stored in JSON.",
+ )
+ with gr.Row():
+ preset_export = gr.DownloadButton(
+ "Export preset",
+ value=settings_preset_download,
+ inputs=preset_name,
+ variant="primary",
+ scale=1,
+ )
+ preset_import = gr.UploadButton(
+ "Import preset",
+ file_count="single",
+ file_types=[".json"],
+ type="filepath",
+ variant="primary",
+ scale=1,
+ )
+ preset_status = gr.Markdown("", elem_id="preset-status")
+ return SettingsTab(
+ ai_gpu_selector, video_gpu_selector, preview_encoding_selector,
+ preset_name, preset_export, preset_import, preset_status
+ )
+
+
+
+def settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab) -> list[object]:
+ return [
+ *image_tab.neural,
+ image_tab.model_preset,
+ *video_tab.neural,
+ video_tab.model_preset,
+ image_tab.output_format,
+ image_tab.quality,
+ image_tab.rename_mode,
+ image_tab.custom_suffix,
+ video_tab.codec,
+ video_tab.container,
+ video_tab.quality,
+ video_tab.hdr_mode,
+ video_tab.rename_mode,
+ video_tab.custom_suffix,
+ frame_tab.target_fps,
+ frame_tab.engine,
+ frame_tab.codec,
+ frame_tab.container,
+ frame_tab.quality,
+ frame_tab.hdr_mode,
+ frame_tab.rename_mode,
+ frame_tab.custom_suffix,
+ settings_tab.ai_gpu_selector,
+ settings_tab.video_gpu_selector,
+ settings_tab.preview_encoding_selector,
+ ]
+
+
+def bind_settings_events(settings_tab, image_tab, video_tab, frame_tab) -> None:
+ for component in image_tab.settings_inputs:
+ component.input(
+ persist_image_settings,
+ inputs=image_tab.settings_inputs,
+ outputs=[*video_tab.neural, video_tab.model_preset],
+ queue=False,
+ )
+ for component in video_tab.settings_inputs:
+ component.input(
+ persist_video_settings,
+ inputs=video_tab.settings_inputs,
+ outputs=[*image_tab.neural, image_tab.model_preset],
+ queue=False,
+ )
+ for component in frame_tab.settings_inputs:
+ component.input(
+ persist_frame_interpolation_settings,
+ inputs=frame_tab.settings_inputs,
+ queue=False,
+ )
+
+ outputs = settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab)
+ settings_tab.preset_export.click(
+ settings_preset_export_status,
+ inputs=settings_tab.preset_name,
+ outputs=settings_tab.preset_status,
+ queue=False,
+ )
+ settings_tab.preset_import.upload(
+ apply_settings_preset,
+ inputs=[settings_tab.preset_import, settings_tab.preset_name],
+ outputs=[settings_tab.preset_name, *outputs, settings_tab.preset_status],
+ queue=False,
+ )
+ for selector in [settings_tab.ai_gpu_selector, settings_tab.video_gpu_selector]:
+ selector.input(
+ persist_gpu_settings,
+ inputs=[settings_tab.ai_gpu_selector, settings_tab.video_gpu_selector],
+ queue=False,
+ )
+ settings_tab.preview_encoding_selector.input(
+ persist_preview_encoding,
+ inputs=settings_tab.preview_encoding_selector,
+ queue=False,
+ )
+
+ reset_outputs = [*outputs, image_tab.status, video_tab.status, frame_tab.status]
+ image_tab.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
+ video_tab.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
+ frame_tab.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
diff --git a/src/video/__init__.py b/src/video/__init__.py
new file mode 100644
index 0000000..bc7fb6a
--- /dev/null
+++ b/src/video/__init__.py
@@ -0,0 +1,20 @@
+from .batch import convert_videos
+from .models import (
+ ConversionOptions, ConversionResult, DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES,
+ UPSCALING_MODES, VideoBatchResult, VideoConversionFailure, VideoConversionSuccess,
+)
+from .processor import convert_video
+from .sizing import (
+ AUTO_BITRATE_DIVISORS, ENCODING_QUALITIES, UPSCALING_CHOICES,
+ calculate_auto_bitrate_kbps, probe_video, resolve_encoding_quality,
+ resolve_native_settings, resolve_output_size, resolve_upscaling_mode, validate_codec_container,
+)
+
+__all__ = [
+ "AUTO_BITRATE_DIVISORS", "ConversionOptions", "ConversionResult", "DLSS_MODEL_PRESETS",
+ "ENCODING_QUALITIES", "NR_PRESETS", "NR_STYLES", "UPSCALING_CHOICES", "UPSCALING_MODES",
+ "VideoBatchResult", "VideoConversionFailure", "VideoConversionSuccess",
+ "calculate_auto_bitrate_kbps", "convert_video", "convert_videos", "probe_video",
+ "resolve_encoding_quality", "resolve_native_settings", "resolve_output_size",
+ "resolve_upscaling_mode", "validate_codec_container",
+]
diff --git a/src/video/batch.py b/src/video/batch.py
new file mode 100644
index 0000000..6eb661d
--- /dev/null
+++ b/src/video/batch.py
@@ -0,0 +1,112 @@
+from __future__ import annotations
+
+import os
+import time
+from pathlib import Path
+from typing import Callable, Iterable
+
+from ..core.jobs import Cancelled, active_job
+from ..core.paths import LOGS
+from ..core.runtime import prepare_runtime
+from .models import (
+ ConversionOptions, VideoBatchResult, VideoConversionFailure, VideoConversionSuccess,
+)
+from .processor import _BATCH_CONTEXT, convert_video
+from .reports import _write_video_batch_manifest
+
+def convert_videos(
+ input_paths: Iterable[str | os.PathLike[str]],
+ options: ConversionOptions | None = None,
+ progress: Callable[[float, str], None] | None = None,
+) -> VideoBatchResult:
+ """Convert videos sequentially while holding one cancellable GPU batch slot."""
+ options = options or ConversionOptions()
+ paths = [Path(path).resolve() for path in input_paths]
+ if not paths:
+ raise ValueError("Choose at least one video.")
+
+ prepared_runtime = prepare_runtime()
+ LOGS.mkdir(exist_ok=True)
+ stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
+ successes: list[VideoConversionSuccess] = []
+ failures: list[VideoConversionFailure] = []
+ cancelled = False
+ total = len(paths)
+
+ with active_job() as controller:
+ if getattr(_BATCH_CONTEXT, "controller", None) is not None:
+ raise RuntimeError("A video batch is already active on this worker thread.")
+ _BATCH_CONTEXT.controller = controller
+ _BATCH_CONTEXT.prepared_runtime = prepared_runtime
+ try:
+ for index, path in enumerate(paths):
+ position = index + 1
+ prefix = f"[{position}/{total}] {path.name}"
+ if controller.cancel.is_set():
+ cancelled = True
+ failures.extend(
+ VideoConversionFailure(
+ queued_index,
+ str(queued),
+ "Cancelled before rendering.",
+ cancelled=True,
+ )
+ for queued_index, queued in enumerate(paths[index:], start=index)
+ )
+ break
+
+ def report_item(
+ value: float,
+ message: str,
+ *,
+ item_index: int = index,
+ item_prefix: str = prefix,
+ ) -> None:
+ bounded = min(1.0, max(0.0, float(value)))
+ overall = (item_index + bounded) / total
+ if progress:
+ progress(overall, f"{item_prefix} — {message}")
+
+ if progress:
+ progress(index / total, f"{prefix} — starting")
+ try:
+ result = convert_video(path, options, progress=report_item)
+ except Cancelled:
+ cancelled = True
+ failures.append(
+ VideoConversionFailure(
+ index,
+ str(path),
+ "Cancelled during rendering.",
+ cancelled=True,
+ )
+ )
+ failures.extend(
+ VideoConversionFailure(
+ queued_index,
+ str(queued),
+ "Cancelled before rendering.",
+ cancelled=True,
+ )
+ for queued_index, queued in enumerate(paths[position:], start=position)
+ )
+ break
+ except Exception as exc:
+ failures.append(VideoConversionFailure(index, str(path), str(exc)))
+ if progress:
+ progress(position / total, f"{prefix} — failed")
+ continue
+
+ successes.append(VideoConversionSuccess(index, str(path), result))
+ if progress:
+ progress(position / total, f"{prefix} — complete")
+ finally:
+ del _BATCH_CONTEXT.controller
+ del _BATCH_CONTEXT.prepared_runtime
+
+ manifest_path = _write_video_batch_manifest(
+ stamp, options, successes, failures, cancelled
+ )
+ if progress:
+ progress(1.0, "Cancelled" if cancelled else "Complete")
+ return VideoBatchResult(successes, failures, cancelled, manifest_path)
diff --git a/src/video/guides.py b/src/video/guides.py
new file mode 100644
index 0000000..8f690b3
--- /dev/null
+++ b/src/video/guides.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import cv2
+import numpy as np
+
+@dataclass(slots=True)
+class GuideFrame:
+ motion: np.ndarray
+ reset: bool
+ scene_score: float
+
+
+class TemporalGuideGenerator:
+ """Estimate the guide buffers an encoded video does not contain."""
+
+ def __init__(self, width: int, height: int, flow_width: int = 640) -> None:
+ self.width = width
+ self.height = height
+ scale = min(1.0, flow_width / width)
+ self.flow_width = max(64, int(round(width * scale / 2) * 2))
+ self.flow_height = max(64, int(round(height * scale / 2) * 2))
+ self.previous_gray: np.ndarray | None = None
+ self.zero_motion = np.zeros((height, width, 2), dtype=np.float16)
+ self.dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
+ self.dis.setUseSpatialPropagation(True)
+ self.dis.setFinestScale(1)
+
+ def _small_gray(self, rgba: np.ndarray) -> np.ndarray:
+ gray = cv2.cvtColor(rgba, cv2.COLOR_RGBA2GRAY)
+ return cv2.resize(
+ gray,
+ (self.flow_width, self.flow_height),
+ interpolation=cv2.INTER_AREA,
+ )
+
+ def process(self, rgba: np.ndarray) -> GuideFrame:
+ current = self._small_gray(rgba)
+ if self.previous_gray is None:
+ motion = self.zero_motion
+ reset = True
+ scene_score = 1.0
+ else:
+ scene_score = float(np.mean(cv2.absdiff(current, self.previous_gray))) / 255.0
+ reset = scene_score > 0.24
+ if reset:
+ motion = self.zero_motion
+ else:
+ motion = self.dis.calc(current, self.previous_gray, None)
+ motion = cv2.resize(
+ motion,
+ (self.width, self.height),
+ interpolation=cv2.INTER_LINEAR,
+ )
+ motion[..., 0] *= self.width / self.flow_width
+ motion[..., 1] *= self.height / self.flow_height
+ motion = np.ascontiguousarray(motion.astype(np.float16))
+ self.previous_gray = current
+ return GuideFrame(
+ motion=motion,
+ reset=reset,
+ scene_score=scene_score,
+ )
diff --git a/src/video/models.py b/src/video/models.py
new file mode 100644
index 0000000..8c229fe
--- /dev/null
+++ b/src/video/models.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES
+
+
+@dataclass(slots=True)
+class ConversionOptions:
+ ai_gpu_uuid: str = "auto"
+ video_gpu_uuid: str = "auto"
+ nr_style: str = "Default"
+ nr_intensity: float = 1.0
+ local_tone_strength: float = 1.0
+ local_structure_strength: float = 1.0
+ skin_structure_strength: float = -1.0
+ upscaling_factor: float = 1.0
+ codec: str = "H.264"
+ container: str = "MP4"
+ quality: str = "Auto (Default)"
+ preserve_hdr: bool = False
+ warmup_frames: int = 0
+ preview_seconds: float | None = None
+ preview_frames: int | None = None
+ nr_preset: str = "Default"
+ automatic_mask: bool = False
+ rename_mode: str = "Auto"
+ custom_suffix: str = "_DLSS5"
+ dlss_model_preset: str = "Default"
+ # True = truncated preview uses the forced H.264 SDR path (current behavior).
+ # False = truncated preview uses the user's codec/container (HDR preserved).
+ preview_compat: bool = True
+
+@dataclass(slots=True)
+class ConversionResult:
+ output_path: str
+ report_path: str
+ frames: int
+ nr_count_evidence: int
+ elapsed_seconds: float
+ gpu: str
+ input_width: int
+ input_height: int
+ render_width: int
+ render_height: int
+ output_width: int
+ output_height: int
+ upscaling_factor: float
+ dlss_mode: str
+ dlss_model_preset: str = "Default"
+ applied_dlss_model_preset: int = 0
+
+
+@dataclass(slots=True)
+class VideoConversionSuccess:
+ index: int
+ input_path: str
+ result: ConversionResult
+
+
+@dataclass(slots=True)
+class VideoConversionFailure:
+ index: int
+ input_path: str
+ error: str
+ cancelled: bool = False
+
+
+@dataclass(slots=True)
+class VideoBatchResult:
+ successes: list[VideoConversionSuccess]
+ failures: list[VideoConversionFailure]
+ cancelled: bool
+ manifest_path: str
diff --git a/src/video/preview.py b/src/video/preview.py
new file mode 100644
index 0000000..574c50f
--- /dev/null
+++ b/src/video/preview.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+import traceback
+from pathlib import Path
+
+import gradio as gr
+
+from ..core.ffmpeg.preview import (
+ is_browser_playable, make_browser_preview, normalize_preview_encoding,
+ resolve_final_preview, resolve_preview_codec, wants_compat_preview,
+)
+from ..settings.models import coerce_hdr_mode, parse_automatic_mask
+from ..settings.storage import current_preview_encoding, processing_gpu_settings
+from .models import ConversionOptions
+from .processor import convert_video
+
+PREVIEW_SECONDS = 3.0
+
+def _process_video(
+ input_path: str | None,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool,
+ progress,
+ preview_seconds: float | None,
+ preview_frames: int | None,
+) -> tuple[str | None, str]:
+ if not input_path:
+ raise gr.Error("Choose a video first.")
+ is_preview = preview_seconds is not None or preview_frames is not None
+ ai_gpu_uuid, video_gpu_uuid = processing_gpu_settings()
+ try:
+ preview_mode = current_preview_encoding()
+ except Exception:
+ preview_mode = "Auto"
+ preview_mode = normalize_preview_encoding(preview_mode)
+ if is_preview:
+ effective_codec, effective_container = resolve_preview_codec(
+ codec, container, preview_mode
+ )
+ compat_preview = wants_compat_preview(codec, container, preview_mode)
+ else:
+ effective_codec, effective_container = codec, container
+ compat_preview = False
+ # HDR Mode only for allowed codecs. Compat (forced H.264) previews stay SDR
+ # 8-bit; user-encoded previews preserve the HDR choice.
+ effective_hdr = coerce_hdr_mode(effective_codec, hdr_mode) and (
+ not is_preview or not compat_preview
+ )
+ options = ConversionOptions(
+ ai_gpu_uuid=ai_gpu_uuid,
+ video_gpu_uuid=video_gpu_uuid,
+ nr_preset=nr_preset,
+ nr_style=nr_style,
+ nr_intensity=nr_intensity,
+ 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),
+ dlss_model_preset=dlss_model_preset,
+ upscaling_factor=upscaling_factor,
+ codec=effective_codec,
+ container=effective_container,
+ quality=quality,
+ preserve_hdr=effective_hdr,
+ preview_seconds=preview_seconds,
+ preview_frames=preview_frames,
+ preview_compat=compat_preview,
+ )
+
+ def report(value: float, message: str) -> None:
+ progress(value, desc=message)
+
+ try:
+ result = convert_video(input_path, options, progress=report)
+ except Exception as exc:
+ traceback.print_exc()
+ return None, f"Failed: {exc}"
+ source_name = Path(input_path).name
+ if is_preview:
+ # Truncated previews normally show the encoded file directly. In Auto
+ # mode the pre-check may have selected the user encoding but the actual
+ # file can still probe as unplayable (rare); then derive one H.264 file.
+ output_preview = result.output_path
+ derived_note = ""
+ if preview_mode == "Auto" and not compat_preview:
+ try:
+ playable = is_browser_playable(result.output_path)
+ except Exception:
+ playable = False
+ if not playable:
+ try:
+ output_preview = make_browser_preview(result.output_path)
+ derived_note = " (browser preview transcoded to H.264)"
+ except Exception:
+ output_preview = result.output_path
+ if preview_frames is not None:
+ return output_preview, (
+ f"One-frame preview complete for {source_name} on {result.gpu} "
+ f"in {result.elapsed_seconds:.1f}s. "
+ f"DLSS {result.dlss_mode}: {result.render_width}×{result.render_height} → "
+ f"{result.output_width}×{result.output_height}. Signed feature 18 confirmed."
+ f"{derived_note}"
+ )
+ return output_preview, (
+ f"Preview complete for {source_name}: {result.frames} frames from the first "
+ f"{PREVIEW_SECONDS:g} seconds processed "
+ f"on {result.gpu} in {result.elapsed_seconds:.1f}s. DLSS {result.dlss_mode}: "
+ f"{result.render_width}×{result.render_height} → {result.output_width}×{result.output_height}. "
+ "All frames returned success with signed feature 18 confirmed."
+ f"{derived_note}"
+ )
+ output_preview, used_derivative = resolve_final_preview(
+ result.output_path, preview_mode
+ )
+ status = (
+ f"Complete: {result.frames} frames processed on {result.gpu} in {result.elapsed_seconds:.1f}s. "
+ f"All {result.nr_count_evidence} frames returned success with signed feature 18 confirmed. "
+ f"DLSS {result.dlss_mode}: {result.render_width}×{result.render_height} → "
+ f"{result.output_width}×{result.output_height}."
+ )
+ if used_derivative:
+ status += " Browser preview transcoded to H.264; the original file is unchanged."
+ elif output_preview is None:
+ status += f" {effective_container} output was created successfully, but browser preview is unavailable."
+ return output_preview, status
+
+def normalize_video_paths(paths: list[str] | str | None) -> list[str]:
+ if not paths:
+ return []
+ return [paths] if isinstance(paths, str) else list(paths)
+
+
+def first_video_path(paths: list[str] | str | None) -> str | None:
+ normalized = normalize_video_paths(paths)
+ return normalized[0] if normalized else None
+
+
+def update_video_preview_mode(paths: list[str] | str | None):
+ normalized = normalize_video_paths(paths)
+ single = len(normalized) == 1
+ input_value = normalized[0] if single else None
+ return (
+ gr.update(value=input_value, visible=single),
+ gr.update(value=None, visible=single),
+ gr.update(visible=single),
+ gr.update(visible=single),
+ )
+
+def preview_video(
+ input_path: list[str] | str | None,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool = False,
+ progress=gr.Progress(track_tqdm=False),
+):
+ selected = first_video_path(input_path)
+ return _process_video(
+ selected, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
+ skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
+ codec, container, quality, hdr_mode,
+ progress, PREVIEW_SECONDS, None
+ )
+
+
+def preview_one_frame(
+ input_path: list[str] | str | None,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool = False,
+ progress=gr.Progress(track_tqdm=False),
+):
+ selected = first_video_path(input_path)
+ return _process_video(
+ selected, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
+ skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
+ codec, container, quality, hdr_mode,
+ progress, None, 1
+ )
diff --git a/src/video.py b/src/video/processor.py
similarity index 62%
rename from src/video.py
rename to src/video/processor.py
index a872972..f2e548b 100644
--- a/src/video.py
+++ b/src/video/processor.py
@@ -8,322 +8,31 @@ import shutil
import threading
import time
from contextlib import nullcontext, suppress
-from dataclasses import asdict, dataclass
+from dataclasses import asdict
from fractions import Fraction
from pathlib import Path
-from typing import Callable, Iterable
+from typing import Callable
import av
import cv2
import numpy as np
-from . import ffmpeg
-from .naming import output_filename, require_available_output, validate_rename
-from .runtime import (
- JOBS,
- LOGS,
- OUTPUTS,
- Cancelled,
- DLSSFrameSession,
- active_job,
- resize_fit,
- resolve_runtime_ai_gpu,
- rotate_frame,
- verify_feature_18,
+from ..core import ffmpeg
+from ..core.gpu_selection import resolve_runtime_ai_gpu
+from ..core.jobs import Cancelled, active_job
+from ..core.naming import output_filename, require_available_output, validate_rename
+from ..core.paths import JOBS, LOGS, OUTPUTS
+from ..core.runtime import (
+ DLSSFrameSession, prepare_runtime, resize_fit, rotate_frame, verify_feature_18,
write_failure_report,
)
+from .guides import TemporalGuideGenerator
+from .models import ConversionOptions, ConversionResult, DLSS_MODEL_PRESETS
+from .sizing import resolve_native_settings, resolve_output_size, resolve_upscaling_mode
-
-ENCODING_QUALITIES = ffmpeg.ENCODING_QUALITIES
-AUTO_BITRATE_DIVISORS = ffmpeg.AUTO_BITRATE_DIVISORS
-calculate_auto_bitrate_kbps = ffmpeg.calculate_auto_bitrate_kbps
-probe_video = ffmpeg.probe_video
validate_codec_container = ffmpeg.validate_codec_container
-
-
-@dataclass(slots=True)
-class ConversionOptions:
- ai_gpu_uuid: str = "auto"
- video_gpu_uuid: str = "auto"
- nr_style: str = "Default"
- nr_intensity: float = 1.0
- local_tone_strength: float = 1.0
- local_structure_strength: float = 1.0
- skin_structure_strength: float = -1.0
- upscaling_factor: float = 1.0
- codec: str = "H.264"
- container: str = "MP4"
- quality: str = "Auto (Default)"
- preserve_hdr: bool = False
- warmup_frames: int = 0
- preview_seconds: float | None = None
- preview_frames: int | None = None
- nr_preset: str = "Default"
- automatic_mask: bool = False
- rename_mode: str = "Auto"
- custom_suffix: str = "_DLSS5"
- dlss_model_preset: str = "Default"
-
-
-NR_PRESETS = {
- "Default": 0,
- "Preset #1": 1,
- "Preset #2": 2,
- "Preset #3": 3,
-}
-
-NR_STYLES = {
- "Default": 0,
- "Natural": 1,
- "Cinematic": 2,
-}
-
-DLSS_MODEL_PRESETS = {
- "Default": 0,
- "J": 10,
- "K": 11,
- "L": 12,
- "M": 13,
-}
-
-UPSCALING_MODES = {
- 1.0: {"label": "1× (DLAA / native)", "name": "DLAA", "perf_quality": 5},
- 1.5: {"label": "1.5× (Quality)", "name": "Quality", "perf_quality": 2},
- 1.724: {"label": "1.724× (Balanced)", "name": "Balanced", "perf_quality": 1},
- 2.0: {"label": "2× (Performance)", "name": "Performance", "perf_quality": 0},
- 3.0: {
- "label": "3× (Ultra Performance)",
- "name": "Ultra Performance",
- "perf_quality": 3,
- },
-}
-UPSCALING_CHOICES = tuple(
- (mode["label"], factor) for factor, mode in UPSCALING_MODES.items()
-)
-
-
-def resolve_upscaling_mode(raw_factor: float) -> tuple[float, dict[str, str | int]]:
- try:
- factor = float(raw_factor)
- except (TypeError, ValueError) as exc:
- raise ValueError(
- "Upscaling factor must be one of the supported NVIDIA DLSS modes."
- ) from exc
- if not math.isfinite(factor):
- raise ValueError("Upscaling factor must be one of the supported NVIDIA DLSS modes.")
- for supported, mode in UPSCALING_MODES.items():
- if math.isclose(factor, supported, rel_tol=0.0, abs_tol=1e-9):
- return supported, mode
- choices = ", ".join(f"{factor:g}×" for factor in UPSCALING_MODES)
- raise ValueError(f"Unsupported upscaling factor {factor:g}×. Choose one of: {choices}.")
-
-
-def _nearest_even(value: float) -> int:
- return max(2, int(math.floor(value / 2.0 + 0.5)) * 2)
-
-
-def resolve_output_size(width: int, height: int, factor: float) -> tuple[int, int]:
- factor, _ = resolve_upscaling_mode(factor)
- output_width = _nearest_even(int(width) * factor)
- output_height = _nearest_even(int(height) * factor)
- long_edge = max(output_width, output_height)
- short_edge = min(output_width, output_height)
- if long_edge > 7680 or short_edge > 4320:
- valid = [
- candidate
- for candidate in UPSCALING_MODES
- if max(_nearest_even(width * candidate), _nearest_even(height * candidate)) <= 7680
- and min(_nearest_even(width * candidate), _nearest_even(height * candidate))
- <= 4320
- ]
- recommendation = max(valid) if valid else None
- hint = (
- f" Choose {recommendation:g}× or lower for this video."
- if recommendation is not None
- else " The source already exceeds the supported 8K boundary."
- )
- raise ValueError(
- f"The requested {output_width}×{output_height} output exceeds the supported "
- f"7680×4320 boundary.{hint}"
- )
- return output_width, output_height
-
-
-def resolve_encoding_quality(
- options: ConversionOptions, width: int, height: int, fps: float
-) -> dict:
- return ffmpeg.resolve_encoding_quality(
- options.quality, options.codec, width, height, fps
- )
-
-
-def resolve_native_settings(options: ConversionOptions) -> dict[str, int | float]:
- """Validate public NR controls and translate them to the worker protocol."""
- try:
- preset = NR_PRESETS[options.nr_preset]
- except KeyError as exc:
- choices = ", ".join(NR_PRESETS)
- raise ValueError(
- f"Unknown NR Preset: {options.nr_preset!r}. Choose one of: {choices}."
- ) from exc
-
- try:
- style = NR_STYLES[options.nr_style]
- except KeyError as exc:
- choices = ", ".join(NR_STYLES)
- raise ValueError(
- f"Unknown NR Style: {options.nr_style!r}. Choose one of: {choices}."
- ) from exc
-
- try:
- model_preset = DLSS_MODEL_PRESETS[options.dlss_model_preset]
- except KeyError as exc:
- choices = ", ".join(DLSS_MODEL_PRESETS)
- raise ValueError(
- f"Unknown DLSS Model Preset: {options.dlss_model_preset!r}. "
- f"Choose one of: {choices}."
- ) from exc
-
- controls = {
- "NR Intensity": (options.nr_intensity, 0.0, 2.0),
- "Local Tone Strength": (options.local_tone_strength, 0.0, 2.0),
- "Local Structure Strength": (options.local_structure_strength, 0.0, 2.0),
- "Skin Structure Strength": (options.skin_structure_strength, -1.0, 2.0),
- }
- validated: dict[str, float] = {}
- for label, (raw_value, minimum, maximum) in controls.items():
- try:
- value = float(raw_value)
- except (TypeError, ValueError) as exc:
- raise ValueError(
- f"{label} must be a number between {minimum:g} and {maximum:g}."
- ) from exc
- if not math.isfinite(value) or not minimum <= value <= maximum:
- 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": int(options.automatic_mask),
- "ui_correction": 0,
- "intensity": validated["NR Intensity"],
- "local_tone": validated["Local Tone Strength"],
- "local_structure": validated["Local Structure Strength"],
- "skin_structure": validated["Skin Structure Strength"],
- "dlss_model_preset": model_preset,
- }
-
-
-@dataclass(slots=True)
-class ConversionResult:
- output_path: str
- report_path: str
- frames: int
- nr_count_evidence: int
- elapsed_seconds: float
- gpu: str
- input_width: int
- input_height: int
- render_width: int
- render_height: int
- output_width: int
- output_height: int
- upscaling_factor: float
- dlss_mode: str
- dlss_model_preset: str = "Default"
- applied_dlss_model_preset: int = 0
-
-
-@dataclass(slots=True)
-class VideoConversionSuccess:
- index: int
- input_path: str
- result: ConversionResult
-
-
-@dataclass(slots=True)
-class VideoConversionFailure:
- index: int
- input_path: str
- error: str
- cancelled: bool = False
-
-
-@dataclass(slots=True)
-class VideoBatchResult:
- successes: list[VideoConversionSuccess]
- failures: list[VideoConversionFailure]
- cancelled: bool
- manifest_path: str
-
-
_BATCH_CONTEXT = threading.local()
-
-@dataclass(slots=True)
-class GuideFrame:
- motion: np.ndarray
- reset: bool
- scene_score: float
-
-
-class TemporalGuideGenerator:
- """Estimate the guide buffers an encoded video does not contain."""
-
- def __init__(self, width: int, height: int, flow_width: int = 640) -> None:
- self.width = width
- self.height = height
- scale = min(1.0, flow_width / width)
- self.flow_width = max(64, int(round(width * scale / 2) * 2))
- self.flow_height = max(64, int(round(height * scale / 2) * 2))
- self.previous_gray: np.ndarray | None = None
- self.zero_motion = np.zeros((height, width, 2), dtype=np.float16)
- self.dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
- self.dis.setUseSpatialPropagation(True)
- self.dis.setFinestScale(1)
-
- def _small_gray(self, rgba: np.ndarray) -> np.ndarray:
- gray = cv2.cvtColor(rgba, cv2.COLOR_RGBA2GRAY)
- return cv2.resize(
- gray,
- (self.flow_width, self.flow_height),
- interpolation=cv2.INTER_AREA,
- )
-
- def process(self, rgba: np.ndarray) -> GuideFrame:
- current = self._small_gray(rgba)
- if self.previous_gray is None:
- motion = self.zero_motion
- reset = True
- scene_score = 1.0
- else:
- scene_score = float(np.mean(cv2.absdiff(current, self.previous_gray))) / 255.0
- reset = scene_score > 0.24
- if reset:
- motion = self.zero_motion
- else:
- motion = self.dis.calc(current, self.previous_gray, None)
- motion = cv2.resize(
- motion,
- (self.width, self.height),
- interpolation=cv2.INTER_LINEAR,
- )
- motion[..., 0] *= self.width / self.flow_width
- motion[..., 1] *= self.height / self.flow_height
- motion = np.ascontiguousarray(motion.astype(np.float16))
- self.previous_gray = current
- return GuideFrame(
- motion=motion,
- reset=reset,
- scene_score=scene_score,
- )
-
-
def _validate_preview_options(
options: ConversionOptions,
) -> tuple[float | None, int | None]:
@@ -356,8 +65,6 @@ def convert_video(
options: ConversionOptions | None = None,
progress: Callable[[float, str], None] | None = None,
) -> ConversionResult:
- from .prepare import prepare_runtime
-
options = options or ConversionOptions()
source = Path(input_path).resolve()
if not source.is_file():
@@ -366,10 +73,16 @@ def convert_video(
validate_rename(options.rename_mode, options.custom_suffix)
preview_seconds, preview_frames = _validate_preview_options(options)
is_preview = preview_seconds is not None or preview_frames is not None
- if options.preserve_hdr:
- raise RuntimeError(
- "HDR preservation is disabled in this build because the verified DLSSNR path is "
- "RGBA8. HDR input is converted to SDR instead of being mislabeled as HDR."
+ # Compat previews use the forced H.264 SDR 8-bit path; user-encoded previews
+ # (Preview Encoding Auto-playable / Disabled) preserve the HDR choice.
+ compat_preview = is_preview and bool(getattr(options, "preview_compat", True))
+ hdr_requested = bool(options.preserve_hdr)
+ if compat_preview:
+ hdr_requested = False
+ if hdr_requested and not ffmpeg.hdr_mode_supported(options.codec):
+ raise ValueError(
+ f"HDR Mode is only available for H.265, H.265 (NVIDIA NVENC), AV1, AV1 (NVIDIA NVENC) and ProRes Proxy; "
+ f"current codec is {options.codec!r}."
)
prepared_runtime = getattr(_BATCH_CONTEXT, "prepared_runtime", None)
if prepared_runtime is None:
@@ -380,6 +93,27 @@ def convert_video(
with job_context as controller:
assert controller is not None
started = time.perf_counter()
+
+ def _report_progress(value: float, desc: str) -> None:
+ if progress is None:
+ return
+ try:
+ v = float(value)
+ v = 0.0 if v < 0 else (1.0 if v > 1 else v)
+ elapsed = time.perf_counter() - started
+ if 0.01 < v < 0.99 and elapsed > 0.5:
+ eta = elapsed * (1 - v) / max(v, 1e-6)
+ desc = f"{desc} - Time Remaining: {eta:.1f}s"
+ else:
+ v = float(value) if isinstance(value, (int, float)) else v
+ # Use positional `desc` so it works for both gr.Progress(desc=) and report_item(message)
+ progress(v, desc)
+ except Exception:
+ try:
+ progress(value, desc)
+ except Exception:
+ pass
+
timings: dict[str, float] = {}
job_dir: Path | None = None
output: Path | None = None
@@ -428,10 +162,20 @@ def convert_video(
video_gpu = ffmpeg.resolve_video_gpu(
prepared_runtime.gpus,
options.video_gpu_uuid,
- "H.264" if is_preview else options.codec,
+ "H.264" if compat_preview else options.codec,
output_width,
output_height,
)
+ # HDR metadata to copy – 10-bit path when HDR Mode is on
+ hdr_metadata = None
+ effective_hdr = hdr_requested and (not is_preview or not compat_preview)
+ if effective_hdr:
+ hdr_metadata = {
+ "color_space": metadata.get("color_space", "unknown"),
+ "color_primaries": metadata.get("color_primaries", "unknown"),
+ "color_transfer": metadata.get("color_transfer", "unknown"),
+ "hdr": bool(metadata.get("hdr", False)),
+ }
OUTPUTS.mkdir(exist_ok=True)
LOGS.mkdir(exist_ok=True)
JOBS.mkdir(exist_ok=True)
@@ -462,8 +206,7 @@ def convert_video(
require_available_output(output)
temp_video = job_dir / "processed-video.mkv"
native = resolve_native_settings(options)
- if progress:
- progress(0.01, f"Starting feature 18 on {gpu['display_name']}")
+ _report_progress(0.01, f"Starting feature 18 on {gpu['display_name']}")
encoder_setup: list[tuple] = []
encoding_stage_started = time.perf_counter()
@@ -482,6 +225,8 @@ def convert_video(
float(metadata["fps"]),
None if video_gpu is None else int(video_gpu["cuda_ordinal"]),
video_gpu is not None,
+ hdr_mode=effective_hdr,
+ hdr_metadata=hdr_metadata,
)
)
except BaseException as exc:
@@ -528,12 +273,11 @@ def convert_video(
minimum_height = session.minimum_height
maximum_width = session.maximum_width
maximum_height = session.maximum_height
- if progress:
- progress(
- 0.03,
- f"DLSS {mode['name']}: {render_width}×{render_height} → "
- f"{output_width}×{output_height}",
- )
+ _report_progress(
+ 0.03,
+ f"DLSS {mode['name']}: {render_width}×{render_height} → "
+ f"{output_width}×{output_height}",
+ )
(
encoder,
@@ -691,8 +435,8 @@ def convert_video(
raise Cancelled("Render stopped by user.")
delivered += 1
now = time.perf_counter()
- if progress and (delivered == frame_count or now - last_progress_update >= 0.1):
- progress(
+ if delivered == frame_count or now - last_progress_update >= 0.1:
+ _report_progress(
0.04 + 0.84 * delivered / frame_count,
f"DLSS 5 frame {delivered}/{frame_count}",
)
@@ -737,8 +481,7 @@ def convert_video(
nr_upscaling_active = bool(feature_evidence["nr_upscaling_active"])
nr_native_fallback = bool(feature_evidence["nr_native_fallback"])
carrier_create_result = str(feature_evidence["carrier_create_result"])
- if progress:
- progress(0.91, "Muxing original audio and metadata")
+ _report_progress(0.91, "Muxing original audio and metadata")
mux_started = time.perf_counter()
ffmpeg.final_mux(temp_video, source, output, options.container, controller)
timings["final_mux_seconds"] = time.perf_counter() - mux_started
@@ -823,15 +566,12 @@ def convert_video(
"carrier_create_result": carrier_create_result,
"successful_neural_rendering_frames": nr_count,
"addon_release": runtime_bundle["addon"]["release"],
- "addon_sha256": runtime_bundle["addon"]["sha256"].lower(),
- "model_sha256": runtime_bundle["neural_runtime"]["sha256"].lower(),
- "worker_sha256": runtime_bundle["worker"]["sha256"].lower(),
"loaded_module_inventory": [
- "nvngx.dll (standalone worker image)",
- "dxgi.dll (ReShade carrier)",
- "renodx-dlss5.addon64",
- "nvngx_dlss.dll",
- "nvngx_dlssnr.dll",
+ "host/nvngx.dll (standalone worker image)",
+ "host/dxgi.dll (ReShade carrier)",
+ "host/renodx-dlss5.addon64",
+ "dlss/nvngx_dlss.dll",
+ "host/nvngx_dlssnr.dll",
"system D3D12/DXGI/NGX core",
],
"native_settings": native,
@@ -845,8 +585,7 @@ def convert_video(
}
report_path = LOGS / f"{output.name}.report.json"
report_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
- if progress:
- progress(1.0, "Complete — feature 18 confirmed")
+ _report_progress(1.0, "Complete — feature 18 confirmed")
return ConversionResult(
str(output),
str(report_path),
@@ -910,122 +649,3 @@ def convert_video(
pipeline_stop.set()
if job_dir and job_dir.exists():
shutil.rmtree(job_dir, ignore_errors=True)
-
-
-def _write_video_batch_manifest(
- stamp: str,
- options: ConversionOptions,
- successes: list[VideoConversionSuccess],
- failures: list[VideoConversionFailure],
- cancelled: bool,
-) -> str:
- LOGS.mkdir(exist_ok=True)
- manifest = {
- "status": "cancelled" if cancelled else ("partial" if failures else "success"),
- "options": asdict(options),
- "successes": [asdict(item) for item in successes],
- "failures": [asdict(item) for item in failures],
- }
- manifest_path = LOGS / f"DLSS5_VIDEO_BATCH_{stamp}.manifest.json"
- manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
- return str(manifest_path)
-
-
-def convert_videos(
- input_paths: Iterable[str | os.PathLike[str]],
- options: ConversionOptions | None = None,
- progress: Callable[[float, str], None] | None = None,
-) -> VideoBatchResult:
- """Convert videos sequentially while holding one cancellable GPU batch slot."""
- from .prepare import prepare_runtime
-
- options = options or ConversionOptions()
- paths = [Path(path).resolve() for path in input_paths]
- if not paths:
- raise ValueError("Choose at least one video.")
-
- prepared_runtime = prepare_runtime()
- LOGS.mkdir(exist_ok=True)
- stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000:06d}"
- successes: list[VideoConversionSuccess] = []
- failures: list[VideoConversionFailure] = []
- cancelled = False
- total = len(paths)
-
- with active_job() as controller:
- if getattr(_BATCH_CONTEXT, "controller", None) is not None:
- raise RuntimeError("A video batch is already active on this worker thread.")
- _BATCH_CONTEXT.controller = controller
- _BATCH_CONTEXT.prepared_runtime = prepared_runtime
- try:
- for index, path in enumerate(paths):
- position = index + 1
- prefix = f"[{position}/{total}] {path.name}"
- if controller.cancel.is_set():
- cancelled = True
- failures.extend(
- VideoConversionFailure(
- queued_index,
- str(queued),
- "Cancelled before rendering.",
- cancelled=True,
- )
- for queued_index, queued in enumerate(paths[index:], start=index)
- )
- break
-
- def report_item(
- value: float,
- message: str,
- *,
- item_index: int = index,
- item_prefix: str = prefix,
- ) -> None:
- bounded = min(1.0, max(0.0, float(value)))
- overall = (item_index + bounded) / total
- if progress:
- progress(overall, f"{item_prefix} — {message}")
-
- if progress:
- progress(index / total, f"{prefix} — starting")
- try:
- result = convert_video(path, options, progress=report_item)
- except Cancelled:
- cancelled = True
- failures.append(
- VideoConversionFailure(
- index,
- str(path),
- "Cancelled during rendering.",
- cancelled=True,
- )
- )
- failures.extend(
- VideoConversionFailure(
- queued_index,
- str(queued),
- "Cancelled before rendering.",
- cancelled=True,
- )
- for queued_index, queued in enumerate(paths[position:], start=position)
- )
- break
- except Exception as exc:
- failures.append(VideoConversionFailure(index, str(path), str(exc)))
- if progress:
- progress(position / total, f"{prefix} — failed")
- continue
-
- successes.append(VideoConversionSuccess(index, str(path), result))
- if progress:
- progress(position / total, f"{prefix} — complete")
- finally:
- del _BATCH_CONTEXT.controller
- del _BATCH_CONTEXT.prepared_runtime
-
- manifest_path = _write_video_batch_manifest(
- stamp, options, successes, failures, cancelled
- )
- if progress:
- progress(1.0, "Cancelled" if cancelled else "Complete")
- return VideoBatchResult(successes, failures, cancelled, manifest_path)
diff --git a/src/video/reports.py b/src/video/reports.py
new file mode 100644
index 0000000..ddb2d89
--- /dev/null
+++ b/src/video/reports.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+import json
+from dataclasses import asdict
+
+from ..core.paths import LOGS
+from .models import ConversionOptions, VideoConversionFailure, VideoConversionSuccess
+
+def _write_video_batch_manifest(
+ stamp: str,
+ options: ConversionOptions,
+ successes: list[VideoConversionSuccess],
+ failures: list[VideoConversionFailure],
+ cancelled: bool,
+) -> str:
+ LOGS.mkdir(exist_ok=True)
+ manifest = {
+ "status": "cancelled" if cancelled else ("partial" if failures else "success"),
+ "options": asdict(options),
+ "successes": [asdict(item) for item in successes],
+ "failures": [asdict(item) for item in failures],
+ }
+ manifest_path = LOGS / f"DLSS5_VIDEO_BATCH_{stamp}.manifest.json"
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+ return str(manifest_path)
diff --git a/src/video/sizing.py b/src/video/sizing.py
new file mode 100644
index 0000000..adb88a0
--- /dev/null
+++ b/src/video/sizing.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from ..core import ffmpeg
+from ..core.runtime import (
+ DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES,
+ resolve_native_settings, resolve_output_size, resolve_upscaling_mode,
+)
+from .models import ConversionOptions
+
+UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
+ENCODING_QUALITIES = ffmpeg.ENCODING_QUALITIES
+AUTO_BITRATE_DIVISORS = ffmpeg.AUTO_BITRATE_DIVISORS
+calculate_auto_bitrate_kbps = ffmpeg.calculate_auto_bitrate_kbps
+probe_video = ffmpeg.probe_video
+validate_codec_container = ffmpeg.validate_codec_container
+
+
+def resolve_encoding_quality(
+ options: ConversionOptions, width: int, height: int, fps: float
+) -> dict:
+ return ffmpeg.resolve_encoding_quality(
+ options.quality, options.codec, width, height, fps
+ )
diff --git a/src/video/ui.py b/src/video/ui.py
new file mode 100644
index 0000000..ffc0659
--- /dev/null
+++ b/src/video/ui.py
@@ -0,0 +1,365 @@
+from __future__ import annotations
+
+import traceback
+from dataclasses import dataclass
+from pathlib import Path
+
+import gradio as gr
+
+from ..core.ffmpeg import hdr_mode_supported
+from ..core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview
+from ..core.jobs import cancel_active_job
+from ..core.naming import RENAME_MODES
+from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES
+from ..settings.models import (
+ AUTOMATIC_MASK_CHOICES, CODEC_CHOICES, CONTAINER_CHOICES, QUALITY_CHOICES, UISettings,
+ automatic_mask_choice, coerce_hdr_mode, parse_automatic_mask,
+)
+from ..settings.storage import current_preview_encoding, processing_gpu_settings
+from .batch import convert_videos
+from .models import ConversionOptions
+from .preview import (
+ _process_video, normalize_video_paths, preview_one_frame, preview_video, update_video_preview_mode,
+)
+
+
+def hdr_mode_update(codec: str):
+ allowed = hdr_mode_supported(codec)
+ if not allowed:
+ return gr.update(value=False, interactive=False)
+ return gr.update(interactive=True)
+
+
+def rename_suffix_update(mode: str):
+ return gr.update(interactive=mode == "Custom")
+
+
+UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
+
+
+def build_neural_controls(settings: UISettings):
+ nr_preset = gr.Dropdown(
+ list(NR_PRESETS), value=settings.nr_preset, label="NR Preset",
+ info="Experimental content-dependent neural-rendering model hint. Default is recommended."
+ )
+ nr_style = gr.Radio(
+ list(NR_STYLES), value=settings.nr_style, label="NR Style",
+ info="Selects the native neural-rendering style."
+ )
+ upscaling_factor = gr.Dropdown(
+ choices=list(UPSCALING_CHOICES), value=settings.upscaling_factor,
+ label="Upscaling factor", info="Uses NVIDIA's fixed DLSS modes. DLAA keeps source resolution."
+ )
+ with gr.Row():
+ nr_intensity = gr.Slider(
+ 0.0, 2.0, value=settings.nr_intensity, step=0.05, precision=2,
+ label="NR Intensity", info="Overall neural-rendering strength.", buttons=["reset"]
+ )
+ local_tone_strength = gr.Slider(
+ 0.0, 2.0, value=settings.local_tone_strength, step=0.05, precision=2,
+ label="Local Tone Strength", info="Local tone and contrast enhancement.", buttons=["reset"]
+ )
+ with gr.Row():
+ local_structure_strength = gr.Slider(
+ 0.0, 2.0, value=settings.local_structure_strength, step=0.05, precision=2,
+ label="Local Structure Strength", info="Local detail and texture structure.", buttons=["reset"]
+ )
+ skin_structure_strength = gr.Slider(
+ -1.0, 2.0, value=settings.skin_structure_strength, step=0.05, precision=2,
+ 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, automatic_mask
+ ]
+
+
+def build_dlss_model_control(settings: UISettings):
+ return gr.Dropdown(
+ choices=list(DLSS_MODEL_PRESETS),
+ value=settings.dlss_model_preset,
+ label="DLSS Model Preset",
+ info=(
+ "Default lets NVIDIA select its normal mode-specific presets. "
+ "J, K, L, or M forces that model preset for every DLSS scaling mode."
+ ),
+ )
+
+def render_video(
+ input_path: str,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool = False,
+ progress=gr.Progress(track_tqdm=False),
+):
+ return _process_video(
+ input_path, nr_preset, nr_style, nr_intensity, local_tone_strength, local_structure_strength,
+ skin_structure_strength, upscaling_factor, automatic_mask, dlss_model_preset,
+ codec, container, quality, hdr_mode,
+ progress, None, None
+ )
+
+def render_video_batch(
+ input_paths: list[str] | str | None,
+ nr_preset: str,
+ nr_style: str,
+ nr_intensity: float,
+ local_tone_strength: float,
+ local_structure_strength: float,
+ skin_structure_strength: float,
+ upscaling_factor: float,
+ automatic_mask: str,
+ dlss_model_preset: str,
+ codec: str,
+ container: str,
+ quality: str,
+ hdr_mode: bool,
+ rename_mode: str,
+ custom_suffix: str,
+ progress=gr.Progress(track_tqdm=False),
+) -> tuple[object, list[str], list[list[str]], str]:
+ paths = normalize_video_paths(input_paths)
+ if not paths:
+ raise gr.Error("Choose at least one video first.")
+ effective_hdr = coerce_hdr_mode(codec, hdr_mode)
+ options = ConversionOptions(
+ ai_gpu_uuid=processing_gpu_settings()[0],
+ video_gpu_uuid=processing_gpu_settings()[1],
+ nr_preset=nr_preset,
+ nr_style=nr_style,
+ nr_intensity=nr_intensity,
+ 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),
+ dlss_model_preset=dlss_model_preset,
+ upscaling_factor=upscaling_factor,
+ codec=codec,
+ container=container,
+ quality=quality,
+ preserve_hdr=effective_hdr,
+ rename_mode=rename_mode,
+ custom_suffix=custom_suffix,
+ )
+
+ def report(value: float, message: str) -> None:
+ progress(value, desc=message)
+
+ try:
+ result = convert_videos(paths, options, progress=report)
+ except Exception as exc:
+ traceback.print_exc()
+ return gr.update(value=None, visible=len(paths) == 1), [], [], f"Failed: {exc}"
+
+ ordered_rows: list[tuple[int, list[str]]] = []
+ for item in result.successes:
+ conversion = item.result
+ details = (
+ f"{conversion.frames} frames in {conversion.elapsed_seconds:.1f}s; "
+ f"DLSS {conversion.dlss_mode}: "
+ f"{conversion.render_width}×{conversion.render_height} → "
+ f"{conversion.output_width}×{conversion.output_height}; "
+ f"report: {conversion.report_path}"
+ )
+ ordered_rows.append(
+ (
+ item.index,
+ [
+ Path(item.input_path).name,
+ "Complete",
+ Path(conversion.output_path).name,
+ details,
+ ],
+ )
+ )
+ for item in result.failures:
+ state = "Skipped" if item.error == "Cancelled before rendering." else (
+ "Cancelled" if item.cancelled else "Failed"
+ )
+ ordered_rows.append(
+ (item.index, [Path(item.input_path).name, state, "", item.error])
+ )
+ rows = [row for _index, row in sorted(ordered_rows, key=lambda entry: entry[0])]
+ files = [item.result.output_path for item in result.successes]
+ try:
+ preview_mode = normalize_preview_encoding(current_preview_encoding())
+ except Exception:
+ preview_mode = "Auto"
+ output_preview = None
+ used_derivative = False
+ if len(paths) == 1 and result.successes:
+ candidate = result.successes[0].result.output_path
+ output_preview, used_derivative = resolve_final_preview(
+ candidate, preview_mode
+ )
+ failed_count = sum(not item.cancelled for item in result.failures)
+ cancelled_count = sum(
+ item.cancelled and item.error != "Cancelled before rendering."
+ for item in result.failures
+ )
+ skipped_count = sum(
+ item.error == "Cancelled before rendering." for item in result.failures
+ )
+ state = "Cancelled" if result.cancelled else "Complete"
+ status = (
+ f"{state}: {len(result.successes)} completed, {failed_count} failed, "
+ f"{cancelled_count} cancelled, {skipped_count} skipped. "
+ f"Batch manifest: {result.manifest_path}"
+ )
+ if result.failures:
+ status += f"\nFirst error: {result.failures[0].error}"
+ if used_derivative:
+ status += "\nBrowser preview transcoded to H.264; the original file is unchanged."
+ return gr.update(value=output_preview, visible=len(paths) == 1), files, rows, status
+
+@dataclass(slots=True)
+class VideoTab:
+ sources: object
+ input_preview: object
+ neural: list[object]
+ model_preset: object
+ quality: object
+ codec: object
+ container: object
+ rename_mode: object
+ custom_suffix: object
+ hdr_mode: object
+ preview_frame: object
+ preview: object
+ render: object
+ stop: object
+ reset: object
+ output_video: object
+ output_files: object
+ status: object
+ results: object
+
+ @property
+ def render_inputs(self) -> list[object]:
+ return [
+ self.sources, *self.neural, self.model_preset, self.codec, self.container,
+ self.quality, self.hdr_mode, self.rename_mode, self.custom_suffix,
+ ]
+
+ @property
+ def preview_inputs(self) -> list[object]:
+ return [
+ self.sources, *self.neural, self.model_preset, self.codec, self.container,
+ self.quality, self.hdr_mode,
+ ]
+
+ @property
+ def settings_inputs(self) -> list[object]:
+ return [
+ *self.neural, self.model_preset, self.codec, self.container, self.quality,
+ self.hdr_mode, self.rename_mode, self.custom_suffix,
+ ]
+
+
+def build_video_tab(settings: UISettings) -> VideoTab:
+ with gr.Row():
+ with gr.Column(scale=3):
+ sources = gr.File(
+ label="Input video(s)", file_count="multiple", file_types=["video"],
+ type="filepath", allow_reordering=True, elem_id="video-upload-list",
+ )
+ input_preview = gr.Video(label="Input video preview", interactive=False, visible=False)
+ with gr.Accordion("DLSS 5 Neural Rendering Settings", open=True):
+ neural = build_neural_controls(settings)
+ with gr.Accordion("DLSS 5 Settings", open=True):
+ model_preset = build_dlss_model_control(settings)
+ quality = gr.Radio(
+ QUALITY_CHOICES, value=settings.quality, label="Encoding quality",
+ info="Auto uses output resolution, FPS, and codec. Good = Auto×2, Best = Auto×4, Max = CQ 0.",
+ )
+ with gr.Row():
+ codec = gr.Dropdown(
+ CODEC_CHOICES, value=settings.codec, label="Video codec",
+ info="Plain = CPU (libx264 / libx265 / libsvtav1). Suffixed (NVIDIA NVENC) = GPU. ProRes Proxy uses 10-bit 4:2:2 and requires MOV or MKV.",
+ )
+ container = gr.Dropdown(CONTAINER_CHOICES, value=settings.container, label="Container")
+ with gr.Row():
+ rename_mode = gr.Radio(
+ RENAME_MODES, value=settings.video_rename_mode, label="Rename",
+ info="Auto adds the current DLSS5 timestamp; Copy keeps the original base name; Custom appends your suffix.",
+ )
+ custom_suffix = gr.Textbox(
+ value=settings.video_custom_suffix, label="Custom suffix", placeholder="_DLSS5",
+ interactive=settings.video_rename_mode == "Custom",
+ )
+ hdr_mode = gr.Checkbox(
+ value=settings.hdr_mode and hdr_mode_supported(settings.codec),
+ label="HDR Mode",
+ info="When on: 10-bit output, copies input colorspace; keeps HDR if input is HDR. Only for H.265 / AV1 / ProRes.",
+ interactive=hdr_mode_supported(settings.codec),
+ )
+ with gr.Row():
+ preview_frame = gr.Button("Preview 1 frame", visible=False)
+ preview = gr.Button("Preview 3 sec", visible=False)
+ render = gr.Button("Render video(s)", variant="primary")
+ stop = gr.Button("Stop", variant="stop")
+ reset = gr.Button("Reset settings")
+ with gr.Column(scale=3):
+ output_video = gr.Video(label="Output video", interactive=False, visible=False)
+ output_files = gr.File(
+ label="Rendered video files", file_count="multiple", interactive=False,
+ elem_id="video-output-list",
+ )
+ status = gr.Textbox(label="Status", interactive=False)
+ results = gr.Dataframe(
+ headers=["Input", "Result", "Output", "Details"],
+ datatype=["str", "str", "str", "str"], interactive=False,
+ label="Batch results", wrap=True,
+ )
+ tab = VideoTab(
+ sources, input_preview, neural, model_preset, quality, codec, container, rename_mode,
+ custom_suffix, hdr_mode, preview_frame, preview, render, stop, reset, output_video,
+ output_files, status, results
+ )
+ bind_video_events(tab)
+ return tab
+
+
+def bind_video_events(tab: VideoTab) -> None:
+ tab.sources.change(
+ update_video_preview_mode, inputs=tab.sources,
+ outputs=[tab.input_preview, tab.output_video, tab.preview_frame, tab.preview],
+ queue=False, show_progress="hidden",
+ )
+ tab.rename_mode.change(rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False)
+ tab.codec.change(hdr_mode_update, inputs=tab.codec, outputs=tab.hdr_mode, queue=False)
+ tab.render.click(
+ render_video_batch, inputs=tab.render_inputs,
+ outputs=[tab.output_video, tab.output_files, tab.results, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_video,
+ )
+ tab.preview.click(
+ preview_video, inputs=tab.preview_inputs, outputs=[tab.output_video, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_video,
+ )
+ tab.preview_frame.click(
+ preview_one_frame, inputs=tab.preview_inputs, outputs=[tab.output_video, tab.status],
+ concurrency_limit=1, show_progress="full", show_progress_on=tab.output_video,
+ )
+ tab.stop.click(cancel_active_job, outputs=tab.status, queue=False)
+
diff --git a/start.bat b/start.bat
index 441372e..ad56b73 100644
--- a/start.bat
+++ b/start.bat
@@ -1,8 +1,12 @@
@echo off
setlocal
cd /d "%~dp0"
+chcp 65001 >nul
+title DLSS 5 Visual Enhancer
+cls
set "PYTHONNOUSERSITE=1"
set "PYTHONDONTWRITEBYTECODE=1"
+set "PYTHONIOENCODING=utf-8"
set "GRADIO_ANALYTICS_ENABLED=False"
"%~dp0bin\python-3.13.15-embed-amd64\python.exe" "%~dp0app.py"
if errorlevel 1 pause