DLSS 5 Neural Rendering for Images & Video with Frame Generation, RTX Video Super Resolution, HDR, and Color Grading
TypeScript ai-upscalingdlssdlss-5dlss5dlssgframe-generationframe-interpolationimage-enhancementimage-upscalingneural-renderingnvidianvidia-dlss-5nvidia-rtxrtx-videortx-video-super-resolutionvideo-enhancementvideo-upscaling
Add files via upload
Merserkf9064948cca3
diff --git a/app.py b/app.pyindex b8e0228..15d091a 100644--- a/app.py+++ b/app.py@@ -1,230 +1,313 @@-from __future__ import annotations--from pathlib import Path--# 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-- _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--from src.core.cache_cleanup import (- CACHE_MAX_AGE_SECONDS,- CACHE_SWEEP_INTERVAL_SECONDS,- cleanup_old_caches,-)-from src.core.dlss_architecture import apply_dlss_architecture, init_dlssnr_runtime+from __future__ import annotations++from pathlib import Path++# 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++ _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++from src.about.ui import build_about_tab+from src.core.cache_cleanup import (+ CACHE_MAX_AGE_SECONDS,+ CACHE_SWEEP_INTERVAL_SECONDS,+ cleanup_old_caches,+)from src.core.paths import LIVE_DIR, 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.live.ui import build_live_tab-from src.settings.ui import bind_settings_events, build_settings_tab, initialize_settings-from src.video.ui import build_video_tab--APP_CSS = r"""-/* Keep the header links identical even when one URL has been visited. */-#app-title a,-#app-title a:visited,-#app-title a:hover,-#app-title a:active {- color: #00bfff !important;- opacity: 1 !important;+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.live.ui import build_live_tab+from src.neural_rendering.image.decoder import initialize_image_runtime+from src.neural_rendering.ui import build_neural_rendering_tab+from src.settings.ui import bind_settings_events, build_settings_tab, initialize_settings+from src.upscale.ui import build_upscale_tab++APP_CSS = r"""+/* Center the About contents in the space below the app title and tab bar. */+#about-content {+ display: grid;+ place-items: center;+ min-height: calc(100dvh - 12rem);+ padding: 2rem 1rem;+ box-sizing: border-box;+ text-align: center;+}++#about-content .about-details {+ max-width: 36rem;+}++#about-content h2 {+ margin: 0;+ font-size: 1.5rem;+ font-weight: 600;+ line-height: 1.35;+}++#about-content .about-version {+ margin: 0.6rem 0 0;+}++#about-content .about-links {+ margin-top: 2rem;+}++#about-content .about-links p {+ margin: 0 0 1.25rem;+}++#about-content .about-description {+ display: block;+ margin-top: 0.4rem;+ color: var(--body-text-color-subdued);+ font-size: 0.875rem;+}++#about-content .about-copyright {+ margin: 2rem 0 0;+}++/* Keep project links the same color after visiting them. */+#about-content a,+#about-content a:visited,+#about-content a:hover,+#about-content a:active {+ color: #00bfff !important;+ opacity: 1 !important;+ font-weight: 600;+}++#about-content a:hover {+ text-decoration: underline;+}++/* Match every image/video drop zone to the 16:9 input preview surface. */+.media-upload-surface {+ aspect-ratio: 16 / 9;+ height: auto !important;+ min-height: 0 !important;}-/* Keep large upload batches compact: roughly three file rows, then scroll. */+/* Keep uploaded batches inside that surface and scroll when needed. */#image-upload-list .file-preview-holder,-#image-output-list .file-preview-holder,#video-upload-list .file-preview-holder,-#video-output-list .file-preview-holder,-#frame-interpolation-upload-list .file-preview-holder,-#frame-interpolation-output-list .file-preview-holder {- max-height: 210px !important;+#upscale-image-upload-list .file-preview-holder,+#upscale-upload-list .file-preview-holder,+#frame-interpolation-upload-list .file-preview-holder {+ max-height: 100% !important;overflow-x: hidden !important;overflow-y: auto !important;- overscroll-behavior: contain;- scrollbar-gutter: stable;-}-+ overscroll-behavior: contain;+ scrollbar-gutter: stable;+}+#image-upload-list .file-preview,-#image-output-list .file-preview,#video-upload-list .file-preview,-#video-output-list .file-preview,-#frame-interpolation-upload-list .file-preview,-#frame-interpolation-output-list .file-preview {+#upscale-image-upload-list .file-preview,+#upscale-upload-list .file-preview,+#frame-interpolation-upload-list .file-preview {max-height: none !important;}--/* A single input or output preview is a full 16:9 viewport without scrolling. */++/* A single input or output preview is a full 16:9 viewport without scrolling. */#image-input-preview:has(.gallery-item:only-child),-#image-output-preview:has(.gallery-item:only-child) {- aspect-ratio: 16 / 9;- height: auto !important;- min-height: 0 !important;-}--#image-input-preview:has(.gallery-item:only-child) .gallery-container,-#image-input-preview:has(.gallery-item:only-child) .grid-wrap,-#image-input-preview:has(.gallery-item:only-child) .grid-container,-#image-input-preview:has(.gallery-item:only-child) .gallery-item,-#image-input-preview:has(.gallery-item:only-child) .thumbnail-lg,-#image-output-preview:has(.gallery-item:only-child) .gallery-container,-#image-output-preview:has(.gallery-item:only-child) .grid-wrap,+#image-output-preview:has(.gallery-item:only-child),+#upscale-image-input-preview:has(.gallery-item:only-child),+#upscale-image-output-preview:has(.gallery-item:only-child) {+ aspect-ratio: 16 / 9;+ height: auto !important;+ min-height: 0 !important;+}++#image-input-preview:has(.gallery-item:only-child) .gallery-container,+#image-input-preview:has(.gallery-item:only-child) .grid-wrap,+#image-input-preview:has(.gallery-item:only-child) .grid-container,+#image-input-preview:has(.gallery-item:only-child) .gallery-item,+#image-input-preview:has(.gallery-item:only-child) .thumbnail-lg,+#image-output-preview:has(.gallery-item:only-child) .gallery-container,+#image-output-preview:has(.gallery-item:only-child) .grid-wrap,#image-output-preview:has(.gallery-item:only-child) .grid-container,#image-output-preview:has(.gallery-item:only-child) .gallery-item,-#image-output-preview:has(.gallery-item:only-child) .thumbnail-lg {- box-sizing: border-box;- height: 100% !important;- min-height: 0 !important;-}-+#image-output-preview:has(.gallery-item:only-child) .thumbnail-lg,+#upscale-image-input-preview:has(.gallery-item:only-child) .gallery-container,+#upscale-image-input-preview:has(.gallery-item:only-child) .grid-wrap,+#upscale-image-input-preview:has(.gallery-item:only-child) .grid-container,+#upscale-image-input-preview:has(.gallery-item:only-child) .gallery-item,+#upscale-image-input-preview:has(.gallery-item:only-child) .thumbnail-lg,+#upscale-image-output-preview:has(.gallery-item:only-child) .gallery-container,+#upscale-image-output-preview:has(.gallery-item:only-child) .grid-wrap,+#upscale-image-output-preview:has(.gallery-item:only-child) .grid-container,+#upscale-image-output-preview:has(.gallery-item:only-child) .gallery-item,+#upscale-image-output-preview:has(.gallery-item:only-child) .thumbnail-lg {+ box-sizing: border-box;+ height: 100% !important;+ min-height: 0 !important;+}+#image-input-preview:has(.gallery-item:only-child) .grid-wrap,-#image-output-preview:has(.gallery-item:only-child) .grid-wrap {- overflow: hidden !important;-}-+#image-output-preview:has(.gallery-item:only-child) .grid-wrap,+#upscale-image-input-preview:has(.gallery-item:only-child) .grid-wrap,+#upscale-image-output-preview:has(.gallery-item:only-child) .grid-wrap {+ overflow: hidden !important;+}+#image-input-preview:has(.gallery-item:only-child) .grid-container,-#image-output-preview:has(.gallery-item:only-child) .grid-container {- grid-template-rows: minmax(0, 1fr) !important;- grid-auto-rows: minmax(0, 1fr) !important;-}-+#image-output-preview:has(.gallery-item:only-child) .grid-container,+#upscale-image-input-preview:has(.gallery-item:only-child) .grid-container,+#upscale-image-output-preview:has(.gallery-item:only-child) .grid-container {+ grid-template-rows: minmax(0, 1fr) !important;+ grid-auto-rows: minmax(0, 1fr) !important;+}+#image-input-preview:has(.gallery-item:only-child) img,-#image-output-preview:has(.gallery-item:only-child) img {- height: 100% !important;+#image-output-preview:has(.gallery-item:only-child) img,+#upscale-image-input-preview:has(.gallery-item:only-child) img,+#upscale-image-output-preview:has(.gallery-item:only-child) img {+ height: 100% !important;+ width: 100% !important;+ object-fit: contain !important;+}++/* The replacement and clear actions share the media preview width. */+.media-input-actions {+ width: 100% !important;+ max-width: none !important;+}++.media-input-actions > .media-select-button,+.media-input-actions > .media-clear-button {+ flex: 1 1 0 !important;+ min-width: 0 !important;+}++.media-select-button button,+.media-clear-button {width: 100% !important;- object-fit: contain !important;}-"""---def build_app() -> gr.Blocks:- """Build the UI from cached settings and feature-owned tab modules."""- prepared = prepare_runtime()- initialize_image_runtime()- settings, _gpu_warning, ai_gpu_choices, video_gpu_choices = initialize_settings(prepared)- # Re-apply the DLSS Architecture NR runtime for the loaded setting- # (no-op when the host copy already matches; failures only warn).- try:- apply_dlss_architecture(settings.dlss_architecture, prepared.gpu)- except Exception:- pass+"""+++def build_app() -> gr.Blocks:+ """Build the UI from cached settings and feature-owned tab modules."""+ prepared = prepare_runtime()+ initialize_image_runtime()+ settings, _gpu_warning, ai_gpu_choices, video_gpu_choices = initialize_settings(prepared)with gr.Blocks(- title="DLSS 5 Visual Enhancer",- # Official Gradio cache cleanup (see guides/resource-cleanup): every- # CACHE_SWEEP_INTERVAL_SECONDS, delete tracked temp files older than- # CACHE_MAX_AGE_SECONDS; full wipe on graceful shutdown. Crash orphans- # are covered by cleanup_old_caches() at startup in main().- delete_cache=(CACHE_SWEEP_INTERVAL_SECONDS, CACHE_MAX_AGE_SECONDS),- ) as demo:- gr.Markdown(- "# DLSS 5 Visual Enhancer\n"- "[Support on Patreon](https://www.patreon.com/MM744) | "- "[GitHub](https://github.com/Merserk/dlss5-visual-enhancer)",- elem_id="app-title",- )- with gr.Tabs(selected="image"):- with gr.Tab("Image", id="image"):- image_tab = build_image_tab(settings)- with gr.Tab("Video", id="video"):- video_tab = build_video_tab(settings)- with gr.Tab("Frame Interpolation", id="frame-interpolation"):- frame_tab = build_frame_interpolation_tab(settings)- with gr.Tab("Live", id="live"):- live_tab = build_live_tab(settings)- with gr.Tab("Settings", id="settings"):- settings_tab = build_settings_tab(settings, ai_gpu_choices, video_gpu_choices)-- bind_settings_events(settings_tab, image_tab, video_tab, frame_tab, live_tab)- return demo---def main() -> None:- OUTPUTS.mkdir(exist_ok=True)- LOGS.mkdir(exist_ok=True)- LIVE_DIR.mkdir(exist_ok=True)- # Drop leftover Live session dirs from dead runs (previous process is gone).- try:- from src.live.pipeline import sweep_stale_live_dirs-- sweep_stale_live_dirs()- except Exception:- pass- # Remove stale Gradio caches / temp leftovers from previous (possibly- # crashed) runs before serving. Best effort: never blocks startup.- try:- cleanup_old_caches()- except Exception:- pass- # Ensure the per-architecture NR runtimes exist and stage the saved- # DLSS Architecture build into host/ before prepare_runtime() warms it.- # Best effort: never blocks startup.- try:- init_dlssnr_runtime()- except Exception:- pass+ title="DLSS 5 Visual Enhancer",+ # Official Gradio cache cleanup (see guides/resource-cleanup): every+ # CACHE_SWEEP_INTERVAL_SECONDS, delete tracked temp files older than+ # CACHE_MAX_AGE_SECONDS; full wipe on graceful shutdown. Crash orphans+ # are covered by cleanup_old_caches() at startup in main().+ delete_cache=(CACHE_SWEEP_INTERVAL_SECONDS, CACHE_MAX_AGE_SECONDS),+ ) as demo:+ gr.Markdown(+ "# DLSS 5 Visual Enhancer",+ elem_id="app-title",+ )+ with gr.Tabs(selected="neural-rendering"):+ with gr.Tab("Neural Rendering", id="neural-rendering"):+ neural_rendering_tab = build_neural_rendering_tab(settings)+ with gr.Tab("Upscale", id="upscale"):+ upscale_tab = build_upscale_tab(settings)+ with gr.Tab("Frame Interpolation", id="frame-interpolation"):+ frame_tab = build_frame_interpolation_tab(settings)+ with gr.Tab("Live", id="live"):+ live_tab = build_live_tab(settings)+ with gr.Tab("Settings", id="settings"):+ settings_tab = build_settings_tab(settings, ai_gpu_choices, video_gpu_choices)+ with gr.Tab("About", id="about"):+ build_about_tab()++ bind_settings_events(+ settings_tab,+ neural_rendering_tab.image,+ neural_rendering_tab.video,+ frame_tab,+ live_tab,+ upscale_tab,+ )+ return demo+++def main() -> None:+ OUTPUTS.mkdir(exist_ok=True)+ LOGS.mkdir(exist_ok=True)+ LIVE_DIR.mkdir(exist_ok=True)+ # Drop leftover Live session dirs from dead runs (previous process is gone).+ try:+ from src.live.pipeline import sweep_stale_live_dirs++ sweep_stale_live_dirs()+ except Exception:+ pass+ # Remove stale Gradio caches / temp leftovers from previous (possibly+ # crashed) runs before serving. Best effort: never blocks startup.+ try:+ cleanup_old_caches()+ except Exception:+ pass# 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:- prepare_runtime()- except Exception as exc:- 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-- demo = build_app()- # 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__":- main()+ 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:+ prepare_runtime()+ except Exception as exc:+ 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++ demo = build_app()+ # 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__":+ main()diff --git a/src/__init__.py b/src/__init__.pyindex 3ceb7d0..9bf2145 100644--- a/src/__init__.py+++ b/src/__init__.py@@ -1,7 +1,7 @@"""Portable DLSS 5 Visual Enhancer for images and video."""from .core.ffmpeg import probe_video-from .image import (+from .neural_rendering.image import (ImageBatchResult,ImageConversionFailure,ImageConversionOptions,@@ -19,7 +19,7 @@ from .frame_interpolation import (interpolate_videos,probe_frame_interpolation_capabilities,)-from .video import (+from .neural_rendering.video import (ConversionOptions,ConversionResult,VideoBatchResult,diff --git a/src/about/__init__.py b/src/about/__init__.pynew file mode 100644index 0000000..11af3be--- /dev/null+++ b/src/about/__init__.py@@ -0,0 +1 @@+"""Application information and project links."""diff --git a/src/about/ui.py b/src/about/ui.pynew file mode 100644index 0000000..041526c--- /dev/null+++ b/src/about/ui.py@@ -0,0 +1,26 @@+import gradio as gr+++def build_about_tab():+ return gr.HTML(+ """+ <section class="about-details" aria-labelledby="about-name">+ <h2 id="about-name">DLSS 5 Visual Enhancer</h2>+ <p class="about-version">Version v7.0</p>+ <div class="about-links">+ <p>+ <a href="https://github.com/Merserk/dlss5-visual-enhancer"+ target="_blank" rel="noopener noreferrer">GitHub</a>+ <span class="about-description">Source code, updates, and issue reporting.</span>+ </p>+ <p>+ <a href="https://www.patreon.com/MM744"+ target="_blank" rel="noopener noreferrer">Support on Patreon</a>+ </p>+ </div>+ <p class="about-copyright">© Merserk</p>+ </section>+ """,+ elem_id="about-content",+ padding=False,+ )diff --git a/src/core/batch_ui.py b/src/core/batch_ui.pyindex 94a3956..14fd69e 100644--- a/src/core/batch_ui.py+++ b/src/core/batch_ui.py@@ -15,13 +15,55 @@ BATCH_HEADERS = ["File", "State", "Progress", "Elapsed", "Output path", "Detailsdef build_path_controls():- source = gr.Textbox(label="Input path", placeholder=r"C:\Users\You\Downloads\Videos",- info="Absolute file or folder path. Overrides uploads; folder contents only, sorted by filename.")- destination = gr.Textbox(label="Output path", placeholder=r"D:\Rendered outputs",- info="Output folder; blank uses the app's outputs folder. Either path disables previews and downloads.")+ source = gr.Textbox(+ label="Input path (Optional)", placeholder=r"D:\Render\inputs",+ info="Absolute file or folder path. Overrides uploads; folder contents only, sorted by filename.",+ )+ destination = gr.Textbox(+ label="Output path (Optional)", placeholder=r"D:\Render\outputs",+ info="Output folder; blank uses the app's outputs folder. Either path disables previews and downloads.",+ )return source, destination+def build_media_select_button(label: str, file_types: list[str], elem_id: str):+ """Build the replacement picker shown below an input preview."""+ return gr.UploadButton(+ label,+ file_count="multiple",+ file_types=file_types,+ type="filepath",+ visible=True,+ size="lg",+ scale=1,+ min_width=0,+ elem_id=elem_id,+ elem_classes=["media-select-button"],+ )+++def build_media_clear_button(elem_id: str):+ """Build the clear action displayed to the right of a replacement picker."""+ return gr.Button(+ "Clear",+ visible=True,+ size="lg",+ scale=1,+ min_width=0,+ elem_id=elem_id,+ elem_classes=["media-clear-button"],+ )+++def input_surface_updates(show_preview: bool, input_path: str | None = None):+ """Swap the drop zone for its preview while uploads are the active input mode."""+ upload_enabled = not bool(str(input_path or "").strip())+ return (+ gr.update(visible=not show_preview, interactive=upload_enabled),+ gr.update(visible=show_preview and upload_enabled),+ )++class BatchRun:def __init__(self, paths):self.controller = JobController()@@ -81,19 +123,41 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(tab.job_state = gr.State(value=lambda: uuid.uuid4().hex, delete_callback=release_view)is_image = kind == "image"input_media = tab.input_gallery if is_image else tab.input_preview- media = ([tab.output_gallery, tab.output_files, tab.zip_download] if is_image else- [tab.output_video, tab.output_files])+ media = [tab.output_gallery] if is_image else [tab.output_video]+ archive_download = getattr(tab, "zip_download", None)+ if archive_download is not None:+ media.append(tab.zip_download)preview_buttons = [button for button, _fn in preview_actions]- controls = [tab.sources, tab.input_path, tab.output_path, tab.render, tab.reset, *preview_buttons]+ controls = [+ tab.sources, tab.select_source, tab.clear_source, tab.input_path, tab.output_path,+ tab.render, tab.reset, *preview_buttons,+ ]outputs = [*media, tab.results, tab.status, *controls]path_inputs = [tab.job_state, tab.input_path, tab.output_path]def empty_media(disk):- return [gr.update(value=None, visible=not disk) for _ in media]+ values = [gr.update(value=None, visible=not disk)]+ if archive_download is not None:+ values.append(gr.update(value=None, visible=False))+ return values++ def completed_media(result, disk):+ if result is None or disk:+ return empty_media(disk)+ values = list(result[:len(media)])+ if archive_download is not None:+ archive_path = values[-1]+ values[-1] = gr.update(value=archive_path, visible=bool(archive_path))+ return valuesdef control_updates(busy, input_path):- return [gr.update(interactive=not busy and not bool(str(input_path or "").strip())),- *[gr.update(interactive=not busy) for _ in controls[1:]]]+ upload_enabled = not busy and not bool(str(input_path or "").strip())+ return [+ gr.update(interactive=upload_enabled),+ gr.update(interactive=upload_enabled),+ gr.update(interactive=upload_enabled),+ *[gr.update(interactive=not busy) for _ in controls[3:]],+ ]def refresh(key, input_path, output_path, *args):view = _view(key)@@ -106,29 +170,54 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(if busy and disk and view.job is not None and view.job.is_preview:view.job.controller.stop()if busy and not disk:- return [gr.skip()] * (1 + len(media) + len(preview_buttons) + 1)+ return [gr.skip()] * (1 + len(media) + len(preview_buttons) + 2)+ show_input_media = Falseif disk:values = [gr.update(value=None, visible=False), *empty_media(True),*[gr.update(visible=False) for _ in preview_buttons]]elif is_image:previews = preview_mode(args[0])- values = [gr.update(value=previews, visible=bool(previews)), *empty_media(False)]+ show_input_media = bool(previews)+ values = [gr.update(value=previews, visible=show_input_media), *empty_media(False)]else:input_update, output_update, *buttons = preview_mode(*args)- values = [input_update, output_update, gr.update(value=None, visible=True), *buttons]+ sources = args[0]+ show_input_media = bool([sources] if isinstance(sources, str) else list(sources or []))+ values = [input_update, output_update, *empty_media(False)[1:], *buttons]with view.lock:if revision != view.revision:- return [gr.skip()] * (1 + len(media) + len(preview_buttons) + 1)- return [*values, gr.update(interactive=not bool(str(input_path or "").strip()))]+ return [gr.skip()] * (1 + len(media) + len(preview_buttons) + 2)+ source_update, actions_update = input_surface_updates(show_input_media, input_path)+ return [+ *values,+ source_update,+ actions_update,+ ]source_args = [tab.sources]if hasattr(tab, "target_fps"):source_args += [tab.target_fps, tab.engine]- refresh_outputs = [input_media, *media, *preview_buttons, tab.sources]+ refresh_outputs = [+ input_media, *media, *preview_buttons,+ tab.sources, tab.input_actions,+ ]+ tab.select_source.upload(+ lambda selected: gr.update(value=selected),+ inputs=tab.select_source,+ outputs=tab.sources,+ queue=False,+ show_progress="hidden",+ )+ tab.clear_source.click(+ lambda: gr.update(value=None),+ outputs=tab.sources,+ queue=False,+ show_progress="hidden",+ )for component in (tab.sources, tab.input_path, tab.output_path):- event = component.change if component is tab.sources else component.input- event(refresh, inputs=[*path_inputs, *source_args], outputs=refresh_outputs,- queue=False, show_progress="hidden")+ # Textbox changes also cover pasted paths and programmatic value updates.+ component.change(refresh, inputs=[*path_inputs, *source_args], outputs=refresh_outputs,+ queue=False, show_progress="hidden")def stream(key, input_path, output_path, *args):view = _view(key)@@ -168,9 +257,7 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(*[gr.skip() for _ in controls])job.close()row_values, status = job.progress.display(destination)- final_media = empty_media(disk)- if job.result is not None and not disk:- final_media = list(job.result[:len(media)])+ final_media = completed_media(job.result, disk)if job.error and job.error not in status:status += f"\n{job.error}"with view.lock:@@ -203,9 +290,14 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(def guarded_preview(function):def preview(key, input_path, output_path, *args, progress=gr.Progress(track_tqdm=False)):+ def empty_preview(video, status):+ values = (video, status)+ if archive_download is not None:+ values += (gr.update(value=None, visible=False),)+ return valuesview = _view(key)if direct_disk_mode(input_path, output_path):- return gr.update(value=None, visible=False), "Previews are disabled when a path is supplied."+ return empty_preview(gr.update(value=None, visible=False), "Previews are disabled when a path is supplied.")with view.lock:if view.job is not None:raise gr.Error("A job is already running in this tab.")@@ -217,10 +309,12 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(with use_job_controller(job.controller):result = function(*args, progress=progress)if job.controller.cancel.is_set():- return gr.update(value=None, visible=False), "Preview cancelled."+ return empty_preview(gr.update(value=None, visible=False), "Preview cancelled.")with view.lock:if view.revision != revision or view.disk:- return gr.skip(), gr.skip()+ return (gr.skip(),) * (2 + int(archive_download is not None))+ if archive_download is not None:+ return (*result, gr.update(value=None, visible=False))return resultfinally:job.done.set()@@ -230,4 +324,5 @@ def bind_batch_ui(tab, render_function, *, kind, preview_mode, preview_actions=(return previewfor button, function in preview_actions:button.click(guarded_preview(function), inputs=[*path_inputs, *tab.preview_inputs],- outputs=[tab.output_video, tab.status], concurrency_limit=None, show_progress="hidden")+ outputs=[tab.output_video, tab.status, *([archive_download] if archive_download is not None else [])],+ concurrency_limit=None, show_progress="hidden")diff --git a/src/core/disk_paths.py b/src/core/disk_paths.pyindex 754cddd..7528f6a 100644--- a/src/core/disk_paths.py+++ b/src/core/disk_paths.py@@ -4,6 +4,9 @@ from __future__ import annotationsimport mimetypesimport osimport tempfile+import time+import uuid+import zipfilefrom pathlib import Pathfrom .naming import require_available_output@@ -33,7 +36,7 @@ def supported_file(path: Path, kind: str) -> bool:if kind == "image":# Lazy imports avoid coupling the core module's initialization to Image.from PIL import Image- from ..image.models import RAW_EXTENSIONS+ from ..neural_rendering.image.models import RAW_EXTENSIONSreturn suffix in (set(Image.registered_extensions()) | RAW_EXTENSIONS | {".svg", ".heic", ".heif"})if kind != "video":raise ValueError(f"Unknown media type: {kind}")@@ -116,3 +119,57 @@ class OutputFile:self.destination.unlink()except FileNotFoundError:pass+++def create_media_archive(+ paths,+ output_dir,+ prefix: str,+ *,+ controller=None,+) -> str | None:+ """Atomically store successful media in an uncompressed, cancellable ZIP."""+ sources = [Path(path).resolve() for path in paths]+ if not sources or (controller is not None and controller.cancel.is_set()):+ return None+ destination = prepare_output_dir(output_dir)+ stamp = time.strftime("%Y%m%d-%H%M%S")+ archive_path = destination / f"{prefix}_{stamp}_{uuid.uuid4().hex[:8]}.zip"+ output_file = OutputFile(archive_path)+ cancelled = False+ try:+ used_names: set[str] = set()+ with zipfile.ZipFile(+ output_file.temporary, "w", compression=zipfile.ZIP_STORED, allowZip64=True,+ ) as archive:+ for source in sources:+ if controller is not None and controller.cancel.is_set():+ cancelled = True+ break+ candidate = source.name+ index = 2+ while candidate.casefold() in used_names:+ candidate = f"{source.stem}_{index}{source.suffix}"+ index += 1+ used_names.add(candidate.casefold())+ info = zipfile.ZipInfo.from_file(source, arcname=candidate)+ info.compress_type = zipfile.ZIP_STORED+ with source.open("rb") as input_stream, archive.open(+ info, "w", force_zip64=True,+ ) as output_stream:+ while True:+ if controller is not None and controller.cancel.is_set():+ cancelled = True+ break+ chunk = input_stream.read(1024 * 1024)+ if not chunk:+ break+ output_stream.write(chunk)+ if cancelled:+ break+ if cancelled or (controller is not None and controller.cancel.is_set()):+ return None+ output_file.publish()+ return str(archive_path)+ finally:+ output_file.cleanup()diff --git a/src/core/dlss_architecture.py b/src/core/dlss_architecture.pydeleted file mode 100644index 6c5a4fe..0000000--- a/src/core/dlss_architecture.py+++ /dev/null@@ -1,250 +0,0 @@-from __future__ import annotations--"""Selectable DLSS 5 Neural Rendering architecture builds.--``bin/runtime/dlssnr/`` holds one ``nvngx_dlssnr.dll`` per GPU-architecture-floor (extracted from the ``bin/*.zip`` archives)::-- dlssnr/Turing+/nvngx_dlssnr.dll- dlssnr/Ada Lovelace+/nvngx_dlssnr.dll- dlssnr/Blackwell+/nvngx_dlssnr.dll--The native worker (``bin/runtime/host/nvngx.dll``) loads the NR runtime-through the NGX API by filename convention from ``host/`` (and ``dlss/``),-with no architecture gating of its own — so selecting an architecture is a-pure file swap of ``host/nvngx_dlssnr.dll`` (which RenoDX requires to sit-next to itself). No native recompilation is involved.--Policy (per product decision):-- ``Auto`` maps RTX 20/30 (Turing/Ampere) to ``Turing+``, RTX 40 (Ada) to- ``Ada Lovelace+``, RTX 50 (Blackwell) to ``Blackwell+``; unknown GPUs fall- back to ``Turing+`` (the historical default build).-- Applied at startup (before ``prepare_runtime()`` warms the DLL) and again- before each render. The worker is a per-job subprocess, so swapping- between jobs cannot race a running render. Identical content is skipped.-- Any failure warns (``logs/dlssnr_architecture.log``) and keeps the- current host DLL; renders proceed. These helpers never raise.-"""--import hashlib-import time-import zipfile-from pathlib import Path-from typing import Any--from .paths import DLSSNR_DIR, LOGS, NEURAL_RUNTIME, ROOT--DLL_FILENAME = "nvngx_dlssnr.dll"-LOG_FILENAME = "dlssnr_architecture.log"--DLSS_ARCHITECTURE_CHOICES = (- "Auto",- "Turing and higher",- "Ada Lovelace and higher",- "Blackwell and higher",-)-DEFAULT_DLSS_ARCHITECTURE = "Auto"--_CHOICE_SUBFOLDERS: dict[str, str | None] = {- "Auto": None,- "Turing and higher": "Turing+",- "Ada Lovelace and higher": "Ada Lovelace+",- "Blackwell and higher": "Blackwell+",-}--_SUBFOLDER_ZIPS: dict[str, str] = {- "Turing+": "Turing+.zip",- "Ada Lovelace+": "Ada Lovelace+.zip",- "Blackwell+": "Blackwell+.zip",-}---def _warn(message: str) -> None:- try:- LOGS.mkdir(parents=True, exist_ok=True)- stamp = time.strftime("%Y-%m-%d %H:%M:%S")- with open(LOGS / LOG_FILENAME, "a", encoding="utf-8") as handle:- handle.write(f"{stamp} {message}\n")- except OSError:- pass---def _sha256(path: Path) -> str | None:- try:- 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()- except OSError:- return None---def subfolder_for_choice(choice: str) -> str | None:- """Return the explicit arch subfolder, or None for ``Auto``."""- return _CHOICE_SUBFOLDERS.get(choice)---def subfolder_for_gpu(gpu: dict[str, Any] | None) -> str:- """Map a detected GPU to its ``Auto`` arch subfolder (Turing+ default)."""- architecture = ""- generation: Any = None- if isinstance(gpu, dict):- architecture = str(gpu.get("architecture") or "")- generation = gpu.get("generation")- if architecture == "Blackwell" or generation == 50:- return "Blackwell+"- if architecture == "Ada" or generation == 40:- return "Ada Lovelace+"- return "Turing+"---def resolve_subfolder(choice: str, gpu: dict[str, Any] | None) -> str:- """Resolve a DLSS Architecture setting (possibly ``Auto``) to a folder."""- if choice not in DLSS_ARCHITECTURE_CHOICES:- _warn(f"Unknown DLSS Architecture {choice!r}; using {DEFAULT_DLSS_ARCHITECTURE!r}.")- choice = DEFAULT_DLSS_ARCHITECTURE- explicit = subfolder_for_choice(choice)- if explicit is not None:- return explicit- return subfolder_for_gpu(gpu)---def arch_dll_path(subfolder: str) -> Path:- return DLSSNR_DIR / subfolder / DLL_FILENAME---def ensure_dlssnr_dlls() -> dict[str, bool]:- """Extract any missing arch DLL from its ``bin/*.zip``. Never raises.-- Returns ``{subfolder: available}``.- """- availability: dict[str, bool] = {}- for subfolder, zip_name in _SUBFOLDER_ZIPS.items():- destination = arch_dll_path(subfolder)- try:- if destination.is_file():- availability[subfolder] = True- continue- zip_path = ROOT / "bin" / zip_name- if not zip_path.is_file():- _warn(- f"DLSS Architecture DLL missing: {destination} "- f"(archive {zip_path} not found)."- )- availability[subfolder] = False- continue- with zipfile.ZipFile(zip_path) as archive:- if archive.namelist() != [DLL_FILENAME]:- _warn(- f"Archive {zip_path} has unexpected contents; "- f"expected only {DLL_FILENAME}."- )- availability[subfolder] = False- continue- data = archive.read(DLL_FILENAME)- destination.parent.mkdir(parents=True, exist_ok=True)- temporary = destination.with_name(f".{DLL_FILENAME}.tmp")- temporary.write_bytes(data)- temporary.replace(destination)- availability[subfolder] = True- except Exception as exc: # noqa: BLE001 - warn-and-continue policy- _warn(f"Could not provide {destination}: {exc}.")- availability[subfolder] = False- return availability---def apply_dlss_architecture(choice: str, gpu: dict[str, Any] | None) -> str:- """Copy the resolved arch DLL over ``host/nvngx_dlssnr.dll``.-- Returns the applied subfolder name, or ``""`` when nothing was applied- (missing source or copy failure — the current host DLL is kept and the- caller should proceed). Never raises.- """- try:- ensure_dlssnr_dlls()- subfolder = resolve_subfolder(choice, gpu)- source = arch_dll_path(subfolder)- if not source.is_file():- _warn(- f"DLSS Architecture {choice!r} unavailable "- f"({source} missing); keeping current host DLL."- )- return ""- source_hash = _sha256(source)- if source_hash is not None and source_hash == _sha256(NEURAL_RUNTIME):- return subfolder- # prepare_runtime() memory-maps the host DLL for warming and holds- # the mapping for the process lifetime; on Windows an open mapping- # blocks replacement, so release it before swapping (next- # prepare_runtime() call transparently re-warms the new file).- try:- from .runtime import close_prepared_runtime-- close_prepared_runtime()- except Exception: # noqa: BLE001 - best effort- pass- NEURAL_RUNTIME.parent.mkdir(parents=True, exist_ok=True)- temporary = NEURAL_RUNTIME.with_name(f".{DLL_FILENAME}.tmp")- temporary.write_bytes(source.read_bytes())- temporary.replace(NEURAL_RUNTIME)- return subfolder- except Exception as exc: # noqa: BLE001 - warn-and-continue policy- _warn(f"Could not apply DLSS Architecture {choice!r}: {exc}.")- return ""---def _current_choice_and_gpu() -> tuple[str, dict[str, Any] | None]:- from ..settings.storage import CONFIG_PATH, SETTINGS_STATE, load_settings-- from .gpu_detection import detect_gpus- from .gpu_selection import resolve_runtime_ai_gpu-- with SETTINGS_STATE.lock:- settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)- choice = getattr(settings, "dlss_architecture", DEFAULT_DLSS_ARCHITECTURE)- if choice not in DLSS_ARCHITECTURE_CHOICES:- choice = DEFAULT_DLSS_ARCHITECTURE- try:- gpus = detect_gpus()- except Exception as exc: # noqa: BLE001 - no GPU info available- _warn(f"GPU detection unavailable for DLSS Architecture: {exc}.")- return choice, None- try:- gpu = resolve_runtime_ai_gpu(- gpus, {}, getattr(settings, "ai_gpu_uuid", "auto")- )- except Exception as exc: # noqa: BLE001 - e.g. no RTX GPU- _warn(f"AI GPU resolution unavailable for DLSS Architecture: {exc}.")- return choice, None- return choice, gpu---def init_dlssnr_runtime() -> str:- """Ensure arch DLLs and apply the saved setting. Call before ``prepare_runtime()``.-- Returns the applied subfolder name or ``""``. Never raises.- """- try:- choice, gpu = _current_choice_and_gpu()- return apply_dlss_architecture(choice, gpu)- except Exception as exc: # noqa: BLE001 - startup must never block- _warn(f"DLSS Architecture init failed: {exc}.")- return ""---def apply_current_dlss_architecture(gpu: dict[str, Any] | None) -> str:- """Re-apply the live setting before a render. Call with the job's GPU.-- Returns the applied subfolder name or ``""``. Never raises.- """- try:- from ..settings.storage import CONFIG_PATH, SETTINGS_STATE, load_settings-- with SETTINGS_STATE.lock:- settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)- choice = getattr(settings, "dlss_architecture", DEFAULT_DLSS_ARCHITECTURE)- return apply_dlss_architecture(choice, gpu)- except Exception as exc: # noqa: BLE001 - render must never block- _warn(f"DLSS Architecture pre-render apply failed: {exc}.")- return ""diff --git a/src/core/ffmpeg/encoder.py b/src/core/ffmpeg/encoder.pyindex dba456a..12f5d66 100644--- a/src/core/ffmpeg/encoder.py+++ b/src/core/ffmpeg/encoder.py@@ -4,7 +4,7 @@ import subprocessimport threadingfrom pathlib import Path-from ..jobs import JobController, drain_text+from ..jobs import BoundedLogBuffer, JobController, drain_bounded_text, drain_textfrom ..paths import FFMPEGfrom .codecs import (CODEC_CHOICES, _NVENC_ENCODERS, _base_codec, _hdr_color_args,@@ -302,6 +302,7 @@ def start_encoder(hdr_mode: bool = False,hdr_metadata: dict | None = None,preserve_timestamps: bool = False,+ *, video_filter: str | None = None, keep_start_time: bool = False, bounded_logs: bool = False,):codec_args, selected, quality = _codec_command(codec, quality_name, width, height, fps, gpu_ordinal, require_nvenc, hdr_mode, hdr_metadata@@ -312,6 +313,7 @@ def start_encoder("-loglevel","warning","-y",+ *(["-copyts"] if keep_start_time else []),"-f","nut","-i",@@ -319,10 +321,12 @@ def start_encoder("-map","0:v:0","-an",+ *(["-vf", video_filter] if video_filter else []),*codec_args,"-fps_mode","passthrough",*(["-enc_time_base:v", "demux"] if preserve_timestamps else []),+ *(["-avoid_negative_ts", "disabled"] if keep_start_time else []),str(temp_video),]process = subprocess.Popen(@@ -330,10 +334,11 @@ def start_encoder(stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),)controller.register(process)- logs: list[str] = []+ logs = BoundedLogBuffer(max_tail=60) if bounded_logs else []assert process.stderr is not None- thread = threading.Thread(target=drain_text, args=(process.stderr, logs), daemon=True)+ thread = threading.Thread(target=drain_bounded_text if bounded_logs else drain_text, args=(process.stderr, logs), daemon=True)thread.start()return process, thread, logs, selected, qualitydiff --git a/src/core/ffmpeg/mux.py b/src/core/ffmpeg/mux.pyindex 235044f..2964106 100644--- a/src/core/ffmpeg/mux.py+++ b/src/core/ffmpeg/mux.py@@ -53,6 +53,7 @@ def final_mux(controller: JobController | None = None,preserve_supported_subtitles: bool = False,*, render_note: str | None = None, metadata_diagnostics: dict | None = None,+ source_time_origin: float | None = None,) -> None:check_cancelled(controller)if render_note is None or container not in VIDEO_NOTE_FORMATS:@@ -60,7 +61,7 @@ def final_mux(record_embedding(metadata_diagnostics, "skipped", reason="unsupported_format")elif metadata_diagnostics is not None and not metadata_diagnostics:record_embedding(metadata_diagnostics, "not_requested")- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles)+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, source_time_origin=source_time_origin)returntry:@@ -73,12 +74,12 @@ def final_mux(except (ValueError, TypeError, RuntimeError) as exc:check_cancelled(controller)embedding_warning(metadata_diagnostics, exc)- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles)+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, source_time_origin=source_time_origin)returntry:_final_mux_once(temp_video, source, output, container, controller,- preserve_supported_subtitles, comment=comment)+ preserve_supported_subtitles, comment=comment, source_time_origin=source_time_origin)if _read_comment(output, controller) != comment:raise MetadataNoteError("Saved video did not retain the settings note")except Cancelled:@@ -88,7 +89,7 @@ def final_mux(if isinstance(exc, _MuxFailure) and exc.filesystem_error:raiseembedding_warning(metadata_diagnostics, exc)- _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles)+ _final_mux_once(temp_video, source, output, container, controller, preserve_supported_subtitles, source_time_origin=source_time_origin)returnrecord_embedding(metadata_diagnostics, "embedded", field="format.comment")@@ -114,7 +115,7 @@ class _MuxFailure(RuntimeError):def _final_mux_once(temp_video: Path, source: Path, output: Path, container: str,controller: JobController | None, preserve_supported_subtitles: bool,- *, comment: str | None = None,+ *, comment: str | None = None, source_time_origin: float | None = None,) -> None:check_cancelled(controller)duration = _probe_rendered_duration(temp_video, controller)@@ -164,10 +165,12 @@ def _final_mux_once("-loglevel","warning","-y",+ *(["-copyts"] if source_time_origin is not None else []),"-i",str(temp_video),"-t",f"{duration:.9f}",+ *(["-itsoffset", f"{-source_time_origin:.9f}"] if source_time_origin is not None else []),"-i",str(source),*maps,@@ -176,6 +179,7 @@ def _final_mux_once("-map_chapters","1",*streams,+ *(["-avoid_negative_ts", "disabled", "-metadata:s:v:0", "rotate=0"] if source_time_origin is not None else []),*(["-metadata", "comment=" + comment] if comment is not None else []),str(output),]diff --git a/src/core/ffmpeg/preview.py b/src/core/ffmpeg/preview.pyindex f1443d3..d9e1f99 100644--- a/src/core/ffmpeg/preview.py+++ b/src/core/ffmpeg/preview.py@@ -84,6 +84,7 @@ def make_browser_preview(source: str | Path,dest_dir: str | Path | None = None,controller=None,+ *, sdr_filter: str | None = None,) -> str:"""Transcode an existing result file to a browser-playable H.264 MP4.@@ -118,6 +119,7 @@ def make_browser_preview("0:v:0","-map","0:a?",+ *(["-vf", sdr_filter, "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-color_range", "tv"] if sdr_filter else []),"-c:v","libx264","-preset",diff --git a/src/core/gpu_detection.py b/src/core/gpu_detection.pyindex 717fc0e..721c635 100644--- a/src/core/gpu_detection.py+++ b/src/core/gpu_detection.py@@ -7,40 +7,6 @@ from functools import lru_cachefrom 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])",@@ -91,23 +57,12 @@ def _cuda_device_identities() -> dict[str, dict[str, Any]]:@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 = Trueexcept (OSError, subprocess.TimeoutExpired) as exc:raise RuntimeError("NVIDIA driver tools are unavailable; an RTX GPU and current driver are required."@@ -124,27 +79,22 @@ def detect_gpus() -> tuple[dict[str, Any], ...]:continueif len(parts) == 4:legacy_row = True- name, driver, memory, capability = parts+ name, driver, memory, _legacy_capability = partsindex, uuid, pci_bus_id = str(fallback_index), f"index:{fallback_index}", ""- elif len(parts) == 6 and used_fallback_query:+ elif len(parts) == 6:legacy_row = Falseindex, 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 = partselse: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."+ "memory, 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)@@ -155,12 +105,8 @@ def detect_gpus() -> tuple[dict[str, Any], ...]: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 = Nonecompatibility_error = ""- if is_rtx:- architecture, generation = _classify_rtx_architecture(name, capability)- else:+ if not is_rtx:compatibility_error = "The device name does not identify an RTX GPU."devices.append({@@ -171,9 +117,6 @@ def detect_gpus() -> tuple[dict[str, Any], ...]:"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,diff --git a/src/core/paths.py b/src/core/paths.pyindex 646ba71..9af5ff7 100644--- a/src/core/paths.py+++ b/src/core/paths.py@@ -8,19 +8,16 @@ RUNTIME = ROOT / "bin" / "runtime"HOST_DIR = RUNTIME / "host"DLSS_DIR = RUNTIME / "dlss"DLSSG_DIR = RUNTIME / "dlssg"-# Per-architecture Neural Rendering builds (see src/core/dlss_architecture.py).-# The live copy stays at NEURAL_RUNTIME in host/ (RenoDX discovery rule).+# Universal FP16 Neural Rendering runtime for all supported RTX architectures.DLSSNR_DIR = RUNTIME / "dlssnr"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"+ADDON = DLSSNR_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"+NEURAL_RUNTIME = DLSSNR_DIR / "nvngx_dlssnr.dll"# Live-tab externals (vendored, optional: only Live sessions require them).MPV = ROOT / "bin" / "mpv" / "mpv.exe"YTDLP = ROOT / "bin" / "yt-dlp" / "yt-dlp.exe"diff --git a/src/core/runtime.py b/src/core/runtime.pyindex 9921d53..378d969 100644--- a/src/core/runtime.py+++ b/src/core/runtime.py@@ -20,7 +20,10 @@ import numpy as npfrom .gpu_detection import detect_gpusfrom .gpu_selection import resolve_runtime_ai_gpufrom .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+from .paths import (+ ADDON, DLSS_SUPERRES, FFMPEG, FFPROBE, HOST_DIR, HOST_DXGI, LOGS,+ NEURAL_RUNTIME, RESHADE_LOG, RUNTIME, WORKER,+)@@ -204,7 +207,7 @@ def inspect_runtime_bundle(def validate_gpu_runtime(gpu: dict[str, Any], bundle: dict[str, Any] | None = None) -> dict[str, Any]:- """Return runtime metadata without generation, version, or hash compatibility locks."""+ """Return runtime metadata without version or hash compatibility locks."""del gpureturn bundle or inspect_runtime_bundle()@@ -224,22 +227,11 @@ def classify_worker_failure("evaluate raised 0xC0000005" in evidenceor "feature 18 evaluate raised an exception" in evidence)- 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 "- f"RTX 30-series path before frame {frame_index} completed. Ordinary D3D12/NGX "- "initialization may still have succeeded; the failure is inside the patched neural "- "runtime/add-on evaluation."- )- 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:+ if access_violation:summary = (f"DLSS 5 feature 18 raised access violation 0xC0000005 before frame {frame_index} "- "completed inside the neural runtime/add-on evaluation."+ "completed inside the universal neural runtime/add-on evaluation. Update the "+ "NVIDIA driver and verify the bundled DLSSNR runtime is intact.")else:summary = (@@ -337,9 +329,10 @@ def validate_runtime_files() -> None:if leftovers:raise RuntimeError("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"+ "Move host files (nvngx.dll, dxgi.dll, ReShade.ini) to bin/runtime/host/, "+ "nvngx_dlss.dll to bin/runtime/dlss/, renodx-dlss5.addon64 and "+ "nvngx_dlssnr.dll to bin/runtime/dlssnr/, and "+ "frame_interpolation/dlssg/* to bin/runtime/dlssg/.\n"+ "\n".join(leftovers))# Note: ReShade.ini is not required here. The worker rewrites every NR keydiff --git a/src/frame_interpolation/preview.py b/src/frame_interpolation/preview.pyindex 6ef26d2..6015821 100644--- a/src/frame_interpolation/preview.py+++ b/src/frame_interpolation/preview.py@@ -90,10 +90,12 @@ def update_frame_interpolation_preview_mode(engine: str,):normalized = normalize_video_paths(paths)+ available = bool(normalized)single = len(normalized) == 1+ label = "Input video preview" if len(normalized) <= 1 else f"Input video preview (first of {len(normalized)})"return (- gr.update(value=normalized[0] if single else None, visible=single),- gr.update(value=None, visible=single),+ gr.update(value=normalized[0] if available else None, visible=available, label=label),+ gr.update(value=None, visible=True),gr.update(visible=single),)diff --git a/src/frame_interpolation/processor.py b/src/frame_interpolation/processor.pyindex 5b2afac..7f6d4c7 100644--- a/src/frame_interpolation/processor.py+++ b/src/frame_interpolation/processor.py@@ -17,7 +17,6 @@ import avimport numpy as npfrom ..core import ffmpeg-from ..core.dlss_architecture import apply_current_dlss_architecturefrom ..core.gpu_selection import resolve_runtime_ai_gpufrom ..core.jobs import Cancelled, active_jobfrom ..core.naming import output_filename, validate_rename@@ -224,12 +223,6 @@ def interpolate_video(ai_gpu = resolve_runtime_ai_gpu(prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid)- # Stage the selected DLSS Architecture NR build before workers spawn- # (warn-and-continue: render proceeds with the current DLL).- try:- apply_current_dlss_architecture(ai_gpu)- except Exception:- passcapabilities = probe_frame_interpolation_capabilities(options.ai_gpu_uuid)if not capabilities.available:raise RuntimeError(diff --git a/src/frame_interpolation/ui.py b/src/frame_interpolation/ui.pyindex 7201b9d..53db347 100644--- a/src/frame_interpolation/ui.py+++ b/src/frame_interpolation/ui.py@@ -5,7 +5,11 @@ from dataclasses import dataclassfrom pathlib import Pathimport gradio as gr-from ..core.batch_ui import BATCH_HEADERS, bind_batch_ui, build_path_controls+from ..core.batch_ui import (+ BATCH_HEADERS, bind_batch_ui, build_media_clear_button, build_media_select_button,+ build_path_controls,+)+from ..core.disk_paths import create_media_archivefrom ..core.ffmpeg import hdr_mode_supportedfrom ..core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview@@ -67,7 +71,7 @@ def render_frame_interpolation_batch(traceback.print_exc()if on_item_update is not None:raise- return gr.update(value=None, visible=len(paths) == 1), [], [], f"Failed: {exc}"+ return gr.update(value=None, visible=not direct_disk), None, [], f"Failed: {exc}"ordered: list[tuple[int, list[str]]] = []for item in result.successes:value = item.result@@ -105,12 +109,20 @@ def render_frame_interpolation_batch(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=not direct_disk and len(paths) == 1), ([] if direct_disk else files), rows, status+ archive_path = None+ if not direct_disk and not result.cancelled:+ archive_path = create_media_archive(+ files, output_dir, "DLSSFG_VIDEO_BATCH", controller=controller,+ )+ return gr.update(value=preview, visible=not direct_disk), archive_path, rows, status@dataclass(slots=True)class FrameInterpolationTab:sources: objectinput_preview: object+ input_actions: object+ select_source: object+ clear_source: objecttarget_fps: objectengine: objectquality: object@@ -124,7 +136,7 @@ class FrameInterpolationTab:stop: objectreset: objectoutput_video: object- output_files: object+ zip_download: objectstatus: objectresults: objectinput_path: object = None@@ -156,9 +168,18 @@ def build_frame_interpolation_tab(settings: UISettings) -> FrameInterpolationTabsources = gr.File(label="Input video(s)", file_count="multiple", file_types=["video"],type="filepath", allow_reordering=True, elem_id="frame-interpolation-upload-list",+ elem_classes=["media-upload-surface"],)- input_path, output_path = build_path_controls()input_preview = gr.Video(label="Input video preview", interactive=False, visible=False)+ with gr.Row(+ visible=False, elem_id="frame-interpolation-input-actions",+ elem_classes=["media-input-actions"],+ ) as input_actions:+ select_source = build_media_select_button(+ "Choose Videos", ["video"], "frame-interpolation-select-input",+ )+ clear_source = build_media_clear_button("frame-interpolation-clear-input")+ input_path, output_path = build_path_controls()with gr.Accordion("DLSS Frame Generation Settings", open=True):with gr.Row():target_fps = gr.Dropdown(@@ -202,11 +223,10 @@ def build_frame_interpolation_tab(settings: UISettings) -> FrameInterpolationTabstop = 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",+ output_video = gr.Video(+ label="Interpolated output", interactive=False, visible=True, height=520,)+ zip_download = gr.DownloadButton("Save as ZIP", visible=False)status = gr.Textbox(label="Status", interactive=False, lines=5, max_lines=12)results = gr.Dataframe(headers=BATCH_HEADERS,@@ -214,8 +234,8 @@ def build_frame_interpolation_tab(settings: UISettings) -> FrameInterpolationTablabel="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+ sources, input_preview, input_actions, select_source, clear_source, target_fps, engine, quality, codec, container, rename_mode,+ custom_suffix, hdr_mode, preview, render, stop, reset, output_video, zip_download, status, results)tab.input_path, tab.output_path = input_path, output_pathbind_frame_interpolation_events(tab)diff --git a/src/live/models.py b/src/live/models.pyindex 46d2a28..d2bc621 100644--- a/src/live/models.py+++ b/src/live/models.py@@ -21,7 +21,7 @@ class LiveOptions:source: str = ""max_height: int = 720- # Shared DLSS values (mirrored with the Image/Video tabs, persisted+ # Shared DLSS values (mirrored with the Neural Rendering modes, persisted# globally); effects can update during playback, sizing stays fixed.nr_preset: str = "Default"nr_style: str = "Default"diff --git a/src/live/pipeline.py b/src/live/pipeline.pyindex 2f54765..7c02fd4 100644--- a/src/live/pipeline.py+++ b/src/live/pipeline.py@@ -16,14 +16,13 @@ from pathlib import Pathimport avimport numpy as np-from ..core.dlss_architecture import apply_current_dlss_architecturefrom ..core.gpu_selection import resolve_runtime_ai_gpufrom ..core.jobs import BoundedLogBuffer, Cancelled, JobController, active_job, drain_bounded_textfrom ..core.paths import FFMPEG, LIVE_DIR, LOGSfrom ..core.runtime import (DLSSFrameSession, prepare_runtime, resolve_native_settings,resolve_output_size, resolve_upscaling_mode, verify_feature_18)from ..settings.storage import processing_gpu_settings-from ..video.guides import TemporalGuideGenerator+from ..neural_rendering.video.guides import TemporalGuideGeneratorfrom .effects import EffectSettings, EffectUpdates, NativeDeadline, EFFECT_REPLACEMENT_TIMEOUTfrom .hls_server import HlsServerfrom .models import (LIVE_FRAME_COUNT, LIVE_FPS_CHOICES, LIVE_GUIDE_CHOICES,@@ -476,7 +475,6 @@ class LiveSession(threading.Thread):prepared_runtime = prepare_runtime()ai_uuid, video_uuid = processing_gpu_settings()gpu = resolve_runtime_ai_gpu(prepared_runtime.gpus, prepared_runtime.runtime_bundle, ai_uuid)- apply_current_dlss_architecture(gpu)nvenc, ordinal = self._select_encoder(prepared_runtime.gpus, video_uuid, out_w, out_h)self._set(input_size=f"{in_w}x{in_h}", output_size=f"{out_w}x{out_h}",encoder="NVIDIA NVENC" if nvenc else "CPU x264")diff --git a/src/live/ui.py b/src/live/ui.pyindex e97cadc..83bca3a 100644--- a/src/live/ui.py+++ b/src/live/ui.py@@ -6,7 +6,7 @@ from pathlib import Pathimport gradio as grfrom ..settings.models import UISettings, parse_automatic_mask-from ..video.ui import build_dlss_model_control, build_neural_controls+from ..neural_rendering.video.ui import build_dlss_model_control, build_neural_controlsfrom .models import (LIVE_FPS_CHOICES, LIVE_GUIDE_CHOICES, LIVE_MAX_HEIGHT_CHOICES,LIVE_MAX_HEIGHTS, LIVE_SEGMENT_CHOICES, LIVE_SOURCE_QUALITY_CHOICES)from .pipeline import is_live_running, live_status, start_live_session, stop_live_session@@ -166,7 +166,7 @@ def build_live_tab(settings: UISettings) -> LiveTab:label="Local video", file_count="single", file_types=["video"],type="filepath", interactive=True,)- gr.Markdown("Live applies DLSS effect changes automatically, including shared edits from other tabs. "+ gr.Markdown("Live applies DLSS effect changes automatically, including shared edits from Neural Rendering's Image and Video modes. ""Edits are combined for 0.5 seconds; applying them takes a few seconds, ""plus playback buffering.")with gr.Accordion("DLSS 5 Neural Rendering Settings", open=True):diff --git a/src/neural_rendering/__init__.py b/src/neural_rendering/__init__.pynew file mode 100644index 0000000..210dc05--- /dev/null+++ b/src/neural_rendering/__init__.py@@ -0,0 +1 @@+"""DLSS Neural Rendering workflows for images and videos."""diff --git a/src/image/__init__.py b/src/neural_rendering/image/__init__.pysimilarity index 100%rename from src/image/__init__.pyrename to src/neural_rendering/image/__init__.pydiff --git a/src/image/batch.py b/src/neural_rendering/image/batch.pysimilarity index 95%rename from src/image/batch.pyrename to src/neural_rendering/image/batch.pyindex 7438e47..107f8cd 100644--- a/src/image/batch.py+++ b/src/neural_rendering/image/batch.py@@ -11,15 +11,14 @@ from typing import Callable, Iterableimport cv2import numpy as np-from ..core.batch_progress import BatchItemUpdate, BatchProgress-from ..core.disk_paths import OutputFile, prepare_output_dir-from ..core.dlss_architecture import apply_current_dlss_architecture-from ..core.gpu_selection import resolve_runtime_ai_gpu-from ..core.jobs import Cancelled, JobController, active_job-from ..core.render_metadata import prepare_render_note-from ..core.naming import output_filename, validate_rename-from ..core.paths import LOGS, OUTPUTS-from ..core.runtime import (+from ...core.batch_progress import BatchItemUpdate, BatchProgress+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.gpu_selection import resolve_runtime_ai_gpu+from ...core.jobs import Cancelled, JobController, active_job+from ...core.render_metadata import prepare_render_note+from ...core.naming import output_filename, 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,)@@ -80,10 +79,6 @@ def convert_images(raise Cancelled("Stopped before rendering.")prepared = prepare_runtime()gpu = resolve_runtime_ai_gpu(prepared.gpus, prepared.runtime_bundle, options.ai_gpu_uuid)- try:- apply_current_dlss_architecture(gpu)- except Exception:- passfactor, mode = resolve_upscaling_mode(options.upscaling_factor)native = resolve_native_settings(options)next_decode = Nonediff --git a/src/image/decoder.py b/src/neural_rendering/image/decoder.pysimilarity index 100%rename from src/image/decoder.pyrename to src/neural_rendering/image/decoder.pydiff --git a/src/image/encoder.py b/src/neural_rendering/image/encoder.pysimilarity index 99%rename from src/image/encoder.pyrename to src/neural_rendering/image/encoder.pyindex ec5abcd..7bb6056 100644--- a/src/image/encoder.py+++ b/src/neural_rendering/image/encoder.py@@ -11,8 +11,8 @@ import numpy as npfrom PIL import Imagefrom .models import ImageConversionOptions-from ..core.jobs import Cancelled-from ..core.render_metadata import (+from ...core.jobs import Cancelled+from ...core.render_metadata import (IMAGE_NOTE_FORMATS, MetadataNoteError, check_cancelled, embedding_warning,merge_render_note, record_embedding,)diff --git a/src/image/models.py b/src/neural_rendering/image/models.pysimilarity index 100%rename from src/image/models.pyrename to src/neural_rendering/image/models.pydiff --git a/src/image/processor.py b/src/neural_rendering/image/processor.pysimilarity index 100%rename from src/image/processor.pyrename to src/neural_rendering/image/processor.pydiff --git a/src/image/reports.py b/src/neural_rendering/image/reports.pysimilarity index 96%rename from src/image/reports.pyrename to src/neural_rendering/image/reports.pyindex 40f586b..aee59ad 100644--- a/src/image/reports.py+++ b/src/neural_rendering/image/reports.py@@ -7,10 +7,10 @@ from pathlib import Pathfrom PIL import TiffImagePlugin-from ..core.paths import LOGS, OUTPUTS-from ..core.disk_paths import OutputFile-from ..core.jobs import Cancelled-from ..core.runtime import DLSSFrameSession, DLSS_MODEL_PRESETS+from ...core.paths import LOGS, OUTPUTS+from ...core.disk_paths import OutputFile+from ...core.jobs import Cancelled+from ...core.runtime import DLSSFrameSession, DLSS_MODEL_PRESETSfrom .decoder import _DecodedImagefrom .models import ImageConversionFailure, ImageConversionOptions, ImageConversionResult@@ -90,6 +90,7 @@ def _write_report("carrier_create_result": evidence["carrier_create_result"],"native_settings": session.native_settings,"addon_release": session.runtime_bundle["addon"]["release"],+ "dlssnr_runtime": session.runtime_bundle["neural_runtime"],"worker_log": session.worker_logs,"worker_log_dropped_lines": session.worker_log_dropped_lines,"dlssnr_evidence": evidence["evidence"],diff --git a/src/image/ui.py b/src/neural_rendering/image/ui.pysimilarity index 88%rename from src/image/ui.pyrename to src/neural_rendering/image/ui.pyindex 62ea40a..f39ab4b 100644--- a/src/image/ui.py+++ b/src/neural_rendering/image/ui.py@@ -5,13 +5,16 @@ from dataclasses import dataclassfrom pathlib import Pathimport gradio as gr-from ..core.batch_ui import BATCH_HEADERS, bind_batch_ui, build_path_controls+from ...core.batch_ui import (+ BATCH_HEADERS, bind_batch_ui, build_media_clear_button, build_media_select_button,+ build_path_controls,+)from PIL import Image-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 ...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_settingsfrom .decoder import decode_imagefrom .encoder import take_image_previewfrom .batch import convert_images@@ -150,7 +153,7 @@ def render_image_batch(traceback.print_exc()if on_item_update is not None:raise- return [], [], None, [], f"Failed: {exc}"+ return [], None, [], f"Failed: {exc}"gallery = []for item in ([] if direct_disk else result.successes):@@ -161,7 +164,6 @@ def render_image_batch(preview.thumbnail((1600, 1200), Image.Resampling.LANCZOS)preview = preview.copy()gallery.append((preview, Path(item.output_path).name))- files = [] if direct_disk else [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@@ -176,12 +178,15 @@ def render_image_batch()if result.failures:status += f"\nFirst error: {result.failures[0].error}"- return gallery, files, result.zip_path, rows, status+ return gallery, result.zip_path, rows, status@dataclass(slots=True)class ImageTab:sources: objectinput_gallery: object+ input_actions: object+ select_source: object+ clear_source: objectneural: list[object]model_preset: objectoutput_format: object@@ -192,7 +197,6 @@ class ImageTab:stop: objectreset: objectoutput_gallery: object- output_files: objectzip_download: objectstatus: objectresults: object@@ -216,12 +220,21 @@ def build_image_tab(settings: UISettings) -> ImageTab:sources = gr.File(label="Input image(s)", file_count="multiple", file_types=upload_types,type="filepath", allow_reordering=True, elem_id="image-upload-list",+ elem_classes=["media-upload-surface"],)- input_path, output_path = build_path_controls()input_gallery = gr.Gallery(label="Input preview", columns=3, height=520, object_fit="contain",interactive=False, visible=False, buttons=["fullscreen"], elem_id="image-input-preview",)+ with gr.Row(+ visible=False, elem_id="image-input-actions",+ elem_classes=["media-input-actions"],+ ) as input_actions:+ select_source = build_media_select_button(+ "Choose Images", upload_types, "image-select-input",+ )+ clear_source = build_media_clear_button("image-clear-input")+ input_path, output_path = build_path_controls()with gr.Accordion("DLSS 5 Neural Rendering Settings", open=True):neural = build_neural_controls(settings)with gr.Accordion("DLSS 5 Settings", open=True):@@ -254,11 +267,7 @@ def build_image_tab(settings: UISettings) -> ImageTab: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")+ zip_download = gr.DownloadButton("Save as ZIP", visible=False)status = gr.Textbox(label="Status", interactive=False, lines=5, max_lines=12)results = gr.Dataframe(headers=BATCH_HEADERS,@@ -266,8 +275,8 @@ def build_image_tab(settings: UISettings) -> ImageTab: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+ sources, input_gallery, input_actions, select_source, clear_source, neural, model_preset, output_format, quality, rename_mode,+ custom_suffix, render, stop, reset, output_gallery, zip_download, status, results)tab.input_path, tab.output_path = input_path, output_pathbind_image_events(tab)diff --git a/src/neural_rendering/ui.py b/src/neural_rendering/ui.pynew file mode 100644index 0000000..b6c3f65--- /dev/null+++ b/src/neural_rendering/ui.py@@ -0,0 +1,50 @@+from __future__ import annotations++from dataclasses import dataclass++import gradio as gr++from ..settings.models import UISettings+from .image.ui import ImageTab, build_image_tab+from .video.ui import VideoTab, build_video_tab+++MODE_CHOICES = ("Image", "Video")+++def mode_visibility(mode: str) -> tuple[dict, dict]:+ """Show one workflow while keeping both component trees alive."""+ show_video = mode == "Video"+ return gr.update(visible=not show_video), gr.update(visible=show_video)+++@dataclass(slots=True)+class NeuralRenderingTab:+ mode: object+ image: ImageTab+ video: VideoTab+ image_panel: object+ video_panel: object+++def build_neural_rendering_tab(settings: UISettings) -> NeuralRenderingTab:+ mode = gr.Radio(+ choices=list(MODE_CHOICES),+ value="Image",+ label="Mode",+ interactive=True,+ elem_id="neural-rendering-mode",+ )+ with gr.Column(visible=True, elem_id="neural-rendering-image") as image_panel:+ image_tab = build_image_tab(settings)+ with gr.Column(visible=False, elem_id="neural-rendering-video") as video_panel:+ video_tab = build_video_tab(settings)++ mode.change(+ mode_visibility,+ inputs=mode,+ outputs=[image_panel, video_panel],+ queue=False,+ show_progress="hidden",+ )+ return NeuralRenderingTab(mode, image_tab, video_tab, image_panel, video_panel)diff --git a/src/video/__init__.py b/src/neural_rendering/video/__init__.pysimilarity index 100%rename from src/video/__init__.pyrename to src/neural_rendering/video/__init__.pydiff --git a/src/video/batch.py b/src/neural_rendering/video/batch.pysimilarity index 93%rename from src/video/batch.pyrename to src/neural_rendering/video/batch.pyindex 2e62b2e..38ef354 100644--- a/src/video/batch.py+++ b/src/neural_rendering/video/batch.py@@ -6,11 +6,11 @@ from dataclasses import replacefrom pathlib import Pathfrom typing import Callable, Iterable-from ..core.batch_progress import BatchItemUpdate, BatchProgress-from ..core.disk_paths import prepare_output_dir-from ..core.jobs import Cancelled, JobController, active_job-from ..core.paths import LOGS-from ..core.runtime import prepare_runtime+from ...core.batch_progress import BatchItemUpdate, BatchProgress+from ...core.disk_paths import prepare_output_dir+from ...core.jobs import Cancelled, JobController, active_job+from ...core.paths import LOGS+from ...core.runtime import prepare_runtimefrom .models import ConversionOptions, VideoBatchResult, VideoConversionFailure, VideoConversionSuccessfrom . import processorfrom .reports import _write_video_batch_manifestdiff --git a/src/video/guides.py b/src/neural_rendering/video/guides.pysimilarity index 100%rename from src/video/guides.pyrename to src/neural_rendering/video/guides.pydiff --git a/src/video/models.py b/src/neural_rendering/video/models.pysimilarity index 95%rename from src/video/models.pyrename to src/neural_rendering/video/models.pyindex 8c229fe..36668e6 100644--- a/src/video/models.py+++ b/src/neural_rendering/video/models.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom dataclasses import dataclass-from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES+from ...core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES@dataclass(slots=True)diff --git a/src/video/preview.py b/src/neural_rendering/video/preview.pysimilarity index 93%rename from src/video/preview.pyrename to src/neural_rendering/video/preview.pyindex 574c50f..05da2bf 100644--- a/src/video/preview.py+++ b/src/neural_rendering/video/preview.py@@ -5,12 +5,12 @@ from pathlib import Pathimport gradio as gr-from ..core.ffmpeg.preview import (+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 ...settings.models import coerce_hdr_mode, parse_automatic_mask+from ...settings.storage import current_preview_encoding, processing_gpu_settingsfrom .models import ConversionOptionsfrom .processor import convert_video@@ -148,11 +148,13 @@ def first_video_path(paths: list[str] | str | None) -> str | None:def update_video_preview_mode(paths: list[str] | str | None):normalized = normalize_video_paths(paths)+ available = bool(normalized)single = len(normalized) == 1- input_value = normalized[0] if single else None+ input_value = normalized[0] if available else None+ input_label = "Input video preview" if len(normalized) <= 1 else f"Input video preview (first of {len(normalized)})"return (- gr.update(value=input_value, visible=single),- gr.update(value=None, visible=single),+ gr.update(value=input_value, visible=available, label=input_label),+ gr.update(value=None, visible=True),gr.update(visible=single),gr.update(visible=single),)diff --git a/src/video/processor.py b/src/neural_rendering/video/processor.pysimilarity index 97%rename from src/video/processor.pyrename to src/neural_rendering/video/processor.pyindex 39c3ce2..b52d5be 100644--- a/src/video/processor.py+++ b/src/neural_rendering/video/processor.py@@ -17,15 +17,14 @@ from typing import Callableimport avimport numpy as np-from ..core import ffmpeg-from ..core.dlss_architecture import apply_current_dlss_architecture-from ..core.gpu_selection import resolve_runtime_ai_gpu-from ..core.jobs import Cancelled, active_job-from ..core.naming import output_filename, validate_rename-from ..core.disk_paths import OutputFile, prepare_output_dir-from ..core.render_metadata import prepare_render_note-from ..core.paths import JOBS, LOGS, OUTPUTS-from ..core.runtime import (+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, validate_rename+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.render_metadata import prepare_render_note+from ...core.paths import JOBS, LOGS, OUTPUTS+from ...core.runtime import (DLSSFrameSession, prepare_runtime, resize_fit, rotate_frame, verify_feature_18,write_failure_report,)@@ -126,12 +125,6 @@ def convert_video(gpu: dict | None = resolve_runtime_ai_gpu(prepared_runtime.gpus, prepared_runtime.runtime_bundle, options.ai_gpu_uuid)- # Stage the selected DLSS Architecture NR build before the worker- # spawns (warn-and-continue: render proceeds with the current DLL).- try:- apply_current_dlss_architecture(gpu)- except Exception:- passvideo_gpu: dict | None = Noneruntime_bundle: dict | None = prepared_runtime.runtime_bundleencoder = None@@ -650,12 +643,13 @@ def convert_video("carrier_create_result": carrier_create_result,"successful_neural_rendering_frames": nr_count,"addon_release": runtime_bundle["addon"]["release"],+ "dlssnr_runtime": runtime_bundle["neural_runtime"],"loaded_module_inventory": ["host/nvngx.dll (standalone worker image)","host/dxgi.dll (ReShade carrier)",- "host/renodx-dlss5.addon64",+ "dlssnr/renodx-dlss5.addon64","dlss/nvngx_dlss.dll",- "host/nvngx_dlssnr.dll",+ "dlssnr/nvngx_dlssnr.dll","system D3D12/DXGI/NGX core",],"native_settings": native,diff --git a/src/video/reports.py b/src/neural_rendering/video/reports.pysimilarity index 96%rename from src/video/reports.pyrename to src/neural_rendering/video/reports.pyindex 027c738..0886adb 100644--- a/src/video/reports.py+++ b/src/neural_rendering/video/reports.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom dataclasses import asdict-from ..core.paths import LOGS+from ...core.paths import LOGSfrom .models import ConversionOptions, VideoConversionFailure, VideoConversionSuccessdef _write_video_batch_manifest(diff --git a/src/video/sizing.py b/src/neural_rendering/video/sizing.pysimilarity index 92%rename from src/video/sizing.pyrename to src/neural_rendering/video/sizing.pyindex 090a8b0..a1c3505 100644--- a/src/video/sizing.py+++ b/src/neural_rendering/video/sizing.py@@ -1,7 +1,7 @@from __future__ import annotations-from ..core import ffmpeg-from ..core.runtime import (+from ...core import ffmpeg+from ...core.runtime import (UPSCALING_MODES,resolve_native_settings, resolve_output_size, resolve_upscaling_mode,)diff --git a/src/video/ui.py b/src/neural_rendering/video/ui.pysimilarity index 87%rename from src/video/ui.pyrename to src/neural_rendering/video/ui.pyindex 3b8e99d..cbf292f 100644--- a/src/video/ui.py+++ b/src/neural_rendering/video/ui.py@@ -5,17 +5,21 @@ from dataclasses import dataclassfrom pathlib import Pathimport gradio as gr-from ..core.batch_ui import BATCH_HEADERS, bind_batch_ui, build_path_controls+from ...core.batch_ui import (+ BATCH_HEADERS, bind_batch_ui, build_media_clear_button, build_media_select_button,+ build_path_controls,+)+from ...core.disk_paths import create_media_archive-from ..core.ffmpeg import hdr_mode_supported-from ..core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview-from ..core.naming import RENAME_MODES-from ..core.runtime import DLSS_MODEL_PRESETS, NR_PRESETS, NR_STYLES, UPSCALING_MODES-from ..settings.models import (+from ...core.ffmpeg import hdr_mode_supported+from ...core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview+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 ...settings.storage import current_preview_encoding, processing_gpu_settingsfrom .batch import convert_videosfrom .models import ConversionOptionsfrom .preview import (@@ -138,7 +142,7 @@ def render_video_batch(custom_suffix: str,progress=gr.Progress(track_tqdm=False),*, output_dir=None, controller=None, on_item_update=None, direct_disk=False,-) -> tuple[object, list[str], list[list[str]], str]:+) -> tuple[object, str | None, list[list[str]], str]:paths = normalize_video_paths(input_paths)if not paths:raise gr.Error("Choose at least one video first.")@@ -173,7 +177,7 @@ def render_video_batch(traceback.print_exc()if on_item_update is not None:raise- return gr.update(value=None, visible=len(paths) == 1), [], [], f"Failed: {exc}"+ return gr.update(value=None, visible=not direct_disk), None, [], f"Failed: {exc}"ordered_rows: list[tuple[int, list[str]]] = []for item in result.successes:@@ -204,7 +208,6 @@ def render_video_batch((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:@@ -234,12 +237,23 @@ def render_video_batch(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=not direct_disk and len(paths) == 1), ([] if direct_disk else files), rows, status+ archive_path = None+ if not direct_disk and not result.cancelled:+ archive_path = create_media_archive(+ (item.result.output_path for item in result.successes),+ output_dir,+ "DLSS5_VIDEO_BATCH",+ controller=controller,+ )+ return gr.update(value=output_preview, visible=not direct_disk), archive_path, rows, status@dataclass(slots=True)class VideoTab:sources: objectinput_preview: object+ input_actions: object+ select_source: object+ clear_source: objectneural: list[object]model_preset: objectquality: object@@ -254,7 +268,7 @@ class VideoTab:stop: objectreset: objectoutput_video: object- output_files: object+ zip_download: objectstatus: objectresults: objectinput_path: object = None@@ -289,9 +303,18 @@ def build_video_tab(settings: UISettings) -> VideoTab:sources = gr.File(label="Input video(s)", file_count="multiple", file_types=["video"],type="filepath", allow_reordering=True, elem_id="video-upload-list",+ elem_classes=["media-upload-surface"],)- input_path, output_path = build_path_controls()input_preview = gr.Video(label="Input video preview", interactive=False, visible=False)+ with gr.Row(+ visible=False, elem_id="video-input-actions",+ elem_classes=["media-input-actions"],+ ) as input_actions:+ select_source = build_media_select_button(+ "Choose Videos", ["video"], "video-select-input",+ )+ clear_source = build_media_clear_button("video-clear-input")+ input_path, output_path = build_path_controls()with gr.Accordion("DLSS 5 Neural Rendering Settings", open=True):neural = build_neural_controls(settings)with gr.Accordion("DLSS 5 Settings", open=True):@@ -328,11 +351,10 @@ def build_video_tab(settings: UISettings) -> VideoTab: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",+ output_video = gr.Video(+ label="Output video", interactive=False, visible=True, height=520,)+ zip_download = gr.DownloadButton("Save as ZIP", visible=False)status = gr.Textbox(label="Status", interactive=False, lines=5, max_lines=12)results = gr.Dataframe(headers=BATCH_HEADERS,@@ -340,9 +362,9 @@ def build_video_tab(settings: UISettings) -> VideoTab:label="Batch results", wrap=True,)tab = VideoTab(- sources, input_preview, neural, model_preset, quality, codec, container, rename_mode,+ sources, input_preview, input_actions, select_source, clear_source, neural, model_preset, quality, codec, container, rename_mode,custom_suffix, hdr_mode, preview_frame, preview, render, stop, reset, output_video,- output_files, status, results+ zip_download, status, results)tab.input_path, tab.output_path = input_path, output_pathbind_video_events(tab)diff --git a/src/settings/models.py b/src/settings/models.pyindex f9b7c86..d43daef 100644--- a/src/settings/models.py+++ b/src/settings/models.py@@ -1,175 +1,208 @@-from __future__ import annotations--from dataclasses import dataclass, replace--from ..core.dlss_architecture import DLSS_ARCHITECTURE_CHOICES+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 validate_rename-from ..core.runtime import 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")-+from ..core.naming import validate_rename+from ..core.runtime import resolve_native_settings, resolve_upscaling_mode+from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES+from .migration import _migrate_codec+from ..upscale.video.models import options_from_settings+from ..upscale.image.models import options_from_settings as image_upscale_options++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)+UPSCALE_MODE_CHOICES = ("Image", "Video")+++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"+ 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"- dlss_architecture: 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,+ upscale_mode: str = "Image"+ upscale_image_vsr_quality: int = 4+ upscale_image_size_mode: str = "Scale factor"+ upscale_image_scale_factor: float = 2.0+ upscale_image_width: int = 3840+ upscale_image_height: int = 2160+ upscale_image_aspect_lock: bool = True+ upscale_image_output_format: str = "PNG"+ upscale_image_quality: int = 95+ upscale_image_preserve_metadata: bool = True+ upscale_image_rename_mode: str = "Auto"+ upscale_image_custom_suffix: str = "_RTXIMAGE"+ upscale_vsr_enabled: bool = True+ upscale_vsr_quality: int = 4+ upscale_size_mode: str = "Scale factor"+ upscale_scale_factor: float = 2.0+ upscale_width: int = 3840+ upscale_height: int = 2160+ upscale_aspect_lock: bool = True+ upscale_hdr_enabled: bool = False+ upscale_hdr_contrast: int = 100+ upscale_hdr_saturation: int = 100+ upscale_hdr_middle_gray: int = 50+ upscale_hdr_peak_luminance: int = 1000+ upscale_hdr_precision: str = "Packed 10-bit"+ upscale_codec: str = "H.265 (NVIDIA NVENC)"+ upscale_container: str = "MP4"+ upscale_quality: str = "Auto (Default)"+ upscale_rename_mode: str = "Auto"+ upscale_custom_suffix: str = "_RTXVIDEO"++ 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:+ options_from_settings(settings).validate(for_render=False)+ image_upscale_options(settings).validate(for_render=False)+ 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,+ ),+ "Upscale mode": (+ settings.upscale_mode,+ UPSCALE_MODE_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,- ),- "DLSS Architecture": (- settings.dlss_architecture,- DLSS_ARCHITECTURE_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+ }+ 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 settingsdiff --git a/src/settings/presets.py b/src/settings/presets.pyindex fd83487..e805380 100644--- a/src/settings/presets.py+++ b/src/settings/presets.py@@ -10,7 +10,7 @@ from pathlib import Pathfrom typing import Anyfrom .models import (- MAX_PRESET_BYTES, PRESET_FORMAT, PRESET_SCHEMA_VERSION, UISettings, _validate,+ DEFAULT_SETTINGS, MAX_PRESET_BYTES, PRESET_FORMAT, PRESET_SCHEMA_VERSION, UISettings, _validate,)_WINDOWS_RESERVED_NAMES = {@@ -137,5 +137,12 @@ def import_settings_preset(for key, value in imported.items()if key in known_names}+ # Presets created before the Upscale tab get its defaults independently of+ # whichever RTX settings happen to be selected when the preset is imported.+ for key in known_names:+ if key.startswith("upscale_") and key not in changes:+ changes[key] = getattr(DEFAULT_SETTINGS, key)+ if changes.get("upscale_vsr_quality") == 0:+ changes["upscale_vsr_quality"] = DEFAULT_SETTINGS.upscale_vsr_qualitymerged = replace(current, **changes)return name, _validate(merged)diff --git a/src/settings/storage.py b/src/settings/storage.pyindex 5a4b0ed..5076e14 100644--- a/src/settings/storage.py+++ b/src/settings/storage.py@@ -1,292 +1,320 @@-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 __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_codecfrom .models import (CODEC_CHOICES, CONFIG_SECTION, CONTAINER_CHOICES, DEFAULT_SETTINGS, IMAGE_FORMAT_CHOICES,- PREVIEW_ENCODING_CHOICES, QUALITY_CHOICES, UISettings, _validate,+ PREVIEW_ENCODING_CHOICES, QUALITY_CHOICES, UPSCALE_MODE_CHOICES, UISettings, _validate,)-from ..core.dlss_architecture import DLSS_ARCHITECTURE_CHOICES--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+from ..upscale.video.models import SETTING_FIELDS, options_from_settings+from ..upscale.image.models import SETTING_FIELDS as IMAGE_UPSCALE_FIELDS, options_from_settings as image_upscale_options++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,+ ),+ upscale_mode=choice(+ "upscale_mode",+ UPSCALE_MODE_CHOICES,+ DEFAULT_SETTINGS.upscale_mode,),- 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,- ),- dlss_architecture=choice(- "dlss_architecture",- DLSS_ARCHITECTURE_CHOICES,- DEFAULT_SETTINGS.dlss_architecture,- ),- )- # 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] = {+ )+ # 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+ upscale_values = {}+ for prefix, names, factory in (("upscale_", SETTING_FIELDS, options_from_settings),+ ("upscale_image_", IMAGE_UPSCALE_FIELDS, image_upscale_options)):+ for name in names:+ key = prefix + name+ default = getattr(DEFAULT_SETTINGS, key)+ raw = section.get(key)+ if raw is None:+ continue+ try:+ if isinstance(default, bool):+ value = boolean(key, default)+ elif isinstance(default, int):+ value = int(raw)+ elif isinstance(default, float):+ value = float(raw)+ else:+ value = str(raw)+ if name == "vsr_quality" and value == 0:+ value = default+ candidate = replace(settings, **upscale_values, **{key: value})+ factory(candidate).validate(for_render=False)+ upscale_values[key] = value+ except (ValueError, TypeError, OverflowError):+ continue+ return replace(settings, **upscale_values)+++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] = {+ **{"upscale_image_" + name: str(getattr(settings, "upscale_image_" + name)) for name in IMAGE_UPSCALE_FIELDS},+ **{"upscale_" + name: str(getattr(settings, "upscale_" + name)) for name in SETTING_FIELDS},+ "upscale_mode": settings.upscale_mode,"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,- "dlss_architecture": settings.dlss_architecture,+ "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)++ 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.pyindex 452346f..3995830 100644--- a/src/settings/ui.py+++ b/src/settings/ui.py@@ -1,615 +1,633 @@-from __future__ import annotations--from dataclasses import dataclass, replace--import gradio as gr--from ..core.dlss_architecture import apply_dlss_architecture+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 UPSCALING_MODES, prepare_runtime-from ..core.ffmpeg.preview import normalize_preview_encoding+from ..core.gpu_selection import gpu_choice_label+from ..core.paths import CONFIG_PATH+from ..core.runtime import UPSCALING_MODES, prepare_runtime+from ..core.ffmpeg.preview import normalize_preview_encodingfrom .models import (- DEFAULT_SETTINGS, DLSS_ARCHITECTURE_CHOICES,- PREVIEW_ENCODING_CHOICES, UISettings,+ DEFAULT_SETTINGS, PREVIEW_ENCODING_CHOICES, UPSCALE_MODE_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 _mirrored_dlss_values(settings: UISettings) -> tuple:- """Shared 9-tuple twice: feeds two sibling tabs' neural controls."""- shared = _shared_dlss_values(settings)- return (*shared, *shared)---def _notify_live_effects(settings: UISettings) -> None:- # Call while holding _CONFIG_LOCK: submissions follow the saved commit- # order, including imports/resets. This only enqueues an immutable snapshot.- from ..live.pipeline import update_live_effects-- update_live_effects(settings)---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:- 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- _notify_live_effects(settings)- return _mirrored_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:- 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- _notify_live_effects(settings)- return _mirrored_dlss_values(settings)---def persist_live_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,-) -> tuple:- 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,- )- if settings != current:- save_settings(CONFIG_PATH, settings)+from .presets import export_settings_preset, import_settings_preset, preset_filename+from .storage import SETTINGS_STATE, load_settings, save_settings+from ..upscale.video.models import SETTING_FIELDS, UpscaleOptions+from ..upscale.image.models import SETTING_FIELDS as IMAGE_UPSCALE_FIELDS, ImageUpscaleOptions++_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 _mirrored_dlss_values(settings: UISettings) -> tuple:+ """Shared 9-tuple twice: feeds the Image and Video mode controls."""+ shared = _shared_dlss_values(settings)+ return (*shared, *shared)+++def _notify_live_effects(settings: UISettings) -> None:+ # Call while holding _CONFIG_LOCK: submissions follow the saved commit+ # order, including imports/resets. This only enqueues an immutable snapshot.+ from ..live.pipeline import update_live_effects++ update_live_effects(settings)+++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:+ 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+ _notify_live_effects(settings)+ return _mirrored_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:+ 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+ _notify_live_effects(settings)+ return _mirrored_dlss_values(settings)+++def persist_live_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,+) -> tuple:+ 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,+ )+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ SETTINGS_STATE.current = settings+ _notify_live_effects(settings)+ return _mirrored_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 persist_upscale_settings(*values) -> None:+ chosen = dict(zip(SETTING_FIELDS, values))+ if not hdr_mode_supported(chosen["codec"]):+ chosen["hdr_enabled"] = False+ options = UpscaleOptions(**chosen)+ options.validate(for_render=False)+ defaults = UpscaleOptions()+ for name in SETTING_FIELDS:+ if type(getattr(defaults, name)) is int:+ chosen[name] = int(chosen[name])+ chosen["scale_factor"] = float(chosen["scale_factor"])+ with _CONFIG_LOCK:+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)+ settings = replace(current, **{"upscale_" + name: value for name, value in chosen.items()})+ if settings != current:+ save_settings(CONFIG_PATH, settings)+ SETTINGS_STATE.current = settings+++def persist_image_upscale_settings(*values) -> None:+ chosen = dict(zip(IMAGE_UPSCALE_FIELDS, values))+ ImageUpscaleOptions(**chosen).validate()+ defaults = ImageUpscaleOptions()+ for name in IMAGE_UPSCALE_FIELDS:+ if type(getattr(defaults, name)) is int:+ chosen[name] = int(chosen[name])+ chosen["scale_factor"] = float(chosen["scale_factor"])+ with _CONFIG_LOCK:+ current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)+ settings = replace(current, **{"upscale_image_" + n: v for n, v in chosen.items()})+ if settings != current:+ save_settings(CONFIG_PATH, settings)SETTINGS_STATE.current = settings- _notify_live_effects(settings)- return _mirrored_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:+def persist_upscale_mode(mode: str) -> None:+ if mode not in UPSCALE_MODE_CHOICES:+ raise gr.Error(f"Upscale mode must be one of: {', '.join(UPSCALE_MODE_CHOICES)}.")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,- )+ settings = replace(current, upscale_mode=mode)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 (+++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,*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,- settings.dlss_architecture,- *shared,- )---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_dlss_architecture(dlss_architecture: str) -> None:- if not isinstance(dlss_architecture, str) or dlss_architecture not in DLSS_ARCHITECTURE_CHOICES:- raise gr.Error(- f"DLSS Architecture must be one of: {', '.join(DLSS_ARCHITECTURE_CHOICES)}."- )- with _CONFIG_LOCK:- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)- settings = replace(current, dlss_architecture=dlss_architecture)- if settings != current:- save_settings(CONFIG_PATH, settings)- SETTINGS_STATE.current = settings- # A Live worker may be between replacements. Pin its runtime for the- # entire session, including that brief interval with no DLL loaded.- from ..live.pipeline import is_live_running- if is_live_running():- return- # Swap the host NR runtime immediately so the next render uses it.- # Failures only warn (logged); the saved setting still applies later.- try:- prepared = prepare_runtime()- apply_dlss_architecture(settings.dlss_architecture, prepared.gpu)- except Exception:- pass--+ settings.upscale_mode,+ *(getattr(settings, "upscale_" + name) for name in SETTING_FIELDS),+ *(getattr(settings, "upscale_image_" + name) for name in IMAGE_UPSCALE_FIELDS),+ )+++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- _notify_live_effects(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- _notify_live_effects(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)+ 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+ _notify_live_effects(DEFAULT_SETTINGS)+ message = "All Neural Rendering, Upscale, and Frame Interpolation settings were reset to defaults."+ return (+ *_settings_component_values(DEFAULT_SETTINGS),+ message,+ message,+ 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+ _notify_live_effects(imported)+ return (+ name,+ *_settings_component_values(imported),+ f"Imported preset {name!r}; all modes, tabs, and saved startup settings were updated."+ + (f" {gpu_warning}" if gpu_warning else ""),+ )++@dataclass(slots=True)class SettingsTab:ai_gpu_selector: objectvideo_gpu_selector: objectpreview_encoding_selector: object- architecture_selector: objectpreset_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."- ),- )+ 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, RTX Video, 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 DLSS Neural Rendering, RTX Video, and Frame Generation.",+ )+ 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 Neural Rendering's Video mode, "+ "Upscale, and Frame Interpolation (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(- "## DLSS 5 Architecture\n"- "Selects which Neural Rendering runtime build is used for Image, Video, "- "and Frame Interpolation. Auto picks from the AI Processing GPU: "- "RTX 20/30 uses Turing+, RTX 40 uses Ada Lovelace+, RTX 50 uses Blackwell+. "- "Takes effect on the next render."- )- architecture_selector = gr.Dropdown(- choices=list(DLSS_ARCHITECTURE_CHOICES),- value=settings.dlss_architecture,- label="DLSS 5 Architecture",- info="Auto, Turing and higher, Ada Lovelace and higher, or Blackwell and higher.",- )- 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")+ "## Settings Presets\n"+ "Export every adjustable option from Neural Rendering's Image and Video modes, "+ "Upscale, and Frame Interpolation, 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,- architecture_selector,preset_name, preset_export, preset_import, preset_status- )----def settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab, live_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,+ )++++def settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab, live_tab, upscale_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,- settings_tab.architecture_selector,*live_tab.neural,live_tab.model_preset,- ]---def bind_settings_events(settings_tab, image_tab, video_tab, frame_tab, live_tab) -> None:- video_mirror = [*video_tab.neural, video_tab.model_preset]- image_mirror = [*image_tab.neural, image_tab.model_preset]- live_mirror = [*live_tab.neural, live_tab.model_preset]- for component in image_tab.settings_inputs:- component.input(- persist_image_settings,- inputs=image_tab.settings_inputs,- outputs=[*video_mirror, *live_mirror],- queue=False,- )- for component in video_tab.settings_inputs:- component.input(- persist_video_settings,- inputs=video_tab.settings_inputs,- outputs=[*image_mirror, *live_mirror],- queue=False,- )- for component in live_tab.settings_inputs:- component.input(- persist_live_settings,- inputs=live_tab.settings_inputs,- outputs=[*image_mirror, *video_mirror],- 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, live_tab)- settings_tab.preset_export.click(- settings_preset_export_status,- inputs=settings_tab.preset_name,- outputs=settings_tab.preset_status,+ upscale_tab.mode,+ *upscale_tab.video.settings_inputs,+ *upscale_tab.image.settings_inputs,+ ]+++def bind_settings_events(settings_tab, image_tab, video_tab, frame_tab, live_tab, upscale_tab) -> None:+ video_mirror = [*video_tab.neural, video_tab.model_preset]+ image_mirror = [*image_tab.neural, image_tab.model_preset]+ live_mirror = [*live_tab.neural, live_tab.model_preset]+ for component in image_tab.settings_inputs:+ component.input(+ persist_image_settings,+ inputs=image_tab.settings_inputs,+ outputs=[*video_mirror, *live_mirror],+ queue=False,+ )+ for component in video_tab.settings_inputs:+ component.input(+ persist_video_settings,+ inputs=video_tab.settings_inputs,+ outputs=[*image_mirror, *live_mirror],+ queue=False,+ )+ for component in live_tab.settings_inputs:+ component.input(+ persist_live_settings,+ inputs=live_tab.settings_inputs,+ outputs=[*image_mirror, *video_mirror],+ queue=False,+ )+ for component in frame_tab.settings_inputs:+ component.input(+ persist_frame_interpolation_settings,+ inputs=frame_tab.settings_inputs,+ queue=False,+ )++ for component in upscale_tab.video.settings_inputs:+ component.change(persist_upscale_settings, inputs=upscale_tab.video.settings_inputs, queue=False, show_progress="hidden")+ for component in upscale_tab.image.settings_inputs:+ component.change(persist_image_upscale_settings, inputs=upscale_tab.image.settings_inputs, queue=False, show_progress="hidden")+ upscale_tab.mode.input(+ persist_upscale_mode,+ inputs=upscale_tab.mode,queue=False,+ show_progress="hidden",)- 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,- )- settings_tab.architecture_selector.input(- persist_dlss_architecture,- inputs=settings_tab.architecture_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)+ outputs = settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab, live_tab, upscale_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, upscale_tab.video.status, upscale_tab.image.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)+ upscale_tab.video.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)+ upscale_tab.image.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)diff --git a/src/upscale/__init__.py b/src/upscale/__init__.pynew file mode 100644index 0000000..34e3689--- /dev/null+++ b/src/upscale/__init__.py@@ -0,0 +1,14 @@+"""NVIDIA RTX Super Resolution workflows for images and videos."""+++def __getattr__(name):+ if name in {"upscale_image", "upscale_images", "ImageUpscaleOptions", "ImageUpscaleResult", "ImageUpscaleBatchResult"}:+ from . import image+ return getattr(image, name)+ if name == "upscale_video":+ from .video.processor import upscale_video+ return upscale_video+ if name == "upscale_videos":+ from .video.batch import upscale_videos+ return upscale_videos+ raise AttributeError(name)diff --git a/src/upscale/image/__init__.py b/src/upscale/image/__init__.pynew file mode 100644index 0000000..4a7506b--- /dev/null+++ b/src/upscale/image/__init__.py@@ -0,0 +1,12 @@+"""RTX VSR still-image API."""+from .models import ImageUpscaleOptions, ImageUpscaleResult, ImageUpscaleBatchResult, ImageUpscaleFailure+++def __getattr__(name):+ if name == "upscale_image":+ from .processor import upscale_image+ return upscale_image+ if name == "upscale_images":+ from .batch import upscale_images+ return upscale_images+ raise AttributeError(name)diff --git a/src/upscale/image/batch.py b/src/upscale/image/batch.pynew file mode 100644index 0000000..33d4387--- /dev/null+++ b/src/upscale/image/batch.py@@ -0,0 +1,66 @@+from __future__ import annotations++import json+import time+import uuid+from dataclasses import asdict, replace+from pathlib import Path++from ...core.batch_progress import BatchProgress+from ...core.disk_paths import prepare_output_dir+from ...core.jobs import Cancelled, JobController, active_job+from ...core.paths import LOGS+from ..video.native import probe_capabilities+from .models import ImageUpscaleOptions, ImageUpscaleBatchResult, ImageUpscaleFailure+from .processor import upscale_image+++def upscale_images(input_paths, options=None, progress=None, *, output_dir=None, controller=None,+ on_item_update=None, generate_previews=True):+ options = replace(options) if options else ImageUpscaleOptions()+ options.validate()+ paths = [Path(p).resolve() for p in input_paths]+ if not paths:+ raise ValueError("Choose at least one image.")+ controller = controller or JobController()+ reporter = BatchProgress(paths, on_item_update, progress)+ successes, failures = [], []+ try:+ destination = prepare_output_dir(output_dir)+ with active_job(controller):+ if controller.cancel.is_set():+ raise Cancelled("Stopped before rendering.")+ caps = probe_capabilities(options.ai_gpu_uuid, controller=controller)+ for i, path in enumerate(paths):+ if controller.cancel.is_set():+ break+ reporter.advance(i)+ try:+ result = upscale_image(path, options, lambda v, m, i=i: reporter.advance(i, v, m),+ output_dir=destination, controller=controller, _owns_slot=True,+ _capabilities=caps, generate_previews=generate_previews)+ except Exception as exc:+ cancelled = controller.cancel.is_set() or isinstance(exc, Cancelled)+ failures.append(ImageUpscaleFailure(i, str(path), str(exc), cancelled))+ reporter.fail(i, exc, cancelled=cancelled)+ if cancelled:+ controller.stop()+ break+ else:+ successes.append(result)+ reporter.complete(i, result.output_path, "; ".join([*result.warnings, f"Report: {result.report_path}"]))+ if controller.cancel.is_set():+ for item in reporter.items:+ if item.state == "Queued":+ failures.append(ImageUpscaleFailure(item.index, item.input_path, "Cancelled before rendering.", True))+ reporter.skip_from(0)+ LOGS.mkdir(exist_ok=True)+ manifest = LOGS / f"upscale-image-batch-{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:8]}.json"+ result = ImageUpscaleBatchResult(successes, failures, controller.cancel.is_set(), str(manifest))+ manifest.write_text(json.dumps({**asdict(result), "options": asdict(options),+ "progress": reporter.diagnostics(final=True)}, indent=2), encoding="utf-8")+ reporter.finish(cancelled=result.cancelled, manifest_path=str(manifest))+ return result+ except BaseException as exc:+ reporter.finish(cancelled=controller.cancel.is_set(), error=str(exc))+ raisediff --git a/src/upscale/image/models.py b/src/upscale/image/models.pynew file mode 100644index 0000000..4e41030--- /dev/null+++ b/src/upscale/image/models.py@@ -0,0 +1,95 @@+from __future__ import annotations++import math+from dataclasses import dataclass, field, fields++from ..video.models import SCALE_FACTORS, SIZE_MODES, TEXTURE_LIMIT, VSR_QUALITIES, UpscaleOptions+from ...core.naming import validate_rename+from ...neural_rendering.image.models import IMAGE_FORMATS, IMAGE_EXTENSIONS+++@dataclass(slots=True)+class ImageUpscaleOptions:+ vsr_quality: int = 4+ size_mode: str = "Scale factor"+ scale_factor: float = 2.0+ width: int = 3840+ height: int = 2160+ aspect_lock: bool = True+ output_format: str = "PNG"+ quality: int = 95+ preserve_metadata: bool = True+ rename_mode: str = "Auto"+ custom_suffix: str = "_RTXIMAGE"+ ai_gpu_uuid: str = "auto"++ def validate(self, *, for_render: bool = True):+ for name, low, high in (("vsr_quality", 1, 4), ("width", 1, TEXTURE_LIMIT),+ ("height", 1, TEXTURE_LIMIT), ("quality", 1, 100)):+ value = getattr(self, name)+ if (isinstance(value, bool) or not isinstance(value, (int, float)) or+ not math.isfinite(value) or int(value) != value or not low <= value <= high):+ raise ValueError(f"{name} must be an integer from {low} to {high}.")+ if (isinstance(self.scale_factor, bool) or not isinstance(self.scale_factor, (int, float)) or+ not math.isfinite(self.scale_factor) or self.scale_factor < 1):+ raise ValueError("Scale factor must be a finite number of at least 1.")+ if self.size_mode not in SIZE_MODES or self.output_format not in IMAGE_FORMATS:+ raise ValueError("Unknown image sizing mode or output format.")+ if not isinstance(self.aspect_lock, bool) or not isinstance(self.preserve_metadata, bool):+ raise ValueError("Aspect lock and metadata preservation must be on or off.")+ validate_rename(self.rename_mode, self.custom_suffix)++ def native_options(self):+ # Only frame processing settings cross into the existing worker protocol.+ return UpscaleOptions(vsr_quality=int(self.vsr_quality), ai_gpu_uuid=self.ai_gpu_uuid)+++SETTING_FIELDS = tuple(f.name for f in fields(ImageUpscaleOptions) if f.name != "ai_gpu_uuid")+++def options_from_settings(settings):+ return ImageUpscaleOptions(**{n: getattr(settings, "upscale_image_" + n) for n in SETTING_FIELDS},+ ai_gpu_uuid=settings.ai_gpu_uuid)+++def output_size(width, height, options):+ options.validate()+ if min(width, height) < 1 or max(width, height) > TEXTURE_LIMIT:+ raise ValueError("Input dimensions must be between 1 and 16384 pixels.")+ if options.size_mode == "Scale factor":+ w, h = width * options.scale_factor, height * options.scale_factor+ else:+ w = options.width+ h = w * height / width if options.aspect_lock else options.height+ if not math.isfinite(w) or not math.isfinite(h) or max(w, h) > TEXTURE_LIMIT:+ raise ValueError("Requested output exceeds D3D11's 16384-pixel texture dimension.")+ if w < width or h < height:+ raise ValueError("Upscale output must not be smaller than the source.")+ return math.ceil(w), math.ceil(h)+++@dataclass(slots=True)+class ImageUpscaleResult:+ input_path: str+ output_path: str+ report_path: str+ output_width: int+ output_height: int+ elapsed_seconds: float+ warnings: list[str] = field(default_factory=list)+++@dataclass(slots=True)+class ImageUpscaleFailure:+ index: int+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(slots=True)+class ImageUpscaleBatchResult:+ successes: list[ImageUpscaleResult]+ failures: list[ImageUpscaleFailure]+ cancelled: bool+ manifest_path: strdiff --git a/src/upscale/image/processor.py b/src/upscale/image/processor.pynew file mode 100644index 0000000..5e5d03d--- /dev/null+++ b/src/upscale/image/processor.py@@ -0,0 +1,118 @@+from __future__ import annotations++import json+import time+import uuid+from contextlib import nullcontext, suppress+from dataclasses import asdict, replace+from pathlib import Path++import numpy as np+from PIL import Image++from ..video.native import RTXVideoSession, probe_capabilities+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.jobs import Cancelled, active_job+from ...core.naming import output_filename+from ...core.paths import LOGS+from ...neural_rendering.image.decoder import decode_image+from ...neural_rendering.image.encoder import _encode_image+from ...neural_rendering.image.models import ImageConversionOptions+from .models import IMAGE_EXTENSIONS, ImageUpscaleOptions, ImageUpscaleResult, output_size+++def srgb_to_worker(rgba):+ """The video pipeline uses BT.709 primaries with BT.470M (gamma 2.2) RGB."""+ rgb = rgba[..., :3].astype(np.float32) / 255+ linear = np.where(rgb <= .04045, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)+ packed = np.empty_like(rgba)+ packed[..., :3] = np.rint(np.clip(linear, 0, 1) ** (1 / 2.2) * 255).astype(np.uint8)+ packed[..., 3] = 255+ return np.ascontiguousarray(packed)+++def worker_to_srgb(data, width, height, alpha):+ rgba = np.frombuffer(data, dtype=np.uint8).reshape(height, width, 4).copy()+ linear = (rgba[..., :3].astype(np.float32) / 255) ** 2.2+ rgb = np.where(linear <= .0031308, linear * 12.92, 1.055 * linear ** (1 / 2.4) - .055)+ rgba[..., :3] = np.rint(np.clip(rgb, 0, 1) * 255).astype(np.uint8)+ with Image.fromarray(alpha) as mask:+ with mask.resize((width, height), Image.Resampling.LANCZOS) as scaled:+ rgba[..., 3] = np.asarray(scaled)+ return rgba+++def upscale_image(input_path, options=None, progress=None, *, output_dir=None, controller=None,+ generate_previews=True, _owns_slot=False, _capabilities=None):+ options = replace(options) if options else ImageUpscaleOptions()+ options.validate()+ source = Path(input_path).resolve()+ if not source.is_file():+ raise FileNotFoundError(source)+ with nullcontext(controller) if _owns_slot else active_job(controller) as controller:+ return _process(source, options, progress, output_dir, controller, generate_previews, _capabilities)+++def _process(source, options, progress, output_dir, controller, generate_previews, capabilities):+ started = time.monotonic()+ stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]+ LOGS.mkdir(exist_ok=True)+ report_path = LOGS / f"upscale-image-{stamp}.json"+ report = {"input": str(source), "options": asdict(options), "pipeline": "RTX VSR still image",+ "color": "sRGB → gamma 2.2 RGB → RTX VSR → sRGB"}+ destination_file = None+ session = None++ def update(value, message):+ if controller.cancel.is_set():+ raise Cancelled("Image upscale stopped by user.")+ if progress:+ progress(value, message)++ try:+ update(.01, "Decoding image")+ decoded = decode_image(source)+ height, width = decoded.rgba.shape[:2]+ ow, oh = output_size(width, height, options)+ caps = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)+ output = prepare_output_dir(output_dir) / output_filename(+ source, IMAGE_EXTENSIONS[options.output_format], options.rename_mode, options.custom_suffix,+ f"{source.stem}_RTXIMAGE_{stamp}")+ destination_file = OutputFile(output)+ report.update(input_dimensions=[width, height], output_dimensions=[ow, oh],+ capabilities=asdict(caps), decoder=decoded.decoder, warnings=decoded.warnings)+ update(.15, f"RTX VSR: {width}×{height} → {ow}×{oh}")+ with RTXVideoSession(width, height, ow, oh, options.native_options(), 1, caps, controller) as session:+ processed = worker_to_srgb(session.process_frame(srgb_to_worker(decoded.rgba)), ow, oh, decoded.alpha)+ if session.completed_frames != 1:+ raise RuntimeError("RTX VSR did not process exactly one image.")+ update(.80, "Saving image")+ export = ImageConversionOptions(output_format=options.output_format, quality=int(options.quality),+ preserve_metadata=options.preserve_metadata)+ warnings = list(decoded.warnings)+ warnings.extend(_encode_image(destination_file.temporary, processed, export, decoded.metadata,+ generate_preview=generate_previews, preview_path=output, controller=controller))+ with Image.open(destination_file.temporary) as saved:+ saved.load()+ if saved.size != (ow, oh):+ raise RuntimeError("Saved image dimensions do not match the VSR output.")+ update(.98, "Verifying output")+ report.update(status="success", output=str(output), warnings=warnings, sdk_evaluations=1,+ last_ngx_results=session.last_results, worker_log=list(session.logs),+ elapsed_seconds=time.monotonic() - started)+ report_path.write_text(json.dumps(report, indent=2, default=str), encoding="utf-8")+ destination_file.publish()+ return ImageUpscaleResult(str(source), str(output), str(report_path), ow, oh,+ time.monotonic() - started, warnings)+ except BaseException as exc:+ cancelled = controller.cancel.is_set() or isinstance(exc, Cancelled)+ report.update(status="cancelled" if cancelled else "failed", error=str(exc),+ worker_log=list(session.logs) if session else [], elapsed_seconds=time.monotonic() - started)+ with suppress(OSError):+ report_path.write_text(json.dumps(report, indent=2, default=str), encoding="utf-8")+ if cancelled and not isinstance(exc, Cancelled):+ raise Cancelled("Image upscale stopped by user.") from exc+ raise+ finally:+ if destination_file:+ destination_file.cleanup()diff --git a/src/upscale/image/ui.py b/src/upscale/image/ui.pynew file mode 100644index 0000000..8be6088--- /dev/null+++ b/src/upscale/image/ui.py@@ -0,0 +1,168 @@+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import gradio as gr++from ...core.batch_ui import (BATCH_HEADERS, bind_batch_ui, build_media_clear_button,+ build_media_select_button, build_path_controls)+from ...core.disk_paths import create_media_archive, resolve_inputs+from ...core.naming import RENAME_MODES+from ...neural_rendering.image.decoder import decode_image+from ...neural_rendering.image.encoder import take_image_preview+from ...neural_rendering.image.models import RAW_EXTENSIONS+from ...neural_rendering.image.ui import preview_input_images+from ...settings.storage import processing_gpu_settings+from .batch import upscale_images+from .models import (IMAGE_FORMATS, SCALE_FACTORS, SETTING_FIELDS, SIZE_MODES, VSR_QUALITIES,+ ImageUpscaleOptions, options_from_settings, output_size)+++def options_from_values(values):+ options = ImageUpscaleOptions(**dict(zip(SETTING_FIELDS, values)), ai_gpu_uuid=processing_gpu_settings()[0])+ options.validate()+ return options+++def render_image_batch(paths, *values, progress=None, output_dir=None, controller=None,+ on_item_update=None, direct_disk=False):+ result = upscale_images(paths, options_from_values(values), progress, output_dir=output_dir,+ controller=controller, on_item_update=on_item_update, generate_previews=not direct_disk)+ gallery = []+ if not direct_disk:+ for item in result.successes:+ preview = take_image_preview(item.output_path)+ if preview is not None:+ gallery.append((preview, Path(item.output_path).name))+ archive_path = None+ if not direct_disk and not result.cancelled:+ archive_path = create_media_archive(+ (item.output_path for item in result.successes),+ output_dir,+ "RTXVIDEO_IMAGE_BATCH",+ controller=controller,+ )+ return gallery, archive_path, [], str(result.manifest_path)+++def describe_size(paths, input_path, *values):+ if not paths and not str(input_path or "").strip():+ return ""+ try:+ options = options_from_values(values)+ sources = resolve_inputs(input_path, paths, "image")+ lines = []+ for path in sources[:8]:+ decoded = decode_image(path)+ h, w = decoded.rgba.shape[:2]+ ow, oh = output_size(w, h, options)+ lines.append(f"**{Path(path).name}**: {w}×{h} → **{ow}×{oh}**")+ if len(sources) > 8:+ lines.append(f"{len(sources)-8} more images; dimensions are calculated for each source.")+ return "\n\n".join(lines)+ except Exception as exc:+ return str(exc)+++def build_image_tab(settings):+ opts = options_from_settings(settings)+ upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]+ c = {}+ 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="upscale-image-upload-list",+ elem_classes=["media-upload-surface"])+ input_gallery = gr.Gallery(+ label="Input images", columns=3, height=520, object_fit="contain",+ visible=False, interactive=False, type="pil", buttons=["fullscreen"],+ elem_id="upscale-image-input-preview",+ )+ with gr.Row(visible=False, elem_classes=["media-input-actions"]) as input_actions:+ select_source = build_media_select_button(+ "Choose Images", upload_types, "upscale-image-select-input",+ )+ clear_source = build_media_clear_button("upscale-image-clear-input")+ input_path, output_path = build_path_controls()+ with gr.Accordion("RTX Video Super Resolution", open=True, elem_id="upscale-image-vsr-box"):+ c["vsr_quality"] = gr.Dropdown(VSR_QUALITIES, value=opts.vsr_quality, label="VSR quality")+ c["size_mode"] = gr.Radio(SIZE_MODES, value=opts.size_mode, label="Output sizing")+ c["scale_factor"] = gr.Dropdown(+ SCALE_FACTORS, value=opts.scale_factor, label="Scale factor",+ )+ with gr.Row(+ visible=opts.size_mode == "Custom dimensions",+ elem_id="upscale-image-custom-dimensions",+ ) as custom_dimensions_row:+ c["width"] = gr.Number(value=opts.width, minimum=1, maximum=16384, precision=0, label="Output width")+ c["height"] = gr.Number(value=opts.height, minimum=1, maximum=16384, precision=0, label="Output height")+ c["aspect_lock"] = gr.Checkbox(value=opts.aspect_lock, label="Lock aspect ratio", info="Custom width determines height for each image.")+ dimensions = gr.Markdown(visible=False, elem_id="upscale-image-dimensions")+ c["output_format"] = gr.Dropdown(IMAGE_FORMATS, value=opts.output_format, label="Output format")+ c["quality"] = gr.Slider(1, 100, value=opts.quality, step=1, precision=0, label="Image quality", info="Used for JPEG, WebP, and AVIF.")+ c["preserve_metadata"] = gr.Checkbox(value=opts.preserve_metadata, label="Preserve metadata")+ with gr.Row():+ c["rename_mode"] = gr.Radio(RENAME_MODES, value=opts.rename_mode, label="Rename")+ c["custom_suffix"] = gr.Textbox(value=opts.custom_suffix, label="Custom suffix", interactive=opts.rename_mode == "Custom")+ with gr.Row():+ render = gr.Button("Upscale 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="Upscaled images", columns=2, height=520, object_fit="contain",+ interactive=False, type="pil",+ buttons=["download", "download_all", "fullscreen"],+ elem_id="upscale-image-output-preview",+ )+ zip_download = gr.DownloadButton("Save as ZIP", visible=False)+ status = gr.Textbox(label="Status", interactive=False, lines=5)+ results = gr.Dataframe(headers=BATCH_HEADERS, datatype=["str"] * len(BATCH_HEADERS), interactive=False,+ label="Batch results", wrap=True)+ tab = SimpleNamespace(sources=sources, input_gallery=input_gallery, input_actions=input_actions,+ select_source=select_source, clear_source=clear_source, input_path=input_path,+ output_path=output_path, render=render, stop=stop, reset=reset, output_gallery=output_gallery,+ zip_download=zip_download, status=status, results=results,+ controls=c, settings_inputs=[c[n] for n in SETTING_FIELDS])+ tab.render_inputs = [sources, *tab.settings_inputs]+ bind_batch_ui(tab, render_image_batch, kind="image", preview_mode=preview_input_images)+ c["rename_mode"].change(lambda mode: gr.update(interactive=mode == "Custom"), inputs=c["rename_mode"], outputs=c["custom_suffix"], queue=False)++ def sizing_controls(mode, lock):+ custom = mode == "Custom dimensions"+ return (gr.update(visible=not custom), gr.update(visible=custom),+ gr.update(visible=custom), gr.update(visible=custom, interactive=not lock),+ gr.update(visible=custom))++ sizing_outputs = [c["scale_factor"], custom_dimensions_row, c["width"], c["height"], c["aspect_lock"]]+ for name in ("size_mode", "aspect_lock"):+ c[name].change(sizing_controls, inputs=[c["size_mode"], c["aspect_lock"]], outputs=sizing_outputs, queue=False)+ for component, update in zip(sizing_outputs, sizing_controls(opts.size_mode, opts.aspect_lock)):+ for key in ("visible", "interactive"):+ if key in update:+ setattr(component, key, update[key])+ def custom_dimensions(paths, path, mode, factor, width, lock, initialize=False):+ if mode != "Custom dimensions":+ return gr.skip(), gr.skip()+ try:+ decoded = decode_image(resolve_inputs(path, paths, "image")[0])+ h, w = decoded.rgba.shape[:2]+ options = (ImageUpscaleOptions(scale_factor=factor) if initialize else+ ImageUpscaleOptions(size_mode=mode, width=width, aspect_lock=True))+ ow, oh = output_size(w, h, options)+ return (ow if initialize else gr.skip()), (oh if lock or initialize else gr.skip())+ except Exception:+ return gr.skip(), gr.skip()++ size_inputs = [sources, input_path, c["size_mode"], c["scale_factor"], c["width"], c["aspect_lock"]]+ c["size_mode"].input(lambda *args: custom_dimensions(*args, initialize=True), inputs=size_inputs,+ outputs=[c["width"], c["height"]], queue=False)+ for component in (c["width"], c["aspect_lock"]):+ component.input(custom_dimensions, inputs=size_inputs, outputs=[c["width"], c["height"]], queue=False)+ for component in (sources, input_path, *[c[n] for n in ("size_mode", "scale_factor", "width", "height", "aspect_lock")]):+ component.change(lambda *args: gr.update(value=(text := describe_size(*args)), visible=bool(text)),+ inputs=[sources, input_path, *tab.settings_inputs], outputs=dimensions,+ queue=False, show_progress="hidden", trigger_mode="always_last")+ return tabdiff --git a/src/upscale/ui.py b/src/upscale/ui.pynew file mode 100644index 0000000..0d272c1--- /dev/null+++ b/src/upscale/ui.py@@ -0,0 +1,33 @@+from dataclasses import dataclass++import gradio as gr++from ..settings.models import UPSCALE_MODE_CHOICES+from .image.ui import build_image_tab+from .video.ui import build_upscale_tab as build_video_tab+++def mode_visibility(mode):+ return gr.update(visible=mode == "Image"), gr.update(visible=mode == "Video")+++@dataclass+class UpscaleTab:+ mode: object+ image: object+ video: object+ image_panel: object+ video_panel: object+++def build_upscale_tab(settings):+ selected_mode = settings.upscale_mode+ mode = gr.Radio(+ list(UPSCALE_MODE_CHOICES), value=selected_mode, label="Mode", elem_id="upscale-mode"+ )+ with gr.Column(visible=selected_mode == "Image", elem_id="upscale-image") as image_panel:+ image = build_image_tab(settings)+ with gr.Column(visible=selected_mode == "Video", elem_id="upscale-video") as video_panel:+ video = build_video_tab(settings)+ mode.change(mode_visibility, inputs=mode, outputs=[image_panel, video_panel], queue=False, show_progress="hidden")+ return UpscaleTab(mode, image, video, image_panel, video_panel)diff --git a/src/upscale/video/__init__.py b/src/upscale/video/__init__.pynew file mode 100644index 0000000..4d95032--- /dev/null+++ b/src/upscale/video/__init__.py@@ -0,0 +1 @@+"""RTX Video upscaling workflow."""diff --git a/src/upscale/video/batch.py b/src/upscale/video/batch.pynew file mode 100644index 0000000..588f274--- /dev/null+++ b/src/upscale/video/batch.py@@ -0,0 +1,63 @@+from __future__ import annotations++import json+import time+import uuid+from dataclasses import asdict, replace+from pathlib import Path++from ...core.batch_progress import BatchProgress+from ...core.disk_paths import prepare_output_dir+from ...core.jobs import Cancelled, JobController, active_job+from ...core.paths import LOGS+from .models import UpscaleOptions, UpscaleBatchResult, UpscaleSuccess, UpscaleFailure+from .native import probe_capabilities+from .processor import upscale_video+++def upscale_videos(input_paths, options=None, progress=None, *, output_dir=None, controller=None, on_item_update=None):+ options = replace(options) if options else UpscaleOptions()+ options.validate()+ paths = [Path(p).resolve() for p in input_paths]+ if not paths:+ raise ValueError("Choose at least one video.")+ controller = controller or JobController()+ reporter = BatchProgress(paths, on_item_update, progress)+ successes, failures = [], []+ try:+ destination = prepare_output_dir(output_dir)+ with active_job(controller):+ if controller.cancel.is_set():+ raise Cancelled("Stopped before rendering.")+ caps = probe_capabilities(options.ai_gpu_uuid, controller=controller)+ for i, path in enumerate(paths):+ if controller.cancel.is_set():+ break+ reporter.advance(i)+ try:+ result = upscale_video(path, options, lambda v, m, i=i: reporter.advance(i, v, m),+ output_dir=destination, controller=controller, _owns_slot=True, _capabilities=caps)+ except Exception as exc:+ cancelled = controller.cancel.is_set() or isinstance(exc, Cancelled)+ failures.append(UpscaleFailure(i, str(path), str(exc), cancelled))+ reporter.fail(i, exc, cancelled=cancelled)+ if cancelled:+ controller.stop(); break+ else:+ successes.append(UpscaleSuccess(i, str(path), result))+ reporter.complete(i, result.output_path, f"{result.frames} frames; report: {result.report_path}")+ if controller.cancel.is_set():+ for item in reporter.items:+ if item.state == "Queued":+ failures.append(UpscaleFailure(item.index, item.input_path, "Cancelled before rendering.", True))+ reporter.skip_from(0)+ LOGS.mkdir(exist_ok=True)+ manifest = LOGS / f"upscale-batch-{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:8]}.json"+ result = UpscaleBatchResult(successes, failures, controller.cancel.is_set(), str(manifest))+ manifest.write_text(json.dumps({**asdict(result), "options": asdict(options),+ "progress": reporter.diagnostics(final=True)}, indent=2), encoding="utf-8")+ reporter.finish(cancelled=result.cancelled, manifest_path=str(manifest))+ return result+ except BaseException as exc:+ reporter.finish(cancelled=controller.cancel.is_set(), error=str(exc))+ raisediff --git a/src/upscale/video/components.py b/src/upscale/video/components.pynew file mode 100644index 0000000..2a82c6c--- /dev/null+++ b/src/upscale/video/components.py@@ -0,0 +1,16 @@+from pathlib import Path++import gradio as gr+from gradio.data_classes import FileData+++class ManagedVideo(gr.Video):+ """The Upscale pipeline owns color conversion and preview encoding."""++ is_template = True++ def postprocess(self, value):+ # gr.Video otherwise silently converts HEVC/MOV/MKV to H.264, including+ # when Preview Encoding is Disabled. FileData still uses Gradio's normal+ # file validation/cache/serving path; only automatic encoding is omitted.+ return None if value is None else FileData(path=str(value), orig_name=Path(value).name)diff --git a/src/upscale/video/components.pyi b/src/upscale/video/components.pyinew file mode 100644index 0000000..00a948f--- /dev/null+++ b/src/upscale/video/components.pyi@@ -0,0 +1,22 @@+from pathlib import Path++import gradio as gr+from gradio.data_classes import FileData++from gradio.events import Dependency++class ManagedVideo(gr.Video):+ """The Upscale pipeline owns color conversion and preview encoding."""++ is_template = True++ def postprocess(self, value):+ # gr.Video otherwise silently converts HEVC/MOV/MKV to H.264, including+ # when Preview Encoding is Disabled. FileData still uses Gradio's normal+ # file validation/cache/serving path; only automatic encoding is omitted.+ return None if value is None else FileData(path=str(value), orig_name=Path(value).name)+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING+ from gradio.blocks import Block+ if TYPE_CHECKING:+ from gradio.components import Timer+ from gradio.components.base import Component\ No newline at end of filediff --git a/src/upscale/video/media.py b/src/upscale/video/media.pynew file mode 100644index 0000000..c0414ca--- /dev/null+++ b/src/upscale/video/media.py@@ -0,0 +1,217 @@+from __future__ import annotations++import math+import subprocess+import threading+from contextlib import suppress+from fractions import Fraction+from pathlib import Path++import av+import numpy as np++from ...core.ffmpeg.probe import _run_json+from ...core.jobs import BoundedLogBuffer, Cancelled, drain_bounded_text+from ...core.paths import FFMPEG, FFPROBE++HDR_TAGS = {"smpte2084", "arib-std-b67"}+++def positive_fraction(value, default=Fraction(1)):+ try:+ result = Fraction(str(value).replace(":", "/"))+ return result if result > 0 else default+ except (ValueError, ZeroDivisionError):+ return default+++class PipeReader:+ """Do not expose the Windows pipe's unusable seek method to libavformat."""+ def __init__(self, stream):+ self.stream = stream++ def read(self, size):+ return self.stream.read(size)+++class PipeWriter:+ def __init__(self, stream):+ self.stream = stream++ def write(self, data):+ view = memoryview(data)+ size = len(view)+ while view:+ n = self.stream.write(view)+ if not n:+ raise BrokenPipeError("Encoder pipe closed.")+ view = view[n:]+ return size++ def flush(self):+ self.stream.flush()+++def inspect_video(path: Path, controller=None, *, reject_hdr=False) -> dict:+ data = _run_json([str(FFPROBE), "-v", "error", "-select_streams", "v:0", "-show_streams",+ "-show_format", "-of", "json", str(path)], controller=controller)+ streams = data.get("streams") or []+ if not streams:+ raise ValueError("The selected file contains no video stream.")+ stream = streams[0]+ side = stream.get("side_data_list") or []+ hdr = stream.get("color_transfer") in HDR_TAGS or any("dovi" in str(s).lower() or "dolby vision" in str(s).lower() for s in side)+ if reject_hdr and hdr:+ raise ValueError("Existing HDR input is not supported by Upscale. Supply SDR footage; RTX Video HDR converts SDR to new HDR.")+ width, height = int(stream["width"]), int(stream["height"])+ rotation = int(next((s["rotation"] for s in side if "rotation" in s), (stream.get("tags") or {}).get("rotate", 0))) % 360+ if rotation not in (0, 90, 180, 270):+ raise ValueError("Upscale supports rotation metadata in multiples of 90 degrees.")+ raw_sar = stream.get("sample_aspect_ratio", "1:1")+ sar = positive_fraction(raw_sar)+ if rotation in (90, 270):+ width, height, sar = height, width, 1 / sar+ pixel_format = stream.get("pix_fmt", "yuv420p")+ depth = max(c.bits for c in av.VideoFormat(pixel_format).components)+ rate = positive_fraction(stream.get("avg_frame_rate"),+ positive_fraction(stream.get("r_frame_rate"), Fraction(30)))+ origin = float(data.get("format", {}).get("start_time") or stream.get("start_time") or 0)+ return {"stream": stream, "hdr": hdr, "depth": depth, "rotation": rotation,+ "source_width": width, "source_height": height, "sar": sar,+ "width": math.ceil(width * sar / 2) * 2, "height": math.ceil(height / 2) * 2,+ "rate": rate, "duration": float(data.get("format", {}).get("duration") or stream.get("duration") or 0),+ "origin": origin, "frames": int(stream.get("nb_frames") or 0) if str(stream.get("nb_frames", "0")).isdigit() else 0}+++def decode_filter(meta: dict) -> tuple[str, list[str]]:+ s = meta["stream"]+ sd = int(s["height"]) <= 576+ fallback = "bt470bg" if int(s["height"]) == 576 else "smpte170m" if sd else "bt709"+ assumptions = []+ def color(key, default):+ v = s.get(key)+ if not v or v in ("unknown", "unspecified", "reserved"):+ assumptions.append(f"Unspecified {key}: assumed {default}.")+ return default+ return v+ matrix = color("color_space", "gbr" if av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else fallback)+ primaries = color("color_primaries", fallback)+ transfer = color("color_transfer", "bt709")+ range_in = "full" if s.get("color_range") == "pc" or av.VideoFormat(s.get("pix_fmt", "yuv420p")).is_rgb else "limited"+ planar = "gbrp10le" if meta["depth"] > 8 else "gbrp"+ # Planar 10-bit has a stable NUT tag across bundled FFmpeg/PyAV versions.+ # Some releases disagree on the packed x2bgr10 tag (decoded as rgb555).+ packed = "gbrp10le" if meta["depth"] > 8 else "rgba"+ filters = [f"zscale=matrixin={matrix}:primariesin={primaries}:transferin={transfer}:rangein={range_in}:matrix=gbr:primaries=bt709:transfer=bt470m:range=full", f"format={planar}"]+ if meta["rotation"] == 90:+ filters.append("transpose=cclock")+ elif meta["rotation"] == 270:+ filters.append("transpose=clock")+ elif meta["rotation"] == 180:+ filters += ["hflip", "vflip"]+ filters += [f"scale={meta['width']}:{meta['height']}:flags=lanczos", "setsar=1", f"format={packed}", f"setpts=PTS-({meta['origin']:.9f})/TB"]+ if meta["depth"] > 10:+ assumptions.append("Source precision converted to the SDK's supported 10-bit RGB input.")+ return ",".join(filters), assumptions+++def output_filter(pixel_format: int, hdr: bool) -> str:+ planar = {1: "gbrp", 2: "gbrp10le", 3: "gbrpf32le"}[pixel_format]+ pin = "bt2020" if hdr and pixel_format == 2 else "bt709"+ tin = "linear" if pixel_format == 3 else "smpte2084" if hdr else "bt470m"+ pout, tout, matrix = ("bt2020", "smpte2084", "bt2020nc") if hdr else ("bt709", "bt709", "bt709")+ return (f"format={planar},zscale=matrixin=gbr:primariesin={pin}:transferin={tin}:rangein=full:"+ f"matrix={matrix}:primaries={pout}:transfer={tout}:range=limited" + (":npl=80" if pixel_format == 3 else ""))+++def start_decoder(source, meta, controller):+ vf, assumptions = decode_filter(meta)+ command = [str(FFMPEG), "-hide_banner", "-v", "warning", "-xerror", "-copyts", "-noautorotate", "-i", str(source),+ "-map", "0:v:0", "-an", "-sn", "-dn", "-vf", vf, "-c:v", "rawvideo", "-pix_fmt",+ "gbrp10le" if meta["depth"] > 8 else "rgba", "-fps_mode", "passthrough", "-enc_time_base", "demux",+ "-f", "nut", "pipe:1"]+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)+ controller.register(process)+ logs = BoundedLogBuffer(max_tail=60)+ thread = threading.Thread(target=drain_bounded_text, args=(process.stderr, logs), daemon=True)+ thread.start()+ return process, thread, logs, assumptions+++def packed_bytes(frame: av.VideoFrame) -> np.ndarray:+ if frame.format.name == "gbrp10le":+ channels = [np.frombuffer(p, dtype="<u2").reshape(frame.height, p.line_size // 2)[:, :frame.width].astype(np.uint32)+ for p in frame.planes]+ g,b,r = channels+ return np.ascontiguousarray(r | (g << 10) | (b << 20) | np.uint32(3 << 30))+ if frame.format.name != "rgba":+ raise RuntimeError(f"Unexpected decoder pixel format {frame.format.name}; expected rgba or gbrp10le.")+ p = frame.planes[0]+ return np.ascontiguousarray(np.frombuffer(p, dtype=np.uint8).reshape(frame.height, p.line_size)[:, :frame.width * 4])+++def result_frame(data, width, height, pixel_format):+ if pixel_format == 2:+ packed = np.frombuffer(data, dtype="<u4").reshape(height, width)+ out = av.VideoFrame(width, height, "gbrp10le")+ for plane, shift in zip(out.planes, (10, 20, 0)):+ padded = np.zeros((height, plane.line_size // 2), dtype="<u2")+ padded[:, :width] = (packed >> shift) & 1023+ plane.update(padded)+ return out+ if pixel_format == 3:+ rgba = np.frombuffer(data, dtype="<f2").reshape(height, width, 4).astype(np.float32)+ if not np.isfinite(rgba[:, :, :3]).all():+ raise RuntimeError("RTX Video HDR returned non-finite pixels.")+ out = av.VideoFrame(width, height, "gbrpf32le")+ for plane, channel in zip(out.planes, (1, 2, 0)):+ padded = np.zeros((height, plane.line_size // 4), dtype="<f4")+ padded[:, :width] = rgba[:, :, channel]+ plane.update(padded)+ return out+ out = av.VideoFrame(width, height, "rgba")+ p = out.planes[0]+ raw = np.frombuffer(data, dtype=np.uint8).reshape(height, width * 4)+ if p.line_size == width * 4:+ p.update(raw)+ else:+ padded = np.zeros((height, p.line_size), dtype=np.uint8)+ padded[:, :width * 4] = raw+ p.update(padded)+ return out+++def finish_process(process, thread, logs, controller, *, expected_stop=False):+ try:+ if expected_stop and process.poll() is None:+ process.terminate()+ process.wait(timeout=120)+ thread.join(timeout=2)+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ if process.returncode and not expected_stop:+ detail = logs.snapshot() if hasattr(logs, "snapshot") else logs[-60:]+ raise RuntimeError("Video subprocess failed:\n" + "\n".join(detail))+ finally:+ controller.unregister(process)+++def close_process(process, controller, thread=None):+ """Reap before deleting the job directory, including failed/partial encodes."""+ try:+ if process.poll() is None:+ with suppress(OSError):+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ finally:+ controller.unregister(process)+ if thread is not None:+ thread.join(timeout=2)+ for stream in (process.stdin, process.stdout, process.stderr):+ if stream:+ with suppress(OSError):+ stream.close()diff --git a/src/upscale/video/models.py b/src/upscale/video/models.pynew file mode 100644index 0000000..81c5be4--- /dev/null+++ b/src/upscale/video/models.py@@ -0,0 +1,155 @@+from __future__ import annotations++import math+from dataclasses import dataclass, fields+from fractions import Fraction++from ...core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, hdr_mode_supported, validate_codec_container+from ...core.naming import validate_rename++VSR_QUALITIES = [("1 - Low", 1), ("2 - Medium", 2), ("3 - High", 3), ("4 - Ultra", 4)]+SCALE_FACTORS = [("1×", 1.0), ("1.5×", 1.5), ("2×", 2.0), ("3×", 3.0), ("4×", 4.0)]+SIZE_MODES = ("Scale factor", "Custom dimensions")+HDR_PRECISIONS = ("Packed 10-bit", "FP16")+HDR_PRECISION_CHOICES = [("Packed 10-bit", "Packed 10-bit"), ("Packed 10-bit (FP16)", "FP16")]+TEXTURE_LIMIT = 16384+++@dataclass(slots=True)+class UpscaleOptions:+ vsr_enabled: bool = True+ vsr_quality: int = 4+ size_mode: str = "Scale factor"+ scale_factor: float = 2.0+ width: int = 3840+ height: int = 2160+ aspect_lock: bool = True+ hdr_enabled: bool = False+ hdr_contrast: int = 100+ hdr_saturation: int = 100+ hdr_middle_gray: int = 50+ hdr_peak_luminance: int = 1000+ hdr_precision: str = "Packed 10-bit"+ codec: str = "H.265 (NVIDIA NVENC)"+ container: str = "MP4"+ quality: str = "Auto (Default)"+ rename_mode: str = "Auto"+ custom_suffix: str = "_RTXVIDEO"+ ai_gpu_uuid: str = "auto"+ video_gpu_uuid: str = "auto"+ preview_seconds: float | None = None+ preview_frames: int | None = None++ def validate(self, *, for_render: bool = True) -> None:+ for name in ("vsr_enabled", "hdr_enabled", "aspect_lock"):+ if not isinstance(getattr(self, name), bool):+ raise ValueError(f"{name} must be on or off.")+ for name, low, high in (+ ("vsr_quality", 0, 4), ("width", 2, TEXTURE_LIMIT), ("height", 2, TEXTURE_LIMIT),+ ("hdr_contrast", 0, 200), ("hdr_saturation", 0, 200),+ ("hdr_middle_gray", 10, 100), ("hdr_peak_luminance", 400, 2000),+ ):+ v = getattr(self, name)+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or int(v) != v or not low <= v <= high:+ raise ValueError(f"{name.replace('_', ' ')} must be an integer from {low} to {high}.")+ if isinstance(self.scale_factor, bool) or not isinstance(self.scale_factor, (int, float)) or not math.isfinite(self.scale_factor) or self.scale_factor < 1:+ raise ValueError("Scale factor must be a finite number of at least 1.")+ for value, choices, name in ((self.size_mode, SIZE_MODES, "size mode"), (self.hdr_precision, HDR_PRECISIONS, "HDR precision"),+ (self.codec, CODEC_CHOICES, "codec"), (self.quality, ENCODING_QUALITIES, "encoding quality")):+ if value not in choices:+ raise ValueError(f"Unknown {name}: {value!r}.")+ if self.container not in ("MP4", "MKV", "MOV"):+ raise ValueError("Unknown output container.")+ if for_render:+ validate_codec_container(self.codec, self.container)+ validate_rename(self.rename_mode, self.custom_suffix)+ if for_render and not (self.vsr_enabled or self.hdr_enabled):+ raise ValueError("Enable RTX Video Super Resolution or RTX Video HDR.")+ if self.hdr_enabled and not hdr_mode_supported(self.codec):+ raise ValueError("RTX Video HDR requires H.265, AV1, or ProRes. H.264 cannot store this HDR output.")+ if self.preview_frames is not None and (isinstance(self.preview_frames, bool) or+ not isinstance(self.preview_frames, (int, float)) or+ not math.isfinite(self.preview_frames) or+ int(self.preview_frames) != self.preview_frames or self.preview_frames < 1):+ raise ValueError("Preview frame count must be a positive integer.")+ if self.preview_seconds is not None and (isinstance(self.preview_seconds, bool) or+ not isinstance(self.preview_seconds, (int, float)) or+ not math.isfinite(self.preview_seconds) or self.preview_seconds <= 0):+ raise ValueError("Preview duration must be positive and finite.")+ if self.preview_seconds is not None and self.preview_frames is not None:+ raise ValueError("Select one preview limit.")+++SETTING_FIELDS = tuple(f.name for f in fields(UpscaleOptions) if f.name not in {+ "ai_gpu_uuid", "video_gpu_uuid", "preview_seconds", "preview_frames",+})+++def options_from_settings(settings) -> UpscaleOptions:+ return UpscaleOptions(**{name: getattr(settings, "upscale_" + name) for name in SETTING_FIELDS},+ ai_gpu_uuid=settings.ai_gpu_uuid, video_gpu_uuid=settings.video_gpu_uuid)+++def output_size(width: int, height: int, options: UpscaleOptions, sar: Fraction = Fraction(1)) -> tuple[int, int, str]:+ """Return square-pixel output dimensions; width drives a locked custom size."""+ options.validate()+ display_width = width * float(sar)+ if not options.vsr_enabled:+ w, h = display_width, float(height)+ elif options.size_mode == "Scale factor":+ w, h = display_width * options.scale_factor, height * options.scale_factor+ else:+ w = float(options.width)+ h = w * height / display_width if options.aspect_lock else float(options.height)+ if not math.isfinite(w) or not math.isfinite(h) or max(w, h) > TEXTURE_LIMIT:+ raise ValueError("Requested output exceeds D3D11's 16384-pixel texture dimension. Choose a smaller size.")+ # All offered delivery codecs accept even dimensions. Never round below source.+ ow, oh = max(2, math.ceil(w / 2) * 2), max(2, math.ceil(h / 2) * 2)+ if options.vsr_enabled and (ow < math.ceil(display_width) or oh < height):+ raise ValueError("Upscale output must not be smaller than the source. Use 1× for native-resolution enhancement.")+ rounding = " (rounded up to even dimensions for encoding)" if (ow != w or oh != h) else ""+ return ow, oh, rounding+++@dataclass(slots=True)+class UpscaleCapabilities:+ gpu: dict+ luid: str+ vsr: dict+ hdr: dict+ sdk_version: str = "1.1.0"+ worker_version: str = "1.0.0"+++@dataclass(slots=True)+class UpscaleResult:+ output_path: str+ report_path: str+ frames: int+ output_width: int+ output_height: int+ hdr: bool+ elapsed_seconds: float+++@dataclass(slots=True)+class UpscaleSuccess:+ index: int+ input_path: str+ result: UpscaleResult+++@dataclass(slots=True)+class UpscaleFailure:+ index: int+ input_path: str+ error: str+ cancelled: bool = False+++@dataclass(slots=True)+class UpscaleBatchResult:+ successes: list[UpscaleSuccess]+ failures: list[UpscaleFailure]+ cancelled: bool+ manifest_path: strdiff --git a/src/upscale/video/native.py b/src/upscale/video/native.pynew file mode 100644index 0000000..2cedeb3--- /dev/null+++ b/src/upscale/video/native.py@@ -0,0 +1,225 @@+from __future__ import annotations++import collections+import ctypes+import json+import struct+import subprocess+import threading+import time+from contextlib import nullcontext, suppress+from functools import lru_cache++from ...core.gpu_detection import detect_gpus+from ...core.gpu_selection import resolve_ai_gpu+from ...core.jobs import Cancelled, JobController, current_job_controller, use_job_controller+from ...core.paths import RUNTIME+from .models import UpscaleCapabilities, UpscaleOptions++RUNTIME_DIR = RUNTIME / "rtx_video"+WORKER = RUNTIME_DIR / "rtx-video-worker.exe"+MAGIC, FRAME, VERSION = 0x31585452, 0x314D5246, 1+++def gpu_luid(gpu: dict) -> str:+ driver = ctypes.WinDLL("nvcuda.dll")+ device, mask = ctypes.c_int(), ctypes.c_uint()+ luid = (ctypes.c_char * 8)()+ if driver.cuInit(0) or driver.cuDeviceGet(ctypes.byref(device), int(gpu["cuda_ordinal"])) or driver.cuDeviceGetLuid(luid, ctypes.byref(mask), device):+ raise RuntimeError("Cannot match the selected NVIDIA GPU to its DirectX adapter.")+ return bytes(luid).hex()+++def runtime_files() -> None:+ for path in (WORKER, RUNTIME_DIR / "nvngx_vsr.dll", RUNTIME_DIR / "nvngx_truehdr.dll"):+ if not path.is_file():+ raise RuntimeError(f"RTX Video runtime is missing: {path}. Rebuild or restore the RTX Video runtime.")+++@lru_cache(maxsize=8)+def _probe(luid: str, worker_stamp: int, vsr_stamp: int, hdr_stamp: int) -> dict:+ controller = current_job_controller() or JobController()+ process = subprocess.Popen([str(WORKER), "--probe", "--gpu-luid", luid], cwd=RUNTIME_DIR,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)+ controller.register(process)+ deadline = time.monotonic() + 90+ try:+ while True:+ if controller.cancel.is_set():+ raise Cancelled("Stopped while checking RTX Video capabilities.")+ if time.monotonic() >= deadline:+ raise RuntimeError("RTX Video capability check timed out. Check the NVIDIA driver and retry.")+ try:+ stdout, stderr = process.communicate(timeout=.2)+ break+ except subprocess.TimeoutExpired:+ continue+ if controller.cancel.is_set():+ raise Cancelled("Stopped while checking RTX Video capabilities.")+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ controller.unregister(process)+ process.stdout.close()+ process.stderr.close()+ try:+ data = json.loads(stdout)+ except ValueError as exc:+ raise RuntimeError("RTX Video capability probe returned invalid data: " + stderr.decode("utf-8", "replace")[-3000:]) from exc+ if process.returncode or "error" in data:+ raise RuntimeError(data.get("error") or stderr.decode("utf-8", "replace")[-3000:])+ if data.get("protocol_version") != VERSION:+ raise RuntimeError("RTX Video worker version does not match this application.")+ return data+++def probe_capabilities(gpu_uuid: str = "auto", *, controller=None) -> UpscaleCapabilities:+ runtime_files()+ gpu = resolve_ai_gpu(detect_gpus(), gpu_uuid)+ luid = gpu_luid(gpu)+ with use_job_controller(controller) if controller is not None else nullcontext():+ if controller is not None and controller.cancel.is_set():+ raise Cancelled("Stopped before checking RTX Video capabilities.")+ data = _probe(luid, *(p.stat().st_mtime_ns for p in (WORKER, RUNTIME_DIR / "nvngx_vsr.dll", RUNTIME_DIR / "nvngx_truehdr.dll")))+ return UpscaleCapabilities(gpu, luid, data["vsr"], data["hdr"], data["sdk_version"], data["worker_version"])+++class RTXVideoSession:+ """Bounded synchronous frame exchange with a watchdog and cancellable process."""++ def __init__(self, width: int, height: int, output_width: int, output_height: int,+ options: UpscaleOptions, input_format: int, capabilities: UpscaleCapabilities,+ controller: JobController, *, timeout: float = 180):+ options.validate()+ runtime_files()+ for enabled, cap, name in ((options.vsr_enabled, capabilities.vsr, "VSR"), (options.hdr_enabled, capabilities.hdr, "HDR")):+ if enabled and not cap.get("available"):+ raise RuntimeError(f"RTX Video {name} is unavailable on {capabilities.gpu['name']}. "+ f"Minimum driver {cap.get('min_driver_major', 0)}.{cap.get('min_driver_minor', 0)}; "+ f"initialization result 0x{cap.get('init_result', 0):08X}.")+ self.output_format = (3 if options.hdr_precision == "FP16" else 2) if options.hdr_enabled else input_format+ self.input_bytes = width * height * 4+ self.output_bytes = output_width * output_height * (8 if self.output_format == 3 else 4)+ self.controller, self.timeout = controller, timeout+ self.logs = collections.deque(maxlen=150)+ self.process = subprocess.Popen([str(WORKER), "--serve", "--gpu-luid", capabilities.luid], cwd=RUNTIME_DIR,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ bufsize=0, creationflags=subprocess.CREATE_NO_WINDOW)+ controller.register(self.process)+ self.closed = False+ self.completed_frames = 0+ self.last_results = (0, 0)+ self.deadline = time.monotonic() + timeout+ self.timed_out = False+ self._done = threading.Event()+ self._reader = threading.Thread(target=self._read_logs, daemon=True)+ self._guard = threading.Thread(target=self._watchdog, daemon=True)+ self._reader.start(); self._guard.start()+ try:+ self._write(struct.pack("<15I", MAGIC, VERSION, width, height, output_width, output_height,+ input_format, self.output_format, options.vsr_enabled, int(options.vsr_quality),+ options.hdr_enabled, int(options.hdr_contrast), int(options.hdr_saturation),+ int(options.hdr_middle_gray), int(options.hdr_peak_luminance)))+ magic, status, version, ibytes, obytes = struct.unpack("<5I", self._read(20))+ if (magic, status, version, ibytes, obytes) != (MAGIC, 0, VERSION, self.input_bytes, self.output_bytes):+ raise RuntimeError("RTX Video worker returned an invalid setup response.")+ self.deadline = float("inf")+ except BaseException:+ self.close(abort=True)+ raise++ def _read_logs(self):+ for line in iter(self.process.stderr.readline, b""):+ text = line.decode("utf-8", "replace").rstrip()+ if text:+ self.logs.append(text)++ def _watchdog(self):+ while not self._done.wait(.2):+ if time.monotonic() > self.deadline:+ self.timed_out = True+ self.process.kill()+ break++ def _error(self):+ if self.controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ self._reader.join(timeout=.2)+ detail = "timed out" if self.timed_out else "closed unexpectedly"+ raise RuntimeError(f"RTX Video worker {detail}.\n" + "\n".join(self.logs)[-4000:])++ def _write(self, data):+ view = memoryview(data).cast("B")+ try:+ while view:+ n = self.process.stdin.write(view)+ if not n:+ self._error()+ view = view[n:]+ except (OSError, ValueError):+ self._error()++ def _read(self, count):+ data = bytearray(count)+ view = memoryview(data)+ while view:+ n = self.process.stdout.readinto(view)+ if not n:+ self._error()+ view = view[n:]+ return data++ def process_frame(self, pixels) -> bytearray:+ if self.closed:+ raise RuntimeError("RTX Video session is closed.")+ if self.controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ if memoryview(pixels).nbytes != self.input_bytes:+ raise ValueError("Incorrect RTX Video input frame byte count.")+ self.deadline = time.monotonic() + self.timeout+ try:+ self._write(struct.pack("<3I", FRAME, self.completed_frames, self.input_bytes))+ self._write(pixels)+ magic, index, status, size, vsr, hdr = struct.unpack("<6I", self._read(24))+ if (magic, index) != (FRAME, self.completed_frames):+ raise RuntimeError("RTX Video frame identity mismatch.")+ if status:+ raise RuntimeError(f"RTX Video evaluation failed: VSR=0x{vsr:08X}, HDR=0x{hdr:08X}.")+ if size != self.output_bytes:+ raise RuntimeError("RTX Video output frame byte count mismatch.")+ result = self._read(size)+ self.completed_frames += 1+ self.last_results = (vsr, hdr)+ return result+ finally:+ self.deadline = float("inf")++ def close(self, *, abort=False):+ if self.closed:+ return+ self.closed = True+ self._done.set()+ try:+ if abort and self.process.poll() is None:+ self.process.terminate()+ with suppress(OSError):+ self.process.stdin.close()+ try:+ self.process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ self.process.kill(); self.process.wait(timeout=5)+ finally:+ self.controller.unregister(self.process)+ self._reader.join(timeout=1)+ self._guard.join(timeout=1)+ for stream in (self.process.stdout, self.process.stderr):+ stream.close()+ if not abort and self.process.returncode:+ raise RuntimeError("RTX Video worker failed during shutdown.\n" + "\n".join(self.logs)[-3000:])++ def __enter__(self):+ return self++ def __exit__(self, exc_type, *_):+ self.close(abort=exc_type is not None)diff --git a/src/upscale/video/preview.py b/src/upscale/video/preview.pynew file mode 100644index 0000000..89a6b3f--- /dev/null+++ b/src/upscale/video/preview.py@@ -0,0 +1,53 @@+from __future__ import annotations++from dataclasses import replace+from pathlib import Path++import gradio as gr++from ...core.ffmpeg.preview import is_browser_playable, make_browser_preview+from ...settings.storage import current_preview_encoding+from .media import inspect_video+from .processor import upscale_video+++def display_result(result, options, controller=None):+ mode = current_preview_encoding()+ if mode == "Disabled":+ return result.output_path, "Actual output; browser HDR/codec support depends on your display and browser."+ if not options.hdr_enabled and mode == "Auto" and is_browser_playable(result.output_path):+ return result.output_path, ""+ vf = None+ if options.hdr_enabled:+ peak = options.hdr_peak_luminance / 100+ vf = ("zscale=matrixin=bt2020nc:primariesin=bt2020:transferin=smpte2084:rangein=limited:"+ "transfer=linear:npl=100,format=gbrpf32le,zscale=primaries=bt709,"+ f"tonemap=mobius:desat=2:peak={peak:g},zscale=transfer=bt709:matrix=bt709:range=limited,format=yuv420p")+ try:+ path = make_browser_preview(result.output_path, controller=controller, sdr_filter=vf)+ except Exception as exc:+ return None, f"Output saved; browser preview unavailable: {exc}"+ return path, "SDR tone-mapped browser preview. Download the original for HDR playback." if options.hdr_enabled else "H.264 browser preview."+++def preview_upscale(paths, options, *, one_frame=False, progress=None):+ paths = [paths] if isinstance(paths, str) else list(paths or [])+ if len(paths) != 1:+ raise gr.Error("Select one video to preview.")+ from ...core.jobs import current_job_controller+ controller = current_job_controller()+ opts = replace(options, preview_frames=1 if one_frame else None, preview_seconds=None if one_frame else 3.0)+ result = upscale_video(paths[0], opts, progress=progress, controller=controller)+ display, detail = display_result(result, opts, controller)+ return gr.update(value=display, visible=True, label="SDR tone-mapped preview (download original for HDR)" if opts.hdr_enabled and current_preview_encoding() != "Disabled" else "Output preview"), (+ f"Preview complete: {result.output_width}×{result.output_height}, {result.frames} frames.\n{detail}\n"+ f"Original preview file: {result.output_path}\nReport: {result.report_path}")+++def preview_mode(paths):+ paths = [paths] if isinstance(paths, str) else list(paths or [])+ available = bool(paths)+ single = len(paths) == 1+ label = "Input video preview" if len(paths) <= 1 else f"Input video preview (first of {len(paths)})"+ return (gr.update(value=paths[0] if available else None, visible=available, label=label),+ gr.update(value=None, visible=True), gr.update(visible=single), gr.update(visible=single))diff --git a/src/upscale/video/processor.py b/src/upscale/video/processor.pynew file mode 100644index 0000000..95a5e07--- /dev/null+++ b/src/upscale/video/processor.py@@ -0,0 +1,203 @@+from __future__ import annotations++import json+import math+import tempfile+import time+import uuid+from contextlib import ExitStack, nullcontext, suppress+from dataclasses import asdict, replace+from fractions import Fraction+from pathlib import Path++import av++from ...core import ffmpeg+from ...core.disk_paths import OutputFile, prepare_output_dir+from ...core.gpu_detection import detect_gpus+from ...core.jobs import Cancelled, active_job+from ...core.naming import output_filename+from ...core.paths import JOBS, LOGS+from .media import PipeReader, PipeWriter, close_process, finish_process, inspect_video, output_filter, packed_bytes, result_frame, start_decoder+from .models import UpscaleOptions, UpscaleResult, output_size+from .native import RTXVideoSession, probe_capabilities+++def upscale_video(input_path, options: UpscaleOptions | None = None, progress=None, *, output_dir=None,+ controller=None, _owns_slot=False, _capabilities=None) -> UpscaleResult:+ options = replace(options) if options else UpscaleOptions()+ options.validate()+ source = Path(input_path).resolve()+ if not source.is_file():+ raise FileNotFoundError(source)+ context = nullcontext(controller) if _owns_slot else active_job(controller)+ with context as controller:+ return _process(source, options, progress, output_dir, controller, _capabilities)+++def _process(source, options, progress, output_dir, controller, capabilities):+ started = time.monotonic()+ stamp = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]+ LOGS.mkdir(exist_ok=True); JOBS.mkdir(exist_ok=True)+ report_path = LOGS / f"upscale-{stamp}.json"+ report = {"input": str(source), "options": asdict(options), "status": "running", "pipeline": "RTX Video SDK / D3D11"}+ processes = []+ destination_file = None+ session = None+ delivered = 0+ def check_cancel():+ if controller.cancel.is_set():+ raise Cancelled("Upscale stopped by user.")+ def update(value, message):+ check_cancel()+ if progress:+ progress(value, message)+ try:+ update(.01, "Checking SDR source and RTX Video capabilities")+ meta = inspect_video(source, controller, reject_hdr=True)+ width, height = meta["width"], meta["height"]+ ow, oh, rounding = output_size(width, height, options)+ caps = capabilities or probe_capabilities(options.ai_gpu_uuid, controller=controller)+ video_gpu = ffmpeg.resolve_video_gpu(detect_gpus(), options.video_gpu_uuid, options.codec, ow, oh)+ report.update(capabilities=asdict(caps), video_gpu=video_gpu, input_metadata=meta,+ output_dimensions=[ow, oh], rounding=rounding)+ destination = prepare_output_dir(output_dir)+ extension = {"MP4": ".mp4", "MKV": ".mkv", "MOV": ".mov"}[options.container]+ preview = options.preview_frames is not None or options.preview_seconds is not None+ kind = "RTXVIDEO_PREVIEW" if preview else "RTXVIDEO"+ output = destination / output_filename(source, extension, "Auto" if preview else options.rename_mode,+ options.custom_suffix, f"{source.stem}_{kind}_{stamp}")+ destination_file = OutputFile(output)+ input_format = 2 if meta["depth"] > 8 else 1+ ten_bit = options.hdr_enabled or (input_format == 2 and ffmpeg.hdr_mode_supported(options.codec))+ colors = {"color_space": "bt2020nc" if options.hdr_enabled else "bt709",+ "color_transfer": "smpte2084" if options.hdr_enabled else "bt709",+ "color_primaries": "bt2020" if options.hdr_enabled else "bt709", "hdr": options.hdr_enabled}+ with tempfile.TemporaryDirectory(prefix="rtx-video-", dir=JOBS) as job_dir, ExitStack() as stack:+ session = stack.enter_context(RTXVideoSession(width, height, ow, oh, options, input_format, caps, controller))+ # Matroska's millisecond time base would quantize fractional/VFR PTS.+ temp_video = Path(job_dir) / ("encoded.mov" if options.codec == "ProRes Proxy" else "encoded.mp4")+ encoder, enc_thread, enc_logs, selected, quality = ffmpeg.start_encoder(+ temp_video, options.codec, options.quality, controller, ow, oh, float(meta["rate"]),+ None if video_gpu is None else int(video_gpu["cuda_ordinal"]), video_gpu is not None,+ hdr_mode=ten_bit, hdr_metadata=colors, preserve_timestamps=True,+ video_filter=output_filter(session.output_format, options.hdr_enabled), keep_start_time=True,+ bounded_logs=True,+ )+ processes.append(encoder)+ stack.callback(close_process, encoder, controller, enc_thread)+ decoder, dec_thread, dec_logs, assumptions = start_decoder(source, meta, controller)+ processes.append(decoder)+ stack.callback(close_process, decoder, controller, dec_thread)+ report.update(encoder=selected, encoding_quality=quality, warnings=assumptions,+ input_format=input_format, output_format=session.output_format, color=colors,+ applied_settings={"vsr_enabled": options.vsr_enabled,+ "vsr_quality": options.vsr_quality if options.vsr_enabled else None,+ "hdr_enabled": options.hdr_enabled,+ "hdr": {name: getattr(options, name) for name in+ ("hdr_contrast", "hdr_saturation", "hdr_middle_gray",+ "hdr_peak_luminance", "hdr_precision")} if options.hdr_enabled else None,+ "input_dimensions": [width, height], "output_dimensions": [ow, oh],+ "input_color": "Full-range BT.709 RGB, gamma 2.2", "full_frame": True})+ decoded = stack.enter_context(av.open(PipeReader(decoder.stdout), mode="r", format="nut"))+ source_stream = decoded.streams.video[0]+ tb = source_stream.time_base+ nut = stack.enter_context(av.open(PipeWriter(encoder.stdin), mode="w", format="nut"))+ raw = nut.add_stream("rawvideo", rate=meta["rate"])+ raw.width, raw.height = ow, oh+ raw.pix_fmt = {1: "rgba", 2: "gbrp10le", 3: "gbrpf32le"}[session.output_format]+ raw.time_base = tb; raw.codec_context.time_base = tb+ first_time, last_pts, stopped_early = None, None, False+ eval_seconds = 0.0+ timestamps_fallback = 0+ estimated = max(1, meta["frames"] or math.ceil(meta["duration"] * float(meta["rate"])))+ limit = options.preview_frames+ if options.preview_seconds is not None:+ estimated = min(estimated, max(1, math.ceil(options.preview_seconds * float(meta["rate"]))))+ if limit:+ estimated = min(estimated, limit)+ last_update = 0+ for frame in decoded.decode(source_stream):+ check_cancel()+ if frame.pts is None:+ pts = round(Fraction(delivered, 1) / meta["rate"] / tb)+ timestamps_fallback += 1+ else:+ pts = round(frame.pts * frame.time_base / tb)+ timestamp = pts * tb+ if first_time is None:+ first_time = timestamp+ if (limit and delivered >= limit) or (options.preview_seconds is not None and delivered and timestamp - first_time >= options.preview_seconds):+ stopped_early = True+ break+ if last_pts is not None and pts <= last_pts:+ raise ValueError("Source timestamps are not strictly increasing; refusing to drop or duplicate frames.")+ if (frame.width, frame.height) != (width, height):+ raise ValueError("Source dimensions changed during decoding.")+ t0 = time.monotonic()+ pixels = session.process_frame(packed_bytes(frame))+ eval_seconds += time.monotonic() - t0+ result = result_frame(pixels, ow, oh, session.output_format)+ result.pts, result.time_base = pts, tb+ for packet in raw.encode(result):+ nut.mux(packet)+ delivered += 1+ last_pts = pts+ now = time.monotonic()+ if now - last_update > .2:+ update(min(.87, .05 + .82 * delivered / estimated),+ f"RTX Video: {width}×{height} → {ow}×{oh}; {delivered} frames; {delivered / max(.01, now-started):.1f} fps")+ last_update = now+ if not delivered:+ raise ValueError("The input contains no decodable video frames.")+ for packet in raw.encode():+ nut.mux(packet)+ nut.close(); encoder.stdin.close()+ decoded.close()+ finish_process(decoder, dec_thread, dec_logs, controller, expected_stop=stopped_early)+ session.close()+ finish_process(encoder, enc_thread, enc_logs, controller)+ if not preview and (not meta["frames"] or delivered != meta["frames"]):+ exact = ffmpeg.probe_video(source, count_mode="exact", strict_decode=True, controller=controller)+ if exact["frames"] != delivered:+ raise RuntimeError(f"Source has {exact['frames']} frames but only {delivered} were processed.")+ if session.completed_frames != delivered:+ raise RuntimeError("RTX Video worker processed an unexpected number of frames.")+ update(.90, "Muxing original audio and subtitles")+ ffmpeg.final_mux(temp_video, source, destination_file.temporary, options.container, controller,+ preserve_supported_subtitles=True, source_time_origin=meta["origin"])+ update(.96, "Verifying output frames, resolution, and HDR signaling")+ verified = ffmpeg.probe_video(destination_file.temporary, count_mode="packets", controller=controller)+ if verified["frames"] != delivered:+ verified = ffmpeg.probe_video(destination_file.temporary, count_mode="exact", strict_decode=True, controller=controller)+ if verified["frames"] != delivered or (verified["width"], verified["height"]) != (ow, oh):+ raise RuntimeError("Saved output does not match processed frame count or dimensions.")+ saved = inspect_video(destination_file.temporary, controller)+ if options.hdr_enabled and (saved["depth"] < 10 or not saved["hdr"] or+ saved["stream"].get("color_primaries") != "bt2020" or saved["stream"].get("color_space") != "bt2020nc"):+ raise RuntimeError("Saved file failed HDR color and bit-depth verification.")+ if not options.hdr_enabled and saved["hdr"]:+ raise RuntimeError("SDR output unexpectedly contains HDR signaling.")+ check_cancel()+ report.update(status="success", output=str(output), frames=delivered, verified_output=saved,+ sdk_evaluations=delivered, last_ngx_results=session.last_results,+ timestamp_fallback_frames=timestamps_fallback,+ timings={"total_seconds": time.monotonic()-started, "ngx_evaluation_seconds": eval_seconds},+ worker_log=list(session.logs), decoder_log=dec_logs.snapshot(), encoder_log=enc_logs.snapshot())+ report_path.write_text(json.dumps(report, indent=2, default=str), encoding="utf-8")+ destination_file.publish()+ return UpscaleResult(str(output), str(report_path), delivered, ow, oh, options.hdr_enabled, time.monotonic()-started)+ except BaseException as exc:+ report.update(status="cancelled" if controller.cancel.is_set() or isinstance(exc, Cancelled) else "failed",+ error=str(exc), frames=delivered, elapsed_seconds=time.monotonic()-started,+ worker_log=list(session.logs) if session else [])+ with suppress(OSError):+ report_path.write_text(json.dumps(report, indent=2, default=str), encoding="utf-8")+ if controller.cancel.is_set() and not isinstance(exc, Cancelled):+ raise Cancelled("Upscale stopped by user.") from exc+ raise+ finally:+ for process in processes:+ close_process(process, controller)+ if destination_file:+ destination_file.cleanup()diff --git a/src/upscale/video/ui.py b/src/upscale/video/ui.pynew file mode 100644index 0000000..1abdc02--- /dev/null+++ b/src/upscale/video/ui.py@@ -0,0 +1,227 @@+from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++import gradio as gr++from ...core.batch_ui import (+ BATCH_HEADERS, bind_batch_ui, build_media_clear_button, build_media_select_button,+ build_path_controls,+)+from ...core.disk_paths import create_media_archive, resolve_inputs+from ...core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, hdr_mode_supported+from ...core.naming import RENAME_MODES+from ...settings.storage import processing_gpu_settings+from .batch import upscale_videos+from .components import ManagedVideo+from .media import inspect_video+from .models import (HDR_PRECISION_CHOICES, SCALE_FACTORS, SETTING_FIELDS, SIZE_MODES,+ VSR_QUALITIES, UpscaleOptions, options_from_settings, output_size)+from .preview import display_result, preview_mode, preview_upscale+++def options_from_values(values):+ ai, video = processing_gpu_settings()+ return UpscaleOptions(**dict(zip(SETTING_FIELDS, values)), ai_gpu_uuid=ai, video_gpu_uuid=video)+++def render_upscale_batch(paths, *values, progress=None, output_dir=None, controller=None, on_item_update=None, direct_disk=False):+ options = options_from_values(values)+ result = upscale_videos(paths, options, progress, output_dir=output_dir, controller=controller, on_item_update=on_item_update)+ files = [item.result.output_path for item in result.successes]+ output, detail = None, ""+ if not direct_disk and len(paths) == 1 and result.successes and not result.cancelled:+ output, detail = display_result(result.successes[0].result, options, controller)+ status = f"{'Cancelled' if result.cancelled else 'Complete'}: {len(files)} completed; {len(result.failures)} failed/skipped.\n{detail}\nReport: {result.manifest_path}"+ if result.failures:+ status += "\n" + result.failures[0].error+ archive_path = None+ if not direct_disk and not result.cancelled:+ archive_path = create_media_archive(+ files, output_dir, "RTXVIDEO_VIDEO_BATCH", controller=controller,+ )+ return gr.update(value=output, visible=not direct_disk, label="SDR tone-mapped preview (download original for HDR)" if options.hdr_enabled and detail.startswith("SDR") else "Output video"), archive_path, [], status+++def preview_frame(paths, *values, progress=gr.Progress(track_tqdm=False)):+ return preview_upscale(paths, options_from_values(values), one_frame=True, progress=lambda v,m: progress(v, desc=m))+++def preview_clip(paths, *values, progress=gr.Progress(track_tqdm=False)):+ return preview_upscale(paths, options_from_values(values), progress=lambda v,m: progress(v, desc=m))+++def describe_size(paths, input_path, *values):+ if not paths and not str(input_path or "").strip():+ return ""+ try:+ options = options_from_values(values)+ sources = resolve_inputs(input_path, paths, "video")+ lines = []+ for path in sources[:8]:+ m = inspect_video(Path(path), reject_hdr=True)+ w, h, note = output_size(m["width"], m["height"], options)+ lines.append(f"**{Path(path).name}**: {m['source_width']}×{m['source_height']} → **{w}×{h}**{note}")+ if len(sources) > 8:+ lines.append(f"{len(sources)-8} more files; dimensions are calculated independently for each source.")+ return "\n\n".join(lines)+ except Exception as exc:+ return str(exc)+++@dataclass+class UpscaleTab:+ sources: object+ input_preview: object+ input_actions: object+ select_source: object+ clear_source: object+ controls: dict+ preview_frame: object+ preview: object+ render: object+ stop: object+ reset: object+ output_video: object+ zip_download: object+ status: object+ results: object+ input_path: object+ output_path: object+ job_state: object = None++ @property+ def settings_inputs(self):+ return [self.controls[n] for n in SETTING_FIELDS]++ @property+ def render_inputs(self):+ return [self.sources, *self.settings_inputs]++ @property+ def preview_inputs(self):+ return self.render_inputs+++def build_upscale_tab(settings):+ opts = options_from_settings(settings)+ c = {}+ 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="upscale-upload-list",+ elem_classes=["media-upload-surface"])+ input_preview = ManagedVideo(label="Input video preview", interactive=False, visible=False)+ with gr.Row(+ visible=False, elem_id="upscale-input-actions",+ elem_classes=["media-input-actions"],+ ) as input_actions:+ select_source = build_media_select_button(+ "Choose Videos", ["video"], "upscale-select-input",+ )+ clear_source = build_media_clear_button("upscale-clear-input")+ input_path, output_path = build_path_controls()+ with gr.Accordion("RTX Video Super Resolution", open=True):+ c["vsr_enabled"] = gr.Checkbox(value=opts.vsr_enabled, label="RTX Video Super Resolution")+ c["vsr_quality"] = gr.Dropdown(VSR_QUALITIES, value=opts.vsr_quality, label="VSR quality", info="Ultra gives the highest quality.")+ c["size_mode"] = gr.Radio(SIZE_MODES, value=opts.size_mode, label="Output sizing")+ c["scale_factor"] = gr.Dropdown(+ SCALE_FACTORS, value=opts.scale_factor, label="Scale factor",+ info="1× enhances at original resolution. Other factors increase width and height.",+ )+ with gr.Row(+ visible=opts.size_mode == "Custom dimensions",+ elem_id="upscale-video-custom-dimensions",+ ) as custom_dimensions_row:+ c["width"] = gr.Number(value=opts.width, minimum=2, maximum=16384, precision=0, label="Output width")+ c["height"] = gr.Number(value=opts.height, minimum=2, maximum=16384, precision=0, label="Output height")+ c["aspect_lock"] = gr.Checkbox(value=opts.aspect_lock, label="Lock aspect ratio", info="Custom width determines height for each source.")+ dimensions = gr.Markdown(visible=False, elem_id="upscale-video-dimensions")+ with gr.Accordion("RTX Video HDR", open=True):+ c["hdr_enabled"] = gr.Checkbox(value=opts.hdr_enabled, label="Convert SDR to HDR", interactive=hdr_mode_supported(opts.codec),+ info="Creates HDR highlights and colors. Requires H.265, AV1, or ProRes output.")+ with gr.Column(visible=opts.hdr_enabled) as hdr_controls:+ with gr.Row():+ c["hdr_contrast"] = gr.Slider(0, 200, value=opts.hdr_contrast, step=1, precision=0, label="HDR contrast")+ c["hdr_saturation"] = gr.Slider(0, 200, value=opts.hdr_saturation, step=1, precision=0, label="HDR saturation")+ with gr.Row():+ c["hdr_middle_gray"] = gr.Slider(10, 100, value=opts.hdr_middle_gray, step=1, precision=0, label="HDR middle gray")+ c["hdr_peak_luminance"] = gr.Slider(400, 2000, value=opts.hdr_peak_luminance, step=1, precision=0, label="HDR peak luminance (nits)")+ c["hdr_precision"] = gr.Radio(HDR_PRECISION_CHOICES, value=opts.hdr_precision, label="HDR processing precision",+ info="FP16 uses more memory. HDR video exports use 10-bit color in both modes.")+ c["quality"] = gr.Radio(ENCODING_QUALITIES, value=opts.quality, label="Encoding quality")+ with gr.Row():+ c["codec"] = gr.Dropdown(CODEC_CHOICES, value=opts.codec, label="Video codec", info="Plain = CPU; NVIDIA NVENC = GPU. ProRes requires MOV or MKV.")+ c["container"] = gr.Dropdown(("MP4", "MKV", "MOV"), value=opts.container, label="Container")+ with gr.Row():+ c["rename_mode"] = gr.Radio(RENAME_MODES, value=opts.rename_mode, label="Rename")+ c["custom_suffix"] = gr.Textbox(value=opts.custom_suffix, label="Custom suffix", interactive=opts.rename_mode == "Custom")+ with gr.Row():+ preview_frame_button = gr.Button("Preview 1 frame", visible=False)+ preview_button = gr.Button("Preview 3 sec", visible=False)+ render = gr.Button("Upscale video(s)", variant="primary")+ stop = gr.Button("Stop", variant="stop")+ reset = gr.Button("Reset settings")+ with gr.Column(scale=3):+ output_video = ManagedVideo(+ label="Output video", interactive=False, visible=True, height=520,+ )+ zip_download = gr.DownloadButton("Save as ZIP", visible=False)+ status = gr.Textbox(label="Status", interactive=False, lines=5, max_lines=12)+ results = gr.Dataframe(headers=BATCH_HEADERS, datatype=["str"]*len(BATCH_HEADERS), interactive=False, label="Batch results", wrap=True)+ tab = UpscaleTab(sources, input_preview, input_actions, select_source, clear_source, c, preview_frame_button, preview_button, render, stop, reset,+ output_video, zip_download, status, results, input_path, output_path)+ bind_batch_ui(tab, render_upscale_batch, kind="video", preview_mode=preview_mode,+ preview_actions=[(tab.preview_frame, preview_frame), (tab.preview, preview_clip)])+ c["hdr_enabled"].change(lambda enabled: gr.update(visible=enabled), inputs=c["hdr_enabled"], outputs=hdr_controls, queue=False)+ c["codec"].change(lambda codec: gr.update(interactive=True) if hdr_mode_supported(codec) else gr.update(value=False, interactive=False),+ inputs=c["codec"], outputs=c["hdr_enabled"], queue=False)+ c["rename_mode"].change(lambda mode: gr.update(interactive=mode == "Custom"), inputs=c["rename_mode"], outputs=c["custom_suffix"], queue=False)+ def sizing_controls(enabled, mode, lock):+ custom = mode == "Custom dimensions"+ return [gr.update(interactive=enabled), gr.update(interactive=enabled),+ gr.update(visible=not custom, interactive=enabled), gr.update(visible=custom),+ gr.update(visible=custom, interactive=enabled),+ gr.update(visible=custom, interactive=enabled and not lock),+ gr.update(visible=custom, interactive=enabled)]+ sizing_outputs = [c["vsr_quality"], c["size_mode"], c["scale_factor"], custom_dimensions_row,+ c["width"], c["height"], c["aspect_lock"]]+ for name in ("vsr_enabled", "size_mode", "aspect_lock"):+ c[name].change(sizing_controls, inputs=[c["vsr_enabled"], c["size_mode"], c["aspect_lock"]], outputs=sizing_outputs, queue=False)+ def initialize_custom(paths, path, factor, mode):+ if mode != "Custom dimensions":+ return gr.skip(), gr.skip()+ try:+ src = resolve_inputs(path, paths, "video")[0]+ m = inspect_video(Path(src), reject_hdr=True)+ w,h,_ = output_size(m["width"], m["height"], UpscaleOptions(scale_factor=factor))+ return w,h+ except Exception:+ return gr.skip(), gr.skip()+ c["size_mode"].input(initialize_custom, inputs=[sources, input_path, c["scale_factor"], c["size_mode"]], outputs=[c["width"], c["height"]], queue=False)+ def locked_height(paths, path, width, lock):+ if not lock:+ return gr.skip()+ try:+ src = resolve_inputs(path, paths, "video")[0]+ m = inspect_video(Path(src), reject_hdr=True)+ _, h, _ = output_size(m["width"], m["height"], UpscaleOptions(size_mode="Custom dimensions", width=width))+ return h+ except Exception:+ return gr.skip()+ for name in ("width", "aspect_lock"):+ c[name].input(locked_height, inputs=[sources, input_path, c["width"], c["aspect_lock"]], outputs=c["height"], queue=False)+ for component in (sources, input_path, *tab.settings_inputs):+ component.change(+ lambda *args: gr.update(value=(text := describe_size(*args)), visible=bool(text)),+ inputs=[sources, input_path, *tab.settings_inputs], outputs=dimensions,+ queue=False, show_progress="hidden", trigger_mode="always_last",+ )+ # Initialize state directly; events handle subsequent preset/reset changes.+ initial = sizing_controls(opts.vsr_enabled, opts.size_mode, opts.aspect_lock)+ for component, update in zip(sizing_outputs, initial):+ for key in ("visible", "interactive"):+ if key in update:+ setattr(component, key, update[key])+ return tab