Skip to content

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

Add files via upload

Merserkd165988bd106
diff --git a/Visual Enhancer.exe b/Visual Enhancer.exe
new file mode 100644
index 0000000..9f51684
Binary files /dev/null and b/Visual Enhancer.exe differ
diff --git a/app.py b/app.py
index eeb3640..0d25e6f 100644
--- a/app.py
+++ b/app.py
@@ -1,544 +1,14 @@
from __future__ import annotations
-from pathlib import Path
-import os
+import sys
-# Resolve the portable Gradio cache without importing the ``src.core`` package:
-# importing that package executes its __init__ and may load heavy/media modules.
-# Gradio reads GRADIO_TEMP_DIR during import in some modules, so this must be
-# the first application setup performed.
-_APP_ROOT = Path(__file__).resolve().parent
-_APP_GRADIO_TEMP = _APP_ROOT / "temp" / "gradio"
-_APP_GRADIO_TEMP.mkdir(parents=True, exist_ok=True)
-os.environ["GRADIO_TEMP_DIR"] = str(_APP_GRADIO_TEMP)
+from src.desktop.app import launch_desktop
-# 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.batch_ui import bind_input_surface_reactivation
-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.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.neural_rendering.composition_ui import bind_composition_mask_events
-from src.settings.ui import bind_settings_events, build_settings_tab, initialize_settings
-from src.upscale.ui import build_upscale_tab
-
-APP_CSS = r"""
-/* Internal lazy-ZIP download targets must always remain in the DOM for the
- one-click browser download trigger, but must never appear as UI controls. */
-.internal-zip-download {
- display: none !important;
-}
-
-/* Stateful mode trees stay mounted. The radio's client guard stores the latest
- requested mode on <html>; these selectors remain authoritative even if an
- older backend visibility response arrives later. The correct panel can be
- briefly blank while loading, but the wrong panel can never be exposed. */
-html[data-neural-rendering-mode="Video"] #neural-rendering-image,
-html[data-neural-rendering-mode="Image"] #neural-rendering-video,
-html[data-upscale-mode="Video"] #upscale-image,
-html[data-upscale-mode="Image"] #upscale-video {
- display: none !important;
-}
-
-/* First paint has no dataset yet (the guards only run on mode.change), so the
- rules above match nothing and both panels would stack. Hide the Video panel
- by default; the load-time JS below immediately corrects this when the saved
- Upscale mode is Video, and the change-guards take over afterwards. */
-html:not([data-neural-rendering-mode]) #neural-rendering-video,
-html:not([data-upscale-mode]) #upscale-video {
- display: none !important;
-}
-
-/* Keep the app brand and native top-level tabs on one horizontal header line.
- Gradio measures a visually-hidden copy of the tab buttons for overflow, so
- shift that measurement surface by the same fixed brand width as the visible
- tab list to preserve the built-in overflow menu calculation. */
-#main-tabs {
- --main-brand-width: 8.75rem;
-}
-
-#main-tabs > .tab-wrapper {
- justify-content: flex-start;
- min-width: 0;
-}
-
-#main-tabs > .tab-wrapper::before {
- content: "DLSS 5 VE";
- display: flex;
- flex: 0 0 var(--main-brand-width);
- align-self: stretch;
- align-items: center;
- box-sizing: border-box;
- padding-right: var(--size-3);
- color: var(--body-text-color);
- font-size: var(--text-lg);
- font-weight: 700;
- white-space: nowrap;
-}
-
-#main-tabs > .tab-wrapper > .tab-container[role="tablist"] {
- flex: 1 1 auto;
- width: auto !important;
- min-width: 0;
-}
-
-#main-tabs > .tab-wrapper > .tab-container.visually-hidden {
- left: var(--main-brand-width);
-}
-
-/* Image / Video is a compact second navigation line in workflows that support
- both modes. Keep the native Gradio radio buttons and their behavior, but
- remove the surrounding form/label and prevent the two choices from wrapping. */
-#neural-rendering-mode,
-#upscale-mode {
- flex: 0 0 auto !important;
- width: max-content !important;
- max-width: 100%;
- min-width: 0 !important;
-}
-
-#neural-rendering-mode .wrap,
-#upscale-mode .wrap {
- flex-wrap: nowrap !important;
-}
-
-/* On Windows Chromium, hovering a compact radio choice can briefly make the
- max-content radio surface report horizontal overflow and expose a native
- scrollbar. These two-choice selectors never need scrolling, so keep the
- overflow paintable without creating a scroll container. */
-#neural-rendering-mode,
-#upscale-mode,
-#neural-rendering-mode .wrap,
-#upscale-mode .wrap {
- overflow: visible !important;
- scrollbar-width: none;
-}
-
-#neural-rendering-mode::-webkit-scrollbar,
-#upscale-mode::-webkit-scrollbar,
-#neural-rendering-mode .wrap::-webkit-scrollbar,
-#upscale-mode .wrap::-webkit-scrollbar {
- display: none;
-}
-
-/* Center the About contents in the space below the compact one-row header. */
-#about-content {
- display: grid;
- place-items: center;
- min-height: calc(100dvh - 8rem);
- 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 uploaded batches inside that surface and scroll when needed. */
-#image-upload-list .file-preview-holder,
-#video-upload-list .file-preview-holder,
-#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;
-}
-
-#image-upload-list .file-preview,
-#video-upload-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. */
-#image-input-preview:has(.gallery-item:only-child),
-#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,
-#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,
-#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,
-#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,
-#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;
-}
-
-/* Neural Rendering is structurally split into several Gradio Forms by its
- two slider Rows. Visually merge only those Forms into one native-looking
- block without changing any child component sizing, spacing, or controls. */
-.neural-controls-unified {
- background: var(--block-background-fill);
- border-radius: var(--block-radius);
- box-shadow: var(--block-shadow);
- overflow: hidden;
-}
-
-.neural-controls-unified::after {
- content: "";
- position: absolute;
- inset: 0;
- box-sizing: border-box;
- border: var(--block-border-width) solid var(--block-border-color);
- border-radius: inherit;
- pointer-events: none;
- z-index: 1;
-}
-
-.neural-controls-unified .form {
- background: transparent !important;
- border-color: transparent !important;
- border-radius: 0 !important;
- box-shadow: none !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)
- 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:
- # Image and Live have no output-codec choice and remain GPU-resident.
- # Video processors derive CUDA versus host staging from their codec.
- processing_engine_state = gr.State(value=True)
- nr_mask_state = gr.State(value=None)
- with gr.Tabs(selected="neural-rendering", elem_id="main-tabs"):
- # Keep every tab tree mounted from first paint. Stateful File/Gallery/Video
- # components otherwise get lazily mounted when a tab is first selected,
- # which can briefly restore their construction-time visibility/value state.
- with gr.Tab("Neural Rendering", id="neural-rendering", render_children=True) as neural_root_tab:
- neural_rendering_tab = build_neural_rendering_tab(settings, processing_engine_state, nr_mask_state)
- with gr.Tab("Upscale", id="upscale", render_children=True) as upscale_root_tab:
- upscale_tab = build_upscale_tab(settings)
- with gr.Tab("Frame Interpolation", id="frame-interpolation", render_children=True) as frame_root_tab:
- frame_tab = build_frame_interpolation_tab(settings)
- with gr.Tab("Live", id="live", render_children=True) as live_root_tab:
- live_tab = build_live_tab(settings, processing_engine_state, nr_mask_state)
- with gr.Tab("Settings", id="settings", render_children=True) as settings_root_tab:
- settings_tab = build_settings_tab(settings, ai_gpu_choices, video_gpu_choices)
- with gr.Tab("About", id="about", render_children=True) as about_root_tab:
- build_about_tab()
-
- # Mounted video elements can otherwise keep decoding/playing while their
- # workflow is hidden. Pause media whenever the user changes top-level tabs.
- pause_media_js = """() => {
- document.querySelectorAll('video').forEach((video) => {
- try { video.pause(); } catch (_) {}
- });
- }"""
- for root_tab in (
- neural_root_tab, upscale_root_tab, frame_root_tab,
- live_root_tab, settings_root_tab, about_root_tab,
- ):
- root_tab.select(
- None, js=pause_media_js, queue=False, show_progress="hidden",
- trigger_mode="always_last",
- )
-
- # Gradio can restore construction-time child visibility when a mounted
- # top-level tab is shown again. Reconcile only the input surface state;
- # rendered outputs, save controls, and thumbnails are left untouched.
- bind_input_surface_reactivation(neural_root_tab, neural_rendering_tab.image, kind="image", event_name="select")
- bind_input_surface_reactivation(neural_root_tab, neural_rendering_tab.video, kind="video", event_name="select")
- bind_input_surface_reactivation(upscale_root_tab, upscale_tab.image, kind="image", event_name="select")
- bind_input_surface_reactivation(upscale_root_tab, upscale_tab.video, kind="video", event_name="select")
- bind_input_surface_reactivation(frame_root_tab, frame_tab, kind="video", event_name="select")
-
- bind_settings_events(
- settings_tab,
- neural_rendering_tab.image,
- neural_rendering_tab.video,
- frame_tab,
- live_tab,
- upscale_tab,
- )
- bind_composition_mask_events(
- nr_mask_state,
- neural_rendering_tab.image.composition,
- neural_rendering_tab.video.composition,
- live_tab.composition,
- )
-
- # First paint has no dataset for the CSS guards above (they only run on
- # mode.change), so both Image and Video panels would stack until the
- # first toggle. Seed both attributes on load from the construction-time
- # radio values; Neural Rendering always starts on Image, Upscale honors
- # the persisted setting. Existing change-guards remain authoritative
- # afterwards. Trees stay mounted; this only affects CSS visibility.
- initial_upscale_mode = settings.upscale_mode if settings.upscale_mode in ("Image", "Video") else "Image"
- init_mode_js = (
- "() => {"
- " try {"
- " var html = document.documentElement;"
- " if (!html.hasAttribute('data-neural-rendering-mode')) {"
- " html.setAttribute('data-neural-rendering-mode', 'Image');"
- " }"
- f" if (!html.hasAttribute('data-upscale-mode')) {{"
- f" html.setAttribute('data-upscale-mode', '{initial_upscale_mode}');"
- " }"
- " var hiddenIds = [];"
- " if (html.getAttribute('data-neural-rendering-mode') === 'Video') {"
- " hiddenIds.push('neural-rendering-image');"
- " } else {"
- " hiddenIds.push('neural-rendering-video');"
- " }"
- " if (html.getAttribute('data-upscale-mode') === 'Video') {"
- " hiddenIds.push('upscale-image');"
- " } else {"
- " hiddenIds.push('upscale-video');"
- " }"
- " hiddenIds.forEach(function (id) {"
- " var panel = document.getElementById(id);"
- " if (panel) { panel.querySelectorAll('video').forEach(function (node) {"
- " try { node.pause(); } catch (_) {}"
- " }); }"
- " });"
- " } catch (_) {}"
- "}"
- )
- demo.load(
- None, js=init_mode_js, queue=False, show_progress="hidden",
- trigger_mode="always_last",
- )
- 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:
- prepared = prepare_runtime()
- except Exception as exc:
- try:
- from src.core import app_log
-
- app_log.error("startup", f"preparation failed: {exc}")
- except Exception:
- pass
- raise SystemExit(1) from exc
- try:
- from src.core import app_log
-
- app_log.info("startup", f"ready gpu={prepared.gpu.get('display_name', 'GPU')}")
- except Exception:
- pass
-
- 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
- finally:
- try:
- from src.core import app_log
-
- app_log.info("app", "stop")
- except Exception:
- pass
+def main() -> int:
+ """Launch the PySide6 + Qt Quick/QML desktop application."""
+ return launch_desktop()
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/src/__init__.py b/src/__init__.py
index 9bf2145..7f4ebd7 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -1,4 +1,4 @@
-"""Portable DLSS 5 Visual Enhancer for images and video."""
+"""Portable Visual Enhancer for images and video."""
from .core.ffmpeg import probe_video
from .neural_rendering.image import (
diff --git a/src/about/ui.py b/src/about/ui.py
deleted file mode 100644
index 68f985a..0000000
--- a/src/about/ui.py
+++ /dev/null
@@ -1,27 +0,0 @@
-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 v9.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/Merserk"
- target="_blank" rel="noopener noreferrer">Patreon</a>
- <span class="about-description">Support the creator and future development.</span>
- </p>
- </div>
- <p class="about-copyright">&copy; Merserk</p>
- </section>
- """,
- elem_id="about-content",
- padding=False,
- )
diff --git a/src/core/app_log.py b/src/core/app_log.py
index 7994a36..57cd9e9 100644
--- a/src/core/app_log.py
+++ b/src/core/app_log.py
@@ -19,6 +19,7 @@ from .paths import LOGS
_lock = threading.Lock()
_handle: io.TextIOWrapper | None = None
_session_path: Path | None = None
+_listeners: set = set()
MAX_MSG = 300
MAX_TAIL = 500
@@ -96,6 +97,18 @@ def session_path() -> str:
return str(init_session())
+
+def add_listener(callback) -> None:
+ """Subscribe to structured log events: ``callback(level, tag, message)``."""
+ with _lock:
+ _listeners.add(callback)
+
+
+def remove_listener(callback) -> None:
+ with _lock:
+ _listeners.discard(callback)
+
+
def _write(level: str, tag: str, msg: str) -> None:
global _handle
line = f"[{time.strftime('%H:%M:%S')}] {level} {tag}: {msg}\n"
@@ -117,8 +130,14 @@ def _write(level: str, tag: str, msg: str) -> None:
with _lock:
handle.write(line)
handle.flush()
+ listeners = tuple(_listeners)
except (OSError, ValueError):
- pass
+ listeners = ()
+ for callback in listeners:
+ try:
+ callback(level, tag, msg)
+ except Exception:
+ pass
def info(tag: str, msg: object) -> None:
diff --git a/src/core/batch_ui.py b/src/core/batch_ui.py
deleted file mode 100644
index c8431f1..0000000
--- a/src/core/batch_ui.py
+++ /dev/null
@@ -1,871 +0,0 @@
-"""Shared Gradio disk controls and a bounded, session-owned streaming batch UI."""
-from __future__ import annotations
-
-import json
-import threading
-import uuid
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import gradio as gr
-
-from .batch_progress import BatchProgress
-from .disk_paths import create_media_archive, direct_disk_mode, prepare_output_dir, resolve_inputs
-from .jobs import JobController, use_job_controller
-from .paths import GRADIO_TEMP
-
-BATCH_HEADERS = ["File", "State", "Progress", "Elapsed", "Output path", "Details"]
-
-
-def build_path_controls():
- # Keep the two disk-path fields in their own layout scope. Without an
- # explicit boundary Gradio may merge adjacent encoding/output controls
- # into the same generated Form, producing inconsistent visual grouping
- # between workflows. A default Column is structural only (no panel
- # styling), so the path fields retain their existing native appearance.
- with gr.Column():
- source = gr.Textbox(
- label="Input path (Optional)", placeholder=r"D:\Render\inputs",
- )
- destination = gr.Textbox(
- label="Output path (Optional)", placeholder=r"D:\Render\outputs",
- )
- 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 build_save_controls(kind: str, elem_id: str):
- """Build direct-save and lazy-archive controls for an image/video batch tab."""
- if kind not in {"image", "video"}:
- raise ValueError(f"Unknown media type: {kind}")
- direct = gr.DownloadButton(
- f"Save {kind.title()}", value=None, visible=False, elem_id=f"{elem_id}-direct-save"
- )
- archive = gr.Button("Save as ZIP", visible=False, elem_id=f"{elem_id}-save-zip")
- # Keep the internal download target permanently rendered so the chained JS
- # action can click it after lazy ZIP creation. It is hidden exclusively by
- # application CSS instead of Gradio's visibility state; tab remounts can
- # otherwise leak a `visible="hidden"` DownloadButton into the normal UI.
- archive_download = gr.DownloadButton(
- "Download ZIP",
- value=None,
- visible=True,
- elem_id=f"{elem_id}-zip-download",
- elem_classes=["internal-zip-download"],
- )
- return direct, archive, archive_download
-
-
-def _stable_visible(show: bool):
- """Keep stateful media components mounted even when they are not displayed."""
- return True if show else "hidden"
-
-
-def input_surface_updates(show_preview: bool, input_path: str | None = None):
- """Atomically swap upload/preview actions without unmounting either tree."""
- upload_enabled = not bool(str(input_path or "").strip())
- return (
- gr.update(visible=_stable_visible(not show_preview), interactive=upload_enabled),
- gr.update(visible=show_preview and upload_enabled),
- )
-
-
-class BatchRun:
- def __init__(self, paths):
- self.controller = JobController()
- self.progress = BatchProgress(paths)
- self.done = threading.Event()
- self.result = None
- self.error = ""
- self.thread = None
- self.is_preview = False
- self.is_auto_preview = False
-
- def start(self, operation):
- def work():
- try:
- with use_job_controller(self.controller):
- self.result = operation(self)
- except BaseException as exc:
- self.error = str(exc)
- self.progress.finish(cancelled=self.controller.cancel.is_set(), error=str(exc))
- finally:
- self.done.set()
- self.thread = threading.Thread(target=work, name="dlss-batch-ui", daemon=True)
- self.thread.start()
-
- def close(self):
- if not self.done.is_set():
- self.controller.stop()
- if self.thread is not None:
- self.thread.join()
-
-
-@dataclass(frozen=True, slots=True)
-class _FileIdentity:
- path: str
- device: int
- inode: int
- size: int
- mtime_ns: int
-
-
-@dataclass(slots=True)
-class _DownloadState:
- kind: str
- input_count: int
- paths: tuple[str, ...]
- identities: tuple[_FileIdentity, ...]
- output_dir: str
- archive_prefix: str
- archive_path: str | None = None
- archive_lock: threading.Lock = field(default_factory=threading.Lock)
-
-
-@dataclass
-class _View:
- lock: threading.RLock = field(default_factory=threading.RLock)
- job: BatchRun | None = None
- revision: int = 0
- disk: bool = False
- download: _DownloadState | None = None
- # Input media preparation can be slower than navigation (RAW/HEIF/image
- # thumbnails, video inspection). Track readiness independently so a tab
- # reactivation can hide stale construction-time controls until the accepted
- # refresh has completed.
- input_ready: bool = True
- auto_revision: int = 0
- auto_preview_path: str | None = None
-
-
-_views: dict[str, _View] = {}
-_views_lock = threading.Lock()
-
-
-def _view(key):
- with _views_lock:
- return _views.setdefault(key, _View())
-
-
-def _discard_auto_preview(path: str | None) -> None:
- """Remove only previews owned by the app's managed Gradio temp tree."""
- if not path:
- return
- try:
- candidate = Path(path).resolve()
- root = GRADIO_TEMP.resolve()
- if candidate.is_relative_to(root):
- candidate.unlink(missing_ok=True)
- try:
- candidate.parent.rmdir()
- except OSError:
- pass
- except (OSError, RuntimeError, ValueError):
- pass
-
-
-def _managed_preview_path(media) -> str | None:
- """Find a generated media path inside a Gradio update/value structure."""
- if isinstance(media, (str, Path)):
- try:
- candidate = Path(media).resolve()
- if candidate.is_file() and candidate.is_relative_to(GRADIO_TEMP.resolve()):
- return str(candidate)
- except (OSError, RuntimeError, ValueError):
- return None
- return None
- if isinstance(media, dict):
- return _managed_preview_path(media.get("value"))
- if isinstance(media, (list, tuple)):
- for item in media:
- if path := _managed_preview_path(item):
- return path
- return None
-
-
-def release_view(key):
- with _views_lock:
- view = _views.pop(key, None)
- if view and view.job:
- view.job.controller.stop()
- if view:
- _discard_auto_preview(view.auto_preview_path)
-
-
-def _uploaded_source_count(value) -> int:
- if isinstance(value, str):
- return 1 if value.strip() else 0
- try:
- return len(list(value or []))
- except TypeError:
- return 1 if value else 0
-
-
-def _has_uploaded_sources(value) -> bool:
- return _uploaded_source_count(value) > 0
-
-
-def bind_input_surface_reactivation(trigger, tab, *, kind: str, event_name: str | None = None):
- """Re-assert one tab's upload/preview visibility after navigation.
-
- Gradio may restore a child component's construction-time visibility when a
- parent Tab/Column is hidden and shown again. Uploaded values themselves are
- still correct, so this callback intentionally changes *visibility only*: it
- never regenerates thumbnails, clears outputs, invalidates downloads, or
- mutates render state. If an input refresh is still running, both the upload
- and preview are kept hidden until that accepted refresh publishes its final
- state.
- """
- if kind not in {"image", "video"}:
- raise ValueError(f"Unknown media type: {kind}")
- input_media = tab.input_gallery if kind == "image" else tab.input_preview
- preview_buttons = [
- component for name in ("preview_frame", "preview")
- if (component := getattr(tab, name, None)) is not None
- ]
-
- def reconcile(key, input_path, output_path, sources):
- view = _view(key)
- disk = direct_disk_mode(input_path, output_path)
- source_count = _uploaded_source_count(sources)
- has_sources = source_count > 0
- with view.lock:
- ready = view.input_ready
-
- # Direct-disk mode intentionally uses the original upload/path surface
- # rules and suppresses browser previews/downloads.
- if disk:
- return (
- gr.update(visible=True),
- gr.update(visible="hidden"),
- gr.update(visible=False),
- *[gr.update(visible=False) for _ in preview_buttons],
- )
- if not has_sources:
- return (
- gr.update(visible=True),
- gr.update(visible="hidden"),
- gr.update(visible=False),
- *[gr.update(visible=False) for _ in preview_buttons],
- )
- if not ready:
- # The source exists but its preview is still being prepared. Never
- # flash the upload box as if the workspace were empty.
- return (
- gr.update(visible="hidden"),
- gr.update(visible="hidden"),
- gr.update(visible=False),
- *[gr.update(visible=False) for _ in preview_buttons],
- )
- return (
- gr.update(visible="hidden"),
- gr.update(visible=True),
- gr.update(visible=True),
- *[gr.update(visible=source_count == 1) for _ in preview_buttons],
- )
-
- inputs = [tab.job_state, tab.input_path, tab.output_path, tab.sources]
- outputs = [tab.sources, input_media, tab.input_actions, *preview_buttons]
- kwargs = dict(
- inputs=inputs, outputs=outputs, queue=False, show_progress="hidden",
- trigger_mode="always_last",
- )
- if event_name is None:
- return trigger.then(reconcile, **kwargs)
- return getattr(trigger, event_name)(reconcile, **kwargs)
-
-
-def _identity(path: str) -> _FileIdentity:
- source = Path(path).resolve()
- stat = source.stat()
- if not source.is_file():
- raise ValueError(f"Rendered output is no longer a file: {source}")
- return _FileIdentity(
- str(source), int(stat.st_dev), int(stat.st_ino), int(stat.st_size), int(stat.st_mtime_ns)
- )
-
-
-def _validate_download_state(state: _DownloadState) -> None:
- current = tuple(_identity(path) for path in state.paths)
- if current != state.identities:
- raise ValueError(
- "One or more rendered outputs changed or were removed after rendering. "
- "Render the batch again before creating its ZIP."
- )
-
-
-def _archive_trigger_js(elem_id: str) -> str:
- encoded = json.dumps(elem_id)
- return f"""() => {{
- const root = document.getElementById({encoded});
- const target = root && (root.matches('a,button') ? root : root.querySelector('a,button'));
- if (target) target.click();
- }}"""
-
-
-def bind_batch_ui(
- tab, render_function, *, kind, preview_mode, archive_prefix: str, preview_actions=(),
- realtime_preview=None, realtime_components=(),
-):
- """Bind one batch tab, including direct single-file and lazy multi-file downloads.
-
- Render callbacks return four values: display media, successful master output
- paths, batch rows, and status text. The archive is intentionally *not* part
- of rendering; it is created only when the user clicks Save as ZIP.
- """
- 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
- display_media = tab.output_gallery if is_image else tab.output_video
- direct_save = tab.save_download
- archive_button = tab.zip_button
- archive_download = tab.zip_download
- media_outputs = [display_media, direct_save, archive_button, archive_download]
- preview_buttons = [button for button, _fn in preview_actions]
- controls = [
- tab.sources, tab.select_source, tab.clear_source, tab.input_path, tab.output_path,
- tab.render, tab.reset, *preview_buttons,
- ]
- outputs = [*media_outputs, tab.results, tab.status, *controls]
- path_inputs = [tab.job_state, tab.input_path, tab.output_path]
-
- def empty_save_controls():
- return (
- gr.update(value=None, visible=False),
- gr.update(visible=False),
- gr.update(value=None),
- )
-
- def empty_media(disk):
- return [
- gr.update(value=None, visible=not disk),
- *empty_save_controls(),
- ]
-
- def completed_media(result, disk, *, input_count: int, destination: str, view: _View):
- if result is None or disk:
- with view.lock:
- view.download = None
- return empty_media(disk)
-
- display_value, successful_paths, _rows, _status = result
- successful_paths = tuple(str(Path(path).resolve()) for path in (successful_paths or []))
- if not successful_paths:
- with view.lock:
- view.download = None
- return [display_value, *empty_save_controls()]
-
- try:
- identities = tuple(_identity(path) for path in successful_paths)
- except Exception:
- # Rendering reported a success that cannot be downloaded anymore.
- # Keep the media preview/result rows, but never expose a stale save action.
- with view.lock:
- view.download = None
- return [display_value, *empty_save_controls()]
-
- state = _DownloadState(
- kind=kind,
- input_count=input_count,
- paths=successful_paths,
- identities=identities,
- output_dir=destination,
- archive_prefix=archive_prefix,
- )
- with view.lock:
- view.download = state
-
- if input_count == 1:
- return [
- display_value,
- gr.update(value=successful_paths[0], visible=True, label=f"Save {kind.title()}"),
- gr.update(visible=False),
- gr.update(value=None),
- ]
- return [
- display_value,
- gr.update(value=None, visible=False),
- gr.update(visible=True),
- gr.update(value=None),
- ]
-
- def control_updates(busy, input_path):
- 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)
- disk = direct_disk_mode(input_path, output_path)
- with view.lock:
- view.revision += 1
- revision = view.revision
- view.disk = disk
- view.download = None
- view.input_ready = False
- busy = view.job is not None and not view.job.done.is_set()
- if busy and disk and view.job is not None and view.job.is_preview:
- view.job.controller.stop()
- if busy and not disk:
- with view.lock:
- if revision == view.revision:
- view.input_ready = True
- return [gr.skip()] * (1 + len(media_outputs) + len(preview_buttons) + 2)
- show_input_media = False
- try:
- if disk:
- values = [gr.update(value=None, visible="hidden"), *empty_media(True),
- *[gr.update(visible=False) for _ in preview_buttons]]
- elif is_image:
- previews = preview_mode(args[0])
- show_input_media = bool(previews)
- source_count = _uploaded_source_count(args[0])
- values = [
- gr.update(value=previews, visible=_stable_visible(show_input_media)),
- *empty_media(False),
- *[gr.update(visible=source_count == 1) for _ in preview_buttons],
- ]
- else:
- input_update, output_update, *buttons = preview_mode(*args)
- sources = args[0]
- show_input_media = bool([sources] if isinstance(sources, str) else list(sources or []))
- values = [input_update, output_update, *empty_save_controls(), *buttons]
- except BaseException:
- with view.lock:
- if revision == view.revision:
- view.input_ready = True
- raise
- with view.lock:
- if revision != view.revision:
- return [gr.skip()] * (1 + len(media_outputs) + len(preview_buttons) + 2)
- view.input_ready = True
- 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_outputs, *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):
- # 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",
- trigger_mode="always_last",
- )
-
- def stream(key, input_path, output_path, *args):
- view = _view(key)
- with view.lock:
- if view.job is not None:
- raise gr.Error("A job is already running in this tab.")
- job = BatchRun([])
- view.job = job
- view.download = None
- view.disk = direct_disk_mode(input_path, output_path)
- disk = view.disk
- destination = ""
- started = False
- paths = []
- try:
- # Resolve once. Direct paths never become a gr.File/gr.Video/Gallery value.
- paths = resolve_inputs(input_path, args[0], kind)
- destination = str(prepare_output_dir(output_path, user_input=True))
- job.progress = BatchProgress(paths)
- row_values, status = job.progress.display(destination)
- yield (*empty_media(disk), row_values, status, *control_updates(True, input_path))
-
- def operation(run):
- return render_function(
- paths, *args[1:], progress=lambda *a, **k: None,
- output_dir=destination, controller=run.controller,
- on_item_update=run.progress.apply, direct_disk=disk,
- )
-
- job.start(operation)
- started = True
- while not job.done.wait(.25):
- with view.lock:
- if view.job is not job:
- return
- row_values, status = job.progress.display(destination)
- if job.controller.cancel.is_set():
- status += "\nStopping — cleaning up the current job. Completed outputs will be kept."
- # No media postprocessing/cache transfer during progress refreshes.
- yield (*[gr.skip() for _ in media_outputs], row_values, status,
- *[gr.skip() for _ in controls])
- job.close()
- row_values, status = job.progress.display(destination)
- final_media = completed_media(
- job.result, disk, input_count=len(paths), destination=destination, view=view
- )
- if job.error and job.error not in status:
- status += f"\n{job.error}"
- with view.lock:
- if view.job is not job:
- return
- yield (*final_media, row_values, status, *control_updates(False, input_path))
- except Exception as exc:
- job.progress.finish(cancelled=job.controller.cancel.is_set(), error=str(exc))
- row_values, status = job.progress.display(destination)
- with view.lock:
- view.download = None
- yield (*empty_media(view.disk), row_values, status, *control_updates(False, input_path))
- finally:
- if started:
- job.close()
- with view.lock:
- if view.job is job:
- view.job = None
-
- tab.render.click(
- stream,
- inputs=[*path_inputs, *tab.render_inputs],
- outputs=outputs,
- concurrency_limit=None,
- trigger_mode="once",
- show_progress="hidden",
- )
-
- def stop(key):
- view = _view(key)
- with view.lock:
- job = view.job
- if job is not None and not job.done.is_set():
- job.controller.stop()
- # The streaming callback remains the only writer of batch status.
- return gr.skip()
-
- tab.stop.click(stop, inputs=tab.job_state, outputs=tab.status, queue=False, show_progress="hidden")
-
- def create_lazy_archive(key):
- view = _view(key)
- with view.lock:
- state = view.download
- busy = view.job is not None and not view.job.done.is_set()
- if busy:
- raise gr.Error("Wait for the current render to finish before creating its ZIP.")
- if state is None or state.input_count < 2 or not state.paths:
- raise gr.Error("There is no completed multi-file batch to save as ZIP.")
- with state.archive_lock:
- try:
- _validate_download_state(state)
- if state.archive_path and Path(state.archive_path).is_file():
- archive_path = state.archive_path
- else:
- archive_path = create_media_archive(
- state.paths, state.output_dir, state.archive_prefix
- )
- if not archive_path:
- raise RuntimeError("The ZIP archive was not created.")
- state.archive_path = archive_path
- return gr.update(value=archive_path)
- except gr.Error:
- raise
- except Exception as exc:
- raise gr.Error(f"Could not create ZIP: {exc}") from exc
-
- archive_event = archive_button.click(
- create_lazy_archive,
- inputs=tab.job_state,
- outputs=archive_download,
- concurrency_limit=1,
- trigger_mode="once",
- show_progress="minimal",
- )
- archive_event.success(
- fn=None,
- js=_archive_trigger_js(archive_download.elem_id),
- queue=False,
- show_progress="hidden",
- )
-
- def guarded_preview(function):
- def preview(key, input_path, output_path, *args, progress=gr.Progress(track_tqdm=False)):
- def empty_preview(media, status):
- return (media, status, *empty_save_controls())
-
- view = _view(key)
- if direct_disk_mode(input_path, output_path):
- with view.lock:
- view.download = None
- yield empty_preview(
- gr.update(value=None, visible=False),
- "Previews are disabled when a path is supplied.",
- )
- return
- with view.lock:
- if view.job is not None:
- raise gr.Error("A job is already running in this tab.")
- job = BatchRun([])
- job.is_preview = True
- view.job = job
- view.download = None
- revision = view.revision
- # Hide every save action before expensive preview work starts so a
- # previous completed render can never be downloaded as if it were
- # the new preview/result.
- yield (gr.skip(), gr.skip(), *empty_save_controls())
- try:
- with use_job_controller(job.controller):
- result = function(*args, progress=progress)
- if job.controller.cancel.is_set():
- yield empty_preview(gr.update(value=None, visible=False), "Preview cancelled.")
- return
- with view.lock:
- stale = view.revision != revision or view.disk
- if stale:
- yield (gr.skip(),) * 5
- return
- yield (*result, *empty_save_controls())
- finally:
- job.done.set()
- with view.lock:
- if view.job is job:
- view.job = None
- return preview
-
- for button, function in preview_actions:
- button.click(
- guarded_preview(function),
- inputs=[*path_inputs, *tab.preview_inputs],
- outputs=[display_media, tab.status, direct_save, archive_button, archive_download],
- concurrency_limit=None,
- show_progress="hidden",
- )
-
- if realtime_preview is None:
- return
-
- # User input invalidates the current preview synchronously, even while its
- # queued backend call is still evaluating. Slider previews trigger on
- # release so dragging never launches one GPU job per intermediate value;
- # dropdown/radio changes trigger immediately.
- auto_token = gr.State(0)
-
- def invalidate_auto_preview(key, sources):
- view = _view(key)
- old_path = None
- with view.lock:
- view.auto_revision += 1
- token = view.auto_revision
- job = view.job
- if job is not None and job.is_preview and not job.done.is_set():
- job.controller.stop()
- if _uploaded_source_count(sources) != 1:
- old_path = view.auto_preview_path
- view.auto_preview_path = None
- _discard_auto_preview(old_path)
- return token
-
- def automatic_preview(
- key, token, input_path, output_path, *args,
- progress=gr.Progress(track_tqdm=False),
- ):
- unchanged = (gr.skip(),) * 5
- view = _view(key)
- try:
- token = int(token)
- except (TypeError, ValueError):
- yield unchanged
- return
- if direct_disk_mode(input_path, output_path) or _uploaded_source_count(args[0]) != 1:
- yield unchanged
- return
-
- with view.lock:
- stale = token != view.auto_revision
- existing = view.job
- if stale:
- yield unchanged
- return
- if existing is not None and not existing.done.is_set():
- if not existing.is_preview:
- # Production output owns the tab and the process-wide GPU slot.
- yield unchanged
- return
- existing.controller.stop()
- if not existing.done.wait(5.0):
- yield unchanged
- return
-
- with view.lock:
- stale = token != view.auto_revision or view.disk
- busy = view.job is not None and not view.job.done.is_set()
- if not stale and not busy:
- job = BatchRun([])
- job.is_preview = True
- job.is_auto_preview = True
- view.job = job
- view.download = None
- source_revision = view.revision
- if stale or busy:
- yield unchanged
- return
-
- # Preserve the current visual until its replacement is ready, but hide
- # save actions immediately because this is an ephemeral preview.
- yield (gr.skip(), gr.skip(), *empty_save_controls())
- preview_dir = GRADIO_TEMP / "neural-realtime" / str(key)
- preview_dir.mkdir(parents=True, exist_ok=True)
- try:
- # A short quiet window coalesces keyboard/radio changes that arrive
- # together (for example a preset selection updating several fields).
- if job.controller.cancel.wait(0.18):
- yield unchanged
- return
- with view.lock:
- stale = token != view.auto_revision
- if stale:
- yield unchanged
- return
- with use_job_controller(job.controller):
- result = realtime_preview(
- *args,
- progress=progress,
- output_dir=preview_dir,
- controller=job.controller,
- ephemeral_preview=True,
- )
- with view.lock:
- stale = (
- job.controller.cancel.is_set()
- or token != view.auto_revision
- or source_revision != view.revision
- or view.disk
- )
- if stale:
- _discard_auto_preview(_managed_preview_path(result[0]))
- yield unchanged
- return
-
- managed_path = _managed_preview_path(result[0])
- with view.lock:
- old_path = view.auto_preview_path
- view.auto_preview_path = managed_path
- if old_path != managed_path:
- _discard_auto_preview(old_path)
- yield (*result, *empty_save_controls())
- except Exception as exc:
- with view.lock:
- stale = job.controller.cancel.is_set() or token != view.auto_revision
- if stale:
- yield unchanged
- else:
- yield (
- gr.skip(),
- f"Automatic preview failed: {exc}",
- *empty_save_controls(),
- )
- finally:
- job.done.set()
- with view.lock:
- if view.job is job:
- view.job = None
-
- triggers = [tab.sources.change]
- triggers.extend(
- component.release if isinstance(component, gr.Slider) else component.input
- for component in realtime_components
- )
- invalidated = gr.on(
- triggers=triggers,
- fn=invalidate_auto_preview,
- inputs=[tab.job_state, tab.sources],
- outputs=auto_token,
- queue=False,
- show_progress="hidden",
- trigger_mode="always_last",
- api_visibility="private",
- )
- invalidated.then(
- automatic_preview,
- inputs=[
- tab.job_state, auto_token, tab.input_path, tab.output_path,
- *tab.preview_inputs,
- ],
- outputs=[display_media, tab.status, direct_save, archive_button, archive_download],
- concurrency_limit=1,
- concurrency_id="neural-realtime-preview",
- trigger_mode="always_last",
- show_progress="hidden",
- api_visibility="private",
- )
-
- def refresh_realtime_preview_after(trigger):
- """Regenerate this tab's preview after a successful programmatic update."""
- reset_invalidated = trigger.success(
- invalidate_auto_preview,
- inputs=[tab.job_state, tab.sources],
- outputs=auto_token,
- queue=False,
- show_progress="hidden",
- trigger_mode="always_last",
- api_visibility="private",
- )
- return reset_invalidated.then(
- automatic_preview,
- inputs=[
- tab.job_state, auto_token, tab.input_path, tab.output_path,
- *tab.preview_inputs,
- ],
- outputs=[display_media, tab.status, direct_save, archive_button, archive_download],
- concurrency_limit=1,
- concurrency_id="neural-realtime-preview",
- trigger_mode="always_last",
- show_progress="hidden",
- api_visibility="private",
- )
-
- return refresh_realtime_preview_after
diff --git a/src/core/cache_cleanup.py b/src/core/cache_cleanup.py
index fe9fcfc..88287cb 100644
--- a/src/core/cache_cleanup.py
+++ b/src/core/cache_cleanup.py
@@ -1,13 +1,11 @@
from __future__ import annotations
-"""Automatic cleanup of stale app-local Gradio caches and job leftovers.
+"""Automatic cleanup of stale app-local temp caches and job leftovers.
-Official Gradio cleanup (``gr.Blocks(delete_cache=...)``) handles tracked
-session files while the server runs and on graceful shutdown. Crash-orphaned
-files are covered here by an age-gated startup sweep over only this install's
-portable locations:
+Crash-orphaned files are covered here by an age-gated startup sweep over only
+this install's portable locations:
-1. ``<app>/temp/gradio`` (Gradio uploads/cache plus UI-owned temp artifacts).
+1. ``<app>/temp/app`` (native Qt preview/preset temp artifacts).
2. Orphaned ``<app>/jobs/*`` per-render dirs left behind by killed runs.
No system/user temp directory is inspected or migrated. This build is isolated
@@ -21,18 +19,18 @@ import shutil
import time
from pathlib import Path
-from .paths import GRADIO_TEMP, JOBS
+from .paths import APP_TEMP, JOBS
-# Agreed retention: sweep hourly while running (via Blocks delete_cache),
-# treat anything older than 24h as stale (startup sweep + periodic sweep).
+# Agreed retention: treat anything older than 24h as stale
+# (startup sweep + periodic sweep).
CACHE_SWEEP_INTERVAL_SECONDS = 3600
CACHE_MAX_AGE_SECONDS = 24 * 3600
-def resolve_gradio_temp_dir() -> Path | None:
- """Return this installation's fixed app-local Gradio temp directory."""
+def resolve_app_temp_dir() -> Path | None:
+ """Return this installation's fixed app-local temp directory."""
try:
- resolved = GRADIO_TEMP.resolve()
+ resolved = APP_TEMP.resolve()
except OSError:
return None
return resolved if resolved.is_dir() else None
@@ -110,10 +108,10 @@ def cleanup_old_caches(
removed_total = 0
freed_total = 0
- gradio_dir = resolve_gradio_temp_dir()
- if gradio_dir is not None:
+ app_dir = resolve_app_temp_dir()
+ if app_dir is not None:
try:
- removed, freed = sweep_dir_by_age(gradio_dir, max_age_seconds)
+ removed, freed = sweep_dir_by_age(app_dir, max_age_seconds)
removed_total += removed
freed_total += freed
except Exception:
diff --git a/src/core/ffmpeg/encoder.py b/src/core/ffmpeg/encoder.py
index 212504d..518de37 100644
--- a/src/core/ffmpeg/encoder.py
+++ b/src/core/ffmpeg/encoder.py
@@ -40,6 +40,7 @@ def _encoder_probe(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
).returncode
== 0
)
diff --git a/src/core/ffmpeg/preview.py b/src/core/ffmpeg/preview.py
index c5032b1..99eb422 100644
--- a/src/core/ffmpeg/preview.py
+++ b/src/core/ffmpeg/preview.py
@@ -151,6 +151,7 @@ def make_browser_preview(
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8", errors="replace",
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
if controller is not None:
controller.register(process)
@@ -175,6 +176,142 @@ def make_browser_preview(
return str(dest)
+def extract_preview_subclip(
+ source: str | Path,
+ dest_dir: str | Path | None = None,
+ *,
+ start_seconds: float = 0.0,
+ length_seconds: float | None = None,
+ single_frame: bool = False,
+ controller=None,
+) -> str:
+ """Extract a frame-quantized subclip starting at ``start_seconds``.
+
+ Callers pass the *nominal frame start* ``(N-1)/fps`` matching the timeline
+ counter ``floor(position*fps)+1``. A raw playhead anywhere inside frame N
+ would otherwise select N+1, because ``-ss`` emits the first frame with
+ ``pts >= START``. A 2 ms epsilon absorbs ``%.6f`` rounding on
+ non-terminating rates (23.976/29.97) so the seek lands on N, not N+1.
+ Accurate output seeking (``-i`` then ``-ss``) is used with a 2 s fast
+ pre-seek so long 4K files stay fast while remaining frame-exact.
+ Returns the temp clip path as string. Caller owns cleanup.
+ """
+ from ..disk_paths import OutputFile
+ from ..jobs import current_job_controller
+
+ controller = controller or current_job_controller()
+ src = Path(source)
+ if not src.is_file():
+ raise FileNotFoundError(src)
+ try:
+ start = max(0.0, float(start_seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
+ if start <= 0.05 and not single_frame and not length_seconds:
+ return str(src)
+ # Epsilon: land just inside the intended frame's leading edge.
+ aligned = max(0.0, start - 0.002)
+ fast = max(0.0, aligned - 2.0)
+ accurate = max(0.0, aligned - fast)
+ from ..paths import OUTPUTS
+ out_dir = Path(dest_dir) if dest_dir is not None else OUTPUTS
+ out_dir.mkdir(parents=True, exist_ok=True)
+ suffix = "_PLAYHEADFRAME.mp4" if single_frame else "_PLAYHEAD.mp4"
+ dest = out_dir / f"{src.stem}{suffix}"
+ counter = 1
+ while dest.exists():
+ counter += 1
+ dest = out_dir / f"{src.stem}{suffix.replace('.mp4', f'_{counter}.mp4')}"
+ output_file = OutputFile(dest)
+ command = [
+ str(FFMPEG), "-hide_banner", "-loglevel", "warning", "-y",
+ "-ss", f"{fast:.6f}", "-i", str(src),
+ "-ss", f"{accurate:.6f}",
+ ]
+ if single_frame:
+ command += ["-frames:v", "1"]
+ elif length_seconds is not None and float(length_seconds) > 0:
+ command += ["-t", f"{float(length_seconds):.6f}"]
+ command += [
+ "-map", "0:v:0",
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "16",
+ "-pix_fmt", "yuv420p",
+ "-movflags", "+faststart",
+ str(output_file.temporary),
+ ]
+ process = None
+ try:
+ process = subprocess.Popen(
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, encoding="utf-8", errors="replace",
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ if controller is not None:
+ controller.register(process)
+ _stdout, stderr = process.communicate()
+ if process.returncode:
+ app_log.error("ffmpeg-preview", "playhead subclip failed", (stderr or "")[-500:])
+ raise RuntimeError("Playhead subclip failed:\n" + (stderr or "")[-2000:])
+ if not Path(output_file.temporary).is_file():
+ raise RuntimeError("Playhead subclip produced no file.")
+ if controller is not None and controller.cancel.is_set():
+ from ..jobs import Cancelled
+ raise Cancelled("Preview cancelled.")
+ output_file.publish()
+ finally:
+ if process is not None:
+ if process.poll() is None:
+ process.terminate()
+ process.communicate()
+ if controller is not None:
+ controller.unregister(process)
+ output_file.cleanup()
+ return str(dest)
+
+
+def grab_video_poster_jpeg(
+ source: str | Path,
+ *,
+ seconds: float = 0.0,
+ max_width: int = 960,
+ controller=None,
+) -> bytes:
+ """Extract one JPEG still at ``seconds`` for the QML poster fallback."""
+ import subprocess as _sp
+
+ src = Path(source)
+ if not src.is_file():
+ raise FileNotFoundError(src)
+ try:
+ start = max(0.0, float(seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
+ aligned = max(0.0, start - 0.002)
+ fast = max(0.0, aligned - 2.0)
+ accurate = max(0.0, aligned - fast)
+ command = [
+ str(FFMPEG), "-hide_banner", "-loglevel", "error", "-y",
+ "-ss", f"{fast:.6f}", "-i", str(src),
+ "-ss", f"{accurate:.6f}", "-frames:v", "1",
+ *([ "-vf", f"scale={int(max_width)}:-2"] if max_width and max_width > 0 else []),
+ "-q:v", "3", "-f", "mjpeg", "pipe:1",
+ ]
+ process = _sp.Popen(
+ command, stdout=_sp.PIPE, stderr=_sp.PIPE,
+ creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0),
+ )
+ try:
+ out, err = process.communicate(timeout=30)
+ except _sp.TimeoutExpired:
+ process.kill()
+ out, err = process.communicate()
+ raise RuntimeError("Poster extraction timed out.")
+ if process.returncode or not out:
+ detail = (err.decode("utf-8", "replace") if isinstance(err, bytes) else str(err or ""))[-500:]
+ raise RuntimeError(f"Poster extraction failed: {detail}")
+ return bytes(out)
+
+
def resolve_final_preview(
result_path: str | Path | None,
mode: object,
diff --git a/src/core/gpu_detection.py b/src/core/gpu_detection.py
index 721c635..1b0963e 100644
--- a/src/core/gpu_detection.py
+++ b/src/core/gpu_detection.py
@@ -62,7 +62,10 @@ def detect_gpus() -> tuple[dict[str, Any], ...]:
"--format=csv,noheader,nounits",
]
try:
- result = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ result = subprocess.run(
+ command, capture_output=True, text=True, timeout=10,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
except (OSError, subprocess.TimeoutExpired) as exc:
raise RuntimeError(
"NVIDIA driver tools are unavailable; an RTX GPU and current driver are required."
diff --git a/src/core/neural_bridge.py b/src/core/neural_bridge.py
index 8c32d81..f3da295 100644
--- a/src/core/neural_bridge.py
+++ b/src/core/neural_bridge.py
@@ -34,6 +34,22 @@ FORMAT_NV12 = 2
FORMAT_P010 = 3
+def _bridge_failure_requires_restart(detail: str) -> bool:
+ """Return whether retrying through either memory path is unsafe/useless."""
+ lowered = detail.lower()
+ return any(
+ marker in lowered
+ for marker in (
+ "corrupt",
+ "access violation",
+ "device recovery failed",
+ "device recovery aborted",
+ "device removal",
+ "reinitialization failed",
+ )
+ )
+
+
class FrameDescriptorV1(ctypes.Structure):
_fields_ = [
("struct_size", ctypes.c_uint32),
@@ -1237,7 +1253,7 @@ class NeuralBridgeManager:
elapsed = time.perf_counter() - started
if not ok:
detail = _text(error.value) or "unknown CUDA frame-ABI failure"
- if "corrupt" in detail.lower() or "access violation" in detail.lower():
+ if _bridge_failure_requires_restart(detail):
self._poisoned_reason = detail
raise NeuralBridgePoisonedError(
f"{detail}. Restart the application before rendering again."
@@ -1551,7 +1567,7 @@ class NeuralBridgeManager:
elapsed = time.perf_counter() - started
if not ok:
detail = _text(error.value) or "unknown feature-18 failure"
- if "corrupt" in detail.lower() or "access violation" in detail.lower():
+ if _bridge_failure_requires_restart(detail):
self._poisoned_reason = detail
raise NeuralBridgePoisonedError(
f"{detail}. Restart the application before rendering again."
@@ -1596,7 +1612,7 @@ class NeuralBridgeManager:
evaluate_seconds = time.perf_counter() - evaluate_started
if not ok:
detail = _text(error.value) or "unknown CUDA interoperability failure"
- if "corrupt" in detail.lower() or "access violation" in detail.lower():
+ if _bridge_failure_requires_restart(detail):
self._poisoned_reason = detail
raise NeuralBridgePoisonedError(
f"{detail}. Restart the application before rendering again."
diff --git a/src/core/nr_composition.py b/src/core/nr_composition.py
index 445045c..1ea5585 100644
--- a/src/core/nr_composition.py
+++ b/src/core/nr_composition.py
@@ -148,7 +148,7 @@ def mask_report(selection: object | None, feather: int) -> dict[str, Any]:
def report_options(options: object) -> dict[str, Any]:
- """Return dataclass options without leaking a Gradio temporary path."""
+ """Return dataclass options without leaking an app temporary path."""
values = asdict(options)
selection = values.pop("nr_mask", None)
values["custom_nr_mask"] = mask_report(selection, int(values.get("mask_feather", 0)))
diff --git a/src/core/paths.py b/src/core/paths.py
index 95ec8da..7b4f6f2 100644
--- a/src/core/paths.py
+++ b/src/core/paths.py
@@ -5,13 +5,13 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
TEMP = ROOT / "temp"
-GRADIO_TEMP = TEMP / "gradio"
+APP_TEMP = TEMP / "app"
RUNTIME = ROOT / "bin" / "runtime"
DLSSG_DIR = RUNTIME / "dlssg"
# In-process D3D12/NGX feature-18 runtime. The bridge and caller shim are
# self-contained and require no Python tensor framework or external add-on.
DLSSNR_DIR = RUNTIME / "dlssnr"
-DLSSNR_BRIDGE = DLSSNR_DIR / "neuroframe_engine.dll"
+DLSSNR_BRIDGE = DLSSNR_DIR / "neuroframe_engine_neural_rendering.dll"
DLSSNR_CALLER_SHIM = DLSSNR_DIR / "neuroframe_caller.dll"
FFMPEG = ROOT / "bin" / "ffmpeg" / "bin" / "ffmpeg.exe"
FFPROBE = ROOT / "bin" / "ffmpeg" / "bin" / "ffprobe.exe"
diff --git a/src/core/render_metadata.py b/src/core/render_metadata.py
index b43b558..b1471b1 100644
--- a/src/core/render_metadata.py
+++ b/src/core/render_metadata.py
@@ -5,7 +5,11 @@ import re
from .jobs import Cancelled
-APPLICATION = "DLSS 5 Visual Enhancer"
+APPLICATION = "Visual Enhancer"
+LEGACY_APPLICATION = "DLSS 5 Visual Enhancer"
+# Accept both headers when reading so outputs written before the rename
+# still merge cleanly; new notes are always written with APPLICATION.
+_APP_HEADER = r"(?:Visual Enhancer|DLSS 5 Visual Enhancer):"
PREFIX = "DLSS 5 Neural Rendering Settings - "
IMAGE_NOTE_FORMATS = frozenset({"PNG", "JPEG", "WebP", "AVIF", "TIFF"})
VIDEO_NOTE_FORMATS = frozenset({"MP4", "MKV"})
@@ -17,7 +21,7 @@ _LABELS = (
"GPU Memory Path", "Scale",
)
_NUMBER = r"-?\d+(?:\.\d+)?(?:e[+-]?\d+)?"
-_SCALE_VALUE = r"(?:Source|75%|50%|25%)"
+_SCALE_VALUE = r"(?:Source|200%|175%|150%|125%|75%|50%|25%)"
_VALUES = (
r"(?:Default|Natural|Cinematic)",
_NUMBER, r"[1-4]", _NUMBER, _NUMBER,
@@ -76,27 +80,27 @@ _LEGACY_LABELS = (
"GPU Memory Path", "Output Scale",
)
_OWN_NOTE = re.compile(
- r"(?m)^" + re.escape(APPLICATION + ":") + r"\r?\n" + re.escape(PREFIX)
+ r"(?m)^" + _APP_HEADER + r"\r?\n" + re.escape(PREFIX)
+ ", ".join(re.escape(label + " - ") + value for label, value in zip(_LABELS, _VALUES))
+ r"(?=\r?$)"
)
_V4_NOTE = re.compile(
- r"(?m)^" + re.escape(APPLICATION + ":") + r"\r?\n" + re.escape(PREFIX)
+ r"(?m)^" + _APP_HEADER + r"\r?\n" + re.escape(PREFIX)
+ ", ".join(re.escape(label + " - ") + value for label, value in zip(_V4_LABELS, _V4_VALUES))
+ r"(?=\r?$)"
)
_V3_NOTE = re.compile(
- r"(?m)^" + re.escape(APPLICATION + ":") + r"\r?\n" + re.escape(PREFIX)
+ r"(?m)^" + _APP_HEADER + r"\r?\n" + re.escape(PREFIX)
+ ", ".join(re.escape(label + " - ") + value for label, value in zip(_V3_LABELS, _V3_VALUES))
+ r"(?=\r?$)"
)
_V2_NOTE = re.compile(
- r"(?m)^" + re.escape(APPLICATION + ":") + r"\r?\n" + re.escape(PREFIX)
+ r"(?m)^" + _APP_HEADER + r"\r?\n" + re.escape(PREFIX)
+ ", ".join(re.escape(label + " - ") + value for label, value in zip(_V2_LABELS, _V2_VALUES))
+ r"(?=\r?$)"
)
_LEGACY_NOTE = re.compile(
- r"(?m)^" + re.escape(APPLICATION + ":") + r"\r?\n" + re.escape(PREFIX)
+ r"(?m)^" + _APP_HEADER + r"\r?\n" + re.escape(PREFIX)
+ ", ".join(re.escape(label + " - ") + value for label, value in zip(_LEGACY_LABELS, _LEGACY_VALUES))
+ r"(?=\r?$)"
)
diff --git a/src/core/runtime.py b/src/core/runtime.py
index 77721f1..4a9936b 100644
--- a/src/core/runtime.py
+++ b/src/core/runtime.py
@@ -46,9 +46,14 @@ NR_STYLES = {
}
# Feature 18 is evaluated at the final neural dimensions. Scaling below 1x is
-# an explicit Lanczos downscale before Neural Rendering.
+# an explicit Lanczos downscale before Neural Rendering; scaling above 1x is
+# an explicit Lanczos upscale before Neural Rendering.
UPSCALING_MODES = {
1.0: {"label": "Source (Original)", "name": "Source", "perf_quality": 0},
+ 2.0: {"label": "200%", "name": "Lanczos 200%", "perf_quality": 0},
+ 1.75: {"label": "175%", "name": "Lanczos 175%", "perf_quality": 0},
+ 1.5: {"label": "150%", "name": "Lanczos 150%", "perf_quality": 0},
+ 1.25: {"label": "125%", "name": "Lanczos 125%", "perf_quality": 0},
0.75: {"label": "75%", "name": "Lanczos 75%", "perf_quality": 0},
0.5: {"label": "50%", "name": "Lanczos 50%", "perf_quality": 0},
0.25: {"label": "25%", "name": "Lanczos 25%", "perf_quality": 0},
@@ -62,13 +67,13 @@ def resolve_upscaling_mode(raw_factor: float) -> tuple[float, dict[str, str | in
try:
factor = float(raw_factor)
except (TypeError, ValueError) as exc:
- raise ValueError("Scale must be one of: Source, 75%, 50%, 25%.") from exc
+ raise ValueError("Scale must be one of: Source, 200%, 175%, 150%, 125%, 75%, 50%, 25%.") from exc
if not math.isfinite(factor):
- raise ValueError("Scale must be one of: Source, 75%, 50%, 25%.")
+ raise ValueError("Scale must be one of: Source, 200%, 175%, 150%, 125%, 75%, 50%, 25%.")
for supported, mode in UPSCALING_MODES.items():
if math.isclose(factor, supported, rel_tol=0.0, abs_tol=1e-9):
return supported, mode
- raise ValueError("Scale must be one of: Source, 75%, 50%, 25%.")
+ raise ValueError("Scale must be one of: Source, 200%, 175%, 150%, 125%, 75%, 50%, 25%.")
def _nearest_even(value: float) -> int:
@@ -94,7 +99,7 @@ def resolve_output_size(width: int, height: int, factor: float) -> tuple[int, in
return output_width, output_height
-def resolve_native_settings(options: Any) -> dict[str, int | float | bool]:
+def resolve_native_settings(options: Any, *, gpu_mode: bool | None = None) -> dict[str, int | float | bool]:
try:
style = NR_STYLES[options.nr_style]
except KeyError as exc:
@@ -132,7 +137,13 @@ def resolve_native_settings(options: Any) -> dict[str, int | float | bool]:
raise ValueError("Mask Feather must be an integer from 0 to 128.")
if not 0 <= int(mask_feather) <= 128:
raise ValueError("Mask Feather must be between 0 and 128 pixels.")
- gpu_mode = getattr(options, "nr_gpu_mode", True)
+ codec_name = str(getattr(options, "codec", ""))
+ if gpu_mode is None:
+ # Automatic path selection: an NVENC codec takes the CUDA transport,
+ # a CPU codec takes the host-memory path. Options without a codec
+ # (images, Live) default to GPU-resident; host pipelines pass False
+ # explicitly.
+ gpu_mode = True if not hasattr(options, "codec") else "NVENC" in codec_name.upper()
if not isinstance(gpu_mode, bool):
raise ValueError("Neural Rendering GPU mode must be a boolean value.")
nr_passes = getattr(options, "nr_passes", 1)
@@ -141,7 +152,6 @@ def resolve_native_settings(options: Any) -> dict[str, int | float | bool]:
if not 1 <= nr_passes <= 4:
raise ValueError("NR Passes must be between 1 and 4.")
- codec_name = str(getattr(options, "codec", ""))
prefer_nvof = bool(codec_name and "NVENC" not in codec_name.upper())
return {
"profile": 0,
@@ -1019,6 +1029,7 @@ def _encoder_inventory() -> dict[str, bool]:
text=True,
encoding="utf-8",
errors="replace",
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
if result.returncode:
raise RuntimeError(result.stderr.strip() or "FFmpeg encoder inventory failed.")
diff --git a/src/core/terminal.py b/src/core/terminal.py
index 604b08d..6856ede 100644
--- a/src/core/terminal.py
+++ b/src/core/terminal.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import atexit
import ctypes
from ctypes import wintypes
-import logging
import os
import shutil
import sys
@@ -163,7 +162,7 @@ class TerminalUI:
sys.__stdout__.flush()
def render_loading(self) -> None:
- """Draw centered LOADING screen with same DLSS 5 Visual Enhancer style, no footer."""
+ """Draw centered LOADING screen with same Visual Enhancer style, no footer."""
for stream in (sys.__stdout__, sys.stdout):
if hasattr(stream, "reconfigure"):
try:
@@ -339,17 +338,6 @@ class TerminalUI:
# Suppress warnings
warnings.filterwarnings("ignore")
- # Configure file logging for libraries
- file_handler = logging.FileHandler(str(session), encoding="utf-8")
- file_handler.setLevel(logging.INFO)
- formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s: %(message)s")
- file_handler.setFormatter(formatter)
-
- for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access", "gradio", "fastapi"):
- lg = logging.getLogger(logger_name)
- lg.handlers = [file_handler]
- lg.setLevel(logging.WARNING)
-
def restore_cursor(self) -> None:
"""Show terminal cursor and leave alternate buffer on exit."""
try:
diff --git a/src/desktop/__init__.py b/src/desktop/__init__.py
new file mode 100644
index 0000000..bae41ff
--- /dev/null
+++ b/src/desktop/__init__.py
@@ -0,0 +1 @@
+"""PySide6 + Qt Quick desktop application package for Visual Enhancer."""
diff --git a/src/desktop/app.py b/src/desktop/app.py
new file mode 100644
index 0000000..cb7d9de
--- /dev/null
+++ b/src/desktop/app.py
@@ -0,0 +1,363 @@
+from __future__ import annotations
+
+import ctypes
+import os
+import sys
+from pathlib import Path
+
+from PySide6.QtCore import QTimer, QUrl, Qt
+from PySide6.QtGui import QGuiApplication, QIcon
+from PySide6.QtQml import QQmlApplicationEngine
+
+from ..core.paths import ROOT, OUTPUTS, LOGS, LIVE_DIR
+from ..core.cache_cleanup import cleanup_old_caches
+from .image_provider import PreviewImageProvider
+from .bridge import AppBridge
+from .win_frameless import install_win_chrome, ensure_win_style, log_native_chrome
+
+
+def hide_inherited_console() -> None:
+ """Detach/hide any console inherited when launched windowless.
+
+ The GUI launcher sets DLSS5_WINDOWLESS=1 and starts pythonw.exe with
+ CREATE_NO_WINDOW. If Windows still attached a console (e.g. launched
+ from a console python, or a flashing helper), hide it so double-clicking
+ the .exe shows only the Qt window.
+ """
+ if os.environ.get("DLSS5_WINDOWLESS") != "1":
+ return
+ if sys.platform != "win32":
+ return
+ try:
+ kernel32 = ctypes.windll.kernel32
+ user32 = ctypes.windll.user32
+ hwnd = kernel32.GetConsoleWindow()
+ if hwnd:
+ try:
+ user32.ShowWindow(hwnd, 0) # SW_HIDE
+ except Exception:
+ pass
+ try:
+ kernel32.FreeConsole()
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+
+def apply_windows_dark_titlebar(win_id: int) -> None:
+ """Enable Windows 10/11 dark titlebar styling when native chrome is used."""
+ try:
+ value = ctypes.c_int(1)
+ ctypes.windll.dwmapi.DwmSetWindowAttribute(
+ ctypes.c_void_p(win_id), ctypes.c_uint(20), ctypes.byref(value), ctypes.sizeof(value)
+ )
+ except Exception:
+ pass
+
+
+def enable_dpi_awareness() -> str:
+ """Declare per-monitor DPI awareness before Qt initializes.
+
+ The native frame math (maximized clamp, hit-test mapping) mixes physical
+ pixels with Qt DIPs; without PMv2 awareness Windows scales one side and
+ maximized geometry lands with a large offset. One-shot API: must run
+ before QGuiApplication exists. Never raises.
+ """
+ if sys.platform != "win32":
+ return "non-windows"
+ try:
+ user32 = ctypes.windll.user32
+ try:
+ user32.SetProcessDpiAwarenessContext.argtypes = [ctypes.c_void_p]
+ user32.SetProcessDpiAwarenessContext.restype = ctypes.c_bool
+ if user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(0xFFFFFFFFFFFFFFFC)):
+ return "per-monitor-v2"
+ except Exception:
+ pass
+ try:
+ shcore = ctypes.windll.shcore
+ shcore.SetProcessDpiAwareness.argtypes = [ctypes.c_int]
+ shcore.SetProcessDpiAwareness.restype = ctypes.c_long
+ if shcore.SetProcessDpiAwareness(2) == 0:
+ return "per-monitor-v1"
+ except Exception:
+ pass
+ try:
+ user32.SetProcessDPIAware.argtypes = []
+ user32.SetProcessDPIAware.restype = ctypes.c_bool
+ if user32.SetProcessDPIAware():
+ return "system-aware"
+ except Exception:
+ pass
+ except Exception:
+ pass
+ return "unchanged"
+
+
+def resolve_app_icon() -> Path | None:
+ """Locate the canonical app icon (native (dev)/icon.png). Never raises."""
+ try:
+ candidates = (
+ ROOT / "native (dev)" / "icon.png",
+ ROOT / "icon.png",
+ Path(__file__).resolve().parent / "icon.png",
+ )
+ for candidate in candidates:
+ try:
+ if candidate.is_file():
+ return candidate
+ except Exception:
+ continue
+ except Exception:
+ pass
+ return None
+
+
+APP_USER_MODEL_ID = "Merserk.VisualEnhancer.v10"
+APP_DISPLAY_NAME = "Visual Enhancer"
+
+
+def resolve_launcher_exe() -> Path | None:
+ """Locate the branded launcher .exe next to the app folder. Never raises."""
+ try:
+ for name in ("Visual Enhancer.exe", "DLSS 5 Visual Enhancer.exe"):
+ candidate = ROOT / name
+ if candidate.is_file():
+ return candidate
+ except Exception:
+ pass
+ return None
+
+
+def set_process_appusermodel_id() -> bool:
+ """Declare this pythonw.exe process as our app to the taskbar.
+
+ Without an explicit AppUserModelID, Windows groups the window under the
+ host executable, so the taskbar shows "Python" with the Python icon.
+ Must run before any UI is presented. Never raises.
+ """
+ if sys.platform != "win32":
+ return False
+ try:
+ shell32 = ctypes.windll.shell32
+ shell32.SetCurrentProcessExplicitAppUserModelID.argtypes = [ctypes.c_wchar_p]
+ shell32.SetCurrentProcessExplicitAppUserModelID.restype = ctypes.c_long
+ return int(shell32.SetCurrentProcessExplicitAppUserModelID(APP_USER_MODEL_ID)) == 0
+ except Exception:
+ return False
+
+
+def stamp_taskbar_relaunch(hwnd: int) -> bool:
+ """Brand the live taskbar button via window relaunch properties.
+
+ Sets RelaunchCommand/DisplayName/IconResource (pointing at the branded
+ launcher .exe) plus the window-level AppID, so the Jump List header shows
+ the program name and VE icon, and pinning/relaunch targets the launcher.
+ Never raises.
+ """
+ if sys.platform != "win32" or not hwnd:
+ return False
+ try:
+ ole32 = ctypes.windll.ole32
+ shell32 = ctypes.windll.shell32
+ try:
+ ole32.CoInitialize(None)
+ except Exception:
+ pass
+
+ launcher = resolve_launcher_exe()
+ launcher_str = str(launcher) if launcher is not None else ""
+
+ class _GUID(ctypes.Structure):
+ _fields_ = [
+ ("Data1", ctypes.c_ulong),
+ ("Data2", ctypes.c_ushort),
+ ("Data3", ctypes.c_ushort),
+ ("Data4", ctypes.c_ubyte * 8),
+ ]
+
+ class _PROPERTYKEY(ctypes.Structure):
+ _fields_ = [("fmtid", _GUID), ("pid", ctypes.c_ulong)]
+
+ class _PROPVARIANT(ctypes.Structure):
+ # 16 bytes: vt + reserved, then the value union. Only VT_LPWSTR
+ # is used here; SetValue copies the string synchronously.
+ _fields_ = [
+ ("vt", ctypes.c_ushort),
+ ("wReserved1", ctypes.c_ushort),
+ ("wReserved2", ctypes.c_ushort),
+ ("wReserved3", ctypes.c_ushort),
+ ("value", ctypes.c_void_p),
+ ]
+
+ def _guid(s: str) -> _GUID:
+ parts = s.strip("{}").split("-")
+ d1 = int(parts[0], 16)
+ d2 = int(parts[1], 16)
+ d3 = int(parts[2], 16)
+ d4 = bytes.fromhex(parts[3] + parts[4])
+ return _GUID(d1, d2, d3, (ctypes.c_ubyte * 8)(*d4))
+
+ def _pkey(fmtid: str, pid: int) -> _PROPERTYKEY:
+ return _PROPERTYKEY(_guid(fmtid), pid)
+
+ def _str_var(text: str):
+ buf = ctypes.create_unicode_buffer(text)
+ var = _PROPVARIANT()
+ var.vt = 31 # VT_LPWSTR
+ var.value = ctypes.cast(buf, ctypes.c_void_p).value
+ return var, buf # keep buffer alive for the call
+
+ IID_PPV = _guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99") # IID_IPropertyStore
+ APPMODEL_FMTID = "9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"
+ PKEY_RelaunchCommand = _pkey(APPMODEL_FMTID, 2)
+ PKEY_RelaunchIconResource = _pkey(APPMODEL_FMTID, 3)
+ PKEY_RelaunchDisplayName = _pkey(APPMODEL_FMTID, 4)
+ PKEY_AppId = _pkey(APPMODEL_FMTID, 5)
+
+ shell32.SHGetPropertyStoreForWindow.argtypes = [
+ ctypes.c_void_p, ctypes.POINTER(_GUID), ctypes.POINTER(ctypes.c_void_p),
+ ]
+ shell32.SHGetPropertyStoreForWindow.restype = ctypes.c_long
+ store = ctypes.c_void_p()
+ if int(shell32.SHGetPropertyStoreForWindow(
+ ctypes.c_void_p(hwnd), ctypes.byref(IID_PPV), ctypes.byref(store))) != 0:
+ return False
+ if not store.value:
+ return False
+ try:
+ vtbl = ctypes.cast(store.value, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))
+ set_value_type = ctypes.CFUNCTYPE(
+ ctypes.c_long, ctypes.c_void_p,
+ ctypes.POINTER(_PROPERTYKEY), ctypes.POINTER(_PROPVARIANT))
+ commit_type = ctypes.CFUNCTYPE(ctypes.c_long, ctypes.c_void_p)
+ release_type = ctypes.CFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p)
+ set_value = set_value_type(vtbl.contents[6])
+ commit = commit_type(vtbl.contents[7])
+
+ keepalive = []
+ if launcher_str:
+ for key, text in (
+ (PKEY_RelaunchCommand, launcher_str),
+ (PKEY_RelaunchDisplayName, APP_DISPLAY_NAME),
+ (PKEY_RelaunchIconResource, launcher_str + ",0"),
+ ):
+ var, buf = _str_var(text)
+ keepalive.append(buf)
+ if int(set_value(store, ctypes.byref(key), ctypes.byref(var))) != 0:
+ return False
+ var, buf = _str_var(APP_USER_MODEL_ID)
+ keepalive.append(buf)
+ if int(set_value(store, ctypes.byref(PKEY_AppId), ctypes.byref(var))) != 0:
+ return False
+ return int(commit(store)) == 0
+ finally:
+ try:
+ release = ctypes.CFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p)(
+ ctypes.cast(store.value, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents[2])
+ release(store)
+ except Exception:
+ pass
+ except Exception:
+ return False
+
+
+def launch_desktop() -> int:
+ """Launch the Qt shell immediately, then initialize heavyweight runtimes."""
+ hide_inherited_console()
+ OUTPUTS.mkdir(exist_ok=True)
+ LOGS.mkdir(exist_ok=True)
+ LIVE_DIR.mkdir(exist_ok=True)
+ # Startup sweep of stale temp caches (24h+ old): crash orphans, old
+ # staged pastes and previews. Queues are in-memory per session, so no
+ # live references can exist yet. Never blocks startup.
+ try:
+ cleanup_old_caches()
+ except Exception:
+ pass
+ log_native_chrome(f"dpi-awareness={enable_dpi_awareness()}")
+ # Declare our taskbar identity before any UI exists; otherwise Windows
+ # groups the window under the host executable ("Python").
+ set_process_appusermodel_id()
+
+ QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
+ Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
+ )
+ app = QGuiApplication(sys.argv)
+ app.setApplicationName("Visual Enhancer")
+ app.setApplicationDisplayName("Visual Enhancer")
+ app.setOrganizationName("Merserk")
+ try:
+ icon_path = resolve_app_icon()
+ if icon_path is not None:
+ app.setWindowIcon(QIcon(str(icon_path)))
+ except Exception:
+ pass
+
+ engine = QQmlApplicationEngine()
+ image_provider = PreviewImageProvider()
+ engine.addImageProvider("preview", image_provider)
+
+ bridge = AppBridge(image_provider)
+ app.aboutToQuit.connect(bridge.shutdown)
+ engine.rootContext().setContextProperty("backend", bridge)
+
+ qml_path = Path(__file__).resolve().parent / "qml" / "Main.qml"
+ engine.load(QUrl.fromLocalFile(str(qml_path)))
+ if not engine.rootObjects():
+ try:
+ if sys.stderr is not None:
+ print("Error: Failed to load QML root object.", file=sys.stderr)
+ except Exception:
+ pass
+ return 1
+
+ root_window = engine.rootObjects()[0]
+ # Brand the live taskbar button (name + VE icon + launcher relaunch) and
+ # pin the window icon explicitly so pythonw.exe art never leaks through.
+ try:
+ if icon_path is not None:
+ root_window.setIcon(QIcon(str(icon_path)))
+ except Exception:
+ pass
+ try:
+ stamp_taskbar_relaunch(int(root_window.winId()))
+ except Exception:
+ pass
+ # Native OS chrome (snap layouts, Win+arrows, drag-to-snap/restore) for the
+ # frameless window. QML keeps working fallbacks where this stays inactive.
+ install_win_chrome(root_window)
+ # Parent window for the in-tab Live player container (MPV --wid embed).
+ try:
+ bridge.attachMainWindow(root_window)
+ except Exception:
+ pass
+ # Show windowed; the QML shell applies the saved maximized state itself.
+ try:
+ root_window.show()
+ except Exception:
+ pass
+ # Qt re-applies its own window flags at show(), silently stripping the
+ # native frame bits install_win_chrome added pre-show. Re-assert now and
+ # once more deferred past QML's onCompleted showMaximized/showNormal.
+ def _reaffirm_chrome_style() -> None:
+ try:
+ ensure_win_style(int(root_window.winId()))
+ except Exception:
+ pass
+
+ try:
+ ensure_win_style(int(root_window.winId()))
+ except Exception:
+ pass
+ QTimer.singleShot(250, _reaffirm_chrome_style)
+ try:
+ apply_windows_dark_titlebar(int(root_window.winId()))
+ except Exception:
+ pass
+
+ # Heavy GPU/media initialization deliberately begins only after the first
+ # event-loop turn so the window can paint an Initialization/Diagnostics UI.
+ QTimer.singleShot(0, bridge.initializeRuntime)
+ return app.exec()
diff --git a/src/desktop/bridge.py b/src/desktop/bridge.py
new file mode 100644
index 0000000..b0fccea
--- /dev/null
+++ b/src/desktop/bridge.py
@@ -0,0 +1,4276 @@
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import sys
+import time
+import platform
+import math
+import hashlib
+import shutil
+import tempfile
+import urllib.parse
+import urllib.request
+from pathlib import Path
+from dataclasses import fields as _dataclass_fields, replace
+from typing import Any
+
+from PySide6.QtCore import QObject, QThreadPool, QTimer, QUrl, Signal, Slot, Property, QSettings, qVersion, QBuffer, QIODevice
+from PySide6.QtGui import QGuiApplication, QImage, QPixmap
+
+from ..core.paths import CONFIG_PATH, OUTPUTS, LOGS, FFMPEG, FFPROBE, MPV, APP_TEMP
+from ..core.disk_paths import supported_file as _is_supported_media_file
+from ..core.cache_cleanup import cleanup_old_caches
+from ..core import app_log
+from ..core.runtime import prepare_runtime, NR_STYLES, UPSCALING_MODES, resolve_upscaling_mode, resolve_output_size
+from ..core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, container_for_codec, hdr_mode_supported, probe_video
+from ..core.naming import RENAME_MODES
+from ..core.nr_composition import inspect_nr_mask, mask_status
+from ..settings.models import (
+ CONTAINER_CHOICES, DEFAULT_SETTINGS, PREVIEW_ENCODING_CHOICES, UPSCALE_MODE_CHOICES, UISettings,
+ automatic_mask_choice, coerce_hdr_mode, live_effect_options, parse_automatic_mask, _validate,
+)
+from ..settings.storage import SETTINGS_STATE, load_settings, save_settings
+from ..settings.presets import export_settings_preset, export_settings_preset_to, import_settings_preset
+
+from .models import BatchListModel
+from .image_provider import PreviewImageProvider
+from .workers import JobWorker
+from .state import (
+ PreviewState, IDLE, SCANNING_INPUTS, LOADING_METADATA, PREVIEW_PREPARING,
+ PREVIEW_RUNNING, PREVIEW_CANCELLING, BATCH_PREPARING, BATCH_RUNNING,
+ BATCH_CANCELLING, LIVE_STARTING, LIVE_RUNNING, LIVE_STOPPING, SHUTTING_DOWN, BUSY_STATES,
+)
+
+# Import processing functions
+from ..neural_rendering.image.batch import convert_images
+from ..neural_rendering.image.preview import render_image_preview
+from ..neural_rendering.image.models import ImageConversionOptions, RAW_EXTENSIONS, IMAGE_EXTENSIONS
+from ..neural_rendering.image.decoder import decode_image_preview, full_size_image_preview_path, initialize_image_runtime
+
+from ..neural_rendering.video.batch import convert_videos
+from ..neural_rendering.video.preview import process_video_preview
+from ..neural_rendering.video.models import ConversionOptions
+
+from ..upscale.image.batch import upscale_images
+from ..upscale.image.processor import preview_upscale_image
+from ..upscale.image.models import ImageUpscaleOptions, options_from_settings as image_upscale_options_from_settings, output_size as image_upscale_output_size, SCALE_FACTORS as IMAGE_SCALE_FACTORS, VSR_QUALITIES as IMAGE_VSR_QUALITIES, SIZE_MODES as IMAGE_SIZE_MODES
+
+from ..upscale.video.batch import upscale_videos
+from ..upscale.video.preview import preview_upscale_native
+from ..upscale.video.models import UpscaleOptions, options_from_settings as video_upscale_options_from_settings, output_size as video_upscale_output_size, SCALE_FACTORS as VIDEO_SCALE_FACTORS, VSR_QUALITIES as VIDEO_VSR_QUALITIES, SIZE_MODES as VIDEO_SIZE_MODES, HDR_PRECISION_CHOICES
+
+from ..frame_interpolation.batch import interpolate_videos
+from ..frame_interpolation.preview import preview_frame_interpolation_native
+from ..frame_interpolation.models import FrameInterpolationOptions, FPS_CHOICES, ENGINE_CHOICES, PREVIEW_LENGTH_CHOICES
+
+from ..live.models import LiveOptions, LIVE_MAX_HEIGHTS, LIVE_MAX_HEIGHT_CHOICES, LIVE_SEGMENT_CHOICES, LIVE_FPS_CHOICES, LIVE_SOURCE_QUALITY_CHOICES
+from ..live.pipeline import start_live_session, stop_live_session, live_status, is_live_running, update_live_effects, sweep_stale_live_dirs
+from ..live.mpv_embed import MpvEmbedController
+
+
+# Canonical media-type sets used for auto-switching Image/Video modes and for
+# filtering dropped / picked inputs. Image aliases (.jpeg, .tif, .bmp, .heic,
+# .heif, .svg) match what the Pillow / rawpy / pillow-heif decoder stack in
+# neural_rendering.image.decoder can open; FileDialog filters already offer
+# most of these.
+IMAGE_SUFFIXES = frozenset(
+ {s.lower() for s in IMAGE_EXTENSIONS.values()}
+ | {s.lower() for s in RAW_EXTENSIONS}
+ | {".jpeg", ".tif", ".bmp", ".heic", ".heif", ".svg"}
+)
+VIDEO_SUFFIXES = frozenset(
+ {
+ ".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".ts",
+ ".mts", ".m2ts", ".wmv", ".flv",
+ }
+)
+
+# Browser "Copy image" clipboard handling for Ctrl+V. Chromium puts both an
+# https URL and bitmap pixels on the clipboard; the pixels must win (no
+# network, exact frame the user saw). Remote URLs / <img src> / URL text fall
+# back to a capped download into APP_TEMP.
+_PASTE_DOWNLOAD_TIMEOUT_S = 15
+_PASTE_DOWNLOAD_MAX_BYTES = 30 * 1024 * 1024
+_PASTE_URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE)
+_PASTE_IMG_SRC_RE = re.compile(
+ r"<img\b[^>]*?\bsrc\s*=\s*[\"'](https?://[^\"']+)[\"']", re.IGNORECASE
+)
+# Responsive/original variants: data-* originals first (authoritative full
+# resolution), then the largest srcset entry (convention: ascending widths,
+# so the last http(s) entry wins). Generic URL matches stay last.
+_PASTE_DATA_SRC_RE = re.compile(
+ r"data-(?:src|original|large-image|zoom-image|full-image)\s*=\s*[\"'](https?://[^\"']+)[\"']",
+ re.IGNORECASE,
+)
+_PASTE_SRCSET_RE = re.compile(
+ r"srcset\s*=\s*[\"']([^\"']+)[\"']", re.IGNORECASE
+)
+_PASTE_CONTENT_TYPE_SUFFIX = {
+ "image/jpeg": ".jpg",
+ "image/png": ".png",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+ "image/bmp": ".bmp",
+ "image/avif": ".avif",
+ "image/tiff": ".tiff",
+ "image/svg+xml": ".svg",
+}
+_PASTE_BROWSER_UA = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/126.0 Safari/537.36"
+)
+
+
+class AppBridge(QObject):
+ """Central native bridge between Qt Quick/QML and backend AI runtimes."""
+
+ LIVE_EFFECT_FIELDS = {
+ "live_nr_style", "live_nr_intensity", "live_nr_passes", "live_local_tone_strength",
+ "live_local_structure_strength", "live_skin_structure_strength", "live_automatic_mask",
+ "live_nr_color_strength", "live_tone_preservation", "live_face_skin_protection",
+ "live_grain_preservation", "live_shimmer_suppression", "live_mask_feather", "nr_mask",
+ }
+ LIVE_RESTART_FIELDS = {"ai_gpu_uuid", "video_gpu_uuid", "live_upscaling_factor"}
+
+ # FI settings that invalidate pre-rendered timeline ranges. A tweak
+ # here makes existing green spans stale, so they are cleared. Rename /
+ # output-only settings are excluded, as is the preview length itself
+ # (older spans remain valid footage for their range). Realtime preview
+ # stays disabled for Frame Interpolation regardless (manual Preview only).
+ FI_RANGE_FIELDS = {
+ "frame_interpolation_target_fps", "frame_interpolation_engine",
+ "frame_interpolation_codec", "frame_interpolation_quality",
+ "frame_interpolation_hdr_mode", "preview_encoding",
+ }
+ # Cap stored ranges per context so repeated previews can't grow state.
+ FI_RANGE_LIMIT = 32
+
+ # Settings that materially change the visual result shown in the preview.
+ # Changes to these fields are debounced and automatically re-render the
+ # selected item when Realtime Preview is enabled. Rename/output-only
+ # settings are intentionally excluded so they do not waste GPU work.
+ AUTO_PREVIEW_FIELDS = {
+ "ai_gpu_uuid", "video_gpu_uuid",
+ "nr_style", "nr_intensity", "nr_passes",
+ "local_tone_strength", "local_structure_strength",
+ "skin_structure_strength", "automatic_mask",
+ "nr_color_strength", "tone_preservation",
+ "face_skin_protection", "grain_preservation",
+ "shimmer_suppression", "mask_feather", "nr_mask",
+ "upscaling_factor",
+ "preview_encoding", "full_size_image_previews",
+ "upscale_image_vsr_quality", "upscale_image_size_mode",
+ "upscale_image_scale_factor", "upscale_image_width",
+ "upscale_image_height", "upscale_image_aspect_lock",
+ "upscale_vsr_enabled", "upscale_vsr_quality",
+ "upscale_size_mode", "upscale_scale_factor",
+ "upscale_width", "upscale_height", "upscale_aspect_lock",
+ "upscale_hdr_enabled", "upscale_hdr_contrast",
+ "upscale_hdr_saturation", "upscale_hdr_middle_gray",
+ "upscale_hdr_peak_luminance", "upscale_hdr_precision",
+ "upscale_codec", "upscale_quality",
+ "frame_interpolation_target_fps", "frame_interpolation_engine",
+ "frame_interpolation_codec", "frame_interpolation_quality",
+ "frame_interpolation_hdr_mode",
+ "codec", "quality", "hdr_mode",
+ }
+
+ # UI State Signals
+ activeTabChanged = Signal()
+ nrModeChanged = Signal()
+ upscaleModeChanged = Signal()
+ mediaPreviewChanged = Signal()
+ isProcessingChanged = Signal()
+ overallProgressChanged = Signal()
+ statusMessageChanged = Signal()
+ splitPositionChanged = Signal()
+ hasOutputPreviewChanged = Signal()
+ previewInputUrlChanged = Signal()
+ previewOutputUrlChanged = Signal()
+ previewPosterUrlChanged = Signal()
+ previewSourceChanged = Signal()
+ previewRangesChanged = Signal()
+ inputInfoTextChanged = Signal()
+ outputInfoTextChanged = Signal()
+ logAppended = Signal(str)
+ backendLogReceived = Signal(str, str, str)
+ operationStateChanged = Signal()
+ runtimeStateChanged = Signal()
+ layoutChanged = Signal()
+ sourceSizeChanged = Signal()
+ outputSizeChanged = Signal()
+
+ # Settings Signals
+ settingsUpdated = Signal()
+ gpuChoicesChanged = Signal()
+ presetStatusChanged = Signal()
+ liveStatusTextChanged = Signal()
+ isLiveRunningChanged = Signal()
+ isLiveStartingChanged = Signal()
+ liveTelemetryChanged = Signal()
+ autoPreviewChanged = Signal()
+
+ def __init__(self, image_provider: PreviewImageProvider, parent: Any = None) -> None:
+ super().__init__(parent)
+ self._image_provider = image_provider
+ self._thread_pool = QThreadPool.globalInstance()
+ self._active_worker: JobWorker | None = None
+ self._live_worker: JobWorker | None = None
+ self._scan_worker: JobWorker | None = None
+ self._metadata_worker: JobWorker | None = None
+ self._operation_state = IDLE
+ self._operation_id = 0
+ self._shutting_down = False
+ self._live_effects_dirty = False
+ self._stop_live_after_start = False
+ # Ctrl+V paste request: when the next addFiles scan adds exactly one
+ # new file, auto-select it so its preview loads immediately.
+ # Consumed by addFiles; only paste call sites set it.
+ self._paste_select_single = False
+
+ # Workflows: "neural-rendering", "upscale", "frame-interpolation", "live", "settings", "help"
+ self._active_tab = "neural-rendering"
+ self._nr_mode = "Image"
+
+ # Settings are loaded before runtime preparation so the native shell can
+ # restore user choices even if runtime initialization later fails.
+ self._settings = load_settings(CONFIG_PATH)
+ SETTINGS_STATE.current = self._settings
+ self._upscale_mode = self._settings.upscale_mode if self._settings.upscale_mode in UPSCALE_MODE_CHOICES else "Image"
+
+ # Processing / presentation state. Preview media is stored independently
+ # per workflow context and projected through the public properties below.
+ self._is_processing = False
+ self._overall_progress = 0.0
+ self._status_message = "Initializing runtime…"
+ self._split_position = 0.5
+ self._preset_status = ""
+ self._live_status_text = "Idle. Enter a source and press Start Live."
+ self._is_live_running = False
+ self._is_live_starting = False
+ self._preview_generation = 0
+ self._live_source_fps = 0.0
+ self._live_target_fps = 0.0
+ self._live_effective_fps = 0.0
+ self._live_guide_ms = 0.0
+ self._live_dlss_ms = 0.0
+ self._live_encode_ms = 0.0
+ self._live_dropped_frames = 0
+ self._live_rebuffer_events = 0
+ self._live_av_sync_ms = 0.0
+ self._live_output_size = ""
+ self._live_encoder = ""
+ self._live_player_started = False
+ self._live_embed_wid = 0
+ self._main_window: Any = None
+ self._mpv_embed = MpvEmbedController(self)
+ try:
+ self._mpv_embed.embedError.connect(self._on_mpv_embed_error)
+ except Exception:
+ pass
+
+ self._contexts: dict[str, PreviewState] = {
+ "nr-image": PreviewState(),
+ "nr-video": PreviewState(),
+ "upscale-image": PreviewState(),
+ "upscale-video": PreviewState(),
+ "fi-video": PreviewState(),
+ }
+
+ # Queues per workflow
+ self._nr_image_queue = BatchListModel(self)
+ self._nr_video_queue = BatchListModel(self)
+ self._upscale_image_queue = BatchListModel(self)
+ self._upscale_video_queue = BatchListModel(self)
+ self._fi_queue = BatchListModel(self)
+
+ self._save_timer = QTimer(self)
+ self._save_timer.setSingleShot(True)
+ self._save_timer.setInterval(450)
+ self._save_timer.timeout.connect(self._flush_settings)
+
+ # Hourly temp sweep (startup sweep lives in app.launch_desktop).
+ # Only files older than 24h are removed; staged paste sources in a
+ # still-open session are kept fresh via _touch_if_staged on select.
+ self._sweep_timer = QTimer(self)
+ self._sweep_timer.setSingleShot(False)
+ self._sweep_timer.setInterval(3600 * 1000)
+ self._sweep_timer.timeout.connect(self._sweep_temp_caches)
+ self._sweep_timer.start()
+
+ # Runtime starts in a lightweight bootstrap state. ``initializeRuntime``
+ # populates this asynchronously after the QML window is already visible.
+ self._prepared = None
+ self._runtime_state = "Initializing"
+ self._runtime_error = ""
+
+ # Persistent desktop layout is deliberately separate from render presets.
+ # Renamed in v10: "DLSS 5 Visual Enhancer" -> "Visual Enhancer".
+ # One-time migration so existing window/layout settings survive.
+ self._ui_settings = QSettings("Merserk", "Visual Enhancer")
+ try:
+ if not self._ui_settings.allKeys():
+ legacy = QSettings("Merserk", "DLSS 5 Visual Enhancer")
+ for key in legacy.allKeys():
+ self._ui_settings.setValue(key, legacy.value(key))
+ if legacy.allKeys():
+ self._ui_settings.sync()
+ except Exception:
+ pass
+ self._auto_preview_enabled = str(
+ self._ui_settings.value("preview/realtimeEnabled", "true")
+ ).lower() in {"1", "true", "yes", "on"}
+ self._auto_preview_pending = False
+ self._inspector_width = int(self._ui_settings.value("layout/inspectorWidth", 400))
+ self._queue_height = int(self._ui_settings.value("layout/queueHeight", 190))
+ self._log_height = int(self._ui_settings.value("layout/logHeight", 220))
+ self._focus_preview = False
+ self._window_width = int(self._ui_settings.value("window/width", 1440))
+ self._window_height = int(self._ui_settings.value("window/height", 920))
+ self._window_x = int(self._ui_settings.value("window/x", -1))
+ self._window_y = int(self._ui_settings.value("window/y", -1))
+ self._window_maximized = str(self._ui_settings.value("window/maximized", "false")).lower() in {"1", "true", "yes"}
+
+ self._auto_preview_timer = QTimer(self)
+ self._auto_preview_timer.setSingleShot(True)
+ self._auto_preview_timer.setInterval(360)
+ self._auto_preview_timer.timeout.connect(self._run_auto_preview)
+
+ # Scrub-realtime: timeline moves in Output/2-Up debounce here before a
+ # refresh render starts, so scrubbing never melts the GPU.
+ self._scrub_preview_timer = QTimer(self)
+ self._scrub_preview_timer.setSingleShot(True)
+ self._scrub_preview_timer.setInterval(750)
+ self._scrub_preview_timer.timeout.connect(self._fire_scrub_preview)
+ self._scrub_pending_pos: float | None = None
+
+ self._preview_cache = Path(tempfile.gettempdir()) / "dlss5-visual-enhancer" / "native-preview"
+ try:
+ shutil.rmtree(self._preview_cache, ignore_errors=True)
+ self._preview_cache.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ self._preview_cache = OUTPUTS
+
+ # Telemetry timer for Live mode
+ self._live_timer = QTimer(self)
+ self._live_timer.setInterval(500)
+ self._live_timer.timeout.connect(self._poll_live_status)
+
+ # Log bridge. Backend workers may log from arbitrary threads, so they
+ # emit into this QObject and are appended on the GUI thread.
+ self._logs: list[str] = []
+ self.backendLogReceived.connect(self._append_backend_log)
+ self._backend_log_listener = lambda level, tag, msg: self.backendLogReceived.emit(str(level), str(tag), str(msg))
+ app_log.add_listener(self._backend_log_listener)
+ try:
+ app_log.init_session()
+ except Exception:
+ pass
+
+ def _context_key(self) -> str:
+ if self._active_tab == "neural-rendering":
+ return "nr-image" if self._nr_mode == "Image" else "nr-video"
+ if self._active_tab == "upscale":
+ return "upscale-image" if self._upscale_mode == "Image" else "upscale-video"
+ if self._active_tab == "frame-interpolation":
+ return "fi-video"
+ return "nr-image"
+
+ def _context(self, key: str | None = None) -> PreviewState:
+ return self._contexts[key or self._context_key()]
+
+ def _emit_context(self) -> None:
+ self.previewInputUrlChanged.emit()
+ self.previewOutputUrlChanged.emit()
+ self.previewPosterUrlChanged.emit()
+ self.previewSourceChanged.emit()
+ self.previewRangesChanged.emit()
+ self.mediaPreviewChanged.emit()
+ self.hasOutputPreviewChanged.emit()
+ self.inputInfoTextChanged.emit()
+ self.outputInfoTextChanged.emit()
+ self.sourceSizeChanged.emit()
+ self.outputSizeChanged.emit()
+
+ def _set_operation(self, state: str, message: str | None = None) -> int:
+ self._operation_state = state
+ self._is_processing = state in BUSY_STATES
+ self._operation_id += 1
+ if message is not None:
+ self._status_message = message
+ self.statusMessageChanged.emit()
+ self.operationStateChanged.emit()
+ self.isProcessingChanged.emit()
+ return self._operation_id
+
+ def _finish_operation(self, operation_id: int, message: str | None = None) -> bool:
+ if operation_id != self._operation_id or self._shutting_down:
+ return False
+ self._operation_state = LIVE_RUNNING if self._is_live_running else IDLE
+ self._is_processing = False
+ self._active_worker = None
+ if message is not None:
+ self._status_message = message
+ self.statusMessageChanged.emit()
+ self.operationStateChanged.emit()
+ self.isProcessingChanged.emit()
+ return True
+
+ def _invalidate_preview_generation(self) -> int:
+ self._preview_generation += 1
+ self._context().generation = self._preview_generation
+ return self._preview_generation
+
+ def _fi_preview_length_seconds(self) -> float:
+ """Selected FI preview clip length in seconds (3/5/10/20/30)."""
+ try:
+ length = float(self._settings.frame_interpolation_preview_length)
+ except (TypeError, ValueError):
+ return 3.0
+ return length if (length and math.isfinite(length) and length > 0) else 3.0
+
+ def _add_fi_rendered_range(self, context_key: str, start_seconds: float, media_path: str,
+ length_seconds: float = 3.0) -> None:
+ """Record one FI preview span for the green timeline overlay."""
+ if context_key != "fi-video":
+ return
+ ctx = self._contexts.get(context_key)
+ if ctx is None:
+ return
+ try:
+ start = max(0.0, float(start_seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
+ try:
+ span = max(0.0, float(length_seconds or 0.0))
+ except (TypeError, ValueError):
+ span = 0.0
+ if not (span > 0):
+ return
+ try:
+ duration = float(ctx.duration_seconds or 0.0)
+ except (TypeError, ValueError):
+ duration = 0.0
+ end = start + span
+ if duration > 0:
+ end = min(end, duration)
+ if not (end > start):
+ return
+ try:
+ url = QUrl.fromLocalFile(str(media_path)).toString()
+ except Exception:
+ return
+ if not url:
+ return
+ ranges = list(getattr(ctx, "rendered_ranges", None) or [])
+ ranges.append({"start": start, "end": end, "url": url})
+ # Newest last; drop the oldest beyond the cap. Overlapping spans are
+ # kept as separate entries so each keeps its own clip; they merge
+ # visually by overdraw and playback prefers the newest match.
+ if len(ranges) > int(self.FI_RANGE_LIMIT):
+ ranges = ranges[-int(self.FI_RANGE_LIMIT):]
+ ctx.rendered_ranges = ranges
+ if context_key == self._context_key():
+ self.previewRangesChanged.emit()
+
+ def _clear_fi_rendered_ranges(self, emit: bool = True) -> None:
+ """Drop FI pre-rendered spans (source/settings changed)."""
+ ctx = self._contexts.get("fi-video")
+ if ctx is None:
+ return
+ ctx.rendered_ranges = []
+ if emit and self._context_key() == "fi-video":
+ self.previewRangesChanged.emit()
+
+ # =========================================================================
+ # Properties: General UI State
+ # =========================================================================
+ @Property(str, notify=activeTabChanged)
+ def activeTab(self) -> str:
+ return self._active_tab
+
+ @activeTab.setter
+ def activeTab(self, tab: str) -> None:
+ if tab not in {"neural-rendering", "upscale", "frame-interpolation", "live", "settings", "help"}:
+ return
+ if self._active_tab != tab:
+ self._active_tab = tab
+ self.activeTabChanged.emit()
+ # The Live video is a native child window (MPV --wid) that paints
+ # above the Qt Quick scene and ignores StackLayout/clip. Hide it
+ # whenever the user leaves the Live tab so it can never overlay
+ # Upscale/Neural/Frame-Interpolation; the session keeps running.
+ try:
+ self._mpv_embed.setTabActive(tab == "live")
+ except Exception:
+ pass
+ self._emit_context()
+ self._schedule_auto_preview(180)
+
+ @Property(str, notify=nrModeChanged)
+ def nrMode(self) -> str:
+ return self._nr_mode
+
+ @nrMode.setter
+ def nrMode(self, mode: str) -> None:
+ if mode not in {"Image", "Video"}:
+ return
+ if self._nr_mode != mode:
+ self._nr_mode = mode
+ self.nrModeChanged.emit()
+ self._emit_context()
+ self._schedule_auto_preview(180)
+
+ @Property(str, notify=upscaleModeChanged)
+ def upscaleMode(self) -> str:
+ return self._upscale_mode
+
+ @upscaleMode.setter
+ def upscaleMode(self, mode: str) -> None:
+ if mode not in UPSCALE_MODE_CHOICES:
+ return
+ if self._upscale_mode != mode:
+ if not self._save_setting(upscale_mode=mode):
+ return
+ self._upscale_mode = mode
+ self.upscaleModeChanged.emit()
+ self._emit_context()
+ self._schedule_auto_preview(180)
+
+ @Property(bool, notify=isProcessingChanged)
+ def isProcessing(self) -> bool:
+ return self._is_processing
+
+ @Property(float, notify=overallProgressChanged)
+ def overallProgress(self) -> float:
+ return self._overall_progress
+
+ @Property(str, notify=statusMessageChanged)
+ def statusMessage(self) -> str:
+ return self._status_message
+
+ @Property(float, notify=splitPositionChanged)
+ def splitPosition(self) -> float:
+ return self._split_position
+
+ @splitPosition.setter
+ def splitPosition(self, val: float) -> None:
+ val = max(0.0, min(1.0, float(val)))
+ if abs(self._split_position - val) > 0.001:
+ self._split_position = val
+ self.splitPositionChanged.emit()
+
+ @Property(bool, notify=hasOutputPreviewChanged)
+ def hasOutputPreview(self) -> bool:
+ return self._context().has_output
+
+ @Property(str, notify=previewInputUrlChanged)
+ def previewInputUrl(self) -> str:
+ return self._context().input_url
+
+ @Property(str, notify=previewOutputUrlChanged)
+ def previewOutputUrl(self) -> str:
+ return self._context().output_url
+
+ @Property(str, notify=previewPosterUrlChanged)
+ def previewPosterUrl(self) -> str:
+ return self._context().poster_url
+
+ @Property(float, notify=previewSourceChanged)
+ def previewSourceSeconds(self) -> float:
+ return float(self._context().preview_source_seconds or 0.0)
+
+ @Property(int, notify=previewSourceChanged)
+ def previewSourceFrame(self) -> int:
+ return int(self._context().preview_source_frame or 0)
+
+ @Property(list, notify=previewRangesChanged)
+ def previewRenderedRanges(self) -> list[dict]:
+ """FI pre-rendered timeline spans, newest last.
+
+ Each entry is {"start": seconds, "end": seconds, "url": clip URL}.
+ Empty for every context except fi-video. The timeline paints them
+ green; playback shows the processed clip inside a span and the
+ original source outside of all spans.
+ """
+ try:
+ ranges = getattr(self._context(), "rendered_ranges", None) or []
+ except Exception:
+ return []
+ out: list[dict] = []
+ for entry in ranges:
+ try:
+ out.append({
+ "start": max(0.0, float(entry.get("start", 0.0))),
+ "end": max(0.0, float(entry.get("end", 0.0))),
+ "url": str(entry.get("url", "")),
+ })
+ except (AttributeError, TypeError, ValueError):
+ continue
+ return out
+
+ @Property(str, notify=inputInfoTextChanged)
+ def inputInfoText(self) -> str:
+ return self._context().input_info
+
+ @Property(str, notify=outputInfoTextChanged)
+ def outputInfoText(self) -> str:
+ return self._context().output_info
+
+ @Property(str, notify=presetStatusChanged)
+ def presetStatus(self) -> str:
+ return self._preset_status
+
+ @Property(str, notify=liveStatusTextChanged)
+ def liveStatusText(self) -> str:
+ return self._live_status_text
+
+ @Property(bool, notify=isLiveRunningChanged)
+ def isLiveRunning(self) -> bool:
+ return self._is_live_running
+
+ @Property(bool, notify=isLiveStartingChanged)
+ def isLiveStarting(self) -> bool:
+ return self._is_live_starting
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveSourceFps(self) -> float:
+ return self._live_source_fps
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveTargetFps(self) -> float:
+ return self._live_target_fps
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveEffectiveFps(self) -> float:
+ return self._live_effective_fps
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveGuideMs(self) -> float:
+ return self._live_guide_ms
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveDlssMs(self) -> float:
+ return self._live_dlss_ms
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveEncodeMs(self) -> float:
+ return self._live_encode_ms
+
+ @Property(int, notify=liveTelemetryChanged)
+ def liveDroppedFrames(self) -> int:
+ return self._live_dropped_frames
+
+ @Property(int, notify=liveTelemetryChanged)
+ def liveRebufferEvents(self) -> int:
+ return self._live_rebuffer_events
+
+ @Property(float, notify=liveTelemetryChanged)
+ def liveAvSyncMs(self) -> float:
+ return self._live_av_sync_ms
+
+ @Property(str, notify=liveTelemetryChanged)
+ def liveOutputSize(self) -> str:
+ return self._live_output_size
+
+ @Property(str, notify=liveTelemetryChanged)
+ def liveEncoder(self) -> str:
+ return self._live_encoder
+
+ @Property(bool, notify=liveTelemetryChanged)
+ def livePlayerStarted(self) -> bool:
+ """True once the embedded player renders its first frame."""
+ return self._live_player_started
+
+ @Property(QObject, constant=True)
+ def mpvEmbed(self) -> QObject:
+ """In-tab Live player host (container geometry + pause/mute)."""
+ return self._mpv_embed
+
+ def attachMainWindow(self, window: Any) -> None:
+ """Remember the QML root window for in-tab MPV hosting."""
+ self._main_window = window
+ try:
+ self._mpv_embed.attach_main_window(window)
+ except Exception:
+ pass
+
+ @Slot(str)
+ def _on_mpv_embed_error(self, message: str) -> None:
+ self._log(f"Live player: {message}")
+
+ @Property(str, notify=operationStateChanged)
+ def operationState(self) -> str:
+ return self._operation_state
+
+ @Property(bool, notify=operationStateChanged)
+ def canModifyQueue(self) -> bool:
+ return self._operation_state == IDLE and not self._shutting_down
+
+ @Property(bool, notify=operationStateChanged)
+ def canPreview(self) -> bool:
+ return self._operation_state == IDLE and self._runtime_state == "Ready" and not self._is_live_running
+
+ @Property(bool, notify=operationStateChanged)
+ def canRender(self) -> bool:
+ return self._operation_state == IDLE and self._runtime_state == "Ready" and not self._is_live_running and self._active_render_configuration_valid()
+
+ @Property(bool, notify=operationStateChanged)
+ def canStartLive(self) -> bool:
+ return self._operation_state == IDLE and self._runtime_state == "Ready" and not self._is_live_running
+
+ @Property(bool, notify=operationStateChanged)
+ def canStop(self) -> bool:
+ return self._operation_state in {PREVIEW_RUNNING, PREVIEW_PREPARING, BATCH_RUNNING, BATCH_PREPARING, LIVE_STARTING, LIVE_RUNNING}
+
+ @Property(str, notify=runtimeStateChanged)
+ def runtimeState(self) -> str:
+ return self._runtime_state
+
+ @Property(str, notify=runtimeStateChanged)
+ def runtimeError(self) -> str:
+ return self._runtime_error
+
+ @Property(int, notify=sourceSizeChanged)
+ def sourceWidth(self) -> int:
+ return self._context().source_width
+
+ @Property(int, notify=sourceSizeChanged)
+ def sourceHeight(self) -> int:
+ return self._context().source_height
+
+ @Property(float, notify=sourceSizeChanged)
+ def sourceFps(self) -> float:
+ return self._context().source_fps
+
+ @Property(float, notify=sourceSizeChanged)
+ def sourceDuration(self) -> float:
+ return self._context().duration_seconds
+
+ @Property(int, notify=outputSizeChanged)
+ def outputWidth(self) -> int:
+ return self._context().output_width
+
+ @Property(int, notify=outputSizeChanged)
+ def outputHeight(self) -> int:
+ return self._context().output_height
+
+ @Property(int, notify=layoutChanged)
+ def inspectorWidth(self) -> int:
+ return self._inspector_width
+
+ @inspectorWidth.setter
+ def inspectorWidth(self, value: int) -> None:
+ value = max(300, min(560, int(value)))
+ if value != self._inspector_width:
+ self._inspector_width = value
+ self._ui_settings.setValue("layout/inspectorWidth", value)
+ self.layoutChanged.emit()
+
+ @Property(int, notify=layoutChanged)
+ def queueHeight(self) -> int:
+ return self._queue_height
+
+ @queueHeight.setter
+ def queueHeight(self, value: int) -> None:
+ value = max(120, min(360, int(value)))
+ if value != self._queue_height:
+ self._queue_height = value
+ self._ui_settings.setValue("layout/queueHeight", value)
+ self.layoutChanged.emit()
+
+ @Property(int, notify=layoutChanged)
+ def logHeight(self) -> int:
+ return self._log_height
+
+ @logHeight.setter
+ def logHeight(self, value: int) -> None:
+ value = max(120, min(420, int(value)))
+ if value != self._log_height:
+ self._log_height = value
+ self._ui_settings.setValue("layout/logHeight", value)
+ self.layoutChanged.emit()
+
+ @Property(bool, notify=layoutChanged)
+ def focusPreview(self) -> bool:
+ return self._focus_preview
+
+ @focusPreview.setter
+ def focusPreview(self, value: bool) -> None:
+ value = bool(value)
+ if value != self._focus_preview:
+ self._focus_preview = value
+ self.layoutChanged.emit()
+
+ @Property(bool, notify=autoPreviewChanged)
+ def autoPreviewEnabled(self) -> bool:
+ return self._auto_preview_enabled
+
+ @autoPreviewEnabled.setter
+ def autoPreviewEnabled(self, value: bool) -> None:
+ value = bool(value)
+ if value == self._auto_preview_enabled:
+ return
+ self._auto_preview_enabled = value
+ self._ui_settings.setValue("preview/realtimeEnabled", value)
+ self.autoPreviewChanged.emit()
+ if value:
+ self._schedule_auto_preview(120)
+ else:
+ self._auto_preview_pending = False
+ self._auto_preview_timer.stop()
+
+ def _auto_preview_fingerprint(self, context_key: str | None = None) -> tuple:
+ """Snapshot what the current output preview was rendered from.
+
+ Returns ``(selected source, full settings snapshot)`` for the given
+ context. Compared against ``PreviewState.last_auto_fingerprint`` to
+ decide whether a scheduled auto-preview is redundant (e.g. returning
+ to a tab with unchanged settings). The full settings snapshot —
+ rather than per-tab subsets — keeps shared fields edited on another
+ tab (AI/video GPU, preview encoding) correctly marking this context
+ stale. Never raises; falls back to ``()`` (stale) on any error.
+ """
+ try:
+ key = context_key or self._context_key()
+ queue = self._queue_for_context(key)
+ source = queue.selected_path() or ""
+ try:
+ snapshot = tuple(
+ getattr(self._settings, field.name, None)
+ for field in _dataclass_fields(self._settings)
+ )
+ except Exception:
+ snapshot = ()
+ return (os.path.normcase(os.path.abspath(source)) if source else "", snapshot)
+ except Exception:
+ return ()
+
+ def _schedule_auto_preview(self, delay_ms: int = 360) -> None:
+ """Debounce an automatic preview for the currently selected media.
+
+ Slider drags can emit dozens of values per second; a single GPU preview
+ is launched only after edits settle. If an older preview is still
+ running it is cancelled and its generation is invalidated so it can
+ never overwrite the newer result.
+
+ Frame Interpolation is manual-only ("Preview"): realtime is
+ disabled for fi-video even when the global switch is on, so settings
+ tweaks and tab switches never trigger automatic renders there.
+ """
+ if self._context_key() == "fi-video":
+ self._auto_preview_pending = False
+ try:
+ self._auto_preview_timer.stop()
+ except Exception:
+ pass
+ return
+ if (
+ not self._auto_preview_enabled
+ or self._shutting_down
+ or self._runtime_state != "Ready"
+ or self._active_tab not in {"neural-rendering", "upscale", "frame-interpolation"}
+ ):
+ return
+ try:
+ source = self._active_queue().selected_path()
+ except Exception:
+ source = ""
+ if not source:
+ return
+
+ # Skip-if-fresh: returning to a tab (or mode) whose output preview
+ # already matches the selected source and current settings must not
+ # burn a GPU render. Settings edits change the live snapshot, so
+ # they mismatch and still render; a new selection mismatches too.
+ try:
+ key = self._context_key()
+ ctx = self._contexts[key]
+ if ctx.has_output and ctx.last_auto_fingerprint:
+ if ctx.last_auto_fingerprint == self._auto_preview_fingerprint(key):
+ self._auto_preview_pending = False
+ try:
+ self._auto_preview_timer.stop()
+ except Exception:
+ pass
+ return
+ except Exception:
+ pass
+
+ self._auto_preview_pending = True
+ if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING}:
+ self._invalidate_preview_generation()
+ worker = self._active_worker
+ if worker is not None:
+ try:
+ worker.controller.stop()
+ except Exception:
+ pass
+ self._operation_state = PREVIEW_CANCELLING
+ self._status_message = "Updating realtime preview…"
+ self.operationStateChanged.emit()
+ self.statusMessageChanged.emit()
+ self._auto_preview_timer.start(max(80, int(delay_ms)))
+
+ def _run_auto_preview(self) -> None:
+ if not self._auto_preview_pending or not self._auto_preview_enabled or self._shutting_down:
+ return
+ if self._operation_state == IDLE:
+ self._auto_preview_pending = False
+ self.renderPreview()
+ return
+ # Metadata loading / cancellation should finish quickly. Poll without
+ # blocking the GUI thread and launch the latest preview afterwards.
+ if self._operation_state in {LOADING_METADATA, PREVIEW_PREPARING, PREVIEW_RUNNING, PREVIEW_CANCELLING}:
+ self._auto_preview_timer.start(120)
+
+ # =========================================================================
+ # System Info Properties
+ # =========================================================================
+ def _display_gpu(self) -> dict[str, Any]:
+ """Return the GPU record that should be presented in the desktop UI.
+
+ This is an internal Python helper, not a Qt property. Keeping it as a
+ normal method avoids exposing a Python ``dict`` through the Qt meta
+ object and allows the public string properties below to call it safely.
+ """
+ if self._prepared is None:
+ return {}
+ selected = self._settings.ai_gpu_uuid
+ if selected and selected != "auto":
+ for gpu in self._prepared.gpus:
+ if str(gpu.get("uuid", "")) == selected:
+ return gpu
+ return self._prepared.gpu
+
+ @Property(str, notify=runtimeStateChanged)
+ def gpuName(self) -> str:
+ if self._prepared is None:
+ return "Initializing GPU…" if self._runtime_state == "Initializing" else "GPU unavailable"
+ return self._display_gpu().get("display_name", "NVIDIA GPU")
+
+ @Property(str, notify=runtimeStateChanged)
+ def gpuVram(self) -> str:
+ if self._prepared is None:
+ return ""
+ mb = int(self._display_gpu().get("memory_total_mb", 0) or 0)
+ return f"{mb // 1024} GB" if mb else ""
+
+ @Property(int, notify=runtimeStateChanged)
+ def gpuCount(self) -> int:
+ return len(self._prepared.gpus) if self._prepared is not None else 0
+
+ @Property(QObject, constant=True)
+ def nrImageQueue(self) -> QObject:
+ return self._nr_image_queue
+
+ @Property(QObject, constant=True)
+ def nrVideoQueue(self) -> QObject:
+ return self._nr_video_queue
+
+ @Property(QObject, constant=True)
+ def upscaleImageQueue(self) -> QObject:
+ return self._upscale_image_queue
+
+ @Property(QObject, constant=True)
+ def upscaleVideoQueue(self) -> QObject:
+ return self._upscale_video_queue
+
+ @Property(QObject, constant=True)
+ def fiQueue(self) -> QObject:
+ return self._fi_queue
+
+ @Property(bool, notify=mediaPreviewChanged)
+ def previewInputIsVideo(self) -> bool:
+ return self._context().input_is_video
+
+ @Property(bool, notify=mediaPreviewChanged)
+ def previewOutputIsVideo(self) -> bool:
+ return self._context().output_is_video
+
+ @Property(int, notify=layoutChanged)
+ def windowWidth(self) -> int:
+ return max(1080, self._window_width)
+
+ @Property(int, notify=layoutChanged)
+ def windowHeight(self) -> int:
+ return max(700, self._window_height)
+
+ @Property(int, notify=layoutChanged)
+ def windowX(self) -> int:
+ return self._window_x
+
+ @Property(int, notify=layoutChanged)
+ def windowY(self) -> int:
+ return self._window_y
+
+ @Property(bool, notify=layoutChanged)
+ def windowMaximized(self) -> bool:
+ return self._window_maximized
+
+ @Slot(int, int, int, int, bool)
+ def saveWindowLayout(self, x: int, y: int, width: int, height: int, maximized: bool) -> None:
+ if not maximized and width >= 1080 and height >= 700:
+ self._window_width, self._window_height = int(width), int(height)
+ self._window_x, self._window_y = int(x), int(y)
+ self._ui_settings.setValue("window/width", self._window_width)
+ self._ui_settings.setValue("window/height", self._window_height)
+ self._ui_settings.setValue("window/x", self._window_x)
+ self._ui_settings.setValue("window/y", self._window_y)
+ self._window_maximized = bool(maximized)
+ self._ui_settings.setValue("window/maximized", self._window_maximized)
+ self._ui_settings.sync()
+
+ @Property(str, constant=True)
+ def appVersion(self) -> str:
+ return "v10"
+
+ @Property(str, notify=runtimeStateChanged)
+ def diagnosticsText(self) -> str:
+ lines = [
+ f"Application: Visual Enhancer {self.appVersion}",
+ f"Runtime state: {self._runtime_state}",
+ f"Python: {platform.python_version()}",
+ f"Qt: {qVersion()}",
+ f"OS: {platform.platform()}",
+ f"GPU: {self.gpuName} {self.gpuVram}".rstrip(),
+ f"AI GPU selection: {self._settings.ai_gpu_uuid}",
+ f"Video GPU selection: {self._settings.video_gpu_uuid}",
+ f"FFmpeg: {'Available' if Path(FFMPEG).is_file() else 'Missing'} ({FFMPEG})",
+ f"FFprobe: {'Available' if Path(FFPROBE).is_file() else 'Missing'} ({FFPROBE})",
+ f"MPV: {'Available' if Path(MPV).is_file() else 'Missing'} ({MPV})",
+ f"Outputs: {OUTPUTS}",
+ f"Logs: {LOGS}",
+ f"Config: {CONFIG_PATH}",
+ ]
+ if self._runtime_error:
+ lines.append(f"Runtime error: {self._runtime_error}")
+ return "\n".join(lines)
+
+ @Property(list, constant=True)
+ def nrStyleChoices(self) -> list[str]:
+ return list(NR_STYLES)
+
+ @Property(list, constant=True)
+ def nrScaleChoices(self) -> list[dict[str, float]]:
+ return [{"label": mode["label"], "value": factor} for factor, mode in UPSCALING_MODES.items()]
+
+ @Property(list, constant=True)
+ def imageFormatChoices(self) -> list[str]:
+ return ["PNG", "JPEG", "WebP", "AVIF", "TIFF"]
+
+ @Property(list, constant=True)
+ def containerChoices(self) -> list[str]:
+ return list(CONTAINER_CHOICES)
+
+ @Property(list, constant=True)
+ def codecChoices(self) -> list[str]:
+ return list(CODEC_CHOICES)
+
+ @Property(list, constant=True)
+ def encodingQualityChoices(self) -> list[str]:
+ return list(ENCODING_QUALITIES)
+
+ @Property(list, constant=True)
+ def renameModeChoices(self) -> list[str]:
+ return list(RENAME_MODES)
+
+ @Property(list, constant=True)
+ def fiFpsChoices(self) -> list[dict[str, str]]:
+ return [{"label": f"{v} FPS", "value": v} for v in FPS_CHOICES]
+
+ @Property(list, constant=True)
+ def fiEngineChoices(self) -> list[str]:
+ return list(ENGINE_CHOICES)
+
+ @Property(list, constant=True)
+ def fiPreviewLengthChoices(self) -> list[dict[str, str]]:
+ return [{"label": f"{v}s", "value": v} for v in PREVIEW_LENGTH_CHOICES]
+
+ @Property(list, constant=True)
+ def previewEncodingChoices(self) -> list[str]:
+ return list(PREVIEW_ENCODING_CHOICES)
+
+ @Property(list, constant=True)
+ def liveSourceQualityChoices(self) -> list[str]:
+ return list(LIVE_SOURCE_QUALITY_CHOICES)
+
+ @Property(list, constant=True)
+ def liveMaxHeightChoices(self) -> list[dict[str, str]]:
+ return [{"label": f"{v}p", "value": v} for v in LIVE_MAX_HEIGHT_CHOICES]
+
+ @Property(list, constant=True)
+ def liveSegmentChoices(self) -> list[dict[str, str]]:
+ return [{"label": f"{v} sec", "value": v} for v in LIVE_SEGMENT_CHOICES]
+
+ @Property(list, constant=True)
+ def liveFpsChoices(self) -> list[str]:
+ return list(LIVE_FPS_CHOICES)
+
+ @Property(list, constant=True)
+ def imageSizeModeChoices(self) -> list[str]:
+ return list(IMAGE_SIZE_MODES)
+
+ @Property(list, constant=True)
+ def videoSizeModeChoices(self) -> list[str]:
+ return list(VIDEO_SIZE_MODES)
+
+ @Property(list, constant=True)
+ def imageScaleFactorChoices(self) -> list[dict[str, float]]:
+ return [{"label": label, "value": value} for label, value in IMAGE_SCALE_FACTORS]
+
+ @Property(list, constant=True)
+ def videoScaleFactorChoices(self) -> list[dict[str, float]]:
+ return [{"label": label, "value": value} for label, value in VIDEO_SCALE_FACTORS]
+
+ @Property(list, constant=True)
+ def vsrQualityChoices(self) -> list[dict[str, int]]:
+ return [{"label": label, "value": value} for label, value in VIDEO_VSR_QUALITIES]
+
+ @Property(list, constant=True)
+ def hdrPrecisionChoices(self) -> list[dict[str, str]]:
+ return [{"label": label, "value": value} for label, value in HDR_PRECISION_CHOICES]
+
+ @Property(list, notify=gpuChoicesChanged)
+ def aiGpuChoices(self) -> list[dict[str, str]]:
+ choices = [{"label": "Automatic (Best Available)", "value": "auto"}]
+ for g in (() if self._prepared is None else self._prepared.gpus):
+ if g.get("ai_compatible"):
+ name = g.get("display_name", "GPU")
+ vram = f" | {g.get('memory_total_mb', 0) // 1024} GB" if g.get("memory_total_mb") else ""
+ choices.append({"label": f"{name}{vram}", "value": str(g.get("uuid"))})
+ return choices
+
+ @Property(list, notify=gpuChoicesChanged)
+ def videoGpuChoices(self) -> list[dict[str, str]]:
+ choices = [{"label": "Automatic (Best Available)", "value": "auto"}]
+ for g in (() if self._prepared is None else self._prepared.gpus):
+ if g.get("cuda_ordinal") is not None:
+ name = g.get("display_name", "GPU")
+ choices.append({"label": name, "value": str(g.get("uuid"))})
+ return choices
+
+ @Slot()
+ def initializeRuntime(self) -> None:
+ if self._runtime_state == "Ready" or getattr(self, "_runtime_worker", None) is not None:
+ return
+ self._runtime_state = "Initializing"
+ self._runtime_error = ""
+ self.runtimeStateChanged.emit()
+ self._status_message = "Initializing NVIDIA runtime and media backends…"
+ self.statusMessageChanged.emit()
+
+ def task() -> Any:
+ sweep_stale_live_dirs()
+ initialize_image_runtime()
+ return prepare_runtime()
+
+ worker = JobWorker(task, inject_callbacks=False)
+ self._runtime_worker = worker
+
+ def done(prepared: Any) -> None:
+ self._runtime_worker = None
+ self._prepared = prepared
+ self._runtime_state = "Ready"
+ self._runtime_error = ""
+ self._normalize_gpu_selections()
+ self.runtimeStateChanged.emit()
+ self.gpuChoicesChanged.emit()
+ self.operationStateChanged.emit()
+ self._status_message = "Ready."
+ self.statusMessageChanged.emit()
+ self._log(f"Runtime ready on {self.gpuName}.")
+ self._schedule_auto_preview(180)
+
+ def failed(message: str) -> None:
+ self._runtime_worker = None
+ self._runtime_state = "Failed"
+ self._runtime_error = message
+ self.runtimeStateChanged.emit()
+ self.operationStateChanged.emit()
+ self._status_message = f"Runtime initialization failed: {message}"
+ self.statusMessageChanged.emit()
+ self._log(self._status_message)
+
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ self._thread_pool.start(worker)
+
+ def _normalize_gpu_selections(self) -> None:
+ if self._prepared is None:
+ return
+ ai_values = {item["value"] for item in self.aiGpuChoices}
+ video_values = {item["value"] for item in self.videoGpuChoices}
+ changes: dict[str, Any] = {}
+ messages: list[str] = []
+ if self._settings.ai_gpu_uuid not in ai_values:
+ changes["ai_gpu_uuid"] = "auto"
+ messages.append("Previously selected AI GPU is unavailable; Automatic is being used.")
+ if self._settings.video_gpu_uuid not in video_values:
+ changes["video_gpu_uuid"] = "auto"
+ messages.append("Previously selected video GPU is unavailable; Automatic is being used.")
+ if changes:
+ self._save_setting(**changes)
+ for message in messages:
+ self._log(message)
+
+ # =========================================================================
+ # Settings Properties (Synchronized with UISettings)
+ # =========================================================================
+ def _save_setting(self, **kwargs: Any) -> bool:
+ """Validate and publish a settings transaction atomically.
+
+ QML never observes a configuration that the backend considers invalid.
+ Codec/container/HDR dependencies are normalized as part of the same
+ transaction, and rejected edits immediately re-emit the canonical state.
+ """
+ changed = {k: v for k, v in kwargs.items() if hasattr(self._settings, k) and getattr(self._settings, k) != v}
+ if not changed:
+ return True
+ editable_states = {
+ IDLE, LIVE_RUNNING, LOADING_METADATA, PREVIEW_PREPARING,
+ PREVIEW_RUNNING, PREVIEW_CANCELLING,
+ }
+ if self._operation_state not in editable_states and not self._shutting_down:
+ self._status_message = "Stop the current operation before changing processing settings."
+ self.statusMessageChanged.emit()
+ self.settingsUpdated.emit()
+ return False
+
+ if "codec" in changed:
+ changed["container"] = container_for_codec(str(changed["codec"]))
+ if not hdr_mode_supported(str(changed["codec"])):
+ changed["hdr_mode"] = False
+ if "frame_interpolation_codec" in changed:
+ changed["frame_interpolation_container"] = container_for_codec(str(changed["frame_interpolation_codec"]))
+ if not hdr_mode_supported(str(changed["frame_interpolation_codec"])):
+ changed["frame_interpolation_hdr_mode"] = False
+ if "upscale_codec" in changed:
+ changed["upscale_container"] = container_for_codec(str(changed["upscale_codec"]))
+ if not hdr_mode_supported(str(changed["upscale_codec"])):
+ changed["upscale_hdr_enabled"] = False
+
+ candidate = replace(self._settings, **changed)
+ if not (candidate.upscale_vsr_enabled or candidate.upscale_hdr_enabled):
+ self._status_message = "Upscale Video requires VSR or RTX Video HDR to remain enabled."
+ self.statusMessageChanged.emit()
+ self.settingsUpdated.emit()
+ return False
+ try:
+ candidate = _validate(candidate)
+ except Exception as exc:
+ self._status_message = f"Invalid setting: {exc}"
+ self.statusMessageChanged.emit()
+ self.settingsUpdated.emit()
+ self._log(self._status_message)
+ return False
+
+ self._settings = candidate
+ SETTINGS_STATE.current = self._settings
+ if self._is_live_running and any(field in self.LIVE_EFFECT_FIELDS for field in changed):
+ self._live_effects_dirty = True
+ if self._is_live_running and any(field in self.LIVE_RESTART_FIELDS for field in changed):
+ self._status_message = "Setting saved; this change applies the next time Live is started."
+ self.statusMessageChanged.emit()
+ self.settingsUpdated.emit()
+ if "ai_gpu_uuid" in changed:
+ self.runtimeStateChanged.emit()
+ self.operationStateChanged.emit()
+ self._save_timer.start()
+ if any(field in self.FI_RANGE_FIELDS for field in changed):
+ # Rendered FI spans were built with older settings: drop them so
+ # the green overlay never claims stale footage as processed.
+ self._clear_fi_rendered_ranges()
+ if any(field in self.AUTO_PREVIEW_FIELDS for field in changed):
+ self._schedule_auto_preview()
+ return True
+
+ def _flush_settings(self) -> None:
+ try:
+ save_settings(CONFIG_PATH, self._settings)
+ except Exception as exc:
+ self._log(f"Failed to save settings: {exc}")
+ if self._is_live_running and self._live_effects_dirty:
+ try:
+ update_live_effects(live_effect_options(self._settings))
+ self._live_effects_dirty = False
+ except Exception as exc:
+ self._log(f"Live effect update failed: {exc}")
+
+ @Property(str, notify=settingsUpdated)
+ def nrStyle(self) -> str:
+ return self._settings.nr_style
+
+ @nrStyle.setter
+ def nrStyle(self, val: str) -> None:
+ if val in NR_STYLES and val != self._settings.nr_style:
+ self._save_setting(nr_style=val)
+
+ @Property(float, notify=settingsUpdated)
+ def upscalingFactor(self) -> float:
+ return self._settings.upscaling_factor
+
+ @upscalingFactor.setter
+ def upscalingFactor(self, val: float) -> None:
+ try:
+ factor, _ = resolve_upscaling_mode(val)
+ if factor != self._settings.upscaling_factor:
+ self._save_setting(upscaling_factor=factor)
+ except ValueError:
+ pass
+
+ @Property(float, notify=settingsUpdated)
+ def nrIntensity(self) -> float:
+ return self._settings.nr_intensity
+
+ @nrIntensity.setter
+ def nrIntensity(self, val: float) -> None:
+ self._save_setting(nr_intensity=round(val, 2))
+
+ @Property(int, notify=settingsUpdated)
+ def nrPasses(self) -> int:
+ return self._settings.nr_passes
+
+ @nrPasses.setter
+ def nrPasses(self, val: int) -> None:
+ self._save_setting(nr_passes=int(val))
+
+ @Property(float, notify=settingsUpdated)
+ def localToneStrength(self) -> float:
+ return self._settings.local_tone_strength
+
+ @localToneStrength.setter
+ def localToneStrength(self, val: float) -> None:
+ self._save_setting(local_tone_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def localStructureStrength(self) -> float:
+ return self._settings.local_structure_strength
+
+ @localStructureStrength.setter
+ def localStructureStrength(self, val: float) -> None:
+ self._save_setting(local_structure_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def skinStructureStrength(self) -> float:
+ return self._settings.skin_structure_strength
+
+ @skinStructureStrength.setter
+ def skinStructureStrength(self, val: float) -> None:
+ val = round(val, 2)
+ auto_mask = self._settings.automatic_mask
+ if val > -1.0 and not auto_mask:
+ auto_mask = True
+ self._save_setting(skin_structure_strength=val, automatic_mask=auto_mask)
+
+ @Property(bool, notify=settingsUpdated)
+ def automaticMask(self) -> bool:
+ return self._settings.automatic_mask
+
+ @automaticMask.setter
+ def automaticMask(self, val: bool) -> None:
+ self._save_setting(automatic_mask=bool(val))
+
+ @Property(float, notify=settingsUpdated)
+ def nrColorStrength(self) -> float:
+ return self._settings.nr_color_strength
+
+ @nrColorStrength.setter
+ def nrColorStrength(self, val: float) -> None:
+ self._save_setting(nr_color_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def tonePreservation(self) -> float:
+ return self._settings.tone_preservation
+
+ @tonePreservation.setter
+ def tonePreservation(self, val: float) -> None:
+ self._save_setting(tone_preservation=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def faceSkinProtection(self) -> float:
+ return self._settings.face_skin_protection
+
+ @faceSkinProtection.setter
+ def faceSkinProtection(self, val: float) -> None:
+ self._save_setting(face_skin_protection=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def grainPreservation(self) -> float:
+ return self._settings.grain_preservation
+
+ @grainPreservation.setter
+ def grainPreservation(self, val: float) -> None:
+ self._save_setting(grain_preservation=round(val, 2))
+
+ @Property(int, notify=settingsUpdated)
+ def maskFeather(self) -> int:
+ return self._settings.mask_feather
+
+ @maskFeather.setter
+ def maskFeather(self, val: int) -> None:
+ self._save_setting(mask_feather=int(val))
+
+ @Property(float, notify=settingsUpdated)
+ def shimmerSuppression(self) -> float:
+ return self._settings.shimmer_suppression
+
+ @shimmerSuppression.setter
+ def shimmerSuppression(self, val: float) -> None:
+ self._save_setting(shimmer_suppression=round(val, 2))
+
+ # Independent Live-tab mirrors of the NR controls above. The Live tab
+ # binds only these, so tuning or resetting Live never touches the
+ # Neural Rendering tab (and vice versa).
+ @Property(str, notify=settingsUpdated)
+ def liveNrStyle(self) -> str:
+ return self._settings.live_nr_style
+
+ @liveNrStyle.setter
+ def liveNrStyle(self, val: str) -> None:
+ if val in NR_STYLES and val != self._settings.live_nr_style:
+ self._save_setting(live_nr_style=val)
+
+ @Property(float, notify=settingsUpdated)
+ def liveUpscalingFactor(self) -> float:
+ return self._settings.live_upscaling_factor
+
+ @liveUpscalingFactor.setter
+ def liveUpscalingFactor(self, val: float) -> None:
+ try:
+ factor, _ = resolve_upscaling_mode(val)
+ if factor != self._settings.live_upscaling_factor:
+ self._save_setting(live_upscaling_factor=factor)
+ except ValueError:
+ pass
+
+ @Property(float, notify=settingsUpdated)
+ def liveNrIntensity(self) -> float:
+ return self._settings.live_nr_intensity
+
+ @liveNrIntensity.setter
+ def liveNrIntensity(self, val: float) -> None:
+ self._save_setting(live_nr_intensity=round(val, 2))
+
+ @Property(int, notify=settingsUpdated)
+ def liveNrPasses(self) -> int:
+ return self._settings.live_nr_passes
+
+ @liveNrPasses.setter
+ def liveNrPasses(self, val: int) -> None:
+ self._save_setting(live_nr_passes=int(val))
+
+ @Property(float, notify=settingsUpdated)
+ def liveLocalToneStrength(self) -> float:
+ return self._settings.live_local_tone_strength
+
+ @liveLocalToneStrength.setter
+ def liveLocalToneStrength(self, val: float) -> None:
+ self._save_setting(live_local_tone_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def liveLocalStructureStrength(self) -> float:
+ return self._settings.live_local_structure_strength
+
+ @liveLocalStructureStrength.setter
+ def liveLocalStructureStrength(self, val: float) -> None:
+ self._save_setting(live_local_structure_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def liveSkinStructureStrength(self) -> float:
+ return self._settings.live_skin_structure_strength
+
+ @liveSkinStructureStrength.setter
+ def liveSkinStructureStrength(self, val: float) -> None:
+ val = round(val, 2)
+ auto_mask = self._settings.live_automatic_mask
+ if val > -1.0 and not auto_mask:
+ auto_mask = True
+ self._save_setting(live_skin_structure_strength=val, live_automatic_mask=auto_mask)
+
+ @Property(bool, notify=settingsUpdated)
+ def liveAutomaticMask(self) -> bool:
+ return self._settings.live_automatic_mask
+
+ @liveAutomaticMask.setter
+ def liveAutomaticMask(self, val: bool) -> None:
+ self._save_setting(live_automatic_mask=bool(val))
+
+ @Property(float, notify=settingsUpdated)
+ def liveNrColorStrength(self) -> float:
+ return self._settings.live_nr_color_strength
+
+ @liveNrColorStrength.setter
+ def liveNrColorStrength(self, val: float) -> None:
+ self._save_setting(live_nr_color_strength=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def liveTonePreservation(self) -> float:
+ return self._settings.live_tone_preservation
+
+ @liveTonePreservation.setter
+ def liveTonePreservation(self, val: float) -> None:
+ self._save_setting(live_tone_preservation=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def liveFaceSkinProtection(self) -> float:
+ return self._settings.live_face_skin_protection
+
+ @liveFaceSkinProtection.setter
+ def liveFaceSkinProtection(self, val: float) -> None:
+ self._save_setting(live_face_skin_protection=round(val, 2))
+
+ @Property(float, notify=settingsUpdated)
+ def liveGrainPreservation(self) -> float:
+ return self._settings.live_grain_preservation
+
+ @liveGrainPreservation.setter
+ def liveGrainPreservation(self, val: float) -> None:
+ self._save_setting(live_grain_preservation=round(val, 2))
+
+ @Property(int, notify=settingsUpdated)
+ def liveMaskFeather(self) -> int:
+ return self._settings.live_mask_feather
+
+ @liveMaskFeather.setter
+ def liveMaskFeather(self, val: int) -> None:
+ self._save_setting(live_mask_feather=int(val))
+
+ @Property(float, notify=settingsUpdated)
+ def liveShimmerSuppression(self) -> float:
+ return self._settings.live_shimmer_suppression
+
+ @liveShimmerSuppression.setter
+ def liveShimmerSuppression(self, val: float) -> None:
+ self._save_setting(live_shimmer_suppression=round(val, 2))
+
+ @Property(str, notify=settingsUpdated)
+ def customMaskStatus(self) -> str:
+ return mask_status(self._settings.nr_mask)
+
+ # Output & Format settings
+ @Property(str, notify=settingsUpdated)
+ def imageFormat(self) -> str:
+ return self._settings.image_format
+
+ @imageFormat.setter
+ def imageFormat(self, val: str) -> None:
+ self._save_setting(image_format=val)
+
+ @Property(int, notify=settingsUpdated)
+ def imageQuality(self) -> int:
+ return self._settings.image_quality
+
+ @imageQuality.setter
+ def imageQuality(self, val: int) -> None:
+ self._save_setting(image_quality=int(val))
+
+ @Property(str, notify=settingsUpdated)
+ def imageRenameMode(self) -> str:
+ return self._settings.image_rename_mode
+
+ @imageRenameMode.setter
+ def imageRenameMode(self, val: str) -> None:
+ self._save_setting(image_rename_mode=val)
+
+ @Property(str, notify=settingsUpdated)
+ def imageCustomSuffix(self) -> str:
+ return self._settings.image_custom_suffix
+
+ @imageCustomSuffix.setter
+ def imageCustomSuffix(self, val: str) -> None:
+ self._save_setting(image_custom_suffix=val)
+
+ @Property(str, notify=settingsUpdated)
+ def videoCodec(self) -> str:
+ return self._settings.codec
+
+ @videoCodec.setter
+ def videoCodec(self, val: str) -> None:
+ container = container_for_codec(val)
+ hdr = self._settings.hdr_mode and hdr_mode_supported(val)
+ self._save_setting(codec=val, container=container, hdr_mode=hdr)
+
+ @Property(str, notify=settingsUpdated)
+ def videoContainer(self) -> str:
+ return container_for_codec(self._settings.codec)
+
+ @Property(str, notify=settingsUpdated)
+ def videoQuality(self) -> str:
+ return self._settings.quality
+
+ @videoQuality.setter
+ def videoQuality(self, val: str) -> None:
+ self._save_setting(quality=val)
+
+ @Property(bool, notify=settingsUpdated)
+ def videoHdrMode(self) -> bool:
+ return self._settings.hdr_mode
+
+ @videoHdrMode.setter
+ def videoHdrMode(self, val: bool) -> None:
+ self._save_setting(hdr_mode=coerce_hdr_mode(self._settings.codec, val))
+
+ @Property(str, notify=settingsUpdated)
+ def videoRenameMode(self) -> str:
+ return self._settings.video_rename_mode
+
+ @videoRenameMode.setter
+ def videoRenameMode(self, val: str) -> None:
+ self._save_setting(video_rename_mode=val)
+
+ @Property(str, notify=settingsUpdated)
+ def videoCustomSuffix(self) -> str:
+ return self._settings.video_custom_suffix
+
+ @videoCustomSuffix.setter
+ def videoCustomSuffix(self, val: str) -> None:
+ self._save_setting(video_custom_suffix=val)
+
+ # Upscale Image & Video
+ @Property(int, notify=settingsUpdated)
+ def upscaleImageVsrQuality(self) -> int:
+ return self._settings.upscale_image_vsr_quality
+
+ @upscaleImageVsrQuality.setter
+ def upscaleImageVsrQuality(self, val: int) -> None:
+ self._save_setting(upscale_image_vsr_quality=int(val))
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleImageSizeMode(self) -> str:
+ return self._settings.upscale_image_size_mode
+
+ @upscaleImageSizeMode.setter
+ def upscaleImageSizeMode(self, val: str) -> None:
+ self._save_setting(upscale_image_size_mode=val)
+
+ @Property(float, notify=settingsUpdated)
+ def upscaleImageScaleFactor(self) -> float:
+ return self._settings.upscale_image_scale_factor
+
+ @upscaleImageScaleFactor.setter
+ def upscaleImageScaleFactor(self, val: float) -> None:
+ self._save_setting(upscale_image_scale_factor=float(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleImageWidth(self) -> int:
+ return self._settings.upscale_image_width
+
+ @upscaleImageWidth.setter
+ def upscaleImageWidth(self, val: int) -> None:
+ width = max(1, int(val))
+ if self._settings.upscale_image_aspect_lock and self._context("upscale-image").source_aspect_ratio:
+ height = max(1, round(width / self._context("upscale-image").source_aspect_ratio))
+ self._save_setting(upscale_image_width=width, upscale_image_height=height)
+ else:
+ self._save_setting(upscale_image_width=width)
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleImageHeight(self) -> int:
+ return self._settings.upscale_image_height
+
+ @upscaleImageHeight.setter
+ def upscaleImageHeight(self, val: int) -> None:
+ height = max(1, int(val))
+ if self._settings.upscale_image_aspect_lock and self._context("upscale-image").source_aspect_ratio:
+ width = max(1, round(height * self._context("upscale-image").source_aspect_ratio))
+ self._save_setting(upscale_image_width=width, upscale_image_height=height)
+ else:
+ self._save_setting(upscale_image_height=height)
+
+ @Property(bool, notify=settingsUpdated)
+ def upscaleImageAspectLock(self) -> bool:
+ return self._settings.upscale_image_aspect_lock
+
+ @upscaleImageAspectLock.setter
+ def upscaleImageAspectLock(self, val: bool) -> None:
+ self._save_setting(upscale_image_aspect_lock=bool(val))
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleImageOutputFormat(self) -> str:
+ return self._settings.upscale_image_output_format
+
+ @upscaleImageOutputFormat.setter
+ def upscaleImageOutputFormat(self, val: str) -> None:
+ self._save_setting(upscale_image_output_format=val)
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleImageQuality(self) -> int:
+ return self._settings.upscale_image_quality
+
+ @upscaleImageQuality.setter
+ def upscaleImageQuality(self, val: int) -> None:
+ self._save_setting(upscale_image_quality=int(val))
+
+ @Property(bool, notify=settingsUpdated)
+ def upscaleImagePreserveMetadata(self) -> bool:
+ return self._settings.upscale_image_preserve_metadata
+
+ @upscaleImagePreserveMetadata.setter
+ def upscaleImagePreserveMetadata(self, val: bool) -> None:
+ self._save_setting(upscale_image_preserve_metadata=bool(val))
+
+ # Upscale Video
+ @Property(bool, notify=settingsUpdated)
+ def upscaleVsrEnabled(self) -> bool:
+ return self._settings.upscale_vsr_enabled
+
+ @upscaleVsrEnabled.setter
+ def upscaleVsrEnabled(self, val: bool) -> None:
+ self._save_setting(upscale_vsr_enabled=bool(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleVsrQuality(self) -> int:
+ return self._settings.upscale_vsr_quality
+
+ @upscaleVsrQuality.setter
+ def upscaleVsrQuality(self, val: int) -> None:
+ self._save_setting(upscale_vsr_quality=int(val))
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleSizeMode(self) -> str:
+ return self._settings.upscale_size_mode
+
+ @upscaleSizeMode.setter
+ def upscaleSizeMode(self, val: str) -> None:
+ self._save_setting(upscale_size_mode=val)
+
+ @Property(float, notify=settingsUpdated)
+ def upscaleScaleFactor(self) -> float:
+ return self._settings.upscale_scale_factor
+
+ @upscaleScaleFactor.setter
+ def upscaleScaleFactor(self, val: float) -> None:
+ self._save_setting(upscale_scale_factor=float(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleWidth(self) -> int:
+ return self._settings.upscale_width
+
+ @upscaleWidth.setter
+ def upscaleWidth(self, val: int) -> None:
+ width = max(2, int(val))
+ if self._settings.upscale_aspect_lock and self._context("upscale-video").source_aspect_ratio:
+ height = max(2, round(width / self._context("upscale-video").source_aspect_ratio))
+ self._save_setting(upscale_width=width, upscale_height=height)
+ else:
+ self._save_setting(upscale_width=width)
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleHeight(self) -> int:
+ return self._settings.upscale_height
+
+ @upscaleHeight.setter
+ def upscaleHeight(self, val: int) -> None:
+ height = max(2, int(val))
+ if self._settings.upscale_aspect_lock and self._context("upscale-video").source_aspect_ratio:
+ width = max(2, round(height * self._context("upscale-video").source_aspect_ratio))
+ self._save_setting(upscale_width=width, upscale_height=height)
+ else:
+ self._save_setting(upscale_height=height)
+
+ @Property(bool, notify=settingsUpdated)
+ def upscaleAspectLock(self) -> bool:
+ return self._settings.upscale_aspect_lock
+
+ @upscaleAspectLock.setter
+ def upscaleAspectLock(self, val: bool) -> None:
+ self._save_setting(upscale_aspect_lock=bool(val))
+
+ @Property(bool, notify=settingsUpdated)
+ def upscaleHdrEnabled(self) -> bool:
+ return self._settings.upscale_hdr_enabled
+
+ @upscaleHdrEnabled.setter
+ def upscaleHdrEnabled(self, val: bool) -> None:
+ self._save_setting(upscale_hdr_enabled=bool(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleHdrContrast(self) -> int:
+ return self._settings.upscale_hdr_contrast
+
+ @upscaleHdrContrast.setter
+ def upscaleHdrContrast(self, val: int) -> None:
+ self._save_setting(upscale_hdr_contrast=int(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleHdrSaturation(self) -> int:
+ return self._settings.upscale_hdr_saturation
+
+ @upscaleHdrSaturation.setter
+ def upscaleHdrSaturation(self, val: int) -> None:
+ self._save_setting(upscale_hdr_saturation=int(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleHdrMiddleGray(self) -> int:
+ return self._settings.upscale_hdr_middle_gray
+
+ @upscaleHdrMiddleGray.setter
+ def upscaleHdrMiddleGray(self, val: int) -> None:
+ self._save_setting(upscale_hdr_middle_gray=int(val))
+
+ @Property(int, notify=settingsUpdated)
+ def upscaleHdrPeakLuminance(self) -> int:
+ return self._settings.upscale_hdr_peak_luminance
+
+ @upscaleHdrPeakLuminance.setter
+ def upscaleHdrPeakLuminance(self, val: int) -> None:
+ self._save_setting(upscale_hdr_peak_luminance=int(val))
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleHdrPrecision(self) -> str:
+ return self._settings.upscale_hdr_precision
+
+ @upscaleHdrPrecision.setter
+ def upscaleHdrPrecision(self, val: str) -> None:
+ self._save_setting(upscale_hdr_precision=val)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleCodec(self) -> str:
+ return self._settings.upscale_codec
+
+ @upscaleCodec.setter
+ def upscaleCodec(self, val: str) -> None:
+ container = container_for_codec(val)
+ hdr = self._settings.upscale_hdr_enabled and hdr_mode_supported(val)
+ self._save_setting(upscale_codec=val, upscale_container=container, upscale_hdr_enabled=hdr)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleContainer(self) -> str:
+ return container_for_codec(self._settings.upscale_codec)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleQuality(self) -> str:
+ return self._settings.upscale_quality
+
+ @upscaleQuality.setter
+ def upscaleQuality(self, val: str) -> None:
+ if val in ENCODING_QUALITIES:
+ self._save_setting(upscale_quality=val)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleImageRenameMode(self) -> str:
+ return self._settings.upscale_image_rename_mode
+
+ @upscaleImageRenameMode.setter
+ def upscaleImageRenameMode(self, val: str) -> None:
+ if val in RENAME_MODES:
+ self._save_setting(upscale_image_rename_mode=val)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleImageCustomSuffix(self) -> str:
+ return self._settings.upscale_image_custom_suffix
+
+ @upscaleImageCustomSuffix.setter
+ def upscaleImageCustomSuffix(self, val: str) -> None:
+ self._save_setting(upscale_image_custom_suffix=val)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleRenameMode(self) -> str:
+ return self._settings.upscale_rename_mode
+
+ @upscaleRenameMode.setter
+ def upscaleRenameMode(self, val: str) -> None:
+ if val in RENAME_MODES:
+ self._save_setting(upscale_rename_mode=val)
+
+ @Property(str, notify=settingsUpdated)
+ def upscaleCustomSuffix(self) -> str:
+ return self._settings.upscale_custom_suffix
+
+ @upscaleCustomSuffix.setter
+ def upscaleCustomSuffix(self, val: str) -> None:
+ self._save_setting(upscale_custom_suffix=val)
+
+ # Frame Interpolation
+ @Property(str, notify=settingsUpdated)
+ def fiTargetFps(self) -> str:
+ return self._settings.frame_interpolation_target_fps
+
+ @fiTargetFps.setter
+ def fiTargetFps(self, val: str) -> None:
+ self._save_setting(frame_interpolation_target_fps=val)
+
+ @Property(str, notify=settingsUpdated)
+ def fiEngine(self) -> str:
+ return self._settings.frame_interpolation_engine
+
+ @fiEngine.setter
+ def fiEngine(self, val: str) -> None:
+ self._save_setting(frame_interpolation_engine=val)
+
+ @Property(str, notify=settingsUpdated)
+ def fiCodec(self) -> str:
+ return self._settings.frame_interpolation_codec
+
+ @fiCodec.setter
+ def fiCodec(self, val: str) -> None:
+ container = container_for_codec(val)
+ hdr = self._settings.frame_interpolation_hdr_mode and hdr_mode_supported(val)
+ self._save_setting(frame_interpolation_codec=val, frame_interpolation_container=container, frame_interpolation_hdr_mode=hdr)
+
+ @Property(str, notify=settingsUpdated)
+ def fiContainer(self) -> str:
+ return container_for_codec(self._settings.frame_interpolation_codec)
+
+ @Property(str, notify=settingsUpdated)
+ def fiQuality(self) -> str:
+ return self._settings.frame_interpolation_quality
+
+ @fiQuality.setter
+ def fiQuality(self, val: str) -> None:
+ self._save_setting(frame_interpolation_quality=val)
+
+ @Property(str, notify=settingsUpdated)
+ def fiPreviewLength(self) -> str:
+ return self._settings.frame_interpolation_preview_length
+
+ @fiPreviewLength.setter
+ def fiPreviewLength(self, val: str) -> None:
+ if str(val) in PREVIEW_LENGTH_CHOICES:
+ self._save_setting(frame_interpolation_preview_length=str(val))
+
+ @Property(bool, notify=settingsUpdated)
+ def fiHdrMode(self) -> bool:
+ return self._settings.frame_interpolation_hdr_mode
+
+ @fiHdrMode.setter
+ def fiHdrMode(self, val: bool) -> None:
+ self._save_setting(frame_interpolation_hdr_mode=coerce_hdr_mode(self._settings.frame_interpolation_codec, val))
+
+ @Property(str, notify=settingsUpdated)
+ def fiRenameMode(self) -> str:
+ return self._settings.frame_interpolation_rename_mode
+
+ @fiRenameMode.setter
+ def fiRenameMode(self, val: str) -> None:
+ if val in RENAME_MODES:
+ self._save_setting(frame_interpolation_rename_mode=val)
+
+ @Property(str, notify=settingsUpdated)
+ def fiCustomSuffix(self) -> str:
+ return self._settings.frame_interpolation_custom_suffix
+
+ @fiCustomSuffix.setter
+ def fiCustomSuffix(self, val: str) -> None:
+ self._save_setting(frame_interpolation_custom_suffix=val)
+
+ @Property(bool, notify=settingsUpdated)
+ def videoHdrSupported(self) -> bool:
+ return hdr_mode_supported(self._settings.codec)
+
+ @Property(bool, notify=settingsUpdated)
+ def fiHdrSupported(self) -> bool:
+ return hdr_mode_supported(self._settings.frame_interpolation_codec)
+
+ @Property(bool, notify=settingsUpdated)
+ def upscaleHdrSupported(self) -> bool:
+ return hdr_mode_supported(self._settings.upscale_codec)
+
+ # Global Preferences
+ @Property(str, notify=settingsUpdated)
+ def aiGpuUuid(self) -> str:
+ return self._settings.ai_gpu_uuid
+
+ @aiGpuUuid.setter
+ def aiGpuUuid(self, val: str) -> None:
+ self._save_setting(ai_gpu_uuid=val)
+
+ @Property(str, notify=settingsUpdated)
+ def videoGpuUuid(self) -> str:
+ return self._settings.video_gpu_uuid
+
+ @videoGpuUuid.setter
+ def videoGpuUuid(self, val: str) -> None:
+ self._save_setting(video_gpu_uuid=val)
+
+ @Property(str, notify=settingsUpdated)
+ def previewEncoding(self) -> str:
+ return self._settings.preview_encoding
+
+ @previewEncoding.setter
+ def previewEncoding(self, val: str) -> None:
+ self._save_setting(preview_encoding=val)
+
+ @Property(bool, notify=settingsUpdated)
+ def fullSizeImagePreviews(self) -> bool:
+ return self._settings.full_size_image_previews
+
+ @fullSizeImagePreviews.setter
+ def fullSizeImagePreviews(self, val: bool) -> None:
+ self._save_setting(full_size_image_previews=bool(val))
+
+ def _active_render_configuration_valid(self) -> bool:
+ try:
+ _validate(self._settings)
+ if self._active_tab == "upscale" and self._upscale_mode == "Video":
+ video_upscale_options_from_settings(self._settings).validate(for_render=True)
+ elif self._active_tab == "upscale" and self._upscale_mode == "Image":
+ image_upscale_options_from_settings(self._settings).validate(for_render=True)
+ return True
+ except Exception:
+ return False
+
+ @Property(str, notify=settingsUpdated)
+ def renderValidationMessage(self) -> str:
+ try:
+ _validate(self._settings)
+ if self._active_tab == "upscale" and self._upscale_mode == "Video":
+ video_upscale_options_from_settings(self._settings).validate(for_render=True)
+ elif self._active_tab == "upscale" and self._upscale_mode == "Image":
+ image_upscale_options_from_settings(self._settings).validate(for_render=True)
+ return ""
+ except Exception as exc:
+ return str(exc)
+
+ @Property(str, notify=settingsUpdated)
+ def outputEstimate(self) -> str:
+ context = self._context()
+ width, height = context.source_width, context.source_height
+ if width <= 0 or height <= 0:
+ return ""
+ try:
+ if self._active_tab == "neural-rendering":
+ ow, oh = resolve_output_size(width, height, self._settings.upscaling_factor)
+ return f"{width}×{height} → {ow}×{oh}"
+ if self._active_tab == "upscale" and self._upscale_mode == "Image":
+ ow, oh = image_upscale_output_size(width, height, image_upscale_options_from_settings(self._settings))
+ return f"{width}×{height} → {ow}×{oh}"
+ if self._active_tab == "upscale" and self._upscale_mode == "Video":
+ ow, oh, note = video_upscale_output_size(width, height, video_upscale_options_from_settings(self._settings))
+ return f"{width}×{height} → {ow}×{oh}{note}"
+ if self._active_tab == "frame-interpolation":
+ return f"Target {self._settings.frame_interpolation_target_fps} FPS"
+ except Exception as exc:
+ return f"Output unavailable: {exc}"
+ return ""
+
+ # =========================================================================
+ # Methods & Slots: Presets & Defaults
+ # =========================================================================
+ @Slot()
+ def applyDetailOnly(self) -> None:
+ self._save_setting(nr_color_strength=0.0, tone_preservation=1.0)
+ self._log("Applied Detail-Only preset.")
+
+ @Slot(str)
+ def selectCustomMask(self, file_url_or_path: str) -> None:
+ path = self._clean_path(file_url_or_path)
+ try:
+ selection = inspect_nr_mask(path)
+ self._save_setting(nr_mask=selection)
+ self._log(f"Custom NR Mask loaded: {path}")
+ except Exception as exc:
+ self._log(f"Error loading mask: {exc}")
+
+ @Slot()
+ def clearCustomMask(self) -> None:
+ self._save_setting(nr_mask=None)
+ self._log("Custom NR Mask cleared.")
+
+ @Slot()
+ def resetToDefaults(self) -> None:
+ if self._operation_state not in {IDLE, LIVE_RUNNING}:
+ self._preset_status = "Stop the current operation before resetting settings."
+ self.presetStatusChanged.emit()
+ return
+ self._settings = DEFAULT_SETTINGS
+ SETTINGS_STATE.current = self._settings
+ if self._upscale_mode != DEFAULT_SETTINGS.upscale_mode:
+ self._upscale_mode = DEFAULT_SETTINGS.upscale_mode
+ self.upscaleModeChanged.emit()
+ self._emit_context()
+ if self._is_live_running:
+ self._live_effects_dirty = True
+ self._flush_settings()
+ self.settingsUpdated.emit()
+ self.runtimeStateChanged.emit()
+ self._preset_status = "All settings were reset to factory defaults."
+ self.presetStatusChanged.emit()
+ self._log("Reset all settings to factory defaults.")
+
+ # Per-tab Reset buttons (action bars). Prefix groups track the dataclass
+ # automatically; the Neural group is explicit (sidebar cards + export).
+ TAB_RESET_PREFIXES = {
+ "upscale": "upscale_",
+ "frame-interpolation": "frame_interpolation_",
+ "live": "live_",
+ }
+ TAB_RESET_NEURAL_FIELDS = (
+ "nr_style", "nr_intensity", "nr_passes",
+ "local_tone_strength", "local_structure_strength",
+ "skin_structure_strength", "automatic_mask",
+ "nr_color_strength", "tone_preservation",
+ "face_skin_protection", "grain_preservation",
+ "shimmer_suppression", "mask_feather", "nr_mask",
+ "upscaling_factor",
+ "codec", "quality", "hdr_mode",
+ "image_format", "image_quality",
+ "image_rename_mode", "image_custom_suffix",
+ "video_rename_mode", "video_custom_suffix",
+ )
+ TAB_RESET_LABELS = {
+ "neural-rendering": "Neural Rendering",
+ "upscale": "Upscale",
+ "frame-interpolation": "Frame Interpolation",
+ "live": "Live",
+ }
+
+ @Slot(str)
+ def resetTabSettings(self, tab: str) -> None:
+ """Restore one tab's sidebar settings to factory defaults."""
+ tab = tab or ""
+ if tab in self.TAB_RESET_PREFIXES:
+ prefix = self.TAB_RESET_PREFIXES[tab]
+ names = [f.name for f in _dataclass_fields(UISettings) if f.name.startswith(prefix)]
+ elif tab == "neural-rendering":
+ names = list(self.TAB_RESET_NEURAL_FIELDS)
+ else:
+ return
+ if self._operation_state not in {IDLE, LIVE_RUNNING}:
+ self._preset_status = "Stop the current operation before resetting settings."
+ self.presetStatusChanged.emit()
+ return
+ values = {name: getattr(DEFAULT_SETTINGS, name) for name in names}
+ if not self._save_setting(**values):
+ return
+ if tab == "upscale" and self._upscale_mode != self._settings.upscale_mode:
+ self._upscale_mode = self._settings.upscale_mode
+ self.upscaleModeChanged.emit()
+ self._emit_context()
+ label = self.TAB_RESET_LABELS[tab]
+ self._preset_status = f"{label} settings were reset to defaults."
+ self.presetStatusChanged.emit()
+ self._flush_settings()
+ self._log(f"Reset {label} settings to defaults.")
+
+ @Slot(str, result=str)
+ def exportPreset(self, name: str) -> str:
+ if not name.strip():
+ self._preset_status = "Please enter a preset name."
+ self.presetStatusChanged.emit()
+ return ""
+ try:
+ path = export_settings_preset(name, self._settings)
+ self._preset_status = f"Exported preset '{name}' to {path.name}"
+ self.presetStatusChanged.emit()
+ self._log(f"Exported preset '{name}' to {path}")
+ return str(path)
+ except Exception as exc:
+ self._preset_status = f"Export failed: {exc}"
+ self.presetStatusChanged.emit()
+ return ""
+
+ @Slot(str, str, result=str)
+ def exportPresetTo(self, name: str, file_url_or_path: str) -> str:
+ if not name.strip():
+ self._preset_status = "Please enter a preset name."
+ self.presetStatusChanged.emit()
+ return ""
+ path = self._clean_path(file_url_or_path)
+ if not path:
+ return ""
+ try:
+ written = export_settings_preset_to(name, self._settings, path)
+ self._preset_status = f"Exported preset '{name}' to {written.name}"
+ self.presetStatusChanged.emit()
+ self._log(f"Exported preset '{name}' to {written}")
+ return str(written)
+ except Exception as exc:
+ self._preset_status = f"Export failed: {exc}"
+ self.presetStatusChanged.emit()
+ return ""
+
+ @Slot(str, result=bool)
+ def importPreset(self, file_url_or_path: str) -> bool:
+ if self._operation_state not in {IDLE, LIVE_RUNNING}:
+ self._preset_status = "Stop the current operation before importing a preset."
+ self.presetStatusChanged.emit()
+ return False
+ path = self._clean_path(file_url_or_path)
+ try:
+ name, imported = import_settings_preset(path, self._settings)
+ imported = _validate(imported)
+ self._settings = imported
+ SETTINGS_STATE.current = self._settings
+ if self._upscale_mode != imported.upscale_mode:
+ self._upscale_mode = imported.upscale_mode
+ self.upscaleModeChanged.emit()
+ self._emit_context()
+ if self._is_live_running:
+ self._live_effects_dirty = True
+ self._flush_settings()
+ self.settingsUpdated.emit()
+ self.runtimeStateChanged.emit()
+ self._preset_status = f"Imported preset '{name}' successfully."
+ self.presetStatusChanged.emit()
+ self._log(f"Imported preset '{name}' from {path}")
+ return True
+ except Exception as exc:
+ self._preset_status = f"Import failed: {exc}"
+ self.presetStatusChanged.emit()
+ return False
+
+ # =========================================================================
+ # Queue Management
+ # =========================================================================
+ def _active_queue(self) -> BatchListModel:
+ if self._active_tab == "neural-rendering":
+ return self._nr_image_queue if self._nr_mode == "Image" else self._nr_video_queue
+ if self._active_tab == "upscale":
+ return self._upscale_image_queue if self._upscale_mode == "Image" else self._upscale_video_queue
+ if self._active_tab == "frame-interpolation":
+ return self._fi_queue
+ return self._nr_image_queue
+
+ def _queue_for_context(self, key: str) -> BatchListModel:
+ return {
+ "nr-image": self._nr_image_queue,
+ "nr-video": self._nr_video_queue,
+ "upscale-image": self._upscale_image_queue,
+ "upscale-video": self._upscale_video_queue,
+ "fi-video": self._fi_queue,
+ }[key]
+
+ def _active_accepts_images(self) -> bool:
+ return self._context_key() in {"nr-image", "upscale-image"}
+
+ @staticmethod
+ def _classify_media_suffix(suffix: str) -> str | None:
+ """Classify a file suffix as "image", "video", or None (unsupported)."""
+ s = (suffix or "").lower()
+ if s in IMAGE_SUFFIXES:
+ return "image"
+ if s in VIDEO_SUFFIXES:
+ return "video"
+ return None
+
+ def _detect_batch_kind(self, file_urls: list[str]) -> tuple[int, int]:
+ """Peek dropped/picked inputs and count (image_files, video_files).
+
+ Folders are scanned (early-exits as soon as both kinds are seen).
+ Unsupported files are ignored. Never raises.
+ """
+ images = 0
+ videos = 0
+ try:
+ for value in file_urls or []:
+ if images > 0 and videos > 0:
+ break
+ clean = self._clean_path(value)
+ if not clean:
+ continue
+ path = Path(clean)
+ try:
+ if path.is_dir():
+ for item in path.rglob("*"):
+ if images > 0 and videos > 0:
+ break
+ try:
+ if not item.is_file():
+ continue
+ except OSError:
+ continue
+ kind = self._classify_media_suffix(item.suffix)
+ if kind == "image":
+ images += 1
+ elif kind == "video":
+ videos += 1
+ elif path.is_file():
+ kind = self._classify_media_suffix(path.suffix)
+ if kind == "image":
+ images += 1
+ elif kind == "video":
+ videos += 1
+ except (OSError, PermissionError):
+ continue
+ except Exception:
+ pass
+ return images, videos
+
+ @staticmethod
+ def _supported_file(path: Path, accepts_images: bool) -> bool:
+ if not path.is_file():
+ return False
+ suffix = path.suffix.lower()
+ if accepts_images:
+ return suffix in IMAGE_SUFFIXES
+ return suffix in VIDEO_SUFFIXES
+
+ def _expand_inputs(self, file_urls: list[str], accepts_images: bool, controller=None, progress=None) -> list[str]:
+ collected: list[str] = []
+ roots = list(file_urls or [])
+ total_roots = max(1, len(roots))
+ for root_index, value in enumerate(roots):
+ if controller is not None and controller.cancel.is_set():
+ return []
+ clean = self._clean_path(value)
+ if not clean:
+ continue
+ path = Path(clean)
+ if path.is_dir():
+ try:
+ candidates = []
+ for item in path.rglob("*"):
+ if controller is not None and controller.cancel.is_set():
+ return []
+ if self._supported_file(item, accepts_images):
+ candidates.append(item)
+ candidates.sort(key=lambda x: str(x).casefold())
+ collected.extend(str(item.resolve()) for item in candidates)
+ except (OSError, PermissionError):
+ continue
+ elif self._supported_file(path, accepts_images):
+ collected.append(str(path.resolve()))
+ if progress is not None:
+ progress((root_index + 1) / total_roots, "Scanning inputs…")
+
+ seen: set[str] = set()
+ unique: list[str] = []
+ for item in collected:
+ key = os.path.normcase(os.path.abspath(item))
+ if key not in seen:
+ seen.add(key)
+ unique.append(item)
+ return unique
+
+ @Slot(list)
+ def addFiles(self, file_urls: list[str]) -> None:
+ if not file_urls:
+ return
+ if not self.canModifyQueue:
+ self._status_message = "Queue changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ self._paste_select_single = False
+ return
+ # Consume the Ctrl+V auto-select request (paste call sites only).
+ # When the scan below adds exactly one new file, it gets selected
+ # so its preview loads immediately.
+ select_pasted_single = self._paste_select_single
+ self._paste_select_single = False
+ # Auto-switch Image/Video mode from the dropped/picked content.
+ # Manual segmented buttons remain untouched and still work as override.
+ # Mixed image+video uploads are rejected: only one type per upload.
+ auto_switched: str | None = None
+ if self._active_tab in {"neural-rendering", "upscale"}:
+ image_count, video_count = self._detect_batch_kind(list(file_urls))
+ if image_count > 0 and video_count > 0:
+ self._status_message = "Mixed images and videos are not allowed — please add only one type at a time."
+ self.statusMessageChanged.emit()
+ self._log(self._status_message)
+ return
+ if image_count > 0 or video_count > 0:
+ target = "Image" if image_count > 0 else "Video"
+ if self._active_tab == "upscale":
+ if self._upscale_mode != target:
+ self.upscaleMode = target
+ if self._upscale_mode == target:
+ auto_switched = target
+ self._log(f"Detected {'image' if target == 'Image' else 'video'} input — switched to {target} mode.")
+ else:
+ if self._nr_mode != target:
+ self.nrMode = target
+ if self._nr_mode == target:
+ auto_switched = target
+ self._log(f"Detected {'image' if target == 'Image' else 'video'} input — switched to {target} mode.")
+ context_key = self._context_key()
+ queue = self._queue_for_context(context_key)
+ accepts_images = context_key in {"nr-image", "upscale-image"}
+ operation_id = self._set_operation(SCANNING_INPUTS, "Scanning selected inputs…")
+
+ worker = JobWorker(self._expand_inputs, list(file_urls), accepts_images)
+ self._scan_worker = worker
+
+ def on_progress(fraction: float, message: str) -> None:
+ if operation_id != self._operation_id:
+ return
+ self._overall_progress = fraction
+ self._status_message = message
+ self.overallProgressChanged.emit()
+ self.statusMessageChanged.emit()
+
+ def done(valid_paths: list[str]) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._scan_worker = None
+ before = queue.count
+ queue.add_items(valid_paths)
+ added = queue.count - before
+ kind = "images" if accepts_images else "videos"
+ message = f"Added {added} supported file(s)." if added else f"No supported {kind} were found."
+ if auto_switched and added:
+ message = f"Switched to {auto_switched} mode. {message}"
+ self._finish_operation(operation_id, message)
+ if self._context_key() == context_key:
+ if added == 1 and select_pasted_single:
+ # Single Ctrl+V paste: select the newly added item
+ # (appended at the end) so its preview loads at once.
+ self.selectQueueItem(queue.count - 1)
+ elif added == 0 and select_pasted_single and len(valid_paths) == 1:
+ # Re-pasted duplicate: select the existing row instead.
+ try:
+ needle = os.path.normcase(os.path.abspath(valid_paths[0]))
+ except Exception:
+ needle = ""
+ if needle:
+ for row, existing in enumerate(queue.get_paths()):
+ try:
+ if os.path.normcase(os.path.abspath(existing)) == needle:
+ self.selectQueueItem(row)
+ break
+ except Exception:
+ continue
+ elif added:
+ row = queue.selectedIndex if queue.selectedIndex >= 0 else 0
+ self.selectQueueItem(row)
+ self._log(message)
+
+ def failed(message: str) -> None:
+ self._scan_worker = None
+ self._finish_operation(operation_id, f"Input scan failed: {message}")
+ self._log(f"Input scan failed: {message}")
+
+ worker.signals.progress.connect(on_progress)
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(lambda: self._finish_operation(operation_id, "Input scan cancelled."))
+ self._thread_pool.start(worker)
+
+ @Slot(int)
+ def _sweep_temp_caches(self) -> None:
+ """Hourly best-effort sweep of stale temp caches. Never raises."""
+ try:
+ cleanup_old_caches()
+ except Exception:
+ pass
+
+ @staticmethod
+ def _touch_if_staged(path_str: str) -> None:
+ """Refresh mtime of staged paste sources so the hourly temp sweep
+ never deletes a file still referenced by a live queue. Only touches
+ files under APP_TEMP; user files elsewhere are never modified."""
+ try:
+ if not path_str:
+ return
+ path = Path(path_str)
+ if not path.is_file():
+ return
+ try:
+ staged = path.resolve()
+ root = APP_TEMP.resolve()
+ except OSError:
+ return
+ if root in staged.parents:
+ os.utime(staged, None)
+ except Exception:
+ pass
+
+ def selectQueueItem(self, row: int) -> None:
+ if self._operation_state != IDLE:
+ self._status_message = "Selection changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ return
+ queue = self._active_queue()
+ paths = queue.get_paths()
+ if not (0 <= row < len(paths)):
+ return
+ queue.select(row)
+ self._touch_if_staged(paths[row])
+ self._load_input_preview_async(paths[row], row, self._context_key())
+
+ @Slot(int)
+ def removeQueueItem(self, row: int) -> None:
+ if not self.canModifyQueue:
+ self._status_message = "Queue changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ return
+ queue = self._active_queue()
+ key = self._context_key()
+ queue.remove_item(row)
+ selected = queue.selected_path()
+ if selected:
+ self._load_input_preview_async(selected, queue.selectedIndex, key)
+ else:
+ self._clear_preview_state(key)
+
+ @Slot()
+ def clearActiveQueue(self) -> None:
+ if not self.canModifyQueue:
+ self._status_message = "Queue changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ return
+ key = self._context_key()
+ self._active_queue().clear()
+ self._clear_preview_state(key)
+
+ @Slot()
+ def clearSelectedPreviewItem(self) -> None:
+ """Remove the currently selected item (preview right-click menu).
+
+ Delegates to removeQueueItem so selection advance / preview reload /
+ empty-state clearing behave exactly like the queue's own remove
+ button. Acts on the active tab/mode queue only.
+ """
+ if not self.canModifyQueue:
+ self._status_message = "Queue changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ return
+ queue = self._active_queue()
+ row = queue.selectedIndex
+ if not (0 <= row < queue.count):
+ self._status_message = "No file is selected to clear."
+ self.statusMessageChanged.emit()
+ return
+ self.removeQueueItem(row)
+
+ @Slot()
+ def showSelectedInExplorer(self) -> None:
+ """Reveal the currently selected input file in Explorer (selected).
+
+ Highlights the file with ``explorer /select,`` on Windows instead
+ of merely opening the containing folder like openFolder does.
+ Falls back to opening the parent folder when highlighting is
+ unavailable. Never raises.
+ """
+ selected = ""
+ try:
+ selected = self._active_queue().selected_path() or ""
+ except Exception:
+ selected = ""
+ if not selected:
+ try:
+ selected = self._context().selected_path or ""
+ except Exception:
+ selected = ""
+ if not selected:
+ self._status_message = "No file is selected to show in Explorer."
+ self.statusMessageChanged.emit()
+ return
+ path = Path(selected)
+ if not path.is_file():
+ self._status_message = f"File no longer exists: {path.name}"
+ self.statusMessageChanged.emit()
+ return
+ try:
+ if os.name == "nt":
+ subprocess.Popen(
+ ["explorer", "/select,", str(path)],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ stdin=subprocess.DEVNULL,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ elif sys.platform == "darwin":
+ subprocess.Popen(
+ ["open", "-R", str(path)],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ stdin=subprocess.DEVNULL,
+ )
+ else:
+ from PySide6.QtGui import QDesktopServices
+ from PySide6.QtCore import QUrl as _QUrl
+
+ if not QDesktopServices.openUrl(_QUrl.fromLocalFile(str(path.parent))):
+ raise OSError("Could not open file manager")
+ except Exception as exc:
+ try:
+ parent = path.parent
+ if parent.is_dir():
+ if os.name == "nt":
+ os.startfile(parent)
+ else:
+ from PySide6.QtGui import QDesktopServices
+ from PySide6.QtCore import QUrl as _QUrl
+
+ QDesktopServices.openUrl(_QUrl.fromLocalFile(str(parent)))
+ self._status_message = f"Opened containing folder for {path.name}."
+ self.statusMessageChanged.emit()
+ return
+ except Exception:
+ pass
+ self._status_message = f"Could not show in Explorer: {exc}"
+ self.statusMessageChanged.emit()
+
+ @Slot()
+ def clearCompletedQueueItems(self) -> None:
+ if not self.canModifyQueue:
+ return
+ self._active_queue().clear_completed()
+
+ @Slot()
+ def retryFailedQueueItems(self) -> None:
+ if not self.canModifyQueue:
+ return
+ self._active_queue().retry_failed()
+
+ def _clear_preview_state(self, key: str | None = None) -> None:
+ key = key or self._context_key()
+ self._contexts[key] = PreviewState(generation=self._preview_generation + 1)
+ self._preview_generation += 1
+ self._image_provider.clear(f"input-{key}")
+ self._image_provider.clear(f"output-{key}")
+ self._image_provider.clear(f"poster-{key}")
+ if key == self._context_key():
+ self._emit_context()
+
+ @staticmethod
+ def _image_dimensions(preview: Any) -> tuple[int, int]:
+ width = getattr(preview, "width", 0)
+ height = getattr(preview, "height", 0)
+ if callable(width):
+ width = width()
+ if callable(height):
+ height = height()
+ if (not width or not height) and hasattr(preview, "shape"):
+ shape = getattr(preview, "shape", ())
+ if len(shape) >= 2:
+ height, width = int(shape[0]), int(shape[1])
+ try:
+ return int(width or 0), int(height or 0)
+ except (TypeError, ValueError):
+ return 0, 0
+
+ def _load_input_preview_async(self, path_str: str, row: int, context_key: str) -> None:
+ path = Path(path_str)
+ if not path.is_file():
+ return
+ queue = self._queue_for_context(context_key)
+ context = self._contexts[context_key]
+ context.selected_path = str(path)
+ context.selected_row = row
+ context.output_url = ""
+ context.output_is_video = False
+ context.output_info = ""
+ context.output_width = 0
+ context.output_height = 0
+ context.preview_source_seconds = 0.0
+ context.preview_source_frame = 0
+ context.last_playhead_seconds = 0.0
+ context.rendered_ranges = []
+ context.poster_url = ""
+ self._preview_generation += 1
+ generation = self._preview_generation
+ context.generation = generation
+ self._image_provider.clear(f"poster-{context_key}")
+ if context_key == self._context_key():
+ self._emit_context()
+
+ if self._metadata_worker is not None:
+ try:
+ self._metadata_worker.controller.stop()
+ except Exception:
+ pass
+
+ operation_id = self._set_operation(LOADING_METADATA, "Loading media…")
+ full_size = self._settings.full_size_image_previews
+ accepts_images = context_key in {"nr-image", "upscale-image"}
+
+ def task(controller=None, progress=None) -> dict[str, Any]:
+ suffix = path.suffix.lower()
+ is_image = suffix in IMAGE_SUFFIXES
+ if accepts_images and is_image:
+ if progress:
+ progress(0.15, "Decoding image preview…")
+ max_size = None if full_size else (1920, 1080)
+ preview = decode_image_preview(str(path), max_size)
+ width, height = self._image_dimensions(preview)
+ return {"kind": "image", "preview": preview, "width": width, "height": height}
+ if progress:
+ progress(0.15, "Probing video metadata…")
+ meta = probe_video(str(path), count_mode="metadata")
+ width = int(meta.get("display_width") or meta.get("width") or 0)
+ height = int(meta.get("display_height") or meta.get("height") or 0)
+ rotation = int(meta.get("rotation") or 0)
+ if rotation in {90, 270} and not meta.get("display_width"):
+ width, height = height, width
+ # ffmpeg poster guarantees a visible frame even if QtMultimedia
+ # fails to load the file (black-screen fallback in QML).
+ poster_jpeg: bytes | None = None
+ if progress:
+ progress(0.55, "Extracting poster frame…")
+ try:
+ from ..core.ffmpeg.preview import grab_video_poster_jpeg
+ poster_jpeg = grab_video_poster_jpeg(str(path), seconds=0.0, max_width=960)
+ except Exception as exc:
+ self._log(f"Poster extraction warning for {path.name}: {exc}")
+ return {
+ "kind": "video",
+ "width": width,
+ "height": height,
+ "fps": float(meta.get("fps") or 0.0),
+ "duration": float(meta.get("duration") or 0.0),
+ "meta": meta,
+ "poster_jpeg": poster_jpeg,
+ }
+
+ worker = JobWorker(task)
+ self._metadata_worker = worker
+
+ def progress(fraction: float, message: str) -> None:
+ if generation != self._contexts[context_key].generation:
+ return
+ self._status_message = message
+ self.statusMessageChanged.emit()
+
+ def done(result: dict[str, Any]) -> None:
+ if generation != self._contexts[context_key].generation or self._shutting_down:
+ return
+ self._metadata_worker = None
+ ctx = self._contexts[context_key]
+ width = int(result.get("width") or 0)
+ height = int(result.get("height") or 0)
+ ctx.source_width = width
+ ctx.source_height = height
+ ctx.source_aspect_ratio = (width / height) if width and height else None
+ ctx.source_fps = float(result.get("fps") or 0.0)
+ ctx.duration_seconds = float(result.get("duration") or 0.0)
+ dimensions = f"{width}×{height}" if width and height else ""
+ if result.get("kind") == "image":
+ digest = hashlib.sha1(str(path.resolve()).encode("utf-8", "surrogatepass")).hexdigest()[:16]
+ image_id = f"thumb-{context_key}-{digest}"
+ self._image_provider.set_image(image_id, result.get("preview"))
+ ctx.input_url = f"image://preview/{image_id}?g={generation}"
+ ctx.input_is_video = False
+ ctx.input_info = f"{path.name} | {dimensions}" if dimensions else path.name
+ queue.update_metadata(row, input_dimensions=dimensions, thumbnail_url=ctx.input_url)
+ else:
+ ctx.input_url = QUrl.fromLocalFile(str(path)).toString()
+ ctx.input_is_video = True
+ fps = float(result.get("fps") or 0.0)
+ dur = float(result.get("duration") or 0.0)
+ ctx.input_info = f"{path.name} | {dimensions}" if dimensions else path.name
+ if fps:
+ ctx.input_info += f" | {fps:.3f} FPS".replace(".000", "")
+ if dur:
+ ctx.input_info += f" | {dur:.1f}s"
+ queue.update_metadata(row, input_dimensions=dimensions)
+ poster_jpeg = result.get("poster_jpeg")
+ if poster_jpeg:
+ try:
+ from PIL import Image as _PILImage
+ import io as _io
+ pil = _PILImage.open(_io.BytesIO(bytes(poster_jpeg)))
+ poster_id = f"poster-{context_key}"
+ self._image_provider.set_image(poster_id, pil)
+ ctx.poster_url = f"image://preview/{poster_id}?g={generation}"
+ except Exception as exc:
+ self._log(f"Poster decode warning for {path.name}: {exc}")
+ if context_key == self._context_key():
+ self._emit_context()
+ self.settingsUpdated.emit()
+ if self._finish_operation(operation_id, "Ready."):
+ self._schedule_auto_preview(140)
+
+ def failed(message: str) -> None:
+ if generation != self._contexts[context_key].generation:
+ return
+ self._metadata_worker = None
+ ctx = self._contexts[context_key]
+ ctx.input_url = QUrl.fromLocalFile(str(path)).toString()
+ ctx.input_is_video = context_key not in {"nr-image", "upscale-image"}
+ ctx.input_info = path.name
+ if context_key == self._context_key():
+ self._emit_context()
+ self._finish_operation(operation_id, f"Metadata unavailable for {path.name}.")
+ self._log(f"Media metadata/preview failed for {path.name}: {message}")
+
+ worker.signals.progress.connect(progress)
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(lambda: self._finish_operation(operation_id, "Media loading cancelled."))
+ self._thread_pool.start(worker)
+
+ # =========================================================================
+ # Batch Processing & Worker Dispatch
+ # =========================================================================
+ @Slot()
+ def startActiveBatch(self) -> None:
+ if self._operation_state != IDLE or self._runtime_state != "Ready" or self._is_live_running:
+ self._status_message = "Another operation is active; stop it before starting a batch."
+ self.statusMessageChanged.emit()
+ return
+ queue = self._active_queue()
+ paths = list(queue.get_paths())
+ if not paths:
+ self._status_message = "No files in queue to process."
+ self.statusMessageChanged.emit()
+ return
+ if not self._active_render_configuration_valid():
+ self._status_message = f"Cannot render: {self.renderValidationMessage}"
+ self.statusMessageChanged.emit()
+ return
+
+ self._flush_settings()
+ queue.reset_all_states()
+ self._overall_progress = 0.0
+ self.overallProgressChanged.emit()
+ context_key = self._context_key()
+ settings = self._settings
+ operation_id = self._set_operation(BATCH_PREPARING, "Preparing batch processing…")
+
+ try:
+ if context_key == "nr-image":
+ worker = self._nr_image_batch_worker(paths, settings)
+ elif context_key == "nr-video":
+ worker = self._nr_video_batch_worker(paths, settings)
+ elif context_key == "upscale-image":
+ worker = self._upscale_image_batch_worker(paths, settings)
+ elif context_key == "upscale-video":
+ worker = self._upscale_video_batch_worker(paths, settings)
+ elif context_key == "fi-video":
+ worker = self._fi_batch_worker(paths, settings)
+ else:
+ raise RuntimeError("This workspace does not support batch rendering.")
+ except Exception as exc:
+ self._finish_operation(operation_id, f"Cannot start batch: {exc}")
+ return
+ self._setup_worker(worker, queue, operation_id, context_key)
+
+ def _setup_worker(self, worker: JobWorker, queue: BatchListModel, operation_id: int, context_key: str) -> None:
+ self._active_worker = worker
+ self._operation_state = BATCH_RUNNING
+ self.operationStateChanged.emit()
+
+ def on_progress(fraction: float, message: str) -> None:
+ if operation_id != self._operation_id:
+ return
+ self._overall_progress = max(0.0, min(1.0, float(fraction)))
+ self._status_message = message
+ self.overallProgressChanged.emit()
+ self.statusMessageChanged.emit()
+
+ def on_item_update(idx: int, state: str, prog: float, detail: str, out_p: str, elap: float) -> None:
+ if operation_id != self._operation_id or idx < 0:
+ return
+ queue.update_item_progress(idx, state, prog, detail, out_p, elap)
+ normalized = {"Complete": "Completed", "Processing": "Running"}.get(state, state)
+ if normalized == "Completed" and out_p and Path(out_p).is_file() and idx == queue.selectedIndex:
+ self._set_context_output_from_path(context_key, out_p, "Rendered output")
+
+ def on_finished(result: Any) -> None:
+ if operation_id != self._operation_id:
+ return
+ successes = list(getattr(result, "successes", []) or [])
+ failures = list(getattr(result, "failures", []) or [])
+ cancelled = bool(getattr(result, "cancelled", False))
+ self._overall_progress = 1.0 if not cancelled else self._overall_progress
+ self.overallProgressChanged.emit()
+ if cancelled:
+ message = f"Batch cancelled: {len(successes)} completed, {len(failures)} failed/skipped."
+ elif failures:
+ message = f"Completed with warnings: {len(successes)} completed, {len(failures)} failed."
+ first_error = getattr(failures[0], "error", "") if failures else ""
+ if first_error:
+ message += f" First error: {first_error}"
+ else:
+ message = f"Batch complete: {len(successes) or len(queue.get_paths())} completed."
+ self._finish_operation(operation_id, message)
+ self._log(message)
+
+ def on_failed(error_msg: str) -> None:
+ if operation_id != self._operation_id:
+ return
+ message = f"Batch failed: {error_msg}"
+ self._finish_operation(operation_id, message)
+ self._log(message)
+
+ def on_cancelled() -> None:
+ if operation_id != self._operation_id:
+ return
+ message = "Batch stopped by user."
+ self._finish_operation(operation_id, message)
+ self._log(message)
+
+ worker.signals.progress.connect(on_progress)
+ worker.signals.itemUpdated.connect(on_item_update)
+ worker.signals.finished.connect(on_finished)
+ worker.signals.failed.connect(on_failed)
+ worker.signals.cancelled.connect(on_cancelled)
+ self._thread_pool.start(worker)
+
+ def _set_context_output_from_path(self, context_key: str, output_path: str, label: str = "Output") -> None:
+ path = Path(output_path)
+ if not path.is_file():
+ return
+ context = self._contexts[context_key]
+ ext = path.suffix.lower()
+ image_exts = set(IMAGE_EXTENSIONS.values()) | {".jpg", ".jpeg", ".png", ".webp", ".avif", ".tif", ".tiff"}
+ if ext in image_exts:
+ image_id = f"output-{context_key}"
+ self._image_provider.set_image(image_id, str(path))
+ context.output_url = f"image://preview/{image_id}?g={context.generation}"
+ context.output_is_video = False
+ try:
+ from PIL import Image
+ with Image.open(path) as image:
+ context.output_width, context.output_height = image.size
+ except Exception:
+ context.output_width = context.output_height = 0
+ else:
+ context.output_url = QUrl.fromLocalFile(str(path)).toString()
+ context.output_is_video = True
+ context.output_info = f"{label} | {path.name}"
+ if context_key == self._context_key():
+ self._emit_context()
+
+ def _nr_image_batch_worker(self, paths: list[str], settings: UISettings) -> JobWorker:
+ opts = ImageConversionOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ nr_style=settings.nr_style,
+ nr_intensity=settings.nr_intensity,
+ nr_passes=settings.nr_passes,
+ local_tone_strength=settings.local_tone_strength,
+ local_structure_strength=settings.local_structure_strength,
+ skin_structure_strength=settings.skin_structure_strength,
+ automatic_mask=settings.automatic_mask,
+ nr_color_strength=settings.nr_color_strength,
+ tone_preservation=settings.tone_preservation,
+ face_skin_protection=settings.face_skin_protection,
+ grain_preservation=settings.grain_preservation,
+ mask_feather=settings.mask_feather,
+ nr_mask=settings.nr_mask,
+ upscaling_factor=settings.upscaling_factor,
+ output_format=settings.image_format,
+ quality=settings.image_quality,
+ rename_mode=settings.image_rename_mode,
+ custom_suffix=settings.image_custom_suffix,
+ )
+ return JobWorker(convert_images, paths, opts, output_dir=OUTPUTS, generate_previews=True, create_zip=False)
+
+ def _nr_video_batch_worker(self, paths: list[str], settings: UISettings) -> JobWorker:
+ opts = ConversionOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ video_gpu_uuid=settings.video_gpu_uuid,
+ nr_style=settings.nr_style,
+ nr_intensity=settings.nr_intensity,
+ nr_passes=settings.nr_passes,
+ local_tone_strength=settings.local_tone_strength,
+ local_structure_strength=settings.local_structure_strength,
+ skin_structure_strength=settings.skin_structure_strength,
+ automatic_mask=settings.automatic_mask,
+ nr_color_strength=settings.nr_color_strength,
+ tone_preservation=settings.tone_preservation,
+ face_skin_protection=settings.face_skin_protection,
+ grain_preservation=settings.grain_preservation,
+ shimmer_suppression=settings.shimmer_suppression,
+ mask_feather=settings.mask_feather,
+ nr_mask=settings.nr_mask,
+ upscaling_factor=settings.upscaling_factor,
+ codec=settings.codec,
+ container=container_for_codec(settings.codec),
+ quality=settings.quality,
+ preserve_hdr=coerce_hdr_mode(settings.codec, settings.hdr_mode),
+ rename_mode=settings.video_rename_mode,
+ custom_suffix=settings.video_custom_suffix,
+ )
+ return JobWorker(convert_videos, paths, opts, output_dir=OUTPUTS, create_archive=False)
+
+ def _upscale_image_batch_worker(self, paths: list[str], settings: UISettings) -> JobWorker:
+ opts = image_upscale_options_from_settings(settings)
+ opts.validate(for_render=True)
+ return JobWorker(upscale_images, paths, opts, output_dir=OUTPUTS, generate_previews=True)
+
+ def _upscale_video_batch_worker(self, paths: list[str], settings: UISettings) -> JobWorker:
+ opts = video_upscale_options_from_settings(settings)
+ opts.validate(for_render=True)
+ return JobWorker(upscale_videos, paths, opts, output_dir=OUTPUTS)
+
+ def _fi_batch_worker(self, paths: list[str], settings: UISettings) -> JobWorker:
+ opts = FrameInterpolationOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ video_gpu_uuid=settings.video_gpu_uuid,
+ target_fps=settings.frame_interpolation_target_fps,
+ engine=settings.frame_interpolation_engine,
+ codec=settings.frame_interpolation_codec,
+ container=container_for_codec(settings.frame_interpolation_codec),
+ quality=settings.frame_interpolation_quality,
+ hdr_mode=coerce_hdr_mode(settings.frame_interpolation_codec, settings.frame_interpolation_hdr_mode),
+ rename_mode=settings.frame_interpolation_rename_mode,
+ custom_suffix=settings.frame_interpolation_custom_suffix,
+ )
+ return JobWorker(interpolate_videos, paths, opts, output_dir=OUTPUTS)
+
+ @Slot()
+ def stopActiveBatch(self) -> None:
+ if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING} and self._active_worker is not None:
+ self._operation_state = PREVIEW_CANCELLING
+ self.operationStateChanged.emit()
+ self._active_worker.controller.stop()
+ self._status_message = "Cancelling preview…"
+ self.statusMessageChanged.emit()
+ return
+ if self._operation_state in {BATCH_PREPARING, BATCH_RUNNING} and self._active_worker is not None:
+ self._operation_state = BATCH_CANCELLING
+ self.operationStateChanged.emit()
+ self._active_worker.controller.stop()
+ self._status_message = "Cancelling current batch…"
+ self.statusMessageChanged.emit()
+ self._log("User requested batch cancellation.")
+ return
+ if self._operation_state in {LIVE_STARTING, LIVE_RUNNING}:
+ self._status_message = "Stopping Live session…"
+ self.statusMessageChanged.emit()
+ self.stopLive()
+ return
+
+ # =========================================================================
+ # Previews
+ # =========================================================================
+ @Slot()
+ def renderPreview(self) -> None:
+ # Realtime/auto and menu-driven preview renders the last parked
+ # timeline frame (frame 1 when nothing was ever parked).
+ ctx = self._context()
+ try:
+ parked_ms = max(0.0, float(ctx.last_playhead_seconds or 0.0) * 1000.0)
+ except (TypeError, ValueError):
+ parked_ms = 0.0
+ start_seconds, frame_index = self._quantize_playhead(parked_ms)
+ self._render_preview_impl(start_seconds, frame_index)
+
+ @Slot(float)
+ def notePlayheadMs(self, position_ms: float = 0.0) -> None:
+ """Remember a user-parked timeline position for realtime renders.
+
+ Called from QML transport gestures (seek/step/jump) and pauses only —
+ never from playback ticks — so the stored frame is always a deliberate
+ parking spot. Deliberately signal-free: safe at scrub-tick rates.
+ """
+ try:
+ pos = max(0.0, float(position_ms or 0.0))
+ except (TypeError, ValueError):
+ return
+ if not math.isfinite(pos):
+ return
+ self._context().last_playhead_seconds = pos / 1000.0
+
+ def _quantize_playhead(self, position_ms: float = 0.0) -> tuple[float, int]:
+ """Snap a raw playhead position to the nominal timeline frame.
+
+ Returns ``(start_seconds, frame_index)`` where frame N is
+ ``floor(position*fps)+1`` occupying ``[(N-1)/fps, N/fps)``. A raw
+ ``position/1000`` passed straight to ``ffmpeg -ss`` selects the first
+ frame with ``pts >= START``, i.e. N+1 whenever the playhead sits
+ strictly inside frame N — hence the quantization.
+ """
+ try:
+ raw_seconds = max(0.0, float(position_ms or 0.0) / 1000.0)
+ except (TypeError, ValueError):
+ raw_seconds = 0.0
+ ctx = self._context()
+ try:
+ fps = float(ctx.source_fps or 0.0)
+ except (TypeError, ValueError):
+ fps = 0.0
+ if not (fps and math.isfinite(fps) and fps > 0.01):
+ fps = 30.0
+ try:
+ duration = float(ctx.duration_seconds or 0.0)
+ except (TypeError, ValueError):
+ duration = 0.0
+ # Clamp to probed duration so a stale playhead past EOS falls back
+ # to the last decodable second instead of failing extraction.
+ if duration > 0:
+ raw_seconds = min(raw_seconds, max(0.0, duration - 0.05))
+ total_frames = max(0, int(round(duration * fps))) if duration > 0 else 0
+ frame_index = int(math.floor(raw_seconds * fps)) + 1
+ if total_frames > 0:
+ frame_index = max(1, min(total_frames, frame_index))
+ else:
+ frame_index = max(1, frame_index)
+ start_seconds = (frame_index - 1) / fps if fps > 0 else raw_seconds
+ if duration > 0:
+ start_seconds = min(start_seconds, max(0.0, duration - 0.05))
+ return start_seconds, frame_index
+
+ @Slot(float)
+ def renderPreviewAt(self, position_ms: float = 0.0) -> None:
+ """Explicit Preview: enhance exactly the timeline playhead frame."""
+ start_seconds, frame_index = self._quantize_playhead(position_ms)
+ self.notePlayheadMs(position_ms)
+ self._render_preview_impl(start_seconds, frame_index)
+
+ @Slot(float)
+ def schedulePreviewAt(self, position_ms: float = 0.0) -> None:
+ """Debounced scrub-realtime: refresh the preview at the playhead.
+
+ Called on every user timeline move in Output/2-Up; the actual render
+ starts only after scrubbing settles (~750 ms idle), so scrubbing never
+ melts the GPU. Only refreshes an existing video preview while Realtime
+ is enabled — never during batches, Live, or metadata loading. Frame
+ Interpolation is excluded (manual "Preview" only).
+ """
+ if (
+ self._shutting_down
+ or not self._auto_preview_enabled
+ or self._runtime_state != "Ready"
+ or self._is_live_running
+ ):
+ return
+ if self._context_key() not in {"nr-video", "upscale-video"}:
+ return
+ ctx = self._context()
+ if not ctx.has_output or not ctx.output_is_video:
+ return
+ try:
+ source = self._active_queue().selected_path()
+ except Exception:
+ source = ""
+ if not source:
+ return
+ if self._operation_state in {BATCH_PREPARING, BATCH_RUNNING, BATCH_CANCELLING,
+ LIVE_STARTING, LIVE_RUNNING, LIVE_STOPPING}:
+ return
+ try:
+ self._scrub_pending_pos = max(0.0, float(position_ms or 0.0))
+ except (TypeError, ValueError):
+ self._scrub_pending_pos = 0.0
+ if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING}:
+ # A render is in flight: invalidate it so only the latest settled
+ # position is ever processed, then debounce the replacement.
+ self._invalidate_preview_generation()
+ worker = self._active_worker
+ if worker is not None:
+ try:
+ worker.controller.stop()
+ except Exception:
+ pass
+ self._operation_state = PREVIEW_CANCELLING
+ self.operationStateChanged.emit()
+ self._scrub_preview_timer.start(750)
+
+ def _fire_scrub_preview(self) -> None:
+ """Launch the debounced scrub-refresh render, if still applicable."""
+ if (
+ self._shutting_down
+ or not self._auto_preview_enabled
+ or self._runtime_state != "Ready"
+ or self._is_live_running
+ or self._scrub_pending_pos is None
+ ):
+ self._scrub_pending_pos = None
+ return
+ if self._operation_state in {PREVIEW_PREPARING, PREVIEW_RUNNING, PREVIEW_CANCELLING,
+ LOADING_METADATA, SCANNING_INPUTS}:
+ # Still busy: retry shortly instead of dropping the scrub.
+ self._scrub_preview_timer.start(400)
+ return
+ if self._operation_state != IDLE:
+ self._scrub_pending_pos = None
+ return
+ if self._context_key() not in {"nr-video", "upscale-video"}:
+ self._scrub_pending_pos = None
+ return
+ ctx = self._context()
+ if not ctx.has_output or not ctx.output_is_video:
+ self._scrub_pending_pos = None
+ return
+ pos_ms, self._scrub_pending_pos = self._scrub_pending_pos, None
+ start_seconds, frame_index = self._quantize_playhead(pos_ms)
+ self._render_preview_impl(start_seconds, frame_index)
+
+ @Slot(float)
+ def refreshVideoPoster(self, position_ms: float = 0.0) -> None:
+ """Refresh the poster still (used when the native player stalls)."""
+ context_key = self._context_key()
+ context = self._contexts[context_key]
+ source = context.selected_path or self._active_queue().selected_path()
+ if not source or not Path(source).is_file():
+ return
+ try:
+ seconds = max(0.0, float(position_ms or 0.0) / 1000.0)
+ except (TypeError, ValueError):
+ seconds = 0.0
+ generation = context.generation
+
+ def task(controller=None, progress=None):
+ from ..core.ffmpeg.preview import grab_video_poster_jpeg
+ return grab_video_poster_jpeg(source, seconds=seconds, max_width=960)
+
+ def done(jpeg: bytes) -> None:
+ if generation != self._contexts[context_key].generation or self._shutting_down:
+ return
+ try:
+ from PIL import Image as _PILImage
+ import io as _io
+ pil = _PILImage.open(_io.BytesIO(bytes(jpeg)))
+ poster_id = f"poster-{context_key}"
+ self._image_provider.set_image(poster_id, pil)
+ self._contexts[context_key].poster_url = f"image://preview/{poster_id}?g={generation}"
+ if context_key == self._context_key():
+ self.previewPosterUrlChanged.emit()
+ except Exception as exc:
+ self._log(f"Poster refresh failed: {exc}")
+
+ def failed(message: str) -> None:
+ self._log(f"Poster refresh failed: {message}")
+
+ worker = JobWorker(task, inject_callbacks=False)
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ self._thread_pool.start(worker)
+
+ def _render_preview_impl(self, start_seconds: float = 0.0, frame_index: int = 1) -> None:
+ if not self.canPreview:
+ self._status_message = "Preview is unavailable while another operation is active."
+ self.statusMessageChanged.emit()
+ return
+ queue = self._active_queue()
+ source = queue.selected_path()
+ if not source:
+ self._status_message = "Add and select a file first to preview."
+ self.statusMessageChanged.emit()
+ return
+
+ context_key = self._context_key()
+ context = self._contexts[context_key]
+ self._preview_generation += 1
+ generation = self._preview_generation
+ context.generation = generation
+ # Previews always land in place: the viewer stays on whichever tab
+ # opened the render (Input, Output, or 2-Up) and the finished output
+ # swaps atomically into it. No tab is ever switched programmatically.
+ settings = self._settings
+ # Fingerprint of what this render is built from (selected source +
+ # settings snapshot). Stored on success so later tab/mode switches
+ # can skip the re-render while nothing changed.
+ preview_fingerprint = self._auto_preview_fingerprint(context_key)
+ is_video_context = context_key in {"nr-video", "upscale-video", "fi-video"}
+ try:
+ _fps = float(context.source_fps or 0.0)
+ except (TypeError, ValueError):
+ _fps = 0.0
+ if not (_fps and math.isfinite(_fps) and _fps > 0.01):
+ _fps = 30.0
+ try:
+ _dur = float(context.duration_seconds or 0.0)
+ except (TypeError, ValueError):
+ _dur = 0.0
+ _total = max(0, int(round(_dur * _fps))) if _dur > 0 else 0
+ try:
+ frame_index = max(1, int(frame_index or 1))
+ except (TypeError, ValueError):
+ frame_index = 1
+ if _total > 0:
+ frame_index = min(_total, frame_index)
+ if is_video_context and start_seconds > 0.05 and _total > 0:
+ stamp_label = f" f{frame_index}/{_total} @ {start_seconds:.2f}s"
+ elif is_video_context and start_seconds > 0.05:
+ stamp_label = f" @ {start_seconds:.2f}s"
+ else:
+ stamp_label = ""
+ operation_id = self._set_operation(PREVIEW_PREPARING, f"Rendering preview{stamp_label}…")
+ # Keep the last completed preview visible while the next realtime
+ # generation is rendering. The output is swapped atomically only
+ # after a successful result, eliminating the blank/flicker between
+ # slider edits. Selecting a different source still clears the output.
+
+ try:
+ if context_key == "nr-image":
+ opts = ImageConversionOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ nr_style=settings.nr_style,
+ nr_intensity=settings.nr_intensity,
+ nr_passes=settings.nr_passes,
+ local_tone_strength=settings.local_tone_strength,
+ local_structure_strength=settings.local_structure_strength,
+ skin_structure_strength=settings.skin_structure_strength,
+ automatic_mask=settings.automatic_mask,
+ nr_color_strength=settings.nr_color_strength,
+ tone_preservation=settings.tone_preservation,
+ face_skin_protection=settings.face_skin_protection,
+ grain_preservation=settings.grain_preservation,
+ mask_feather=settings.mask_feather,
+ nr_mask=settings.nr_mask,
+ upscaling_factor=settings.upscaling_factor,
+ output_format="PNG",
+ quality=100,
+ )
+ def task(controller=None, progress=None):
+ return render_image_preview(
+ source, opts, controller=controller, progress=progress,
+ full_size_preview=settings.full_size_image_previews,
+ )
+ result_kind = "image"
+ elif context_key == "upscale-image":
+ opts = image_upscale_options_from_settings(settings)
+ opts.validate(for_render=True)
+ def task(controller=None, progress=None):
+ return preview_upscale_image(
+ source, opts, controller=controller, progress=progress,
+ full_size_preview=settings.full_size_image_previews,
+ )
+ result_kind = "image"
+ elif context_key == "nr-video":
+ opts = ConversionOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ video_gpu_uuid=settings.video_gpu_uuid,
+ nr_style=settings.nr_style,
+ nr_intensity=settings.nr_intensity,
+ nr_passes=settings.nr_passes,
+ local_tone_strength=settings.local_tone_strength,
+ local_structure_strength=settings.local_structure_strength,
+ skin_structure_strength=settings.skin_structure_strength,
+ automatic_mask=settings.automatic_mask,
+ nr_color_strength=settings.nr_color_strength,
+ tone_preservation=settings.tone_preservation,
+ face_skin_protection=settings.face_skin_protection,
+ grain_preservation=settings.grain_preservation,
+ shimmer_suppression=settings.shimmer_suppression,
+ mask_feather=settings.mask_feather,
+ nr_mask=settings.nr_mask,
+ upscaling_factor=settings.upscaling_factor,
+ codec=settings.codec,
+ container=container_for_codec(settings.codec),
+ quality=settings.quality,
+ preserve_hdr=settings.hdr_mode,
+ )
+ def task(controller=None, progress=None):
+ return process_video_preview(
+ source, opts, preview_frames=1,
+ preview_encoding=settings.preview_encoding,
+ progress=progress, output_dir=self._preview_cache,
+ controller=controller, ephemeral_preview=False,
+ start_seconds=start_seconds, frame_index=frame_index,
+ )
+ result_kind = "video"
+ elif context_key == "upscale-video":
+ opts = video_upscale_options_from_settings(settings)
+ opts.validate(for_render=True)
+ def task(controller=None, progress=None):
+ return preview_upscale_native(
+ source, opts, one_frame=True, progress=progress,
+ controller=controller, output_dir=self._preview_cache,
+ preview_encoding=settings.preview_encoding,
+ start_seconds=start_seconds, frame_index=frame_index,
+ )
+ result_kind = "video"
+ elif context_key == "fi-video":
+ opts = FrameInterpolationOptions(
+ ai_gpu_uuid=settings.ai_gpu_uuid,
+ video_gpu_uuid=settings.video_gpu_uuid,
+ target_fps=settings.frame_interpolation_target_fps,
+ engine=settings.frame_interpolation_engine,
+ codec=settings.frame_interpolation_codec,
+ container=container_for_codec(settings.frame_interpolation_codec),
+ quality=settings.frame_interpolation_quality,
+ hdr_mode=settings.frame_interpolation_hdr_mode,
+ )
+ def task(controller=None, progress=None):
+ return preview_frame_interpolation_native(
+ source, opts, preview_encoding=settings.preview_encoding,
+ progress=progress, output_dir=self._preview_cache,
+ controller=controller, start_seconds=start_seconds,
+ frame_index=frame_index,
+ preview_seconds=self._fi_preview_length_seconds(),
+ )
+ result_kind = "video"
+ else:
+ raise RuntimeError("Preview is unavailable for this workspace.")
+ except Exception as exc:
+ self._finish_operation(operation_id, f"Preview configuration error: {exc}")
+ return
+
+ worker = JobWorker(task)
+ self._active_worker = worker
+ self._operation_state = PREVIEW_RUNNING
+ self.operationStateChanged.emit()
+
+ def on_progress(fraction: float, message: str) -> None:
+ if operation_id != self._operation_id or generation != self._contexts[context_key].generation:
+ return
+ self._overall_progress = fraction
+ self._status_message = message
+ self.overallProgressChanged.emit()
+ self.statusMessageChanged.emit()
+
+ def finished(result: Any) -> None:
+ if operation_id != self._operation_id:
+ return
+ if generation != self._contexts[context_key].generation:
+ self._finish_operation(operation_id, "Preview superseded by newer settings.")
+ if self._auto_preview_pending:
+ self._auto_preview_timer.start(80)
+ return
+ ctx = self._contexts[context_key]
+ media, status = result
+ rendered_ok = False
+ if result_kind == "image":
+ if media is not None:
+ image_id = f"output-{context_key}"
+ self._image_provider.set_image(image_id, media)
+ ctx.output_url = f"image://preview/{image_id}?g={generation}"
+ ctx.output_is_video = False
+ ctx.output_width, ctx.output_height = self._image_dimensions(media)
+ ctx.output_info = (
+ f"Enhanced preview | {ctx.output_width}×{ctx.output_height}"
+ if ctx.output_width and ctx.output_height else "Enhanced preview"
+ )
+ rendered_ok = True
+ else:
+ if media and Path(str(media)).is_file():
+ ctx.output_url = QUrl.fromLocalFile(str(media)).toString()
+ ctx.output_is_video = True
+ ctx.preview_source_seconds = max(0.0, float(start_seconds or 0.0))
+ try:
+ ctx.preview_source_frame = max(0, int(frame_index or 0))
+ except (TypeError, ValueError):
+ ctx.preview_source_frame = 0
+ if context_key == "fi-video":
+ # Successful preview render: paint its span green on
+ # the FI timeline (clamped to the source duration).
+ self._add_fi_rendered_range(context_key, start_seconds, str(media),
+ self._fi_preview_length_seconds())
+ if start_seconds > 0.05 and _total > 0:
+ ctx.output_info = f"Preview f{frame_index}/{_total} @ {start_seconds:.2f}s | {Path(str(media)).name}"
+ elif start_seconds > 0.05:
+ ctx.output_info = f"Preview @ {start_seconds:.2f}s | {Path(str(media)).name}"
+ else:
+ ctx.output_info = f"Preview | {Path(str(media)).name}"
+ rendered_ok = True
+ if rendered_ok and preview_fingerprint:
+ # Current output now matches this source + settings: later
+ # tab/mode switches skip the redundant GPU re-render.
+ ctx.last_auto_fingerprint = preview_fingerprint
+ if context_key == self._context_key():
+ self._emit_context()
+ self._overall_progress = 1.0
+ self.overallProgressChanged.emit()
+ # Status bar shows only the main status; the full render detail
+ # goes to the log drawer so no information is lost.
+ self._finish_operation(operation_id, f"Preview complete{stamp_label}.")
+ if status:
+ for line in str(status).splitlines():
+ line = line.strip()
+ if line:
+ self._log(line)
+
+ def failed(message: str) -> None:
+ if operation_id != self._operation_id:
+ return
+ text = f"Preview failed: {message}"
+ self._finish_operation(operation_id, text)
+ self._log(text)
+ if self._auto_preview_pending:
+ self._auto_preview_timer.start(120)
+
+ def cancelled() -> None:
+ if operation_id != self._operation_id:
+ return
+ self._finish_operation(operation_id, "Preview cancelled.")
+ if self._auto_preview_pending:
+ self._auto_preview_timer.start(80)
+
+ worker.signals.progress.connect(on_progress)
+ worker.signals.finished.connect(finished)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(cancelled)
+ self._thread_pool.start(worker)
+
+ # =========================================================================
+ # Live Workflow
+ # =========================================================================
+ @Slot(str, str, str, str, str, str, str, float)
+ def startLive(
+ self,
+ source_mode: str,
+ online_url: str,
+ local_video_path: str,
+ source_quality: str,
+ max_height: str,
+ segment_seconds: str,
+ target_fps: str,
+ buffer_seconds: float,
+ ) -> None:
+ if not self.canStartLive:
+ self._live_status_text = "Live is unavailable while another operation is active."
+ self.liveStatusTextChanged.emit()
+ return
+
+ if source_mode == "Local":
+ cleaned = self._clean_path(local_video_path)
+ if not cleaned or not Path(cleaned).is_file():
+ self._live_status_text = "Select a valid local video file."
+ self.liveStatusTextChanged.emit()
+ return
+ try:
+ if not _is_supported_media_file(Path(cleaned), "video"):
+ self._live_status_text = "Select a valid local video file (MP4/MKV/MOV/AVI/WebM...)."
+ self.liveStatusTextChanged.emit()
+ return
+ except Exception:
+ if Path(cleaned).suffix.lower() not in VIDEO_SUFFIXES:
+ self._live_status_text = "Select a valid local video file (MP4/MKV/MOV/AVI/WebM...)."
+ self.liveStatusTextChanged.emit()
+ return
+ selected_source = cleaned
+ else:
+ selected_source = online_url.strip()
+ if not selected_source:
+ self._live_status_text = "Enter a valid online URL (Twitch, YouTube, HLS, etc.)."
+ self.liveStatusTextChanged.emit()
+ return
+
+ settings = self._settings
+ # In-tab player: prepare the embed container now (GUI thread) so the
+ # session worker can hand its handle straight to MPV at launch time.
+ # ``wid == 0`` degrades to a detached player window, never a failure.
+ ipc_pipe = (
+ f"\\\\.\\pipe\\dlss5-live-{time.strftime('%Y%m%d-%H%M%S')}"
+ f"-{os.getpid()}-{int(time.time() * 1000) % 100000:d}"
+ )
+ wid = 0
+ try:
+ wid, _ = self._mpv_embed.prepare(ipc_pipe)
+ except Exception as exc:
+ self._log(f"Live embed warning: {exc}")
+ self._live_embed_wid = int(wid or 0)
+ self._live_player_started = False
+ try:
+ h = int(max_height) if max_height.isdigit() else 720
+ seg = int(segment_seconds) if segment_seconds.isdigit() else 2
+ if source_quality not in LIVE_SOURCE_QUALITY_CHOICES:
+ source_quality = "Auto"
+ if target_fps not in LIVE_FPS_CHOICES:
+ target_fps = "Auto"
+ opts = LiveOptions(
+ source=selected_source,
+ nr_style=settings.live_nr_style,
+ nr_intensity=settings.live_nr_intensity,
+ nr_passes=settings.live_nr_passes,
+ local_tone_strength=settings.live_local_tone_strength,
+ local_structure_strength=settings.live_local_structure_strength,
+ skin_structure_strength=settings.live_skin_structure_strength,
+ automatic_mask=settings.live_automatic_mask,
+ nr_color_strength=settings.live_nr_color_strength,
+ tone_preservation=settings.live_tone_preservation,
+ face_skin_protection=settings.live_face_skin_protection,
+ grain_preservation=settings.live_grain_preservation,
+ shimmer_suppression=settings.live_shimmer_suppression,
+ mask_feather=settings.live_mask_feather,
+ nr_mask=settings.nr_mask,
+ max_height=h if h in LIVE_MAX_HEIGHTS else 720,
+ upscaling_factor=settings.live_upscaling_factor,
+ segment_seconds=seg if str(seg) in LIVE_SEGMENT_CHOICES else 2,
+ target_fps=target_fps,
+ open_mpv=True,
+ mpv_wid=int(wid),
+ mpv_ipc_server=ipc_pipe,
+ buffer_seconds=max(2.0, min(30.0, float(buffer_seconds))),
+ source_quality=source_quality,
+ )
+ except Exception as exc:
+ self._live_status_text = f"Invalid Live configuration: {exc}"
+ self.liveStatusTextChanged.emit()
+ return
+
+ self._flush_settings()
+ self._is_live_starting = True
+ self._stop_live_after_start = False
+ self.isLiveStartingChanged.emit()
+ operation_id = self._set_operation(LIVE_STARTING, "Resolving source and starting Live pipeline…")
+ self._live_status_text = "Resolving source and starting Live pipeline…"
+ self.liveStatusTextChanged.emit()
+
+ worker = JobWorker(lambda: start_live_session(opts), inject_callbacks=False)
+ self._live_worker = worker
+
+ def done(info: Any) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._live_worker = None
+ self._is_live_starting = False
+ self._is_live_running = bool(getattr(info, "running", False) or is_live_running())
+ self.isLiveStartingChanged.emit()
+ self.isLiveRunningChanged.emit()
+ if self._stop_live_after_start:
+ self._stop_live_after_start = False
+ self.stopLive()
+ return
+ self._live_status_text = getattr(info, "status", "Live session started.")
+ self.liveStatusTextChanged.emit()
+ if self._is_live_running:
+ self._live_timer.start()
+ self._finish_operation(operation_id, "Live session running.")
+ else:
+ self._finish_operation(operation_id, self._live_status_text)
+ self._log(f"Live session started: {selected_source}")
+
+ def failed(message: str) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._live_worker = None
+ self._is_live_starting = False
+ self._is_live_running = False
+ self._stop_live_after_start = False
+ self._live_status_text = f"Live failed: {message}"
+ self.isLiveStartingChanged.emit()
+ self.isLiveRunningChanged.emit()
+ self.liveStatusTextChanged.emit()
+ try:
+ self._mpv_embed.set_session_active(False)
+ except Exception:
+ pass
+ self._finish_operation(operation_id, self._live_status_text)
+ self._log(self._live_status_text)
+
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(lambda: failed("Start cancelled."))
+ self._thread_pool.start(worker)
+
+ @Slot()
+ def stopLive(self) -> None:
+ if self._operation_state == LIVE_STARTING:
+ # Do not cancel the starter worker mid-construction: the backend may
+ # publish its LiveSession after a premature stop check, orphaning it.
+ # Instead, complete construction and stop immediately in ``done``.
+ self._stop_live_after_start = True
+ self._live_status_text = "Cancel requested; stopping as soon as Live finishes starting…"
+ self.liveStatusTextChanged.emit()
+ self._status_message = "Cancelling Live startup…"
+ self.statusMessageChanged.emit()
+ return
+ if not (self._is_live_running or is_live_running()):
+ return
+ if self._operation_state == LIVE_STOPPING:
+ return
+
+ self._live_timer.stop()
+ operation_id = self._set_operation(LIVE_STOPPING, "Stopping Live session…")
+ self._live_status_text = "Stopping Live session…"
+ self.liveStatusTextChanged.emit()
+ worker = JobWorker(stop_live_session, inject_callbacks=False)
+ self._live_worker = worker
+
+ def done(info: Any) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._live_worker = None
+ self._is_live_starting = False
+ self._is_live_running = False
+ self._live_effects_dirty = False
+ self._live_status_text = getattr(info, "status", "Stopped.")
+ self.isLiveStartingChanged.emit()
+ self.isLiveRunningChanged.emit()
+ self.liveStatusTextChanged.emit()
+ try:
+ self._mpv_embed.set_session_active(False)
+ except Exception:
+ pass
+ self._finish_operation(operation_id, "Live session stopped.")
+ self._log("Live session stopped.")
+
+ def failed(message: str) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._live_worker = None
+ self._is_live_starting = False
+ self._is_live_running = bool(is_live_running())
+ self._live_status_text = f"Stop error: {message}"
+ self.isLiveStartingChanged.emit()
+ self.isLiveRunningChanged.emit()
+ self.liveStatusTextChanged.emit()
+ if not self._is_live_running:
+ try:
+ self._mpv_embed.set_session_active(False)
+ except Exception:
+ pass
+ self._finish_operation(operation_id, self._live_status_text)
+ self._log(self._live_status_text)
+
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(lambda: failed("Stop cancelled."))
+ self._thread_pool.start(worker)
+
+ def _poll_live_status(self) -> None:
+ try:
+ info = live_status()
+ self._live_source_fps = float(info.source_fps or 0.0)
+ self._live_target_fps = float(info.target_fps or 0.0)
+ self._live_effective_fps = float(info.effective_fps or 0.0)
+ self._live_guide_ms = float(info.guide_ms or 0.0)
+ self._live_dlss_ms = float(info.dlss_ms or 0.0)
+ self._live_encode_ms = float(info.encode_ms or 0.0)
+ self._live_dropped_frames = int(info.player_dropped_frames or info.dropped_frames or 0)
+ self._live_rebuffer_events = int(info.rebuffer_events or 0)
+ self._live_av_sync_ms = float(info.av_sync_ms or 0.0)
+ self._live_output_size = str(info.output_size or "")
+ self._live_encoder = str(info.encoder or "")
+ self.liveTelemetryChanged.emit()
+ was_running = self._is_live_running
+ self._is_live_running = bool(info.running or is_live_running())
+ if self._is_live_running != was_running:
+ self.isLiveRunningChanged.emit()
+ # Reveal the in-tab player container only once the player reports
+ # its first rendered frame; before that the unpainted native
+ # child window would show the desktop through the app. Hide it
+ # again the moment the session is gone (mpv is owned by it).
+ # A zero handle means detached-window fallback: never reveal.
+ self._live_player_started = bool(getattr(info, "player_started", False))
+ try:
+ if (self._is_live_running and self._live_player_started
+ and self._live_embed_wid
+ and not self._mpv_embed.isActive):
+ self._mpv_embed.set_session_active(True)
+ elif not self._is_live_running and self._mpv_embed.isActive:
+ self._mpv_embed.set_session_active(False)
+ except Exception:
+ pass
+ parts = [info.status]
+ if info.playlist_url:
+ parts.append(f"Playlist: {info.playlist_url}")
+ if info.mpv_running:
+ parts.append(
+ f"MPV: {info.player_dropped_frames} dropped | "
+ f"{info.rebuffer_events} rebuffer events | A/V sync {info.av_sync_ms:+.1f} ms"
+ )
+ if info.output_size:
+ parts.append(
+ f"Received {info.source_size} -> Input {info.input_size} -> "
+ f"Output {info.output_size} | {info.encoder}"
+ )
+ if info.source_quality_note:
+ parts.append(info.source_quality_note)
+ parts.append(f"DLSS effects: {info.effects_status}")
+ if info.source_fps:
+ parts.append(
+ f"Source: {info.source_fps:.1f} fps | Guide: {info.guide_ms:.1f} ms | "
+ f"DLSS: {info.dlss_ms:.1f} ms | Encode: {info.encode_ms:.1f} ms"
+ )
+ self._live_status_text = "\n".join(parts)
+ self.liveStatusTextChanged.emit()
+ if not self._is_live_running:
+ self._live_timer.stop()
+ if self._operation_state == LIVE_RUNNING:
+ self._operation_state = IDLE
+ self.operationStateChanged.emit()
+ self.isProcessingChanged.emit()
+ except Exception as exc:
+ self._log(f"Live telemetry warning: {exc}")
+
+ @Slot()
+ def shutdown(self) -> None:
+ """Flush persistent state and stop owned work/processes during application exit."""
+ if self._shutting_down:
+ return
+ self._shutting_down = True
+ self._operation_state = SHUTTING_DOWN
+ self.operationStateChanged.emit()
+ self.isProcessingChanged.emit()
+ self._save_timer.stop()
+ self._auto_preview_timer.stop()
+ self._auto_preview_pending = False
+ self._scrub_preview_timer.stop()
+ self._scrub_pending_pos = None
+ try:
+ save_settings(CONFIG_PATH, self._settings)
+ except Exception as exc:
+ self._log(f"Failed to save settings during shutdown: {exc}")
+ for worker in (self._active_worker, self._scan_worker, self._metadata_worker, self._live_worker):
+ if worker is not None:
+ try:
+ worker.controller.stop()
+ except Exception:
+ pass
+ self._live_timer.stop()
+ try:
+ self._thread_pool.waitForDone(5000)
+ except Exception:
+ pass
+ # The start worker may have published a LiveSession while shutdown was
+ # waiting for workers. Stop after synchronization so no session escapes.
+ if is_live_running():
+ try:
+ stop_live_session()
+ except Exception as exc:
+ self._log(f"Live shutdown warning: {exc}")
+ try:
+ self._mpv_embed.shutdown()
+ except Exception:
+ pass
+ try:
+ app_log.remove_listener(self._backend_log_listener)
+ except Exception:
+ pass
+ try:
+ if self._preview_cache != OUTPUTS:
+ shutil.rmtree(self._preview_cache, ignore_errors=True)
+ except OSError:
+ pass
+
+ # =========================================================================
+ # Helpers
+ # =========================================================================
+ def _clean_path(self, path_or_url: str) -> str:
+ if not path_or_url:
+ return ""
+ p = path_or_url.strip()
+ if p.startswith("file:///"):
+ p = QUrl(p).toLocalFile()
+ elif p.startswith("file:"):
+ p = QUrl(p).toLocalFile()
+ return str(Path(p).resolve()) if p else ""
+
+ @Slot(str)
+ def openFolder(self, path_str: str) -> None:
+ clean = self._clean_path(path_str) if path_str else str(OUTPUTS.resolve())
+ p = Path(clean)
+ folder = p if p.is_dir() else p.parent
+ if folder.exists():
+ os.startfile(folder)
+
+ @Slot(str)
+ def copyToClipboard(self, text: str) -> None:
+ clipboard = QGuiApplication.clipboard()
+ if clipboard is not None:
+ clipboard.setText(text)
+ self._status_message = "Copied to clipboard."
+ self.statusMessageChanged.emit()
+
+ @staticmethod
+ def _coerce_clipboard_qimage(value: Any) -> QImage | None:
+ """Normalize clipboard pixel payloads to a QImage (or None).
+
+ Browsers/toolkits may expose the bitmap as QImage or QPixmap
+ depending on platform; screenshots arrive as QImage. Never raises.
+ """
+ try:
+ if value is None:
+ return None
+ if isinstance(value, QImage):
+ return value
+ if isinstance(value, QPixmap):
+ try:
+ return value.toImage()
+ except Exception:
+ return None
+ to_image = getattr(value, "toImage", None)
+ if callable(to_image):
+ try:
+ converted = to_image()
+ except Exception:
+ return None
+ return converted if isinstance(converted, QImage) else None
+ except Exception:
+ return None
+ return None
+
+ def _clipboard_pixels(self, mime: Any, clipboard: Any) -> QImage | None:
+ """Return clipboard bitmap pixels, preferring mime imageData. Never raises.
+
+ Falls back from Qt-coerced image objects to raw encoded bytes
+ (``image/png`` / ``image/bmp`` / ``image/jpeg``), which Chromium
+ exposes even when ``imageData()`` comes back null for its DIB.
+ """
+ try:
+ if mime is not None and mime.hasImage():
+ image = self._coerce_clipboard_qimage(mime.imageData())
+ if image is not None and not image.isNull():
+ return image
+ except Exception:
+ pass
+ try:
+ if mime is not None:
+ for fmt in ("image/png", "image/bmp", "image/jpeg", "image/jpg"):
+ try:
+ raw = bytes(mime.data(fmt) or b"")
+ except Exception:
+ continue
+ if not raw:
+ continue
+ try:
+ decoded = QImage.fromData(raw)
+ except Exception:
+ continue
+ if decoded is not None and not decoded.isNull():
+ return decoded
+ except Exception:
+ pass
+ try:
+ if clipboard is not None:
+ image = self._coerce_clipboard_qimage(clipboard.image())
+ if image is not None and not image.isNull():
+ return image
+ except Exception:
+ pass
+ return None
+
+ @staticmethod
+ def _paste_remote_candidates(
+ url_strings: list[str], html: str, text: str
+ ) -> list[str]:
+ """Collect unique http(s) image URL candidates, most-likely first."""
+ seen: set[str] = set()
+ ordered: list[str] = []
+
+ def push(url: str) -> None:
+ url = (url or "").strip().rstrip(".,;)]")
+ if not url or url in seen:
+ return
+ try:
+ scheme = urllib.parse.urlparse(url).scheme.lower()
+ except Exception:
+ return
+ if scheme not in {"http", "https"}:
+ return
+ seen.add(url)
+ ordered.append(url)
+
+ for url in url_strings or []:
+ push(url)
+ try:
+ for match in _PASTE_DATA_SRC_RE.findall(html or ""):
+ push(match)
+ except Exception:
+ pass
+ try:
+ for match in _PASTE_IMG_SRC_RE.findall(html or ""):
+ push(match)
+ except Exception:
+ pass
+ try:
+ for srcset in _PASTE_SRCSET_RE.findall(html or ""):
+ try:
+ entries = [
+ part.strip().split()[0]
+ for part in str(srcset).split(",")
+ if part.strip().split()
+ ]
+ except Exception:
+ continue
+ for entry in reversed(entries):
+ if str(entry).lower().startswith(("http://", "https://")):
+ push(entry)
+ break
+ except Exception:
+ pass
+ try:
+ for match in _PASTE_URL_RE.findall(html or ""):
+ push(match)
+ except Exception:
+ pass
+ try:
+ for match in _PASTE_URL_RE.findall(text or ""):
+ push(match)
+ except Exception:
+ pass
+ return ordered[:8]
+
+ @staticmethod
+ def _paste_extension_for(url: str, content_type: str) -> str:
+ ctype = (content_type or "").split(";")[0].strip().lower()
+ if ctype in _PASTE_CONTENT_TYPE_SUFFIX:
+ return _PASTE_CONTENT_TYPE_SUFFIX[ctype]
+ try:
+ suffix = Path(urllib.parse.urlparse(url).path).suffix.lower()
+ except Exception:
+ suffix = ""
+ if suffix in IMAGE_SUFFIXES:
+ return suffix
+ return ".jpg"
+
+ def _fetch_first_remote_paste_image(self, urls: list[str]) -> str:
+ """Download the first URL that returns image bytes (worker thread).
+
+ Returns the staged local file path. Raises OSError if every URL
+ fails. Must not touch Qt state; called via JobWorker.
+ """
+ last_error = "no URLs"
+ for url in urls or []:
+ try:
+ request = urllib.request.Request(
+ url,
+ headers={
+ "User-Agent": _PASTE_BROWSER_UA,
+ "Accept": "image/avif,image/webp,image/*,*/*;q=0.8",
+ "Referer": "https://www.pinterest.com/",
+ },
+ )
+ with urllib.request.urlopen(
+ request, timeout=_PASTE_DOWNLOAD_TIMEOUT_S
+ ) as response:
+ try:
+ content_type = (
+ response.headers.get_content_type()
+ if hasattr(response.headers, "get_content_type")
+ else str(
+ response.headers.get("Content-Type", "")
+ ).split(";")[0].strip()
+ )
+ except Exception:
+ content_type = ""
+ if not str(content_type or "").lower().startswith("image/"):
+ raise OSError(
+ f"URL did not return an image "
+ f"({content_type or 'unknown type'})."
+ )
+ try:
+ declared = int(
+ str(response.headers.get("Content-Length", "") or "").strip()
+ )
+ except (TypeError, ValueError):
+ declared = 0
+ if declared > _PASTE_DOWNLOAD_MAX_BYTES:
+ raise OSError("Web image is too large (>30 MB).")
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = response.read(65536)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > _PASTE_DOWNLOAD_MAX_BYTES:
+ raise OSError("Web image is too large (>30 MB).")
+ chunks.append(chunk)
+ data = b"".join(chunks)
+ if not data:
+ raise OSError("Downloaded file is empty.")
+ # Fail fast on undecodable payloads (error pages, truncated
+ # bodies) instead of queueing a corpse that errors later
+ # at metadata stage. SVG bypasses the probe: Qt decodes it
+ # through a separate renderer stack.
+ if "svg" not in str(content_type or "").lower():
+ try:
+ probe = QImage.fromData(data)
+ except Exception:
+ probe = None
+ if probe is None or probe.isNull():
+ raise OSError("Downloaded data is not a readable image.")
+ extension = self._paste_extension_for(url, str(content_type))
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
+ digest = hashlib.sha1(data).hexdigest()[:16]
+ target = APP_TEMP / f"paste-dl-{digest}{extension}"
+ if target.is_file():
+ try:
+ os.utime(target, None)
+ except OSError:
+ pass
+ else:
+ target.write_bytes(data)
+ return str(target)
+ except Exception as exc:
+ last_error = str(exc) or type(exc).__name__
+ continue
+ raise OSError(f"Web image download failed: {last_error}")
+
+ def _stage_pasted_qimage(self, image: QImage) -> str:
+ """Stage clipboard pixels as PNG under APP_TEMP. Returns file URL.
+
+ The filename is a content hash, so re-pasting identical pixels
+ resolves to the same path: the queue's duplicate check then selects
+ the existing entry instead of adding another copy.
+ """
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
+ try:
+ buffer = QBuffer()
+ buffer.open(QIODevice.WriteOnly)
+ ok = bool(image.save(buffer, "PNG"))
+ data = bytes(buffer.data()) if ok else b""
+ buffer.close()
+ except Exception:
+ data = b""
+ if not data:
+ raise OSError("Could not stage the pasted image.")
+ digest = hashlib.sha1(data).hexdigest()[:16]
+ target = APP_TEMP / f"paste-{digest}.png"
+ if not target.is_file():
+ target.write_bytes(data)
+ else:
+ try:
+ os.utime(target, None)
+ except OSError:
+ pass
+ return QUrl.fromLocalFile(str(target)).toString()
+
+ def _start_paste_download(self, candidates: list[str]) -> None:
+ """Fetch a web image off the GUI thread, then feed it to addFiles."""
+ operation_id = self._set_operation(SCANNING_INPUTS, "Downloading web image…")
+ worker = JobWorker(
+ self._fetch_first_remote_paste_image,
+ list(candidates),
+ inject_callbacks=False,
+ )
+ self._scan_worker = worker
+
+ def done(local_path: str) -> None:
+ if operation_id != self._operation_id or self._shutting_down:
+ return
+ self._scan_worker = None
+ # Return to Idle first: addFiles refuses queue changes while an
+ # operation is active, and our download op is still that blocker.
+ if not self._finish_operation(operation_id, "Download complete. Scanning…"):
+ return
+ try:
+ self._paste_select_single = True
+ self.addFiles([QUrl.fromLocalFile(str(local_path)).toString()])
+ except Exception as exc:
+ self._status_message = f"Paste failed: {exc}"
+ self.statusMessageChanged.emit()
+ self._log(f"Paste failed: {exc}")
+
+ def failed(message: str) -> None:
+ self._scan_worker = None
+ self._finish_operation(operation_id, f"Web image download failed: {message}")
+ self._log(f"Web image download failed: {message}")
+
+ worker.signals.finished.connect(done)
+ worker.signals.failed.connect(failed)
+ worker.signals.cancelled.connect(
+ lambda: self._finish_operation(operation_id, "Download cancelled.")
+ )
+ self._thread_pool.start(worker)
+
+ @Slot()
+ def pasteFromClipboard(self) -> None:
+ """Paste images/video into the active batch tab from the clipboard.
+
+ Priority (fixes browser "Copy image" shadowing):
+ 1. Bitmap pixels (screenshots, Pinterest/Chrome bitmap) — offline.
+ 2. Local file URLs/paths (Explorer copy).
+ 3. Remote http(s) URLs, HTML <img src>, URL text — async download.
+ Reuses addFiles so scanning, type checks and mode switching behave
+ identically. QML gates this to NR/Upscale/FI tabs; the tab guard
+ below is defense in depth.
+ """
+ if self._active_tab not in {"neural-rendering", "upscale", "frame-interpolation"}:
+ return
+ if not self.canModifyQueue:
+ self._status_message = "Queue changes are disabled while an operation is active."
+ self.statusMessageChanged.emit()
+ return
+ try:
+ clipboard = QGuiApplication.clipboard()
+ mime = clipboard.mimeData() if clipboard is not None else None
+ except Exception as exc:
+ self._log(f"Could not read clipboard: {exc}")
+ return
+ if mime is None:
+ return
+ # 1. Pixels first: exact frame the user saw, no network involved.
+ try:
+ pixels = self._clipboard_pixels(mime, clipboard)
+ if pixels is not None:
+ staged_url = self._stage_pasted_qimage(pixels)
+ self._paste_select_single = True
+ self.addFiles([staged_url])
+ return
+ except Exception as exc:
+ self._paste_select_single = False
+ self._log(f"Clipboard bitmap unavailable, trying file/URL paths: {exc}")
+ # 2. Split clipboard URLs into local files vs remote web links.
+ # Browser copies expose https URLs here; passing those to addFiles
+ # is what used to produce "No supported images were found."
+ local_urls: list[str] = []
+ remote_urls: list[str] = []
+ try:
+ if mime.hasUrls():
+ for item in mime.urls():
+ try:
+ if not item.isValid():
+ continue
+ text = item.toString()
+ if not text:
+ continue
+ scheme = item.scheme().lower() if hasattr(item, "scheme") else ""
+ if not scheme:
+ try:
+ scheme = urllib.parse.urlparse(text).scheme.lower()
+ except Exception:
+ scheme = ""
+ if scheme in {"http", "https"}:
+ remote_urls.append(text)
+ elif item.isLocalFile() if hasattr(item, "isLocalFile") else text.startswith("file:"):
+ local_urls.append(text)
+ else:
+ local_urls.append(text)
+ except Exception:
+ continue
+ except Exception:
+ pass
+ if local_urls:
+ try:
+ self._paste_select_single = True
+ self.addFiles(local_urls)
+ except Exception as exc:
+ self._status_message = f"Paste failed: {exc}"
+ self.statusMessageChanged.emit()
+ self._log(f"Paste failed: {exc}")
+ return
+ # Copied file-path text (e.g. "C:\\pics\\a.jpg" lines) still counts.
+ try:
+ if mime.hasText():
+ paths: list[str] = []
+ for line in str(mime.text() or "").splitlines():
+ candidate = line.strip().strip("\"'")
+ if not candidate or candidate.lower().startswith(("http://", "https://")):
+ continue
+ try:
+ if Path(self._clean_path(candidate)).is_file():
+ paths.append(candidate)
+ except Exception:
+ continue
+ if paths:
+ self._paste_select_single = True
+ self.addFiles(paths)
+ return
+ except Exception:
+ pass
+ # 3. Remote web image (Pinterest "Copy image" / "Copy image address").
+ try:
+ html = str(mime.html()) if mime.hasHtml() else ""
+ except Exception:
+ html = ""
+ try:
+ text = str(mime.text()) if mime.hasText() else ""
+ except Exception:
+ text = ""
+ candidates = self._paste_remote_candidates(remote_urls, html, text)
+ if candidates:
+ self._start_paste_download(candidates)
+ return
+ try:
+ formats = list(mime.formats() or [])[:12]
+ except Exception:
+ formats = []
+ self._status_message = "Clipboard has no images or files to paste."
+ self.statusMessageChanged.emit()
+ self._log(f"Paste found no usable data (formats: {formats}).")
+
+ @Slot(str, str, str)
+ def _append_backend_log(self, level: str, tag: str, message: str) -> None:
+ stamp = time.strftime("%H:%M:%S")
+ entry = f"[{stamp}] {level} {tag}: {message}"
+ self._logs.append(entry)
+ if len(self._logs) > 1000:
+ del self._logs[:200]
+ self.logAppended.emit(entry)
+
+ @Property(str, notify=logAppended)
+ def currentLogPath(self) -> str:
+ try:
+ return app_log.session_path()
+ except Exception:
+ return str(LOGS)
+
+ @Slot()
+ def clearLogDisplay(self) -> None:
+ self._logs.clear()
+ self.logAppended.emit("")
+
+ def _log(self, message: str) -> None:
+ stamp = time.strftime("%H:%M:%S")
+ entry = f"[{stamp}] {message}"
+ self._logs.append(entry)
+ if len(self._logs) > 200:
+ self._logs.pop(0)
+ self.logAppended.emit(entry)
+
+ @Property(str, notify=logAppended)
+ def fullLog(self) -> str:
+ return "\n".join(self._logs)
diff --git a/src/desktop/image_provider.py b/src/desktop/image_provider.py
new file mode 100644
index 0000000..3ffb958
--- /dev/null
+++ b/src/desktop/image_provider.py
@@ -0,0 +1,119 @@
+from __future__ import annotations
+
+import threading
+from collections import OrderedDict
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from PIL import Image
+from PySide6.QtCore import QSize
+from PySide6.QtGui import QImage
+from PySide6.QtQuick import QQuickImageProvider
+
+
+class PreviewImageProvider(QQuickImageProvider):
+ """Thread-safe memory-backed QML image provider with bounded LRU storage."""
+
+ def __init__(self, max_bytes: int = 384 * 1024 * 1024) -> None:
+ super().__init__(QQuickImageProvider.ImageType.Image)
+ self._lock = threading.RLock()
+ self._images: OrderedDict[str, QImage] = OrderedDict()
+ self._sizes: dict[str, int] = {}
+ self._bytes = 0
+ self._max_bytes = max(32 * 1024 * 1024, int(max_bytes))
+
+ @staticmethod
+ def _image_bytes(image: QImage) -> int:
+ try:
+ return int(image.sizeInBytes())
+ except Exception:
+ return int(image.width() * image.height() * max(1, image.depth() // 8))
+
+ def set_image(self, image_id: str, image_data: Any) -> None:
+ qimg = self._to_qimage(image_data)
+ if qimg is None or qimg.isNull():
+ return
+ clean_id = image_id.split("?", 1)[0]
+ with self._lock:
+ old = self._images.pop(clean_id, None)
+ if old is not None:
+ self._bytes -= self._sizes.pop(clean_id, 0)
+ self._images[clean_id] = qimg
+ size = self._image_bytes(qimg)
+ self._sizes[clean_id] = size
+ self._bytes += size
+ while self._bytes > self._max_bytes and len(self._images) > 1:
+ key, _ = self._images.popitem(last=False)
+ self._bytes -= self._sizes.pop(key, 0)
+
+ def clear(self, image_id: str | None = None) -> None:
+ with self._lock:
+ if image_id is not None:
+ clean_id = image_id.split("?", 1)[0]
+ self._images.pop(clean_id, None)
+ self._bytes -= self._sizes.pop(clean_id, 0)
+ else:
+ self._images.clear()
+ self._sizes.clear()
+ self._bytes = 0
+
+ def requestImage(self, image_id: str, size: QSize, requested_size: QSize) -> QImage:
+ clean_id = image_id.split("?", 1)[0]
+ with self._lock:
+ img = self._images.get(clean_id)
+ if img is not None and not img.isNull():
+ self._images.move_to_end(clean_id)
+ size.setWidth(img.width())
+ size.setHeight(img.height())
+ if requested_size.isValid() and requested_size.width() > 0 and requested_size.height() > 0:
+ return img.scaled(requested_size)
+ return img
+ placeholder = QImage(1, 1, QImage.Format.Format_RGBA8888)
+ placeholder.fill(0)
+ size.setWidth(1)
+ size.setHeight(1)
+ return placeholder
+
+ @staticmethod
+ def _to_qimage(data: Any) -> QImage | None:
+ if data is None:
+ return None
+ if isinstance(data, QImage):
+ return data.copy()
+ if isinstance(data, (str, Path)):
+ path_str = str(data).strip()
+ if path_str and Path(path_str).is_file():
+ img = QImage(path_str)
+ if not img.isNull():
+ return img
+ try:
+ with Image.open(path_str) as pil_img:
+ return PreviewImageProvider._pil_to_qimage(pil_img)
+ except Exception:
+ return None
+ return None
+ if isinstance(data, Image.Image):
+ return PreviewImageProvider._pil_to_qimage(data)
+ if isinstance(data, np.ndarray):
+ return PreviewImageProvider._numpy_to_qimage(data)
+ return None
+
+ @staticmethod
+ def _pil_to_qimage(pil_img: Image.Image) -> QImage:
+ converted = pil_img if pil_img.mode == "RGBA" else pil_img.convert("RGBA")
+ data = converted.tobytes("raw", "RGBA")
+ return QImage(data, converted.width, converted.height, QImage.Format.Format_RGBA8888).copy()
+
+ @staticmethod
+ def _numpy_to_qimage(arr: np.ndarray) -> QImage:
+ if arr.ndim == 2:
+ h, w = arr.shape
+ return QImage(arr.data, w, h, w, QImage.Format.Format_Grayscale8).copy()
+ if arr.ndim == 3:
+ h, w, channels = arr.shape
+ if channels == 3:
+ return QImage(arr.data, w, h, 3 * w, QImage.Format.Format_RGB888).copy()
+ if channels == 4:
+ return QImage(arr.data, w, h, 4 * w, QImage.Format.Format_RGBA8888).copy()
+ return QImage()
diff --git a/src/desktop/models.py b/src/desktop/models.py
new file mode 100644
index 0000000..4466d19
--- /dev/null
+++ b/src/desktop/models.py
@@ -0,0 +1,270 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from PySide6.QtCore import QAbstractListModel, QByteArray, QModelIndex, Property, Qt, Signal, Slot
+
+
+@dataclass
+class BatchEntry:
+ index: int
+ input_path: str
+ output_path: str = ""
+ state: str = "Queued"
+ progress: float = 0.0
+ detail: str = ""
+ elapsed_seconds: float = 0.0
+ input_dimensions: str = ""
+ output_dimensions: str = ""
+ thumbnail_url: str = ""
+ selected: bool = False
+
+ @property
+ def file_name(self) -> str:
+ return Path(self.input_path).name
+
+
+class BatchListModel(QAbstractListModel):
+ """QML list model used by all desktop batch queues."""
+
+ countChanged = Signal()
+ selectedIndexChanged = Signal()
+
+ FileNameRole = Qt.ItemDataRole.UserRole + 1
+ InputPathRole = Qt.ItemDataRole.UserRole + 2
+ OutputPathRole = Qt.ItemDataRole.UserRole + 3
+ StateRole = Qt.ItemDataRole.UserRole + 4
+ ProgressRole = Qt.ItemDataRole.UserRole + 5
+ DetailRole = Qt.ItemDataRole.UserRole + 6
+ ElapsedSecondsRole = Qt.ItemDataRole.UserRole + 7
+ InputDimensionsRole = Qt.ItemDataRole.UserRole + 8
+ OutputDimensionsRole = Qt.ItemDataRole.UserRole + 9
+ ThumbnailUrlRole = Qt.ItemDataRole.UserRole + 10
+ IndexRole = Qt.ItemDataRole.UserRole + 11
+ SelectedRole = Qt.ItemDataRole.UserRole + 12
+
+ def __init__(self, parent: Any = None) -> None:
+ super().__init__(parent)
+ self._entries: list[BatchEntry] = []
+ self._selected_index = -1
+
+ def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
+ return 0 if parent.isValid() else len(self._entries)
+
+ @Property(int, notify=countChanged)
+ def count(self) -> int:
+ return len(self._entries)
+
+ @Property(int, notify=selectedIndexChanged)
+ def selectedIndex(self) -> int:
+ return self._selected_index
+
+ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
+ if not index.isValid() or not (0 <= index.row() < len(self._entries)):
+ return None
+ entry = self._entries[index.row()]
+ mapping = {
+ self.FileNameRole: entry.file_name,
+ self.InputPathRole: entry.input_path,
+ self.OutputPathRole: entry.output_path,
+ self.StateRole: entry.state,
+ self.ProgressRole: entry.progress,
+ self.DetailRole: entry.detail,
+ self.ElapsedSecondsRole: entry.elapsed_seconds,
+ self.InputDimensionsRole: entry.input_dimensions,
+ self.OutputDimensionsRole: entry.output_dimensions,
+ self.ThumbnailUrlRole: entry.thumbnail_url,
+ self.IndexRole: entry.index,
+ self.SelectedRole: entry.selected,
+ }
+ return mapping.get(role)
+
+ def roleNames(self) -> dict[int, QByteArray]:
+ return {
+ self.FileNameRole: QByteArray(b"fileName"),
+ self.InputPathRole: QByteArray(b"inputPath"),
+ self.OutputPathRole: QByteArray(b"outputPath"),
+ self.StateRole: QByteArray(b"state"),
+ self.ProgressRole: QByteArray(b"progress"),
+ self.DetailRole: QByteArray(b"detail"),
+ self.ElapsedSecondsRole: QByteArray(b"elapsedSeconds"),
+ self.InputDimensionsRole: QByteArray(b"inputDimensions"),
+ self.OutputDimensionsRole: QByteArray(b"outputDimensions"),
+ self.ThumbnailUrlRole: QByteArray(b"thumbnailUrl"),
+ self.IndexRole: QByteArray(b"itemIndex"),
+ self.SelectedRole: QByteArray(b"selected"),
+ }
+
+ @Slot(list)
+ def set_items(self, paths: list[str]) -> None:
+ self.beginResetModel()
+ self._entries = [BatchEntry(index=i, input_path=p) for i, p in enumerate(paths) if p and Path(p).is_file()]
+ self._selected_index = 0 if self._entries else -1
+ if self._selected_index >= 0:
+ self._entries[0].selected = True
+ self.endResetModel()
+ self.countChanged.emit()
+ self.selectedIndexChanged.emit()
+
+ @Slot(list)
+ def add_items(self, paths: list[str]) -> None:
+ existing_paths = {str(Path(e.input_path).resolve()).lower() for e in self._entries}
+ new_paths: list[str] = []
+ for p in paths:
+ if not p or not Path(p).is_file():
+ continue
+ key = str(Path(p).resolve()).lower()
+ if key not in existing_paths:
+ existing_paths.add(key)
+ new_paths.append(p)
+ if not new_paths:
+ return
+ start = len(self._entries)
+ self.beginInsertRows(QModelIndex(), start, start + len(new_paths) - 1)
+ for i, path in enumerate(new_paths):
+ self._entries.append(BatchEntry(index=start + i, input_path=path))
+ self.endInsertRows()
+ self.countChanged.emit()
+ if self._selected_index < 0:
+ self.select(0)
+
+ @Slot(int)
+ def select(self, row: int) -> None:
+ if not (0 <= row < len(self._entries)):
+ return
+ old = self._selected_index
+ if old == row:
+ return
+ self._selected_index = row
+ if 0 <= old < len(self._entries):
+ self._entries[old].selected = False
+ idx = self.index(old)
+ self.dataChanged.emit(idx, idx, [self.SelectedRole])
+ self._entries[row].selected = True
+ idx = self.index(row)
+ self.dataChanged.emit(idx, idx, [self.SelectedRole])
+ self.selectedIndexChanged.emit()
+
+ @Slot(int)
+ def remove_item(self, row: int) -> None:
+ if not (0 <= row < len(self._entries)):
+ return
+ self.beginRemoveRows(QModelIndex(), row, row)
+ self._entries.pop(row)
+ for i, e in enumerate(self._entries):
+ e.index = i
+ self.endRemoveRows()
+ if not self._entries:
+ new_selected = -1
+ elif self._selected_index == row:
+ new_selected = min(row, len(self._entries) - 1)
+ elif self._selected_index > row:
+ new_selected = self._selected_index - 1
+ else:
+ new_selected = self._selected_index
+ for e in self._entries:
+ e.selected = False
+ self._selected_index = new_selected
+ if new_selected >= 0:
+ self._entries[new_selected].selected = True
+ idx = self.index(new_selected)
+ self.dataChanged.emit(idx, idx, [self.SelectedRole])
+ self.countChanged.emit()
+ self.selectedIndexChanged.emit()
+
+ @Slot()
+ def clear(self) -> None:
+ if not self._entries:
+ return
+ self.beginResetModel()
+ self._entries.clear()
+ self._selected_index = -1
+ self.endResetModel()
+ self.countChanged.emit()
+ self.selectedIndexChanged.emit()
+
+ def get_paths(self) -> list[str]:
+ return [e.input_path for e in self._entries]
+
+ def selected_path(self) -> str | None:
+ if 0 <= self._selected_index < len(self._entries):
+ return self._entries[self._selected_index].input_path
+ return None
+
+ def update_metadata(self, row: int, *, input_dimensions: str | None = None,
+ output_dimensions: str | None = None, thumbnail_url: str | None = None) -> None:
+ if not (0 <= row < len(self._entries)):
+ return
+ entry = self._entries[row]
+ roles: list[int] = []
+ if input_dimensions is not None:
+ entry.input_dimensions = input_dimensions
+ roles.append(self.InputDimensionsRole)
+ if output_dimensions is not None:
+ entry.output_dimensions = output_dimensions
+ roles.append(self.OutputDimensionsRole)
+ if thumbnail_url is not None:
+ entry.thumbnail_url = thumbnail_url
+ roles.append(self.ThumbnailUrlRole)
+ if roles:
+ idx = self.index(row)
+ self.dataChanged.emit(idx, idx, roles)
+
+ def update_item_progress(self, index: int, state: str, progress: float, detail: str = "",
+ output_path: str = "", elapsed_seconds: float = 0.0) -> None:
+ if not (0 <= index < len(self._entries)):
+ return
+ state_aliases = {"Processing": "Running", "Complete": "Completed", "Canceled": "Cancelled"}
+ state = state_aliases.get(state, state)
+ entry = self._entries[index]
+ entry.state = state
+ entry.progress = max(0.0, min(1.0, float(progress)))
+ if detail:
+ entry.detail = detail
+ if output_path:
+ entry.output_path = output_path
+ if elapsed_seconds >= 0:
+ entry.elapsed_seconds = elapsed_seconds
+ idx = self.index(index)
+ self.dataChanged.emit(idx, idx, [self.StateRole, self.ProgressRole, self.DetailRole,
+ self.OutputPathRole, self.ElapsedSecondsRole])
+
+
+ @Slot()
+ def clear_completed(self) -> None:
+ remove = [i for i, e in enumerate(self._entries) if e.state in {"Completed", "CompletedWithWarnings", "Cancelled"}]
+ if not remove:
+ return
+ keep = [e.input_path for i, e in enumerate(self._entries) if i not in set(remove)]
+ self.set_items(keep)
+
+ @Slot()
+ def retry_failed(self) -> None:
+ changed = False
+ for row, entry in enumerate(self._entries):
+ if entry.state in {"Failed", "Cancelled"}:
+ entry.state = "Queued"
+ entry.progress = 0.0
+ entry.detail = ""
+ entry.output_path = ""
+ entry.elapsed_seconds = 0.0
+ idx = self.index(row)
+ self.dataChanged.emit(idx, idx, [self.StateRole, self.ProgressRole, self.DetailRole, self.OutputPathRole, self.ElapsedSecondsRole])
+ changed = True
+ if changed and self._selected_index < 0 and self._entries:
+ self.select(0)
+
+ def reset_all_states(self) -> None:
+ if not self._entries:
+ return
+ for e in self._entries:
+ e.state = "Queued"
+ e.progress = 0.0
+ e.detail = ""
+ e.output_path = ""
+ e.elapsed_seconds = 0.0
+ self.dataChanged.emit(self.index(0), self.index(len(self._entries) - 1),
+ [self.StateRole, self.ProgressRole, self.DetailRole,
+ self.OutputPathRole, self.ElapsedSecondsRole])
diff --git a/src/desktop/qml/Main.qml b/src/desktop/qml/Main.qml
new file mode 100644
index 0000000..73387ce
--- /dev/null
+++ b/src/desktop/qml/Main.qml
@@ -0,0 +1,265 @@
+import QtQuick
+import QtQuick.Window
+import QtQuick.Layouts
+import QtQuick.Controls as QQC2
+import "."
+import "components"
+import "views"
+
+Window {
+ id: appWindow
+ width: typeof backend !== "undefined" && backend ? backend.windowWidth : 1440
+ height: typeof backend !== "undefined" && backend ? backend.windowHeight : 920
+ x: typeof backend !== "undefined" && backend && backend.windowX >= 0 ? Math.max(0, Math.min(Screen.width - width, backend.windowX)) : Math.max(0, (Screen.width - width) / 2)
+ y: typeof backend !== "undefined" && backend && backend.windowY >= 0 ? Math.max(0, Math.min(Screen.height - height, backend.windowY)) : Math.max(0, (Screen.height - height) / 2)
+ minimumWidth: 1080
+ minimumHeight: 700
+ // Start windowed; the saved maximized state is applied natively in
+ // onCompleted (the OS filter supplies a real frame, so maximized fills
+ // the work area with no transparent insets).
+ visibility: Window.Windowed
+ flags: Qt.Window | Qt.FramelessWindowHint
+ title: "Visual Enhancer"
+ color: Theme.bgBase
+
+ readonly property var windowRef: appWindow
+ property bool closeApproved: false
+
+ // Chrome hit-test rects (window-relative DIPs) published by HeaderBar for
+ // the native Windows filter. Default empty = filter falls back to client.
+ property rect minBtnRect: Qt.rect(0, 0, 0, 0)
+ property rect maxBtnRect: Qt.rect(0, 0, 0, 0)
+ property rect closeBtnRect: Qt.rect(0, 0, 0, 0)
+ property rect navTabsRect: Qt.rect(0, 0, 0, 0)
+ property bool chromeRectsReady: false
+
+ Component.onCompleted: {
+ // Native maximize is safe again: the OS filter supplies a real frame
+ // behind the frameless visuals (exact work-area geometry, no
+ // transparent insets). F11 toggles true fullscreen on demand.
+ Qt.callLater(function() {
+ if (typeof backend !== "undefined" && backend && backend.windowMaximized) appWindow.showMaximized()
+ else appWindow.showNormal()
+ })
+ }
+
+ function saveWindowLayout() {
+ if (typeof backend !== "undefined" && backend)
+ backend.saveWindowLayout(appWindow.x, appWindow.y, appWindow.width, appWindow.height, appWindow.visibility === Window.Maximized)
+ }
+
+ onClosing: (close) => {
+ saveWindowLayout()
+ if (!closeApproved && typeof backend !== "undefined" && backend && backend.operationState !== "Idle") {
+ close.accepted = false
+ // The Live video is a native child window that paints above the
+ // whole Qt Quick scene (including modal popups). Hide it before
+ // opening the prompt so the dialog is clickable; the session
+ // keeps running and re-shows from cached geometry on cancel.
+ try {
+ if (backend.mpvEmbed) backend.mpvEmbed.setDialogOpen(true)
+ } catch (e) {}
+ closeDialog.open()
+ }
+ }
+
+ onVisibilityChanged: {
+ // A fullscreen Live video is a separate top-level window: if the
+ // app is minimized/hidden it would strand the video on screen
+ // with its program gone from the taskbar. Dock it back first.
+ try {
+ if ((visibility === Window.Minimized || visibility === Window.Hidden)
+ && typeof backend !== "undefined" && backend && backend.mpvEmbed && backend.mpvEmbed.fullscreen)
+ backend.mpvEmbed.toggleFullscreen()
+ } catch (e) {}
+ }
+
+ Shortcut {
+ sequence: "F11"
+ onActivated: {
+ // A fullscreen Live video owns the screen: F11 first hands the
+ // screen back to the app instead of fighting over window state.
+ try {
+ if (typeof backend !== "undefined" && backend && backend.mpvEmbed && backend.mpvEmbed.fullscreen) {
+ backend.mpvEmbed.toggleFullscreen()
+ return
+ }
+ } catch (e) {}
+ if (appWindow.visibility === Window.FullScreen) appWindow.showNormal(); else appWindow.showFullScreen()
+ }
+ }
+ // The native Live video covers the transport bar in fullscreen, so the
+ // mouse cannot reach "Exit Full" — Esc is the way out (mpv convention).
+ // Guarded by `enabled` so a disabled Shortcut never steals Esc from
+ // text editors, combo popups, or dialogs while not fullscreen.
+ Shortcut {
+ sequence: "Escape"
+ enabled: typeof backend !== "undefined" && backend && backend.mpvEmbed && backend.mpvEmbed.fullscreen ? true : false
+ onActivated: {
+ if (typeof backend === "undefined" || !backend || !backend.mpvEmbed) return
+ if (!backend.mpvEmbed.fullscreen) return
+ backend.mpvEmbed.toggleFullscreen()
+ }
+ }
+ Shortcut {
+ sequence: "Ctrl+Shift+F"
+ onActivated: { if (typeof backend !== "undefined" && backend) backend.focusPreview = !backend.focusPreview }
+ }
+
+ // Global editing shortcuts below must never steal keys from text
+ // editors (stream URL, preset name, path fields all use TextInput).
+ // NOTE: guards live in `enabled` (not only in onActivated) so a
+ // disabled Shortcut never consumes the key — TextInput keeps native
+ // Ctrl+V / Delete / Space behavior while editing.
+ readonly property bool isTextEditing: activeFocusItem instanceof TextInput || activeFocusItem instanceof TextEdit
+ readonly property bool isBatchTab: typeof backend !== "undefined" && backend ? (backend.activeTab === "neural-rendering" || backend.activeTab === "upscale" || backend.activeTab === "frame-interpolation") : false
+ readonly property bool isLiveTab: typeof backend !== "undefined" && backend ? backend.activeTab === "live" : false
+ // True when keyboard focus sits on any tab-focusable control (custom
+ // AppButton/Switch/CheckBox/ComboBox/Slider/IconButton expose
+ // activeFocusOnTab:true and consume Space themselves). Mouse clicks
+ // never move keyboard focus there, so mouse users keep Space-pause.
+ readonly property bool isInteractiveFocused: {
+ var f = activeFocusItem
+ if (!f) return false
+ if (f instanceof TextInput || f instanceof TextEdit) return true
+ try {
+ if (f.activeFocusOnTab === true) return true
+ } catch (e) {}
+ return false
+ }
+
+ function textEditingFocused() {
+ return appWindow.isTextEditing
+ }
+
+ function batchTabActive() {
+ return appWindow.isBatchTab
+ }
+
+ // Ctrl+V: paste Explorer files / screenshots into the active batch tab.
+ Shortcut {
+ sequence: "Ctrl+V"
+ enabled: appWindow.isBatchTab && !appWindow.isTextEditing
+ onActivated: {
+ if (appWindow.textEditingFocused() || !appWindow.batchTabActive()) return
+ if (typeof backend !== "undefined" && backend) backend.pasteFromClipboard()
+ }
+ }
+ // Delete: same as the Clear All queue button (active tab only).
+ Shortcut {
+ sequence: "Delete"
+ enabled: appWindow.isBatchTab && !appWindow.isTextEditing
+ onActivated: {
+ if (appWindow.textEditingFocused() || !appWindow.batchTabActive()) return
+ if (typeof backend !== "undefined" && backend) backend.clearActiveQueue()
+ }
+ }
+ // Space: pause/resume in the Live tab only. Suppressed while a text
+ // field or any keyboard-focused control owns Space (native activation
+ // wins, avoiding a double toggle on custom App* buttons); mouse users
+ // are unaffected (clicking never moves keyboard focus).
+ Shortcut {
+ sequence: "Space"
+ enabled: appWindow.isLiveTab && !appWindow.isInteractiveFocused
+ onActivated: {
+ if (typeof backend === "undefined" || !backend) return
+ if (backend.activeTab !== "live") return
+ if (appWindow.isInteractiveFocused) return
+ if (backend.mpvEmbed && backend.isLiveRunning) backend.mpvEmbed.togglePause()
+ }
+ }
+
+ Column {
+ anchors.fill: parent
+ HeaderBar { id: header; width: parent.width; appBridge: typeof backend !== "undefined" ? backend : null; windowRef: appWindow }
+
+ Item {
+ id: workspace
+ width: parent.width
+ height: parent.height - header.height
+ clip: true
+ StackLayout {
+ anchors.fill: parent
+ currentIndex: {
+ if (typeof backend === "undefined" || !backend) return 0
+ var tab = backend.activeTab
+ if (tab === "neural-rendering") return 0
+ if (tab === "upscale") return 1
+ if (tab === "frame-interpolation") return 2
+ if (tab === "live") return 3
+ if (tab === "settings") return 4
+ if (tab === "help") return 5
+ return 0
+ }
+ NeuralRenderingView { appBridge: typeof backend !== "undefined" ? backend : null }
+ UpscaleView { appBridge: typeof backend !== "undefined" ? backend : null }
+ FrameInterpolationView { appBridge: typeof backend !== "undefined" ? backend : null }
+ LiveView { appBridge: typeof backend !== "undefined" ? backend : null }
+ SettingsView { appBridge: typeof backend !== "undefined" ? backend : null }
+ AboutView { appBridge: typeof backend !== "undefined" ? backend : null }
+ }
+ }
+ }
+
+ // QML resize hit zones (fallback where the native filter is inactive; on
+ // Windows the OS owns the frame edges). Disabled while maximized/fullscreen.
+ property bool qmlResizeActive: !(appWindow.nativeChromeActive === true && appWindow.chromeRectsReady === true) && appWindow.visibility !== Window.Maximized && appWindow.visibility !== Window.FullScreen
+ MouseArea { z:10000; visible: qmlResizeActive; anchors.left:parent.left; anchors.top:parent.top; anchors.bottom:parent.bottom; width:6; cursorShape:Qt.SizeHorCursor; onPressed: { appWindow.startSystemResize(Qt.LeftEdge) } }
+ MouseArea { z:10000; visible: qmlResizeActive; anchors.right:parent.right; anchors.top:parent.top; anchors.bottom:parent.bottom; width:6; cursorShape:Qt.SizeHorCursor; onPressed: { appWindow.startSystemResize(Qt.RightEdge) } }
+ MouseArea { z:10000; visible: qmlResizeActive; anchors.top:parent.top; anchors.left:parent.left; anchors.right:parent.right; height:6; cursorShape:Qt.SizeVerCursor; onPressed: { appWindow.startSystemResize(Qt.TopEdge) } }
+ MouseArea { z:10000; visible: qmlResizeActive; anchors.bottom:parent.bottom; anchors.left:parent.left; anchors.right:parent.right; height:6; cursorShape:Qt.SizeVerCursor; onPressed: { appWindow.startSystemResize(Qt.BottomEdge) } }
+ MouseArea { z:10001; visible: qmlResizeActive; anchors.left:parent.left; anchors.top:parent.top; width:10; height:10; cursorShape:Qt.SizeFDiagCursor; onPressed: { appWindow.startSystemResize(Qt.LeftEdge|Qt.TopEdge) } }
+ MouseArea { z:10001; visible: qmlResizeActive; anchors.right:parent.right; anchors.top:parent.top; width:10; height:10; cursorShape:Qt.SizeBDiagCursor; onPressed: { appWindow.startSystemResize(Qt.RightEdge|Qt.TopEdge) } }
+ MouseArea { z:10001; visible: qmlResizeActive; anchors.left:parent.left; anchors.bottom:parent.bottom; width:10; height:10; cursorShape:Qt.SizeBDiagCursor; onPressed: { appWindow.startSystemResize(Qt.LeftEdge|Qt.BottomEdge) } }
+ MouseArea { z:10001; visible: qmlResizeActive; anchors.right:parent.right; anchors.bottom:parent.bottom; width:10; height:10; cursorShape:Qt.SizeFDiagCursor; onPressed: { appWindow.startSystemResize(Qt.RightEdge|Qt.BottomEdge) } }
+
+ QQC2.Dialog {
+ id: closeDialog
+ parent: QQC2.Overlay.overlay
+ anchors.centerIn: parent
+ width: 420
+ z: 20000
+ focus: true
+ modal: true
+ closePolicy: QQC2.Popup.CloseOnEscape
+ standardButtons: QQC2.Dialog.Yes | QQC2.Dialog.No
+ leftPadding: 20
+ rightPadding: 20
+ topPadding: 16
+ bottomPadding: 12
+ spacing: 8
+ // Borderless custom header: the default Dialog title chrome draws
+ // its own light separator line under the title.
+ header: QQC2.Label {
+ text: "Operation still active"
+ color: Theme.textPrimary
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeTitle
+ font.weight: Font.Bold
+ leftPadding: 20
+ rightPadding: 20
+ topPadding: 16
+ bottomPadding: 4
+ }
+ contentItem: Text {
+ text: "A render, preview, scan, or Live session is still active. Cancel it and exit?"
+ color: Theme.textPrimary; font.family: Theme.fontFamily; wrapMode: Text.WordWrap; width: 360
+ }
+ // Borderless: the previous border.color (light gray) read as a
+ // white outline around the whole box against the dark surface.
+ background: Rectangle { color: Theme.bgSurface; border.width: 0; radius: Theme.radiusLarge }
+ onAboutToShow: {
+ try {
+ if (typeof backend !== "undefined" && backend && backend.mpvEmbed) backend.mpvEmbed.setDialogOpen(true)
+ } catch (e) {}
+ }
+ onClosed: {
+ // Cancelled (No / Escape / X): restore the Live video if its tab
+ // is visible; the controller re-shows from cached geometry.
+ try {
+ if (typeof backend !== "undefined" && backend && backend.mpvEmbed) backend.mpvEmbed.setDialogOpen(false)
+ } catch (e) {}
+ }
+ onAccepted: { appWindow.closeApproved = true; appWindow.close() }
+ }
+}
diff --git a/src/desktop/qml/Theme.qml b/src/desktop/qml/Theme.qml
new file mode 100644
index 0000000..c962c11
--- /dev/null
+++ b/src/desktop/qml/Theme.qml
@@ -0,0 +1,91 @@
+import QtQuick
+
+pragma Singleton
+
+QtObject {
+ id: root
+
+ // =========================================================================
+ // Color Palette: Near-black + charcoal with cyan-to-green primary gradient
+ // =========================================================================
+ readonly property color bgBase: "#0F0F11" // Near-black main background
+ readonly property color bgSurface: "#27272A" // Dark charcoal cards, sidebar, header, drawers
+ readonly property color bgCard: "#27272A" // Slightly elevated card background
+ readonly property color bgInput: "#1B1B1E" // Text inputs, slider grooves, wells
+ readonly property color bgInputHover: "#232326" // Input hover state
+ readonly property color bgHover: "#303034" // General button / item hover state
+ readonly property color bgPressed: "#3A3A3F" // Button pressed state
+ readonly property color bgSelected: "#33363B" // Selected queue item or tab
+
+ // Borders & Separators
+ readonly property color borderSubtle: "#35353A" // Hairline panel borders
+ readonly property color borderDefault: "#45454B" // Input / card borders
+ readonly property color borderActive: "#5A5A61" // Hovered / focused borders
+ readonly property color borderAccent: "#0387C2" // Accent border
+
+ // Primary Action Gradient (cyan-blue -> bright green -> deep green)
+ readonly property color primaryGradStart: "#0387C2" // Left side of button
+ readonly property color primaryGradMid: "#10B882" // Green highlight
+ readonly property color primaryGradEnd: "#06996B" // Right side of button
+
+ // Technical Accents (green primary actions)
+ readonly property color accent: "#0387C2" // Primary brand action color
+ readonly property color accentHover: "#06996B" // Primary action hover - always solid green
+ readonly property color accentPressed: "#057A54" // Primary action pressed - darker green
+ readonly property color primaryDisabled: "#047857" // Disabled primary - still clearly green
+ readonly property color primaryDisabledText: "#C7D2CE" // Text on disabled primary
+ readonly property color accentGlow: "#200387C2" // Subtle glow around active element
+ readonly property color accentMuted: "#12333D" // Background tint for active pill tabs
+
+ // Status Colors
+ readonly property color success: "#10B981" // Complete / Ready / Online
+ readonly property color successBg: "#152E25"
+ readonly property color warning: "#F59E0B" // Caution / HDR note
+ readonly property color warningBg: "#2F2515"
+ readonly property color danger: "#EF4444" // Stop / Cancel / Error
+ readonly property color dangerHover: "#F87171"
+ readonly property color dangerPressed: "#DC2626"
+ readonly property color dangerBg: "#331818"
+
+ // Typography Colors
+ readonly property color textPrimary: "#F1F5F9" // High contrast off-white
+ readonly property color textSecondary: "#A8ADB5" // Subdued labels & hints
+ readonly property color textMuted: "#71767E" // Placeholders & disabled
+ readonly property color textAccent: "#079CAC" // Accent highlighted values
+
+ // =========================================================================
+ // Typography Hierarchy
+ // =========================================================================
+ readonly property string fontFamily: Qt.application.font.family
+ readonly property string monoFontFamily: "Consolas"
+
+ readonly property int fontSizeSmall: 11
+ readonly property int fontSizeBody: 12
+ readonly property int fontSizeLabel: 13
+ readonly property int fontSizeSubtitle: 14
+ readonly property int fontSizeTitle: 16
+ readonly property int fontSizeHeader: 18
+
+ // =========================================================================
+ // Geometry & Metrics
+ // =========================================================================
+ readonly property int radiusSmall: 4
+ readonly property int radiusMedium: 6
+ readonly property int radiusLarge: 8
+
+ readonly property int controlHeight: 32
+ readonly property int controlHeightSmall: 26
+ readonly property int controlHeightLarge: 38
+
+ readonly property int spacingSmall: 6
+ readonly property int spacingMedium: 10
+ readonly property int spacingLarge: 16
+ readonly property int spacingHuge: 24
+
+ // =========================================================================
+ // Transitions & Animations
+ // =========================================================================
+ readonly property int animFast: 120
+ readonly property int animNormal: 200
+ readonly property int animSlow: 300
+}
diff --git a/src/desktop/qml/components/BatchQueueDrawer.qml b/src/desktop/qml/components/BatchQueueDrawer.qml
new file mode 100644
index 0000000..1107e05
--- /dev/null
+++ b/src/desktop/qml/components/BatchQueueDrawer.qml
@@ -0,0 +1,151 @@
+import QtQuick
+import QtQuick.Dialogs
+import ".."
+import "../controls"
+
+Rectangle {
+ id: drawer
+ property var appBridge: null
+ property var queueModel: null
+ property bool collapsed: false
+ property bool hidden: false
+ property int expandedHeight: appBridge ? appBridge.queueHeight : 190
+
+ height: hidden ? 0 : (collapsed ? 36 : expandedHeight)
+ visible: !hidden
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Behavior on height { NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad } }
+
+ Rectangle {
+ id: header
+ anchors.top: parent.top; anchors.left: parent.left; anchors.right: parent.right
+ height: 36; color: "transparent"
+ Row {
+ anchors.left: parent.left; anchors.leftMargin: 12; anchors.verticalCenter: parent.verticalCenter; spacing: 8
+ Text { text: "Batch Queue"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; font.weight: Font.DemiBold; color: Theme.textPrimary; anchors.verticalCenter: parent.verticalCenter }
+ AppBadge { text: queueModel ? (queueModel.count + " files") : "0 files"; variant: queueModel && queueModel.count > 0 ? "accent" : "neutral"; anchors.verticalCenter: parent.verticalCenter }
+ AppButton { text: "+ Files"; buttonHeight: 22; enabled: appBridge ? appBridge.canModifyQueue : true; onClicked: fileDialog.open() }
+ AppButton { text: "+ Folder"; buttonHeight: 22; enabled: appBridge ? appBridge.canModifyQueue : true; onClicked: folderDialog.open() }
+ AppButton { text: "Clear Done"; buttonHeight: 22; enabled: queueModel && queueModel.count > 0 && (appBridge ? appBridge.canModifyQueue : true); onClicked: { if (appBridge) appBridge.clearCompletedQueueItems() } }
+ AppButton { text: "Clear All"; buttonHeight: 22; enabled: queueModel && queueModel.count > 0 && (appBridge ? appBridge.canModifyQueue : true); onClicked: { if (appBridge) appBridge.clearActiveQueue() } }
+ }
+ AppIconButton {
+ anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter
+ iconSymbol: drawer.collapsed ? "^" : "v"
+ tooltipText: drawer.collapsed ? "Expand queue" : "Collapse queue"
+ onClicked: drawer.collapsed = !drawer.collapsed
+ }
+ Rectangle { anchors.bottom: parent.bottom; anchors.left: parent.left; anchors.right: parent.right; height: 1; color: Theme.borderSubtle }
+ }
+
+ ListView {
+ id: queueList
+ anchors.top: header.bottom; anchors.left: parent.left; anchors.right: parent.right; anchors.bottom: parent.bottom
+ anchors.margins: 8; orientation: ListView.Horizontal; spacing: 8; clip: true
+ visible: !drawer.collapsed; model: drawer.queueModel
+
+ delegate: Rectangle {
+ id: itemCard
+ required property int index
+ required property string fileName
+ required property string inputPath
+ required property string outputPath
+ required property string state
+ required property real progress
+ required property string detail
+ required property real elapsedSeconds
+ required property string inputDimensions
+ required property string outputDimensions
+ required property string thumbnailUrl
+ required property bool selected
+
+ width: Math.min(300, Math.max(250, queueList.width * 0.24))
+ height: queueList.height - 2
+ radius: Theme.radiusMedium
+ color: selected ? Theme.bgSelected : (selectMouse.containsMouse ? Theme.bgCard : Theme.bgInput)
+ border.color: selected ? Theme.accent : (selectMouse.containsMouse ? Theme.borderActive : Theme.borderSubtle)
+ border.width: selected ? 1.5 : 1
+
+ MouseArea {
+ id: selectMouse; anchors.fill: parent; z: 0; hoverEnabled: true
+ enabled: appBridge ? appBridge.canModifyQueue : true
+ cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: { if (appBridge) appBridge.selectQueueItem(itemCard.index) }
+ }
+
+ Row {
+ anchors.fill: parent; anchors.margins: 8; spacing: 8; z: 1
+ Rectangle {
+ width: Math.min(90, parent.height - 4); height: parent.height - 4
+ radius: Theme.radiusSmall; color: Theme.bgBase; clip: true
+ Image { anchors.fill: parent; source: itemCard.thumbnailUrl; visible: itemCard.thumbnailUrl !== ""; fillMode: Image.PreserveAspectCrop; asynchronous: true; cache: false }
+ Text { anchors.centerIn: parent; visible: itemCard.thumbnailUrl === ""; text: "MEDIA"; color: Theme.textMuted; font.family: Theme.monoFontFamily; font.pixelSize: 10 }
+ }
+
+ Column {
+ width: parent.width - Math.min(90, parent.height - 4) - 8; height: parent.height; spacing: 4
+ Row {
+ width: parent.width; spacing: 6
+ Text { width: parent.width - removeBtn.width - 8; text: itemCard.fileName; elide: Text.ElideMiddle; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; font.weight: Font.DemiBold; color: Theme.textPrimary }
+ AppIconButton {
+ id: removeBtn; z: 20; iconSymbol: "x"; buttonSize: 20; showTooltip: false
+ visible: appBridge ? appBridge.canModifyQueue : true
+ onClicked: { if (appBridge) appBridge.removeQueueItem(itemCard.index) }
+ }
+ }
+ Row {
+ spacing: 6
+ AppBadge {
+ text: itemCard.state || "Queued"
+ variant: itemCard.state === "Completed" ? "success" : (itemCard.state === "Failed" ? "danger" : (itemCard.state === "Running" ? "accent" : (itemCard.state === "Cancelled" ? "warning" : "neutral")))
+ }
+ Text { text: itemCard.inputDimensions || ""; font.family: Theme.monoFontFamily; font.pixelSize: 10; color: Theme.textMuted; anchors.verticalCenter: parent.verticalCenter }
+ }
+ Text { width: parent.width; text: itemCard.detail || (itemCard.outputDimensions ? ("Output " + itemCard.outputDimensions) : ""); elide: Text.ElideRight; font.family: Theme.monoFontFamily; font.pixelSize: 10; color: Theme.textMuted }
+ Rectangle {
+ width: parent.width; height: 5; radius: 2.5; color: Theme.bgBase
+ visible: itemCard.state === "Running" || itemCard.state === "Completed" || itemCard.progress > 0
+ Rectangle { height: parent.height; width: parent.width * Math.max(0, Math.min(1, itemCard.progress)); radius: 2.5; color: itemCard.state === "Completed" ? Theme.success : Theme.accent }
+ }
+ Row {
+ width: parent.width; spacing: 8
+ Text { text: itemCard.elapsedSeconds > 0 ? (itemCard.elapsedSeconds.toFixed(1) + "s") : ""; color: Theme.textMuted; font.family: Theme.monoFontFamily; font.pixelSize: 10 }
+ AppButton { text: "Reveal"; buttonHeight: 20; visible: itemCard.outputPath !== ""; onClicked: { if (appBridge) appBridge.openFolder(itemCard.outputPath) } }
+ }
+ }
+ }
+ }
+
+ Text {
+ anchors.centerIn: parent; visible: !queueModel || queueModel.count === 0
+ text: "Queue is empty. Add files, add a folder, or drop media into the viewport."
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textMuted
+ }
+ }
+
+ MouseArea {
+ anchors.left: parent.left; anchors.right: parent.right; anchors.top: parent.top
+ height: 5; z: 100; visible: !drawer.collapsed && !drawer.hidden; cursorShape: Qt.SizeVerCursor
+ property real pressY: 0; property real startHeight: 0
+ onPressed: (mouse) => { pressY = mouse.y; startHeight = drawer.expandedHeight }
+ onPositionChanged: (mouse) => {
+ if (!pressed) return
+ var h = Math.max(120, Math.min(360, startHeight + pressY - mouse.y))
+ drawer.expandedHeight = h
+ if (drawer.appBridge) drawer.appBridge.queueHeight = Math.round(h)
+ }
+ }
+
+ FolderDialog { id: folderDialog; title: "Add Folder to Batch"; onAccepted: { if (appBridge) appBridge.addFiles([selectedFolder.toString()]) } }
+ FileDialog {
+ id: fileDialog; title: "Add Files to Batch"; fileMode: FileDialog.OpenFiles; nameFilters: ["All Media Files (*.*)"]
+ onAccepted: {
+ if (!appBridge || selectedFiles.length === 0) return
+ var urls = []; for (var i = 0; i < selectedFiles.length; i++) urls.push(selectedFiles[i].toString())
+ appBridge.addFiles(urls)
+ }
+ }
+}
diff --git a/src/desktop/qml/components/CompositionCard.qml b/src/desktop/qml/components/CompositionCard.qml
new file mode 100644
index 0000000..dc5becd
--- /dev/null
+++ b/src/desktop/qml/components/CompositionCard.qml
@@ -0,0 +1,142 @@
+import QtQuick
+import QtQuick.Dialogs
+import ".."
+import "../controls"
+
+AppCard {
+ id: root
+
+ property var appBridge: null
+ title: "Composition & Masking"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ // Detail-Only Preset Button
+ Row {
+ width: parent.width
+ spacing: 8
+
+ AppButton {
+ text: "Apply Detail-Only Preset"
+ width: parent.width
+ buttonHeight: 28
+ onClicked: {
+ if (appBridge) appBridge.applyDetailOnly()
+ }
+ }
+ }
+
+ // Sliders
+ AppSlider {
+ width: parent.width
+ label: "NR Color Strength"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.nrColorStrength : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.nrColorStrength = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Tone Preservation"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 0.0
+ value: appBridge ? appBridge.tonePreservation : 0.0
+ onValueModified: (v) => { if (appBridge) appBridge.tonePreservation = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Face / Skin Protection"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 0.0
+ value: appBridge ? appBridge.faceSkinProtection : 0.0
+ onValueModified: (v) => { if (appBridge) appBridge.faceSkinProtection = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Grain Preservation"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 0.0
+ value: appBridge ? appBridge.grainPreservation : 0.0
+ onValueModified: (v) => { if (appBridge) appBridge.grainPreservation = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Mask Feather"
+ unit: "px"
+ from: 0
+ to: 128
+ stepSize: 1
+ precision: 0
+ defaultValue: 0
+ value: appBridge ? appBridge.maskFeather : 0
+ onValueModified: (v) => { if (appBridge) appBridge.maskFeather = Math.round(v) }
+ }
+
+ // Custom NR Mask Box
+ Rectangle {
+ width: parent.width
+ height: 64
+ radius: Theme.radiusMedium
+ color: Theme.bgInput
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Column {
+ anchors.centerIn: parent
+ spacing: 4
+
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 8
+
+ AppButton {
+ text: "Load Custom Mask..."
+ buttonHeight: 24
+ onClicked: maskDialog.open()
+ }
+
+ AppButton {
+ text: "Clear Mask"
+ buttonHeight: 24
+ onClicked: {
+ if (appBridge) appBridge.clearCustomMask()
+ }
+ }
+ }
+
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: appBridge ? appBridge.customMaskStatus : "No mask loaded"
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textMuted
+ }
+ }
+ }
+ }
+
+ FileDialog {
+ id: maskDialog
+ title: "Select Custom NR Mask"
+ nameFilters: ["Image Files (*.png *.jpg *.jpeg *.webp *.tiff *.bmp)", "All Files (*.*)"]
+ onAccepted: {
+ if (appBridge && selectedFile) {
+ appBridge.selectCustomMask(selectedFile.toString())
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/components/DropZone.qml b/src/desktop/qml/components/DropZone.qml
new file mode 100644
index 0000000..e68e5d3
--- /dev/null
+++ b/src/desktop/qml/components/DropZone.qml
@@ -0,0 +1,105 @@
+import QtQuick
+import QtQuick.Dialogs
+import ".."
+import "../controls"
+
+Rectangle {
+ id: root
+
+ property var appBridge: null
+ property string mediaKind: "image/video" // "image", "video", "image/video"
+
+ // No box visuals: transparent background, no border. The whole empty
+ // viewport stays clickable (opens file picker) and droppable.
+ color: dropArea.containsDrag ? Theme.bgSelected : "transparent"
+
+ Behavior on color { ColorAnimation { duration: Theme.animFast } }
+
+ DropArea {
+ id: dropArea
+ anchors.fill: parent
+ onDropped: (drop) => {
+ if (drop.hasUrls && appBridge) {
+ var urls = []
+ for (var i = 0; i < drop.urls.length; i++) {
+ urls.push(drop.urls[i].toString())
+ }
+ appBridge.addFiles(urls)
+ }
+ }
+ }
+
+ MouseArea {
+ id: clickArea
+ anchors.fill: parent
+ hoverEnabled: true
+ cursorShape: Qt.PointingHandCursor
+ onClicked: fileDialog.open()
+ }
+
+ Column {
+ anchors.centerIn: parent
+ spacing: 16
+ width: Math.min(parent.width - 40, 480)
+
+ // Main prompt
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Drag and drop media files here"
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeTitle
+ font.weight: Font.DemiBold
+ color: Theme.textPrimary
+ }
+
+ // Action Buttons
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 12
+
+ AppButton {
+ text: "Choose Files..."
+ variant: "secondary"
+ onClicked: fileDialog.open()
+ }
+
+ AppButton {
+ text: "Choose Folder..."
+ variant: "secondary"
+ onClicked: folderDialog.open()
+ }
+ }
+ }
+
+ FileDialog {
+ id: fileDialog
+ title: "Select Input Media"
+ fileMode: FileDialog.OpenFiles
+ nameFilters: [
+ "All Media Files (*.mp4 *.mkv *.mov *.avi *.webm *.png *.jpg *.jpeg *.webp *.avif *.tiff *.bmp *.cr2 *.nef *.arw *.dng *.heic)",
+ "Video Files (*.mp4 *.mkv *.mov *.avi *.webm)",
+ "Image Files (*.png *.jpg *.jpeg *.webp *.avif *.tiff *.bmp *.cr2 *.nef *.arw *.dng *.heic)",
+ "All Files (*.*)"
+ ]
+ onAccepted: {
+ if (appBridge && selectedFiles.length > 0) {
+ var urls = []
+ for (var i = 0; i < selectedFiles.length; i++) {
+ urls.push(selectedFiles[i].toString())
+ }
+ appBridge.addFiles(urls)
+ }
+ }
+ }
+
+ FolderDialog {
+ id: folderDialog
+ title: "Select Folder Containing Media"
+ onAccepted: {
+ if (appBridge) {
+ var folderPath = selectedFolder.toString()
+ appBridge.addFiles([folderPath])
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/components/HeaderBar.qml b/src/desktop/qml/components/HeaderBar.qml
new file mode 100644
index 0000000..c40a052
--- /dev/null
+++ b/src/desktop/qml/components/HeaderBar.qml
@@ -0,0 +1,157 @@
+import QtQuick
+import QtQuick.Window
+import ".."
+import "../controls"
+
+Rectangle {
+ id: root
+ property var appBridge: null
+ property var windowRef: null
+ readonly property bool compact: width < 1320
+ readonly property bool narrow: width < 1140
+
+ height: 50
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ // QML drag/double-click fallbacks. On Windows the native filter reports
+ // HTCAPTION for empty header space, so the OS owns drag, double-click
+ // maximize and edge snap there (double-handling would fight it). The
+ // fallbacks stay live until hit-test rects are published, so the header
+ // is never dead while the filter is still blind.
+ readonly property bool nativeChrome: windowRef && windowRef.nativeChromeActive === true && windowRef.chromeRectsReady === true
+ MouseArea {
+ anchors.fill: parent; z: 0
+ onPressed: { if (!root.nativeChrome && windowRef && windowRef.visibility !== Window.Maximized && windowRef.visibility !== Window.FullScreen) windowRef.startSystemMove() }
+ onDoubleClicked: {
+ if (!windowRef || root.nativeChrome) return
+ root.toggleMaximize()
+ }
+ }
+
+ // Native maximize/restore (the OS filter supplies a real frame behind the
+ // frameless visuals, so geometry, taskbar and animations are correct).
+ function toggleMaximize() {
+ if (!windowRef) return
+ if (windowRef.visibility === Window.Maximized || windowRef.visibility === Window.FullScreen) windowRef.showNormal()
+ else windowRef.showMaximized()
+ }
+
+ // Window-relative chrome rects (DIPs) for the native hit-test filter, so
+ // snap/min/max/close land exactly on the drawn buttons and tab clicks
+ // still reach QML. Refreshed whenever the header layout changes.
+ function updateChromeRects() {
+ if (!windowRef || !windowRef.contentItem) return
+ var p
+ p = minBtn.mapToItem(windowRef.contentItem, 0, 0)
+ windowRef.minBtnRect = Qt.rect(p.x, p.y, Math.max(minBtn.width, minBtn.implicitWidth), Math.max(minBtn.height, minBtn.implicitHeight))
+ p = maxBtn.mapToItem(windowRef.contentItem, 0, 0)
+ windowRef.maxBtnRect = Qt.rect(p.x, p.y, Math.max(maxBtn.width, maxBtn.implicitWidth), Math.max(maxBtn.height, maxBtn.implicitHeight))
+ p = closeBtn.mapToItem(windowRef.contentItem, 0, 0)
+ windowRef.closeBtnRect = Qt.rect(p.x, p.y, Math.max(closeBtn.width, closeBtn.implicitWidth), Math.max(closeBtn.height, closeBtn.implicitHeight))
+ p = navTabs.mapToItem(windowRef.contentItem, 0, 0)
+ windowRef.navTabsRect = Qt.rect(p.x, p.y, navTabs.width, navTabs.height)
+ windowRef.chromeRectsReady = windowRef.minBtnRect.width > 0 && windowRef.maxBtnRect.width > 0
+ && windowRef.closeBtnRect.width > 0 && windowRef.navTabsRect.width > 0
+ && windowRef.minBtnRect.height > 0 && windowRef.maxBtnRect.height > 0
+ && windowRef.closeBtnRect.height > 0 && windowRef.navTabsRect.height > 0
+ }
+ onWidthChanged: updateChromeRects()
+ Component.onCompleted: Qt.callLater(updateChromeRects)
+ Connections {
+ target: rightArea
+ function onWidthChanged() { root.updateChromeRects() }
+ }
+ Connections {
+ target: navTabs
+ function onWidthChanged() { root.updateChromeRects() }
+ }
+ Connections {
+ target: windowRef
+ function onHeightChanged() { root.updateChromeRects() }
+ function onWidthChanged() { root.updateChromeRects() }
+ // Maximize/restore settles geometry asynchronously; refresh once the
+ // state lands so the native filter never aims at pre-toggle rects.
+ function onVisibilityChanged() { Qt.callLater(root.updateChromeRects) }
+ }
+
+ Row {
+ id: brand; z: 2
+ anchors.left: parent.left; anchors.leftMargin: 12; anchors.verticalCenter: parent.verticalCenter; spacing: 8
+ Image {
+ source: Qt.resolvedUrl("../../../../native (dev)/icon.png")
+ width: 28; height: 28
+ fillMode: Image.PreserveAspectFit
+ smooth: true
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ Text { text: "Visual Enhancer"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeTitle; font.weight: Font.Normal; color: Theme.textPrimary; anchors.verticalCenter: parent.verticalCenter }
+ }
+
+ Row {
+ id: rightArea; z: 2
+ anchors.right: parent.right; anchors.rightMargin: 8; anchors.verticalCenter: parent.verticalCenter; spacing: root.compact ? 6 : 10
+ Row {
+ spacing: 2
+ // Window-chrome buttons: vector icons, no hover tooltips (they sit
+ // at y=0 where an above-anchored popup would clip outside the window).
+ // On Windows the native filter hit-tests these rects (snap flyout,
+ // system press animations); the QML handlers are the fallback path
+ // for the pre-rects blind window only. The nativeChrome guard keeps
+ // single ownership: without it a transition-frame double delivery
+ // would toggle maximize twice (apparent no-op) or fight the OS.
+ // Minimize intentionally has no nativeChrome guard: minimize is
+ // idempotent, and if the OS hit-test claimed the click QML never
+ // receives it — so a click arriving here always means the OS did
+ // NOT claim it (mapping miss) and minimizing is the right action.
+ // maxBtn/closeBtn keep the guard (toggle/close double-delivery).
+ AppIconButton { id: minBtn; iconKind: "min"; showTooltip: false; onClicked: { if (windowRef) windowRef.showMinimized() } }
+ AppIconButton {
+ id: maxBtn
+ iconKind: windowRef && (windowRef.visibility === Window.Maximized || windowRef.visibility === Window.FullScreen) ? "restore" : "max"
+ showTooltip: false
+ onClicked: { if (root.nativeChrome) return; root.toggleMaximize() }
+ }
+ AppIconButton { id: closeBtn; iconKind: "close"; showTooltip: false; hoverColor: Theme.danger; onClicked: { if (root.nativeChrome) return; if (windowRef) windowRef.close() } }
+ }
+ }
+
+ // Menu-style navigation: plain compact text tabs grouped on the left,
+ // active tab shown by accent text color only (no button chrome).
+ Row {
+ id: navTabs; z: 3
+ anchors.left: brand.right; anchors.leftMargin: 16
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 4
+ readonly property var tabs: [
+ { id:"neural-rendering", full:"Neural Rendering", short:"Neural" },
+ { id:"upscale", full:"Upscale", short:"Upscale" },
+ { id:"frame-interpolation", full:"Frame Interpolation", short:"Interp" },
+ { id:"live", full:"Live", short:"Live" },
+ { id:"settings", full:"Settings", short:"Settings" },
+ { id:"help", full:"Help", short:"Help" }
+ ]
+ Repeater {
+ model: navTabs.tabs
+ Item {
+ id: tabBtn
+ height: 28
+ width: tabLabel.implicitWidth + 20
+ readonly property bool isActive: appBridge ? appBridge.activeTab === modelData.id : false
+ Text {
+ id: tabLabel
+ anchors.centerIn: parent
+ text: root.compact ? modelData.short : modelData.full
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel
+ font.weight: Font.Normal
+ color: tabBtn.isActive ? Theme.accent : (tabMouse.containsMouse ? Theme.textPrimary : Theme.textSecondary)
+ }
+ MouseArea {
+ id: tabMouse; anchors.fill: parent; hoverEnabled: true; cursorShape: Qt.PointingHandCursor
+ onClicked: { if (appBridge) appBridge.activeTab = modelData.id }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/components/MediaViewport.qml b/src/desktop/qml/components/MediaViewport.qml
new file mode 100644
index 0000000..a672ef6
--- /dev/null
+++ b/src/desktop/qml/components/MediaViewport.qml
@@ -0,0 +1,773 @@
+import QtQuick
+import QtQuick.Window
+import QtQuick.Controls as QQC2
+import QtMultimedia
+import ".."
+import "../controls"
+
+Rectangle {
+ id: viewport
+ property var appBridge: null
+ property string viewMode: "split"
+ property real zoomFactor: 1.0
+ property real panX: 0
+ property real panY: 0
+ // Default to Input so a freshly finished single-frame preview never
+ // hijacks the timeline (output is ~1 frame -> 00:00/00:00 + EOS black).
+ property bool showVideoOutput: false
+ // 2-Up comparison: input + output side by side with one shared timeline.
+ property bool videoTwoUp: false
+ property string playerError: ""
+ // Hold-to-peek state: press-and-hold on the video shows the enhanced
+ // preview frame; release restores the original. Pure momentary - the
+ // Input/Output tabs remain the sticky switch.
+ property bool peekActive: false
+ property bool peekPrevShowOutput: false
+ property bool peekWasPlaying: false
+
+ color: Theme.bgBase
+ clip: true
+ focus: true
+
+ readonly property bool hasInput: appBridge ? appBridge.previewInputUrl !== "" : false
+ readonly property bool hasOutput: appBridge ? appBridge.hasOutputPreview : false
+ readonly property bool isVideo: appBridge ? (appBridge.previewInputIsVideo || appBridge.previewOutputIsVideo) : false
+ readonly property bool showingOutput: viewport.showVideoOutput && viewport.hasOutput && appBridge && appBridge.previewOutputIsVideo
+ readonly property bool showingTwoUp: viewport.videoTwoUp && viewport.isVideo && viewport.hasOutput && appBridge && appBridge.previewOutputIsVideo
+ // Output mirror gate: input masters the timeline in every layout while a
+ // video preview exists; the output pane follows clamped to its duration.
+ readonly property bool mirrorOutput: viewport.isVideo && viewport.hasOutput && appBridge && appBridge.previewOutputIsVideo
+ // Scrub-realtime eligibility: Realtime on + an existing video preview, in
+ // any layout. The transport always masters the input timeline (even on
+ // the Output tab), so every scrub addresses input frames and refreshes
+ // the preview at the settled playhead. The Preview button stays the
+ // manual render path. Frame Interpolation is manual-only ("Preview"):
+ // it never scrub-refreshes even when the global switch is on.
+ readonly property bool isFITab: appBridge && appBridge.activeTab === "frame-interpolation"
+ readonly property bool scrubRefreshEligible: appBridge && appBridge.autoPreviewEnabled && !viewport.isFITab && viewport.hasOutput && appBridge.previewOutputIsVideo
+ // FI pre-rendered span containing timeline second sec, newest first wins
+ // so re-rendered spans resolve to the latest clip. Null when outside all
+ // green spans (or when ranges are unavailable).
+ function fiRangeAt(sec) {
+ if (!viewport.isFITab || !appBridge || !appBridge.previewRenderedRanges) return null
+ var rs = appBridge.previewRenderedRanges
+ for (var i = rs.length - 1; i >= 0; i--) {
+ var r = rs[i]
+ if (sec >= r.start && sec < r.end) return r
+ }
+ return null
+ }
+ // Range under the live playhead + the clip the output pane should show
+ // on the FI tab. Swap discipline (this is what keeps playback smooth):
+ // a VISIBLE player is never re-pointed. fiPinned is assigned only while
+ // hidden (forward pre-warm), on settled pause/seek snaps, or in 2-Up
+ // exact-follow. Boundary flips therefore land on an already-decoding
+ // player: blue > green > blue = input-as-output > processed > input.
+ property var fiPinned: null
+ // Pre-warm horizon (seconds): while playing forward hidden, preload the
+ // clip of the span starting inside this window. Tunable; ~1s covers a
+ // cold demux+decode spin-up with margin, costing ~1s of double decode.
+ property real fiLookaheadSec: 1.0
+ // Last tick position: tells continuous play apart from seek jumps.
+ property real fiLastPosMs: -1
+ function fiPinTo(r) {
+ var au = (viewport.fiPinned && viewport.fiPinned.url) ? viewport.fiPinned.url : ""
+ var bu = (r && r.url) ? r.url : ""
+ if (au !== bu) viewport.fiPinned = r
+ }
+ readonly property string fiOutputUrl: {
+ if (!viewport.isFITab || !appBridge) return ""
+ if (viewport.fiPinned && viewport.fiPinned.url) return viewport.fiPinned.url
+ return appBridge.previewInputIsVideo ? appBridge.previewInputUrl : ""
+ }
+ readonly property var activePlayer: showingOutput ? outputPlayer : inputPlayer
+ readonly property real playheadMs: viewport.isVideo ? inputPlayer.position : (activePlayer ? activePlayer.position : 0)
+ readonly property real inputDurationMs: appBridge ? appBridge.sourceDuration * 1000.0 : 0
+ readonly property real inputFps: appBridge && appBridge.sourceFps > 0 ? appBridge.sourceFps : 30.0
+ readonly property bool inputReady: inputPlayer.duration > 0 && (inputPlayer.mediaStatus === MediaPlayer.LoadedMedia || inputPlayer.mediaStatus === MediaPlayer.BufferedMedia)
+ readonly property bool outputReady: outputPlayer.duration > 0 && (outputPlayer.mediaStatus === MediaPlayer.LoadedMedia || outputPlayer.mediaStatus === MediaPlayer.BufferedMedia)
+ readonly property bool activeReady: showingOutput ? outputReady : inputReady
+ readonly property int sourceWidth: appBridge && appBridge.sourceWidth > 0 ? appBridge.sourceWidth : 1
+ readonly property int sourceHeight: appBridge && appBridge.sourceHeight > 0 ? appBridge.sourceHeight : 1
+ readonly property real fitScale: Math.max(0.0001, Math.min(canvas.width / sourceWidth, canvas.height / sourceHeight))
+ readonly property real displayScale: fitScale * zoomFactor
+
+ function resetPan() { panX = 0; panY = 0 }
+ function fitToWindow() { zoomFactor = 1.0; resetPan() }
+ function actualPixels() {
+ var logicalScale = 1.0 / Math.max(1.0, Screen.devicePixelRatio)
+ zoomFactor = Math.max(0.05, Math.min(32.0, logicalScale / fitScale))
+ resetPan()
+ }
+ function clampPan() {
+ var overX = Math.max(0, sourceWidth * displayScale - canvas.width) / 2
+ var overY = Math.max(0, sourceHeight * displayScale - canvas.height) / 2
+ panX = Math.max(-overX, Math.min(overX, panX))
+ panY = Math.max(-overY, Math.min(overY, panY))
+ }
+ function changeZoom(multiplier) {
+ zoomFactor = Math.max(0.05, Math.min(32.0, zoomFactor * multiplier))
+ Qt.callLater(clampPan)
+ }
+
+ onSourceWidthChanged: fitToWindow()
+ onSourceHeightChanged: fitToWindow()
+
+ // Previews always land in place: the viewer stays on whichever tab
+ // opened the render (Input, Output, or 2-Up). No tab is ever switched
+ // programmatically - only the user (tabs) or a hold-release (peek) does.
+ //
+ // Same-frame sync needs no seeking: the transport masters the input
+ // timeline in every layout, so Input/Output/2-Up always share one
+ // playhead and the Input tab shows the scrubbed original by construction.
+
+ AudioOutput { id: mediaAudio; volume: 0.8; muted: false }
+ // Dedicated input player: transport/scrubbing always survives a preview.
+ MediaPlayer {
+ id: inputPlayer
+ objectName: "inputPlayer"
+ source: viewport.isVideo && appBridge && appBridge.previewInputIsVideo ? appBridge.previewInputUrl : ""
+ audioOutput: mediaAudio
+ videoOutput: inputSurface
+ // Keep the last frame on screen instead of clearing to black at EOS.
+ loops: MediaPlayer.Infinite
+ property bool primePending: false
+ onSourceChanged: {
+ viewport.playerError = ""
+ viewport.peekActive = false
+ viewport.peekWasPlaying = false
+ pause()
+ // position assignment before media is loaded is ignored; the
+ // priming handler below re-applies it once Loaded/Buffered.
+ position = 0
+ primePending = source !== ""
+ }
+ onMediaStatusChanged: (status) => {
+ if ((status === MediaPlayer.LoadedMedia || status === MediaPlayer.BufferedMedia) && primePending) {
+ primePending = false
+ // Play-then-pause forces WMF to paint the first frame; a bare
+ // pause()/position=0 leaves VideoOutput black on Windows.
+ play()
+ pause()
+ position = 0
+ }
+ if (status === MediaPlayer.EndOfMedia && !viewport.showingOutput) {
+ // Infinite loops already rewinds; keep position sane for UI.
+ }
+ if (status === MediaPlayer.InvalidMedia) {
+ viewport.playerError = inputPlayer.errorString !== "" ? inputPlayer.errorString : "Unsupported video format."
+ }
+ }
+ onErrorOccurred: (error, errorString) => {
+ if (error !== MediaPlayer.NoError)
+ viewport.playerError = errorString
+ console.warn("inputPlayer error:", error, errorString, "source:", source)
+ }
+ onDurationChanged: (d) => { console.log("inputPlayer duration:", d, "source:", source) }
+ // Output mirror: input is the master timeline in every layout; the
+ // output follows clamped to its own (usually single-frame) duration.
+ // One-directional so no feedback loop is possible. On the FI tab the
+ // playhead is mapped into the green span's own clip instead, and
+ // while playing the viewer auto-shows processed footage inside green
+ // spans and the original outside (paused tabs stay manual; peek and
+ // 2-Up are never overridden).
+ onPositionChanged: (pos) => {
+ if (viewport.isFITab && viewport.mirrorOutput) {
+ var r = viewport.fiRangeAt(pos / 1000.0)
+ var inputPlaying = inputPlayer.playbackState === MediaPlayer.PlayingState
+ var jump = viewport.fiLastPosMs < 0 || Math.abs(pos - viewport.fiLastPosMs) > 800
+ // Pinned clip went stale (ranges cleared by a settings tweak
+ // mid-play): drop it so the next rule re-pins exact.
+ if (viewport.fiPinned && viewport.fiPinned.url && appBridge && appBridge.previewRenderedRanges) {
+ var alive = false
+ var rs0 = appBridge.previewRenderedRanges
+ for (var k = 0; k < rs0.length; k++) {
+ if (rs0[k].url === viewport.fiPinned.url) { alive = true; break }
+ }
+ if (!alive) viewport.fiPinned = null
+ }
+ // Pinned range snapshot for this tick (null = blue / input).
+ var pr = (viewport.fiPinned && viewport.fiPinned.start !== undefined) ? viewport.fiPinned : null
+ var sec = pos / 1000.0
+ // Pin discipline: a visible player is never re-pointed, so no
+ // reload can ever stall visible playback — except rolling
+ // forward across a span-to-span hop, where the pinned clip no
+ // longer covers the playhead (steady spans never hit this).
+ if (viewport.videoTwoUp) {
+ viewport.fiPinTo(r)
+ } else if (r && viewport.showingOutput && (!pr || sec < pr.start || sec >= pr.end)) {
+ viewport.fiPinTo(r)
+ } else if (!inputPlaying) {
+ viewport.fiPinTo(r) // settled pause: exact inspection frame
+ } else if (jump) {
+ // Seek while playing: prefer the lookahead span so a jump
+ // landing just before green doesn't reload twice in a row.
+ var wj = viewport.fiRangeAt(sec + viewport.fiLookaheadSec)
+ viewport.fiPinTo(wj ? wj : r)
+ } else if (!viewport.showingOutput) {
+ var w = viewport.fiRangeAt(sec + viewport.fiLookaheadSec)
+ if (w) viewport.fiPinTo(w) // hidden pre-warm only
+ }
+ // Pin may have moved above; refresh the snapshot for mirror
+ // and pre-roll below.
+ pr = (viewport.fiPinned && viewport.fiPinned.start !== undefined) ? viewport.fiPinned : null
+ // Auto-show flip at the exact boundary (both panes hot).
+ if (inputPlaying && !viewport.peekActive && !viewport.videoTwoUp) {
+ var want = (r !== null)
+ if (viewport.showVideoOutput !== want)
+ viewport.showVideoOutput = want
+ }
+ // Mirror + run state. The mirror follows the PINNED clip (not
+ // just the current span): during approach the future clip is
+ // held at its first frame, so the entry flip lands on a hot,
+ // in-sync player instead of cold-seeking from the clip end
+ // (that cold seek was the ~200ms entry flicker). Output always
+ // carries timeline footage, so it simply tracks the input;
+ // hidden + unneeded decode is shed by pausing.
+ if (outputPlayer.duration > 0) {
+ var base = pr ? (pos - pr.start * 1000.0) : pos
+ if (base < 0) {
+ // Approach hold: first frame stays painted. Seek back
+ // only while parked — never yank a pre-rolling clip
+ // mid spin-up (it free-runs its final stretch).
+ if (outputPlayer.playbackState !== MediaPlayer.PlayingState
+ && Math.abs(outputPlayer.position) > 120)
+ outputPlayer.position = 0
+ } else {
+ var tgt = Math.max(0, Math.min(outputPlayer.duration, base))
+ if (Math.abs(outputPlayer.position - tgt) > 120)
+ outputPlayer.position = tgt
+ }
+ }
+ // Pre-roll: run the hidden clip through the final stretch
+ // before its span so entry needs zero spin-up. Window matches
+ // the mirror deadband, so free-run drift never trips a
+ // correction seek; the clip was primed during pre-warm, so
+ // play() resumes in a frame or two.
+ var distStart = pr ? (pr.start * 1000.0 - pos) : 1e18
+ var preRoll = inputPlaying && !viewport.showingOutput && !viewport.videoTwoUp
+ && pr && distStart >= 0 && distStart < 120
+ var shouldRun = inputPlaying && (viewport.showingOutput || viewport.showingTwoUp || preRoll)
+ if (shouldRun && outputPlayer.playbackState !== MediaPlayer.PlayingState)
+ outputPlayer.play()
+ else if (!shouldRun && outputPlayer.playbackState === MediaPlayer.PlayingState)
+ outputPlayer.pause()
+ viewport.fiLastPosMs = pos
+ return
+ }
+ if (!viewport.mirrorOutput || outputPlayer.duration <= 0) return
+ var target = Math.max(0, Math.min(outputPlayer.duration, pos))
+ if (Math.abs(outputPlayer.position - target) > 120)
+ outputPlayer.position = target
+ }
+ onPlaybackStateChanged: (state) => {
+ // Parked: remember the frame so realtime auto-renders (settings
+ // tweaks, menu action) preview it instead of frame 1. Independent
+ // of mirroring so it also works before any output exists.
+ if (state !== MediaPlayer.PlayingState && appBridge && viewport.isVideo)
+ appBridge.notePlayheadMs(inputPlayer.position)
+ if (!viewport.mirrorOutput) return
+ // Output always carries timeline-meaningful footage (on FI the
+ // original outside green, the range clip inside), so it simply
+ // runs/pauses with the input on every tab. On FI pause the pin
+ // snaps exact (ticks don't fire while paused, so the Output tab
+ // inspects the settled frame, not a stale pre-warmed clip).
+ if (viewport.isFITab && state !== MediaPlayer.PlayingState)
+ viewport.fiPinTo(viewport.fiRangeAt(viewport.playheadMs / 1000.0))
+ if (state === MediaPlayer.PlayingState) outputPlayer.play()
+ else outputPlayer.pause()
+ }
+ }
+ // Dedicated preview-output player (usually a single enhanced frame).
+ // Independent from inputPlayer so stepping/scrubbing the source is never
+ // clamped to the 1-frame preview duration. On the FI tab the source
+ // follows the pinned span (pre-warmed up to fiLookaheadSec ahead while
+ // hidden, snapped exact on pause/seek); everywhere else it is the
+ // latest preview output. FI range clips play once (loops: 1) so a span
+ // never replays at its end — playback continues with the original.
+ MediaPlayer {
+ id: outputPlayer
+ objectName: "outputPlayer"
+ source: viewport.isVideo && appBridge ? (viewport.isFITab ? viewport.fiOutputUrl : (appBridge.previewOutputIsVideo ? appBridge.previewOutputUrl : "")) : ""
+ audioOutput: mediaAudio
+ videoOutput: outputSurface
+ loops: viewport.isFITab ? 1 : MediaPlayer.Infinite
+ property bool primePending: false
+ onSourceChanged: {
+ pause()
+ position = 0
+ primePending = source !== ""
+ }
+ onMediaStatusChanged: (status) => {
+ if ((status === MediaPlayer.LoadedMedia || status === MediaPlayer.BufferedMedia) && primePending) {
+ primePending = false
+ play()
+ pause()
+ position = 0
+ }
+ if (status === MediaPlayer.InvalidMedia && viewport.showingOutput) {
+ viewport.playerError = errorString !== "" ? errorString : "Preview output is not playable."
+ }
+ }
+ onErrorOccurred: (error, errorString) => {
+ if (error !== MediaPlayer.NoError && viewport.showingOutput)
+ viewport.playerError = errorString
+ console.warn("outputPlayer error:", error, errorString, "source:", source)
+ }
+ }
+
+ Keys.onPressed: (event) => {
+ var transportPlayer = videoTransport.player
+ if (viewport.isVideo && videoTransport.visible && transportPlayer) {
+ if (event.key === Qt.Key_Space) {
+ if (transportPlayer.playbackState === MediaPlayer.PlayingState) transportPlayer.pause(); else transportPlayer.play()
+ event.accepted = true
+ } else if (event.key === Qt.Key_Left) { videoTransport.stepFrames(-1); event.accepted = true }
+ else if (event.key === Qt.Key_Right) { videoTransport.stepFrames(1); event.accepted = true }
+ } else {
+ if (event.key === Qt.Key_0) { viewport.fitToWindow(); event.accepted = true }
+ if (event.key === Qt.Key_1) { viewport.actualPixels(); event.accepted = true }
+ }
+ }
+
+ Rectangle {
+ id: toolbar
+ z: 20
+ anchors.top: parent.top; anchors.left: parent.left; anchors.right: parent.right
+ height: 42; visible: viewport.hasInput
+ color: "#E014171D"; border.color: Theme.borderSubtle
+
+ Row {
+ anchors.left: parent.left; anchors.leftMargin: 10; anchors.verticalCenter: parent.verticalCenter; spacing: 8
+ AppSegmentedControl {
+ visible: !viewport.isVideo
+ width: 250
+ model: [{label:"Split",value:"split"},{label:"2-Up",value:"sideBySide"},{label:"Output",value:"single"}]
+ currentValue: viewport.viewMode
+ onActivated: (v) => viewport.viewMode = v
+ }
+ AppSegmentedControl {
+ visible: viewport.isVideo && viewport.hasOutput && appBridge && appBridge.previewOutputIsVideo
+ width: 225
+ model: [{label:"Input",value:"input"},{label:"Output",value:"output"},{label:"2-Up",value:"twoup"}]
+ currentValue: viewport.videoTwoUp ? "twoup" : (viewport.showVideoOutput ? "output" : "input")
+ onActivated: (v) => {
+ if (v === "twoup") {
+ viewport.videoTwoUp = true
+ } else {
+ viewport.videoTwoUp = false
+ viewport.showVideoOutput = (v === "output")
+ }
+ }
+ }
+ Text {
+ width: Math.max(120, toolbar.width - 620)
+ text: appBridge ? appBridge.inputInfoText + (appBridge.hasOutputPreview ? " -> " + appBridge.outputInfoText : "") : ""
+ elide: Text.ElideMiddle; color: Theme.textSecondary
+ font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+
+ Row {
+ visible: !viewport.isVideo
+ anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter; spacing: 6
+ AppButton { text: "Fit"; buttonHeight: 26; width: 48; onClicked: viewport.fitToWindow() }
+ AppButton { text: "100%"; buttonHeight: 26; width: 54; onClicked: viewport.actualPixels() }
+ Text { text: Math.round(viewport.displayScale * Math.max(1.0, Screen.devicePixelRatio) * 100) + "%"; color: Theme.textPrimary; font.family: Theme.monoFontFamily; anchors.verticalCenter: parent.verticalCenter }
+ AppIconButton { iconSymbol: "-"; showTooltip: false; onClicked: viewport.changeZoom(0.8) }
+ AppIconButton { iconSymbol: "+"; showTooltip: false; onClicked: viewport.changeZoom(1.25) }
+ AppIconButton {
+ iconSymbol: appBridge && appBridge.focusPreview ? "[X]" : "[ ]"
+ showTooltip: false
+ onClicked: { if (appBridge) appBridge.focusPreview = !appBridge.focusPreview }
+ }
+ }
+ }
+
+ DropZone { anchors.fill: parent; visible: !viewport.hasInput; appBridge: viewport.appBridge }
+
+ Item {
+ id: canvas
+ anchors.top: toolbar.bottom; anchors.left: parent.left; anchors.right: parent.right
+ anchors.bottom: videoTransport.visible ? videoTransport.top : parent.bottom
+ visible: viewport.hasInput; clip: true
+
+ // ffmpeg-extracted poster behind the INPUT surface only: guarantees a
+ // visible first frame even while WMF is loading or on decode error.
+ // Never shown under Output/2-Up panes - a frameless VideoOutput is
+ // transparent, so the fullscreen input poster would bleed through as
+ // a "big image under" artifact on every preview swap (~100 ms).
+ Image {
+ id: videoPoster
+ objectName: "videoPoster"
+ anchors.fill: parent
+ visible: viewport.isVideo && !viewport.showingOutput && !viewport.showingTwoUp && !viewport.inputReady
+ source: appBridge ? appBridge.previewPosterUrl : ""
+ fillMode: Image.PreserveAspectFit; cache: false; asynchronous: true; smooth: true
+ }
+
+ // Single-pane surfaces double as 2-Up panes: only their geometry
+ // changes, so players never re-link outputs (no repaint stall).
+ VideoOutput {
+ id: inputSurface
+ objectName: "inputSurface"
+ anchors.top: parent.top; anchors.bottom: parent.bottom; anchors.left: parent.left
+ width: viewport.showingTwoUp ? (parent.width - 4) / 2 : parent.width
+ visible: viewport.isVideo && (!viewport.showingOutput || viewport.showingTwoUp)
+ fillMode: VideoOutput.PreserveAspectFit
+ }
+ VideoOutput {
+ id: outputSurface
+ objectName: "outputSurface"
+ anchors.top: parent.top; anchors.bottom: parent.bottom; anchors.right: parent.right
+ width: viewport.showingTwoUp ? (parent.width - 4) / 2 : parent.width
+ visible: viewport.isVideo && (viewport.showingOutput || viewport.showingTwoUp)
+ fillMode: VideoOutput.PreserveAspectFit
+ }
+
+ // 2-Up comparison chrome: pane badges + output loading placeholder.
+ // Mirrors the image side-by-side pattern.
+ AppBadge {
+ anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10
+ visible: viewport.showingTwoUp; text: "INPUT"
+ }
+ AppBadge {
+ anchors.right: parent.right; anchors.top: parent.top; anchors.margins: 10
+ visible: viewport.showingTwoUp
+ text: viewport.outputReady ? ("OUTPUT" + (appBridge && appBridge.previewSourceFrame > 0 ? " f" + appBridge.previewSourceFrame : "")) : "NO OUTPUT"
+ variant: viewport.outputReady ? "accent" : "neutral"
+ }
+ Text {
+ anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter
+ width: (parent.width - 4) / 2; horizontalAlignment: Text.AlignHCenter
+ visible: viewport.showingTwoUp && !viewport.outputReady
+ text: "Loading preview..."
+ color: Theme.textMuted; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall
+ }
+
+ // Single-Output swap veil: the output surface is transparent until the
+ // new clip primes, so dim it with a label instead of flashing the
+ // (wrong) input poster underneath.
+ Rectangle {
+ anchors.fill: parent; z: 2
+ objectName: "outputLoadingVeil"
+ visible: viewport.isVideo && viewport.showingOutput && !viewport.showingTwoUp && !viewport.outputReady
+ color: "#AA0B0D12"
+ Text {
+ anchors.centerIn: parent
+ text: "Loading preview..."
+ color: Theme.textMuted; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall
+ }
+ }
+
+ // Hold-to-peek: press-and-hold on the video shows the enhanced
+ // preview frame while held, release restores the original input.
+ // Frozen (both players paused) for frame-accurate A/B comparison.
+ MouseArea {
+ id: peekArea
+ anchors.fill: parent
+ z: 4
+ visible: viewport.isVideo && viewport.hasOutput && appBridge && appBridge.previewOutputIsVideo && !viewport.showingTwoUp
+ acceptedButtons: Qt.LeftButton
+ hoverEnabled: true
+ cursorShape: containsMouse ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onPressed: (mouse) => {
+ viewport.peekPrevShowOutput = viewport.showVideoOutput
+ viewport.peekWasPlaying = viewport.activePlayer && viewport.activePlayer.playbackState === MediaPlayer.PlayingState
+ inputPlayer.pause()
+ outputPlayer.pause()
+ viewport.showVideoOutput = true
+ viewport.peekActive = true
+ viewport.forceActiveFocus()
+ mouse.accepted = true
+ }
+ function endPeek(restorePlayback) {
+ if (!viewport.peekActive) return
+ viewport.peekActive = false
+ viewport.showVideoOutput = viewport.peekPrevShowOutput
+ if (restorePlayback && viewport.peekWasPlaying && viewport.activePlayer)
+ viewport.activePlayer.play()
+ viewport.peekWasPlaying = false
+ }
+ onReleased: endPeek(true)
+ onCanceled: endPeek(true)
+ }
+
+ // Peek badge + highlight while held.
+ Rectangle {
+ z: 6
+ anchors.top: parent.top; anchors.topMargin: 10
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: viewport.peekActive && viewport.showingOutput
+ width: peekLabel.width + 24; height: 28; radius: 14
+ color: "#CC14B8A6"; border.color: Theme.accent; border.width: 1
+ Text {
+ id: peekLabel
+ anchors.centerIn: parent
+ text: "PREVIEW"
+ color: "white"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; font.bold: true
+ }
+ }
+ Rectangle {
+ anchors.fill: parent; z: 3
+ visible: viewport.peekActive && viewport.showingOutput
+ color: "transparent"; border.color: Theme.accent; border.width: 2
+ }
+
+ // Decode-error overlay: poster stays visible underneath.
+ Rectangle {
+ anchors.fill: parent
+ visible: viewport.isVideo && viewport.playerError !== "" && !viewport.activeReady
+ color: "#AA000000"; z: 5
+ Text {
+ anchors.centerIn: parent; width: parent.width - 40
+ horizontalAlignment: Text.AlignHCenter; wrapMode: Text.Wrap
+ text: "Video cannot be played natively:\n" + viewport.playerError + "\nPoster frame shown. Scrub with < > or open the file externally."
+ color: Theme.warning; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall
+ }
+ }
+
+ Item {
+ id: imageLayer
+ anchors.fill: parent
+ visible: !viewport.isVideo && viewport.viewMode !== "sideBySide"
+
+ Item {
+ id: mediaFrame
+ z: 1
+ width: viewport.sourceWidth; height: viewport.sourceHeight
+ transformOrigin: Item.TopLeft
+ scale: viewport.displayScale
+ x: (imageLayer.width - width * scale) / 2 + viewport.panX
+ y: (imageLayer.height - height * scale) / 2 + viewport.panY
+
+ Image {
+ anchors.fill: parent
+ source: appBridge ? appBridge.previewInputUrl : ""
+ fillMode: Image.Stretch; cache: false; asynchronous: true; smooth: true
+ }
+
+ Item {
+ anchors.fill: parent
+ visible: viewport.hasOutput && viewport.viewMode === "split"
+ clip: true
+ Item {
+ x: parent.width * (appBridge ? appBridge.splitPosition : 0.5)
+ width: parent.width - x; height: parent.height; clip: true
+ Image {
+ x: -parent.x; width: mediaFrame.width; height: mediaFrame.height
+ source: appBridge ? appBridge.previewOutputUrl : ""
+ fillMode: Image.Stretch; cache: false; smooth: true
+ }
+ }
+ Rectangle {
+ id: divider
+ x: parent.width * (appBridge ? appBridge.splitPosition : 0.5) - 0.75 / Math.max(0.001, mediaFrame.scale)
+ width: 1.5 / Math.max(0.001, mediaFrame.scale); height: parent.height; color: Theme.accent; z: 4
+ MouseArea {
+ id: splitMouse
+ anchors.fill: parent; anchors.margins: -10 / Math.max(0.001, mediaFrame.scale); cursorShape: Qt.SplitHCursor; hoverEnabled: true
+ function setSplit(mx, my) {
+ if (!appBridge) return
+ var p = splitMouse.mapToItem(divider.parent, mx, my)
+ var w = divider.parent.width
+ if (w > 0) appBridge.splitPosition = Math.max(0.02, Math.min(0.98, p.x / w))
+ }
+ onPressed: (m) => setSplit(m.x, m.y)
+ onPositionChanged: (m) => {
+ if (pressed) setSplit(m.x, m.y)
+ }
+ }
+ }
+ }
+
+ Image {
+ anchors.fill: parent
+ visible: viewport.hasOutput && viewport.viewMode === "single"
+ source: appBridge ? appBridge.previewOutputUrl : ""
+ fillMode: Image.Stretch; cache: false; smooth: true
+ }
+ }
+
+ MouseArea {
+ id: panArea
+ z: 0
+ anchors.fill: parent; acceptedButtons: Qt.LeftButton | Qt.MiddleButton
+ cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor
+ property real pressX: 0; property real pressY: 0; property real originPanX: 0; property real originPanY: 0
+ onPressed: (mouse) => { pressX = mouse.x; pressY = mouse.y; originPanX = viewport.panX; originPanY = viewport.panY; viewport.forceActiveFocus() }
+ onPositionChanged: (mouse) => {
+ if (!pressed) return
+ viewport.panX = originPanX + mouse.x - pressX
+ viewport.panY = originPanY + mouse.y - pressY
+ viewport.clampPan()
+ }
+ onDoubleClicked: viewport.fitToWindow()
+ onWheel: (wheel) => { viewport.changeZoom(wheel.angleDelta.y > 0 ? 1.12 : 0.89); wheel.accepted = true }
+ }
+ }
+
+ Row {
+ anchors.fill: parent; spacing: 4
+ visible: !viewport.isVideo && viewport.viewMode === "sideBySide"
+ Rectangle {
+ width: (parent.width - 4) / 2; height: parent.height; color: Theme.bgBase
+ Image { anchors.fill: parent; anchors.margins: 4; source: appBridge ? appBridge.previewInputUrl : ""; fillMode: Image.PreserveAspectFit; cache: false }
+ AppBadge { anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10; text: "INPUT" }
+ }
+ Rectangle {
+ width: (parent.width - 4) / 2; height: parent.height; color: Theme.bgBase
+ Image { anchors.fill: parent; anchors.margins: 4; source: appBridge ? appBridge.previewOutputUrl : ""; fillMode: Image.PreserveAspectFit; cache: false }
+ AppBadge { anchors.left: parent.left; anchors.top: parent.top; anchors.margins: 10; text: viewport.hasOutput ? "OUTPUT" : "NO OUTPUT"; variant: viewport.hasOutput ? "accent" : "neutral" }
+ }
+ }
+
+ // Right-click catcher for the preview context menu. RightButton ONLY
+ // and stacked BELOW the interactive layers, so hover/cursor behavior
+ // (split divider, pan hand, peek pointer) is untouched: none of the
+ // layers above accept RightButton, so those presses fall through to
+ // here. Inert when empty so DropZone keeps its own behavior.
+ MouseArea {
+ id: rightClickLayer
+ anchors.fill: parent
+ z: -1
+ enabled: viewport.hasInput
+ acceptedButtons: Qt.RightButton
+ hoverEnabled: false
+ onPressed: (mouse) => {
+ if (mouse.button === Qt.RightButton && viewport.hasInput) {
+ previewMenu.popup(rightClickLayer, mouse.x, mouse.y)
+ mouse.accepted = true
+ }
+ }
+ }
+ }
+
+ VideoTransportBar {
+ id: videoTransport
+ objectName: "videoTransport"
+ anchors.left: parent.left; anchors.right: parent.right; anchors.bottom: parent.bottom
+ visible: viewport.hasInput && viewport.isVideo
+ // The transport always masters the input timeline (even on the Output
+ // tab); the output pane mirrors it. Scrubbing anywhere addresses
+ // input frames, so refreshes can never clobber the preview.
+ player: inputPlayer
+ frameRate: viewport.inputFps
+ fallbackDurationMs: viewport.inputDurationMs
+ fallbackFrameRate: viewport.inputFps
+ // Green pre-rendered spans (FI "Preview" only; [] elsewhere).
+ renderedRanges: viewport.isFITab && appBridge ? appBridge.previewRenderedRanges : []
+ onUserScrubbed: (posMs) => {
+ appBridge.notePlayheadMs(posMs)
+ if (viewport.scrubRefreshEligible) appBridge.schedulePreviewAt(posMs)
+ }
+ }
+
+ // Status readout, bottom-left. Idle "Ready." is hidden when empty;
+ // any other status still shows, and everything shows once loaded.
+ Row {
+ id: statusOverlay
+ z: 30
+ visible: viewport.hasInput || (appBridge && appBridge.statusMessage !== "Ready.")
+ anchors.left: parent.left; anchors.leftMargin: 10
+ anchors.bottom: videoTransport.visible ? videoTransport.top : parent.bottom
+ anchors.bottomMargin: 8
+ spacing: 8
+ Rectangle {
+ width: 8; height: 8; radius: 4; anchors.verticalCenter: parent.verticalCenter
+ color: {
+ if (!appBridge) return Theme.textMuted
+ if (appBridge.runtimeState === "Failed") return Theme.danger
+ if (appBridge.operationState === "LiveRunning") return Theme.danger
+ if (appBridge.isProcessing) return Theme.accent
+ if (appBridge.runtimeState === "Initializing") return Theme.warning
+ return Theme.success
+ }
+ }
+ Text {
+ width: Math.min(520, viewport.width * 0.6); elide: Text.ElideRight
+ text: appBridge ? appBridge.statusMessage : "Ready."
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textSecondary; anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+
+ Rectangle {
+ anchors.centerIn: parent
+ visible: appBridge && (appBridge.operationState === "PreviewPreparing" || appBridge.operationState === "PreviewRunning" || appBridge.operationState === "LoadingMetadata")
+ width: Math.min(parent.width - 40, 300); height: 64; radius: Theme.radiusLarge
+ color: Theme.bgSurface; border.color: Theme.accent
+ Text { anchors.centerIn: parent; text: appBridge ? appBridge.statusMessage : "Working..."; color: Theme.textPrimary; font.family: Theme.fontFamily; elide: Text.ElideRight; width: parent.width - 24; horizontalAlignment: Text.AlignHCenter }
+ }
+
+ // Preview right-click menu: Clear single / Clear all / Show in Explorer
+ // (current selection only). Compact dark styling hugging items closely on all 4 sides.
+ // Clear actions honor canModifyQueue (dimmed while busy); Show in Explorer only needs loaded input.
+ QQC2.Menu {
+ id: previewMenu
+ leftInset: 0
+ rightInset: 0
+ topInset: 0
+ bottomInset: 0
+ topPadding: 3
+ bottomPadding: 3
+ leftPadding: 3
+ rightPadding: 3
+ spacing: 1
+
+ TextMetrics {
+ id: previewFontMetrics
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeBody
+ text: "Show in Explorer"
+ }
+
+ background: Rectangle {
+ color: Theme.bgSurface
+ border.color: Theme.borderDefault
+ border.width: 1
+ radius: Theme.radiusSmall
+ implicitWidth: Math.max(124, Math.ceil(previewFontMetrics.width) + 24)
+ }
+
+ delegate: QQC2.MenuItem {
+ id: previewMi
+ implicitHeight: 25
+ leftPadding: 10
+ rightPadding: 10
+ indicator: null
+ contentItem: Text {
+ text: previewMi.text
+ color: !previewMi.enabled ? Theme.textMuted : (previewMi.highlighted ? Theme.textPrimary : Theme.textSecondary)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeBody
+ font.weight: Font.Normal
+ elide: Text.ElideRight
+ verticalAlignment: Text.AlignVCenter
+ }
+ background: Rectangle {
+ color: previewMi.highlighted && previewMi.enabled ? Theme.bgHover : "transparent"
+ radius: 3
+ }
+ }
+
+ QQC2.MenuItem {
+ implicitHeight: 25
+ text: viewport.isVideo ? "Clear video" : "Clear image"
+ enabled: viewport.hasInput && appBridge && appBridge.canModifyQueue
+ onTriggered: { if (appBridge) appBridge.clearSelectedPreviewItem() }
+ }
+ QQC2.MenuItem {
+ implicitHeight: 25
+ text: "Clear all"
+ enabled: viewport.hasInput && appBridge && appBridge.canModifyQueue
+ onTriggered: { if (appBridge) appBridge.clearActiveQueue() }
+ }
+ QQC2.MenuItem {
+ implicitHeight: 25
+ text: "Show in Explorer"
+ enabled: viewport.hasInput && appBridge
+ onTriggered: { if (appBridge) appBridge.showSelectedInExplorer() }
+ }
+ }
+}
diff --git a/src/desktop/qml/components/MenuStrip.qml b/src/desktop/qml/components/MenuStrip.qml
new file mode 100644
index 0000000..abd2061
--- /dev/null
+++ b/src/desktop/qml/components/MenuStrip.qml
@@ -0,0 +1,243 @@
+import QtQuick
+import QtQuick.Controls as QQC2
+import ".."
+
+// Topaz-style menu strip: File / View / Process / Help. Every item maps to
+// an existing bridge slot/property; window-level actions (exit, fullscreen,
+// console) are forwarded as signals owned by Main.qml.
+Row {
+ id: root
+ property var appBridge: null
+ property bool consoleOpen: false
+ signal exitRequested()
+ signal toggleFullscreenRequested()
+ signal toggleConsoleRequested()
+
+ height: 44
+ spacing: 2
+
+ // Only one menu open at a time; hovering another title switches to it.
+ property var openMenu: null
+ function toggleMenu(menu, button) {
+ if (root.openMenu === menu) {
+ menu.dismiss()
+ root.openMenu = null
+ } else {
+ if (root.openMenu) root.openMenu.dismiss()
+ menu.popup(button, 0, button.height)
+ root.openMenu = menu
+ }
+ }
+ function onMenuClosed(menu) {
+ if (root.openMenu === menu) root.openMenu = null
+ }
+
+ // Shared dark chrome for all menus.
+ Component {
+ id: menuBackground
+ Rectangle {
+ color: Theme.bgSurface
+ border.color: Theme.borderDefault
+ border.width: 1
+ radius: 8
+ implicitWidth: 250
+ }
+ }
+ Component {
+ id: menuDelegate
+ QQC2.MenuItem {
+ id: mi
+ contentItem: Text {
+ text: mi.text
+ color: !mi.enabled ? Theme.textMuted : (mi.highlighted ? Theme.textPrimary : Theme.textSecondary)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeBody
+ elide: Text.ElideRight
+ verticalAlignment: Text.AlignVCenter
+ }
+ background: Rectangle {
+ color: mi.highlighted && mi.enabled ? Theme.bgHover : "transparent"
+ radius: 5
+ }
+ indicator: Item {
+ implicitWidth: 26
+ implicitHeight: 20
+ Rectangle {
+ anchors.centerIn: parent
+ width: 6
+ height: 6
+ radius: 3
+ color: mi.checked ? Theme.accent : "transparent"
+ border.color: Theme.borderDefault
+ border.width: mi.checked ? 0 : 1
+ visible: mi.checkable
+ }
+ }
+ }
+ }
+
+ // -- menu title buttons -------------------------------------------
+ Repeater {
+ model: [
+ { label: "File", menu: fileMenu },
+ { label: "View", menu: viewMenu },
+ { label: "Process", menu: processMenu },
+ { label: "Help", menu: helpMenu }
+ ]
+ Item {
+ required property var modelData
+ height: 44
+ width: btnLabel.implicitWidth + 24
+ Text {
+ id: btnLabel
+ anchors.centerIn: parent
+ text: parent.modelData.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: root.openMenu === parent.modelData.menu ? Theme.accent
+ : (btnMouse.containsMouse ? Theme.textPrimary : Theme.textSecondary)
+ }
+ MouseArea {
+ id: btnMouse
+ anchors.fill: parent
+ hoverEnabled: true
+ cursorShape: Qt.PointingHandCursor
+ onClicked: root.toggleMenu(parent.modelData.menu, parent)
+ onContainsMouseChanged: {
+ if (containsMouse && root.openMenu && root.openMenu !== parent.modelData.menu)
+ root.toggleMenu(parent.modelData.menu, parent)
+ }
+ }
+ }
+ }
+
+ // -- File ----------------------------------------------------------
+ QQC2.Menu {
+ id: fileMenu
+ background: menuBackground
+ delegate: menuDelegate
+ onClosed: root.onMenuClosed(fileMenu)
+ QQC2.MenuItem {
+ text: "Open Outputs Folder"
+ enabled: root.appBridge !== null
+ onTriggered: { if (root.appBridge) root.appBridge.openFolder("") }
+ }
+ QQC2.MenuItem {
+ text: "Open Logs Folder"
+ enabled: root.appBridge && root.appBridge.currentLogPath !== ""
+ onTriggered: { if (root.appBridge) root.appBridge.openFolder(root.appBridge.currentLogPath) }
+ }
+ Loader { sourceComponent: menuSeparator }
+ QQC2.MenuItem {
+ text: "Exit"
+ onTriggered: root.exitRequested()
+ }
+ }
+
+ // -- View ----------------------------------------------------------
+ QQC2.Menu {
+ id: viewMenu
+ background: menuBackground
+ delegate: menuDelegate
+ onClosed: root.onMenuClosed(viewMenu)
+ QQC2.MenuItem {
+ text: "Neural Rendering"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "neural-rendering"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "neural-rendering" }
+ }
+ QQC2.MenuItem {
+ text: "Upscale"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "upscale"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "upscale" }
+ }
+ QQC2.MenuItem {
+ text: "Frame Interpolation"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "frame-interpolation"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "frame-interpolation" }
+ }
+ QQC2.MenuItem {
+ text: "Live"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "live"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "live" }
+ }
+ QQC2.MenuItem {
+ text: "Settings"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "settings"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "settings" }
+ }
+ QQC2.MenuItem {
+ text: "Help"
+ checkable: true
+ checked: root.appBridge && root.appBridge.activeTab === "help"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "help" }
+ }
+ Loader { sourceComponent: menuSeparator }
+ QQC2.MenuItem {
+ text: "Focus Preview"
+ checkable: true
+ checked: root.appBridge ? root.appBridge.focusPreview : false
+ onTriggered: { if (root.appBridge) root.appBridge.focusPreview = !root.appBridge.focusPreview }
+ }
+ QQC2.MenuItem {
+ text: "Fullscreen"
+ onTriggered: root.toggleFullscreenRequested()
+ }
+ QQC2.MenuItem {
+ text: "Console"
+ checkable: true
+ checked: root.consoleOpen
+ onTriggered: root.toggleConsoleRequested()
+ }
+ }
+
+ // -- Process -------------------------------------------------------
+ QQC2.Menu {
+ id: processMenu
+ background: menuBackground
+ delegate: menuDelegate
+ onClosed: root.onMenuClosed(processMenu)
+ QQC2.MenuItem {
+ text: "Start / Render"
+ enabled: root.appBridge ? root.appBridge.canRender : false
+ onTriggered: { if (root.appBridge) root.appBridge.startActiveBatch() }
+ }
+ QQC2.MenuItem {
+ text: "Preview"
+ enabled: root.appBridge ? root.appBridge.canPreview : false
+ onTriggered: { if (root.appBridge) root.appBridge.renderPreview() }
+ }
+ QQC2.MenuItem {
+ text: "Stop"
+ enabled: root.appBridge ? root.appBridge.canStop : false
+ onTriggered: { if (root.appBridge) root.appBridge.stopActiveBatch() }
+ }
+ Loader { sourceComponent: menuSeparator }
+ QQC2.MenuItem {
+ text: "Stop Live Session"
+ enabled: root.appBridge ? root.appBridge.isLiveRunning : false
+ onTriggered: { if (root.appBridge) root.appBridge.stopLive() }
+ }
+ }
+
+ // -- Help ----------------------------------------------------------
+ QQC2.Menu {
+ id: helpMenu
+ background: menuBackground
+ delegate: menuDelegate
+ onClosed: root.onMenuClosed(helpMenu)
+ QQC2.MenuItem {
+ text: "Help"
+ onTriggered: { if (root.appBridge) root.appBridge.activeTab = "help" }
+ }
+ QQC2.MenuItem {
+ text: "Open Logs Folder"
+ enabled: root.appBridge && root.appBridge.currentLogPath !== ""
+ onTriggered: { if (root.appBridge) root.appBridge.openFolder(root.appBridge.currentLogPath) }
+ }
+ }
+}
diff --git a/src/desktop/qml/components/VideoTransportBar.qml b/src/desktop/qml/components/VideoTransportBar.qml
new file mode 100644
index 0000000..6582770
--- /dev/null
+++ b/src/desktop/qml/components/VideoTransportBar.qml
@@ -0,0 +1,172 @@
+import QtQuick
+import QtMultimedia
+import ".."
+import "../controls"
+
+Rectangle {
+ id: root
+ property var player: null
+ property real frameRate: 30.0
+ property bool muted: false
+ // Fallback metadata from ffprobe (bridge.sourceDuration/sourceFps) so the
+ // timeline never sticks at 00:00 when MediaPlayer hasn't loaded yet.
+ property real fallbackDurationMs: 0
+ property real fallbackFrameRate: 30.0
+ // Emitted only for direct user timeline moves (scrub/step/jump), never
+ // for programmatic seeks or playback ticks. The viewport debounces these
+ // into scrub-realtime preview refreshes.
+ signal userScrubbed(real posMs)
+ // Pre-rendered timeline spans (seconds) painted green, e.g. Frame
+ // Interpolation "Preview" clips: [{start: 12.0, end: 15.0, url: ...}].
+ // Empty for every other workflow, which leaves the groove untouched.
+ property var renderedRanges: []
+ height: 50
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ readonly property real effectiveFps: frameRate > 0.01 ? frameRate : (fallbackFrameRate > 0.01 ? fallbackFrameRate : 30.0)
+ readonly property real effectiveDuration: root.player && root.player.duration > 0 ? root.player.duration : fallbackDurationMs
+ readonly property real effectivePosition: root.player ? Math.max(0, Math.min(effectiveDuration > 0 ? effectiveDuration : root.player.position, root.player.position)) : 0
+ readonly property int currentFrame: Math.floor(effectivePosition * effectiveFps / 1000.0) + (effectiveDuration > 0 ? 1 : 0)
+ readonly property int totalFrames: effectiveFps > 0 && effectiveDuration > 0 ? Math.max(1, Math.round(effectiveDuration * effectiveFps / 1000.0)) : 0
+
+ function fmt(ms) {
+ var total = Math.max(0, Math.floor(ms / 1000))
+ var h = Math.floor(total / 3600)
+ var m = Math.floor((total % 3600) / 60)
+ var s = total % 60
+ function pad(v) { return v < 10 ? "0" + v : "" + v }
+ return h > 0 ? (h + ":" + pad(m) + ":" + pad(s)) : (pad(m) + ":" + pad(s))
+ }
+ function fmtPrecise(ms) {
+ // Sub-second durations (single-frame previews) would floor to 00:00;
+ // show tenths so a 41ms preview reads 00:00.0 instead of 00:00.
+ if (ms < 1000) {
+ var tenths = Math.max(0, Math.floor(ms / 100))
+ return "00:00." + tenths
+ }
+ return fmt(ms)
+ }
+ function fmtDuration(ms) {
+ return ms > 0 && ms < 1000 ? fmtPrecise(ms) : fmt(ms)
+ }
+ function stepFrames(frames) {
+ if (!root.player) return
+ var dur = root.player.duration > 0 ? root.player.duration : fallbackDurationMs
+ if (!root.player.seekable && root.player.duration <= 0 && dur <= 0) return
+ root.player.pause()
+ var target = root.player.position + frames * 1000.0 / effectiveFps
+ if (dur > 0) target = Math.max(0, Math.min(dur, target))
+ else target = Math.max(0, target)
+ root.player.position = target
+ root.userScrubbed(target)
+ }
+
+ Row {
+ anchors.fill: parent
+ anchors.margins: 8
+ spacing: 7
+
+ AppIconButton { iconSymbol: "|<"; tooltipText: "Start"; onClicked: { if (root.player) { root.player.pause(); root.player.position = 0; root.userScrubbed(0) } } }
+ AppIconButton { iconSymbol: "<"; tooltipText: "Previous frame"; onClicked: root.stepFrames(-1) }
+ AppButton {
+ text: root.player && root.player.playbackState === MediaPlayer.PlayingState ? "Pause" : "Play"
+ width: 66; buttonHeight: 30
+ onClicked: {
+ if (!root.player) return
+ if (root.player.playbackState === MediaPlayer.PlayingState) root.player.pause()
+ else root.player.play()
+ }
+ }
+ AppIconButton { iconSymbol: ">"; tooltipText: "Next frame"; onClicked: root.stepFrames(1) }
+
+ Rectangle {
+ width: Math.max(120, parent.width - 430)
+ height: 14; radius: 7; anchors.verticalCenter: parent.verticalCenter; color: Theme.bgInput
+ clip: true
+ Rectangle {
+ id: playheadFill
+ readonly property bool atEnd: width >= parent.width || (root.effectiveDuration > 0 && root.effectivePosition >= root.effectiveDuration)
+ width: parent.width * (root.effectiveDuration > 0 ? Math.max(0, Math.min(1, root.effectivePosition / root.effectiveDuration)) : 0)
+ height: parent.height
+ color: Theme.accent
+ topLeftRadius: 7
+ bottomLeftRadius: 7
+ topRightRadius: atEnd ? 7 : 0
+ bottomRightRadius: atEnd ? 7 : 0
+
+ // Thin white vertical cutoff line at the moving head
+ Rectangle {
+ id: playheadCutoff
+ anchors.right: parent.right
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ width: 1.5
+ color: "#FFFFFF"
+ visible: parent.width >= 2 && !playheadFill.atEnd
+ }
+ }
+ // Green pre-rendered spans (FI "Preview"). Painted over the
+ // accent playhead fill so a rendered span always reads green:
+ // blue advances up to it, green holds while playing through it,
+ // blue resumes after it. Exact position still shows in the label.
+ Repeater {
+ model: root.renderedRanges
+ Rectangle {
+ required property var modelData
+ y: 0; height: parent.height; radius: 0; color: Theme.success
+ x: {
+ var dur = root.effectiveDuration
+ if (!(dur > 0)) return 0
+ var s = Math.max(0, Math.min(dur / 1000.0, modelData.start || 0))
+ return parent.width * (s / (dur / 1000.0))
+ }
+ width: {
+ var dur = root.effectiveDuration
+ if (!(dur > 0)) return 0
+ var total = dur / 1000.0
+ var s = Math.max(0, Math.min(total, modelData.start || 0))
+ var e = Math.max(0, Math.min(total, modelData.end || 0))
+ return Math.max(0, parent.width * ((e - s) / total))
+ }
+ }
+ }
+ MouseArea {
+ anchors.fill: parent; cursorShape: Qt.PointingHandCursor
+ function seek(mouseX) {
+ var dur = root.player && root.player.duration > 0 ? root.player.duration : root.fallbackDurationMs
+ if (root.player && dur > 0) {
+ var target = Math.max(0, Math.min(dur, mouseX / width * dur))
+ root.player.position = target
+ root.userScrubbed(target)
+ }
+ }
+ onPressed: (mouse) => seek(mouse.x)
+ onPositionChanged: (mouse) => { if (pressed) seek(mouse.x) }
+ }
+ }
+
+ Text {
+ anchors.verticalCenter: parent.verticalCenter
+ text: {
+ var pos = root.player ? root.player.position : 0
+ var dur = root.player && root.player.duration > 0 ? root.player.duration : root.fallbackDurationMs
+ var label = root.fmt(pos) + " / " + root.fmtDuration(dur)
+ if (root.totalFrames > 0 && root.totalFrames < 100000)
+ label += " - f" + root.currentFrame + "/" + root.totalFrames
+ else if (root.player && root.player.duration > 0 && root.player.duration < 1000)
+ label += " - 1 frame"
+ return label
+ }
+ color: Theme.textSecondary; font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall
+ }
+
+ AppComboBox {
+ width: 72; comboHeight: 30
+ model: [{label:"0.5x",value:0.5},{label:"1x",value:1.0},{label:"1.5x",value:1.5},{label:"2x",value:2.0}]
+ currentValue: root.player ? root.player.playbackRate : 1.0
+ onActivated: (v) => { if (root.player) root.player.playbackRate = v }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppBadge.qml b/src/desktop/qml/controls/AppBadge.qml
new file mode 100644
index 0000000..9abd254
--- /dev/null
+++ b/src/desktop/qml/controls/AppBadge.qml
@@ -0,0 +1,50 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string text: ""
+ property string variant: "neutral" // "neutral", "success", "warning", "danger", "accent"
+
+ implicitWidth: label.implicitWidth + 12
+ implicitHeight: 20
+
+ Rectangle {
+ anchors.fill: parent
+ radius: Theme.radiusSmall
+
+ color: {
+ if (control.variant === "success") return Theme.successBg
+ if (control.variant === "warning") return Theme.warningBg
+ if (control.variant === "danger") return Theme.dangerBg
+ if (control.variant === "accent") return Theme.accentMuted
+ return Theme.bgInput
+ }
+
+ border.color: {
+ if (control.variant === "success") return Theme.success
+ if (control.variant === "warning") return Theme.warning
+ if (control.variant === "danger") return Theme.danger
+ if (control.variant === "accent") return Theme.accent
+ return Theme.borderSubtle
+ }
+ border.width: 1
+
+ Text {
+ id: label
+ anchors.centerIn: parent
+ text: control.text
+ font.family: Theme.monoFontFamily
+ font.pixelSize: 10
+ font.weight: Font.DemiBold
+ color: {
+ if (control.variant === "success") return Theme.success
+ if (control.variant === "warning") return Theme.warning
+ if (control.variant === "danger") return Theme.danger
+ if (control.variant === "accent") return Theme.accent
+ return Theme.textSecondary
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppButton.qml b/src/desktop/qml/controls/AppButton.qml
new file mode 100644
index 0000000..c7a59da
--- /dev/null
+++ b/src/desktop/qml/controls/AppButton.qml
@@ -0,0 +1,114 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string text: ""
+ property string variant: "secondary" // "primary", "secondary", "danger", "ghost"
+ // NOTE: uses built-in Item.enabled (do NOT redeclare it here).
+ property int buttonHeight: Theme.controlHeight
+ property int customRadius: Theme.radiusMedium
+ property color customColor: "transparent"
+
+ signal clicked()
+
+ implicitWidth: Math.max(80, label.implicitWidth + 24)
+ implicitHeight: buttonHeight
+ // Default size so the pill always renders, even in plain Row/Column
+ // positioners (explicit width:/height: usages override these).
+ width: implicitWidth
+ height: implicitHeight
+ // Disabled primary stays full-strength at the same #06996B so the
+ // main action is pixel-identical enabled vs disabled (only
+ // clickability differs); other variants dim.
+ opacity: enabled ? 1.0 : (control.variant === "primary" ? 1.0 : 0.45)
+ activeFocusOnTab: enabled
+ Keys.onPressed: (event) => {
+ if (enabled && (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter)) { clicked(); event.accepted = true }
+ }
+
+ Rectangle {
+ id: bg
+ anchors.fill: parent
+ radius: control.customRadius
+ border.width: 1
+
+ color: {
+ // Primary is permanently #06996B in idle, hover AND disabled:
+ // same hardcoded value everywhere so mouse navigate or
+ // enabled state can never change it. Secondary keeps the
+ // neutral dark look; danger keeps red.
+ if (!control.enabled) {
+ if (control.variant === "primary") return "#06996B"
+ if (control.variant === "danger") return Theme.danger
+ return Theme.bgInput
+ }
+ if (mouseArea.pressed) {
+ if (control.variant === "primary") return Theme.accentPressed
+ if (control.variant === "danger") return Theme.dangerPressed
+ return Theme.bgPressed
+ }
+ if (mouseArea.containsMouse) {
+ // Primary hover is exactly #06996B: zero visible change
+ // when navigating the mouse over the button.
+ if (control.variant === "primary") return "#06996B"
+ if (control.variant === "danger") return Theme.dangerHover
+ if (control.variant === "ghost") return Theme.bgHover
+ return Theme.bgHover
+ }
+ // NOTE: must use Qt.colorEqual here. A plain
+ // `customColor !== "transparent"` is ALWAYS true (color value
+ // vs string literal never compare equal), which used to make
+ // every idle button transparent.
+ if (!Qt.colorEqual(control.customColor, "transparent")) return control.customColor
+ // Idle: primary is always solid #06996B (hardcoded so the main
+ // action color can never depend on theme resolution).
+ if (control.variant === "primary") return "#06996B"
+ if (control.variant === "danger") return Theme.danger
+ if (control.variant === "ghost") return "transparent"
+ return Theme.bgInput
+ }
+
+ border.color: {
+ if (control.variant === "primary" || control.variant === "danger") return "transparent"
+ if (control.activeFocus) return Theme.accent
+ if (mouseArea.containsMouse) return Theme.borderActive
+ return Theme.borderDefault
+ }
+
+ Behavior on color {
+ ColorAnimation { duration: Theme.animFast }
+ }
+ Behavior on border.color {
+ ColorAnimation { duration: Theme.animFast }
+ }
+ }
+
+ Text {
+ id: label
+ anchors.centerIn: parent
+ text: control.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ font.weight: control.variant === "primary" ? Font.DemiBold : Font.Normal
+ color: {
+ if (control.variant === "primary") return "#FFFFFF"
+ if (control.variant === "danger") return "#FFFFFF"
+ if (mouseArea.containsMouse) return Theme.textPrimary
+ return Theme.textSecondary
+ }
+ }
+
+ MouseArea {
+ id: mouseArea
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (control.enabled) {
+ control.clicked()
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppCard.qml b/src/desktop/qml/controls/AppCard.qml
new file mode 100644
index 0000000..23892ad
--- /dev/null
+++ b/src/desktop/qml/controls/AppCard.qml
@@ -0,0 +1,100 @@
+import QtQuick
+import ".."
+
+Item {
+ id: card
+
+ property string title: ""
+ property bool collapsible: true
+ property bool collapsed: false
+ default property alias content: contentContainer.data
+
+ implicitWidth: 320
+ implicitHeight: header.height + (collapsed ? 0 : (contentContainer.childrenRect.height + 24))
+
+ Rectangle {
+ id: bg
+ anchors.fill: parent
+ radius: Theme.radiusLarge
+ color: Theme.bgCard
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ // Header
+ Rectangle {
+ id: header
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 38
+ color: "transparent"
+
+ Row {
+ anchors.left: parent.left
+ anchors.leftMargin: 12
+ anchors.right: chevron.left
+ anchors.rightMargin: 8
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 8
+
+ Text {
+ text: card.title
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeSubtitle
+ font.weight: Font.DemiBold
+ color: Theme.textPrimary
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+
+ Text {
+ id: chevron
+ visible: card.collapsible
+ anchors.right: parent.right
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ text: card.collapsed ? "v" : "^"
+ font.pixelSize: 10
+ color: headerMouse.containsMouse ? Theme.textPrimary : Theme.textMuted
+ }
+
+ MouseArea {
+ id: headerMouse
+ anchors.fill: parent
+ hoverEnabled: card.collapsible
+ cursorShape: card.collapsible ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (card.collapsible) {
+ card.collapsed = !card.collapsed
+ }
+ }
+ }
+
+ // Hairline separator when expanded
+ Rectangle {
+ visible: !card.collapsed
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.leftMargin: 12
+ anchors.right: parent.right
+ anchors.rightMargin: 12
+ height: 1
+ color: Theme.borderSubtle
+ }
+ }
+
+ // Content Area
+ Item {
+ id: contentContainer
+ visible: !card.collapsed
+ anchors.top: header.bottom
+ anchors.topMargin: 12
+ anchors.left: parent.left
+ anchors.leftMargin: 12
+ anchors.right: parent.right
+ anchors.rightMargin: 12
+ height: childrenRect.height
+ clip: false
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppCheckBox.qml b/src/desktop/qml/controls/AppCheckBox.qml
new file mode 100644
index 0000000..cc87f0f
--- /dev/null
+++ b/src/desktop/qml/controls/AppCheckBox.qml
@@ -0,0 +1,57 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string label: ""
+ property bool checked: false
+ property bool enabled: true
+
+ signal toggled(bool isChecked)
+
+ implicitWidth: Math.max(100, labelText.implicitWidth + 28)
+ implicitHeight: 24
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled
+ Keys.onPressed: (event) => { if (enabled && (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter)) { toggled(!checked); event.accepted = true } }
+
+ Row {
+ anchors.fill: parent
+ spacing: 8
+
+ Rectangle {
+ id: box
+ width: 18
+ height: 18
+ radius: Theme.radiusSmall
+ anchors.verticalCenter: parent.verticalCenter
+ color: control.checked ? Theme.accent : Theme.bgInput
+ border.color: control.activeFocus ? Theme.accent : (control.checked ? Theme.accent : (mouseArea.containsMouse ? Theme.borderActive : Theme.borderDefault))
+ border.width: 1
+
+ Behavior on color { ColorAnimation { duration: Theme.animFast } }
+ }
+
+ Text {
+ id: labelText
+ anchors.verticalCenter: parent.verticalCenter
+ text: control.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: mouseArea.containsMouse ? Theme.textPrimary : Theme.textSecondary
+ }
+ }
+
+ MouseArea {
+ id: mouseArea
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (control.enabled) {
+ control.toggled(!control.checked)
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppComboBox.qml b/src/desktop/qml/controls/AppComboBox.qml
new file mode 100644
index 0000000..bc49b00
--- /dev/null
+++ b/src/desktop/qml/controls/AppComboBox.qml
@@ -0,0 +1,113 @@
+import QtQuick
+import QtQuick.Controls as QQC2
+import ".."
+
+Item {
+ id: control
+ property string label: ""
+ property var model: []
+ property var currentValue: undefined
+ property int currentIndex: -1
+ property bool enabled: true
+ property int comboHeight: Theme.controlHeight
+ // Drop-up mode for combos docked at the window bottom (e.g. the FI
+ // action-bar length picker): the list opens above the box instead of
+ // falling off-window. Defaults off; every existing combo is unaffected.
+ property bool dropUp: false
+ signal activated(var value, int index)
+
+ implicitWidth: 200
+ implicitHeight: label !== "" ? (comboHeight + 20) : comboHeight
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled
+
+ function getLabel(item) {
+ if (item === undefined || item === null) return ""
+ if (typeof item === "object" && item.label !== undefined) return item.label
+ return item.toString()
+ }
+ function getValue(item) {
+ if (item === undefined || item === null) return undefined
+ if (typeof item === "object" && item.value !== undefined) return item.value
+ return item
+ }
+ function syncIndex() {
+ currentIndex = -1
+ if (!model) return
+ for (var i = 0; i < model.length; i++) {
+ if (getValue(model[i]) === currentValue) { currentIndex = i; return }
+ }
+ }
+ function displayText() {
+ if (currentIndex >= 0 && model && currentIndex < model.length) return getLabel(model[currentIndex])
+ return currentValue === undefined || currentValue === null || currentValue === "" ? "Select..." : "Unavailable: " + currentValue
+ }
+ onCurrentValueChanged: syncIndex()
+ onModelChanged: syncIndex()
+ Component.onCompleted: syncIndex()
+ Keys.onPressed: (event) => {
+ if (!enabled || !model || model.length === 0) return
+ if (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
+ popup.open(); event.accepted = true
+ } else if (event.key === Qt.Key_Down || event.key === Qt.Key_Right) {
+ var i = Math.min(model.length - 1, Math.max(-1, currentIndex) + 1)
+ activated(getValue(model[i]), i); event.accepted = true
+ } else if (event.key === Qt.Key_Up || event.key === Qt.Key_Left) {
+ var j = Math.max(0, currentIndex <= 0 ? 0 : currentIndex - 1)
+ activated(getValue(model[j]), j); event.accepted = true
+ }
+ }
+
+ Text {
+ visible: control.label !== ""; anchors.top: parent.top; anchors.left: parent.left
+ text: control.label; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textSecondary
+ }
+ Rectangle {
+ id: box; anchors.bottom: parent.bottom; anchors.left: parent.left; anchors.right: parent.right
+ height: control.comboHeight; radius: Theme.radiusMedium
+ color: mouseArea.containsMouse || popup.visible ? Theme.bgInputHover : Theme.bgInput
+ border.color: control.activeFocus || popup.visible ? Theme.accent : (mouseArea.containsMouse ? Theme.borderActive : Theme.borderDefault)
+ border.width: 1
+ Text {
+ anchors.left: parent.left; anchors.leftMargin: 10; anchors.right: arrow.left; anchors.rightMargin: 6
+ anchors.verticalCenter: parent.verticalCenter; elide: Text.ElideRight
+ text: control.displayText(); font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel
+ color: control.currentIndex >= 0 ? Theme.textPrimary : Theme.warning
+ }
+ Text { id: arrow; anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter; text: popup.visible ? "^" : "v"; color: Theme.textMuted }
+ MouseArea {
+ id: mouseArea; anchors.fill: parent; hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: { if (control.enabled) { control.forceActiveFocus(); popup.visible ? popup.close() : popup.open() } }
+ }
+ }
+
+ QQC2.Popup {
+ id: popup
+ x: 0; y: control.dropUp ? (box.y - height - 4) : (box.y + box.height + 4)
+ width: control.width; height: Math.min(260, Math.max(36, (control.model ? control.model.length : 0) * 32 + 8))
+ padding: 4; modal: false
+ closePolicy: QQC2.Popup.CloseOnEscape | QQC2.Popup.CloseOnPressOutside
+ background: Rectangle { radius: Theme.radiusMedium; color: Theme.bgSurface; border.color: Theme.borderActive; border.width: 1 }
+ contentItem: ListView {
+ id: listView; clip: true; model: control.model; boundsBehavior: Flickable.StopAtBounds
+ delegate: Rectangle {
+ required property var modelData
+ required property int index
+ width: listView.width; height: 32; radius: Theme.radiusSmall
+ color: itemMouse.containsMouse ? Theme.bgHover : (control.currentIndex === index ? Theme.bgSelected : "transparent")
+ Text {
+ anchors.left: parent.left; anchors.leftMargin: 8; anchors.right: check.left; anchors.rightMargin: 6; anchors.verticalCenter: parent.verticalCenter
+ text: control.getLabel(modelData); elide: Text.ElideRight
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel
+ color: control.currentIndex === index ? Theme.accent : Theme.textSecondary
+ }
+ Text { id: check; anchors.right: parent.right; anchors.rightMargin: 8; anchors.verticalCenter: parent.verticalCenter; visible: control.currentIndex === index; text: "X"; color: Theme.accent }
+ MouseArea {
+ id: itemMouse; anchors.fill: parent; hoverEnabled: true; cursorShape: Qt.PointingHandCursor
+ onClicked: { control.activated(control.getValue(modelData), index); popup.close(); control.forceActiveFocus() }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppFilePicker.qml b/src/desktop/qml/controls/AppFilePicker.qml
new file mode 100644
index 0000000..693b41f
--- /dev/null
+++ b/src/desktop/qml/controls/AppFilePicker.qml
@@ -0,0 +1,106 @@
+import QtQuick
+import QtQuick.Dialogs
+import ".."
+
+Item {
+ id: control
+ property string label: ""
+ property string placeholderText: ""
+ property string selectedPath: ""
+ property bool selectFolder: false
+ property bool enabled: true
+ property var nameFilters: ["All Files (*.*)"]
+ signal pathChanged(string path)
+
+ implicitWidth: 260
+ implicitHeight: label !== "" ? (Theme.controlHeight + 20) : Theme.controlHeight
+ opacity: enabled ? 1.0 : 0.45
+
+ function syncPath() {
+ if (!pathInput.activeFocus || pathInput.text !== control.selectedPath)
+ pathInput.text = control.selectedPath
+ }
+ onSelectedPathChanged: syncPath()
+ Component.onCompleted: syncPath()
+
+ Text {
+ visible: control.label !== ""
+ anchors.top: parent.top; anchors.left: parent.left
+ text: control.label
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textSecondary
+ }
+
+ Row {
+ anchors.bottom: parent.bottom; anchors.left: parent.left; anchors.right: parent.right
+ height: Theme.controlHeight; spacing: 6
+ Rectangle {
+ width: parent.width - browseBtn.width - 6; height: parent.height
+ radius: Theme.radiusMedium; color: Theme.bgInput
+ border.color: pathInput.activeFocus ? Theme.accent : Theme.borderDefault; border.width: 1
+ clip: true
+ TextInput {
+ id: pathInput
+ anchors.left: parent.left; anchors.leftMargin: 8
+ anchors.right: clearBtn.visible ? clearBtn.left : parent.right; anchors.rightMargin: 8
+ anchors.verticalCenter: parent.verticalCenter
+ enabled: control.enabled
+ font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textPrimary
+ selectByMouse: true; selectionColor: Theme.accent; clip: true
+ onEditingFinished: { control.pathChanged(text); control.syncPath() }
+ onAccepted: { control.pathChanged(text); control.syncPath() }
+ Text {
+ anchors.fill: parent; visible: pathInput.text === "" && !pathInput.activeFocus
+ text: control.placeholderText; font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel; color: Theme.textMuted
+ }
+ }
+ Text {
+ id: clearBtn; visible: pathInput.text !== "" && control.enabled
+ anchors.right: parent.right; anchors.rightMargin: 8; anchors.verticalCenter: parent.verticalCenter
+ text: "x"; font.pixelSize: 14; color: clearMouse.containsMouse ? Theme.textPrimary : Theme.textMuted
+ MouseArea {
+ id: clearMouse; anchors.fill: parent; anchors.margins: -5; hoverEnabled: true
+ cursorShape: Qt.PointingHandCursor
+ onClicked: { pathInput.text = ""; control.pathChanged("") }
+ }
+ }
+ }
+ AppButton {
+ id: browseBtn; text: "Browse"; width: 70; buttonHeight: Theme.controlHeight; enabled: control.enabled
+ onClicked: control.selectFolder ? folderDialog.open() : fileDialog.open()
+ }
+ }
+
+ FolderDialog {
+ id: folderDialog
+ title: "Select Folder"
+ onAccepted: {
+ // NOTE: QML url has no toLocalFile(); pass the URL string and
+ // let Python _clean_path() convert via QUrl.toLocalFile().
+ var s = selectedFolder.toString()
+ pathInput.text = s
+ control.pathChanged(s)
+ }
+ }
+ FileDialog {
+ id: fileDialog
+ title: "Select File"
+ fileMode: FileDialog.OpenFile
+ nameFilters: control.nameFilters
+ onAccepted: {
+ var u = selectedFile
+ if ((u === undefined || u === null) && selectedFiles !== undefined && selectedFiles.length > 0)
+ u = selectedFiles[0]
+ if ((u === undefined || u === null) && currentFile !== undefined)
+ u = currentFile
+ if (u === undefined || u === null)
+ return
+ var s = u.toString()
+ if (!s)
+ return
+ pathInput.text = s
+ control.pathChanged(s)
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppIconButton.qml b/src/desktop/qml/controls/AppIconButton.qml
new file mode 100644
index 0000000..27e8fa7
--- /dev/null
+++ b/src/desktop/qml/controls/AppIconButton.qml
@@ -0,0 +1,156 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string iconSymbol: "" // e.g. "x", "R", "S", ">", "II", "O", "[]", "..."
+ property string tooltipText: ""
+ property bool showTooltip: true
+ // Vector chrome icon kind: "" (use iconSymbol text), "min", "max", "restore", "close".
+ // Vector icons are font-independent so they stay crisp at any DPI/scale.
+ property string iconKind: ""
+ property bool enabled: true
+ property int buttonSize: 28
+ property color activeColor: Theme.textSecondary
+ property color hoverColor: Theme.textPrimary
+
+ signal clicked()
+
+ implicitWidth: buttonSize
+ implicitHeight: buttonSize
+ opacity: enabled ? 1.0 : 0.4
+ activeFocusOnTab: enabled
+ Keys.onPressed: (event) => { if (enabled && (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter)) { clicked(); event.accepted = true } }
+
+ Rectangle {
+ id: bg
+ anchors.fill: parent
+ radius: Theme.radiusSmall
+ color: mouseArea.pressed ? Theme.bgPressed : (mouseArea.containsMouse ? Theme.bgHover : "transparent")
+ border.color: control.activeFocus ? Theme.accent : (mouseArea.containsMouse ? Theme.borderSubtle : "transparent")
+ border.width: 1
+
+ Behavior on color {
+ ColorAnimation { duration: Theme.animFast }
+ }
+ }
+
+ Text {
+ visible: control.iconKind === ""
+ anchors.centerIn: parent
+ text: control.iconSymbol
+ font.family: Theme.fontFamily
+ font.pixelSize: 13
+ color: mouseArea.containsMouse ? control.hoverColor : control.activeColor
+ }
+
+ // Vector window-chrome icons (no font glyphs, DPI-independent).
+ Item {
+ visible: control.iconKind !== ""
+ anchors.centerIn: parent
+ width: 12
+ height: 12
+ property color iconColor: mouseArea.containsMouse ? control.hoverColor : control.activeColor
+
+ // Minimize: centered horizontal bar.
+ Rectangle {
+ visible: control.iconKind === "min"
+ anchors.centerIn: parent
+ width: 10
+ height: 1.6
+ color: parent.iconColor
+ }
+
+ // Maximize: single outline square.
+ Rectangle {
+ visible: control.iconKind === "max"
+ anchors.centerIn: parent
+ width: 10
+ height: 10
+ color: "transparent"
+ border.color: parent.iconColor
+ border.width: 1.5
+ }
+
+ // Restore: two overlapping squares (back offset up-right).
+ Item {
+ visible: control.iconKind === "restore"
+ anchors.centerIn: parent
+ width: 12
+ height: 12
+ property color rc: parent.iconColor
+ Rectangle {
+ x: 3; y: 0; width: 8; height: 8
+ color: "transparent"
+ border.color: parent.rc
+ border.width: 1.4
+ }
+ Rectangle {
+ x: 1; y: 3; width: 8; height: 8
+ color: bg.color
+ border.color: parent.rc
+ border.width: 1.4
+ }
+ }
+
+ // Close: X from two rotated bars.
+ Item {
+ visible: control.iconKind === "close"
+ anchors.centerIn: parent
+ width: 12
+ height: 12
+ property color xc: parent.iconColor
+ Rectangle {
+ anchors.centerIn: parent
+ width: 12.5
+ height: 1.6
+ rotation: 45
+ color: parent.xc
+ }
+ Rectangle {
+ anchors.centerIn: parent
+ width: 12.5
+ height: 1.6
+ rotation: -45
+ color: parent.xc
+ }
+ }
+ }
+
+ MouseArea {
+ id: mouseArea
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (control.enabled) control.clicked()
+ }
+ }
+
+ // Tooltip (opt-out via showTooltip; window-chrome buttons disable it
+ // because they sit at y=0 and the popup would clip outside the window).
+ Rectangle {
+ id: tip
+ visible: control.showTooltip && mouseArea.containsMouse && control.tooltipText !== ""
+ anchors.bottom: parent.top
+ anchors.bottomMargin: 6
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: tipText.implicitWidth + 12
+ height: tipText.implicitHeight + 6
+ radius: Theme.radiusSmall
+ color: "#0F1216"
+ border.color: Theme.borderActive
+ border.width: 1
+ z: 999
+
+ Text {
+ id: tipText
+ anchors.centerIn: parent
+ text: control.tooltipText
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textPrimary
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppProgressBar.qml b/src/desktop/qml/controls/AppProgressBar.qml
new file mode 100644
index 0000000..234fb92
--- /dev/null
+++ b/src/desktop/qml/controls/AppProgressBar.qml
@@ -0,0 +1,66 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property real progress: 0.0 // 0.0 to 1.0
+ property string statusText: ""
+ property bool indeterminate: false
+
+ implicitWidth: 200
+ implicitHeight: 22
+
+ Column {
+ anchors.fill: parent
+ spacing: 4
+
+ Row {
+ width: parent.width
+ visible: control.statusText !== "" || control.progress > 0
+
+ Text {
+ text: control.statusText
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textSecondary
+ elide: Text.ElideRight
+ width: parent.width - pctText.implicitWidth - 8
+ }
+
+ Text {
+ id: pctText
+ text: Math.round(control.progress * 100) + "%"
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ font.weight: Font.DemiBold
+ color: Theme.accent
+ anchors.right: parent.right
+ }
+ }
+
+ Rectangle {
+ width: parent.width
+ height: 6
+ radius: 3
+ color: Theme.bgInput
+ border.color: Theme.borderSubtle
+ border.width: 1
+ clip: true
+
+ Rectangle {
+ id: barFill
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ width: Math.max(0, Math.min(parent.width, parent.width * control.progress))
+ radius: 3
+ color: Theme.accent
+
+ Behavior on width {
+ NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppSegmentedControl.qml b/src/desktop/qml/controls/AppSegmentedControl.qml
new file mode 100644
index 0000000..37558ed
--- /dev/null
+++ b/src/desktop/qml/controls/AppSegmentedControl.qml
@@ -0,0 +1,133 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string label: ""
+ property var model: [] // e.g. ["Image", "Video"] or [{label: "...", value: "..."}]
+ property var currentValue: undefined
+ property int currentIndex: 0
+ property int controlHeight: Theme.controlHeightSmall
+ property bool enabled: true
+
+ signal activated(var value, int index)
+
+ implicitWidth: 220
+ implicitHeight: label !== "" ? (controlHeight + 20) : controlHeight
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled
+ Keys.onPressed: (event) => {
+ if (!enabled || !model || model.length === 0) return
+ var next = currentIndex
+ if (event.key === Qt.Key_Right || event.key === Qt.Key_Down) next = Math.min(model.length - 1, Math.max(-1, currentIndex) + 1)
+ else if (event.key === Qt.Key_Left || event.key === Qt.Key_Up) next = Math.max(0, currentIndex <= 0 ? 0 : currentIndex - 1)
+ else return
+ activated(getValue(model[next]), next); event.accepted = true
+ }
+
+ function getLabel(item) {
+ if (item === undefined || item === null) return ""
+ if (typeof item === "object" && item.label !== undefined) return item.label
+ return item.toString()
+ }
+
+ function getValue(item) {
+ if (item === undefined || item === null) return undefined
+ if (typeof item === "object" && item.value !== undefined) return item.value
+ return item
+ }
+
+ function syncIndex() {
+ currentIndex = -1
+ if (!model || model.length === 0) return
+ for (var i = 0; i < model.length; i++) {
+ if (getValue(model[i]) === currentValue) {
+ currentIndex = i
+ return
+ }
+ }
+ }
+
+ onCurrentValueChanged: syncIndex()
+ onModelChanged: syncIndex()
+
+ Text {
+ id: labelText
+ visible: control.label !== ""
+ anchors.top: parent.top
+ anchors.left: parent.left
+ text: control.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textSecondary
+ }
+
+ Rectangle {
+ id: container
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: control.controlHeight
+ radius: Theme.radiusMedium
+ color: Theme.bgInput
+ border.color: control.activeFocus ? Theme.accent : Theme.borderSubtle
+ border.width: 1
+
+ // Animated Active Pill
+ Rectangle {
+ id: indicator
+ y: 2
+ height: parent.height - 4
+ width: (parent.width - 4) / Math.max(1, (control.model ? control.model.length : 1))
+ x: 2 + Math.max(0, control.currentIndex) * width
+ visible: control.currentIndex >= 0
+ radius: Theme.radiusSmall
+ color: Theme.bgCard
+ border.color: Theme.borderActive
+ border.width: 1
+
+ Behavior on x {
+ NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad }
+ }
+ }
+
+ // Segments Row
+ Row {
+ anchors.fill: parent
+ anchors.margins: 2
+
+ Repeater {
+ model: control.model
+
+ Item {
+ id: segmentItem
+ width: (container.width - 4) / Math.max(1, control.model.length)
+ height: container.height - 4
+
+ Text {
+ anchors.centerIn: parent
+ text: getLabel(modelData)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ font.weight: control.currentIndex === index ? Font.DemiBold : Font.Normal
+ color: control.currentIndex === index ? Theme.textPrimary : (segMouse.containsMouse ? Theme.textPrimary : Theme.textMuted)
+ }
+
+ MouseArea {
+ id: segMouse
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (control.enabled) {
+ var val = getValue(modelData)
+ control.activated(val, index)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppSlider.qml b/src/desktop/qml/controls/AppSlider.qml
new file mode 100644
index 0000000..d9d1c3a
--- /dev/null
+++ b/src/desktop/qml/controls/AppSlider.qml
@@ -0,0 +1,200 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string label: ""
+ property real from: 0.0
+ property real to: 1.0
+ property real stepSize: 0.05
+ property real value: 0.0
+ property real defaultValue: 0.0
+ property int precision: 2
+ property string unit: ""
+ property bool enabled: true
+
+ signal valueModified(real newValue)
+
+ implicitWidth: 260
+ implicitHeight: 48
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled
+
+ function keyboardStep(direction) {
+ var step = stepSize > 0 ? stepSize : (to - from) / 100
+ var next = Math.max(from, Math.min(to, value + direction * step))
+ valueModified(next)
+ }
+ Keys.onPressed: (event) => {
+ if (!enabled) return
+ if (event.key === Qt.Key_Left || event.key === Qt.Key_Down) { keyboardStep(-1); event.accepted = true }
+ else if (event.key === Qt.Key_Right || event.key === Qt.Key_Up) { keyboardStep(1); event.accepted = true }
+ else if (event.key === Qt.Key_Home) { valueModified(from); event.accepted = true }
+ else if (event.key === Qt.Key_End) { valueModified(to); event.accepted = true }
+ }
+
+ // Top row: Label, Reset icon, and Numeric Readout
+ Row {
+ id: headerRow
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 18
+
+ Text {
+ id: labelText
+ text: control.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textSecondary
+ anchors.verticalCenter: parent.verticalCenter
+ }
+
+ Item {
+ // Spacer
+ width: Math.max(8, headerRow.width - labelText.implicitWidth - valueDisplayRow.implicitWidth)
+ height: 1
+ }
+
+ Row {
+ id: valueDisplayRow
+ spacing: 6
+ anchors.verticalCenter: parent.verticalCenter
+
+ // Reset action
+ Rectangle {
+ width: 14
+ height: 14
+ radius: 7
+ color: resetArea.containsMouse ? Theme.bgHover : "transparent"
+ visible: Math.abs(control.value - control.defaultValue) > 0.001
+ anchors.verticalCenter: parent.verticalCenter
+
+ Text {
+ anchors.centerIn: parent
+ text: "R"
+ font.pixelSize: 10
+ color: resetArea.containsMouse ? Theme.accent : Theme.textMuted
+ }
+
+ MouseArea {
+ id: resetArea
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: Qt.PointingHandCursor
+ onClicked: {
+ control.valueModified(control.defaultValue)
+ }
+ }
+ }
+
+ Text {
+ text: {
+ var strVal = control.precision > 0 ? control.value.toFixed(control.precision) : Math.round(control.value).toString()
+ return control.unit !== "" ? (strVal + " " + control.unit) : strVal
+ }
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ font.weight: Font.DemiBold
+ color: Math.abs(control.value - control.defaultValue) > 0.001 ? Theme.accent : Theme.textPrimary
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+ }
+
+ // Slider track & thumb
+ Item {
+ id: trackArea
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: parent.bottom
+ height: 22
+
+ // Background groove
+ Rectangle {
+ id: groove
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 4
+ radius: 2
+ color: Theme.bgInput
+ border.color: Theme.borderSubtle
+ border.width: 1
+ }
+
+ // Active highlighted track fill
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.left: groove.left
+ width: Math.max(0, Math.min(groove.width, (thumb.x + thumb.width / 2)))
+ height: 4
+ radius: 2
+ color: Theme.accent
+ }
+
+ // Thumb handle
+ Rectangle {
+ id: thumb
+ y: (trackArea.height - height) / 2
+ x: {
+ var range = control.to - control.from
+ if (range <= 0) return 0
+ var pct = Math.max(0.0, Math.min(1.0, (control.value - control.from) / range))
+ return pct * (trackArea.width - width)
+ }
+ width: 14
+ height: 14
+ radius: 7
+ color: sliderMouse.containsMouse || sliderMouse.drag.active ? "#FFFFFF" : Theme.textPrimary
+ border.color: control.activeFocus || sliderMouse.drag.active ? Theme.accent : Theme.borderActive
+ border.width: 2
+
+ Rectangle {
+ anchors.centerIn: parent
+ width: 4
+ height: 4
+ radius: 2
+ color: Theme.accent
+ }
+
+ Behavior on scale {
+ NumberAnimation { duration: Theme.animFast }
+ }
+ }
+
+ MouseArea {
+ id: sliderMouse
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+
+ function updateValue(mouseX) {
+ var clampedX = Math.max(0, Math.min(trackArea.width - thumb.width, mouseX - thumb.width / 2))
+ var pct = clampedX / (trackArea.width - thumb.width)
+ var rawVal = control.from + pct * (control.to - control.from)
+ if (control.stepSize > 0) {
+ var steps = Math.round((rawVal - control.from) / control.stepSize)
+ rawVal = control.from + steps * control.stepSize
+ }
+ rawVal = Math.max(control.from, Math.min(control.to, rawVal))
+ control.valueModified(rawVal)
+ }
+
+ onPressed: (mouse) => {
+ if (control.enabled) updateValue(mouse.x)
+ }
+
+ onPositionChanged: (mouse) => {
+ if (control.enabled && pressed) updateValue(mouse.x)
+ }
+
+ onDoubleClicked: {
+ if (control.enabled) {
+ control.valueModified(control.defaultValue)
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppSwitch.qml b/src/desktop/qml/controls/AppSwitch.qml
new file mode 100644
index 0000000..fc1d405
--- /dev/null
+++ b/src/desktop/qml/controls/AppSwitch.qml
@@ -0,0 +1,72 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string label: ""
+ property bool checked: false
+ property bool enabled: true
+
+ signal toggled(bool isChecked)
+
+ implicitWidth: Math.max(120, labelText.implicitWidth + 48)
+ implicitHeight: 26
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled
+ Keys.onPressed: (event) => { if (enabled && (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter)) { toggled(!checked); event.accepted = true } }
+
+ Row {
+ anchors.fill: parent
+ spacing: 10
+
+ Rectangle {
+ id: track
+ width: 38
+ height: 20
+ radius: 10
+ anchors.verticalCenter: parent.verticalCenter
+ color: control.checked ? Theme.accent : Theme.bgInput
+ border.color: control.activeFocus ? Theme.accent : (control.checked ? Theme.accent : (mouseArea.containsMouse ? Theme.borderActive : Theme.borderDefault))
+ border.width: 1
+
+ Behavior on color { ColorAnimation { duration: Theme.animFast } }
+
+ // Switch thumb
+ Rectangle {
+ id: thumb
+ y: 2
+ x: control.checked ? (track.width - width - 2) : 2
+ width: 16
+ height: 16
+ radius: 8
+ color: "#FFFFFF"
+
+ Behavior on x {
+ NumberAnimation { duration: Theme.animFast; easing.type: Easing.OutQuad }
+ }
+ }
+ }
+
+ Text {
+ id: labelText
+ anchors.verticalCenter: parent.verticalCenter
+ text: control.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: mouseArea.containsMouse ? Theme.textPrimary : Theme.textSecondary
+ }
+ }
+
+ MouseArea {
+ id: mouseArea
+ anchors.fill: parent
+ hoverEnabled: control.enabled
+ cursorShape: control.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
+ onClicked: {
+ if (control.enabled) {
+ control.toggled(!control.checked)
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/controls/AppTextField.qml b/src/desktop/qml/controls/AppTextField.qml
new file mode 100644
index 0000000..b63a58d
--- /dev/null
+++ b/src/desktop/qml/controls/AppTextField.qml
@@ -0,0 +1,116 @@
+import QtQuick
+import ".."
+
+Item {
+ id: control
+
+ property string label: ""
+ property string placeholderText: ""
+ property string text: ""
+ property bool enabled: true
+ property int fieldHeight: Theme.controlHeight
+ property bool readOnly: false
+ property bool commitOnEveryEdit: true
+
+ signal accepted()
+ signal textEdited(string newText)
+ signal textCommitted(string newText)
+
+ implicitWidth: 240
+ implicitHeight: label !== "" ? (fieldHeight + 20) : fieldHeight
+ opacity: enabled ? 1.0 : 0.45
+ activeFocusOnTab: enabled && !readOnly
+
+ function syncFromCanonical() {
+ if (!input.activeFocus || input.text !== control.text) {
+ input.text = control.text
+ }
+ }
+ onTextChanged: syncFromCanonical()
+ Component.onCompleted: syncFromCanonical()
+
+ Text {
+ visible: control.label !== ""
+ anchors.top: parent.top
+ anchors.left: parent.left
+ text: control.label
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textSecondary
+ }
+
+ Rectangle {
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: control.fieldHeight
+ radius: Theme.radiusMedium
+ color: Theme.bgInput
+ border.color: input.activeFocus ? Theme.accent : Theme.borderDefault
+ border.width: 1
+
+ TextInput {
+ id: input
+ anchors.left: parent.left
+ anchors.leftMargin: 10
+ anchors.right: clearBtn.visible ? clearBtn.left : parent.right
+ anchors.rightMargin: 8
+ anchors.verticalCenter: parent.verticalCenter
+ readOnly: control.readOnly
+ enabled: control.enabled
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textPrimary
+ selectByMouse: true
+ selectionColor: Theme.accent
+ selectedTextColor: "#FFFFFF"
+ clip: true
+
+ onTextEdited: {
+ if (control.commitOnEveryEdit) control.textEdited(text)
+ }
+ onEditingFinished: {
+ control.textCommitted(text)
+ if (!control.commitOnEveryEdit) control.textEdited(text)
+ control.syncFromCanonical()
+ }
+ onAccepted: {
+ control.textCommitted(text)
+ if (!control.commitOnEveryEdit) control.textEdited(text)
+ control.accepted()
+ }
+
+ Text {
+ anchors.fill: parent
+ visible: input.text === "" && !input.activeFocus
+ text: control.placeholderText
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeLabel
+ color: Theme.textMuted
+ }
+ }
+
+ Text {
+ id: clearBtn
+ visible: input.text !== "" && !control.readOnly && control.enabled
+ anchors.right: parent.right
+ anchors.rightMargin: 8
+ anchors.verticalCenter: parent.verticalCenter
+ text: "x"
+ font.pixelSize: 14
+ color: clearMouse.containsMouse ? Theme.textPrimary : Theme.textMuted
+ MouseArea {
+ id: clearMouse
+ anchors.fill: parent
+ anchors.margins: -5
+ hoverEnabled: true
+ cursorShape: Qt.PointingHandCursor
+ onClicked: {
+ input.text = ""
+ control.textEdited("")
+ control.textCommitted("")
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/qmldir b/src/desktop/qml/qmldir
new file mode 100644
index 0000000..d57fb86
--- /dev/null
+++ b/src/desktop/qml/qmldir
@@ -0,0 +1 @@
+singleton Theme 1.0 Theme.qml
diff --git a/src/desktop/qml/views/AboutView.qml b/src/desktop/qml/views/AboutView.qml
new file mode 100644
index 0000000..3bbd6a7
--- /dev/null
+++ b/src/desktop/qml/views/AboutView.qml
@@ -0,0 +1,35 @@
+import QtQuick
+import ".."
+import "../controls"
+
+Rectangle {
+ id: root
+ property var appBridge: null
+ color: Theme.bgBase
+
+ Item {
+ anchors.fill: parent; anchors.margins: 28
+ Column {
+ id: aboutCol
+ width: Math.min(parent.width, 1120); anchors.centerIn: parent; spacing: 20
+ Column {
+ anchors.horizontalCenter: parent.horizontalCenter; spacing: 4
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Visual Enhancer"; font.family: Theme.fontFamily; font.pixelSize: 22; font.weight: Font.Bold; color: Theme.textPrimary
+ }
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Advanced neural image & video processing"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textSecondary
+ }
+ }
+
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter; spacing: 12
+ AppButton { text: "GitHub Repository"; onClicked: Qt.openUrlExternally("https://github.com/Merserk/dlss5-visual-enhancer") }
+ AppButton { text: "Support on Patreon"; onClicked: Qt.openUrlExternally("https://www.patreon.com/Merserk") }
+ }
+ Text { anchors.horizontalCenter: parent.horizontalCenter; text: "© 2026 Merserk. NVIDIA, DLSS, and RTX are trademarks of NVIDIA Corporation."; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textMuted }
+ }
+ }
+}
diff --git a/src/desktop/qml/views/FrameInterpolationView.qml b/src/desktop/qml/views/FrameInterpolationView.qml
new file mode 100644
index 0000000..652542a
--- /dev/null
+++ b/src/desktop/qml/views/FrameInterpolationView.qml
@@ -0,0 +1,249 @@
+import QtQuick
+import ".."
+import "../controls"
+import "../components"
+
+Item {
+ id: root
+
+ property var appBridge: null
+ readonly property int adaptiveInspectorWidth: width >= 2560 ? 520 : (width >= 1920 ? 460 : (width >= 1600 ? 420 : (width >= 1280 ? 380 : 340)))
+
+ Row {
+ anchors.fill: parent
+
+ // Center Area: Media Viewport + Batch Queue Drawer
+ Item {
+ width: parent.width - sidebar.width
+ height: parent.height
+
+ MediaViewport {
+ id: viewport
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: queueDrawer.top
+ appBridge: root.appBridge
+ }
+
+ BatchQueueDrawer {
+ id: queueDrawer
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ appBridge: root.appBridge
+ queueModel: root.appBridge ? root.appBridge.fiQueue : null
+ hidden: appBridge ? appBridge.focusPreview : false
+ expandedHeight: appBridge ? appBridge.queueHeight : 190
+ }
+ }
+
+ // Right Sidebar
+ Rectangle {
+ id: sidebar
+ width: appBridge && appBridge.focusPreview ? 0 : Math.max(root.adaptiveInspectorWidth, Math.min(560, appBridge ? appBridge.inspectorWidth : root.adaptiveInspectorWidth))
+ height: parent.height
+ visible: width > 0
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ MouseArea {
+ id: inspectorResizeHandle
+ anchors.left: parent.left
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ width: 6
+ z: 100
+ cursorShape: Qt.SizeHorCursor
+ onPositionChanged: (mouse) => {
+ if (!pressed || !appBridge) return
+ var pt = inspectorResizeHandle.mapToItem(root, mouse.x, mouse.y)
+ appBridge.inspectorWidth = Math.max(300, Math.min(560, root.width - pt.x))
+ }
+ }
+
+ Column {
+ anchors.fill: parent
+
+ Flickable {
+ width: parent.width
+ height: parent.height - actionBar.height
+ contentWidth: width
+ contentHeight: contentCol.implicitHeight + 24
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+
+ Column {
+ id: contentCol
+ width: parent.width - 24
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: parent.top
+ anchors.topMargin: 12
+ spacing: 12
+
+ // Card 1: Frame Generation Configuration
+ AppCard {
+ width: parent.width
+ title: "DLSS-G Frame Generation"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Target Output Frame Rate"
+ model: appBridge ? appBridge.fiFpsChoices : []
+ currentValue: appBridge ? appBridge.fiTargetFps : "60"
+ onActivated: (v) => { if (appBridge) appBridge.fiTargetFps = v }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "DLSS-G Engine"
+ model: appBridge ? appBridge.fiEngineChoices : []
+ currentValue: appBridge ? appBridge.fiEngine : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.fiEngine = v }
+ }
+
+ Text {
+ width: parent.width
+ text: appBridge ? appBridge.outputEstimate : ""
+ wrapMode: Text.Wrap
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textMuted
+ }
+ }
+ }
+
+ // Card 2: Export Settings
+ AppCard {
+ width: parent.width
+ title: "Encoding & Output"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Video Codec"
+ model: appBridge ? appBridge.codecChoices : []
+ currentValue: appBridge ? appBridge.fiCodec : "H.264 (NVIDIA NVENC)"
+ onActivated: (v) => { if (appBridge) appBridge.fiCodec = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Container (automatic)"
+ model: appBridge ? appBridge.containerChoices : []
+ currentValue: appBridge ? appBridge.fiContainer : "MP4"
+ enabled: false
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Quality Preset"
+ model: appBridge ? appBridge.encodingQualityChoices : []
+ currentValue: appBridge ? appBridge.fiQuality : "Auto (Default)"
+ onActivated: (v) => { if (appBridge) appBridge.fiQuality = v }
+ }
+
+ AppCheckBox {
+ label: "Preserve 10-bit HDR"
+ checked: appBridge ? appBridge.fiHdrMode : false
+ enabled: appBridge ? appBridge.fiHdrSupported : false
+ onToggled: (c) => { if (appBridge) appBridge.fiHdrMode = c }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Rename Mode"
+ model: appBridge ? appBridge.renameModeChoices : []
+ currentValue: appBridge ? appBridge.fiRenameMode : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.fiRenameMode = v }
+ }
+
+ AppTextField {
+ visible: appBridge && appBridge.fiRenameMode === "Custom"
+ width: parent.width
+ label: "Custom Suffix"
+ text: appBridge ? appBridge.fiCustomSuffix : "_Frame_Interpolation"
+ onTextEdited: (t) => { if (appBridge) appBridge.fiCustomSuffix = t }
+ }
+ }
+ }
+ }
+ }
+
+ // Sticky Bottom Action Bar
+ Rectangle {
+ id: actionBar
+ width: parent.width
+ height: 54
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Column {
+ anchors.fill: parent
+ anchors.margins: 8
+ spacing: 4
+
+ Row {
+ width: parent.width
+ spacing: 8
+
+ AppButton {
+ text: "Preview"
+ width: 90
+ buttonHeight: 34
+ enabled: appBridge ? appBridge.canPreview : false
+ onClicked: { if (appBridge) appBridge.renderPreviewAt(viewport.playheadMs) }
+ }
+
+ AppComboBox {
+ width: 60
+ comboHeight: 34
+ dropUp: true
+ model: appBridge ? appBridge.fiPreviewLengthChoices : []
+ currentValue: appBridge ? appBridge.fiPreviewLength : "3"
+ onActivated: (v) => { if (appBridge) appBridge.fiPreviewLength = v }
+ }
+
+ AppButton {
+ text: appBridge && appBridge.canStop ? "Stop" : "Interpolate Video(s)"
+ variant: appBridge && appBridge.canStop ? "danger" : "primary"
+ width: parent.width - 362
+ buttonHeight: 34
+ enabled: appBridge ? (appBridge.canStop || appBridge.canRender) : false
+ onClicked: {
+ if (appBridge) {
+ if (appBridge.canStop) appBridge.stopActiveBatch()
+ else if (appBridge.canRender) appBridge.startActiveBatch()
+ }
+ }
+ }
+
+ AppButton {
+ text: "Reset"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.resetTabSettings("frame-interpolation") }
+ }
+
+ AppButton {
+ text: "Outputs"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.openFolder("") }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/views/LiveView.qml b/src/desktop/qml/views/LiveView.qml
new file mode 100644
index 0000000..9c4b9d5
--- /dev/null
+++ b/src/desktop/qml/views/LiveView.qml
@@ -0,0 +1,590 @@
+import QtQuick
+import QtQuick.Window
+import ".."
+import "../controls"
+import "../components"
+
+Item {
+ id: root
+
+ property var appBridge: null
+ readonly property int adaptiveInspectorWidth: width >= 2560 ? 520 : (width >= 1920 ? 470 : (width >= 1600 ? 430 : (width >= 1280 ? 390 : 350)))
+ readonly property bool showLiveVideo: appBridge && (appBridge.isLiveRunning || appBridge.operationState === "LiveStarting")
+
+ property string sourceMode: "Online"
+ property string onlineUrl: ""
+ property string localVideoPath: ""
+ property string sourceQuality: "Auto"
+ property string maxHeight: "720"
+ property string segmentSeconds: "2"
+ property string targetFps: "Auto"
+ property real bufferSeconds: 6.0
+ property bool videoExpanded: false
+
+ function syncLiveVideo() {
+ if (!root.showLiveVideo || !appBridge || !appBridge.mpvEmbed) return
+ // Native overlay guard: the embed container is a top-level OS window
+ // that StackLayout/clip cannot hide. Never (re)position or re-show
+ // it unless the Live tab is the visible one and this view is shown.
+ if (!root.visible) return
+ try {
+ if (appBridge.activeTab !== "live") return
+ } catch (e) {}
+ var host = Window.window
+ if (!host || !host.contentItem) return
+ // Client-relative: the embed container is a child window, so its
+ // origin is the client area (below the native caption), not the
+ // outer frame. This holds with any window frame style.
+ var pt = videoSurface.mapToGlobal(0, 0)
+ var origin = host.contentItem.mapToGlobal(0, 0)
+ appBridge.mpvEmbed.setGeometry(pt.x - origin.x, pt.y - origin.y, videoSurface.width, videoSurface.height)
+ }
+
+ onVisibleChanged: {
+ // StackLayout hides non-current tabs: re-sync on return so the
+ // native window snaps back to the slot without waiting for the
+ // 250ms keep-alive timer.
+ if (visible && showLiveVideo) Qt.callLater(syncLiveVideo)
+ }
+
+ onShowLiveVideoChanged: {
+ if (showLiveVideo) Qt.callLater(syncLiveVideo)
+ else videoExpanded = false
+ }
+
+ Row {
+ anchors.fill: parent
+
+ // Left Area: Live Telemetry & Monitoring Canvas
+ Rectangle {
+ width: parent.width - sidebar.width
+ height: parent.height
+ color: Theme.bgBase
+
+ Column {
+ id: leftCol
+ anchors.fill: parent
+ anchors.margins: 24
+ spacing: 16
+
+ // Live Monitor Header
+ Row {
+ id: liveHeader
+ width: parent.width
+ spacing: 12
+
+ Rectangle {
+ width: 12
+ height: 12
+ radius: 6
+ color: appBridge && appBridge.isLiveRunning ? Theme.danger : Theme.textMuted
+ anchors.verticalCenter: parent.verticalCenter
+
+ SequentialAnimation on opacity {
+ running: appBridge && appBridge.isLiveRunning
+ loops: Animation.Infinite
+ NumberAnimation { from: 1.0; to: 0.3; duration: 800 }
+ NumberAnimation { from: 0.3; to: 1.0; duration: 800 }
+ }
+ }
+
+ Text {
+ text: appBridge && appBridge.isLiveRunning ? "LIVE STREAM ACTIVE" : "LIVE ENGINE STANDBY"
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeTitle
+ font.weight: Font.Bold
+ color: appBridge && appBridge.isLiveRunning ? Theme.danger : Theme.textSecondary
+ anchors.verticalCenter: parent.verticalCenter
+ }
+ }
+
+ // In-tab player (embedded MPV). Always visible so standby
+ // mirrors the active layout; idle shows a black blank slot.
+ Column {
+ id: livePlayer
+ width: parent.width
+ visible: true
+ spacing: 8
+
+ Item {
+ id: videoSurface
+ width: parent.width
+ // Flexible: take all vertical room left by header /
+ // transport / KPI / log strip (theater mode takes all).
+ // Idle shows a 16:9 black blank of the same shape.
+ height: {
+ if (!root.showLiveVideo) return Math.max(200, Math.min(width * 9 / 16, 720))
+ if (root.videoExpanded)
+ return Math.max(200, leftCol.height - liveHeader.height - 34 - 8 - 16)
+ var room = leftCol.height - liveHeader.height - kpiFlow.height - 120 - 34 - 8 - 48
+ return Math.max(200, Math.min(Math.min(width * 9 / 16, 720), room))
+ }
+ onWidthChanged: root.syncLiveVideo()
+ onHeightChanged: root.syncLiveVideo()
+
+ Rectangle {
+ anchors.fill: parent
+ radius: Theme.radiusLarge
+ color: "#000000"
+ border.color: Theme.borderDefault
+ border.width: 1
+ }
+
+ // Shown only while a session is starting/running and the
+ // first frame hasn't rendered yet: idle is a pure
+ // black blank, never a "Buffering..." message.
+ Column {
+ anchors.centerIn: parent
+ spacing: 10
+ visible: root.showLiveVideo && (appBridge ? !appBridge.livePlayerStarted : true)
+
+ Rectangle {
+ width: 12
+ height: 12
+ radius: 6
+ color: Theme.accent
+ anchors.horizontalCenter: parent.horizontalCenter
+
+ SequentialAnimation on opacity {
+ running: true
+ loops: Animation.Infinite
+ NumberAnimation { from: 1.0; to: 0.3; duration: 600 }
+ NumberAnimation { from: 0.3; to: 1.0; duration: 600 }
+ }
+ }
+
+ Text {
+ text: appBridge && appBridge.operationState === "LiveStarting"
+ ? "Loading... Please wait."
+ : "Buffering... Please wait."
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeBody
+ color: Theme.textSecondary
+ anchors.horizontalCenter: parent.horizontalCenter
+ }
+ }
+ }
+
+ Row {
+ id: liveTransport
+ width: parent.width
+ height: 34
+ spacing: 8
+
+ AppButton {
+ width: 88
+ buttonHeight: 32
+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.paused ? "Resume" : "Pause"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.togglePause() }
+ }
+ AppButton {
+ width: 88
+ buttonHeight: 32
+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.muted ? "Unmute" : "Mute"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.toggleMute() }
+ }
+ AppButton {
+ width: 52
+ buttonHeight: 32
+ text: "Vol-"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.volumeDown() }
+ }
+ Text {
+ width: 56
+ text: appBridge && appBridge.mpvEmbed ? "Vol " + appBridge.mpvEmbed.volume : "Vol -"
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textSecondary
+ elide: Text.ElideRight
+ anchors.verticalCenter: parent.verticalCenter
+ horizontalAlignment: Text.AlignHCenter
+ }
+ AppButton {
+ width: 52
+ buttonHeight: 32
+ text: "Vol+"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.volumeUp() }
+ }
+ // Spacer: pushes Expand + Full Screen to the right end
+ // (plain Row cannot right-anchor children). Clamped so
+ // narrow windows degrade to left-packed, never overlap.
+ Item {
+ width: Math.max(0, parent.width - 600)
+ height: 1
+ }
+ AppButton {
+ width: 104
+ buttonHeight: 32
+ text: root.videoExpanded ? "Restore" : "Expand"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { root.videoExpanded = !root.videoExpanded; Qt.callLater(root.syncLiveVideo) }
+ }
+ AppButton {
+ width: 104
+ buttonHeight: 32
+ text: appBridge && appBridge.mpvEmbed && appBridge.mpvEmbed.fullscreen ? "Exit Full" : "Full Screen"
+ enabled: appBridge && appBridge.isLiveRunning
+ onClicked: { if (appBridge && appBridge.mpvEmbed) appBridge.mpvEmbed.toggleFullscreen() }
+ }
+ }
+ }
+
+ Connections {
+ target: Window.window
+ function onXChanged() { root.syncLiveVideo() }
+ function onYChanged() { root.syncLiveVideo() }
+ function onWidthChanged() { root.syncLiveVideo() }
+ function onHeightChanged() { root.syncLiveVideo() }
+ }
+
+ Connections {
+ target: appBridge
+ function onActiveTabChanged() {
+ if (appBridge && appBridge.activeTab === "live" && root.showLiveVideo)
+ Qt.callLater(root.syncLiveVideo)
+ }
+ }
+
+ Timer {
+ interval: 250
+ running: root.showLiveVideo && root.visible && appBridge && appBridge.activeTab === "live"
+ repeat: true
+ onTriggered: root.syncLiveVideo()
+ }
+
+ // High-signal telemetry remains visible at a glance on large displays.
+ // Hidden in theater mode so the video takes the whole canvas.
+ Flow {
+ id: kpiFlow
+ width: parent.width
+ visible: !root.videoExpanded
+ height: root.videoExpanded ? 0 : (width >= 900 ? 72 : 144)
+ spacing: 8
+
+ Repeater {
+ model: [
+ { label: "SOURCE", value: appBridge && appBridge.liveSourceFps > 0 ? appBridge.liveSourceFps.toFixed(2) + " fps" : "-" },
+ { label: "OUTPUT", value: appBridge && appBridge.liveEffectiveFps > 0 ? appBridge.liveEffectiveFps.toFixed(2) + " fps" : (appBridge && appBridge.liveTargetFps > 0 ? appBridge.liveTargetFps.toFixed(2) + " fps" : "-") },
+ { label: "DLSS", value: appBridge && appBridge.liveDlssMs > 0 ? appBridge.liveDlssMs.toFixed(1) + " ms" : "-" },
+ { label: "ENCODE", value: appBridge && appBridge.liveEncodeMs > 0 ? appBridge.liveEncodeMs.toFixed(1) + " ms" : "-" },
+ { label: "DROPPED", value: appBridge ? String(appBridge.liveDroppedFrames) : "0" },
+ { label: "REBUFFER", value: appBridge ? String(appBridge.liveRebufferEvents) : "0" }
+ ]
+ delegate: Rectangle {
+ required property var modelData
+ width: kpiFlow.width >= 900 ? (kpiFlow.width - 40) / 6 : (kpiFlow.width - 16) / 3
+ height: 64
+ radius: Theme.radiusMedium
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ Column {
+ anchors.fill: parent; anchors.margins: 10; spacing: 4
+ Text { text: modelData.label; color: Theme.textMuted; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; font.weight: Font.DemiBold }
+ Text { text: modelData.value; color: Theme.textPrimary; font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeBody; font.weight: Font.DemiBold; elide: Text.ElideRight; width: parent.width }
+ }
+ }
+ }
+ }
+
+ // Telemetry Terminal Box: fills the remaining canvas in both
+ // idle and running states (scrollable), hidden in theater mode.
+ Rectangle {
+ id: telemetryBox
+ width: parent.width
+ visible: !root.videoExpanded
+ height: {
+ if (root.videoExpanded) return 0
+ return Math.max(140, parent.height - liveHeader.height - livePlayer.height - kpiFlow.height - 48)
+ }
+ radius: Theme.radiusLarge
+ color: Theme.bgSurface
+ border.color: Theme.borderDefault
+ border.width: 1
+ clip: true
+
+ Flickable {
+ anchors.fill: parent
+ anchors.margins: 16
+ contentWidth: width
+ contentHeight: telemetryText.implicitHeight
+ clip: true
+
+ Text {
+ id: telemetryText
+ width: parent.width
+ text: appBridge ? appBridge.liveStatusText : "Idle."
+ font.family: Theme.monoFontFamily
+ font.pixelSize: 13
+ lineHeight: 1.4
+ color: appBridge && appBridge.isLiveRunning ? Theme.textPrimary : Theme.textMuted
+ }
+ }
+ }
+ }
+ }
+
+ // Right Sidebar: Live Configuration
+ Rectangle {
+ id: sidebar
+ width: appBridge && appBridge.focusPreview ? 0 : Math.max(root.adaptiveInspectorWidth, Math.min(560, appBridge ? appBridge.inspectorWidth : root.adaptiveInspectorWidth))
+ height: parent.height
+ visible: width > 0
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ MouseArea {
+ id: inspectorResizeHandle
+ anchors.left: parent.left; anchors.top: parent.top; anchors.bottom: parent.bottom
+ width: 6; z: 100; cursorShape: Qt.SizeHorCursor
+ onPositionChanged: (mouse) => {
+ if (!pressed || !appBridge) return
+ var pt = inspectorResizeHandle.mapToItem(root, mouse.x, mouse.y)
+ appBridge.inspectorWidth = Math.max(300, Math.min(560, root.width - pt.x))
+ }
+ }
+
+ Column {
+ anchors.fill: parent
+
+ Flickable {
+ width: parent.width
+ height: parent.height - actionBar.height
+ contentWidth: width
+ contentHeight: liveCol.implicitHeight + 24
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+
+ Column {
+ id: liveCol
+ width: parent.width - 24
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: parent.top
+ anchors.topMargin: 12
+ spacing: 12
+
+ // Card 1: Source Selection
+ AppCard {
+ width: parent.width
+ title: "Stream Source"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppSegmentedControl {
+ width: parent.width
+ model: ["Online", "Local"]
+ currentValue: root.sourceMode
+ onActivated: (v) => { root.sourceMode = v }
+ }
+
+ AppTextField {
+ visible: root.sourceMode === "Online"
+ width: parent.width
+ label: "Online Stream URL"
+ placeholderText: "YouTube, Twitch, or HLS/RTMP URL..."
+ text: root.onlineUrl
+ onTextEdited: (t) => { root.onlineUrl = t }
+ }
+
+ AppFilePicker {
+ visible: root.sourceMode === "Local"
+ width: parent.width
+ label: "Local Video File"
+ placeholderText: "Select MP4/MKV video..."
+ selectedPath: root.localVideoPath
+ nameFilters: [
+ "Video Files (*.mp4 *.mkv *.mov *.avi *.webm *.m4v *.ts *.mts *.m2ts *.mxf *.vob *.wmv *.flv *.mpg *.mpeg *.mpe *.ogv *.3gp *.3g2 *.asf *.divx *.f4v *.m2v *.m1v *.m2t)",
+ "All Files (*.*)"
+ ]
+ onPathChanged: (p) => { root.localVideoPath = p }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Source Quality"
+ model: appBridge ? appBridge.liveSourceQualityChoices : []
+ currentValue: root.sourceQuality
+ onActivated: (v) => { root.sourceQuality = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Max Input Resolution"
+ model: appBridge ? appBridge.liveMaxHeightChoices : []
+ currentValue: root.maxHeight
+ onActivated: (v) => { root.maxHeight = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "HLS Segment Duration"
+ model: appBridge ? appBridge.liveSegmentChoices : []
+ currentValue: root.segmentSeconds
+ onActivated: (v) => { root.segmentSeconds = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Target FPS"
+ model: appBridge ? appBridge.liveFpsChoices : []
+ currentValue: root.targetFps
+ onActivated: (v) => { root.targetFps = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Playback Buffer"
+ unit: "sec"
+ from: 2
+ to: 30
+ stepSize: 1
+ precision: 0
+ defaultValue: 6
+ value: root.bufferSeconds
+ onValueModified: (v) => { root.bufferSeconds = Math.round(v) }
+ }
+ }
+ }
+
+ // Card 2: Live AI Neural Controls (Dynamic Live Sync!)
+ AppCard {
+ width: parent.width
+ title: "Live DLSS Effects"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "NR Style"
+ model: appBridge ? appBridge.nrStyleChoices : []
+ currentValue: appBridge ? appBridge.liveNrStyle : "Default"
+ onActivated: (v) => { if (appBridge) appBridge.liveNrStyle = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "NR Intensity"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.liveNrIntensity : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.liveNrIntensity = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Shimmer Suppression"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 0.70
+ value: appBridge ? appBridge.liveShimmerSuppression : 0.70
+ onValueModified: (v) => { if (appBridge) appBridge.liveShimmerSuppression = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Local Tone Strength"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.liveLocalToneStrength : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.liveLocalToneStrength = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Local Structure Strength"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.liveLocalStructureStrength : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.liveLocalStructureStrength = v }
+ }
+
+ AppSlider { width: parent.width; label: "NR Passes"; from: 1; to: 4; stepSize: 1; precision: 0; defaultValue: 1; value: appBridge ? appBridge.liveNrPasses : 1; onValueModified: (v) => { if (appBridge) appBridge.liveNrPasses = Math.round(v) } }
+ AppSlider { width: parent.width; label: "Skin Structure"; from: -1; to: 2; stepSize: 0.05; defaultValue: -1; value: appBridge ? appBridge.liveSkinStructureStrength : -1; onValueModified: (v) => { if (appBridge) appBridge.liveSkinStructureStrength = v } }
+ AppSwitch { label: "Automatic Mask"; checked: appBridge ? appBridge.liveAutomaticMask : false; onToggled: (v) => { if (appBridge) appBridge.liveAutomaticMask = v } }
+ AppSlider { width: parent.width; label: "Color Strength"; from: 0; to: 1; stepSize: 0.05; defaultValue: 1; value: appBridge ? appBridge.liveNrColorStrength : 1; onValueModified: (v) => { if (appBridge) appBridge.liveNrColorStrength = v } }
+ AppSlider { width: parent.width; label: "Tone Preservation"; from: 0; to: 1; stepSize: 0.05; defaultValue: 0; value: appBridge ? appBridge.liveTonePreservation : 0; onValueModified: (v) => { if (appBridge) appBridge.liveTonePreservation = v } }
+ AppSlider { width: parent.width; label: "Face / Skin Protection"; from: 0; to: 1; stepSize: 0.05; defaultValue: 0; value: appBridge ? appBridge.liveFaceSkinProtection : 0; onValueModified: (v) => { if (appBridge) appBridge.liveFaceSkinProtection = v } }
+ AppSlider { width: parent.width; label: "Grain Preservation"; from: 0; to: 1; stepSize: 0.05; defaultValue: 0; value: appBridge ? appBridge.liveGrainPreservation : 0; onValueModified: (v) => { if (appBridge) appBridge.liveGrainPreservation = v } }
+ AppSlider { width: parent.width; label: "Mask Feather"; from: 0; to: 128; stepSize: 1; precision: 0; defaultValue: 0; value: appBridge ? appBridge.liveMaskFeather : 0; onValueModified: (v) => { if (appBridge) appBridge.liveMaskFeather = Math.round(v) } }
+ AppComboBox { width: parent.width; dropUp: true; label: "Live Scale"; model: appBridge ? appBridge.nrScaleChoices : []; currentValue: appBridge ? appBridge.liveUpscalingFactor : 1.0; onActivated: (v) => { if (appBridge) appBridge.liveUpscalingFactor = v } }
+ }
+ }
+ }
+ }
+
+ // Action Bar
+ Rectangle {
+ id: actionBar
+ width: parent.width
+ height: 72
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Row {
+ anchors.fill: parent
+ anchors.margins: 10
+ spacing: 8
+
+ AppButton {
+ width: parent.width - 98
+ buttonHeight: 36
+ text: appBridge && appBridge.operationState === "LiveStarting" ? "Cancel Live Startup" : (appBridge && appBridge.isLiveRunning ? "Stop Live Session" : (appBridge && appBridge.operationState === "LiveStopping" ? "Stopping Live..." : "Start Live Session"))
+ variant: appBridge && appBridge.canStop ? "danger" : "primary"
+ enabled: appBridge ? (appBridge.canStartLive || appBridge.canStop) : false
+ onClicked: {
+ if (!appBridge) return
+ if (appBridge.canStop) {
+ appBridge.stopActiveBatch()
+ } else if (appBridge.canStartLive) {
+ appBridge.startLive(
+ root.sourceMode,
+ root.onlineUrl,
+ root.localVideoPath,
+ root.sourceQuality,
+ root.maxHeight,
+ root.segmentSeconds,
+ root.targetFps,
+ root.bufferSeconds
+ )
+ }
+ }
+ }
+
+ AppButton {
+ text: "Reset"
+ width: 90
+ buttonHeight: 36
+ onClicked: {
+ root.sourceMode = "Online"
+ root.onlineUrl = ""
+ root.localVideoPath = ""
+ root.sourceQuality = "Auto"
+ root.maxHeight = "720"
+ root.segmentSeconds = "2"
+ root.targetFps = "Auto"
+ root.bufferSeconds = 6
+ if (appBridge) appBridge.resetTabSettings("live")
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/views/NeuralRenderingView.qml b/src/desktop/qml/views/NeuralRenderingView.qml
new file mode 100644
index 0000000..463ebd6
--- /dev/null
+++ b/src/desktop/qml/views/NeuralRenderingView.qml
@@ -0,0 +1,392 @@
+import QtQuick
+import ".."
+import "../controls"
+import "../components"
+
+Item {
+ id: root
+
+ property var appBridge: null
+ readonly property int adaptiveInspectorWidth: width >= 2560 ? 520 : (width >= 1920 ? 460 : (width >= 1600 ? 420 : (width >= 1280 ? 380 : 340)))
+
+ readonly property bool isImage: appBridge ? (appBridge.nrMode === "Image") : true
+ readonly property var activeQueue: appBridge ? (isImage ? appBridge.nrImageQueue : appBridge.nrVideoQueue) : null
+
+ Row {
+ anchors.fill: parent
+
+ // Main Center Area: Media Viewport + Batch Queue Drawer
+ Item {
+ width: parent.width - sidebar.width
+ height: parent.height
+
+ MediaViewport {
+ id: viewport
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: queueDrawer.top
+ appBridge: root.appBridge
+ }
+
+ BatchQueueDrawer {
+ id: queueDrawer
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ appBridge: root.appBridge
+ queueModel: root.activeQueue
+ hidden: appBridge ? appBridge.focusPreview : false
+ expandedHeight: appBridge ? appBridge.queueHeight : 190
+ }
+ }
+
+ // Right Sidebar: Parameters & Inspector (Topaz-style)
+ Rectangle {
+ id: sidebar
+ width: appBridge && appBridge.focusPreview ? 0 : Math.max(root.adaptiveInspectorWidth, Math.min(560, appBridge ? appBridge.inspectorWidth : root.adaptiveInspectorWidth))
+ height: parent.height
+ visible: width > 0
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ MouseArea {
+ id: inspectorResizeHandle
+ anchors.left: parent.left
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ width: 6
+ z: 100
+ cursorShape: Qt.SizeHorCursor
+ onPositionChanged: (mouse) => {
+ if (!pressed || !appBridge) return
+ var pt = inspectorResizeHandle.mapToItem(root, mouse.x, mouse.y)
+ appBridge.inspectorWidth = Math.max(300, Math.min(560, root.width - pt.x))
+ }
+ }
+
+ Column {
+ anchors.fill: parent
+
+ // Workflow Submode Switcher: Image vs Video
+ Rectangle {
+ width: parent.width
+ height: 48
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Row {
+ anchors.centerIn: parent
+ spacing: 8
+
+ AppSegmentedControl {
+ model: ["Image", "Video"]
+ currentValue: root.appBridge ? root.appBridge.nrMode : "Image"
+ onActivated: (val) => {
+ if (root.appBridge) root.appBridge.nrMode = val
+ }
+ }
+ }
+ }
+
+ // Scrollable Cards Area
+ Flickable {
+ id: flick
+ width: parent.width
+ height: parent.height - 48 - actionBar.height
+ contentWidth: width
+ contentHeight: contentCol.implicitHeight + 24
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+
+ Column {
+ id: contentCol
+ width: parent.width - 24
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: parent.top
+ anchors.topMargin: 12
+ spacing: 12
+
+ // Card 1: Neural Rendering Parameters
+ AppCard {
+ width: parent.width
+ title: "DLSS Neural Model"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "NR Style"
+ model: appBridge ? appBridge.nrStyleChoices : []
+ currentValue: appBridge ? appBridge.nrStyle : "Default"
+ onActivated: (v) => { if (appBridge) appBridge.nrStyle = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Scale"
+model: appBridge ? appBridge.nrScaleChoices : []
+ currentValue: appBridge ? appBridge.upscalingFactor : 1.0
+ onActivated: (v) => { if (appBridge) appBridge.upscalingFactor = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "NR Intensity"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.nrIntensity : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.nrIntensity = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "NR Passes"
+ from: 1
+ to: 4
+ stepSize: 1
+ precision: 0
+ defaultValue: 1
+ value: appBridge ? appBridge.nrPasses : 1
+ onValueModified: (v) => { if (appBridge) appBridge.nrPasses = Math.round(v) }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Local Tone Strength"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.localToneStrength : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.localToneStrength = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Local Structure Strength"
+ from: 0.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: 1.0
+ value: appBridge ? appBridge.localStructureStrength : 1.0
+ onValueModified: (v) => { if (appBridge) appBridge.localStructureStrength = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Skin Structure Strength"
+ from: -1.0
+ to: 2.0
+ stepSize: 0.05
+ defaultValue: -1.0
+ value: appBridge ? appBridge.skinStructureStrength : -1.0
+ onValueModified: (v) => { if (appBridge) appBridge.skinStructureStrength = v }
+ }
+
+ AppSwitch {
+ label: "Automatic Mask"
+ checked: appBridge ? appBridge.automaticMask : false
+ onToggled: (c) => { if (appBridge) appBridge.automaticMask = c }
+ }
+
+ AppSlider {
+ visible: !root.isImage
+ width: parent.width
+ label: "Shimmer Suppression"
+ from: 0.0
+ to: 1.0
+ stepSize: 0.05
+ defaultValue: 0.70
+ value: appBridge ? appBridge.shimmerSuppression : 0.70
+ onValueModified: (v) => { if (appBridge) appBridge.shimmerSuppression = v }
+ }
+ }
+ }
+
+ // Card 2: Composition & Masking
+ CompositionCard {
+ width: parent.width
+ appBridge: root.appBridge
+ }
+
+ // Card 3: Export & Encoding Settings
+ AppCard {
+ width: parent.width
+ title: "Export Settings"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ // IMAGE SPECIFIC
+ Column {
+ visible: root.isImage
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Output Format"
+ model: appBridge ? appBridge.imageFormatChoices : []
+ currentValue: appBridge ? appBridge.imageFormat : "PNG"
+ onActivated: (v) => { if (appBridge) appBridge.imageFormat = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Image Quality"
+ from: 1
+ to: 100
+ stepSize: 1
+ precision: 0
+ defaultValue: 95
+ value: appBridge ? appBridge.imageQuality : 95
+ onValueModified: (v) => { if (appBridge) appBridge.imageQuality = Math.round(v) }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Rename Mode"
+ model: appBridge ? appBridge.renameModeChoices : []
+ currentValue: appBridge ? appBridge.imageRenameMode : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.imageRenameMode = v }
+ }
+
+ AppTextField {
+ visible: appBridge && appBridge.imageRenameMode === "Custom"
+ width: parent.width
+ label: "Custom Suffix"
+ text: appBridge ? appBridge.imageCustomSuffix : "_Neural_Rendering"
+ onTextEdited: (t) => { if (appBridge) appBridge.imageCustomSuffix = t }
+ }
+ }
+
+ // VIDEO SPECIFIC
+ Column {
+ visible: !root.isImage
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Video Codec"
+ model: appBridge ? appBridge.codecChoices : []
+ currentValue: appBridge ? appBridge.videoCodec : "H.264 (NVIDIA NVENC)"
+ onActivated: (v) => { if (appBridge) appBridge.videoCodec = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Container"
+ model: appBridge ? appBridge.containerChoices : []
+ currentValue: appBridge ? appBridge.videoContainer : "MP4"
+ enabled: false
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Encoding Quality"
+ model: appBridge ? appBridge.encodingQualityChoices : []
+ currentValue: appBridge ? appBridge.videoQuality : "Auto (Default)"
+ onActivated: (v) => { if (appBridge) appBridge.videoQuality = v }
+ }
+
+ AppCheckBox {
+ label: "10-bit HDR Mode"
+ checked: appBridge ? appBridge.videoHdrMode : false
+ onToggled: (c) => { if (appBridge) appBridge.videoHdrMode = c }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Rename Mode"
+ model: appBridge ? appBridge.renameModeChoices : []
+ currentValue: appBridge ? appBridge.videoRenameMode : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.videoRenameMode = v }
+ }
+
+ AppTextField {
+ visible: appBridge && appBridge.videoRenameMode === "Custom"
+ width: parent.width
+ label: "Custom Suffix"
+ text: appBridge ? appBridge.videoCustomSuffix : "_Neural_Rendering"
+ onTextEdited: (t) => { if (appBridge) appBridge.videoCustomSuffix = t }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Sticky Bottom Action Bar
+ Rectangle {
+ id: actionBar
+ width: parent.width
+ height: 54
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Column {
+ anchors.fill: parent
+ anchors.margins: 8
+ spacing: 4
+
+ Row {
+ width: parent.width
+ spacing: 8
+
+ AppButton {
+ text: "Preview"
+ width: 90
+ buttonHeight: 34
+ enabled: appBridge ? appBridge.canPreview : false
+ onClicked: {
+ if (appBridge) appBridge.renderPreviewAt(viewport.playheadMs)
+ }
+ }
+
+ AppButton {
+ text: appBridge && appBridge.canStop ? "Stop" : (root.isImage ? "Render Image(s)" : "Render Video(s)")
+ variant: appBridge && appBridge.canStop ? "danger" : "primary"
+ width: parent.width - 294
+ buttonHeight: 34
+ enabled: appBridge ? (appBridge.canStop || appBridge.canRender) : false
+ onClicked: {
+ if (appBridge) {
+ if (appBridge.canStop) {
+ appBridge.stopActiveBatch()
+ } else if (appBridge.canRender) {
+ appBridge.startActiveBatch()
+ }
+ }
+ }
+ }
+
+ AppButton {
+ text: "Reset"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.resetTabSettings("neural-rendering") }
+ }
+
+ AppButton {
+ text: "Outputs"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.openFolder("") }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/qml/views/SettingsView.qml b/src/desktop/qml/views/SettingsView.qml
new file mode 100644
index 0000000..43adfd9
--- /dev/null
+++ b/src/desktop/qml/views/SettingsView.qml
@@ -0,0 +1,124 @@
+import QtQuick
+import QtQuick.Dialogs
+import QtQuick.Controls as QQC2
+import ".."
+import "../controls"
+
+Rectangle {
+ id: root
+ property var appBridge: null
+ property string presetName: ""
+ color: Theme.bgBase
+
+ Flickable {
+ anchors.fill: parent; anchors.margins: 28
+ contentWidth: width
+ contentHeight: settingsCol.implicitHeight + 48
+ clip: true; boundsBehavior: Flickable.StopAtBounds
+
+ Column {
+ id: settingsCol
+ width: Math.min(parent.width, 1120)
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 20
+
+ Column {
+ width: parent.width; spacing: 4
+ Text { text: "Preferences & System Configuration"; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeHeader; font.weight: Font.Bold; color: Theme.textPrimary }
+ Text { width: parent.width; text: "Configure hardware assignment, preview behavior, native layout, and portable settings presets."; wrapMode: Text.Wrap; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textSecondary }
+ }
+
+ Flow {
+ id: cardFlow
+ width: parent.width; spacing: 14
+ property real cardWidth: width >= 920 ? (width - spacing) / 2 : width
+
+ AppCard {
+ width: cardFlow.cardWidth; title: "Hardware & GPU Acceleration"; collapsible: false
+ Column {
+ width: parent.width; spacing: 16
+ AppComboBox { width: parent.width; label: "AI Processing GPU (Tensor Cores / NGX)"; model: appBridge ? appBridge.aiGpuChoices : []; currentValue: appBridge ? appBridge.aiGpuUuid : "auto"; onActivated: (v) => { if (appBridge) appBridge.aiGpuUuid = v } }
+ AppComboBox { width: parent.width; label: "Video Processing GPU (NVENC / NVDEC)"; model: appBridge ? appBridge.videoGpuChoices : []; currentValue: appBridge ? appBridge.videoGpuUuid : "auto"; onActivated: (v) => { if (appBridge) appBridge.videoGpuUuid = v } }
+ Text { width: parent.width; wrapMode: Text.Wrap; text: appBridge && appBridge.runtimeState === "Failed" ? appBridge.runtimeError : ("Runtime: " + (appBridge ? appBridge.runtimeState : "Initializing")); font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall; color: appBridge && appBridge.runtimeState === "Failed" ? Theme.danger : Theme.textMuted }
+ }
+ }
+
+ AppCard {
+ width: cardFlow.cardWidth; title: "Preview & Rendering Engine"; collapsible: false
+ Column {
+ width: parent.width; spacing: 16
+ AppSegmentedControl { width: parent.width; label: "Preview Encoding Strategy"; model: appBridge ? appBridge.previewEncodingChoices : []; currentValue: appBridge ? appBridge.previewEncoding : "Auto"; onActivated: (v) => { if (appBridge) appBridge.previewEncoding = v } }
+ AppSwitch { width: parent.width; label: "Realtime Preview"; checked: appBridge ? appBridge.autoPreviewEnabled : true; enabled: appBridge ? appBridge.runtimeState === "Ready" : false; onToggled: (v) => { if (appBridge) appBridge.autoPreviewEnabled = v } }
+ AppCheckBox { label: "Full-size high-fidelity image previews"; checked: appBridge ? appBridge.fullSizeImagePreviews : false; onToggled: (c) => { if (appBridge) appBridge.fullSizeImagePreviews = c } }
+ Text { width: parent.width; wrapMode: Text.Wrap; text: "Full-size previews preserve source detail but can use substantially more RAM on large RAW/8K images."; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.textMuted }
+ }
+ }
+
+ AppCard {
+ width: cardFlow.cardWidth; title: "Settings Presets"; collapsible: false
+ Column {
+ width: parent.width; spacing: 12
+ AppTextField { width: parent.width; placeholderText: "Preset name (e.g. 4K Master)..."; text: root.presetName; onTextEdited: (t) => root.presetName = t }
+ Row {
+ spacing: 8
+ AppButton {
+ text: "Export Preset..."
+ onClicked: {
+ if (root.presetName.trim().length === 0) { if (appBridge) appBridge.exportPreset(""); return }
+ presetSaveDialog.open()
+ }
+ }
+ AppButton { text: "Import..."; onClicked: presetImportDialog.open() }
+ }
+ Text { visible: appBridge && appBridge.presetStatus !== ""; width: parent.width; wrapMode: Text.Wrap; text: appBridge ? appBridge.presetStatus : ""; font.family: Theme.monoFontFamily; font.pixelSize: Theme.fontSizeSmall; color: Theme.accent }
+ }
+ }
+
+ AppCard {
+ width: cardFlow.cardWidth; title: "Maintenance & Defaults"; collapsible: false
+ Column {
+ width: parent.width; spacing: 12
+ Text { width: parent.width; wrapMode: Text.Wrap; text: "Factory reset restores all DLSS, upscale, interpolation, GPU, mask, and encoding settings. Window geometry remains a desktop preference."; font.family: Theme.fontFamily; font.pixelSize: Theme.fontSizeLabel; color: Theme.textSecondary }
+ Row {
+ width: parent.width; spacing: 8
+ AppButton { text: "Open Logs"; onClicked: { if (appBridge) appBridge.openFolder(appBridge.currentLogPath) } }
+ AppButton { text: "Reset All Settings to Defaults"; variant: "danger"; onClicked: resetDialog.open() }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ FileDialog {
+ id: presetImportDialog; title: "Import Preset JSON"; nameFilters: ["JSON Presets (*.json)", "All Files (*.*)"]
+ onAccepted: { if (appBridge && selectedFile) appBridge.importPreset(selectedFile.toString()) }
+ }
+ FileDialog {
+ id: presetSaveDialog; title: "Export Preset JSON"; fileMode: FileDialog.SaveFile; nameFilters: ["JSON Presets (*.json)"]
+ onAccepted: { if (appBridge && selectedFile) appBridge.exportPresetTo(root.presetName, selectedFile.toString()) }
+ }
+
+ QQC2.Dialog {
+ id: resetDialog; width: 420; x: Math.max(20, (root.width - width) / 2); y: Math.max(20, (root.height - height) / 2); modal: true
+ standardButtons: QQC2.Dialog.Yes | QQC2.Dialog.No
+ leftPadding: 20
+ rightPadding: 20
+ topPadding: 16
+ bottomPadding: 12
+ spacing: 8
+ // Borderless custom header: the default Dialog title chrome draws
+ // its own light separator line under the title.
+ header: QQC2.Label {
+ text: "Reset all settings?"
+ color: Theme.textPrimary; font.family: Theme.fontFamily
+ font.pixelSize: Theme.fontSizeTitle; font.weight: Font.Bold
+ leftPadding: 20; rightPadding: 20; topPadding: 16; bottomPadding: 4
+ }
+ contentItem: Text { width: 360; wrapMode: Text.Wrap; text: "This restores every processing setting and clears the custom mask. This cannot be undone unless you exported a preset."; color: Theme.textPrimary; font.family: Theme.fontFamily }
+ // Borderless: the previous danger-colored border read as a light
+ // outline around the whole box against the dark surface.
+ background: Rectangle { color: Theme.bgSurface; border.width: 0; radius: Theme.radiusLarge }
+ onAccepted: { if (appBridge) appBridge.resetToDefaults() }
+ }
+}
diff --git a/src/desktop/qml/views/UpscaleView.qml b/src/desktop/qml/views/UpscaleView.qml
new file mode 100644
index 0000000..30222e4
--- /dev/null
+++ b/src/desktop/qml/views/UpscaleView.qml
@@ -0,0 +1,459 @@
+import QtQuick
+import ".."
+import "../controls"
+import "../components"
+
+Item {
+ id: root
+
+ property var appBridge: null
+ readonly property int adaptiveInspectorWidth: width >= 2560 ? 520 : (width >= 1920 ? 460 : (width >= 1600 ? 420 : (width >= 1280 ? 380 : 340)))
+
+ readonly property bool isImage: appBridge ? (appBridge.upscaleMode === "Image") : true
+ readonly property var activeQueue: appBridge ? (isImage ? appBridge.upscaleImageQueue : appBridge.upscaleVideoQueue) : null
+
+ Row {
+ anchors.fill: parent
+
+ // Main Center Area: Media Viewport + Batch Queue Drawer
+ Item {
+ width: parent.width - sidebar.width
+ height: parent.height
+
+ MediaViewport {
+ id: viewport
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: queueDrawer.top
+ appBridge: root.appBridge
+ }
+
+ BatchQueueDrawer {
+ id: queueDrawer
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ appBridge: root.appBridge
+ queueModel: root.activeQueue
+ hidden: appBridge ? appBridge.focusPreview : false
+ expandedHeight: appBridge ? appBridge.queueHeight : 190
+ }
+ }
+
+ // Right Sidebar
+ Rectangle {
+ id: sidebar
+ width: appBridge && appBridge.focusPreview ? 0 : Math.max(root.adaptiveInspectorWidth, Math.min(560, appBridge ? appBridge.inspectorWidth : root.adaptiveInspectorWidth))
+ height: parent.height
+ visible: width > 0
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ MouseArea {
+ id: inspectorResizeHandle
+ anchors.left: parent.left
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ width: 6
+ z: 100
+ cursorShape: Qt.SizeHorCursor
+ onPositionChanged: (mouse) => {
+ if (!pressed || !appBridge) return
+ var pt = inspectorResizeHandle.mapToItem(root, mouse.x, mouse.y)
+ appBridge.inspectorWidth = Math.max(300, Math.min(560, root.width - pt.x))
+ }
+ }
+
+ Column {
+ anchors.fill: parent
+
+ // Workflow Submode Switcher: Image vs Video
+ Rectangle {
+ width: parent.width
+ height: 48
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Row {
+ anchors.centerIn: parent
+ spacing: 8
+
+ AppSegmentedControl {
+ model: ["Image", "Video"]
+ currentValue: root.appBridge ? root.appBridge.upscaleMode : "Image"
+ onActivated: (val) => {
+ if (root.appBridge) root.appBridge.upscaleMode = val
+ }
+ }
+ }
+ }
+
+ // Scrollable Cards Area
+ Flickable {
+ width: parent.width
+ height: parent.height - 48 - actionBar.height
+ contentWidth: width
+ contentHeight: contentCol.implicitHeight + 24
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+
+ Column {
+ id: contentCol
+ width: parent.width - 24
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: parent.top
+ anchors.topMargin: 12
+ spacing: 12
+
+ // Card 1: RTX Video Super Resolution (VSR)
+ AppCard {
+ width: parent.width
+ title: "RTX Video Super Resolution"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppSwitch {
+ visible: !root.isImage
+ label: "Enable RTX VSR"
+ checked: appBridge ? appBridge.upscaleVsrEnabled : true
+ enabled: appBridge ? (!checked || appBridge.upscaleHdrEnabled) : true
+ onToggled: (c) => { if (appBridge) appBridge.upscaleVsrEnabled = c }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "VSR Quality"
+model: appBridge ? appBridge.vsrQualityChoices : []
+ currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageVsrQuality : 4) : (appBridge ? appBridge.upscaleVsrQuality : 4)
+ onActivated: (v) => {
+ if (appBridge) {
+ if (root.isImage) appBridge.upscaleImageVsrQuality = v
+ else appBridge.upscaleVsrQuality = v
+ }
+ }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Sizing Mode"
+ model: appBridge ? (root.isImage ? appBridge.imageSizeModeChoices : appBridge.videoSizeModeChoices) : []
+ currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageSizeMode : "Scale factor") : (appBridge ? appBridge.upscaleSizeMode : "Scale factor")
+ onActivated: (v) => {
+ if (appBridge) {
+ if (root.isImage) appBridge.upscaleImageSizeMode = v
+ else appBridge.upscaleSizeMode = v
+ }
+ }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Scale Factor"
+ visible: (root.isImage ? appBridge.upscaleImageSizeMode : appBridge.upscaleSizeMode) === "Scale factor"
+ model: appBridge ? (root.isImage ? appBridge.imageScaleFactorChoices : appBridge.videoScaleFactorChoices) : []
+ currentValue: root.isImage ? (appBridge ? appBridge.upscaleImageScaleFactor : 2.0) : (appBridge ? appBridge.upscaleScaleFactor : 2.0)
+ onActivated: (v) => {
+ if (appBridge) {
+ if (root.isImage) appBridge.upscaleImageScaleFactor = v
+ else appBridge.upscaleScaleFactor = v
+ }
+ }
+ }
+
+ Row {
+ width: parent.width
+ spacing: 8
+ visible: (root.isImage ? appBridge.upscaleImageSizeMode : appBridge.upscaleSizeMode) === "Custom dimensions"
+
+ AppTextField {
+ width: (parent.width - 8) / 2
+ label: "Width (px)"
+ text: (root.isImage ? appBridge.upscaleImageWidth : appBridge.upscaleWidth).toString()
+ commitOnEveryEdit: false
+ onTextEdited: (t) => {
+ var num = parseInt(t)
+ if (!isNaN(num) && num > 0) {
+ if (root.isImage) appBridge.upscaleImageWidth = num
+ else appBridge.upscaleWidth = num
+ }
+ }
+ }
+
+ AppTextField {
+ width: (parent.width - 8) / 2
+ label: "Height (px)"
+ text: (root.isImage ? appBridge.upscaleImageHeight : appBridge.upscaleHeight).toString()
+ commitOnEveryEdit: false
+ onTextEdited: (t) => {
+ var num = parseInt(t)
+ if (!isNaN(num) && num > 0) {
+ if (root.isImage) appBridge.upscaleImageHeight = num
+ else appBridge.upscaleHeight = num
+ }
+ }
+ }
+ }
+
+ AppCheckBox {
+ label: "Lock Aspect Ratio"
+ checked: root.isImage ? (appBridge ? appBridge.upscaleImageAspectLock : true) : (appBridge ? appBridge.upscaleAspectLock : true)
+ onToggled: (c) => {
+ if (appBridge) {
+ if (root.isImage) appBridge.upscaleImageAspectLock = c
+ else appBridge.upscaleAspectLock = c
+ }
+ }
+ }
+
+ Text {
+ width: parent.width
+ visible: appBridge && appBridge.outputEstimate !== ""
+ text: appBridge ? appBridge.outputEstimate : ""
+ wrapMode: Text.Wrap
+ font.family: Theme.monoFontFamily
+ font.pixelSize: Theme.fontSizeSmall
+ color: Theme.textMuted
+ }
+ }
+ }
+
+ // Card 2: RTX Video HDR (Video Only)
+ AppCard {
+ visible: !root.isImage
+ width: parent.width
+ title: "RTX Video HDR"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ AppSwitch {
+ label: "Convert SDR to HDR"
+ checked: appBridge ? appBridge.upscaleHdrEnabled : false
+ enabled: appBridge ? (appBridge.upscaleHdrSupported && (!checked || appBridge.upscaleVsrEnabled)) : false
+ onToggled: (c) => { if (appBridge) appBridge.upscaleHdrEnabled = c }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "HDR Contrast"
+ from: 0
+ to: 200
+ stepSize: 1
+ precision: 0
+ defaultValue: 100
+ value: appBridge ? appBridge.upscaleHdrContrast : 100
+ onValueModified: (v) => { if (appBridge) appBridge.upscaleHdrContrast = Math.round(v) }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "HDR Saturation"
+ from: 0
+ to: 200
+ stepSize: 1
+ precision: 0
+ defaultValue: 100
+ value: appBridge ? appBridge.upscaleHdrSaturation : 100
+ onValueModified: (v) => { if (appBridge) appBridge.upscaleHdrSaturation = Math.round(v) }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Middle Gray"
+ from: 10
+ to: 100
+ stepSize: 1
+ precision: 0
+ defaultValue: 50
+ value: appBridge ? appBridge.upscaleHdrMiddleGray : 50
+ onValueModified: (v) => { if (appBridge) appBridge.upscaleHdrMiddleGray = Math.round(v) }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Peak Luminance"
+ unit: "nits"
+ from: 400
+ to: 2000
+ stepSize: 50
+ precision: 0
+ defaultValue: 1000
+ value: appBridge ? appBridge.upscaleHdrPeakLuminance : 1000
+ onValueModified: (v) => { if (appBridge) appBridge.upscaleHdrPeakLuminance = Math.round(v) }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "HDR Precision"
+ model: appBridge ? appBridge.hdrPrecisionChoices : []
+ currentValue: appBridge ? appBridge.upscaleHdrPrecision : "Packed 10-bit"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleHdrPrecision = v }
+ }
+ }
+ }
+
+ // Card 3: Export Settings
+ AppCard {
+ width: parent.width
+ title: "Export & Formats"
+
+ Column {
+ width: parent.width
+ spacing: 12
+
+ Column {
+ visible: root.isImage
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Format"
+ model: appBridge ? appBridge.imageFormatChoices : []
+ currentValue: appBridge ? appBridge.upscaleImageOutputFormat : "PNG"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleImageOutputFormat = v }
+ }
+
+ AppSlider {
+ width: parent.width
+ label: "Quality"
+ from: 1
+ to: 100
+ stepSize: 1
+ precision: 0
+ defaultValue: 95
+ value: appBridge ? appBridge.upscaleImageQuality : 95
+ onValueModified: (v) => { if (appBridge) appBridge.upscaleImageQuality = Math.round(v) }
+ }
+
+ AppCheckBox {
+ label: "Preserve EXIF Metadata"
+ checked: appBridge ? appBridge.upscaleImagePreserveMetadata : true
+ onToggled: (c) => { if (appBridge) appBridge.upscaleImagePreserveMetadata = c }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Rename Mode"
+ model: appBridge ? appBridge.renameModeChoices : []
+ currentValue: appBridge ? appBridge.upscaleImageRenameMode : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleImageRenameMode = v }
+ }
+ AppTextField {
+ visible: appBridge && appBridge.upscaleImageRenameMode === "Custom"
+ width: parent.width
+ label: "Custom Suffix"
+ text: appBridge ? appBridge.upscaleImageCustomSuffix : "_Upscale"
+ onTextEdited: (t) => { if (appBridge) appBridge.upscaleImageCustomSuffix = t }
+ }
+ }
+
+ Column {
+ visible: !root.isImage
+ width: parent.width
+ spacing: 12
+
+ AppComboBox {
+ width: parent.width
+ label: "Codec"
+ model: appBridge ? appBridge.codecChoices : []
+ currentValue: appBridge ? appBridge.upscaleCodec : "H.265 (NVIDIA NVENC)"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleCodec = v }
+ }
+
+ AppComboBox {
+ width: parent.width
+ label: "Quality"
+ model: appBridge ? appBridge.encodingQualityChoices : []
+ currentValue: appBridge ? appBridge.upscaleQuality : "Auto (Default)"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleQuality = v }
+ }
+
+ AppSegmentedControl {
+ width: parent.width
+ label: "Rename Mode"
+ model: appBridge ? appBridge.renameModeChoices : []
+ currentValue: appBridge ? appBridge.upscaleRenameMode : "Auto"
+ onActivated: (v) => { if (appBridge) appBridge.upscaleRenameMode = v }
+ }
+ AppTextField {
+ visible: appBridge && appBridge.upscaleRenameMode === "Custom"
+ width: parent.width
+ label: "Custom Suffix"
+ text: appBridge ? appBridge.upscaleCustomSuffix : "_Upscale"
+ onTextEdited: (t) => { if (appBridge) appBridge.upscaleCustomSuffix = t }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Bottom Action Bar
+ Rectangle {
+ id: actionBar
+ width: parent.width
+ height: 54
+ color: Theme.bgSurface
+ border.color: Theme.borderSubtle
+ border.width: 1
+
+ Column {
+ anchors.fill: parent
+ anchors.margins: 8
+ spacing: 4
+
+ Row {
+ width: parent.width
+ spacing: 8
+
+ AppButton {
+ text: "Preview"
+ width: 90
+ buttonHeight: 34
+ enabled: appBridge ? appBridge.canPreview : false
+ onClicked: {
+ if (appBridge) appBridge.renderPreviewAt(viewport.playheadMs)
+ }
+ }
+
+ AppButton {
+ text: appBridge && appBridge.canStop ? "Stop" : "Upscale Batch"
+ variant: appBridge && appBridge.canStop ? "danger" : "primary"
+ width: parent.width - 294
+ buttonHeight: 34
+ enabled: appBridge ? (appBridge.canStop || appBridge.canRender) : false
+ onClicked: {
+ if (appBridge) {
+ if (appBridge.canStop) appBridge.stopActiveBatch()
+ else if (appBridge.canRender) appBridge.startActiveBatch()
+ }
+ }
+ }
+
+ AppButton {
+ text: "Reset"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.resetTabSettings("upscale") }
+ }
+
+ AppButton {
+ text: "Outputs"
+ width: 90
+ buttonHeight: 34
+ onClicked: { if (appBridge) appBridge.openFolder("") }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/desktop/state.py b/src/desktop/state.py
new file mode 100644
index 0000000..80aef86
--- /dev/null
+++ b/src/desktop/state.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+
+IDLE = "Idle"
+SCANNING_INPUTS = "ScanningInputs"
+LOADING_METADATA = "LoadingMetadata"
+PREVIEW_PREPARING = "PreviewPreparing"
+PREVIEW_RUNNING = "PreviewRunning"
+PREVIEW_CANCELLING = "PreviewCancelling"
+BATCH_PREPARING = "BatchPreparing"
+BATCH_RUNNING = "BatchRunning"
+BATCH_CANCELLING = "BatchCancelling"
+LIVE_STARTING = "LiveStarting"
+LIVE_RUNNING = "LiveRunning"
+LIVE_STOPPING = "LiveStopping"
+SHUTTING_DOWN = "ShuttingDown"
+
+BUSY_STATES = {
+ SCANNING_INPUTS,
+ LOADING_METADATA,
+ PREVIEW_PREPARING,
+ PREVIEW_RUNNING,
+ PREVIEW_CANCELLING,
+ BATCH_PREPARING,
+ BATCH_RUNNING,
+ BATCH_CANCELLING,
+ LIVE_STARTING,
+ LIVE_STOPPING,
+ SHUTTING_DOWN,
+}
+
+
+@dataclass(slots=True)
+class PreviewState:
+ input_url: str = ""
+ output_url: str = ""
+ poster_url: str = ""
+ input_is_video: bool = False
+ output_is_video: bool = False
+ input_info: str = ""
+ output_info: str = ""
+ source_aspect_ratio: float | None = None
+ source_width: int = 0
+ source_height: int = 0
+ source_fps: float = 0.0
+ duration_seconds: float = 0.0
+ output_width: int = 0
+ output_height: int = 0
+ # Numeric source of the video preview: timeline seconds + nominal frame
+ # the enhanced output was built from. Lets Input re-show the same frame.
+ preview_source_seconds: float = 0.0
+ preview_source_frame: int = 0
+ # Last user-parked timeline position (seconds) in this context, pushed
+ # from QML transport gestures and pauses. Realtime auto-renders use it
+ # so a settings tweak previews the parked frame instead of frame 1.
+ last_playhead_seconds: float = 0.0
+ selected_path: str = ""
+ selected_row: int = -1
+ generation: int = 0
+ # Skip-if-fresh marker for realtime auto-preview: (selected source,
+ # settings snapshot) captured when the current output preview finished
+ # rendering. Empty = stale (first visit, cleared queue, cancelled
+ # render). Tab/mode switches skip the GPU re-render while this matches.
+ last_auto_fingerprint: tuple = ()
+ # Frame Interpolation pre-rendered timeline ranges, newest last. Each
+ # entry is {"start": seconds, "end": seconds, "url": clip file URL}.
+ # Overlapping ranges are kept as separate entries (they merge visually
+ # by overdraw); playback picks the newest range containing the playhead
+ # so re-rendered spans always resolve to the latest clip.
+ rendered_ranges: list = field(default_factory=list)
+
+ @property
+ def has_output(self) -> bool:
+ return bool(self.output_url)
diff --git a/src/desktop/win_frameless.py b/src/desktop/win_frameless.py
new file mode 100644
index 0000000..9f2946f
--- /dev/null
+++ b/src/desktop/win_frameless.py
@@ -0,0 +1,599 @@
+from __future__ import annotations
+
+"""Native frameless-window behaviors on Windows.
+
+A Qt frameless window loses OS chrome behaviors: no Snap Layout flyout, no
+Win+arrow snapping, no drag-to-snap/restore. This module restores them while
+keeping the custom QML title-bar visuals:
+
+- Adds WS_THICKFRAME / MAXIMIZEBOX / MINIMIZEBOX / SYSMENU to the style.
+- ``WM_NCCALCSIZE`` returns 0 so the client fills the whole window (no visible
+ frame; maximized fills exactly the work area, no transparent DWM insets).
+- ``WM_NCHITTEST`` returns HTMINBUTTON/HTMAXBUTTON/HTCLOSE over the QML chrome
+ buttons (the Snap Layout flyout appears over maximize), HTCAPTION over empty
+ header background (native drag, double-click maximize, edge snap with
+ proportional drag-restore), resize codes on the frame edges, and HTCLIENT
+ over interactive QML (nav tabs) so clicks still reach Qt.
+- ``WM_GETMINMAXINFO`` clamps maximized size/position to the monitor work area
+ (taskbar stays visible) and enforces the 1080x700 minimum.
+
+No-op on other platforms. On success the installer sets the dynamic property
+``nativeChromeActive`` on the window so QML stands down its own drag/resize
+handling where the OS takes over.
+"""
+
+import ctypes
+import math
+import sys
+import time
+from ctypes import wintypes
+from pathlib import Path
+
+from PySide6.QtCore import QAbstractNativeEventFilter, QCoreApplication
+
+from ..core.paths import LOGS
+
+WM_NCCALCSIZE = 0x0083
+WM_NCHITTEST = 0x0084
+WM_GETMINMAXINFO = 0x0024
+WM_SYSCOMMAND = 0x0112
+WM_NCLBUTTONDOWN = 0x00A1
+
+# Caption-action syscommands (wParam masked with 0xFFF0 per MS docs; the
+# low bits are internally used). SC_CLOSE is deliberately never intercepted
+# so the QML unsaved-operation confirm dialog keeps working.
+SC_MINIMIZE = 0xF020
+SC_MAXIMIZE = 0xF030
+SC_RESTORE = 0xF061
+
+SW_MINIMIZE = 6
+SW_MAXIMIZE = 3
+SW_RESTORE = 9
+
+HTCLIENT = 1
+HTCAPTION = 2
+HTMINBUTTON = 8
+HTMAXBUTTON = 9
+HTLEFT = 10
+HTRIGHT = 11
+HTTOP = 12
+HTTOPLEFT = 13
+HTTOPRIGHT = 14
+HTBOTTOM = 15
+HTBOTTOMLEFT = 16
+HTBOTTOMRIGHT = 17
+HTCLOSE = 20
+
+GWL_STYLE = -16
+GWL_EXSTYLE = -20
+WS_EX_APPWINDOW = 0x00040000
+WS_THICKFRAME = 0x00040000
+WS_MAXIMIZEBOX = 0x00010000
+WS_MINIMIZEBOX = 0x00020000
+WS_SYSMENU = 0x00080000
+# Frame bits the OS requires for caption-button actions. DefWindowProc
+# consumes an HTMINBUTTON click yet silently drops the minimize when
+# WS_MINIMIZEBOX is absent (same gating for maximize/resize) — a fully
+# dead button no QML fallback can rescue, since the click never reaches Qt.
+STYLE_CHROME_BITS = WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU
+
+SM_CXSIZEFRAME = 32
+SM_CXPADDEDBORDER = 92
+MONITOR_DEFAULTTONEAREST = 2
+
+SWP_NOSIZE = 0x0001
+SWP_NOMOVE = 0x0002
+SWP_NOZORDER = 0x0004
+SWP_NOACTIVATE = 0x0010
+SWP_FRAMECHANGED = 0x0020
+
+HEADER_HEIGHT_DIP = 50.0
+MIN_WIDTH_DIP = 1080
+MIN_HEIGHT_DIP = 700
+# Hit-test tolerance (DIPs) applied around each chrome button rect. The QML
+# buttons are 28px with 2px gaps; without tolerance, clicks landing exactly
+# in a gap (or on a 1px fractional-DPR rounding seam) fall through to
+# HTCAPTION resize/drag handling and look like dead clicks that need several
+# retries. 3 DIPs fully covers the gaps; overlapping claims resolve
+# deterministically in check order (close > max > min), same as before.
+CHROME_BTN_TOL_DIP = 3.0
+
+
+class _POINT(ctypes.Structure):
+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
+
+
+class _MINMAXINFO(ctypes.Structure):
+ _fields_ = [
+ ("ptReserved", _POINT),
+ ("ptMaxSize", _POINT),
+ ("ptMaxPosition", _POINT),
+ ("ptMinTrackSize", _POINT),
+ ("ptMaxTrackSize", _POINT),
+ ]
+
+
+class _RECT(ctypes.Structure):
+ _fields_ = [
+ ("left", ctypes.c_long),
+ ("top", ctypes.c_long),
+ ("right", ctypes.c_long),
+ ("bottom", ctypes.c_long),
+ ]
+
+
+class _MONITORINFO(ctypes.Structure):
+ _fields_ = [
+ ("cbSize", wintypes.DWORD),
+ ("rcMonitor", _RECT),
+ ("rcWork", _RECT),
+ ("dwFlags", wintypes.DWORD),
+ ]
+
+
+class _MSG(ctypes.Structure):
+ _fields_ = [
+ ("hWnd", wintypes.HWND),
+ ("message", wintypes.UINT),
+ ("wParam", wintypes.WPARAM),
+ ("lParam", wintypes.LPARAM),
+ ("time", wintypes.DWORD),
+ ("pt", _POINT),
+ ]
+
+
+_USER32 = None
+_LOG_CAP_BYTES = 64 * 1024
+
+
+def log_native_chrome(text: str) -> None:
+ """Append one diagnostics line; never raises (used for snap/maximize triage)."""
+ try:
+ LOGS.mkdir(parents=True, exist_ok=True)
+ path = LOGS / "native-chrome.log"
+ try:
+ if path.is_file() and path.stat().st_size > _LOG_CAP_BYTES:
+ path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ stamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ with open(path, "a", encoding="utf-8", errors="replace") as handle:
+ handle.write(f"[{stamp}] {text}\n")
+ except Exception:
+ pass
+
+
+def _user32():
+ """Cached user32 handle with prototypes (Windows only; never call elsewhere)."""
+ global _USER32
+ if _USER32 is None:
+ u = ctypes.windll.user32
+ u.GetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int]
+ u.GetWindowLongPtrW.restype = wintypes.LPARAM
+ u.SetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.LPARAM]
+ u.SetWindowLongPtrW.restype = wintypes.LPARAM
+ u.SetWindowPos.argtypes = [
+ wintypes.HWND, wintypes.HWND,
+ ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, wintypes.UINT,
+ ]
+ u.SetWindowPos.restype = wintypes.BOOL
+ u.GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(_RECT)]
+ u.GetWindowRect.restype = wintypes.BOOL
+ u.ClientToScreen.argtypes = [wintypes.HWND, ctypes.POINTER(_POINT)]
+ u.ClientToScreen.restype = wintypes.BOOL
+ u.GetSystemMetrics.argtypes = [ctypes.c_int]
+ u.GetSystemMetrics.restype = ctypes.c_int
+ u.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD]
+ u.MonitorFromWindow.restype = wintypes.HMONITOR
+ u.GetMonitorInfoW.argtypes = [wintypes.HMONITOR, ctypes.POINTER(_MONITORINFO)]
+ u.GetMonitorInfoW.restype = wintypes.BOOL
+ u.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
+ u.ShowWindow.restype = wintypes.BOOL
+ u.IsZoomed.argtypes = [wintypes.HWND]
+ u.IsZoomed.restype = wintypes.BOOL
+ _USER32 = u
+ return _USER32
+
+
+def _msg_address(message) -> int | None:
+ try:
+ return int(message.__int__())
+ except Exception:
+ pass
+ try:
+ return int(message)
+ except Exception:
+ return None
+
+
+class WinFramelessFilter(QAbstractNativeEventFilter):
+ """Hit-test + frame handling for the single main window (Windows only)."""
+
+ def __init__(self, window) -> None:
+ super().__init__()
+ self._window = window
+ try:
+ self._hwnd = int(window.winId())
+ except Exception:
+ self._hwnd = 0
+ self._logged_calcsize = False
+ self._logged_minmax = False
+
+ # -- helpers ---------------------------------------------------------
+ def _dip_rect(self, name: str) -> tuple[float, float, float, float] | None:
+ try:
+ rect = self._window.property(name)
+ except Exception:
+ return None
+ if rect is None:
+ return None
+ try:
+ x, y, w, h = rect.x(), rect.y(), rect.width(), rect.height()
+ except Exception:
+ return None
+ if w <= 0 or h <= 0:
+ return None
+ return (float(x), float(y), float(w), float(h))
+
+ def _rects_ready(self) -> bool:
+ """True once QML has published all hit-test rects with real sizes."""
+ for name in ("closeBtnRect", "maxBtnRect", "minBtnRect", "navTabsRect"):
+ if self._dip_rect(name) is None:
+ return False
+ return True
+
+ def _device_ratio(self) -> float:
+ try:
+ dpr = float(self._window.devicePixelRatio())
+ except Exception:
+ return 1.0
+ return dpr if dpr > 0 else 1.0
+
+ def _window_rect(self) -> tuple[int, int, int, int] | None:
+ rect = _RECT()
+ try:
+ if not _user32().GetWindowRect(self._hwnd, ctypes.byref(rect)):
+ return None
+ except Exception:
+ return None
+ return (rect.left, rect.top, rect.right, rect.bottom)
+
+ def _client_origin(self) -> tuple[int, int] | None:
+ """Screen position (physical px) of the Qt client/content origin.
+
+ For a WS_THICKFRAME frameless window GetWindowRect includes the
+ invisible resize borders, while QML DIP rects are relative to the
+ client origin. Mapping buttons from the outer origin shifts every
+ hit region ~7px (more at >100% DPI) off the drawn button, making
+ edge clicks fall through to resize/caption handling.
+ """
+ try:
+ pt = _POINT(0, 0)
+ if not _user32().ClientToScreen(self._hwnd, ctypes.byref(pt)):
+ return None
+ except Exception:
+ return None
+ return (pt.x, pt.y)
+
+ def _in_dip_rect(
+ self, name: str, px: int, py: int,
+ origin_x: int, origin_y: int, dpr: float,
+ tol_dip: float = 0.0,
+ ) -> bool:
+ rect = self._dip_rect(name)
+ if rect is None:
+ return False
+ # Inflate in DIP space, then snap outward to whole physical pixels so
+ # a fractional-DPR rounding edge can never carve a dead seam into a
+ # 28px target or its 2px inter-button gaps.
+ x0 = math.floor(origin_x + (rect[0] - tol_dip) * dpr)
+ y0 = math.floor(origin_y + (rect[1] - tol_dip) * dpr)
+ x1 = math.ceil(origin_x + (rect[0] + rect[2] + tol_dip) * dpr)
+ y1 = math.ceil(origin_y + (rect[1] + rect[3] + tol_dip) * dpr)
+ return (x0 <= px < x1) and (y0 <= py < y1)
+
+ # -- message handlers -------------------------------------------------
+ def _hit_test(self, px: int, py: int) -> int:
+ bounds = self._window_rect()
+ if bounds is None:
+ return HTCLIENT
+ left, top, right, bottom = bounds
+ dpr = self._device_ratio()
+ try:
+ frame = _user32().GetSystemMetrics(SM_CXSIZEFRAME)
+ frame += _user32().GetSystemMetrics(SM_CXPADDEDBORDER)
+ except Exception:
+ frame = 8
+ if frame < 1:
+ frame = 8
+
+ # Custom chrome buttons first (above everything else up there).
+ # DIP rects are client-relative, so they must be mapped from the
+ # client origin (ClientToScreen), NOT the outer GetWindowRect origin
+ # which includes the invisible thick-frame borders.
+ origin = self._client_origin()
+ if origin is None:
+ origin = (left, top)
+ cx, cy = origin
+ # Keep the required style bits present (Qt re-applies its own flags
+ # at show() and on some state changes). Log-on-repair only.
+ try:
+ _style = int(_user32().GetWindowLongPtrW(self._hwnd, GWL_STYLE))
+ if _style and (_style & STYLE_CHROME_BITS) != STYLE_CHROME_BITS:
+ ensure_win_style(self._hwnd)
+ except Exception:
+ pass
+ if self._in_dip_rect("closeBtnRect", px, py, cx, cy, dpr, CHROME_BTN_TOL_DIP):
+ return HTCLOSE
+ if self._in_dip_rect("maxBtnRect", px, py, cx, cy, dpr, CHROME_BTN_TOL_DIP):
+ return HTMAXBUTTON
+ if self._in_dip_rect("minBtnRect", px, py, cx, cy, dpr, CHROME_BTN_TOL_DIP):
+ return HTMINBUTTON
+
+ # Resize frame (corners before edges).
+ in_left = px < left + frame
+ in_right = px >= right - frame
+ in_top = py < top + frame
+ in_bottom = py >= bottom - frame
+ if in_top and in_left:
+ return HTTOPLEFT
+ if in_top and in_right:
+ return HTTOPRIGHT
+ if in_bottom and in_left:
+ return HTBOTTOMLEFT
+ if in_bottom and in_right:
+ return HTBOTTOMRIGHT
+ if in_left:
+ return HTLEFT
+ if in_right:
+ return HTRIGHT
+ if in_top:
+ return HTTOP
+ if in_bottom:
+ return HTBOTTOM
+
+ # Until QML publishes hit-test rects, keep the header client-side so
+ # every button stays clickable via the QML fallbacks.
+ if not self._rects_ready():
+ return HTCLIENT
+
+ # Interactive nav tabs stay client-side so clicks reach QML.
+ if self._in_dip_rect("navTabsRect", px, py, cx, cy, dpr):
+ return HTCLIENT
+
+ # Empty header background behaves like a title bar (native drag,
+ # double-click maximize, drag-to-snap with proportional restore).
+ if (py - cy) < HEADER_HEIGHT_DIP * dpr:
+ return HTCAPTION
+ return HTCLIENT
+
+ def _clamp_max_info(self, lparam: int = 0) -> None:
+ try:
+ info = ctypes.cast(lparam, ctypes.POINTER(_MINMAXINFO)).contents
+ except Exception:
+ return
+ try:
+ u = _user32()
+ monitor = u.MonitorFromWindow(self._hwnd, MONITOR_DEFAULTTONEAREST)
+ if not monitor:
+ return
+ mi = _MONITORINFO()
+ mi.cbSize = ctypes.sizeof(_MONITORINFO)
+ if not u.GetMonitorInfoW(monitor, ctypes.byref(mi)):
+ return
+ info.ptMaxPosition.x = abs(mi.rcWork.left - mi.rcMonitor.left)
+ info.ptMaxPosition.y = abs(mi.rcWork.top - mi.rcMonitor.top)
+ info.ptMaxSize.x = abs(mi.rcWork.right - mi.rcWork.left)
+ info.ptMaxSize.y = abs(mi.rcWork.bottom - mi.rcWork.top)
+ if not self._logged_minmax:
+ self._logged_minmax = True
+ log_native_chrome(
+ f"minmax pos=({info.ptMaxPosition.x},{info.ptMaxPosition.y}) "
+ f"size=({info.ptMaxSize.x},{info.ptMaxSize.y}) "
+ f"work=({mi.rcWork.left},{mi.rcWork.top},{mi.rcWork.right},{mi.rcWork.bottom})"
+ )
+ dpr = self._device_ratio()
+ info.ptMinTrackSize.x = int(MIN_WIDTH_DIP * dpr)
+ info.ptMinTrackSize.y = int(MIN_HEIGHT_DIP * dpr)
+ except Exception:
+ pass
+
+ # -- filter entry ------------------------------------------------------
+ def nativeEventFilter(self, eventType, message):
+ if isinstance(eventType, bytes):
+ event_name = eventType
+ elif isinstance(eventType, bytearray):
+ event_name = bytes(eventType)
+ else:
+ try:
+ event_name = bytes(eventType)
+ except Exception:
+ try:
+ event_name = str(eventType).encode("utf-8", "ignore")
+ except Exception:
+ return False, 0
+ if event_name != b"windows_generic_MSG":
+ return False, 0
+ addr = _msg_address(message)
+ if addr is None:
+ return False, 0
+ try:
+ msg = ctypes.cast(addr, ctypes.POINTER(_MSG)).contents
+ except Exception:
+ return False, 0
+ try:
+ hwnd = int(msg.hWnd or 0)
+ except Exception:
+ return False, 0
+ if hwnd != self._hwnd:
+ return False, 0
+ try:
+ code = int(msg.message)
+ except Exception:
+ return False, 0
+ if code == WM_NCHITTEST:
+ try:
+ lparam = int(msg.lParam)
+ except Exception:
+ return False, 0
+ px = ctypes.c_short(lparam & 0xFFFF).value
+ py = ctypes.c_short((lparam >> 16) & 0xFFFF).value
+ try:
+ return True, int(self._hit_test(px, py))
+ except Exception:
+ return False, 0
+ if code == WM_NCCALCSIZE:
+ if not self._logged_calcsize:
+ self._logged_calcsize = True
+ log_native_chrome("nccalcsize handled")
+ return True, 0
+ if code == WM_GETMINMAXINFO:
+ try:
+ self._clamp_max_info(lparam=int(msg.lParam))
+ except Exception:
+ pass
+ return True, 0
+ if code == WM_SYSCOMMAND:
+ # Caption actions also arrive without any button press (Alt+Space
+ # menu, taskbar thumbnail buttons). Execute them directly: same
+ # outcome as a healthy OS path, completion when it drops them.
+ # SC_CLOSE is never touched so the QML unsaved-operation confirm
+ # dialog keeps working. Failures only are logged.
+ try:
+ cmd = int(msg.wParam) & 0xFFF0
+ except Exception:
+ return False, 0
+ if cmd == SC_MINIMIZE:
+ try:
+ _user32().ShowWindow(self._hwnd, SW_MINIMIZE)
+ except Exception as exc:
+ log_native_chrome(f"syscommand SC_MINIMIZE failed: {exc!r}")
+ return True, 0
+ if cmd == SC_MAXIMIZE:
+ try:
+ _user32().ShowWindow(self._hwnd, SW_MAXIMIZE)
+ except Exception as exc:
+ log_native_chrome(f"syscommand SC_MAXIMIZE failed: {exc!r}")
+ return True, 0
+ if cmd == SC_RESTORE:
+ try:
+ _user32().ShowWindow(self._hwnd, SW_RESTORE)
+ except Exception as exc:
+ log_native_chrome(f"syscommand SC_RESTORE failed: {exc!r}")
+ return True, 0
+ return False, 0
+ if code == WM_NCLBUTTONDOWN:
+ # Press-side caption actions for min/max: the release half of
+ # caption gestures never reaches DefWindowProc on this setup (no
+ # UP, no syscommand), so release-based handling cannot work.
+ # Acting on the press with the identical absolute action instead.
+ # Absolute actions, so anything completing later anyway is a
+ # harmless no-op double. Close is excluded: destroying on press
+ # would bypass the unsaved-work guard. Failures only are logged.
+ try:
+ ht = int(msg.wParam) & 0xFFFF
+ except Exception:
+ return False, 0
+ if ht == HTMINBUTTON:
+ try:
+ _user32().ShowWindow(self._hwnd, SW_MINIMIZE)
+ except Exception as exc:
+ log_native_chrome(f"press-act SC_MINIMIZE failed: {exc!r}")
+ elif ht == HTMAXBUTTON:
+ try:
+ try:
+ _press_zoomed = bool(_user32().IsZoomed(self._hwnd))
+ except Exception:
+ _press_zoomed = False
+ if _press_zoomed:
+ _user32().ShowWindow(self._hwnd, SW_RESTORE)
+ else:
+ _user32().ShowWindow(self._hwnd, SW_MAXIMIZE)
+ except Exception as exc:
+ log_native_chrome(f"press-act SC_MAXIMIZE failed: {exc!r}")
+ return False, 0
+ return False, 0
+
+
+def ensure_win_style(hwnd: int) -> str:
+ """Re-assert native frame style bits Qt may have overwritten.
+
+ Qt (6.8+) re-applies its own window flags at show() and on some state
+ changes, silently stripping the THICKFRAME/MAXIMIZEBOX/MINIMIZEBOX/
+ SYSMENU bits install_win_chrome added pre-show. Returns a short status
+ for logging; never raises.
+ """
+ if sys.platform != "win32" or not hwnd:
+ return "skipped"
+ try:
+ u = _user32()
+ before = int(u.GetWindowLongPtrW(hwnd, GWL_STYLE))
+ status = f"{before:#x} (intact)"
+ if (before & STYLE_CHROME_BITS) != STYLE_CHROME_BITS:
+ wanted = before | STYLE_CHROME_BITS
+ u.SetWindowLongPtrW(hwnd, GWL_STYLE, wanted)
+ u.SetWindowPos(
+ hwnd, 0, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
+ )
+ after = int(u.GetWindowLongPtrW(hwnd, GWL_STYLE))
+ log_native_chrome(f"style-healed {before:#x}->{after:#x}")
+ status = f"{before:#x}->{after:#x}"
+ # A minimized popup without a taskbar button strands the window
+ # (nothing to click to restore it). Guarantee the affordance.
+ try:
+ ex_before = int(u.GetWindowLongPtrW(hwnd, GWL_EXSTYLE))
+ if not (ex_before & WS_EX_APPWINDOW):
+ u.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex_before | WS_EX_APPWINDOW)
+ log_native_chrome(f"exstyle-appwindow {ex_before:#x}->{ex_before | WS_EX_APPWINDOW:#x}")
+ status += " +appwindow"
+ except Exception:
+ pass
+ return status
+ except Exception as exc:
+ log_native_chrome(f"style-ensure failed: {exc!r}")
+ return "failed"
+
+
+def install_win_chrome(window) -> bool:
+ """Enable native frame behaviors for a frameless QML window.
+
+ Returns True when the OS path is active (QML reads the dynamic
+ ``nativeChromeActive`` property to stand down its fallbacks).
+ """
+ if sys.platform != "win32":
+ return False
+ try:
+ hwnd = int(window.winId())
+ except Exception:
+ return False
+ if not hwnd:
+ return False
+ try:
+ u = _user32()
+ style_before = int(u.GetWindowLongPtrW(hwnd, GWL_STYLE))
+ style = style_before | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU
+ u.SetWindowLongPtrW(hwnd, GWL_STYLE, style)
+ style_after = int(u.GetWindowLongPtrW(hwnd, GWL_STYLE))
+ u.SetWindowPos(
+ hwnd, 0, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
+ )
+ app = QCoreApplication.instance()
+ filt = WinFramelessFilter(window)
+ if app is not None:
+ app.installNativeEventFilter(filt)
+ # Kept alive on the window; QML reads nativeChromeActive as fallback guard.
+ window._win_frameless_filter = filt # type: ignore[attr-defined]
+ window.setProperty("nativeChromeActive", True)
+ try:
+ dpr = float(window.devicePixelRatio())
+ except Exception:
+ dpr = 0.0
+ log_native_chrome(
+ f"install hwnd={hwnd:#x} style {style_before:#x}->{style_after:#x} dpr={dpr}"
+ )
+ return True
+ except Exception as exc:
+ log_native_chrome(f"install failed: {exc!r}")
+ return False
diff --git a/src/desktop/workers.py b/src/desktop/workers.py
new file mode 100644
index 0000000..f391ad0
--- /dev/null
+++ b/src/desktop/workers.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import inspect
+import traceback
+from typing import Any, Callable
+
+from PySide6.QtCore import QObject, QRunnable, Signal, Slot
+from ..core.jobs import JobController, Cancelled, use_job_controller
+from ..core.batch_progress import BatchItemUpdate
+
+
+class WorkerSignals(QObject):
+ """Signals for background task execution."""
+ started = Signal()
+ progress = Signal(float, str)
+ itemUpdated = Signal(int, str, float, str, str, float)
+ finished = Signal(object)
+ failed = Signal(str)
+ cancelled = Signal()
+
+
+class JobWorker(QRunnable):
+ """Execute a cancellable task without blocking the Qt GUI thread.
+
+ Backend jobs use ``controller``, ``progress`` and ``on_item_update`` callback
+ names, while desktop-only helper jobs often do not. Callback injection is
+ therefore signature-aware instead of blindly passing keywords to every
+ callable.
+ """
+
+ def __init__(
+ self,
+ task_fn: Callable[..., Any],
+ *args: Any,
+ controller: JobController | None = None,
+ inject_callbacks: bool = True,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__()
+ self.task_fn = task_fn
+ self.args = args
+ self.kwargs = kwargs
+ self.controller = controller or JobController()
+ self.inject_callbacks = inject_callbacks
+ self.signals = WorkerSignals()
+ self.setAutoDelete(True)
+
+ def on_batch_item_update(self, update: BatchItemUpdate) -> None:
+ idx = update.index if update.index is not None else -1
+ self.signals.itemUpdated.emit(
+ idx,
+ update.state,
+ update.progress,
+ update.detail,
+ update.output_path,
+ update.elapsed_seconds,
+ )
+
+ def on_progress(self, fraction: float, message: str) -> None:
+ self.signals.progress.emit(max(0.0, min(1.0, float(fraction))), str(message))
+
+ def _accepted_kwargs(self) -> tuple[set[str], bool]:
+ try:
+ signature = inspect.signature(self.task_fn)
+ except (TypeError, ValueError):
+ return set(), True
+ names: set[str] = set()
+ var_kwargs = False
+ for parameter in signature.parameters.values():
+ if parameter.kind == inspect.Parameter.VAR_KEYWORD:
+ var_kwargs = True
+ elif parameter.kind in (
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ ):
+ names.add(parameter.name)
+ return names, var_kwargs
+
+ @Slot()
+ def run(self) -> None:
+ self.signals.started.emit()
+ try:
+ with use_job_controller(self.controller):
+ kwargs = dict(self.kwargs)
+ if self.inject_callbacks:
+ accepted, var_kwargs = self._accepted_kwargs()
+ optional = {
+ "controller": self.controller,
+ "progress": self.on_progress,
+ "on_item_update": self.on_batch_item_update,
+ }
+ for name, value in optional.items():
+ if name not in kwargs and (var_kwargs or name in accepted):
+ kwargs[name] = value
+
+ result = self.task_fn(*self.args, **kwargs)
+ if self.controller.cancel.is_set():
+ self.signals.cancelled.emit()
+ else:
+ self.signals.finished.emit(result)
+ except Cancelled:
+ self.signals.cancelled.emit()
+ except Exception as exc:
+ traceback.print_exc()
+ self.signals.failed.emit(str(exc))
diff --git a/src/frame_interpolation/capabilities.py b/src/frame_interpolation/capabilities.py
index 927e2b6..721519f 100644
--- a/src/frame_interpolation/capabilities.py
+++ b/src/frame_interpolation/capabilities.py
@@ -37,7 +37,8 @@ def _authenticode_status(path: Path) -> str:
"Import-Module \"$env:WINDIR\\System32\\WindowsPowerShell\\v1.0\\Modules\\"
"Microsoft.PowerShell.Security\\Microsoft.PowerShell.Security.psd1\"; "
f"[string](Get-AuthenticodeSignature -LiteralPath '{escaped}').Status"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except (OSError, subprocess.TimeoutExpired):
return "Unavailable"
return process.stdout.strip() if process.returncode == 0 else "Unavailable"
diff --git a/src/frame_interpolation/models.py b/src/frame_interpolation/models.py
index 3ff0b04..49da98e 100644
--- a/src/frame_interpolation/models.py
+++ b/src/frame_interpolation/models.py
@@ -24,6 +24,10 @@ FPS_RATES: dict[str, Fraction] = {
}
FPS_CHOICES = tuple(FPS_RATES)
ENGINE_CHOICES = ("Auto", "Native DLSSG", "Cascade")
+# Preview clip lengths (seconds) offered in the FI action bar. Stored as
+# strings like the FPS choice; converted to float at render time.
+PREVIEW_LENGTH_CHOICES = ("3", "5", "10", "20", "30")
+PREVIEW_LENGTH_DEFAULT = "3"
def resolve_target_rate(value: str | int | float | Fraction) -> Fraction:
diff --git a/src/frame_interpolation/native.py b/src/frame_interpolation/native.py
index 9e3ef14..77e511f 100644
--- a/src/frame_interpolation/native.py
+++ b/src/frame_interpolation/native.py
@@ -17,7 +17,7 @@ from ..core.ngx_runtime import NGX_RUNTIME_LOCK
from ..core.paths import RUNTIME
RUNTIME_DIR = RUNTIME / "dlssg"
-BRIDGE = RUNTIME_DIR / "neuroframe_engine.dll"
+BRIDGE = RUNTIME_DIR / "neuroframe_engine_frame_interpolation.dll"
BRIDGE_ABI_VERSION = 1
MEMORY_HOST, MEMORY_CUDA = 1, 2
FORMAT_RGBA8, FORMAT_NV12, FORMAT_P010 = 1, 4, 5
@@ -149,7 +149,9 @@ class _BridgeManager:
try:
library = ctypes.WinDLL(str(BRIDGE))
except OSError as exc:
- raise DLSSGBridgeError(f"Could not load neuroframe_engine.dll: {exc}") from exc
+ raise DLSSGBridgeError(
+ f"Could not load neuroframe_engine_frame_interpolation.dll: {exc}"
+ ) from exc
library.fi_abi_version.restype = ctypes.c_uint32
library.fi_version.restype = ctypes.c_char_p
library.fi_init.argtypes = [ctypes.c_int, ctypes.c_wchar_p, ctypes.c_void_p, ctypes.c_int]
diff --git a/src/frame_interpolation/preview.py b/src/frame_interpolation/preview.py
index 13eb8d4..5b074eb 100644
--- a/src/frame_interpolation/preview.py
+++ b/src/frame_interpolation/preview.py
@@ -1,16 +1,14 @@
from __future__ import annotations
-import traceback
+from dataclasses import replace
from pathlib import Path
-import gradio as gr
-
from ..core.ffmpeg import probe_video
from ..core.ffmpeg.preview import (
is_browser_playable, make_browser_preview, normalize_preview_encoding,
resolve_preview_codec, wants_compat_preview,
)
-from ..settings.storage import current_preview_encoding, processing_gpu_settings
+from ..settings.storage import processing_gpu_settings
from .capabilities import probe_frame_interpolation_capabilities
from .models import FrameInterpolationOptions
from .processor import interpolate_video
@@ -29,6 +27,7 @@ def first_video_path(paths: list[str] | str | None) -> str | None:
normalized = normalize_video_paths(paths)
return normalized[0] if normalized else None
+
def frame_interpolation_capability_text() -> str:
ai_gpu_uuid, _video_gpu_uuid = processing_gpu_settings()
capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
@@ -41,8 +40,8 @@ def frame_interpolation_capability_text() -> str:
state = "Ready" if capabilities.available else "Unavailable"
detail = f"\n{capabilities.detail}" if capabilities.detail else ""
return (
- f"{state} — GPU: {capabilities.gpu} | Driver: {capabilities.driver} | "
- f"HAGS: {hags}\nNative maximum: {native} | Cascade: {cascade} | "
+ f"{state} — GPU: {capabilities.gpu} | Driver: {capabilities.driver} | HAGS: {hags}\n"
+ f"Native maximum: {native} | Cascade: {cascade} | "
f"NVOF: {'SLOW/available' if capabilities.nvof_available else 'unavailable'}\n"
f"Bridge: {capabilities.bridge_version} (ABI {capabilities.bridge_abi_version}) | "
f"CUDA interop: {'ready' if capabilities.cuda_interop else 'unavailable'} | "
@@ -63,11 +62,8 @@ def describe_frame_interpolation_plan(
ai_gpu_uuid, _video_gpu_uuid = processing_gpu_settings()
capabilities = probe_frame_interpolation_capabilities(ai_gpu_uuid)
plan = choose_interpolation_plan(
- metadata["rate"],
- FrameInterpolationOptions(target_fps=target_fps).target_rate,
- engine,
- capabilities.native_multiplier,
- cfr=bool(metadata.get("cfr", True)),
+ metadata["rate"], FrameInterpolationOptions(target_fps=target_fps).target_rate,
+ engine, capabilities.native_multiplier, cfr=bool(metadata.get("cfr", True)),
)
if plan.cascade_stages:
precision = (
@@ -87,77 +83,85 @@ def describe_frame_interpolation_plan(
return f"Preflight: {exc}"
-def update_frame_interpolation_preview_mode(
- paths: list[str] | str | None,
- target_fps: str,
- engine: str,
-):
- normalized = normalize_video_paths(paths)
- 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 available else None, visible=True if available else "hidden", label=label),
- gr.update(value=None, visible=True),
- gr.update(visible=single),
- )
-
-def preview_frame_interpolation(
- input_paths: list[str] | str | None,
- target_fps: str,
- engine: str,
- codec: str,
- container: str,
- quality: str,
- progress=gr.Progress(track_tqdm=False),
-):
- selected = first_video_path(input_paths)
- if not selected:
- raise gr.Error("Choose one video first.")
+def preview_frame_interpolation_native(
+ input_path: str,
+ options: FrameInterpolationOptions,
+ *,
+ preview_encoding: str = "Auto",
+ progress=None,
+ output_dir=None,
+ controller=None,
+ start_seconds: float | None = None,
+ frame_index: int | None = None,
+ preview_seconds: float | None = None,
+) -> tuple[str | None, str]:
+ if not input_path or not Path(input_path).is_file():
+ raise ValueError("Choose one valid video first.")
+ try:
+ length_seconds = max(0.0, float(preview_seconds if preview_seconds is not None else PREVIEW_SECONDS))
+ except (TypeError, ValueError):
+ length_seconds = PREVIEW_SECONDS
+ if not (length_seconds > 0):
+ length_seconds = PREVIEW_SECONDS
try:
- preview_mode = normalize_preview_encoding(current_preview_encoding())
- except Exception:
- preview_mode = "Auto"
+ start = max(0.0, float(start_seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
+ try:
+ frame_no = max(1, int(frame_index or 1)) if frame_index else 1
+ except (TypeError, ValueError):
+ frame_no = 1
+ effective_path = str(input_path)
+ temp_clip: str | None = None
+ if start > 0.05:
+ from ..core.ffmpeg.preview import extract_preview_subclip
+ temp_clip = extract_preview_subclip(
+ str(input_path), dest_dir=output_dir, start_seconds=start,
+ length_seconds=length_seconds, controller=controller,
+ )
+ effective_path = temp_clip
+ preview_encoding_mode = normalize_preview_encoding(preview_encoding)
effective_codec, effective_container = resolve_preview_codec(
- codec, container, preview_mode
+ options.codec, options.container, preview_encoding_mode
)
- compat_preview = wants_compat_preview(codec, container, preview_mode)
- options = FrameInterpolationOptions(
- ai_gpu_uuid=processing_gpu_settings()[0],
- video_gpu_uuid=processing_gpu_settings()[1],
- target_fps=target_fps,
- engine=engine,
+ compat_preview = wants_compat_preview(options.codec, options.container, preview_encoding_mode)
+ effective = replace(
+ options,
codec=effective_codec,
container=effective_container,
- quality=quality,
- preview_seconds=PREVIEW_SECONDS,
+ hdr_mode=(options.hdr_mode and not compat_preview),
+ preview_seconds=length_seconds,
preview_compat=compat_preview,
)
- try:
- result = interpolate_video(
- selected,
- options,
- lambda value, message: progress(value, desc=message),
- )
- except Exception as exc:
- traceback.print_exc()
- return None, f"Failed: {exc}"
+ result = interpolate_video(
+ effective_path,
+ effective,
+ progress,
+ output_dir=output_dir,
+ controller=controller,
+ )
+ if temp_clip:
+ try:
+ Path(temp_clip).unlink(missing_ok=True)
+ except OSError:
+ pass
output_preview = result.output_path
derived_note = ""
- if preview_mode == "Auto" and not compat_preview:
+ if preview_encoding_mode == "Auto" and not compat_preview:
try:
playable = is_browser_playable(result.output_path)
except Exception:
playable = False
if not playable:
try:
- output_preview = make_browser_preview(result.output_path)
- derived_note = " (browser preview transcoded to H.264)"
+ output_preview = make_browser_preview(
+ result.output_path, dest_dir=output_dir, controller=controller
+ )
+ derived_note = " (compatibility preview transcoded to H.264)"
except Exception:
output_preview = result.output_path
return output_preview, (
- f"Preview complete: {result.output_frames} frames, {result.selected_path}, "
+ f"Preview complete f{frame_no} @ {start:.2f}s: {result.output_frames} frames, {result.selected_path}, "
f"{result.cascade_stages} cascade stage(s), {result.generated_frames} DLSSG-selected "
- f"frames in {result.elapsed_seconds:.1f}s. Report: {result.report_path}"
- f"{derived_note}"
+ f"frames in {result.elapsed_seconds:.1f}s. Report: {result.report_path}{derived_note}"
)
diff --git a/src/frame_interpolation/processor.py b/src/frame_interpolation/processor.py
index 1881141..baa3ef7 100644
--- a/src/frame_interpolation/processor.py
+++ b/src/frame_interpolation/processor.py
@@ -324,9 +324,7 @@ def interpolate_video(
raise Cancelled("Frame interpolation stopped by user.")
if progress:
value = max(0.0, min(1.0, float(value)))
- elapsed = time.perf_counter() - started
- if 0.01 < value < 0.99 and elapsed > .5:
- message += f" - Time Remaining: {elapsed * (1-value) / max(value,1e-6):.1f}s"
+ # Status bar shows only the main status; no ETA suffix.
progress(value, message)
output_file: OutputFile | None = None
@@ -373,7 +371,7 @@ def interpolate_video(
capabilities.native_multiplier, cfr=cfr)
output_count = output_frame_count(duration, options.target_rate)
timings["probe_seconds"] = time.perf_counter() - probe_start
- update(.01, f"{plan.path}: {source_rate} → {options.target_rate} FPS")
+ update(.01, "Preparing frame interpolation")
selected_codec = "H.264 (NVIDIA NVENC)" if compat_preview else options.codec
video_gpu = ffmpeg.resolve_video_gpu(
@@ -585,8 +583,7 @@ def interpolate_video(
now = time.perf_counter()
if now - last_update > .2:
update(.04 + .82 * decoded / max(1, source_frames),
- f"DLSSG GPU pipeline {decoded}/{source_frames}; "
- f"{writer.next_index/max(.01,now-pipeline_start):.1f} output fps")
+ "Interpolating frames")
last_update = now
if decoded != source_frames:
raise RuntimeError(f"Decoded {decoded} source frames; expected {source_frames}.")
diff --git a/src/frame_interpolation/ui.py b/src/frame_interpolation/ui.py
deleted file mode 100644
index 6075ce1..0000000
--- a/src/frame_interpolation/ui.py
+++ /dev/null
@@ -1,263 +0,0 @@
-from __future__ import annotations
-
-import traceback
-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, build_save_controls,
-)
-
-from ..core.ffmpeg import container_for_codec, hdr_mode_supported
-from ..core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview
-from ..core.naming import RENAME_MODES
-from ..settings.models import CODEC_CHOICES, CONTAINER_CHOICES, QUALITY_CHOICES, UISettings, coerce_hdr_mode
-from ..settings.storage import current_preview_encoding, processing_gpu_settings
-from .batch import interpolate_videos
-from .models import ENGINE_CHOICES, FPS_CHOICES, FrameInterpolationOptions
-from .preview import normalize_video_paths, preview_frame_interpolation, update_frame_interpolation_preview_mode
-
-
-def hdr_mode_update(codec: str):
- allowed = hdr_mode_supported(codec)
- if not allowed:
- return gr.update(value=False, interactive=False)
- return gr.update(interactive=True)
-
-
-def codec_settings_update(codec: str):
- return gr.update(value=container_for_codec(codec)), hdr_mode_update(codec)
-
-
-def rename_suffix_update(mode: str):
- return gr.update(interactive=mode == "Custom")
-
-def render_frame_interpolation_batch(
- input_paths: list[str] | str | None,
- target_fps: str,
- engine: str,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
- *, output_dir=None, controller=None, on_item_update=None, direct_disk=False,
-):
- paths = normalize_video_paths(input_paths)
- if not paths:
- raise gr.Error("Choose at least one video first.")
- effective_hdr = coerce_hdr_mode(codec, hdr_mode)
- options = FrameInterpolationOptions(
- ai_gpu_uuid=processing_gpu_settings()[0],
- video_gpu_uuid=processing_gpu_settings()[1],
- target_fps=target_fps,
- engine=engine,
- codec=codec,
- container=container,
- quality=quality,
- hdr_mode=effective_hdr,
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = interpolate_videos(paths, options, report, output_dir=output_dir,
- controller=controller, on_item_update=on_item_update)
- except Exception as exc:
- traceback.print_exc()
- if on_item_update is not None:
- raise
- 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
- details = (
- f"{value.output_frames} frames; {value.selected_path}; "
- f"{value.elapsed_seconds:.1f}s; processing {value.output_frames / max(value.elapsed_seconds, 0.001):.1f} frames/s; "
- f"native {value.native_multiplier}×; cascade stages {value.cascade_stages}; "
- f"copied {value.copied_frames}, DLSSG {value.generated_frames}, "
- f"cuts {value.scene_cuts}; {value.decode_backend} → {value.encode_backend}; "
- f"memory {value.memory_path}; transfers {value.upload_bytes}/{value.download_bytes} bytes; "
- f"pool {value.surface_pool_pressure.get('allocated', 0)}/"
- f"{value.surface_pool_pressure.get('capacity', 0)} "
- f"(waits {value.surface_pool_pressure.get('waits', 0)}); "
- f"bridge {value.bridge_version}/ABI {value.bridge_abi_version}; report: {value.report_path}"
- )
- ordered.append(
- (item.index, [Path(item.input_path).name, "Complete", Path(value.output_path).name, details])
- )
- for item in result.failures:
- state = "Skipped" if item.error == "Cancelled before rendering." else (
- "Cancelled" if item.cancelled else "Failed"
- )
- ordered.append((item.index, [Path(item.input_path).name, state, "", item.error]))
- rows = [row for _index, row in sorted(ordered, key=lambda entry: entry[0])]
- files = [item.result.output_path for item in result.successes]
- try:
- preview_mode = normalize_preview_encoding(current_preview_encoding())
- except Exception:
- preview_mode = "Auto"
- preview = None
- used_derivative = False
- if not direct_disk and len(paths) == 1 and result.successes and not result.cancelled:
- preview, used_derivative = resolve_final_preview(files[0], preview_mode, controller=controller)
- status = (
- f"{'Cancelled' if result.cancelled else 'Complete'}: "
- f"{len(result.successes)} completed, {len(result.failures)} failed/cancelled. "
- f"Batch manifest: {result.manifest_path}"
- )
- if result.failures:
- status += f"\nFirst error: {result.failures[0].error}"
- if used_derivative:
- status += "\nBrowser preview transcoded to H.264; the original file is unchanged."
- return gr.update(value=preview, visible=not direct_disk), files, rows, status
-
-@dataclass(slots=True)
-class FrameInterpolationTab:
- sources: object
- input_preview: object
- input_actions: object
- select_source: object
- clear_source: object
- target_fps: object
- engine: object
- quality: object
- codec: object
- container: object
- rename_mode: object
- custom_suffix: object
- hdr_mode: object
- preview: object
- render: object
- stop: object
- reset: object
- output_video: object
- save_download: object
- zip_button: object
- zip_download: object
- status: object
- results: object
- input_path: object = None
- output_path: object = None
- job_state: object = None
-
- @property
- def render_inputs(self) -> list[object]:
- return [
- self.sources, self.target_fps, self.engine, self.codec, self.container, self.quality,
- self.hdr_mode, self.rename_mode, self.custom_suffix,
- ]
-
- @property
- def preview_inputs(self) -> list[object]:
- return [self.sources, self.target_fps, self.engine, self.codec, self.container, self.quality]
-
- @property
- def settings_inputs(self) -> list[object]:
- return [
- self.target_fps, self.engine, self.codec, self.container, self.quality,
- self.hdr_mode, self.rename_mode, self.custom_suffix,
- ]
-
-
-def build_frame_interpolation_tab(settings: UISettings) -> FrameInterpolationTab:
- with gr.Row():
- with gr.Column(scale=3):
- sources = gr.File(
- label="Input video(s)", file_count="multiple", file_types=["video"],
- type="filepath", allow_reordering=True, elem_id="frame-interpolation-upload-list",
- elem_classes=["media-upload-surface"],
- )
- input_preview = gr.Video(label="Input video preview", interactive=False, visible="hidden")
- 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")
- with gr.Row():
- render = gr.Button("Interpolate video(s)", variant="primary")
- preview = gr.Button("Preview 3 sec", visible=False)
- stop = gr.Button("Stop", variant="stop")
- reset = gr.Button("Reset settings")
- with gr.Column():
- with gr.Row():
- target_fps = gr.Dropdown(
- FPS_CHOICES, value=settings.frame_interpolation_target_fps,
- label="Output FPS",
- )
- engine = gr.Radio(
- ENGINE_CHOICES, value=settings.frame_interpolation_engine, label="DLSS engine",
- )
- input_path, output_path = build_path_controls()
- quality = gr.Radio(
- QUALITY_CHOICES, value=settings.frame_interpolation_quality,
- label="Encoding quality",
- )
- with gr.Row():
- codec = gr.Dropdown(
- CODEC_CHOICES, value=settings.frame_interpolation_codec,
- label="Video codec",
- )
- container = gr.Dropdown(
- CONTAINER_CHOICES,
- value=container_for_codec(settings.frame_interpolation_codec),
- label="Container (automatic)", interactive=False,
- )
- with gr.Row():
- rename_mode = gr.Radio(
- RENAME_MODES, value=settings.frame_interpolation_rename_mode, label="Rename",
- )
- custom_suffix = gr.Textbox(
- value=settings.frame_interpolation_custom_suffix, label="Custom suffix",
- placeholder="_Frame_Interpolation", interactive=settings.frame_interpolation_rename_mode == "Custom",
- )
- hdr_mode = gr.Checkbox(
- value=settings.frame_interpolation_hdr_mode and hdr_mode_supported(settings.frame_interpolation_codec),
- label="HDR Mode",
- interactive=hdr_mode_supported(settings.frame_interpolation_codec),
- )
- with gr.Column(scale=3):
- output_video = gr.Video(
- label="Interpolated output", interactive=False, visible=True, height=520,
- )
- save_download, zip_button, zip_download = build_save_controls("video", "frame-interpolation")
- 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 = FrameInterpolationTab(
- sources=sources, input_preview=input_preview, input_actions=input_actions,
- select_source=select_source, clear_source=clear_source, target_fps=target_fps,
- engine=engine, quality=quality, codec=codec,
- container=container, rename_mode=rename_mode, custom_suffix=custom_suffix,
- hdr_mode=hdr_mode, preview=preview, render=render, stop=stop, reset=reset,
- output_video=output_video, save_download=save_download, zip_button=zip_button,
- zip_download=zip_download, status=status, results=results)
- tab.input_path, tab.output_path = input_path, output_path
- bind_frame_interpolation_events(tab)
- return tab
-
-
-def bind_frame_interpolation_events(tab: FrameInterpolationTab) -> None:
- bind_batch_ui(
- tab, render_frame_interpolation_batch, kind="video",
- preview_mode=update_frame_interpolation_preview_mode, archive_prefix="DLSSFG_VIDEO_BATCH",
- preview_actions=[(tab.preview, preview_frame_interpolation)],
- )
- tab.codec.change(
- codec_settings_update, inputs=tab.codec,
- outputs=[tab.container, tab.hdr_mode], queue=False,
- )
- tab.rename_mode.change(rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False)
diff --git a/src/live/__init__.py b/src/live/__init__.py
index 2905f8e..909f431 100644
--- a/src/live/__init__.py
+++ b/src/live/__init__.py
@@ -6,13 +6,10 @@ from .pipeline import (
stop_live_session,
sweep_stale_live_dirs,
)
-from .ui import LiveTab, build_live_tab
__all__ = [
"LiveOptions",
"LiveSessionInfo",
- "LiveTab",
- "build_live_tab",
"is_live_running",
"live_status",
"start_live_session",
diff --git a/src/live/effects.py b/src/live/effects.py
index 6a1b489..ecaa555 100644
--- a/src/live/effects.py
+++ b/src/live/effects.py
@@ -31,7 +31,6 @@ class EffectSettings:
mask_feather: int
nr_mask: object | None
automatic_mask: bool
- nr_gpu_mode: bool
@classmethod
def from_options(cls, options) -> EffectSettings:
diff --git a/src/live/models.py b/src/live/models.py
index d4c22fc..5431005 100644
--- a/src/live/models.py
+++ b/src/live/models.py
@@ -31,7 +31,6 @@ class LiveOptions:
mask_feather: int = 0
nr_mask: object | None = None
automatic_mask: bool = False
- nr_gpu_mode: bool = True
# Source default: Live renders at the input size; 75%/50%/25% downscale
# first (Lanczos) and keep the pipe/NVENC cheap on mid-range GPUs.
upscaling_factor: float = 1.0
@@ -42,6 +41,11 @@ class LiveOptions:
network_timeout: float = 20.0
open_mpv: bool = True
mpv_args: tuple[str, ...] = ()
+ # In-tab embedding (Windows): parent-window handle for ``--wid`` plus the
+ # JSON IPC pipe for transport. ``mpv_wid == 0`` falls back to a detached
+ # player window. Set by the bridge on the GUI thread before launch.
+ mpv_wid: int = 0
+ mpv_ipc_server: str = ""
# Debug/diagnostics: keep the session HLS dir instead of sweeping it.
keep_files: bool = False
source_quality: str = "Auto"
@@ -83,6 +87,10 @@ class LiveSessionInfo:
effective_fps: float = 0.0
elapsed_seconds: float = 0.0
mpv_running: bool = False
+ # True once the embedded player reported actual playback (first frame).
+ # The in-tab container stays hidden until then so no unpainted native
+ # window is ever exposed. Sourced from the lua state file's `started`.
+ player_started: bool = False
player_dropped_frames: int = 0
rebuffer_events: int = 0
av_sync_ms: float = 0.0
diff --git a/src/live/mpv_embed.py b/src/live/mpv_embed.py
new file mode 100644
index 0000000..4bb2f22
--- /dev/null
+++ b/src/live/mpv_embed.py
@@ -0,0 +1,1013 @@
+from __future__ import annotations
+
+"""In-tab MPV hosting for the Live workflow (Windows ``--wid`` embedding).
+
+The Live pipeline keeps producing HLS exactly as before; instead of opening a
+separate MPV window, the vendored ``mpv.exe`` is told to attach to a dedicated
+child ``QWindow`` that floats over the Live tab's video slot. MPV creates its
+own child window covering that container and letterboxes the video itself, so
+the Python side only has to keep the container geometry in sync with QML.
+
+Threading: every method here must run on the GUI thread (QML slots and the
+bridge run there). The pipeline worker thread never touches this object; the
+bridge hands the container HWND + IPC pipe name to the session via
+``LiveOptions`` before the worker starts.
+
+Transport (pause/mute/volume) goes through MPV's JSON IPC named pipe on a
+short-lived daemon thread so the GUI never blocks. Every command reads
+MPV's reply and only then updates local state, so rejections surface via
+``embedError`` instead of failing silently. Fullscreen is video-only while
+embedded (MPV owns no top-level window under ``--wid``): the container is
+promoted to a top-level fullscreen window, leaving the app window alone.
+Playback telemetry still comes from the existing ``player_status.lua``
+state file (see ``player.py``).
+"""
+
+import ctypes
+import itertools
+import json
+import sys
+import threading
+import time
+from typing import Any
+
+from PySide6.QtCore import QObject, Signal, Slot, Property, Qt
+
+try:
+ from PySide6.QtGui import QRasterWindow as _QRasterWindowBase
+except Exception:
+ _QRasterWindowBase = None # type: ignore[assignment, misc]
+
+
+def _pipe_name(stamp: str) -> str:
+ return f"\\\\.\\pipe\\dlss5-live-{stamp}"
+
+
+_request_ids = itertools.count(1)
+_request_lock = threading.Lock()
+
+
+def _kernel32():
+ """kernel32 with explicit prototypes (never truncate 64-bit HANDLEs)."""
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ try:
+ kernel32.CreateFileW.argtypes = [
+ ctypes.c_wchar_p, ctypes.c_ulong, ctypes.c_ulong,
+ ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p,
+ ]
+ kernel32.CreateFileW.restype = ctypes.c_void_p
+ kernel32.WriteFile.argtypes = [
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong,
+ ctypes.POINTER(ctypes.c_ulong), ctypes.c_void_p,
+ ]
+ kernel32.WriteFile.restype = ctypes.c_bool
+ kernel32.ReadFile.argtypes = [
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong,
+ ctypes.POINTER(ctypes.c_ulong), ctypes.c_void_p,
+ ]
+ kernel32.ReadFile.restype = ctypes.c_bool
+ kernel32.PeekNamedPipe.argtypes = [
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong,
+ ctypes.POINTER(ctypes.c_ulong),
+ ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong),
+ ]
+ kernel32.PeekNamedPipe.restype = ctypes.c_bool
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+ kernel32.CloseHandle.restype = ctypes.c_bool
+ except Exception:
+ pass
+ return kernel32
+
+
+def _read_reply(kernel32: Any, handle: Any, request_id: int, *, timeout: float = 3.0) -> dict:
+ """Read newline-delimited JSON until our command reply arrives."""
+ deadline = time.monotonic() + max(0.5, timeout)
+ pending = b""
+ while time.monotonic() < deadline:
+ available = ctypes.c_ulong(0)
+ try:
+ peeked = kernel32.PeekNamedPipe(handle, None, 0, None, ctypes.byref(available), None)
+ except Exception:
+ peeked = False
+ if not peeked:
+ raise OSError(f"Lost MPV IPC pipe while reading ({ctypes.get_last_error()}).")
+ if not available.value:
+ time.sleep(0.02)
+ continue
+ chunk = ctypes.create_string_buffer(min(65536, available.value + 16))
+ got = ctypes.c_ulong(0)
+ if not kernel32.ReadFile(handle, chunk, len(chunk) - 1, ctypes.byref(got), None):
+ err = ctypes.get_last_error()
+ if err != 234 or not got.value: # 234 = MORE_DATA, keep draining
+ raise OSError(f"Could not read MPV IPC reply ({err}).")
+ pending += chunk.raw[: got.value]
+ while b"\n" in pending:
+ raw, pending = pending.split(b"\n", 1)
+ raw = raw.strip()
+ if not raw:
+ continue
+ try:
+ message = json.loads(raw.decode("utf-8", "replace"))
+ except ValueError:
+ continue
+ if not isinstance(message, dict):
+ continue
+ if message.get("request_id") == request_id or (
+ request_id == 0 and "error" in message
+ ):
+ return message
+ # Anything else is an unsolicited event; keep waiting for ours.
+ raise TimeoutError("Timed out waiting for MPV IPC reply.")
+
+
+def _ipc_roundtrip(
+ pipe: str,
+ command: list,
+ *,
+ tries: int = 8,
+ open_delay: float = 0.15,
+ reply_timeout: float = 3.0,
+) -> dict:
+ """Send one JSON IPC command and return MPV's reply object.
+
+ Raises with MPV's own error text when the command is rejected, so
+ transport failures are diagnosable instead of silent.
+ """
+ with _request_lock:
+ request_id = next(_request_ids)
+ payload = (
+ json.dumps({"command": command, "request_id": request_id}) + "\n"
+ ).encode("utf-8")
+ kernel32 = _kernel32()
+ GENERIC_READ_WRITE = 0xC0000000
+ OPEN_EXISTING = 3
+ INVALID_HANDLE = ctypes.c_void_p(-1).value
+
+ def _usable(handle: Any) -> bool:
+ try:
+ value = handle.value if isinstance(handle, ctypes.c_void_p) else handle
+ except Exception:
+ return False
+ return value is not None and value not in (0, INVALID_HANDLE)
+
+ last_error: Exception | None = None
+ for _ in range(max(1, tries)):
+ handle = None
+ try:
+ handle = kernel32.CreateFileW(pipe, GENERIC_READ_WRITE, 0, None, OPEN_EXISTING, 0, None)
+ if not _usable(handle):
+ raise OSError(f"Could not open MPV IPC pipe ({ctypes.get_last_error()}).")
+ written = ctypes.c_ulong(0)
+ if not kernel32.WriteFile(handle, payload, len(payload), ctypes.byref(written), None):
+ raise OSError(f"Could not write MPV IPC pipe ({ctypes.get_last_error()}).")
+ if written.value != len(payload):
+ raise OSError("Short write to MPV IPC pipe.")
+ reply = _read_reply(kernel32, handle, request_id, timeout=reply_timeout)
+ if reply.get("error") not in (None, "success"):
+ raise RuntimeError(f"MPV rejected command {command!r}: {reply.get('error')}")
+ return reply
+ except (OSError, TimeoutError) as exc: # pipe not ready yet; retry briefly
+ last_error = exc
+ time.sleep(open_delay)
+ finally:
+ if _usable(handle):
+ try:
+ kernel32.CloseHandle(handle)
+ except Exception:
+ pass
+ if last_error is not None:
+ raise last_error
+ raise OSError("Could not reach MPV IPC pipe.")
+
+
+class _FsExitKeyHook:
+ """WH_KEYBOARD_LL hook: Esc/F11 exits video-only fullscreen.
+
+ Installed on the GUI thread for the duration of video-only
+ fullscreen and removed afterwards. The QML Escape shortcut cannot
+ fire there (it belongs to the app window, which does not own keyboard
+ focus) and MPV ignores keys, so a thread hook is the only
+ focus-proof path. Acts only when the foreground window is our video
+ (the container, its MPV child, or the exit pill), so Esc pressed
+ anywhere else is never disturbed. Windows-only; ``install`` returns
+ False everywhere else (the QML shortcut remains as backup).
+ """
+
+ WH_KEYBOARD_LL = 13
+ WM_KEYDOWN = 0x0100
+ WM_SYSKEYDOWN = 0x0104
+ VK_ESCAPE = 0x1B
+ VK_F11 = 0x7A
+
+ class _KbdStruct(ctypes.Structure):
+ _fields_ = [
+ ("vkCode", ctypes.c_uint),
+ ("scanCode", ctypes.c_uint),
+ ("flags", ctypes.c_uint),
+ ("time", ctypes.c_uint),
+ ("dwExtraInfo", ctypes.c_void_p),
+ ]
+
+ def __init__(self) -> None:
+ self._hook: Any = None
+ self._proc: Any = None
+ self._user32: Any = None
+ self._on_exit: Any = None
+
+ def install(self, on_exit: Any, container_hwnd: int, extra_hwnds: tuple = ()) -> bool:
+ """Install the hook. Returns False when unavailable."""
+ try:
+ self.uninstall()
+ except Exception:
+ pass
+ if sys.platform != "win32" or not callable(on_exit):
+ return False
+ try:
+ container = int(container_hwnd or 0)
+ except Exception:
+ container = 0
+ if container <= 0:
+ return False
+ try:
+ allowed = {container}
+ for extra in extra_hwnds or ():
+ try:
+ number = int(extra or 0)
+ except Exception:
+ continue
+ if number > 0:
+ allowed.add(number)
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ user32.GetForegroundWindow.restype = ctypes.c_void_p
+ user32.IsChild.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ user32.IsChild.restype = ctypes.c_bool
+ user32.CallNextHookEx.argtypes = [
+ ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p,
+ ]
+ user32.CallNextHookEx.restype = ctypes.c_longlong
+ user32.UnhookWindowsHookEx.argtypes = [ctypes.c_void_p]
+ user32.UnhookWindowsHookEx.restype = ctypes.c_bool
+ user32.SetWindowsHookExW.argtypes = [
+ ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint,
+ ]
+ user32.SetWindowsHookExW.restype = ctypes.c_void_p
+ self._on_exit = on_exit
+ struct_type = self._KbdStruct
+ exit_keys = (self.VK_ESCAPE, self.VK_F11)
+ down_msgs = (self.WM_KEYDOWN, self.WM_SYSKEYDOWN)
+
+ def _proc(nCode: int, wParam: int, lParam: int) -> int:
+ try:
+ if nCode == 0 and wParam in down_msgs and lParam:
+ try:
+ vk = struct_type.from_address(int(lParam)).vkCode
+ except Exception:
+ vk = 0
+ if vk in exit_keys:
+ try:
+ foreground = int(user32.GetForegroundWindow() or 0)
+ except Exception:
+ foreground = 0
+ if foreground and (
+ foreground in allowed
+ or bool(user32.IsChild(container, foreground))
+ ):
+ try:
+ if callable(self._on_exit):
+ self._on_exit()
+ except Exception:
+ pass
+ return 1 # swallow: our video owns the screen
+ return int(user32.CallNextHookEx(None, nCode, wParam, lParam))
+ except Exception:
+ try:
+ return int(user32.CallNextHookEx(None, nCode, wParam, lParam))
+ except Exception:
+ return 0
+
+ proc_type = ctypes.WINFUNCTYPE( # type: ignore[attr-defined]
+ ctypes.c_longlong, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p
+ )
+ self._proc = proc_type(_proc)
+ hook = user32.SetWindowsHookExW(self.WH_KEYBOARD_LL, self._proc, None, 0)
+ try:
+ valid = int(hook or 0) > 0
+ except Exception:
+ valid = False
+ if not valid:
+ self._proc = None
+ self._on_exit = None
+ return False
+ self._hook = hook
+ self._user32 = user32
+ return True
+ except Exception:
+ self._proc = None
+ self._on_exit = None
+ return False
+
+ def uninstall(self) -> None:
+ """Remove the hook. Idempotent; never raises."""
+ hook, self._hook = self._hook, None
+ self._on_exit = None
+ if hook:
+ try:
+ user32 = self._user32 or ctypes.windll.user32 # type: ignore[attr-defined]
+ user32.UnhookWindowsHookEx(hook)
+ except Exception:
+ pass
+ # NOTE: self._proc is deliberately kept alive so a stray OS
+ # callback can never hit a garbage-collected function pointer.
+
+
+if _QRasterWindowBase is not None:
+
+ class _FsExitPill(_QRasterWindowBase):
+ """Clickable 'Exit fullscreen' pill above the fullscreen video.
+
+ QML cannot render here (the native video paints above the whole
+ Qt Quick scene), so this is a tiny native child of the promoted
+ container: it travels with it automatically, needs no screen/DPI
+ math beyond the parent size, and dies with the session. Opaque
+ Theme-matching colors (translucency is unreliable for native
+ child windows).
+ """
+
+ PILL_W = 252
+ PILL_H = 40
+ MARGIN = 16
+
+ def __init__(self, parent: Any = None) -> None:
+ super().__init__(parent)
+ self._on_clicked: Any = None
+ try:
+ self.setTitle("Exit fullscreen")
+ except Exception:
+ pass
+ try:
+ self.resize(self.PILL_W, self.PILL_H)
+ except Exception:
+ pass
+ try:
+ self.setCursor(Qt.PointingHandCursor)
+ except Exception:
+ pass
+
+ def set_clicked(self, callback: Any) -> None:
+ self._on_clicked = callback
+
+ def place_top_right(self, parent_w: int, parent_h: int) -> None:
+ try:
+ width = max(2, int(parent_w))
+ except Exception:
+ return
+ try:
+ self.setX(max(0, width - self.PILL_W - self.MARGIN))
+ self.setY(self.MARGIN)
+ self.resize(self.PILL_W, self.PILL_H)
+ except Exception:
+ pass
+
+ def paintEvent(self, event: Any) -> None:
+ try:
+ from PySide6.QtGui import QPainter, QColor
+
+ painter = QPainter(self)
+ try:
+ painter.setRenderHint(QPainter.Antialiasing, True)
+ painter.setBrush(QColor(27, 27, 30))
+ painter.setPen(QColor(69, 69, 75))
+ painter.drawRoundedRect(
+ 0, 0, self.PILL_W - 1, self.PILL_H - 1, 10, 10
+ )
+ font = self.font()
+ try:
+ font.setPixelSize(13)
+ except Exception:
+ pass
+ painter.setFont(font)
+ painter.setPen(QColor(241, 245, 249))
+ painter.drawText(
+ painter.viewport(),
+ int(Qt.AlignCenter),
+ "× Exit fullscreen (Esc)",
+ )
+ finally:
+ painter.end()
+ except Exception:
+ pass
+
+ def mousePressEvent(self, event: Any) -> None:
+ try:
+ if event is not None and event.button() == Qt.LeftButton:
+ if callable(self._on_clicked):
+ self._on_clicked()
+ return
+ except Exception:
+ pass
+
+else:
+ _FsExitPill = None # type: ignore[assignment, misc]
+
+
+class MpvEmbedController(QObject):
+ """Owns the in-tab MPV container window and its IPC transport."""
+
+ embedError = Signal(str)
+ pausedChanged = Signal()
+ mutedChanged = Signal()
+ volumeChanged = Signal()
+ activeChanged = Signal()
+ tabActiveChanged = Signal()
+ dialogOpenChanged = Signal()
+ fullscreenChanged = Signal()
+
+ MPV_DEFAULT_VOLUME = 100
+ MPV_MAX_VOLUME = 130
+ VOLUME_STEP = 5
+
+ def __init__(self, parent: Any = None) -> None:
+ super().__init__(parent)
+ self._main_window: Any | None = None
+ self._container: Any | None = None
+ self._session_active = False
+ self._ipc_pipe = ""
+ self._paused = False
+ self._muted = False
+ self._volume = self.MPV_DEFAULT_VOLUME
+ self._fullscreen = False
+ # Whether the Live tab is currently visible. The embed container is
+ # a native child window that always paints above the Qt Quick scene
+ # (QML clip/StackLayout cannot clip it), so it must be hidden
+ # whenever the user switches to another tab — while the session
+ # (audio/pipeline) keeps running in the background.
+ self._tab_visible = True
+ # True while a modal app dialog (e.g. the "Operation still active"
+ # exit prompt) is open. Dialogs live in the Qt Quick scene, so the
+ # native container would otherwise paint over them and steal clicks.
+ self._dialog_open = False
+ # Native HWND handed to MPV via --wid (0 = detached fallback where
+ # MPV owns its own window and IPC fullscreen genuinely works).
+ self._wid = 0
+ # True while the video-only fullscreen mode is active (container
+ # promoted to a top-level fullscreen window; the app window is
+ # never touched). MPV cannot fullscreen itself when embedded via
+ # --wid (it owns no top-level window), so the container itself
+ # goes fullscreen instead. Only moved/reparented natively with
+ # the same HWND and no flag changes, so MPV's attachment stays
+ # valid.
+ self._qt_fs = False
+ # Fullscreen exit UI: native pill button above the video + a
+ # foreground-gated Esc/F11 hook (see _show_fs_ui). Both funnel
+ # into _fs_exit_requested; both are inert outside fullscreen.
+ self._fs_pill: Any = None
+ self._fs_keys = _FsExitKeyHook()
+ # Last QML-reported geometry (parent-relative DIPs). Re-applied when
+ # the session activates so early reports are not lost.
+ self._geom: tuple[float, float, float, float] | None = None
+
+ # -- window ---------------------------------------------------------
+ def attach_main_window(self, window: Any) -> None:
+ """Remember the QML root window; must run on the GUI thread."""
+ self._main_window = window
+
+ def _ensure_container(self) -> bool:
+ """Create the (hidden) container child window. Returns success."""
+ if self._container is not None:
+ return True
+ if self._main_window is None:
+ return False
+ try:
+ from PySide6.QtGui import QWindow
+
+ container = QWindow(self._main_window)
+ container.setFlags(Qt.FramelessWindowHint)
+ container.setTitle("DLSS 5 Live")
+ container.resize(2, 2)
+ container.setVisible(False)
+ self._container = container
+ return True
+ except Exception as exc:
+ self.embedError.emit(f"Could not create Live video slot: {exc}")
+ return False
+
+ def prepare(self, ipc_pipe: str) -> tuple[int, str]:
+ """Create the container (hidden) and return its HWND + IPC pipe.
+
+ Called from ``startLive`` on the GUI thread *before* the session
+ worker starts, so the pipeline can pass both straight to MPV.
+ Falls back to ``(0, pipe)`` (detached window) when unavailable.
+ """
+ self._ipc_pipe = ipc_pipe or ""
+ self._paused = False
+ self._muted = False
+ self._volume = self.MPV_DEFAULT_VOLUME
+ self._fullscreen = False
+ self._qt_fs = False
+ self._wid = 0
+ for signal in (self.pausedChanged, self.mutedChanged, self.volumeChanged,
+ self.fullscreenChanged):
+ try:
+ signal.emit()
+ except Exception:
+ pass
+ if not self._ensure_container():
+ return 0, self._ipc_pipe
+ try:
+ assert self._container is not None
+ self._container.setVisible(False)
+ hwnd = int(self._container.winId())
+ self._wid = int(hwnd or 0)
+ return (hwnd if hwnd else 0), self._ipc_pipe
+ except Exception as exc:
+ self._wid = 0
+ self.embedError.emit(f"Could not query Live video slot handle: {exc}")
+ return 0, self._ipc_pipe
+
+ @Slot(float, float, float, float)
+ def setGeometry(self, x: float, y: float, w: float, h: float) -> None:
+ """Move/resize the container (client-relative DIPs, from QML)."""
+ try:
+ self._geom = (float(x), float(y), float(w), float(h))
+ except Exception:
+ return
+ if self._container is None:
+ return
+ self._apply_visibility()
+
+ @Slot(bool)
+ def setTabActive(self, active: bool) -> None:
+ """Show/hide the native container for Live-tab visibility.
+
+ Called from the ``activeTab`` setter on the GUI thread whenever the
+ user switches tabs. The Live session (pipeline + audio) keeps
+ running; only the native overlay window is hidden so it can never
+ paint over Upscale / Neural Rendering / other tabs. Returning to
+ the Live tab re-shows it at the last reported geometry.
+ """
+ try:
+ active = bool(active)
+ except Exception:
+ return
+ if active == self._tab_visible:
+ return
+ self._tab_visible = active
+ try:
+ self.tabActiveChanged.emit()
+ except Exception:
+ pass
+ if not active and self._fullscreen:
+ self._exit_fullscreen_if_needed()
+ self._apply_visibility()
+
+ @Slot(bool)
+ def setDialogOpen(self, open: bool) -> None:
+ """Hide the native container while a modal dialog is open.
+
+ QML popups/dialogs (including the exit prompt) live in the Qt Quick
+ scene, which a native child window always paints above. Hiding here
+ keeps the dialog clickable; the session keeps running and the cached
+ geometry re-shows the video as soon as the dialog closes.
+ """
+ try:
+ open = bool(open)
+ except Exception:
+ return
+ if open == self._dialog_open:
+ return
+ self._dialog_open = open
+ try:
+ self.dialogOpenChanged.emit()
+ except Exception:
+ pass
+ if open:
+ self._exit_fullscreen_if_needed()
+ self._apply_visibility()
+
+ def _is_embedded(self) -> bool:
+ """True when MPV renders into our container (vs detached window)."""
+ try:
+ return bool(self._wid) and self._container is not None
+ except Exception:
+ return False
+
+ def _exit_fullscreen_if_needed(self) -> None:
+ """Leave fullscreen so no orphan overlay survives a hide/stop.
+
+ Video-only mode (embedded): dock the container back into the app
+ window synchronously. Detached fallback: ask MPV to leave
+ fullscreen via IPC (it owns its window there, so IPC works).
+ """
+ if not self._fullscreen:
+ self._qt_fs = False
+ return
+ if self._qt_fs:
+ try:
+ self._hide_fs_ui()
+ except Exception:
+ pass
+ try:
+ self._restore_video_slot()
+ except Exception:
+ pass
+ self._qt_fs = False
+ self._fullscreen = False
+ try:
+ self.fullscreenChanged.emit()
+ except Exception:
+ pass
+ return
+ try:
+ self._send(
+ ["set", "fullscreen", "no"],
+ lambda _reply: (setattr(self, "_fullscreen", False),
+ self.fullscreenChanged.emit()),
+ )
+ except Exception:
+ pass
+
+ def _enter_qt_fullscreen(self) -> None:
+ """Put only the video on screen; the app window stays as it is.
+
+ The container is promoted to a top-level fullscreen window (pure
+ native reparent, same HWND, no flags touched), so MPV's ``--wid``
+ attachment keeps rendering and its child window covers the new
+ fullscreen parent automatically, letterboxing the video itself.
+ """
+ if self._main_window is None or self._container is None:
+ raise RuntimeError("Live video slot is unavailable.")
+ try:
+ screen = self._main_window.screen()
+ except Exception:
+ screen = None
+ try:
+ if screen is not None:
+ self._container.setScreen(screen)
+ except Exception:
+ pass
+ try:
+ self._container.setParent(None)
+ except Exception as exc:
+ raise RuntimeError(f"Could not enter fullscreen: {exc}.")
+ try:
+ actual_wid = int(self._container.winId())
+ except Exception:
+ actual_wid = 0
+ if self._wid and actual_wid and actual_wid != self._wid:
+ # Native window was recreated: MPV is still attached to the
+ # dead HWND. Dock back immediately so the session keeps
+ # playing in its slot instead of going black.
+ try:
+ self._container.setParent(self._main_window)
+ except Exception:
+ pass
+ try:
+ self._apply_visibility()
+ except Exception:
+ pass
+ raise RuntimeError(
+ "Fullscreen is not supported on this setup "
+ "(video slot was recreated); playing in-slot."
+ )
+ try:
+ self._container.showFullScreen()
+ except Exception as exc:
+ try:
+ self._container.setParent(self._main_window)
+ except Exception:
+ pass
+ raise RuntimeError(f"Could not enter fullscreen: {exc}.")
+ try:
+ self._container.raise_()
+ except Exception:
+ pass
+ self._qt_fs = True
+ self._fullscreen = True
+ try:
+ self.fullscreenChanged.emit()
+ except Exception:
+ pass
+ try:
+ self._show_fs_ui()
+ except Exception:
+ pass
+
+ def _fs_exit_requested(self) -> None:
+ """Exit fullscreen from the pill/hook. No-op when not fullscreen."""
+ try:
+ if self._fullscreen:
+ self.toggleFullscreen()
+ except Exception:
+ pass
+
+ def _show_fs_ui(self) -> None:
+ """Show the exit pill above the fs video and arm the Esc hook."""
+ if self._container is None:
+ return
+ try:
+ if _FsExitPill is not None:
+ if self._fs_pill is None:
+ self._fs_pill = _FsExitPill(self._container)
+ self._fs_pill.set_clicked(self._fs_exit_requested)
+ try:
+ screen = self._container.screen()
+ if screen is not None:
+ size = screen.size()
+ parent_w, parent_h = int(size.width()), int(size.height())
+ else:
+ parent_w, parent_h = 0, 0
+ except Exception:
+ parent_w, parent_h = 0, 0
+ if parent_w < 2 or parent_h < 2:
+ try:
+ parent_w = int(self._container.width())
+ parent_h = int(self._container.height())
+ except Exception:
+ parent_w, parent_h = 0, 0
+ if parent_w >= 2 and parent_h >= 2:
+ self._fs_pill.place_top_right(parent_w, parent_h)
+ try:
+ self._fs_pill.raise_()
+ except Exception:
+ pass
+ try:
+ if not self._fs_pill.isVisible():
+ self._fs_pill.setVisible(True)
+ except Exception:
+ pass
+ except Exception:
+ pass
+ try:
+ pill_hwnd = 0
+ if self._fs_pill is not None:
+ try:
+ pill_hwnd = int(self._fs_pill.winId() or 0)
+ except Exception:
+ pill_hwnd = 0
+ self._fs_keys.install(
+ self._fs_exit_requested,
+ int(self._wid or 0),
+ (pill_hwnd,) if pill_hwnd > 0 else (),
+ )
+ except Exception:
+ pass
+
+ def _hide_fs_ui(self) -> None:
+ """Hide the exit pill and disarm the Esc hook. Idempotent."""
+ try:
+ self._fs_keys.uninstall()
+ except Exception:
+ pass
+ try:
+ if self._fs_pill is not None and self._fs_pill.isVisible():
+ self._fs_pill.setVisible(False)
+ except Exception:
+ pass
+
+ def _restore_video_slot(self) -> None:
+ """Dock the container back into the app window's video slot."""
+ if self._container is None:
+ return
+ try:
+ self._container.showNormal()
+ except Exception:
+ pass
+ if self._main_window is not None:
+ try:
+ self._container.setParent(self._main_window)
+ except Exception:
+ pass
+
+ def _apply_visibility(self) -> None:
+ """Central visibility gate: session AND tab AND no dialog AND geom.
+
+ While video-only fullscreen is active the container is a top-level
+ fullscreen window: slot geometry syncs must NOT touch it (they
+ would drag the fullscreen window around), so this is a no-op that
+ only ensures it stays visible. Slot geometry is preserved for the
+ restore.
+ """
+ if self._container is None:
+ return
+ try:
+ if not self._session_active or not self._tab_visible or self._dialog_open:
+ try:
+ if self._container.isVisible():
+ self._container.setVisible(False)
+ except Exception:
+ try:
+ self._container.setVisible(False)
+ except Exception:
+ pass
+ return
+ if self._qt_fs and self._fullscreen and self._is_embedded():
+ try:
+ if not self._container.isVisible():
+ self._container.setVisible(True)
+ except Exception:
+ pass
+ return
+ if self._geom is None:
+ return
+ x, y, w, h = self._geom
+ if w < 2 or h < 2:
+ self._container.setVisible(False)
+ return
+ self._container.setX(int(round(x)))
+ self._container.setY(int(round(y)))
+ self._container.resize(max(2, int(round(w))), max(2, int(round(h))))
+ if not self._container.isVisible():
+ self._container.setVisible(True)
+ except Exception:
+ pass
+
+ def set_session_active(self, active: bool) -> None:
+ """Show/hide the container for a Live session (GUI thread)."""
+ self._session_active = bool(active)
+ if not active:
+ # Dock the video back first: stopping mid-fullscreen must
+ # never strand a fullscreen video window with no session.
+ try:
+ self._exit_fullscreen_if_needed()
+ except Exception:
+ pass
+ self._paused = False
+ self._muted = False
+ self._volume = self.MPV_DEFAULT_VOLUME
+ self._fullscreen = False
+ self._qt_fs = False
+ for signal in (self.pausedChanged, self.mutedChanged, self.volumeChanged,
+ self.fullscreenChanged):
+ try:
+ signal.emit()
+ except Exception:
+ pass
+ try:
+ self.activeChanged.emit()
+ except Exception:
+ pass
+ self._apply_visibility()
+
+ @Property(bool, notify=activeChanged)
+ def isActive(self) -> bool:
+ return self._session_active
+
+ @Property(bool, notify=tabActiveChanged)
+ def tabActive(self) -> bool:
+ return self._tab_visible
+
+ @Property(bool, notify=dialogOpenChanged)
+ def dialogOpen(self) -> bool:
+ return self._dialog_open
+
+ def shutdown(self) -> None:
+ """Hide and release the container (app exit, GUI thread)."""
+ try:
+ self._hide_fs_ui()
+ except Exception:
+ pass
+ self._session_active = False
+ self._tab_visible = True
+ self._dialog_open = False
+ self._qt_fs = False
+ self._fs_pill = None
+ self._wid = 0
+ self._geom = None
+ try:
+ if self._container is not None:
+ self._container.setVisible(False)
+ except Exception:
+ pass
+ self._container = None
+ self._main_window = None
+
+ # -- transport (mpv JSON IPC, checked replies on a daemon thread) ----
+ def _send(self, command: list, apply: Any) -> None:
+ """Run one IPC round-trip; ``apply(reply)`` only on MPV success."""
+ pipe = self._ipc_pipe
+ if not pipe:
+ self.embedError.emit("Live player control is unavailable (no session).")
+ return
+
+ def _run() -> None:
+ try:
+ reply = _ipc_roundtrip(pipe, command)
+ except Exception as exc:
+ try:
+ self.embedError.emit(f"Live player control failed: {exc}")
+ except Exception:
+ pass
+ return
+ try:
+ apply(reply)
+ except Exception:
+ pass
+
+ threading.Thread(target=_run, daemon=True, name="dlss5-live-ipc").start()
+
+ @Slot()
+ def togglePause(self) -> None:
+ """Toggle MPV pause; flips the label only on MPV success."""
+ def _apply(_reply: dict) -> None:
+ self._paused = not self._paused
+ self.pausedChanged.emit()
+
+ self._send(["cycle", "pause"], _apply)
+
+ @Slot()
+ def toggleMute(self) -> None:
+ """Toggle MPV mute; flips the label only on MPV success."""
+ def _apply(_reply: dict) -> None:
+ self._muted = not self._muted
+ self.mutedChanged.emit()
+
+ self._send(["cycle", "mute"], _apply)
+
+ def _bump_volume(self, delta: int) -> None:
+ """Step MPV volume relatively, then read back the true value."""
+ pipe = self._ipc_pipe
+ if not pipe:
+ self.embedError.emit("Live player control is unavailable (no session).")
+ return
+
+ def _run() -> None:
+ try:
+ _ipc_roundtrip(pipe, ["add", "volume", int(delta)])
+ reply = _ipc_roundtrip(pipe, ["get_property", "volume"])
+ value = int(round(float(reply.get("data", self._volume))))
+ except Exception as exc:
+ try:
+ self.embedError.emit(f"Live volume control failed: {exc}")
+ except Exception:
+ pass
+ return
+ try:
+ self._volume = max(0, min(self.MPV_MAX_VOLUME, value))
+ self.volumeChanged.emit()
+ except Exception:
+ pass
+
+ threading.Thread(target=_run, daemon=True, name="dlss5-live-ipc").start()
+
+ @Slot()
+ def volumeUp(self) -> None:
+ """Raise MPV volume one step; updates the label on success."""
+ self._bump_volume(self.VOLUME_STEP)
+
+ @Slot()
+ def volumeDown(self) -> None:
+ """Lower MPV volume one step; updates the label on success."""
+ self._bump_volume(-self.VOLUME_STEP)
+
+ @Slot()
+ def toggleFullscreen(self) -> None:
+ """Toggle video-only fullscreen (Qt-side when embedded, IPC if detached).
+
+ MPV cannot fullscreen itself while embedded via ``--wid`` (it owns
+ no top-level window; ``cycle fullscreen`` succeeds with zero visual
+ effect). The embedded path therefore promotes the container itself
+ to a top-level fullscreen window — only the video takes the
+ screen, the app window stays exactly as it is. The detached
+ fallback keeps the original IPC command, which works there.
+ """
+ if self._fullscreen:
+ try:
+ self._exit_fullscreen_if_needed()
+ except Exception as exc:
+ self.embedError.emit(f"Could not leave fullscreen: {exc}")
+ return
+ self._apply_visibility()
+ return
+ if self._is_embedded():
+ if not self._session_active:
+ self.embedError.emit("Start a Live session before using Full Screen.")
+ return
+ try:
+ self._enter_qt_fullscreen()
+ except Exception as exc:
+ self.embedError.emit(f"Could not enter fullscreen: {exc}")
+ return
+ self._apply_visibility()
+ return
+
+ def _apply(_reply: dict) -> None:
+ self._fullscreen = not self._fullscreen
+ self.fullscreenChanged.emit()
+
+ self._send(["cycle", "fullscreen"], _apply)
+
+ @Property(bool, notify=fullscreenChanged)
+ def fullscreen(self) -> bool:
+ return self._fullscreen
+
+ @Property(bool, notify=pausedChanged)
+ def paused(self) -> bool:
+ return self._paused
+
+ @Property(bool, notify=mutedChanged)
+ def muted(self) -> bool:
+ return self._muted
+
+ @Property(int, notify=volumeChanged)
+ def volume(self) -> int:
+ return self._volume
diff --git a/src/live/pipeline.py b/src/live/pipeline.py
index 3bbb623..c7f69d6 100644
--- a/src/live/pipeline.py
+++ b/src/live/pipeline.py
@@ -154,9 +154,12 @@ class LiveSession(threading.Thread):
item: VideoFrame, index: int):
native = None
try:
- with NativeDeadline(self.controller, EFFECT_REPLACEMENT_TIMEOUT) as deadline:
- native = DLSSFrameSession(**native_args, controller=deadline,
- native_settings=resolve_native_settings(settings),
+ with NativeDeadline(self.controller, EFFECT_REPLACEMENT_TIMEOUT) as deadline:
+ # The replacement session must match the running path: CUDA
+ # branch native_args carry cuda_video=True, host ones don't.
+ native = DLSSFrameSession(**native_args, controller=deadline,
+ native_settings=resolve_native_settings(
+ settings, gpu_mode=bool(native_args.get("cuda_video", False))),
composition_mask=settings.nr_mask)
native.diagnostics.encode_backend = (
"nvenc" if self.info.encoder == "NVIDIA NVENC" else "cpu"
@@ -224,7 +227,7 @@ class LiveSession(threading.Thread):
# startup, and include its cost in automatic cadence selection.
return False, None
- def _decoder_command(self, source: ResolvedSource, width: int, height: int, rate) -> list[str]:
+ def _decoder_command(self, source: ResolvedSource, width: int, height: int, rate, *, cuda: bool) -> list[str]:
opts = self.options
command = [str(FFMPEG), "-hide_banner", "-loglevel", "warning", "-nostdin", "-filter_threads", "2"]
# HLS broadcasts can jump clocks at reconnects/ad boundaries. Let
@@ -239,7 +242,7 @@ class LiveSession(threading.Thread):
command += [*input_args(source.audio_url, source.audio_headers, opts.network_timeout),
"-thread_queue_size", "32", "-i", source.audio_url]
audio_input = "1"
- if opts.nr_gpu_mode:
+ if cuda:
# Demux compressed video without decoding pixels. Audio alone is
# normalized to timestamped stereo PCM for PyAV's HLS mux.
command += ["-map", "0:v:0", "-map", f"{audio_input}:a:0?", "-sn", "-dn",
@@ -403,7 +406,7 @@ class LiveSession(threading.Thread):
)
try:
decoder = self._spawn(
- "demux", self._decoder_command(resolved, in_w, in_h, self._rate.rate),
+ "demux", self._decoder_command(resolved, in_w, in_h, self._rate.rate, cuda=True),
stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,
)
decode_device = HWAccel(
@@ -577,11 +580,9 @@ class LiveSession(threading.Thread):
if request is None:
output, output_pts, cost = evaluate(self.effects.applied, reset)
else:
- old_settings = self.effects.applied
- update_started = time.perf_counter()
- try:
- if not request.settings.nr_gpu_mode:
- raise RuntimeError("Changing GPU mode during Live requires Stop and Start.")
+ old_settings = self.effects.applied
+ update_started = time.perf_counter()
+ try:
output, output_pts, cost = evaluate(request.settings, True)
self.effects.complete(
request, pts=pts,
@@ -708,11 +709,12 @@ class LiveSession(threading.Thread):
self._player_state = json.loads((self._session_dir / "player.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
pass
- code = self._mpv.poll()
- self._set(mpv_running=code is None)
- self._set(player_dropped_frames=int(self._player_state.get("dropped", 0)) +
- int(self._player_state.get("decoder_dropped", 0)),
- rebuffer_events=int(self._player_state.get("stalls", 0)),
+ code = self._mpv.poll()
+ self._set(mpv_running=code is None)
+ self._set(player_started=bool(self._player_state.get("started", False)),
+ player_dropped_frames=int(self._player_state.get("dropped", 0)) +
+ int(self._player_state.get("decoder_dropped", 0)),
+ rebuffer_events=int(self._player_state.get("stalls", 0)),
av_sync_ms=float(self._player_state.get("avsync", 0)) * 1000)
if code is not None and not finished:
if code:
@@ -725,10 +727,12 @@ class LiveSession(threading.Thread):
if ready and not self._player_attempted:
self._player_attempted = True
self._playback_started = now
- if self.options.open_mpv:
- self._mpv = launch_mpv(self.info.playlist_url, self._title, self.options.mpv_args,
- buffer_seconds=min(self.options.buffer_seconds, published),
- state_path=self._session_dir / "player.json")
+ if self.options.open_mpv:
+ self._mpv = launch_mpv(self.info.playlist_url, self._title, self.options.mpv_args,
+ buffer_seconds=min(self.options.buffer_seconds, published),
+ state_path=self._session_dir / "player.json",
+ wid=int(getattr(self.options, "mpv_wid", 0) or 0),
+ ipc_server=str(getattr(self.options, "mpv_ipc_server", "") or ""))
self._set(mpv_running=True)
info = self.snapshot()
position = (float(self._player_state.get("position", 0)) if self._mpv
@@ -791,18 +795,15 @@ class LiveSession(threading.Thread):
out_w, out_h = resolve_output_size(in_w, in_h, factor)
self._set(status=f"Preparing Neural Rendering: {in_w}x{in_h} -> {out_w}x{out_h}...")
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)
- encoder_uuid = ai_uuid if options.nr_gpu_mode else video_uuid
- nvenc, ordinal = self._select_encoder(prepared_runtime.gpus, encoder_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")
- if options.nr_gpu_mode:
- if not nvenc or ordinal is None:
- raise RuntimeError(
- "GPU ON Live requires H.264 NVENC on the selected AI GPU. "
- "Switch GPU OFF to use the host-staging CPU encoder boundary."
- )
+ ai_uuid, video_uuid = processing_gpu_settings()
+ gpu = resolve_runtime_ai_gpu(prepared_runtime.gpus, prepared_runtime.runtime_bundle, ai_uuid)
+ # Automatic path selection: NVENC on the AI GPU takes the CUDA path,
+ # anything else falls back to the host-memory path with a CPU encoder.
+ nvenc, ordinal = self._select_encoder(prepared_runtime.gpus, ai_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")
+ cuda_path = bool(nvenc and ordinal is not None)
+ if cuda_path:
self._produce_cuda(
resolved, metadata, in_w, in_h, out_w, out_h, factor, mode,
prepared_runtime, gpu, ordinal,
@@ -819,12 +820,12 @@ class LiveSession(threading.Thread):
native_args = dict(input_width=in_w, input_height=in_h, output_width=out_w, output_height=out_h,
frame_count=None, warmup_frames=0, factor=factor, mode=mode,
gpu=gpu, runtime_bundle=prepared_runtime.runtime_bundle)
- native = DLSSFrameSession(**native_args, native_settings=resolve_native_settings(options),
+ native = DLSSFrameSession(**native_args, native_settings=resolve_native_settings(options, gpu_mode=False),
composition_mask=options.nr_mask,
controller=self.controller)
native.diagnostics.encode_backend = "nvenc" if nvenc else "cpu"
self._last_progress = time.monotonic()
- decoder = self._spawn("decoder", self._decoder_command(resolved, out_w, out_h, self._rate.rate),
+ decoder = self._spawn("decoder", self._decoder_command(resolved, out_w, out_h, self._rate.rate, cuda=False),
stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
processes.append(decoder)
encoder = self._spawn("encoder", self._encoder_command(self._rate.rate, ordinal, nvenc),
diff --git a/src/live/player.py b/src/live/player.py
index 8fde274..cb487bb 100644
--- a/src/live/player.py
+++ b/src/live/player.py
@@ -29,8 +29,8 @@ def check_live_binaries(*, resolve_pages: bool, play: bool) -> None:
)
if play and not MPV.is_file():
raise RuntimeError(
- f"MPV is not installed ({MPV} missing); uncheck "
- "'Open in MPV' or restore the portable player."
+ f"MPV is not installed ({MPV} missing); "
+ "restore the portable player to watch Live in-tab."
)
@@ -41,8 +41,15 @@ def launch_mpv(
*,
buffer_seconds: float = 6.0,
state_path: Path | None = None,
+ wid: int = 0,
+ ipc_server: str = "",
) -> subprocess.Popen:
- """Open the vendored MPV on a Live playlist. Raises on missing binary."""
+ """Play a Live playlist on the vendored MPV. Raises on missing binary.
+
+ When ``wid`` is a valid parent-window handle the player attaches to it
+ (in-tab embedding) instead of opening its own window. ``ipc_server``
+ enables the JSON IPC channel used by the in-tab transport controls.
+ """
if not MPV.is_file():
raise RuntimeError(
f"MPV is not installed ({MPV} missing); the Live stream "
@@ -69,8 +76,24 @@ def launch_mpv(
f"--title=DLSS 5 Live — {title}",
"--terminal=no",
*extra_args,
- playlist_url,
]
+ if wid:
+ # In-tab embedding: MPV creates its own child window covering the
+ # given parent and letterboxes the video itself. Input goes to the
+ # QML transport (pause/mute via IPC); the OSD would only fight it.
+ command += [
+ f"--wid={int(wid)}",
+ "--force-window=yes",
+ "--no-border",
+ "--keepaspect=yes",
+ "--input-vo-keyboard=no",
+ "--no-osc",
+ "--no-osd-bar",
+ "--cursor-autohide=no",
+ ]
+ if ipc_server:
+ command.append(f"--input-ipc-server={ipc_server}")
+ command.append(playlist_url)
creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
try:
process = subprocess.Popen(
diff --git a/src/live/ui.py b/src/live/ui.py
deleted file mode 100644
index f1eabd8..0000000
--- a/src/live/ui.py
+++ /dev/null
@@ -1,238 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass
-from pathlib import Path
-
-import gradio as gr
-
-from ..settings.models import UISettings, parse_automatic_mask
-from ..neural_rendering.video.ui import build_neural_controls
-from ..neural_rendering.composition_ui import CompositionWidgets, build_composition_widgets
-from .models import (LIVE_FPS_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
-from .models import LiveOptions
-
-
-def start_live(
- source: str,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- max_height: str,
- segment_seconds: str,
- open_mpv: bool,
- target_fps: str = "Auto",
- buffer_seconds: float = 6.0,
- source_quality: str = "Auto",
- source_mode: str = "Online",
- local_video: str | None = None,
-) -> str:
- if is_live_running():
- raise gr.Error("A Live session is already running; Stop it first.")
- if source_mode == "Local":
- if not local_video or not Path(local_video).is_file():
- raise gr.Error("Select a local video before starting Live.")
- selected_source = str(local_video)
- elif source_mode == "Online":
- selected_source = (source or "").strip()
- if not selected_source:
- raise gr.Error("Enter an online URL, or select Local to use the uploaded video.")
- else:
- raise gr.Error("Choose Online or Local as the source.")
- try:
- height = int(max_height)
- except (TypeError, ValueError):
- height = 720
- try:
- segment = int(segment_seconds)
- except (TypeError, ValueError):
- segment = 2
- try:
- factor = float(upscaling_factor)
- except (TypeError, ValueError):
- raise gr.Error("Choose a valid scale.") from None
- try:
- auto_mask = parse_automatic_mask(automatic_mask)
- except ValueError as exc:
- raise gr.Error(str(exc)) from exc
- options = LiveOptions(
- source=selected_source,
- nr_style=nr_style,
- nr_intensity=float(nr_intensity),
- nr_passes=int(nr_passes),
- local_tone_strength=float(local_tone_strength),
- local_structure_strength=float(local_structure_strength),
- skin_structure_strength=float(skin_structure_strength),
- automatic_mask=auto_mask,
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- shimmer_suppression=float(shimmer_suppression),
- mask_feather=int(mask_feather),
- nr_mask=nr_mask,
- nr_gpu_mode=nr_gpu_mode,
- max_height=height if height in LIVE_MAX_HEIGHTS else 720,
- upscaling_factor=factor,
- segment_seconds=segment if segment in (1, 2, 4, 6) else 2,
- open_mpv=bool(open_mpv),
- target_fps=target_fps,
- buffer_seconds=float(buffer_seconds),
- source_quality=source_quality,
- )
- try:
- info = start_live_session(options)
- except RuntimeError as exc:
- raise gr.Error(str(exc)) from exc
- return info.status
-
-
-def stop_live() -> str:
- try:
- info = stop_live_session()
- except RuntimeError as exc:
- raise gr.Error(str(exc)) from exc
- return info.status
-
-
-def refresh_live_status() -> str:
- info = live_status()
- if not info.running and info.status == "Idle.":
- return "Idle. Enter a source and press Start Live."
- parts = [info.status]
- if info.playlist_url:
- parts.append(f"Playlist: {info.playlist_url}")
- if info.mpv_running:
- parts.append(f"MPV: {info.player_dropped_frames} dropped | {info.rebuffer_events} rebuffer events | "
- f"A/V offset {info.av_sync_ms:+.1f} ms")
- if info.output_size:
- parts.append(f"Received {info.source_size} -> Processing {info.input_size} -> Output {info.output_size} | {info.encoder}")
- if info.source_quality_note:
- parts.append(info.source_quality_note)
- parts.append(f"DLSS effects: {info.effects_status}")
- if info.applied_at_pts is not None:
- parts.append(f"Latest applied change starts at video time {info.applied_at_pts / 90000:.2f}s; "
- "buffered video keeps its previous appearance until then.")
- if info.effects_error:
- parts.append(f"Effect update: {info.effects_error}")
- if info.processing and info.source_fps:
- parts.append(f"Source: {info.source_fps:.2f} fps. Scene analysis: {info.guide_ms:.1f} ms | "
- f"DLSS: {info.dlss_ms:.1f} ms | Encode transport: {info.encode_ms:.1f} ms")
- if info.report_path:
- parts.append(f"Diagnostics: {info.report_path}")
- return "\n".join(parts)
-
-
-@dataclass(slots=True)
-class LiveTab:
- source: object
- neural: list[object]
- composition: CompositionWidgets
- mask_state: object
- gpu_mode: object
- max_height: object
- segment: object
- open_mpv: object
- start: object
- stop: object
- status: object
- target_fps: object
- buffer: object
- source_quality: object
- source_mode: object
- local_video: object
-
- @property
- def settings_inputs(self) -> list[object]:
- # Shared DLSS values only (persisted globally + mirrored); the rest
- # of the Live options are session-local.
- return [*self.neural]
-
-
-def build_live_tab(settings: UISettings, gpu_mode_state: object, mask_state: object) -> LiveTab:
- height_labels = {"1440": "1440p (2K)", "2160": "2160p (4K)"}
- with gr.Row():
- with gr.Column(scale=3):
- source_mode = gr.Radio(
- choices=["Online", "Local"], value="Online", label="Source",
- )
- source = gr.Textbox(
- label="Online URL",
- placeholder="Direct stream URL, YouTube or Twitch URL",
- )
- local_video = gr.File(
- label="Local video", file_count="single", file_types=["video"],
- type="filepath", interactive=True,
- )
- with gr.Row():
- start = gr.Button("Start Live", variant="primary")
- stop = gr.Button("Stop", variant="stop")
- with gr.Column(elem_classes=["neural-controls-unified"]):
- neural = build_neural_controls(settings)
- composition = build_composition_widgets()
- with gr.Row():
- source_quality = gr.Dropdown(
- choices=[("Auto (follow Max input height)" if height == "Auto" else
- height_labels.get(height, f"{height}p"), height)
- for height in LIVE_SOURCE_QUALITY_CHOICES],
- value="Auto", label="Source quality",
- )
- max_height = gr.Dropdown(
- choices=[(height_labels.get(height, height), height) for height in LIVE_MAX_HEIGHT_CHOICES],
- value="720",
- label="Max input height",
- )
- segment = gr.Dropdown(
- choices=list(LIVE_SEGMENT_CHOICES),
- value="2",
- label="Segment length (s)",
- )
- with gr.Row():
- target_fps = gr.Dropdown(
- choices=list(LIVE_FPS_CHOICES), value="Auto", label="Live frame rate",
- )
- buffer = gr.Slider(
- minimum=2, maximum=30, step=1, value=6, label="Playback buffer (seconds)",
- )
- open_mpv = gr.Checkbox(
- value=True,
- label="Open in MPV",
- )
- with gr.Column(scale=3):
- status = gr.Textbox(
- label="Live status",
- value="Idle. Enter a source and press Start Live.",
- interactive=False,
- lines=10,
- )
- tab = LiveTab(
- source, neural, composition, mask_state, gpu_mode_state, max_height, segment,
- open_mpv, start, stop, status, target_fps, buffer, source_quality,
- source_mode, local_video,
- )
- start.click(
- start_live,
- inputs=[source, *neural, mask_state, gpu_mode_state, max_height, segment, open_mpv, target_fps, buffer,
- source_quality, source_mode, local_video],
- outputs=status,
- concurrency_limit=1,
- show_progress="full",
- )
- stop.click(stop_live, outputs=status, queue=False, show_progress="hidden")
- timer = gr.Timer(0.5)
- timer.tick(refresh_live_status, outputs=status, queue=False, show_progress="hidden")
- return tab
diff --git a/src/neural_rendering/composition_ui.py b/src/neural_rendering/composition_ui.py
deleted file mode 100644
index 4a500f9..0000000
--- a/src/neural_rendering/composition_ui.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Shared Image/Video/Live controls for the post-DLSS compositor."""
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import gradio as gr
-
-from ..core.nr_composition import inspect_nr_mask, mask_status
-from ..settings.models import UISettings
-
-
-@dataclass(slots=True)
-class CompositionWidgets:
- mask: object
- mask_status: object
- detail_only: object
-
-
-def build_composition_sliders(settings: UISettings) -> list[object]:
- # Created directly in the parent Column (no gr.Row): each slider spans the
- # full width in one vertical stack. Return order is unchanged.
- color = gr.Slider(
- 0.0, 1.0, value=settings.nr_color_strength, step=0.05, precision=2,
- label="NR Color Strength", buttons=["reset"],
- )
- tone = gr.Slider(
- 0.0, 1.0, value=settings.tone_preservation, step=0.05, precision=2,
- label="Tone Preservation", buttons=["reset"],
- )
- face_skin = gr.Slider(
- 0.0, 1.0, value=settings.face_skin_protection, step=0.05, precision=2,
- label="Face/Skin Protection", buttons=["reset"],
- )
- grain = gr.Slider(
- 0.0, 1.0, value=settings.grain_preservation, step=0.05, precision=2,
- label="Grain Preservation", buttons=["reset"],
- )
- feather = gr.Slider(
- 0, 128, value=settings.mask_feather, step=1, precision=0,
- label="Mask Feather (output pixels)", buttons=["reset"],
- )
- return [color, tone, face_skin, grain, feather]
-
-
-def build_composition_widgets() -> CompositionWidgets:
- detail_only = gr.Button(
- "Detail-Only",
- size="sm",
- variant="secondary",
- )
- mask = gr.Image(
- label="Custom NR Mask",
- type="filepath",
- # Preserve the uploaded bytes and original filename for EXIF/animation
- # handling plus report hashing; decoding/conversion belongs to our mask
- # preparation step, not Gradio's image preprocessor.
- image_mode=None,
- sources=["upload"],
- height=180,
- )
- status = gr.Markdown(mask_status(None))
- return CompositionWidgets(mask, status, detail_only)
-
-
-def _select_mask(path: str | None):
- try:
- selection = inspect_nr_mask(path)
- except ValueError as exc:
- raise gr.Error(str(exc)) from exc
- from ..settings.ui import persist_nr_mask
-
- persist_nr_mask(selection)
- value = selection.state() if selection is not None else None
- display_path = selection.path if selection is not None else None
- status = mask_status(selection)
- return value, display_path, display_path, display_path, status, status, status
-
-
-def _clear_mask():
- return _select_mask(None)
-
-
-def bind_composition_mask_events(
- mask_state: object,
- image_widgets: CompositionWidgets,
- video_widgets: CompositionWidgets,
- live_widgets: CompositionWidgets,
-) -> None:
- widgets = (image_widgets, video_widgets, live_widgets)
- masks = [item.mask for item in widgets]
- statuses = [item.mask_status for item in widgets]
- outputs = [mask_state, *masks, *statuses]
- for item in widgets:
- item.mask.upload(
- _select_mask,
- inputs=item.mask,
- outputs=outputs,
- queue=False,
- show_progress="hidden",
- )
- item.mask.clear(
- _clear_mask,
- outputs=outputs,
- queue=False,
- show_progress="hidden",
- )
diff --git a/src/neural_rendering/image/decoder.py b/src/neural_rendering/image/decoder.py
index e77988e..d79f77a 100644
--- a/src/neural_rendering/image/decoder.py
+++ b/src/neural_rendering/image/decoder.py
@@ -14,13 +14,13 @@ import rawpy
import resvg_py
from PIL import Image, ImageCms, ImageOps
-from ...core.paths import GRADIO_TEMP
+from ...core.paths import APP_TEMP
from .models import RAW_EXTENSIONS
pillow_heif.register_heif_opener()
Image.MAX_IMAGE_PIXELS = 100_000_000
-# Formats modern Chromium-based Gradio clients can display without a display
+# Formats the native Qt image provider can display without a
# conversion. Animated raster inputs are still converted below so the preview
# matches the processing pipeline's first-frame/page semantics.
_BROWSER_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".avif", ".bmp"}
@@ -174,7 +174,7 @@ def decode_image_preview(
"""Decode a UI preview without constructing the full render-time NumPy payload.
``max_size=None`` preserves the decoded source dimensions. This is used only
- by the opt-in full-size Gradio preview path.
+ by the opt-in full-size native preview path.
"""
source = Path(path).resolve()
suffix = source.suffix.lower()
@@ -243,12 +243,12 @@ def _direct_browser_image(source: Path) -> bool:
def full_size_image_preview_path(path: str | os.PathLike[str]) -> str:
- """Return a browser-displayable full-resolution path for an image.
+ """Return a displayable full-resolution path for an image.
- Browser-native, single-frame formats are served directly so no pixels are
+ Native single-frame formats are served directly so no pixels are
copied or re-encoded. RAW/HEIF/TIFF/animated/other Pillow-readable sources
are converted once to a lossless full-resolution PNG in the app-local
- Gradio temp directory.
+ temp directory.
"""
source = Path(path).resolve()
if not source.is_file():
@@ -259,14 +259,14 @@ def full_size_image_preview_path(path: str | os.PathLike[str]) -> str:
stat = source.stat()
identity = f"{source}|{stat.st_dev}|{stat.st_ino}|{stat.st_size}|{stat.st_mtime_ns}"
digest = hashlib.sha256(identity.encode("utf-8", "surrogatepass")).hexdigest()[:24]
- GRADIO_TEMP.mkdir(parents=True, exist_ok=True)
- destination = GRADIO_TEMP / f"dlss5-fullsize-source-{digest}.png"
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
+ destination = APP_TEMP / f"dlss5-fullsize-source-{digest}.png"
if destination.is_file():
return str(destination.resolve())
image = decode_image_preview(source, None)
handle, raw_temp = tempfile.mkstemp(
- prefix="dlss5-fullsize-source-write-", suffix=".png", dir=GRADIO_TEMP
+ prefix="dlss5-fullsize-source-write-", suffix=".png", dir=APP_TEMP
)
os.close(handle)
temporary = Path(raw_temp)
diff --git a/src/neural_rendering/image/encoder.py b/src/neural_rendering/image/encoder.py
index 3a8b02a..e63b9b9 100644
--- a/src/neural_rendering/image/encoder.py
+++ b/src/neural_rendering/image/encoder.py
@@ -14,7 +14,7 @@ from PIL import Image
from .models import ImageConversionOptions
from ...core.jobs import Cancelled
-from ...core.paths import GRADIO_TEMP
+from ...core.paths import APP_TEMP
from ...core.render_metadata import (
IMAGE_NOTE_FORMATS, MetadataNoteError, check_cancelled, embedding_warning,
merge_render_note, record_embedding,
@@ -71,9 +71,9 @@ def take_image_preview(output_path: str | os.PathLike[str]) -> Image.Image | Non
def _spill_preview(key: str, image: Image.Image) -> None:
- GRADIO_TEMP.mkdir(parents=True, exist_ok=True)
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
handle, raw_path = tempfile.mkstemp(
- prefix="dlss5-preview-", suffix=".png", dir=GRADIO_TEMP
+ prefix="dlss5-preview-", suffix=".png", dir=APP_TEMP
)
os.close(handle)
path = Path(raw_path)
@@ -119,15 +119,14 @@ def make_image_preview(
def save_full_size_image_preview(
rgba: np.ndarray, output_format: str, has_transparency: bool | None = None,
) -> str:
- """Write processed preview pixels as a full-resolution browser-safe PNG.
+ """Write processed preview pixels as a full-resolution PNG for the native viewer.
- This avoids handing a full-size PIL object to Gradio (which would create an
- additional cache encode). JPEG preview semantics still composite transparent
+ JPEG preview semantics still composite transparent
pixels over white, matching the production JPEG path.
"""
- GRADIO_TEMP.mkdir(parents=True, exist_ok=True)
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
handle, raw_path = tempfile.mkstemp(
- prefix="dlss5-fullsize-processed-", suffix=".png", dir=GRADIO_TEMP
+ prefix="dlss5-fullsize-processed-", suffix=".png", dir=APP_TEMP
)
os.close(handle)
path = Path(raw_path)
diff --git a/src/neural_rendering/image/models.py b/src/neural_rendering/image/models.py
index c1d59e5..866c15d 100644
--- a/src/neural_rendering/image/models.py
+++ b/src/neural_rendering/image/models.py
@@ -33,7 +33,6 @@ class ImageConversionOptions:
preserve_metadata: bool = True
warmup_frames: int = 0
automatic_mask: bool = False
- nr_gpu_mode: bool = True
rename_mode: str = "Auto"
custom_suffix: str = "_Neural_Rendering"
diff --git a/src/neural_rendering/image/ui.py b/src/neural_rendering/image/ui.py
deleted file mode 100644
index dbcbdf1..0000000
--- a/src/neural_rendering/image/ui.py
+++ /dev/null
@@ -1,394 +0,0 @@
-from __future__ import annotations
-
-import traceback
-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, build_save_controls,
-)
-from PIL import Image
-
-from ...core.naming import RENAME_MODES
-from ...core.runtime import NR_STYLES, UPSCALING_MODES
-from ...settings.models import AUTOMATIC_MASK_CHOICES, UISettings, automatic_mask_choice, parse_automatic_mask
-from ...settings.storage import full_size_image_previews_enabled, processing_gpu_settings
-from .decoder import decode_image_preview, full_size_image_preview_path
-from .encoder import take_image_preview
-from .batch import convert_images
-from .preview import render_image_preview
-from .models import IMAGE_FORMATS, RAW_EXTENSIONS, ImageConversionOptions
-from ..composition_ui import CompositionWidgets, build_composition_sliders, build_composition_widgets
-
-
-def rename_suffix_update(mode: str):
- return gr.update(interactive=mode == "Custom")
-
-
-UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
-
-
-def build_neural_controls(settings: UISettings):
- nr_style = gr.Radio(
- list(NR_STYLES), value=settings.nr_style, label="NR Style",
- )
- upscaling_factor = gr.Dropdown(
- choices=list(UPSCALING_CHOICES), value=settings.upscaling_factor,
- label="Scale",
- )
- # Each control is created directly in the parent Column (no gr.Row), so
- # every slider spans the full width in one vertical stack. Creation order
- # sets the visual order; the returned list keeps the canonical positional
- # order consumed by render/persist/settings-mirror code.
- nr_intensity = gr.Slider(
- 0.0, 2.0, value=settings.nr_intensity, step=0.05, precision=2,
- label="NR Intensity", buttons=["reset"],
- )
- nr_passes = gr.Slider(
- 1, 4, value=settings.nr_passes, step=1, precision=0,
- label="NR Passes", buttons=["reset"],
- )
- local_tone_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_tone_strength, step=0.05, precision=2,
- label="Local Tone Strength", buttons=["reset"]
- )
- local_structure_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_structure_strength, step=0.05, precision=2,
- label="Local Structure Strength", buttons=["reset"]
- )
- skin_structure_strength = gr.Slider(
- -1.0, 2.0, value=settings.skin_structure_strength, step=0.05, precision=2,
- label="Skin Structure Strength",
- buttons=["reset"],
- )
- composition = build_composition_sliders(settings)
- automatic_mask = gr.Radio(
- choices=AUTOMATIC_MASK_CHOICES,
- value=automatic_mask_choice(settings.automatic_mask),
- label="Automatic Mask",
- )
- return [
- nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask
- ] + composition
-
-
-def preview_input_images(paths: list[str] | str | None):
- if not paths:
- return []
- if isinstance(paths, str):
- paths = [paths]
- full_size = full_size_image_previews_enabled()
- previews = []
- for raw_path in paths:
- try:
- image = (
- full_size_image_preview_path(raw_path)
- if full_size
- else decode_image_preview(raw_path, (1200, 900))
- )
- previews.append((image, Path(raw_path).name))
- except Exception:
- continue
- return previews
-
-
-def _image_options(
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- image_format: str,
- image_quality: float,
- rename_mode: str,
- custom_suffix: str,
-) -> ImageConversionOptions:
- return ImageConversionOptions(
- ai_gpu_uuid=processing_gpu_settings()[0],
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- local_tone_strength=local_tone_strength,
- local_structure_strength=local_structure_strength,
- skin_structure_strength=skin_structure_strength,
- automatic_mask=parse_automatic_mask(automatic_mask),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- mask_feather=int(mask_feather),
- nr_mask=nr_mask,
- nr_gpu_mode=nr_gpu_mode,
- upscaling_factor=upscaling_factor,
- output_format=image_format,
- quality=int(image_quality),
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
-
-def render_image_batch(
- input_paths: list[str] | str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- image_format: str,
- image_quality: float,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
- *, output_dir=None, controller=None, on_item_update=None, direct_disk=False,
-):
- if not input_paths:
- raise gr.Error("Choose at least one image first.")
- if isinstance(input_paths, str):
- input_paths = [input_paths]
- options = _image_options(
- nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask,
- nr_color_strength, tone_preservation, face_skin_protection, grain_preservation,
- mask_feather, nr_mask, nr_gpu_mode,
- image_format, image_quality, rename_mode, custom_suffix,
- )
- full_size = full_size_image_previews_enabled()
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = convert_images(input_paths, options, progress=report, output_dir=output_dir,
- controller=controller, on_item_update=on_item_update,
- generate_previews=not direct_disk and not full_size, create_zip=False)
- except Exception as exc:
- traceback.print_exc()
- if on_item_update is not None:
- raise
- return [], None, [], f"Failed: {exc}"
-
- gallery = []
- for item in ([] if direct_disk else result.successes):
- preview = None
- if full_size:
- try:
- preview = full_size_image_preview_path(item.output_path)
- except Exception:
- # Preview display must never invalidate a successful render.
- preview = None
- else:
- preview = take_image_preview(item.output_path)
- if preview is None:
- with Image.open(item.output_path) as output:
- preview = output.convert("RGBA")
- preview.thumbnail((1200, 900), Image.Resampling.BILINEAR)
- preview = preview.copy()
- gallery.append((preview, Path(item.output_path).name))
- rows = [
- [Path(item.input_path).name, "Complete", Path(item.output_path).name, "; ".join(item.warnings)]
- for item in result.successes
- ]
- rows.extend(
- [Path(item.input_path).name, "Failed", "", item.error] for item in result.failures
- )
- state = "Cancelled" if result.cancelled else "Complete"
- status = (
- f"{state}: {len(result.successes)} image(s) rendered, {len(result.failures)} failed. "
- "Every successful output returned feature-18 success and has a diagnostic report."
- )
- if result.failures:
- status += f"\nFirst error: {result.failures[0].error}"
- return gallery, [item.output_path for item in result.successes], rows, status
-
-
-def preview_rendered_image(
- input_paths: list[str] | str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- image_format: str,
- image_quality: float,
- rename_mode: str,
- custom_suffix: str,
- progress=gr.Progress(track_tqdm=False),
- *, output_dir=None, controller=None, ephemeral_preview=False,
-):
- del output_dir, ephemeral_preview
- paths = [input_paths] if isinstance(input_paths, str) else list(input_paths or [])
- if len(paths) != 1:
- raise gr.Error("Choose exactly one image to preview.")
- options = _image_options(
- nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask,
- nr_color_strength, tone_preservation, face_skin_protection, grain_preservation,
- mask_feather, nr_mask, nr_gpu_mode,
- image_format, image_quality, rename_mode, custom_suffix,
- )
- full_size = full_size_image_previews_enabled()
- image, status = render_image_preview(
- paths[0], options, progress=lambda value, message: progress(value, desc=message),
- controller=controller, full_size_preview=full_size,
- )
- return (
- gr.update(value=[(image, f"Preview — {Path(paths[0]).name}")], visible=True),
- status,
- )
-
-
-@dataclass(slots=True)
-class ImageTab:
- sources: object
- input_gallery: object
- input_actions: object
- select_source: object
- clear_source: object
- neural: list[object]
- composition: CompositionWidgets
- mask_state: object
- gpu_mode: object
- output_format: object
- quality: object
- rename_mode: object
- custom_suffix: object
- render: object
- stop: object
- preview: object
- reset: object
- output_gallery: object
- save_download: object
- zip_button: object
- zip_download: object
- status: object
- results: object
- input_path: object = None
- output_path: object = None
- job_state: object = None
- refresh_realtime_preview_after: object = None
-
- @property
- def render_inputs(self) -> list[object]:
- return [self.sources, *self.neural, self.mask_state, self.gpu_mode, self.output_format, self.quality, self.rename_mode, self.custom_suffix]
-
- @property
- def preview_inputs(self) -> list[object]:
- return self.render_inputs
-
- @property
- def settings_inputs(self) -> list[object]:
- return [*self.neural, self.output_format, self.quality, self.rename_mode, self.custom_suffix]
-
-
-def build_image_tab(settings: UISettings, gpu_mode_state: object, mask_state: object) -> ImageTab:
- upload_types = ["image", ".svg", ".heic", ".heif", *sorted(RAW_EXTENSIONS)]
- with gr.Row():
- with gr.Column(scale=3):
- sources = gr.File(
- label="Input image(s)", file_count="multiple", file_types=upload_types,
- type="filepath", allow_reordering=True, elem_id="image-upload-list",
- elem_classes=["media-upload-surface"],
- )
- input_gallery = gr.Gallery(
- label="Input preview", columns=3, height=520, object_fit="contain",
- interactive=False, visible="hidden", 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")
- with gr.Row():
- render = gr.Button("Render image(s)", variant="primary")
- stop = gr.Button("Stop", variant="stop")
- preview = gr.Button("Preview", visible=False)
- reset = gr.Button("Reset settings")
- with gr.Column(elem_classes=["neural-controls-unified"]):
- neural = build_neural_controls(settings)
- composition = build_composition_widgets()
- input_path, output_path = build_path_controls()
- with gr.Row():
- output_format = gr.Dropdown(
- list(IMAGE_FORMATS), value=settings.image_format, label="Output format",
- )
- quality = gr.Slider(
- 1, 100, value=settings.image_quality, step=1, precision=0,
- label="Lossy quality",
- )
- with gr.Row():
- rename_mode = gr.Radio(
- RENAME_MODES, value=settings.image_rename_mode, label="Rename",
- )
- custom_suffix = gr.Textbox(
- value=settings.image_custom_suffix, label="Custom suffix", placeholder="_Neural_Rendering",
- interactive=settings.image_rename_mode == "Custom",
- )
- with gr.Column(scale=3):
- output_gallery = gr.Gallery(
- label="Enhanced previews", columns=2, height=520, object_fit="contain",
- interactive=False, buttons=["download", "download_all", "fullscreen"],
- elem_id="image-output-preview",
- )
- save_download, zip_button, zip_download = build_save_controls("image", "nr-image")
- 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 = ImageTab(
- sources, input_gallery, input_actions, select_source, clear_source, neural, composition, mask_state, gpu_mode_state, output_format, quality, rename_mode,
- custom_suffix, render, stop, preview, reset, output_gallery, save_download, zip_button, zip_download, status, results
- )
- tab.input_path, tab.output_path = input_path, output_path
- bind_image_events(tab)
- return tab
-
-
-def bind_image_events(tab: ImageTab) -> None:
- tab.refresh_realtime_preview_after = bind_batch_ui(
- tab, render_image_batch, kind="image", preview_mode=preview_input_images,
- archive_prefix="DLSS5_IMAGE_BATCH",
- preview_actions=[(tab.preview, preview_rendered_image)],
- realtime_preview=preview_rendered_image,
- realtime_components=tab.neural,
- )
- tab.rename_mode.change(
- rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False,
- )
diff --git a/src/neural_rendering/ui.py b/src/neural_rendering/ui.py
deleted file mode 100644
index ad9e1f1..0000000
--- a/src/neural_rendering/ui.py
+++ /dev/null
@@ -1,94 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-import gradio as gr
-
-from ..core.batch_ui import bind_input_surface_reactivation
-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 _stable_visible(show: bool):
- # ``hidden`` keeps the component tree mounted while taking no layout space.
- return True if show else "hidden"
-
-
-def mode_visibility(mode: str) -> tuple[dict, dict]:
- """Show one workflow while keeping both stateful component trees mounted."""
- show_video = mode == "Video"
- return (
- gr.update(visible=_stable_visible(not show_video)),
- gr.update(visible=_stable_visible(show_video)),
- )
-
-
-_MODE_GUARD_JS = """(mode) => {
- document.documentElement.dataset.neuralRenderingMode = mode;
- const hiddenPanel = document.getElementById(
- mode === 'Video' ? 'neural-rendering-image' : 'neural-rendering-video'
- );
- if (hiddenPanel) {
- hiddenPanel.querySelectorAll('video').forEach((node) => {
- try { node.pause(); } catch (_) {}
- });
- }
-}"""
-
-
-@dataclass(slots=True)
-class NeuralRenderingTab:
- mode: object
- image: ImageTab
- video: VideoTab
- image_panel: object
- video_panel: object
-
-
-def build_neural_rendering_tab(
- settings: UISettings, gpu_mode_state: object, mask_state: object,
-) -> NeuralRenderingTab:
- mode = gr.Radio(
- choices=list(MODE_CHOICES),
- value="Image",
- label=None,
- show_label=False,
- container=False,
- interactive=True,
- elem_id="neural-rendering-mode",
- )
- with gr.Column(
- visible=True, elem_id="neural-rendering-image", elem_classes=["workflow-mode-panel"],
- ) as image_panel:
- image_tab = build_image_tab(settings, gpu_mode_state, mask_state)
- with gr.Column(
- visible="hidden", elem_id="neural-rendering-video", elem_classes=["workflow-mode-panel"],
- ) as video_panel:
- video_tab = build_video_tab(settings, gpu_mode_state, mask_state)
-
- # First hide the old panel synchronously in the browser. The backend update
- # then makes the requested panel authoritative. If requests overlap, the
- # latest client guard still prevents an older response from exposing the
- # wrong panel; at worst the correct panel stays blank until the latest reply.
- transition = mode.change(
- None, inputs=mode, js=_MODE_GUARD_JS, queue=False, show_progress="hidden",
- trigger_mode="always_last",
- )
- visibility = transition.then(
- mode_visibility,
- inputs=mode,
- outputs=[image_panel, video_panel],
- queue=False,
- show_progress="hidden",
- trigger_mode="always_last",
- )
- # Re-assert the upload/preview invariant after the mode panel is restored.
- # This is non-destructive: it only corrects visibility and never regenerates
- # media or clears output/download state.
- bind_input_surface_reactivation(visibility, image_tab, kind="image")
- bind_input_surface_reactivation(visibility, video_tab, kind="video")
- return NeuralRenderingTab(mode, image_tab, video_tab, image_panel, video_panel)
diff --git a/src/neural_rendering/video/cuda_pipeline.py b/src/neural_rendering/video/cuda_pipeline.py
index 013457f..de7f58f 100644
--- a/src/neural_rendering/video/cuda_pipeline.py
+++ b/src/neural_rendering/video/cuda_pipeline.py
@@ -189,7 +189,7 @@ def convert_video_cuda_nvenc(
options={"primary_ctx": "1"},
is_hw_owned=True,
)
- _progress(progress, 0.01, f"Starting feature 18 on {gpu['display_name']}")
+ _progress(progress, 0.01, "Starting feature 18")
with av.open(str(source), hwaccel=decode_device) as decoded:
input_stream = decoded.streams.video[0]
input_stream.thread_type = "AUTO"
@@ -356,7 +356,7 @@ def convert_video_cuda_nvenc(
_progress(
progress,
0.04 + 0.84 * min(1.0, delivered / estimated_frames),
- f"Neural Rendering frame {delivered} (estimated {estimated_frames})",
+ "Rendering video frames",
)
if not delivered:
raise RuntimeError("The input video contains no decodable frames.")
diff --git a/src/neural_rendering/video/models.py b/src/neural_rendering/video/models.py
index ce5411a..c505f16 100644
--- a/src/neural_rendering/video/models.py
+++ b/src/neural_rendering/video/models.py
@@ -31,7 +31,6 @@ class ConversionOptions:
preview_seconds: float | None = None
preview_frames: int | None = None
automatic_mask: bool = False
- nr_gpu_mode: bool = True
rename_mode: str = "Auto"
custom_suffix: str = "_Neural_Rendering"
# True = truncated preview uses the forced H.264 SDR path (current behavior).
diff --git a/src/neural_rendering/video/preview.py b/src/neural_rendering/video/preview.py
index 2ebcf43..2dce65d 100644
--- a/src/neural_rendering/video/preview.py
+++ b/src/neural_rendering/video/preview.py
@@ -1,134 +1,135 @@
from __future__ import annotations
-import traceback
+from dataclasses import replace
from pathlib import Path
-
-import gradio as gr
+from typing import Callable, Any
from ...core.jobs import Cancelled
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
from .models import ConversionOptions
from .processor import convert_video
PREVIEW_SECONDS = 3.0
+ProgressCallback = Callable[[float, str], None]
+
+
+def _emit_progress(progress: Any, value: float, message: str) -> None:
+ if progress is None:
+ return
+ try:
+ progress(float(value), str(message))
+ except TypeError:
+ progress(float(value), desc=str(message))
-def _process_video(
- input_path: str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool,
- progress,
- preview_seconds: float | None,
- preview_frames: int | None,
+
+def process_video_preview(
+ input_path: str,
+ options: ConversionOptions,
*,
+ preview_seconds: float | None = None,
+ preview_frames: int | None = None,
+ preview_encoding: str = "Auto",
+ progress: ProgressCallback | Any | None = None,
output_dir=None,
controller=None,
ephemeral_preview: bool = False,
+ start_seconds: float | None = None,
+ frame_index: int | None = None,
) -> tuple[str | None, str]:
+ """Qt-native Neural Rendering preview used by the desktop UI.
+
+ Returns a plain ``(media_path, status)`` tuple with no UI-framework objects.
+ """
if not input_path:
- raise gr.Error("Choose a video first.")
- is_preview = preview_seconds is not None or preview_frames is not None
- ai_gpu_uuid, video_gpu_uuid = processing_gpu_settings()
+ raise ValueError("Choose a video first.")
+ source = Path(input_path)
+ if not source.is_file():
+ raise FileNotFoundError(source)
+ try:
+ start = max(0.0, float(start_seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
try:
- preview_mode = current_preview_encoding()
- except Exception:
- preview_mode = "Auto"
- preview_mode = normalize_preview_encoding(preview_mode)
+ frame_no = max(1, int(frame_index or 1)) if frame_index else 1
+ except (TypeError, ValueError):
+ frame_no = 1
+ effective_source = str(source)
+ temp_clip: str | None = None
+ if start > 0.05 and preview_frames is not None:
+ from ...core.ffmpeg.preview import extract_preview_subclip
+ _emit_progress(progress, 0.02, "Seeking to timeline frame…")
+ temp_clip = extract_preview_subclip(
+ str(source), dest_dir=output_dir, start_seconds=start,
+ single_frame=True, controller=controller,
+ )
+ effective_source = temp_clip
+
+ is_preview = preview_seconds is not None or preview_frames is not None
+ preview_encoding_mode = normalize_preview_encoding(preview_encoding)
if is_preview:
effective_codec, effective_container = resolve_preview_codec(
- codec, container, preview_mode
+ options.codec, options.container, preview_encoding_mode
+ )
+ compat_preview = wants_compat_preview(
+ options.codec, options.container, preview_encoding_mode
)
- compat_preview = wants_compat_preview(codec, container, preview_mode)
else:
- effective_codec, effective_container = codec, container
+ effective_codec, effective_container = options.codec, options.container
compat_preview = False
- # HDR Mode only for allowed codecs. Compat (forced H.264) previews stay SDR
- # 8-bit; user-encoded previews preserve the HDR choice.
- effective_hdr = coerce_hdr_mode(effective_codec, hdr_mode) and (
+
+ effective_hdr = coerce_hdr_mode(effective_codec, options.preserve_hdr) and (
not is_preview or not compat_preview
)
- options = ConversionOptions(
- ai_gpu_uuid=ai_gpu_uuid,
- video_gpu_uuid=video_gpu_uuid,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- local_tone_strength=local_tone_strength,
- local_structure_strength=local_structure_strength,
- skin_structure_strength=skin_structure_strength,
- automatic_mask=parse_automatic_mask(automatic_mask),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- shimmer_suppression=float(shimmer_suppression),
- mask_feather=int(mask_feather),
- nr_mask=nr_mask,
- nr_gpu_mode=nr_gpu_mode,
- upscaling_factor=upscaling_factor,
+ effective = replace(
+ options,
codec=effective_codec,
container=effective_container,
- quality=quality,
preserve_hdr=effective_hdr,
preview_seconds=preview_seconds,
preview_frames=preview_frames,
preview_compat=compat_preview,
)
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
try:
result = convert_video(
- input_path, options, progress=report, output_dir=output_dir,
+ effective_source,
+ effective,
+ progress=lambda value, message: _emit_progress(progress, value, message),
+ output_dir=output_dir,
controller=controller,
)
except Cancelled:
return None, "Preview cancelled."
- except Exception as exc:
- traceback.print_exc()
- return None, f"Failed: {exc}"
+ finally:
+ if temp_clip:
+ try:
+ Path(temp_clip).unlink(missing_ok=True)
+ except OSError:
+ pass
def finish(media_path: str | None, status: str) -> tuple[str | None, str]:
if ephemeral_preview:
- # report_path now points at the shared session log (or a kept
- # .err file): only remove legacy per-job report JSONs.
- if Path(result.report_path).name.endswith(".report.json"):
- Path(result.report_path).unlink(missing_ok=True)
- if media_path and Path(media_path).resolve() != Path(result.output_path).resolve():
- Path(result.output_path).unlink(missing_ok=True)
+ try:
+ if Path(result.report_path).name.endswith(".report.json"):
+ Path(result.report_path).unlink(missing_ok=True)
+ except OSError:
+ pass
+ try:
+ if media_path and Path(media_path).resolve() != Path(result.output_path).resolve():
+ Path(result.output_path).unlink(missing_ok=True)
+ except OSError:
+ pass
return media_path, status
- source_name = Path(input_path).name
+ source_name = source.name
if is_preview:
- # Truncated previews normally show the encoded file directly. In Auto
- # mode the pre-check may have selected the user encoding but the actual
- # file can still probe as unplayable (rare); then derive one H.264 file.
output_preview = result.output_path
derived_note = ""
- if preview_mode == "Auto" and not compat_preview:
+ if preview_encoding_mode == "Auto" and not compat_preview:
try:
playable = is_browser_playable(result.output_path)
except Exception:
@@ -136,133 +137,42 @@ def _process_video(
if not playable:
try:
output_preview = make_browser_preview(
- result.output_path, dest_dir=output_dir, controller=controller,
+ result.output_path,
+ dest_dir=output_dir,
+ controller=controller,
)
- derived_note = " (browser preview transcoded to H.264)"
+ derived_note = " (compatibility preview transcoded to H.264)"
except Exception:
output_preview = result.output_path
if preview_frames is not None:
- return finish(output_preview, (
- f"One-frame preview complete for {source_name} on {result.gpu} "
- f"in {result.elapsed_seconds:.1f}s. "
- f"Neural dimensions {result.render_width}×{result.render_height}; "
- f"{result.resize_method}, {result.memory_path}. Feature 18 confirmed."
- f"{derived_note}"
- ))
- return finish(output_preview, (
+ stamp = f" f{frame_no} @ {start:.2f}s" if start > 0.05 else ""
+ return finish(
+ output_preview,
+ f"One-frame preview complete{stamp} for {source_name} on {result.gpu} "
+ f"in {result.elapsed_seconds:.1f}s. Neural dimensions "
+ f"{result.render_width}×{result.render_height}; {result.resize_method}, "
+ f"{result.memory_path}. Feature 18 confirmed.{derived_note}",
+ )
+ return finish(
+ output_preview,
f"Preview complete for {source_name}: {result.frames} frames from the first "
- f"{PREVIEW_SECONDS:g} seconds processed "
- f"on {result.gpu} in {result.elapsed_seconds:.1f}s. Neural dimensions "
+ f"{PREVIEW_SECONDS:g} seconds processed on {result.gpu} in "
+ f"{result.elapsed_seconds:.1f}s. Neural dimensions "
f"{result.render_width}×{result.render_height}; {result.resize_method}, "
- f"{result.memory_path}. All frames returned feature-18 success."
- f"{derived_note}"
- ))
+ f"{result.memory_path}. All frames returned feature-18 success.{derived_note}",
+ )
+
output_preview, used_derivative = resolve_final_preview(
- result.output_path, preview_mode, bounded_proxy=True
+ result.output_path, preview_encoding_mode, bounded_proxy=True
)
status = (
- f"Complete: {result.frames} frames processed on {result.gpu} in {result.elapsed_seconds:.1f}s. "
- f"All {result.nr_count_evidence} frames returned feature-18 success. "
- f"Neural dimensions {result.render_width}×{result.render_height}; "
+ f"Complete: {result.frames} frames processed on {result.gpu} in "
+ f"{result.elapsed_seconds:.1f}s. All {result.nr_count_evidence} frames returned "
+ f"feature-18 success. Neural dimensions {result.render_width}×{result.render_height}; "
f"{result.resize_method}, {result.memory_path}."
)
if used_derivative:
- status += " A short H.264 browser proxy was created; the complete original output is unchanged."
+ status += " A short H.264 compatibility proxy was created; the original output is unchanged."
elif output_preview is None:
- status += f" {effective_container} output was created successfully, but browser preview is unavailable."
+ status += f" {effective_container} output was created successfully, but inline preview is unavailable."
return finish(output_preview, status)
-
-def normalize_video_paths(paths: list[str] | str | None) -> list[str]:
- if not paths:
- return []
- return [paths] if isinstance(paths, str) else list(paths)
-
-
-def first_video_path(paths: list[str] | str | None) -> str | None:
- normalized = normalize_video_paths(paths)
- return normalized[0] if normalized else None
-
-
-def update_video_preview_mode(paths: list[str] | str | None):
- normalized = normalize_video_paths(paths)
- available = bool(normalized)
- single = len(normalized) == 1
- 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=True if available else "hidden", label=input_label),
- gr.update(value=None, visible=True),
- gr.update(visible=single),
- gr.update(visible=single),
- )
-
-def preview_video(
- input_path: list[str] | str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool = False,
- progress=gr.Progress(track_tqdm=False),
-):
- selected = first_video_path(input_path)
- return _process_video(
- selected, nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask,
- nr_color_strength, tone_preservation, face_skin_protection, grain_preservation,
- mask_feather, shimmer_suppression, nr_mask, nr_gpu_mode,
- codec, container, quality, hdr_mode,
- progress, PREVIEW_SECONDS, None
- )
-
-
-def preview_one_frame(
- input_path: list[str] | str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool = False,
- progress=gr.Progress(track_tqdm=False),
- *, output_dir=None, controller=None, ephemeral_preview=False,
-):
- selected = first_video_path(input_path)
- return _process_video(
- selected, nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask,
- nr_color_strength, tone_preservation, face_skin_protection, grain_preservation,
- mask_feather, shimmer_suppression, nr_mask, nr_gpu_mode,
- codec, container, quality, hdr_mode,
- progress, None, 1, output_dir=output_dir, controller=controller,
- ephemeral_preview=ephemeral_preview,
- )
diff --git a/src/neural_rendering/video/processor.py b/src/neural_rendering/video/processor.py
index bac58e9..109dff9 100644
--- a/src/neural_rendering/video/processor.py
+++ b/src/neural_rendering/video/processor.py
@@ -15,7 +15,6 @@ from typing import Callable
import av
import numpy as np
-from av.codec.hwaccel import HWAccel
from ...core import app_log, ffmpeg
from ...core.gpu_selection import resolve_runtime_ai_gpu
@@ -84,10 +83,10 @@ def convert_video(
# Compat previews use the forced H.264 SDR 8-bit path; user-encoded previews
# (Preview Encoding Auto-playable / Disabled) preserve the HDR choice.
compat_preview = is_preview and bool(getattr(options, "preview_compat", True))
- # Processing-engine selection is codec-driven. Keep the legacy option in
- # the data model for preset/API compatibility, but never let an old saved
- # value override the automatic NVENC/CPU routing decision.
- options.nr_gpu_mode = automatic_gpu_mode(options.codec)
+ # Processing-engine selection is codec-driven: NVENC encoders take the
+ # CUDA transport, CPU codecs take the host-memory path. There is no
+ # user-facing mode switch.
+ cuda_path = automatic_gpu_mode(options.codec)
hdr_requested = bool(options.preserve_hdr)
if compat_preview:
hdr_requested = False
@@ -104,7 +103,7 @@ def convert_video(
with job_context as controller:
assert controller is not None
- if options.nr_gpu_mode:
+ if cuda_path:
from .cuda_pipeline import convert_video_cuda_nvenc
return convert_video_cuda_nvenc(
@@ -126,13 +125,8 @@ def convert_video(
try:
v = float(value)
v = 0.0 if v < 0 else (1.0 if v > 1 else v)
- elapsed = time.perf_counter() - started
- if 0.01 < v < 0.99 and elapsed > 0.5:
- eta = elapsed * (1 - v) / max(v, 1e-6)
- desc = f"{desc} - Time Remaining: {eta:.1f}s"
- else:
- v = float(value) if isinstance(value, (int, float)) else v
- # Use positional `desc` so it works for both gr.Progress(desc=) and report_item(message)
+ # Status bar shows only the main status; no ETA suffix.
+ # Native Qt progress callback: progress(value, message).
progress(v, desc)
except Exception:
try:
@@ -237,7 +231,8 @@ def convert_video(
)
output_file = OutputFile(output)
temp_video = job_dir / (f"processed-video{extension}" if preview_frames is not None else "processed-video.mkv")
- native = resolve_native_settings(options)
+ # Host-memory path (CPU codec): stage explicitly, never CUDA.
+ native = resolve_native_settings(options, gpu_mode=False)
metadata_diagnostics: dict = {}
render_note = prepare_render_note(options, metadata_diagnostics)
video_duration = float(metadata.get("video_stream_duration") or 0.0)
@@ -260,7 +255,7 @@ def convert_video(
if preview_seconds is not None
else (video_duration if video_duration > 0.0 else None)
)
- _report_progress(0.01, f"Starting feature 18 on {gpu['display_name']}")
+ _report_progress(0.01, "Starting feature 18")
encoder_setup: list[tuple] = []
encoding_stage_started = time.perf_counter()
@@ -269,11 +264,9 @@ def convert_video(
nonlocal video_gpu
encoder_started = time.perf_counter()
try:
- # GPU ON co-locates NVENC with feature 18 on the AI GPU.
- # GPU OFF retains the separate Video Processing selection.
- encoder_gpu_uuid = (
- str(gpu["uuid"]) if options.nr_gpu_mode else options.video_gpu_uuid
- )
+ # The host-memory path retains the separate Video
+ # Processing GPU selection for the CPU encoder stage.
+ encoder_gpu_uuid = options.video_gpu_uuid
video_gpu = ffmpeg.resolve_video_gpu(
prepared_runtime.gpus,
encoder_gpu_uuid,
@@ -316,19 +309,8 @@ def convert_video(
encoder_setup_thread.start()
preopened_decoder = None
# Final-residual stabilization needs the original RGBA frame after
- # composition. Keep decode on the host for this non-NVENC path;
+ # composition. Decode stays on the host for this non-NVENC path;
# feature 18 and optical flow still execute on the selected GPU.
- if options.nr_gpu_mode and float(options.shimmer_suppression) <= 0.0:
- # FFmpeg's CUDA hwdevice must be created before NGX retains the
- # CUDA primary context on affected Windows driver versions.
- decode_device = HWAccel(
- "cuda",
- device=str(int(gpu.get("cuda_ordinal", gpu.get("index", 0)))),
- allow_software_fallback=True,
- options={"primary_ctx": "1"},
- is_hw_owned=True,
- )
- preopened_decoder = av.open(str(source), hwaccel=decode_device)
session_started = time.perf_counter()
session = DLSSFrameSession(
input_width=input_width,
@@ -365,8 +347,7 @@ def convert_video(
maximum_height = session.maximum_height
_report_progress(
0.03,
- f"DLSS {mode['name']}: {render_width}×{render_height} → "
- f"{output_width}×{output_height}",
+ "Preparing video rendering",
)
(
@@ -644,7 +625,7 @@ def convert_video(
if now - last_progress_update >= 0.1:
_report_progress(
0.04 + 0.84 * min(1.0, delivered / estimated_frames),
- f"DLSS 5 frame {delivered} (estimated {estimated_frames})",
+ "Rendering video frames",
)
last_progress_update = now
diff --git a/src/neural_rendering/video/ui.py b/src/neural_rendering/video/ui.py
deleted file mode 100644
index 15dd809..0000000
--- a/src/neural_rendering/video/ui.py
+++ /dev/null
@@ -1,400 +0,0 @@
-from __future__ import annotations
-
-import traceback
-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, build_save_controls,
-)
-from ...core.ffmpeg import container_for_codec, hdr_mode_supported
-from ...core.ffmpeg.preview import normalize_preview_encoding, resolve_final_preview
-from ...core.naming import RENAME_MODES
-from ...core.runtime import NR_STYLES, UPSCALING_MODES
-from ...settings.models import (
- AUTOMATIC_MASK_CHOICES, CODEC_CHOICES, CONTAINER_CHOICES, QUALITY_CHOICES, UISettings,
- automatic_mask_choice, coerce_hdr_mode, parse_automatic_mask,
-)
-from ...settings.storage import current_preview_encoding, processing_gpu_settings
-from .batch import convert_videos
-from .models import ConversionOptions
-from .preview import (
- _process_video, normalize_video_paths, preview_one_frame, preview_video, update_video_preview_mode,
-)
-from ..composition_ui import CompositionWidgets, build_composition_sliders, build_composition_widgets
-
-
-def hdr_mode_update(codec: str):
- allowed = hdr_mode_supported(codec)
- if not allowed:
- return gr.update(value=False, interactive=False)
- return gr.update(interactive=True)
-
-
-def rename_suffix_update(mode: str):
- return gr.update(interactive=mode == "Custom")
-
-
-UPSCALING_CHOICES = tuple((mode["label"], factor) for factor, mode in UPSCALING_MODES.items())
-
-
-def build_neural_controls(settings: UISettings):
- nr_style = gr.Radio(
- list(NR_STYLES), value=settings.nr_style, label="NR Style",
- )
- upscaling_factor = gr.Dropdown(
- choices=list(UPSCALING_CHOICES), value=settings.upscaling_factor,
- label="Scale",
- )
- # Each control is created directly in the parent Column (no gr.Row), so
- # every slider spans the full width in one vertical stack. Creation order
- # sets the visual order; the returned list keeps the canonical positional
- # order consumed by render/persist/settings-mirror code.
- nr_intensity = gr.Slider(
- 0.0, 2.0, value=settings.nr_intensity, step=0.05, precision=2,
- label="NR Intensity", buttons=["reset"],
- )
- nr_passes = gr.Slider(
- 1, 4, value=settings.nr_passes, step=1, precision=0,
- label="NR Passes", buttons=["reset"],
- )
- local_tone_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_tone_strength, step=0.05, precision=2,
- label="Local Tone Strength", buttons=["reset"]
- )
- local_structure_strength = gr.Slider(
- 0.0, 2.0, value=settings.local_structure_strength, step=0.05, precision=2,
- label="Local Structure Strength", buttons=["reset"],
- )
- skin_structure_strength = gr.Slider(
- -1.0, 2.0, value=settings.skin_structure_strength, step=0.05, precision=2,
- label="Skin Structure Strength",
- buttons=["reset"],
- )
- composition = build_composition_sliders(settings)
- shimmer_suppression = gr.Slider(
- 0.0, 1.0, value=settings.shimmer_suppression, step=0.05, precision=2,
- label="Shimmer Suppression", buttons=["reset"],
- )
- automatic_mask = gr.Radio(
- choices=AUTOMATIC_MASK_CHOICES,
- value=automatic_mask_choice(settings.automatic_mask),
- label="Automatic Mask",
- )
- controls = [
- nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask
- ] + composition
- return [*controls, shimmer_suppression]
-
-
-def render_video(
- input_path: str,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool = False,
- progress=gr.Progress(track_tqdm=False),
-):
- return _process_video(
- input_path, nr_style, nr_intensity, nr_passes, local_tone_strength, local_structure_strength,
- skin_structure_strength, upscaling_factor, automatic_mask,
- nr_color_strength, tone_preservation, face_skin_protection, grain_preservation,
- mask_feather, shimmer_suppression, nr_mask, nr_gpu_mode,
- codec, container, quality, hdr_mode,
- progress, None, None
- )
-
-def render_video_batch(
- input_paths: list[str] | str | None,
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- nr_mask: object | None,
- nr_gpu_mode: bool,
- codec: str,
- container: str,
- quality: str,
- hdr_mode: bool,
- rename_mode: str,
- 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]:
- paths = normalize_video_paths(input_paths)
- if not paths:
- raise gr.Error("Choose at least one video first.")
- effective_hdr = coerce_hdr_mode(codec, hdr_mode)
- options = ConversionOptions(
- ai_gpu_uuid=processing_gpu_settings()[0],
- video_gpu_uuid=processing_gpu_settings()[1],
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- local_tone_strength=local_tone_strength,
- local_structure_strength=local_structure_strength,
- skin_structure_strength=skin_structure_strength,
- automatic_mask=parse_automatic_mask(automatic_mask),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- shimmer_suppression=float(shimmer_suppression),
- mask_feather=int(mask_feather),
- nr_mask=nr_mask,
- nr_gpu_mode=nr_gpu_mode,
- upscaling_factor=upscaling_factor,
- codec=codec,
- container=container,
- quality=quality,
- preserve_hdr=effective_hdr,
- rename_mode=rename_mode,
- custom_suffix=custom_suffix,
- )
-
- def report(value: float, message: str) -> None:
- progress(value, desc=message)
-
- try:
- result = convert_videos(
- paths, options, progress=report, output_dir=output_dir, controller=controller,
- on_item_update=on_item_update, create_archive=False,
- )
- except Exception as exc:
- traceback.print_exc()
- if on_item_update is not None:
- raise
- 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:
- conversion = item.result
- details = (
- f"{conversion.frames} frames in {conversion.elapsed_seconds:.1f}s; "
- f"Neural {conversion.render_width}×{conversion.render_height}; "
- f"{conversion.resize_method}, {conversion.memory_path}; "
- f"report: {conversion.report_path}"
- )
- ordered_rows.append(
- (
- item.index,
- [
- Path(item.input_path).name,
- "Complete",
- Path(conversion.output_path).name,
- details,
- ],
- )
- )
- for item in result.failures:
- state = "Skipped" if item.error == "Cancelled before rendering." else (
- "Cancelled" if item.cancelled else "Failed"
- )
- ordered_rows.append(
- (item.index, [Path(item.input_path).name, state, "", item.error])
- )
- rows = [row for _index, row in sorted(ordered_rows, key=lambda entry: entry[0])]
- try:
- preview_mode = normalize_preview_encoding(current_preview_encoding())
- except Exception:
- preview_mode = "Auto"
- output_preview = None
- used_derivative = False
- if not direct_disk and len(paths) == 1 and result.successes and not result.cancelled:
- candidate = result.successes[0].result.output_path
- output_preview, used_derivative = resolve_final_preview(
- candidate, preview_mode, controller=controller, bounded_proxy=True
- )
- failed_count = sum(not item.cancelled for item in result.failures)
- cancelled_count = sum(
- item.cancelled and item.error != "Cancelled before rendering."
- for item in result.failures
- )
- skipped_count = sum(
- item.error == "Cancelled before rendering." for item in result.failures
- )
- state = "Cancelled" if result.cancelled else "Complete"
- status = (
- f"{state}: {len(result.successes)} completed, {failed_count} failed, "
- f"{cancelled_count} cancelled, {skipped_count} skipped. "
- f"Batch manifest: {result.manifest_path}"
- )
- if result.failures:
- status += f"\nFirst error: {result.failures[0].error}"
- if used_derivative:
- status += "\nA short H.264 browser proxy was created; the complete original output is unchanged."
- files = [item.result.output_path for item in result.successes]
- return gr.update(value=output_preview, visible=not direct_disk), files, rows, status
-
-@dataclass(slots=True)
-class VideoTab:
- sources: object
- input_preview: object
- input_actions: object
- select_source: object
- clear_source: object
- neural: list[object]
- composition: CompositionWidgets
- mask_state: object
- gpu_mode: object
- quality: object
- codec: object
- container: object
- rename_mode: object
- custom_suffix: object
- hdr_mode: object
- preview_frame: object
- preview: object
- render: object
- stop: object
- reset: object
- output_video: object
- save_download: object
- zip_button: object
- zip_download: object
- status: object
- results: object
- input_path: object = None
- output_path: object = None
- job_state: object = None
- refresh_realtime_preview_after: object = None
-
- @property
- def render_inputs(self) -> list[object]:
- return [
- self.sources, *self.neural, self.mask_state, self.gpu_mode, self.codec, self.container,
- self.quality, self.hdr_mode, self.rename_mode, self.custom_suffix,
- ]
-
- @property
- def preview_inputs(self) -> list[object]:
- return [
- self.sources, *self.neural, self.mask_state, self.gpu_mode, self.codec, self.container,
- self.quality, self.hdr_mode,
- ]
-
- @property
- def settings_inputs(self) -> list[object]:
- return [
- *self.neural, self.codec, self.container, self.quality,
- self.hdr_mode, self.rename_mode, self.custom_suffix,
- ]
-
-
-def build_video_tab(settings: UISettings, gpu_mode_state: object, mask_state: object) -> VideoTab:
- with gr.Row():
- with gr.Column(scale=3):
- sources = gr.File(
- label="Input video(s)", file_count="multiple", file_types=["video"],
- type="filepath", allow_reordering=True, elem_id="video-upload-list",
- elem_classes=["media-upload-surface"],
- )
- input_preview = gr.Video(label="Input video preview", interactive=False, visible="hidden")
- 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")
- with gr.Row():
- render = gr.Button("Render video(s)", variant="primary")
- stop = gr.Button("Stop", variant="stop")
- preview_frame = gr.Button("Preview 1 frame", visible=False)
- preview = gr.Button("Preview 3 sec", visible=False)
- reset = gr.Button("Reset settings")
- with gr.Column(elem_classes=["neural-controls-unified"]):
- neural = build_neural_controls(settings)
- composition = build_composition_widgets()
- input_path, output_path = build_path_controls()
- quality = gr.Radio(
- QUALITY_CHOICES, value=settings.quality, label="Encoding quality",
- )
- with gr.Row():
- codec = gr.Dropdown(
- CODEC_CHOICES, value=settings.codec, label="Video codec",
- )
- container = gr.Dropdown(
- CONTAINER_CHOICES, value=container_for_codec(settings.codec),
- label="Container (automatic)", interactive=False,
- )
- with gr.Row():
- rename_mode = gr.Radio(
- RENAME_MODES, value=settings.video_rename_mode, label="Rename",
- )
- custom_suffix = gr.Textbox(
- value=settings.video_custom_suffix, label="Custom suffix", placeholder="_Neural_Rendering",
- interactive=settings.video_rename_mode == "Custom",
- )
- hdr_mode = gr.Checkbox(
- value=settings.hdr_mode and hdr_mode_supported(settings.codec),
- label="HDR Mode",
- interactive=hdr_mode_supported(settings.codec),
- )
- with gr.Column(scale=3):
- output_video = gr.Video(
- label="Output video", interactive=False, visible=True, height=520,
- )
- save_download, zip_button, zip_download = build_save_controls("video", "nr-video")
- 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 = VideoTab(
- sources, input_preview, input_actions, select_source, clear_source, neural, composition, mask_state, gpu_mode_state, quality, codec, container, rename_mode,
- custom_suffix, hdr_mode, preview_frame, preview, render, stop, reset, output_video,
- save_download, zip_button, zip_download, status, results
- )
- tab.input_path, tab.output_path = input_path, output_path
- bind_video_events(tab)
- return tab
-
-
-def bind_video_events(tab: VideoTab) -> None:
- tab.refresh_realtime_preview_after = bind_batch_ui(
- tab, render_video_batch, kind="video", preview_mode=update_video_preview_mode,
- archive_prefix="DLSS5_VIDEO_BATCH",
- preview_actions=[(tab.preview_frame, preview_one_frame), (tab.preview, preview_video)],
- realtime_preview=preview_one_frame,
- realtime_components=tab.neural,
- )
- tab.rename_mode.change(rename_suffix_update, inputs=tab.rename_mode, outputs=tab.custom_suffix, queue=False)
- tab.codec.change(
- lambda selected: (
- gr.update(value=container_for_codec(selected)),
- hdr_mode_update(selected),
- ),
- inputs=tab.codec, outputs=[tab.container, tab.hdr_mode], queue=False,
- )
diff --git a/src/settings/models.py b/src/settings/models.py
index 04b42e6..bf33202 100644
--- a/src/settings/models.py
+++ b/src/settings/models.py
@@ -1,11 +1,12 @@
from __future__ import annotations
from dataclasses import dataclass, replace
+from types import SimpleNamespace
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 ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES, PREVIEW_LENGTH_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
@@ -57,9 +58,27 @@ class UISettings:
# remains reset-based and does not consume this value.
shimmer_suppression: float = 0.70
mask_feather: int = 0
- # Validated Gradio upload identity; intentionally omitted from config/presets.
+ # Validated native file-picker identity; intentionally omitted from config/presets.
nr_mask: object | None = None
upscaling_factor: float = 1.0
+ # Independent Live-tab mirrors of the NR controls above. The Live tab
+ # reads/writes only these, so tuning or resetting Live never touches
+ # the Neural Rendering tab (and vice versa). nr_mask stays shared:
+ # only the Neural tab manages the custom mask.
+ live_nr_style: str = "Default"
+ live_nr_intensity: float = 1.0
+ live_nr_passes: int = 1
+ live_local_tone_strength: float = 1.0
+ live_local_structure_strength: float = 1.0
+ live_skin_structure_strength: float = -1.0
+ live_nr_color_strength: float = 1.0
+ live_tone_preservation: float = 0.0
+ live_face_skin_protection: float = 0.0
+ live_grain_preservation: float = 0.0
+ live_shimmer_suppression: float = 0.70
+ live_mask_feather: int = 0
+ live_automatic_mask: bool = False
+ live_upscaling_factor: float = 1.0
# Factory default only. Existing saved codec values are loaded unchanged.
codec: str = "H.264 (NVIDIA NVENC)"
container: str = "MP4"
@@ -72,7 +91,6 @@ class UISettings:
image_custom_suffix: str = "_Neural_Rendering"
video_rename_mode: str = "Auto"
video_custom_suffix: str = "_Neural_Rendering"
- nr_gpu_mode: bool = True
frame_interpolation_target_fps: str = "60"
frame_interpolation_engine: str = "Auto"
# Factory default only. Existing saved selections are loaded unchanged.
@@ -80,11 +98,11 @@ class UISettings:
frame_interpolation_container: str = "MP4"
frame_interpolation_quality: str = "Auto (Default)"
frame_interpolation_hdr_mode: bool = False
- frame_interpolation_gpu_mode: bool = True
frame_interpolation_rename_mode: str = "Auto"
frame_interpolation_custom_suffix: str = "_Frame_Interpolation"
+ frame_interpolation_preview_length: str = "3"
preview_encoding: str = "Auto"
- full_size_image_previews: bool = False
+ full_size_image_previews: bool = True
upscale_mode: str = "Image"
upscale_image_vsr_quality: int = 4
upscale_image_size_mode: str = "Scale factor"
@@ -118,7 +136,7 @@ class UISettings:
def component_values(
self,
- ) -> tuple[str, float, int, float, float, float, float, float, float, float, float, int, float, bool, bool, str, str, str]:
+ ) -> tuple[str, float, int, float, float, float, float, float, float, float, float, int, float, bool, str, str, str]:
return (
self.nr_style,
self.nr_intensity,
@@ -134,13 +152,36 @@ class UISettings:
self.mask_feather,
self.upscaling_factor,
self.automatic_mask,
- self.nr_gpu_mode,
self.codec,
self.container,
self.quality,
)
+def live_effect_options(settings: UISettings) -> SimpleNamespace:
+ """Namespace exposing the Live tab's independent NR values under the
+ shared nr_* names consumed by the live pipeline (EffectSettings).
+
+ The custom mask stays shared: only the Neural tab manages it.
+ """
+ return SimpleNamespace(
+ nr_style=settings.live_nr_style,
+ nr_intensity=settings.live_nr_intensity,
+ nr_passes=settings.live_nr_passes,
+ local_tone_strength=settings.live_local_tone_strength,
+ local_structure_strength=settings.live_local_structure_strength,
+ skin_structure_strength=settings.live_skin_structure_strength,
+ nr_color_strength=settings.live_nr_color_strength,
+ tone_preservation=settings.live_tone_preservation,
+ face_skin_protection=settings.live_face_skin_protection,
+ grain_preservation=settings.live_grain_preservation,
+ shimmer_suppression=settings.live_shimmer_suppression,
+ mask_feather=settings.live_mask_feather,
+ nr_mask=settings.nr_mask,
+ automatic_mask=settings.live_automatic_mask,
+ )
+
+
DEFAULT_SETTINGS = UISettings()
@@ -158,21 +199,28 @@ def _validate(settings: UISettings) -> UISettings:
raise ValueError("NR Passes must be an integer from 1 to 4.")
if not 1 <= settings.nr_passes <= 4:
raise ValueError("NR Passes must be between 1 and 4.")
+ if isinstance(settings.live_nr_passes, bool) or not isinstance(settings.live_nr_passes, int):
+ raise ValueError("Live NR Passes must be an integer from 1 to 4.")
+ if not 1 <= settings.live_nr_passes <= 4:
+ raise ValueError("Live NR Passes must be between 1 and 4.")
if isinstance(settings.mask_feather, bool) or not isinstance(settings.mask_feather, int):
raise ValueError("Mask Feather must be an integer from 0 to 128.")
if not 0 <= settings.mask_feather <= 128:
raise ValueError("Mask Feather must be between 0 and 128 pixels.")
+ if isinstance(settings.live_mask_feather, bool) or not isinstance(settings.live_mask_feather, int):
+ raise ValueError("Live Mask Feather must be an integer from 0 to 128.")
+ if not 0 <= settings.live_mask_feather <= 128:
+ raise ValueError("Live Mask Feather must be between 0 and 128 pixels.")
resolve_upscaling_mode(settings.upscaling_factor)
+ resolve_upscaling_mode(settings.live_upscaling_factor)
if not isinstance(settings.automatic_mask, bool):
raise ValueError("Automatic Mask must be a boolean value.")
- if not isinstance(settings.nr_gpu_mode, bool):
- raise ValueError("Neural Rendering GPU mode must be a boolean value.")
+ if not isinstance(settings.live_automatic_mask, bool):
+ raise ValueError("Live 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.")
- if not isinstance(settings.frame_interpolation_gpu_mode, bool):
- raise ValueError("Frame Interpolation GPU mode must be a boolean value.")
if not isinstance(settings.full_size_image_previews, bool):
raise ValueError("Full size quality preview must be a boolean value.")
# Migrate old codec names before validation
@@ -217,6 +265,10 @@ def _validate(settings: UISettings) -> UISettings:
settings.frame_interpolation_quality,
QUALITY_CHOICES,
),
+ "Frame Interpolation preview length": (
+ settings.frame_interpolation_preview_length,
+ PREVIEW_LENGTH_CHOICES,
+ ),
"Preview encoding": (
settings.preview_encoding,
PREVIEW_ENCODING_CHOICES,
diff --git a/src/settings/presets.py b/src/settings/presets.py
index 921f074..b85c909 100644
--- a/src/settings/presets.py
+++ b/src/settings/presets.py
@@ -9,7 +9,7 @@ from dataclasses import asdict, fields, replace
from pathlib import Path
from typing import Any
-from ..core.paths import GRADIO_TEMP
+from ..core.paths import APP_TEMP
from .models import (
DEFAULT_SETTINGS, MAX_PRESET_BYTES, PRESET_FORMAT, PRESET_SCHEMA_VERSION, UISettings, _validate,
)
@@ -66,8 +66,8 @@ def export_settings_preset(name: str, settings: UISettings) -> Path:
"""Write a validated preset to an isolated temporary download directory."""
document = preset_document(name, settings)
filename = preset_filename(document["name"])
- GRADIO_TEMP.mkdir(parents=True, exist_ok=True)
- directory = Path(tempfile.mkdtemp(prefix="dlss5-settings-preset-", dir=GRADIO_TEMP))
+ APP_TEMP.mkdir(parents=True, exist_ok=True)
+ directory = Path(tempfile.mkdtemp(prefix="dlss5-settings-preset-", dir=APP_TEMP))
path = directory / filename
path.write_text(
json.dumps(document, indent=2, ensure_ascii=False) + "\n",
@@ -120,7 +120,7 @@ def import_settings_preset(
if not isinstance(document, dict):
raise ValueError("Preset JSON must contain an object at its top level.")
if document.get("format") != PRESET_FORMAT:
- raise ValueError("This JSON file is not a DLSS 5 Visual Enhancer settings preset.")
+ raise ValueError("This JSON file is not a Visual Enhancer settings preset.")
version = document.get("schema_version")
if isinstance(version, bool) or not isinstance(version, int):
raise ValueError("Preset schema_version must be an integer.")
@@ -143,9 +143,9 @@ def import_settings_preset(
}
if version == 1:
# v1's DLSS model-preset field was never applied by feature 18. Ignore
- # it and default the newly introduced shared GPU staging switch to ON.
+ # it. (The retired GPU staging switch from old presets is filtered by
+ # known_names above; the runtime path is codec-driven now.)
changes.pop("dlss_model_preset", None)
- changes["nr_gpu_mode"] = DEFAULT_SETTINGS.nr_gpu_mode
if version < 3:
changes["nr_color_strength"] = DEFAULT_SETTINGS.nr_color_strength
changes["tone_preservation"] = DEFAULT_SETTINGS.tone_preservation
@@ -157,8 +157,6 @@ def import_settings_preset(
changes["nr_passes"] = DEFAULT_SETTINGS.nr_passes
if version < 6:
changes["shimmer_suppression"] = DEFAULT_SETTINGS.shimmer_suppression
- if version < 7:
- changes["frame_interpolation_gpu_mode"] = DEFAULT_SETTINGS.frame_interpolation_gpu_mode
# NR Preset was removed entirely (non-functional). Old preset files still
# carry it; ignore so imports from previous builds keep working.
# (Unknown keys are already filtered above; this covers any edge case where
@@ -173,3 +171,31 @@ def import_settings_preset(
changes["upscale_vsr_quality"] = DEFAULT_SETTINGS.upscale_vsr_quality
merged = replace(current, **changes)
return name, _validate(merged)
+
+
+def export_settings_preset_to(
+ name: str,
+ settings: UISettings,
+ destination: str | os.PathLike[str],
+) -> Path:
+ """Atomically write a validated preset to a user-selected destination."""
+ document = preset_document(name, settings)
+ target = Path(destination).expanduser()
+ if target.suffix.casefold() != ".json":
+ target = target.with_suffix(".json")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ payload = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
+ fd, temp_name = tempfile.mkstemp(
+ prefix=target.stem + ".", suffix=".tmp", dir=str(target.parent)
+ )
+ temp_path = Path(temp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temp_path, target)
+ except Exception:
+ temp_path.unlink(missing_ok=True)
+ raise
+ return target.resolve()
diff --git a/src/settings/storage.py b/src/settings/storage.py
index aab7e8a..c392a26 100644
--- a/src/settings/storage.py
+++ b/src/settings/storage.py
@@ -11,7 +11,7 @@ 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 NR_STYLES, resolve_upscaling_mode
-from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES
+from ..frame_interpolation.models import ENGINE_CHOICES, FPS_CHOICES, PREVIEW_LENGTH_CHOICES
from .migration import _migrate_codec
from .models import (
CODEC_CHOICES, CONFIG_SECTION, CONTAINER_CHOICES, DEFAULT_SETTINGS, IMAGE_FORMAT_CHOICES,
@@ -180,7 +180,6 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:
"mask_feather", 0, 128, DEFAULT_SETTINGS.mask_feather
)),
automatic_mask=boolean("automatic_mask", DEFAULT_SETTINGS.automatic_mask),
- nr_gpu_mode=boolean("nr_gpu_mode", DEFAULT_SETTINGS.nr_gpu_mode),
upscaling_factor=upscaling_factor(),
codec=codec_choice("codec", DEFAULT_SETTINGS.codec),
container=choice("container", CONTAINER_CHOICES, DEFAULT_SETTINGS.container),
@@ -215,8 +214,11 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:
DEFAULT_SETTINGS.frame_interpolation_quality,
),
frame_interpolation_hdr_mode=fi_hdr_mode_value(),
- frame_interpolation_gpu_mode=boolean(
- "frame_interpolation_gpu_mode", DEFAULT_SETTINGS.frame_interpolation_gpu_mode),
+ frame_interpolation_preview_length=choice(
+ "frame_interpolation_preview_length",
+ PREVIEW_LENGTH_CHOICES,
+ DEFAULT_SETTINGS.frame_interpolation_preview_length,
+ ),
frame_interpolation_rename_mode=frame_interpolation_rename_mode,
frame_interpolation_custom_suffix=frame_interpolation_custom_suffix,
preview_encoding=choice(
@@ -233,6 +235,50 @@ def load_settings(path: str | os.PathLike[str]) -> UISettings:
DEFAULT_SETTINGS.upscale_mode,
),
)
+ # First-run migration: Live mirrors default to the loaded shared NR
+ # values so previous Live tunings survive the split. Factory defaults
+ # apply only to fresh configs and to per-tab Reset.
+ def live_upscaling_factor() -> float:
+ try:
+ return resolve_upscaling_mode(float(section.get(
+ "live_upscaling_factor", str(settings.upscaling_factor))))[0]
+ except (TypeError, ValueError):
+ return settings.upscaling_factor
+ settings = replace(
+ settings,
+ live_nr_style=choice("live_nr_style", tuple(NR_STYLES), settings.nr_style),
+ live_nr_intensity=number("live_nr_intensity", 0.0, 2.0, settings.nr_intensity),
+ live_nr_passes=integer("live_nr_passes", 1, 4, settings.nr_passes),
+ live_local_tone_strength=number(
+ "live_local_tone_strength", 0.0, 2.0, settings.local_tone_strength
+ ),
+ live_local_structure_strength=number(
+ "live_local_structure_strength", 0.0, 2.0, settings.local_structure_strength
+ ),
+ live_skin_structure_strength=number(
+ "live_skin_structure_strength", -1.0, 2.0, settings.skin_structure_strength
+ ),
+ live_nr_color_strength=number(
+ "live_nr_color_strength", 0.0, 1.0, settings.nr_color_strength
+ ),
+ live_tone_preservation=number(
+ "live_tone_preservation", 0.0, 1.0, settings.tone_preservation
+ ),
+ live_face_skin_protection=number(
+ "live_face_skin_protection", 0.0, 1.0, settings.face_skin_protection
+ ),
+ live_grain_preservation=number(
+ "live_grain_preservation", 0.0, 1.0, settings.grain_preservation
+ ),
+ live_shimmer_suppression=number(
+ "live_shimmer_suppression", 0.0, 1.0, settings.shimmer_suppression
+ ),
+ live_mask_feather=int(number(
+ "live_mask_feather", 0, 128, settings.mask_feather
+ )),
+ live_automatic_mask=boolean("live_automatic_mask", settings.automatic_mask),
+ live_upscaling_factor=live_upscaling_factor(),
+ )
# 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:
@@ -293,8 +339,21 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:
"shimmer_suppression": f"{settings.shimmer_suppression:.2f}",
"mask_feather": str(settings.mask_feather),
"automatic_mask": str(settings.automatic_mask).lower(),
- "nr_gpu_mode": str(settings.nr_gpu_mode).lower(),
"upscaling_factor": f"{settings.upscaling_factor:g}",
+ "live_nr_style": settings.live_nr_style,
+ "live_nr_intensity": f"{settings.live_nr_intensity:.2f}",
+ "live_nr_passes": str(settings.live_nr_passes),
+ "live_local_tone_strength": f"{settings.live_local_tone_strength:.2f}",
+ "live_local_structure_strength": f"{settings.live_local_structure_strength:.2f}",
+ "live_skin_structure_strength": f"{settings.live_skin_structure_strength:.2f}",
+ "live_nr_color_strength": f"{settings.live_nr_color_strength:.2f}",
+ "live_tone_preservation": f"{settings.live_tone_preservation:.2f}",
+ "live_face_skin_protection": f"{settings.live_face_skin_protection:.2f}",
+ "live_grain_preservation": f"{settings.live_grain_preservation:.2f}",
+ "live_shimmer_suppression": f"{settings.live_shimmer_suppression:.2f}",
+ "live_mask_feather": str(settings.live_mask_feather),
+ "live_automatic_mask": str(settings.live_automatic_mask).lower(),
+ "live_upscaling_factor": f"{settings.live_upscaling_factor:g}",
"codec": settings.codec,
"container": settings.container,
"quality": settings.quality,
@@ -311,7 +370,7 @@ def save_settings(path: str | os.PathLike[str], settings: UISettings) -> None:
"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_gpu_mode": str(settings.frame_interpolation_gpu_mode).lower(),
+ "frame_interpolation_preview_length": settings.frame_interpolation_preview_length,
"frame_interpolation_rename_mode": settings.frame_interpolation_rename_mode,
"frame_interpolation_custom_suffix": settings.frame_interpolation_custom_suffix,
"preview_encoding": settings.preview_encoding,
diff --git a/src/settings/ui.py b/src/settings/ui.py
deleted file mode 100644
index a777f13..0000000
--- a/src/settings/ui.py
+++ /dev/null
@@ -1,793 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass, replace
-
-import gradio as gr
-
-from ..core.ffmpeg import container_for_codec, 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 .models import (
- 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
-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())
-_SKIN_STRUCTURE_INDEX = 5
-_AUTOMATIC_MASK_INDEX = 7
-_NR_COLOR_INDEX = 8
-_TONE_PRESERVATION_INDEX = 9
-def automatic_mask_for_skin_input(
- skin_structure_strength: float, automatic_mask: str,
-) -> str:
- """Make an explicit Skin adjustment effective without overriding later Mask Off."""
- try:
- skin = float(skin_structure_strength)
- except (TypeError, ValueError) as exc:
- raise gr.Error("Skin Structure Strength must be between -1 and 2.") from exc
- if not -1.0 <= skin <= 2.0:
- raise gr.Error("Skin Structure Strength must be between -1 and 2.")
- return "On" if skin > -1.0 else automatic_mask
-
-
-def _persist_skin_input(persist, values: tuple) -> tuple:
- effective = list(values)
- effective[_AUTOMATIC_MASK_INDEX] = automatic_mask_for_skin_input(
- effective[_SKIN_STRUCTURE_INDEX], effective[_AUTOMATIC_MASK_INDEX]
- )
- mirrored = persist(*effective)
- return (effective[_AUTOMATIC_MASK_INDEX], *mirrored)
-
-
-def _neural_values(
- settings: UISettings,
-) -> tuple[str, float, int, float, float, float, float, str, float, float, float, float, int]:
- return (
- settings.nr_style,
- settings.nr_intensity,
- settings.nr_passes,
- settings.local_tone_strength,
- settings.local_structure_strength,
- settings.skin_structure_strength,
- settings.upscaling_factor,
- automatic_mask_choice(settings.automatic_mask),
- settings.nr_color_strength,
- settings.tone_preservation,
- settings.face_skin_protection,
- settings.grain_preservation,
- settings.mask_feather,
- )
-
-
-def _mirrored_dlss_values(settings: UISettings) -> tuple:
- """Image controls followed by temporal Video/Live controls."""
- shared = _neural_values(settings)
- temporal = (*shared, settings.shimmer_suppression)
- return (*shared, *temporal)
-
-
-def _video_live_values(settings: UISettings) -> tuple:
- return (*_neural_values(settings), settings.shimmer_suppression)
-
-
-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_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- 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_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- 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),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- mask_feather=int(mask_feather),
- 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)
- temporal = _video_live_values(settings)
- return (*temporal, *temporal)
-
-
-def persist_video_settings(
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
- 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)
- container = container_for_codec(codec)
- coerced_hdr = coerce_hdr_mode(codec, hdr_mode)
- settings = replace(
- current,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- 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),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- mask_feather=int(mask_feather),
- shimmer_suppression=float(shimmer_suppression),
- 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 (*_neural_values(settings), *_video_live_values(settings))
-
-
-def persist_live_settings(
- nr_style: str,
- nr_intensity: float,
- nr_passes: float,
- local_tone_strength: float,
- local_structure_strength: float,
- skin_structure_strength: float,
- upscaling_factor: float,
- automatic_mask: str,
- nr_color_strength: float,
- tone_preservation: float,
- face_skin_protection: float,
- grain_preservation: float,
- mask_feather: float,
- shimmer_suppression: float,
-) -> tuple:
- with _CONFIG_LOCK:
- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- settings = replace(
- current,
- nr_style=nr_style,
- nr_intensity=nr_intensity,
- nr_passes=int(nr_passes),
- 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),
- nr_color_strength=float(nr_color_strength),
- tone_preservation=float(tone_preservation),
- face_skin_protection=float(face_skin_protection),
- grain_preservation=float(grain_preservation),
- mask_feather=int(mask_feather),
- shimmer_suppression=float(shimmer_suppression),
- )
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- SETTINGS_STATE.current = settings
- _notify_live_effects(settings)
- return (*_neural_values(settings), *_video_live_values(settings))
-
-
-def persist_image_skin_settings(*values) -> tuple:
- return _persist_skin_input(persist_image_settings, values)
-
-
-def persist_video_skin_settings(*values) -> tuple:
- return _persist_skin_input(persist_video_settings, values)
-
-
-def persist_live_skin_settings(*values) -> tuple:
- return _persist_skin_input(persist_live_settings, values)
-
-
-def persist_nr_mask(selection: object | None) -> None:
- """Update session-only mask state without writing its temporary path to disk."""
- from ..core.nr_composition import mask_selection
-
- selected = mask_selection(selection)
- with _CONFIG_LOCK:
- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- settings = replace(current, nr_mask=selected)
- SETTINGS_STATE.current = settings
- _notify_live_effects(settings)
-
-
-def apply_detail_only_settings() -> tuple:
- """Apply the editable Detail-Only preset to every mirrored interface."""
- with _CONFIG_LOCK:
- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- settings = replace(current, nr_color_strength=0.0, tone_preservation=1.0)
- if settings != current:
- save_settings(CONFIG_PATH, settings)
- SETTINGS_STATE.current = settings
- _notify_live_effects(settings)
- shared = _neural_values(settings)
- temporal = _video_live_values(settings)
- return (*shared, *temporal, *temporal)
-
-
-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)
- container = container_for_codec(codec)
- 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))
- chosen["container"] = container_for_codec(chosen["codec"])
- 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
-
-
-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)
- 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 = _neural_values(settings)
- temporal = _video_live_values(settings)
- return (
- *shared,
- *temporal,
- 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,
- container_for_codec(settings.codec),
- 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,
- container_for_codec(settings.frame_interpolation_codec),
- 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.full_size_image_previews,
- *temporal,
- settings.upscale_mode,
- *(container_for_codec(settings.upscale_codec) if name == "container"
- else 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"
- # Old presets may contain manual path flags. They are retained by the
- # storage schema for compatibility but normalized so they cannot affect
- # the now-automatic runtime choice.
- return replace(
- settings,
- ai_gpu_uuid=ai_uuid,
- video_gpu_uuid=video_uuid,
- nr_gpu_mode=True,
- frame_interpolation_gpu_mode=True,
- container=container_for_codec(settings.codec),
- frame_interpolation_container=container_for_codec(settings.frame_interpolation_codec),
- upscale_container=container_for_codec(settings.upscale_codec),
- ), " ".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_full_size_image_previews(enabled: bool) -> None:
- if not isinstance(enabled, bool):
- raise gr.Error("Full size quality preview must be enabled or disabled.")
- with _CONFIG_LOCK:
- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- settings = replace(current, full_size_image_previews=enabled)
- 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:
- current = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- # Custom NR Mask is session-scoped, so resetting persisted controls must
- # not silently detach the mask that remains visible in all three tabs.
- settings = replace(DEFAULT_SETTINGS, nr_mask=current.nr_mask)
- save_settings(CONFIG_PATH, settings)
- SETTINGS_STATE.current = settings
- _notify_live_effects(settings)
- message = "All Neural Rendering, Upscale, and Frame Interpolation settings were reset to defaults."
- return (
- *_settings_component_values(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: object
- video_gpu_selector: object
- preview_encoding_selector: object
- full_size_image_previews: object
- preset_name: object
- preset_export: object
- preset_import: object
- preset_status: object
-
-
-def initialize_settings(prepared) -> tuple[UISettings, str, list[tuple[str, str]], list[tuple[str, str]]]:
- settings = SETTINGS_STATE.current or load_settings(CONFIG_PATH)
- normalized, warning = _normalize_gpu_settings(settings, prepared)
- if normalized != settings:
- save_settings(CONFIG_PATH, normalized)
- SETTINGS_STATE.current = normalized
- ai_choices, video_choices = _gpu_choices(prepared)
- return normalized, warning, ai_choices, video_choices
-
-
-def current_settings() -> UISettings:
- with _CONFIG_LOCK:
- return SETTINGS_STATE.current or load_settings(CONFIG_PATH)
-
-
-def build_settings_tab(
- settings: UISettings,
- ai_gpu_choices: list[tuple[str, str]],
- video_gpu_choices: list[tuple[str, str]],
-) -> SettingsTab:
- gr.Markdown("## GPU Selection")
- with gr.Row():
- ai_gpu_selector = gr.Dropdown(
- choices=ai_gpu_choices,
- value=settings.ai_gpu_uuid,
- label="AI Processing GPU",
- )
- video_gpu_selector = gr.Dropdown(
- choices=video_gpu_choices,
- value=settings.video_gpu_uuid,
- label="Video Processing GPU",
- )
- gr.Markdown("## Preview Encoding")
- preview_encoding_selector = gr.Radio(
- choices=list(PREVIEW_ENCODING_CHOICES),
- value=normalize_preview_encoding(settings.preview_encoding),
- label="Preview Encoding",
- show_label=False,
- )
- gr.Markdown("## Image Preview Quality")
- full_size_image_previews = gr.Checkbox(
- value=settings.full_size_image_previews,
- label="Full size quality preview",
- )
- gr.Markdown("## Settings Presets")
- preset_name = gr.Textbox(
- label="Preset name",
- placeholder="Preset 13",
- )
- 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, full_size_image_previews,
- preset_name, preset_export, preset_import, preset_status
- )
-
-
-
-def settings_component_outputs(image_tab, video_tab, frame_tab, settings_tab, live_tab, upscale_tab) -> list[object]:
- return [
- *image_tab.neural,
- *video_tab.neural,
- 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.full_size_image_previews,
- *live_tab.neural,
- 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]
- image_mirror = [*image_tab.neural]
- live_mirror = [*live_tab.neural]
- for component in image_tab.settings_inputs:
- if component is image_tab.neural[_SKIN_STRUCTURE_INDEX]:
- continue
- component.input(
- persist_image_settings,
- inputs=image_tab.settings_inputs,
- outputs=[*video_mirror, *live_mirror],
- queue=False,
- )
- for component in video_tab.settings_inputs:
- if component is video_tab.neural[_SKIN_STRUCTURE_INDEX]:
- continue
- component.input(
- persist_video_settings,
- inputs=video_tab.settings_inputs,
- outputs=[*image_mirror, *live_mirror],
- queue=False,
- )
- for component in live_tab.settings_inputs:
- if component is live_tab.neural[_SKIN_STRUCTURE_INDEX]:
- continue
- component.input(
- persist_live_settings,
- inputs=live_tab.settings_inputs,
- outputs=[*image_mirror, *video_mirror],
- queue=False,
- )
- image_tab.neural[_SKIN_STRUCTURE_INDEX].input(
- persist_image_skin_settings,
- inputs=image_tab.settings_inputs,
- outputs=[image_tab.neural[_AUTOMATIC_MASK_INDEX], *video_mirror, *live_mirror],
- queue=False,
- )
- video_tab.neural[_SKIN_STRUCTURE_INDEX].input(
- persist_video_skin_settings,
- inputs=video_tab.settings_inputs,
- outputs=[video_tab.neural[_AUTOMATIC_MASK_INDEX], *image_mirror, *live_mirror],
- queue=False,
- )
- live_tab.neural[_SKIN_STRUCTURE_INDEX].input(
- persist_live_skin_settings,
- inputs=live_tab.settings_inputs,
- outputs=[live_tab.neural[_AUTOMATIC_MASK_INDEX], *image_mirror, *video_mirror],
- queue=False,
- )
- detail_outputs = [*image_tab.neural, *video_tab.neural, *live_tab.neural]
- for button in (
- image_tab.composition.detail_only,
- video_tab.composition.detail_only,
- live_tab.composition.detail_only,
- ):
- button.click(
- apply_detail_only_settings,
- outputs=detail_outputs,
- queue=False,
- show_progress="hidden",
- )
- 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",
- )
- 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,
- )
- settings_tab.full_size_image_previews.input(
- persist_full_size_image_previews,
- inputs=settings_tab.full_size_image_previews,
- queue=False,
- )
- reset_outputs = [*outputs, image_tab.status, video_tab.status, frame_tab.status, upscale_tab.video.status, upscale_tab.image.status]
- image_reset = image_tab.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
- video_reset = video_tab.reset.click(reset_saved_settings, outputs=reset_outputs, queue=False)
- # Reset writes every shared Neural Rendering control programmatically, which
- # does not emit the direct input/release events used by automatic previews.
- # Refresh both workflows so a prepared preview in the hidden mode cannot
- # remain rendered with the pre-reset settings.
- for reset_event in (image_reset, video_reset):
- image_tab.refresh_realtime_preview_after(reset_event)
- video_tab.refresh_realtime_preview_after(reset_event)
- 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/image/processor.py b/src/upscale/image/processor.py
index 92086af..8cab2d8 100644
--- a/src/upscale/image/processor.py
+++ b/src/upscale/image/processor.py
@@ -69,7 +69,7 @@ def preview_upscale_image(input_path, options=None, progress=None, *, controller
update(.12, "Checking RTX Video capabilities")
caps = probe_capabilities(options.ai_gpu_uuid, controller=controller)
- update(.24, f"RTX VSR: {width}×{height} → {ow}×{oh}")
+ update(.24, "Processing with RTX VSR")
with RTXVideoSession(
width, height, ow, oh, options.native_options(), 1, caps, controller,
image_srgb=True,
@@ -140,7 +140,7 @@ def _process(source, options, progress, output_dir, controller, generate_preview
source, IMAGE_EXTENSIONS[options.output_format], options.rename_mode, options.custom_suffix,
f"{source.stem}_RTXIMAGE_{stamp}")
destination_file = OutputFile(output)
- update(.15, f"RTX VSR: {width}×{height} → {ow}×{oh}")
+ update(.15, "Processing with RTX VSR")
key = (width, height, ow, oh, int(options.vsr_quality), str(caps.gpu.get("uuid", "")))
if session_cache is None:
session_context = RTXVideoSession(
diff --git a/src/upscale/image/ui.py b/src/upscale/image/ui.py
deleted file mode 100644
index a3bf33c..0000000
--- a/src/upscale/image/ui.py
+++ /dev/null
@@ -1,203 +0,0 @@
-from __future__ import annotations
-
-from pathlib import Path
-from types import SimpleNamespace
-
-import gradio as gr
-from PIL import Image
-
-from ...core.batch_ui import (BATCH_HEADERS, bind_batch_ui, build_media_clear_button,
- build_media_select_button, build_path_controls, build_save_controls)
-from ...core.disk_paths import resolve_inputs
-from ...core.naming import RENAME_MODES
-from ...neural_rendering.image.decoder import decode_image, full_size_image_preview_path
-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 full_size_image_previews_enabled, processing_gpu_settings
-from .batch import upscale_images
-from .processor import preview_upscale_image
-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):
- full_size = full_size_image_previews_enabled()
- 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 and not full_size,
- )
- gallery = []
- if not direct_disk:
- for item in result.successes:
- preview = None
- if full_size:
- try:
- preview = full_size_image_preview_path(item.output_path)
- except Exception:
- preview = None
- else:
- preview = take_image_preview(item.output_path)
- if preview is None:
- try:
- with Image.open(item.output_path) as output:
- preview = output.convert("RGBA")
- preview.thumbnail((1200, 900), Image.Resampling.BILINEAR)
- preview = preview.copy()
- except Exception:
- continue
- gallery.append((preview, Path(item.output_path).name))
- files = [item.output_path for item in result.successes]
- return gallery, files, [], str(result.manifest_path)
-
-
-def preview_image(paths, *values, progress=gr.Progress(track_tqdm=False)):
- selected = [paths] if isinstance(paths, str) else list(paths or [])
- if len(selected) != 1:
- raise gr.Error("Choose exactly one image to preview.")
- full_size = full_size_image_previews_enabled()
- image, status = preview_upscale_image(
- selected[0], options_from_values(values),
- progress=lambda value, message: progress(value, desc=message),
- full_size_preview=full_size,
- )
- return (
- gr.update(value=[(image, f"Preview — {Path(selected[0]).name}")], visible=True),
- status,
- )
-
-
-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="hidden", 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")
- with gr.Row():
- render = gr.Button("Upscale image(s)", variant="primary")
- stop = gr.Button("Stop", variant="stop")
- preview = gr.Button("Preview", visible=False)
- reset = gr.Button("Reset settings")
- with gr.Column(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")
- dimensions = gr.Markdown(visible=False, elem_id="upscale-image-dimensions")
- input_path, output_path = build_path_controls()
- 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")
- 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.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",
- )
- save_download, zip_button, zip_download = build_save_controls("image", "upscale-image")
- 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, preview=preview, reset=reset, output_gallery=output_gallery,
- save_download=save_download, zip_button=zip_button, 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]
- tab.preview_inputs = list(tab.render_inputs)
- bind_batch_ui(
- tab, render_image_batch, kind="image", preview_mode=preview_input_images,
- archive_prefix="RTXVIDEO_IMAGE_BATCH",
- preview_actions=[(tab.preview, preview_image)],
- )
- 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 tab
diff --git a/src/upscale/ui.py b/src/upscale/ui.py
deleted file mode 100644
index 1420efb..0000000
--- a/src/upscale/ui.py
+++ /dev/null
@@ -1,77 +0,0 @@
-from dataclasses import dataclass
-
-import gradio as gr
-
-from ..core.batch_ui import bind_input_surface_reactivation
-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 _stable_visible(show: bool):
- return True if show else "hidden"
-
-
-def mode_visibility(mode):
- return (
- gr.update(visible=_stable_visible(mode == "Image")),
- gr.update(visible=_stable_visible(mode == "Video")),
- )
-
-
-_MODE_GUARD_JS = """(mode) => {
- document.documentElement.dataset.upscaleMode = mode;
- const hiddenPanel = document.getElementById(
- mode === 'Video' ? 'upscale-image' : 'upscale-video'
- );
- if (hiddenPanel) {
- hiddenPanel.querySelectorAll('video').forEach((node) => {
- try { node.pause(); } catch (_) {}
- });
- }
-}"""
-
-
-@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=None,
- show_label=False,
- container=False,
- elem_id="upscale-mode",
- )
- with gr.Column(
- visible=_stable_visible(selected_mode == "Image"),
- elem_id="upscale-image",
- elem_classes=["workflow-mode-panel"],
- ) as image_panel:
- image = build_image_tab(settings)
- with gr.Column(
- visible=_stable_visible(selected_mode == "Video"),
- elem_id="upscale-video",
- elem_classes=["workflow-mode-panel"],
- ) as video_panel:
- video = build_video_tab(settings)
-
- transition = mode.change(
- None, inputs=mode, js=_MODE_GUARD_JS, queue=False, show_progress="hidden",
- trigger_mode="always_last",
- )
- visibility = transition.then(
- mode_visibility, inputs=mode, outputs=[image_panel, video_panel],
- queue=False, show_progress="hidden", trigger_mode="always_last",
- )
- bind_input_surface_reactivation(visibility, image, kind="image")
- bind_input_surface_reactivation(visibility, video, kind="video")
- return UpscaleTab(mode, image, video, image_panel, video_panel)
diff --git a/src/upscale/video/components.py b/src/upscale/video/components.py
deleted file mode 100644
index 2a82c6c..0000000
--- a/src/upscale/video/components.py
+++ /dev/null
@@ -1,16 +0,0 @@
-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.pyi
deleted file mode 100644
index 00a948f..0000000
--- a/src/upscale/video/components.pyi
+++ /dev/null
@@ -1,22 +0,0 @@
-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 file
diff --git a/src/upscale/video/cuda_pipeline.py b/src/upscale/video/cuda_pipeline.py
index c40ca56..7d84e92 100644
--- a/src/upscale/video/cuda_pipeline.py
+++ b/src/upscale/video/cuda_pipeline.py
@@ -283,7 +283,7 @@ def convert_video_cuda_nvenc(
progress(max(0.0, min(1.0, value)), message)
try:
- update(0.01, f"Preparing CUDA decode and encode on {ai_gpu.get('name', 'NVIDIA GPU')}")
+ update(0.01, "Preparing video processing")
job = tempfile.TemporaryDirectory(prefix="rtx-video-cuda-", dir=JOBS)
try:
job_dir = Path(job.name)
@@ -487,8 +487,7 @@ def convert_video_cuda_nvenc(
if now - last_update > 0.2:
update(
min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),
- f"RTX Video CUDA: {width}×{height} → {output_width}×{output_height}; "
- f"{delivered} frames; {delivered / max(0.01, now-started):.1f} fps",
+ "Upscaling video",
)
last_update = now
if not delivered:
diff --git a/src/upscale/video/host_pipeline.py b/src/upscale/video/host_pipeline.py
index 2fe71fa..76589cf 100644
--- a/src/upscale/video/host_pipeline.py
+++ b/src/upscale/video/host_pipeline.py
@@ -331,7 +331,7 @@ def convert_video_inprocess_host(
encode_queue: queue.Queue | None = None
try:
- update(0.01, f"Preparing in-process CUDA and {encoder.display_name}")
+ update(0.01, "Preparing video processing")
JOBS.mkdir(exist_ok=True)
job = tempfile.TemporaryDirectory(prefix="rtx-video-host-", dir=JOBS)
try:
@@ -526,8 +526,7 @@ def convert_video_inprocess_host(
if now - last_update > 0.2:
update(
min(0.87, 0.05 + 0.82 * delivered / max(1, estimated)),
- f"RTX Video pinned pipeline: {width}×{height} → {output_width}×{output_height}; "
- f"{delivered} frames; {delivered / max(0.01, now-started):.1f} fps")
+ "Upscaling video")
last_update = now
if not delivered:
raise ValueError("The input contains no decodable video frames.")
diff --git a/src/upscale/video/media.py b/src/upscale/video/media.py
index 27322c9..bca3676 100644
--- a/src/upscale/video/media.py
+++ b/src/upscale/video/media.py
@@ -131,7 +131,7 @@ def start_decoder(source, meta, controller):
"-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)
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
controller.register(process)
logs = BoundedLogBuffer(max_tail=60)
thread = threading.Thread(target=drain_bounded_text, args=(process.stderr, logs), daemon=True)
diff --git a/src/upscale/video/native.py b/src/upscale/video/native.py
index 86457b6..af1242f 100644
--- a/src/upscale/video/native.py
+++ b/src/upscale/video/native.py
@@ -28,7 +28,7 @@ from .models import UpscaleCapabilities, UpscaleOptions
RUNTIME_DIR = RUNTIME / "rtx_video"
-BRIDGE = RUNTIME_DIR / "neuroframe_engine.dll"
+BRIDGE = RUNTIME_DIR / "neuroframe_engine_upscaling.dll"
WORKER = (ROOT / "native (dev)" / "Upscale" / "RTX Video" / "rtx_video" /
"build" / "legacy" / "rtx-video-worker.exe")
BRIDGE_ABI_VERSION = 1
@@ -334,7 +334,7 @@ def probe_legacy_capabilities(luid: str) -> dict[str, Any]:
process = subprocess.Popen(
[str(WORKER), "--probe", "--gpu-luid", luid], cwd=WORKER.parent,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- creationflags=subprocess.CREATE_NO_WINDOW,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
controller.register(process)
try:
diff --git a/src/upscale/video/preview.py b/src/upscale/video/preview.py
index f2e53d2..7059305 100644
--- a/src/upscale/video/preview.py
+++ b/src/upscale/video/preview.py
@@ -3,51 +3,100 @@ 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()
+def display_result_native(result, options, *, preview_encoding: str = "Auto", controller=None, output_dir=None):
+ """Return a plain media path/detail tuple with no UI-framework objects."""
+ mode = preview_encoding
if mode == "Disabled":
- return result.output_path, "Actual output; browser HDR/codec support depends on your display and browser."
+ return result.output_path, "Actual output; HDR/codec support depends on the native media backend."
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")
+ 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)
+ path = make_browser_preview(
+ result.output_path, dest_dir=output_dir, 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}")
+ return None, f"Output saved; compatibility preview unavailable: {exc}"
+ return path, (
+ "SDR tone-mapped compatibility preview. Open the original for HDR playback."
+ if options.hdr_enabled else "H.264 compatibility preview."
+ )
-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=True if available else "hidden", label=label),
- gr.update(value=None, visible=True), gr.update(visible=single), gr.update(visible=single))
+def preview_upscale_native(
+ path: str,
+ options,
+ *,
+ one_frame: bool = False,
+ progress=None,
+ controller=None,
+ output_dir=None,
+ preview_encoding: str = "Auto",
+ start_seconds: float | None = None,
+ frame_index: int | None = None,
+):
+ if not path or not Path(path).is_file():
+ raise ValueError("Select one valid video to preview.")
+ try:
+ start = max(0.0, float(start_seconds or 0.0))
+ except (TypeError, ValueError):
+ start = 0.0
+ try:
+ frame_no = max(1, int(frame_index or 1)) if frame_index else 1
+ except (TypeError, ValueError):
+ frame_no = 1
+ effective_path = str(path)
+ temp_clip: str | None = None
+ # Explicit Preview must enhance the timeline playhead, not frame 0.
+ # Extract a seek-accurate 1-frame subclip first; the RTX pipeline then
+ # processes that frame unchanged (no pipeline timing changes required).
+ if one_frame and start > 0.05:
+ from ...core.ffmpeg.preview import extract_preview_subclip
+ if progress:
+ try:
+ progress(0.02, "Seeking to timeline frame…")
+ except TypeError:
+ pass
+ temp_clip = extract_preview_subclip(
+ path, dest_dir=output_dir, start_seconds=start,
+ single_frame=True, controller=controller,
+ )
+ effective_path = temp_clip
+ opts = replace(
+ options,
+ preview_frames=1 if one_frame else None,
+ preview_seconds=None if one_frame else 3.0,
+ )
+ try:
+ result = upscale_video(
+ effective_path, opts, progress=progress, controller=controller, output_dir=output_dir
+ )
+ finally:
+ if temp_clip:
+ try:
+ Path(temp_clip).unlink(missing_ok=True)
+ except OSError:
+ pass
+ display, detail = display_result_native(
+ result,
+ opts,
+ preview_encoding=preview_encoding,
+ controller=controller,
+ output_dir=output_dir,
+ )
+ stamp = f" f{frame_no} @ {start:.2f}s" if (one_frame and start > 0.05) else ""
+ return display, (
+ f"Preview complete{stamp}: {result.output_width}×{result.output_height}, {result.frames} frames.\n"
+ f"{detail}\nOriginal preview file: {result.output_path}\nReport: {result.report_path}"
+ )
diff --git a/src/upscale/video/ui.py b/src/upscale/video/ui.py
deleted file mode 100644
index 64c5aa2..0000000
--- a/src/upscale/video/ui.py
+++ /dev/null
@@ -1,235 +0,0 @@
-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, build_save_controls,
-)
-from ...core.disk_paths import resolve_inputs
-from ...core.ffmpeg import CODEC_CHOICES, ENCODING_QUALITIES, container_for_codec, 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()
- selected = dict(zip(SETTING_FIELDS, values))
- selected["container"] = container_for_codec(selected["codec"])
- return UpscaleOptions(**selected, 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
- 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"), files, [], 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
- save_download: object
- zip_button: 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="hidden")
- 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")
- with gr.Row():
- render = gr.Button("Upscale video(s)", variant="primary")
- stop = gr.Button("Stop", variant="stop")
- preview_frame_button = gr.Button("Preview 1 frame", visible=False)
- preview_button = gr.Button("Preview 3 sec", visible=False)
- reset = gr.Button("Reset settings")
- with gr.Column():
- c["vsr_enabled"] = gr.Checkbox(value=opts.vsr_enabled, label="Enable")
- 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-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")
- dimensions = gr.Markdown(visible=False, elem_id="upscale-video-dimensions")
- input_path, output_path = build_path_controls()
- 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))
- 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")
- 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")
- c["container"] = gr.Dropdown(
- ("MP4", "MKV", "MOV"), value=container_for_codec(opts.codec),
- label="Container (automatic)", interactive=False,
- )
- 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.Column(scale=3):
- output_video = ManagedVideo(
- label="Output video", interactive=False, visible=True, height=520,
- )
- save_download, zip_button, zip_download = build_save_controls("video", "upscale-video")
- 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, save_download, zip_button, zip_download, status, results, input_path, output_path)
- bind_batch_ui(
- tab, render_upscale_batch, kind="video", preview_mode=preview_mode,
- archive_prefix="RTXVIDEO_VIDEO_BATCH",
- 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(value=container_for_codec(codec)),
- gr.update(interactive=True) if hdr_mode_supported(codec)
- else gr.update(value=False, interactive=False),
- ),
- inputs=c["codec"], outputs=[c["container"], 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
diff --git a/start.bat b/start.bat
deleted file mode 100644
index 01e6038..0000000
--- a/start.bat
+++ /dev/null
@@ -1,14 +0,0 @@
-@echo off
-setlocal
-cd /d "%~dp0"
-chcp 65001 >nul
-title DLSS 5 Visual Enhancer
-cls
-set "PYTHONNOUSERSITE=1"
-set "PYTHONDONTWRITEBYTECODE=1"
-set "PYTHONIOENCODING=utf-8"
-set "GRADIO_ANALYTICS_ENABLED=False"
-set "GRADIO_TEMP_DIR=%~dp0temp\gradio"
-if not exist "%GRADIO_TEMP_DIR%" mkdir "%GRADIO_TEMP_DIR%"
-"%~dp0bin\python-3.13.15-embed-amd64\python.exe" "%~dp0app.py"
-if errorlevel 1 pause